diff --git a/src/lib/ImageView.ts b/src/lib/ImageView.ts index 4ef881cf..361d43b5 100644 --- a/src/lib/ImageView.ts +++ b/src/lib/ImageView.ts @@ -43,9 +43,9 @@ export function ImageView( image.dataset["ilb2Video"] !== undefined && videoId !== undefined; if (isVideo) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- Checked by the if above - const videoElement = videoCache.element(videoId!); - if (videoElement !== undefined) { - [imageElement, isVideoPreloaded] = videoElement; + const preloadedVideo = videoCache.get(videoId!); + if (preloadedVideo !== undefined) { + [imageElement, isVideoPreloaded] = preloadedVideo.element(); } else { isVideo = false; } @@ -58,7 +58,18 @@ export function ImageView( nextImage: () => void, closeLightbox: () => void, ): void { - if (!isVideo) { + if (isVideo) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- Checked by the if in the constructor + const preloadedVideo = videoCache.get(videoId!); + if (preloadedVideo?.shouldAutoplay() === true) { + const [videoElement, isLoaded] = preloadedVideo.element(); + if (isLoaded) { + void videoElement.play(); + } else { + videoElement.autoplay = true; + } + } + } else { (imageElement as HTMLImageElement).addEventListener("click", (e) => { e.stopPropagation(); if (options.quitOnImgClick) { diff --git a/src/lib/PreloadedVideo.ts b/src/lib/PreloadedVideo.ts index 4743bf63..8f0c4196 100644 --- a/src/lib/PreloadedVideo.ts +++ b/src/lib/PreloadedVideo.ts @@ -3,6 +3,7 @@ import type { VideoOptions } from "./interfaces/VideoOptions"; export interface PreloadedVideo { element(): [HTMLVideoElement, boolean]; id(): string; + shouldAutoplay(): boolean; } export function PreloadedVideo( @@ -58,18 +59,16 @@ export function PreloadedVideo( } function element(): [HTMLVideoElement, boolean] { - if (autoplay) { - if (isLoaded) { - void videoElement.play(); - } else { - videoElement.autoplay = true; - } - } return [videoElement, isLoaded]; } + function shouldAutoplay(): boolean { + return autoplay; + } + return { element, id, + shouldAutoplay, }; } diff --git a/src/lib/VideoCache.ts b/src/lib/VideoCache.ts index ee9ebe6c..e6b3da19 100644 --- a/src/lib/VideoCache.ts +++ b/src/lib/VideoCache.ts @@ -4,7 +4,7 @@ import { PreloadedVideo } from "./PreloadedVideo"; export interface VideoCache { add(elements: Array): void; - element(videoId: string): [HTMLVideoElement, boolean] | undefined; + get(videoId: string): PreloadedVideo | undefined; } export function VideoCache(): VideoCache { @@ -22,13 +22,12 @@ export function VideoCache(): VideoCache { } } - function element(videoId: string): [HTMLVideoElement, boolean] | undefined { - const video = videos.find((x) => x.id() === videoId); - return video?.element(); + function get(videoId: string): PreloadedVideo | undefined { + return videos.find((x) => x.id() === videoId); } return { add, - element, + get, }; }