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