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