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