Debian Codegraph @

dojox/date/islamic/locale.js

raw symbols SCIP
1 define(["dojox/main", "dojo/_base/lang", "dojo/_base/array", "dojo/date", "dojo/i18n", "dojo/regexp", "dojo/string", "./Date", "dojo/i18n!dojo/cldr/nls/islamic"],
2 function(dojox, lang, arr, dd, i18n, regexp, string, IDate, bundle){
3
4 var ilocale = lang.getObject("date.islamic.locale", true, dojox);
5
6 // Format a pattern without literals
7 function formatPattern(dateObject, bundle, locale, fullYear, pattern){
8
9 return pattern.replace(/([a-z])\1*/ig, function(match){
10 var s, pad;
11 var c = match.charAt(0);
12 var l = match.length;
13 var widthList = ["abbr", "wide", "narrow"];
14
15 switch(c){
16 case 'G':
17 s = bundle["eraAbbr"][0];
18 break;
19 case 'y':
20 s = String(dateObject.getFullYear());
21 break;
22 case 'M':
23 var m = dateObject.getMonth();
24 if(l<3){
25 s = m+1; pad = true;
26 }else{
27 var propM = ["months", "format", widthList[l-3]].join("-");
28 s = bundle[propM][m];
29 }
30 break;
31 case 'd':
32 s = dateObject.getDate(true); pad = true;
33 break;
34 case 'E':
35 var d = dateObject.getDay();
36 if(l<3){
37 s = d+1; pad = true;
38 }else{
39 var propD = ["days", "format", widthList[l-3]].join("-");
40 s = bundle[propD][d];
41 }
42 break;
43 case 'a':
44 var timePeriod = (dateObject.getHours() < 12) ? 'am' : 'pm';
45 s = bundle['dayPeriods-format-wide-' + timePeriod];
46 break;
47 case 'h':
48 case 'H':
49 case 'K':
50 case 'k':
51 var h = dateObject.getHours();
52 switch (c){
53 case 'h': // 1-12
54 s = (h % 12) || 12;
55 break;
56 case 'H': // 0-23
57 s = h;
58 break;
59 case 'K': // 0-11
60 s = (h % 12);
61 break;
62 case 'k': // 1-24
63 s = h || 24;
64 break;
65 }
66 pad = true;
67 break;
68 case 'm':
69 s = dateObject.getMinutes(); pad = true;
70 break;
71 case 's':
72 s = dateObject.getSeconds(); pad = true;
73 break;
74 case 'S':
75 s = Math.round(dateObject.getMilliseconds() * Math.pow(10, l-3)); pad = true;
76 break;
77 case 'z':
78 // We only have one timezone to offer; the one from the browser
79 s = dd.getTimezoneName(dateObject.toGregorian());
80 if(s){ break; }
81 l = 4;
82 // fallthrough... use GMT if tz not available
83 case 'Z':
84 var offset = dateObject.toGregorian().getTimezoneOffset();
85 var tz = [
86 (offset <= 0 ? "+" : "-"),
87 string.pad(Math.floor(Math.abs(offset) / 60), 2),
88 string.pad(Math.abs(offset) % 60, 2)
89 ];
90 if(l == 4){
91 tz.splice(0, 0, "GMT");
92 tz.splice(3, 0, ":");
93 }
94 s = tz.join("");
95 break;
96 default:
97 throw new Error("dojox.date.islamic.locale.formatPattern: invalid pattern char: "+pattern);
98 }
99 if(pad){ s = string.pad(s, l); }
100 return s;
101 });
102 }
103
104 // based on and similar to dojo.date.locale.format
105 ilocale.format = function(/*dojox/date/islamic/Date*/dateObject, /*Object?*/options){
106 // summary:
107 // Format a Date object as a String, using settings.
108 options = options || {};
109
110 var locale = i18n.normalizeLocale(options.locale);
111 var formatLength = options.formatLength || 'short';
112 var bundle = ilocale._getIslamicBundle(locale);
113 var str = [];
114
115 var sauce = lang.hitch(this, formatPattern, dateObject, bundle, locale, options.fullYear);
116 if(options.selector == "year"){
117 var year = dateObject.getFullYear();
118 return year;
119 }
120 if(options.selector != "time"){
121 var datePattern = options.datePattern || bundle["dateFormat-"+formatLength];
122 if(datePattern){str.push(_processPattern(datePattern, sauce));}
123 }
124 if(options.selector != "date"){
125 var timePattern = options.timePattern || bundle["timeFormat-"+formatLength];
126 if(timePattern){str.push(_processPattern(timePattern, sauce));}
127 }
128 var result = str.join(" "); //TODO: use locale-specific pattern to assemble date + time
129
130 return result; // String
131 };
132
133 ilocale.regexp = function(/*object?*/options){
134 // summary:
135 // Builds the regular needed to parse a islamic.Date
136
137 // based on and similar to dojo.date.locale.regexp
138
139 return ilocale._parseInfo(options).regexp; // String
140 };
141
142 ilocale._parseInfo = function(/*oblect?*/options){
143 /* based on and similar to dojo.date.locale._parseInfo */
144
145 options = options || {};
146 var locale = i18n.normalizeLocale(options.locale);
147 var bundle = ilocale._getIslamicBundle(locale);
148 var formatLength = options.formatLength || 'short';
149 var datePattern = options.datePattern || bundle["dateFormat-" + formatLength];
150 var timePattern = options.timePattern || bundle["timeFormat-" + formatLength];
151
152 var pattern;
153 if(options.selector == 'date'){
154 pattern = datePattern;
155 }else if(options.selector == 'time'){
156 pattern = timePattern;
157 }else{
158 pattern = (typeof (timePattern) == "undefined") ? datePattern : datePattern + ' ' + timePattern;
159 }
160
161 var tokens = [];
162
163 var re = _processPattern(pattern, lang.hitch(this, _buildDateTimeRE, tokens, bundle, options));
164 return {regexp: re, tokens: tokens, bundle: bundle};
165 };
166
167 ilocale.parse = function(/*String*/value, /*Object?*/options){
168 // summary:
169 // This function parse string date value according to options
170
171 // based on and similar to dojo.date.locale.parse
172
173 value = value.replace(/[\u200E\u200F\u202A\u202E]/g, ""); //remove bidi non-printing chars
174
175 if(!options){ options={}; }
176 var info = ilocale._parseInfo(options);
177
178 var tokens = info.tokens, bundle = info.bundle;
179 var regexp = info.regexp.replace(/[\u200E\u200F\u202A\u202E]/g, ""); //remove bidi non-printing chars from the pattern
180 var re = new RegExp("^" + regexp + "$");
181
182 var match = re.exec(value);
183
184 var locale = i18n.normalizeLocale(options.locale);
185
186 if(!match){ return null; } // null
187
188 var date, date1;
189
190 var result = [1389,0,1,0,0,0,0]; //FIXME: islamic date for [1970,0,1,0,0,0,0] used in gregorian locale
191 var amPm = "";
192 var mLength = 0;
193 var widthList = ["abbr", "wide", "narrow"];
194 var valid = arr.every(match, function(v, i){
195 if(!i){return true;}
196 var token=tokens[i-1];
197 var l=token.length;
198 switch(token.charAt(0)){
199 case 'y':
200 result[0] = Number(v);
201 break;
202 case 'M':
203 if(l>2){
204 var months = bundle['months-format-' + widthList[l-3]].concat();
205 if(!options.strict){
206 //Tolerate abbreviating period in month part
207 //Case-insensitive comparison
208 v = v.replace(".","").toLowerCase();
209 months = arr.map(months, function(s){ return s ? s.replace(".","").toLowerCase() : s; } );
210 }
211 v = arr.indexOf(months, v);
212 if(v == -1){
213 return false;
214 }
215 mLength = l;
216 }else{
217 v--;
218 }
219 result[1] = Number(v);
220 break;
221 case 'D':
222 result[1] = 0;
223 // fallthrough...
224 case 'd':
225 result[2] = Number(v);
226 break;
227 case 'a': //am/pm
228 var am = options.am || bundle['dayPeriods-format-wide-am'],
229 pm = options.pm || bundle['dayPeriods-format-wide-pm'];
230 if(!options.strict){
231 var period = /\./g;
232 v = v.replace(period,'').toLowerCase();
233 am = am.replace(period,'').toLowerCase();
234 pm = pm.replace(period,'').toLowerCase();
235 }
236 if(options.strict && v != am && v != pm){
237 return false;
238 }
239
240 // we might not have seen the hours field yet, so store the state and apply hour change later
241 amPm = (v == pm) ? 'p' : (v == am) ? 'a' : '';
242 break;
243 case 'K': //hour (1-24)
244 if(v == 24){ v = 0; }
245 // fallthrough...
246 case 'h': //hour (1-12)
247 case 'H': //hour (0-23)
248 case 'k': //hour (0-11)
249 //in the 12-hour case, adjusting for am/pm requires the 'a' part
250 //which could come before or after the hour, so we will adjust later
251 result[3] = Number(v);
252 break;
253 case 'm': //minutes
254 result[4] = Number(v);
255 break;
256 case 's': //seconds
257 result[5] = Number(v);
258 break;
259 case 'S': //milliseconds
260 result[6] = Number(v);
261 }
262 return true;
263 });
264
265 var hours = +result[3];
266 if(amPm === 'p' && hours < 12){
267 result[3] = hours + 12; //e.g., 3pm -> 15
268 }else if(amPm === 'a' && hours == 12){
269 result[3] = 0; //12am -> 0
270 }
271 var dateObject = new IDate(result[0], result[1], result[2], result[3], result[4], result[5], result[6]);
272 return dateObject;
273 };
274
275 function _processPattern(pattern, applyPattern, applyLiteral, applyAll){
276 // summary:
277 // Process a pattern with literals in it
278
279 // Break up on single quotes, treat every other one as a literal, except '' which becomes '
280 var identity = function(x){return x;};
281 applyPattern = applyPattern || identity;
282 applyLiteral = applyLiteral || identity;
283 applyAll = applyAll || identity;
284
285 //split on single quotes (which escape literals in date format strings)
286 //but preserve escaped single quotes (e.g., o''clock)
287 var chunks = pattern.match(/(''|[^'])+/g);
288 var literal = pattern.charAt(0) == "'";
289
290 arr.forEach(chunks, function(chunk, i){
291 if(!chunk){
292 chunks[i]='';
293 }else{
294 chunks[i]=(literal ? applyLiteral : applyPattern)(chunk);
295 literal = !literal;
296 }
297 });
298 return applyAll(chunks.join(''));
299 }
300
301 function _buildDateTimeRE (tokens, bundle, options, pattern){
302 // based on and similar to dojo.date.locale._buildDateTimeRE
303
304 pattern = regexp.escapeString(pattern);
305 var locale = i18n.normalizeLocale(options.locale);
306
307 return pattern.replace(/([a-z])\1*/ig, function(match){
308
309 // Build a simple regexp. Avoid captures, which would ruin the tokens list
310 var s;
311 var c = match.charAt(0);
312 var l = match.length;
313 var p2 = '', p3 = '';
314 if(options.strict){
315 if(l > 1){ p2 = '0' + '{'+(l-1)+'}'; }
316 if(l > 2){ p3 = '0' + '{'+(l-2)+'}'; }
317 }else{
318 p2 = '0?'; p3 = '0{0,2}';
319 }
320 switch(c){
321 case 'y':
322 s = '\\d+';
323 break;
324 case 'M':
325 s = (l>2) ? '\\S+ ?\\S+' : p2+'[1-9]|1[0-2]';
326 break;
327 case 'd':
328 s = '[12]\\d|'+p2+'[1-9]|3[01]';
329 break;
330 case 'E':
331 s = '\\S+';
332 break;
333 case 'h': //hour (1-12)
334 s = p2+'[1-9]|1[0-2]';
335 break;
336 case 'k': //hour (0-11)
337 s = p2+'\\d|1[01]';
338 break;
339 case 'H': //hour (0-23)
340 s = p2+'\\d|1\\d|2[0-3]';
341 break;
342 case 'K': //hour (1-24)
343 s = p2+'[1-9]|1\\d|2[0-4]';
344 break;
345 case 'm':
346 case 's':
347 s = p2+'\\d|[0-5]\\d';
348 break;
349 case 'S':
350 s = '\\d{'+l+'}';
351 break;
352 case 'a':
353 var am = options.am || bundle['dayPeriods-format-wide-am'],
354 pm = options.pm || bundle['dayPeriods-format-wide-pm'];
355 if(options.strict){
356 s = am + '|' + pm;
357 }else{
358 s = am + '|' + pm;
359 if(am != am.toLowerCase()){ s += '|' + am.toLowerCase(); }
360 if(pm != pm.toLowerCase()){ s += '|' + pm.toLowerCase(); }
361 }
362 break;
363 default:
364 s = ".*";
365 }
366 if(tokens){ tokens.push(match); }
367 return "(" + s + ")"; // add capture
368 }).replace(/[\xa0 ]/g, "[\\s\\xa0]"); // normalize whitespace. Need explicit handling of \xa0 for IE. */
369 }
370
371 var _customFormats = [];
372 ilocale.addCustomFormats = function(/*String*/packageName, /*String*/bundleName){
373 // summary:
374 // Add a reference to a bundle containing localized custom formats to be
375 // used by date/time formatting and parsing routines.
376 _customFormats.push({pkg:packageName,name:bundleName});
377 };
378
379 ilocale._getIslamicBundle = function(/*String*/locale){
380 var islamic = {};
381 arr.forEach(_customFormats, function(desc){
382 var bundle = i18n.getLocalization(desc.pkg, desc.name, locale);
383 islamic = lang.mixin(islamic, bundle);
384 }, this);
385 return islamic; /*Object*/
386 };
387
388 ilocale.addCustomFormats("dojo.cldr","islamic");
389
390 ilocale.getNames = function(/*String*/item, /*String*/type, /*String?*/context, /*String?*/locale, /*dojox/date/islamic/Date?*/date){
391 // summary:
392 // Used to get localized strings from dojo.cldr for day or month names.
393 var label;
394 var lookup = ilocale._getIslamicBundle(locale);
395 var props = [item, context, type];
396 if(context == 'standAlone'){
397 var key = props.join('-');
398 label = lookup[key];
399 // Fall back to 'format' flavor of name
400 if(label[0] == 1){ label = undefined; } // kludge, in the absence of real aliasing support in dojo.cldr
401 }
402 props[1] = 'format';
403
404 // return by copy so changes won't be made accidentally to the in-memory model
405 return (label || lookup[props.join('-')]).concat(); /*Array*/
406 };
407
408
409 ilocale.weekDays = ilocale.getNames('days', 'wide', 'format');
410
411 ilocale.months = ilocale.getNames('months', 'wide', 'format');
412
413 return ilocale;
414 });