Debian Codegraph @

extensions/Echo/modules/ext.echo.init.js

raw symbols SCIP
1 /**
2 * @module module:ext.echo.init
3 */
4
5 /* eslint-disable no-jquery/no-global-selector */
6 mw.echo = mw.echo || {};
7 mw.echo.config = mw.echo.config || {};
8 // Set default max prioritized action links per item
9 mw.echo.config.maxPrioritizedActions = 2;
10
11 /**
12 * Initialise desktop Echo experience
13 */
14 function initDesktop() {
15 'use strict';
16
17 // Remove ?markasread=XYZ from the URL
18 const url = new URL( location.href );
19 if ( url.searchParams.has( 'markasread' ) ) {
20 url.searchParams.delete( 'markasread' );
21 url.searchParams.delete( 'markasreadwiki' );
22 history.replaceState( null, '', url );
23 }
24
25 // Activate OOUI
26 $( () => {
27 const maxNotificationCount = require( './config.json' ).EchoMaxNotificationCount,
28 pollingRate = require( './config.json' ).EchoPollForUpdates,
29 documentTitle = document.title,
30 $existingAlertLink = $( '#pt-notifications-alert a' ),
31 $existingMessageLink = $( '#pt-notifications-notice a' ),
32 numAlerts = $existingAlertLink.attr( 'data-counter-num' ),
33 numMessages = $existingMessageLink.attr( 'data-counter-num' ),
34 badgeLabelAlerts = $existingAlertLink.attr( 'data-counter-text' ),
35 badgeLabelMessages = $existingMessageLink.attr( 'data-counter-text' ),
36 // eslint-disable-next-line no-jquery/no-class-state
37 hasUnseenAlerts = $existingAlertLink.hasClass( 'mw-echo-unseen-notifications' ),
38 // eslint-disable-next-line no-jquery/no-class-state
39 hasUnseenMessages = $existingMessageLink.hasClass( 'mw-echo-unseen-notifications' ),
40 // latestMessageNotifTime is the time of most recent notification that came when we called showNotificationSnippet last
41 // the function showNotificationSnippet returns the time of the latest notification and latestMessageNotifTime is updated
42 // Store links
43 links = {
44 notifications: $existingAlertLink.attr( 'href' ) || mw.util.getUrl( 'Special:Notifications' ),
45 preferences: ( $( '#pt-preferences a' ).attr( 'href' ) || mw.util.getUrl( 'Special:Preferences' ) ) +
46 '#mw-prefsection-echo'
47 };
48 let alertController, messageController,
49 latestMessageNotifTime = new Date(),
50 latestAlertNotifTime = new Date(),
51 alertCount = parseInt( numAlerts ),
52 messageCount = parseInt( numMessages ),
53 loadingPromise = null;
54
55 function updateDocumentTitleWithNotificationCount( totalAlertCount, totalMessageCount ) {
56 const totalCount = totalAlertCount + totalMessageCount;
57
58 let newTitle = documentTitle;
59 if ( totalCount > 0 ) {
60 let convertedTotalCount = totalCount <= maxNotificationCount ? totalCount : maxNotificationCount + 1;
61 convertedTotalCount = mw.msg( 'echo-badge-count', mw.language.convertNumber( convertedTotalCount ) );
62 newTitle = mw.msg( 'parentheses', convertedTotalCount ) + ' ' + documentTitle;
63 }
64 document.title = newTitle;
65 }
66
67 /**
68 * Show notification snippet via mw.notify of notifications which came after highestNotifTime.
69 *
70 * @param {mw.echo.dm.ModelManager} modelManager
71 * @param {Date} highestNotifTime Timestamp of latest notification the last time function was called
72 * @return {Date} Timestamp of latest notification
73 */
74 function showNotificationSnippet( modelManager, highestNotifTime ) {
75 let highestTime = highestNotifTime;
76 modelManager.getLocalNotifications().forEach( ( notificationItem ) => {
77 const timestampAsDate = new Date( notificationItem.timestamp );
78 if ( timestampAsDate > highestNotifTime ) {
79 if ( timestampAsDate > highestTime ) {
80 highestTime = timestampAsDate;
81 }
82 if ( !notificationItem.seen ) {
83 mw.notify( $.parseHTML( notificationItem.content.header ), { title: mw.msg( 'echo-displaysnippet-title' ) } );
84 }
85 }
86 }
87 );
88 return highestTime;
89 }
90
91 /**
92 * Change the seen state of badges if there are any unseen notifications.
93 *
94 * @param {mw.echo.dm.ModelManager} modelManager
95 * @param {mw.echo.ui.NotificationBadgeWidget} badgeWidget
96 */
97 function updateBadgeState( modelManager, badgeWidget ) {
98 modelManager.getLocalNotifications().forEach( ( notificationItem ) => {
99 if ( !notificationItem.isSeen() ) {
100 badgeWidget.updateBadgeSeenState( true );
101 }
102 } );
103 }
104
105 function isLivePollingFeatureEnabledOnWiki() {
106 return pollingRate !== 0;
107 }
108
109 /**
110 * User has opted in to preference to show notification snippets and update document title with unread count.
111 *
112 * Only useful when isLivePollingFeatureEnabledOnWiki() returns true.
113 *
114 * @return {boolean} User preference
115 */
116 function userHasOptedInToLiveNotifications() {
117 return mw.user.options.get( 'echo-show-poll-updates' ) === '1';
118 }
119
120 // Change document title on initialization only when polling rate feature flag is non-zero.
121 if ( isLivePollingFeatureEnabledOnWiki() && userHasOptedInToLiveNotifications() ) {
122 updateDocumentTitleWithNotificationCount( alertCount, messageCount );
123 }
124
125 function loadEcho() {
126 if ( loadingPromise !== null ) {
127 return loadingPromise;
128 }
129 // This part executes only once, either when header icons are clicked or after completion of 60secs whichever occur first.
130 const echoApi = new mw.echo.api.EchoApi();
131
132 loadingPromise = mw.loader.using( 'ext.echo.ui.desktop' ).then( () => {
133
134 // Overlay
135 mw.echo.ui.$overlay.appendTo( document.body );
136
137 const unreadAlertCounter = new mw.echo.dm.UnreadNotificationCounter( echoApi, 'alert', maxNotificationCount );
138 const alertModelManager = new mw.echo.dm.ModelManager( unreadAlertCounter, { type: 'alert' } );
139 alertController = new mw.echo.Controller( echoApi, alertModelManager );
140
141 mw.echo.ui.alertWidget = new mw.echo.ui.NotificationBadgeWidget(
142 alertController,
143 alertModelManager,
144 links,
145 {
146 numItems: Number( numAlerts ),
147 convertedNumber: badgeLabelAlerts,
148 hasUnseen: hasUnseenAlerts,
149 badgeIcon: 'bell',
150 $overlay: mw.echo.ui.$overlay,
151 href: $existingAlertLink.attr( 'href' )
152 }
153 );
154
155 // Replace the link button with the ooui button
156 $existingAlertLink.parent().replaceWith( mw.echo.ui.alertWidget.$element );
157
158 alertModelManager.on( 'allTalkRead', () => {
159 // If there was a talk page notification, get rid of it
160 $( '#pt-talk-alert' ).remove();
161 } );
162
163 // listen to event countChange and change title only if polling rate is non-zero
164 if ( isLivePollingFeatureEnabledOnWiki() ) {
165 alertModelManager.getUnreadCounter().on( 'countChange', ( count ) => {
166 alertController.fetchLocalNotifications().then( () => {
167 updateBadgeState( alertModelManager, mw.echo.ui.alertWidget );
168 if ( userHasOptedInToLiveNotifications() ) {
169 latestAlertNotifTime = showNotificationSnippet( alertModelManager, latestAlertNotifTime );
170 alertCount = count;
171 updateDocumentTitleWithNotificationCount( count, messageCount );
172 }
173 } );
174 } );
175 }
176
177 // Load message button and popup if messages exist
178 if ( $existingMessageLink.length ) {
179 const unreadMessageCounter = new mw.echo.dm.UnreadNotificationCounter( echoApi, 'message', maxNotificationCount );
180 const messageModelManager = new mw.echo.dm.ModelManager( unreadMessageCounter, { type: 'message' } );
181 messageController = new mw.echo.Controller( echoApi, messageModelManager );
182
183 mw.echo.ui.messageWidget = new mw.echo.ui.NotificationBadgeWidget(
184 messageController,
185 messageModelManager,
186 links,
187 {
188 $overlay: mw.echo.ui.$overlay,
189 numItems: Number( numMessages ),
190 hasUnseen: hasUnseenMessages,
191 badgeIcon: 'tray',
192 convertedNumber: badgeLabelMessages,
193 href: $existingMessageLink.attr( 'href' )
194 }
195 );
196
197 // Replace the link button with the ooui button
198 $existingMessageLink.parent().replaceWith( mw.echo.ui.messageWidget.$element );
199
200 // listen to event countChange and change title only if polling rate is non-zero
201 if ( isLivePollingFeatureEnabledOnWiki() ) {
202 messageModelManager.getUnreadCounter().on( 'countChange', ( count ) => {
203 messageController.fetchLocalNotifications().then( () => {
204 updateBadgeState( messageModelManager, mw.echo.ui.messageWidget );
205 if ( userHasOptedInToLiveNotifications() ) {
206 latestMessageNotifTime = showNotificationSnippet( messageModelManager, latestMessageNotifTime );
207 messageCount = count;
208 updateDocumentTitleWithNotificationCount( alertCount, count );
209 }
210 } );
211 } );
212 }
213 }
214 } );
215 return loadingPromise;
216 }
217
218 // Respond to click on the notification button and load the UI on demand
219 $( '.mw-echo-notification-badge-nojs' ).on( 'click', function ( e ) {
220 const timeOfClick = mw.now(),
221 $badge = $( this ),
222 clickedSection = $badge.parent().prop( 'id' ) === 'pt-notifications-alert' ? 'alert' : 'message';
223 if ( e.which !== 1 || $badge.data( 'clicked' ) ) {
224 // Do not return false (as that calls stopPropagation)
225 e.preventDefault();
226 return;
227 }
228
229 $badge.data( 'clicked', true );
230
231 // Dim the badge while we load
232 $badge.addClass( 'mw-echo-notifications-badge-dimmed' );
233
234 // Fire the notification API requests
235 const echoApi = new mw.echo.api.EchoApi();
236 echoApi.fetchNotifications( clickedSection )
237 .then( ( data ) => {
238 mw.track( 'timing.MediaWiki.echo.overlay.api', mw.now() - timeOfClick );
239 return data;
240 } );
241
242 loadEcho().then( () => {
243 // Now that the module loaded, show the popup
244 const selectedWidget = clickedSection === 'alert' ? mw.echo.ui.alertWidget : mw.echo.ui.messageWidget;
245 selectedWidget.once( 'finishLoading', () => {
246 // Log timing after notifications are shown
247 mw.track( 'timing.MediaWiki.echo.overlay', mw.now() - timeOfClick );
248 } );
249 selectedWidget.popup.toggle( true );
250 mw.track( 'timing.MediaWiki.echo.overlay.ooui', mw.now() - timeOfClick );
251
252 if ( hasUnseenAlerts || hasUnseenMessages ) {
253 // Clicked on the flyout due to having unread notifications
254 // This is part of tracking how likely users are to click a badge with unseen notifications.
255 // The other part is the 'echo.unseen' counter, see EchoHooks::onSkinTemplateNavigationUniversal().
256 mw.track( 'counter.MediaWiki.echo.unseen.click' );
257 }
258 }, () => {
259 // Un-dim badge if loading failed
260 $badge.removeClass( 'mw-echo-notifications-badge-dimmed' );
261 } );
262 // Prevent default. Do not return false (as that calls stopPropagation)
263 e.preventDefault();
264 } );
265
266 function pollForNotificationCountUpdates() {
267 alertController.refreshUnreadCount();
268 messageController.refreshUnreadCount();
269 // Make notification update after n*pollingRate(time in secs) where n depends on document.hidden
270 setTimeout( pollForNotificationCountUpdates, ( document.hidden ? 5 : 1 ) * pollingRate * 1000 );
271 }
272
273 function pollStart() {
274 if ( mw.config.get( 'skin' ) !== 'minerva' && isLivePollingFeatureEnabledOnWiki() ) {
275 // load widgets if not loaded already then start polling
276 loadEcho().then( pollForNotificationCountUpdates );
277 }
278 }
279
280 setTimeout( pollStart, 60 * 1000 );
281
282 } );
283
284 }
285
286 /**
287 * Initialise a mobile experience instead
288 */
289 function initMobile() {
290 if ( !mw.user.isAnon() ) {
291 mw.loader.using( [ 'ext.echo.mobile', 'mobile.startup' ] ).then( ( require ) => {
292 require( 'ext.echo.mobile' ).init();
293 } );
294 }
295 }
296
297 $( () => {
298 if ( mw.config.get( 'wgMFMode' ) ) {
299 initMobile();
300 } else {
301 // Echo is intentionally disable for the Minerva desktop skin (https://phabricator.wikimedia.org/T343839)
302 // The suggested fix is documented in https://phabricator.wikimedia.org/T343838,
303 if ( mw.config.get( 'skin' ) !== 'minerva' ) {
304 initDesktop();
305 }
306 }
307 } );