Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(web): add TimelineView with branches and composer

Richie McIlroyed154bba7c10
diff --git a/apps/web/app/s/[videoId]/_components/timeline/TimelineActiveCue.tsx b/apps/web/app/s/[videoId]/_components/timeline/TimelineActiveCue.tsx
new file mode 100644
index 000000000..2c990f834
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/TimelineActiveCue.tsx
@@ -0,0 +1,70 @@
+"use client";
+
+import { type RefObject, useEffect, useMemo, useRef } from "react";
+import type { CommentType } from "../../Share";
+import { useCoarseTime } from "../playback/PlaybackContext";
+import { ACTIVE_CUE_WINDOW } from "./timeline-constants";
+import type { BranchNode } from "./timeline-layout";
+
+interface TimelineActiveCueProps {
+ branches: readonly BranchNode<CommentType>[];
+ containerRef: RefObject<HTMLDivElement | null>;
+}
+
+const escapeId = (id: string) =>
+ typeof CSS !== "undefined" && typeof CSS.escape === "function"
+ ? CSS.escape(id)
+ : id.replace(/["\\]/g, "\\$&");
+
+/**
+ * Rings whichever branch the playhead is currently sitting on.
+ *
+ * This is the only component in the band that re-renders while the video plays,
+ * and it renders nothing: the highlight is a `data-active` attribute written
+ * straight onto the node, so the memoised branches are never disturbed.
+ */
+export function TimelineActiveCue({
+ branches,
+ containerRef,
+}: TimelineActiveCueProps) {
+ const time = useCoarseTime(250);
+ const previousRef = useRef<string | null>(null);
+
+ const marks = useMemo(
+ () => branches.map((node) => ({ id: node.id, t: node.t })),
+ [branches],
+ );
+
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!container) return;
+
+ // Latest mark the playhead has reached, as long as it is still fresh.
+ let next: string | null = null;
+ for (const mark of marks) {
+ if (mark.t > time + ACTIVE_CUE_WINDOW) break;
+ if (Math.abs(mark.t - time) <= ACTIVE_CUE_WINDOW) next = mark.id;
+ }
+
+ if (next === previousRef.current) return;
+
+ const find = (id: string) =>
+ container.querySelector<HTMLElement>(
+ `[data-comment-id="${escapeId(id)}"]`,
+ );
+
+ if (previousRef.current)
+ find(previousRef.current)?.removeAttribute("data-active");
+ if (next) find(next)?.setAttribute("data-active", "");
+ previousRef.current = next;
+ }, [marks, time, containerRef]);
+
+ useEffect(
+ () => () => {
+ previousRef.current = null;
+ },
+ [],
+ );
+
+ return null;
+}
diff --git a/apps/web/app/s/[videoId]/_components/timeline/TimelineBranch.tsx b/apps/web/app/s/[videoId]/_components/timeline/TimelineBranch.tsx
new file mode 100644
index 000000000..5a5403993
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/TimelineBranch.tsx
@@ -0,0 +1,204 @@
+"use client";
+
+import type { ImageUpload } from "@cap/web-domain";
+import clsx from "clsx";
+import { motion } from "motion/react";
+import { memo, type ReactNode } from "react";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
+import { NODE_SIZE } from "./timeline-constants";
+
+export type BranchGlyph = "text" | "emoji" | "video" | "audio";
+
+interface BranchAnchorProps {
+ left: string;
+ stem: number;
+ delay: number;
+ reduceMotion: boolean;
+ children: ReactNode;
+}
+
+/**
+ * Zero-width post at a point in time: a hairline growing down off the anchor
+ * line with the node parked on the end of it. Shared by single nodes and
+ * clusters so both hang at exactly the same depth.
+ */
+export function BranchAnchor({
+ left,
+ stem,
+ delay,
+ reduceMotion,
+ children,
+}: BranchAnchorProps) {
+ return (
+ <motion.div
+ // top 0 is the anchor line: the ruler hairline across the top of the
+ // comments surface, so stems drop off the ruler rather than the strip.
+ className="pointer-events-none absolute top-0 z-30 w-0"
+ style={{ left, transformOrigin: "top" }}
+ initial={
+ reduceMotion ? { opacity: 0 } : { opacity: 0, scaleY: 0.4, y: -6 }
+ }
+ animate={reduceMotion ? { opacity: 1 } : { opacity: 1, scaleY: 1, y: 0 }}
+ transition={
+ reduceMotion
+ ? { duration: 0 }
+ : { type: "spring", stiffness: 420, damping: 30, delay }
+ }
+ >
+ <span
+ aria-hidden
+ className="absolute top-0 left-0 w-px -translate-x-1/2 bg-gradient-to-b from-gray-7 to-transparent"
+ style={{ height: Math.max(0, stem - NODE_SIZE / 2) }}
+ />
+ {children}
+ </motion.div>
+ );
+}
+
+// The pseudo-element grows the hit area to ~46px on touch screens (the visual
+// node is 30px, under the 44px guideline) without touching the layout; hit
+// tests on a pseudo-element resolve to the button itself, so node-targeted
+// delegation (`closest("[data-comment-id]")`) still works.
+export const NODE_BASE_CLASS =
+ "pointer-events-auto absolute left-0 flex -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full transition-shadow focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-9 data-[active]:ring-2 data-[active]:ring-blue-9 [@media(pointer:coarse)]:before:content-[''] [@media(pointer:coarse)]:before:absolute [@media(pointer:coarse)]:before:-inset-2 [@media(pointer:coarse)]:before:rounded-full";
+
+interface TimelineBranchProps {
+ id: string;
+ /** Padded-calc `left`, computed once per layout pass. */
+ left: string;
+ stem: number;
+ glyph: BranchGlyph;
+ /** Emoji glyph, or the first line of a text comment for the label. */
+ content: string;
+ avatarUrl: ImageUpload.ImageUrl | null;
+ authorName: string;
+ timeLabel: string;
+ sending: boolean;
+ delay: number;
+ reduceMotion: boolean;
+ /** Dropped under reduced motion so nothing morphs into the card. */
+ morphId?: string;
+}
+
+/**
+ * One comment on the rail. Everything it receives is a primitive, so the memo
+ * actually holds and a hover somewhere else in the band re-renders nothing.
+ */
+export const TimelineBranch = memo(function TimelineBranch({
+ id,
+ left,
+ stem,
+ glyph,
+ content,
+ avatarUrl,
+ authorName,
+ timeLabel,
+ sending,
+ delay,
+ reduceMotion,
+ morphId,
+}: TimelineBranchProps) {
+ const label =
+ glyph === "emoji"
+ ? `Reaction ${content} by ${authorName} at ${timeLabel}`
+ : `Comment by ${authorName} at ${timeLabel}`;
+
+ return (
+ <BranchAnchor
+ left={left}
+ stem={stem}
+ delay={delay}
+ reduceMotion={reduceMotion}
+ >
+ <button
+ type="button"
+ data-comment-id={id}
+ data-timeline-node=""
+ aria-label={label}
+ title={label}
+ className={clsx(
+ NODE_BASE_CLASS,
+ glyph === "emoji"
+ ? "text-[22px] leading-none"
+ : "shadow-[0_1px_3px_rgba(18,22,31,0.10)]",
+ glyph === "audio" ? "bg-blue-9 text-white" : null,
+ glyph === "text" || glyph === "video"
+ ? "bg-white text-gray-12 ring-1 ring-gray-5"
+ : null,
+ sending && "opacity-50",
+ )}
+ style={{ top: stem, width: NODE_SIZE, height: NODE_SIZE }}
+ >
+ <BranchGlyphContent
+ glyph={glyph}
+ content={content}
+ avatarUrl={avatarUrl}
+ authorName={authorName}
+ morphId={reduceMotion ? undefined : morphId}
+ />
+ </button>
+ </BranchAnchor>
+ );
+});
+
+function BranchGlyphContent({
+ glyph,
+ content,
+ avatarUrl,
+ authorName,
+ morphId,
+}: {
+ glyph: BranchGlyph;
+ content: string;
+ avatarUrl: ImageUpload.ImageUrl | null;
+ authorName: string;
+ morphId?: string;
+}) {
+ if (glyph === "emoji") {
+ return (
+ <span aria-hidden className="font-emoji">
+ {content}
+ </span>
+ );
+ }
+
+ if (glyph === "video") {
+ return <PlayGlyph />;
+ }
+
+ if (glyph === "audio") {
+ return <MicGlyph />;
+ }
+
+ // The avatar, not the ring, carries the morph: when the card opens the ring
+ // stays put on the rail so the branch never looks like it vanished.
+ return (
+ <motion.span
+ layoutId={morphId}
+ className="block overflow-hidden rounded-full size-[26px]"
+ >
+ <SignedImageUrl
+ image={avatarUrl}
+ name={authorName}
+ className="size-full"
+ letterClass="text-[11px] font-medium"
+ />
+ </motion.span>
+ );
+}
+
+/** Inline rather than an icon-pack import: two paths, no tree-shaking bet. */
+export const PlayGlyph = () => (
+ <svg viewBox="0 0 12 12" className="size-4 fill-current" aria-hidden>
+ <title>Video comment</title>
+ <path d="M4 2.6c0-.5.5-.8.9-.5l4 3.4c.3.3.3.7 0 1l-4 3.4c-.4.3-.9 0-.9-.5V2.6Z" />
+ </svg>
+);
+
+export const MicGlyph = () => (
+ <svg viewBox="0 0 12 12" className="size-4 fill-current" aria-hidden>
+ <title>Voice note</title>
+ <path d="M6 1.2a1.6 1.6 0 0 0-1.6 1.6v2.6a1.6 1.6 0 1 0 3.2 0V2.8A1.6 1.6 0 0 0 6 1.2Z" />
+ <path d="M3 5.2a.5.5 0 0 0-1 0 4 4 0 0 0 3.5 3.97v1.13a.5.5 0 0 0 1 0V9.17A4 4 0 0 0 10 5.2a.5.5 0 0 0-1 0 3 3 0 0 1-6 0Z" />
+ </svg>
+);
diff --git a/apps/web/app/s/[videoId]/_components/timeline/TimelineBranchCard.tsx b/apps/web/app/s/[videoId]/_components/timeline/TimelineBranchCard.tsx
new file mode 100644
index 000000000..62bc2adf5
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/TimelineBranchCard.tsx
@@ -0,0 +1,216 @@
+"use client";
+
+import { motion } from "motion/react";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
+import type { CommentType } from "../../Share";
+import { MediaCommentBody } from "../media-comment/MediaCommentBody";
+import { isMediaComment } from "../media-comment/media-comment-types";
+import { formatTimeAgo } from "../tabs/Activity/utils";
+import {
+ CARD_WIDTH,
+ NODE_SIZE,
+ RAIL_PAD_X,
+ usableWidth,
+} from "./timeline-constants";
+import { formatClock } from "./timeline-format";
+import type { BranchNode } from "./timeline-layout";
+
+interface TimelineBranchCardProps {
+ node: BranchNode<CommentType>;
+ percent: number;
+ stem: number;
+ /** Live height of the comments shelf the card's `bottom` is measured from. */
+ shelfHeight: number;
+ trackWidth: number;
+ replyCounts: ReadonlyMap<string, number>;
+ reduceMotion: boolean;
+ pinned: boolean;
+ onSeek: (time: number) => void;
+ onPin: (id: string) => void;
+ onKeepOpen: () => void;
+ onClose: () => void;
+}
+
+/** Keep the card inside the band no matter how close to the edge the node is. */
+const clampCenter = (percent: number, trackWidth: number): number => {
+ const x = RAIL_PAD_X + (percent / 100) * usableWidth(trackWidth);
+ const half = CARD_WIDTH / 2;
+ if (trackWidth < CARD_WIDTH + 16) return trackWidth / 2;
+ return Math.min(Math.max(x, half + 8), trackWidth - half - 8);
+};
+
+/**
+ * The hover/pinned card. Opens upward out of the comments surface, over the
+ * transport and the strip: the surface is under a hundred pixels tall and a
+ * comment body is not.
+ */
+export function TimelineBranchCard({
+ node,
+ percent,
+ stem,
+ shelfHeight,
+ trackWidth,
+ replyCounts,
+ reduceMotion,
+ pinned,
+ onSeek,
+ onPin,
+ onKeepOpen,
+ onClose,
+}: TimelineBranchCardProps) {
+ const center = clampCenter(percent, trackWidth);
+ const spring = reduceMotion
+ ? { duration: 0 }
+ : ({ type: "spring", stiffness: 420, damping: 34 } as const);
+
+ return (
+ <motion.div
+ data-timeline-card=""
+ className="pointer-events-auto absolute z-40 w-72"
+ style={{
+ left: center,
+ bottom: shelfHeight - stem + NODE_SIZE / 2 + 8,
+ translateX: "-50%",
+ }}
+ initial={
+ reduceMotion ? { opacity: 0 } : { opacity: 0, y: 8, scale: 0.97 }
+ }
+ animate={reduceMotion ? { opacity: 1 } : { opacity: 1, y: 0, scale: 1 }}
+ exit={
+ reduceMotion
+ ? { opacity: 0, transition: { duration: 0 } }
+ : { opacity: 0, y: 6, scale: 0.98, transition: { duration: 0.12 } }
+ }
+ transition={spring}
+ onPointerEnter={onKeepOpen}
+ onPointerLeave={pinned ? undefined : onClose}
+ >
+ <div className="new-card-style overflow-hidden p-3">
+ {node.kind === "single" ? (
+ <SingleCard
+ comment={node.comment}
+ t={node.t}
+ replies={replyCounts.get(node.comment.id) ?? 0}
+ reduceMotion={reduceMotion}
+ onSeek={onSeek}
+ />
+ ) : (
+ <ClusterCard
+ comments={node.comments}
+ onPick={(comment) => {
+ onSeek(comment.timestamp ?? node.t);
+ onPin(comment.id);
+ }}
+ />
+ )}
+ </div>
+ </motion.div>
+ );
+}
+
+function SingleCard({
+ comment,
+ t,
+ replies,
+ reduceMotion,
+ onSeek,
+}: {
+ comment: CommentType;
+ t: number;
+ replies: number;
+ reduceMotion: boolean;
+ onSeek: (time: number) => void;
+}) {
+ const name = comment.authorName || "Someone";
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center gap-2">
+ <motion.span
+ layoutId={reduceMotion ? undefined : `branch-${comment.id}`}
+ className="block overflow-hidden rounded-full size-6 shrink-0"
+ >
+ <SignedImageUrl
+ image={comment.authorImage ?? null}
+ name={name}
+ className="size-full"
+ letterClass="text-[10px] font-medium"
+ />
+ </motion.span>
+ <span className="min-w-0 flex-1 truncate text-[13px] font-medium text-gray-12">
+ {name}
+ </span>
+ <span className="text-[11px] text-gray-9">
+ {formatTimeAgo(new Date(comment.createdAt))}
+ </span>
+ <button
+ type="button"
+ onClick={() => onSeek(t)}
+ className="rounded-md bg-gray-2 px-1.5 py-0.5 font-mono text-[11px] tabular-nums text-gray-11 ring-1 ring-gray-4 transition-colors hover:bg-gray-3 hover:text-gray-12"
+ >
+ {formatClock(t)}
+ </button>
+ </div>
+
+ {isMediaComment(comment) ? (
+ <MediaCommentBody comment={comment} />
+ ) : (
+ <p className="whitespace-pre-wrap break-words text-sm text-gray-11">
+ {comment.content}
+ </p>
+ )}
+
+ {replies > 0 && (
+ <span className="text-xs text-gray-9">
+ {replies} {replies === 1 ? "reply" : "replies"}
+ </span>
+ )}
+ </div>
+ );
+}
+
+function ClusterCard({
+ comments,
+ onPick,
+}: {
+ comments: readonly CommentType[];
+ onPick: (comment: CommentType) => void;
+}) {
+ return (
+ <div className="flex flex-col gap-0.5">
+ <span className="px-1 pb-1 text-[11px] font-medium uppercase tracking-wide text-gray-9">
+ {comments.length} comments
+ </span>
+ {comments.map((comment) => (
+ <button
+ key={comment.id}
+ type="button"
+ onClick={() => onPick(comment)}
+ className="flex items-center gap-2 rounded-lg px-1 py-1 text-left transition-colors hover:bg-gray-2"
+ >
+ <span className="block overflow-hidden rounded-full size-5 shrink-0">
+ <SignedImageUrl
+ image={comment.authorImage ?? null}
+ name={comment.authorName || "Someone"}
+ className="size-full"
+ letterClass="text-[9px] font-medium"
+ />
+ </span>
+ <span className="min-w-0 flex-1 truncate text-[13px] text-gray-11">
+ <span className="font-medium text-gray-12">
+ {comment.authorName || "Someone"}
+ </span>{" "}
+ {isMediaComment(comment)
+ ? comment.type === "video"
+ ? "sent a video"
+ : "sent a voice note"
+ : comment.content}
+ </span>
+ <span className="font-mono text-[11px] tabular-nums text-gray-9">
+ {formatClock(comment.timestamp ?? 0)}
+ </span>
+ </button>
+ ))}
+ </div>
+ );
+}
diff --git a/apps/web/app/s/[videoId]/_components/timeline/TimelineBranchCluster.tsx b/apps/web/app/s/[videoId]/_components/timeline/TimelineBranchCluster.tsx
new file mode 100644
index 000000000..3007989e5
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/TimelineBranchCluster.tsx
@@ -0,0 +1,94 @@
+"use client";
+
+import type { ImageUpload } from "@cap/web-domain";
+import clsx from "clsx";
+import { memo } from "react";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
+import { BranchAnchor, NODE_BASE_CLASS } from "./TimelineBranch";
+import { NODE_SIZE } from "./timeline-constants";
+
+export interface ClusterFace {
+ id: string;
+ name: string;
+ image: ImageUpload.ImageUrl | null;
+}
+
+interface TimelineBranchClusterProps {
+ id: string;
+ left: string;
+ stem: number;
+ /** Pre-sliced to three by the layout pass; stable across hover renders. */
+ faces: readonly ClusterFace[];
+ total: number;
+ timeLabel: string;
+ delay: number;
+ reduceMotion: boolean;
+}
+
+/**
+ * A stack of comments that landed too close together to draw separately.
+ * Widens with the number of faces, so it still reads as "several people" at a
+ * glance without blowing past its neighbours.
+ */
+export const TimelineBranchCluster = memo(function TimelineBranchCluster({
+ id,
+ left,
+ stem,
+ faces,
+ total,
+ timeLabel,
+ delay,
+ reduceMotion,
+}: TimelineBranchClusterProps) {
+ const overflow = total - faces.length;
+ const label = `${total} comments at ${timeLabel}`;
+
+ return (
+ <BranchAnchor
+ left={left}
+ stem={stem}
+ delay={delay}
+ reduceMotion={reduceMotion}
+ >
+ <button
+ type="button"
+ data-comment-id={id}
+ data-timeline-node=""
+ aria-label={label}
+ title={label}
+ className={clsx(
+ NODE_BASE_CLASS,
+ "h-[30px] gap-0 rounded-full bg-white px-1.5 ring-1 ring-gray-5",
+ "shadow-[0_1px_3px_rgba(18,22,31,0.10)]",
+ )}
+ style={{ top: stem }}
+ >
+ {faces.map((face, index) => (
+ <span
+ key={face.id}
+ className={clsx(
+ "block overflow-hidden rounded-full ring-1 ring-white size-[22px]",
+ index > 0 && "-ml-2.5",
+ )}
+ style={{ zIndex: faces.length - index }}
+ >
+ <SignedImageUrl
+ image={face.image}
+ name={face.name}
+ className="size-full"
+ letterClass="text-[10px] font-medium"
+ />
+ </span>
+ ))}
+ {overflow > 0 && (
+ <span
+ className="ml-1 rounded-full bg-gray-3 px-1 text-[11px] font-medium leading-5 tabular-nums text-gray-11"
+ style={{ minWidth: NODE_SIZE / 2 }}
+ >
+ +{overflow}
+ </span>
+ )}
+ </button>
+ </BranchAnchor>
+ );
+});
diff --git a/apps/web/app/s/[videoId]/_components/timeline/TimelineBranches.tsx b/apps/web/app/s/[videoId]/_components/timeline/TimelineBranches.tsx
new file mode 100644
index 000000000..c6a285c77
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/TimelineBranches.tsx
@@ -0,0 +1,210 @@
+"use client";
+
+import { AnimatePresence, useReducedMotion } from "motion/react";
+import { useCallback, useEffect, useMemo, useRef } from "react";
+import type { CommentType } from "../../Share";
+import { TimelineBranch } from "./TimelineBranch";
+import { TimelineBranchCard } from "./TimelineBranchCard";
+import {
+ type ClusterFace,
+ TimelineBranchCluster,
+} from "./TimelineBranchCluster";
+import {
+ useTimelineActions,
+ useTimelineEnv,
+ useTimelineState,
+} from "./TimelineProvider";
+import {
+ CARD_CLOSE_GRACE,
+ CARD_OPEN_DELAY,
+ clampedRailLeft,
+ fractionInWindow,
+ NODE_SIZE,
+} from "./timeline-constants";
+import { formatClock } from "./timeline-format";
+import type { BranchNode } from "./timeline-layout";
+
+const CLUSTER_FACES = 3;
+
+interface TimelineBranchesProps {
+ branches: readonly BranchNode<CommentType>[];
+ windowStart: number;
+ windowEnd: number;
+ stems: readonly [number, number];
+ trackWidth: number;
+ /** Live height of the comments shelf; cards anchor their feet to it. */
+ shelfHeight: number;
+ replyCounts: ReadonlyMap<string, number>;
+ onSeek: (time: number) => void;
+}
+
+/**
+ * The branch layer. One click and one hover listener for the whole band,
+ * dispatched by `data-comment-id`, so a video with two hundred comments still
+ * only has two listeners attached.
+ */
+export function TimelineBranches({
+ branches,
+ windowStart,
+ windowEnd,
+ stems,
+ trackWidth,
+ shelfHeight,
+ replyCounts,
+ onSeek,
+}: TimelineBranchesProps) {
+ const reduceMotion = useReducedMotion() ?? false;
+ const { compact, hasHover } = useTimelineEnv();
+ const { hoveredId, expandedId } = useTimelineState();
+ const { setHoveredId, setExpandedId, toggleExpandedId } =
+ useTimelineActions();
+
+ const openTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const closeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const clearTimers = useCallback(() => {
+ if (openTimer.current) clearTimeout(openTimer.current);
+ if (closeTimer.current) clearTimeout(closeTimer.current);
+ openTimer.current = null;
+ closeTimer.current = null;
+ }, []);
+
+ useEffect(() => clearTimers, [clearTimers]);
+
+ // Everything a node needs is precomputed here, so the memoised nodes below
+ // only ever see primitives and stable arrays.
+ const items = useMemo(
+ () =>
+ branches.map((node, index) => {
+ const percent = Math.min(
+ 100,
+ Math.max(0, fractionInWindow(node.t, windowStart, windowEnd) * 100),
+ );
+ return {
+ node,
+ // Clamped: the rail runs edge to edge now, so a node at 0:00 would
+ // otherwise hang half off the surface.
+ left: clampedRailLeft(percent, NODE_SIZE + 4),
+ percent,
+ stem: stems[node.lane],
+ delay: Math.min(index * 0.018, 0.26),
+ timeLabel: formatClock(node.t),
+ };
+ }),
+ [branches, windowStart, windowEnd, stems],
+ );
+
+ const handlePointerOver = (event: React.PointerEvent<HTMLDivElement>) => {
+ if (!hasHover || compact) return;
+ const target = (event.target as HTMLElement).closest("[data-comment-id]");
+ const id = target?.getAttribute("data-comment-id") ?? null;
+ if (!id || id === hoveredId) return;
+ clearTimers();
+ openTimer.current = setTimeout(() => setHoveredId(id), CARD_OPEN_DELAY);
+ };
+
+ const handlePointerOut = (event: React.PointerEvent<HTMLDivElement>) => {
+ if (!hasHover || compact) return;
+ const next = event.relatedTarget;
+ if (next instanceof Node && event.currentTarget.contains(next)) return;
+ clearTimers();
+ closeTimer.current = setTimeout(() => setHoveredId(null), CARD_CLOSE_GRACE);
+ };
+
+ const handleClick = (event: React.MouseEvent<HTMLDivElement>) => {
+ const target = (event.target as HTMLElement).closest("[data-comment-id]");
+ const id = target?.getAttribute("data-comment-id");
+ if (!id) return;
+ clearTimers();
+ setHoveredId(null);
+ toggleExpandedId(id);
+ };
+
+ const activeId = expandedId ?? (compact ? null : hoveredId);
+ const active = activeId
+ ? items.find((item) => item.node.id === activeId)
+ : undefined;
+
+ return (
+ // biome-ignore lint/a11y/noStaticElementInteractions: delegation layer only; every target inside is a real button.
+ // biome-ignore lint/a11y/useKeyWithClickEvents: Enter and Space already fire click on those buttons.
+ <div
+ data-timeline-branches=""
+ className="pointer-events-none absolute inset-0"
+ onPointerOver={handlePointerOver}
+ onPointerOut={handlePointerOut}
+ onClick={handleClick}
+ >
+ {items.map((item) =>
+ item.node.kind === "single" ? (
+ <TimelineBranch
+ key={item.node.id}
+ id={item.node.id}
+ left={item.left}
+ stem={item.stem}
+ glyph={item.node.comment.type}
+ content={item.node.comment.content}
+ avatarUrl={item.node.comment.authorImage ?? null}
+ authorName={item.node.comment.authorName || "Someone"}
+ timeLabel={item.timeLabel}
+ sending={item.node.comment.sending === true}
+ delay={item.delay}
+ reduceMotion={reduceMotion}
+ morphId={`branch-${item.node.id}`}
+ />
+ ) : (
+ <TimelineBranchCluster
+ key={item.node.id}
+ id={item.node.id}
+ left={item.left}
+ stem={item.stem}
+ faces={facesOf(item.node)}
+ total={item.node.comments.length}
+ timeLabel={item.timeLabel}
+ delay={item.delay}
+ reduceMotion={reduceMotion}
+ />
+ ),
+ )}
+
+ <AnimatePresence initial={false}>
+ {active && !compact && (
+ <TimelineBranchCard
+ key={active.node.id}
+ node={active.node}
+ percent={active.percent}
+ stem={active.stem}
+ shelfHeight={shelfHeight}
+ trackWidth={trackWidth}
+ replyCounts={replyCounts}
+ reduceMotion={reduceMotion}
+ pinned={expandedId === active.node.id}
+ onSeek={onSeek}
+ onPin={setExpandedId}
+ onKeepOpen={clearTimers}
+ onClose={() => {
+ clearTimers();
+ setHoveredId(null);
+ setExpandedId(null);
+ }}
+ />
+ )}
+ </AnimatePresence>
+ </div>
+ );
+}
+
+const facesCache = new WeakMap<object, ClusterFace[]>();
+
+/** Stable per-node face list so the cluster memo actually holds. */
+function facesOf(node: Extract<BranchNode<CommentType>, { kind: "cluster" }>) {
+ const cached = facesCache.get(node);
+ if (cached) return cached;
+ const faces = node.comments.slice(0, CLUSTER_FACES).map((comment) => ({
+ id: comment.id,
+ name: comment.authorName || "Someone",
+ image: comment.authorImage ?? null,
+ }));
+ facesCache.set(node, faces);
+ return faces;
+}
diff --git a/apps/web/app/s/[videoId]/_components/timeline/TimelineChapterTicks.tsx b/apps/web/app/s/[videoId]/_components/timeline/TimelineChapterTicks.tsx
new file mode 100644
index 000000000..4bb0915dd
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/TimelineChapterTicks.tsx
@@ -0,0 +1,67 @@
+"use client";
+
+import { memo, useMemo } from "react";
+import { fractionInWindow, railLeft } from "./timeline-constants";
+
+export interface TimelineChapter {
+ title: string;
+ start: number;
+}
+
+interface TimelineChapterTicksProps {
+ chapters: readonly TimelineChapter[];
+ duration: number;
+ windowStart: number;
+ windowEnd: number;
+}
+
+/**
+ * Chapter starts as cuts in the film: hairlines through the strip with a small
+ * notch on its bottom edge. Sits in its own pointer-transparent layer above the
+ * tiles so it never steals a scrub.
+ */
+export const TimelineChapterTicks = memo(function TimelineChapterTicks({
+ chapters,
+ duration,
+ windowStart,
+ windowEnd,
+}: TimelineChapterTicksProps) {
+ const ticks = useMemo(() => {
+ if (!Number.isFinite(duration) || duration <= 0) return [];
+ if (windowEnd - windowStart <= 0) return [];
+ return chapters
+ .filter(
+ (chapter) =>
+ Number.isFinite(chapter.start) &&
+ chapter.start > 0 &&
+ chapter.start < duration &&
+ chapter.start >= windowStart &&
+ chapter.start <= windowEnd,
+ )
+ .map((chapter) => ({
+ key: `${chapter.start}-${chapter.title}`,
+ title: chapter.title,
+ left: railLeft(
+ fractionInWindow(chapter.start, windowStart, windowEnd) * 100,
+ ),
+ }));
+ }, [chapters, duration, windowStart, windowEnd]);
+
+ if (!ticks.length) return null;
+
+ return (
+ <div aria-hidden className="pointer-events-none absolute inset-0 z-[15]">
+ {ticks.map((tick) => (
+ <span
+ key={tick.key}
+ title={tick.title}
+ className="absolute inset-y-0 w-px -translate-x-1/2"
+ style={{ left: tick.left }}
+ >
+ <span className="absolute inset-0 bg-gray-12/50" />
+ <span className="absolute -bottom-1 left-1/2 h-1.5 w-[3px] -translate-x-1/2 rounded-full bg-gray-9" />
+ </span>
+ ))}
+ </div>
+ );
+});
diff --git a/apps/web/app/s/[videoId]/_components/timeline/TimelineComposer.tsx b/apps/web/app/s/[videoId]/_components/timeline/TimelineComposer.tsx
new file mode 100644
index 000000000..2bbca8b42
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/TimelineComposer.tsx
@@ -0,0 +1,280 @@
+"use client";
+
+import { Comment, type Video } from "@cap/web-domain";
+import { AnimatePresence, motion, useReducedMotion } from "motion/react";
+import { startTransition, useEffect, useState } from "react";
+import { newComment } from "@/actions/videos/new-comment";
+import { useCurrentUser } from "@/app/Layout/AuthContext";
+import type { CommentType } from "../../Share";
+import { AuthOverlay } from "../AuthOverlay";
+import { MicGlyph } from "./TimelineBranch";
+import { useTimelineActions, useTimelineState } from "./TimelineProvider";
+import {
+ CARD_WIDTH,
+ fractionInWindow,
+ RAIL_PAD_X,
+ usableWidth,
+} from "./timeline-constants";
+import { formatClock } from "./timeline-format";
+
+/**
+ * Recording kinds the composer can ask for. The timeline only expresses the
+ * intent and the time it happened at; capture, upload and the optimistic media
+ * comment all belong to whoever supplies `onRecordIntent`.
+ */
+export type RecordIntentKind = "screen" | "camera" | "voice";
+
+export interface TimelineComposerProps {
+ videoId: Video.VideoId;
+ trackWidth: number;
+ windowStart: number;
+ windowEnd: number;
+ /** Server's view of the viewer; the auth hook supplies who they are. */
+ viewerSignedIn?: boolean;
+ onOptimisticComment?: (comment: CommentType) => void;
+ onCommentSuccess?: (comment: CommentType) => void;
+ /** Overrides the locally owned auth dialog when the host has its own. */
+ onRequestAuth?: () => void;
+ /**
+ * Supplied by the recording phase. Until then the buttons stay out, but the
+ * row keeps its height so adding them later moves nothing.
+ */
+ onRecordIntent?: (kind: RecordIntentKind, t: number) => void;
+}
+
+const RECORD_OPTIONS: { kind: RecordIntentKind; label: string }[] = [
+ { kind: "screen", label: "Record screen" },
+ { kind: "camera", label: "Record camera" },
+ { kind: "voice", label: "Record voice note" },
+];
+
+const clampCenter = (percent: number, trackWidth: number): number => {
+ const x = RAIL_PAD_X + (percent / 100) * usableWidth(trackWidth);
+ const half = CARD_WIDTH / 2;
+ if (trackWidth < CARD_WIDTH + 16) return trackWidth / 2;
+ return Math.min(Math.max(x, half + 8), trackWidth - half - 8);
+};
+
+/** Anchored "comment at this exact moment" card. */
+export function TimelineComposer({
+ videoId,
+ trackWidth,
+ windowStart,
+ windowEnd,
+ viewerSignedIn = false,
+ onOptimisticComment,
+ onCommentSuccess,
+ onRequestAuth,
+ onRecordIntent,
+}: TimelineComposerProps) {
+ const { composerAnchor } = useTimelineState();
+ const { closeComposer } = useTimelineActions();
+ const user = useCurrentUser();
+ const reduceMotion = useReducedMotion() ?? false;
+ const [value, setValue] = useState("");
+ const [showAuthOverlay, setShowAuthOverlay] = useState(false);
+
+ // Both have to agree: the page was rendered for a signed-in viewer and the
+ // client knows who that is.
+ const canComment = viewerSignedIn && user !== null;
+ const anchorTime = composerAnchor?.t ?? 0;
+
+ useEffect(() => {
+ if (!composerAnchor) setValue("");
+ }, [composerAnchor]);
+
+ const requestAuth = () => {
+ if (onRequestAuth) onRequestAuth();
+ else setShowAuthOverlay(true);
+ };
+
+ const submit = async () => {
+ const content = value.trim();
+ if (!content || !user || !canComment) return;
+
+ const optimistic: CommentType = {
+ id: Comment.CommentId.make(`temp-${Date.now()}`),
+ authorId: user.id,
+ authorName: user.name,
+ authorImage: user.imageUrl,
+ content,
+ createdAt: new Date(),
+ videoId,
+ parentCommentId: Comment.CommentId.make(""),
+ type: "text",
+ timestamp: anchorTime,
+ updatedAt: new Date(),
+ mediaKey: null,
+ mediaDuration: null,
+ mediaMeta: null,
+ sending: true,
+ };
+
+ onOptimisticComment?.(optimistic);
+ setValue("");
+ closeComposer();
+
+ try {
+ const saved = await newComment({
+ content,
+ videoId,
+ authorImage: user.imageUrl,
+ parentCommentId: Comment.CommentId.make(""),
+ type: "text",
+ timestamp: anchorTime,
+ });
+ startTransition(() => {
+ onCommentSuccess?.(saved);
+ });
+ } catch (error) {
+ console.error("Error posting comment:", error);
+ }
+ };
+
+ // Clamped into the window: zooming past the anchor must slide the card to
+ // the edge it left through, not off the deck.
+ const percent = Math.min(
+ 100,
+ Math.max(0, fractionInWindow(anchorTime, windowStart, windowEnd) * 100),
+ );
+
+ return (
+ <>
+ <AnimatePresence>
+ {composerAnchor && (
+ <motion.div
+ layout
+ key="timeline-composer"
+ className="absolute bottom-full z-50 mb-2 w-72"
+ style={{
+ left: clampCenter(percent, trackWidth),
+ translateX: "-50%",
+ }}
+ initial={
+ reduceMotion ? { opacity: 0 } : { opacity: 0, scale: 0.9, y: 6 }
+ }
+ animate={
+ reduceMotion ? { opacity: 1 } : { opacity: 1, scale: 1, y: 0 }
+ }
+ exit={
+ reduceMotion
+ ? { opacity: 0, transition: { duration: 0 } }
+ : { opacity: 0, scale: 0.94, transition: { duration: 0.12 } }
+ }
+ transition={
+ reduceMotion
+ ? { duration: 0 }
+ : { type: "spring", stiffness: 420, damping: 34 }
+ }
+ onKeyDown={(event) => {
+ if (event.key === "Escape") {
+ event.stopPropagation();
+ closeComposer();
+ }
+ }}
+ >
+ <div className="new-card-style flex flex-col gap-2 p-2.5">
+ <div className="flex items-center gap-2">
+ <span className="rounded-md bg-gray-2 px-1.5 py-0.5 font-mono text-[11px] tabular-nums text-gray-11 ring-1 ring-gray-4">
+ {formatClock(anchorTime)}
+ </span>
+ <span className="text-xs text-gray-10">
+ {canComment
+ ? "Comment at this moment"
+ : "Join the conversation"}
+ </span>
+ </div>
+
+ {canComment ? (
+ <input
+ // biome-ignore lint/a11y/noAutofocus: the composer is opened by an explicit click.
+ autoFocus
+ type="text"
+ value={value}
+ maxLength={255}
+ placeholder="Add a comment"
+ aria-label={`Comment at ${formatClock(anchorTime)}`}
+ onChange={(event) => setValue(event.target.value)}
+ onBlur={() => {
+ if (!value.trim()) closeComposer();
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ void submit();
+ }
+ }}
+ className="h-8 w-full rounded-lg bg-gray-2 px-2 text-sm text-gray-12 outline-none ring-1 ring-gray-4 placeholder:text-gray-9 focus:ring-blue-9"
+ />
+ ) : (
+ <button
+ type="button"
+ onClick={requestAuth}
+ className="h-8 w-full rounded-lg bg-gray-12 text-[13px] font-medium text-white transition-opacity hover:opacity-90"
+ >
+ Sign in to comment
+ </button>
+ )}
+
+ {/* Reserved even when empty so the recording phase can drop its
+ buttons in without the card changing height. preventDefault
+ keeps the focused (empty) input from blurring on the way to a
+ button — that blur closes the composer, and the click would
+ land on an unmounted node. */}
+ <div
+ className="flex h-8 items-center gap-1"
+ onPointerDown={(event) => event.preventDefault()}
+ >
+ {onRecordIntent
+ ? RECORD_OPTIONS.map((option) => (
+ <button
+ key={option.kind}
+ type="button"
+ aria-label={option.label}
+ title={option.label}
+ onClick={() => {
+ if (!canComment) {
+ requestAuth();
+ return;
+ }
+ onRecordIntent(option.kind, anchorTime);
+ }}
+ className="flex size-8 items-center justify-center rounded-lg text-gray-11 transition-colors hover:bg-gray-2 hover:text-gray-12"
+ >
+ <RecordIcon kind={option.kind} />
+ </button>
+ ))
+ : null}
+ </div>
+ </div>
+ </motion.div>
+ )}
+ </AnimatePresence>
+
+ {!onRequestAuth && (
+ <AuthOverlay
+ isOpen={showAuthOverlay}
+ onClose={() => setShowAuthOverlay(false)}
+ />
+ )}
+ </>
+ );
+}
+
+function RecordIcon({ kind }: { kind: RecordIntentKind }) {
+ if (kind === "voice") return <MicGlyph />;
+ if (kind === "camera") {
+ return (
+ <svg viewBox="0 0 16 16" className="size-4 fill-current" aria-hidden>
+ <title>Camera</title>
+ <path d="M2.5 4A1.5 1.5 0 0 0 1 5.5v5A1.5 1.5 0 0 0 2.5 12h6A1.5 1.5 0 0 0 10 10.5v-5A1.5 1.5 0 0 0 8.5 4h-6Zm9.2 2.4 2.6-1.5c.3-.2.7 0 .7.4v5.4c0 .4-.4.6-.7.4l-2.6-1.5V6.4Z" />
+ </svg>
+ );
+ }
+ return (
+ <svg viewBox="0 0 16 16" className="size-4 fill-current" aria-hidden>
+ <title>Screen</title>
+ <path d="M2 4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V4Zm3.2 9.4h5.6a.6.6 0 1 1 0 1.2H5.2a.6.6 0 1 1 0-1.2Z" />
+ </svg>
+ );
+}
diff --git a/apps/web/app/s/[videoId]/_components/timeline/TimelineHoverGhost.tsx b/apps/web/app/s/[videoId]/_components/timeline/TimelineHoverGhost.tsx
new file mode 100644
index 000000000..ea8e99eaa
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/TimelineHoverGhost.tsx
@@ -0,0 +1,188 @@
+"use client";
+
+import { type RefObject, useEffect, useRef } from "react";
+import { useTimelineWindowRef } from "./TimelineProvider";
+import {
+ fractionInWindow,
+ GHOST_CARD_WIDTH,
+ RAIL_PAD_X,
+ timeFromClientX,
+ usableWidth,
+} from "./timeline-constants";
+import { formatClock } from "./timeline-format";
+import type { FilmstripFrames } from "./useFilmstripFrames";
+
+interface TimelineHoverGhostProps {
+ stripRef: RefObject<HTMLDivElement | null>;
+ widthRef: RefObject<number>;
+ onAddAtTime: (time: number) => void;
+ enabled: boolean;
+ /** Same tiles the filmstrip renders; the preview borrows the one under it. */
+ filmstrip: FilmstripFrames;
+ tileCount: number;
+}
+
+/**
+ * "You could put a comment here." A preview card that follows the pointer
+ * across the strip — the frame under the cursor plus an "Add at" affordance —
+ * with direct DOM writes; the only React in the loop is the card's click
+ * handler, which reads the time out of a ref.
+ *
+ * The card opens upward, briefly over the bottom of the video: standard
+ * scrub-preview behaviour, and the reason nothing up the band may clip.
+ */
+export function TimelineHoverGhost({
+ stripRef,
+ widthRef,
+ onAddAtTime,
+ enabled,
+ filmstrip,
+ tileCount,
+}: TimelineHoverGhostProps) {
+ const windowRef = useTimelineWindowRef();
+ const rootRef = useRef<HTMLDivElement | null>(null);
+ const cardRef = useRef<HTMLButtonElement | null>(null);
+ const imgWrapRef = useRef<HTMLSpanElement | null>(null);
+ const imgRef = useRef<HTMLImageElement | null>(null);
+ const chipRef = useRef<HTMLSpanElement | null>(null);
+ const timeRef = useRef(0);
+
+ // The pointer handler reads tiles out of a ref so a capture flush never
+ // re-binds the listeners.
+ const framesRef = useRef<FilmstripFrames>(filmstrip);
+ const tileCountRef = useRef(tileCount);
+ useEffect(() => {
+ framesRef.current = filmstrip;
+ tileCountRef.current = tileCount;
+ }, [filmstrip, tileCount]);
+
+ useEffect(() => {
+ const strip = stripRef.current;
+ const root = rootRef.current;
+ const card = cardRef.current;
+ const chip = chipRef.current;
+ if (!enabled || !strip || !root || !card || !chip) return;
+
+ let lastLabel = "";
+ let lastFrameSrc: string | null = null;
+ let visible = false;
+
+ const show = (next: boolean) => {
+ if (visible === next) return;
+ visible = next;
+ root.style.opacity = next ? "1" : "0";
+ };
+
+ const handleMove = (event: PointerEvent) => {
+ // Nodes and cards own their own hover affordances.
+ const target = event.target as HTMLElement | null;
+ if (target?.closest("[data-timeline-node],[data-timeline-card]")) {
+ show(false);
+ return;
+ }
+
+ const rect = strip.getBoundingClientRect();
+ const { start, end } = windowRef.current;
+ const time = timeFromClientX(event.clientX, rect, start, end);
+ timeRef.current = time;
+
+ const width = widthRef.current;
+ const fraction = Math.min(
+ 1,
+ Math.max(0, fractionInWindow(time, start, end)),
+ );
+ const x = RAIL_PAD_X + fraction * usableWidth(width);
+ root.style.transform = `translate3d(${x}px, 0, 0)`;
+
+ // Keep the card inside the band; the connector line stays on the
+ // true position, so near an edge the card slides off-centre instead
+ // of clipping.
+ const half = GHOST_CARD_WIDTH / 2;
+ const clampedX = Math.min(Math.max(x, half + 6), width - half - 6);
+ card.style.left = `${clampedX - x}px`;
+
+ const label = `Add at ${formatClock(time)}`;
+ if (label !== lastLabel) {
+ lastLabel = label;
+ chip.textContent = label;
+ }
+
+ const tiles = framesRef.current.tiles;
+ const count = tileCountRef.current;
+ const index =
+ count > 0 ? Math.min(count - 1, Math.floor(fraction * count)) : -1;
+ const src = index >= 0 ? (tiles[index] ?? null) : null;
+ if (src !== lastFrameSrc) {
+ lastFrameSrc = src;
+ const wrap = imgWrapRef.current;
+ const img = imgRef.current;
+ if (wrap && img) {
+ if (src) {
+ img.src = src;
+ wrap.style.display = "";
+ } else {
+ wrap.style.display = "none";
+ }
+ }
+ }
+
+ show(true);
+ };
+
+ const handleLeave = () => show(false);
+
+ strip.addEventListener("pointermove", handleMove);
+ strip.addEventListener("pointerleave", handleLeave);
+ return () => {
+ strip.removeEventListener("pointermove", handleMove);
+ strip.removeEventListener("pointerleave", handleLeave);
+ };
+ }, [enabled, stripRef, widthRef, windowRef]);
+
+ if (!enabled) return null;
+
+ return (
+ <div
+ ref={rootRef}
+ className="pointer-events-none absolute inset-y-0 left-0 z-30 w-0 opacity-0 transition-opacity duration-150 will-change-transform"
+ style={{ transform: "translate3d(-9999px, 0, 0)" }}
+ >
+ {/* Connector from the card down onto the strip's top edge. */}
+ <span
+ aria-hidden
+ className="absolute left-0 w-px -translate-x-1/2 bg-gray-8"
+ style={{ bottom: "100%", height: 10 }}
+ />
+ <button
+ ref={cardRef}
+ type="button"
+ tabIndex={-1}
+ onClick={() => onAddAtTime(timeRef.current)}
+ className="pointer-events-auto absolute bottom-full -translate-x-1/2 overflow-hidden rounded-xl bg-white text-left ring-1 ring-gray-5 shadow-[0_4px_16px_rgba(18,22,31,0.14)] transition-shadow hover:shadow-[0_6px_20px_rgba(18,22,31,0.18)]"
+ style={{ marginBottom: 10, width: GHOST_CARD_WIDTH }}
+ >
+ <span
+ ref={imgWrapRef}
+ aria-hidden
+ className="block h-[70px] w-full bg-gray-3"
+ style={{ display: "none" }}
+ >
+ <img
+ ref={imgRef}
+ alt=""
+ draggable={false}
+ className="size-full select-none object-cover"
+ />
+ </span>
+ <span className="flex items-center justify-center gap-1 px-3 py-1.5 text-xs font-medium text-gray-12">
+ <span aria-hidden className="text-gray-9">
+ +
+ </span>
+ <span ref={chipRef} className="whitespace-nowrap tabular-nums">
+ Add at 0:00
+ </span>
+ </span>
+ </button>
+ </div>
+ );
+}
diff --git a/apps/web/app/s/[videoId]/_components/timeline/TimelineMobileSheet.tsx b/apps/web/app/s/[videoId]/_components/timeline/TimelineMobileSheet.tsx
new file mode 100644
index 000000000..1a0b2c67a
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/TimelineMobileSheet.tsx
@@ -0,0 +1,130 @@
+"use client";
+
+import { AnimatePresence, motion, useReducedMotion } from "motion/react";
+import { SignedImageUrl } from "@/components/SignedImageUrl";
+import type { CommentType } from "../../Share";
+import { MediaCommentBody } from "../media-comment/MediaCommentBody";
+import { isMediaComment } from "../media-comment/media-comment-types";
+import { formatTimeAgo } from "../tabs/Activity/utils";
+import { useTimelineActions, useTimelineState } from "./TimelineProvider";
+import { formatClock } from "./timeline-format";
+import { type BranchNode, branchComments } from "./timeline-layout";
+
+interface TimelineMobileSheetProps {
+ branches: readonly BranchNode<CommentType>[];
+ onSeek: (time: number) => void;
+}
+
+/**
+ * Touch replacement for the hover card. A hover card on a phone is a card that
+ * never opens, so below `lg` a tap raises a dismissible bottom sheet instead.
+ */
+export function TimelineMobileSheet({
+ branches,
+ onSeek,
+}: TimelineMobileSheetProps) {
+ const { expandedId } = useTimelineState();
+ const { setExpandedId } = useTimelineActions();
+ const reduceMotion = useReducedMotion() ?? false;
+
+ const node = expandedId
+ ? branches.find((branch) => branch.id === expandedId)
+ : undefined;
+ const comments = node ? branchComments(node) : [];
+ const close = () => setExpandedId(null);
+
+ return (
+ <AnimatePresence>
+ {node && (
+ <motion.div
+ key="timeline-sheet"
+ className="fixed inset-0 z-[60] flex items-end lg:hidden"
+ initial={{ opacity: 0 }}
+ animate={{ opacity: 1 }}
+ exit={{ opacity: 0 }}
+ transition={{ duration: reduceMotion ? 0 : 0.16 }}
+ >
+ <button
+ type="button"
+ aria-label="Close comments"
+ onClick={close}
+ className="absolute inset-0 bg-black/30"
+ />
+
+ <motion.div
+ role="dialog"
+ aria-label="Comments at this point"
+ className="relative w-full rounded-t-2xl border-t border-gray-5 bg-white pb-[env(safe-area-inset-bottom)]"
+ initial={reduceMotion ? { opacity: 0 } : { y: "100%" }}
+ animate={reduceMotion ? { opacity: 1 } : { y: 0 }}
+ exit={reduceMotion ? { opacity: 0 } : { y: "100%" }}
+ transition={
+ reduceMotion
+ ? { duration: 0 }
+ : { type: "spring", stiffness: 420, damping: 36 }
+ }
+ drag={reduceMotion ? false : "y"}
+ dragConstraints={{ top: 0, bottom: 0 }}
+ dragElastic={{ top: 0, bottom: 0.4 }}
+ onDragEnd={(_event, info) => {
+ if (info.offset.y > 80 || info.velocity.y > 500) close();
+ }}
+ >
+ <div className="flex justify-center py-2">
+ <span className="h-1 w-9 rounded-full bg-gray-5" />
+ </div>
+
+ <div className="max-h-[60vh] overflow-y-auto px-4 pb-4">
+ <span className="block pb-2 text-[11px] font-medium uppercase tracking-wide text-gray-9">
+ {formatClock(node.t)}
+ </span>
+ <ul className="flex flex-col gap-3">
+ {comments.map((comment) => (
+ <li key={comment.id} className="flex gap-2">
+ <span className="block overflow-hidden rounded-full size-6 shrink-0">
+ <SignedImageUrl
+ image={comment.authorImage ?? null}
+ name={comment.authorName || "Someone"}
+ className="size-full"
+ letterClass="text-[10px] font-medium"
+ />
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <span className="truncate text-[13px] font-medium text-gray-12">
+ {comment.authorName || "Someone"}
+ </span>
+ <span className="text-[11px] text-gray-9">
+ {formatTimeAgo(new Date(comment.createdAt))}
+ </span>
+ <button
+ type="button"
+ onClick={() => {
+ onSeek(comment.timestamp ?? node.t);
+ close();
+ }}
+ className="ml-auto rounded-md bg-gray-2 px-1.5 py-0.5 font-mono text-[11px] tabular-nums text-gray-11 ring-1 ring-gray-4"
+ >
+ {formatClock(comment.timestamp ?? node.t)}
+ </button>
+ </div>
+ {isMediaComment(comment) ? (
+ <div className="pt-1">
+ <MediaCommentBody comment={comment} />
+ </div>
+ ) : (
+ <p className="whitespace-pre-wrap break-words pt-0.5 text-sm text-gray-11">
+ {comment.content}
+ </p>
+ )}
+ </div>
+ </li>
+ ))}
+ </ul>
+ </div>
+ </motion.div>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ );
+}
diff --git a/apps/web/app/s/[videoId]/_components/timeline/TimelinePlayhead.tsx b/apps/web/app/s/[videoId]/_components/timeline/TimelinePlayhead.tsx
new file mode 100644
index 000000000..af14a6080
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/TimelinePlayhead.tsx
@@ -0,0 +1,69 @@
+"use client";
+
+import { type RefObject, useEffect, useRef } from "react";
+import { usePlayback } from "../playback/PlaybackContext";
+import { useTimelineWindowRef } from "./TimelineProvider";
+import {
+ fractionInWindow,
+ RAIL_PAD_X,
+ usableWidth,
+} from "./timeline-constants";
+
+interface TimelinePlayheadProps {
+ /** Live band width, kept by the view's ResizeObserver. */
+ widthRef: RefObject<number>;
+}
+
+/**
+ * Rendered exactly once and then never again: the subscriber writes a transform
+ * straight to the DOM, so a playing video costs zero React work here — including
+ * when a zoom pushes the playhead out of the window and the needle has to
+ * disappear. Deliberately unlabelled: the transport clock is the deck's single
+ * time readout, and the needle only marks where it is.
+ */
+export function TimelinePlayhead({ widthRef }: TimelinePlayheadProps) {
+ const playback = usePlayback();
+ const windowRef = useTimelineWindowRef();
+ const rootRef = useRef<HTMLDivElement | null>(null);
+
+ useEffect(() => {
+ const root = rootRef.current;
+ if (!root) return;
+
+ let visible = true;
+
+ return playback.subscribe((time) => {
+ const { start, end } = windowRef.current;
+ const fraction = fractionInWindow(time, start, end);
+ const inside = fraction >= 0 && fraction <= 1;
+ if (inside !== visible) {
+ visible = inside;
+ root.style.opacity = inside ? "1" : "0";
+ }
+ if (!inside) return;
+ const width = widthRef.current;
+ const x = RAIL_PAD_X + fraction * usableWidth(width);
+ // The dot is 12px wide and centred; with the rail running edge to edge
+ // an unclamped 0%/100% would hang it half outside the card (the grid
+ // has no clip — the shelf's cards must escape). Same lean the branch
+ // stems make at the extremes.
+ const clamped = width > 12 ? Math.min(Math.max(x, 6), width - 6) : x;
+ root.style.transform = `translate3d(${clamped}px, 0, 0)`;
+ });
+ }, [playback, widthRef, windowRef]);
+
+ return (
+ <div
+ ref={rootRef}
+ aria-hidden
+ className="pointer-events-none absolute inset-y-0 left-0 z-20 w-0 will-change-transform"
+ style={{ transform: "translate3d(0, 0, 0)" }}
+ >
+ {/* Needle through the filmstrip: dark core, white halo so it reads on
+ any frame underneath. */}
+ <div className="absolute inset-y-0 left-0 w-[3px] -translate-x-1/2 rounded-full bg-gray-12 shadow-[0_0_0_1px_rgba(255,255,255,0.85)]" />
+ {/* Grab handle straddling the strip's bottom edge, facing the deck. */}
+ <div className="absolute bottom-0 left-0 size-3 -translate-x-1/2 translate-y-1/2 rounded-full bg-gray-12 ring-2 ring-white shadow-[0_1px_3px_rgba(18,22,31,0.25)]" />
+ </div>
+ );
+}
diff --git a/apps/web/app/s/[videoId]/_components/timeline/TimelineProvider.tsx b/apps/web/app/s/[videoId]/_components/timeline/TimelineProvider.tsx
new file mode 100644
index 000000000..8e47e23a1
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/TimelineProvider.tsx
@@ -0,0 +1,279 @@
+"use client";
+
+import {
+ createContext,
+ type ReactNode,
+ type RefObject,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ useSyncExternalStore,
+} from "react";
+import {
+ clampWindow,
+ fullWindow,
+ isFullWindow,
+ panWindowBy,
+ type TimelineWindow,
+ zoomWindowAt,
+} from "./timeline-window";
+
+/** Where the composer is anchored on the rail. */
+export interface ComposerAnchor {
+ t: number;
+}
+
+interface TimelineState {
+ hoveredId: string | null;
+ /** Pinned card; survives pointer-out until dismissed. */
+ expandedId: string | null;
+ composerAnchor: ComposerAnchor | null;
+}
+
+interface TimelineActions {
+ setHoveredId: (id: string | null) => void;
+ setExpandedId: (id: string | null) => void;
+ toggleExpandedId: (id: string) => void;
+ openComposer: (t: number) => void;
+ closeComposer: () => void;
+ /** Above 1 zooms in. `focusT` keeps its place under the pointer. */
+ zoomAtTime: (factor: number, focusT: number) => void;
+ panBy: (deltaSeconds: number) => void;
+ resetZoom: () => void;
+ setWindow: (window: TimelineWindow) => void;
+}
+
+/** Viewport facts the band branches on. Changes are rare. */
+interface TimelineEnv {
+ /** Below `lg`: nodes open a bottom sheet instead of a hover card. */
+ compact: boolean;
+ /** Real hover pointer; gates the hover card and the "add here" ghost. */
+ hasHover: boolean;
+}
+
+interface TimelineWindowValue extends TimelineWindow {
+ zoomed: boolean;
+}
+
+const StateContext = createContext<TimelineState | null>(null);
+const ActionsContext = createContext<TimelineActions | null>(null);
+const EnvContext = createContext<TimelineEnv | null>(null);
+const WindowContext = createContext<TimelineWindowValue | null>(null);
+const WindowRefContext = createContext<RefObject<TimelineWindow> | null>(null);
+
+interface TimelineProviderProps extends TimelineEnv {
+ /** Latest known video duration; the window is always a slice of it. */
+ duration: number;
+ children: ReactNode;
+}
+
+/**
+ * Timeline-local UI state, split so the pieces that only dispatch (nodes, rail,
+ * ghost) never re-render when the pieces that read (cards, sheet, composer)
+ * change.
+ *
+ * The zoom window lives here in two forms: a context value for the components
+ * that re-lay out when it moves, and a ref mirror written in the same tick, so
+ * playback-store subscribers can turn a time into an x position without
+ * subscribing to React at all.
+ */
+export function TimelineProvider({
+ compact,
+ hasHover,
+ duration,
+ children,
+}: TimelineProviderProps) {
+ const [hoveredId, setHoveredId] = useState<string | null>(null);
+ const [expandedId, setExpandedId] = useState<string | null>(null);
+ const [composerAnchor, setComposerAnchor] = useState<ComposerAnchor | null>(
+ null,
+ );
+
+ // null means "the whole video", which is not the same as [0, duration]
+ // before the duration is known.
+ const [zoomWindow, setZoomWindow] = useState<TimelineWindow | null>(null);
+ const durationRef = useRef(duration);
+ durationRef.current = duration;
+
+ const windowRef = useRef<TimelineWindow>(fullWindow(duration));
+ const pendingRef = useRef<TimelineWindow | null>(null);
+ const hasPendingRef = useRef(false);
+ const frameRef = useRef(0);
+
+ // Gestures fire far faster than React should re-render, so the ref moves
+ // immediately and the state catches up once per frame.
+ const applyWindow = useCallback((next: TimelineWindow | null) => {
+ windowRef.current = next ?? fullWindow(durationRef.current);
+ pendingRef.current = next;
+ hasPendingRef.current = true;
+ if (frameRef.current !== 0) return;
+ if (typeof requestAnimationFrame !== "function") {
+ hasPendingRef.current = false;
+ setZoomWindow(next);
+ return;
+ }
+ frameRef.current = requestAnimationFrame(() => {
+ frameRef.current = 0;
+ if (!hasPendingRef.current) return;
+ hasPendingRef.current = false;
+ setZoomWindow(pendingRef.current);
+ });
+ }, []);
+
+ useEffect(
+ () => () => {
+ if (frameRef.current !== 0) cancelAnimationFrame(frameRef.current);
+ },
+ [],
+ );
+
+ const resolved = useMemo<TimelineWindowValue>(() => {
+ const window = zoomWindow
+ ? clampWindow(zoomWindow, duration)
+ : fullWindow(duration);
+ return { ...window, zoomed: !isFullWindow(window, duration) };
+ }, [zoomWindow, duration]);
+
+ // Duration arrives after the first paint and a full window has to grow with
+ // it. The gesture path writes the ref itself, so this only covers that case.
+ useEffect(() => {
+ windowRef.current = { start: resolved.start, end: resolved.end };
+ }, [resolved]);
+
+ const toggleExpandedId = useCallback((id: string) => {
+ setExpandedId((prev) => (prev === id ? null : id));
+ }, []);
+
+ const openComposer = useCallback((t: number) => {
+ setExpandedId(null);
+ setComposerAnchor({ t });
+ }, []);
+
+ const closeComposer = useCallback(() => setComposerAnchor(null), []);
+
+ const zoomAtTime = useCallback(
+ (factor: number, focusT: number) => {
+ const total = durationRef.current;
+ const next = zoomWindowAt(windowRef.current, factor, focusT, total);
+ applyWindow(isFullWindow(next, total) ? null : next);
+ },
+ [applyWindow],
+ );
+
+ const panBy = useCallback(
+ (deltaSeconds: number) => {
+ const total = durationRef.current;
+ if (isFullWindow(windowRef.current, total)) return;
+ applyWindow(panWindowBy(windowRef.current, deltaSeconds, total));
+ },
+ [applyWindow],
+ );
+
+ const resetZoom = useCallback(() => applyWindow(null), [applyWindow]);
+
+ const setWindow = useCallback(
+ (next: TimelineWindow) => {
+ const total = durationRef.current;
+ const clamped = clampWindow(next, total);
+ applyWindow(isFullWindow(clamped, total) ? null : clamped);
+ },
+ [applyWindow],
+ );
+
+ const actions = useMemo<TimelineActions>(
+ () => ({
+ setHoveredId,
+ setExpandedId,
+ toggleExpandedId,
+ openComposer,
+ closeComposer,
+ zoomAtTime,
+ panBy,
+ resetZoom,
+ setWindow,
+ }),
+ [
+ toggleExpandedId,
+ openComposer,
+ closeComposer,
+ zoomAtTime,
+ panBy,
+ resetZoom,
+ setWindow,
+ ],
+ );
+
+ const state = useMemo<TimelineState>(
+ () => ({ hoveredId, expandedId, composerAnchor }),
+ [hoveredId, expandedId, composerAnchor],
+ );
+
+ const env = useMemo<TimelineEnv>(
+ () => ({ compact, hasHover }),
+ [compact, hasHover],
+ );
+
+ return (
+ <EnvContext.Provider value={env}>
+ <ActionsContext.Provider value={actions}>
+ <WindowRefContext.Provider value={windowRef}>
+ <WindowContext.Provider value={resolved}>
+ <StateContext.Provider value={state}>
+ {children}
+ </StateContext.Provider>
+ </WindowContext.Provider>
+ </WindowRefContext.Provider>
+ </ActionsContext.Provider>
+ </EnvContext.Provider>
+ );
+}
+
+const required = <T,>(value: T | null, name: string): T => {
+ if (!value)
+ throw new Error(`${name} must be used inside a <TimelineProvider>`);
+ return value;
+};
+
+export const useTimelineState = () =>
+ required(useContext(StateContext), "useTimelineState");
+
+export const useTimelineActions = () =>
+ required(useContext(ActionsContext), "useTimelineActions");
+
+export const useTimelineEnv = () =>
+ required(useContext(EnvContext), "useTimelineEnv");
+
+/** Re-renders when the window moves. For anything that re-lays out. */
+export const useTimelineWindow = () =>
+ required(useContext(WindowContext), "useTimelineWindow");
+
+/** Never re-renders. For playback subscribers writing straight to the DOM. */
+export const useTimelineWindowRef = () =>
+ required(useContext(WindowRefContext), "useTimelineWindowRef");
+
+const noopSubscribe = () => () => {};
+
+/** `matchMedia` as an external store, so it never renders twice on mount. */
+export function useMediaQuery(query: string, serverValue = false): boolean {
+ const subscribe = useMemo(() => {
+ if (typeof window === "undefined" || !window.matchMedia)
+ return noopSubscribe;
+ return (onChange: () => void) => {
+ const list = window.matchMedia(query);
+ list.addEventListener("change", onChange);
+ return () => list.removeEventListener("change", onChange);
+ };
+ }, [query]);
+
+ const getSnapshot = useCallback(() => {
+ if (typeof window === "undefined" || !window.matchMedia) return serverValue;
+ return window.matchMedia(query).matches;
+ }, [query, serverValue]);
+
+ const getServerSnapshot = useCallback(() => serverValue, [serverValue]);
+
+ return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
+}
diff --git a/apps/web/app/s/[videoId]/_components/timeline/TimelineRail.tsx b/apps/web/app/s/[videoId]/_components/timeline/TimelineRail.tsx
new file mode 100644
index 000000000..f5cd636c9
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/TimelineRail.tsx
@@ -0,0 +1,316 @@
+"use client";
+
+import clsx from "clsx";
+import { memo, type RefObject, useCallback, useEffect, useRef } from "react";
+import { usePlayback } from "../playback/PlaybackContext";
+import { useTimelineActions, useTimelineWindowRef } from "./TimelineProvider";
+import { TimelineWaveform } from "./TimelineWaveform";
+import {
+ fractionInWindow,
+ timeFromClientX,
+ usableWidth,
+} from "./timeline-constants";
+import { formatClock } from "./timeline-format";
+import type { FilmstripFrames } from "./useFilmstripFrames";
+
+interface TimelineRailProps {
+ /** Latest known duration; only used for the ARIA range. */
+ duration: number;
+ railRef: RefObject<HTMLDivElement | null>;
+ filmstrip: FilmstripFrames;
+ /** How many tiles the strip renders; frames may be sparser than this. */
+ tileCount: number;
+ envelope: Float32Array | null;
+ windowStart: number;
+ windowEnd: number;
+}
+
+/**
+ * The strip: a filmstrip of preview frames with the audio drawn over it, owning
+ * pointer hit-testing for seeking. Playback progress is a subtle wash plus an
+ * underline, both driven by one `--p` custom property written straight to the
+ * DOM by a playback-store subscriber — the tiles never re-render while the
+ * video plays.
+ */
+export function TimelineRail({
+ duration,
+ railRef,
+ filmstrip,
+ tileCount,
+ envelope,
+ windowStart,
+ windowEnd,
+}: TimelineRailProps) {
+ const playback = usePlayback();
+ const windowRef = useTimelineWindowRef();
+ const { zoomAtTime, panBy } = useTimelineActions();
+ const progressRef = useRef<HTMLDivElement | null>(null);
+ const pendingSeekRef = useRef<number | null>(null);
+ const seekFrameRef = useRef(0);
+
+ // One finger on touch: a tap seeks on release, a 6px drag starts scrubbing.
+ // Two fingers: pinch zooms around the midpoint and the midpoint's travel
+ // pans — the only way to pan a zoomed window on touch, since one finger is
+ // the scrubber. Mouse and pen keep the immediate seek-on-down behaviour.
+ // "spent" is a pinch that lost a finger: the survivor must not scrub.
+ const pointersRef = useRef(new Map<number, { x: number; y: number }>());
+ const modeRef = useRef<"idle" | "pending" | "scrub" | "pinch" | "spent">(
+ "idle",
+ );
+ const touchDownRef = useRef<{ x: number; time: number } | null>(null);
+ const pinchRef = useRef<{ dist: number; midX: number } | null>(null);
+
+ useEffect(() => {
+ const progress = progressRef.current;
+ const rail = railRef.current;
+ if (!progress) return;
+
+ let lastSecond = -1;
+
+ return playback.subscribe((time) => {
+ const { start, end } = windowRef.current;
+ const fraction = Math.min(
+ 1,
+ Math.max(0, fractionInWindow(time, start, end)),
+ );
+ progress.style.setProperty("--p", `${fraction * 100}%`);
+
+ if (!rail) return;
+ const second = Math.round(time);
+ if (second === lastSecond) return;
+ lastSecond = second;
+ rail.setAttribute("aria-valuenow", String(second));
+ rail.setAttribute("aria-valuetext", formatClock(time));
+ });
+ }, [playback, railRef, windowRef]);
+
+ // Scrubbing lands at most one seek per frame; the media element is slow to
+ // honour `currentTime` and a pointermove burst would queue them all up.
+ const scheduleSeek = useCallback(
+ (time: number) => {
+ pendingSeekRef.current = time;
+ if (seekFrameRef.current !== 0) return;
+ seekFrameRef.current = requestAnimationFrame(() => {
+ seekFrameRef.current = 0;
+ const next = pendingSeekRef.current;
+ pendingSeekRef.current = null;
+ if (next !== null) playback.seek(next);
+ });
+ },
+ [playback],
+ );
+
+ useEffect(
+ () => () => {
+ if (seekFrameRef.current !== 0)
+ cancelAnimationFrame(seekFrameRef.current);
+ },
+ [],
+ );
+
+ const timeAt = useCallback(
+ (clientX: number) => {
+ const rail = railRef.current;
+ if (!rail) return 0;
+ const { start, end } = windowRef.current;
+ // The rail spans the full band; timeFromClientX subtracts the pad.
+ return timeFromClientX(clientX, rail.getBoundingClientRect(), start, end);
+ },
+ [railRef, windowRef],
+ );
+
+ return (
+ <div
+ ref={railRef}
+ role="slider"
+ tabIndex={0}
+ aria-label="Seek"
+ aria-orientation="horizontal"
+ aria-valuemin={0}
+ aria-valuemax={Math.max(0, Math.round(duration))}
+ aria-valuenow={0}
+ data-timeline-rail=""
+ className="absolute inset-0 z-10 cursor-pointer touch-none focus-visible:outline-none group"
+ onPointerDown={(event) => {
+ if (event.button !== 0) return;
+ event.currentTarget.setPointerCapture(event.pointerId);
+ pointersRef.current.set(event.pointerId, {
+ x: event.clientX,
+ y: event.clientY,
+ });
+ if (pointersRef.current.size === 2) {
+ // Second finger: whatever was in flight becomes a pinch.
+ const [a, b] = [...pointersRef.current.values()];
+ if (a && b) {
+ pinchRef.current = {
+ dist: Math.max(20, Math.hypot(b.x - a.x, b.y - a.y)),
+ midX: (a.x + b.x) / 2,
+ };
+ modeRef.current = "pinch";
+ touchDownRef.current = null;
+ pendingSeekRef.current = null;
+ }
+ return;
+ }
+ if (pointersRef.current.size > 2) return;
+ if (event.pointerType === "touch") {
+ // No seek yet: this may become a pinch or stay a tap.
+ modeRef.current = "pending";
+ touchDownRef.current = {
+ x: event.clientX,
+ time: timeAt(event.clientX),
+ };
+ } else {
+ modeRef.current = "scrub";
+ playback.seek(timeAt(event.clientX));
+ }
+ }}
+ onPointerMove={(event) => {
+ const tracked = pointersRef.current.get(event.pointerId);
+ if (tracked) {
+ tracked.x = event.clientX;
+ tracked.y = event.clientY;
+ }
+ const mode = modeRef.current;
+ if (mode === "pinch") {
+ const prev = pinchRef.current;
+ const rail = railRef.current;
+ if (!prev || !rail || pointersRef.current.size < 2) return;
+ const [a, b] = [...pointersRef.current.values()];
+ if (!a || !b) return;
+ const dist = Math.max(20, Math.hypot(b.x - a.x, b.y - a.y));
+ const midX = (a.x + b.x) / 2;
+ const rect = rail.getBoundingClientRect();
+ const factor = dist / prev.dist;
+ if (Math.abs(factor - 1) > 0.002) {
+ const { start, end } = windowRef.current;
+ zoomAtTime(factor, timeFromClientX(prev.midX, rect, start, end));
+ }
+ const dx = midX - prev.midX;
+ const usable = usableWidth(rect.width);
+ if (dx !== 0 && usable > 0) {
+ // windowRef is written synchronously by zoomAtTime, so the pan
+ // reads the post-zoom span.
+ const { start, end } = windowRef.current;
+ panBy((-dx / usable) * (end - start));
+ }
+ pinchRef.current = { dist, midX };
+ return;
+ }
+ if (mode === "pending") {
+ const down = touchDownRef.current;
+ if (down && Math.abs(event.clientX - down.x) > 6) {
+ modeRef.current = "scrub";
+ touchDownRef.current = null;
+ playback.seek(timeAt(event.clientX));
+ }
+ return;
+ }
+ if (mode === "scrub") scheduleSeek(timeAt(event.clientX));
+ }}
+ onPointerUp={(event) => {
+ pointersRef.current.delete(event.pointerId);
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) {
+ event.currentTarget.releasePointerCapture(event.pointerId);
+ }
+ const mode = modeRef.current;
+ if (mode === "pinch") {
+ pinchRef.current = null;
+ modeRef.current = pointersRef.current.size > 0 ? "spent" : "idle";
+ return;
+ }
+ if (mode === "pending" && touchDownRef.current) {
+ playback.seek(touchDownRef.current.time);
+ }
+ touchDownRef.current = null;
+ if (pointersRef.current.size === 0) modeRef.current = "idle";
+ }}
+ onPointerCancel={(event) => {
+ pointersRef.current.delete(event.pointerId);
+ pinchRef.current = null;
+ touchDownRef.current = null;
+ if (pointersRef.current.size === 0) modeRef.current = "idle";
+ }}
+ >
+ <div
+ ref={progressRef}
+ // Edge to edge and square: the strip is the top of the card's light
+ // chrome, so its base is a quiet gray the frames land on and the dark
+ // waveform reads over even before any frame has been captured.
+ // Focus feedback is an inset ring, corners having gone.
+ className="relative h-full overflow-hidden bg-gray-3 group-focus-visible:ring-2 group-focus-visible:ring-inset group-focus-visible:ring-blue-9"
+ >
+ <FilmstripTiles tileCount={tileCount} tiles={filmstrip.tiles} />
+
+ <TimelineWaveform
+ envelope={envelope}
+ start={windowStart}
+ end={windowEnd}
+ duration={duration}
+ />
+
+ {/* Played wash: barely-there shade so progress reads on the film
+ without hiding it. Driven by --p, no React involved. */}
+ <div
+ aria-hidden
+ className="absolute inset-0 bg-gray-12/10"
+ style={{ clipPath: "inset(0 calc(100% - var(--p, 0%)) 0 0)" }}
+ />
+ {/* Progress underline along the strip's bottom edge. */}
+ <div
+ aria-hidden
+ className="absolute inset-x-0 bottom-0 h-[3px] rounded-full bg-gray-12"
+ style={{ clipPath: "inset(0 calc(100% - var(--p, 0%)) 0 0)" }}
+ />
+ </div>
+ </div>
+ );
+}
+
+/**
+ * The tiles. Memoised on the tiles array, which only changes on a capture flush
+ * or a window move — playback and hover cost this component nothing.
+ *
+ * Deliberately washed out: the film is texture here, and the waveform drawn over
+ * it is the layer meant to be read. A white veil rather than a dark one, so the
+ * strip stays part of the card's light chrome whatever the footage looks like.
+ */
+const FilmstripTiles = memo(function FilmstripTiles({
+ tileCount,
+ tiles,
+}: {
+ tileCount: number;
+ tiles: readonly (string | null)[];
+}) {
+ return (
+ <>
+ <div aria-hidden className="absolute inset-0 flex">
+ {Array.from({ length: tileCount }, (_, index) => {
+ const src = tiles[index] ?? null;
+ return (
+ <div
+ key={index}
+ className={clsx(
+ "relative h-full min-w-0 flex-1",
+ !src && "animate-pulse bg-gray-4",
+ )}
+ >
+ {src && (
+ <img
+ src={src}
+ alt=""
+ draggable={false}
+ className="absolute inset-0 size-full select-none object-cover opacity-0 brightness-105 saturate-[.9] transition-opacity duration-300"
+ onLoad={(event) => {
+ event.currentTarget.style.opacity = "1";
+ }}
+ />
+ )}
+ </div>
+ );
+ })}
+ </div>
+ <div aria-hidden className="absolute inset-0 bg-white/45" />
+ </>
+ );
+});
diff --git a/apps/web/app/s/[videoId]/_components/timeline/TimelineRuler.tsx b/apps/web/app/s/[videoId]/_components/timeline/TimelineRuler.tsx
new file mode 100644
index 000000000..3b6f1170e
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/TimelineRuler.tsx
@@ -0,0 +1,66 @@
+"use client";
+
+import { memo, useMemo } from "react";
+import { fractionInWindow, railLeft } from "./timeline-constants";
+
+/** Tick intervals, coarsest last. The first one under the cap wins. */
+const TICK_STEPS = [1, 5, 15, 30, 60, 300, 600, 1800, 3600];
+const MAX_TICKS = 12;
+
+const pickStep = (span: number): number => {
+ for (const step of TICK_STEPS) {
+ if (span / step <= MAX_TICKS) return step;
+ }
+ return TICK_STEPS[TICK_STEPS.length - 1] as number;
+};
+
+interface TimelineRulerProps {
+ windowStart: number;
+ windowEnd: number;
+}
+
+/**
+ * The anchor line: a hairline across the top of the comments surface with
+ * interval ticks on it, so branch stems have something to hang from and the
+ * strip above reads as a timeline rather than a bare bar.
+ *
+ * Unlabelled by design — the transport clock is the deck's only time readout.
+ * Memoised on the window alone: the ruler has no idea the video is playing and
+ * must never learn.
+ */
+export const TimelineRuler = memo(function TimelineRuler({
+ windowStart,
+ windowEnd,
+}: TimelineRulerProps) {
+ const ticks = useMemo(() => {
+ const span = windowEnd - windowStart;
+ if (!Number.isFinite(span) || span <= 0) return [];
+ const step = pickStep(span);
+ const marks: { t: number; left: string }[] = [];
+ const first = Math.ceil(windowStart / step) * step;
+ for (let t = first; t < windowEnd; t += step) {
+ if (t <= 0) continue;
+ marks.push({
+ t,
+ left: railLeft(fractionInWindow(t, windowStart, windowEnd) * 100),
+ });
+ }
+ return marks;
+ }, [windowStart, windowEnd]);
+
+ return (
+ <div
+ aria-hidden
+ className="pointer-events-none absolute inset-x-0 top-0 h-2"
+ >
+ <span className="absolute inset-x-0 top-0 h-px bg-gray-5" />
+ {ticks.map((tick) => (
+ <span
+ key={tick.t}
+ className="absolute top-0 h-1.5 w-px -translate-x-1/2 bg-gray-6"
+ style={{ left: tick.left }}
+ />
+ ))}
+ </div>
+ );
+});
diff --git a/apps/web/app/s/[videoId]/_components/timeline/TimelineSkeleton.tsx b/apps/web/app/s/[videoId]/_components/timeline/TimelineSkeleton.tsx
new file mode 100644
index 000000000..1b092152a
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/TimelineSkeleton.tsx
@@ -0,0 +1,19 @@
+/**
+ * Lives in its own module so `Share.tsx` can render it as the Suspense
+ * fallback without statically importing `TimelineView`, which would pull the
+ * timeline back into the main chunk and defeat the `next/dynamic` split.
+ *
+ * Heights and chrome track the band in `TimelineView`: filmstrip ghost, then
+ * the control-bar row closing the card. The comments shelf only exists when
+ * there are branches, so the skeleton shows the collapsed shape.
+ */
+export function TimelineSkeleton() {
+ return (
+ <div className="flex w-full flex-col">
+ <div className="h-11 shrink-0 animate-pulse bg-gray-3 lg:h-16" />
+ <div className="flex h-14 shrink-0 items-center rounded-b-xl border-t border-gray-4 bg-white pl-4">
+ <div className="size-8 rounded-full bg-gray-4" />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/app/s/[videoId]/_components/timeline/TimelineView.tsx b/apps/web/app/s/[videoId]/_components/timeline/TimelineView.tsx
new file mode 100644
index 000000000..bbd40bcd2
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/TimelineView.tsx
@@ -0,0 +1,567 @@
+"use client";
+
+import type { Video } from "@cap/web-domain";
+import { motion, useReducedMotion } from "motion/react";
+import dynamic from "next/dynamic";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import type { CommentType } from "../../Share";
+import { usePlayback } from "../playback/PlaybackContext";
+import { filmstripTileCount } from "./filmstrip-math";
+import { TimelineActiveCue } from "./TimelineActiveCue";
+import { TimelineBranches } from "./TimelineBranches";
+import {
+ type TimelineChapter,
+ TimelineChapterTicks,
+} from "./TimelineChapterTicks";
+import { type RecordIntentKind, TimelineComposer } from "./TimelineComposer";
+import { TimelineHoverGhost } from "./TimelineHoverGhost";
+import { TimelineMobileSheet } from "./TimelineMobileSheet";
+import { TimelinePlayhead } from "./TimelinePlayhead";
+import {
+ TimelineProvider,
+ useMediaQuery,
+ useTimelineActions,
+ useTimelineWindow,
+ useTimelineWindowRef,
+} from "./TimelineProvider";
+import { TimelineRail } from "./TimelineRail";
+import { TimelineRuler } from "./TimelineRuler";
+import { TimelineZoomControls } from "./TimelineZoomControls";
+import {
+ KEYBOARD_SEEK_STEP,
+ LANE_STEM,
+ LANE_STEM_MOBILE,
+ MIN_NODE_GAP,
+ MIN_NODE_GAP_MOBILE,
+ NODE_SIZE,
+ quantizeWidth,
+ stripHeight,
+ timeFromClientX,
+ usableWidth,
+} from "./timeline-constants";
+import { layoutBranches } from "./timeline-layout";
+import { followWindow, isFullWindow } from "./timeline-window";
+import { type FilmstripSource, useFilmstripFrames } from "./useFilmstripFrames";
+import { useTimelineWaveform } from "./useTimelineWaveform";
+
+export { TimelineSkeleton } from "./TimelineSkeleton";
+
+// Capture + upload code loads only when someone actually presses record.
+const RecorderSurface = dynamic(() => import("./recording/RecorderSurface"), {
+ ssr: false,
+});
+
+const EASE: [number, number, number, number] = [0.32, 0.72, 0, 1];
+
+const EMPTY_CHAPTERS: TimelineChapter[] = [];
+
+/** Wheel deltas are device-dependent; this keeps a notch from jumping a decade. */
+const WHEEL_ZOOM_RATE = 0.012;
+const WHEEL_ZOOM_MAX = 1.6;
+
+export interface TimelineViewProps {
+ comments: CommentType[];
+ videoId: Video.VideoId;
+ chapters?: { title: string; start: number }[];
+ /** Drives the strip's waveform: a transcript when there is one. */
+ transcriptionStatus?: string | null;
+ /**
+ * Where the filmstrip's preview frames come from. Omitted (e.g. while an
+ * upload is still in flight) the strip falls back to a quiet placeholder.
+ */
+ filmstripSource?: FilmstripSource | null;
+ onOptimisticComment?: (comment: CommentType) => void;
+ onCommentSuccess?: (comment: CommentType) => void;
+ canRecordMedia?: boolean;
+ viewerSignedIn?: boolean;
+ /** Owner/org viewer setting: emoji reactions are hidden when set. */
+ disableReactions?: boolean;
+ /**
+ * Fires when a recording flow starts/ends so the host can lock the view
+ * toggle (leaving the timeline would discard the take).
+ */
+ onRecordingActiveChange?: (active: boolean) => void;
+ /**
+ * Supplied by the recording phase. Until it arrives the composer hides its
+ * capture buttons but keeps the row, so wiring this up later moves nothing.
+ */
+ onRecordIntent?: (kind: RecordIntentKind, t: number) => void;
+ /**
+ * Hands the host the element the video player's own control bar portals
+ * into: the row closing the bottom of the card. The deck has no transport
+ * of its own — one player, one set of controls.
+ */
+ onControlsSlotChange?: (el: HTMLElement | null) => void;
+}
+
+/**
+ * The timeline band under the video: the filmstrip fixed to the video's bottom
+ * edge, the transport under it, and comments branching down off the ruler.
+ *
+ * Read-only with respect to the player — it drives the shared playback store
+ * rather than owning a video element — and deliberately render-quiet. While the
+ * video plays only `TimelineActiveCue` and `TimelineTransport` re-render; the
+ * playhead, the rail fill and the hover ghost all write to the DOM directly.
+ */
+export default function TimelineView(props: TimelineViewProps) {
+ const reduceMotion = useReducedMotion() ?? false;
+ const isDesktop = useMediaQuery("(min-width: 1024px)", true);
+ const hasHover = useMediaQuery("(hover: hover) and (pointer: fine)", true);
+ const playback = usePlayback();
+
+ // Duration is read off the store rather than held in state, and only
+ // promoted to state when it actually changes: the subscriber below fires
+ // every frame during playback and must not re-render the deck each time.
+ // It lives up here because the provider clamps the zoom window against it.
+ const [duration, setDuration] = useState(() => playback.getDuration());
+ const durationRef = useRef(duration);
+
+ useEffect(
+ () =>
+ playback.subscribe(() => {
+ const next = playback.getDuration();
+ if (Math.abs(next - durationRef.current) < 0.001) return;
+ durationRef.current = next;
+ setDuration(next);
+ }),
+ [playback],
+ );
+
+ return (
+ <motion.div
+ // Slides down from beneath the stage rather than up from the page:
+ // the band is the bottom half of the player strip, and the brief
+ // overlap during the move is white-on-white, so it reads as unfolding.
+ initial={reduceMotion ? { opacity: 0 } : { opacity: 0, y: -14 }}
+ animate={reduceMotion ? { opacity: 1 } : { opacity: 1, y: 0 }}
+ exit={
+ reduceMotion
+ ? { opacity: 0, transition: { duration: 0 } }
+ : { opacity: 0, y: -10, transition: { duration: 0.16, ease: EASE } }
+ }
+ transition={
+ reduceMotion ? { duration: 0 } : { duration: 0.32, ease: EASE }
+ }
+ data-timeline-view=""
+ // Transparent: the band is the lower body of the player card the host
+ // grid draws, so the card's colour and corners show through.
+ className="relative w-full"
+ >
+ <TimelineProvider
+ compact={!isDesktop}
+ hasHover={hasHover}
+ duration={duration}
+ >
+ <TimelineBand
+ {...props}
+ compact={!isDesktop}
+ hasHover={hasHover}
+ duration={duration}
+ />
+ </TimelineProvider>
+ </motion.div>
+ );
+}
+
+/**
+ * Everything below the provider, so the band can reach timeline UI state
+ * (the composer anchor, the zoom window) through the same hooks its children
+ * use.
+ */
+function TimelineBand({
+ comments,
+ videoId,
+ chapters = EMPTY_CHAPTERS,
+ transcriptionStatus,
+ filmstripSource = null,
+ onOptimisticComment,
+ onCommentSuccess,
+ canRecordMedia = false,
+ viewerSignedIn = false,
+ disableReactions = false,
+ onRecordingActiveChange,
+ onRecordIntent,
+ onControlsSlotChange,
+ compact,
+ hasHover,
+ duration,
+}: TimelineViewProps & {
+ compact: boolean;
+ hasHover: boolean;
+ duration: number;
+}) {
+ const playback = usePlayback();
+ const {
+ openComposer,
+ closeComposer,
+ zoomAtTime,
+ panBy,
+ resetZoom,
+ setWindow,
+ } = useTimelineActions();
+ const { start: windowStart, end: windowEnd } = useTimelineWindow();
+ const windowRef = useTimelineWindowRef();
+ const [recordIntent, setRecordIntent] = useState<{
+ kind: RecordIntentKind;
+ t: number;
+ } | null>(null);
+
+ const internalRecordIntent = useCallback(
+ (kind: RecordIntentKind, t: number) => {
+ playback.pause();
+ closeComposer();
+ setRecordIntent({ kind, t });
+ },
+ [playback, closeComposer],
+ );
+
+ useEffect(() => {
+ onRecordingActiveChange?.(recordIntent !== null);
+ return () => onRecordingActiveChange?.(false);
+ }, [recordIntent, onRecordingActiveChange]);
+
+ const stripRef = useRef<HTMLDivElement | null>(null);
+ const railRef = useRef<HTMLDivElement | null>(null);
+ const commentsRef = useRef<HTMLDivElement | null>(null);
+ const widthRef = useRef(0);
+ const [trackWidth, setTrackWidth] = useState(0);
+
+ // Stable identity: an inline ref callback would re-fire (null, el) on every
+ // zoom-driven render and thrash the host's state.
+ const onControlsSlotChangeRef = useRef(onControlsSlotChange);
+ onControlsSlotChangeRef.current = onControlsSlotChange;
+ const controlsSlotRef = useCallback(
+ (el: HTMLElement | null) => onControlsSlotChangeRef.current?.(el),
+ [],
+ );
+
+ const durationRef = useRef(duration);
+ durationRef.current = duration;
+
+ useEffect(() => {
+ const strip = stripRef.current;
+ if (!strip) return;
+
+ const measure = (width: number) => {
+ widthRef.current = width;
+ setTrackWidth((prev) => {
+ const next = quantizeWidth(width);
+ return next === prev ? prev : next;
+ });
+ };
+
+ measure(strip.clientWidth);
+ if (typeof ResizeObserver === "undefined") return;
+ const observer = new ResizeObserver((entries) => {
+ for (const entry of entries) measure(entry.contentRect.width);
+ });
+ observer.observe(strip);
+ return () => observer.disconnect();
+ }, []);
+
+ // Trackpad pinch arrives as a ctrl-wheel, and React's synthetic onWheel is
+ // passive, so preventDefault only works from a manually bound listener.
+ useEffect(() => {
+ const strip = stripRef.current;
+ if (!strip) return;
+
+ const handleWheel = (event: WheelEvent) => {
+ const total = durationRef.current;
+ if (!Number.isFinite(total) || total <= 0) return;
+ const window = windowRef.current;
+
+ if (event.ctrlKey || event.metaKey) {
+ event.preventDefault();
+ const focus = timeFromClientX(
+ event.clientX,
+ strip.getBoundingClientRect(),
+ window.start,
+ window.end,
+ );
+ const factor = Math.min(
+ WHEEL_ZOOM_MAX,
+ Math.max(
+ 1 / WHEEL_ZOOM_MAX,
+ Math.exp(-event.deltaY * WHEEL_ZOOM_RATE),
+ ),
+ );
+ zoomAtTime(factor, focus);
+ return;
+ }
+
+ const horizontal = Math.abs(event.deltaX) > Math.abs(event.deltaY);
+ // A plain vertical wheel belongs to the page, not to the deck.
+ if (!horizontal && !event.shiftKey) return;
+ if (isFullWindow(window, total)) return;
+
+ event.preventDefault();
+ const usable = usableWidth(widthRef.current);
+ if (usable <= 0) return;
+ const delta = horizontal ? event.deltaX : event.deltaY;
+ panBy((delta / usable) * (window.end - window.start));
+ };
+
+ strip.addEventListener("wheel", handleWheel, { passive: false });
+ return () => strip.removeEventListener("wheel", handleWheel);
+ }, [zoomAtTime, panBy, windowRef]);
+
+ // Keeps the playhead on screen once a zoom has left it behind, at one
+ // state update per crossing rather than one per frame.
+ const followedRef = useRef(false);
+ useEffect(
+ () =>
+ playback.subscribe((time) => {
+ if (!playback.getPlaying()) return;
+ const window = windowRef.current;
+ if (time >= window.start && time <= window.end) {
+ followedRef.current = false;
+ return;
+ }
+ if (followedRef.current) return;
+ const next = followWindow(window, time, durationRef.current);
+ if (!next) return;
+ followedRef.current = true;
+ setWindow(next);
+ }),
+ [playback, windowRef, setWindow],
+ );
+
+ // Replies belong to their parent's card, not to a branch of their own; the
+ // disableReactions viewer setting hides emoji everywhere else, so it hides
+ // their branches too.
+ const rootComments = useMemo(
+ () =>
+ comments.filter(
+ (comment) =>
+ !comment.parentCommentId &&
+ !(disableReactions && comment.type === "emoji"),
+ ),
+ [comments, disableReactions],
+ );
+
+ const replyCounts = useMemo(() => {
+ const counts = new Map<string, number>();
+ for (const comment of comments) {
+ const parent = comment.parentCommentId;
+ if (!parent) continue;
+ counts.set(parent, (counts.get(parent) ?? 0) + 1);
+ }
+ return counts;
+ }, [comments]);
+
+ const branches = useMemo(
+ () =>
+ layoutBranches(
+ rootComments,
+ { start: windowStart, end: windowEnd },
+ trackWidth,
+ compact ? MIN_NODE_GAP_MOBILE : MIN_NODE_GAP,
+ ),
+ [rootComments, windowStart, windowEnd, trackWidth, compact],
+ );
+
+ const stems = compact ? LANE_STEM_MOBILE : LANE_STEM;
+
+ // The shelf hugs its content: single-lane days don't pay for lane 1, and
+ // with nothing on it the row disappears entirely.
+ const shelfHeight =
+ branches.length > 0
+ ? Math.max(...branches.map((node) => stems[node.lane])) +
+ NODE_SIZE / 2 +
+ 12
+ : 0;
+
+ // Filmstrip geometry follows the quantised track width, so a resize only
+ // re-tiles at the same coarse steps as the layout.
+ const stripUsable = usableWidth(trackWidth);
+ const tileCount = filmstripTileCount(stripUsable);
+ const stripH = stripHeight(compact);
+ const tileAspect =
+ tileCount > 0 && stripH > 0 ? stripUsable / tileCount / stripH : 16 / 9;
+ const filmstrip = useFilmstripFrames({
+ source: filmstripSource,
+ duration,
+ tileCount,
+ tileAspect,
+ windowStart,
+ windowEnd,
+ });
+
+ const envelope = useTimelineWaveform({
+ videoId,
+ transcriptionStatus,
+ duration,
+ });
+
+ const handleSeek = useCallback(
+ (time: number) => playback.seek(time),
+ [playback],
+ );
+
+ const handleAddAtTime = useCallback(
+ (time: number) => {
+ playback.pause();
+ openComposer(time);
+ },
+ [playback, openComposer],
+ );
+
+ const handleKeyDown = useCallback(
+ (event: React.KeyboardEvent<HTMLDivElement>) => {
+ const target = event.target as HTMLElement | null;
+ if (
+ target instanceof HTMLInputElement ||
+ target instanceof HTMLTextAreaElement
+ ) {
+ return;
+ }
+
+ if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
+ event.preventDefault();
+ const delta =
+ event.key === "ArrowLeft" ? -KEYBOARD_SEEK_STEP : KEYBOARD_SEEK_STEP;
+ playback.seek(playback.getCurrentTime() + delta);
+ return;
+ }
+
+ // Space over a branch node belongs to that button, not to playback.
+ if (event.key === " " || event.key === "Spacebar") {
+ if (target?.closest("[data-timeline-node]")) return;
+ event.preventDefault();
+ if (playback.getPlaying()) playback.pause();
+ else playback.play();
+ }
+ },
+ [playback],
+ );
+
+ return (
+ <>
+ {/* biome-ignore lint/a11y/noStaticElementInteractions: delegates keys for the slider it contains. */}
+ <div className="flex w-full flex-col" onKeyDown={handleKeyDown}>
+ {/* biome-ignore lint/a11y/noStaticElementInteractions: double-click resets a gesture the rail inside already owns. */}
+ <div
+ ref={stripRef}
+ className="relative shrink-0"
+ style={{ height: stripH }}
+ onDoubleClick={resetZoom}
+ >
+ <TimelineRail
+ duration={duration}
+ railRef={railRef}
+ filmstrip={filmstrip}
+ tileCount={tileCount}
+ envelope={envelope}
+ windowStart={windowStart}
+ windowEnd={windowEnd}
+ />
+ <TimelineChapterTicks
+ chapters={chapters}
+ duration={duration}
+ windowStart={windowStart}
+ windowEnd={windowEnd}
+ />
+ <TimelinePlayhead widthRef={widthRef} />
+ <TimelineHoverGhost
+ stripRef={stripRef}
+ widthRef={widthRef}
+ enabled={hasHover && !compact}
+ onAddAtTime={handleAddAtTime}
+ filmstrip={filmstrip}
+ tileCount={tileCount}
+ />
+ </div>
+
+ {/*
+ * Comments live between the strip and the control bar, and the row
+ * only exists while something is on it: no branches, no gap, and the
+ * film sits directly on the controls.
+ */}
+ <div
+ ref={commentsRef}
+ className="relative shrink-0 overflow-visible transition-[height] duration-200"
+ style={{ height: shelfHeight }}
+ >
+ {branches.length > 0 && (
+ <>
+ <TimelineRuler windowStart={windowStart} windowEnd={windowEnd} />
+ <TimelineBranches
+ branches={branches}
+ windowStart={windowStart}
+ windowEnd={windowEnd}
+ stems={stems}
+ trackWidth={trackWidth}
+ shelfHeight={shelfHeight}
+ replyCounts={replyCounts}
+ onSeek={handleSeek}
+ />
+ </>
+ )}
+ <TimelineComposer
+ videoId={videoId}
+ trackWidth={trackWidth}
+ windowStart={windowStart}
+ windowEnd={windowEnd}
+ viewerSignedIn={viewerSignedIn}
+ onOptimisticComment={onOptimisticComment}
+ onCommentSuccess={onCommentSuccess}
+ onRecordIntent={
+ canRecordMedia
+ ? (onRecordIntent ?? internalRecordIntent)
+ : undefined
+ }
+ />
+ </div>
+
+ {/* The card's bottom row: the player's own control bar portals into
+ the slot (context survives portals, so every button keeps its
+ store) in its light tone, and the rounded corners close the unit.
+ The hairline stands in for the strip's bottom edge when the
+ comments shelf is collapsed and the film sits straight on it. */}
+ <div className="flex h-14 shrink-0 items-center gap-1 rounded-b-xl border-t border-gray-4 bg-white">
+ <div
+ ref={controlsSlotRef}
+ className="relative h-full min-w-0 flex-1"
+ />
+ {/*
+ * Touch replacement for the hover ghost: without a hover pointer
+ * (or below lg) there is no "add here" affordance on the strip, so
+ * the bar carries one that opens the composer at the playhead.
+ */}
+ {!(hasHover && !compact) && (
+ <button
+ type="button"
+ aria-label="Comment at current time"
+ title="Comment at current time"
+ onClick={() => handleAddAtTime(playback.getCurrentTime())}
+ className="flex size-8 shrink-0 items-center justify-center rounded-full text-gray-10 transition-colors hover:bg-gray-3 hover:text-gray-12 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-9"
+ >
+ <svg
+ viewBox="0 0 16 16"
+ className="size-4 fill-current"
+ aria-hidden
+ >
+ <title>Add comment</title>
+ <path d="M8 1.5c-3.6 0-6.5 2.5-6.5 5.6 0 1.8 1 3.4 2.5 4.4-.1.8-.5 1.6-1.1 2.3-.2.2 0 .6.3.6 1.4-.1 2.6-.6 3.5-1.3.4.1.8.1 1.3.1 3.6 0 6.5-2.5 6.5-5.6S11.6 1.5 8 1.5Zm.6 3.4v1.5h1.5a.6.6 0 1 1 0 1.2H8.6v1.5a.6.6 0 1 1-1.2 0V7.6H5.9a.6.6 0 1 1 0-1.2h1.5V4.9a.6.6 0 1 1 1.2 0Z" />
+ </svg>
+ </button>
+ )}
+ <TimelineZoomControls />
+ </div>
+ </div>
+
+ {recordIntent && (
+ <RecorderSurface
+ kind={recordIntent.kind}
+ timestamp={recordIntent.t}
+ videoId={videoId}
+ onOptimisticComment={onOptimisticComment}
+ onCommentSuccess={onCommentSuccess}
+ onClose={() => setRecordIntent(null)}
+ />
+ )}
+ <TimelineMobileSheet branches={branches} onSeek={handleSeek} />
+ <TimelineActiveCue branches={branches} containerRef={commentsRef} />
+ </>
+ );
+}
diff --git a/apps/web/app/s/[videoId]/_components/timeline/TimelineWaveform.tsx b/apps/web/app/s/[videoId]/_components/timeline/TimelineWaveform.tsx
new file mode 100644
index 000000000..089e14d92
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/TimelineWaveform.tsx
@@ -0,0 +1,114 @@
+"use client";
+
+import { memo, useEffect, useRef, useState } from "react";
+
+interface TimelineWaveformProps {
+ envelope: Float32Array | null;
+ start: number;
+ end: number;
+ duration: number;
+}
+
+/** Peak height as a share of half the strip. */
+const AMPLITUDE = 0.86;
+
+// Light enough that a wall-to-wall envelope (any video with continuous speech)
+// reads as texture over the film rather than a solid block covering it.
+const FILL = "rgba(18,22,31,0.4)";
+
+/**
+ * The readable layer over the washed-out film: a symmetric envelope of the audio,
+ * drawn once per (envelope, window, size) and never again. Playback does not
+ * touch it — progress is the wash and the underline above.
+ */
+export const TimelineWaveform = memo(function TimelineWaveform({
+ envelope,
+ start,
+ end,
+ duration,
+}: TimelineWaveformProps) {
+ const canvasRef = useRef<HTMLCanvasElement | null>(null);
+ const [size, setSize] = useState({ width: 0, height: 0 });
+
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!canvas || typeof ResizeObserver === "undefined") return;
+
+ const measure = () => {
+ const width = Math.round(canvas.clientWidth);
+ const height = Math.round(canvas.clientHeight);
+ setSize((prev) =>
+ prev.width === width && prev.height === height
+ ? prev
+ : { width, height },
+ );
+ };
+
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(canvas);
+ return () => observer.disconnect();
+ }, []);
+
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!canvas) return;
+ const { width, height } = size;
+ if (width <= 0 || height <= 0) return;
+
+ const dpr = Math.min(3, window.devicePixelRatio || 1);
+ canvas.width = Math.round(width * dpr);
+ canvas.height = Math.round(height * dpr);
+
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return;
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ ctx.clearRect(0, 0, width, height);
+
+ const buckets = envelope?.length ?? 0;
+ const span = end - start;
+ if (!buckets || span <= 0 || !Number.isFinite(duration) || duration <= 0)
+ return;
+
+ const centre = height / 2;
+ const scale = centre * AMPLITUDE;
+
+ // One averaged sample per pixel column, so zooming out never aliases the
+ // envelope into noise and zooming in never draws a staircase.
+ const tops: number[] = new Array(width + 1);
+ for (let x = 0; x <= width; x += 1) {
+ const from = start + (x / width) * span;
+ const to = start + ((x + 1) / width) * span;
+ const first = Math.max(0, Math.floor((from / duration) * buckets));
+ const last = Math.min(buckets - 1, Math.ceil((to / duration) * buckets));
+
+ let total = 0;
+ let count = 0;
+ for (let index = first; index <= last; index += 1) {
+ total += envelope?.[index] ?? 0;
+ count += 1;
+ }
+ tops[x] = count > 0 ? total / count : 0;
+ }
+
+ ctx.beginPath();
+ ctx.moveTo(0, centre - (tops[0] ?? 0) * scale);
+ for (let x = 1; x <= width; x += 1) {
+ ctx.lineTo(x, centre - (tops[x] ?? 0) * scale);
+ }
+ for (let x = width; x >= 0; x -= 1) {
+ ctx.lineTo(x, centre + (tops[x] ?? 0) * scale);
+ }
+ ctx.closePath();
+ ctx.fillStyle = FILL;
+ ctx.fill();
+ }, [envelope, start, end, duration, size]);
+
+ return (
+ <canvas
+ ref={canvasRef}
+ aria-hidden
+ className="pointer-events-none absolute inset-0 size-full"
+ />
+ );
+});
diff --git a/apps/web/app/s/[videoId]/_components/timeline/TimelineZoomControls.tsx b/apps/web/app/s/[videoId]/_components/timeline/TimelineZoomControls.tsx
new file mode 100644
index 000000000..9a838dea9
--- /dev/null
+++ b/apps/web/app/s/[videoId]/_components/timeline/TimelineZoomControls.tsx
@@ -0,0 +1,68 @@
+"use client";
+
+import { usePlayback } from "../playback/PlaybackContext";
+import { useTimelineActions, useTimelineWindow } from "./TimelineProvider";
+import { ZOOM_STEP } from "./timeline-constants";
+
+/**
+ * Zoom in, zoom out, and a Fit escape hatch that only exists while there is
+ * something to escape from. No percentage readout: the window is legible from
+ * the strip itself, and the clock stays the deck's only number.
+ */
+export function TimelineZoomControls() {
+ const playback = usePlayback();
+ const { zoomed } = useTimelineWindow();
+ const { zoomAtTime, resetZoom } = useTimelineActions();
+
+ const zoom = (factor: number) =>
+ zoomAtTime(factor, playback.getCurrentTime());
+
+ // This cluster lives at the end of the docked control bar's row, so it
+ // dresses like the player controls beside it.
+ return (
+ <div className="flex shrink-0 items-center gap-1 pr-4">
+ {zoomed && (
+ <button
+ type="button"
+ onClick={resetZoom}
+ className="rounded-md px-2 py-1 text-xs font-medium text-gray-10 transition-colors hover:text-gray-12 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-9"
+ >
+ Fit
+ </button>
+ )}
+ {/* Hidden on phones: the strip pinch-zooms there, and the docked bar
+ needs every pixel. Fit stays — it is the escape hatch after a pinch. */}
+ <button
+ type="button"
+ aria-label="Zoom out"
+ onClick={() => zoom(1 / ZOOM_STEP)}
+ className="max-sm:hidden flex size-8 items-center justify-center rounded-full text-gray-10 transition-colors hover:bg-gray-3 hover:text-gray-12 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-9"
+ >
+ <MinusIcon />
+ </button>
+ <button
+ type="button"
+ aria-label="Zoom in"
+ onClick={() => zoom(ZOOM_STEP)}
+ className="max-sm:hidden flex size-8 items-center justify-center rounded-full text-gray-10 transition-colors hover:bg-gray-3 hover:text-gray-12 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-9"
+ >
+ <PlusIcon />
+ </button>
+ </div>
+ );
+}
+
+const MinusIcon = () => (
+ <svg viewBox="0 0 16 16" className="size-4 fill-current" aria-hidden>
+ <title>Zoom out</title>
+ <rect x="3" y="7.3" width="10" height="1.4" rx="0.7" />
+ </svg>
+);
+
+const PlusIcon = () => (
+ <svg viewBox="0 0 16 16" className="size-4 fill-current" aria-hidden>
+ <title>Zoom in</title>
+ <rect x="3" y="7.3" width="10" height="1.4" rx="0.7" />
+ <rect x="7.3" y="3" width="1.4" height="10" rx="0.7" />
+ </svg>
+);