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