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} [placeholderLabel=No date selected] Placeholder text shown when the widget is not
76 * selected. Default text taken from message `mw-widgets-dateinput-no-date`.
77 * @cfg {string} [placeholderDateFormat] User-visible date format string displayed in the textual input
78 * field when it's empty. Should be the same as `inputFormat`, but translated to the user's
79 * language. When not given, defaults to a translated version of 'YYYY-MM-DD' or 'YYYY-MM',
80 * depending on `precision`.
81 * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`.
82 * @cfg {string} [mustBeAfter] Validates the date to be after this. In the 'YYYY-MM-DD' format.
83 * @cfg {string} [mustBeBefore] Validates the date to be before this. In the 'YYYY-MM-DD' format.
84 * @cfg {jQuery} [$overlay] Render the calendar into a separate layer. This configuration is
85 * useful in cases where the expanded calendar is larger than its container. The specified
86 * overlay layer is usually on top of the container and has a larger area. By default, the
87 * calendar uses relative positioning.
89 mw
.widgets
.DateInputWidget
= function MWWDateInputWidget( config
) {
90 var placeholderDateFormat
, mustBeAfter
, mustBeBefore
;
92 // Config initialization
96 placeholderLabel
: mw
.msg( 'mw-widgets-dateinput-no-date' )
98 if ( config
.required
) {
99 if ( config
.indicator
=== undefined ) {
100 config
.indicator
= 'required';
104 if ( config
.placeholderDateFormat
) {
105 placeholderDateFormat
= config
.placeholderDateFormat
;
106 } else if ( config
.inputFormat
) {
107 // We have no way to display a translated placeholder for custom formats
108 placeholderDateFormat
= '';
110 // Messages: mw-widgets-dateinput-placeholder-day, mw-widgets-dateinput-placeholder-month
111 placeholderDateFormat
= mw
.msg( 'mw-widgets-dateinput-placeholder-' + config
.precision
);
114 // Properties (must be set before parent constructor, which calls #setValue)
115 this.$handle
= $( '<div>' );
116 this.label
= new OO
.ui
.LabelWidget();
117 this.textInput
= new OO
.ui
.TextInputWidget( {
118 required
: config
.required
,
119 placeholder
: placeholderDateFormat
,
120 validate
: this.validateDate
.bind( this )
122 this.calendar
= new mw
.widgets
.CalendarWidget( {
123 lazyInitOnToggle
: true,
124 // Can't pass `$floatableContainer: this.$element` here, the latter is not set yet.
125 // Instead we call setFloatableContainer() below.
126 precision
: config
.precision
129 this.inTextInput
= 0;
130 this.inputFormat
= config
.inputFormat
;
131 this.displayFormat
= config
.displayFormat
;
132 this.required
= config
.required
;
133 this.placeholderLabel
= config
.placeholderLabel
;
135 // Validate and set min and max dates as properties
136 if ( config
.mustBeAfter
!== undefined ) {
137 mustBeAfter
= moment( config
.mustBeAfter
, 'YYYY-MM-DD' );
138 if ( mustBeAfter
.isValid() ) {
139 this.mustBeAfter
= mustBeAfter
;
142 if ( config
.mustBeBefore
!== undefined ) {
143 mustBeBefore
= moment( config
.mustBeBefore
, 'YYYY-MM-DD' );
144 if ( mustBeBefore
.isValid() ) {
145 this.mustBeBefore
= mustBeBefore
;
149 // Parent constructor
150 mw
.widgets
.DateInputWidget
.parent
.call( this, config
);
152 // Mixin constructors
153 OO
.ui
.mixin
.IndicatorElement
.call( this, config
);
156 this.calendar
.connect( this, {
157 change
: 'onCalendarChange'
159 this.textInput
.connect( this, {
161 change
: 'onTextInputChange'
164 focusout
: this.onBlur
.bind( this )
166 this.calendar
.$element
.on( {
167 click
: this.onCalendarClick
.bind( this ),
168 keypress
: this.onCalendarKeyPress
.bind( this )
171 click
: this.onClick
.bind( this ),
172 keypress
: this.onKeyPress
.bind( this )
176 // Move 'tabindex' from this.$input (which is invisible) to the visible handle
177 this.setTabIndexedElement( this.$handle
);
179 .append( this.label
.$element
, this.$indicator
)
180 .addClass( 'mw-widget-dateInputWidget-handle' );
181 this.calendar
.$element
182 .addClass( 'mw-widget-dateInputWidget-calendar' );
184 .addClass( 'mw-widget-dateInputWidget' )
185 .append( this.$handle
, this.textInput
.$element
, this.calendar
.$element
);
187 // config.overlay is the selector to be used for config.$overlay, specified from PHP
188 if ( config
.overlay
) {
189 config
.$overlay
= $( config
.overlay
);
192 if ( config
.$overlay
) {
193 this.calendar
.setFloatableContainer( this.$element
);
194 config
.$overlay
.append( this.calendar
.$element
);
196 // The text input and calendar are not in DOM order, so fix up focus transitions.
197 this.textInput
.$input
.on( 'keydown', function ( e
) {
198 if ( e
.which
=== OO
.ui
.Keys
.TAB
) {
200 // Tabbing backward from text input: normal browser behavior
203 // Tabbing forward from text input: just focus the calendar
204 this.calendar
.$element
.focus();
209 this.calendar
.$element
.on( 'keydown', function ( e
) {
210 if ( e
.which
=== OO
.ui
.Keys
.TAB
) {
212 // Tabbing backward from calendar: just focus the text input
213 this.textInput
.$input
.focus();
216 // Tabbing forward from calendar: focus the text input, then allow normal browser
217 // behavior to move focus to next focusable after it
218 this.textInput
.$input
.focus();
224 // Set handle label and hide stuff
226 this.textInput
.toggle( false );
227 this.calendar
.toggle( false );
229 // Hide unused <input> from PHP after infusion is done
230 // See InputWidget#reusePreInfuseDOM about config.$input
231 if ( config
.$input
) {
232 config
.$input
.addClass( 'oo-ui-element-hidden' );
238 OO
.inheritClass( mw
.widgets
.DateInputWidget
, OO
.ui
.InputWidget
);
239 OO
.mixinClass( mw
.widgets
.DateInputWidget
, OO
.ui
.mixin
.IndicatorElement
);
247 mw
.widgets
.DateInputWidget
.prototype.getInputElement = function () {
248 return $( '<input>' ).attr( 'type', 'hidden' );
252 * Respond to calendar date change events.
256 mw
.widgets
.DateInputWidget
.prototype.onCalendarChange = function () {
258 if ( !this.inTextInput
) {
259 // If this is caused by user typing in the input field, do not set anything.
260 // The value may be invalid (see #onTextInputChange), but displayable on the calendar.
261 this.setValue( this.calendar
.getDate() );
267 * Respond to text input value change events.
271 mw
.widgets
.DateInputWidget
.prototype.onTextInputChange = function () {
274 value
= this.textInput
.getValue(),
275 valid
= this.isValidDate( value
);
278 if ( value
=== '' ) {
280 widget
.setValue( '' );
281 } else if ( valid
) {
282 // Well-formed date value, parse and set it
283 mom
= moment( value
, widget
.getInputFormat() );
284 // Use English locale to avoid number formatting
285 widget
.setValue( mom
.locale( 'en' ).format( widget
.getInternalFormat() ) );
287 // Not well-formed, but possibly partial? Try updating the calendar, but do not set the
288 // internal value. Generally this only makes sense when 'inputFormat' is little-endian (e.g.
289 // 'YYYY-MM-DD'), but that's hard to check for, and might be difficult to handle the parsing
290 // right for weird formats. So limit this trick to only when we're using the default
291 // 'inputFormat', which is the same as the internal format, 'YYYY-MM-DD'.
292 if ( widget
.getInputFormat() === widget
.getInternalFormat() ) {
293 widget
.calendar
.setDate( widget
.textInput
.getValue() );
296 widget
.inTextInput
--;
303 mw
.widgets
.DateInputWidget
.prototype.setValue = function ( value
) {
304 var oldValue
= this.value
;
306 if ( !moment( value
, this.getInternalFormat() ).isValid() ) {
310 mw
.widgets
.DateInputWidget
.parent
.prototype.setValue
.call( this, value
);
312 if ( this.value
!== oldValue
) {
314 this.setValidityFlag();
321 * Handle text input and calendar blur events.
325 mw
.widgets
.DateInputWidget
.prototype.onBlur = function () {
327 setTimeout( function () {
328 var $focussed
= $( ':focus' );
329 // Deactivate unless the focus moved to something else inside this widget
331 !OO
.ui
.contains( widget
.$element
[ 0 ], $focussed
[ 0 ], true ) &&
332 // Calendar might be in an $overlay
333 !OO
.ui
.contains( widget
.calendar
.$element
[ 0 ], $focussed
[ 0 ], true )
343 mw
.widgets
.DateInputWidget
.prototype.focus = function () {
351 mw
.widgets
.DateInputWidget
.prototype.blur = function () {
357 * Update the contents of the label, text input and status of calendar to reflect selected value.
361 mw
.widgets
.DateInputWidget
.prototype.updateUI = function () {
363 if ( this.getValue() === '' ) {
364 this.textInput
.setValue( '' );
365 this.calendar
.setDate( null );
366 this.label
.setLabel( this.placeholderLabel
);
367 this.$element
.addClass( 'mw-widget-dateInputWidget-empty' );
369 moment
= this.getMoment();
370 if ( !this.inTextInput
) {
371 this.textInput
.setValue( moment
.format( this.getInputFormat() ) );
373 if ( !this.inCalendar
) {
374 this.calendar
.setDate( this.getValue() );
376 this.label
.setLabel( moment
.format( this.getDisplayFormat() ) );
377 this.$element
.removeClass( 'mw-widget-dateInputWidget-empty' );
382 * Deactivate this input field for data entry. Closes the calendar and hides the text field.
386 mw
.widgets
.DateInputWidget
.prototype.deactivate = function () {
387 this.$element
.removeClass( 'mw-widget-dateInputWidget-active' );
389 this.textInput
.toggle( false );
390 this.calendar
.toggle( false );
391 this.setValidityFlag();
395 * Activate this input field for data entry. Opens the calendar and shows the text field.
399 mw
.widgets
.DateInputWidget
.prototype.activate = function () {
400 this.calendar
.resetUI();
401 this.$element
.addClass( 'mw-widget-dateInputWidget-active' );
403 this.textInput
.toggle( true );
404 this.calendar
.toggle( true );
406 this.textInput
.$input
.focus();
410 * Get the date format to be used for handle label when the input is inactive.
413 * @return {string} Format string
415 mw
.widgets
.DateInputWidget
.prototype.getDisplayFormat = function () {
416 var localeData
, llll
, lll
, ll
, format
;
418 if ( this.displayFormat
!== undefined ) {
419 return this.displayFormat
;
422 if ( this.calendar
.getPrecision() === 'month' ) {
425 // The formats Moment.js provides:
426 // * ll: Month name, day of month, year
427 // * lll: Month name, day of month, year, time
428 // * llll: Month name, day of month, day of week, year, time
430 // The format we want:
431 // * ????: Month name, day of month, day of week, year
433 // We try to construct it as 'llll - (lll - ll)' and hope for the best.
434 // This seems to work well for many languages (maybe even all?).
436 localeData
= moment
.localeData( moment
.locale() );
437 llll
= localeData
.longDateFormat( 'llll' );
438 lll
= localeData
.longDateFormat( 'lll' );
439 ll
= localeData
.longDateFormat( 'll' );
440 format
= llll
.replace( lll
.replace( ll
, '' ), '' );
447 * Get the date format to be used for the text field when the input is active.
450 * @return {string} Format string
452 mw
.widgets
.DateInputWidget
.prototype.getInputFormat = function () {
453 if ( this.inputFormat
!== undefined ) {
454 return this.inputFormat
;
460 }[ this.calendar
.getPrecision() ];
464 * Get the date format to be used internally for the value. This is not configurable in any way,
465 * and always either 'YYYY-MM-DD' or 'YYYY-MM'.
468 * @return {string} Format string
470 mw
.widgets
.DateInputWidget
.prototype.getInternalFormat = function () {
474 }[ this.calendar
.getPrecision() ];
478 * Get the Moment object for current value.
480 * @return {Object} Moment object
482 mw
.widgets
.DateInputWidget
.prototype.getMoment = function () {
483 return moment( this.getValue(), this.getInternalFormat() );
487 * Handle mouse click events.
490 * @param {jQuery.Event} e Mouse click event
491 * @return {boolean} False to cancel the default event
493 mw
.widgets
.DateInputWidget
.prototype.onClick = function ( e
) {
494 if ( !this.isDisabled() && e
.which
=== 1 ) {
501 * Handle key press events.
504 * @param {jQuery.Event} e Key press event
505 * @return {boolean} False to cancel the default event
507 mw
.widgets
.DateInputWidget
.prototype.onKeyPress = function ( e
) {
508 if ( !this.isDisabled() &&
509 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
517 * Handle calendar key press events.
520 * @param {jQuery.Event} e Key press event
521 * @return {boolean} False to cancel the default event
523 mw
.widgets
.DateInputWidget
.prototype.onCalendarKeyPress = function ( e
) {
524 if ( !this.isDisabled() && e
.which
=== OO
.ui
.Keys
.ENTER
) {
526 this.$handle
.focus();
532 * Handle calendar click events.
535 * @param {jQuery.Event} e Mouse click event
536 * @return {boolean} False to cancel the default event
538 mw
.widgets
.DateInputWidget
.prototype.onCalendarClick = function ( e
) {
540 !this.isDisabled() &&
542 $( e
.target
).hasClass( 'mw-widget-calendarWidget-day' )
545 this.$handle
.focus();
551 * Handle text input enter events.
555 mw
.widgets
.DateInputWidget
.prototype.onEnter = function () {
557 this.$handle
.focus();
562 * @param {string} date Date string, to be valid, must be in 'YYYY-MM-DD' or 'YYYY-MM' format or
563 * (unless the field is required) empty
566 mw
.widgets
.DateInputWidget
.prototype.validateDate = function ( date
) {
569 isValid
= !this.required
;
571 isValid
= this.isValidDate( date
) && this.isInRange( date
);
578 * @param {string} date Date string, to be valid, must be in 'YYYY-MM-DD' or 'YYYY-MM' format
581 mw
.widgets
.DateInputWidget
.prototype.isValidDate = function ( date
) {
582 // "Half-strict mode": for example, for the format 'YYYY-MM-DD', 2015-1-3 instead of 2015-01-03
583 // is okay, but 2015-01 isn't, and neither is 2015-01-foo. Use Moment's "fuzzy" mode and check
584 // parsing flags for the details (stolen from implementation of moment#isValid).
586 mom
= moment( date
, this.getInputFormat() ),
587 flags
= mom
.parsingFlags();
589 return mom
.isValid() && flags
.charsLeftOver
=== 0 && flags
.unusedTokens
.length
=== 0;
593 * Validates if the date is within the range configured with {@link #cfg-mustBeAfter}
594 * and {@link #cfg-mustBeBefore}.
597 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
598 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
601 mw
.widgets
.DateInputWidget
.prototype.isInRange = function ( date
) {
602 var momentDate
, isAfter
, isBefore
;
603 if ( this.mustBeAfter
=== undefined && this.mustBeBefore
=== undefined ) {
606 momentDate
= moment( date
, 'YYYY-MM-DD' );
607 isAfter
= ( this.mustBeAfter
=== undefined || momentDate
.isAfter( this.mustBeAfter
) );
608 isBefore
= ( this.mustBeBefore
=== undefined || momentDate
.isBefore( this.mustBeBefore
) );
609 return isAfter
&& isBefore
;
613 * Get the validity of current value.
615 * This method returns a promise that resolves if the value is valid and rejects if
616 * it isn't. Uses {@link #validateDate}.
618 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
620 mw
.widgets
.DateInputWidget
.prototype.getValidity = function () {
621 var isValid
= this.validateDate( this.getValue() );
624 return $.Deferred().resolve().promise();
626 return $.Deferred().reject().promise();
631 * Sets the 'invalid' flag appropriately.
633 * @param {boolean} [isValid] Optionally override validation result
635 mw
.widgets
.DateInputWidget
.prototype.setValidityFlag = function ( isValid
) {
637 setFlag = function ( valid
) {
639 widget
.$input
.attr( 'aria-invalid', 'true' );
641 widget
.$input
.removeAttr( 'aria-invalid' );
643 widget
.setFlags( { invalid
: !valid
} );
646 if ( isValid
!== undefined ) {
649 this.getValidity().then( function () {
657 }( jQuery
, mediaWiki
) );