mw.widgets.DateInputWidget: Implement $overlay config option
[lhc/web/wiklou.git] / resources / src / mediawiki.widgets / mw.widgets.DateInputWidget.js
1 /*!
2 * MediaWiki Widgets – DateInputWidget class.
3 *
4 * @copyright 2011-2015 MediaWiki Widgets Team and others; see AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7 /*global moment */
8 ( function ( $, mw ) {
9
10 /**
11 * Creates an mw.widgets.DateInputWidget object.
12 *
13 * @example
14 * // Date input widget showcase
15 * var fieldset = new OO.ui.FieldsetLayout( {
16 * items: [
17 * new OO.ui.FieldLayout(
18 * new mw.widgets.DateInputWidget(),
19 * {
20 * align: 'top',
21 * label: 'Select date'
22 * }
23 * ),
24 * new OO.ui.FieldLayout(
25 * new mw.widgets.DateInputWidget( { precision: 'month' } ),
26 * {
27 * align: 'top',
28 * label: 'Select month'
29 * }
30 * ),
31 * new OO.ui.FieldLayout(
32 * new mw.widgets.DateInputWidget( {
33 * inputFormat: 'DD.MM.YYYY',
34 * displayFormat: 'Do [of] MMMM [anno Domini] YYYY'
35 * } ),
36 * {
37 * align: 'top',
38 * label: 'Select date (custom formats)'
39 * }
40 * )
41 * ]
42 * } );
43 * $( 'body' ).append( fieldset.$element );
44 *
45 * The value is stored in 'YYYY-MM-DD' or 'YYYY-MM' format:
46 *
47 * @example
48 * // Accessing values in a date input widget
49 * var dateInput = new mw.widgets.DateInputWidget();
50 * var $label = $( '<p>' );
51 * $( 'body' ).append( $label, dateInput.$element );
52 * dateInput.on( 'change', function () {
53 * // The value will always be a valid date or empty string, malformed input is ignored
54 * var date = dateInput.getValue();
55 * $label.text( 'Selected date: ' + ( date || '(none)' ) );
56 * } );
57 *
58 * @class
59 * @extends OO.ui.InputWidget
60 *
61 * @constructor
62 * @param {Object} [config] Configuration options
63 * @cfg {string} [precision='day'] Date precision to use, 'day' or 'month'
64 * @cfg {string} [value] Day or month date (depending on `precision`), in the format 'YYYY-MM-DD'
65 * or 'YYYY-MM'. If not given or empty string, no date is selected.
66 * @cfg {string} [inputFormat] Date format string to use for the textual input field. Displayed
67 * while the widget is active, and the user can type in a date in this format. Should be short
68 * and easy to type. When not given, defaults to 'YYYY-MM-DD' or 'YYYY-MM', depending on
69 * `precision`.
70 * @cfg {string} [displayFormat] Date format string to use for the clickable label. Displayed
71 * while the widget is inactive. Should be as unambiguous as possible (for example, prefer to
72 * spell out the month, rather than rely on the order), even if that makes it longer. When not
73 * given, the default is language-specific.
74 * @cfg {string} [placeholder] User-visible date format string displayed in the textual input
75 * field when it's empty. Should be the same as `inputFormat`, but translated to the user's
76 * language. When not given, defaults to a translated version of 'YYYY-MM-DD' or 'YYYY-MM',
77 * depending on `precision`.
78 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
79 * @cfg {string} [mustBeAfter] Validates the date to be after this. In the 'YYYY-MM-DD' format.
80 * @cfg {string} [mustBeBefore] Validates the date to be before this. In the 'YYYY-MM-DD' format.
81 * @cfg {jQuery} [$overlay] Render the calendar into a separate layer. This configuration is
82 * useful in cases where the expanded calendar is larger than its container. The specified
83 * overlay layer is usually on top of the container and has a larger area. By default, the
84 * calendar uses relative positioning.
85 */
86 mw.widgets.DateInputWidget = function MWWDateInputWidget( config ) {
87 // Config initialization
88 config = $.extend( { precision: 'day' }, config );
89 if ( config.required ) {
90 if ( config.indicator === undefined ) {
91 config.indicator = 'required';
92 }
93 }
94
95 var placeholder, mustBeAfter, mustBeBefore;
96 if ( config.placeholder ) {
97 placeholder = config.placeholder;
98 } else if ( config.inputFormat ) {
99 // We have no way to display a translated placeholder for custom formats
100 placeholder = '';
101 } else {
102 // Messages: mw-widgets-dateinput-placeholder-day, mw-widgets-dateinput-placeholder-month
103 placeholder = mw.msg( 'mw-widgets-dateinput-placeholder-' + config.precision );
104 }
105
106 // Properties (must be set before parent constructor, which calls #setValue)
107 this.handle = new OO.ui.LabelWidget();
108 this.textInput = new OO.ui.TextInputWidget( {
109 placeholder: placeholder,
110 validate: this.validateDate.bind( this )
111 } );
112 this.calendar = new mw.widgets.CalendarWidget( {
113 // Can't pass `$floatableContainer: this.$element` here, the latter is not set yet.
114 // Instead we call setFloatableContainer() below.
115 precision: config.precision
116 } );
117 this.inCalendar = 0;
118 this.inTextInput = 0;
119 this.inputFormat = config.inputFormat;
120 this.displayFormat = config.displayFormat;
121
122 // Validate and set min and max dates as properties
123 mustBeAfter = moment( config.mustBeAfter, 'YYYY-MM-DD' );
124 mustBeBefore = moment( config.mustBeBefore, 'YYYY-MM-DD' );
125 if (
126 config.mustBeAfter !== undefined &&
127 mustBeAfter.isValid()
128 ) {
129 this.mustBeAfter = mustBeAfter;
130 }
131
132 if (
133 config.mustBeBefore !== undefined &&
134 mustBeBefore.isValid()
135 ) {
136 this.mustBeBefore = mustBeBefore;
137 }
138
139 // Parent constructor
140 mw.widgets.DateInputWidget.parent.call( this, config );
141
142 // Events
143 this.calendar.connect( this, {
144 change: 'onCalendarChange'
145 } );
146 this.textInput.connect( this, {
147 enter: 'onEnter',
148 change: 'onTextInputChange'
149 } );
150 this.$element.on( {
151 focusout: this.onBlur.bind( this )
152 } );
153 this.calendar.$element.on( {
154 keypress: this.onCalendarKeyPress.bind( this )
155 } );
156 this.handle.$element.on( {
157 click: this.onClick.bind( this ),
158 keypress: this.onKeyPress.bind( this )
159 } );
160
161 // Initialization
162 if ( config.required ) {
163 this.$input.attr( 'required', 'required' );
164 this.$input.attr( 'aria-required', 'true' );
165 }
166 // Move 'tabindex' from this.$input (which is invisible) to the visible handle
167 this.setTabIndexedElement( this.handle.$element );
168 this.handle.$element
169 .addClass( 'mw-widget-dateInputWidget-handle' );
170 this.calendar.$element
171 .addClass( 'mw-widget-dateInputWidget-calendar' );
172 this.$element
173 .addClass( 'mw-widget-dateInputWidget' )
174 .append( this.handle.$element, this.textInput.$element, this.calendar.$element );
175
176 if ( config.$overlay ) {
177 this.calendar.setFloatableContainer( this.$element );
178 config.$overlay.append( this.calendar.$element );
179
180 // The text input and calendar are not in DOM order, so fix up focus transitions.
181 this.textInput.$input.on( 'keydown', function ( e ) {
182 if ( e.which === OO.ui.Keys.TAB ) {
183 if ( e.shiftKey ) {
184 // Tabbing backward from text input: normal browser behavior
185 $.noop();
186 } else {
187 // Tabbing forward from text input: just focus the calendar
188 this.calendar.$element.focus();
189 return false;
190 }
191 }
192 }.bind( this ) );
193 this.calendar.$element.on( 'keydown', function ( e ) {
194 if ( e.which === OO.ui.Keys.TAB ) {
195 if ( e.shiftKey ) {
196 // Tabbing backward from calendar: just focus the text input
197 this.textInput.$input.focus();
198 return false;
199 } else {
200 // Tabbing forward from calendar: focus the text input, then allow normal browser
201 // behavior to move focus to next focusable after it
202 this.textInput.$input.focus();
203 }
204 }
205 }.bind( this ) );
206 }
207
208 // Set handle label and hide stuff
209 this.updateUI();
210 this.deactivate();
211 };
212
213 /* Inheritance */
214
215 OO.inheritClass( mw.widgets.DateInputWidget, OO.ui.InputWidget );
216
217 /* Methods */
218
219 /**
220 * @inheritdoc
221 * @protected
222 */
223 mw.widgets.DateInputWidget.prototype.getInputElement = function () {
224 return $( '<input type="hidden">' );
225 };
226
227 /**
228 * Respond to calendar date change events.
229 *
230 * @private
231 */
232 mw.widgets.DateInputWidget.prototype.onCalendarChange = function () {
233 this.inCalendar++;
234 if ( !this.inTextInput ) {
235 // If this is caused by user typing in the input field, do not set anything.
236 // The value may be invalid (see #onTextInputChange), but displayable on the calendar.
237 this.setValue( this.calendar.getDate() );
238 }
239 this.inCalendar--;
240 };
241
242 /**
243 * Respond to text input value change events.
244 *
245 * @private
246 */
247 mw.widgets.DateInputWidget.prototype.onTextInputChange = function () {
248 var mom,
249 widget = this,
250 value = this.textInput.getValue(),
251 valid = this.isValidDate( value );
252 this.inTextInput++;
253
254 if ( value === '' ) {
255 // No date selected
256 widget.setValue( '' );
257 } else if ( valid ) {
258 // Well-formed date value, parse and set it
259 mom = moment( value, widget.getInputFormat() );
260 // Use English locale to avoid number formatting
261 widget.setValue( mom.locale( 'en' ).format( widget.getInternalFormat() ) );
262 } else {
263 // Not well-formed, but possibly partial? Try updating the calendar, but do not set the
264 // internal value. Generally this only makes sense when 'inputFormat' is little-endian (e.g.
265 // 'YYYY-MM-DD'), but that's hard to check for, and might be difficult to handle the parsing
266 // right for weird formats. So limit this trick to only when we're using the default
267 // 'inputFormat', which is the same as the internal format, 'YYYY-MM-DD'.
268 if ( widget.getInputFormat() === widget.getInternalFormat() ) {
269 widget.calendar.setDate( widget.textInput.getValue() );
270 }
271 }
272 widget.inTextInput--;
273
274 };
275
276 /**
277 * @inheritdoc
278 */
279 mw.widgets.DateInputWidget.prototype.setValue = function ( value ) {
280 var oldValue = this.value;
281
282 if ( !moment( value, this.getInternalFormat() ).isValid() ) {
283 value = '';
284 }
285
286 mw.widgets.DateInputWidget.parent.prototype.setValue.call( this, value );
287
288 if ( this.value !== oldValue ) {
289 this.updateUI();
290 }
291
292 return this;
293 };
294
295 /**
296 * Handle text input and calendar blur events.
297 *
298 * @private
299 */
300 mw.widgets.DateInputWidget.prototype.onBlur = function () {
301 var widget = this;
302 setTimeout( function () {
303 var $focussed = $( ':focus' );
304 // Deactivate unless the focus moved to something else inside this widget
305 if (
306 !OO.ui.contains( widget.$element[ 0 ], $focussed[ 0 ], true ) &&
307 // Calendar might be in an $overlay
308 !OO.ui.contains( widget.calendar.$element[ 0 ], $focussed[ 0 ], true )
309 ) {
310 widget.deactivate();
311 }
312 }, 0 );
313 };
314
315 /**
316 * @inheritdoc
317 */
318 mw.widgets.DateInputWidget.prototype.focus = function () {
319 this.activate();
320 return this;
321 };
322
323 /**
324 * @inheritdoc
325 */
326 mw.widgets.DateInputWidget.prototype.blur = function () {
327 this.deactivate();
328 return this;
329 };
330
331 /**
332 * Update the contents of the label, text input and status of calendar to reflect selected value.
333 *
334 * @private
335 */
336 mw.widgets.DateInputWidget.prototype.updateUI = function () {
337 if ( this.getValue() === '' ) {
338 this.textInput.setValue( '' );
339 this.calendar.setDate( null );
340 this.handle.setLabel( mw.msg( 'mw-widgets-dateinput-no-date' ) );
341 this.$element.addClass( 'mw-widget-dateInputWidget-empty' );
342 } else {
343 if ( !this.inTextInput ) {
344 this.textInput.setValue( this.getMoment().format( this.getInputFormat() ) );
345 }
346 if ( !this.inCalendar ) {
347 this.calendar.setDate( this.getValue() );
348 }
349 this.handle.setLabel( this.getMoment().format( this.getDisplayFormat() ) );
350 this.$element.removeClass( 'mw-widget-dateInputWidget-empty' );
351 }
352 };
353
354 /**
355 * Deactivate this input field for data entry. Closes the calendar and hides the text field.
356 *
357 * @private
358 */
359 mw.widgets.DateInputWidget.prototype.deactivate = function () {
360 this.$element.removeClass( 'mw-widget-dateInputWidget-active' );
361 this.handle.toggle( true );
362 this.textInput.toggle( false );
363 this.calendar.toggle( false );
364 };
365
366 /**
367 * Activate this input field for data entry. Opens the calendar and shows the text field.
368 *
369 * @private
370 */
371 mw.widgets.DateInputWidget.prototype.activate = function () {
372 this.calendar.resetUI();
373 this.$element.addClass( 'mw-widget-dateInputWidget-active' );
374 this.handle.toggle( false );
375 this.textInput.toggle( true );
376 this.calendar.toggle( true );
377
378 this.textInput.$input.focus();
379 };
380
381 /**
382 * Get the date format to be used for handle label when the input is inactive.
383 *
384 * @private
385 * @return {string} Format string
386 */
387 mw.widgets.DateInputWidget.prototype.getDisplayFormat = function () {
388 if ( this.displayFormat !== undefined ) {
389 return this.displayFormat;
390 }
391
392 if ( this.calendar.getPrecision() === 'month' ) {
393 return 'MMMM YYYY';
394 } else {
395 // The formats Moment.js provides:
396 // * ll: Month name, day of month, year
397 // * lll: Month name, day of month, year, time
398 // * llll: Month name, day of month, day of week, year, time
399 //
400 // The format we want:
401 // * ????: Month name, day of month, day of week, year
402 //
403 // We try to construct it as 'llll - (lll - ll)' and hope for the best.
404 // This seems to work well for many languages (maybe even all?).
405
406 var localeData = moment.localeData( moment.locale() ),
407 llll = localeData.longDateFormat( 'llll' ),
408 lll = localeData.longDateFormat( 'lll' ),
409 ll = localeData.longDateFormat( 'll' ),
410 format = llll.replace( lll.replace( ll, '' ), '' );
411
412 return format;
413 }
414 };
415
416 /**
417 * Get the date format to be used for the text field when the input is active.
418 *
419 * @private
420 * @return {string} Format string
421 */
422 mw.widgets.DateInputWidget.prototype.getInputFormat = function () {
423 if ( this.inputFormat !== undefined ) {
424 return this.inputFormat;
425 }
426
427 return {
428 day: 'YYYY-MM-DD',
429 month: 'YYYY-MM'
430 }[ this.calendar.getPrecision() ];
431 };
432
433 /**
434 * Get the date format to be used internally for the value. This is not configurable in any way,
435 * and always either 'YYYY-MM-DD' or 'YYYY-MM'.
436 *
437 * @private
438 * @return {string} Format string
439 */
440 mw.widgets.DateInputWidget.prototype.getInternalFormat = function () {
441 return {
442 day: 'YYYY-MM-DD',
443 month: 'YYYY-MM'
444 }[ this.calendar.getPrecision() ];
445 };
446
447 /**
448 * Get the Moment object for current value.
449 *
450 * @return {Object} Moment object
451 */
452 mw.widgets.DateInputWidget.prototype.getMoment = function () {
453 return moment( this.getValue(), this.getInternalFormat() );
454 };
455
456 /**
457 * Handle mouse click events.
458 *
459 * @private
460 * @param {jQuery.Event} e Mouse click event
461 */
462 mw.widgets.DateInputWidget.prototype.onClick = function ( e ) {
463 if ( !this.isDisabled() && e.which === 1 ) {
464 this.activate();
465 }
466 return false;
467 };
468
469 /**
470 * Handle key press events.
471 *
472 * @private
473 * @param {jQuery.Event} e Key press event
474 */
475 mw.widgets.DateInputWidget.prototype.onKeyPress = function ( e ) {
476 if ( !this.isDisabled() &&
477 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
478 ) {
479 this.activate();
480 return false;
481 }
482 };
483
484 /**
485 * Handle calendar key press events.
486 *
487 * @private
488 * @param {jQuery.Event} e Key press event
489 */
490 mw.widgets.DateInputWidget.prototype.onCalendarKeyPress = function ( e ) {
491 if ( !this.isDisabled() && e.which === OO.ui.Keys.ENTER ) {
492 this.deactivate();
493 this.handle.$element.focus();
494 return false;
495 }
496 };
497
498 /**
499 * Handle text input enter events.
500 *
501 * @private
502 */
503 mw.widgets.DateInputWidget.prototype.onEnter = function () {
504 this.deactivate();
505 this.handle.$element.focus();
506 };
507
508 /**
509 * @private
510 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
511 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
512 * @returns {boolean}
513 */
514 mw.widgets.DateInputWidget.prototype.validateDate = function ( date ) {
515 if ( date === '' ) {
516 return true;
517 }
518
519 var isValid = this.isValidDate( date ) && this.isInRange( date );
520 this.setValidityFlag( isValid );
521 return isValid;
522 };
523
524 /**
525 * @private
526 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
527 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
528 * @returns {boolean}
529 */
530 mw.widgets.DateInputWidget.prototype.isValidDate = function ( date ) {
531 // "Half-strict mode": for example, for the format 'YYYY-MM-DD', 2015-1-3 instead of 2015-01-03
532 // is okay, but 2015-01 isn't, and neither is 2015-01-foo. Use Moment's "fuzzy" mode and check
533 // parsing flags for the details (stoled from implementation of #isValid).
534 var
535 mom = moment( date, this.getInputFormat() ),
536 flags = mom.parsingFlags();
537
538 return mom.isValid() && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0;
539 };
540
541 /**
542 * Validates if the date is within the range configured with {@link #cfg-mustBeAfter}
543 * and {@link #cfg-mustBeBefore}.
544 *
545 * @private
546 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
547 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
548 * @returns {boolean}
549 */
550 mw.widgets.DateInputWidget.prototype.isInRange = function ( date ) {
551 var momentDate = moment( date, 'YYYY-MM-DD' ),
552 isAfter = ( this.mustBeAfter === undefined || momentDate.isAfter( this.mustBeAfter ) ),
553 isBefore = ( this.mustBeBefore === undefined || momentDate.isBefore( this.mustBeBefore ) );
554
555 return isAfter && isBefore;
556 };
557
558 /**
559 * Get the validity of current value.
560 *
561 * This method returns a promise that resolves if the value is valid and rejects if
562 * it isn't. Uses {@link #validateDate}.
563 *
564 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
565 */
566 mw.widgets.DateInputWidget.prototype.getValidity = function () {
567 var isValid = this.validateDate( this.getValue() );
568
569 if ( isValid ) {
570 return $.Deferred().resolve().promise();
571 } else {
572 return $.Deferred().reject().promise();
573 }
574 };
575
576 /**
577 * Sets the 'invalid' flag appropriately.
578 *
579 * @param {boolean} [isValid] Optionally override validation result
580 */
581 mw.widgets.DateInputWidget.prototype.setValidityFlag = function ( isValid ) {
582 var widget = this,
583 setFlag = function ( valid ) {
584 if ( !valid ) {
585 widget.$input.attr( 'aria-invalid', 'true' );
586 } else {
587 widget.$input.removeAttr( 'aria-invalid' );
588 }
589 widget.setFlags( { invalid: !valid } );
590 };
591
592 if ( isValid !== undefined ) {
593 setFlag( isValid );
594 } else {
595 this.getValidity().then( function () {
596 setFlag( true );
597 }, function () {
598 setFlag( false );
599 } );
600 }
601 };
602
603 }( jQuery, mediaWiki ) );