Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(web): add share playback store and context

Richie McIlroye834c218fde4
diff --git a/apps/web/app/s/[videoId]/_components/playback/PlaybackContext.tsx b/apps/web/app/s/[videoId]/_components/playback/PlaybackContext.tsx
new file mode 100644
index 000000000..4a1e99860
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/playback/PlaybackContext.tsx
@@ -0,0 +1,135 @@
+"use client";
+
+import {
+ createContext,
+ type ReactNode,
+ type RefObject,
+ useContext,
+ useEffect,
+ useRef,
+ useState,
+ useSyncExternalStore,
+} from "react";
+import { createPlaybackStore, type PlaybackStore } from "./playback-store";
+import { useVideoElement } from "./useVideoElement";
+
+const PlaybackContext = createContext<PlaybackStore | null>(null);
+
+interface PlaybackProviderProps {
+ videoRef: RefObject<HTMLVideoElement | null>;
+ stageRef: RefObject<HTMLElement | null>;
+ fallbackDuration?: number | null;
+ children: ReactNode;
+}
+
+export function PlaybackProvider({
+ videoRef,
+ stageRef,
+ fallbackDuration = 0,
+ children,
+}: PlaybackProviderProps) {
+ // One store per provider mount. The context value is the store itself, so its
+ // identity never changes and consumers never re-render because of us.
+ const storeRef = useRef<PlaybackStore | null>(null);
+ if (storeRef.current === null) {
+ storeRef.current = createPlaybackStore(fallbackDuration);
+ }
+ const store = storeRef.current;
+
+ useEffect(() => {
+ store.setFallbackDuration(fallbackDuration ?? 0);
+ }, [store, fallbackDuration]);
+
+ useVideoElement({ store, videoRef, stageRef });
+
+ return (
+ <PlaybackContext.Provider value={store}>
+ {children}
+ </PlaybackContext.Provider>
+ );
+}
+
+/**
+ * Subscription handle for the share page's media element. Stable for the life
+ * of the provider, so it is safe to put in dependency arrays.
+ */
+export function usePlayback(): PlaybackStore {
+ const store = useContext(PlaybackContext);
+ if (!store) {
+ throw new Error("usePlayback must be used inside a <PlaybackProvider>");
+ }
+ return store;
+}
+
+/**
+ * Like `usePlayback`, but null outside a provider — for components that also
+ * render in trees with no main video (composer previews, embeds).
+ */
+export function useOptionalPlayback(): PlaybackStore | null {
+ return useContext(PlaybackContext);
+}
+
+const getServerPlaying = () => false;
+
+/** Re-renders only when playback starts or stops. */
+export function usePlaying(): boolean {
+ const store = usePlayback();
+ return useSyncExternalStore(
+ store.subscribePlaying,
+ store.getPlaying,
+ getServerPlaying,
+ );
+}
+
+const now = () =>
+ typeof performance !== "undefined" ? performance.now() : Date.now();
+
+/**
+ * Current time as React state, throttled to at most one update per
+ * `intervalMs`. For consumers that need a number in the render tree (labels,
+ * active-chapter highlighting) rather than a DOM write.
+ */
+export function useCoarseTime(intervalMs = 250): number {
+ const store = usePlayback();
+ const [time, setTime] = useState(() => store.getCurrentTime());
+
+ useEffect(() => {
+ let last = Number.NEGATIVE_INFINITY;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ let pending: number | null = null;
+
+ const flush = () => {
+ timer = null;
+ if (pending === null) return;
+ last = now();
+ const value = pending;
+ pending = null;
+ setTime(value);
+ };
+
+ const unsubscribe = store.subscribe((next) => {
+ const elapsed = now() - last;
+ if (elapsed >= intervalMs) {
+ if (timer !== null) {
+ clearTimeout(timer);
+ timer = null;
+ }
+ pending = null;
+ last = now();
+ setTime(next);
+ return;
+ }
+ // Hold the newest value and flush it on the trailing edge, so a pause
+ // mid-interval still lands on the real final position.
+ pending = next;
+ if (timer === null) timer = setTimeout(flush, intervalMs - elapsed);
+ });
+
+ return () => {
+ unsubscribe();
+ if (timer !== null) clearTimeout(timer);
+ };
+ }, [store, intervalMs]);
+
+ return time;
+}
diff --git a/apps/web/app/s/[videoId]/_components/playback/playback-store.ts b/apps/web/app/s/[videoId]/_components/playback/playback-store.ts
new file mode 100644
index 000000000..4c7452eac
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/playback/playback-store.ts
@@ -0,0 +1,211 @@
+/**
+ * Framework-free subscription store around the share page's `<video>` element.
+ *
+ * The share page grew a second view (timeline) whose consumers need the current
+ * playback time at frame rate. Putting that in React state would re-render the
+ * whole page 60 times a second, so instead everything subscribes here and
+ * writes to the DOM directly.
+ *
+ * A single `requestAnimationFrame` loop runs *only* while the media is playing
+ * (mirroring the follow loop in `edit/EditVideoClient.tsx`). While paused the
+ * store still emits one-shot updates from `seeking`/`seeked`/`timeupdate`/
+ * `loadedmetadata`, so scrubbing stays live without burning frames.
+ */
+
+export type TimeSubscriber = (time: number) => void;
+export type PlayingSubscriber = () => void;
+
+export type PlaybackStore = ReturnType<typeof createPlaybackStore>;
+
+const isFiniteDuration = (value: number | null | undefined): value is number =>
+ typeof value === "number" && Number.isFinite(value) && value > 0;
+
+const normalizeDuration = (value: number | null | undefined): number =>
+ isFiniteDuration(value) ? value : 0;
+
+export function createPlaybackStore(fallbackDuration: number | null = 0) {
+ let element: HTMLVideoElement | null = null;
+ let frame = 0;
+ let time = 0;
+ let playing = false;
+ let fallback = normalizeDuration(fallbackDuration);
+ let duration = fallback;
+
+ const timeSubscribers = new Set<TimeSubscriber>();
+ const playingSubscribers = new Set<PlayingSubscriber>();
+
+ const emitTime = () => {
+ for (const subscriber of timeSubscribers) subscriber(time);
+ };
+
+ const setPlaying = (next: boolean) => {
+ if (playing === next) return;
+ playing = next;
+ for (const subscriber of playingSubscribers) subscriber();
+ };
+
+ /** Pull `currentTime`/`duration` off the element and notify time subscribers. */
+ const sample = (force = false) => {
+ if (element && isFiniteDuration(element.duration)) {
+ duration = element.duration;
+ }
+ const next = element?.currentTime ?? time;
+ if (next === time && !force) return;
+ time = next;
+ emitTime();
+ };
+
+ const stopFrames = () => {
+ if (frame === 0) return;
+ cancelAnimationFrame(frame);
+ frame = 0;
+ };
+
+ const tick = () => {
+ frame = 0;
+ sample();
+ if (element && !element.paused && !element.ended) {
+ frame = requestAnimationFrame(tick);
+ }
+ };
+
+ const startFrames = () => {
+ if (frame !== 0) return;
+ if (typeof requestAnimationFrame !== "function") return;
+ frame = requestAnimationFrame(tick);
+ };
+
+ const handlePlay = () => {
+ setPlaying(true);
+ startFrames();
+ };
+
+ const handleStop = () => {
+ stopFrames();
+ setPlaying(false);
+ sample(true);
+ };
+
+ const handleTimeChange = () => sample();
+
+ const MEDIA_EVENTS = [
+ ["play", handlePlay],
+ ["playing", handlePlay],
+ ["pause", handleStop],
+ ["ended", handleStop],
+ ["seeking", handleTimeChange],
+ ["seeked", handleTimeChange],
+ ["timeupdate", handleTimeChange],
+ ["loadedmetadata", handleTimeChange],
+ ["durationchange", handleTimeChange],
+ ] as const;
+
+ const teardown = () => {
+ stopFrames();
+ if (!element) return;
+ for (const [event, handler] of MEDIA_EVENTS) {
+ element.removeEventListener(event, handler);
+ }
+ element = null;
+ };
+
+ /**
+ * Point the store at a (possibly new) media element. Safe to call with the
+ * element that is already attached, which is a no-op.
+ */
+ const attach = (next: HTMLVideoElement | null) => {
+ if (next === element) return;
+ teardown();
+ if (!next) {
+ setPlaying(false);
+ sample(true);
+ return;
+ }
+ element = next;
+ for (const [event, handler] of MEDIA_EVENTS) {
+ element.addEventListener(event, handler);
+ }
+ sample(true);
+ if (!element.paused && !element.ended) handlePlay();
+ else setPlaying(false);
+ };
+
+ const detach = () => {
+ teardown();
+ setPlaying(false);
+ };
+
+ const subscribe = (subscriber: TimeSubscriber) => {
+ timeSubscribers.add(subscriber);
+ // Hand the subscriber the current position straight away so it can paint
+ // once on mount instead of waiting for the next media event.
+ subscriber(time);
+ return () => {
+ timeSubscribers.delete(subscriber);
+ };
+ };
+
+ const subscribePlaying = (subscriber: PlayingSubscriber) => {
+ playingSubscribers.add(subscriber);
+ return () => {
+ playingSubscribers.delete(subscriber);
+ };
+ };
+
+ const getCurrentTime = () => element?.currentTime ?? time;
+
+ const getDuration = () => {
+ if (element && isFiniteDuration(element.duration)) return element.duration;
+ return duration || fallback;
+ };
+
+ const getPlaying = () => playing;
+
+ const setFallbackDuration = (next: number | null) => {
+ fallback = normalizeDuration(next);
+ if (!isFiniteDuration(duration)) duration = fallback;
+ };
+
+ const seek = (target: number) => {
+ if (!element) return;
+ const total = getDuration();
+ const clamped = isFiniteDuration(total)
+ ? Math.max(0, Math.min(total - 0.001, target))
+ : Math.max(0, target);
+ try {
+ element.currentTime = clamped;
+ } catch (error) {
+ console.error("Failed to seek video:", error);
+ return;
+ }
+ sample(true);
+ };
+
+ const play = () => {
+ const started = element?.play();
+ if (started && typeof started.catch === "function") {
+ started.catch(() => {
+ /* autoplay rejections are the caller's problem, not ours */
+ });
+ }
+ };
+
+ const pause = () => element?.pause();
+
+ const getElement = () => element;
+
+ return {
+ attach,
+ detach,
+ subscribe,
+ subscribePlaying,
+ getCurrentTime,
+ getDuration,
+ getPlaying,
+ getElement,
+ setFallbackDuration,
+ seek,
+ play,
+ pause,
+ };
+}
diff --git a/apps/web/app/s/[videoId]/_components/playback/useVideoElement.ts b/apps/web/app/s/[videoId]/_components/playback/useVideoElement.ts
new file mode 100644
index 000000000..d6e269ef3
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/playback/useVideoElement.ts
@@ -0,0 +1,63 @@
+"use client";
+
+import { type RefObject, useEffect } from "react";
+import type { PlaybackStore } from "./playback-store";
+
+interface UseVideoElementOptions {
+ store: PlaybackStore;
+ /** Imperative handle forwarded by `ShareVideo`. */
+ videoRef: RefObject<HTMLVideoElement | null>;
+ /** The stage card, used both as the query root and the mutation scope. */
+ stageRef: RefObject<HTMLElement | null>;
+}
+
+/**
+ * Keeps `store` attached to whichever `<video>` is currently live inside the
+ * stage.
+ *
+ * `ShareVideo`'s `useImperativeHandle(ref, () => videoRef.current, [])` has
+ * empty deps, so the forwarded ref is captured once and goes stale the moment
+ * the player swaps between its HLS and MP4 implementations. We therefore treat
+ * the forwarded ref as a hint only: it wins when it still points at a mounted
+ * element, otherwise we fall back to querying the stage. A MutationObserver on
+ * the stage catches the swap itself, and `loadedmetadata` (captured, since it
+ * does not bubble) catches the case where the element is reused but reloaded.
+ */
+export function useVideoElement({
+ store,
+ videoRef,
+ stageRef,
+}: UseVideoElementOptions) {
+ useEffect(() => {
+ const stage = stageRef.current;
+
+ const resolve = (): HTMLVideoElement | null => {
+ const fromRef = videoRef.current;
+ if (fromRef?.isConnected) return fromRef;
+ return stage?.querySelector("video") ?? null;
+ };
+
+ let attached: HTMLVideoElement | null = null;
+ const sync = () => {
+ const next = resolve();
+ if (next === attached) return;
+ attached = next;
+ store.attach(next);
+ };
+
+ sync();
+
+ let observer: MutationObserver | null = null;
+ if (stage && typeof MutationObserver === "function") {
+ observer = new MutationObserver(sync);
+ observer.observe(stage, { childList: true, subtree: true });
+ }
+ stage?.addEventListener("loadedmetadata", sync, true);
+
+ return () => {
+ observer?.disconnect();
+ stage?.removeEventListener("loadedmetadata", sync, true);
+ store.detach();
+ };
+ }, [store, videoRef, stageRef]);
+}