π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Simplify video viewer transitions with cover fades
Anand Baburajan7a79e0374856
diff --git a/web/apps/space/src/components/FileViewer.tsx b/web/apps/space/src/components/FileViewer.tsxindex d2a787b01e..31b2d70fec 100644--- a/web/apps/space/src/components/FileViewer.tsx+++ b/web/apps/space/src/components/FileViewer.tsx@@ -37,7 +37,6 @@ import {playViewerOpen,viewerCornerRadii,viewerOriginKey,- viewerVideoFrame,} from "components/viewer-transition";import log from "ente-base/log";import { useCommentCount } from "hooks/use-comment-count";@@ -267,8 +266,12 @@ interface ViewerMotion {reveal?: () => void;}-const endOpenFlight = (motion: ViewerMotion, root: HTMLElement) => {- motion.flight?.release();+const endOpenFlight = (+ motion: ViewerMotion,+ root: HTMLElement,+ fadeOut = false,+) => {+ motion.flight?.release(fadeOut);motion.flight = undefined;delete root.dataset.spaceViewerFlying;delete root.dataset.spaceViewerWaiting;@@ -295,7 +298,7 @@ const handOverOpenFlight = (image.naturalWidth > 0 &&image.isConnected &&!content?.isDecoding);- if (isShown) endOpenFlight(motion, root);+ if (isShown) endOpenFlight(motion, root, content?.data.type == "video");};const viewerTouchPoint = (event: Event) => {@@ -807,6 +810,11 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({viewerPhotosRef.current[pswp?.currIndex ?? activePhotoIndex];const element = pswp?.currSlide?.content.element;const video = element?.querySelector("video");+ const preview =+ element instanceof HTMLImageElement+ ? element+ : element?.querySelector("img");+ const fadeFromVideo = Boolean(video && !motion.flight);let from: ViewerPhotoState | undefined = motion.flight?.current();let src = from ? motion.flight?.src : undefined;const rect = element?.getBoundingClientRect();@@ -817,10 +825,8 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({rect &&rect.width > 0 &&rect.height > 0 &&- ((element instanceof HTMLImageElement &&- element.complete &&- element.naturalWidth > 0) ||- video)+ preview?.complete &&+ preview.naturalWidth > 0) {const scale = Number(pswp.currSlide?.container.style.scale) || 1;from = shownPhotoState(@@ -828,10 +834,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({{ x: 0, y: 0, w: window.innerWidth, h: window.innerHeight },viewerCornerRadii(element, scale),);- src =- element instanceof HTMLImageElement- ? element.currentSrc || element.src- : (viewerVideoFrame(video) ?? video?.poster);+ src = preview.currentSrc || preview.src;}window.scrollTo({ ...pageScrollRef.current, behavior: "instant" });const origin =@@ -856,6 +859,7 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({{origin,src,+ fadeFromVideo,photo: {width: item.width ?? defaultPhotoWidth,height: item.height ?? defaultPhotoHeight,@@ -864,9 +868,11 @@ export const SpaceFileViewer: React.FC<SpaceFileViewerProps> = ({from,throwVelocity,startBackground,+ () => {+ if (root.isConnected) onCloseRef.current();+ },);- }- onCloseRef.current();+ } else onCloseRef.current();};React.useImperativeHandle(diff --git a/web/apps/space/src/components/InlinePostVideo.tsx b/web/apps/space/src/components/InlinePostVideo.tsxindex b6074ff6af..acda39a533 100644--- a/web/apps/space/src/components/InlinePostVideo.tsx+++ b/web/apps/space/src/components/InlinePostVideo.tsx@@ -72,7 +72,9 @@ export const SpaceInlinePostVideo: React.FC<{}, [shouldPreload, onLoadVideo, video]);useEffect(() => {- player.current!.setPoster(imageUrl);+ const element = player.current!.video;+ if (imageUrl) element.poster = imageUrl;+ else element.removeAttribute("poster");}, [imageUrl, onLoadVideo, video]);useEffect(() => {diff --git a/web/apps/space/src/components/PostVideoContent.ts b/web/apps/space/src/components/PostVideoContent.tsindex 6e714ddf6d..61d2058d86 100644--- a/web/apps/space/src/components/PostVideoContent.ts+++ b/web/apps/space/src/components/PostVideoContent.ts@@ -44,7 +44,6 @@ export const createSpaceVideoContent = (height: "100%",objectFit: inline ? "cover" : "contain",cursor: "pointer",- opacity: "0",});const button = document.createElement("button");button.type = "button";@@ -110,14 +109,13 @@ export const createSpaceVideoContent = (}supportMessage.style.marginTop = "2px";errorMessage.append(errorTitle, supportMessage);- const poster =+ const cover =!inline && item.imageUrl ? document.createElement("img") : undefined;- element.append(video);- if (poster) {- poster.alt = "";- poster.src = item.imageUrl!;- poster.hidden = true;- Object.assign(poster.style, {+ if (cover) {+ video.style.position = "relative";+ cover.alt = "";+ cover.src = item.imageUrl!;+ Object.assign(cover.style, {position: "absolute",inset: "0",width: "100%",@@ -125,56 +123,25 @@ export const createSpaceVideoContent = (objectFit: "contain",pointerEvents: "none",});- element.append(poster);+ element.append(cover);}- element.append(button, loading, errorMessage);+ element.append(video, button, loading, errorMessage);let generation = 0;let sourceGeneration = 0;let pendingLoad: Promise<void> | undefined;let ownedURL: string | undefined;let disposed = false;+ void (cover?.decode() ?? Promise.resolve())+ .catch(() => cover?.remove())+ .then(() => {+ if (!disposed) onReady?.();+ });let active = false;let autoplayBlocked = false;let failure: "error" | "rate-limit" | undefined;- let posterState: "pending" | "ready" | "unavailable" = poster- ? "pending"- : "unavailable";- let hasPresentedFrame = false;- let ready = false;let retryTimer: ReturnType<typeof setTimeout> | undefined;let loadingTimer: ReturnType<typeof setTimeout> | undefined;let playbackTimeout: ReturnType<typeof setTimeout> | undefined;- const updatePreview = () => {- if (disposed) return;- const frameVisible =- hasPresentedFrame ||- (!video.poster && video.readyState >= video.HAVE_CURRENT_DATA);- video.style.opacity = frameVisible ? "1" : "0";- video.dataset.spaceVideoFrameVisible = String(frameVisible);- if (poster) poster.hidden = posterState != "ready" || frameVisible;- if (- !ready &&- (posterState == "ready" ||- frameVisible ||- !errorMessage.hidden ||- (posterState == "unavailable" &&- button.getAttribute("aria-hidden") == "false"))- ) {- ready = true;- onReady?.();- }- };- void poster?.decode().then(- () => {- posterState = "ready";- updatePreview();- },- () => {- posterState = "unavailable";- video.removeAttribute("poster");- updatePreview();- },- );const hideLoading = () => {clearTimeout(loadingTimer);loadingTimer = undefined;@@ -214,18 +181,14 @@ export const createSpaceVideoContent = (video.setAttribute("aria-disabled", String(blocked));video.style.cursor = blocked ? "default" : "pointer";errorMessage.hidden = !active || !failure;- updatePreview();};const showPlaying = () => {- if (video.readyState >= video.HAVE_CURRENT_DATA)- hasPresentedFrame = true;hideLoading();failure = undefined;errorMessage.hidden = true;button.disabled = false;button.setAttribute("aria-hidden", "true");video.setAttribute("aria-label", "Pause video");- updatePreview();};const pause = () => {generation++;@@ -237,10 +200,8 @@ export const createSpaceVideoContent = (sourceGeneration++;pendingLoad = undefined;pause();- hasPresentedFrame = false;video.removeAttribute("src");video.load();- updatePreview();};const failPlayback = (reason: "timeout" | "media" | "play",@@ -377,12 +338,6 @@ export const createSpaceVideoContent = (if (!video.paused) showLoading();};video.onplaying = showPlaying;- video.onloadeddata = updatePreview;- video.onseeked = () => {- if (video.readyState >= video.HAVE_CURRENT_DATA)- hasPresentedFrame = true;- updatePreview();- };video.onerror = () => {if (active) failPlayback("media");else reset();@@ -403,11 +358,6 @@ export const createSpaceVideoContent = (return {element,video,- setPoster: (url: string | undefined) => {- if (url) video.poster = url;- else video.removeAttribute("poster");- updatePreview();- },preload,play,pause,diff --git a/web/apps/space/src/components/viewer-transition.ts b/web/apps/space/src/components/viewer-transition.tsindex 87ba587943..f2fc09a1c0 100644--- a/web/apps/space/src/components/viewer-transition.ts+++ b/web/apps/space/src/components/viewer-transition.ts@@ -14,6 +14,7 @@ const openDuration = 0.48;const openBounce = 0.26;const closeDuration = 0.36;const swapFadeMs = 220;+const coverFadeMs = 150;const closingFlights = new WeakMap<HTMLElement, () => void>();export const viewerOriginKey = (spaceId?: string, postId?: number) =>@@ -28,26 +29,11 @@ export const findViewerOrigin = (key: string | undefined) =>interface ViewerFlightTarget {origin: HTMLElement;- src: string | HTMLCanvasElement;+ src: string;+ fadeFromVideo?: boolean;photo: { width: number; height: number };}-export const viewerVideoFrame = (- video: HTMLVideoElement | null | undefined,-) => {- if (- !video ||- video.readyState < video.HAVE_CURRENT_DATA ||- video.dataset.spaceVideoFrameVisible != "true"- )- return undefined;- const frame = document.createElement("canvas");- frame.width = video.videoWidth;- frame.height = video.videoHeight;- frame.getContext("2d")!.drawImage(video, 0, 0);- return frame;-};-const rectOf = (element: Element): ViewerRect => {const { left, top, width, height } = element.getBoundingClientRect();return { x: left, y: top, w: width, h: height };@@ -129,11 +115,7 @@ const runSpring = ({};// A cropping window and the photo inside it, both moved with transforms.-const createFlyer = (- root: HTMLElement,- src: string | HTMLCanvasElement,- base: ViewerRect,-) => {+const createFlyer = (root: HTMLElement, src: string, base: ViewerRect) => {const flyer = document.createElement("div");flyer.setAttribute("aria-hidden", "true");Object.assign(flyer.style, {@@ -148,10 +130,9 @@ const createFlyer = (willChange: "transform",zIndex: "1",});- const image =- typeof src == "string"- ? Object.assign(document.createElement("img"), { alt: "", src })- : src;+ const image = document.createElement("img");+ image.alt = "";+ image.src = src;Object.assign(image.style, {display: "block",height: `${base.h}px`,@@ -314,14 +295,13 @@ export const playViewerOpen = (tileImage?.complete && tileImage.naturalWidth > 0? tileImage: thumbnail;- const flightSrc =- viewerVideoFrame(origin.querySelector("video")) ??- (preview?.currentSrc || src);+ const flightSrc = preview?.currentSrc || src;const { flyer, image, draw } = createFlyer(root, flightSrc, to);let rider: ReturnType<typeof createRider>;let started = false;let disposed = false;let stopSpring: () => void = () => undefined;+ let fade: Animation | undefined;const drawAt = (value: number) => {const state = mixPhotoState(from, end, value);draw(state);@@ -332,38 +312,58 @@ export const playViewerOpen = (drawAt(0);setProgress(0);- const release = () => {+ const release = (fadeOut = false) => {disposed = true;- flyer.remove();+ fade?.cancel();rider?.remove();+ if (fadeOut) {+ fade = flyer.animate([{ opacity: 1 }, { opacity: 0 }], {+ duration: coverFadeMs,+ easing: "ease",+ fill: "forwards",+ });+ fade.addEventListener("finish", () => flyer.remove(), {+ once: true,+ });+ } else flyer.remove();};const reveal = () => {origin.style.opacity = "";rider?.reveal();};- void ("decode" in image ? image.decode() : Promise.resolve()).then(+ const start = () => {+ if (disposed) return;+ origin.style.opacity = "0";+ delete root.dataset.spaceViewerWaiting;+ stopSpring = runSpring({+ from: 0,+ to: 1,+ velocity: 0,+ duration: openDuration,+ bounce: openBounce,+ restDelta: 1.5 / Math.max(1, photoStateTravel(from, end)),+ onUpdate: (value) => {+ t = value;+ drawAt(t);+ setProgress(t);+ },+ onDone: onLanded,+ });+ };+ void image.decode().then(() => {if (disposed) return;started = true;flyer.style.visibility = "";- origin.style.opacity = "0";- delete root.dataset.spaceViewerWaiting;rider = createRider(flyer, origin);drawAt(0);- stopSpring = runSpring({- from: 0,- to: 1,- velocity: 0,- duration: openDuration,- bounce: openBounce,- restDelta: 1.5 / Math.max(1, photoStateTravel(from, end)),- onUpdate: (value) => {- t = value;- drawAt(t);- setProgress(t);- },- onDone: onLanded,- });+ if (origin.querySelector("video")) {+ fade = image.animate([{ opacity: 0 }, { opacity: 1 }], {+ duration: coverFadeMs,+ easing: "ease",+ });+ fade.addEventListener("finish", start, { once: true });+ } else start();},() => {if (!disposed) onLanded();@@ -389,12 +389,16 @@ export const playViewerOpen = (// throwVelocity is in px per ms. A photo other than the tile's fades into it.export const playViewerClose = (viewerRoot: HTMLElement,- { origin, src, photo }: ViewerFlightTarget,+ { origin, src, photo, fadeFromVideo }: ViewerFlightTarget,from: ViewerPhotoState,throwVelocity: { x: number; y: number },startBackground: number,+ onStart: () => void = () => undefined,) => {- if (prefersReducedMotion() || !isOnScreen(origin)) return undefined;+ if (prefersReducedMotion() || !isOnScreen(origin)) {+ onStart();+ return;+ }const root = document.createElement("div");root.setAttribute("aria-hidden", "true");@@ -419,8 +423,8 @@ export const playViewerClose = (rider?.draw(state, t);root.style.backgroundColor = `rgb(0 0 0 / ${startBackground * viewerBackgroundOpacity(t)})`;};- origin.style.opacity = "0";- drawAt(1);+ draw(from);+ rider?.draw(from, 1);const dx =end.visible.x +@@ -436,7 +440,9 @@ export const playViewerClose = (const tileImage = origin.querySelector<HTMLImageElement>("img:not([aria-hidden])",);- const isTilePhoto = tileImage?.currentSrc == src || tileImage?.src == src;+ const isTilePhoto =+ !origin.querySelector("video") &&+ (tileImage?.currentSrc == src || tileImage?.src == src);let fade: Animation | undefined;const cleanUp = () => {@@ -447,29 +453,44 @@ export const playViewerClose = (root.remove();closingFlights.delete(origin);};- const stopSpring = runSpring({- from: 1,- to: 0,- velocity: Math.min(1.2, Math.max(-8, -toward / distance)),- duration: closeDuration,- bounce: 0,- restDelta: 0.5 / Math.max(1, photoStateTravel(from, end)),- onUpdate: drawAt,- onDone: () => {- origin.style.opacity = "";- rider?.reveal();- if (isTilePhoto) {- cleanUp();- } else {- fade = root.animate([{ opacity: 1 }, { opacity: 0 }], {- duration: swapFadeMs,- easing: "ease",- fill: "forwards",- });- fade.addEventListener("finish", cleanUp, { once: true });- }- },- });+ let stopSpring: () => void = () => undefined;+ const start = () => {+ root.style.zIndex = "1299";+ origin.style.opacity = "0";+ drawAt(1);+ onStart();+ stopSpring = runSpring({+ from: 1,+ to: 0,+ velocity: Math.min(1.2, Math.max(-8, -toward / distance)),+ duration: closeDuration,+ bounce: 0,+ restDelta: 0.5 / Math.max(1, photoStateTravel(from, end)),+ onUpdate: drawAt,+ onDone: () => {+ origin.style.opacity = "";+ rider?.reveal();+ if (isTilePhoto) {+ cleanUp();+ } else {+ fade = root.animate([{ opacity: 1 }, { opacity: 0 }], {+ duration: swapFadeMs,+ easing: "ease",+ fill: "forwards",+ });+ fade.addEventListener("finish", cleanUp, { once: true });+ }+ },+ });+ };+ if (fadeFromVideo) {+ root.style.zIndex = "1301";+ fade = flyer.animate([{ opacity: 0 }, { opacity: 1 }], {+ duration: coverFadeMs,+ easing: "ease",+ });+ fade.addEventListener("finish", start, { once: true });+ } else start();closingFlights.set(origin, () => {stopSpring();cleanUp();diff --git a/web/apps/space/tests/post-video-content.test.ts b/web/apps/space/tests/post-video-content.test.tsindex 17eef835c4..408afb04b4 100644--- a/web/apps/space/tests/post-video-content.test.ts+++ b/web/apps/space/tests/post-video-content.test.ts@@ -1,6 +1,5 @@import { afterEach, beforeEach, expect, test, vi } from "vitest";import { createSpaceVideoContent } from "../src/components/PostVideoContent";-import { viewerVideoFrame } from "../src/components/viewer-transition";import { SpaceMediaRateLimitError } from "../src/services/media-load";import type {SpacePostAsset,@@ -10,8 +9,7 @@ import type {vi.mock("ente-base/log-web", () => ({ logToDisk: vi.fn() }));class Element extends EventTarget {- style: Record<string, string> = {};- dataset: Record<string, string> = {};+ style = {};attributes = new Map<string, string>();children: Element[] = [];disabled = false;@@ -32,28 +30,16 @@ class Element extends EventTarget {}class Video extends Element {- HAVE_CURRENT_DATA = 2;- readyState = 0;preload = "none";paused = true;ended = false;currentTime = 0;onpause?: () => void;onplaying?: () => void;- onloadeddata?: () => void;- onseeked?: () => void;- onended?: () => void;- get poster() {- return this.getAttribute("poster") ?? "";- }- set poster(value: string) {- this.setAttribute("poster", value);- }set src(value: string) {this.setAttribute("src", value);}play = vi.fn(() => {- this.readyState = this.HAVE_CURRENT_DATA;this.paused = false;this.onplaying?.();return Promise.resolve();@@ -63,28 +49,21 @@ class Video extends Element {this.paused = true;this.onpause?.();}- load = vi.fn(() => {- this.readyState = 0;- });-}--class Poster extends Element {- decode = () => decodePoster();+ load = vi.fn();}-class Canvas extends Element {- getContext = () => ({ drawImage: vi.fn() });+class Cover extends Element {+ decode = () => Promise.resolve();+ remove = vi.fn();}let contents: ReturnType<typeof createSpaceVideoContent>[];let load: ReturnType<typeof vi.fn<SpacePostAssetURLLoader>>;let revokeURL: ReturnType<typeof vi.spyOn>;-let decodePoster: ReturnType<typeof vi.fn<() => Promise<void>>>;beforeEach(() => {vi.useFakeTimers();contents = [];- decodePoster = vi.fn<() => Promise<void>>().mockResolvedValue(undefined);load = vi.fn<SpacePostAssetURLLoader>().mockResolvedValue("blob:video");revokeURL = vi.spyOn(URL, "revokeObjectURL")@@ -97,10 +76,8 @@ beforeEach(() => {tag == "video"? new Video(): tag == "img"- ? new Poster()- : tag == "canvas"- ? new Canvas()- : new Element(),+ ? new Cover()+ : new Element(),}),);});@@ -129,15 +106,12 @@ const create = ({ ...options, inline },);contents.push(content);- const children = (content.element as unknown as Element).children;- const poster = children.find((child) => child instanceof Poster);- const [video, button, loading, error] = children.filter(- (child) => child != poster,- );+ const [video, button, loading, error] = (+ content.element as unknown as Element+ ).children.filter((child) => !(child instanceof Cover));return {...content,video: video as Video,- poster,button: button!,loading: loading!,error: error!,@@ -167,200 +141,6 @@ test("a video can download and play before its cover image is available", asyncexpect(content.video.getAttribute("poster")).toBeNull();});-test("viewer content waits for its cover to decode before handing over the flyer", async () => {- const decoded = Promise.withResolvers<undefined>();- decodePoster.mockReturnValue(decoded.promise);- const onReady = vi.fn(() => expect(content.poster?.hidden).toBe(false));- const content = create(false, "blob:poster", { onReady });- await vi.advanceTimersByTimeAsync(0);- expect(onReady).not.toHaveBeenCalled();- expect(content.poster?.hidden).toBe(true);-- decoded.resolve(undefined);- await vi.advanceTimersByTimeAsync(0);- expect(onReady).toHaveBeenCalledOnce();- expect(content.video.readyState).toBe(0);- expect(content.video.play).not.toHaveBeenCalled();-});--test("playback can hand over before its cover finishes loading", async () => {- const decoded = Promise.withResolvers<undefined>();- decodePoster.mockReturnValue(decoded.promise);- const onReady = vi.fn();- const content = create(false, "blob:poster", { onReady });- content.video.readyState = content.video.HAVE_CURRENT_DATA;- content.video.onloadeddata?.();- expect(onReady).not.toHaveBeenCalled();- expect(content.video.style.opacity).toBe("0");- expect(- viewerVideoFrame(content.video as unknown as HTMLVideoElement),- ).toBeUndefined();- content.play();- await vi.advanceTimersByTimeAsync(0);- expect(onReady).toHaveBeenCalledOnce();- expect(content.poster?.hidden).toBe(true);-- decoded.resolve(undefined);- await vi.advanceTimersByTimeAsync(0);- expect(onReady).toHaveBeenCalledOnce();- expect(content.poster?.hidden).toBe(true);-});--test.each(["ready", "failed"])(- "blocked autoplay waits for a pending cover to become %s",- async (result) => {- const decoded = Promise.withResolvers<undefined>();- decodePoster.mockReturnValue(decoded.promise);- const onReady = vi.fn();- const content = create(false, "blob:poster", { onReady });- content.video.play.mockRejectedValue(- new DOMException("Blocked", "NotAllowedError"),- );- content.play();- await vi.advanceTimersByTimeAsync(0);- expect(content.button.getAttribute("aria-hidden")).toBe("false");- expect(onReady).not.toHaveBeenCalled();-- if (result == "ready") decoded.resolve(undefined);- else decoded.reject(new Error("decode failed"));- await vi.advanceTimersByTimeAsync(0);- expect(onReady).toHaveBeenCalledOnce();- expect(content.poster?.hidden).toBe(result != "ready");- expect(content.video.style.opacity).toBe("0");- },-);--test.each(["", "blob:failed-poster"])(- "blocked autoplay without a usable cover (%s) hands over to Play",- async (url) => {- decodePoster.mockRejectedValue(new Error("decode failed"));- const onReady = vi.fn();- const content = create(false, url, { onReady });- await vi.advanceTimersByTimeAsync(0);- expect(onReady).not.toHaveBeenCalled();- content.video.play.mockRejectedValue(- new DOMException("Blocked", "NotAllowedError"),- );- content.play();- await vi.advanceTimersByTimeAsync(0);- expect(onReady).toHaveBeenCalledOnce();- expect(content.button.getAttribute("aria-hidden")).toBe("false");- expect(content.error.hidden).toBe(true);- },-);--test("the viewer cover yields to playback and returns when the video resets", async () => {- const onReady = vi.fn();- const content = create(false, "blob:poster", { onReady });- await vi.advanceTimersByTimeAsync(0);- expect(content.poster?.hidden).toBe(false);- content.play();- await vi.advanceTimersByTimeAsync(0);- expect(content.poster?.hidden).toBe(true);-- content.pause();- expect(content.poster?.hidden).toBe(true);- expect(- viewerVideoFrame(content.video as unknown as HTMLVideoElement),- ).toBeInstanceOf(Canvas);-- content.deactivate();- expect(content.poster?.hidden).toBe(false);- expect(- viewerVideoFrame(content.video as unknown as HTMLVideoElement),- ).toBeUndefined();- expect(onReady).toHaveBeenCalledOnce();-});--test("feed snapshots follow the displayed cover, playing frame, and paused frame", async () => {- const content = create();- await content.preload();- content.video.readyState = content.video.HAVE_CURRENT_DATA;- content.video.onloadeddata?.();- expect(content.video.style.opacity).toBe("0");- expect(- viewerVideoFrame(content.video as unknown as HTMLVideoElement),- ).toBeUndefined();-- content.play();- await vi.advanceTimersByTimeAsync(0);- expect(content.video.style.opacity).toBe("1");- expect(- viewerVideoFrame(content.video as unknown as HTMLVideoElement),- ).toBeInstanceOf(Canvas);- content.deactivate();- expect(content.video.style.opacity).toBe("1");- expect(- viewerVideoFrame(content.video as unknown as HTMLVideoElement),- ).toBeInstanceOf(Canvas);-- content.video.onended?.();- content.video.readyState = content.video.HAVE_CURRENT_DATA;- content.video.onloadeddata?.();- expect(content.video.style.opacity).toBe("0");- expect(- viewerVideoFrame(content.video as unknown as HTMLVideoElement),- ).toBeUndefined();-});--test("a late feed cover replaces only a frame that has not played or been sought", () => {- const content = create(true, "");- content.video.readyState = content.video.HAVE_CURRENT_DATA;- content.video.onloadeddata?.();- expect(content.video.style.opacity).toBe("1");- content.setPoster("blob:late-poster");- expect(content.video.style.opacity).toBe("0");- expect(- viewerVideoFrame(content.video as unknown as HTMLVideoElement),- ).toBeUndefined();-- content.video.onseeked?.();- expect(content.video.style.opacity).toBe("1");- expect(- viewerVideoFrame(content.video as unknown as HTMLVideoElement),- ).toBeInstanceOf(Canvas);- content.setPoster("blob:new-poster");- expect(content.video.style.opacity).toBe("1");-});--test("destroyed viewer content cannot hand over after late cover or video readiness", async () => {- const decoded = Promise.withResolvers<undefined>();- decodePoster.mockReturnValue(decoded.promise);- const onReady = vi.fn();- const content = create(false, "blob:poster", { onReady });- content.destroy();- decoded.resolve(undefined);- await vi.advanceTimersByTimeAsync(0);- content.video.readyState = content.video.HAVE_CURRENT_DATA;- content.video.onloadeddata?.();- expect(onReady).not.toHaveBeenCalled();- expect(content.poster?.hidden).toBe(true);-});--test("a failed cover waits for a video frame before handing over", async () => {- decodePoster.mockRejectedValue(new Error("decode failed"));- const onReady = vi.fn();- const content = create(false, "blob:poster", { onReady });- await vi.advanceTimersByTimeAsync(0);- expect(onReady).not.toHaveBeenCalled();-- content.video.readyState = content.video.HAVE_CURRENT_DATA;- content.video.onloadeddata?.();- expect(onReady).toHaveBeenCalledOnce();- expect(content.poster?.hidden).toBe(true);-});--test("failed cover and video loading hand over to the visible error", async () => {- decodePoster.mockRejectedValue(new Error("decode failed"));- load.mockRejectedValue(new Error("Offline"));- const onReady = vi.fn(() => expect(content.error.hidden).toBe(false));- const content = create(false, "blob:poster", { onReady });- content.play();- await vi.advanceTimersByTimeAsync(0);- expect(onReady).toHaveBeenCalledOnce();- expect(content.errorTitle.textContent).toBe("Couldn't play video.");-});-test("autoplay joins an in-flight preload without downloading the video again", async () => {const download = Promise.withResolvers<string>();load.mockReturnValue(download.promise);diff --git a/web/apps/space/tests/viewer-transition.test.ts b/web/apps/space/tests/viewer-transition.test.tsindex e9619b3b2c..3930e85bd5 100644--- a/web/apps/space/tests/viewer-transition.test.ts+++ b/web/apps/space/tests/viewer-transition.test.ts@@ -3,7 +3,6 @@ import {playViewerClose,playViewerOpen,viewerOriginKey,- viewerVideoFrame,} from "../src/components/viewer-transition";import { fullPhotoState } from "../src/utils/viewer-geometry";@@ -16,7 +15,7 @@ test("tiles are matched by space and post", () => {expect(viewerOriginKey("space", undefined)).toBeUndefined();});-const pendingFlight = (video?: HTMLVideoElement) => {+const pendingFlight = () => {let resolveDecode!: () => void;let rejectDecode!: (error: Error) => void;const decoded = new Promise<void>((resolve, reject) => {@@ -30,13 +29,6 @@ const pendingFlight = (video?: HTMLVideoElement) => {remove: vi.fn(),};const image = { style: {}, src: "", decode: () => decoded };- const drawFrame = vi.fn();- const frame = {- style: {},- width: 0,- height: 0,- getContext: () => ({ drawImage: drawFrame }),- };const origin = {style: { opacity: "" },closest: () => null,@@ -47,15 +39,12 @@ const pendingFlight = (video?: HTMLVideoElement) => {height: 100,}),querySelector: (selector: string) =>- selector == "video"- ? (video ?? null)- : selector == "img[aria-hidden]"- ? { currentSrc: "data:thumbnail" }- : null,+ selector == "img[aria-hidden]"+ ? { currentSrc: "data:thumbnail" }+ : null,};vi.stubGlobal("document", {- createElement: (tag: string) =>- tag == "canvas" ? frame : tag == "img" ? image : flyer,+ createElement: (tag: string) => (tag == "img" ? image : flyer),});vi.stubGlobal("window", {innerWidth: 390,@@ -88,8 +77,6 @@ const pendingFlight = (video?: HTMLVideoElement) => {return {flight,flyer,- frame,- drawFrame,image,origin,requestFrame,@@ -140,49 +127,7 @@ test("a failed flyer leaves the tile visible and allows viewer handover", asyncflight.stop();});-test("a playing video opens with its current frame without decoding the poster", async () => {- const video = {- dataset: { spaceVideoFrameVisible: "true" },- readyState: 2,- HAVE_CURRENT_DATA: 2,- videoWidth: 1920,- videoHeight: 1080,- } as unknown as HTMLVideoElement;- const { flight, flyer, frame, drawFrame, origin, requestFrame } =- pendingFlight(video);-- expect(frame.width).toBe(1920);- expect(frame.height).toBe(1080);- expect(drawFrame).toHaveBeenCalledExactlyOnceWith(video, 0, 0);- expect(flight.src).toBe(frame);- expect(flyer.append).toHaveBeenCalledWith(frame);- await Promise.resolve();- expect(origin.style.opacity).toBe("0");- expect(requestFrame).toHaveBeenCalledOnce();- flight.stop();-});--test.each([1, 2])(- "a video displaying its poster opens using that poster at readyState %i",- async (readyState) => {- const { flight, drawFrame, image, origin, resolveDecode } =- pendingFlight({- readyState,- HAVE_CURRENT_DATA: 2,- dataset: { spaceVideoFrameVisible: "false" },- } as unknown as HTMLVideoElement);-- expect(drawFrame).not.toHaveBeenCalled();- expect(image.src).toBe("data:thumbnail");- expect(origin.style.opacity).toBe("");- resolveDecode();- await Promise.resolve();- expect(origin.style.opacity).toBe("0");- flight.stop();- },-);--const closingFlight = (src: string | HTMLCanvasElement = "full-photo") => {+const closingFlight = (src = "full-photo") => {const { flight, origin, requestFrame } = pendingFlight();flight.stop();vi.mocked(cancelAnimationFrame).mockClear();@@ -281,27 +226,3 @@ test("reopening during the thumbnail fade cancels the old overlay", () => {expect(root.remove).toHaveBeenCalledOnce();flight.stop();});--test("closing a video keeps its captured frame until it fades into the tile", () => {- const { flight, frame } = pendingFlight();- flight.stop();- const snapshot = viewerVideoFrame({- dataset: { spaceVideoFrameVisible: "true" },- readyState: 2,- HAVE_CURRENT_DATA: 2,- videoWidth: 1920,- videoHeight: 1080,- } as unknown as HTMLVideoElement)!;- expect(snapshot).toBe(frame);-- const { root, origin, fade, finishSpring } = closingFlight(snapshot);- expect(origin.style.opacity).toBe("0");- expect(snapshot.style.transform).toBeDefined();- finishSpring();- expect(origin.style.opacity).toBe("");- expect(root.animate).toHaveBeenCalledOnce();- expect(root.remove).not.toHaveBeenCalled();- const finish = fade.addEventListener.mock.calls[0]![1] as () => void;- finish();- expect(root.remove).toHaveBeenCalledOnce();-});