c8093bb83316df84ea23798bb86de8f43c9593a4
[lhc/web/wiklou.git] / resources / src / mediawiki.widgets / mw.widgets.DateInputWidget.js
1 /*!
2 * MediaWiki Widgets – DateInputWidget class.
3 *
4 * @copyright 2011-2015 MediaWiki Widgets Team and others; see AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7 /*global moment */
8 ( function ( $, mw ) {
9
10 /**
11 * Creates an mw.widgets.DateInputWidget object.
12 *
13 * @example
14 * // Date input widget showcase
15 * var fieldset = new OO.ui.FieldsetLayout( {
16 * items: [
17 * new OO.ui.FieldLayout(
18 * new mw.widgets.DateInputWidget(),
19 * {
20 * align: 'top',
21 * label: 'Select date'
22 * }
23 * ),
24 * new OO.ui.FieldLayout(
25 * new mw.widgets.DateInputWidget( { precision: 'month' } ),
26 * {
27 * align: 'top',
28 * label: 'Select month'
29 * }
30 * ),
31 * new OO.ui.FieldLayout(
32 * new mw.widgets.DateInputWidget( {
33 * inputFormat: 'DD.MM.YYYY',
34 * displayFormat: 'Do [of] MMMM [anno Domini] YYYY'
35 * } ),
36 * {
37 * align: 'top',
38 * label: 'Select date (custom formats)'
39 * }
40 * )
41 * ]
42 * } );
43 * $( 'body' ).append( fieldset.$element );
44 *
45 * The value is stored in 'YYYY-MM-DD' or 'YYYY-MM' format:
46 *
47 * @example
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)' ) );
56 * } );
57 *
58 * @class
59 * @extends OO.ui.InputWidget
60 *
61 * @constructor
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
69 * `precision`.
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 */
80 mw.widgets.DateInputWidget = function MWWDateInputWidget( config ) {
81 // Config initialization
82 config = $.extend( { precision: 'day' }, config );
83 if ( config.required ) {
84 if ( config.indicator === undefined ) {
85 config.indicator = 'required';
86 }
87 }
88
89 var placeholder;
90 if ( config.placeholder ) {
91 placeholder = config.placeholder;
92 } else if ( config.inputFormat ) {
93 // We have no way to display a translated placeholder for custom formats
94 placeholder = '';
95 } else {
96 // Messages: mw-widgets-dateinput-placeholder-day, mw-widgets-dateinput-placeholder-month
97 placeholder = mw.msg( 'mw-widgets-dateinput-placeholder-' + config.precision );
98 }
99
100 // Properties (must be set before parent constructor, which calls #setValue)
101 this.handle = new OO.ui.LabelWidget();
102 this.textInput = new OO.ui.TextInputWidget( {
103 placeholder: placeholder,
104 validate: this.validateDate.bind( this )
105 } );
106 this.calendar = new mw.widgets.CalendarWidget( {
107 precision: config.precision
108 } );
109 this.inCalendar = 0;
110 this.inTextInput = 0;
111 this.inputFormat = config.inputFormat;
112 this.displayFormat = config.displayFormat;
113
114 // Parent constructor
115 mw.widgets.DateInputWidget.parent.call( this, config );
116
117 // Events
118 this.calendar.connect( this, {
119 change: 'onCalendarChange'
120 } );
121 this.textInput.connect( this, {
122 enter: 'onEnter',
123 change: 'onTextInputChange'
124 } );
125 this.$element.on( {
126 focusout: this.onBlur.bind( this )
127 } );
128 this.calendar.$element.on( {
129 keypress: this.onCalendarKeyPress.bind( this )
130 } );
131 this.handle.$element.on( {
132 click: this.onClick.bind( this ),
133 keypress: this.onKeyPress.bind( this )
134 } );
135
136 // Initialization
137 if ( config.required ) {
138 this.$input.attr( 'required', 'required' );
139 this.$input.attr( 'aria-required', 'true' );
140 }
141 // Move 'tabindex' from this.$input (which is invisible) to the visible handle
142 this.setTabIndexedElement( this.handle.$element );
143 this.handle.$element
144 .addClass( 'mw-widget-dateInputWidget-handle' );
145 this.$element
146 .addClass( 'mw-widget-dateInputWidget' )
147 .append( this.handle.$element, this.textInput.$element, this.calendar.$element );
148 // Set handle label and hide stuff
149 this.updateUI();
150 this.deactivate();
151 };
152
153 /* Inheritance */
154
155 OO.inheritClass( mw.widgets.DateInputWidget, OO.ui.InputWidget );
156
157 /* Methods */
158
159 /**
160 * @inheritdoc
161 * @protected
162 */
163 mw.widgets.DateInputWidget.prototype.getInputElement = function () {
164 return $( '<input type="hidden">' );
165 };
166
167 /**
168 * Respond to calendar date change events.
169 *
170 * @private
171 */
172 mw.widgets.DateInputWidget.prototype.onCalendarChange = function () {
173 this.inCalendar++;
174 if ( !this.inTextInput ) {
175 // If this is caused by user typing in the input field, do not set anything.
176 // The value may be invalid (see #onTextInputChange), but displayable on the calendar.
177 this.setValue( this.calendar.getDate() );
178 }
179 this.inCalendar--;
180 };
181
182 /**
183 * Respond to text input value change events.
184 *
185 * @private
186 */
187 mw.widgets.DateInputWidget.prototype.onTextInputChange = function () {
188 var
189 widget = this,
190 value = this.textInput.getValue();
191 this.inTextInput++;
192 this.textInput.isValid().done( function ( valid ) {
193 if ( value === '' ) {
194 // No date selected
195 widget.setValue( '' );
196 } else if ( valid ) {
197 // Well-formed date value, parse and set it
198 var mom = moment( value, widget.getInputFormat() );
199 // Use English locale to avoid number formatting
200 widget.setValue( mom.locale( 'en' ).format( widget.getInternalFormat() ) );
201 } else {
202 // Not well-formed, but possibly partial? Try updating the calendar, but do not set the
203 // internal value. Generally this only makes sense when 'inputFormat' is little-endian (e.g.
204 // 'YYYY-MM-DD'), but that's hard to check for, and might be difficult to handle the parsing
205 // right for weird formats. So limit this trick to only when we're using the default
206 // 'inputFormat', which is the same as the internal format, 'YYYY-MM-DD'.
207 if ( widget.getInputFormat() === widget.getInternalFormat() ) {
208 widget.calendar.setDate( widget.textInput.getValue() );
209 }
210 }
211 widget.inTextInput--;
212 } );
213 };
214
215 /**
216 * @inheritdoc
217 */
218 mw.widgets.DateInputWidget.prototype.setValue = function ( value ) {
219 var oldValue = this.value;
220
221 if ( !moment( value, this.getInternalFormat() ).isValid() ) {
222 value = '';
223 }
224
225 mw.widgets.DateInputWidget.parent.prototype.setValue.call( this, value );
226
227 if ( this.value !== oldValue ) {
228 this.updateUI();
229 }
230
231 return this;
232 };
233
234 /**
235 * Handle text input and calendar blur events.
236 *
237 * @private
238 */
239 mw.widgets.DateInputWidget.prototype.onBlur = function () {
240 var widget = this;
241 setTimeout( function () {
242 var $focussed = $( ':focus' );
243 // Deactivate unless the focus moved to something else inside this widget
244 if ( !OO.ui.contains( widget.$element[ 0 ], $focussed[ 0 ], true ) ) {
245 widget.deactivate();
246 }
247 }, 0 );
248 };
249
250 /**
251 * @inheritdoc
252 */
253 mw.widgets.DateInputWidget.prototype.focus = function () {
254 this.activate();
255 return this;
256 };
257
258 /**
259 * @inheritdoc
260 */
261 mw.widgets.DateInputWidget.prototype.blur = function () {
262 this.deactivate();
263 return this;
264 };
265
266 /**
267 * Update the contents of the label, text input and status of calendar to reflect selected value.
268 *
269 * @private
270 */
271 mw.widgets.DateInputWidget.prototype.updateUI = function () {
272 if ( this.getValue() === '' ) {
273 this.textInput.setValue( '' );
274 this.calendar.setDate( null );
275 this.handle.setLabel( mw.msg( 'mw-widgets-dateinput-no-date' ) );
276 this.$element.addClass( 'mw-widget-dateInputWidget-empty' );
277 } else {
278 if ( !this.inTextInput ) {
279 this.textInput.setValue( this.getMoment().format( this.getInputFormat() ) );
280 }
281 if ( !this.inCalendar ) {
282 this.calendar.setDate( this.getValue() );
283 }
284 this.handle.setLabel( this.getMoment().format( this.getDisplayFormat() ) );
285 this.$element.removeClass( 'mw-widget-dateInputWidget-empty' );
286 }
287 };
288
289 /**
290 * Deactivate this input field for data entry. Closes the calendar and hides the text field.
291 *
292 * @private
293 */
294 mw.widgets.DateInputWidget.prototype.deactivate = function () {
295 this.$element.removeClass( 'mw-widget-dateInputWidget-active' );
296 this.handle.toggle( true );
297 this.textInput.toggle( false );
298 this.calendar.toggle( false );
299 };
300
301 /**
302 * Activate this input field for data entry. Opens the calendar and shows the text field.
303 *
304 * @private
305 */
306 mw.widgets.DateInputWidget.prototype.activate = function () {
307 this.$element.addClass( 'mw-widget-dateInputWidget-active' );
308 this.handle.toggle( false );
309 this.textInput.toggle( true );
310 this.calendar.toggle( true );
311
312 this.textInput.$input.focus();
313 };
314
315 /**
316 * Get the date format to be used for handle label when the input is inactive.
317 *
318 * @private
319 * @return {string} Format string
320 */
321 mw.widgets.DateInputWidget.prototype.getDisplayFormat = function () {
322 if ( this.displayFormat !== undefined ) {
323 return this.displayFormat;
324 }
325
326 if ( this.calendar.getPrecision() === 'month' ) {
327 return 'MMMM YYYY';
328 } else {
329 // The formats Moment.js provides:
330 // * ll: Month name, day of month, year
331 // * lll: Month name, day of month, year, time
332 // * llll: Month name, day of month, day of week, year, time
333 //
334 // The format we want:
335 // * ????: Month name, day of month, day of week, year
336 //
337 // We try to construct it as 'llll - (lll - ll)' and hope for the best.
338 // This seems to work well for many languages (maybe even all?).
339
340 var localeData = moment.localeData( moment.locale() ),
341 llll = localeData.longDateFormat( 'llll' ),
342 lll = localeData.longDateFormat( 'lll' ),
343 ll = localeData.longDateFormat( 'll' ),
344 format = llll.replace( lll.replace( ll, '' ), '' );
345
346 return format;
347 }
348 };
349
350 /**
351 * Get the date format to be used for the text field when the input is active.
352 *
353 * @private
354 * @return {string} Format string
355 */
356 mw.widgets.DateInputWidget.prototype.getInputFormat = function () {
357 if ( this.inputFormat !== undefined ) {
358 return this.inputFormat;
359 }
360
361 return {
362 day: 'YYYY-MM-DD',
363 month: 'YYYY-MM'
364 }[ this.calendar.getPrecision() ];
365 };
366
367 /**
368 * Get the date format to be used internally for the value. This is not configurable in any way,
369 * and always either 'YYYY-MM-DD' or 'YYYY-MM'.
370 *
371 * @private
372 * @return {string} Format string
373 */
374 mw.widgets.DateInputWidget.prototype.getInternalFormat = function () {
375 return {
376 day: 'YYYY-MM-DD',
377 month: 'YYYY-MM'
378 }[ this.calendar.getPrecision() ];
379 };
380
381 /**
382 * Get the Moment object for current value.
383 *
384 * @return {Object} Moment object
385 */
386 mw.widgets.DateInputWidget.prototype.getMoment = function () {
387 return moment( this.getValue(), this.getInternalFormat() );
388 };
389
390 /**
391 * Handle mouse click events.
392 *
393 * @private
394 * @param {jQuery.Event} e Mouse click event
395 */
396 mw.widgets.DateInputWidget.prototype.onClick = function ( e ) {
397 if ( !this.isDisabled() && e.which === 1 ) {
398 this.activate();
399 }
400 return false;
401 };
402
403 /**
404 * Handle key press events.
405 *
406 * @private
407 * @param {jQuery.Event} e Key press event
408 */
409 mw.widgets.DateInputWidget.prototype.onKeyPress = function ( e ) {
410 if ( !this.isDisabled() &&
411 ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER )
412 ) {
413 this.activate();
414 return false;
415 }
416 };
417
418 /**
419 * Handle calendar key press events.
420 *
421 * @private
422 * @param {jQuery.Event} e Key press event
423 */
424 mw.widgets.DateInputWidget.prototype.onCalendarKeyPress = function ( e ) {
425 if ( !this.isDisabled() && e.which === OO.ui.Keys.ENTER ) {
426 this.deactivate();
427 this.handle.$element.focus();
428 return false;
429 }
430 };
431
432 /**
433 * Handle text input enter events.
434 *
435 * @private
436 */
437 mw.widgets.DateInputWidget.prototype.onEnter = function () {
438 this.deactivate();
439 this.handle.$element.focus();
440 };
441
442 /**
443 * @private
444 * @param {string} date Date string, to be valid, must be empty (no date selected) or in
445 * 'YYYY-MM-DD' or 'YYYY-MM' format to be valid
446 */
447 mw.widgets.DateInputWidget.prototype.validateDate = function ( date ) {
448 if ( date === '' ) {
449 return true;
450 }
451
452 // "Half-strict mode": for example, for the format 'YYYY-MM-DD', 2015-1-3 instead of 2015-01-03
453 // is okay, but 2015-01 isn't, and neither is 2015-01-foo. Use Moment's "fuzzy" mode and check
454 // parsing flags for the details (stoled from implementation of #isValid).
455 var
456 mom = moment( date, this.getInputFormat() ),
457 flags = mom.parsingFlags();
458
459 return mom.isValid() && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0;
460 };
461
462 }( jQuery, mediaWiki ) );