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