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