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