Files
hyperframes/packages/studio/src/captions/components/CaptionTimeline.tsx
T
Vance IngallsandClaude Opus 5 254de3d1c4 fix(studio): captions UX — mode exit, undo, autosave surfacing, honest gating (#1968)
Caption-editing fixes from the studio UX review. This surface held five of
the thirteen criticals; the theme is that the editing UI shipped ahead of
its apply/persist pipeline, so several controls mutated an in-memory model
with no downstream effect, and the mode itself could never be exited.

Mode trap: caption edit mode auto-activated on detection and had no exit —
`setEditMode(false)` and `reset()` had zero call sites, so the caption
overlay replaced normal element editing for the rest of the session, even
after switching compositions. The store now resets on composition change
(flushing the last debounced edit first), an "Editing captions · Exit" pill
sits on the preview, and a re-enter button appears once dismissed.

Honest gating of dead surfaces: the Animation tab (31 presets ×
duration/ease/stagger/intensity) edited state that was never applied to
playback nor serialized — wiring it needs a CaptionOverride schema
extension in packages/core plus a runtime engine, so the tab is now visibly
disabled with an amber "isn't applied to playback or saved yet" notice
instead of silently discarding work. Timing edge-drags moved a block that
never changed playback and never saved; the handles are gone and the blocks
remain as select/seek targets. Double-click split desynced the overlay↔DOM
index mapping, so split is out until regeneration exists.

Undo: store-level undo/redo (cap 50, 800ms coalescing by edit target)
across all ten mutations, with ⌘Z/⇧⌘Z intercepted while caption mode is
active and reapplied to the live iframe. Previously ⌘Z reverted an
unrelated file edit while the bad caption drag persisted.

Autosave: save failures, including non-2xx, raise a persistent "not
saved — Retry" banner; the code's own comment called this a data-loss path
and it was telemetry-only. Debounced saves flush on unmount instead of
being discarded, `beforeunload` flushes and warns while pending, and
corrupt overrides JSON is distinguished from a missing file.

Input safety and a11y: arrow-key nudge no longer hijacks arrows inside
form inputs; numeric fields commit finite values only (typing "-" used to
inject NaN into gsap and persist null); "Mixed" shows on multi-select
divergence; Escape cancels an in-flight drag and restores the pre-drag
transform; ⌘A selects all; caption blocks are keyboard-selectable with a
playhead line and click-to-seek (CaptionTimeline's `onSeek` prop existed
but nothing passed it); 24px hit areas around the 8px handles; a hint when
no boxes are visible; visible input focus styles; tablist semantics.

Perf: the 66ms getBoundingClientRect polling loop is replaced with
event-driven updates (player-store subscription, preview messages,
ResizeObserver, rAF-coalesced); the interval now runs only during playback.

Reconciled against main: StudioPreviewArea.tsx was deleted by the Studio
revamp (#2291), so the mode pill, the sync-error banner and the re-enter
button move to its successor, nle/PreviewOverlays.tsx, and the caption
track's onSeek is wired in EditorShell. The per-keyframe
onChangeKeyframeEase change that also lived in that file is dropped:
main removed the prop, and #1967 now routes the diamond menu's ease action
to the focused-ease-segment editor instead.

Restacked onto main now that PRs 1962-1967 have squash-merged, so this
carries only its own changes.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 11:37:28 -07:00

145 lines
4.5 KiB
TypeScript

import { memo, useCallback } from "react";
import { useCaptionStore } from "../store";
import { usePlayerStore } from "../../player";
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const GROUP_COLORS = [
"#3CE6AC",
"#FF6B6B",
"#4ECDC4",
"#FFE66D",
"#A78BFA",
"#F472B6",
"#34D399",
"#FB923C",
"#60A5FA",
"#C084FC",
];
const TRACK_LEFT_PAD = 32;
// Timing edge-drag and double-click group split were removed deliberately:
// segment timing and group structure only mutate the in-memory model — they
// are never applied to playback nor serialized to caption-overrides.json, so
// the UI was confirming edits that didn't exist. Restore them only alongside
// a real apply/persist pipeline.
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
interface CaptionTimelineProps {
pixelsPerSecond: number;
onSeek?: (time: number) => void;
}
// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------
export const CaptionTimeline = memo(function CaptionTimeline({
pixelsPerSecond,
onSeek,
}: CaptionTimelineProps) {
const model = useCaptionStore((s) => s.model);
const selectedSegmentIds = useCaptionStore((s) => s.selectedSegmentIds);
const selectSegment = useCaptionStore((s) => s.selectSegment);
const currentTime = usePlayerStore((s) => s.currentTime);
const handleBlockClick = useCallback(
(e: React.MouseEvent, segId: string) => {
e.stopPropagation();
selectSegment(segId, e.shiftKey);
},
[selectSegment],
);
const handleBlockKeyDown = useCallback(
(e: React.KeyboardEvent, segId: string) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
e.stopPropagation();
selectSegment(segId, e.shiftKey);
}
},
[selectSegment],
);
const handleTrackClick = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
if (!onSeek) return;
const rect = (e.currentTarget as HTMLDivElement).getBoundingClientRect();
const x = e.clientX - rect.left - TRACK_LEFT_PAD;
const time = Math.max(0, x / pixelsPerSecond);
onSeek(time);
},
[onSeek, pixelsPerSecond],
);
if (!model) return null;
const playheadLeft = TRACK_LEFT_PAD + currentTime * pixelsPerSecond;
return (
<div
className="relative select-none overflow-x-auto"
style={{ height: 40, minWidth: "100%" }}
onClick={handleTrackClick}
>
{model.groupOrder.map((groupId, groupIdx) => {
const group = model.groups.get(groupId);
if (!group) return null;
const color = GROUP_COLORS[groupIdx % GROUP_COLORS.length];
return group.segmentIds.map((segId) => {
const seg = model.segments.get(segId);
if (!seg) return null;
const left = TRACK_LEFT_PAD + seg.start * pixelsPerSecond;
const width = Math.max((seg.end - seg.start) * pixelsPerSecond, 4);
const isSelected = selectedSegmentIds.has(segId);
return (
<div
key={segId}
role="button"
tabIndex={0}
aria-label={`Caption word "${seg.text}"`}
aria-pressed={isSelected}
className={`absolute top-1 bottom-1 rounded flex items-center overflow-hidden cursor-pointer focus-visible:ring-1 focus-visible:ring-white outline-none${
isSelected ? " ring-1 ring-white/50 z-10" : ""
}`}
style={{
left,
width,
backgroundColor: color,
zIndex: isSelected ? 10 : 1,
}}
onClick={(e) => handleBlockClick(e, segId)}
onKeyDown={(e) => handleBlockKeyDown(e, segId)}
>
{/* Text label */}
<span
className="flex-1 truncate px-2 pointer-events-none"
style={{ fontSize: 9, color: "#000000", lineHeight: 1 }}
>
{seg.text}
</span>
</div>
);
});
})}
{/* Playhead — correlates blocks with the current frame */}
<div
className="absolute top-0 bottom-0 w-px bg-white/70 pointer-events-none z-20"
style={{ left: playheadLeft }}
aria-hidden="true"
/>
</div>
);
});