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
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
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 * @cfg {jQuery} [$overlay] Render the calendar into a separate layer. This configuration is
82 * useful in cases where the expanded calendar is larger than its container. The specified
83 * overlay layer is usually on top of the container and has a larger area. By default, the
84 * calendar uses relative positioning.
86 mw
.widgets
.DateInputWidget
= function MWWDateInputWidget( config
) {
87 // Config initialization
88 config
= $.extend( { precision
: 'day' }, config
);
89 if ( config
.required
) {
90 if ( config
.indicator
=== undefined ) {
91 config
.indicator
= 'required';
95 var placeholder
, mustBeAfter
, mustBeBefore
;
96 if ( config
.placeholder
) {
97 placeholder
= config
.placeholder
;
98 } else if ( config
.inputFormat
) {
99 // We have no way to display a translated placeholder for custom formats
102 // Messages: mw-widgets-dateinput-placeholder-day, mw-widgets-dateinput-placeholder-month
103 placeholder
= mw
.msg( 'mw-widgets-dateinput-placeholder-' + config
.precision
);
106 // Properties (must be set before parent constructor, which calls #setValue)
107 this.handle
= new OO
.ui
.LabelWidget();
108 this.textInput
= new OO
.ui
.TextInputWidget( {
109 placeholder
: placeholder
,
110 validate
: this.validateDate
.bind( this )
112 this.calendar
= new mw
.widgets
.CalendarWidget( {
113 // Can't pass `$floatableContainer: this.$element` here, the latter is not set yet.
114 // Instead we call setFloatableContainer() below.
115 precision
: config
.precision
118 this.inTextInput
= 0;
119 this.inputFormat
= config
.inputFormat
;
120 this.displayFormat
= config
.displayFormat
;
122 // Validate and set min and max dates as properties
123 mustBeAfter
= moment( config
.mustBeAfter
, 'YYYY-MM-DD' );
124 mustBeBefore
= moment( config
.mustBeBefore
, 'YYYY-MM-DD' );
126 config
.mustBeAfter
!== undefined &&
127 mustBeAfter
.isValid()
129 this.mustBeAfter
= mustBeAfter
;
133 config
.mustBeBefore
!== undefined &&
134 mustBeBefore
.isValid()
136 this.mustBeBefore
= mustBeBefore
;
139 // Parent constructor
140 mw
.widgets
.DateInputWidget
.parent
.call( this, config
);
143 this.calendar
.connect( this, {
144 change
: 'onCalendarChange'
146 this.textInput
.connect( this, {
148 change
: 'onTextInputChange'
151 focusout
: this.onBlur
.bind( this )
153 this.calendar
.$element
.on( {
154 keypress
: this.onCalendarKeyPress
.bind( this )
156 this.handle
.$element
.on( {
157 click
: this.onClick
.bind( this ),
158 keypress
: this.onKeyPress
.bind( this )
162 if ( config
.required
) {
163 this.$input
.attr( 'required', 'required' );
164 this.$input
.attr( 'aria-required', 'true' );
166 // Move 'tabindex' from this.$input (which is invisible) to the visible handle
167 this.setTabIndexedElement( this.handle
.$element
);
169 .addClass( 'mw-widget-dateInputWidget-handle' );
170 this.calendar
.$element
171 .addClass( 'mw-widget-dateInputWidget-calendar' );
173 .addClass( 'mw-widget-dateInputWidget' )
174 .append( this.handle
.$element
, this.textInput
.$element
, this.calendar
.$element
);
176 if ( config
.$overlay
) {
177 this.calendar
.setFloatableContainer( this.$element
);
178 config
.$overlay
.append( this.calendar
.$element
);
180 // The text input and calendar are not in DOM order, so fix up focus transitions.
181 this.textInput
.$input
.on( 'keydown', function ( e
) {
182 if ( e
.which
=== OO
.ui
.Keys
.TAB
) {
184 // Tabbing backward from text input: normal browser behavior
187 // Tabbing forward from text input: just focus the calendar
188 this.calendar
.$element
.focus();
193 this.calendar
.$element
.on( 'keydown', function ( e
) {
194 if ( e
.which
=== OO
.ui
.Keys
.TAB
) {
196 // Tabbing backward from calendar: just focus the text input
197 this.textInput
.$input
.focus();
200 // Tabbing forward from calendar: focus the text input, then allow normal browser
201 // behavior to move focus to next focusable after it
202 this.textInput
.$input
.focus();
208 // Set handle label and hide stuff
215 OO
.inheritClass( mw
.widgets
.DateInputWidget
, OO
.ui
.InputWidget
);
223 mw
.widgets
.DateInputWidget
.prototype.getInputElement = function () {
224 return $( '<input type="hidden">' );
228 * Respond to calendar date change events.
232 mw
.widgets
.DateInputWidget
.prototype.onCalendarChange = function () {
234 if ( !this.inTextInput
) {
235 // If this is caused by user typing in the input field, do not set anything.
236 // The value may be invalid (see #onTextInputChange), but displayable on the calendar.
237 this.setValue( this.calendar
.getDate() );
243 * Respond to text input value change events.
247 mw
.widgets
.DateInputWidget
.prototype.onTextInputChange = function () {
250 value
= this.textInput
.getValue(),
251 valid
= this.isValidDate( value
);
254 if ( value
=== '' ) {
256 widget
.setValue( '' );
257 } else if ( valid
) {
258 // Well-formed date value, parse and set it
259 mom
= moment( value
, widget
.getInputFormat() );
260 // Use English locale to avoid number formatting
261 widget
.setValue( mom
.locale( 'en' ).format( widget
.getInternalFormat() ) );
263 // Not well-formed, but possibly partial? Try updating the calendar, but do not set the
264 // internal value. Generally this only makes sense when 'inputFormat' is little-endian (e.g.
265 // 'YYYY-MM-DD'), but that's hard to check for, and might be difficult to handle the parsing
266 // right for weird formats. So limit this trick to only when we're using the default
267 // 'inputFormat', which is the same as the internal format, 'YYYY-MM-DD'.
268 if ( widget
.getInputFormat() === widget
.getInternalFormat() ) {
269 widget
.calendar
.setDate( widget
.textInput
.getValue() );
272 widget
.inTextInput
--;
279 mw
.widgets
.DateInputWidget
.prototype.setValue = function ( value
) {
280 var oldValue
= this.value
;
282 if ( !moment( value
, this.getInternalFormat() ).isValid() ) {
286 mw
.widgets
.DateInputWidget
.parent
.prototype.setValue
.call( this, value
);
288 if ( this.value
!== oldValue
) {
296 * Handle text input and calendar blur events.
300 mw
.widgets
.DateInputWidget
.prototype.onBlur = function () {
302 setTimeout( function () {
303 var $focussed
= $( ':focus' );
304 // Deactivate unless the focus moved to something else inside this widget
306 !OO
.ui
.contains( widget
.$element
[ 0 ], $focussed
[ 0 ], true ) &&
307 // Calendar might be in an $overlay
308 !OO
.ui
.contains( widget
.calendar
.$element
[ 0 ], $focussed
[ 0 ], true )
318 mw
.widgets
.DateInputWidget
.prototype.focus = function () {
326 mw
.widgets
.DateInputWidget
.prototype.blur = function () {
332 * Update the contents of the label, text input and status of calendar to reflect selected value.
336 mw
.widgets
.DateInputWidget
.prototype.updateUI = function () {
337 if ( this.getValue() === '' ) {
338 this.textInput
.setValue( '' );
339 this.calendar
.setDate( null );
340 this.handle
.setLabel( mw
.msg( 'mw-widgets-dateinput-no-date' ) );
341 this.$element
.addClass( 'mw-widget-dateInputWidget-empty' );
343 if ( !this.inTextInput
) {
344 this.textInput
.setValue( this.getMoment().format( this.getInputFormat() ) );
346 if ( !this.inCalendar
) {
347 this.calendar
.setDate( this.getValue() );
349 this.handle
.setLabel( this.getMoment().format( this.getDisplayFormat() ) );
350 this.$element
.removeClass( 'mw-widget-dateInputWidget-empty' );
355 * Deactivate this input field for data entry. Closes the calendar and hides the text field.
359 mw
.widgets
.DateInputWidget
.prototype.deactivate = function () {
360 this.$element
.removeClass( 'mw-widget-dateInputWidget-active' );
361 this.handle
.toggle( true );
362 this.textInput
.toggle( false );
363 this.calendar
.toggle( false );
367 * Activate this input field for data entry. Opens the calendar and shows the text field.
371 mw
.widgets
.DateInputWidget
.prototype.activate = function () {
372 this.calendar
.resetUI();
373 this.$element
.addClass( 'mw-widget-dateInputWidget-active' );
374 this.handle
.toggle( false );
375 this.textInput
.toggle( true );
376 this.calendar
.toggle( true );
378 this.textInput
.$input
.focus();
382 * Get the date format to be used for handle label when the input is inactive.
385 * @return {string} Format string
387 mw
.widgets
.DateInputWidget
.prototype.getDisplayFormat = function () {
388 if ( this.displayFormat
!== undefined ) {
389 return this.displayFormat
;
392 if ( this.calendar
.getPrecision() === 'month' ) {
395 // The formats Moment.js provides:
396 // * ll: Month name, day of month, year
397 // * lll: Month name, day of month, year, time
398 // * llll: Month name, day of month, day of week, year, time
400 // The format we want:
401 // * ????: Month name, day of month, day of week, year
403 // We try to construct it as 'llll - (lll - ll)' and hope for the best.
404 // This seems to work well for many languages (maybe even all?).
406 var localeData
= moment
.localeData( moment
.locale() ),
407 llll
= localeData
.longDateFormat( 'llll' ),
408 lll
= localeData
.longDateFormat( 'lll' ),
409 ll
= localeData
.longDateFormat( 'll' ),
410 format
= llll
.replace( lll
.replace( ll
, '' ), '' );
417 * Get the date format to be used for the text field when the input is active.
420 * @return {string} Format string
422 mw
.widgets
.DateInputWidget
.prototype.getInputFormat = function () {
423 if ( this.inputFormat
!== undefined ) {
424 return this.inputFormat
;
430 }[ this.calendar
.getPrecision() ];
434 * Get the date format to be used internally for the value. This is not configurable in any way,
435 * and always either 'YYYY-MM-DD' or 'YYYY-MM'.
438 * @return {string} Format string
440 mw
.widgets
.DateInputWidget
.prototype.getInternalFormat = function () {
444 }[ this.calendar
.getPrecision() ];
448 * Get the Moment object for current value.
450 * @return {Object} Moment object
452 mw
.widgets
.DateInputWidget
.prototype.getMoment = function () {
453 return moment( this.getValue(), this.getInternalFormat() );
457 * Handle mouse click events.
460 * @param {jQuery.Event} e Mouse click event
462 mw
.widgets
.DateInputWidget
.prototype.onClick = function ( e
) {
463 if ( !this.isDisabled() && e
.which
=== 1 ) {
470 * Handle key press events.
473 * @param {jQuery.Event} e Key press event
475 mw
.widgets
.DateInputWidget
.prototype.onKeyPress = function ( e
) {
476 if ( !this.isDisabled() &&
477 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
485 * Handle calendar key press events.
488 * @param {jQuery.Event} e Key press event
490 mw
.widgets
.DateInputWidget
.prototype.onCalendarKeyPress = function ( e
) {
491 if ( !this.isDisabled() && e
.which
=== OO
.ui
.Keys
.ENTER
) {
493 this.handle
.$element
.focus();
499 * Handle text input enter events.
503 mw
.widgets
.DateInputWidget
.prototype.onEnter = function () {
505 this.handle
.$element
.focus();
510 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
511 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
514 mw
.widgets
.DateInputWidget
.prototype.validateDate = function ( date
) {
519 var isValid
= this.isValidDate( date
) && this.isInRange( date
);
520 this.setValidityFlag( isValid
);
526 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
527 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
530 mw
.widgets
.DateInputWidget
.prototype.isValidDate = function ( date
) {
531 // "Half-strict mode": for example, for the format 'YYYY-MM-DD', 2015-1-3 instead of 2015-01-03
532 // is okay, but 2015-01 isn't, and neither is 2015-01-foo. Use Moment's "fuzzy" mode and check
533 // parsing flags for the details (stoled from implementation of #isValid).
535 mom
= moment( date
, this.getInputFormat() ),
536 flags
= mom
.parsingFlags();
538 return mom
.isValid() && flags
.charsLeftOver
=== 0 && flags
.unusedTokens
.length
=== 0;
542 * Validates if the date is within the range configured with {@link #cfg-mustBeAfter}
543 * and {@link #cfg-mustBeBefore}.
546 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
547 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
550 mw
.widgets
.DateInputWidget
.prototype.isInRange = function ( date
) {
551 var momentDate
= moment( date
, 'YYYY-MM-DD' ),
552 isAfter
= ( this.mustBeAfter
=== undefined || momentDate
.isAfter( this.mustBeAfter
) ),
553 isBefore
= ( this.mustBeBefore
=== undefined || momentDate
.isBefore( this.mustBeBefore
) );
555 return isAfter
&& isBefore
;
559 * Get the validity of current value.
561 * This method returns a promise that resolves if the value is valid and rejects if
562 * it isn't. Uses {@link #validateDate}.
564 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
566 mw
.widgets
.DateInputWidget
.prototype.getValidity = function () {
567 var isValid
= this.validateDate( this.getValue() );
570 return $.Deferred().resolve().promise();
572 return $.Deferred().reject().promise();
577 * Sets the 'invalid' flag appropriately.
579 * @param {boolean} [isValid] Optionally override validation result
581 mw
.widgets
.DateInputWidget
.prototype.setValidityFlag = function ( isValid
) {
583 setFlag = function ( valid
) {
585 widget
.$input
.attr( 'aria-invalid', 'true' );
587 widget
.$input
.removeAttr( 'aria-invalid' );
589 widget
.setFlags( { invalid
: !valid
} );
592 if ( isValid
!== undefined ) {
595 this.getValidity().then( function () {
603 }( jQuery
, mediaWiki
) );