Roo/DatePicker.js
[roojs1] / Roo / DatePicker.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11  
12 /**
13  * @class Roo.DatePicker
14  * @extends Roo.Component
15  * Simple date picker class.
16  * @constructor
17  * Create a new DatePicker
18  * @param {Object} config The config object
19  */
20 Roo.DatePicker = function(config){
21     Roo.DatePicker.superclass.constructor.call(this, config);
22
23     this.value = config && config.value ?
24                  config.value.clearTime() : new Date().clearTime();
25
26     this.addEvents({
27         /**
28              * @event select
29              * Fires when a date is selected
30              * @param {DatePicker} this
31              * @param {Date} date The selected date
32              */
33         select: true
34     });
35
36     if(this.handler){
37         this.on("select", this.handler,  this.scope || this);
38     }
39     // build the disabledDatesRE
40     if(!this.disabledDatesRE && this.disabledDates){
41         var dd = this.disabledDates;
42         var re = "(?:";
43         for(var i = 0; i < dd.length; i++){
44             re += dd[i];
45             if(i != dd.length-1) re += "|";
46         }
47         this.disabledDatesRE = new RegExp(re + ")");
48     }
49 };
50
51 Roo.extend(Roo.DatePicker, Roo.Component, {
52     /**
53      * @cfg {String} todayText
54      * The text to display on the button that selects the current date (defaults to "Today")
55      */
56     todayText : "Today",
57     /**
58      * @cfg {String} okText
59      * The text to display on the ok button
60      */
61     okText : "&#160;OK&#160;", // &#160; to give the user extra clicking room
62     /**
63      * @cfg {String} cancelText
64      * The text to display on the cancel button
65      */
66     cancelText : "Cancel",
67     /**
68      * @cfg {String} todayTip
69      * The tooltip to display for the button that selects the current date (defaults to "{current date} (Spacebar)")
70      */
71     todayTip : "{0} (Spacebar)",
72     /**
73      * @cfg {Date} minDate
74      * Minimum allowable date (JavaScript date object, defaults to null)
75      */
76     minDate : null,
77     /**
78      * @cfg {Date} maxDate
79      * Maximum allowable date (JavaScript date object, defaults to null)
80      */
81     maxDate : null,
82     /**
83      * @cfg {String} minText
84      * The error text to display if the minDate validation fails (defaults to "This date is before the minimum date")
85      */
86     minText : "This date is before the minimum date",
87     /**
88      * @cfg {String} maxText
89      * The error text to display if the maxDate validation fails (defaults to "This date is after the maximum date")
90      */
91     maxText : "This date is after the maximum date",
92     /**
93      * @cfg {String} format
94      * The default date format string which can be overriden for localization support.  The format must be
95      * valid according to {@link Date#parseDate} (defaults to 'm/d/y').
96      */
97     format : "m/d/y",
98     /**
99      * @cfg {Array} disabledDays
100      * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
101      */
102     disabledDays : null,
103     /**
104      * @cfg {String} disabledDaysText
105      * The tooltip to display when the date falls on a disabled day (defaults to "")
106      */
107     disabledDaysText : "",
108     /**
109      * @cfg {RegExp} disabledDatesRE
110      * JavaScript regular expression used to disable a pattern of dates (defaults to null)
111      */
112     disabledDatesRE : null,
113     /**
114      * @cfg {String} disabledDatesText
115      * The tooltip text to display when the date falls on a disabled date (defaults to "")
116      */
117     disabledDatesText : "",
118     /**
119      * @cfg {Boolean} constrainToViewport
120      * True to constrain the date picker to the viewport (defaults to true)
121      */
122     constrainToViewport : true,
123     /**
124      * @cfg {Array} monthNames
125      * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
126      */
127     monthNames : Date.monthNames,
128     /**
129      * @cfg {Array} dayNames
130      * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
131      */
132     dayNames : Date.dayNames,
133     /**
134      * @cfg {String} nextText
135      * The next month navigation button tooltip (defaults to 'Next Month (Control+Right)')
136      */
137     nextText: 'Next Month (Control+Right)',
138     /**
139      * @cfg {String} prevText
140      * The previous month navigation button tooltip (defaults to 'Previous Month (Control+Left)')
141      */
142     prevText: 'Previous Month (Control+Left)',
143     /**
144      * @cfg {String} monthYearText
145      * The header month selector tooltip (defaults to 'Choose a month (Control+Up/Down to move years)')
146      */
147     monthYearText: 'Choose a month (Control+Up/Down to move years)',
148     /**
149      * @cfg {Number} startDay
150      * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
151      */
152     startDay : 0,
153     /**
154      * @cfg {Bool} showClear
155      * Show a clear button (usefull for date form elements that can be blank.)
156      */
157     
158     showClear: false,
159     
160     /**
161      * Sets the value of the date field
162      * @param {Date} value The date to set
163      */
164     setValue : function(value){
165         var old = this.value;
166         this.value = value.clearTime(true);
167         if(this.el){
168             this.update(this.value);
169         }
170     },
171
172     /**
173      * Gets the current selected value of the date field
174      * @return {Date} The selected date
175      */
176     getValue : function(){
177         return this.value;
178     },
179
180     // private
181     focus : function(){
182         if(this.el){
183             this.update(this.activeDate);
184         }
185     },
186
187     // private
188     onRender : function(container, position){
189         var m = [
190              '<table cellspacing="0">',
191                 '<tr><td class="x-date-left"><a href="#" title="', this.prevText ,'">&#160;</a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="', this.nextText ,'">&#160;</a></td></tr>',
192                 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
193         var dn = this.dayNames;
194         for(var i = 0; i < 7; i++){
195             var d = this.startDay+i;
196             if(d > 6){
197                 d = d-7;
198             }
199             m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
200         }
201         m[m.length] = "</tr></thead><tbody><tr>";
202         for(var i = 0; i < 42; i++) {
203             if(i % 7 == 0 && i != 0){
204                 m[m.length] = "</tr><tr>";
205             }
206             m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
207         }
208         m[m.length] = '</tr></tbody></table></td></tr><tr>'+
209             '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
210
211         var el = document.createElement("div");
212         el.className = "x-date-picker";
213         el.innerHTML = m.join("");
214
215         container.dom.insertBefore(el, position);
216
217         this.el = Roo.get(el);
218         this.eventEl = Roo.get(el.firstChild);
219
220         new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
221             handler: this.showPrevMonth,
222             scope: this,
223             preventDefault:true,
224             stopDefault:true
225         });
226
227         new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
228             handler: this.showNextMonth,
229             scope: this,
230             preventDefault:true,
231             stopDefault:true
232         });
233
234         this.eventEl.on("mousewheel", this.handleMouseWheel,  this);
235
236         this.monthPicker = this.el.down('div.x-date-mp');
237         this.monthPicker.enableDisplayMode('block');
238         
239         var kn = new Roo.KeyNav(this.eventEl, {
240             "left" : function(e){
241                 e.ctrlKey ?
242                     this.showPrevMonth() :
243                     this.update(this.activeDate.add("d", -1));
244             },
245
246             "right" : function(e){
247                 e.ctrlKey ?
248                     this.showNextMonth() :
249                     this.update(this.activeDate.add("d", 1));
250             },
251
252             "up" : function(e){
253                 e.ctrlKey ?
254                     this.showNextYear() :
255                     this.update(this.activeDate.add("d", -7));
256             },
257
258             "down" : function(e){
259                 e.ctrlKey ?
260                     this.showPrevYear() :
261                     this.update(this.activeDate.add("d", 7));
262             },
263
264             "pageUp" : function(e){
265                 this.showNextMonth();
266             },
267
268             "pageDown" : function(e){
269                 this.showPrevMonth();
270             },
271
272             "enter" : function(e){
273                 e.stopPropagation();
274                 return true;
275             },
276
277             scope : this
278         });
279
280         this.eventEl.on("click", this.handleDateClick,  this, {delegate: "a.x-date-date"});
281
282         this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday,  this);
283
284         this.el.unselectable();
285         
286         this.cells = this.el.select("table.x-date-inner tbody td");
287         this.textNodes = this.el.query("table.x-date-inner tbody span");
288
289         this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
290             text: "&#160;",
291             tooltip: this.monthYearText
292         });
293
294         this.mbtn.on('click', this.showMonthPicker, this);
295         this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
296
297
298         var today = (new Date()).dateFormat(this.format);
299         
300         var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
301         if (this.showClear) {
302             baseTb.add( new Roo.Toolbar.Fill());
303         }
304         baseTb.add({
305             text: String.format(this.todayText, today),
306             tooltip: String.format(this.todayTip, today),
307             handler: this.selectToday,
308             scope: this
309         });
310         
311         //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
312             
313         //});
314         if (this.showClear) {
315             
316             baseTb.add( new Roo.Toolbar.Fill());
317             baseTb.add({
318                 text: '&#160;',
319                 cls: 'x-btn-icon x-btn-clear',
320                 handler: function() {
321                     //this.value = '';
322                     this.fireEvent("select", this, '');
323                 },
324                 scope: this
325             });
326         }
327         
328         
329         if(Roo.isIE){
330             this.el.repaint();
331         }
332         this.update(this.value);
333     },
334
335     createMonthPicker : function(){
336         if(!this.monthPicker.dom.firstChild){
337             var buf = ['<table border="0" cellspacing="0">'];
338             for(var i = 0; i < 6; i++){
339                 buf.push(
340                     '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
341                     '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
342                     i == 0 ?
343                     '<td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-prev"></a></td><td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-next"></a></td></tr>' :
344                     '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
345                 );
346             }
347             buf.push(
348                 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
349                     this.okText,
350                     '</button><button type="button" class="x-date-mp-cancel">',
351                     this.cancelText,
352                     '</button></td></tr>',
353                 '</table>'
354             );
355             this.monthPicker.update(buf.join(''));
356             this.monthPicker.on('click', this.onMonthClick, this);
357             this.monthPicker.on('dblclick', this.onMonthDblClick, this);
358
359             this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
360             this.mpYears = this.monthPicker.select('td.x-date-mp-year');
361
362             this.mpMonths.each(function(m, a, i){
363                 i += 1;
364                 if((i%2) == 0){
365                     m.dom.xmonth = 5 + Math.round(i * .5);
366                 }else{
367                     m.dom.xmonth = Math.round((i-1) * .5);
368                 }
369             });
370         }
371     },
372
373     showMonthPicker : function(){
374         this.createMonthPicker();
375         var size = this.el.getSize();
376         this.monthPicker.setSize(size);
377         this.monthPicker.child('table').setSize(size);
378
379         this.mpSelMonth = (this.activeDate || this.value).getMonth();
380         this.updateMPMonth(this.mpSelMonth);
381         this.mpSelYear = (this.activeDate || this.value).getFullYear();
382         this.updateMPYear(this.mpSelYear);
383
384         this.monthPicker.slideIn('t', {duration:.2});
385     },
386
387     updateMPYear : function(y){
388         this.mpyear = y;
389         var ys = this.mpYears.elements;
390         for(var i = 1; i <= 10; i++){
391             var td = ys[i-1], y2;
392             if((i%2) == 0){
393                 y2 = y + Math.round(i * .5);
394                 td.firstChild.innerHTML = y2;
395                 td.xyear = y2;
396             }else{
397                 y2 = y - (5-Math.round(i * .5));
398                 td.firstChild.innerHTML = y2;
399                 td.xyear = y2;
400             }
401             this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
402         }
403     },
404
405     updateMPMonth : function(sm){
406         this.mpMonths.each(function(m, a, i){
407             m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
408         });
409     },
410
411     selectMPMonth: function(m){
412         
413     },
414
415     onMonthClick : function(e, t){
416         e.stopEvent();
417         var el = new Roo.Element(t), pn;
418         if(el.is('button.x-date-mp-cancel')){
419             this.hideMonthPicker();
420         }
421         else if(el.is('button.x-date-mp-ok')){
422             this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
423             this.hideMonthPicker();
424         }
425         else if(pn = el.up('td.x-date-mp-month', 2)){
426             this.mpMonths.removeClass('x-date-mp-sel');
427             pn.addClass('x-date-mp-sel');
428             this.mpSelMonth = pn.dom.xmonth;
429         }
430         else if(pn = el.up('td.x-date-mp-year', 2)){
431             this.mpYears.removeClass('x-date-mp-sel');
432             pn.addClass('x-date-mp-sel');
433             this.mpSelYear = pn.dom.xyear;
434         }
435         else if(el.is('a.x-date-mp-prev')){
436             this.updateMPYear(this.mpyear-10);
437         }
438         else if(el.is('a.x-date-mp-next')){
439             this.updateMPYear(this.mpyear+10);
440         }
441     },
442
443     onMonthDblClick : function(e, t){
444         e.stopEvent();
445         var el = new Roo.Element(t), pn;
446         if(pn = el.up('td.x-date-mp-month', 2)){
447             this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
448             this.hideMonthPicker();
449         }
450         else if(pn = el.up('td.x-date-mp-year', 2)){
451             this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
452             this.hideMonthPicker();
453         }
454     },
455
456     hideMonthPicker : function(disableAnim){
457         if(this.monthPicker){
458             if(disableAnim === true){
459                 this.monthPicker.hide();
460             }else{
461                 this.monthPicker.slideOut('t', {duration:.2});
462             }
463         }
464     },
465
466     // private
467     showPrevMonth : function(e){
468         this.update(this.activeDate.add("mo", -1));
469     },
470
471     // private
472     showNextMonth : function(e){
473         this.update(this.activeDate.add("mo", 1));
474     },
475
476     // private
477     showPrevYear : function(){
478         this.update(this.activeDate.add("y", -1));
479     },
480
481     // private
482     showNextYear : function(){
483         this.update(this.activeDate.add("y", 1));
484     },
485
486     // private
487     handleMouseWheel : function(e){
488         var delta = e.getWheelDelta();
489         if(delta > 0){
490             this.showPrevMonth();
491             e.stopEvent();
492         } else if(delta < 0){
493             this.showNextMonth();
494             e.stopEvent();
495         }
496     },
497
498     // private
499     handleDateClick : function(e, t){
500         e.stopEvent();
501         if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
502             this.setValue(new Date(t.dateValue));
503             this.fireEvent("select", this, this.value);
504         }
505     },
506
507     // private
508     selectToday : function(){
509         this.setValue(new Date().clearTime());
510         this.fireEvent("select", this, this.value);
511     },
512
513     // private
514     update : function(date){
515         var vd = this.activeDate;
516         this.activeDate = date;
517         if(vd && this.el){
518             var t = date.getTime();
519             if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
520                 this.cells.removeClass("x-date-selected");
521                 this.cells.each(function(c){
522                    if(c.dom.firstChild.dateValue == t){
523                        c.addClass("x-date-selected");
524                        setTimeout(function(){
525                             try{c.dom.firstChild.focus();}catch(e){}
526                        }, 50);
527                        return false;
528                    }
529                 });
530                 return;
531             }
532         }
533         var days = date.getDaysInMonth();
534         var firstOfMonth = date.getFirstDateOfMonth();
535         var startingPos = firstOfMonth.getDay()-this.startDay;
536
537         if(startingPos <= this.startDay){
538             startingPos += 7;
539         }
540
541         var pm = date.add("mo", -1);
542         var prevStart = pm.getDaysInMonth()-startingPos;
543
544         var cells = this.cells.elements;
545         var textEls = this.textNodes;
546         days += startingPos;
547
548         // convert everything to numbers so it's fast
549         var day = 86400000;
550         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
551         var today = new Date().clearTime().getTime();
552         var sel = date.clearTime().getTime();
553         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
554         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
555         var ddMatch = this.disabledDatesRE;
556         var ddText = this.disabledDatesText;
557         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
558         var ddaysText = this.disabledDaysText;
559         var format = this.format;
560
561         var setCellClass = function(cal, cell){
562             cell.title = "";
563             var t = d.getTime();
564             cell.firstChild.dateValue = t;
565             if(t == today){
566                 cell.className += " x-date-today";
567                 cell.title = cal.todayText;
568             }
569             if(t == sel){
570                 cell.className += " x-date-selected";
571                 setTimeout(function(){
572                     try{cell.firstChild.focus();}catch(e){}
573                 }, 50);
574             }
575             // disabling
576             if(t < min) {
577                 cell.className = " x-date-disabled";
578                 cell.title = cal.minText;
579                 return;
580             }
581             if(t > max) {
582                 cell.className = " x-date-disabled";
583                 cell.title = cal.maxText;
584                 return;
585             }
586             if(ddays){
587                 if(ddays.indexOf(d.getDay()) != -1){
588                     cell.title = ddaysText;
589                     cell.className = " x-date-disabled";
590                 }
591             }
592             if(ddMatch && format){
593                 var fvalue = d.dateFormat(format);
594                 if(ddMatch.test(fvalue)){
595                     cell.title = ddText.replace("%0", fvalue);
596                     cell.className = " x-date-disabled";
597                 }
598             }
599         };
600
601         var i = 0;
602         for(; i < startingPos; i++) {
603             textEls[i].innerHTML = (++prevStart);
604             d.setDate(d.getDate()+1);
605             cells[i].className = "x-date-prevday";
606             setCellClass(this, cells[i]);
607         }
608         for(; i < days; i++){
609             intDay = i - startingPos + 1;
610             textEls[i].innerHTML = (intDay);
611             d.setDate(d.getDate()+1);
612             cells[i].className = "x-date-active";
613             setCellClass(this, cells[i]);
614         }
615         var extraDays = 0;
616         for(; i < 42; i++) {
617              textEls[i].innerHTML = (++extraDays);
618              d.setDate(d.getDate()+1);
619              cells[i].className = "x-date-nextday";
620              setCellClass(this, cells[i]);
621         }
622
623         this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
624
625         if(!this.internalRender){
626             var main = this.el.dom.firstChild;
627             var w = main.offsetWidth;
628             this.el.setWidth(w + this.el.getBorderWidth("lr"));
629             Roo.fly(main).setWidth(w);
630             this.internalRender = true;
631             // opera does not respect the auto grow header center column
632             // then, after it gets a width opera refuses to recalculate
633             // without a second pass
634             if(Roo.isOpera && !this.secondPass){
635                 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
636                 this.secondPass = true;
637                 this.update.defer(10, this, [date]);
638             }
639         }
640     }
641 });