b478c4a95c82e3d9f251e04774d0e35d3258f8fe
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.$element
.addClass( 'mw-widget-dateInputWidget-active' );
328 this.handle
.toggle( false );
329 this.textInput
.toggle( true );
330 this.calendar
.toggle( true );
332 this.textInput
.$input
.focus();
336 * Get the date format to be used for handle label when the input is inactive.
339 * @return {string} Format string
341 mw
.widgets
.DateInputWidget
.prototype.getDisplayFormat = function () {
342 if ( this.displayFormat
!== undefined ) {
343 return this.displayFormat
;
346 if ( this.calendar
.getPrecision() === 'month' ) {
349 // The formats Moment.js provides:
350 // * ll: Month name, day of month, year
351 // * lll: Month name, day of month, year, time
352 // * llll: Month name, day of month, day of week, year, time
354 // The format we want:
355 // * ????: Month name, day of month, day of week, year
357 // We try to construct it as 'llll - (lll - ll)' and hope for the best.
358 // This seems to work well for many languages (maybe even all?).
360 var localeData
= moment
.localeData( moment
.locale() ),
361 llll
= localeData
.longDateFormat( 'llll' ),
362 lll
= localeData
.longDateFormat( 'lll' ),
363 ll
= localeData
.longDateFormat( 'll' ),
364 format
= llll
.replace( lll
.replace( ll
, '' ), '' );
371 * Get the date format to be used for the text field when the input is active.
374 * @return {string} Format string
376 mw
.widgets
.DateInputWidget
.prototype.getInputFormat = function () {
377 if ( this.inputFormat
!== undefined ) {
378 return this.inputFormat
;
384 }[ this.calendar
.getPrecision() ];
388 * Get the date format to be used internally for the value. This is not configurable in any way,
389 * and always either 'YYYY-MM-DD' or 'YYYY-MM'.
392 * @return {string} Format string
394 mw
.widgets
.DateInputWidget
.prototype.getInternalFormat = function () {
398 }[ this.calendar
.getPrecision() ];
402 * Get the Moment object for current value.
404 * @return {Object} Moment object
406 mw
.widgets
.DateInputWidget
.prototype.getMoment = function () {
407 return moment( this.getValue(), this.getInternalFormat() );
411 * Handle mouse click events.
414 * @param {jQuery.Event} e Mouse click event
416 mw
.widgets
.DateInputWidget
.prototype.onClick = function ( e
) {
417 if ( !this.isDisabled() && e
.which
=== 1 ) {
424 * Handle key press events.
427 * @param {jQuery.Event} e Key press event
429 mw
.widgets
.DateInputWidget
.prototype.onKeyPress = function ( e
) {
430 if ( !this.isDisabled() &&
431 ( e
.which
=== OO
.ui
.Keys
.SPACE
|| e
.which
=== OO
.ui
.Keys
.ENTER
)
439 * Handle calendar key press events.
442 * @param {jQuery.Event} e Key press event
444 mw
.widgets
.DateInputWidget
.prototype.onCalendarKeyPress = function ( e
) {
445 if ( !this.isDisabled() && e
.which
=== OO
.ui
.Keys
.ENTER
) {
447 this.handle
.$element
.focus();
453 * Handle text input enter events.
457 mw
.widgets
.DateInputWidget
.prototype.onEnter = function () {
459 this.handle
.$element
.focus();
464 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
465 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
468 mw
.widgets
.DateInputWidget
.prototype.validateDate = function ( date
) {
473 var isValid
= this.isValidDate( date
) && this.isInRange( date
);
474 this.setValidityFlag( isValid
);
480 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
481 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
484 mw
.widgets
.DateInputWidget
.prototype.isValidDate = function ( date
) {
485 // "Half-strict mode": for example, for the format 'YYYY-MM-DD', 2015-1-3 instead of 2015-01-03
486 // is okay, but 2015-01 isn't, and neither is 2015-01-foo. Use Moment's "fuzzy" mode and check
487 // parsing flags for the details (stoled from implementation of #isValid).
489 mom
= moment( date
, this.getInputFormat() ),
490 flags
= mom
.parsingFlags();
492 return mom
.isValid() && flags
.charsLeftOver
=== 0 && flags
.unusedTokens
.length
=== 0;
496 * Validates if the date is within the range configured with {@link #cfg-mustBeAfter}
497 * and {@link #cfg-mustBeBefore}.
500 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
501 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
504 mw
.widgets
.DateInputWidget
.prototype.isInRange = function ( date
) {
505 var momentDate
= moment( date
, 'YYYY-MM-DD' ),
506 isAfter
= ( this.mustBeAfter
=== undefined || momentDate
.isAfter( this.mustBeAfter
) ),
507 isBefore
= ( this.mustBeBefore
=== undefined || momentDate
.isBefore( this.mustBeBefore
) );
509 return isAfter
&& isBefore
;
513 * Get the validity of current value.
515 * This method returns a promise that resolves if the value is valid and rejects if
516 * it isn't. Uses {@link #validateDate}.
518 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
520 mw
.widgets
.DateInputWidget
.prototype.getValidity = function () {
521 var isValid
= this.validateDate( this.getValue() );
524 return $.Deferred().resolve().promise();
526 return $.Deferred().reject().promise();
531 * Sets the 'invalid' flag appropriately.
533 * @param {boolean} [isValid] Optionally override validation result
535 mw
.widgets
.DateInputWidget
.prototype.setValidityFlag = function ( isValid
) {
537 setFlag = function ( valid
) {
539 widget
.$input
.attr( 'aria-invalid', 'true' );
541 widget
.$input
.removeAttr( 'aria-invalid' );
543 widget
.setFlags( { invalid
: !valid
} );
546 if ( isValid
!== undefined ) {
549 this.getValidity().then( function () {
557 }( jQuery
, mediaWiki
) );