Merge "Hoist validation errors from hidden fields to the top of the form"
[lhc/web/wiklou.git] / resources / src / mediawiki.widgets / mw.widgets.CalendarWidget.js
1 /*!
2 * MediaWiki Widgets – CalendarWidget 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.CalendarWidget object.
12 *
13 * You will most likely want to use mw.widgets.DateInputWidget instead of CalendarWidget directly.
14 *
15 * @class
16 * @extends OO.ui.Widget
17 * @mixins OO.ui.mixin.TabIndexedElement
18 *
19 * @constructor
20 * @param {Object} [config] Configuration options
21 * @cfg {string} [precision='day'] Date precision to use, 'day' or 'month'
22 * @cfg {string|null} [date=null] Day or month date (depending on `precision`), in the format
23 * 'YYYY-MM-DD' or 'YYYY-MM'. When null, the calendar will show today's date, but not select
24 * it.
25 */
26 mw.widgets.CalendarWidget = function MWWCalendarWidget( config ) {
27 // Config initialization
28 config = config || {};
29
30 // Parent constructor
31 mw.widgets.CalendarWidget.parent.call( this, config );
32
33 // Mixin constructors
34 OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$element } ) );
35
36 // Properties
37 this.precision = config.precision || 'day';
38 // Currently selected date (day or month)
39 this.date = null;
40 // Current UI state (date and precision we're displaying right now)
41 this.moment = null;
42 this.displayLayer = this.getDisplayLayers()[ 0 ]; // 'month', 'year', 'duodecade'
43
44 this.$header = $( '<div>' ).addClass( 'mw-widget-calendarWidget-header' );
45 this.$bodyOuterWrapper = $( '<div>' ).addClass( 'mw-widget-calendarWidget-body-outer-wrapper' );
46 this.$bodyWrapper = $( '<div>' ).addClass( 'mw-widget-calendarWidget-body-wrapper' );
47 this.$body = $( '<div>' ).addClass( 'mw-widget-calendarWidget-body' );
48 this.labelButton = new OO.ui.ButtonWidget( {
49 tabIndex: -1,
50 label: '',
51 framed: false,
52 classes: [ 'mw-widget-calendarWidget-labelButton' ]
53 } );
54 this.upButton = new OO.ui.ButtonWidget( {
55 tabIndex: -1,
56 framed: false,
57 icon: 'collapse',
58 classes: [ 'mw-widget-calendarWidget-upButton' ]
59 } );
60 this.prevButton = new OO.ui.ButtonWidget( {
61 tabIndex: -1,
62 framed: false,
63 icon: 'previous',
64 classes: [ 'mw-widget-calendarWidget-prevButton' ]
65 } );
66 this.nextButton = new OO.ui.ButtonWidget( {
67 tabIndex: -1,
68 framed: false,
69 icon: 'next',
70 classes: [ 'mw-widget-calendarWidget-nextButton' ]
71 } );
72
73 // Events
74 this.labelButton.connect( this, { click: 'onUpButtonClick' } );
75 this.upButton.connect( this, { click: 'onUpButtonClick' } );
76 this.prevButton.connect( this, { click: 'onPrevButtonClick' } );
77 this.nextButton.connect( this, { click: 'onNextButtonClick' } );
78 this.$element.on( {
79 focus: this.onFocus.bind( this ),
80 mousedown: this.onClick.bind( this ),
81 keydown: this.onKeyDown.bind( this )
82 } );
83
84 // Initialization
85 this.$element
86 .addClass( 'mw-widget-calendarWidget' )
87 .append( this.$header, this.$bodyOuterWrapper.append( this.$bodyWrapper.append( this.$body ) ) );
88 this.$header.append(
89 this.prevButton.$element,
90 this.nextButton.$element,
91 this.upButton.$element,
92 this.labelButton.$element
93 );
94 this.setDate( config.date !== undefined ? config.date : null );
95 };
96
97 /* Inheritance */
98
99 OO.inheritClass( mw.widgets.CalendarWidget, OO.ui.Widget );
100 OO.mixinClass( mw.widgets.CalendarWidget, OO.ui.mixin.TabIndexedElement );
101
102 /* Events */
103
104 /**
105 * @event change
106 *
107 * A change event is emitted when the chosen date changes.
108 *
109 * @param {string} date Day or month date, in the format 'YYYY-MM-DD' or 'YYYY-MM'
110 */
111
112 /* Methods */
113
114 /**
115 * Get the date format ('YYYY-MM-DD' or 'YYYY-MM', depending on precision), which is used
116 * internally and for dates accepted by #setDate and returned by #getDate.
117 *
118 * @private
119 * @returns {string} Format
120 */
121 mw.widgets.CalendarWidget.prototype.getDateFormat = function () {
122 return {
123 day: 'YYYY-MM-DD',
124 month: 'YYYY-MM'
125 }[ this.precision ];
126 };
127
128 /**
129 * Get the date precision this calendar uses, 'day' or 'month'.
130 *
131 * @private
132 * @returns {string} Precision, 'day' or 'month'
133 */
134 mw.widgets.CalendarWidget.prototype.getPrecision = function () {
135 return this.precision;
136 };
137
138 /**
139 * Get list of possible display layers.
140 *
141 * @private
142 * @returns {string[]} Layers
143 */
144 mw.widgets.CalendarWidget.prototype.getDisplayLayers = function () {
145 return [ 'month', 'year', 'duodecade' ].slice( this.precision === 'month' ? 1 : 0 );
146 };
147
148 /**
149 * Update the calendar.
150 *
151 * @private
152 * @param {string|null} [fade=null] Direction in which to fade out current calendar contents,
153 * 'previous', 'next', 'up' or 'down'; or 'auto', which has the same result as 'previous' or
154 * 'next' depending on whether the current date is later or earlier than the previous.
155 */
156 mw.widgets.CalendarWidget.prototype.updateUI = function ( fade ) {
157 var items, today, selected, currentMonth, currentYear, currentDay, i, needsFade,
158 $bodyWrapper = this.$bodyWrapper;
159
160 if (
161 this.displayLayer === this.previousDisplayLayer &&
162 this.date === this.previousDate &&
163 this.previousMoment &&
164 this.previousMoment.isSame( this.moment, this.precision === 'month' ? 'month' : 'day' )
165 ) {
166 // Already displayed
167 return;
168 }
169
170 if ( fade === 'auto' ) {
171 if ( !this.previousMoment ) {
172 fade = null;
173 } else if ( this.previousMoment.isBefore( this.moment, this.precision === 'month' ? 'month' : 'day' ) ) {
174 fade = 'next';
175 } else if ( this.previousMoment.isAfter( this.moment, this.precision === 'month' ? 'month' : 'day' ) ) {
176 fade = 'previous';
177 } else {
178 fade = null;
179 }
180 }
181
182 items = [];
183 if ( this.$oldBody ) {
184 this.$oldBody.remove();
185 }
186 this.$oldBody = this.$body.addClass( 'mw-widget-calendarWidget-old-body' );
187 // Clone without children
188 this.$body = $( this.$body[ 0 ].cloneNode( false ) )
189 .removeClass( 'mw-widget-calendarWidget-old-body' )
190 .toggleClass( 'mw-widget-calendarWidget-body-month', this.displayLayer === 'month' )
191 .toggleClass( 'mw-widget-calendarWidget-body-year', this.displayLayer === 'year' )
192 .toggleClass( 'mw-widget-calendarWidget-body-duodecade', this.displayLayer === 'duodecade' );
193
194 today = moment();
195 selected = moment( this.getDate(), this.getDateFormat() );
196
197 switch ( this.displayLayer ) {
198 case 'month':
199 this.labelButton.setLabel( this.moment.format( 'MMMM YYYY' ) );
200 this.upButton.toggle( true );
201
202 // First week displayed is the first week spanned by the month, unless it begins on Monday, in
203 // which case first week displayed is the previous week. This makes the calendar "balanced"
204 // and also neatly handles 28-day February sometimes spanning only 4 weeks.
205 currentDay = moment( this.moment ).startOf( 'month' ).subtract( 1, 'day' ).startOf( 'week' );
206
207 // Day-of-week labels. Localisation-independent: works with weeks starting on Saturday, Sunday
208 // or Monday.
209 for ( i = 0; i < 7; i++ ) {
210 items.push(
211 $( '<div>' )
212 .addClass( 'mw-widget-calendarWidget-day-heading' )
213 .text( currentDay.format( 'dd' ) )
214 );
215 currentDay.add( 1, 'day' );
216 }
217 currentDay.subtract( 7, 'days' );
218
219 // Actual calendar month. Always displays 6 weeks, for consistency (months can span 4 to 6
220 // weeks).
221 for ( i = 0; i < 42; i++ ) {
222 items.push(
223 $( '<div>' )
224 .addClass( 'mw-widget-calendarWidget-item mw-widget-calendarWidget-day' )
225 .toggleClass( 'mw-widget-calendarWidget-day-additional', !currentDay.isSame( this.moment, 'month' ) )
226 .toggleClass( 'mw-widget-calendarWidget-day-today', currentDay.isSame( today, 'day' ) )
227 .toggleClass( 'mw-widget-calendarWidget-item-selected', currentDay.isSame( selected, 'day' ) )
228 .text( currentDay.format( 'D' ) )
229 .data( 'date', currentDay.date() )
230 .data( 'month', currentDay.month() )
231 .data( 'year', currentDay.year() )
232 );
233 currentDay.add( 1, 'day' );
234 }
235 break;
236
237 case 'year':
238 this.labelButton.setLabel( this.moment.format( 'YYYY' ) );
239 this.upButton.toggle( true );
240
241 currentMonth = moment( this.moment ).startOf( 'year' );
242 for ( i = 0; i < 12; i++ ) {
243 items.push(
244 $( '<div>' )
245 .addClass( 'mw-widget-calendarWidget-item mw-widget-calendarWidget-month' )
246 .toggleClass( 'mw-widget-calendarWidget-item-selected', currentMonth.isSame( selected, 'month' ) )
247 .text( currentMonth.format( 'MMMM' ) )
248 .data( 'month', currentMonth.month() )
249 );
250 currentMonth.add( 1, 'month' );
251 }
252 // Shuffle the array to display months in columns rather than rows.
253 items = [
254 items[ 0 ], items[ 6 ], // | January | July |
255 items[ 1 ], items[ 7 ], // | February | August |
256 items[ 2 ], items[ 8 ], // | March | September |
257 items[ 3 ], items[ 9 ], // | April | October |
258 items[ 4 ], items[ 10 ], // | May | November |
259 items[ 5 ], items[ 11 ] // | June | December |
260 ];
261 break;
262
263 case 'duodecade':
264 this.labelButton.setLabel( null );
265 this.upButton.toggle( false );
266
267 currentYear = moment( { year: Math.floor( this.moment.year() / 20 ) * 20 } );
268 for ( i = 0; i < 20; i++ ) {
269 items.push(
270 $( '<div>' )
271 .addClass( 'mw-widget-calendarWidget-item mw-widget-calendarWidget-year' )
272 .toggleClass( 'mw-widget-calendarWidget-item-selected', currentYear.isSame( selected, 'year' ) )
273 .text( currentYear.format( 'YYYY' ) )
274 .data( 'year', currentYear.year() )
275 );
276 currentYear.add( 1, 'year' );
277 }
278 break;
279 }
280
281 this.$body.append.apply( this.$body, items );
282
283 $bodyWrapper
284 .removeClass( 'mw-widget-calendarWidget-body-wrapper-fade-up' )
285 .removeClass( 'mw-widget-calendarWidget-body-wrapper-fade-down' )
286 .removeClass( 'mw-widget-calendarWidget-body-wrapper-fade-previous' )
287 .removeClass( 'mw-widget-calendarWidget-body-wrapper-fade-next' );
288
289 needsFade = this.previousDisplayLayer !== this.displayLayer;
290 if ( this.displayLayer === 'month' ) {
291 needsFade = needsFade || !this.moment.isSame( this.previousMoment, 'month' );
292 } else if ( this.displayLayer === 'year' ) {
293 needsFade = needsFade || !this.moment.isSame( this.previousMoment, 'year' );
294 } else if ( this.displayLayer === 'duodecade' ) {
295 needsFade = needsFade || (
296 Math.floor( this.moment.year() / 20 ) * 20 !==
297 Math.floor( this.previousMoment.year() / 20 ) * 20
298 );
299 }
300
301 if ( fade && needsFade ) {
302 this.$oldBody.find( '.mw-widget-calendarWidget-item-selected' )
303 .removeClass( 'mw-widget-calendarWidget-item-selected' );
304 if ( fade === 'previous' || fade === 'up' ) {
305 this.$body.insertBefore( this.$oldBody );
306 } else if ( fade === 'next' || fade === 'down' ) {
307 this.$body.insertAfter( this.$oldBody );
308 }
309 setTimeout( function () {
310 $bodyWrapper.addClass( 'mw-widget-calendarWidget-body-wrapper-fade-' + fade );
311 }.bind( this ), 0 );
312 } else {
313 this.$oldBody.replaceWith( this.$body );
314 }
315
316 this.previousMoment = moment( this.moment );
317 this.previousDisplayLayer = this.displayLayer;
318 this.previousDate = this.date;
319
320 this.$body.on( 'click', this.onBodyClick.bind( this ) );
321 };
322
323 /**
324 * Handle click events on the "up" button, switching to less precise view.
325 *
326 * @private
327 */
328 mw.widgets.CalendarWidget.prototype.onUpButtonClick = function () {
329 var
330 layers = this.getDisplayLayers(),
331 currentLayer = layers.indexOf( this.displayLayer );
332 if ( currentLayer !== layers.length - 1 ) {
333 // One layer up
334 this.displayLayer = layers[ currentLayer + 1 ];
335 this.updateUI( 'up' );
336 } else {
337 this.updateUI();
338 }
339 };
340
341 /**
342 * Handle click events on the "previous" button, switching to previous pane.
343 *
344 * @private
345 */
346 mw.widgets.CalendarWidget.prototype.onPrevButtonClick = function () {
347 switch ( this.displayLayer ) {
348 case 'month':
349 this.moment.subtract( 1, 'month' );
350 break;
351 case 'year':
352 this.moment.subtract( 1, 'year' );
353 break;
354 case 'duodecade':
355 this.moment.subtract( 20, 'years' );
356 break;
357 }
358 this.updateUI( 'previous' );
359 };
360
361 /**
362 * Handle click events on the "next" button, switching to next pane.
363 *
364 * @private
365 */
366 mw.widgets.CalendarWidget.prototype.onNextButtonClick = function () {
367 switch ( this.displayLayer ) {
368 case 'month':
369 this.moment.add( 1, 'month' );
370 break;
371 case 'year':
372 this.moment.add( 1, 'year' );
373 break;
374 case 'duodecade':
375 this.moment.add( 20, 'years' );
376 break;
377 }
378 this.updateUI( 'next' );
379 };
380
381 /**
382 * Handle click events anywhere in the body of the widget, which contains the matrix of days,
383 * months or years to choose. Maybe change the pane or switch to more precise view, depending on
384 * what gets clicked.
385 *
386 * @private
387 */
388 mw.widgets.CalendarWidget.prototype.onBodyClick = function ( e ) {
389 var
390 $target = $( e.target ),
391 layers = this.getDisplayLayers(),
392 currentLayer = layers.indexOf( this.displayLayer );
393 if ( $target.data( 'year' ) !== undefined ) {
394 this.moment.year( $target.data( 'year' ) );
395 }
396 if ( $target.data( 'month' ) !== undefined ) {
397 this.moment.month( $target.data( 'month' ) );
398 }
399 if ( $target.data( 'date' ) !== undefined ) {
400 this.moment.date( $target.data( 'date' ) );
401 }
402 if ( currentLayer === 0 ) {
403 this.setDateFromMoment();
404 this.updateUI( 'auto' );
405 } else {
406 // One layer down
407 this.displayLayer = layers[ currentLayer - 1 ];
408 this.updateUI( 'down' );
409 }
410 };
411
412 /**
413 * Set the date.
414 *
415 * @param {string|null} [date=null] Day or month date, in the format 'YYYY-MM-DD' or 'YYYY-MM'.
416 * When null, the calendar will show today's date, but not select it. When invalid, the date
417 * is not changed.
418 */
419 mw.widgets.CalendarWidget.prototype.setDate = function ( date ) {
420 var mom = date !== null ? moment( date, this.getDateFormat() ) : moment();
421 if ( mom.isValid() ) {
422 this.moment = mom;
423 if ( date !== null ) {
424 this.setDateFromMoment();
425 } else if ( this.date !== null ) {
426 this.date = null;
427 this.emit( 'change', this.date );
428 }
429 this.displayLayer = this.getDisplayLayers()[ 0 ];
430 this.updateUI();
431 }
432 };
433
434 /**
435 * Reset the user interface of this widget to reflect selected date.
436 */
437 mw.widgets.CalendarWidget.prototype.resetUI = function () {
438 this.moment = this.getDate() !== null ? moment( this.getDate(), this.getDateFormat() ) : moment();
439 this.displayLayer = this.getDisplayLayers()[ 0 ];
440 this.updateUI();
441 };
442
443 /**
444 * Set the date from moment object.
445 *
446 * @private
447 */
448 mw.widgets.CalendarWidget.prototype.setDateFromMoment = function () {
449 // Switch to English locale to avoid number formatting. We want the internal value to be
450 // '2015-07-24' and not '٢٠١٥-٠٧-٢٤' even if the UI language is Arabic.
451 var newDate = moment( this.moment ).locale( 'en' ).format( this.getDateFormat() );
452 if ( this.date !== newDate ) {
453 this.date = newDate;
454 this.emit( 'change', this.date );
455 }
456 };
457
458 /**
459 * Get current date, in the format 'YYYY-MM-DD' or 'YYYY-MM', depending on precision. Digits will
460 * not be localised.
461 *
462 * @returns {string|null} Date string
463 */
464 mw.widgets.CalendarWidget.prototype.getDate = function () {
465 return this.date;
466 };
467
468 /**
469 * Handle focus events.
470 *
471 * @private
472 */
473 mw.widgets.CalendarWidget.prototype.onFocus = function () {
474 this.displayLayer = this.getDisplayLayers()[ 0 ];
475 this.updateUI( 'down' );
476 };
477
478 /**
479 * Handle mouse click events.
480 *
481 * @private
482 * @param {jQuery.Event} e Mouse click event
483 */
484 mw.widgets.CalendarWidget.prototype.onClick = function ( e ) {
485 if ( !this.isDisabled() && e.which === 1 ) {
486 // Prevent unintended focussing
487 return false;
488 }
489 };
490
491 /**
492 * Handle key down events.
493 *
494 * @private
495 * @param {jQuery.Event} e Key down event
496 */
497 mw.widgets.CalendarWidget.prototype.onKeyDown = function ( e ) {
498 var
499 /*jshint -W024*/
500 dir = OO.ui.Element.static.getDir( this.$element ),
501 /*jshint +W024*/
502 nextDirectionKey = dir === 'ltr' ? OO.ui.Keys.RIGHT : OO.ui.Keys.LEFT,
503 prevDirectionKey = dir === 'ltr' ? OO.ui.Keys.LEFT : OO.ui.Keys.RIGHT,
504 changed = true;
505
506 if ( !this.isDisabled() ) {
507 switch ( e.which ) {
508 case prevDirectionKey:
509 this.moment.subtract( 1, this.precision === 'month' ? 'month' : 'day' );
510 break;
511 case nextDirectionKey:
512 this.moment.add( 1, this.precision === 'month' ? 'month' : 'day' );
513 break;
514 case OO.ui.Keys.UP:
515 this.moment.subtract( 1, this.precision === 'month' ? 'month' : 'week' );
516 break;
517 case OO.ui.Keys.DOWN:
518 this.moment.add( 1, this.precision === 'month' ? 'month' : 'week' );
519 break;
520 case OO.ui.Keys.PAGEUP:
521 this.moment.subtract( 1, this.precision === 'month' ? 'year' : 'month' );
522 break;
523 case OO.ui.Keys.PAGEDOWN:
524 this.moment.add( 1, this.precision === 'month' ? 'year' : 'month' );
525 break;
526 default:
527 changed = false;
528 break;
529 }
530
531 if ( changed ) {
532 this.displayLayer = this.getDisplayLayers()[ 0 ];
533 this.setDateFromMoment();
534 this.updateUI( 'auto' );
535 return false;
536 }
537 }
538 };
539
540 }( jQuery, mediaWiki ) );