2 * MediaWiki Widgets – DateInputWidget class.
4 * @copyright 2011-2015 MediaWiki Widgets Team and others; see AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
11 * Creates an mw.widgets.DateInputWidget object.
14 * // Date input widget showcase
15 * var fieldset = new OO.ui.FieldsetLayout( {
17 * new OO.ui.FieldLayout(
18 * new mw.widgets.DateInputWidget(),
21 * label: 'Select date'
24 * new OO.ui.FieldLayout(
25 * new mw.widgets.DateInputWidget( { precision: 'month' } ),
28 * label: 'Select month'
31 * new OO.ui.FieldLayout(
32 * new mw.widgets.DateInputWidget( {
33 * inputFormat: 'DD.MM.YYYY',
34 * displayFormat: 'Do [of] MMMM [anno Domini] YYYY'
38 * label: 'Select date (custom formats)'
43 * $( 'body' ).append( fieldset.$element );
45 * The value is stored in 'YYYY-MM-DD' or 'YYYY-MM' format:
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)' ) );
59 * @extends OO.ui.TextInputWidget
60 * @mixins OO.ui.mixin.IndicatorElement
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
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.
91 mw.widgets.DateInputWidget = function MWWDateInputWidget( config ) {
92 var placeholderDateFormat, mustBeAfter, mustBeBefore;
94 // Config initialization
97 longDisplayFormat: false,
99 placeholderLabel: mw.msg( 'mw-widgets-dateinput-no-date' )
101 if ( config.required ) {
102 if ( config.indicator === undefined ) {
103 config.indicator = 'required';
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 = '';
113 // Messages: mw-widgets-dateinput-placeholder-day, mw-widgets-dateinput-placeholder-month
114 placeholderDateFormat = mw.msg( 'mw-widgets-dateinput-placeholder-' + config.precision );
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 )
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
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
141 if ( config.mustBeAfter !== undefined ) {
142 mustBeAfter = moment( config.mustBeAfter, 'YYYY-MM-DD' );
143 if ( mustBeAfter.isValid() ) {
144 this.mustBeAfter = mustBeAfter;
147 if ( config.mustBeBefore !== undefined ) {
148 mustBeBefore = moment( config.mustBeBefore, 'YYYY-MM-DD' );
149 if ( mustBeBefore.isValid() ) {
150 this.mustBeBefore = mustBeBefore;
153 // Parent constructor
154 mw.widgets.DateInputWidget.parent.call( this, config );
156 // Mixin constructors
157 OO.ui.mixin.IndicatorElement.call( this, config );
160 this.calendar.connect( this, {
161 change: 'onCalendarChange'
163 this.textInput.connect( this, {
165 change: 'onTextInputChange'
168 focusout: this.onBlur.bind( this )
170 this.calendar.$element.on( {
171 click: this.onCalendarClick.bind( this ),
172 keypress: this.onCalendarKeyPress.bind( this )
175 click: this.onClick.bind( this ),
176 keypress: this.onKeyPress.bind( this ),
177 focus: this.onFocus.bind( this )
181 // Move 'tabindex' from this.$input (which is invisible) to the visible handle
182 this.setTabIndexedElement( 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' );
189 .addClass( 'mw-widget-dateInputWidget' )
190 .append( this.$handle, this.textInput.$element, this.calendar.$element );
192 // config.overlay is the selector to be used for config.$overlay, specified from PHP
193 if ( config.overlay ) {
194 config.$overlay = $( config.overlay );
197 if ( config.$overlay ) {
198 this.calendar.setFloatableContainer( this.$element );
199 config.$overlay.append( this.calendar.$element );
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 ) {
205 // Tabbing backward from text input: normal browser behavior
208 // Tabbing forward from text input: just focus the calendar
209 this.calendar.$element.focus();
214 this.calendar.$element.on( 'keydown', function ( e ) {
215 if ( e.which === OO.ui.Keys.TAB ) {
217 // Tabbing backward from calendar: just focus the text input
218 this.textInput.$input.focus();
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();
229 // Set handle label and hide stuff
231 this.textInput.toggle( false );
232 this.calendar.toggle( false );
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' );
243 OO.inheritClass( mw.widgets.DateInputWidget, OO.ui.TextInputWidget );
244 OO.mixinClass( mw.widgets.DateInputWidget, OO.ui.mixin.IndicatorElement );
249 * Fired when the widget is deactivated (i.e. the calendar is closed). This can happen because
250 * the user selected a value, or because the user blurred the widget.
253 * @param {boolean} userSelected Whether the deactivation happened because the user selected a value
262 mw.widgets.DateInputWidget.prototype.getInputElement = function () {
263 return $( '<input>' ).attr( 'type', 'hidden' );
267 * Respond to calendar date change events.
271 mw.widgets.DateInputWidget.prototype.onCalendarChange = function () {
273 if ( !this.inTextInput ) {
274 // If this is caused by user typing in the input field, do not set anything.
275 // The value may be invalid (see #onTextInputChange), but displayable on the calendar.
276 this.setValue( this.calendar.getDate() );
282 * Respond to text input value change events.
286 mw.widgets.DateInputWidget.prototype.onTextInputChange = function () {
289 value = this.textInput.getValue(),
290 valid = this.isValidDate( value );
293 if ( value === '' ) {
295 widget.setValue( '' );
296 } else if ( valid ) {
297 // Well-formed date value, parse and set it
298 mom = moment( value, widget.getInputFormat() );
299 // Use English locale to avoid number formatting
300 widget.setValue( mom.locale( 'en' ).format( widget.getInternalFormat() ) );
302 // Not well-formed, but possibly partial? Try updating the calendar, but do not set the
303 // internal value. Generally this only makes sense when 'inputFormat' is little-endian (e.g.
304 // 'YYYY-MM-DD'), but that's hard to check for, and might be difficult to handle the parsing
305 // right for weird formats. So limit this trick to only when we're using the default
306 // 'inputFormat', which is the same as the internal format, 'YYYY-MM-DD'.
307 if ( widget.getInputFormat() === widget.getInternalFormat() ) {
308 widget.calendar.setDate( widget.textInput.getValue() );
311 widget.inTextInput--;
318 mw.widgets.DateInputWidget.prototype.setValue = function ( value ) {
319 var oldValue = this.value;
321 if ( !moment( value, this.getInternalFormat() ).isValid() ) {
325 mw.widgets.DateInputWidget.parent.prototype.setValue.call( this, value );
327 if ( this.value !== oldValue ) {
329 this.setValidityFlag();
336 * Handle text input and calendar blur events.
340 mw.widgets.DateInputWidget.prototype.onBlur = function () {
342 setTimeout( function () {
343 var $focussed = $( ':focus' );
344 // Deactivate unless the focus moved to something else inside this widget
346 !OO.ui.contains( widget.$element[ 0 ], $focussed[ 0 ], true ) &&
347 // Calendar might be in an $overlay
348 !OO.ui.contains( widget.calendar.$element[ 0 ], $focussed[ 0 ], true )
358 mw.widgets.DateInputWidget.prototype.focus = function () {
366 mw.widgets.DateInputWidget.prototype.blur = function () {
372 * Update the contents of the label, text input and status of calendar to reflect selected value.
376 mw.widgets.DateInputWidget.prototype.updateUI = function () {
378 if ( this.getValue() === '' ) {
379 this.textInput.setValue( '' );
380 this.calendar.setDate( null );
381 this.innerLabel.setLabel( this.placeholderLabel );
382 this.$element.addClass( 'mw-widget-dateInputWidget-empty' );
384 moment = this.getMoment();
385 if ( !this.inTextInput ) {
386 this.textInput.setValue( moment.format( this.getInputFormat() ) );
388 if ( !this.inCalendar ) {
389 this.calendar.setDate( this.getValue() );
391 this.innerLabel.setLabel( moment.format( this.getDisplayFormat() ) );
392 this.$element.removeClass( 'mw-widget-dateInputWidget-empty' );
397 * Deactivate this input field for data entry. Closes the calendar and hides the text field.
400 * @param {boolean} [userSelected] Whether we are deactivating because the user selected a value
402 mw.widgets.DateInputWidget.prototype.deactivate = function ( userSelected ) {
403 this.$element.removeClass( 'mw-widget-dateInputWidget-active' );
405 this.textInput.toggle( false );
406 this.calendar.toggle( false );
407 this.setValidityFlag();
409 if ( userSelected ) {
410 // Prevent focusing the handle from reopening the calendar
412 this.$handle.focus();
413 this.closing = false;
416 this.emit( 'deactivate', !!userSelected );
420 * Activate this input field for data entry. Opens the calendar and shows the text field.
424 mw.widgets.DateInputWidget.prototype.activate = function () {
425 this.calendar.resetUI();
426 this.$element.addClass( 'mw-widget-dateInputWidget-active' );
428 this.textInput.toggle( true );
429 this.calendar.toggle( true );
431 this.textInput.$input.focus();
435 * Get the date format to be used for handle label when the input is inactive.
438 * @return {string} Format string
440 mw.widgets.DateInputWidget.prototype.getDisplayFormat = function () {
441 var localeData, llll, lll, ll, format;
443 if ( this.displayFormat !== undefined ) {
444 return this.displayFormat;
447 if ( this.calendar.getPrecision() === 'month' ) {
450 // The formats Moment.js provides:
451 // * ll: Month name, day of month, year
452 // * lll: Month name, day of month, year, time
453 // * llll: Month name, day of month, day of week, year, time
455 // The format we want:
456 // * ????: Month name, day of month, day of week, year
458 // We try to construct it as 'llll - (lll - ll)' and hope for the best.
459 // This seems to work well for many languages (maybe even all?).
461 localeData = moment.localeData( moment.locale() );
462 llll = localeData.longDateFormat( 'llll' );
463 lll = localeData.longDateFormat( 'lll' );
464 ll = localeData.longDateFormat( 'll' );
465 format = llll.replace( lll.replace( ll, '' ), '' );
467 if ( this.longDisplayFormat ) {
468 format = format.replace( 'MMM', 'MMMM' ).replace( 'ddd', 'dddd' );
476 * Get the date format to be used for the text field when the input is active.
479 * @return {string} Format string
481 mw.widgets.DateInputWidget.prototype.getInputFormat = function () {
482 if ( this.inputFormat !== undefined ) {
483 return this.inputFormat;
489 }[ this.calendar.getPrecision() ];
493 * Get the date format to be used internally for the value. This is not configurable in any way,
494 * and always either 'YYYY-MM-DD' or 'YYYY-MM'.
497 * @return {string} Format string
499 mw.widgets.DateInputWidget.prototype.getInternalFormat = function () {
503 }[ this.calendar.getPrecision() ];
507 * Get the Moment object for current value.
509 * @return {Object} Moment object
511 mw.widgets.DateInputWidget.prototype.getMoment = function () {
512 return moment( this.getValue(), this.getInternalFormat() );
516 * Handle mouse click events.
519 * @param {jQuery.Event} e Mouse click event
520 * @return {boolean} False to cancel the default event
522 mw.widgets.DateInputWidget.prototype.onClick = function ( e ) {
523 if ( !this.isDisabled() && e.which === 1 ) {
530 * Handle key press events.
533 * @param {jQuery.Event} e Key press event
534 * @return {boolean} False to cancel the default event
536 mw.widgets.DateInputWidget.prototype.onKeyPress = function ( e ) {
537 if ( !this.isDisabled() &&
538 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
546 * Handle focus events.
550 mw.widgets.DateInputWidget.prototype.onFocus = function () {
551 if ( !this.closing ) {
557 * Handle calendar key press events.
560 * @param {jQuery.Event} e Key press event
561 * @return {boolean} False to cancel the default event
563 mw.widgets.DateInputWidget.prototype.onCalendarKeyPress = function ( e ) {
564 if ( !this.isDisabled() && e.which === OO.ui.Keys.ENTER ) {
565 this.deactivate( true );
571 * Handle calendar click events.
574 * @param {jQuery.Event} e Mouse click event
575 * @return {boolean} False to cancel the default event
577 mw.widgets.DateInputWidget.prototype.onCalendarClick = function ( e ) {
578 var targetClass = this.calendar.getPrecision() === 'month' ?
579 'mw-widget-calendarWidget-month' :
580 'mw-widget-calendarWidget-day';
582 !this.isDisabled() &&
584 $( e.target ).hasClass( targetClass )
586 this.deactivate( true );
592 * Handle text input enter events.
596 mw.widgets.DateInputWidget.prototype.onEnter = function () {
597 this.deactivate( true );
602 * @param {string} date Date string, to be valid, must be in 'YYYY-MM-DD' or 'YYYY-MM' format or
603 * (unless the field is required) empty
606 mw.widgets.DateInputWidget.prototype.validateDate = function ( date ) {
609 isValid = !this.required;
611 isValid = this.isValidDate( date ) && this.isInRange( date );
618 * @param {string} date Date string, to be valid, must be in 'YYYY-MM-DD' or 'YYYY-MM' format
621 mw.widgets.DateInputWidget.prototype.isValidDate = function ( date ) {
622 // "Half-strict mode": for example, for the format 'YYYY-MM-DD', 2015-1-3 instead of 2015-01-03
623 // is okay, but 2015-01 isn't, and neither is 2015-01-foo. Use Moment's "fuzzy" mode and check
624 // parsing flags for the details (stolen from implementation of moment#isValid).
626 mom = moment( date, this.getInputFormat() ),
627 flags = mom.parsingFlags();
629 return mom.isValid() && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0;
633 * Validates if the date is within the range configured with {@link #cfg-mustBeAfter}
634 * and {@link #cfg-mustBeBefore}.
637 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
638 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
641 mw.widgets.DateInputWidget.prototype.isInRange = function ( date ) {
642 var momentDate, isAfter, isBefore;
643 if ( this.mustBeAfter === undefined && this.mustBeBefore === undefined ) {
646 momentDate = moment( date, 'YYYY-MM-DD' );
647 isAfter = ( this.mustBeAfter === undefined || momentDate.isAfter( this.mustBeAfter ) );
648 isBefore = ( this.mustBeBefore === undefined || momentDate.isBefore( this.mustBeBefore ) );
649 return isAfter && isBefore;
653 * Get the validity of current value.
655 * This method returns a promise that resolves if the value is valid and rejects if
656 * it isn't. Uses {@link #validateDate}.
658 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
660 mw.widgets.DateInputWidget.prototype.getValidity = function () {
661 var isValid = this.validateDate( this.getValue() );
664 return $.Deferred().resolve().promise();
666 return $.Deferred().reject().promise();
671 * Sets the 'invalid' flag appropriately.
673 * @param {boolean} [isValid] Optionally override validation result
675 mw.widgets.DateInputWidget.prototype.setValidityFlag = function ( isValid ) {
677 setFlag = function ( valid ) {
679 widget.$input.attr( 'aria-invalid', 'true' );
681 widget.$input.removeAttr( 'aria-invalid' );
683 widget.setFlags( { invalid: !valid } );
686 if ( isValid !== undefined ) {
689 this.getValidity().then( function () {
697 }( jQuery, mediaWiki ) );