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.
82 mw
.widgets
.DateInputWidget
= function MWWDateInputWidget( config
) {
83 // Config initialization
84 config
= $.extend( { precision
: 'day' }, config
);
85 if ( config
.required
) {
86 if ( config
.indicator
=== undefined ) {
87 config
.indicator
= 'required';
91 var placeholder
, mustBeAfter
, mustBeBefore
;
92 if ( config
.placeholder
) {
93 placeholder
= config
.placeholder
;
94 } else if ( config
.inputFormat
) {
95 // We have no way to display a translated placeholder for custom formats
98 // Messages: mw-widgets-dateinput-placeholder-day, mw-widgets-dateinput-placeholder-month
99 placeholder
= mw
.msg( 'mw-widgets-dateinput-placeholder-' + config
.precision
);
102 // Properties (must be set before parent constructor, which calls #setValue)
103 this.handle
= new OO
.ui
.LabelWidget();
104 this.textInput
= new OO
.ui
.TextInputWidget( {
105 placeholder
: placeholder
,
106 validate
: this.validateDate
.bind( this )
108 this.calendar
= new mw
.widgets
.CalendarWidget( {
109 precision
: config
.precision
112 this.inTextInput
= 0;
113 this.inputFormat
= config
.inputFormat
;
114 this.displayFormat
= config
.displayFormat
;
116 // Validate and set min and max dates as properties
117 mustBeAfter
= moment( config
.mustBeAfter
, 'YYYY-MM-DD' );
118 mustBeBefore
= moment( config
.mustBeBefore
, 'YYYY-MM-DD' );
120 config
.mustBeAfter
!== undefined &&
121 mustBeAfter
.isValid()
123 this.mustBeAfter
= mustBeAfter
;
127 config
.mustBeBefore
!== undefined &&
128 mustBeBefore
.isValid()
130 this.mustBeBefore
= mustBeBefore
;
133 // Parent constructor
134 mw
.widgets
.DateInputWidget
.parent
.call( this, config
);
137 this.calendar
.connect( this, {
138 change
: 'onCalendarChange'
140 this.textInput
.connect( this, {
142 change
: 'onTextInputChange'
145 focusout
: this.onBlur
.bind( this )
147 this.calendar
.$element
.on( {
148 keypress
: this.onCalendarKeyPress
.bind( this )
150 this.handle
.$element
.on( {
151 click
: this.onClick
.bind( this ),
152 keypress
: this.onKeyPress
.bind( this )
156 if ( config
.required
) {
157 this.$input
.attr( 'required', 'required' );
158 this.$input
.attr( 'aria-required', 'true' );
160 // Move 'tabindex' from this.$input (which is invisible) to the visible handle
161 this.setTabIndexedElement( this.handle
.$element
);
163 .addClass( 'mw-widget-dateInputWidget-handle' );
165 .addClass( 'mw-widget-dateInputWidget' )
166 .append( this.handle
.$element
, this.textInput
.$element
, this.calendar
.$element
);
167 // Set handle label and hide stuff
174 OO
.inheritClass( mw
.widgets
.DateInputWidget
, OO
.ui
.InputWidget
);
182 mw
.widgets
.DateInputWidget
.prototype.getInputElement = function () {
183 return $( '<input type="hidden">' );
187 * Respond to calendar date change events.
191 mw
.widgets
.DateInputWidget
.prototype.onCalendarChange = function () {
193 if ( !this.inTextInput
) {
194 // If this is caused by user typing in the input field, do not set anything.
195 // The value may be invalid (see #onTextInputChange), but displayable on the calendar.
196 this.setValue( this.calendar
.getDate() );
202 * Respond to text input value change events.
206 mw
.widgets
.DateInputWidget
.prototype.onTextInputChange = function () {
209 value
= this.textInput
.getValue(),
210 valid
= this.isValidDate( value
);
213 if ( value
=== '' ) {
215 widget
.setValue( '' );
216 } else if ( valid
) {
217 // Well-formed date value, parse and set it
218 mom
= moment( value
, widget
.getInputFormat() );
219 // Use English locale to avoid number formatting
220 widget
.setValue( mom
.locale( 'en' ).format( widget
.getInternalFormat() ) );
222 // Not well-formed, but possibly partial? Try updating the calendar, but do not set the
223 // internal value. Generally this only makes sense when 'inputFormat' is little-endian (e.g.
224 // 'YYYY-MM-DD'), but that's hard to check for, and might be difficult to handle the parsing
225 // right for weird formats. So limit this trick to only when we're using the default
226 // 'inputFormat', which is the same as the internal format, 'YYYY-MM-DD'.
227 if ( widget
.getInputFormat() === widget
.getInternalFormat() ) {
228 widget
.calendar
.setDate( widget
.textInput
.getValue() );
231 widget
.inTextInput
--;
238 mw
.widgets
.DateInputWidget
.prototype.setValue = function ( value
) {
239 var oldValue
= this.value
;
241 if ( !moment( value
, this.getInternalFormat() ).isValid() ) {
245 mw
.widgets
.DateInputWidget
.parent
.prototype.setValue
.call( this, value
);
247 if ( this.value
!== oldValue
) {
255 * Handle text input and calendar blur events.
259 mw
.widgets
.DateInputWidget
.prototype.onBlur = function () {
261 setTimeout( function () {
262 var $focussed
= $( ':focus' );
263 // Deactivate unless the focus moved to something else inside this widget
264 if ( !OO
.ui
.contains( widget
.$element
[ 0 ], $focussed
[ 0 ], true ) ) {
273 mw
.widgets
.DateInputWidget
.prototype.focus = function () {
281 mw
.widgets
.DateInputWidget
.prototype.blur = function () {
287 * Update the contents of the label, text input and status of calendar to reflect selected value.
291 mw
.widgets
.DateInputWidget
.prototype.updateUI = function () {
292 if ( this.getValue() === '' ) {
293 this.textInput
.setValue( '' );
294 this.calendar
.setDate( null );
295 this.handle
.setLabel( mw
.msg( 'mw-widgets-dateinput-no-date' ) );
296 this.$element
.addClass( 'mw-widget-dateInputWidget-empty' );
298 if ( !this.inTextInput
) {
299 this.textInput
.setValue( this.getMoment().format( this.getInputFormat() ) );
301 if ( !this.inCalendar
) {
302 this.calendar
.setDate( this.getValue() );
304 this.handle
.setLabel( this.getMoment().format( this.getDisplayFormat() ) );
305 this.$element
.removeClass( 'mw-widget-dateInputWidget-empty' );
310 * Deactivate this input field for data entry. Closes the calendar and hides the text field.
314 mw
.widgets
.DateInputWidget
.prototype.deactivate = function () {
315 this.$element
.removeClass( 'mw-widget-dateInputWidget-active' );
316 this.handle
.toggle( true );
317 this.textInput
.toggle( false );
318 this.calendar
.toggle( false );
322 * Activate this input field for data entry. Opens the calendar and shows the text field.
326 mw
.widgets
.DateInputWidget
.prototype.activate = function () {
327 this.calendar
.resetUI();
328 this.$element
.addClass( 'mw-widget-dateInputWidget-active' );
329 this.handle
.toggle( false );
330 this.textInput
.toggle( true );
331 this.calendar
.toggle( true );
333 this.textInput
.$input
.focus();
337 * Get the date format to be used for handle label when the input is inactive.
340 * @return {string} Format string
342 mw
.widgets
.DateInputWidget
.prototype.getDisplayFormat = function () {
343 if ( this.displayFormat
!== undefined ) {
344 return this.displayFormat
;
347 if ( this.calendar
.getPrecision() === 'month' ) {
350 // The formats Moment.js provides:
351 // * ll: Month name, day of month, year
352 // * lll: Month name, day of month, year, time
353 // * llll: Month name, day of month, day of week, year, time
355 // The format we want:
356 // * ????: Month name, day of month, day of week, year
358 // We try to construct it as 'llll - (lll - ll)' and hope for the best.
359 // This seems to work well for many languages (maybe even all?).
361 var localeData
= moment
.localeData( moment
.locale() ),
362 llll
= localeData
.longDateFormat( 'llll' ),
363 lll
= localeData
.longDateFormat( 'lll' ),
364 ll
= localeData
.longDateFormat( 'll' ),
365 format
= llll
.replace( lll
.replace( ll
, '' ), '' );
372 * Get the date format to be used for the text field when the input is active.
375 * @return {string} Format string
377 mw
.widgets
.DateInputWidget
.prototype.getInputFormat = function () {
378 if ( this.inputFormat
!== undefined ) {
379 return this.inputFormat
;
385 }[ this.calendar
.getPrecision() ];
389 * Get the date format to be used internally for the value. This is not configurable in any way,
390 * and always either 'YYYY-MM-DD' or 'YYYY-MM'.
393 * @return {string} Format string
395 mw
.widgets
.DateInputWidget
.prototype.getInternalFormat = function () {
399 }[ this.calendar
.getPrecision() ];
403 * Get the Moment object for current value.
405 * @return {Object} Moment object
407 mw
.widgets
.DateInputWidget
.prototype.getMoment = function () {
408 return moment( this.getValue(), this.getInternalFormat() );
412 * Handle mouse click events.
415 * @param {jQuery.Event} e Mouse click event
417 mw
.widgets
.DateInputWidget
.prototype.onClick = function ( e
) {
418 if ( !this.isDisabled() && e
.which
=== 1 ) {
425 * Handle key press events.
428 * @param {jQuery.Event} e Key press event
430 mw
.widgets
.DateInputWidget
.prototype.onKeyPress = function ( e
) {
431 if ( !this.isDisabled() &&
432 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
440 * Handle calendar key press events.
443 * @param {jQuery.Event} e Key press event
445 mw
.widgets
.DateInputWidget
.prototype.onCalendarKeyPress = function ( e
) {
446 if ( !this.isDisabled() && e
.which
=== OO
.ui
.Keys
.ENTER
) {
448 this.handle
.$element
.focus();
454 * Handle text input enter events.
458 mw
.widgets
.DateInputWidget
.prototype.onEnter = function () {
460 this.handle
.$element
.focus();
465 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
466 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
469 mw
.widgets
.DateInputWidget
.prototype.validateDate = function ( date
) {
474 var isValid
= this.isValidDate( date
) && this.isInRange( date
);
475 this.setValidityFlag( isValid
);
481 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
482 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
485 mw
.widgets
.DateInputWidget
.prototype.isValidDate = function ( date
) {
486 // "Half-strict mode": for example, for the format 'YYYY-MM-DD', 2015-1-3 instead of 2015-01-03
487 // is okay, but 2015-01 isn't, and neither is 2015-01-foo. Use Moment's "fuzzy" mode and check
488 // parsing flags for the details (stoled from implementation of #isValid).
490 mom
= moment( date
, this.getInputFormat() ),
491 flags
= mom
.parsingFlags();
493 return mom
.isValid() && flags
.charsLeftOver
=== 0 && flags
.unusedTokens
.length
=== 0;
497 * Validates if the date is within the range configured with {@link #cfg-mustBeAfter}
498 * and {@link #cfg-mustBeBefore}.
501 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
502 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
505 mw
.widgets
.DateInputWidget
.prototype.isInRange = function ( date
) {
506 var momentDate
= moment( date
, 'YYYY-MM-DD' ),
507 isAfter
= ( this.mustBeAfter
=== undefined || momentDate
.isAfter( this.mustBeAfter
) ),
508 isBefore
= ( this.mustBeBefore
=== undefined || momentDate
.isBefore( this.mustBeBefore
) );
510 return isAfter
&& isBefore
;
514 * Get the validity of current value.
516 * This method returns a promise that resolves if the value is valid and rejects if
517 * it isn't. Uses {@link #validateDate}.
519 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
521 mw
.widgets
.DateInputWidget
.prototype.getValidity = function () {
522 var isValid
= this.validateDate( this.getValue() );
525 return $.Deferred().resolve().promise();
527 return $.Deferred().reject().promise();
532 * Sets the 'invalid' flag appropriately.
534 * @param {boolean} [isValid] Optionally override validation result
536 mw
.widgets
.DateInputWidget
.prototype.setValidityFlag = function ( isValid
) {
538 setFlag = function ( valid
) {
540 widget
.$input
.attr( 'aria-invalid', 'true' );
542 widget
.$input
.removeAttr( 'aria-invalid' );
544 widget
.setFlags( { invalid
: !valid
} );
547 if ( isValid
!== undefined ) {
550 this.getValidity().then( function () {
558 }( jQuery
, mediaWiki
) );