Debian Codegraph @

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