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