Merge "Add tests for WikiMap and WikiReference"
[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.$element.addClass( 'mw-widget-dateInputWidget-active' );
328 this.handle.toggle( false );
329 this.textInput.toggle( true );
330 this.calendar.toggle( true );
331
332 this.textInput.$input.focus();
333 };
334
335 /**
336 * Get the date format to be used for handle label when the input is inactive.
337 *
338 * @private
339 * @return {string} Format string
340 */
341 mw.widgets.DateInputWidget.prototype.getDisplayFormat = function () {
342 if ( this.displayFormat !== undefined ) {
343 return this.displayFormat;
344 }
345
346 if ( this.calendar.getPrecision() === 'month' ) {
347 return 'MMMM YYYY';
348 } else {
349 // The formats Moment.js provides:
350 // * ll: Month name, day of month, year
351 // * lll: Month name, day of month, year, time
352 // * llll: Month name, day of month, day of week, year, time
353 //
354 // The format we want:
355 // * ????: Month name, day of month, day of week, year
356 //
357 // We try to construct it as 'llll - (lll - ll)' and hope for the best.
358 // This seems to work well for many languages (maybe even all?).
359
360 var localeData = moment.localeData( moment.locale() ),
361 llll = localeData.longDateFormat( 'llll' ),
362 lll = localeData.longDateFormat( 'lll' ),
363 ll = localeData.longDateFormat( 'll' ),
364 format = llll.replace( lll.replace( ll, '' ), '' );
365
366 return format;
367 }
368 };
369
370 /**
371 * Get the date format to be used for the text field when the input is active.
372 *
373 * @private
374 * @return {string} Format string
375 */
376 mw.widgets.DateInputWidget.prototype.getInputFormat = function () {
377 if ( this.inputFormat !== undefined ) {
378 return this.inputFormat;
379 }
380
381 return {
382 day: 'YYYY-MM-DD',
383 month: 'YYYY-MM'
384 }[ this.calendar.getPrecision() ];
385 };
386
387 /**
388 * Get the date format to be used internally for the value. This is not configurable in any way,
389 * and always either 'YYYY-MM-DD' or 'YYYY-MM'.
390 *
391 * @private
392 * @return {string} Format string
393 */
394 mw.widgets.DateInputWidget.prototype.getInternalFormat = function () {
395 return {
396 day: 'YYYY-MM-DD',
397 month: 'YYYY-MM'
398 }[ this.calendar.getPrecision() ];
399 };
400
401 /**
402 * Get the Moment object for current value.
403 *
404 * @return {Object} Moment object
405 */
406 mw.widgets.DateInputWidget.prototype.getMoment = function () {
407 return moment( this.getValue(), this.getInternalFormat() );
408 };
409
410 /**
411 * Handle mouse click events.
412 *
413 * @private
414 * @param {jQuery.Event} e Mouse click event
415 */
416 mw.widgets.DateInputWidget.prototype.onClick = function ( e ) {
417 if ( !this.isDisabled() && e.which === 1 ) {
418 this.activate();
419 }
420 return false;
421 };
422
423 /**
424 * Handle key press events.
425 *
426 * @private
427 * @param {jQuery.Event} e Key press event
428 */
429 mw.widgets.DateInputWidget.prototype.onKeyPress = function ( e ) {
430 if ( !this.isDisabled() &&
431 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
432 ) {
433 this.activate();
434 return false;
435 }
436 };
437
438 /**
439 * Handle calendar key press events.
440 *
441 * @private
442 * @param {jQuery.Event} e Key press event
443 */
444 mw.widgets.DateInputWidget.prototype.onCalendarKeyPress = function ( e ) {
445 if ( !this.isDisabled() && e.which === OO.ui.Keys.ENTER ) {
446 this.deactivate();
447 this.handle.$element.focus();
448 return false;
449 }
450 };
451
452 /**
453 * Handle text input enter events.
454 *
455 * @private
456 */
457 mw.widgets.DateInputWidget.prototype.onEnter = function () {
458 this.deactivate();
459 this.handle.$element.focus();
460 };
461
462 /**
463 * @private
464 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
465 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
466 * @returns {boolean}
467 */
468 mw.widgets.DateInputWidget.prototype.validateDate = function ( date ) {
469 if ( date === '' ) {
470 return true;
471 }
472
473 var isValid = this.isValidDate( date ) && this.isInRange( date );
474 this.setValidityFlag( isValid );
475 return isValid;
476 };
477
478 /**
479 * @private
480 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
481 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
482 * @returns {boolean}
483 */
484 mw.widgets.DateInputWidget.prototype.isValidDate = function ( date ) {
485 // "Half-strict mode": for example, for the format 'YYYY-MM-DD', 2015-1-3 instead of 2015-01-03
486 // is okay, but 2015-01 isn't, and neither is 2015-01-foo. Use Moment's "fuzzy" mode and check
487 // parsing flags for the details (stoled from implementation of #isValid).
488 var
489 mom = moment( date, this.getInputFormat() ),
490 flags = mom.parsingFlags();
491
492 return mom.isValid() && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0;
493 };
494
495 /**
496 * Validates if the date is within the range configured with {@link #cfg-mustBeAfter}
497 * and {@link #cfg-mustBeBefore}.
498 *
499 * @private
500 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
501 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
502 * @returns {boolean}
503 */
504 mw.widgets.DateInputWidget.prototype.isInRange = function ( date ) {
505 var momentDate = moment( date, 'YYYY-MM-DD' ),
506 isAfter = ( this.mustBeAfter === undefined || momentDate.isAfter( this.mustBeAfter ) ),
507 isBefore = ( this.mustBeBefore === undefined || momentDate.isBefore( this.mustBeBefore ) );
508
509 return isAfter && isBefore;
510 };
511
512 /**
513 * Get the validity of current value.
514 *
515 * This method returns a promise that resolves if the value is valid and rejects if
516 * it isn't. Uses {@link #validateDate}.
517 *
518 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
519 */
520 mw.widgets.DateInputWidget.prototype.getValidity = function () {
521 var isValid = this.validateDate( this.getValue() );
522
523 if ( isValid ) {
524 return $.Deferred().resolve().promise();
525 } else {
526 return $.Deferred().reject().promise();
527 }
528 };
529
530 /**
531 * Sets the 'invalid' flag appropriately.
532 *
533 * @param {boolean} [isValid] Optionally override validation result
534 */
535 mw.widgets.DateInputWidget.prototype.setValidityFlag = function ( isValid ) {
536 var widget = this,
537 setFlag = function ( valid ) {
538 if ( !valid ) {
539 widget.$input.attr( 'aria-invalid', 'true' );
540 } else {
541 widget.$input.removeAttr( 'aria-invalid' );
542 }
543 widget.setFlags( { invalid: !valid } );
544 };
545
546 if ( isValid !== undefined ) {
547 setFlag( isValid );
548 } else {
549 this.getValidity().then( function () {
550 setFlag( true );
551 }, function () {
552 setFlag( false );
553 } );
554 }
555 };
556
557 }( jQuery, mediaWiki ) );