initial import
[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         baseTb.add({
302             text: String.format(this.todayText, today),
303             tooltip: String.format(this.todayTip, today),
304             handler: this.selectToday,
305             scope: this
306         });
307         
308         //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
309             
310         //});
311         if (this.showClear) {
312             
313             baseTb.add( new Roo.Toolbar.Fill());
314             baseTb.add({
315                 text: '&#160;',
316                 cls: 'x-btn-icon x-btn-clear',
317                 handler: function() {
318                     //this.value = '';
319                     this.fireEvent("select", this, '');
320                 },
321                 scope: this
322             });
323         }
324         
325         
326         if(Roo.isIE){
327             this.el.repaint();
328         }
329         this.update(this.value);
330     },
331
332     createMonthPicker : function(){
333         if(!this.monthPicker.dom.firstChild){
334             var buf = ['<table border="0" cellspacing="0">'];
335             for(var i = 0; i < 6; i++){
336                 buf.push(
337                     '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
338                     '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
339                     i == 0 ?
340                     '<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>' :
341                     '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
342                 );
343             }
344             buf.push(
345                 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
346                     this.okText,
347                     '</button><button type="button" class="x-date-mp-cancel">',
348                     this.cancelText,
349                     '</button></td></tr>',
350                 '</table>'
351             );
352             this.monthPicker.update(buf.join(''));
353             this.monthPicker.on('click', this.onMonthClick, this);
354             this.monthPicker.on('dblclick', this.onMonthDblClick, this);
355
356             this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
357             this.mpYears = this.monthPicker.select('td.x-date-mp-year');
358
359             this.mpMonths.each(function(m, a, i){
360                 i += 1;
361                 if((i%2) == 0){
362                     m.dom.xmonth = 5 + Math.round(i * .5);
363                 }else{
364                     m.dom.xmonth = Math.round((i-1) * .5);
365                 }
366             });
367         }
368     },
369
370     showMonthPicker : function(){
371         this.createMonthPicker();
372         var size = this.el.getSize();
373         this.monthPicker.setSize(size);
374         this.monthPicker.child('table').setSize(size);
375
376         this.mpSelMonth = (this.activeDate || this.value).getMonth();
377         this.updateMPMonth(this.mpSelMonth);
378         this.mpSelYear = (this.activeDate || this.value).getFullYear();
379         this.updateMPYear(this.mpSelYear);
380
381         this.monthPicker.slideIn('t', {duration:.2});
382     },
383
384     updateMPYear : function(y){
385         this.mpyear = y;
386         var ys = this.mpYears.elements;
387         for(var i = 1; i <= 10; i++){
388             var td = ys[i-1], y2;
389             if((i%2) == 0){
390                 y2 = y + Math.round(i * .5);
391                 td.firstChild.innerHTML = y2;
392                 td.xyear = y2;
393             }else{
394                 y2 = y - (5-Math.round(i * .5));
395                 td.firstChild.innerHTML = y2;
396                 td.xyear = y2;
397             }
398             this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
399         }
400     },
401
402     updateMPMonth : function(sm){
403         this.mpMonths.each(function(m, a, i){
404             m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
405         });
406     },
407
408     selectMPMonth: function(m){
409         
410     },
411
412     onMonthClick : function(e, t){
413         e.stopEvent();
414         var el = new Roo.Element(t), pn;
415         if(el.is('button.x-date-mp-cancel')){
416             this.hideMonthPicker();
417         }
418         else if(el.is('button.x-date-mp-ok')){
419             this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
420             this.hideMonthPicker();
421         }
422         else if(pn = el.up('td.x-date-mp-month', 2)){
423             this.mpMonths.removeClass('x-date-mp-sel');
424             pn.addClass('x-date-mp-sel');
425             this.mpSelMonth = pn.dom.xmonth;
426         }
427         else if(pn = el.up('td.x-date-mp-year', 2)){
428             this.mpYears.removeClass('x-date-mp-sel');
429             pn.addClass('x-date-mp-sel');
430             this.mpSelYear = pn.dom.xyear;
431         }
432         else if(el.is('a.x-date-mp-prev')){
433             this.updateMPYear(this.mpyear-10);
434         }
435         else if(el.is('a.x-date-mp-next')){
436             this.updateMPYear(this.mpyear+10);
437         }
438     },
439
440     onMonthDblClick : function(e, t){
441         e.stopEvent();
442         var el = new Roo.Element(t), pn;
443         if(pn = el.up('td.x-date-mp-month', 2)){
444             this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
445             this.hideMonthPicker();
446         }
447         else if(pn = el.up('td.x-date-mp-year', 2)){
448             this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
449             this.hideMonthPicker();
450         }
451     },
452
453     hideMonthPicker : function(disableAnim){
454         if(this.monthPicker){
455             if(disableAnim === true){
456                 this.monthPicker.hide();
457             }else{
458                 this.monthPicker.slideOut('t', {duration:.2});
459             }
460         }
461     },
462
463     // private
464     showPrevMonth : function(e){
465         this.update(this.activeDate.add("mo", -1));
466     },
467
468     // private
469     showNextMonth : function(e){
470         this.update(this.activeDate.add("mo", 1));
471     },
472
473     // private
474     showPrevYear : function(){
475         this.update(this.activeDate.add("y", -1));
476     },
477
478     // private
479     showNextYear : function(){
480         this.update(this.activeDate.add("y", 1));
481     },
482
483     // private
484     handleMouseWheel : function(e){
485         var delta = e.getWheelDelta();
486         if(delta > 0){
487             this.showPrevMonth();
488             e.stopEvent();
489         } else if(delta < 0){
490             this.showNextMonth();
491             e.stopEvent();
492         }
493     },
494
495     // private
496     handleDateClick : function(e, t){
497         e.stopEvent();
498         if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
499             this.setValue(new Date(t.dateValue));
500             this.fireEvent("select", this, this.value);
501         }
502     },
503
504     // private
505     selectToday : function(){
506         this.setValue(new Date().clearTime());
507         this.fireEvent("select", this, this.value);
508     },
509
510     // private
511     update : function(date){
512         var vd = this.activeDate;
513         this.activeDate = date;
514         if(vd && this.el){
515             var t = date.getTime();
516             if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
517                 this.cells.removeClass("x-date-selected");
518                 this.cells.each(function(c){
519                    if(c.dom.firstChild.dateValue == t){
520                        c.addClass("x-date-selected");
521                        setTimeout(function(){
522                             try{c.dom.firstChild.focus();}catch(e){}
523                        }, 50);
524                        return false;
525                    }
526                 });
527                 return;
528             }
529         }
530         var days = date.getDaysInMonth();
531         var firstOfMonth = date.getFirstDateOfMonth();
532         var startingPos = firstOfMonth.getDay()-this.startDay;
533
534         if(startingPos <= this.startDay){
535             startingPos += 7;
536         }
537
538         var pm = date.add("mo", -1);
539         var prevStart = pm.getDaysInMonth()-startingPos;
540
541         var cells = this.cells.elements;
542         var textEls = this.textNodes;
543         days += startingPos;
544
545         // convert everything to numbers so it's fast
546         var day = 86400000;
547         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
548         var today = new Date().clearTime().getTime();
549         var sel = date.clearTime().getTime();
550         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
551         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
552         var ddMatch = this.disabledDatesRE;
553         var ddText = this.disabledDatesText;
554         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
555         var ddaysText = this.disabledDaysText;
556         var format = this.format;
557
558         var setCellClass = function(cal, cell){
559             cell.title = "";
560             var t = d.getTime();
561             cell.firstChild.dateValue = t;
562             if(t == today){
563                 cell.className += " x-date-today";
564                 cell.title = cal.todayText;
565             }
566             if(t == sel){
567                 cell.className += " x-date-selected";
568                 setTimeout(function(){
569                     try{cell.firstChild.focus();}catch(e){}
570                 }, 50);
571             }
572             // disabling
573             if(t < min) {
574                 cell.className = " x-date-disabled";
575                 cell.title = cal.minText;
576                 return;
577             }
578             if(t > max) {
579                 cell.className = " x-date-disabled";
580                 cell.title = cal.maxText;
581                 return;
582             }
583             if(ddays){
584                 if(ddays.indexOf(d.getDay()) != -1){
585                     cell.title = ddaysText;
586                     cell.className = " x-date-disabled";
587                 }
588             }
589             if(ddMatch && format){
590                 var fvalue = d.dateFormat(format);
591                 if(ddMatch.test(fvalue)){
592                     cell.title = ddText.replace("%0", fvalue);
593                     cell.className = " x-date-disabled";
594                 }
595             }
596         };
597
598         var i = 0;
599         for(; i < startingPos; i++) {
600             textEls[i].innerHTML = (++prevStart);
601             d.setDate(d.getDate()+1);
602             cells[i].className = "x-date-prevday";
603             setCellClass(this, cells[i]);
604         }
605         for(; i < days; i++){
606             intDay = i - startingPos + 1;
607             textEls[i].innerHTML = (intDay);
608             d.setDate(d.getDate()+1);
609             cells[i].className = "x-date-active";
610             setCellClass(this, cells[i]);
611         }
612         var extraDays = 0;
613         for(; i < 42; i++) {
614              textEls[i].innerHTML = (++extraDays);
615              d.setDate(d.getDate()+1);
616              cells[i].className = "x-date-nextday";
617              setCellClass(this, cells[i]);
618         }
619
620         this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
621
622         if(!this.internalRender){
623             var main = this.el.dom.firstChild;
624             var w = main.offsetWidth;
625             this.el.setWidth(w + this.el.getBorderWidth("lr"));
626             Roo.fly(main).setWidth(w);
627             this.internalRender = true;
628             // opera does not respect the auto grow header center column
629             // then, after it gets a width opera refuses to recalculate
630             // without a second pass
631             if(Roo.isOpera && !this.secondPass){
632                 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
633                 this.secondPass = true;
634                 this.update.defer(10, this, [date]);
635             }
636         }
637     }
638 });