Debian Codegraph @

resources/src/mediawiki.notification/notification.js

raw symbols SCIP
1 ( function () {
2 'use strict';
3
4 let notification = null,
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 const preReadyNotifQueue = [];
11
12 /**
13 * @classdesc Describes a notification. See [mw.notification module]{@link mw.notification}. A Notification object for 1 message.
14 *
15 * The constructor is not publicly accessible; use [mw.notification.notify]{@link mw.notification} instead.
16 * This does not insert anything into the document. To add to document use
17 * [mw.notification.notify]{@link mw.notification#notify}.
18 *
19 * @class Notification
20 * @global
21 * @hideconstructor
22 * @param {mw.Message|jQuery|HTMLElement|string} message
23 * @param {mw.notification.NotificationOptions} options
24 */
25 function Notification( message, options ) {
26
27 const $notification = $( '<div>' )
28 .data( 'mw-notification', this )
29 .attr( 'role', 'status' )
30 .addClass( [
31 'mw-notification',
32 options.autoHide ? 'mw-notification-autohide' : 'mw-notification-noautohide'
33 ] );
34
35 if ( options.tag ) {
36 // Sanitize options.tag before it is used by any code. (Including Notification class methods)
37 options.tag = options.tag.replace( /[ _-]+/g, '-' ).replace( /[^-a-z0-9]+/ig, '' );
38 if ( options.tag ) {
39 // eslint-disable-next-line mediawiki/class-doc
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 // The following classes are used here:
50 // * mw-notification-type-error
51 // * mw-notification-type-warn
52 $notification.addClass( 'mw-notification-type-' + options.type );
53 }
54
55 if ( options.title ) {
56 $( '<div>' )
57 .addClass( 'mw-notification-title' )
58 .text( options.title )
59 .appendTo( $notification );
60 }
61
62 if ( options.id ) {
63 $notification.attr( 'id', options.id );
64 }
65
66 if ( options.classes ) {
67 // eslint-disable-next-line mediawiki/class-doc
68 $notification.addClass( options.classes );
69 }
70
71 const $notificationContent = $( '<div>' ).addClass( 'mw-notification-content' );
72
73 if ( typeof message === 'object' ) {
74 // Handle mw.Message objects separately from DOM nodes and jQuery objects
75 if ( message instanceof mw.Message ) {
76 $notificationContent.html( message.parse() );
77 } else {
78 $notificationContent.append( message );
79 }
80 } else {
81 $notificationContent.text( message );
82 }
83
84 $notificationContent.appendTo( $notification );
85
86 // Private state parameters, meant for internal use only
87 // autoHideSeconds: String alias for number of seconds for timeout of auto-hiding notifications.
88 // isOpen: Set to true after .start() is called to avoid double calls.
89 // Set back to false after .close() to avoid duplicating the close animation.
90 // isPaused: false after .resume(), true after .pause(). Avoids duplicating or breaking the hide timeouts.
91 // Set to true initially so .start() can call .resume().
92 // message: The message passed to the notification. Unused now but may be used in the future
93 // to stop replacement of a tagged notification with another notification using the same message.
94 // options: The options passed to the notification with a little sanitization. Used by various methods.
95 // $notification: jQuery object containing the notification DOM node.
96 // timeout: Holds appropriate methods to set/clear timeouts
97 this.autoHideSeconds = options.autoHideSeconds &&
98 notification.autoHideSeconds[ options.autoHideSeconds ] ||
99 notification.autoHideSeconds.short;
100 this.isOpen = false;
101 this.isPaused = true;
102 this.message = message;
103 this.options = options;
104 this.$notification = $notification;
105 if ( options.visibleTimeout ) {
106 this.timeout = require( 'mediawiki.visibleTimeout' );
107 } else {
108 this.timeout = {
109 set: setTimeout,
110 clear: clearTimeout
111 };
112 }
113 }
114
115 /**
116 * Start the notification. Called automatically by mw.notification#notify
117 * (possibly asynchronously on document-ready).
118 *
119 * This inserts the notification into the page, closes any matching tagged notifications,
120 * handles the fadeIn animations and replacement transitions, and starts autoHide timers.
121 *
122 * @private
123 */
124 Notification.prototype.start = function () {
125 $area.css( 'display', '' );
126
127 if ( this.isOpen ) {
128 return;
129 }
130
131 this.isOpen = true;
132 openNotificationCount++;
133
134 const options = this.options;
135 const $notification = this.$notification;
136
137 let $tagMatches;
138 if ( options.tag ) {
139 // Find notifications with the same tag
140 $tagMatches = $area.find( '.mw-notification-tag-' + options.tag );
141 }
142
143 // If we found existing notification with the same tag, replace them
144 if ( options.tag && $tagMatches.length ) {
145
146 // While there can be only one "open" notif with a given tag, there can be several
147 // matches here because they remain in the DOM until the animation is finished.
148 $tagMatches.each( function () {
149 const notif = $( this ).data( 'mw-notification' );
150 if ( notif && notif.isOpen ) {
151 // Detach from render flow with position absolute so that the new tag can
152 // occupy its space instead.
153 notif.$notification
154 .css( {
155 position: 'absolute',
156 width: notif.$notification.width()
157 } )
158 .css( notif.$notification.position() )
159 .addClass( 'mw-notification-replaced' );
160 notif.close();
161 }
162 } );
163
164 $notification
165 .insertBefore( $tagMatches.first() )
166 .addClass( 'mw-notification-visible' );
167 } else {
168 $area.append( $notification );
169 requestAnimationFrame( () => {
170 // This frame renders the element in the area (invisible)
171 requestAnimationFrame( () => {
172 $notification.addClass( 'mw-notification-visible' );
173 } );
174 } );
175 }
176
177 // By default a notification is paused.
178 // If this notification is within the first {autoHideLimit} notifications then
179 // start the auto-hide timer as soon as it's created.
180 const autohideCount = $area.find( '.mw-notification-autohide' ).length;
181 if ( autohideCount <= notification.autoHideLimit ) {
182 this.resume();
183 }
184 };
185
186 /**
187 * Pause any running auto-hide timer for this notification.
188 *
189 * @memberof Notification
190 */
191 Notification.prototype.pause = function () {
192 if ( this.isPaused ) {
193 return;
194 }
195 this.isPaused = true;
196
197 if ( this.timeoutId ) {
198 this.timeout.clear( this.timeoutId );
199 delete this.timeoutId;
200 }
201 };
202
203 /**
204 * Start autoHide timer if not already started.
205 * Does nothing if autoHide is disabled.
206 * Either to resume from pause or to make the first start.
207 *
208 * @memberof Notification
209 */
210 Notification.prototype.resume = function () {
211 const notif = this;
212
213 if ( !notif.isPaused ) {
214 return;
215 }
216 // Start any autoHide timeouts
217 if ( notif.options.autoHide ) {
218 notif.isPaused = false;
219 notif.timeoutId = notif.timeout.set( () => {
220 // Already finished, so don't try to re-clear it
221 delete notif.timeoutId;
222 notif.close();
223 }, this.autoHideSeconds * 1000 );
224 }
225 };
226
227 /**
228 * Close the notification.
229 *
230 * @memberof Notification
231 */
232 Notification.prototype.close = function () {
233 const notif = this;
234
235 if ( !this.isOpen ) {
236 return;
237 }
238
239 this.isOpen = false;
240 openNotificationCount--;
241
242 // Clear any remaining timeout on close
243 this.pause();
244
245 // Remove the mw-notification-autohide class from the notification to avoid
246 // having a half-closed notification counted as a notification to resume
247 // when handling {autoHideLimit}.
248 this.$notification.removeClass( 'mw-notification-autohide' );
249
250 // Now that a notification is being closed. Start auto-hide timers for any
251 // notification that has now become one of the first {autoHideLimit} notifications.
252 notification.resume();
253
254 requestAnimationFrame( () => {
255 notif.$notification.removeClass( 'mw-notification-visible' );
256
257 setTimeout( () => {
258 if ( openNotificationCount === 0 ) {
259 // Hide the area after the last notification closes. Otherwise, the padding on
260 // the area can be obscure content, despite the area being empty/invisible (T54659). // FIXME
261 $area.css( 'display', 'none' );
262 notif.$notification.remove();
263 } else {
264 // FIXME: Use CSS transition
265 // eslint-disable-next-line no-jquery/no-slide
266 notif.$notification.slideUp( 'fast', function () {
267 $( this ).remove();
268 } );
269 }
270 }, 500 );
271 } );
272 };
273
274 /**
275 * Helper function, take a list of notification divs and call
276 * a function on the Notification instance attached to them.
277 *
278 * @private
279 * @static
280 * @param {jQuery} $notifications A jQuery object containing notification divs
281 * @param {string} fn The name of the function to call on the Notification instance
282 */
283 function callEachNotification( $notifications, fn ) {
284 $notifications.each( function () {
285 const notif = $( this ).data( 'mw-notification' );
286 if ( notif ) {
287 notif[ fn ]();
288 }
289 } );
290 }
291
292 /**
293 * Initialisation.
294 * Must only be called once, and not before the document is ready.
295 *
296 * @ignore
297 */
298 function init() {
299 let offset, $overlay,
300 isFloating = false;
301
302 function updateAreaMode() {
303 const shouldFloat = window.pageYOffset > offset.top;
304 if ( isFloating === shouldFloat ) {
305 return;
306 }
307 isFloating = shouldFloat;
308 $area
309 .toggleClass( 'mw-notification-area-floating', isFloating )
310 .toggleClass( 'mw-notification-area-layout', !isFloating );
311 }
312
313 // Look for a preset notification area in the skin.
314 // 'data-mw*' attributes are banned from user content in Sanitizer.
315 $area = $( '.mw-notification-area[data-mw="interface"]' ).first();
316 if ( !$area.length ) {
317 $area = $( '<div>' ).addClass( 'mw-notification-area' );
318 // Create overlay div for the notification area
319 $overlay = $( '<div>' ).addClass( 'mw-notification-area-overlay' );
320 // Append the notification area to the overlay wrapper area
321 $overlay.append( $area );
322 $( document.body ).append( $overlay );
323 }
324 $area
325 .addClass( 'mw-notification-area-layout' )
326 // The ID attribute here is deprecated.
327 .attr( 'id', 'mw-notification-area' )
328 // Pause auto-hide timers when the mouse is in the notification area.
329 .on( {
330 mouseenter: notification.pause,
331 mouseleave: notification.resume
332 } )
333 // When clicking on a notification close it.
334 .on( 'click', '.mw-notification', function () {
335 const notif = $( this ).data( 'mw-notification' );
336 if ( notif ) {
337 notif.close();
338 }
339 } )
340 // Stop click events from <a> and <select> tags from propagating to prevent clicks
341 // from hiding a notification. stopPropagation() bubbles up, not down,
342 // hence this should not conflict with OOUI's own click handlers.
343 .on( 'click', 'a, select, .oo-ui-dropdownInputWidget', ( e ) => {
344 e.stopPropagation();
345 } );
346
347 // Read from the DOM:
348 // Must be in the next frame to avoid synchronous layout
349 // computation from offset()/getBoundingClientRect().
350 requestAnimationFrame( () => {
351 let notif;
352
353 offset = $area.offset();
354
355 // Initial mode (reads, and then maybe writes)
356 updateAreaMode();
357
358 // Once we have the offset for where it would normally render, set the
359 // initial state of the (currently empty) notification area to be hidden.
360 $area.css( 'display', 'none' );
361
362 $( window ).on( 'scroll', updateAreaMode );
363
364 // Handle pre-ready queue.
365 isPageReady = true;
366 while ( preReadyNotifQueue.length ) {
367 notif = preReadyNotifQueue.shift();
368 notif.start();
369 }
370 } );
371 }
372
373 /**
374 * Library for sending notifications to end users.
375 *
376 * @namespace mw.notification
377 * @memberof mw
378 * @singleton
379 */
380 notification = {
381 /**
382 * Pause auto-hide timers for all notifications.
383 * Notifications will not auto-hide until resume is called.
384 *
385 * @see Notification#pause
386 * @memberof mw.notification
387 */
388 pause: function () {
389 callEachNotification(
390 $area.children( '.mw-notification' ),
391 'pause'
392 );
393 },
394
395 /**
396 * Resume any paused auto-hide timers from the beginning.
397 * Only the first {@link mw.notification.autoHideLimit} timers will be resumed.
398 *
399 * @memberof mw.notification
400 */
401 resume: function () {
402 callEachNotification(
403 // Only call resume on the first #autoHideLimit notifications.
404 // Exclude noautohide notifications to avoid bugs where #autoHideLimit
405 // `{ autoHide: false }` notifications are at the start preventing any
406 // auto-hide notifications from being autohidden.
407 $area.children( '.mw-notification-autohide' ).slice( 0, notification.autoHideLimit ),
408 'resume'
409 );
410 },
411
412 /**
413 * Display a notification message to the user.
414 *
415 * @memberof mw.notification
416 * @param {HTMLElement|HTMLElement[]|jQuery|mw.Message|string} message
417 * @param {mw.notification.NotificationOptions} [options] The options to use
418 * for the notification. Options not specified default to the values in
419 * [#defaults]{@link mw.notification.defaults}.
420 * @return {Notification} Notification object
421 */
422 notify: function ( message, options ) {
423 options = Object.assign( {}, notification.defaults, options );
424
425 const notif = new Notification( message, options );
426
427 if ( isPageReady ) {
428 notif.start();
429 } else {
430 preReadyNotifQueue.push( notif );
431 }
432
433 return notif;
434 },
435
436 /**
437 * @memberof mw.notification
438 * @typedef {Object} NotificationOptions
439 * @property {boolean} autoHide Whether the notification should automatically
440 * be hidden after shown. Or if it should persist.
441 * @property {string} autoHideSeconds Key to
442 * [#autoHideSeconds]{@link mw.notification.autoHideSeconds} for number of
443 * seconds for timeout of auto-hide notifications.
444 * @property {string|null} tag When a notification is tagged only one message
445 * with that tag will be displayed. Trying to display a new notification
446 * with the same tag as one already being displayed will cause the other
447 * notification to be closed and this new notification to open up inside
448 * the same place as the previous notification.
449 * @property {string|null} title Title for the notification. Will be displayed
450 * above the content. Usually in bold.
451 * @property {string|null} type The type of the message used for styling.
452 * Examples: `info`, `warn`, `error`, `success`.
453 * @property {boolean} visibleTimeout Whether the autoHide timeout should be
454 * based on time the page was visible to user. Or if it should use wall
455 * clock time.
456 * @property {string|false} id HTML ID to set on the notification element.
457 * @property {string|string[]|false} classes CSS class names to be set on the
458 * notification element.
459 */
460
461 /**
462 * The defaults for [#notify]{@link mw.notification.notify} options parameter.
463 *
464 * @memberof mw.notification
465 * @type {mw.notification.NotificationOptions}
466 */
467 defaults: {
468 autoHide: true,
469 autoHideSeconds: 'short',
470 tag: null,
471 title: null,
472 type: null,
473 visibleTimeout: true,
474 id: false,
475 classes: false
476 },
477
478 /**
479 * Map of predefined auto-hide timeout keys to second values. `short` is
480 * used by default, and other values can be added for use in [#notify]{@link mw.notification.notify}.
481 *
482 * @memberof mw.notification
483 * @type {Object.<string, number>}
484 * @property {number} short 5 seconds (default)
485 * @property {number} long 30 seconds
486 */
487 autoHideSeconds: {
488 short: 5,
489 long: 30
490 },
491
492 /**
493 * Maximum number of simultaneous notifications to start auto-hide timers for.
494 * Only this number of notifications being displayed will be auto-hidden at one time.
495 * Any additional notifications in the list will only start counting their timeout for
496 * auto-hiding after the previous messages have been closed.
497 *
498 * This basically represents the minimal number of notifications the user should
499 * be able to process during the {@link mw.notification.defaults default} `autoHideSeconds` time.
500 *
501 * @memberof mw.notification
502 * @type {number}
503 */
504 autoHideLimit: 3
505 };
506
507 if ( window.QUnit ) {
508 $area = $( document.body );
509 } else {
510 // Don't run UI logic while under test.
511 // Let the test control this instead.
512 $( init );
513 }
514
515 mw.notification = notification;
516
517 }() );