Merge "Fix typo in comment"
[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 () {
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.TextInputWidget
60 * @mixins OO.ui.mixin.IndicatorElement
61 *
62 * @constructor
63 * @param {Object} [config] Configuration options
64 * @cfg {string} [precision='day'] Date precision to use, 'day' or 'month'
65 * @cfg {string} [value] Day or month date (depending on `precision`), in the format 'YYYY-MM-DD'
66 * or 'YYYY-MM'. If not given or empty string, no date is selected.
67 * @cfg {string} [inputFormat] Date format string to use for the textual input field. Displayed
68 * while the widget is active, and the user can type in a date in this format. Should be short
69 * and easy to type. When not given, defaults to 'YYYY-MM-DD' or 'YYYY-MM', depending on
70 * `precision`.
71 * @cfg {string} [displayFormat] Date format string to use for the clickable label. Displayed
72 * while the widget is inactive. Should be as unambiguous as possible (for example, prefer to
73 * spell out the month, rather than rely on the order), even if that makes it longer. When not
74 * given, the default is language-specific.
75 * @cfg {boolean} [longDisplayFormat=false] If a custom displayFormat is not specified, use
76 * unabbreviated day of the week and month names in the default language-specific displayFormat.
77 * @cfg {string} [placeholderLabel=No date selected] Placeholder text shown when the widget is not
78 * selected. Default text taken from message `mw-widgets-dateinput-no-date`.
79 * @cfg {string} [placeholderDateFormat] User-visible date format string displayed in the textual input
80 * field when it's empty. Should be the same as `inputFormat`, but translated to the user's
81 * language. When not given, defaults to a translated version of 'YYYY-MM-DD' or 'YYYY-MM',
82 * depending on `precision`.
83 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
84 * @cfg {string} [mustBeAfter] Validates the date to be after this. In the 'YYYY-MM-DD' format.
85 * @cfg {string} [mustBeBefore] Validates the date to be before this. In the 'YYYY-MM-DD' format.
86 * @cfg {jQuery} [$overlay] Render the calendar into a separate layer. This configuration is
87 * useful in cases where the expanded calendar is larger than its container. The specified
88 * overlay layer is usually on top of the container and has a larger area. By default, the
89 * calendar uses relative positioning.
90 */
91 mw.widgets.DateInputWidget = function MWWDateInputWidget( config ) {
92 var placeholderDateFormat, mustBeAfter, mustBeBefore, $overlay;
93
94 // Config initialization
95 config = $.extend( {
96 precision: 'day',
97 longDisplayFormat: false,
98 required: false,
99 placeholderLabel: mw.msg( 'mw-widgets-dateinput-no-date' )
100 }, config );
101 if ( config.required ) {
102 if ( config.indicator === undefined ) {
103 config.indicator = 'required';
104 }
105 }
106
107 if ( config.placeholderDateFormat ) {
108 placeholderDateFormat = config.placeholderDateFormat;
109 } else if ( config.inputFormat ) {
110 // We have no way to display a translated placeholder for custom formats
111 placeholderDateFormat = '';
112 } else {
113 // The following messages are used here:
114 // * mw-widgets-dateinput-placeholder-day
115 // * mw-widgets-dateinput-placeholder-month
116 placeholderDateFormat = mw.msg( 'mw-widgets-dateinput-placeholder-' + config.precision );
117 }
118
119 // Properties (must be set before parent constructor, which calls #setValue)
120 this.$handle = $( '<div>' );
121 this.innerLabel = new OO.ui.LabelWidget();
122 this.textInput = new OO.ui.TextInputWidget( {
123 required: config.required,
124 placeholder: placeholderDateFormat,
125 validate: this.validateDate.bind( this )
126 } );
127 this.calendar = new mw.widgets.CalendarWidget( {
128 lazyInitOnToggle: true,
129 // Can't pass `$floatableContainer: this.$element` here, the latter is not set yet.
130 // Instead we call setFloatableContainer() below.
131 precision: config.precision
132 } );
133 this.inCalendar = 0;
134 this.inTextInput = 0;
135 this.closing = false;
136 this.inputFormat = config.inputFormat;
137 this.displayFormat = config.displayFormat;
138 this.longDisplayFormat = config.longDisplayFormat;
139 this.required = config.required;
140 this.placeholderLabel = config.placeholderLabel;
141 // Validate and set min and max dates as properties
142
143 if ( config.mustBeAfter !== undefined ) {
144 mustBeAfter = moment( config.mustBeAfter, 'YYYY-MM-DD' );
145 if ( mustBeAfter.isValid() ) {
146 this.mustBeAfter = mustBeAfter;
147 }
148 }
149 if ( config.mustBeBefore !== undefined ) {
150 mustBeBefore = moment( config.mustBeBefore, 'YYYY-MM-DD' );
151 if ( mustBeBefore.isValid() ) {
152 this.mustBeBefore = mustBeBefore;
153 }
154 }
155 // Parent constructor
156 mw.widgets.DateInputWidget.parent.call( this, config );
157
158 // Mixin constructors
159 OO.ui.mixin.IndicatorElement.call( this, config );
160
161 // Events
162 this.calendar.connect( this, {
163 change: 'onCalendarChange'
164 } );
165 this.textInput.connect( this, {
166 enter: 'onEnter',
167 change: 'onTextInputChange'
168 } );
169 this.$element.on( {
170 focusout: this.onBlur.bind( this )
171 } );
172 this.calendar.$element.on( {
173 focusout: this.onBlur.bind( this ),
174 click: this.onCalendarClick.bind( this ),
175 keypress: this.onCalendarKeyPress.bind( this )
176 } );
177 this.$handle.on( {
178 click: this.onClick.bind( this ),
179 keypress: this.onKeyPress.bind( this ),
180 focus: this.onFocus.bind( this )
181 } );
182
183 // Initialization
184 // Move 'tabindex' from this.$input (which is invisible) to the visible handle
185 this.setTabIndexedElement( this.$handle );
186 this.$handle
187 .append( this.innerLabel.$element, this.$indicator )
188 .addClass( 'mw-widget-dateInputWidget-handle' );
189 this.calendar.$element
190 .addClass( 'mw-widget-dateInputWidget-calendar' );
191 this.$element
192 .addClass( 'mw-widget-dateInputWidget' )
193 .append( this.$handle, this.textInput.$element, this.calendar.$element );
194
195 $overlay = config.$overlay === true ? OO.ui.getDefaultOverlay() : config.$overlay;
196
197 if ( $overlay ) {
198 this.calendar.setFloatableContainer( this.$element );
199 $overlay.append( this.calendar.$element );
200
201 // The text input and calendar are not in DOM order, so fix up focus transitions.
202 this.textInput.$input.on( 'keydown', function ( e ) {
203 if ( e.which === OO.ui.Keys.TAB ) {
204 if ( e.shiftKey ) {
205 // Tabbing backward from text input: normal browser behavior
206 } else {
207 // Tabbing forward from text input: just focus the calendar
208 this.calendar.$element.trigger( 'focus' );
209 return false;
210 }
211 }
212 }.bind( this ) );
213 this.calendar.$element.on( 'keydown', function ( e ) {
214 if ( e.which === OO.ui.Keys.TAB ) {
215 if ( e.shiftKey ) {
216 // Tabbing backward from calendar: just focus the text input
217 this.textInput.$input.trigger( 'focus' );
218 return false;
219 } else {
220 // Tabbing forward from calendar: focus the text input, then allow normal browser
221 // behavior to move focus to next focusable after it
222 this.textInput.$input.trigger( 'focus' );
223 }
224 }
225 }.bind( this ) );
226 }
227
228 // Set handle label and hide stuff
229 this.updateUI();
230 this.textInput.toggle( false );
231 this.calendar.toggle( false );
232
233 // Hide unused <input> from PHP after infusion is done
234 // See InputWidget#reusePreInfuseDOM about config.$input
235 if ( config.$input ) {
236 config.$input.addClass( 'oo-ui-element-hidden' );
237 }
238 };
239
240 /* Inheritance */
241
242 OO.inheritClass( mw.widgets.DateInputWidget, OO.ui.TextInputWidget );
243 OO.mixinClass( mw.widgets.DateInputWidget, OO.ui.mixin.IndicatorElement );
244
245 /* Events */
246
247 /**
248 * Fired when the widget is deactivated (i.e. the calendar is closed). This can happen because
249 * the user selected a value, or because the user blurred the widget.
250 *
251 * @event deactivate
252 * @param {boolean} userSelected Whether the deactivation happened because the user selected a value
253 */
254
255 /* Methods */
256
257 /**
258 * @inheritdoc
259 * @protected
260 */
261 mw.widgets.DateInputWidget.prototype.getInputElement = function () {
262 return $( '<input>' ).attr( 'type', 'hidden' );
263 };
264
265 /**
266 * Respond to calendar date change events.
267 *
268 * @private
269 */
270 mw.widgets.DateInputWidget.prototype.onCalendarChange = function () {
271 this.inCalendar++;
272 if ( !this.inTextInput ) {
273 // If this is caused by user typing in the input field, do not set anything.
274 // The value may be invalid (see #onTextInputChange), but displayable on the calendar.
275 this.setValue( this.calendar.getDate() );
276 }
277 this.inCalendar--;
278 };
279
280 /**
281 * Respond to text input value change events.
282 *
283 * @private
284 */
285 mw.widgets.DateInputWidget.prototype.onTextInputChange = function () {
286 var mom,
287 widget = this,
288 value = this.textInput.getValue(),
289 valid = this.isValidDate( value );
290 this.inTextInput++;
291
292 if ( value === '' ) {
293 // No date selected
294 widget.setValue( '' );
295 } else if ( valid ) {
296 // Well-formed date value, parse and set it
297 mom = moment( value, widget.getInputFormat() );
298 // Use English locale to avoid number formatting
299 widget.setValue( mom.locale( 'en' ).format( widget.getInternalFormat() ) );
300 } else {
301 // Not well-formed, but possibly partial? Try updating the calendar, but do not set the
302 // internal value. Generally this only makes sense when 'inputFormat' is little-endian (e.g.
303 // 'YYYY-MM-DD'), but that's hard to check for, and might be difficult to handle the parsing
304 // right for weird formats. So limit this trick to only when we're using the default
305 // 'inputFormat', which is the same as the internal format, 'YYYY-MM-DD'.
306 if ( widget.getInputFormat() === widget.getInternalFormat() ) {
307 widget.calendar.setDate( widget.textInput.getValue() );
308 }
309 }
310 widget.inTextInput--;
311
312 };
313
314 /**
315 * @inheritdoc
316 */
317 mw.widgets.DateInputWidget.prototype.setValue = function ( value ) {
318 var oldValue = this.value;
319
320 if ( !moment( value, this.getInternalFormat() ).isValid() ) {
321 value = '';
322 }
323
324 mw.widgets.DateInputWidget.parent.prototype.setValue.call( this, value );
325
326 if ( this.value !== oldValue ) {
327 this.updateUI();
328 this.setValidityFlag();
329 }
330
331 return this;
332 };
333
334 /**
335 * Handle text input and calendar blur events.
336 *
337 * @private
338 */
339 mw.widgets.DateInputWidget.prototype.onBlur = function () {
340 var widget = this;
341 setTimeout( function () {
342 var $focussed = $( ':focus' );
343 // Deactivate unless the focus moved to something else inside this widget
344 if (
345 !OO.ui.contains( widget.$element[ 0 ], $focussed[ 0 ], true ) &&
346 // Calendar might be in an $overlay
347 !OO.ui.contains( widget.calendar.$element[ 0 ], $focussed[ 0 ], true )
348 ) {
349 widget.deactivate();
350 }
351 }, 0 );
352 };
353
354 /**
355 * @inheritdoc
356 */
357 mw.widgets.DateInputWidget.prototype.focus = function () {
358 this.activate();
359 return this;
360 };
361
362 /**
363 * @inheritdoc
364 */
365 mw.widgets.DateInputWidget.prototype.blur = function () {
366 this.deactivate();
367 return this;
368 };
369
370 /**
371 * Update the contents of the label, text input and status of calendar to reflect selected value.
372 *
373 * @private
374 */
375 mw.widgets.DateInputWidget.prototype.updateUI = function () {
376 var moment;
377 if ( this.getValue() === '' ) {
378 this.textInput.setValue( '' );
379 this.calendar.setDate( null );
380 this.innerLabel.setLabel( this.placeholderLabel );
381 this.$element.addClass( 'mw-widget-dateInputWidget-empty' );
382 } else {
383 moment = this.getMoment();
384 if ( !this.inTextInput ) {
385 this.textInput.setValue( moment.format( this.getInputFormat() ) );
386 }
387 if ( !this.inCalendar ) {
388 this.calendar.setDate( this.getValue() );
389 }
390 this.innerLabel.setLabel( moment.format( this.getDisplayFormat() ) );
391 this.$element.removeClass( 'mw-widget-dateInputWidget-empty' );
392 }
393 };
394
395 /**
396 * Deactivate this input field for data entry. Closes the calendar and hides the text field.
397 *
398 * @private
399 * @param {boolean} [userSelected] Whether we are deactivating because the user selected a value
400 */
401 mw.widgets.DateInputWidget.prototype.deactivate = function ( userSelected ) {
402 this.$element.removeClass( 'mw-widget-dateInputWidget-active' );
403 this.$handle.show();
404 this.textInput.toggle( false );
405 this.calendar.toggle( false );
406 this.setValidityFlag();
407
408 if ( userSelected ) {
409 // Prevent focusing the handle from reopening the calendar
410 this.closing = true;
411 this.$handle.trigger( 'focus' );
412 this.closing = false;
413 }
414
415 this.emit( 'deactivate', !!userSelected );
416 };
417
418 /**
419 * Activate this input field for data entry. Opens the calendar and shows the text field.
420 *
421 * @private
422 */
423 mw.widgets.DateInputWidget.prototype.activate = function () {
424 this.calendar.resetUI();
425 this.$element.addClass( 'mw-widget-dateInputWidget-active' );
426 this.$handle.hide();
427 this.textInput.toggle( true );
428 this.calendar.toggle( true );
429
430 this.textInput.$input.trigger( 'focus' );
431 };
432
433 /**
434 * Get the date format to be used for handle label when the input is inactive.
435 *
436 * @private
437 * @return {string} Format string
438 */
439 mw.widgets.DateInputWidget.prototype.getDisplayFormat = function () {
440 var localeData, llll, lll, ll, format;
441
442 if ( this.displayFormat !== undefined ) {
443 return this.displayFormat;
444 }
445
446 if ( this.calendar.getPrecision() === 'month' ) {
447 return 'MMMM YYYY';
448 } else {
449 // The formats Moment.js provides:
450 // * ll: Month name, day of month, year
451 // * lll: Month name, day of month, year, time
452 // * llll: Month name, day of month, day of week, year, time
453 //
454 // The format we want:
455 // * ????: Month name, day of month, day of week, year
456 //
457 // We try to construct it as 'llll - (lll - ll)' and hope for the best.
458 // This seems to work well for many languages (maybe even all?).
459
460 localeData = moment.localeData( moment.locale() );
461 llll = localeData.longDateFormat( 'llll' );
462 lll = localeData.longDateFormat( 'lll' );
463 ll = localeData.longDateFormat( 'll' );
464 format = llll.replace( lll.replace( ll, '' ), '' );
465
466 if ( this.longDisplayFormat ) {
467 // Replace MMM to MMMM and ddd to dddd but don't change MMMM and dddd
468 format = format.replace( /MMMM?/, 'MMMM' ).replace( /dddd?/, 'dddd' );
469 }
470
471 return format;
472 }
473 };
474
475 /**
476 * Get the date format to be used for the text field when the input is active.
477 *
478 * @private
479 * @return {string} Format string
480 */
481 mw.widgets.DateInputWidget.prototype.getInputFormat = function () {
482 if ( this.inputFormat !== undefined ) {
483 return this.inputFormat;
484 }
485
486 return {
487 day: 'YYYY-MM-DD',
488 month: 'YYYY-MM'
489 }[ this.calendar.getPrecision() ];
490 };
491
492 /**
493 * Get the date format to be used internally for the value. This is not configurable in any way,
494 * and always either 'YYYY-MM-DD' or 'YYYY-MM'.
495 *
496 * @private
497 * @return {string} Format string
498 */
499 mw.widgets.DateInputWidget.prototype.getInternalFormat = function () {
500 return {
501 day: 'YYYY-MM-DD',
502 month: 'YYYY-MM'
503 }[ this.calendar.getPrecision() ];
504 };
505
506 /**
507 * Get the Moment object for current value.
508 *
509 * @return {Object} Moment object
510 */
511 mw.widgets.DateInputWidget.prototype.getMoment = function () {
512 return moment( this.getValue(), this.getInternalFormat() );
513 };
514
515 /**
516 * Handle mouse click events.
517 *
518 * @private
519 * @param {jQuery.Event} e Mouse click event
520 * @return {boolean} False to cancel the default event
521 */
522 mw.widgets.DateInputWidget.prototype.onClick = function ( e ) {
523 if ( !this.isDisabled() && e.which === 1 ) {
524 this.activate();
525 }
526 return false;
527 };
528
529 /**
530 * Handle key press events.
531 *
532 * @private
533 * @param {jQuery.Event} e Key press event
534 * @return {boolean} False to cancel the default event
535 */
536 mw.widgets.DateInputWidget.prototype.onKeyPress = function ( e ) {
537 if ( !this.isDisabled() &&
538 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
539 ) {
540 this.activate();
541 return false;
542 }
543 };
544
545 /**
546 * Handle focus events.
547 *
548 * @private
549 */
550 mw.widgets.DateInputWidget.prototype.onFocus = function () {
551 if ( !this.closing ) {
552 this.activate();
553 }
554 };
555
556 /**
557 * Handle calendar key press events.
558 *
559 * @private
560 * @param {jQuery.Event} e Key press event
561 * @return {boolean} False to cancel the default event
562 */
563 mw.widgets.DateInputWidget.prototype.onCalendarKeyPress = function ( e ) {
564 if ( !this.isDisabled() && e.which === OO.ui.Keys.ENTER ) {
565 this.deactivate( true );
566 return false;
567 }
568 };
569
570 /**
571 * Handle calendar click events.
572 *
573 * @private
574 * @param {jQuery.Event} e Mouse click event
575 * @return {boolean} False to cancel the default event
576 */
577 mw.widgets.DateInputWidget.prototype.onCalendarClick = function ( e ) {
578 var targetClass = this.calendar.getPrecision() === 'month' ?
579 'mw-widget-calendarWidget-month' :
580 'mw-widget-calendarWidget-day';
581 if (
582 !this.isDisabled() &&
583 e.which === 1 &&
584 // eslint-disable-next-line no-jquery/no-class-state
585 $( e.target ).hasClass( targetClass )
586 ) {
587 this.deactivate( true );
588 return false;
589 }
590 };
591
592 /**
593 * Handle text input enter events.
594 *
595 * @private
596 */
597 mw.widgets.DateInputWidget.prototype.onEnter = function () {
598 this.deactivate( true );
599 };
600
601 /**
602 * @private
603 * @param {string} date Date string, to be valid, must be in 'YYYY-MM-DD' or 'YYYY-MM' format or
604 * (unless the field is required) empty
605 * @return {boolean}
606 */
607 mw.widgets.DateInputWidget.prototype.validateDate = function ( date ) {
608 var isValid;
609 if ( date === '' ) {
610 isValid = !this.required;
611 } else {
612 isValid = this.isValidDate( date ) && this.isInRange( date );
613 }
614 return isValid;
615 };
616
617 /**
618 * @private
619 * @param {string} date Date string, to be valid, must be in 'YYYY-MM-DD' or 'YYYY-MM' format
620 * @return {boolean}
621 */
622 mw.widgets.DateInputWidget.prototype.isValidDate = function ( date ) {
623 // "Half-strict mode": for example, for the format 'YYYY-MM-DD', 2015-1-3 instead of 2015-01-03
624 // is okay, but 2015-01 isn't, and neither is 2015-01-foo. Use Moment's "fuzzy" mode and check
625 // parsing flags for the details (stolen from implementation of moment#isValid).
626 var
627 mom = moment( date, this.getInputFormat() ),
628 flags = mom.parsingFlags();
629
630 return mom.isValid() && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0;
631 };
632
633 /**
634 * Validates if the date is within the range configured with {@link #cfg-mustBeAfter}
635 * and {@link #cfg-mustBeBefore}.
636 *
637 * @private
638 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
639 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
640 * @return {boolean}
641 */
642 mw.widgets.DateInputWidget.prototype.isInRange = function ( date ) {
643 var momentDate, isAfter, isBefore;
644 if ( this.mustBeAfter === undefined && this.mustBeBefore === undefined ) {
645 return true;
646 }
647 momentDate = moment( date, 'YYYY-MM-DD' );
648 isAfter = ( this.mustBeAfter === undefined || momentDate.isAfter( this.mustBeAfter ) );
649 isBefore = ( this.mustBeBefore === undefined || momentDate.isBefore( this.mustBeBefore ) );
650 return isAfter && isBefore;
651 };
652
653 /**
654 * Get the validity of current value.
655 *
656 * This method returns a promise that resolves if the value is valid and rejects if
657 * it isn't. Uses {@link #validateDate}.
658 *
659 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
660 */
661 mw.widgets.DateInputWidget.prototype.getValidity = function () {
662 var isValid = this.validateDate( this.getValue() );
663
664 if ( isValid ) {
665 return $.Deferred().resolve().promise();
666 } else {
667 return $.Deferred().reject().promise();
668 }
669 };
670
671 /**
672 * Sets the 'invalid' flag appropriately.
673 *
674 * @param {boolean} [isValid] Optionally override validation result
675 */
676 mw.widgets.DateInputWidget.prototype.setValidityFlag = function ( isValid ) {
677 var widget = this,
678 setFlag = function ( valid ) {
679 if ( !valid ) {
680 widget.$input.attr( 'aria-invalid', 'true' );
681 } else {
682 widget.$input.removeAttr( 'aria-invalid' );
683 }
684 widget.setFlags( { invalid: !valid } );
685 };
686
687 if ( isValid !== undefined ) {
688 setFlag( isValid );
689 } else {
690 this.getValidity().then( function () {
691 setFlag( true );
692 }, function () {
693 setFlag( false );
694 } );
695 }
696 };
697
698 }() );