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              * @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         if (typeof(value) == 'string') {
174          
175             value = Date.parseDate(value, this.format);
176         }
177         
178         this.value = value.clearTime(true);
179         if(this.el){
180             this.update(this.value);
181         }
182     },
183
184     /**
185      * Gets the current selected value of the date field
186      * @return {Date} The selected date
187      */
188     getValue : function(){
189         return this.value;
190     },
191
192     // private
193     focus : function(){
194         if(this.el){
195             this.update(this.activeDate);
196         }
197     },
198
199     // privateval
200     onRender : function(container, position){
201         
202         var m = [
203              '<table cellspacing="0">',
204                 '<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>',
205                 '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
206         var dn = this.dayNames;
207         for(var i = 0; i < 7; i++){
208             var d = this.startDay+i;
209             if(d > 6){
210                 d = d-7;
211             }
212             m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
213         }
214         m[m.length] = "</tr></thead><tbody><tr>";
215         for(var i = 0; i < 42; i++) {
216             if(i % 7 == 0 && i != 0){
217                 m[m.length] = "</tr><tr>";
218             }
219             m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
220         }
221         m[m.length] = '</tr></tbody></table></td></tr><tr>'+
222             '<td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';
223
224         var el = document.createElement("div");
225         el.className = "x-date-picker";
226         el.innerHTML = m.join("");
227
228         container.dom.insertBefore(el, position);
229
230         this.el = Roo.get(el);
231         this.eventEl = Roo.get(el.firstChild);
232
233         new Roo.util.ClickRepeater(this.el.child("td.x-date-left a"), {
234             handler: this.showPrevMonth,
235             scope: this,
236             preventDefault:true,
237             stopDefault:true
238         });
239
240         new Roo.util.ClickRepeater(this.el.child("td.x-date-right a"), {
241             handler: this.showNextMonth,
242             scope: this,
243             preventDefault:true,
244             stopDefault:true
245         });
246
247         this.eventEl.on("mousewheel", this.handleMouseWheel,  this);
248
249         this.monthPicker = this.el.down('div.x-date-mp');
250         this.monthPicker.enableDisplayMode('block');
251         
252         var kn = new Roo.KeyNav(this.eventEl, {
253             "left" : function(e){
254                 e.ctrlKey ?
255                     this.showPrevMonth() :
256                     this.update(this.activeDate.add("d", -1));
257             },
258
259             "right" : function(e){
260                 e.ctrlKey ?
261                     this.showNextMonth() :
262                     this.update(this.activeDate.add("d", 1));
263             },
264
265             "up" : function(e){
266                 e.ctrlKey ?
267                     this.showNextYear() :
268                     this.update(this.activeDate.add("d", -7));
269             },
270
271             "down" : function(e){
272                 e.ctrlKey ?
273                     this.showPrevYear() :
274                     this.update(this.activeDate.add("d", 7));
275             },
276
277             "pageUp" : function(e){
278                 this.showNextMonth();
279             },
280
281             "pageDown" : function(e){
282                 this.showPrevMonth();
283             },
284
285             "enter" : function(e){
286                 e.stopPropagation();
287                 return true;
288             },
289
290             scope : this
291         });
292
293         this.eventEl.on("click", this.handleDateClick,  this, {delegate: "a.x-date-date"});
294
295         this.eventEl.addKeyListener(Roo.EventObject.SPACE, this.selectToday,  this);
296
297         this.el.unselectable();
298         
299         this.cells = this.el.select("table.x-date-inner tbody td");
300         this.textNodes = this.el.query("table.x-date-inner tbody span");
301
302         this.mbtn = new Roo.Button(this.el.child("td.x-date-middle", true), {
303             text: "&#160;",
304             tooltip: this.monthYearText
305         });
306
307         this.mbtn.on('click', this.showMonthPicker, this);
308         this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");
309
310
311         var today = (new Date()).dateFormat(this.format);
312         
313         var baseTb = new Roo.Toolbar(this.el.child("td.x-date-bottom", true));
314         if (this.showClear) {
315             baseTb.add( new Roo.Toolbar.Fill());
316         }
317         baseTb.add({
318             text: String.format(this.todayText, today),
319             tooltip: String.format(this.todayTip, today),
320             handler: this.selectToday,
321             scope: this
322         });
323         
324         //var todayBtn = new Roo.Button(this.el.child("td.x-date-bottom", true), {
325             
326         //});
327         if (this.showClear) {
328             
329             baseTb.add( new Roo.Toolbar.Fill());
330             baseTb.add({
331                 text: '&#160;',
332                 cls: 'x-btn-icon x-btn-clear',
333                 handler: function() {
334                     //this.value = '';
335                     this.fireEvent("select", this, '');
336                 },
337                 scope: this
338             });
339         }
340         
341         
342         if(Roo.isIE){
343             this.el.repaint();
344         }
345         this.update(this.value);
346     },
347
348     createMonthPicker : function(){
349         if(!this.monthPicker.dom.firstChild){
350             var buf = ['<table border="0" cellspacing="0">'];
351             for(var i = 0; i < 6; i++){
352                 buf.push(
353                     '<tr><td class="x-date-mp-month"><a href="#">', this.monthNames[i].substr(0, 3), '</a></td>',
354                     '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', this.monthNames[i+6].substr(0, 3), '</a></td>',
355                     i == 0 ?
356                     '<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>' :
357                     '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
358                 );
359             }
360             buf.push(
361                 '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
362                     this.okText,
363                     '</button><button type="button" class="x-date-mp-cancel">',
364                     this.cancelText,
365                     '</button></td></tr>',
366                 '</table>'
367             );
368             this.monthPicker.update(buf.join(''));
369             this.monthPicker.on('click', this.onMonthClick, this);
370             this.monthPicker.on('dblclick', this.onMonthDblClick, this);
371
372             this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
373             this.mpYears = this.monthPicker.select('td.x-date-mp-year');
374
375             this.mpMonths.each(function(m, a, i){
376                 i += 1;
377                 if((i%2) == 0){
378                     m.dom.xmonth = 5 + Math.round(i * .5);
379                 }else{
380                     m.dom.xmonth = Math.round((i-1) * .5);
381                 }
382             });
383         }
384     },
385
386     showMonthPicker : function(){
387         this.createMonthPicker();
388         var size = this.el.getSize();
389         this.monthPicker.setSize(size);
390         this.monthPicker.child('table').setSize(size);
391
392         this.mpSelMonth = (this.activeDate || this.value).getMonth();
393         this.updateMPMonth(this.mpSelMonth);
394         this.mpSelYear = (this.activeDate || this.value).getFullYear();
395         this.updateMPYear(this.mpSelYear);
396
397         this.monthPicker.slideIn('t', {duration:.2});
398     },
399
400     updateMPYear : function(y){
401         this.mpyear = y;
402         var ys = this.mpYears.elements;
403         for(var i = 1; i <= 10; i++){
404             var td = ys[i-1], y2;
405             if((i%2) == 0){
406                 y2 = y + Math.round(i * .5);
407                 td.firstChild.innerHTML = y2;
408                 td.xyear = y2;
409             }else{
410                 y2 = y - (5-Math.round(i * .5));
411                 td.firstChild.innerHTML = y2;
412                 td.xyear = y2;
413             }
414             this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
415         }
416     },
417
418     updateMPMonth : function(sm){
419         this.mpMonths.each(function(m, a, i){
420             m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
421         });
422     },
423
424     selectMPMonth: function(m){
425         
426     },
427
428     onMonthClick : function(e, t){
429         e.stopEvent();
430         var el = new Roo.Element(t), pn;
431         if(el.is('button.x-date-mp-cancel')){
432             this.hideMonthPicker();
433         }
434         else if(el.is('button.x-date-mp-ok')){
435             this.update(new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
436             this.hideMonthPicker();
437         }
438         else if(pn = el.up('td.x-date-mp-month', 2)){
439             this.mpMonths.removeClass('x-date-mp-sel');
440             pn.addClass('x-date-mp-sel');
441             this.mpSelMonth = pn.dom.xmonth;
442         }
443         else if(pn = el.up('td.x-date-mp-year', 2)){
444             this.mpYears.removeClass('x-date-mp-sel');
445             pn.addClass('x-date-mp-sel');
446             this.mpSelYear = pn.dom.xyear;
447         }
448         else if(el.is('a.x-date-mp-prev')){
449             this.updateMPYear(this.mpyear-10);
450         }
451         else if(el.is('a.x-date-mp-next')){
452             this.updateMPYear(this.mpyear+10);
453         }
454     },
455
456     onMonthDblClick : function(e, t){
457         e.stopEvent();
458         var el = new Roo.Element(t), pn;
459         if(pn = el.up('td.x-date-mp-month', 2)){
460             this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
461             this.hideMonthPicker();
462         }
463         else if(pn = el.up('td.x-date-mp-year', 2)){
464             this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
465             this.hideMonthPicker();
466         }
467     },
468
469     hideMonthPicker : function(disableAnim){
470         if(this.monthPicker){
471             if(disableAnim === true){
472                 this.monthPicker.hide();
473             }else{
474                 this.monthPicker.slideOut('t', {duration:.2});
475             }
476         }
477     },
478
479     // private
480     showPrevMonth : function(e){
481         this.update(this.activeDate.add("mo", -1));
482     },
483
484     // private
485     showNextMonth : function(e){
486         this.update(this.activeDate.add("mo", 1));
487     },
488
489     // private
490     showPrevYear : function(){
491         this.update(this.activeDate.add("y", -1));
492     },
493
494     // private
495     showNextYear : function(){
496         this.update(this.activeDate.add("y", 1));
497     },
498
499     // private
500     handleMouseWheel : function(e){
501         var delta = e.getWheelDelta();
502         if(delta > 0){
503             this.showPrevMonth();
504             e.stopEvent();
505         } else if(delta < 0){
506             this.showNextMonth();
507             e.stopEvent();
508         }
509     },
510
511     // private
512     handleDateClick : function(e, t){
513         e.stopEvent();
514         if(t.dateValue && !Roo.fly(t.parentNode).hasClass("x-date-disabled")){
515             this.setValue(new Date(t.dateValue));
516             this.fireEvent("select", this, this.value);
517         }
518     },
519
520     // private
521     selectToday : function(){
522         this.setValue(new Date().clearTime());
523         this.fireEvent("select", this, this.value);
524     },
525
526     // private
527     update : function(date)
528     {
529         var vd = this.activeDate;
530         this.activeDate = date;
531         if(vd && this.el){
532             var t = date.getTime();
533             if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
534                 this.cells.removeClass("x-date-selected");
535                 this.cells.each(function(c){
536                    if(c.dom.firstChild.dateValue == t){
537                        c.addClass("x-date-selected");
538                        setTimeout(function(){
539                             try{c.dom.firstChild.focus();}catch(e){}
540                        }, 50);
541                        return false;
542                    }
543                 });
544                 return;
545             }
546         }
547         
548         var days = date.getDaysInMonth();
549         var firstOfMonth = date.getFirstDateOfMonth();
550         var startingPos = firstOfMonth.getDay()-this.startDay;
551
552         if(startingPos <= this.startDay){
553             startingPos += 7;
554         }
555
556         var pm = date.add("mo", -1);
557         var prevStart = pm.getDaysInMonth()-startingPos;
558
559         var cells = this.cells.elements;
560         var textEls = this.textNodes;
561         days += startingPos;
562
563         // convert everything to numbers so it's fast
564         var day = 86400000;
565         var d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart)).clearTime();
566         var today = new Date().clearTime().getTime();
567         var sel = date.clearTime().getTime();
568         var min = this.minDate ? this.minDate.clearTime() : Number.NEGATIVE_INFINITY;
569         var max = this.maxDate ? this.maxDate.clearTime() : Number.POSITIVE_INFINITY;
570         var ddMatch = this.disabledDatesRE;
571         var ddText = this.disabledDatesText;
572         var ddays = this.disabledDays ? this.disabledDays.join("") : false;
573         var ddaysText = this.disabledDaysText;
574         var format = this.format;
575
576         var setCellClass = function(cal, cell){
577             cell.title = "";
578             var t = d.getTime();
579             cell.firstChild.dateValue = t;
580             if(t == today){
581                 cell.className += " x-date-today";
582                 cell.title = cal.todayText;
583             }
584             if(t == sel){
585                 cell.className += " x-date-selected";
586                 setTimeout(function(){
587                     try{cell.firstChild.focus();}catch(e){}
588                 }, 50);
589             }
590             // disabling
591             if(t < min) {
592                 cell.className = " x-date-disabled";
593                 cell.title = cal.minText;
594                 return;
595             }
596             if(t > max) {
597                 cell.className = " x-date-disabled";
598                 cell.title = cal.maxText;
599                 return;
600             }
601             if(ddays){
602                 if(ddays.indexOf(d.getDay()) != -1){
603                     cell.title = ddaysText;
604                     cell.className = " x-date-disabled";
605                 }
606             }
607             if(ddMatch && format){
608                 var fvalue = d.dateFormat(format);
609                 if(ddMatch.test(fvalue)){
610                     cell.title = ddText.replace("%0", fvalue);
611                     cell.className = " x-date-disabled";
612                 }
613             }
614         };
615
616         var i = 0;
617         for(; i < startingPos; i++) {
618             textEls[i].innerHTML = (++prevStart);
619             d.setDate(d.getDate()+1);
620             cells[i].className = "x-date-prevday";
621             setCellClass(this, cells[i]);
622         }
623         for(; i < days; i++){
624             intDay = i - startingPos + 1;
625             textEls[i].innerHTML = (intDay);
626             d.setDate(d.getDate()+1);
627             cells[i].className = "x-date-active";
628             setCellClass(this, cells[i]);
629         }
630         var extraDays = 0;
631         for(; i < 42; i++) {
632              textEls[i].innerHTML = (++extraDays);
633              d.setDate(d.getDate()+1);
634              cells[i].className = "x-date-nextday";
635              setCellClass(this, cells[i]);
636         }
637
638         this.mbtn.setText(this.monthNames[date.getMonth()] + " " + date.getFullYear());
639         this.fireEvent('monthchange', this, date);
640         
641         if(!this.internalRender){
642             var main = this.el.dom.firstChild;
643             var w = main.offsetWidth;
644             this.el.setWidth(w + this.el.getBorderWidth("lr"));
645             Roo.fly(main).setWidth(w);
646             this.internalRender = true;
647             // opera does not respect the auto grow header center column
648             // then, after it gets a width opera refuses to recalculate
649             // without a second pass
650             if(Roo.isOpera && !this.secondPass){
651                 main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + "px";
652                 this.secondPass = true;
653                 this.update.defer(10, this, [date]);
654             }
655         }
656         
657         
658     }
659 });