Merge "Add tests for WikiMap and WikiReference"
[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, 'previous',
153 * 'next' or 'up'
154 * @returns {string} Format
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 items = [];
171 if ( this.$oldBody ) {
172 this.$oldBody.remove();
173 }
174 this.$oldBody = this.$body.addClass( 'mw-widget-calendarWidget-old-body' );
175 // Clone without children
176 this.$body = $( this.$body[ 0 ].cloneNode( false ) )
177 .removeClass( 'mw-widget-calendarWidget-old-body' )
178 .toggleClass( 'mw-widget-calendarWidget-body-month', this.displayLayer === 'month' )
179 .toggleClass( 'mw-widget-calendarWidget-body-year', this.displayLayer === 'year' )
180 .toggleClass( 'mw-widget-calendarWidget-body-duodecade', this.displayLayer === 'duodecade' );
181
182 today = moment();
183 selected = moment( this.getDate(), this.getDateFormat() );
184
185 switch ( this.displayLayer ) {
186 case 'month':
187 this.labelButton.setLabel( this.moment.format( 'MMMM YYYY' ) );
188 this.upButton.toggle( true );
189
190 // First week displayed is the first week spanned by the month, unless it begins on Monday, in
191 // which case first week displayed is the previous week. This makes the calendar "balanced"
192 // and also neatly handles 28-day February sometimes spanning only 4 weeks.
193 currentDay = moment( this.moment ).startOf( 'month' ).subtract( 1, 'day' ).startOf( 'week' );
194
195 // Day-of-week labels. Localisation-independent: works with weeks starting on Saturday, Sunday
196 // or Monday.
197 for ( i = 0; i < 7; i++ ) {
198 items.push(
199 $( '<div>' )
200 .addClass( 'mw-widget-calendarWidget-day-heading' )
201 .text( currentDay.format( 'dd' ) )
202 );
203 currentDay.add( 1, 'day' );
204 }
205 currentDay.subtract( 7, 'days' );
206
207 // Actual calendar month. Always displays 6 weeks, for consistency (months can span 4 to 6
208 // weeks).
209 for ( i = 0; i < 42; i++ ) {
210 items.push(
211 $( '<div>' )
212 .addClass( 'mw-widget-calendarWidget-item mw-widget-calendarWidget-day' )
213 .toggleClass( 'mw-widget-calendarWidget-day-additional', !currentDay.isSame( this.moment, 'month' ) )
214 .toggleClass( 'mw-widget-calendarWidget-day-today', currentDay.isSame( today, 'day' ) )
215 .toggleClass( 'mw-widget-calendarWidget-item-selected', currentDay.isSame( selected, 'day' ) )
216 .text( currentDay.format( 'D' ) )
217 .data( 'date', currentDay.date() )
218 .data( 'month', currentDay.month() )
219 .data( 'year', currentDay.year() )
220 );
221 currentDay.add( 1, 'day' );
222 }
223 break;
224
225 case 'year':
226 this.labelButton.setLabel( this.moment.format( 'YYYY' ) );
227 this.upButton.toggle( true );
228
229 currentMonth = moment( this.moment ).startOf( 'year' );
230 for ( i = 0; i < 12; i++ ) {
231 items.push(
232 $( '<div>' )
233 .addClass( 'mw-widget-calendarWidget-item mw-widget-calendarWidget-month' )
234 .toggleClass( 'mw-widget-calendarWidget-item-selected', currentMonth.isSame( selected, 'month' ) )
235 .text( currentMonth.format( 'MMMM' ) )
236 .data( 'month', currentMonth.month() )
237 );
238 currentMonth.add( 1, 'month' );
239 }
240 // Shuffle the array to display months in columns rather than rows.
241 items = [
242 items[ 0 ], items[ 6 ], // | January | July |
243 items[ 1 ], items[ 7 ], // | February | August |
244 items[ 2 ], items[ 8 ], // | March | September |
245 items[ 3 ], items[ 9 ], // | April | October |
246 items[ 4 ], items[ 10 ], // | May | November |
247 items[ 5 ], items[ 11 ] // | June | December |
248 ];
249 break;
250
251 case 'duodecade':
252 this.labelButton.setLabel( null );
253 this.upButton.toggle( false );
254
255 currentYear = moment( { year: Math.floor( this.moment.year() / 20 ) * 20 } );
256 for ( i = 0; i < 20; i++ ) {
257 items.push(
258 $( '<div>' )
259 .addClass( 'mw-widget-calendarWidget-item mw-widget-calendarWidget-year' )
260 .toggleClass( 'mw-widget-calendarWidget-item-selected', currentYear.isSame( selected, 'year' ) )
261 .text( currentYear.format( 'YYYY' ) )
262 .data( 'year', currentYear.year() )
263 );
264 currentYear.add( 1, 'year' );
265 }
266 break;
267 }
268
269 this.$body.append.apply( this.$body, items );
270
271 $bodyWrapper
272 .removeClass( 'mw-widget-calendarWidget-body-wrapper-fade-up' )
273 .removeClass( 'mw-widget-calendarWidget-body-wrapper-fade-down' )
274 .removeClass( 'mw-widget-calendarWidget-body-wrapper-fade-previous' )
275 .removeClass( 'mw-widget-calendarWidget-body-wrapper-fade-next' );
276
277 needsFade = this.previousDisplayLayer !== this.displayLayer;
278 if ( this.displayLayer === 'month' ) {
279 needsFade = needsFade || !this.moment.isSame( this.previousMoment, 'month' );
280 } else if ( this.displayLayer === 'year' ) {
281 needsFade = needsFade || !this.moment.isSame( this.previousMoment, 'year' );
282 } else if ( this.displayLayer === 'duodecade' ) {
283 needsFade = needsFade || (
284 Math.floor( this.moment.year() / 20 ) * 20 !==
285 Math.floor( this.previousMoment.year() / 20 ) * 20
286 );
287 }
288
289 if ( fade && needsFade ) {
290 this.$oldBody.find( '.mw-widget-calendarWidget-item-selected' )
291 .removeClass( 'mw-widget-calendarWidget-item-selected' );
292 if ( fade === 'previous' || fade === 'up' ) {
293 this.$body.insertBefore( this.$oldBody );
294 } else if ( fade === 'next' || fade === 'down' ) {
295 this.$body.insertAfter( this.$oldBody );
296 }
297 setTimeout( function () {
298 $bodyWrapper.addClass( 'mw-widget-calendarWidget-body-wrapper-fade-' + fade );
299 }.bind( this ), 0 );
300 } else {
301 this.$oldBody.replaceWith( this.$body );
302 }
303
304 this.previousMoment = moment( this.moment );
305 this.previousDisplayLayer = this.displayLayer;
306 this.previousDate = this.date;
307
308 this.$body.on( 'click', this.onBodyClick.bind( this ) );
309 };
310
311 /**
312 * Handle click events on the "up" button, switching to less precise view.
313 *
314 * @private
315 */
316 mw.widgets.CalendarWidget.prototype.onUpButtonClick = function () {
317 var
318 layers = this.getDisplayLayers(),
319 currentLayer = layers.indexOf( this.displayLayer );
320 if ( currentLayer !== layers.length - 1 ) {
321 // One layer up
322 this.displayLayer = layers[ currentLayer + 1 ];
323 this.updateUI( 'up' );
324 } else {
325 this.updateUI();
326 }
327 };
328
329 /**
330 * Handle click events on the "previous" button, switching to previous pane.
331 *
332 * @private
333 */
334 mw.widgets.CalendarWidget.prototype.onPrevButtonClick = function () {
335 switch ( this.displayLayer ) {
336 case 'month':
337 this.moment.subtract( 1, 'month' );
338 break;
339 case 'year':
340 this.moment.subtract( 1, 'year' );
341 break;
342 case 'duodecade':
343 this.moment.subtract( 20, 'years' );
344 break;
345 }
346 this.updateUI( 'previous' );
347 };
348
349 /**
350 * Handle click events on the "next" button, switching to next pane.
351 *
352 * @private
353 */
354 mw.widgets.CalendarWidget.prototype.onNextButtonClick = function () {
355 switch ( this.displayLayer ) {
356 case 'month':
357 this.moment.add( 1, 'month' );
358 break;
359 case 'year':
360 this.moment.add( 1, 'year' );
361 break;
362 case 'duodecade':
363 this.moment.add( 20, 'years' );
364 break;
365 }
366 this.updateUI( 'next' );
367 };
368
369 /**
370 * Handle click events anywhere in the body of the widget, which contains the matrix of days,
371 * months or years to choose. Maybe change the pane or switch to more precise view, depending on
372 * what gets clicked.
373 *
374 * @private
375 */
376 mw.widgets.CalendarWidget.prototype.onBodyClick = function ( e ) {
377 var
378 previousMoment = moment( this.moment ),
379 $target = $( e.target ),
380 layers = this.getDisplayLayers(),
381 currentLayer = layers.indexOf( this.displayLayer );
382 if ( $target.data( 'year' ) !== undefined ) {
383 this.moment.year( $target.data( 'year' ) );
384 }
385 if ( $target.data( 'month' ) !== undefined ) {
386 this.moment.month( $target.data( 'month' ) );
387 }
388 if ( $target.data( 'date' ) !== undefined ) {
389 this.moment.date( $target.data( 'date' ) );
390 }
391 if ( currentLayer === 0 ) {
392 this.setDateFromMoment();
393 this.updateUI(
394 this.precision === 'day' && this.moment.isBefore( previousMoment, 'month' ) ? 'previous' :
395 this.precision === 'day' && this.moment.isAfter( previousMoment, 'month' ) ? 'next' : null
396 );
397 } else {
398 // One layer down
399 this.displayLayer = layers[ currentLayer - 1 ];
400 this.updateUI( 'down' );
401 }
402 };
403
404 /**
405 * Set the date.
406 *
407 * @param {string|null} [date=null] Day or month date, in the format 'YYYY-MM-DD' or 'YYYY-MM'.
408 * When null, the calendar will show today's date, but not select it. When invalid, the date
409 * is not changed.
410 */
411 mw.widgets.CalendarWidget.prototype.setDate = function ( date ) {
412 var mom = date !== null ? moment( date, this.getDateFormat() ) : moment();
413 if ( mom.isValid() ) {
414 this.moment = mom;
415 if ( date !== null ) {
416 this.setDateFromMoment();
417 } else if ( this.date !== null ) {
418 this.date = null;
419 this.emit( 'change', this.date );
420 }
421 this.displayLayer = this.getDisplayLayers()[ 0 ];
422 this.updateUI();
423 }
424 };
425
426 /**
427 * Reset the user interface of this widget to reflect selected date.
428 */
429 mw.widgets.CalendarWidget.prototype.resetUI = function () {
430 this.moment = moment( this.getDate(), this.getDateFormat() );
431 this.displayLayer = this.getDisplayLayers()[ 0 ];
432 this.updateUI();
433 };
434
435 /**
436 * Set the date from moment object.
437 *
438 * @private
439 */
440 mw.widgets.CalendarWidget.prototype.setDateFromMoment = function () {
441 // Switch to English locale to avoid number formatting. We want the internal value to be
442 // '2015-07-24' and not '٢٠١٥-٠٧-٢٤' even if the UI language is Arabic.
443 var newDate = moment( this.moment ).locale( 'en' ).format( this.getDateFormat() );
444 if ( this.date !== newDate ) {
445 this.date = newDate;
446 this.emit( 'change', this.date );
447 }
448 };
449
450 /**
451 * Get current date, in the format 'YYYY-MM-DD' or 'YYYY-MM', depending on precision. Digits will
452 * not be localised.
453 *
454 * @returns {string|null} Date string
455 */
456 mw.widgets.CalendarWidget.prototype.getDate = function () {
457 return this.date;
458 };
459
460 /**
461 * Handle focus events.
462 *
463 * @private
464 */
465 mw.widgets.CalendarWidget.prototype.onFocus = function () {
466 this.displayLayer = this.getDisplayLayers()[ 0 ];
467 this.updateUI( 'down' );
468 };
469
470 /**
471 * Handle mouse click events.
472 *
473 * @private
474 * @param {jQuery.Event} e Mouse click event
475 */
476 mw.widgets.CalendarWidget.prototype.onClick = function ( e ) {
477 if ( !this.isDisabled() && e.which === 1 ) {
478 // Prevent unintended focussing
479 return false;
480 }
481 };
482
483 /**
484 * Handle key down events.
485 *
486 * @private
487 * @param {jQuery.Event} e Key down event
488 */
489 mw.widgets.CalendarWidget.prototype.onKeyDown = function ( e ) {
490 var
491 /*jshint -W024*/
492 dir = OO.ui.Element.static.getDir( this.$element ),
493 /*jshint +W024*/
494 nextDirectionKey = dir === 'ltr' ? OO.ui.Keys.RIGHT : OO.ui.Keys.LEFT,
495 prevDirectionKey = dir === 'ltr' ? OO.ui.Keys.LEFT : OO.ui.Keys.RIGHT,
496 updateInDirection = null;
497
498 if ( !this.isDisabled() ) {
499 switch ( e.which ) {
500 case prevDirectionKey:
501 this.moment.subtract( 1, this.precision === 'month' ? 'month' : 'day' );
502 updateInDirection = 'previous';
503 break;
504 case nextDirectionKey:
505 this.moment.add( 1, this.precision === 'month' ? 'month' : 'day' );
506 updateInDirection = 'next';
507 break;
508 case OO.ui.Keys.UP:
509 this.moment.subtract( 1, this.precision === 'month' ? 'month' : 'week' );
510 updateInDirection = 'previous';
511 break;
512 case OO.ui.Keys.DOWN:
513 this.moment.add( 1, this.precision === 'month' ? 'month' : 'week' );
514 updateInDirection = 'next';
515 break;
516 case OO.ui.Keys.PAGEUP:
517 this.moment.subtract( 1, this.precision === 'month' ? 'year' : 'month' );
518 updateInDirection = 'previous';
519 break;
520 case OO.ui.Keys.PAGEDOWN:
521 this.moment.add( 1, this.precision === 'month' ? 'year' : 'month' );
522 updateInDirection = 'next';
523 break;
524 }
525
526 if ( updateInDirection ) {
527 this.displayLayer = this.getDisplayLayers()[ 0 ];
528 this.setDateFromMoment();
529 this.updateUI( updateInDirection );
530 return false;
531 }
532 }
533 };
534
535 }( jQuery, mediaWiki ) );