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