Debian Codegraph @

extensions/MultimediaViewer/resources/mmv.bootstrap/mmv.bootstrap.js

raw symbols SCIP
1 /*
2 * This file is part of the MediaWiki extension MultimediaViewer.
3 *
4 * MultimediaViewer is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * MultimediaViewer is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with MultimediaViewer. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 const Config = require( './mmv.Config.js' );
19 const LightboxImage = require( './mmv.lightboximage.js' );
20 const { extensions } = require( './config.json' );
21 const mwRouter = require( 'mediawiki.router' );
22
23 // We pass this to history.pushState/replaceState to indicate that we're controlling the page URL.
24 // Then we look for this marker on page load so that if the page is refreshed, we don't generate an
25 // extra history entry.
26 const MANAGED_STATE = 'MMV was here!';
27
28 /**
29 * Bootstrap code listening to thumb clicks checking the initial location.hash
30 * Loads the mmv and opens it if necessary
31 */
32 class MultimediaViewerBootstrap {
33 constructor() {
34 // Exposed for tests
35 this.hoverWaitDuration = 200;
36
37 /**
38 * This flag is set to true when we were unable to load the viewer.
39 *
40 * @property {boolean}
41 */
42 this.viewerIsBroken = false;
43
44 this.thumbsReadyDeferred = $.Deferred();
45 /**
46 * @property {LightboxImage[]}
47 */
48 this.thumbs = [];
49 this.$thumbs = null; // will be set by processThumbs
50 this.$parsoidThumbs = null; // will be set in processThumbs
51
52 // find and setup all thumbs on this page
53 // this will run initially and then every time the content changes,
54 // e.g. via a VE edit or pagination in a multipage file
55 mw.hook( 'wikipage.content' ).add( this.processThumbs.bind( this ) );
56
57 // Setup the router
58 this.setupRouter( mwRouter );
59 }
60
61 /**
62 * Routes to a given file.
63 *
64 * @param {string} fileName
65 */
66 route( fileName ) {
67 this.loadViewer( true ).then( ( viewer ) => {
68 let fileTitle;
69 viewer.comingFromHashChange = true;
70 try {
71 let position = fileName.match( Config.POSITION_REGEXP );
72 if ( position ) {
73 position = +position[ 1 ];
74 fileName = fileName.replace( Config.POSITION_REGEXP, '' );
75 } else {
76 position = undefined;
77 }
78 fileName = decodeURIComponent( fileName );
79 fileTitle = new mw.Title( fileName );
80 viewer.loadImageByTitle( fileTitle, position );
81 } catch ( err ) {
82 // ignore routes to invalid titles
83 mw.log.warn( err );
84 }
85 } );
86 }
87
88 /**
89 * Sets up the route handlers
90 *
91 * @param {OO.Router} router
92 */
93 setupRouter( router ) {
94 router.addRoute( Config.ROUTE_REGEXP, this.route.bind( this ) );
95 router.addRoute( Config.LEGACY_ROUTE_REGEXP, this.route.bind( this ) );
96 this.router = router;
97 }
98
99 /**
100 * Loads the mmv module asynchronously and passes the thumb data to it
101 *
102 * @param {boolean} [setupOverlay]
103 * @return {jQuery.Promise}
104 */
105 loadViewer( setupOverlay ) {
106 const deferred = $.Deferred();
107 let viewer;
108 let message;
109
110 // Don't load if someone has specifically stopped us from doing so
111 if ( mw.config.get( 'wgMediaViewer' ) !== true ) {
112 return deferred.reject();
113 }
114
115 if ( history.scrollRestoration ) {
116 history.scrollRestoration = 'manual';
117 }
118
119 // FIXME setupOverlay is a quick hack to avoid setting up and immediately
120 // removing the overlay on a not-MMV -> not-MMV hash change.
121 // loadViewer is called on every click and hash change and setting up
122 // the overlay is not needed on all of those; this logic really should
123 // not be here.
124 if ( setupOverlay ) {
125 this.setupOverlay();
126 }
127
128 mw.loader.using( 'mmv', ( req ) => {
129 try {
130 viewer = this.getViewer( req );
131 } catch ( e ) {
132 message = e.message;
133 if ( e.stack ) {
134 message += `\n${ e.stack }`;
135 }
136 deferred.reject( message );
137 return;
138 }
139 deferred.resolve( viewer );
140 }, ( error ) => {
141 deferred.reject( error.message );
142 } );
143
144 return deferred.promise()
145 .then(
146 ( viewer2 ) => {
147 if ( !this.viewerInitialized ) {
148 if ( this.thumbs.length ) {
149 viewer2.initWithThumbs( this.thumbs );
150 }
151
152 this.viewerInitialized = true;
153 }
154 return viewer2;
155 },
156 ( message2 ) => {
157 mw.log.warn( message2 );
158 this.cleanupOverlay();
159 this.viewerIsBroken = true;
160 mw.notify( `Error loading MediaViewer: ${ message2 }` );
161 return $.Deferred().reject( message2 );
162 }
163 ).always( () => {
164 if ( this.$loadBar ) {
165 this.$loadBar.remove();
166 }
167 } );
168 }
169
170 /**
171 * Processes all thumbs found on the page
172 *
173 * @param {jQuery} $content Element to search for thumbs
174 */
175 processThumbs( $content ) {
176 // MMVB.processThumbs() is a callback for `wikipage.content` hook (see constructor)
177 // which as state in the documentation can be fired when content is added to the DOM
178 // https://doc.wikimedia.org/mediawiki-core/master/js/#!/api/mw.hook
179 // The content being added can contain thumbnails that the MultimediaViewer may need to
180 // process correctly and add the thumbs array, so it's necessary to invalidate the
181 // viewer initialization state if this happens to let the MMVB.loadViewer() to process
182 // new images correctly
183 this.viewerInitialized = false;
184
185 this.$parsoidThumbs = $content.find(
186 '[typeof*="mw:File"] a.mw-file-description img, ' +
187 // TODO: Remove mw:Image when version 2.4.0 of the content is no
188 // longer supported
189 '[typeof*="mw:Image"] a.mw-file-description img'
190 );
191
192 this.$thumbs = $content
193 .find(
194 '.gallery .image img, ' +
195 'a.image img, ' +
196 'a.mw-file-description img, ' +
197 '#file a img'
198 )
199 // Skip duplicates that are actually Parsoid thumbs
200 .not( this.$parsoidThumbs );
201
202 try {
203 this.$thumbs.each( ( i, thumb ) => this.processThumb( thumb ) );
204 this.$parsoidThumbs.each( ( i, thumb ) => this.processParsoidThumb( thumb ) );
205 } finally {
206 this.thumbsReadyDeferred.resolve();
207 }
208 }
209
210 /**
211 * Check if this thumbnail should be handled by MediaViewer
212 *
213 * @param {jQuery} $thumb the thumbnail (an `<img>` element) in question
214 * @return {boolean}
215 */
216 isAllowedThumb( $thumb ) {
217 const selectors = [
218 '.metadata', // this is inside an informational template like {{refimprove}} on enwiki.
219 '.noviewer', // MediaViewer has been specifically disabled for this image
220 '.noarticletext', // we are on an error page for a non-existing article, the image is part of some template
221 '#siteNotice',
222 'ul.mw-gallery-slideshow li.gallerybox' // thumbnails of a slideshow gallery
223 ];
224 return $thumb.closest( selectors.join( ', ' ) ).length === 0;
225
226 }
227
228 /**
229 * @param {mw.Title|null} title
230 * @return {boolean}
231 */
232 isValidExtension( title ) {
233 return title && title.getExtension() && ( title.getExtension().toLowerCase() in extensions );
234 }
235
236 /**
237 * Preload JS/CSS when the mouse cursor hovers the thumb container
238 * (thumb image + caption + border)
239 *
240 * @param {jQuery} $thumbContainer
241 */
242 preloadAssets( $thumbContainer ) {
243 $thumbContainer.on( {
244 mouseenter: () => {
245 // There is no point preloading if clicking the thumb won't open Media Viewer
246 if ( !Config.isMediaViewerEnabledOnClick() ) {
247 return;
248 }
249 this.preloadOnHoverTimer = setTimeout( () => {
250 mw.loader.load( 'mmv' );
251 }, this.hoverWaitDuration );
252 },
253 mouseleave: () => {
254 if ( this.preloadOnHoverTimer ) {
255 clearTimeout( this.preloadOnHoverTimer );
256 }
257 }
258 } );
259 }
260
261 /**
262 * Processes a thumb
263 *
264 * @param {Object} thumb
265 */
266 processThumb( thumb ) {
267 let title;
268 const $thumb = $( thumb );
269 const $link = $thumb.closest( 'a.image, a.mw-file-description' );
270 const $thumbContainer = $link.closest( '.thumb' );
271 const $enlarge = $thumbContainer.find( '.magnify a' );
272 const isFilePageMainThumb = $thumb.closest( '#file' ).length > 0;
273
274 if ( isFilePageMainThumb ) {
275 // main thumbnail (file preview area) of a file page
276 // if this is a PDF filetype thumbnail, it can trick us,
277 // so we short-circuit that logic and use the file page title
278 // instead of the thumbnail logic.
279 title = mw.Title.newFromText( mw.config.get( 'wgTitle' ), mw.config.get( 'wgNamespaceNumber' ) );
280 } else {
281 title = mw.Title.newFromImg( $thumb );
282 }
283
284 if ( !this.isValidExtension( title ) ) {
285 // Short-circuit event handler and interface setup, because
286 // we can't do anything for this filetype
287 return;
288 }
289
290 if ( !this.isAllowedThumb( $thumb ) ) {
291 return;
292 }
293
294 if ( $thumbContainer.length ) {
295 this.preloadAssets( $thumbContainer );
296 }
297
298 if ( isFilePageMainThumb ) {
299 this.processFilePageThumb( $thumb, title );
300 return;
301 }
302
303 // This is the data that will be passed onto the mmv
304 const image = new LightboxImage(
305 $thumb.prop( 'src' ),
306 title,
307 this.thumbs.length,
308 this.thumbs.filter( ( t ) => t.filePageTitle.getPrefixedText() === title.getPrefixedText() ).length + 1,
309 $thumb[ 0 ],
310 this.findCaption( $thumbContainer, $link )
311 );
312 this.thumbs.push( image );
313
314 $link.add( $enlarge ).on( 'click', ( e ) => this.click( e, image ) );
315 }
316
317 /**
318 * Processes a Parsoid thumb, making use of the specified structure,
319 * https://www.mediawiki.org/wiki/Specs/HTML#Media
320 *
321 * @param {Object} thumb
322 */
323 processParsoidThumb( thumb ) {
324 const $thumb = $( thumb );
325 const $link = $thumb.closest( 'a.mw-file-description' );
326 const $thumbContainer = $link.closest(
327 '[typeof*="mw:File"], ' +
328 // TODO: Remove mw:Image when version 2.4.0 of the content is
329 // no longer supported
330 '[typeof*="mw:Image"]'
331 );
332 const title = mw.Title.newFromImg( $thumb );
333 let caption;
334
335 if ( !this.isValidExtension( title ) ) {
336 // Short-circuit event handler and interface setup, because
337 // we can't do anything for this filetype
338 return;
339 }
340
341 if ( !this.isAllowedThumb( $thumb ) ) {
342 return;
343 }
344
345 if ( $thumbContainer.length ) {
346 this.preloadAssets( $thumbContainer );
347 }
348
349 if ( ( $thumbContainer.prop( 'tagName' ) || '' ).toLowerCase() === 'figure' ) {
350 caption = $thumbContainer.find( 'figcaption' ).html() || '';
351 } else {
352 caption = $link.prop( 'title' ) || undefined;
353 }
354
355 // This is the data that will be passed onto the mmv
356 const image = new LightboxImage(
357 $thumb.prop( 'src' ),
358 title,
359 this.thumbs.length,
360 this.thumbs.filter( ( t ) => t.filePageTitle.getPrefixedText() === title.getPrefixedText() ).length + 1,
361 $thumb[ 0 ],
362 caption
363 );
364 this.thumbs.push( image );
365
366 $link.on( 'click', ( e ) => this.click( e, image ) );
367 }
368
369 /**
370 * Processes the main thumbnail of a file page by adding some buttons
371 * below to open MediaViewer.
372 *
373 * @param {jQuery} $thumb
374 * @param {mw.Title} title
375 */
376 processFilePageThumb( $thumb, title ) {
377 // remove the buttons (and the clearing element) if they are already there
378 // this should not happen (at least until we support paged media) but just in case
379 // eslint-disable-next-line no-jquery/no-global-selector
380 $( '.mw-mmv-view-expanded' ).remove();
381
382 const $mmvButton = $( '<button>' )
383 .addClass( 'mw-mmv-view-expanded cdx-button' )
384 .append( $( '<span>' ).addClass( 'cdx-button__icon' ) )
385 .append( ' ' )
386 .append( mw.message( 'multimediaviewer-view-expanded' ).escaped() );
387
388 // eslint-disable-next-line no-jquery/no-global-selector
389 $( '.fullMedia' ).append( $mmvButton );
390
391 const image = new LightboxImage(
392 $thumb.prop( 'src' ),
393 title,
394 this.thumbs.length,
395 1,
396 $thumb[ 0 ],
397 ''
398 );
399 this.thumbs.push( image );
400
401 $mmvButton.on( 'click', () => this.openImage( image ) );
402
403 if ( Config.shouldShowStatusInfo() ) {
404 Config.disableStatusInfo();
405 this.showStatusInfo();
406 }
407 }
408
409 /**
410 * Shows a popup notifying the user
411 */
412 showStatusInfo() {
413 mw.loader.using( 'oojs-ui-core' ).done( () => {
414 const content = document.createElement( 'div' );
415 content.textContent = mw.msg( 'multimediaviewer-disable-info' );
416
417 const popupWidget = new OO.ui.PopupWidget( {
418 label: mw.msg( 'multimediaviewer-disable-info-title' ),
419 $content: $( content ),
420 padded: true,
421 head: true,
422 anchor: true,
423 align: 'center',
424 position: 'above',
425 autoFlip: false,
426 horizontalPosition: 'start',
427 // eslint-disable-next-line no-jquery/no-global-selector
428 $floatableContainer: $( '.mw-mmv-view-expanded' )
429 } );
430 popupWidget.$element.appendTo( document.body );
431 popupWidget.toggleClipping( true );
432 popupWidget.toggle( true );
433 } );
434 }
435
436 /**
437 * Finds the caption for an image.
438 *
439 * @param {jQuery} $thumbContainer The container for the thumbnail.
440 * @param {jQuery} $link The link that encompasses the thumbnail.
441 * @return {string|undefined} Unsafe HTML may be present - caution
442 */
443 findCaption( $thumbContainer, $link ) {
444 if ( !$thumbContainer.length ) {
445 return $link.prop( 'title' ) || undefined;
446 }
447
448 let $thumbCaption = $thumbContainer.find( '.thumbcaption' );
449 if ( $thumbCaption.length > 1 ) {
450 // Template:Multiple_image or some such; try to find closest caption to the image
451 // eslint-disable-next-line no-jquery/no-sizzle
452 $thumbCaption = $link.closest( ':has(> .thumbcaption)', $thumbContainer )
453 .find( '> .thumbcaption' );
454 }
455
456 if ( !$thumbCaption.length ) { // gallery, maybe
457 $thumbCaption = $thumbContainer
458 .closest( '.gallerybox' )
459 .not(
460 // do not treat categories as galleries - the autogenerated caption they have is not helpful
461 () => $thumbContainer.closest( '#mw-category-media' ).length
462 )
463 .not( () => {
464 // do not treat special file related pages as galleries
465 const $specialFileRelatedPages = $(
466 '.page-Special_NewFiles, ' +
467 '.page-Special_MostLinkedFiles,' +
468 '.page-Special_MostGloballyLinkedFiles, ' +
469 '.page-Special_UncategorizedFiles, ' +
470 '.page-Special_UnusedFiles'
471 );
472 return $thumbContainer.closest( $specialFileRelatedPages ).length;
473 } )
474 .find( '.gallerytext' );
475 }
476
477 if ( $thumbCaption.find( '.magnify' ).length ) {
478 $thumbCaption = $thumbCaption.clone();
479 $thumbCaption.find( '.magnify' ).remove();
480 }
481
482 return $thumbCaption.html() || '';
483 }
484
485 /**
486 * Opens MediaViewer and loads the given thumbnail. Requires processThumb() to be called first.
487 *
488 * @param {LightboxImage} image Image
489 */
490 openImage( image ) {
491 this.ensureEventHandlersAreSetUp();
492 const hash = Config.getMediaHash( image.filePageTitle, image.position );
493 location.hash = hash;
494 history.replaceState( MANAGED_STATE, null, hash );
495 }
496
497 /**
498 * Handles a click event on a link
499 *
500 * @param {jQuery.Event} e jQuery event object
501 * @param {LightboxImage} image Image
502 * @return {boolean} a value suitable for an event handler (ie. true if the click should be handled
503 * by the browser).
504 */
505 click( e, image ) {
506 // Do not interfere with non-left clicks or if modifier keys are pressed.
507 if ( ( e.button !== 0 && e.which !== 1 ) || e.altKey || e.ctrlKey || e.shiftKey || e.metaKey ) {
508 return true;
509 }
510
511 // Don't load if someone has specifically stopped us from doing so
512 if ( !Config.isMediaViewerEnabledOnClick() ) {
513 return true;
514 }
515
516 // Don't load if we already tried loading and it failed
517 if ( this.viewerIsBroken ) {
518 return true;
519 }
520
521 // Mark the state so that if the page is refreshed, we don't generate an extra history entry
522 this.openImage( image );
523
524 // calling this late so that in case of errors users at least get to the file page
525 e.preventDefault();
526
527 return false;
528 }
529
530 /**
531 * Returns true if the hash part of the current URL is one that's owned by MMV.
532 *
533 * @return {boolean}
534 * @private
535 */
536 isViewerHash() {
537 const path = location.hash.slice( 1 );
538 return path.match( Config.ROUTE_REGEXP ) || path.match( Config.LEGACY_ROUTE_REGEXP );
539 }
540
541 /**
542 * Handles the browser location hash on pageload or hash change
543 */
544 hash() {
545 const isViewerHash = this.isViewerHash();
546
547 // There is no point loading the mmv if it isn't loaded yet for hash changes unrelated to the mmv
548 // Such as anchor links on the page
549 if ( !this.viewerInitialized && !isViewerHash ) {
550 return;
551 }
552
553 const hash = location.hash;
554 if ( window.history.state !== MANAGED_STATE ) {
555 // First replace the current URL with a URL with a hash.
556 history.replaceState( null, null, '#' );
557 history.pushState( MANAGED_STATE, null, hash );
558 }
559 this.router.checkRoute();
560 }
561
562 /**
563 * Instantiates a new viewer if necessary
564 *
565 * @param {Function} localRequire
566 * @return {MultimediaViewer}
567 */
568 getViewer( localRequire ) {
569 if ( this.viewer === undefined ) {
570 const { MultimediaViewer } = localRequire( 'mmv' );
571 this.viewer = new MultimediaViewer();
572 this.viewer.setupEventHandlers();
573 }
574
575 return this.viewer;
576 }
577
578 /**
579 * Listens to events on the window/document
580 */
581 setupEventHandlers() {
582 /** @property {boolean} eventHandlersHaveBeenSetUp tracks domready event handler state */
583 this.eventHandlersHaveBeenSetUp = true;
584
585 // Interpret any hash that might already be in the url
586 this.hash( true );
587
588 $( document ).on( 'mmv-setup-overlay', () => {
589 this.setupOverlay();
590 } ).on( 'mmv-cleanup-overlay', () => {
591 this.cleanupOverlay();
592 } );
593 }
594
595 /**
596 * Cleans up event handlers, used for tests
597 */
598 cleanupEventHandlers() {
599 $( document ).off( 'mmv-setup-overlay mmv-cleanup-overlay' );
600 this.eventHandlersHaveBeenSetUp = false;
601 }
602
603 /**
604 * Makes sure event handlers are set up properly via MultimediaViewerBootstrap.setupEventHandlers().
605 * Called before loading the main mmv module. At this point, event handers for MultimediaViewerBootstrap
606 * should have been set up, but due to bug 70756 it cannot be guaranteed.
607 */
608 ensureEventHandlersAreSetUp() {
609 if ( !this.eventHandlersHaveBeenSetUp ) {
610 this.setupEventHandlers();
611 }
612 }
613
614 /**
615 * Sets up the overlay while the viewer loads
616 */
617 setupOverlay() {
618 const $body = $( document.body );
619
620 // There are situations where we can call setupOverlay while the overlay is already there,
621 // such as inside this.hash(). In that case, do nothing
622 if ( $body.hasClass( 'mw-mmv-lightbox-open' ) ) {
623 return;
624 }
625
626 if ( !this.$overlay ) {
627 this.$overlay = $( '<div>' )
628 // Dark overlay should stay dark in dark mode
629 .addClass( 'mw-mmv-overlay mw-no-invert' );
630
631 this.$loadBar = $( '<div>' )
632 .addClass( 'cdx-progress-bar' )
633 .attr( {
634 role: 'progressbar',
635 'aria-label': mw.msg( 'multimediaviewer-loading' )
636 } ).append( $( '<div>' ).addClass( 'cdx-progress-bar__bar' ) );
637 this.$overlay.append( this.$loadBar );
638 }
639
640 this.savedScrollTop = $( window ).scrollTop();
641
642 $body.addClass( 'mw-mmv-lightbox-open' )
643 .append( this.$overlay );
644 }
645
646 /**
647 * Cleans up the overlay
648 */
649 cleanupOverlay() {
650 $( document.body ).removeClass( 'mw-mmv-lightbox-open' );
651
652 if ( this.$overlay ) {
653 this.$overlay.remove();
654 }
655
656 if ( this.savedScrollTop !== undefined ) {
657 // setTimeout because otherwise Chrome will scroll back to top after the popstate event handlers run
658 setTimeout( () => {
659 $( window ).scrollTop( this.savedScrollTop );
660 this.savedScrollTop = undefined;
661 } );
662 }
663 }
664
665 whenThumbsReady() {
666 return this.thumbsReadyDeferred.promise();
667 }
668 }
669
670 module.exports = MultimediaViewerBootstrap;