Debian Codegraph @

dijit/CalendarLite.js

raw symbols SCIP
1 define([
2 "dojo/_base/array", // array.forEach array.map
3 "dojo/_base/declare", // declare
4 "dojo/cldr/supplemental", // cldrSupplemental.getFirstDayOfWeek
5 "dojo/date", // date
6 "dojo/date/locale",
7 "dojo/date/stamp", // stamp.fromISOString
8 "dojo/dom", // dom.setSelectable
9 "dojo/dom-class", // domClass.contains
10 "dojo/dom-attr",
11 "dojo/_base/lang", // lang.getObject, lang.hitch
12 "dojo/on",
13 "dojo/sniff", // has("ie") has("webkit")
14 "dojo/string", // string.substitute
15 "./_WidgetBase",
16 "./_TemplatedMixin",
17 "dojo/text!./templates/Calendar.html",
18 "./a11yclick", // not used directly, but template has ondijitclick in it
19 "./hccss" // not used directly, but sets CSS class on <body>
20 ], function(array, declare, cldrSupplemental, date, locale, stamp, dom, domClass, domAttr, lang, on, has, string, _WidgetBase, _TemplatedMixin, template){
21
22
23 // module:
24 // dijit/CalendarLite
25
26 var CalendarLite = declare("dijit.CalendarLite", [_WidgetBase, _TemplatedMixin], {
27 // summary:
28 // Lightweight version of Calendar widget aimed towards mobile use
29 //
30 // description:
31 // A simple GUI for choosing a date in the context of a monthly calendar.
32 // This widget can't be used in a form because it doesn't serialize the date to an
33 // `<input>` field. For a form element, use dijit/form/DateTextBox instead.
34 //
35 // Note that the parser takes all dates attributes passed in the
36 // [RFC 3339 format](http://www.faqs.org/rfcs/rfc3339.html), e.g. `2005-06-30T08:05:00-07:00`
37 // so that they are serializable and locale-independent.
38 //
39 // Also note that this widget isn't keyboard accessible; use dijit.Calendar for that
40 // example:
41 // | var calendar = new dijit.CalendarLite({}, dojo.byId("calendarNode"));
42 //
43 // example:
44 // | <div data-dojo-type="dijit/CalendarLite"></div>
45
46 // Template for main calendar
47 templateString: template,
48
49 // Template for cell for a day of the week (ex: M)
50 dowTemplateString: '<th class="dijitReset dijitCalendarDayLabelTemplate" role="columnheader" scope="col"><span class="dijitCalendarDayLabel">${d}</span></th>',
51
52 // Templates for a single date (ex: 13), and for a row for a week (ex: 20 21 22 23 24 25 26)
53 dateTemplateString: '<td class="dijitReset" role="gridcell" data-dojo-attach-point="dateCells"><span class="dijitCalendarDateLabel" data-dojo-attach-point="dateLabels"></span></td>',
54 weekTemplateString: '<tr class="dijitReset dijitCalendarWeekTemplate" role="row">${d}${d}${d}${d}${d}${d}${d}</tr>',
55
56 // value: Date
57 // The currently selected Date, initially set to invalid date to indicate no selection.
58 value: new Date(""),
59 // TODO: for 2.0 make this a string (ISO format) rather than a Date
60
61 // datePackage: String
62 // JavaScript namespace to find calendar routines. If unspecified, uses Gregorian calendar routines
63 // at dojo/date and dojo/date/locale.
64 datePackage: "",
65 // TODO: for 2.0, replace datePackage with dateModule and dateLocalModule attributes specifying MIDs,
66 // or alternately just get rid of this completely and tell user to use module ID remapping
67 // via require
68
69 // dayWidth: String
70 // How to represent the days of the week in the calendar header. See locale
71 dayWidth: "narrow",
72
73 // tabIndex: String
74 // Order fields are traversed when user hits the tab key
75 tabIndex: "0",
76
77 // dayOffset: Integer
78 // (Optional) The first day of week override. By default the first day of week is determined
79 // for the current locale (extracted from the CLDR).
80 // Special value -1 (default value), means use locale dependent value.
81 dayOffset: -1,
82
83 // currentFocus: Date
84 // Date object containing the currently focused date, or the date which would be focused
85 // if the calendar itself was focused. Also indicates which year and month to display,
86 // i.e. the current "page" the calendar is on.
87 currentFocus: new Date(),
88
89 // Put the summary to the node with role=grid
90 _setSummaryAttr: "gridNode",
91
92 baseClass: "dijitCalendar dijitCalendarLite",
93
94 _isValidDate: function(/*Date*/ value){
95 // summary:
96 // Runs various tests on the value, checking that it's a valid date, rather
97 // than blank or NaN.
98 // tags:
99 // private
100 return value && !isNaN(value) && typeof value == "object" &&
101 value.toString() != this.constructor.prototype.value.toString();
102 },
103
104 _getValueAttr: function(){
105 // summary:
106 // Support get('value')
107
108 // this.value is set to 1AM, but return midnight, local time for back-compat
109 var storedVal = this._get("value");
110 if(storedVal && !isNaN(storedVal)){
111 var value = new this.dateClassObj(storedVal);
112 value.setHours(0, 0, 0, 0);
113
114 // If daylight savings pushes midnight to the previous date, fix the Date
115 // object to point at 1am so it will represent the correct day. See #9366
116 if(value.getDate() < storedVal.getDate()){
117 value = this.dateModule.add(value, "hour", 1);
118 }
119 return value;
120 }else{
121 return null;
122 }
123 },
124
125 _setValueAttr: function(/*Date|Number*/ value, /*Boolean*/ priorityChange){
126 // summary:
127 // Support set("value", ...)
128 // description:
129 // Set the current date and update the UI. If the date is disabled, the value will
130 // not change, but the display will change to the corresponding month.
131 // value:
132 // Either a Date or the number of seconds since 1970.
133 // tags:
134 // protected
135 if(typeof value == "string"){
136 value = stamp.fromISOString(value);
137 }
138 value = this._patchDate(value);
139
140 if(this._isValidDate(value) && !this.isDisabledDate(value, this.lang)){
141 this._set("value", value);
142
143 // Set focus cell to the new value. Arguably this should only happen when there isn't a current
144 // focus point. This will also repopulate the grid to new month/year if necessary.
145 this.set("currentFocus", value);
146
147 // Mark the selected date
148 this._markSelectedDates([value]);
149
150 if(this._created && (priorityChange || typeof priorityChange == "undefined")){
151 this.onChange(this.get('value'));
152 }
153 }else{
154 // clear value, and mark all dates as unselected
155 this._set("value", null);
156 this._markSelectedDates([]);
157 }
158 },
159
160 _patchDate: function(/*Date|Number*/ value){
161 // summary:
162 // Convert Number into Date, or copy Date object. Then, round to nearest day,
163 // setting to 1am to avoid issues when DST shift occurs at midnight, see #8521, #9366)
164 if(value || value === 0){
165 value = new this.dateClassObj(value);
166 value.setHours(1, 0, 0, 0);
167 }
168 return value;
169 },
170
171 _setText: function(node, text){
172 // summary:
173 // This just sets the content of node to the specified text.
174 // Can't do "node.innerHTML=text" because of an IE bug w/tables, see #3434.
175 // tags:
176 // private
177 while(node.firstChild){
178 node.removeChild(node.firstChild);
179 }
180 node.appendChild(node.ownerDocument.createTextNode(text));
181 },
182
183 _populateGrid: function(){
184 // summary:
185 // Fills in the calendar grid with each day (1-31).
186 // Call this on creation, when moving to a new month.
187 // tags:
188 // private
189
190 var month = new this.dateClassObj(this.currentFocus);
191 month.setDate(1);
192 month = this._patchDate(month); // needed if currentFocus is start or end of DST, see #17033
193
194 var firstDay = month.getDay(),
195 daysInMonth = this.dateModule.getDaysInMonth(month),
196 daysInPreviousMonth = this.dateModule.getDaysInMonth(this.dateModule.add(month, "month", -1)),
197 today = new this.dateClassObj(),
198 dayOffset = this.dayOffset >= 0 ? this.dayOffset : cldrSupplemental.getFirstDayOfWeek(this.lang);
199 if(dayOffset > firstDay){
200 dayOffset -= 7;
201 }
202
203 // If they didn't provide a summary, change the default summary to match with the new month
204 if(!this.summary){
205 var monthNames = this.dateLocaleModule.getNames('months', 'wide', 'standAlone', this.lang, month)
206 this.gridNode.setAttribute("summary", monthNames[month.getMonth()]);
207 }
208
209 // Mapping from date (as specified by number returned from Date.valueOf()) to corresponding <td>
210 this._date2cell = {};
211
212 // Iterate through dates in the calendar and fill in date numbers and style info
213 array.forEach(this.dateCells, function(template, idx){
214 var i = idx + dayOffset;
215 var date = new this.dateClassObj(month),
216 number, clazz = "dijitCalendar", adj = 0;
217
218 if(i < firstDay){
219 number = daysInPreviousMonth - firstDay + i + 1;
220 adj = -1;
221 clazz += "Previous";
222 }else if(i >= (firstDay + daysInMonth)){
223 number = i - firstDay - daysInMonth + 1;
224 adj = 1;
225 clazz += "Next";
226 }else{
227 number = i - firstDay + 1;
228 clazz += "Current";
229 }
230
231 if(adj){
232 date = this.dateModule.add(date, "month", adj);
233 }
234 date.setDate(number);
235
236 if(!this.dateModule.compare(date, today, "date")){
237 clazz = "dijitCalendarCurrentDate " + clazz;
238 }
239
240 if(this.isDisabledDate(date, this.lang)){
241 clazz = "dijitCalendarDisabledDate " + clazz;
242 template.setAttribute("aria-disabled", "true");
243 }else{
244 clazz = "dijitCalendarEnabledDate " + clazz;
245 template.removeAttribute("aria-disabled");
246 template.setAttribute("aria-selected", "false");
247 }
248
249 var clazz2 = this.getClassForDate(date, this.lang);
250 if(clazz2){
251 clazz = clazz2 + " " + clazz;
252 }
253
254 template.className = clazz + "Month dijitCalendarDateTemplate";
255
256 // Each cell has an associated integer value representing it's date
257 var dateVal = date.valueOf();
258 this._date2cell[dateVal] = template;
259 template.dijitDateValue = dateVal;
260
261 // Set Date string (ex: "13").
262
263 var localizedDate = date.getDateLocalized ? date.getDateLocalized(this.lang) : date.getDate()
264 this._setText(this.dateLabels[idx], localizedDate);
265 domAttr.set(template, 'aria-label', locale.format(date, {
266 selector: 'date',
267 formatLength: 'long'
268 }));
269 }, this);
270 },
271
272 _populateControls: function(){
273 // summary:
274 // Fill in localized month, and prev/current/next years
275 // tags:
276 // protected
277
278 var month = new this.dateClassObj(this.currentFocus);
279 month.setDate(1);
280
281 // set name of this month
282 this.monthWidget.set("month", month);
283
284 var y = month.getFullYear() - 1;
285 var d = new this.dateClassObj();
286 array.forEach(["previous", "current", "next"], function(name){
287 d.setFullYear(y++);
288 this._setText(this[name + "YearLabelNode"],
289 this.dateLocaleModule.format(d, {selector: 'year', locale: this.lang}));
290 }, this);
291 },
292
293 goToToday: function(){
294 // summary:
295 // Sets calendar's value to today's date
296 this.set('value', new this.dateClassObj());
297 },
298
299 constructor: function(params /*===== , srcNodeRef =====*/){
300 // summary:
301 // Create the widget.
302 // params: Object|null
303 // Hash of initialization parameters for widget, including scalar values (like title, duration etc.)
304 // and functions, typically callbacks like onClick.
305 // The hash can contain any of the widget's properties, excluding read-only properties.
306 // srcNodeRef: DOMNode|String?
307 // If a srcNodeRef (DOM node) is specified, replace srcNodeRef with my generated DOM tree
308
309 this.dateModule = params.datePackage ? lang.getObject(params.datePackage, false) : date;
310 this.dateClassObj = this.dateModule.Date || Date;
311 this.dateLocaleModule = params.datePackage ? lang.getObject(params.datePackage + ".locale", false) : locale;
312 },
313
314 _createMonthWidget: function(){
315 // summary:
316 // Creates the drop down button that displays the current month and lets user pick a new one
317
318 return CalendarLite._MonthWidget({
319 id: this.id + "_mddb",
320 lang: this.lang,
321 dateLocaleModule: this.dateLocaleModule
322 }, this.monthNode);
323 },
324
325 buildRendering: function(){
326 // Markup for days of the week (referenced from template)
327 var d = this.dowTemplateString,
328 dayNames = this.dateLocaleModule.getNames('days', this.dayWidth, 'standAlone', this.lang),
329 dayOffset = this.dayOffset >= 0 ? this.dayOffset : cldrSupplemental.getFirstDayOfWeek(this.lang);
330 this.dayCellsHtml = string.substitute([d, d, d, d, d, d, d].join(""), {d: ""}, function(){
331 return dayNames[dayOffset++ % 7];
332 });
333
334 // Markup for dates of the month (referenced from template), but without numbers filled in
335 var r = string.substitute(this.weekTemplateString, {d: this.dateTemplateString});
336 this.dateRowsHtml = [r, r, r, r, r, r].join("");
337
338 // Instantiate from template.
339 // dateCells and dateLabels arrays filled when _Templated parses my template.
340 this.dateCells = [];
341 this.dateLabels = [];
342 this.inherited(arguments);
343
344 dom.setSelectable(this.domNode, false);
345
346 var dateObj = new this.dateClassObj(this.currentFocus);
347
348 this.monthWidget = this._createMonthWidget();
349
350 this.set('currentFocus', dateObj, false); // draw the grid to the month specified by currentFocus
351 },
352
353 postCreate: function(){
354 this.inherited(arguments);
355 this._connectControls();
356 },
357
358 _connectControls: function(){
359 // summary:
360 // Set up connects for increment/decrement of months/years
361 // tags:
362 // protected
363
364 var connect = lang.hitch(this, function(nodeProp, part, amount){
365 this[nodeProp].dojoClick = true;
366 return on(this[nodeProp], "click", lang.hitch(this, function(){
367 this._setCurrentFocusAttr(this.dateModule.add(this.currentFocus, part, amount));
368 }));
369 });
370
371 this.own(
372 connect("incrementMonth", "month", 1),
373 connect("decrementMonth", "month", -1),
374 connect("nextYearLabelNode", "year", 1),
375 connect("previousYearLabelNode", "year", -1)
376 );
377 },
378
379 _setCurrentFocusAttr: function(/*Date*/ date, /*Boolean*/ forceFocus){
380 // summary:
381 // If the calendar currently has focus, then focuses specified date,
382 // changing the currently displayed month/year if necessary.
383 // If the calendar doesn't have focus, updates currently
384 // displayed month/year, and sets the cell that will get focus
385 // when Calendar is focused.
386 // forceFocus:
387 // If true, will focus() the cell even if calendar itself doesn't have focus
388
389 var oldFocus = this.currentFocus,
390 oldCell = this._getNodeByDate(oldFocus);
391 date = this._patchDate(date);
392
393 this._set("currentFocus", date);
394
395 // If the focus is on a different month than the current calendar month, switch the displayed month.
396 // Also will populate the grid initially, on Calendar creation.
397 if(!this._date2cell || this.dateModule.difference(oldFocus, date, "month") != 0){
398 this._populateGrid();
399 this._populateControls();
400 this._markSelectedDates([this.value]);
401 }
402
403 // set tabIndex=0 on new cell, and focus it (but only if Calendar itself is focused)
404 var newCell = this._getNodeByDate(date);
405 newCell.setAttribute("tabIndex", this.tabIndex);
406 if(this.focused || forceFocus){
407 newCell.focus();
408 }
409
410 // set tabIndex=-1 on old focusable cell
411 if(oldCell && oldCell != newCell){
412 if(has("webkit")){ // see #11064 about webkit bug
413 oldCell.setAttribute("tabIndex", "-1");
414 }else{
415 oldCell.removeAttribute("tabIndex");
416 }
417 }
418 },
419
420 focus: function(){
421 // summary:
422 // Focus the calendar by focusing one of the calendar cells
423 this._setCurrentFocusAttr(this.currentFocus, true);
424 },
425
426 _onDayClick: function(/*Event*/ evt){
427 // summary:
428 // Handler for day clicks, selects the date if appropriate
429 // tags:
430 // protected
431 evt.stopPropagation();
432 evt.preventDefault();
433 for(var node = evt.target; node && !node.dijitDateValue && node.dijitDateValue !== 0; node = node.parentNode){
434 ;
435 }
436 if(node && !domClass.contains(node, "dijitCalendarDisabledDate")){
437 this.set('value', node.dijitDateValue);
438 }
439 },
440
441 _getNodeByDate: function(/*Date*/ value){
442 // summary:
443 // Returns the cell corresponding to the date, or null if the date is not within the currently
444 // displayed month.
445 value = this._patchDate(value);
446 return value && this._date2cell ? this._date2cell[value.valueOf()] : null;
447 },
448
449 _markSelectedDates: function(/*Date[]*/ dates){
450 // summary:
451 // Marks the specified cells as selected, and clears cells previously marked as selected.
452 // For CalendarLite at most one cell is selected at any point, but this allows an array
453 // for easy subclassing.
454
455 // Function to mark a cell as selected or unselected
456 function mark(/*Boolean*/ selected, /*DomNode*/ cell){
457 domClass.toggle(cell, "dijitCalendarSelectedDate", selected);
458 cell.setAttribute("aria-selected", selected ? "true" : "false");
459 }
460
461 // Clear previously selected cells.
462 array.forEach(this._selectedCells || [], lang.partial(mark, false));
463
464 // Mark newly selected cells. Ignore dates outside the currently displayed month.
465 this._selectedCells = array.filter(array.map(dates, this._getNodeByDate, this), function(n){
466 return n;
467 });
468 array.forEach(this._selectedCells, lang.partial(mark, true));
469 },
470
471 onChange: function(/*Date*/ /*===== date =====*/){
472 // summary:
473 // Called only when the selected date has changed
474 },
475
476 isDisabledDate: function(/*===== dateObject, locale =====*/){
477 // summary:
478 // May be overridden to disable certain dates in the calendar e.g. `isDisabledDate=dojo.date.locale.isWeekend`
479 // dateObject: Date
480 // locale: String?
481 // tags:
482 // extension
483 /*=====
484 return false; // Boolean
485 =====*/
486 },
487
488 getClassForDate: function(/*===== dateObject, locale =====*/){
489 // summary:
490 // May be overridden to return CSS classes to associate with the date entry for the given dateObject,
491 // for example to indicate a holiday in specified locale.
492 // dateObject: Date
493 // locale: String?
494 // tags:
495 // extension
496
497 /*=====
498 return ""; // String
499 =====*/
500 }
501 });
502
503 CalendarLite._MonthWidget = declare("dijit.CalendarLite._MonthWidget", _WidgetBase, {
504 // summary:
505 // Displays name of current month padded to the width of the month
506 // w/the longest name, so that changing months doesn't change width.
507 //
508 // Create as:
509 // | new Calendar._MonthWidget({
510 // | lang: ...,
511 // | dateLocaleModule: ...
512 // | })
513
514 _setMonthAttr: function(month){
515 // summary:
516 // Set the current month to display as a label
517 var monthNames = this.dateLocaleModule.getNames('months', 'wide', 'standAlone', this.lang, month),
518 spacer =
519 (has("ie") == 6 ? "" : "<div class='dijitSpacer'>" +
520 array.map(monthNames,function(s){
521 return "<div>" + s + "</div>";
522 }).join("") + "</div>");
523
524 // Set name of current month and also fill in spacer element with all the month names
525 // (invisible) so that the maximum width will affect layout. But not on IE6 because then
526 // the center <TH> overlaps the right <TH> (due to a browser bug).
527 this.domNode.innerHTML =
528 spacer +
529 "<div class='dijitCalendarMonthLabel dijitCalendarCurrentMonthLabel'>" +
530 monthNames[month.getMonth()] + "</div>";
531 }
532 });
533
534 return CalendarLite;
535 });