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