source: Dev/trunk/src/client/dojox/widget/MultiSelectCalendar.js @ 485

Last change on this file since 485 was 483, checked in by hendrikvanantwerpen, 11 years ago

Added Dojo 1.9.3 release.

File size: 34.4 KB
Line 
1define("dojox/widget/MultiSelectCalendar", [
2    "dojo/main", "dijit",
3    "dojo/text!./MultiSelectCalendar/MultiSelectCalendar.html",
4    "dojo/cldr/supplemental",
5    "dojo/date",
6    "dojo/date/locale",
7    "dijit/_Widget", "dijit/_TemplatedMixin", "dijit/_WidgetsInTemplateMixin",
8        "dijit/_CssStateMixin", "dijit/form/DropDownButton", "dijit/typematic"
9],
10    function(dojo, dijit, template, supplemental, date, locale,
11                _Widget, _TemplatedMixin, _WidgetsInTemplateMixin,
12                _CssStateMixin, DropDownButton, typematic) {
13
14dojo.experimental("dojox.widget.MultiSelectCalendar");
15
16var MultiSelectCalendar = dojo.declare(
17        "dojox.widget.MultiSelectCalendar",
18        [_Widget, _TemplatedMixin, _WidgetsInTemplateMixin, _CssStateMixin],
19        {
20                // summary:
21                //              A simple GUI for choosing several dates in the context of a monthly calendar.
22                //
23                // description:
24                //              A simple GUI for choosing several dates in the context of a monthly calendar.
25                //              This widget serialises its selected dates to ISO dates or ISO ranges of dates,
26                //              depending on developer selection
27                //              Note that it accepts an Array of ISO dates as its input
28                //
29                // example:
30                //      |       var calendar = new dojox.widget.MultiSelectCalendar({value: ['2011-05-07,'2011-05-08',2011-05-09','2011-05-23']}, dojo.byId("calendarNode"));
31                //
32                // example:
33                //      |       <div dojoType="dojox.widget.MultiSelectCalendar"></div>
34
35                templateString: template,
36                widgetsInTemplate: true,
37
38                // value: Date
39                //              The currently selected Dates, initially set to an empty object to indicate no selection.
40                value: {},
41
42                // datePackage: String
43                //              JavaScript namespace to find Calendar routines.  Uses Gregorian Calendar routines
44                //              at dojo.date by default.
45                datePackage: "dojo.date",
46
47                // dayWidth: String
48                //              How to represent the days of the week in the calendar header. See dojo.date.locale
49                dayWidth: "narrow",
50
51                // tabIndex: String
52                //              Order fields are traversed when user hits the tab key
53                tabIndex: "0",
54               
55                // if returnIsoRanges is true, the selected dates will be returned as ISO ranges
56                // else each selected date will be returned sequentially
57                returnIsoRanges : false,
58               
59                // currentFocus: Date
60                //              Date object containing the currently focused date, or the date which would be focused
61                //              if the calendar itself was focused.   Also indicates which year and month to display,
62                //              i.e. the current "page" the calendar is on.
63                currentFocus: new Date(),
64
65                baseClass:"dijitCalendar",
66               
67                cssStateNodes: {
68                        "decrementMonth": "dijitCalendarArrow",
69                        "incrementMonth": "dijitCalendarArrow",
70                        "previousYearLabelNode": "dijitCalendarPreviousYear",
71                        "nextYearLabelNode": "dijitCalendarNextYear"                   
72                },
73
74                _areValidDates: function(/*Date*/ value){
75                        // summary:
76                        //              Runs various tests on each selected date, checking that they're a valid date, rather
77                        //              than blank or NaN.
78                        // tags:
79                        //              private
80                        for (var selDate in this.value){
81                                valid = (selDate && !isNaN(selDate) && typeof value == "object" && selDate.toString() != this.constructor.prototype.value.toString());
82                                if(!valid){ return false; }
83                        }
84                        return true;
85                },
86
87                _getValueAttr: function(){
88                        // summary:
89                        //              this method returns the list of selected dates in an array structure
90                        if(this.returnIsoRanges){
91                                datesWithRanges = this._returnDatesWithIsoRanges(this._sort());
92                                return datesWithRanges;
93                        }else{
94                                return this._sort();
95                        }
96                },
97               
98                _setValueAttr: function(/*Date|Number|array*/ value, /*Boolean*/ priorityChange){
99                        // summary:
100                        //              Support set("value", ...)
101                        // description:
102                        //              Set the passed dates to the selected date and updates the value of this widget
103                        //              to reflect that
104                        // value:
105                        //              Can be a Date, the number of milliseconds since 1970 or an array of ISO dates (['2011-07-01', '2001-06-01']).
106                        // tags:
107                        //              protected
108                       
109                        //If we are passed an array of ISO dates, we are going to mark each date in the list as selected
110                        //We perform the normalization of the passed date
111                        this.value = {};
112                        if(dojo.isArray(value)) {
113                                dojo.forEach(value,function(element, i){
114                                        //Each element of the array could be a date or a date range
115                                        var slashPosition = element.indexOf("/");
116                                        if(slashPosition == -1){
117                                                //The element is a single date
118                                                this.value[element] = 1;
119                                        }else{
120                                                //We have a slash somewhere in the string so this is an ISO date range
121                                                var dateA = dojo.date.stamp.fromISOString(element.substr(0,10));
122                                                var dateB = dojo.date.stamp.fromISOString(element.substr(11,10));
123                                               
124                                                this.toggleDate(dateA,[],[]);
125                                                if((dateA - dateB) > 0){
126                                                        //We select the first date then the rest is handled as if we had selected a range
127                                                        this._addToRangeRTL(dateA, dateB, [], []);     
128                                                }else{
129                                                        //We select the first date then the rest is handled as if we had selected a range
130                                                        this._addToRangeLTR(dateA, dateB, [], []);     
131                                                }
132                                        }
133                                },this);
134                        if(value.length > 0){
135                                this.focusOnLastDate(value[value.length-1]);
136                        }
137                        }else{
138                                if(value){
139                                        // convert from Number to Date, or make copy of Date object so that setHours() call below
140                                        // doesn't affect original value
141                                        value = new this.dateClassObj(value);
142                                }
143                                if(this._isValidDate(value)){
144                                        value.setHours(1, 0, 0, 0); // round to nearest day (1am to avoid issues when DST shift occurs at midnight, see #8521, #9366)
145       
146                                        if(!this.isDisabledDate(value, this.lang)){
147                                                dateIndex = dojo.date.stamp.toISOString(value).substring(0,10);
148                                               
149                                                this.value[dateIndex] = 1;
150               
151                                                // Set focus cell to the new value.   Arguably this should only happen when there isn't a current
152                                                // focus point.   This will also repopulate the grid, showing the new selected value (and possibly
153                                                // new month/year).
154                                                this.set("currentFocus", value);
155       
156                                                if(priorityChange || typeof priorityChange == "undefined"){
157                                                        this.onChange(this.get('value'));
158                                                        this.onValueSelected(this.get('value'));        // remove in 2.0
159                                                }
160                                        }
161                                }
162                        }
163                        this._populateGrid();
164                },
165                focusOnLastDate : function(lastElement){
166                        //We put the focus on the last date so that when the user re-clicks on the calendar it will be
167                        //on the proper month
168                        var slashPositionLastDate = lastElement.indexOf("/");
169                        var dateA,dateB;
170                        if(slashPositionLastDate == -1){
171                                //This is a singleDate
172                                lastDate = lastElement;
173                        }else{
174                                dateA=new dojo.date.stamp.fromISOString(lastElement.substr(0,10));
175                                dateB=new dojo.date.stamp.fromISOString(lastElement.substr(11,10));
176                                if((dateA - dateB) > 0){
177                                        lastDate = dateA;
178                                }else{
179                                        lastDate = dateB;
180                                }
181                        }
182                        this.set("currentFocus", lastDate);             
183                },
184                _isValidDate: function(/*Date*/ value){
185                        // summary:
186                        //              Runs various tests on the value, checking that it's a valid date, rather
187                        //              than blank or NaN.
188                        // tags:
189                        //              private
190                        return value && !isNaN(value) && typeof value == "object" &&
191                                value.toString() != this.constructor.prototype.value.toString();
192                },
193                _setText: function(node, text){
194                        // summary:
195                        //              This just sets the content of node to the specified text.
196                        //              Can't do "node.innerHTML=text" because of an IE bug w/tables, see #3434.
197                        // tags:
198                        //              private
199                        while(node.firstChild){
200                                node.removeChild(node.firstChild);
201                        }
202                        node.appendChild(dojo.doc.createTextNode(text));
203                },
204
205                _populateGrid: function(){
206                        // summary:
207                        //              Fills in the calendar grid with each day (1-31)
208                        // tags:
209                        //              private
210
211                        var month = new this.dateClassObj(this.currentFocus);
212                        month.setDate(1);
213
214                        var firstDay = month.getDay(),
215                                daysInMonth = this.dateFuncObj.getDaysInMonth(month),
216                                daysInPreviousMonth = this.dateFuncObj.getDaysInMonth(this.dateFuncObj.add(month, "month", -1)),
217                                today = new this.dateClassObj(),
218                                dayOffset = dojo.cldr.supplemental.getFirstDayOfWeek(this.lang);
219                        if(dayOffset > firstDay){ dayOffset -= 7; }
220
221                        //List of all 42 displayed days in the calendar
222                        this.listOfNodes = dojo.query(".dijitCalendarDateTemplate", this.domNode);
223
224                        // Iterate through dates in the calendar and fill in date numbers and style info
225                        this.listOfNodes.forEach(function(template, i){
226                                i += dayOffset;
227                                var date = new this.dateClassObj(month),
228                                        number, clazz = "dijitCalendar", adj = 0;
229
230                                if(i < firstDay){
231                                        number = daysInPreviousMonth - firstDay + i + 1;
232                                        adj = -1;
233                                        clazz += "Previous";
234                                }else if(i >= (firstDay + daysInMonth)){
235                                        number = i - firstDay - daysInMonth + 1;
236                                        adj = 1;
237                                        clazz += "Next";
238                                }else{
239                                        number = i - firstDay + 1;
240                                        clazz += "Current";
241                                }
242
243                                if(adj){
244                                        date = this.dateFuncObj.add(date, "month", adj);
245                                }
246                                date.setDate(number);
247
248                                if(!this.dateFuncObj.compare(date, today, "date")){
249                                        clazz = "dijitCalendarCurrentDate " + clazz;
250                                }
251
252                                //If the date falls outside of the min or max constraints, we do nothing
253                                dateIndex = dojo.date.stamp.toISOString(date).substring(0,10);
254                               
255                                if(!this.isDisabledDate(date, this.lang)){
256                                        //If the node is already selected, the user clicking on it once more will deselect it
257                                        //so we will destroy it in the value object. If the date was not previously selected
258                                        //The user wants to select it so we add it to the value object
259                                        if(this._isSelectedDate(date, this.lang)){
260                                                if(this.value[dateIndex]){
261                                                        clazz = "dijitCalendarSelectedDate " + clazz;
262                                                }else{
263                                                        clazz = clazz.replace("dijitCalendarSelectedDate ","");
264                                                }
265                                        }
266                                }
267                                if(this._isSelectedDate(date, this.lang)){
268                                        clazz = "dijitCalendarBrowsingDate " + clazz;
269                                }
270
271                                if(this.isDisabledDate(date, this.lang)){
272                                        clazz = "dijitCalendarDisabledDate " + clazz;
273                                }
274
275                                var clazz2 = this.getClassForDate(date, this.lang);
276                                if(clazz2){
277                                        clazz = clazz2 + " " + clazz;
278                                }
279
280                                template.className = clazz + "Month dijitCalendarDateTemplate";
281                                template.dijitDateValue = date.valueOf();                               // original code
282                                dojo.attr(template, "dijitDateValue", date.valueOf());  // so I can dojo.query() it
283                                var label = dojo.query(".dijitCalendarDateLabel", template)[0],
284                                        text = date.getDateLocalized ? date.getDateLocalized(this.lang) : date.getDate();
285                                this._setText(label, text);
286                        }, this);
287
288                        // Repopulate month drop down list based on current year.
289                        // Need to do this to hide leap months in Hebrew calendar.
290                        var monthNames = this.dateLocaleModule.getNames('months', 'wide', 'standAlone', this.lang, month);
291                        this.monthDropDownButton.dropDown.set("months", monthNames);
292
293                        // Set name of current month and also fill in spacer element with all the month names
294                        // (invisible) so that the maximum width will affect layout.   But not on IE6 because then
295                        // the center <TH> overlaps the right <TH> (due to a browser bug).
296                        this.monthDropDownButton.containerNode.innerHTML =
297                                (dojo.isIE == 6 ? "" : "<div class='dijitSpacer'>" + this.monthDropDownButton.dropDown.domNode.innerHTML + "</div>") +
298                                "<div class='dijitCalendarMonthLabel dijitCalendarCurrentMonthLabel'>" +  monthNames[month.getMonth()] + "</div>";
299
300                        // Fill in localized prev/current/next years
301                        var y = month.getFullYear() - 1;
302                        var d = new this.dateClassObj();
303                        dojo.forEach(["previous", "current", "next"], function(name){
304                                d.setFullYear(y++);
305                                this._setText(this[name+"YearLabelNode"],
306                                        this.dateLocaleModule.format(d, {selector:'year', locale:this.lang}));
307                        }, this);
308                },
309
310                goToToday: function(){
311                        // summary:
312                        //              We go to today but we do no select it
313                        this.set('currentFocus', new this.dateClassObj(), false);
314                },
315
316                constructor: function(/*Object*/args){
317                        var dateClass = (args.datePackage && (args.datePackage != "dojo.date"))? args.datePackage + ".Date" : "Date";
318                        this.dateClassObj = dojo.getObject(dateClass, false);
319                        this.datePackage = args.datePackage || this.datePackage;
320                        this.dateFuncObj = dojo.getObject(this.datePackage, false);
321                        this.dateLocaleModule = dojo.getObject(this.datePackage + ".locale", false);
322                },
323
324                buildRendering: function(){
325                        this.inherited(arguments);
326                        dojo.setSelectable(this.domNode, false);
327
328                        var cloneClass = dojo.hitch(this, function(clazz, n){
329                                var template = dojo.query(clazz, this.domNode)[0];
330                                for(var i=0; i<n; i++){
331                                        template.parentNode.appendChild(template.cloneNode(true));
332                                }
333                        });
334
335                        // clone the day label and calendar day templates 6 times to make 7 columns
336                        cloneClass(".dijitCalendarDayLabelTemplate", 6);
337                        cloneClass(".dijitCalendarDateTemplate", 6);
338
339                        // now make 6 week rows
340                        cloneClass(".dijitCalendarWeekTemplate", 5);
341
342                        // insert localized day names in the header
343                        var dayNames = this.dateLocaleModule.getNames('days', this.dayWidth, 'standAlone', this.lang);
344                        var dayOffset = dojo.cldr.supplemental.getFirstDayOfWeek(this.lang);
345                        dojo.query(".dijitCalendarDayLabel", this.domNode).forEach(function(label, i){
346                                this._setText(label, dayNames[(i + dayOffset) % 7]);
347                        }, this);
348
349                        var dateObj = new this.dateClassObj(this.currentFocus);
350
351                        this.monthDropDownButton.dropDown = new MonthDropDown({
352                                id: this.id + "_mdd",
353                                onChange: dojo.hitch(this, "_onMonthSelect")
354                        });
355
356                        this.set('currentFocus', dateObj, false);       // draw the grid to the month specified by currentFocus
357
358                        // Set up repeating mouse behavior for increment/decrement of months/years
359                        var _this = this;
360                        var typematic = function(nodeProp, dateProp, adj){
361                                _this._connects.push(
362                                        dijit.typematic.addMouseListener(_this[nodeProp], _this, function(count){
363                                                if(count >= 0){ _this._adjustDisplay(dateProp, adj); }
364                                        }, 0.8, 500)
365                                );
366                        };
367                        typematic("incrementMonth", "month", 1);
368                        typematic("decrementMonth", "month", -1);
369                        typematic("nextYearLabelNode", "year", 1);
370                        typematic("previousYearLabelNode", "year", -1);
371                },
372
373                _adjustDisplay: function(/*String*/ part, /*int*/ amount){
374                        // summary:
375                        //              Moves calendar forwards or backwards by months or years
376                        // part:
377                        //              "month" or "year"
378                        // amount:
379                        //              Number of months or years
380                        // tags:
381                        //              private
382                        this._setCurrentFocusAttr(this.dateFuncObj.add(this.currentFocus, part, amount));
383                },
384
385                _setCurrentFocusAttr: function(/*Date*/ date, /*Boolean*/ forceFocus){
386                        // summary:
387                        //              If the calendar currently has focus, then focuses specified date,
388                        //              changing the currently displayed month/year if necessary.
389                        //              If the calendar doesn't have focus, updates currently
390                        //              displayed month/year, and sets the cell that will get focus.
391                        // forceFocus:
392                        //              If true, will focus() the cell even if calendar itself doesn't have focus
393
394                        var oldFocus = this.currentFocus,
395                                oldCell = oldFocus ? dojo.query("[dijitDateValue=" + oldFocus.valueOf() + "]", this.domNode)[0] : null;
396
397                        // round specified value to nearest day (1am to avoid issues when DST shift occurs at midnight, see #8521, #9366)
398                        date = new this.dateClassObj(date);
399                        date.setHours(1, 0, 0, 0);
400
401                        this._set("currentFocus", date);
402                        var currentMonth = dojo.date.stamp.toISOString(date).substring(0,7);
403                        //We only redraw the grid if we're in a new month
404                        if(currentMonth != this.previousMonth){
405                                this._populateGrid();
406                                this.previousMonth = currentMonth;
407                        }
408
409                        // set tabIndex=0 on new cell, and focus it (but only if Calendar itself is focused)
410                        var newCell = dojo.query("[dijitDateValue='" + date.valueOf() + "']", this.domNode)[0];
411                        newCell.setAttribute("tabIndex", this.tabIndex);
412                        if(this._focused || forceFocus){
413                                newCell.focus();
414                        }
415
416                        // set tabIndex=-1 on old focusable cell
417                        if(oldCell && oldCell != newCell){
418                                if(dojo.isWebKit){      // see #11064 about webkit bug
419                                        oldCell.setAttribute("tabIndex", "-1");
420                                }else{
421                                                oldCell.removeAttribute("tabIndex");                           
422                                }
423                        }
424                },
425
426                focus: function(){
427                        // summary:
428                        //              Focus the calendar by focusing one of the calendar cells
429                        this._setCurrentFocusAttr(this.currentFocus, true);
430                },
431
432                _onMonthSelect: function(/*Number*/ newMonth){
433                        // summary:
434                        //              Handler for when user selects a month from the drop down list
435                        // tags:
436                        //              protected
437
438                        // move to selected month, bounding by the number of days in the month
439                        // (ex: dec 31 --> jan 28, not jan 31)
440                        this.currentFocus = this.dateFuncObj.add(this.currentFocus, "month",
441                                newMonth - this.currentFocus.getMonth());
442                        this._populateGrid();
443                },
444               
445                toggleDate : function(/*date*/ dateToToggle, /*array of dates*/ selectedDates, /*array of dates*/ unselectedDates){
446                       
447                        //Obtain CSS class before toggling if necessary
448                        var dateIndex = dojo.date.stamp.toISOString(dateToToggle).substring(0,10);                       
449                        //If previously selected we unselect and vice-versa
450                        if(this.value[dateIndex]){
451                                this.unselectDate(dateToToggle, unselectedDates);                       
452                        }else{
453                                this.selectDate(dateToToggle, selectedDates);
454                        }               
455                },
456               
457                selectDate : function(/*date*/ dateToSelect, /*array of dates*/ selectedDates){
458                        //Selects the passed iso date, changes its class and records it in the selected dates array
459                        var node = this._getNodeByDate(dateToSelect);
460                        var clazz = node.className;
461                        var dateIndex = dojo.date.stamp.toISOString(dateToSelect).substring(0,10);
462                        this.value[dateIndex] = 1;
463                        selectedDates.push(dateIndex);                 
464                        clazz = "dijitCalendarSelectedDate " + clazz;
465                        //We update CSS class
466                        node.className = clazz;
467                },
468               
469                unselectDate : function(/*date*/ dateToUnselect, /*array of dates*/ unselectedDates){
470                        //Unselects the passed iso date, changes its class and records it in the unselected dates array
471                        var node = this._getNodeByDate(dateToUnselect);
472                        var clazz = node.className;
473                        var dateIndex = dojo.date.stamp.toISOString(dateToUnselect).substring(0,10);
474                        delete(this.value[dateIndex]);
475                        unselectedDates.push(dateIndex);
476                        clazz = clazz.replace("dijitCalendarSelectedDate ","");
477                        //We update CSS class
478                        node.className = clazz;
479                },
480
481                _getNodeByDate : function(/*ISO date*/ dateNode){
482                        //return the node that corresponds to the passed ISO date
483                        var firstDate = new this.dateClassObj(this.listOfNodes[0].dijitDateValue);
484                        var difference = Math.abs(dojo.date.difference(firstDate, dateNode, "day"));
485                        return this.listOfNodes[difference];
486                },
487
488                _onDayClick: function(/*Event*/ evt){
489                        // summary:
490                        //              Handler for day clicks, selects the date if appropriate
491                        // tags:
492                        //              protected
493                       
494                        //If we coming out of selecting a range, we need to skip this onDayClick or else we
495                        //are going to deselect a date that has just been selected or deselect one that just was
496                        //selected
497                                dojo.stopEvent(evt);
498                                for(var node = evt.target; node && !node.dijitDateValue; node = node.parentNode);
499                                if(node && !dojo.hasClass(node, "dijitCalendarDisabledDate")){
500                                        value = new this.dateClassObj(node.dijitDateValue);
501                                        if(!this.rangeJustSelected){
502                                                this.toggleDate(value,[],[]);
503                                                //To record the date that was selected prior to the one currently selected
504                                                //needed in the event we are selecting a range of dates
505                                                this.previouslySelectedDay = value;
506                                                this.set("currentFocus", value);
507                                                this.onValueSelected([dojo.date.stamp.toISOString(value).substring(0,10)]);
508                                               
509                                        }else{
510                                                this.rangeJustSelected = false;
511                                                this.set("currentFocus", value);
512                                        }
513                                }
514                },
515
516                _onDayMouseOver: function(/*Event*/ evt){
517                        // summary:
518                        //              Handler for mouse over events on days, sets hovered style
519                        // tags:
520                        //              protected
521
522                        // event can occur on <td> or the <span> inside the td,
523                        // set node to the <td>.
524                        var node =
525                                dojo.hasClass(evt.target, "dijitCalendarDateLabel") ?
526                                evt.target.parentNode :
527                                evt.target;
528
529                        if(node && (node.dijitDateValue || node == this.previousYearLabelNode || node == this.nextYearLabelNode) ){
530                                dojo.addClass(node, "dijitCalendarHoveredDate");
531                                this._currentNode = node;
532                        }
533                },
534                _setEndRangeAttr: function(/*Date*/ value){
535                        // description:
536                        //              records the end of a date range
537                        // tags:
538                        //              protected
539                        value = new this.dateClassObj(value);
540                        value.setHours(1); // to avoid issues when DST shift occurs at midnight, see #8521, #9366
541                        this.endRange = value;
542                },
543                _getEndRangeAttr: function(){
544                //              Returns the EndRange date that is set when selecting a range
545                        var value = new this.dateClassObj(this.endRange);
546                        value.setHours(0, 0, 0, 0); // return midnight, local time for back-compat
547               
548                        // If daylight savings pushes midnight to the previous date, fix the Date
549                        // object to point at 1am so it will represent the correct day. See #9366
550                        if(value.getDate() < this.endRange.getDate()){
551                                value = this.dateFuncObj.add(value, "hour", 1);
552                        }
553                        return value;
554                },
555
556                _onDayMouseOut: function(/*Event*/ evt){
557                        // summary:
558                        //              Handler for mouse out events on days, clears hovered style
559                        // tags:
560                        //              protected
561       
562                        if(!this._currentNode){ return; }
563                       
564                        // if mouse out occurs moving from <td> to <span> inside <td>, ignore it
565                        if(evt.relatedTarget && evt.relatedTarget.parentNode == this._currentNode){ return; }
566                        var cls = "dijitCalendarHoveredDate";
567                        if(dojo.hasClass(this._currentNode, "dijitCalendarActiveDate")) {
568                                cls += " dijitCalendarActiveDate";
569                        }
570                        dojo.removeClass(this._currentNode, cls);
571                        this._currentNode = null;
572                },
573                _onDayMouseDown: function(/*Event*/ evt){
574                        var node = evt.target.parentNode;
575                        if(node && node.dijitDateValue){
576                                dojo.addClass(node, "dijitCalendarActiveDate");
577                                this._currentNode = node;
578                        }
579                        //if shift is pressed, we know the user is selecting a range,
580                        //in which case we are going to select a range of date
581                        if(evt.shiftKey && this.previouslySelectedDay){
582                                //necessary to know whether or not we are in the process of selecting a range of dates 
583                                this.selectingRange = true;
584                                this.set('endRange', node.dijitDateValue);
585                                this._selectRange();
586                        }else{
587                                this.selectingRange = false;
588                                this.previousRangeStart = null;
589                                this.previousRangeEnd = null;
590                        }
591                },
592               
593                _onDayMouseUp: function(/*Event*/ evt){
594                        var node = evt.target.parentNode;
595                        if(node && node.dijitDateValue){
596                                dojo.removeClass(node, "dijitCalendarActiveDate");
597                        }
598                },
599
600//TODO: use typematic
601                handleKey: function(/*Event*/ evt){
602                        // summary:
603                        //              Provides keyboard navigation of calendar.
604                        // description:
605                        //              Called from _onKeyDown() to handle keypress on a stand alone Calendar,
606                        //              and also from `dijit.form._DateTimeTextBox` to pass a keypress event
607                        //              from the `dijit.form.DateTextBox` to be handled in this widget
608                        // returns:
609                        //              False if the key was recognized as a navigation key,
610                        //              to indicate that the event was handled by Calendar and shouldn't be propogated
611                        // tags:
612                        //              protected
613                        var dk = dojo.keys,
614                                increment = -1,
615                                interval,
616                                newValue = this.currentFocus;
617                        switch(evt.keyCode){
618                                case dk.RIGHT_ARROW:
619                                        increment = 1;
620                                        //fallthrough...
621                                case dk.LEFT_ARROW:
622                                        interval = "day";
623                                        if(!this.isLeftToRight()){ increment *= -1; }
624                                        break;
625                                case dk.DOWN_ARROW:
626                                        increment = 1;
627                                        //fallthrough...
628                                case dk.UP_ARROW:
629                                        interval = "week";
630                                        break;
631                                case dk.PAGE_DOWN:
632                                        increment = 1;
633                                        //fallthrough...
634                                case dk.PAGE_UP:
635                                        interval = evt.ctrlKey || evt.altKey ? "year" : "month";
636                                        break;
637                                case dk.END:
638                                        // go to the next month
639                                        newValue = this.dateFuncObj.add(newValue, "month", 1);
640                                        // subtract a day from the result when we're done
641                                        interval = "day";
642                                        //fallthrough...
643                                case dk.HOME:
644                                        newValue = new this.dateClassObj(newValue);
645                                        newValue.setDate(1);
646                                        break;
647                                case dk.ENTER:
648                                case dk.SPACE:
649                                        if(evt.shiftKey && this.previouslySelectedDay){
650                                                this.selectingRange = true;
651                                                this.set('endRange', newValue);
652                                                this._selectRange();
653                                        }else{
654                                                this.selectingRange = false;                           
655                                                this.toggleDate(newValue,[],[]);
656                                                //We record the selected date as the previous one
657                                                //In case we are selecting the first date of a range
658                                                this.previouslySelectedDay = newValue;
659                                                this.previousRangeStart = null;
660                                                this.previousRangeEnd = null;
661                                                this.onValueSelected([dojo.date.stamp.toISOString(newValue).substring(0,10)]);
662                                               
663                                        }
664                                        break;
665                                default:
666                                        return true;
667                        }
668
669                        if(interval){
670                                newValue = this.dateFuncObj.add(newValue, interval, increment);
671                        }
672
673                        this.set("currentFocus", newValue);
674
675                        return false;
676                },
677
678                _onKeyDown: function(/*Event*/ evt){
679                        // summary:
680                        //              For handling keypress events on a stand alone calendar
681                        if(!this.handleKey(evt)){
682                                dojo.stopEvent(evt);
683                        }
684                },
685               
686                _removeFromRangeLTR : function(/*date*/ beginning, /*date*/ end, /*array*/selectedDates, /*array*/unselectedDates){
687        //In this method we remove some dates from a range from left to right
688                        difference = Math.abs(dojo.date.difference(beginning, end, "day"));
689                        for(var i = 0; i <= difference; i++){
690                                var nextDay = dojo.date.add(beginning, 'day',i);
691                                this.toggleDate(nextDay, selectedDates, unselectedDates);
692                        }
693                        if(this.previousRangeEnd == null){
694                                //necessary to keep track of the previous range's end date
695                                this.previousRangeEnd = end;
696                        }else{
697                                if(dojo.date.compare(end, this.previousRangeEnd, 'date') > 0 )
698                                        this.previousRangeEnd = end;
699                        }
700                        if(this.previousRangeStart == null){
701                                //necessary to keep track of the previous range's start date
702                                this.previousRangeStart = end;
703                        }else{
704                                if(dojo.date.compare(end, this.previousRangeStart, 'date') > 0 )
705                                        this.previousRangeStart = end;
706                        }
707                        this.previouslySelectedDay = dojo.date.add(nextDay, 'day',1);   
708                },
709                _removeFromRangeRTL : function(/*date*/ beginning, /*date*/ end, /*array*/selectedDates, /*array*/unselectedDates){
710                        //If the end of the range is earlier than the beginning (back in time),
711                        //we are going to start from the end and move backward
712       
713                        difference = Math.abs(dojo.date.difference(beginning, end, "day"));
714                        for(var i = 0; i <= difference; i++){
715                                var nextDay = dojo.date.add(beginning, 'day',-i);
716                                this.toggleDate(nextDay, selectedDates, unselectedDates);
717                        }
718                        if(this.previousRangeEnd == null){
719                                this.previousRangeEnd = end;
720                        }else{
721                                if(dojo.date.compare(end, this.previousRangeEnd, 'date') < 0 ){
722                                        this.previousRangeEnd = end;
723                                }
724                        }
725                        if(this.previousRangeStart == null){
726                                this.previousRangeStart = end;
727                        }else{
728                                if(dojo.date.compare(end, this.previousRangeStart, 'date') < 0 ){
729                                        this.previousRangeStart = end;
730                                }
731                        }
732                        this.previouslySelectedDay = dojo.date.add(nextDay, 'day',-1);
733                },
734                _addToRangeRTL : function(/*date*/ beginning, /*date*/ end, /*array*/selectedDates, /*array*/unselectedDates){
735               
736                        difference = Math.abs(dojo.date.difference(beginning, end, "day"));
737                        //If the end of the range is earlier than the beginning (back in time),
738                        //we are going to start from the end and move backward
739                        for(var i = 1; i <= difference; i++){
740                                var nextDay = dojo.date.add(beginning, 'day',-i);
741                                this.toggleDate(nextDay, selectedDates, unselectedDates);
742                        }
743       
744                        if(this.previousRangeStart == null){
745                                this.previousRangeStart = end;
746                        }else{
747                                if(dojo.date.compare(end, this.previousRangeStart, 'date') < 0 ){
748                                        this.previousRangeStart = end;
749                                }
750                        }
751                        if(this.previousRangeEnd == null){
752                                this.previousRangeEnd = beginning;
753                        }else{
754                                if(dojo.date.compare(beginning, this.previousRangeEnd, 'date') > 0 ){
755                                        this.previousRangeEnd = beginning;
756                                }
757                        }
758                        this.previouslySelectedDay = nextDay;
759                },
760                _addToRangeLTR : function(/*date*/ beginning, /*date*/ end, /*array*/selectedDates, /*array*/unselectedDates){
761                        //If the end of the range is later than the beginning,
762                        //adding dates from left to right
763                        difference = Math.abs(dojo.date.difference(beginning, end, "day"));
764                        for(var i = 1; i <= difference; i++){
765                                var nextDay = dojo.date.add(beginning, 'day',i);
766                                this.toggleDate(nextDay, selectedDates, unselectedDates);
767                        }
768                        if(this.previousRangeStart == null){
769                                this.previousRangeStart = beginning;
770                        }else{
771                                if(dojo.date.compare(beginning, this.previousRangeStart, 'date') < 0 ){
772                                        this.previousRangeStart = beginning;
773                                }
774                        }
775                        if(this.previousRangeEnd == null){
776                                this.previousRangeEnd = end;
777                        }else{
778                                if(dojo.date.compare(end, this.previousRangeEnd, 'date') > 0 ){
779                                        this.previousRangeEnd = end;
780                                }
781                        }
782                        this.previouslySelectedDay = nextDay;
783                },
784                _selectRange : function(){
785                        //This method will toggle the dates in the selected range.
786                        var selectedDates = []; //Will gather the list of ISO dates that are selected
787                        var unselectedDates = []; //Will gather the list of ISO dates that are unselected
788                        var beginning = this.previouslySelectedDay;
789                        var end = this.get('endRange');
790                       
791                        if(!this.previousRangeStart && !this.previousRangeEnd){
792                                removingFromRange = false;
793                        }else{
794                                if((dojo.date.compare(end, this.previousRangeStart, 'date') < 0) || (dojo.date.compare(end, this.previousRangeEnd, 'date') > 0)){
795                                //We are adding to range
796                                        removingFromRange = false;
797                                }else{// Otherwise we are removing from the range
798                                        removingFromRange = true;
799                                }
800                        }
801                        if(removingFromRange == true){
802                                if(dojo.date.compare(end, beginning, 'date') < 0){
803                                        //We are removing from the range, starting from the end (Right to left)
804                                        this._removeFromRangeRTL(beginning, end, selectedDates, unselectedDates);
805                                }else{
806                                //The end of the range is later in time than the beginning: We go from left to right
807                                        this._removeFromRangeLTR(beginning, end, selectedDates, unselectedDates);
808                                }
809                        }else{
810                                //We are adding to the range
811                                if(dojo.date.compare(end, beginning, 'date') < 0){
812                                        this._addToRangeRTL(beginning, end, selectedDates, unselectedDates);
813                                }else{
814                                        this._addToRangeLTR(beginning, end, selectedDates, unselectedDates);
815                                }
816                        }
817                        //We call the extension point with the changed dates
818                        if(selectedDates.length > 0){
819                                this.onValueSelected(selectedDates);
820                        }
821                        if(unselectedDates.length > 0){
822                                this.onValueUnselected(unselectedDates);
823                        }
824                        this.rangeJustSelected = true; //Indicates that we just selected a range.
825                },
826
827                onValueSelected: function(/*array of ISO dates*/ dates){
828                        // summary:
829                        //              Notification that a date cell or more were selected.
830                        // description:
831                        //              Passes on the list of ISO dates that are selected
832                        // tags:
833                        //              protected
834                },
835
836                onValueUnselected: function(/*array of ISO dates*/ dates){
837                        // summary:
838                        //              Notification that a date cell or more were unselected.
839                        // description:
840                        //              Passes on the list of ISO dates that are unselected
841                        // tags:
842                        //              protected
843                },
844                onChange: function(/*Date*/ date){
845                        // summary:
846                        //              Called only when the selected date has changed
847                },
848
849                _isSelectedDate: function(/*Date*/ dateObject, /*String?*/ locale){
850                        // summary:
851                        //              Returns true if the passed date is part of the selected dates of the calendar
852                       
853                                dateIndex = dojo.date.stamp.toISOString(dateObject).substring(0,10);
854                                return this.value[dateIndex];
855                },
856
857                isDisabledDate: function(/*Date*/ dateObject, /*String?*/ locale){
858                        // summary:
859                        //              May be overridden to disable certain dates in the calendar e.g. `isDisabledDate=dojo.date.locale.isWeekend`
860                        // tags:
861                        //              extension
862/*=====
863                        return false; // Boolean
864=====*/
865                },
866
867                getClassForDate: function(/*Date*/ dateObject, /*String?*/ locale){
868                        // summary:
869                        //              May be overridden to return CSS classes to associate with the date entry for the given dateObject,
870                        //              for example to indicate a holiday in specified locale.
871                        // tags:
872                        //              extension
873
874/*=====
875                        return ""; // String
876=====*/
877                },
878                _sort : function(){
879                        //This function returns a sorted version of the value array that represents the selected dates.
880                        if(this.value == {}){return [];}
881                        //We create an array of date objects with the dates that were selected by the user.
882                        var selectedDates = [];
883                        for (var selDate in this.value){
884                                selectedDates.push(selDate);
885                        }
886                        //Actual sorting
887                        selectedDates.sort(function(a, b){
888                                var dateA=new Date(a), dateB=new Date(b);
889                                return dateA-dateB;
890                        });
891                        return selectedDates;
892                },
893                _returnDatesWithIsoRanges : function(selectedDates /*Array of sorted ISO dates*/){
894                //this method receives a sorted array of dates and returns an array of dates and date ranges where
895                //such range exist. For instance when passed with selectedDates = ['2010-06-14', '2010-06-15', '2010-12-25']
896                //it would return [2010-06-14/2010-06-15,  '2010-12-25']
897                var returnDates = [];
898                if(selectedDates.length > 1){
899                        //initialisation
900                        var weHaveRange = false,
901                                rangeCount = 0,
902                                startRange = null,
903                                lastDayRange = null,
904                                previousDate = dojo.date.stamp.fromISOString(selectedDates[0]);
905                       
906                        for(var i = 1; i < selectedDates.length+1; i++){
907                                currentDate = dojo.date.stamp.fromISOString(selectedDates[i]);
908                                if(weHaveRange){
909                                //We are in the middle of a range                               
910                                        difference = Math.abs(dojo.date.difference(previousDate, currentDate, "day"));
911                                        if(difference == 1){
912                                                //we continue with the range
913                                                lastDayRange = currentDate;
914                                        }else{
915                                                //end of the range, reset variables for maybe the next range..
916                                                range = dojo.date.stamp.toISOString(startRange).substring(0,10)
917                                                                + "/" + dojo.date.stamp.toISOString(lastDayRange).substring(0,10);
918                                                returnDates.push(range);
919                                                weHaveRange = false;
920                                        }
921                                }else{
922                                        //We are not in a range to begin with
923                                        difference = Math.abs(dojo.date.difference(previousDate, currentDate, "day"));
924                                        if(difference == 1){
925                                                //These are two consecutive dates: This is a range!
926                                                weHaveRange = true;
927                                                startRange = previousDate;
928                                                lastDayRange = currentDate;
929                                        }else{
930                                                //this is a standalone date
931                                                returnDates.push(dojo.date.stamp.toISOString(previousDate).substring(0,10));
932                                        }
933                                }
934                                previousDate = currentDate;
935                        }
936                        return returnDates;
937                }else{
938                        //If there's only one selected date we return only it
939                                return selectedDates;
940                        }
941                }
942        }       
943);
944
945//FIXME: can we use dijit.Calendar._MonthDropDown directly?
946var MonthDropDown = MultiSelectCalendar._MonthDropDown = dojo.declare("dojox.widget._MonthDropDown",
947    [_Widget, _TemplatedMixin, _WidgetsInTemplateMixin], {
948        // summary:
949        //              The month drop down
950
951        // months: String[]
952        //              List of names of months, possibly w/some undefined entries for Hebrew leap months
953        //              (ex: ["January", "February", undefined, "April", ...])
954        months: [],
955
956        templateString: "<div class='dijitCalendarMonthMenu dijitMenu' " +
957                "dojoAttachEvent='onclick:_onClick,onmouseover:_onMenuHover,onmouseout:_onMenuHover'></div>",
958
959        _setMonthsAttr: function(/*String[]*/ months){
960                this.domNode.innerHTML = dojo.map(months, function(month, idx){
961                                return month ? "<div class='dijitCalendarMonthLabel' month='" + idx +"'>" + month + "</div>" : "";
962                        }).join("");
963        },
964
965        _onClick: function(/*Event*/ evt){
966                this.onChange(dojo.attr(evt.target, "month"));
967        },
968
969        onChange: function(/*Number*/ month){
970                // summary:
971                //              Callback when month is selected from drop down
972        },
973
974        _onMenuHover: function(evt){
975                dojo.toggleClass(evt.target, "dijitCalendarMonthLabelHover", evt.type == "mouseover");
976        }
977});
978
979return MultiSelectCalendar;
980
981});
Note: See TracBrowser for help on using the repository browser.