Debian Codegraph @

extensions/MultimediaViewer/resources/mmv/mmv.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.bootstrap' );
19 const HtmlUtils = require( './mmv.HtmlUtils.js' );
20 const ViewLogger = require( './logging/mmv.logging.ViewLogger.js' );
21 const Api = require( './provider/mmv.provider.Api.js' );
22 const GuessedThumbnailInfo = require( './provider/mmv.provider.GuessedThumbnailInfo.js' );
23 const ImageProvider = require( './provider/mmv.provider.Image.js' );
24 const ImageInfo = require( './provider/mmv.provider.ImageInfo.js' );
25 const ThumbnailInfo = require( './provider/mmv.provider.ThumbnailInfo.js' );
26 const ImageModel = require( './model/mmv.model.Image.js' );
27 const License = require( './model/mmv.model.License.js' );
28 const TaskQueue = require( './model/mmv.model.TaskQueue.js' );
29 const Thumbnail = require( './model/mmv.model.Thumbnail.js' );
30 const ThumbnailWidth = require( './model/mmv.model.ThumbnailWidth.js' );
31 const Canvas = require( './ui/mmv.ui.canvas.js' );
32 const CanvasButtons = require( './ui/mmv.ui.canvasButtons.js' );
33 const Description = require( './ui/mmv.ui.description.js' );
34 const Dialog = require( './ui/mmv.ui.dialog.js' );
35 const UiElement = require( './ui/mmv.ui.js' );
36 const MetadataPanel = require( './ui/mmv.ui.metadataPanel.js' );
37 const MetadataPanelScroller = require( './ui/mmv.ui.metadataPanelScroller.js' );
38 const Permission = require( './ui/mmv.ui.permission.js' );
39 const ProgressBar = require( './ui/mmv.ui.progressBar.js' );
40 const StripeButtons = require( './ui/mmv.ui.stripeButtons.js' );
41 const TruncatableTextField = require( './ui/mmv.ui.truncatableTextField.js' );
42 const LightboxInterface = require( './mmv.lightboxinterface.js' );
43 const ThumbnailWidthCalculator = require( './mmv.ThumbnailWidthCalculator.js' );
44 const { extensions, useThumbnailGuessing } = require( './config.json' );
45
46 const router = require( 'mediawiki.router' );
47 let comingFromHashChange = false;
48
49 /**
50 * Analyses the page, looks for image content and sets up the hooks
51 * to manage the viewing experience of such content.
52 */
53 class MultimediaViewer {
54 constructor() {
55 const apiCacheMaxAge = 86400; // one day (24 hours * 60 min * 60 sec)
56 const apiCacheFiveMinutes = 300; // 5 min * 60 sec
57 const api = new mw.Api();
58
59 /**
60 * @property {ImageProvider}
61 * @private
62 */
63 this.imageProvider = new ImageProvider();
64
65 /**
66 * @property {ImageInfo}
67 * @private
68 */
69 this.imageInfoProvider = new ImageInfo( api, {
70 language: Config.language(),
71 maxage: apiCacheFiveMinutes
72 } );
73
74 /**
75 * @property {ThumbnailInfo}
76 * @private
77 */
78 this.thumbnailInfoProvider = new ThumbnailInfo( api,
79 { maxage: apiCacheMaxAge } );
80
81 /**
82 * @property {ThumbnailInfo}
83 * @private
84 */
85 this.guessedThumbnailInfoProvider = new GuessedThumbnailInfo();
86
87 /**
88 * Image index on page.
89 *
90 * @property {number}
91 */
92 this.currentIndex = 0;
93
94 /**
95 * @property {OO.Router} router
96 */
97 this.router = router;
98 this.setupRouter();
99 comingFromHashChange = false;
100
101 /**
102 * UI object used to display the pictures in the page.
103 *
104 * @property {LightboxInterface}
105 * @private
106 */
107 this.ui = new LightboxInterface();
108
109 /** @property {string} documentTitle base document title, MediaViewer will expand this */
110 this.documentTitle = document.title;
111
112 /**
113 * @property {ViewLogger} view -
114 */
115 this.viewLogger = new ViewLogger( window );
116
117 /**
118 * Stores whether the real image was loaded and displayed already.
119 * This is reset when paging, so it is not necessarily accurate.
120 *
121 * @property {boolean}
122 */
123 this.realThumbnailShown = false;
124 }
125
126 /**
127 * Initialize the lightbox interface given an array of thumbnail
128 * objects.
129 *
130 * @param {LightboxImage[]} thumbs
131 */
132 initWithThumbs( thumbs ) {
133 this.thumbs = thumbs;
134 }
135
136 /**
137 * Handles resize events in viewer.
138 */
139 resize() {
140 const image = this.thumbs[ this.currentIndex ];
141 const ext = this.thumbs[ this.currentIndex ].filePageTitle.getExtension().toLowerCase();
142
143 this.preloadThumbnails();
144
145 if ( image ) {
146 const imageWidths = this.ui.canvas.getCurrentImageWidths();
147
148 this.fetchThumbnailForLightboxImage(
149 image, imageWidths.real
150 ).then( ( thumbnail, image2 ) => {
151 // eslint-disable-next-line mediawiki/class-doc
152 image2.className = ext;
153 this.setImage( thumbnail, image2, imageWidths );
154 }, ( error ) => {
155 this.ui.canvas.showError( error );
156 } );
157 }
158
159 this.ui.updateControls( this.thumbs.length > 1 );
160 }
161
162 /**
163 * Loads and sets the specified image. It also updates the controls.
164 *
165 * @param {Thumbnail} thumbnail thumbnail information
166 * @param {HTMLImageElement} imageElement
167 * @param {ThumbnailWidth} imageWidths
168 */
169 setImage( thumbnail, imageElement, imageWidths ) {
170 this.ui.canvas.setImageAndMaxDimensions( thumbnail, imageElement, imageWidths );
171 this.ui.updateControls( this.thumbs.length > 1 );
172 }
173
174 /**
175 * Loads a specified image.
176 *
177 * @param {LightboxImage} image
178 */
179 loadImage( image ) {
180 const $initialImage = $( image.thumbnail ).clone();
181
182 const pluginsPromise = this.loadExtensionPlugins( image.filePageTitle.getExtension().toLowerCase() );
183
184 this.currentIndex = image.index;
185
186 this.currentImage = image;
187
188 if ( !this.isOpen ) {
189 $( document ).trigger( $.Event( 'mmv-setup-overlay' ) );
190 this.ui.open();
191 this.isOpen = true;
192 } else {
193 this.ui.empty();
194 }
195
196 this.setTitle();
197
198 // At this point we can't show the thumbnail because we don't
199 // know what size it should be. We still assign it to allow for
200 // size calculations in getCurrentImageWidths, which needs to know
201 // the aspect ratio
202 // eslint-disable-next-line mediawiki/class-doc
203 $initialImage.hide()
204 .removeAttr( 'style' )
205 .removeClass()
206 .addClass( `mw-mmv-placeholder-image ${ image.filePageTitle.getExtension().toLowerCase() }` );
207
208 this.ui.canvas.set( image, $initialImage );
209
210 this.preloadImagesMetadata();
211 this.preloadThumbnails();
212 const imageWidths = this.ui.canvas.getCurrentImageWidths();
213
214 const imagePromise = this.fetchThumbnailForLightboxImage( image, imageWidths.real );
215
216 if ( imagePromise.state() === 'pending' ) {
217 this.displayPlaceholderThumbnail( image, $initialImage, imageWidths );
218 }
219 this.resetThumbnailStates();
220 this.setupProgressBar( image, imagePromise, imageWidths.real );
221
222 const metadataPromise = this.fetchSizeIndependentLightboxInfo( image.filePageTitle );
223
224 imagePromise.then(
225 // done
226 ( thumbnail, imageElement ) => {
227 if ( this.currentIndex !== image.index ) {
228 return;
229 }
230
231 // eslint-disable-next-line mediawiki/class-doc
232 imageElement.className = `mw-mmv-final-image ${ image.filePageTitle.getExtension().toLowerCase() }`;
233 imageElement.alt = image.alt;
234
235 $.when( metadataPromise, pluginsPromise ).then( ( imageInfo ) => {
236 $( document ).trigger( $.Event( 'mmv-metadata', { viewer: this, image, imageInfo } ) );
237 } );
238
239 this.displayRealThumbnail( thumbnail, imageElement, imageWidths );
240 },
241 // fail
242 ( error ) => {
243 this.ui.canvas.showError( error );
244 return $.Deferred().reject( error );
245 }
246 );
247
248 metadataPromise.then(
249 // done
250 ( imageInfo ) => {
251 if ( this.currentIndex !== image.index ) {
252 return;
253 }
254
255 this.ui.panel.setImageInfo( image, imageInfo );
256
257 // File reuse steals a bunch of information from the DOM, so do it last
258 this.ui.setFileReuseData( imageInfo, image.caption, image.alt );
259 },
260 // fail
261 ( error ) => {
262 if ( this.currentIndex === image.index ) {
263 // Set title to caption or file name if caption is not available;
264 // see setTitle() in mmv.ui.metadataPanel for extended caption fallback
265 this.ui.panel.showError( image.caption ?
266 HtmlUtils.htmlToTextWithTags( image.caption ) :
267 image.filePageTitle.getNameText(), error );
268 }
269
270 return $.Deferred().reject( error );
271 }
272 );
273
274 $.when( imagePromise, metadataPromise ).then( () => {
275 if ( this.currentIndex !== image.index ) {
276 return;
277 }
278
279 this.ui.panel.scroller.animateMetadataOnce();
280 } );
281 }
282
283 /**
284 * Loads an image by its title
285 *
286 * @param {mw.Title} title
287 * @param {number} [position]
288 */
289 loadImageByTitle( title, position ) {
290 if ( !this.thumbs || !this.thumbs.length ) {
291 return;
292 }
293
294 const thumb = this.thumbs.find( ( t ) => t.filePageTitle.getPrefixedText() === title.getPrefixedText() &&
295 ( !position || t.position === position )
296 );
297
298 if ( !thumb ) {
299 this.onTitleNotFound( title );
300 return;
301 }
302
303 this.loadImage( thumb );
304 }
305
306 /**
307 * When the image to load is not present on the current page,
308 * a notification is shown to the user and the MMV is closed.
309 *
310 * @param {mw.Title} title
311 * @private
312 */
313 onTitleNotFound( title ) {
314 this.close();
315 const text = mw.msg( 'multimediaviewer-file-not-found-error', title.getMainText() );
316 const $link = $( '<a>' ).text( mw.msg( 'multimediaviewer-file-page' ) ).prop( 'href', title.getUrl() );
317 const $message = $( '<div>' ).text( text ).append( $( '<br>' ) ).append( $link );
318 mw.notify( $message );
319 }
320
321 /**
322 * Resets the cross-request states needed to handle the thumbnail logic.
323 */
324 resetThumbnailStates() {
325 this.realThumbnailShown = false;
326 }
327
328 /**
329 * Display the real, full-resolution, thumbnail that was fetched with fetchThumbnail
330 *
331 * @param {Thumbnail} thumbnail
332 * @param {HTMLImageElement} imageElement
333 * @param {ThumbnailWidth} imageWidths
334 */
335 displayRealThumbnail( thumbnail, imageElement, imageWidths ) {
336 this.realThumbnailShown = true;
337 this.setImage( thumbnail, imageElement, imageWidths );
338 this.viewLogger.attach( thumbnail.url );
339 }
340
341 /**
342 * Display the thumbnail from the page
343 *
344 * @param {LightboxImage} image
345 * @param {jQuery} $initialImage The thumbnail from the page
346 * @param {ThumbnailWidth} imageWidths
347 * @param {boolean} [recursion=false] for internal use, never set this when calling from outside
348 */
349 displayPlaceholderThumbnail( image, $initialImage, imageWidths, recursion ) {
350 const size = { width: image.originalWidth, height: image.originalHeight };
351
352 // If the actual image has already been displayed, there's no point showing the thumbnail.
353 // This can happen if the API request to get the original image size needed to show the
354 // placeholder thumbnail takes longer then loading the actual thumbnail.
355 if ( this.realThumbnailShown ) {
356 return;
357 }
358
359 // Width/height of the original image are added to the HTML by MediaViewer via a PHP hook,
360 // and can be missing in exotic circumstances, e. g. when the extension has only been
361 // enabled recently and the HTML cache has not cleared yet. If that is the case, we need
362 // to fetch the size from the API first.
363 if ( !size.width || !size.height ) {
364 if ( recursion ) {
365 // this should not be possible, but an infinite recursion is nasty
366 // business, so we make a sense check
367 throw new Error( 'MediaViewer internal error: displayPlaceholderThumbnail recursion' );
368 }
369 this.imageInfoProvider.get( image.filePageTitle ).done( ( imageInfo ) => {
370 // Make sure the user has not navigated away while we were waiting for the size
371 if ( this.currentIndex === image.index ) {
372 image.originalWidth = imageInfo.width;
373 image.originalHeight = imageInfo.height;
374 this.displayPlaceholderThumbnail( image, $initialImage, imageWidths, true );
375 }
376 } );
377 } else {
378 this.ui.canvas.maybeDisplayPlaceholder( size, $initialImage, imageWidths );
379 }
380 }
381
382 /**
383 * Displays a progress bar for the image loading, if necessary, and sets up handling of
384 * all the related callbacks.
385 *
386 * @param {LightboxImage} image
387 * @param {jQuery.Promise.<Thumbnail, HTMLImageElement>} imagePromise
388 * @param {number} imageWidth needed for caching progress (FIXME)
389 */
390 setupProgressBar( image, imagePromise, imageWidth ) {
391 const progressBar = this.ui.panel.progressBar;
392 const key = `${ image.filePageTitle.getPrefixedDb() }|${ imageWidth }`;
393
394 if ( !this.progressCache[ key ] ) {
395 // Animate progress bar to 5 to give a sense that something is happening, and make sure
396 // the progress bar is noticeable, even if we're sitting at 0% stuck waiting for
397 // server-side processing, such as thumbnail (re)generation
398 progressBar.jumpTo( 0 );
399 progressBar.animateTo( 5 );
400 this.progressCache[ key ] = 5;
401 } else {
402 progressBar.jumpTo( this.progressCache[ key ] );
403 }
404
405 // FIXME would be nice to have a "filtered" promise which does not fire when the image is not visible
406 imagePromise.then(
407 // done
408 ( thumbnail, imageElement ) => {
409 this.progressCache[ key ] = 100;
410 if ( this.currentIndex === image.index ) {
411 // Fallback in case the browser doesn't have fancy progress updates
412 progressBar.animateTo( 100 );
413
414 // Hide progress bar, we're done
415 // TODO not really needed, but testcase depends on it
416 progressBar.hide();
417 }
418
419 return $.Deferred().resolve( thumbnail, imageElement );
420 },
421 // fail
422 ( error ) => {
423 this.progressCache[ key ] = 100;
424
425 if ( this.currentIndex === image.index ) {
426 // Hide progress bar on error
427 progressBar.hide();
428 }
429
430 return $.Deferred().reject( error );
431 },
432 // progress
433 ( progress ) => {
434 // We pretend progress is always at least 5%, so progress events below 5% should be ignored
435 // 100 will be handled by the done handler, do not mix two animations
436 if ( progress >= 5 && progress < 100 ) {
437 this.progressCache[ key ] = progress;
438
439 // Touch the UI only if the user is looking at this image
440 if ( this.currentIndex === image.index ) {
441 progressBar.animateTo( progress );
442 }
443 }
444
445 return progress;
446 }
447 );
448 }
449
450 /**
451 * Orders lightboximage indexes for preloading. Works similar to $.each, except it only takes
452 * the callback argument. Calls the callback with each lightboximage index in some sequence
453 * that is ideal for preloading.
454 *
455 * @private
456 * @param {function(number, LightboxImage)} callback
457 */
458 eachPreloadableLightboxIndex( callback ) {
459 for ( let i = 0; i <= this.preloadDistance; i++ ) {
460 if ( this.currentIndex + i < this.thumbs.length ) {
461 callback(
462 this.currentIndex + i,
463 this.thumbs[ this.currentIndex + i ]
464 );
465 }
466 if ( i && this.currentIndex - i >= 0 ) { // skip duplicate for i==0
467 callback(
468 this.currentIndex - i,
469 this.thumbs[ this.currentIndex - i ]
470 );
471 }
472 }
473 }
474
475 /**
476 * A helper function to fill up the preload queues.
477 * taskFactory(lightboxImage) should return a preload task for the given lightboximage.
478 *
479 * @private
480 * @param {function(LightboxImage)} taskFactory
481 * @return {TaskQueue}
482 */
483 pushLightboxImagesIntoQueue( taskFactory ) {
484 const queue = new TaskQueue();
485
486 this.eachPreloadableLightboxIndex( ( i, lightboxImage ) => {
487 queue.push( taskFactory( lightboxImage ) );
488 } );
489
490 return queue;
491 }
492
493 /**
494 * Cancels in-progress image metadata preloading.
495 */
496 cancelImageMetadataPreloading() {
497 if ( this.metadataPreloadQueue ) {
498 this.metadataPreloadQueue.cancel();
499 }
500 }
501
502 /**
503 * Cancels in-progress image thumbnail preloading.
504 */
505 cancelThumbnailsPreloading() {
506 if ( this.thumbnailPreloadQueue ) {
507 this.thumbnailPreloadQueue.cancel();
508 }
509 }
510
511 /**
512 * Preload metadata for next and prev N image (N = MMVP.preloadDistance).
513 * Two images will be loaded at a time (one forward, one backward), with closer images
514 * being loaded sooner.
515 */
516 preloadImagesMetadata() {
517 this.cancelImageMetadataPreloading();
518
519 this.metadataPreloadQueue = this.pushLightboxImagesIntoQueue( ( lightboxImage ) => () => this.fetchSizeIndependentLightboxInfo( lightboxImage.filePageTitle ) );
520
521 this.metadataPreloadQueue.execute();
522 }
523
524 /**
525 * Preload thumbnails for next and prev N image (N = MMVP.preloadDistance).
526 * Two images will be loaded at a time (one forward, one backward), with closer images
527 * being loaded sooner.
528 */
529 preloadThumbnails() {
530 this.cancelThumbnailsPreloading();
531
532 this.thumbnailPreloadQueue = this.pushLightboxImagesIntoQueue( ( lightboxImage ) => () => {
533 // viewer.ui.canvas.getLightboxImageWidths needs the viewer to be open
534 // because it needs to read the size of visible elements
535 if ( !this.isOpen ) {
536 return;
537 }
538
539 const imageWidths = this.ui.canvas.getLightboxImageWidths( lightboxImage );
540
541 return this.fetchThumbnailForLightboxImage( lightboxImage, imageWidths.real );
542 } );
543
544 this.thumbnailPreloadQueue.execute();
545 }
546
547 /**
548 * Loads all the size-independent information needed by the lightbox (image metadata, repo
549 * information).
550 *
551 * @param {mw.Title} fileTitle Title of the file page for the image.
552 * @return {jQuery.Promise.<ImageModel>}
553 */
554 fetchSizeIndependentLightboxInfo( fileTitle ) {
555 return this.imageInfoProvider.get( fileTitle );
556 }
557
558 /**
559 * Loads size-dependent components of a lightbox - the thumbnail model and the image itself.
560 *
561 * @param {LightboxImage} image
562 * @param {number} width the width of the requested thumbnail
563 * @return {jQuery.Promise.<Thumbnail, HTMLImageElement>}
564 */
565 fetchThumbnailForLightboxImage( image, width ) {
566 return this.fetchThumbnail(
567 image.filePageTitle,
568 width,
569 image.src,
570 image.originalWidth,
571 image.originalHeight
572 );
573 }
574
575 /**
576 * Loads size-dependent components of a lightbox - the thumbnail model and the image itself.
577 *
578 * @param {mw.Title} fileTitle
579 * @param {number} width the width of the requested thumbnail
580 * @param {string} [sampleUrl] a thumbnail URL for the same file (but with different size) (might be missing)
581 * @param {number} [originalWidth] the width of the original, full-sized file (might be missing)
582 * @param {number} [originalHeight] the height of the original, full-sized file (might be missing)
583 * @param {boolean} [useThumbnailGuessing0] the useThumbnailGuessing flag
584 * @return {jQuery.Promise.<Thumbnail, HTMLImageElement>} A promise resolving to
585 * a thumbnail model and an <img> element. It might or might not have progress events which
586 * return a single number.
587 */
588 fetchThumbnail( fileTitle, width, sampleUrl, originalWidth, originalHeight, useThumbnailGuessing0 = useThumbnailGuessing ) {
589 let guessing = false;
590 const combinedDeferred = $.Deferred();
591 let thumbnailPromise;
592 let imagePromise;
593
594 if ( fileTitle.getExtension().toLowerCase() !== 'svg' && originalWidth && width > originalWidth ) {
595 // Do not request images larger than the original image
596 width = originalWidth;
597 }
598
599 if ( sampleUrl && originalWidth && originalHeight && useThumbnailGuessing0 ) {
600 guessing = true;
601 thumbnailPromise = this.guessedThumbnailInfoProvider.get(
602 fileTitle, sampleUrl, width, originalWidth, originalHeight
603 ).then( null, () => this.thumbnailInfoProvider.get( fileTitle, sampleUrl, width ) );
604 } else {
605 thumbnailPromise = this.thumbnailInfoProvider.get( fileTitle, sampleUrl, width );
606 }
607
608 imagePromise = thumbnailPromise.then( ( thumbnail ) => this.imageProvider.get( thumbnail.url ) );
609
610 if ( guessing ) {
611 // If we guessed wrong, need to retry with real URL on failure.
612 // As a side effect this introduces an extra (harmless) retry of a failed thumbnailInfoProvider.get call
613 // because thumbnailInfoProvider.get is already called above when guessedThumbnailInfoProvider.get fails.
614 imagePromise = imagePromise
615 .then( null, () => this.thumbnailInfoProvider.get( fileTitle, sampleUrl, width )
616 .then( ( thumbnail ) => this.imageProvider.get( thumbnail.url ) ) );
617 }
618
619 // In jQuery<3, $.when used to also relay notify, but that is no longer
620 // the case - but we still want to pass it along...
621 $.when( thumbnailPromise, imagePromise ).then( combinedDeferred.resolve, combinedDeferred.reject );
622 imagePromise.then( null, null, ( arg, progress ) => {
623 combinedDeferred.notify( progress );
624 } );
625 return combinedDeferred;
626 }
627
628 /**
629 * Loads an image at a specified index in the viewer's thumbnail array.
630 *
631 * @param {number} index
632 */
633 loadIndex( index ) {
634 if ( index < this.thumbs.length && index >= 0 ) {
635 this.viewLogger.recordViewDuration();
636
637 const thumb = this.thumbs[ index ];
638 this.loadImage( thumb );
639 router.navigateTo( null, {
640 path: Config.getMediaHash( thumb.filePageTitle, thumb.position ),
641 useReplaceState: true
642 } );
643 }
644 }
645
646 /**
647 * Opens the last image
648 */
649 firstImage() {
650 this.loadIndex( 0 );
651 }
652
653 /**
654 * Opens the last image
655 */
656 lastImage() {
657 this.loadIndex( this.thumbs.length - 1 );
658 }
659
660 /**
661 * Opens the next image
662 */
663 nextImage() {
664 if ( this.currentIndex === this.thumbs.length - 1 ) {
665 this.firstImage();
666 } else {
667 this.loadIndex( this.currentIndex + 1 );
668 }
669 }
670
671 /**
672 * Opens the previous image
673 */
674 prevImage() {
675 if ( this.currentIndex === 0 ) {
676 this.lastImage();
677 } else {
678 this.loadIndex( this.currentIndex - 1 );
679 }
680 }
681
682 /**
683 * Handles close event coming from the lightbox
684 */
685 close() {
686 this.viewLogger.recordViewDuration();
687 this.viewLogger.unattach();
688
689 if ( comingFromHashChange ) {
690 comingFromHashChange = false;
691 } else {
692 this.router.back();
693 }
694 // update title after route change, see T225387
695 document.title = this.createDocumentTitle( null );
696
697 // This has to happen after the hash reset, because setting the hash to # will reset the page scroll
698 $( document ).trigger( $.Event( 'mmv-cleanup-overlay' ) );
699
700 this.isOpen = false;
701 }
702
703 /**
704 * Sets up the route handlers
705 */
706 setupRouter() {
707 // handle empty hashes, and anchor links (page sections, possibly including /)
708 this.router.addRoute( /.*$/, () => {
709 if ( this.isOpen ) {
710 comingFromHashChange = true;
711 document.title = this.createDocumentTitle( null );
712 if ( this.ui ) {
713 // FIXME triggers mmv-close event, which calls viewer.close()
714 this.ui.unattach();
715 } else {
716 this.close();
717 }
718 }
719 } );
720 }
721
722 /**
723 * Updates the page title to reflect the current title.
724 */
725 setTitle() {
726 // update title after route change, see T225387
727 document.title = this.createDocumentTitle( this.currentImage && this.currentImage.filePageTitle );
728 }
729
730 /**
731 * Creates a string which can be shown as document title (the text at the top of the browser window).
732 *
733 * @param {mw.Title|null} imageTitle the title object for the image which is displayed; null when the
734 * viewer is being closed
735 * @return {string}
736 */
737 createDocumentTitle( imageTitle ) {
738 if ( imageTitle ) {
739 return `${ imageTitle.getNameText() } - ${ this.documentTitle }`;
740 } else {
741 return this.documentTitle;
742 }
743 }
744
745 /**
746 * Fired when the viewer is closed. This is used by the lightbox to notify the main app.
747 *
748 * @event MultimediaViewer#mmv-close
749 */
750
751 /**
752 * Fired when the user requests the next image.
753 *
754 * @event MultimediaViewer#mmv-next
755 */
756
757 /**
758 * Fired when the user requests the previous image.
759 *
760 * @event MultimediaViewer#mmv-prev
761 */
762
763 /**
764 * Fired when the screen size changes. Debounced to avoid continuous triggering while resizing with a mouse.
765 *
766 * @event MultimediaViewer#mmv-resize-end
767 */
768
769 /**
770 * Used by components to request a thumbnail URL for the current thumbnail, with a given size.
771 *
772 * @event MultimediaViewer#mmv-request-thumbnail
773 * @param {number} size
774 */
775
776 /**
777 * Registers all event handlers
778 */
779 setupEventHandlers() {
780 this.ui.connect( this, {
781 first: 'firstImage',
782 last: 'lastImage',
783 next: 'nextImage',
784 prev: 'prevImage'
785 } );
786
787 $( document ).on( 'mmv-close.mmvp', () => {
788 this.close();
789 } ).on( 'mmv-resize-end.mmvp', () => {
790 this.resize();
791 } ).on( 'mmv-request-thumbnail.mmvp', ( e, size ) => {
792 if ( this.currentImage && this.currentImage.filePageTitle ) {
793 return this.thumbnailInfoProvider.get( this.currentImage.filePageTitle, this.currentImage.src, size );
794 } else {
795 return $.Deferred().reject();
796 }
797 } ).on( 'mmv-viewfile.mmvp', () => {
798 this.imageInfoProvider.get( this.currentImage.filePageTitle ).done( ( imageInfo ) => {
799 document.location = imageInfo.url;
800 } );
801 } );
802 }
803
804 /**
805 * Unregisters all event handlers. Currently only used in tests.
806 */
807 cleanupEventHandlers() {
808 $( document ).off( 'mmv-close.mmvp mmv-resize-end.mmvp' );
809
810 this.ui.disconnect( this );
811 }
812
813 /**
814 * Loads the RL module defined for a given file extension, if any
815 *
816 * @param {string} extension File extension
817 * @return {jQuery.Promise}
818 */
819 loadExtensionPlugins( extension ) {
820 const deferred = $.Deferred();
821
822 if ( !( extension in extensions ) || extensions[ extension ] === 'default' ) {
823 return deferred.resolve();
824 }
825
826 mw.loader.using( extensions[ extension ], () => {
827 deferred.resolve();
828 } );
829
830 return deferred;
831 }
832 }
833
834 /**
835 * Image loading progress. Keyed by image (database) name + '|' + thumbnail width in pixels,
836 * value is a number between 0-100.
837 *
838 * @private
839 * @property {Object.<string, number>}
840 */
841 MultimediaViewer.prototype.progressCache = {};
842
843 /**
844 * Preload this many prev/next images to speed up navigation.
845 * (E.g. preloadDistance = 3 means that the previous 3 and the next 3 images will be loaded.)
846 * Preloading only happens when the viewer is open.
847 *
848 * @property {number}
849 */
850 MultimediaViewer.prototype.preloadDistance = 1;
851
852 /**
853 * Stores image metadata preloads, so they can be cancelled.
854 *
855 * @property {TaskQueue}
856 */
857 MultimediaViewer.prototype.metadataPreloadQueue = null;
858
859 /**
860 * Stores image thumbnail preloads, so they can be cancelled.
861 *
862 * @property {TaskQueue}
863 */
864 MultimediaViewer.prototype.thumbnailPreloadQueue = null;
865
866 module.exports = {
867 Api,
868 Canvas,
869 CanvasButtons,
870 Description,
871 Dialog,
872 GuessedThumbnailInfo,
873 HtmlUtils,
874 ImageInfo,
875 ImageModel,
876 ImageProvider,
877 License,
878 LightboxInterface,
879 MetadataPanel,
880 MetadataPanelScroller,
881 MultimediaViewer,
882 Permission,
883 ProgressBar,
884 StripeButtons,
885 TaskQueue,
886 Thumbnail,
887 ThumbnailInfo,
888 ThumbnailWidth,
889 ThumbnailWidthCalculator,
890 TruncatableTextField,
891 UiElement,
892 ViewLogger
893 };