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