Debian Codegraph @

dojox/date/hebrew/locale.js

raw symbols SCIP
1 define(["dojox/main", "dojo/_base/lang", "dojo/_base/array", "dojo/date", "dojo/i18n", "dojo/regexp", "dojo/string", "./Date", "./numerals", "dojo/i18n!dojo/cldr/nls/hebrew"],
2 function(dojox, lang, arr, dd, i18n, regexp, string, HDate, numerals){
3
4 var hlocale = lang.getObject("date.hebrew.locale", true, dojox);
5
6 //Load the bundles containing localization information for
7 // names and formats
8 i18n.getLocalization("dojo.cldr", "hebrew");
9
10 // Format a pattern without literals
11 function formatPattern(dateObject, bundle, locale, fullYear, pattern){
12
13 return pattern.replace(/([a-z])\1*/ig, function(match){
14 var s, pad;
15 var c = match.charAt(0);
16 var l = match.length;
17 var widthList = ["abbr", "wide", "narrow"];
18
19 switch(c){
20 case 'G':
21 s = bundle[(l < 4) ? "eraAbbr" : "eraNames"][0];
22 break;
23 case 'y':
24 if(locale.match(/^he(?:-.+)?$/)){
25 s = numerals.getYearHebrewLetters(dateObject.getFullYear());
26 }else{
27 s = String(dateObject.getFullYear());
28 }
29 break;
30 case 'M':
31 var m = dateObject.getMonth();
32 if(l<3){
33 if(!dateObject.isLeapYear(dateObject.getFullYear()) && m>5){m--;}
34 if(locale.match(/^he(?:-.+)?$/)){
35 s = numerals.getMonthHebrewLetters(m);
36 }else{
37 s = m+1; pad = true;
38 }
39 }else{
40 var monthNames = hlocale.getNames('months',widthList[l-3], 'format', locale, dateObject);
41 s = monthNames[m];
42 }
43 break;
44 case 'd':
45 if(locale.match(/^he(?:-.+)?$/)){
46 s = dateObject.getDateLocalized(locale);
47 }else{
48 s = dateObject.getDate(); pad = true;
49 }
50 break;
51 case 'E':
52 var d = dateObject.getDay();
53 if(l<3){
54 s = d+1; pad = true;
55 }else{
56 var propD = ["days", "format", widthList[l-3]].join("-");
57 s = bundle[propD][d];
58 }
59 break;
60 case 'a':
61 var timePeriod = (dateObject.getHours() < 12) ? 'am' : 'pm';
62 s = bundle['dayPeriods-format-wide-' + timePeriod];
63 break;
64 case 'h':
65 case 'H':
66 case 'K':
67 case 'k':
68 var h = dateObject.getHours();
69 // strange choices in the date format make it impossible to write this succinctly
70 switch (c){
71 case 'h': // 1-12
72 s = (h % 12) || 12;
73 break;
74 case 'H': // 0-23
75 s = h;
76 break;
77 case 'K': // 0-11
78 s = (h % 12);
79 break;
80 case 'k': // 1-24
81 s = h || 24;
82 break;
83 }
84 pad = true;
85 break;
86 case 'm':
87 s = dateObject.getMinutes(); pad = true;
88 break;
89 case 's':
90 s = dateObject.getSeconds(); pad = true;
91 break;
92 case 'S':
93 s = Math.round(dateObject.getMilliseconds() * Math.pow(10, l-3)); pad = true;
94 break;
95 case 'z':
96 s = "";
97 break;
98 default:
99 throw new Error("dojox.date.hebrew.locale.formatPattern: invalid pattern char: "+pattern);
100 }
101 if(pad){ s = string.pad(s, l); }
102 return s;
103 });
104 }
105
106 hlocale.format = function(/*dojox/date/hebrewDate*/dateObject, /*object?*/options){
107 // summary:
108 // Format a Date object as a String, using settings.
109 // description:
110 // Create a string from a hebrew.Date object using a known pattern.
111 // By default, this method formats both date and time from dateObject.
112 // Default formatting lengths is 'short'
113 // dateObject:
114 // the date and/or time to be formatted. If a time only is formatted,
115 // the values in the year, month, and day fields are irrelevant. The
116 // opposite is true when formatting only dates.
117
118 // based on and similar to dojo.date.locale.format
119
120 options = options || {};
121
122 var locale = i18n.normalizeLocale(options.locale);
123 var formatLength = options.formatLength || 'short';
124 var bundle = hlocale._getHebrewBundle(locale);
125 var str = [];
126
127 var sauce = lang.hitch(this, formatPattern, dateObject, bundle, locale, options.fullYear);
128 if(options.selector == "year"){
129 var year = dateObject.getFullYear();
130 return locale.match(/^he(?:-.+)?$/) ?
131 numerals.getYearHebrewLetters(year) : year;
132 }
133 if(options.selector != "time"){
134 var datePattern = options.datePattern || bundle["dateFormat-"+formatLength];
135 if(datePattern){str.push(_processPattern(datePattern, sauce));}
136 }
137 if(options.selector != "date"){
138 var timePattern = options.timePattern || bundle["timeFormat-"+formatLength];
139 if(timePattern){str.push(_processPattern(timePattern, sauce));}
140 }
141 var result = str.join(" "); //TODO: use locale-specific pattern to assemble date + time
142
143 return result; // String
144 };
145
146 hlocale.regexp = function(/*object?*/options){
147 // summary:
148 // Builds the regular needed to parse a hebrew.Date
149
150 // based on and similar to dojo.date.locale.regexp
151
152 return hlocale._parseInfo(options).regexp; // String
153 };
154
155 hlocale._parseInfo = function(/*oblect?*/options){
156 /* based on and similar to dojo.date.locale._parseInfo */
157
158 options = options || {};
159 var locale = i18n.normalizeLocale(options.locale);
160 var bundle = hlocale._getHebrewBundle(locale);
161
162 var formatLength = options.formatLength || 'short';
163 var datePattern = options.datePattern || bundle["dateFormat-" + formatLength];
164 var timePattern = options.timePattern || bundle["timeFormat-" + formatLength];
165
166 var pattern;
167 if(options.selector == 'date'){
168 pattern = datePattern;
169 }else if(options.selector == 'time'){
170 pattern = timePattern;
171 }else{
172 pattern = (timePattern === undefined) ? datePattern : datePattern + ' ' + timePattern; //hebrew resource file does not contain time patterns - a bug?
173 }
174
175 var tokens = [];
176
177 var re = _processPattern(pattern, lang.hitch(this, _buildDateTimeRE, tokens, bundle, options));
178 return {regexp: re, tokens: tokens, bundle: bundle};
179 };
180
181 hlocale.parse = function(/*String*/value, /*Object?*/options){
182 // summary:
183 // This function parse string date value according to options
184 // example:
185 // | var dateHebrew = dojox.date.hebrew.locale.parse('11/10/5740', {datePattern:'dd/MM/yy', selector:'date'});
186 // | in Hebrew locale string for parsing contains Hebrew Numerals
187 // |
188 // | options = {datePattern:'dd MMMM yy', selector:'date'};
189 // |
190 // | y - year
191 // | M, MM - short month
192 // | MMM, MMMM - long month
193 // | d - date
194 // | a - am, pm
195 // | E, EE, EEE, EEEE - week day
196 // |
197 // | h, H, k, K, m, s, S, - time format
198
199 // based on and similar to dojo.date.locale.parse
200
201 value = value.replace(/[\u200E\u200F\u202A-\u202E]/g, ""); //remove special chars
202
203 if(!options){options={};}
204 var info = hlocale._parseInfo(options);
205
206 var tokens = info.tokens, bundle = info.bundle;
207 var re = new RegExp("^" + info.regexp + "$");
208
209 var match = re.exec(value);
210
211 var locale = i18n.normalizeLocale(options.locale);
212
213 if(!match){ return null; } // null
214
215 var date, date1;
216
217 //var result = [1970,0,1,0,0,0,0]; //
218 var result = [5730,3,23,0,0,0,0]; // hebrew date for [1970,0,1,0,0,0,0] used in gregorian locale
219 var amPm = "";
220 var mLength = 0;
221 var widthList = ["abbr", "wide", "narrow"];
222 var valid = arr.every(match, function(v, i){
223 if(!i){return true;}
224 var token=tokens[i-1];
225 var l=token.length;
226 switch(token.charAt(0)){
227 case 'y':
228 if(locale.match(/^he(?:-.+)?$/)){
229 result[0] = numerals.parseYearHebrewLetters(v);
230 }else{
231 result[0] = Number(v);
232 }
233 break;
234 case 'M':
235 //if it is short format, month is one letter or two letter with "geresh"
236 if(l>2){
237 //we do not know here if the year is leap or not
238 var months = hlocale.getNames('months', widthList[l-3], 'format', locale, new HDate(5769, 1, 1)),
239 leapmonths = hlocale.getNames('months', widthList[l-3], 'format', locale, new HDate(5768, 1, 1));
240 if(!options.strict){
241 //Tolerate abbreviating period in month part
242 //Case-insensitive comparison
243 v = v.replace(".","").toLowerCase();
244 months = arr.map(months, function(s){ return s ? s.replace(".","").toLowerCase() : s; } );
245 leapmonths = arr.map(leapmonths, function(s){ return s ? s.replace(".","").toLowerCase() : s; } );
246 }
247 var monthName = v;
248 v = arr.indexOf(months, monthName);
249 if(v == -1){
250 v = arr.indexOf(leapmonths, monthName);
251 if(v == -1){
252 //console.debug("dojox.date.hebrew.locale.parse: Could not parse month name: second " + v +"'.");
253 return false;
254 }
255 }
256 mLength = l;
257 }else{
258 if(locale.match(/^he(?:-.+)?$/)){
259 v = numerals.parseMonthHebrewLetters(v);
260 }else{
261 v--;
262 }
263 }
264 result[1] = Number(v);
265 break;
266 case 'D':
267 result[1] = 0;
268 // fallthrough...
269 case 'd':
270 if(locale.match(/^he(?:-.+)?$/)){
271 result[2] = numerals.parseDayHebrewLetters(v);
272 }else{
273 result[2] = Number(v);
274 }
275 break;
276 case 'a': //am/pm
277 var am = options.am || bundle['dayPeriods-format-wide-am'],
278 pm = options.pm || bundle['dayPeriods-format-wide-pm'];
279 if(!options.strict){
280 var period = /\./g;
281 v = v.replace(period,'').toLowerCase();
282 am = am.replace(period,'').toLowerCase();
283 pm = pm.replace(period,'').toLowerCase();
284 }
285 if(options.strict && v != am && v != pm){
286 return false;
287 }
288
289 // we might not have seen the hours field yet, so store the state and apply hour change later
290 amPm = (v == pm) ? 'p' : (v == am) ? 'a' : '';
291 break;
292 case 'K': //hour (1-24)
293 if(v == 24){ v = 0; }
294 // fallthrough...
295 case 'h': //hour (1-12)
296 case 'H': //hour (0-23)
297 case 'k': //hour (0-11)
298 //in the 12-hour case, adjusting for am/pm requires the 'a' part
299 //which could come before or after the hour, so we will adjust later
300 result[3] = Number(v);
301 break;
302 case 'm': //minutes
303 result[4] = Number(v);
304 break;
305 case 's': //seconds
306 result[5] = Number(v);
307 break;
308 case 'S': //milliseconds
309 result[6] = Number(v);
310 }
311 return true;
312 });
313
314 var hours = +result[3];
315 if(amPm === 'p' && hours < 12){
316 result[3] = hours + 12; //e.g., 3pm -> 15
317 }else if(amPm === 'a' && hours == 12){
318 result[3] = 0; //12am -> 0
319 }
320 var dateObject = new HDate(result[0], result[1], result[2], result[3], result[4], result[5], result[6]); // hebrew.Date
321 //for non leap year, the index of the short month start from adar should be increased by 1
322 if(mLength < 3 && result[1] >= 5 && !dateObject.isLeapYear(dateObject.getFullYear())){
323 dateObject.setMonth(result[1]+1);
324 }
325 return dateObject; // hebrew.Date
326 };
327
328
329 function _processPattern(pattern, applyPattern, applyLiteral, applyAll){
330 // summary:
331 // Process a pattern with literals in it
332
333 // Break up on single quotes, treat every other one as a literal, except '' which becomes '
334 var identity = function(x){return x;};
335 applyPattern = applyPattern || identity;
336 applyLiteral = applyLiteral || identity;
337 applyAll = applyAll || identity;
338
339 //split on single quotes (which escape literals in date format strings)
340 //but preserve escaped single quotes (e.g., o''clock)
341 var chunks = pattern.match(/(''|[^'])+/g);
342 var literal = pattern.charAt(0) == "'";
343
344 arr.forEach(chunks, function(chunk, i){
345 if(!chunk){
346 chunks[i]='';
347 }else{
348 chunks[i]=(literal ? applyLiteral : applyPattern)(chunk);
349 literal = !literal;
350 }
351 });
352 return applyAll(chunks.join(''));
353 }
354
355 function _buildDateTimeRE (tokens, bundle, options, pattern){
356 // based on and similar to dojo.date.locale._buildDateTimeRE
357
358 pattern = regexp.escapeString(pattern);
359 var locale = i18n.normalizeLocale(options.locale);
360
361 return pattern.replace(/([a-z])\1*/ig, function(match){
362
363 // Build a simple regexp. Avoid captures, which would ruin the tokens list
364 var s;
365 var c = match.charAt(0);
366 var l = match.length;
367 var p2 = '', p3 = '';
368 if(options.strict){
369 if(l > 1){ p2 = '0' + '{'+(l-1)+'}'; }
370 if(l > 2){ p3 = '0' + '{'+(l-2)+'}'; }
371 }else{
372 p2 = '0?'; p3 = '0{0,2}';
373 }
374 switch(c){
375 case 'y':
376 s = '\\S+';
377 break;
378 case 'M':
379 if(locale.match('^he(?:-.+)?$')){
380 s = (l>2) ? '\\S+ ?\\S+' : '\\S{1,4}';
381 }else{
382 s = (l>2) ? '\\S+ ?\\S+' : p2+'[1-9]|1[0-3]';
383 }
384 break;
385 case 'd':
386 if(locale.match('^he(?:-.+)?$')){
387 s = '\\S[\'\"\'\u05F3]{1,2}\\S?';
388 }else{
389 s = '[12]\\d|'+p2+'[1-9]|30';
390 }
391 break;
392 case 'E':
393 if(locale.match('^he(?:-.+)?$')){
394 s = (l>3) ? '\\S+ ?\\S+' : '\\S';
395 }else{
396 s = '\\S+';
397 }
398 break;
399 case 'h': //hour (1-12)
400 s = p2+'[1-9]|1[0-2]';
401 break;
402 case 'k': //hour (0-11)
403 s = p2+'\\d|1[01]';
404 break;
405 case 'H': //hour (0-23)
406 s = p2+'\\d|1\\d|2[0-3]';
407 break;
408 case 'K': //hour (1-24)
409 s = p2+'[1-9]|1\\d|2[0-4]';
410 break;
411 case 'm':
412 case 's':
413 s = p2+'\\d|[0-5]\\d';
414 break;
415 case 'S':
416 s = '\\d{'+l+'}';
417 break;
418 case 'a':
419 var am = options.am || bundle['dayPeriods-format-wide-am'],
420 pm = options.pm || bundle['dayPeriods-format-wide-pm'];
421 if(options.strict){
422 s = am + '|' + pm;
423 }else{
424 s = am + '|' + pm;
425 if(am != am.toLowerCase()){ s += '|' + am.toLowerCase(); }
426 if(pm != pm.toLowerCase()){ s += '|' + pm.toLowerCase(); }
427 }
428 break;
429 default:
430 s = ".*";
431 }
432 if(tokens){ tokens.push(match); }
433 return "(" + s + ")"; // add capture
434 }).replace(/[\xa0 ]/g, "[\\s\\xa0]"); // normalize whitespace. Need explicit handling of \xa0 for IE. */
435 }
436
437 var _customFormats = [];
438 hlocale.addCustomFormats = function(/*String*/packageName, /*String*/bundleName){
439 // summary:
440 // Add a reference to a bundle containing localized custom formats to be
441 // used by date/time formatting and parsing routines.
442 // description:
443 // The user may add custom localized formats where the bundle has properties following the
444 // same naming convention used by dojo.cldr: `dateFormat-xxxx` / `timeFormat-xxxx`
445 // The pattern string should match the format used by the CLDR.
446 // See dojo.date.locale.format() for details.
447 // The resources must be loaded by dojo.requireLocalization() prior to use
448
449 _customFormats.push({pkg:packageName,name:bundleName});
450 };
451
452 hlocale._getHebrewBundle = function(/*String*/locale){
453 var hebrew = {};
454 arr.forEach(_customFormats, function(desc){
455 var bundle = i18n.getLocalization(desc.pkg, desc.name, locale);
456 hebrew = lang.mixin(hebrew, bundle);
457 }, this);
458 return hebrew; /*Object*/
459 };
460
461 hlocale.addCustomFormats("dojo.cldr","hebrew");
462
463 hlocale.getNames = function(/*String*/item, /*String*/type, /*String?*/context, /*String?*/locale, /*dojox/date/hebrew/Date?*/date){
464 // summary:
465 // Used to get localized strings from dojo.cldr for day or month names.
466 // item:
467 // 'months' || 'days'
468 // type:
469 // 'wide' || 'narrow' || 'abbr' (e.g. "Monday", "Mon", or "M" respectively, in English)
470 // use:
471 // 'standAlone' || 'format' (default)
472 // locale:
473 // override locale used to find the names
474 // date:
475 // required for item=months to determine leap month name
476
477 // using var monthNames = dojox.date.hebrew.locale.getNames('months', 'wide', 'format', 'he', new hebrewDate(5768, 2, 12));
478
479 var label,
480 lookup = hlocale._getHebrewBundle(locale),
481 props = [item, context, type];
482 if(context == 'standAlone'){
483 var key = props.join('-');
484 label = lookup[key];
485 // Fall back to 'format' flavor of name
486 if(label[0] == 1){ label = undefined; } // kludge, in the absence of real aliasing support in dojo.cldr
487 }
488 props[1] = 'format';
489
490 // return by copy so changes won't be made accidentally to the in-memory model
491 var result = (label || lookup[props.join('-')]).concat();
492
493 if(item == "months"){
494 if(date.isLeapYear(date.getFullYear())){
495 // Adar I (6th position in the array) will be used.
496 // Substitute the leap month Adar II for the regular Adar (7th position)
497 props.push("leap");
498 result[6] = lookup[props.join('-')];
499 }else{
500 // Remove Adar I but leave an empty position in the array
501 delete result[5];
502 }
503 }
504
505 return result; /*Array*/
506 };
507
508 return hlocale;
509 });