Merge "Replace Linker::link() with LinkRenderer in includes directory"
[lhc/web/wiklou.git] / resources / src / mediawiki / mediawiki.notification.js
1 ( function ( mw, $ ) {
2 'use strict';
3
4 var notification,
5 // The #mw-notification-area div that all notifications are contained inside.
6 $area,
7 // Number of open notification boxes at any time
8 openNotificationCount = 0,
9 isPageReady = false,
10 preReadyNotifQueue = [],
11 rAF = window.requestAnimationFrame || setTimeout;
12
13 /**
14 * A Notification object for 1 message.
15 *
16 * The underscore in the name is to avoid a bug <https://github.com/senchalabs/jsduck/issues/304>.
17 * It is not part of the actual class name.
18 *
19 * The constructor is not publicly accessible; use mw.notification#notify instead.
20 * This does not insert anything into the document (see #start).
21 *
22 * @class mw.Notification_
23 * @alternateClassName mw.Notification
24 * @constructor
25 * @private
26 * @param {mw.Message|jQuery|HTMLElement|string} message
27 * @param {Object} options
28 */
29 function Notification( message, options ) {
30 var $notification, $notificationContent;
31
32 $notification = $( '<div class="mw-notification"></div>' )
33 .data( 'mw.notification', this )
34 .addClass( options.autoHide ? 'mw-notification-autohide' : 'mw-notification-noautohide' );
35
36 if ( options.tag ) {
37 // Sanitize options.tag before it is used by any code. (Including Notification class methods)
38 options.tag = options.tag.replace( /[ _\-]+/g, '-' ).replace( /[^\-a-z0-9]+/ig, '' );
39 if ( options.tag ) {
40 $notification.addClass( 'mw-notification-tag-' + options.tag );
41 } else {
42 delete options.tag;
43 }
44 }
45
46 if ( options.type ) {
47 // Sanitize options.type
48 options.type = options.type.replace( /[ _\-]+/g, '-' ).replace( /[^\-a-z0-9]+/ig, '' );
49 $notification.addClass( 'mw-notification-type-' + options.type );
50 }
51
52 if ( options.title ) {
53 $( '<div class="mw-notification-title"></div>' )
54 .text( options.title )
55 .appendTo( $notification );
56 }
57
58 $notificationContent = $( '<div class="mw-notification-content"></div>' );
59
60 if ( typeof message === 'object' ) {
61 // Handle mw.Message objects separately from DOM nodes and jQuery objects
62 if ( message instanceof mw.Message ) {
63 $notificationContent.html( message.parse() );
64 } else {
65 $notificationContent.append( message );
66 }
67 } else {
68 $notificationContent.text( message );
69 }
70
71 $notificationContent.appendTo( $notification );
72
73 // Private state parameters, meant for internal use only
74 // isOpen: Set to true after .start() is called to avoid double calls.
75 // Set back to false after .close() to avoid duplicating the close animation.
76 // isPaused: false after .resume(), true after .pause(). Avoids duplicating or breaking the hide timeouts.
77 // Set to true initially so .start() can call .resume().
78 // message: The message passed to the notification. Unused now but may be used in the future
79 // to stop replacement of a tagged notification with another notification using the same message.
80 // options: The options passed to the notification with a little sanitization. Used by various methods.
81 // $notification: jQuery object containing the notification DOM node.
82 this.isOpen = false;
83 this.isPaused = true;
84 this.message = message;
85 this.options = options;
86 this.$notification = $notification;
87 }
88
89 /**
90 * Start the notification. Called automatically by mw.notification#notify
91 * (possibly asynchronously on document-ready).
92 *
93 * This inserts the notification into the page, closes any matching tagged notifications,
94 * handles the fadeIn animations and replacement transitions, and starts autoHide timers.
95 *
96 * @private
97 */
98 Notification.prototype.start = function () {
99 var options, $notification, $tagMatches, autohideCount;
100
101 $area.show();
102
103 if ( this.isOpen ) {
104 return;
105 }
106
107 this.isOpen = true;
108 openNotificationCount++;
109
110 options = this.options;
111 $notification = this.$notification;
112
113 if ( options.tag ) {
114 // Find notifications with the same tag
115 $tagMatches = $area.find( '.mw-notification-tag-' + options.tag );
116 }
117
118 // If we found existing notification with the same tag, replace them
119 if ( options.tag && $tagMatches.length ) {
120
121 // While there can be only one "open" notif with a given tag, there can be several
122 // matches here because they remain in the DOM until the animation is finished.
123 $tagMatches.each( function () {
124 var notif = $( this ).data( 'mw.notification' );
125 if ( notif && notif.isOpen ) {
126 // Detach from render flow with position absolute so that the new tag can
127 // occupy its space instead.
128 notif.$notification
129 .css( {
130 position: 'absolute',
131 width: notif.$notification.width()
132 } )
133 .css( notif.$notification.position() )
134 .addClass( 'mw-notification-replaced' );
135 notif.close();
136 }
137 } );
138
139 $notification
140 .insertBefore( $tagMatches.first() )
141 .addClass( 'mw-notification-visible' );
142 } else {
143 $area.append( $notification );
144 rAF( function () {
145 // This frame renders the element in the area (invisible)
146 rAF( function () {
147 $notification.addClass( 'mw-notification-visible' );
148 } );
149 } );
150 }
151
152 // By default a notification is paused.
153 // If this notification is within the first {autoHideLimit} notifications then
154 // start the auto-hide timer as soon as it's created.
155 autohideCount = $area.find( '.mw-notification-autohide' ).length;
156 if ( autohideCount <= notification.autoHideLimit ) {
157 this.resume();
158 }
159 };
160
161 /**
162 * Pause any running auto-hide timer for this notification
163 */
164 Notification.prototype.pause = function () {
165 if ( this.isPaused ) {
166 return;
167 }
168 this.isPaused = true;
169
170 if ( this.timeout ) {
171 clearTimeout( this.timeout );
172 delete this.timeout;
173 }
174 };
175
176 /**
177 * Start autoHide timer if not already started.
178 * Does nothing if autoHide is disabled.
179 * Either to resume from pause or to make the first start.
180 */
181 Notification.prototype.resume = function () {
182 var notif = this;
183 if ( !notif.isPaused ) {
184 return;
185 }
186 // Start any autoHide timeouts
187 if ( notif.options.autoHide ) {
188 notif.isPaused = false;
189 notif.timeout = setTimeout( function () {
190 // Already finished, so don't try to re-clear it
191 delete notif.timeout;
192 notif.close();
193 }, notification.autoHideSeconds * 1000 );
194 }
195 };
196
197 /**
198 * Close the notification.
199 */
200 Notification.prototype.close = function () {
201 var notif = this;
202
203 if ( !this.isOpen ) {
204 return;
205 }
206
207 this.isOpen = false;
208 openNotificationCount--;
209
210 // Clear any remaining timeout on close
211 this.pause();
212
213 // Remove the mw-notification-autohide class from the notification to avoid
214 // having a half-closed notification counted as a notification to resume
215 // when handling {autoHideLimit}.
216 this.$notification.removeClass( 'mw-notification-autohide' );
217
218 // Now that a notification is being closed. Start auto-hide timers for any
219 // notification that has now become one of the first {autoHideLimit} notifications.
220 notification.resume();
221
222 rAF( function () {
223 notif.$notification.removeClass( 'mw-notification-visible' );
224
225 setTimeout( function () {
226 if ( openNotificationCount === 0 ) {
227 // Hide the area after the last notification closes. Otherwise, the padding on
228 // the area can be obscure content, despite the area being empty/invisible (T54659). // FIXME
229 $area.hide();
230 notif.$notification.remove();
231 } else {
232 notif.$notification.slideUp( 'fast', function () {
233 $( this ).remove();
234 } );
235 }
236 }, 500 );
237 } );
238 };
239
240 /**
241 * Helper function, take a list of notification divs and call
242 * a function on the Notification instance attached to them.
243 *
244 * @private
245 * @static
246 * @param {jQuery} $notifications A jQuery object containing notification divs
247 * @param {string} fn The name of the function to call on the Notification instance
248 */
249 function callEachNotification( $notifications, fn ) {
250 $notifications.each( function () {
251 var notif = $( this ).data( 'mw.notification' );
252 if ( notif ) {
253 notif[ fn ]();
254 }
255 } );
256 }
257
258 /**
259 * Initialisation.
260 * Must only be called once, and not before the document is ready.
261 *
262 * @ignore
263 */
264 function init() {
265 var offset, $window = $( window );
266
267 $area = $( '<div id="mw-notification-area" class="mw-notification-area mw-notification-area-layout"></div>' )
268 // Pause auto-hide timers when the mouse is in the notification area.
269 .on( {
270 mouseenter: notification.pause,
271 mouseleave: notification.resume
272 } )
273 // When clicking on a notification close it.
274 .on( 'click', '.mw-notification', function () {
275 var notif = $( this ).data( 'mw.notification' );
276 if ( notif ) {
277 notif.close();
278 }
279 } )
280 // Stop click events from <a> tags from propogating to prevent clicking.
281 // on links from hiding a notification.
282 .on( 'click', 'a', function ( e ) {
283 e.stopPropagation();
284 } );
285
286 // Prepend the notification area to the content area and save it's object.
287 mw.util.$content.prepend( $area );
288 offset = $area.offset();
289 $area.hide();
290
291 function updateAreaMode() {
292 var isFloating = $window.scrollTop() > offset.top;
293 $area
294 .toggleClass( 'mw-notification-area-floating', isFloating )
295 .toggleClass( 'mw-notification-area-layout', !isFloating );
296 }
297
298 $window.on( 'scroll', updateAreaMode );
299
300 // Initial mode
301 updateAreaMode();
302 }
303
304 /**
305 * @class mw.notification
306 * @singleton
307 */
308 notification = {
309 /**
310 * Pause auto-hide timers for all notifications.
311 * Notifications will not auto-hide until resume is called.
312 *
313 * @see mw.Notification#pause
314 */
315 pause: function () {
316 callEachNotification(
317 $area.children( '.mw-notification' ),
318 'pause'
319 );
320 },
321
322 /**
323 * Resume any paused auto-hide timers from the beginning.
324 * Only the first #autoHideLimit timers will be resumed.
325 */
326 resume: function () {
327 callEachNotification(
328 // Only call resume on the first #autoHideLimit notifications.
329 // Exclude noautohide notifications to avoid bugs where #autoHideLimit
330 // `{ autoHide: false }` notifications are at the start preventing any
331 // auto-hide notifications from being autohidden.
332 $area.children( '.mw-notification-autohide' ).slice( 0, notification.autoHideLimit ),
333 'resume'
334 );
335 },
336
337 /**
338 * Display a notification message to the user.
339 *
340 * @param {HTMLElement|HTMLElement[]|jQuery|mw.Message|string} message
341 * @param {Object} options The options to use for the notification.
342 * See #defaults for details.
343 * @return {mw.Notification} Notification object
344 */
345 notify: function ( message, options ) {
346 var notif;
347 options = $.extend( {}, notification.defaults, options );
348
349 notif = new Notification( message, options );
350
351 if ( isPageReady ) {
352 notif.start();
353 } else {
354 preReadyNotifQueue.push( notif );
355 }
356
357 return notif;
358 },
359
360 /**
361 * @property {Object}
362 * The defaults for #notify options parameter.
363 *
364 * - autoHide:
365 * A boolean indicating whether the notifification should automatically
366 * be hidden after shown. Or if it should persist.
367 *
368 * - tag:
369 * An optional string. When a notification is tagged only one message
370 * with that tag will be displayed. Trying to display a new notification
371 * with the same tag as one already being displayed will cause the other
372 * notification to be closed and this new notification to open up inside
373 * the same place as the previous notification.
374 *
375 * - title:
376 * An optional title for the notification. Will be displayed above the
377 * content. Usually in bold.
378 *
379 * - type:
380 * An optional string for the type of the message used for styling:
381 * Examples: 'info', 'warn', 'error'.
382 */
383 defaults: {
384 autoHide: true,
385 tag: false,
386 title: undefined,
387 type: false
388 },
389
390 /**
391 * @property {number}
392 * Number of seconds to wait before auto-hiding notifications.
393 */
394 autoHideSeconds: 5,
395
396 /**
397 * @property {number}
398 * Maximum number of notifications to count down auto-hide timers for.
399 * Only the first #autoHideLimit notifications being displayed will
400 * auto-hide. Any notifications further down in the list will only start
401 * counting down to auto-hide after the first few messages have closed.
402 *
403 * This basically represents the number of notifications the user should
404 * be able to process in #autoHideSeconds time.
405 */
406 autoHideLimit: 3
407 };
408
409 $( function () {
410 var notif;
411
412 init();
413
414 // Handle pre-ready queue.
415 isPageReady = true;
416 while ( preReadyNotifQueue.length ) {
417 notif = preReadyNotifQueue.shift();
418 notif.start();
419 }
420 } );
421
422 mw.notification = notification;
423
424 }( mediaWiki, jQuery ) );