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.InputWidget
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 {string} [placeholder] User-visible date format string displayed in the textual input
76 * field when it's empty. Should be the same as `inputFormat`, but translated to the user's
77 * language. When not given, defaults to a translated version of 'YYYY-MM-DD' or 'YYYY-MM',
78 * depending on `precision`.
79 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
80 * @cfg {string} [mustBeAfter] Validates the date to be after this. In the 'YYYY-MM-DD' format.
81 * @cfg {string} [mustBeBefore] Validates the date to be before this. In the 'YYYY-MM-DD' format.
82 * @cfg {jQuery} [$overlay] Render the calendar into a separate layer. This configuration is
83 * useful in cases where the expanded calendar is larger than its container. The specified
84 * overlay layer is usually on top of the container and has a larger area. By default, the
85 * calendar uses relative positioning.
87 mw.widgets.DateInputWidget = function MWWDateInputWidget( config ) {
88 // Config initialization
89 config = $.extend( { precision: 'day', required: false }, config );
90 if ( config.required ) {
91 if ( config.indicator === undefined ) {
92 config.indicator = 'required';
96 var placeholder, mustBeAfter, mustBeBefore;
97 if ( config.placeholder ) {
98 placeholder = config.placeholder;
99 } else if ( config.inputFormat ) {
100 // We have no way to display a translated placeholder for custom formats
103 // Messages: mw-widgets-dateinput-placeholder-day, mw-widgets-dateinput-placeholder-month
104 placeholder = mw.msg( 'mw-widgets-dateinput-placeholder-' + config.precision );
107 // Properties (must be set before parent constructor, which calls #setValue)
108 this.$handle = $( '<div>' );
109 this.label = new OO.ui.LabelWidget();
110 this.textInput = new OO.ui.TextInputWidget( {
111 required: config.required,
112 placeholder: placeholder,
113 validate: this.validateDate.bind( this )
115 this.calendar = new mw.widgets.CalendarWidget( {
116 // Can't pass `$floatableContainer: this.$element` here, the latter is not set yet.
117 // Instead we call setFloatableContainer() below.
118 precision: config.precision
121 this.inTextInput = 0;
122 this.inputFormat = config.inputFormat;
123 this.displayFormat = config.displayFormat;
124 this.required = config.required;
126 // Validate and set min and max dates as properties
127 mustBeAfter = moment( config.mustBeAfter, 'YYYY-MM-DD' );
128 mustBeBefore = moment( config.mustBeBefore, 'YYYY-MM-DD' );
130 config.mustBeAfter !== undefined &&
131 mustBeAfter.isValid()
133 this.mustBeAfter = mustBeAfter;
137 config.mustBeBefore !== undefined &&
138 mustBeBefore.isValid()
140 this.mustBeBefore = mustBeBefore;
143 // Parent constructor
144 mw.widgets.DateInputWidget.parent.call( this, config );
146 // Mixin constructors
147 OO.ui.mixin.IndicatorElement.call( this, config );
150 this.calendar.connect( this, {
151 change: 'onCalendarChange'
153 this.textInput.connect( this, {
155 change: 'onTextInputChange'
158 focusout: this.onBlur.bind( this )
160 this.calendar.$element.on( {
161 click: this.onCalendarClick.bind( this ),
162 keypress: this.onCalendarKeyPress.bind( this )
165 click: this.onClick.bind( this ),
166 keypress: this.onKeyPress.bind( this )
170 // Move 'tabindex' from this.$input (which is invisible) to the visible handle
171 this.setTabIndexedElement( this.$handle );
173 .append( this.label.$element, this.$indicator )
174 .addClass( 'mw-widget-dateInputWidget-handle' );
175 this.calendar.$element
176 .addClass( 'mw-widget-dateInputWidget-calendar' );
178 .addClass( 'mw-widget-dateInputWidget' )
179 .append( this.$handle, this.textInput.$element, this.calendar.$element );
181 if ( config.$overlay ) {
182 this.calendar.setFloatableContainer( this.$element );
183 config.$overlay.append( this.calendar.$element );
185 // The text input and calendar are not in DOM order, so fix up focus transitions.
186 this.textInput.$input.on( 'keydown', function ( e ) {
187 if ( e.which === OO.ui.Keys.TAB ) {
189 // Tabbing backward from text input: normal browser behavior
192 // Tabbing forward from text input: just focus the calendar
193 this.calendar.$element.focus();
198 this.calendar.$element.on( 'keydown', function ( e ) {
199 if ( e.which === OO.ui.Keys.TAB ) {
201 // Tabbing backward from calendar: just focus the text input
202 this.textInput.$input.focus();
205 // Tabbing forward from calendar: focus the text input, then allow normal browser
206 // behavior to move focus to next focusable after it
207 this.textInput.$input.focus();
213 // Set handle label and hide stuff
215 this.textInput.toggle( false );
216 this.calendar.toggle( false );
221 OO.inheritClass( mw.widgets.DateInputWidget, OO.ui.InputWidget );
222 OO.mixinClass( mw.widgets.DateInputWidget, OO.ui.mixin.IndicatorElement );
230 mw.widgets.DateInputWidget.prototype.getInputElement = function () {
231 return $( '<input type="hidden">' );
235 * Respond to calendar date change events.
239 mw.widgets.DateInputWidget.prototype.onCalendarChange = function () {
241 if ( !this.inTextInput ) {
242 // If this is caused by user typing in the input field, do not set anything.
243 // The value may be invalid (see #onTextInputChange), but displayable on the calendar.
244 this.setValue( this.calendar.getDate() );
250 * Respond to text input value change events.
254 mw.widgets.DateInputWidget.prototype.onTextInputChange = function () {
257 value = this.textInput.getValue(),
258 valid = this.isValidDate( value );
261 if ( value === '' ) {
263 widget.setValue( '' );
264 } else if ( valid ) {
265 // Well-formed date value, parse and set it
266 mom = moment( value, widget.getInputFormat() );
267 // Use English locale to avoid number formatting
268 widget.setValue( mom.locale( 'en' ).format( widget.getInternalFormat() ) );
270 // Not well-formed, but possibly partial? Try updating the calendar, but do not set the
271 // internal value. Generally this only makes sense when 'inputFormat' is little-endian (e.g.
272 // 'YYYY-MM-DD'), but that's hard to check for, and might be difficult to handle the parsing
273 // right for weird formats. So limit this trick to only when we're using the default
274 // 'inputFormat', which is the same as the internal format, 'YYYY-MM-DD'.
275 if ( widget.getInputFormat() === widget.getInternalFormat() ) {
276 widget.calendar.setDate( widget.textInput.getValue() );
279 widget.inTextInput--;
286 mw.widgets.DateInputWidget.prototype.setValue = function ( value ) {
287 var oldValue = this.value;
289 if ( !moment( value, this.getInternalFormat() ).isValid() ) {
293 mw.widgets.DateInputWidget.parent.prototype.setValue.call( this, value );
295 if ( this.value !== oldValue ) {
297 this.setValidityFlag();
304 * Handle text input and calendar blur events.
308 mw.widgets.DateInputWidget.prototype.onBlur = function () {
310 setTimeout( function () {
311 var $focussed = $( ':focus' );
312 // Deactivate unless the focus moved to something else inside this widget
314 !OO.ui.contains( widget.$element[ 0 ], $focussed[ 0 ], true ) &&
315 // Calendar might be in an $overlay
316 !OO.ui.contains( widget.calendar.$element[ 0 ], $focussed[ 0 ], true )
326 mw.widgets.DateInputWidget.prototype.focus = function () {
334 mw.widgets.DateInputWidget.prototype.blur = function () {
340 * Update the contents of the label, text input and status of calendar to reflect selected value.
344 mw.widgets.DateInputWidget.prototype.updateUI = function () {
345 if ( this.getValue() === '' ) {
346 this.textInput.setValue( '' );
347 this.calendar.setDate( null );
348 this.label.setLabel( mw.msg( 'mw-widgets-dateinput-no-date' ) );
349 this.$element.addClass( 'mw-widget-dateInputWidget-empty' );
351 if ( !this.inTextInput ) {
352 this.textInput.setValue( this.getMoment().format( this.getInputFormat() ) );
354 if ( !this.inCalendar ) {
355 this.calendar.setDate( this.getValue() );
357 this.label.setLabel( this.getMoment().format( this.getDisplayFormat() ) );
358 this.$element.removeClass( 'mw-widget-dateInputWidget-empty' );
363 * Deactivate this input field for data entry. Closes the calendar and hides the text field.
367 mw.widgets.DateInputWidget.prototype.deactivate = function () {
368 this.$element.removeClass( 'mw-widget-dateInputWidget-active' );
370 this.textInput.toggle( false );
371 this.calendar.toggle( false );
372 this.setValidityFlag();
376 * Activate this input field for data entry. Opens the calendar and shows the text field.
380 mw.widgets.DateInputWidget.prototype.activate = function () {
381 this.calendar.resetUI();
382 this.$element.addClass( 'mw-widget-dateInputWidget-active' );
384 this.textInput.toggle( true );
385 this.calendar.toggle( true );
387 this.textInput.$input.focus();
391 * Get the date format to be used for handle label when the input is inactive.
394 * @return {string} Format string
396 mw.widgets.DateInputWidget.prototype.getDisplayFormat = function () {
397 if ( this.displayFormat !== undefined ) {
398 return this.displayFormat;
401 if ( this.calendar.getPrecision() === 'month' ) {
404 // The formats Moment.js provides:
405 // * ll: Month name, day of month, year
406 // * lll: Month name, day of month, year, time
407 // * llll: Month name, day of month, day of week, year, time
409 // The format we want:
410 // * ????: Month name, day of month, day of week, year
412 // We try to construct it as 'llll - (lll - ll)' and hope for the best.
413 // This seems to work well for many languages (maybe even all?).
415 var localeData = moment.localeData( moment.locale() ),
416 llll = localeData.longDateFormat( 'llll' ),
417 lll = localeData.longDateFormat( 'lll' ),
418 ll = localeData.longDateFormat( 'll' ),
419 format = llll.replace( lll.replace( ll, '' ), '' );
426 * Get the date format to be used for the text field when the input is active.
429 * @return {string} Format string
431 mw.widgets.DateInputWidget.prototype.getInputFormat = function () {
432 if ( this.inputFormat !== undefined ) {
433 return this.inputFormat;
439 }[ this.calendar.getPrecision() ];
443 * Get the date format to be used internally for the value. This is not configurable in any way,
444 * and always either 'YYYY-MM-DD' or 'YYYY-MM'.
447 * @return {string} Format string
449 mw.widgets.DateInputWidget.prototype.getInternalFormat = function () {
453 }[ this.calendar.getPrecision() ];
457 * Get the Moment object for current value.
459 * @return {Object} Moment object
461 mw.widgets.DateInputWidget.prototype.getMoment = function () {
462 return moment( this.getValue(), this.getInternalFormat() );
466 * Handle mouse click events.
469 * @param {jQuery.Event} e Mouse click event
471 mw.widgets.DateInputWidget.prototype.onClick = function ( e ) {
472 if ( !this.isDisabled() && e.which === 1 ) {
479 * Handle key press events.
482 * @param {jQuery.Event} e Key press event
484 mw.widgets.DateInputWidget.prototype.onKeyPress = function ( e ) {
485 if ( !this.isDisabled() &&
486 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
494 * Handle calendar key press events.
497 * @param {jQuery.Event} e Key press event
499 mw.widgets.DateInputWidget.prototype.onCalendarKeyPress = function ( e ) {
500 if ( !this.isDisabled() && e.which === OO.ui.Keys.ENTER ) {
502 this.$handle.focus();
508 * Handle calendar click events.
511 * @param {jQuery.Event} e Mouse click event
513 mw.widgets.DateInputWidget.prototype.onCalendarClick = function ( e ) {
515 !this.isDisabled() &&
517 $( e.target ).hasClass( 'mw-widget-calendarWidget-day' )
520 this.$handle.focus();
526 * Handle text input enter events.
530 mw.widgets.DateInputWidget.prototype.onEnter = function () {
532 this.$handle.focus();
537 * @param {string} date Date string, to be valid, must be in 'YYYY-MM-DD' or 'YYYY-MM' format or
538 * (unless the field is required) empty
541 mw.widgets.DateInputWidget.prototype.validateDate = function ( date ) {
544 isValid = !this.required;
546 isValid = this.isValidDate( date ) && this.isInRange( date );
553 * @param {string} date Date string, to be valid, must be in 'YYYY-MM-DD' or 'YYYY-MM' format
556 mw.widgets.DateInputWidget.prototype.isValidDate = function ( date ) {
557 // "Half-strict mode": for example, for the format 'YYYY-MM-DD', 2015-1-3 instead of 2015-01-03
558 // is okay, but 2015-01 isn't, and neither is 2015-01-foo. Use Moment's "fuzzy" mode and check
559 // parsing flags for the details (stoled from implementation of moment#isValid).
561 mom = moment( date, this.getInputFormat() ),
562 flags = mom.parsingFlags();
564 return mom.isValid() && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0;
568 * Validates if the date is within the range configured with {@link #cfg-mustBeAfter}
569 * and {@link #cfg-mustBeBefore}.
572 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
573 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
576 mw.widgets.DateInputWidget.prototype.isInRange = function ( date ) {
577 var momentDate = moment( date, 'YYYY-MM-DD' ),
578 isAfter = ( this.mustBeAfter === undefined || momentDate.isAfter( this.mustBeAfter ) ),
579 isBefore = ( this.mustBeBefore === undefined || momentDate.isBefore( this.mustBeBefore ) );
581 return isAfter && isBefore;
585 * Get the validity of current value.
587 * This method returns a promise that resolves if the value is valid and rejects if
588 * it isn't. Uses {@link #validateDate}.
590 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
592 mw.widgets.DateInputWidget.prototype.getValidity = function () {
593 var isValid = this.validateDate( this.getValue() );
596 return $.Deferred().resolve().promise();
598 return $.Deferred().reject().promise();
603 * Sets the 'invalid' flag appropriately.
605 * @param {boolean} [isValid] Optionally override validation result
607 mw.widgets.DateInputWidget.prototype.setValidityFlag = function ( isValid ) {
609 setFlag = function ( valid ) {
611 widget.$input.attr( 'aria-invalid', 'true' );
613 widget.$input.removeAttr( 'aria-invalid' );
615 widget.setFlags( { invalid: !valid } );
618 if ( isValid !== undefined ) {
621 this.getValidity().then( function () {
629 }( jQuery, mediaWiki ) );