Upgrade to ExtJS 4.0.1 - Released 05/18/2011
[extjs.git] / src / form / field / Time.js
1 /**
2  * @class Ext.form.field.Time
3  * @extends Ext.form.field.Picker
4  * <p>Provides a time input field with a time dropdown and automatic time validation.</p>
5  * <p>This field recognizes and uses JavaScript Date objects as its main {@link #value} type (only the time
6  * portion of the date is used; the month/day/year are ignored). In addition, it recognizes string values which
7  * are parsed according to the {@link #format} and/or {@link #altFormats} configs. These may be reconfigured
8  * to use time formats appropriate for the user's locale.</p>
9  * <p>The field may be limited to a certain range of times by using the {@link #minValue} and {@link #maxValue}
10  * configs, and the interval between time options in the dropdown can be changed with the {@link #increment} config.</p>
11  * {@img Ext.form.Time/Ext.form.Time.png Ext.form.Time component}
12  * <p>Example usage:</p>
13  * <pre><code>
14 Ext.create('Ext.form.Panel', {
15     title: 'Time Card',
16     width: 300,
17     bodyPadding: 10,
18     renderTo: Ext.getBody(),        
19     items: [{
20         xtype: 'timefield',
21         name: 'in',
22         fieldLabel: 'Time In',
23         minValue: '6:00 AM',
24         maxValue: '8:00 PM',
25         increment: 30,
26         anchor: '100%'
27     }, {
28         xtype: 'timefield',
29         name: 'out',
30         fieldLabel: 'Time Out',
31         minValue: '6:00 AM',
32         maxValue: '8:00 PM',
33         increment: 30,
34         anchor: '100%'
35    }]
36 });
37 </code></pre>
38  * @constructor
39  * Create a new Time field
40  * @param {Object} config
41  * @xtype timefield
42  */
43 Ext.define('Ext.form.field.Time', {
44     extend:'Ext.form.field.Picker',
45     alias: 'widget.timefield',
46     requires: ['Ext.form.field.Date', 'Ext.picker.Time', 'Ext.view.BoundListKeyNav', 'Ext.Date'],
47     alternateClassName: ['Ext.form.TimeField', 'Ext.form.Time'],
48
49     /**
50      * @cfg {String} triggerCls
51      * An additional CSS class used to style the trigger button.  The trigger will always get the
52      * {@link #triggerBaseCls} by default and <tt>triggerCls</tt> will be <b>appended</b> if specified.
53      * Defaults to <tt>'x-form-time-trigger'</tt> for the Time field trigger.
54      */
55     triggerCls: Ext.baseCSSPrefix + 'form-time-trigger',
56
57     /**
58      * @cfg {Date/String} minValue
59      * The minimum allowed time. Can be either a Javascript date object with a valid time value or a string
60      * time in a valid format -- see {@link #format} and {@link #altFormats} (defaults to undefined).
61      */
62
63     /**
64      * @cfg {Date/String} maxValue
65      * The maximum allowed time. Can be either a Javascript date object with a valid time value or a string
66      * time in a valid format -- see {@link #format} and {@link #altFormats} (defaults to undefined).
67      */
68
69     /**
70      * @cfg {String} minText
71      * The error text to display when the entered time is before {@link #minValue} (defaults to
72      * 'The time in this field must be equal to or after {0}').
73      */
74     minText : "The time in this field must be equal to or after {0}",
75
76     /**
77      * @cfg {String} maxText
78      * The error text to display when the entered time is after {@link #maxValue} (defaults to
79      * 'The time in this field must be equal to or before {0}').
80      */
81     maxText : "The time in this field must be equal to or before {0}",
82
83     /**
84      * @cfg {String} invalidText
85      * The error text to display when the time in the field is invalid (defaults to
86      * '{value} is not a valid time').
87      */
88     invalidText : "{0} is not a valid time",
89
90     /**
91      * @cfg {String} format
92      * The default time format string which can be overriden for localization support.  The format must be
93      * valid according to {@link Ext.Date#parse} (defaults to 'g:i A', e.g., '3:15 PM').  For 24-hour time
94      * format try 'H:i' instead.
95      */
96     format : "g:i A",
97
98     /**
99      * @cfg {String} submitFormat The date format string which will be submitted to the server.
100      * The format must be valid according to {@link Ext.Date#parse} (defaults to <tt>{@link #format}</tt>).
101      */
102
103     /**
104      * @cfg {String} altFormats
105      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
106      * format (defaults to 'g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H|gi a|hi a|giA|hiA|gi A|hi A').
107      */
108     altFormats : "g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H|gi a|hi a|giA|hiA|gi A|hi A",
109
110     /**
111      * @cfg {Number} increment
112      * The number of minutes between each time value in the list (defaults to 15).
113      */
114     increment: 15,
115
116     /**
117      * @cfg {Number} pickerMaxHeight
118      * The maximum height of the {@link Ext.picker.Time} dropdown. Defaults to 300.
119      */
120     pickerMaxHeight: 300,
121
122     /**
123      * @cfg {Boolean} selectOnTab
124      * Whether the Tab key should select the currently highlighted item. Defaults to <tt>true</tt>.
125      */
126     selectOnTab: true,
127
128     /**
129      * @private
130      * This is the date to use when generating time values in the absence of either minValue
131      * or maxValue.  Using the current date causes DST issues on DST boundary dates, so this is an
132      * arbitrary "safe" date that can be any date aside from DST boundary dates.
133      */
134     initDate: '1/1/2008',
135     initDateFormat: 'j/n/Y',
136
137
138     initComponent: function() {
139         var me = this,
140             min = me.minValue,
141             max = me.maxValue;
142         if (min) {
143             me.setMinValue(min);
144         }
145         if (max) {
146             me.setMaxValue(max);
147         }
148         this.callParent();
149     },
150
151     initValue: function() {
152         var me = this,
153             value = me.value;
154
155         // If a String value was supplied, try to convert it to a proper Date object
156         if (Ext.isString(value)) {
157             me.value = me.rawToValue(value);
158         }
159
160         me.callParent();
161     },
162
163     /**
164      * Replaces any existing {@link #minValue} with the new time and refreshes the picker's range.
165      * @param {Date/String} value The minimum time that can be selected
166      */
167     setMinValue: function(value) {
168         var me = this,
169             picker = me.picker;
170         me.setLimit(value, true);
171         if (picker) {
172             picker.setMinValue(me.minValue);
173         }
174     },
175
176     /**
177      * Replaces any existing {@link #maxValue} with the new time and refreshes the picker's range.
178      * @param {Date/String} value The maximum time that can be selected
179      */
180     setMaxValue: function(value) {
181         var me = this,
182             picker = me.picker;
183         me.setLimit(value, false);
184         if (picker) {
185             picker.setMaxValue(me.maxValue);
186         }
187     },
188
189     /**
190      * @private
191      * Updates either the min or max value. Converts the user's value into a Date object whose
192      * year/month/day is set to the {@link #initDate} so that only the time fields are significant.
193      */
194     setLimit: function(value, isMin) {
195         var me = this,
196             d, val;
197         if (Ext.isString(value)) {
198             d = me.parseDate(value);
199         }
200         else if (Ext.isDate(value)) {
201             d = value;
202         }
203         if (d) {
204             val = Ext.Date.clearTime(new Date(me.initDate));
205             val.setHours(d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds());
206             me[isMin ? 'minValue' : 'maxValue'] = val;
207         }
208     },
209
210     rawToValue: function(rawValue) {
211         return this.parseDate(rawValue) || rawValue || null;
212     },
213
214     valueToRaw: function(value) {
215         return this.formatDate(this.parseDate(value));
216     },
217
218     /**
219      * Runs all of Time's validations and returns an array of any errors. Note that this first
220      * runs Text's validations, so the returned array is an amalgamation of all field errors.
221      * The additional validation checks are testing that the time format is valid, that the chosen
222      * time is within the {@link #minValue} and {@link #maxValue} constraints set.
223      * @param {Mixed} value The value to get errors for (defaults to the current field value)
224      * @return {Array} All validation errors for this field
225      */
226     getErrors: function(value) {
227         var me = this,
228             format = Ext.String.format,
229             errors = me.callParent(arguments),
230             minValue = me.minValue,
231             maxValue = me.maxValue,
232             date;
233
234         value = me.formatDate(value || me.processRawValue(me.getRawValue()));
235
236         if (value === null || value.length < 1) { // if it's blank and textfield didn't flag it then it's valid
237              return errors;
238         }
239
240         date = me.parseDate(value);
241         if (!date) {
242             errors.push(format(me.invalidText, value, me.format));
243             return errors;
244         }
245
246         if (minValue && date < minValue) {
247             errors.push(format(me.minText, me.formatDate(minValue)));
248         }
249
250         if (maxValue && date > maxValue) {
251             errors.push(format(me.maxText, me.formatDate(maxValue)));
252         }
253
254         return errors;
255     },
256
257     formatDate: function() {
258         return Ext.form.field.Date.prototype.formatDate.apply(this, arguments);
259     },
260
261     /**
262      * @private
263      * Parses an input value into a valid Date object.
264      * @param {String/Date} value
265      */
266     parseDate: function(value) {
267         if (!value || Ext.isDate(value)) {
268             return value;
269         }
270
271         var me = this,
272             val = me.safeParse(value, me.format),
273             altFormats = me.altFormats,
274             altFormatsArray = me.altFormatsArray,
275             i = 0,
276             len;
277
278         if (!val && altFormats) {
279             altFormatsArray = altFormatsArray || altFormats.split('|');
280             len = altFormatsArray.length;
281             for (; i < len && !val; ++i) {
282                 val = me.safeParse(value, altFormatsArray[i]);
283             }
284         }
285         return val;
286     },
287
288     safeParse: function(value, format){
289         var me = this,
290             utilDate = Ext.Date,
291             parsedDate,
292             result = null;
293
294         if (utilDate.formatContainsDateInfo(format)) {
295             // assume we've been given a full date
296             result = utilDate.parse(value, format);
297         } else {
298             // Use our initial safe date
299             parsedDate = utilDate.parse(me.initDate + ' ' + value, me.initDateFormat + ' ' + format);
300             if (parsedDate) {
301                 result = parsedDate;
302             }
303         }
304         return result;
305     },
306
307     // @private
308     getSubmitValue: function() {
309         var me = this,
310             format = me.submitFormat || me.format,
311             value = me.getValue();
312
313         return value ? Ext.Date.format(value, format) : null;
314     },
315
316     /**
317      * @private
318      * Creates the {@link Ext.picker.Time}
319      */
320     createPicker: function() {
321         var me = this,
322             picker = Ext.create('Ext.picker.Time', {
323                 selModel: {
324                     mode: 'SINGLE'
325                 },
326                 floating: true,
327                 hidden: true,
328                 minValue: me.minValue,
329                 maxValue: me.maxValue,
330                 increment: me.increment,
331                 format: me.format,
332                 ownerCt: this.ownerCt,
333                 renderTo: document.body,
334                 maxHeight: me.pickerMaxHeight,
335                 focusOnToFront: false
336             });
337
338         me.mon(picker.getSelectionModel(), {
339             selectionchange: me.onListSelect,
340             scope: me
341         });
342
343         return picker;
344     },
345
346     /**
347      * @private
348      * Enables the key nav for the Time picker when it is expanded.
349      * TODO this is largely the same logic as ComboBox, should factor out.
350      */
351     onExpand: function() {
352         var me = this,
353             keyNav = me.pickerKeyNav,
354             selectOnTab = me.selectOnTab,
355             picker = me.getPicker(),
356             lastSelected = picker.getSelectionModel().lastSelected,
357             itemNode;
358
359         if (!keyNav) {
360             keyNav = me.pickerKeyNav = Ext.create('Ext.view.BoundListKeyNav', this.inputEl, {
361                 boundList: picker,
362                 forceKeyDown: true,
363                 tab: function(e) {
364                     if (selectOnTab) {
365                         this.selectHighlighted(e);
366                         me.triggerBlur();
367                     }
368                     // Tab key event is allowed to propagate to field
369                     return true;
370                 }
371             });
372             // stop tab monitoring from Ext.form.field.Trigger so it doesn't short-circuit selectOnTab
373             if (selectOnTab) {
374                 me.ignoreMonitorTab = true;
375             }
376         }
377         Ext.defer(keyNav.enable, 1, keyNav); //wait a bit so it doesn't react to the down arrow opening the picker
378
379         // Highlight the last selected item and scroll it into view
380         if (lastSelected) {
381             itemNode = picker.getNode(lastSelected);
382             if (itemNode) {
383                 picker.highlightItem(itemNode);
384                 picker.el.scrollChildIntoView(itemNode, false);
385             }
386         }
387     },
388
389     /**
390      * @private
391      * Disables the key nav for the Time picker when it is collapsed.
392      */
393     onCollapse: function() {
394         var me = this,
395             keyNav = me.pickerKeyNav;
396         if (keyNav) {
397             keyNav.disable();
398             me.ignoreMonitorTab = false;
399         }
400     },
401
402     /**
403      * @private
404      * Handles a time being selected from the Time picker.
405      */
406     onListSelect: function(list, recordArray) {
407         var me = this,
408             record = recordArray[0],
409             val = record ? record.get('date') : null;
410         me.setValue(val);
411         me.fireEvent('select', me, val);
412         me.picker.clearHighlight();
413         me.collapse();
414         me.inputEl.focus();
415     }
416 });
417