Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(embed): initialize delayed players with existing metadata

Rishabh Bothra09ba8321b30a
diff --git a/apps/web/__tests__/unit/embed-video-playback-chrome.test.ts b/apps/web/__tests__/unit/embed-video-playback-chrome.test.ts
index adf7f4425..0d3d00faa 100644
--- a/apps/web/__tests__/unit/embed-video-playback-chrome.test.ts
+++ b/apps/web/__tests__/unit/embed-video-playback-chrome.test.ts
@@ -28,6 +28,7 @@ import {
const dynamicImports = vi.hoisted(() => [] as Promise<unknown>[]);
const dynamicControl = vi.hoisted(() => ({
gate: null as Promise<void> | null,
+ metadataReady: false,
}));
vi.mock("next/dynamic", async () => {
@@ -123,6 +124,20 @@ vi.mock("@/app/embed/[videoId]/_components/use-player-js-receiver", () => ({
usePlayerJsReceiver: () => undefined,
}));
+function attachVideoRef(
+ ref: Ref<HTMLVideoElement>,
+ video: HTMLVideoElement | null,
+) {
+ if (video && dynamicControl.metadataReady) {
+ Object.defineProperties(video, {
+ duration: { configurable: true, value: 60 },
+ readyState: { configurable: true, value: 1 },
+ });
+ }
+ if (typeof ref === "function") return ref(video);
+ if (ref) ref.current = video;
+}
+
vi.mock("@/app/s/[videoId]/_components/CapVideoPlayer", async () => {
const { createElement, useEffect, useState } = await import("react");
const DeferredVideoPlayer = ({
@@ -136,7 +151,8 @@ vi.mock("@/app/s/[videoId]/_components/CapVideoPlayer", async () => {
useEffect(() => setIsMounted(true), []);
return isMounted
? createElement("video", {
- ref: videoRef,
+ ref: (video: HTMLVideoElement | null) =>
+ attachVideoRef(videoRef, video),
"data-default-speed": defaultPlaybackSpeed,
})
: null;
@@ -155,7 +171,8 @@ vi.mock("@/app/s/[videoId]/_components/HLSVideoPlayer", async () => {
defaultPlaybackSpeed?: number;
}) =>
createElement("video", {
- ref: videoRef,
+ ref: (video: HTMLVideoElement | null) =>
+ attachVideoRef(videoRef, video),
"data-default-speed": defaultPlaybackSpeed,
}),
};
@@ -231,12 +248,21 @@ describe("EmbedVideo playback chrome", () => {
afterEach(() => {
dynamicControl.gate = null;
+ dynamicControl.metadataReady = false;
document.body.replaceChildren();
});
- it.each([{ type: "desktopMP4" } as const, { type: "MediaConvert" } as const])(
- "seeks and updates chrome when the $type player loads after mount",
- async (source) => {
+ it.each(
+ [
+ { type: "desktopMP4" } as const,
+ { type: "MediaConvert" } as const,
+ ].flatMap((source) =>
+ [false, true].map((metadataReady) => ({ source, metadataReady })),
+ ),
+ )(
+ "seeks and updates chrome when the $source.type player loads after mount with metadataReady=$metadataReady",
+ async ({ source, metadataReady }) => {
+ dynamicControl.metadataReady = metadataReady;
let release = () => {};
dynamicControl.gate = new Promise<void>((resolve) => {
release = resolve;
@@ -257,10 +283,12 @@ describe("EmbedVideo playback chrome", () => {
});
const video = container.querySelector("video");
if (!video) throw new Error("Player did not load");
- Object.defineProperty(video, "duration", { value: 60 });
- await act(async () => {
- video.dispatchEvent(new Event("loadedmetadata"));
- });
+ if (!metadataReady) {
+ Object.defineProperty(video, "duration", { value: 60 });
+ await act(async () => {
+ video.dispatchEvent(new Event("loadedmetadata"));
+ });
+ }
expect(video.currentTime).toBe(15);
await act(async () => {
video.dispatchEvent(new Event("play"));
diff --git a/apps/web/__tests__/unit/player-js-receiver-mount.test.ts b/apps/web/__tests__/unit/player-js-receiver-mount.test.ts
new file mode 100644
index 000000000..2a1b39002
--- /dev/null
+++ b/apps/web/__tests__/unit/player-js-receiver-mount.test.ts
@@ -0,0 +1,60 @@
+// @vitest-environment jsdom
+
+import { act, createElement, useRef } from "react";
+import { createRoot } from "react-dom/client";
+import { expect, it, vi } from "vitest";
+import { usePlayerJsReceiver } from "@/app/embed/[videoId]/_components/use-player-js-receiver";
+
+it.each([false, true])(
+ "binds and cleans up Player.js with video ref attached=%s",
+ async (attachRef) => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ const postMessage = vi
+ .spyOn(window.parent, "postMessage")
+ .mockImplementation(() => {});
+ const container = document.createElement("div");
+ document.body.append(container);
+ const root = createRoot(container);
+ function Player() {
+ const playerContainerRef = useRef<HTMLDivElement>(null);
+ const videoRef = useRef<HTMLVideoElement>(null);
+ usePlayerJsReceiver({ playerContainerRef, videoRef });
+ return createElement(
+ "div",
+ { ref: playerContainerRef },
+ createElement("video", { ref: attachRef ? videoRef : undefined }),
+ );
+ }
+ const seek = (value: number) =>
+ window.dispatchEvent(
+ new MessageEvent("message", {
+ source: window.parent,
+ origin: window.location.origin,
+ data: JSON.stringify({
+ context: "player.js",
+ method: "setCurrentTime",
+ value,
+ }),
+ }),
+ );
+
+ let video: HTMLVideoElement | null = null;
+ try {
+ await act(async () => root.render(createElement(Player)));
+ video = container.querySelector("video");
+ if (!video) throw new Error("Missing video element");
+ expect(postMessage).toHaveBeenCalledOnce();
+ expect(JSON.parse(String(postMessage.mock.calls[0]?.[0]))).toMatchObject({
+ event: "ready",
+ });
+ seek(15);
+ expect(video.currentTime).toBe(15);
+ } finally {
+ await act(async () => root.unmount());
+ container.remove();
+ vi.unstubAllGlobals();
+ }
+ seek(25);
+ expect(video?.currentTime).toBe(15);
+ },
+);
diff --git a/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx b/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx
index 9a549c894..a73729455 100644
--- a/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx
+++ b/apps/web/app/embed/[videoId]/_components/EmbedVideo.tsx
@@ -257,8 +257,19 @@ export const EmbedVideo = forwardRef<
);
useEffect(() => {
- const player = videoRef.current;
- if (player && player.readyState >= 1) handleLoadedMetadata(player);
+ const container = playerContainerRef.current;
+ if (!container) return;
+ let currentPlayer: HTMLVideoElement | null = null;
+ const syncMetadata = () => {
+ const player = container.querySelector("video");
+ if (player === currentPlayer) return;
+ currentPlayer = player;
+ if (player && player.readyState >= 1) handleLoadedMetadata(player);
+ };
+ const observer = new MutationObserver(syncMetadata);
+ observer.observe(container, { childList: true, subtree: true });
+ syncMetadata();
+ return () => observer.disconnect();
}, [handleLoadedMetadata]);
return (
diff --git a/apps/web/app/embed/[videoId]/_components/use-player-js-receiver.ts b/apps/web/app/embed/[videoId]/_components/use-player-js-receiver.ts
index 13e18b72a..c3081de52 100644
--- a/apps/web/app/embed/[videoId]/_components/use-player-js-receiver.ts
+++ b/apps/web/app/embed/[videoId]/_components/use-player-js-receiver.ts
@@ -258,9 +258,10 @@ export const usePlayerJsReceiver = ({
let currentVideo: HTMLVideoElement | null = null;
let dispose: (() => void) | null = null;
const bind = () => {
- if (videoRef.current === currentVideo) return;
+ const video = videoRef.current ?? playerContainer.querySelector("video");
+ if (video === currentVideo) return;
dispose?.();
- currentVideo = videoRef.current;
+ currentVideo = video;
dispose = currentVideo
? createPlayerJsReceiver({
playerWindow: window,