Merge "Throw an exception if password hash would be truncated by DB"
[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 * @mixins OO.ui.mixin.IndicatorElement
61 *
62 * @constructor
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
70 * `precision`.
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.
88 */
89 mw.widgets.DateInputWidget = function MWWDateInputWidget( config ) {
90 var placeholderDateFormat, mustBeAfter, mustBeBefore;
91
92 // Config initialization
93 config = $.extend( {
94 precision: 'day',
95 required: false,
96 placeholderLabel: mw.msg( 'mw-widgets-dateinput-no-date' )
97 }, config );
98 if ( config.required ) {
99 if ( config.indicator === undefined ) {
100 config.indicator = 'required';
101 }
102 }
103
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 = '';
109 } else {
110 // Messages: mw-widgets-dateinput-placeholder-day, mw-widgets-dateinput-placeholder-month
111 placeholderDateFormat = mw.msg( 'mw-widgets-dateinput-placeholder-' + config.precision );
112 }
113
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 )
121 } );
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
127 } );
128 this.inCalendar = 0;
129 this.inTextInput = 0;
130 this.inputFormat = config.inputFormat;
131 this.displayFormat = config.displayFormat;
132 this.required = config.required;
133 this.placeholderLabel = config.placeholderLabel;
134
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;
140 }
141 }
142 if ( config.mustBeBefore !== undefined ) {
143 mustBeBefore = moment( config.mustBeBefore, 'YYYY-MM-DD' );
144 if ( mustBeBefore.isValid() ) {
145 this.mustBeBefore = mustBeBefore;
146 }
147 }
148
149 // Parent constructor
150 mw.widgets.DateInputWidget.parent.call( this, config );
151
152 // Mixin constructors
153 OO.ui.mixin.IndicatorElement.call( this, config );
154
155 // Events
156 this.calendar.connect( this, {
157 change: 'onCalendarChange'
158 } );
159 this.textInput.connect( this, {
160 enter: 'onEnter',
161 change: 'onTextInputChange'
162 } );
163 this.$element.on( {
164 focusout: this.onBlur.bind( this )
165 } );
166 this.calendar.$element.on( {
167 click: this.onCalendarClick.bind( this ),
168 keypress: this.onCalendarKeyPress.bind( this )
169 } );
170 this.$handle.on( {
171 click: this.onClick.bind( this ),
172 keypress: this.onKeyPress.bind( this )
173 } );
174
175 // Initialization
176 // Move 'tabindex' from this.$input (which is invisible) to the visible handle
177 this.setTabIndexedElement( this.$handle );
178 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' );
183 this.$element
184 .addClass( 'mw-widget-dateInputWidget' )
185 .append( this.$handle, this.textInput.$element, this.calendar.$element );
186
187 // config.overlay is the selector to be used for config.$overlay, specified from PHP
188 if ( config.overlay ) {
189 config.$overlay = $( config.overlay );
190 }
191
192 if ( config.$overlay ) {
193 this.calendar.setFloatableContainer( this.$element );
194 config.$overlay.append( this.calendar.$element );
195
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 ) {
199 if ( e.shiftKey ) {
200 // Tabbing backward from text input: normal browser behavior
201 $.noop();
202 } else {
203 // Tabbing forward from text input: just focus the calendar
204 this.calendar.$element.focus();
205 return false;
206 }
207 }
208 }.bind( this ) );
209 this.calendar.$element.on( 'keydown', function ( e ) {
210 if ( e.which === OO.ui.Keys.TAB ) {
211 if ( e.shiftKey ) {
212 // Tabbing backward from calendar: just focus the text input
213 this.textInput.$input.focus();
214 return false;
215 } else {
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();
219 }
220 }
221 }.bind( this ) );
222 }
223
224 // Set handle label and hide stuff
225 this.updateUI();
226 this.textInput.toggle( false );
227 this.calendar.toggle( false );
228
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' );
233 }
234 };
235
236 /* Inheritance */
237
238 OO.inheritClass( mw.widgets.DateInputWidget, OO.ui.InputWidget );
239 OO.mixinClass( mw.widgets.DateInputWidget, OO.ui.mixin.IndicatorElement );
240
241 /* Methods */
242
243 /**
244 * @inheritdoc
245 * @protected
246 */
247 mw.widgets.DateInputWidget.prototype.getInputElement = function () {
248 return $( '<input>' ).attr( 'type', 'hidden' );
249 };
250
251 /**
252 * Respond to calendar date change events.
253 *
254 * @private
255 */
256 mw.widgets.DateInputWidget.prototype.onCalendarChange = function () {
257 this.inCalendar++;
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() );
262 }
263 this.inCalendar--;
264 };
265
266 /**
267 * Respond to text input value change events.
268 *
269 * @private
270 */
271 mw.widgets.DateInputWidget.prototype.onTextInputChange = function () {
272 var mom,
273 widget = this,
274 value = this.textInput.getValue(),
275 valid = this.isValidDate( value );
276 this.inTextInput++;
277
278 if ( value === '' ) {
279 // No date selected
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() ) );
286 } else {
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() );
294 }
295 }
296 widget.inTextInput--;
297
298 };
299
300 /**
301 * @inheritdoc
302 */
303 mw.widgets.DateInputWidget.prototype.setValue = function ( value ) {
304 var oldValue = this.value;
305
306 if ( !moment( value, this.getInternalFormat() ).isValid() ) {
307 value = '';
308 }
309
310 mw.widgets.DateInputWidget.parent.prototype.setValue.call( this, value );
311
312 if ( this.value !== oldValue ) {
313 this.updateUI();
314 this.setValidityFlag();
315 }
316
317 return this;
318 };
319
320 /**
321 * Handle text input and calendar blur events.
322 *
323 * @private
324 */
325 mw.widgets.DateInputWidget.prototype.onBlur = function () {
326 var widget = this;
327 setTimeout( function () {
328 var $focussed = $( ':focus' );
329 // Deactivate unless the focus moved to something else inside this widget
330 if (
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 )
334 ) {
335 widget.deactivate();
336 }
337 }, 0 );
338 };
339
340 /**
341 * @inheritdoc
342 */
343 mw.widgets.DateInputWidget.prototype.focus = function () {
344 this.activate();
345 return this;
346 };
347
348 /**
349 * @inheritdoc
350 */
351 mw.widgets.DateInputWidget.prototype.blur = function () {
352 this.deactivate();
353 return this;
354 };
355
356 /**
357 * Update the contents of the label, text input and status of calendar to reflect selected value.
358 *
359 * @private
360 */
361 mw.widgets.DateInputWidget.prototype.updateUI = function () {
362 var moment;
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' );
368 } else {
369 moment = this.getMoment();
370 if ( !this.inTextInput ) {
371 this.textInput.setValue( moment.format( this.getInputFormat() ) );
372 }
373 if ( !this.inCalendar ) {
374 this.calendar.setDate( this.getValue() );
375 }
376 this.label.setLabel( moment.format( this.getDisplayFormat() ) );
377 this.$element.removeClass( 'mw-widget-dateInputWidget-empty' );
378 }
379 };
380
381 /**
382 * Deactivate this input field for data entry. Closes the calendar and hides the text field.
383 *
384 * @private
385 */
386 mw.widgets.DateInputWidget.prototype.deactivate = function () {
387 this.$element.removeClass( 'mw-widget-dateInputWidget-active' );
388 this.$handle.show();
389 this.textInput.toggle( false );
390 this.calendar.toggle( false );
391 this.setValidityFlag();
392 };
393
394 /**
395 * Activate this input field for data entry. Opens the calendar and shows the text field.
396 *
397 * @private
398 */
399 mw.widgets.DateInputWidget.prototype.activate = function () {
400 this.calendar.resetUI();
401 this.$element.addClass( 'mw-widget-dateInputWidget-active' );
402 this.$handle.hide();
403 this.textInput.toggle( true );
404 this.calendar.toggle( true );
405
406 this.textInput.$input.focus();
407 };
408
409 /**
410 * Get the date format to be used for handle label when the input is inactive.
411 *
412 * @private
413 * @return {string} Format string
414 */
415 mw.widgets.DateInputWidget.prototype.getDisplayFormat = function () {
416 var localeData, llll, lll, ll, format;
417
418 if ( this.displayFormat !== undefined ) {
419 return this.displayFormat;
420 }
421
422 if ( this.calendar.getPrecision() === 'month' ) {
423 return 'MMMM YYYY';
424 } else {
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
429 //
430 // The format we want:
431 // * ????: Month name, day of month, day of week, year
432 //
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?).
435
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, '' ), '' );
441
442 return format;
443 }
444 };
445
446 /**
447 * Get the date format to be used for the text field when the input is active.
448 *
449 * @private
450 * @return {string} Format string
451 */
452 mw.widgets.DateInputWidget.prototype.getInputFormat = function () {
453 if ( this.inputFormat !== undefined ) {
454 return this.inputFormat;
455 }
456
457 return {
458 day: 'YYYY-MM-DD',
459 month: 'YYYY-MM'
460 }[ this.calendar.getPrecision() ];
461 };
462
463 /**
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'.
466 *
467 * @private
468 * @return {string} Format string
469 */
470 mw.widgets.DateInputWidget.prototype.getInternalFormat = function () {
471 return {
472 day: 'YYYY-MM-DD',
473 month: 'YYYY-MM'
474 }[ this.calendar.getPrecision() ];
475 };
476
477 /**
478 * Get the Moment object for current value.
479 *
480 * @return {Object} Moment object
481 */
482 mw.widgets.DateInputWidget.prototype.getMoment = function () {
483 return moment( this.getValue(), this.getInternalFormat() );
484 };
485
486 /**
487 * Handle mouse click events.
488 *
489 * @private
490 * @param {jQuery.Event} e Mouse click event
491 * @return {boolean} False to cancel the default event
492 */
493 mw.widgets.DateInputWidget.prototype.onClick = function ( e ) {
494 if ( !this.isDisabled() && e.which === 1 ) {
495 this.activate();
496 }
497 return false;
498 };
499
500 /**
501 * Handle key press events.
502 *
503 * @private
504 * @param {jQuery.Event} e Key press event
505 * @return {boolean} False to cancel the default event
506 */
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 )
510 ) {
511 this.activate();
512 return false;
513 }
514 };
515
516 /**
517 * Handle calendar key press events.
518 *
519 * @private
520 * @param {jQuery.Event} e Key press event
521 * @return {boolean} False to cancel the default event
522 */
523 mw.widgets.DateInputWidget.prototype.onCalendarKeyPress = function ( e ) {
524 if ( !this.isDisabled() && e.which === OO.ui.Keys.ENTER ) {
525 this.deactivate();
526 this.$handle.focus();
527 return false;
528 }
529 };
530
531 /**
532 * Handle calendar click events.
533 *
534 * @private
535 * @param {jQuery.Event} e Mouse click event
536 * @return {boolean} False to cancel the default event
537 */
538 mw.widgets.DateInputWidget.prototype.onCalendarClick = function ( e ) {
539 if (
540 !this.isDisabled() &&
541 e.which === 1 &&
542 $( e.target ).hasClass( 'mw-widget-calendarWidget-day' )
543 ) {
544 this.deactivate();
545 this.$handle.focus();
546 return false;
547 }
548 };
549
550 /**
551 * Handle text input enter events.
552 *
553 * @private
554 */
555 mw.widgets.DateInputWidget.prototype.onEnter = function () {
556 this.deactivate();
557 this.$handle.focus();
558 };
559
560 /**
561 * @private
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
564 * @return {boolean}
565 */
566 mw.widgets.DateInputWidget.prototype.validateDate = function ( date ) {
567 var isValid;
568 if ( date === '' ) {
569 isValid = !this.required;
570 } else {
571 isValid = this.isValidDate( date ) && this.isInRange( date );
572 }
573 return isValid;
574 };
575
576 /**
577 * @private
578 * @param {string} date Date string, to be valid, must be in 'YYYY-MM-DD' or 'YYYY-MM' format
579 * @return {boolean}
580 */
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).
585 var
586 mom = moment( date, this.getInputFormat() ),
587 flags = mom.parsingFlags();
588
589 return mom.isValid() && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0;
590 };
591
592 /**
593 * Validates if the date is within the range configured with {@link #cfg-mustBeAfter}
594 * and {@link #cfg-mustBeBefore}.
595 *
596 * @private
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
599 * @return {boolean}
600 */
601 mw.widgets.DateInputWidget.prototype.isInRange = function ( date ) {
602 var momentDate, isAfter, isBefore;
603 if ( this.mustBeAfter === undefined && this.mustBeBefore === undefined ) {
604 return true;
605 }
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;
610 };
611
612 /**
613 * Get the validity of current value.
614 *
615 * This method returns a promise that resolves if the value is valid and rejects if
616 * it isn't. Uses {@link #validateDate}.
617 *
618 * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not.
619 */
620 mw.widgets.DateInputWidget.prototype.getValidity = function () {
621 var isValid = this.validateDate( this.getValue() );
622
623 if ( isValid ) {
624 return $.Deferred().resolve().promise();
625 } else {
626 return $.Deferred().reject().promise();
627 }
628 };
629
630 /**
631 * Sets the 'invalid' flag appropriately.
632 *
633 * @param {boolean} [isValid] Optionally override validation result
634 */
635 mw.widgets.DateInputWidget.prototype.setValidityFlag = function ( isValid ) {
636 var widget = this,
637 setFlag = function ( valid ) {
638 if ( !valid ) {
639 widget.$input.attr( 'aria-invalid', 'true' );
640 } else {
641 widget.$input.removeAttr( 'aria-invalid' );
642 }
643 widget.setFlags( { invalid: !valid } );
644 };
645
646 if ( isValid !== undefined ) {
647 setFlag( isValid );
648 } else {
649 this.getValidity().then( function () {
650 setFlag( true );
651 }, function () {
652 setFlag( false );
653 } );
654 }
655 };
656
657 }( jQuery, mediaWiki ) );