Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(web): add media comment display components
Richie McIlroybb566aab60ff
diff --git a/apps/web/__tests__/unit/media-comment-pseudo-waveform.test.ts b/apps/web/__tests__/unit/media-comment-pseudo-waveform.test.tsnew file mode 100644index 000000000..f0b03618d--- /dev/null+++ b/apps/web/__tests__/unit/media-comment-pseudo-waveform.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it } from "vitest";+import {+ pseudoWaveform,+ resampleWaveform,+ resolveWaveform,+ WAVEFORM_BAR_COUNT,+ WAVEFORM_MAX_PEAK,+ WAVEFORM_MIN_PEAK,+} from "../../app/s/[videoId]/_components/media-comment/WaveformBars";++describe("pseudoWaveform", () => {+ it("is deterministic for a given id", () => {+ expect(pseudoWaveform("comment-abc123")).toEqual(+ pseudoWaveform("comment-abc123"),+ );+ });++ it("differs between ids", () => {+ expect(pseudoWaveform("comment-a")).not.toEqual(+ pseudoWaveform("comment-b"),+ );+ });++ it("stays within the visible band and matches the bar count", () => {+ for (const bars of [WAVEFORM_BAR_COUNT, 40, 1]) {+ const peaks = pseudoWaveform("comment-xyz", bars);+ expect(peaks).toHaveLength(bars);+ for (const peak of peaks) {+ expect(peak).toBeGreaterThanOrEqual(WAVEFORM_MIN_PEAK);+ expect(peak).toBeLessThanOrEqual(WAVEFORM_MAX_PEAK);+ }+ }+ expect(pseudoWaveform("x", 0)).toEqual([]);+ });+});++describe("resampleWaveform", () => {+ it("keeps transients when squashing", () => {+ const peaks = new Array(128).fill(0.2);+ peaks[64] = 0.9;+ const out = resampleWaveform(peaks, 32);+ expect(out).toHaveLength(32);+ expect(Math.max(...out)).toBeCloseTo(0.9);+ });+});++describe("resolveWaveform", () => {+ it("prefers stored peaks and falls back to pseudo", () => {+ const stored = resolveWaveform("id", [0.5, 0.6], 2);+ expect(stored).toEqual([0.5, 0.6]);+ expect(resolveWaveform("id", null, 8)).toEqual(pseudoWaveform("id", 8));+ expect(resolveWaveform("id", [], 8)).toEqual(pseudoWaveform("id", 8));+ });+});diff --git a/apps/web/app/s/[videoId]/_components/media-comment/MediaCommentBody.tsx b/apps/web/app/s/[videoId]/_components/media-comment/MediaCommentBody.tsxnew file mode 100644index 000000000..4caaa1160--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/media-comment/MediaCommentBody.tsx@@ -0,0 +1,51 @@+"use client";++import { useLocalMediaUrl } from "./local-media-urls";+import type { MediaComment } from "./media-comment-types";+import { useMainVideoInterlock } from "./media-playback-registry";+import { VideoCommentCard } from "./VideoCommentCard";+import { VoiceNotePill } from "./VoiceNotePill";++export interface MediaCommentBodyProps {+ comment: MediaComment;+ /**+ * Blob URL for a just-recorded optimistic comment; preferred over the+ * network URL so the author sees their recording instantly.+ */+ localUrl?: string;+ className?: string;+ /** Fewer waveform bars / tighter sizing for narrow containers. */+ compact?: boolean;+}++export const MediaCommentBody = ({+ comment,+ localUrl,+ className,+ compact,+}: MediaCommentBodyProps) => {+ // Refcounted: N mounted bodies still cost one main-video listener.+ useMainVideoInterlock();+ // Optimistic cards play the author's own recording from the local blob+ // registry until the uploaded copy is servable.+ const registryUrl = useLocalMediaUrl(comment.id);+ const effectiveLocalUrl = localUrl ?? registryUrl;++ if (comment.type === "video")+ return (+ <VideoCommentCard+ comment={comment}+ localUrl={effectiveLocalUrl}+ className={className}+ />+ );++ return (+ <VoiceNotePill+ comment={comment}+ localUrl={effectiveLocalUrl}+ compact={compact}+ className={className}+ />+ );+};diff --git a/apps/web/app/s/[videoId]/_components/media-comment/VideoCommentCard.tsx b/apps/web/app/s/[videoId]/_components/media-comment/VideoCommentCard.tsxnew file mode 100644index 000000000..1ac0db8ca--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/media-comment/VideoCommentCard.tsx@@ -0,0 +1,235 @@+"use client";++import { motion } from "motion/react";+import { useCallback, useEffect, useRef, useState } from "react";+import { commentMediaUrl } from "@/lib/comment-media";+import { formatMediaDuration } from "./format-media-duration";+import type { MediaComment } from "./media-comment-types";+import {+ claimPlayback,+ releasePlayback,+ suspendMainVideo,+} from "./media-playback-registry";++const FilmGlyph = () => (+ <svg+ width="20"+ height="20"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.5"+ aria-hidden="true"+ >+ <rect x="3" y="5" width="18" height="14" rx="2" />+ <path d="M7 5v14M17 5v14M3 9h4M3 15h4M17 9h4M17 15h4" />+ </svg>+);++interface VideoCommentCardProps {+ comment: MediaComment;+ localUrl?: string;+ className?: string;+}++/**+ * Video comment: poster with a play circle, swapping to an inline `<video>` on+ * first play. The element is never rendered until then — a sidebar can hold+ * dozens of these. Progress paints via a rAF `scaleX` write, zero renders.+ */+export const VideoCommentCard = ({+ comment,+ localUrl,+ className,+}: VideoCommentCardProps) => {+ const [playing, setPlaying] = useState(false);+ const videoRef = useRef<HTMLVideoElement | null>(null);+ const progressRef = useRef<HTMLDivElement | null>(null);+ const labelRef = useRef<HTMLSpanElement | null>(null);+ const rafRef = useRef(0);++ const src =+ localUrl ??+ (comment.mediaKey+ ? commentMediaUrl(comment.videoId, comment.mediaKey)+ : undefined);+ const thumbnailKey = comment.mediaMeta?.thumbnailKey;+ const posterUrl = thumbnailKey+ ? commentMediaUrl(comment.videoId, thumbnailKey)+ : null;++ const stopPainting = useCallback(+ () => cancelAnimationFrame(rafRef.current),+ [],+ );++ const paintLoop = useCallback(() => {+ const el = videoRef.current;+ if (el) {+ const duration = Number.isFinite(el.duration)+ ? el.duration+ : (comment.mediaDuration ?? 0);+ const fraction = duration > 0 ? el.currentTime / duration : 0;+ if (progressRef.current)+ progressRef.current.style.transform = `scaleX(${Math.min(1, fraction)})`;+ if (labelRef.current) {+ const text = formatMediaDuration(+ Math.max(0, duration - el.currentTime),+ );+ if (labelRef.current.textContent !== text)+ labelRef.current.textContent = text;+ }+ }+ rafRef.current = requestAnimationFrame(paintLoop);+ }, [comment.mediaDuration]);++ // Registry stop collapses the card back to its poster (spec: a video card+ // losing the slot doesn't linger as a paused frame).+ const collapse = useCallback(() => {+ videoRef.current?.pause();+ stopPainting();+ setPlaying(false);+ }, [stopPainting]);++ const close = useCallback(() => {+ const el = videoRef.current;+ collapse();+ if (el) releasePlayback(el, { resumeMain: true });+ }, [collapse]);++ // The <video> mounts only after the play click, so claiming happens via ref+ // callback rather than an effect racing autoPlay.+ const attachVideo = useCallback(+ (el: HTMLVideoElement | null) => {+ videoRef.current = el;+ if (!el) return;+ claimPlayback(el, collapse);+ suspendMainVideo();+ el.addEventListener("ended", () => {+ collapse();+ releasePlayback(el, { resumeMain: true });+ });+ paintLoop();+ },+ [collapse, paintLoop],+ );++ useEffect(+ () => () => {+ stopPainting();+ const el = videoRef.current;+ if (!el) return;+ el.pause();+ releasePlayback(el, { resumeMain: true });+ },+ [stopPainting],+ );++ const togglePause = useCallback(() => {+ const el = videoRef.current;+ if (!el) return;+ if (el.paused) void el.play();+ else el.pause();+ }, []);++ if (!src) return null;++ return (+ <div+ className={`relative w-44 max-w-full overflow-hidden rounded-xl bg-gray-3 ring-1 ring-gray-5 aspect-video ${className ?? ""}`}+ >+ {playing ? (+ <>+ {/* biome-ignore lint/a11y/useMediaCaption: user-generated media comment */}+ <video+ ref={attachVideo}+ src={src}+ autoPlay+ playsInline+ onClick={togglePause}+ className="object-cover size-full cursor-pointer"+ />+ <button+ type="button"+ onClick={close}+ aria-label="Close video comment"+ className="absolute top-1.5 right-1.5 grid size-6 place-items-center rounded-full bg-black/45 text-white backdrop-blur-md"+ >+ <svg+ width="10"+ height="10"+ viewBox="0 0 10 10"+ stroke="currentColor"+ strokeWidth="1.5"+ strokeLinecap="round"+ aria-hidden="true"+ >+ <path d="M1 1l8 8M9 1l-8 8" />+ </svg>+ </button>+ <span+ ref={labelRef}+ className="absolute bottom-1.5 right-1.5 rounded bg-black/60 px-1.5 py-0.5 text-[10px] tabular-nums text-white"+ />+ <div className="absolute inset-x-0 bottom-0 h-0.5 bg-white/40">+ <div+ ref={progressRef}+ className="h-full bg-white origin-left"+ style={{ transform: "scaleX(0)" }}+ />+ </div>+ </>+ ) : (+ <motion.button+ type="button"+ onClick={() => setPlaying(true)}+ aria-label={`Play video comment (${formatMediaDuration(comment.mediaDuration)})`}+ whileHover={{ scale: 1.02 }}+ whileTap={{ scale: 0.985 }}+ className="relative block size-full"+ >+ {posterUrl ? (+ // biome-ignore lint/performance/noImgElement: signed 302 URL, next/image adds nothing+ <img+ src={posterUrl}+ alt=""+ className="object-cover size-full"+ loading="lazy"+ />+ ) : localUrl ? (+ // Optimistic cards have no uploaded thumbnail yet; the blob's own+ // first frame stands in via preload="metadata".+ <video+ src={localUrl}+ preload="metadata"+ muted+ playsInline+ className="object-cover size-full pointer-events-none"+ />+ ) : (+ <div className="grid size-full place-items-center bg-gradient-to-br from-gray-3 to-gray-5 text-gray-8">+ <FilmGlyph />+ </div>+ )}+ <span className="absolute inset-0 grid place-items-center">+ <span className="grid size-9 place-items-center rounded-full bg-black/45 text-white backdrop-blur-md">+ <svg+ width="12"+ height="14"+ viewBox="0 0 10 12"+ fill="currentColor"+ className="translate-x-px"+ aria-hidden="true"+ >+ <path d="M0 1.14c0-.9.98-1.45 1.75-1L9.4 4.7a1.14 1.14 0 0 1 0 1.96L1.75 11.2A1.14 1.14 0 0 1 0 10.22V1.14Z" />+ </svg>+ </span>+ </span>+ <span className="absolute bottom-1.5 right-1.5 rounded bg-black/60 px-1.5 py-0.5 text-[10px] tabular-nums text-white">+ {formatMediaDuration(comment.mediaDuration)}+ </span>+ </motion.button>+ )}+ </div>+ );+};diff --git a/apps/web/app/s/[videoId]/_components/media-comment/VoiceNotePill.tsx b/apps/web/app/s/[videoId]/_components/media-comment/VoiceNotePill.tsxnew file mode 100644index 000000000..d2334f0de--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/media-comment/VoiceNotePill.tsx@@ -0,0 +1,214 @@+"use client";++import { AnimatePresence, motion } from "motion/react";+import { useCallback, useEffect, useRef, useState } from "react";+import { commentMediaUrl } from "@/lib/comment-media";+import { formatMediaDuration } from "./format-media-duration";+import type { MediaComment } from "./media-comment-types";+import {+ claimPlayback,+ releasePlayback,+ suspendMainVideo,+} from "./media-playback-registry";+import {+ resolveWaveform,+ WAVEFORM_BAR_COUNT,+ WAVEFORM_BAR_COUNT_COMPACT,+ WaveformBars,+} from "./WaveformBars";++const PlayGlyph = () => (+ <svg+ width="10"+ height="12"+ viewBox="0 0 10 12"+ fill="currentColor"+ aria-hidden="true"+ >+ <path d="M0 1.14c0-.9.98-1.45 1.75-1L9.4 4.7a1.14 1.14 0 0 1 0 1.96L1.75 11.2A1.14 1.14 0 0 1 0 10.22V1.14Z" />+ </svg>+);++const PauseGlyph = () => (+ <svg+ width="10"+ height="12"+ viewBox="0 0 10 12"+ fill="currentColor"+ aria-hidden="true"+ >+ <rect x="0" y="0" width="3.4" height="12" rx="1" />+ <rect x="6.6" y="0" width="3.4" height="12" rx="1" />+ </svg>+);++interface VoiceNotePillProps {+ comment: MediaComment;+ localUrl?: string;+ compact?: boolean;+ className?: string;+}++/**+ * WhatsApp-style voice note: play circle, waveform with played-portion fill,+ * remaining-time label. Playback progress paints via `--p` + `textContent`+ * inside a rAF loop — no React renders while the note plays.+ */+export const VoiceNotePill = ({+ comment,+ localUrl,+ compact = false,+ className,+}: VoiceNotePillProps) => {+ const [playing, setPlaying] = useState(false);+ const audioRef = useRef<HTMLAudioElement | null>(null);+ const progressRef = useRef<HTMLElement | null>(null);+ const labelRef = useRef<HTMLSpanElement | null>(null);+ const rafRef = useRef(0);++ const barCount = compact ? WAVEFORM_BAR_COUNT_COMPACT : WAVEFORM_BAR_COUNT;+ const peaks = resolveWaveform(+ comment.id,+ comment.mediaMeta?.waveform ?? null,+ barCount,+ );++ const durationOf = useCallback(() => {+ const el = audioRef.current;+ const metaDuration = el?.duration;+ if (metaDuration && Number.isFinite(metaDuration)) return metaDuration;+ return comment.mediaDuration ?? 0;+ }, [comment.mediaDuration]);++ const paint = useCallback(() => {+ const el = audioRef.current;+ if (!el) return;+ const duration = durationOf();+ const fraction = duration > 0 ? el.currentTime / duration : 0;+ progressRef.current?.style.setProperty(+ "--p",+ `${Math.min(100, fraction * 100)}%`,+ );+ if (labelRef.current) {+ const remaining = Math.max(0, duration - el.currentTime);+ const text = formatMediaDuration(remaining);+ if (labelRef.current.textContent !== text)+ labelRef.current.textContent = text;+ }+ }, [durationOf]);++ const stopPainting = useCallback(+ () => cancelAnimationFrame(rafRef.current),+ [],+ );++ const paintLoop = useCallback(() => {+ paint();+ rafRef.current = requestAnimationFrame(paintLoop);+ }, [paint]);++ // The registry's stop: a plain pause that keeps position, so a different+ // card taking over doesn't lose the listener's place in this note.+ const handleRegistryStop = useCallback(() => {+ audioRef.current?.pause();+ stopPainting();+ setPlaying(false);+ }, [stopPainting]);++ const ensureAudio = useCallback(() => {+ if (audioRef.current) return audioRef.current;+ const el = new Audio(+ localUrl ??+ (comment.mediaKey+ ? commentMediaUrl(comment.videoId, comment.mediaKey)+ : ""),+ );+ el.preload = "metadata";+ el.addEventListener("ended", () => {+ stopPainting();+ setPlaying(false);+ el.currentTime = 0;+ progressRef.current?.style.setProperty("--p", "0%");+ if (labelRef.current)+ labelRef.current.textContent = formatMediaDuration(durationOf());+ releasePlayback(el, { resumeMain: true });+ });+ audioRef.current = el;+ return el;+ }, [comment.mediaKey, comment.videoId, durationOf, localUrl, stopPainting]);++ const toggle = useCallback(() => {+ const el = ensureAudio();+ if (playing) {+ // User pause keeps the claim: mid-note is still "their turn", the main+ // video should not snap back.+ el.pause();+ stopPainting();+ setPlaying(false);+ return;+ }+ claimPlayback(el, handleRegistryStop);+ suspendMainVideo();+ void el.play();+ setPlaying(true);+ paintLoop();+ }, [ensureAudio, handleRegistryStop, paintLoop, playing, stopPainting]);++ const seek = useCallback(+ (fraction: number) => {+ const el = ensureAudio();+ const duration = durationOf();+ if (duration <= 0) return;+ el.currentTime = fraction * duration;+ paint();+ },+ [durationOf, ensureAudio, paint],+ );++ useEffect(+ () => () => {+ stopPainting();+ const el = audioRef.current;+ if (!el) return;+ el.pause();+ el.src = "";+ // Unmount ends the interaction outright, so the main video gets its+ // resume if it was owed one.+ releasePlayback(el, { resumeMain: true });+ },+ [stopPainting],+ );++ return (+ <div+ className={`inline-flex h-9 max-w-full items-center gap-2.5 rounded-full bg-gray-2 pl-1 pr-3 ring-1 ring-gray-4 ${className ?? ""}`}+ >+ <button+ type="button"+ onClick={toggle}+ aria-label={playing ? "Pause voice note" : "Play voice note"}+ className="grid text-white rounded-full shrink-0 size-7 place-items-center bg-gray-12"+ >+ <AnimatePresence mode="wait" initial={false}>+ <motion.span+ key={playing ? "pause" : "play"}+ initial={{ scale: 0.8, opacity: 0 }}+ animate={{ scale: 1, opacity: 1 }}+ exit={{ scale: 0.8, opacity: 0 }}+ transition={{ duration: 0.14 }}+ className={playing ? "" : "translate-x-px"}+ >+ {playing ? <PauseGlyph /> : <PlayGlyph />}+ </motion.span>+ </AnimatePresence>+ </button>+ <WaveformBars peaks={peaks} progressRef={progressRef} onSeek={seek} />+ <span+ ref={labelRef}+ className="text-[11px] shrink-0 tabular-nums text-gray-10"+ >+ {formatMediaDuration(comment.mediaDuration)}+ </span>+ </div>+ );+};diff --git a/apps/web/app/s/[videoId]/_components/media-comment/WaveformBars.tsx b/apps/web/app/s/[videoId]/_components/media-comment/WaveformBars.tsxnew file mode 100644index 000000000..6a5cd7efc--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/media-comment/WaveformBars.tsx@@ -0,0 +1,181 @@+"use client";++import type { MouseEvent as ReactMouseEvent, RefObject } from "react";++/** Bars in a full-width voice note, and in a cramped one. */+export const WAVEFORM_BAR_COUNT = 64;+export const WAVEFORM_BAR_COUNT_COMPACT = 40;++/** Peaks stay inside this band so a bar is never invisible and never clipped. */+export const WAVEFORM_MIN_PEAK = 0.15;+export const WAVEFORM_MAX_PEAK = 0.9;++const clampPeak = (value: number) =>+ Math.min(WAVEFORM_MAX_PEAK, Math.max(WAVEFORM_MIN_PEAK, value));++/**+ * Deterministic stand-in waveform for notes recorded before peak extraction+ * existed (or whose extraction failed).+ *+ * Seeded entirely by the comment id, so a given note draws the same shape on+ * every render, in every tab, forever — a random fallback would shimmer on each+ * re-render. Two out-of-phase sines give it a spoken-sentence envelope, an+ * xorshift stream roughens it, and a centre-weighted taper keeps the ends+ * quieter the way a real recording tends to be.+ */+export function pseudoWaveform(+ seed: string,+ bars: number = WAVEFORM_BAR_COUNT,+): number[] {+ if (!Number.isFinite(bars) || bars <= 0) return [];+ const count = Math.floor(bars);++ // FNV-1a over the id: cheap, stable, and well spread for short strings.+ let hash = 0x811c9dc5;+ for (let index = 0; index < seed.length; index += 1) {+ hash ^= seed.charCodeAt(index);+ hash = Math.imul(hash, 0x01000193) >>> 0;+ }++ const phase = ((hash % 1000) / 1000) * Math.PI * 2;+ let state = hash || 0x9e3779b9;+ const peaks: number[] = new Array(count);++ for (let index = 0; index < count; index += 1) {+ state ^= (state << 13) >>> 0;+ state >>>= 0;+ state ^= state >>> 17;+ state ^= (state << 5) >>> 0;+ state >>>= 0;+ const noise = state / 0xffffffff;++ const t = count === 1 ? 0.5 : index / (count - 1);+ const body = (Math.sin(phase + t * Math.PI * 2) + 1) / 2;+ const detail = (Math.sin(phase * 0.7 + t * Math.PI * 11) + 1) / 2;+ const taper = 0.68 + 0.32 * Math.sin(Math.PI * t);+ const mixed = (0.45 * body + 0.27 * detail + 0.28 * noise) * taper;++ peaks[index] = clampPeak(+ WAVEFORM_MIN_PEAK + mixed * (WAVEFORM_MAX_PEAK - WAVEFORM_MIN_PEAK),+ );+ }++ return peaks;+}++/**+ * Squash (or stretch) stored peaks onto the number of bars actually rendered,+ * taking the loudest sample per bucket so a resampled waveform keeps its+ * transients instead of averaging into mush.+ */+export function resampleWaveform(+ peaks: readonly number[],+ bars: number,+): number[] {+ if (!Number.isFinite(bars) || bars <= 0) return [];+ const count = Math.floor(bars);+ const out: number[] = new Array(count);++ for (let index = 0; index < count; index += 1) {+ const start = Math.floor((index * peaks.length) / count);+ const end = Math.max(+ start + 1,+ Math.floor(((index + 1) * peaks.length) / count),+ );+ let peak = 0;+ for (+ let source = start;+ source < end && source < peaks.length;+ source += 1+ ) {+ const value = peaks[source];+ if (typeof value === "number" && Number.isFinite(value) && value > peak) {+ peak = value;+ }+ }+ out[index] = clampPeak(peak);+ }++ return out;+}++/** Stored peaks when we have them, a stable pseudo-waveform when we do not. */+export function resolveWaveform(+ seed: string,+ peaks: readonly number[] | null | undefined,+ bars: number = WAVEFORM_BAR_COUNT,+): number[] {+ if (peaks && peaks.length > 0) return resampleWaveform(peaks, bars);+ return pseudoWaveform(seed, bars);+}++/** Tallest a bar can draw, in px. Peaks are a fraction of this. */+const BAR_MAX_HEIGHT = 20;+const BAR_MIN_HEIGHT = 3;++interface WaveformBarsProps {+ peaks: number[];+ /**+ * Progress wrapper: the player writes `--p` on this node inside its rAF+ * loop, and the blue overlay's clip-path follows without a React render.+ */+ progressRef?: RefObject<HTMLElement | null>;+ onSeek?: (fraction: number) => void;+ className?: string;+}++const barRow = (peaks: number[], color: string) =>+ peaks.map((peak, index) => (+ <span+ key={`${index}-${peak}`}+ className={`w-[2px] shrink-0 rounded-full ${color}`}+ style={{+ height: `${Math.max(BAR_MIN_HEIGHT, Math.round(peak * BAR_MAX_HEIGHT))}px`,+ }}+ />+ ));++/**+ * Two identical bar rows stacked in the same box. The lower one is the unplayed+ * track; the upper one is the played colour, revealed by clipping its wrapper+ * to `--p`. Painting progress as a clip means playback never touches React.+ */+export function WaveformBars({+ peaks,+ progressRef,+ onSeek,+ className,+}: WaveformBarsProps) {+ const seek = (event: ReactMouseEvent<HTMLElement>) => {+ if (!onSeek) return;+ const bounds = event.currentTarget.getBoundingClientRect();+ if (bounds.width <= 0) return;+ const fraction = (event.clientX - bounds.left) / bounds.width;+ onSeek(Math.min(1, Math.max(0, fraction)));+ };++ return (+ // A button (not a div) so the scrub target is a real control, but kept out+ // of the tab order: the play/pause button next to it is the keyboard path,+ // and scrubbing is a pointer-only refinement.+ <button+ type="button"+ tabIndex={-1}+ aria-label="Seek within voice note"+ ref={progressRef as RefObject<HTMLButtonElement | null> | undefined}+ onClick={seek}+ className={`relative flex h-5 min-w-0 shrink items-center gap-px ${+ onSeek ? "cursor-pointer" : "cursor-default"+ } ${className ?? ""}`}+ >+ {barRow(peaks, "bg-gray-7")}+ <span+ aria-hidden+ className="flex absolute inset-0 gap-px items-center"+ style={{ clipPath: "inset(0 calc(100% - var(--p, 0%)) 0 0)" }}+ >+ {barRow(peaks, "bg-blue-9")}+ </span>+ </button>+ );+}diff --git a/apps/web/app/s/[videoId]/_components/media-comment/format-media-duration.ts b/apps/web/app/s/[videoId]/_components/media-comment/format-media-duration.tsnew file mode 100644index 000000000..107fa073c--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/media-comment/format-media-duration.ts@@ -0,0 +1,24 @@+/**+ * `m:ss` clock for media-comment durations, widening to `h:mm:ss` past an hour.+ *+ * Seconds are floored so a 9.7s note reads "0:09" for its whole life instead of+ * flicking to "0:10" a frame before it ends. Non-finite/negative input (an+ * element with no metadata yet) collapses to "0:00".+ */+export function formatMediaDuration(+ seconds: number | null | undefined,+): string {+ const value =+ typeof seconds === "number" && Number.isFinite(seconds) && seconds > 0+ ? Math.floor(seconds)+ : 0;++ const secs = value % 60;+ const mins = Math.floor(value / 60) % 60;+ const hours = Math.floor(value / 3600);+ const pad = (part: number) => part.toString().padStart(2, "0");++ return hours > 0+ ? `${hours}:${pad(mins)}:${pad(secs)}`+ : `${mins}:${pad(secs)}`;+}diff --git a/apps/web/app/s/[videoId]/_components/media-comment/local-media-urls.ts b/apps/web/app/s/[videoId]/_components/media-comment/local-media-urls.tsnew file mode 100644index 000000000..61d46ed4c--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/media-comment/local-media-urls.ts@@ -0,0 +1,61 @@+"use client";++import { useSyncExternalStore } from "react";++/**+ * Blob URLs for just-recorded media comments, keyed by comment id (temp id+ * first, remapped to the real id once the row exists). Module-level because+ * the optimistic card renders in trees (sidebar, timeline) far from the+ * recorder that owns the blob.+ */+const urls = new Map<string, string>();+const listeners = new Set<() => void>();++const notify = () => {+ for (const listener of listeners) listener();+};++const REVOKE_AFTER_REMAP_MS = 5 * 60 * 1000;++export function setLocalMediaUrl(commentId: string, url: string) {+ urls.set(commentId, url);+ notify();+}++/** Point the real comment id at the same blob; schedule the eventual revoke. */+export function remapLocalMediaUrl(tempId: string, realId: string) {+ const url = urls.get(tempId);+ if (!url) return;+ urls.delete(tempId);+ urls.set(realId, url);+ notify();+ // By then the uploaded copy is servable and any in-flight playback of the+ // blob has long finished or moved on.+ setTimeout(() => {+ if (urls.get(realId) !== url) return;+ urls.delete(realId);+ URL.revokeObjectURL(url);+ notify();+ }, REVOKE_AFTER_REMAP_MS);+}++export function dropLocalMediaUrl(commentId: string) {+ const url = urls.get(commentId);+ if (!url) return;+ urls.delete(commentId);+ URL.revokeObjectURL(url);+ notify();+}++const subscribe = (listener: () => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+};++export function useLocalMediaUrl(commentId: string): string | undefined {+ return useSyncExternalStore(+ subscribe,+ () => urls.get(commentId),+ () => undefined,+ );+}diff --git a/apps/web/app/s/[videoId]/_components/media-comment/media-comment-types.ts b/apps/web/app/s/[videoId]/_components/media-comment/media-comment-types.tsnew file mode 100644index 000000000..dc9b0d0e0--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/media-comment/media-comment-types.ts@@ -0,0 +1,21 @@+import type { comments as commentsSchema } from "@cap/database/schema";++/** The slice of a comment row media components need. */+export type MediaComment = Pick<+ typeof commentsSchema.$inferSelect,+ | "id"+ | "type"+ | "videoId"+ | "content"+ | "mediaKey"+ | "mediaDuration"+ | "mediaMeta"+>;++export const isMediaComment = <+ C extends Pick<MediaComment, "type" | "mediaKey">,+>(+ comment: C,+): boolean =>+ (comment.type === "video" || comment.type === "audio") &&+ comment.mediaKey !== null;diff --git a/apps/web/app/s/[videoId]/_components/media-comment/media-playback-registry.ts b/apps/web/app/s/[videoId]/_components/media-comment/media-playback-registry.tsnew file mode 100644index 000000000..597575826--- /dev/null+++ b/apps/web/app/s/[videoId]/_components/media-comment/media-playback-registry.ts@@ -0,0 +1,132 @@+"use client";++/**+ * Module-level traffic control for every media element on the share page.+ *+ * Three rules, all of them global, none of them expressible inside a single+ * card:+ *+ * 1. Only one comment media plays at a time — a new claim stops the old one.+ * 2. A comment taking over pauses the main video, and hands playback back+ * when it is done *only* if the main video was actually playing.+ * 3. The main video starting wins outright and stops all comment media.+ *+ * The state is a module singleton rather than context because the cards live in+ * several trees (sidebar list, timeline lane, composer preview) and must still+ * see each other. React only enters through `useMainVideoInterlock`, which+ * registers the share page's playback store and refcounts its subscription so+ * dozens of mounted cards still add up to exactly one listener.+ */++import { useEffect } from "react";+import { useOptionalPlayback } from "../playback/PlaybackContext";+import type { PlaybackStore } from "../playback/playback-store";++type Active = { el: HTMLMediaElement; stop: () => void };++let active: Active | null = null;++/** The playback store of the main video, while at least one card is mounted. */+let mainStore: PlaybackStore | null = null;+/** The main video was playing when a comment took over, so it is owed a resume. */+let resumeMain = false;++/**+ * Register `el` as the one playing comment media, stopping whoever held the+ * slot before. `stop` must leave the element paused; for the video card it also+ * collapses the card back to its poster.+ */+export function claimPlayback(el: HTMLMediaElement, stop: () => void): void {+ const previous = active && active.el !== el ? active : null;+ // Install the new claim *before* stopping the old one: the outgoing card+ // pauses synchronously, and its own `pause` handler must see that it no+ // longer owns the slot so it does not hand the main video back mid-swap.+ active = { el, stop };+ previous?.stop();+}++/**+ * Give up the slot. `resumeMain` marks the end of a whole interaction (playback+ * ended, the card collapsed, the card unmounted) as opposed to a plain pause,+ * and is the only way the main video is handed back.+ */+export function releasePlayback(+ el: HTMLMediaElement,+ options?: { resumeMain?: boolean },+): void {+ // Someone else already took the slot; they own the main video now.+ if (active?.el !== el) return;+ active = null;+ if (!resumeMain) return;+ resumeMain = false;+ if (!options?.resumeMain) return;+ // Guard against the store already running: `play()` on a playing element is+ // a no-op, but skipping it keeps us out of its subscriber notifications.+ if (mainStore && !mainStore.getPlaying()) mainStore.play();+}++/**+ * Stop whatever comment media is playing. Called when the main video starts, so+ * the pending resume is dropped rather than honoured — the main video is+ * already back.+ */+export function stopAll(): void {+ const current = active;+ active = null;+ resumeMain = false;+ current?.stop();+}++/**+ * Called by a card as it starts playing. Captures whether the main video was+ * running and pauses it. A second card taking over does not re-capture: the+ * main video is already paused, and the original answer is still the right one.+ */+export function suspendMainVideo(): void {+ if (!mainStore || resumeMain) return;+ resumeMain = mainStore.getPlaying();+ if (resumeMain) mainStore.pause();+}++const interlocks = new Map<+ PlaybackStore,+ { refs: number; unsubscribe: () => void }+>();++/**+ * Wires the main video into the registry for as long as any media comment is+ * mounted. Safe (and intended) to call from every `MediaCommentBody`: the+ * subscription itself is refcounted per store, so N cards cost one listener.+ */+export function useMainVideoInterlock(): void {+ const playback = useOptionalPlayback();++ useEffect(() => {+ if (!playback) return;++ mainStore = playback;+ const existing = interlocks.get(playback);+ if (existing) {+ existing.refs += 1;+ } else {+ interlocks.set(playback, {+ refs: 1,+ unsubscribe: playback.subscribePlaying(() => {+ if (playback.getPlaying()) stopAll();+ }),+ });+ }++ return () => {+ const entry = interlocks.get(playback);+ if (!entry) return;+ entry.refs -= 1;+ if (entry.refs > 0) return;+ entry.unsubscribe();+ interlocks.delete(playback);+ if (mainStore !== playback) return;+ mainStore = null;+ resumeMain = false;+ };+ }, [playback]);+}