Debian Codegraph @

skins/MinervaNeue/resources/skins.minerva.scripts/initMobile.js

raw symbols SCIP
1 /**
2 * Initialise code that requires MobileFrontend.
3 */
4
5 module.exports = function () {
6 const
7 ms = require( 'mobile.startup' ),
8 PageHTMLParser = ms.PageHTMLParser,
9 permissions = mw.config.get( 'wgMinervaPermissions' ) || {},
10 notifyOnPageReload = ms.notifyOnPageReload,
11 time = ms.time,
12 preInit = require( './preInit.js' ),
13 mobileRedirect = require( './mobileRedirect.js' ),
14 search = require( './search.js' ),
15 references = require( './references.js' ),
16 TitleUtil = require( './TitleUtil.js' ),
17 issues = require( './page-issues/index.js' ),
18 Toolbar = require( './Toolbar.js' ),
19 ToggleList = require( '../../includes/Skins/ToggleList/ToggleList.js' ),
20 TabScroll = require( './TabScroll.js' ),
21 router = require( 'mediawiki.router' ),
22 ctaDrawers = require( './ctaDrawers.js' ),
23 drawers = require( './drawers.js' ),
24 desktopMMV = mw.loader.getState( 'mmv.bootstrap' ),
25 overlayManager = ms.getOverlayManager(),
26 currentPage = ms.currentPage(),
27 currentPageHTMLParser = ms.currentPageHTMLParser(),
28 api = new mw.Api(),
29 namespaceIDs = mw.config.get( 'wgNamespaceIds' );
30
31 /**
32 * Event handler for clicking on an image thumbnail
33 *
34 * @param {MouseEvent} ev
35 * @ignore
36 */
37 function onClickImage( ev ) {
38 // Do not interfere when a modifier key is pressed.
39 if ( ev.altKey || ev.ctrlKey || ev.shiftKey || ev.metaKey ) {
40 return;
41 }
42
43 const el = ev.target.closest( PageHTMLParser.THUMB_SELECTOR );
44 if ( !el ) {
45 return;
46 }
47
48 const thumb = currentPageHTMLParser.getThumbnail( $( el ) );
49 if ( !thumb ) {
50 return;
51 }
52
53 ev.preventDefault();
54 routeThumbnail( thumb );
55 }
56
57 /**
58 * @param {jQuery.Element} thumbnail
59 * @ignore
60 */
61 function routeThumbnail( thumbnail ) {
62 router.navigate( '#/media/' + encodeURIComponent( thumbnail.getFileName() ) );
63 }
64
65 /**
66 * Add routes to images and handle clicks
67 *
68 * @method
69 * @ignore
70 * @param {HTMLElement} container Container to search within
71 */
72 function initMediaViewer( container ) {
73 // T360781 Ensure correct type before using `addEventListener`.
74 if ( container instanceof HTMLElement ) {
75 container.addEventListener( 'click', onClickImage );
76 }
77 }
78
79 /**
80 * Hijack the Special:Languages link and replace it with a trigger to a languageOverlay
81 * that displays the same data
82 *
83 * @ignore
84 */
85 function initButton() {
86 // This catches language selectors in page actions and in secondary actions (e.g. Main Page)
87 // eslint-disable-next-line no-jquery/no-global-selector
88 const $primaryBtn = $( '.language-selector' );
89
90 if ( $primaryBtn.length ) {
91 // We only bind the click event to the first language switcher in page
92 $primaryBtn.on( 'click', ( ev ) => {
93 ev.preventDefault();
94
95 if ( $primaryBtn.attr( 'href' ) || $primaryBtn.find( 'a' ).length ) {
96 router.navigate( '/languages' );
97 } else {
98 mw.notify( mw.msg( 'mobile-frontend-languages-not-available' ), {
99 tag: 'languages-not-available'
100 } );
101 }
102 } );
103 }
104 }
105
106 /**
107 * Returns a rejected promise if MultimediaViewer is available. Otherwise
108 * returns the mediaViewerOverlay
109 *
110 * @method
111 * @ignore
112 * @param {string} title the title of the image
113 * @return {void|Overlay} note must return void if the overlay should not show (see T262703)
114 * otherwise an Overlay is expected and this can lead to e.on/off is not a function
115 */
116 function makeMediaViewerOverlayIfNeeded( title ) {
117 if ( mw.loader.getState( 'mmv.bootstrap' ) === 'ready' ) {
118 // This means MultimediaViewer has been installed and is loaded.
119 // Avoid loading it (T169622)
120 return;
121 }
122 try {
123 title = decodeURIComponent( title );
124 } catch ( e ) {
125 // e.g. https://ro.m.wikipedia.org/wiki/Elisabeta_I_a_Angliei#/media/Fi%C8%18ier:Elizabeth_I_Rainbow_Portrait.jpg
126 return;
127 }
128
129 return ms.mediaViewer.overlay( {
130 api,
131 thumbnails: currentPageHTMLParser.getThumbnails(),
132 title
133 } );
134 }
135
136 // Routes
137 overlayManager.add( /^\/media\/(.+)$/, makeMediaViewerOverlayIfNeeded );
138 overlayManager.add( /^\/languages$/, () => ms.languages.languageOverlay() );
139 // Register a LanguageInfo overlay which has no built-in functionality;
140 // a hook is fired when a language is selected, and extensions can respond
141 // to that hook. See GrowthExperiments WelcomeSurvey feature (in gerrit
142 // Ib558dc7c46cc56ff667957f9126bbe0471d25b8e for example usage).
143 overlayManager.add( /^\/languages\/all$/, () => ms.languages.languageInfoOverlay( api, true ) );
144 overlayManager.add( /^\/languages\/all\/no-suggestions$/, () => ms.languages.languageInfoOverlay( api, false ) );
145
146 // Setup
147 $( () => {
148 initButton();
149 } );
150
151 /**
152 * Initialisation function for last modified module.
153 *
154 * Enhances an element representing a time
155 * to show a human friendly date in seconds, minutes, hours, days
156 * months or years
157 *
158 * @ignore
159 * @param {jQuery} $lastModifiedLink
160 */
161 function initHistoryLink( $lastModifiedLink ) {
162 const ts = $lastModifiedLink.data( 'timestamp' );
163 if ( ts ) {
164 const username = $lastModifiedLink.data( 'user-name' ) || false;
165 const gender = $lastModifiedLink.data( 'user-gender' );
166 const delta = time.getTimeAgoDelta( parseInt( ts, 10 ) );
167 if ( time.isRecent( delta ) ) {
168 const $bar = $lastModifiedLink.closest( '.last-modified-bar' );
169 $bar.addClass( 'active' );
170 }
171
172 const $msg = $( '<span>' )
173 // The new element should maintain the non-js element's CSS classes.
174 .attr( 'class', $lastModifiedLink.attr( 'class' ) )
175 .html(
176 time.getLastModifiedMessage( ts, username, gender,
177 // For cached HTML
178 $lastModifiedLink.attr( 'href' )
179 )
180 );
181 $lastModifiedLink.replaceWith( $msg );
182 }
183 }
184
185 /**
186 * @method
187 * @param {jQuery.Event} ev
188 */
189 function amcHistoryClickHandler( ev ) {
190 const self = this;
191 const amcOutreach = ms.amcOutreach;
192 const amcCampaign = amcOutreach.loadCampaign();
193 const onDismiss = function () {
194 notifyOnPageReload( mw.msg( 'mobile-frontend-amc-outreach-dismissed-message' ) );
195 window.location = self.href;
196 };
197 const drawer = amcCampaign.showIfEligible( amcOutreach.ACTIONS.onHistoryLink, onDismiss, currentPage.title, 'action=history' );
198
199 if ( drawer ) {
200 ev.preventDefault();
201 // stopPropagation is needed to prevent drawer from immediately closing
202 // when shown (drawers.js adds a click event to window when drawer is
203 // shown
204 ev.stopPropagation();
205
206 drawers.displayDrawer( drawer, {} );
207 drawers.lockScroll();
208 }
209 }
210
211 /**
212 * @method
213 * @param {jQuery} $lastModifiedLink
214 * @ignore
215 */
216 function initAmcHistoryLink( $lastModifiedLink ) {
217 $lastModifiedLink.one( 'click', amcHistoryClickHandler );
218 }
219
220 /**
221 * Initialisation function for last modified times
222 *
223 * Enhances .modified-enhancement element
224 * to show a human friendly date in seconds, minutes, hours, days
225 * months or years
226 *
227 * @ignore
228 */
229 function initModifiedInfo() {
230 // eslint-disable-next-line no-jquery/no-global-selector
231 $( '.modified-enhancement' ).each( ( _i, el ) => {
232 initHistoryLink( $( el ) );
233 } );
234 Array.prototype.forEach.call( document.querySelectorAll( '.mw-diff-timestamp' ), ( tsNode ) => {
235 const ts = tsNode.dataset.timestamp;
236 if ( ts ) {
237 const ago = time.getTimeAgoDelta(
238 parseInt(
239 ( new Date( ts ) ).getTime() / 1000,
240 10
241 )
242 );
243 // Supported messages:
244 // * skin-minerva-time-ago-seconds
245 // * skin-minerva-time-ago-minutes
246 // * skin-minerva-time-ago-hours
247 // * skin-minerva-time-ago-days
248 // * skin-minerva-time-ago-months
249 // * skin-minerva-time-ago-years
250 tsNode.textContent = mw.msg(
251 `skin-minerva-time-ago-${ ago.unit }`,
252 mw.language.convertNumber( ago.value )
253 );
254 }
255 } );
256 }
257
258 /**
259 * Initialisation function for user creation module.
260 *
261 * Enhances an element representing a time
262 * to show a human friendly date in seconds, minutes, hours, days
263 * months or years
264 *
265 * @ignore
266 * @param {jQuery} [$tagline]
267 */
268 function initRegistrationDate( $tagline ) {
269 const ts = $tagline.data( 'userpage-registration-date' );
270
271 if ( ts ) {
272 const msg = time.getRegistrationMessage( ts, $tagline.data( 'userpage-gender' ) );
273 $tagline.text( msg );
274 }
275 }
276
277 /**
278 * Initialisation function for registration date on user page
279 *
280 * Enhances .tagline-userpage element
281 * to show human friendly date in seconds, minutes, hours, days
282 * months or years
283 *
284 * @ignore
285 */
286 function initRegistrationInfo() {
287 // eslint-disable-next-line no-jquery/no-global-selector
288 $( '#tagline-userpage' ).each( ( _i, el ) => {
289 initRegistrationDate( $( el ) );
290 } );
291 }
292
293 /**
294 * Tests a URL to determine if it links to a local User namespace page or not.
295 *
296 * Assuming the current page visited is hosted on metawiki, the following examples would return
297 * true:
298 *
299 * https://meta.wikimedia.org/wiki/User:Foo
300 * /wiki/User:Foo
301 * /wiki/User:Nonexistent_user_page
302 *
303 * The following examples return false:
304 *
305 * https://en.wikipedia.org/wiki/User:Foo
306 * /wiki/Foo
307 * /wiki/User_talk:Foo
308 *
309 * @param {string} url
310 * @return {boolean}
311 */
312 function isUserUri( url ) {
313 const title = TitleUtil.newFromUri( url );
314 const namespace = title ? title.getNamespaceId() : undefined;
315 return namespace === namespaceIDs.user;
316 }
317
318 /**
319 * Strip the edit action from red links to nonexistent User namespace pages.
320 *
321 * @param {jQuery} $redLinks
322 */
323 function initUserRedLinks( $redLinks ) {
324 $redLinks.filter(
325 // Filter out non-User namespace pages.
326 ( _, element ) => isUserUri( element.href )
327 ).each( ( _, element ) => {
328 const uri = new mw.Uri( element.href );
329 if ( uri.query.action !== 'edit' ) {
330 // Nothing to strip.
331 return;
332 }
333
334 // Strip the action.
335 delete uri.query.action;
336
337 // Update the element with the new link.
338 element.href = uri.toString();
339 } );
340 }
341
342 /**
343 * Wires up the notification badge to Echo extension
344 */
345 function setupEcho() {
346 const echoBtn = document.querySelector( '.minerva-notifications .mw-echo-notification-badge-nojs' );
347 if ( echoBtn ) {
348 echoBtn.addEventListener( 'click', ( ev ) => {
349 router.navigate( '#/notifications' );
350 // prevent navigation to original Special:Notifications URL
351 // DO NOT USE stopPropagation or you'll break click tracking in WikimediaEvents
352 ev.preventDefault();
353
354 // Mark as read.
355 echoBtn.dataset.counterNum = 0;
356 echoBtn.dataset.counterText = mw.msg( 'echo-badge-count',
357 mw.language.convertNumber( 0 )
358 );
359
360 } );
361 }
362 }
363
364 $( () => {
365 // eslint-disable-next-line no-jquery/no-global-selector
366 const $watch = $( '#page-actions-watch' );
367 const toolbarElement = document.querySelector( Toolbar.selector );
368 const userMenu = document.querySelector( '.minerva-user-menu' ); // See UserMenuDirector.
369 const navigationDrawer = document.querySelector( '.navigation-drawer' );
370
371 // The `minerva-animations-ready` class can be used by clients to prevent unwanted
372 // CSS transitions from firing on page load in some browsers (see
373 // https://bugs.chromium.org/p/chromium/issues/detail?id=332189 as well as
374 // https://phabricator.wikimedia.org/T234570#5779890). Since JS adds this
375 // class after the CSS transitions loads, this issue is circumvented. See
376 // MainMenu.less for an example of how this is used.
377 $( document.body ).addClass( 'minerva-animations-ready' );
378
379 // eslint-disable-next-line no-jquery/no-global-selector
380 $( '.mw-mf-page-center__mask' ).on( 'click', ( ev ) => {
381 const path = router.getPath();
382 // avoid jumping to the top of the page and polluting history by avoiding the
383 // resetting of the hash unless the hash is being utilised (T237015).
384 if ( !path ) {
385 ev.preventDefault();
386 }
387 } );
388 // Init:
389 // - main menu closes when you click outside of it
390 // - redirects show a toast.
391 preInit();
392 // - references
393 references();
394 // - search
395 search();
396 // - mobile redirect
397 mobileRedirect( ms.amcOutreach, currentPage );
398
399 // Enhance timestamps on last-modified bar and watchlist
400 // to show relative time.
401 initModifiedInfo();
402 initRegistrationInfo();
403 // eslint-disable-next-line no-jquery/no-global-selector
404 initAmcHistoryLink( $( '.last-modified-bar__text a' ) );
405
406 if ( toolbarElement ) {
407 Toolbar.bind( window, toolbarElement );
408 // Update the edit icon and add a download icon.
409 Toolbar.render( window, toolbarElement );
410 }
411 if ( userMenu ) {
412 ToggleList.bind( window, userMenu );
413 }
414 if ( navigationDrawer ) {
415 ToggleList.bind( window, navigationDrawer );
416 const navigationDrawerMask = navigationDrawer.querySelector( '.main-menu-mask' );
417 // The 'for' attribute is used to close the drawer when the mask is clicked without JS
418 // Since we are using JS to enhance the drawer behavior, we need to
419 // remove the attribute to prevent the drawer from being toggled twice
420 navigationDrawerMask.removeAttribute( 'for' );
421 }
422 TabScroll.initTabsScrollPosition();
423 // Setup the issues banner on the page
424 // Pages which dont exist (id 0) cannot have issues
425 if (
426 !currentPage.isMissing &&
427 !currentPage.titleObj.isTalkPage()
428 ) {
429 issues.init( overlayManager, currentPageHTMLParser );
430 }
431
432 // If MobileFrontend installed we add a table of contents icon to the table of contents.
433 // This should probably be done in the parser.
434 // setup toc icons
435 mw.hook( 'wikipage.content' ).add( ( $container ) => {
436 // If the MMV module is missing or disabled from the page, initialise our version
437 if ( desktopMMV === null || desktopMMV === 'registered' ) {
438 initMediaViewer( $container[ 0 ] );
439 }
440
441 // Mutate TOC.
442 const $toctitle = $container.find( '.toctitle' );
443 $( '<span>' ).addClass( 'toc-title-icon' ).prependTo( $toctitle );
444 $( '<span>' ).addClass( 'toc-title-state-icon' ).appendTo( $toctitle );
445
446 // Init red links.
447 const $redLinks = currentPageHTMLParser.getRedLinks();
448 ctaDrawers.initRedlinksCta(
449 $redLinks.filter(
450 // Filter out local User namespace pages.
451 ( _, element ) => !isUserUri( element.href )
452 )
453 );
454 initUserRedLinks( $redLinks );
455 } );
456
457 // wire up watch icon if necessary
458 if ( permissions.watchable && !permissions.watch ) {
459 ctaDrawers.initWatchstarCta( $watch );
460 }
461
462 // If Echo is installed, wire it up.
463 const echoState = mw.loader.getState( 'ext.echo.mobile' );
464 // If Echo is installed, set it up.
465 if ( echoState !== null && echoState !== 'registered' ) {
466 setupEcho();
467 }
468 } );
469 };