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