Skip to content

Open source CapCut alternative.

TypeScript

feat(site): settings panels remember their state per item

David Lec444ca3da03f
diff --git a/site/src/cut/components/ColorPanel.tsx b/site/src/cut/components/ColorPanel.tsx
index 7aed878d..fe0bc5f3 100644
--- a/site/src/cut/components/ColorPanel.tsx
+++ b/site/src/cut/components/ColorPanel.tsx
@@ -25,7 +25,7 @@ import {
} from "@donkeycut/effects-kit";
import { getPreviewCanvas, sampleClipFrameData } from "@/cut/lib/previewCanvas";
import { useEditor } from "@/cut/lib/store";
-import { usePanelView } from "@/cut/lib/panelViews";
+import { usePanelState, useRememberedScroll } from "@/cut/lib/panelState";
import type { VideoClip } from "@/cut/lib/types";
import { ResetButton, Row, useSliderCheckpoint } from "@/cut/components/panelBits";
import { ColorWheel } from "@/cut/components/ColorWheel";
@@ -51,10 +51,7 @@ import { Switch } from "@/components/ui/switch";
export function ColorPanel({ clip }: { clip: VideoClip }) {
// The open level holds for the session per clip, so deselecting and coming
// back lands on the same view.
- const [view, setView] = usePanelView<"presets" | "adjust">(
- `color-level:${clip.id}`,
- "presets"
- );
+ const [view, setView] = usePanelState<"presets" | "adjust">(clip.id, "colorView", "presets");
if (view === "adjust") {
return <AdjustView clip={clip} onBack={() => setView("presets")} />;
}
@@ -95,7 +92,12 @@ function useGradeWriter(clip: VideoClip) {
/* ------------------------------------------------------------------ */
function PresetView({ clip, onAdjust }: { clip: VideoClip; onAdjust: () => void }) {
- const [category, setCategory] = useState<GradePresetCategory | "all">("all");
+ const [category, setCategory] = usePanelState<GradePresetCategory | "all">(
+ clip.id,
+ "colorPresetCategory",
+ "all"
+ );
+ const gridScroll = useRememberedScroll(clip.id, `color-presets:${category}`);
// The clip's own frame, ungraded: a swatch shows what its preset does to the
// footage, never what the clip's current grade already did.
const frame = useClipSourceFrame(clip.id);
@@ -162,6 +164,7 @@ function PresetView({ clip, onAdjust }: { clip: VideoClip; onAdjust: () => void
className="min-h-0 flex-1"
viewportClassName="overscroll-contain"
contentClassName="grid grid-cols-2 gap-2 px-3.5 pt-1 pb-2"
+ {...gridScroll}
>
{presets.map((p) => (
// Keyed by the clip too: a tile holds its last thumb across a
@@ -358,7 +361,8 @@ function StandInScene({ filter, tint }: { filter: string; tint: string | null })
function AdjustView({ clip, onBack }: { clip: VideoClip; onBack: () => void }) {
// The picked tool holds for the session, the same way the open level does.
- const [tool, setTool] = usePanelView<Tool>(`color-tool:${clip.id}`, "basic");
+ const [tool, setTool] = usePanelState<Tool>(clip.id, "colorTool", "basic");
+ const toolScroll = useRememberedScroll(clip.id, `color-adjust:${tool}`);
const { draft, commit } = useGradeWriter(clip);
const grade = clip.grade;
// Manual adjustments only — reset-all keeps the preset layer.
@@ -435,6 +439,7 @@ function AdjustView({ clip, onBack }: { clip: VideoClip; onBack: () => void }) {
className="min-h-0 flex-1"
viewportClassName="overscroll-contain"
contentClassName="flex flex-col gap-1 px-3.5 pt-1 pb-4"
+ {...toolScroll}
>
<Histogram />
{tool === "basic" && <BasicTool grade={grade} draft={draft} commit={commit} />}
@@ -446,7 +451,7 @@ function AdjustView({ clip, onBack }: { clip: VideoClip; onBack: () => void }) {
/>
)}
{tool === "wheels" && <WheelsTool grade={grade} draft={draft} commit={commit} />}
- {tool === "hsl" && <HslTool grade={grade} draft={draft} commit={commit} />}
+ {tool === "hsl" && <HslTool clipId={clip.id} grade={grade} draft={draft} commit={commit} />}
</ScrollArea>
</div>
);
@@ -584,8 +589,8 @@ const HSL_AXES = [
{ index: 2, label: "Luminance" },
] as const;
-function HslTool({ grade, draft, commit }: GradeWrite) {
- const [band, setBand] = useState<HslBand>("orange");
+function HslTool({ clipId, grade, draft, commit }: GradeWrite & { clipId: string }) {
+ const [band, setBand] = usePanelState<HslBand>(clipId, "hslBand", "orange");
const active = HSL_BANDS.find((b) => b.id === band)!;
const tuple: HslTuple = grade?.hsl?.[band] ?? [0, 0, 0];
const write = (to: (g: ColorGrade) => void, next: HslTuple) =>
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index 3e6c67f2..7c0ee583 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -4,7 +4,6 @@ import { useQueryClient } from "@tanstack/react-query";
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { AlignCenter, AlignHorizontalSpaceAround, AlignLeft, AlignRight, AlignVerticalSpaceAround, Bold, ChevronLeft, ChevronRight, Diamond, Frame, House, Italic, Link2, Link2Off, Loader2, type LucideIcon, Palette, PanelRightClose, PanelRightOpen, PenTool, Scissors, Smile, Sparkles, Trash2, Type, User, Volume2 } from "lucide-react";
import { Button } from "@/components/ui/button";
-import { useSpeedCurveUi } from "@/cut/lib/speedCurveUi";
import { EmojiPicker } from "@/cut/components/EmojiPicker";
import { FontPicker } from "@/cut/components/FontPicker";
import {
@@ -79,7 +78,7 @@ import {
restingMaskFrame,
} from "@donkeycut/effects-kit";
import { clipWindow, maxClipFade, useEditor, type EditorState } from "@/cut/lib/store";
-import { usePanelView } from "@/cut/lib/panelViews";
+import { PANEL_GLOBAL, usePanelState, useRememberedScroll } from "@/cut/lib/panelState";
import { usePreviewTime } from "@/cut/lib/playhead";
import { CLIP_MAX_ZOOM, clipCovers, clipKeyed, clipPoseAt, clipZoom, contentRect } from "@/cut/lib/types";
import { AnimationCard, AnimationTiles } from "@/cut/components/AnimationTiles";
@@ -227,7 +226,11 @@ function InspectorColumn({
}) {
const open = useEditor((s) => s.inspectorOpen);
const setOpen = useEditor((s) => s.setInspectorOpen);
- const [view, setView] = useState("main");
+ // The open tab and the Home scroller's place hold per item for the
+ // session, so coming back to an item lands on its panel as it was left.
+ const itemId = clip?.id ?? audio?.id ?? overlay?.id ?? PANEL_GLOBAL;
+ const [view, setView] = usePanelState<string>(itemId, "tab", "main");
+ const homeScroll = useRememberedScroll(itemId, "main");
// Coming home from the animation view marks the return, so the overlay
// panel can scroll its Animation row back into sight; the mark clears on
// the next pick.
@@ -238,7 +241,7 @@ function InspectorColumn({
setView(id);
setOpen(true);
},
- [view, setOpen]
+ [view, setView, setOpen]
);
const nav = useMemo<AnimNav>(
() => ({
@@ -271,7 +274,7 @@ function InspectorColumn({
</AnimNavContext.Provider>
) : (
<AnimNavContext.Provider value={nav}>
- <ScrollArea className="min-h-0 flex-1">
+ <ScrollArea className="min-h-0 flex-1" {...homeScroll}>
{audio ? (
<AudioPanel clip={audio} />
) : overlay ? (
@@ -532,10 +535,12 @@ function LayoutButtons({
* out their own bands around their own scroller; the others ride this one.
*/
function ClipColumn({ clip, tab }: { clip: VideoClip; tab: string }) {
+ // Keyed on the tab: each view keeps its own scroller and its own place.
+ const scroll = useRememberedScroll(clip.id, tab);
if (tab === "color") return <ColorPanel clip={clip} />;
if (tab === "cutout") return <RemovalPanel clip={clip} />;
return (
- <ScrollArea className="min-h-0 flex-1">
+ <ScrollArea key={tab} className="min-h-0 flex-1" {...scroll}>
{tab === "frame" ? (
<ClipFramePanel clip={clip} />
) : tab === "audio" ? (
@@ -600,9 +605,11 @@ function ClipAudioPanel({ clip }: { clip: VideoClip }) {
useEditor.getState().updateClipTransient(clip.id, { sound });
if (phase === "commit") ck.end();
};
- const [view, setView] = usePanelView<"main" | "sound">(`clip-audio:${clip.id}`, "main");
+ const [view, setView] = usePanelState<"main" | "sound">(clip.id, "audioView", "main");
if (view === "sound") {
- return <SoundQualityPanel sound={clip.sound} write={writeSound} onBack={() => setView("main")} />;
+ return (
+ <SoundQualityPanel itemId={clip.id} sound={clip.sound} write={writeSound} onBack={() => setView("main")} />
+ );
}
return (
<>
@@ -674,9 +681,11 @@ const sameSound = (a: ClipSound | undefined, b: ClipSound | undefined) =>
* as absence.
*/
function SoundQualitySections({
+ itemId,
sound,
write,
}: {
+ itemId: string;
sound: ClipSound | undefined;
write: (sound: ClipSound | undefined, phase: "draft" | "commit") => void;
}) {
@@ -731,7 +740,7 @@ function SoundQualitySections({
);
return (
<>
- <SoundPresetsRow sound={sound} onApply={(s) => set(s, "commit")} />
+ <SoundPresetsRow itemId={itemId} sound={sound} onApply={(s) => set(s, "commit")} />
<Section
title="Equalizer"
aside={
@@ -876,10 +885,12 @@ function SoundQualityRow({ sound, onOpen }: { sound: ClipSound | undefined; onOp
/** The Sound quality view, pushed over an audio panel. */
function SoundQualityPanel({
+ itemId,
sound,
write,
onBack,
}: {
+ itemId: string;
sound: ClipSound | undefined;
write: (sound: ClipSound | undefined, phase: "draft" | "commit") => void;
onBack: () => void;
@@ -888,7 +899,7 @@ function SoundQualityPanel({
<>
<SubviewHead title="Sound quality" onBack={onBack} />
<div className="flex flex-col gap-1 px-3.5 pb-4">
- <SoundQualitySections sound={sound} write={write} />
+ <SoundQualitySections itemId={itemId} sound={sound} write={write} />
</div>
</>
);
@@ -899,9 +910,11 @@ function SoundQualityPanel({
* none of them — plus saving the current treatment under a name and
* deleting the saved one that is selected. */
function SoundPresetsRow({
+ itemId,
sound,
onApply,
}: {
+ itemId: string;
sound: ClipSound | undefined;
onApply: (sound: ClipSound | undefined) => void;
}) {
@@ -963,7 +976,7 @@ function SoundPresetsRow({
// Two presets can hold the same settings — one saved while another was
// applied — so the one the user picked stays selected for as long as the
// clip still matches it; the first match stands in otherwise.
- const [picked, setPicked] = useState<string | null>(null);
+ const [picked, setPicked] = usePanelState<string | null>(itemId, "soundPreset", null);
const current =
options.find((o) => o.key === picked && sameSound(o.sound, sound)) ??
options.find((o) => sameSound(o.sound, sound));
@@ -1078,7 +1091,7 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
const speed = speedDraft ?? (curved ? retimeOf(clip).rate : (clip.speed ?? 1));
const speedLen =
curved && speedDraft === null ? retimeOf(clip).len : (clip.out - clip.in) / (speed > 0 ? speed : 1);
- const curveOpen = useSpeedCurveUi((s) => s.open.has(clip.id));
+ const [curveOpen, setCurveOpen] = usePanelState(clip.id, "speedCurve", false);
// Typing can trim out to the source's end but no further; an image has no
// intrinsic duration, so its clip can be any length.
const maxOut = asset && asset.type !== "image" ? asset.duration : Infinity;
@@ -1196,15 +1209,14 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
className="h-6 px-2 text-[11px]"
title="Shape the speed across the footage with nodes"
onClick={() => {
- const ui = useSpeedCurveUi.getState();
if (curveOpen) {
- ui.close(clip.id);
+ setCurveOpen(false);
return;
}
if (!curved) {
useEditor.getState().setClipSpeedCurve(clip.id, flatSpeedCurve(clip));
}
- ui.openFor(clip.id);
+ setCurveOpen(true);
}}
>
{curveOpen ? "Editing" : curved ? "Edit" : "Add"}
@@ -1551,10 +1563,11 @@ function AudioPanel({ clip }: { clip: AudioClip }) {
setAudio(patch);
ck.end();
};
- const [view, setView] = usePanelView<"main" | "sound">(`audio-sound:${clip.id}`, "main");
+ const [view, setView] = usePanelState<"main" | "sound">(clip.id, "soundView", "main");
if (view === "sound") {
return (
<SoundQualityPanel
+ itemId={clip.id}
sound={clip.sound}
write={(sound, phase) => (phase === "commit" ? commitAudio({ sound }) : setAudio({ sound }))}
onBack={() => setView("main")}
@@ -2551,13 +2564,14 @@ type AnimSlot = "in" | "out" | "loop" | "move" | "words";
function AnimationPanel({ overlay: o }: { overlay: Overlay }) {
const anim = o.anim ?? {};
// The active slot holds for the session, like every settings view's tab.
- const [picked, setSlot] = usePanelView<AnimSlot>(`anim-slot:${o.id}`, "in");
+ const [picked, setSlot] = usePanelState<AnimSlot>(o.id, "animSlot", "in");
// Word emphasis is a title's slot; a shape or a sticker has no words, so
// selecting one hands the picker back to the entrance.
const tabs: AnimSlot[] = isTextOverlay(o)
? ["in", "out", "loop", "move", "words"]
: ["in", "out", "loop", "move"];
const slot = tabs.includes(picked) ? picked : "in";
+ const tilesScroll = useRememberedScroll(o.id, `anim:${slot}`);
const active = slot === "move" || slot === "words" ? undefined : anim[slot];
const seconds = slot === "in" || slot === "out" ? anim[slot]?.seconds : undefined;
const activeMove = anim.move;
@@ -2657,9 +2671,10 @@ function AnimationPanel({ overlay: o }: { overlay: Overlay }) {
{/* pt-1 clears the selected tile's ring, which draws outside its box.
The bounce stops here rather than travelling to the panel behind. */}
<ScrollArea
- // Keyed on the tab: a new list of tiles starts at its own top.
+ // Keyed on the tab: each list of tiles keeps its own place.
key={slot}
className="min-h-0 flex-1"
+ {...tilesScroll}
viewportClassName="overscroll-contain"
contentClassName="flex flex-col gap-1 px-3.5 pt-1 pb-2"
>
@@ -3136,6 +3151,8 @@ function MaskShapeIcon({ kind }: { kind: MaskKind }) {
/** How a panel's mask section reads and writes its owner's mask — the same
* section serves overlay elements and video clips through this. */
interface MaskTarget {
+ /** The masked clip or overlay, for the panel's memory of the section. */
+ id: string;
/** Timeline window for the keyframe row and playhead-local time. */
element: { start: number; end: number };
mask?: Mask;
@@ -3280,6 +3297,7 @@ function OverlayMaskSection({ overlay: o }: { overlay: Overlay }) {
return (
<MaskSection
target={{
+ id: o.id,
element: o,
mask: o.mask,
subjectStartsBehind: true,
@@ -3499,6 +3517,7 @@ function ClipMaskSection({ clip }: { clip: VideoClip }) {
return (
<MaskSection
target={{
+ id: clip.id,
element: { start: win.start, end: win.start + win.len },
mask: clip.mask,
set: (mask) => st().updateClip(clip.id, { mask }),
@@ -3525,7 +3544,7 @@ function MaskSection({ target }: { target: MaskTarget }) {
const radiusCk = useSliderCheckpoint();
// Size link: scrubbing one axis carries the other so the shape keeps its
// pixel proportions. On for a circle, which starts round.
- const [linked, setLinked] = useState<boolean | null>(null);
+ const [linked, setLinked] = usePanelState<boolean | null>(target.id, "maskLinked", null);
const m = target.mask;
const tLocal = localTimeOf(target.element, now);
const geom = m ? maskFrameAt(m, tLocal) : null;
diff --git a/site/src/cut/components/RemovalPanel.tsx b/site/src/cut/components/RemovalPanel.tsx
index b9f6d017..45b97d13 100644
--- a/site/src/cut/components/RemovalPanel.tsx
+++ b/site/src/cut/components/RemovalPanel.tsx
@@ -10,6 +10,7 @@ import {
SelectValue,
} from "@/components/ui/select";
import { BRUSH_SIZE_MAX, BRUSH_SIZE_MIN, useBrushUi } from "@/cut/lib/removal/brushUi";
+import { panelState, useRememberedScroll } from "@/cut/lib/panelState";
import {
cancelMatteBake,
confirmMatteBake,
@@ -87,6 +88,7 @@ function useRemovalWriter(clip: VideoClip) {
}
export function RemovalPanel({ clip }: { clip: VideoClip }) {
+ const scroll = useRememberedScroll(clip.id, "cutout");
const removal = clip.removal;
const { commit } = useRemovalWriter(clip);
const peeking = useEditor((s) => s.removalPeek === clip.id);
@@ -110,7 +112,8 @@ export function RemovalPanel({ clip }: { clip: VideoClip }) {
// The brush session follows custom mode while its panel is open.
useEffect(() => {
const brush = useBrushUi.getState();
- if (removal?.mode === "custom" && !removal.off) brush.open(clip.id);
+ if (removal?.mode === "custom" && !removal.off)
+ brush.open(clip.id, panelState.get(clip.id, "brushTool", "brush"));
else if (brush.clipId === clip.id) brush.close();
return () => {
const b = useBrushUi.getState();
@@ -128,6 +131,7 @@ export function RemovalPanel({ clip }: { clip: VideoClip }) {
<ScrollArea
className="min-h-0 flex-1"
viewportClassName="overscroll-contain"
+ {...scroll}
contentClassName="flex flex-col gap-1 px-3.5 pt-1 pb-4"
>
<RemovalView clip={clip} />
@@ -387,7 +391,11 @@ function CustomControls({ clip }: { clip: VideoClip }) {
: "text-muted-foreground hover:text-foreground"
)}
aria-pressed={erasing === erase}
- onClick={() => useBrushUi.getState().setTool(erase ? "erase" : "brush")}
+ onClick={() => {
+ const tool = erase ? "erase" : "brush";
+ panelState.set(clip.id, "brushTool", tool);
+ useBrushUi.getState().setTool(tool);
+ }}
>
{erase ? "Erase" : "Brush"}
</button>
diff --git a/site/src/cut/components/SpeedCurveStrip.tsx b/site/src/cut/components/SpeedCurveStrip.tsx
index cc768dcb..1419d4aa 100644
--- a/site/src/cut/components/SpeedCurveStrip.tsx
+++ b/site/src/cut/components/SpeedCurveStrip.tsx
@@ -29,7 +29,7 @@ import {
skimAt,
subscribePlayhead,
} from "@/cut/lib/playhead";
-import { useSpeedCurveUi } from "@/cut/lib/speedCurveUi";
+import { panelState, usePanelStore } from "@/cut/lib/panelState";
import { useEditor } from "@/cut/lib/store";
import type { VideoClip } from "@/cut/lib/types";
import { cn } from "@/lib/utils";
@@ -81,19 +81,12 @@ export function SpeedCurveStrip() {
const selectedId = useEditor((s) =>
s.selection?.kind === "clip" ? s.selection.id : null,
);
- const clipId = useSpeedCurveUi((s) =>
- selectedId && s.open.has(selectedId) ? selectedId : null,
+ const clipId = usePanelStore((s) =>
+ selectedId && s.items[selectedId]?.speedCurve ? selectedId : null,
);
const clip = useEditor((s) =>
clipId ? s.clips.find((c) => c.id === clipId) : undefined,
);
- // Clips that are gone drop their entry.
- const clipIds = useEditor((s) => s.clips);
- useEffect(() => {
- const ui = useSpeedCurveUi.getState();
- for (const id of ui.open)
- if (!clipIds.some((c) => c.id === id)) ui.close(id);
- }, [clipIds]);
if (!clip) return null;
return <Strip key={clip.id} clip={clip} />;
}
@@ -422,7 +415,7 @@ function Strip({ clip }: { clip: VideoClip }) {
removePicked();
break;
case "Escape":
- useSpeedCurveUi.getState().close(clip.id);
+ panelState.set(clip.id, "speedCurve", false);
break;
default:
return;
@@ -568,7 +561,7 @@ function Strip({ clip }: { clip: VideoClip }) {
</IconButton>
<IconButton
title="Close (Esc)"
- onClick={() => useSpeedCurveUi.getState().close(clip.id)}
+ onClick={() => panelState.set(clip.id, "speedCurve", false)}
>
<X className="size-3.5" />
</IconButton>
diff --git a/site/src/cut/components/SubtitlesPanel.tsx b/site/src/cut/components/SubtitlesPanel.tsx
index 6ca692d3..6f5ab588 100644
--- a/site/src/cut/components/SubtitlesPanel.tsx
+++ b/site/src/cut/components/SubtitlesPanel.tsx
@@ -28,7 +28,7 @@ import { useElapsed } from "@/cut/hooks/useElapsed";
import { useCutCaps } from "@/cut/lib/backend/hooks";
import { useActiveWork, useGenNotify } from "@/cut/lib/genNotify";
import { TIMELINE_H_MIN, useEditor } from "@/cut/lib/store";
-import { usePanelView } from "@/cut/lib/panelViews";
+import { PANEL_GLOBAL, usePanelState } from "@/cut/lib/panelState";
import { usePreviewSelector } from "@/cut/lib/playhead";
import { PLATE_PAD_X, PLATE_PAD_Y, PLATE_RADIUS, plateFill } from "@/cut/lib/textRender";
import {
@@ -97,8 +97,9 @@ export function SubtitlesPanel() {
const hasCues = activeCues.length > 0;
// The open tab holds for the session, so leaving the panel and coming back
// lands on the same one.
- const [tab, setTab] = usePanelView<"content" | "styles" | "options">(
- "subtitles-tab",
+ const [tab, setTab] = usePanelState<"content" | "styles" | "options">(
+ PANEL_GLOBAL,
+ "subtitlesTab",
"content"
);
diff --git a/site/src/cut/lib/panelState.test.ts b/site/src/cut/lib/panelState.test.ts
new file mode 100644
index 00000000..a51f891c
--- /dev/null
+++ b/site/src/cut/lib/panelState.test.ts
@@ -0,0 +1,54 @@
+import { beforeEach, expect, test } from "bun:test";
+import { PANEL_GLOBAL, panelState, usePanelStore } from "./panelState";
+import { useEditor } from "./store";
+import type { AudioClip, Overlay, VideoClip } from "./types";
+
+const clip = (id: string) => ({ id, assetId: "a", in: 0, out: 1 }) as unknown as VideoClip;
+
+beforeEach(() => {
+ usePanelStore.setState({ items: {} });
+ useEditor.setState({ projectId: "p1", clips: [clip("c1"), clip("c2")], audioClips: [], overlays: [] });
+});
+
+test("a field holds per item and falls back to its default", () => {
+ panelState.set("c1", "tab", "color");
+ expect(panelState.get("c1", "tab", "main")).toBe("color");
+ expect(panelState.get("c2", "tab", "main")).toBe("main");
+ expect(panelState.get<boolean | null>("c1", "maskLinked", null)).toBeNull();
+});
+
+test("writing the same value again leaves the store untouched", () => {
+ panelState.set("c1", "tab", "color");
+ const before = usePanelStore.getState().items;
+ panelState.set("c1", "tab", "color");
+ expect(usePanelStore.getState().items).toBe(before);
+});
+
+test("a deleted item takes its memory with it; the rest stays", () => {
+ panelState.set("c1", "tab", "color");
+ panelState.set("c2", "tab", "audio");
+ panelState.set(PANEL_GLOBAL, "subtitlesTab", "styles");
+ useEditor.setState({ clips: [clip("c2")] });
+ expect(usePanelStore.getState().items.c1).toBeUndefined();
+ expect(panelState.get("c2", "tab", "main")).toBe("audio");
+ expect(panelState.get(PANEL_GLOBAL, "subtitlesTab", "content")).toBe("styles");
+});
+
+test("an edit that keeps the element count never sweeps", () => {
+ panelState.set("c1", "tab", "color");
+ useEditor.setState({ clips: [clip("c1"), clip("c3")] });
+ expect(panelState.get("c1", "tab", "main")).toBe("color");
+});
+
+test("switching projects drops every item of the old one", () => {
+ panelState.set("c1", "speedCurve", true);
+ useEditor.setState({
+ projectId: "p2",
+ clips: [],
+ audioClips: [{ id: "m1" } as unknown as AudioClip],
+ overlays: [{ id: "o1" } as unknown as Overlay],
+ });
+ expect(usePanelStore.getState().items.c1).toBeUndefined();
+ panelState.set("o1", "animSlot", "out");
+ expect(panelState.get("o1", "animSlot", "in")).toBe("out");
+});
diff --git a/site/src/cut/lib/panelState.ts b/site/src/cut/lib/panelState.ts
new file mode 100644
index 00000000..6f7ac5a8
--- /dev/null
+++ b/site/src/cut/lib/panelState.ts
@@ -0,0 +1,109 @@
+"use client";
+
+import { useCallback, type UIEvent } from "react";
+import { create } from "zustand";
+
+import { useEditor } from "./store";
+
+/**
+ * The settings panel's memory. Every piece of view state a panel keeps for a
+ * timeline item — the rail tab it was left on, the view inside that tab, the
+ * tool in hand, a toggle, how far it was scrolled — is stored here under the
+ * item's id and a field name, so selecting something else and coming back
+ * lands on the panel exactly as it was left. State that belongs to no single
+ * item (the subtitles tab) sits under `PANEL_GLOBAL`.
+ *
+ * Panels read through `usePanelState` where React needs to re-render and
+ * through `panelState` where an event handler needs the value right now.
+ * Scroll offsets take the second path on every scroll event, so they cost no
+ * render. In-memory only — a reload starts fresh — and an item's entries go
+ * with it when it leaves the document.
+ */
+
+/** The id under which state that is not about one item is kept. */
+export const PANEL_GLOBAL = "global";
+
+type Fields = Record<string, unknown>;
+
+interface PanelStore {
+ items: Record<string, Fields>;
+ set: (item: string, field: string, value: unknown) => void;
+ forget: (keep: (item: string) => boolean) => void;
+}
+
+export const usePanelStore = create<PanelStore>((set) => ({
+ items: {},
+ set: (item, field, value) =>
+ set((s) => {
+ if (s.items[item]?.[field] === value) return s;
+ return { items: { ...s.items, [item]: { ...s.items[item], [field]: value } } };
+ }),
+ forget: (keep) =>
+ set((s) => {
+ const items: Record<string, Fields> = {};
+ let dropped = false;
+ for (const [item, fields] of Object.entries(s.items)) {
+ if (keep(item)) items[item] = fields;
+ else dropped = true;
+ }
+ return dropped ? { items } : s;
+ }),
+}));
+
+/** The memory as plain reads and writes, for handlers and effects. */
+export const panelState = {
+ get<T>(item: string, field: string, initial: T): T {
+ const v = usePanelStore.getState().items[item]?.[field];
+ return v === undefined ? initial : (v as T);
+ },
+ set(item: string, field: string, value: unknown): void {
+ usePanelStore.getState().set(item, field, value);
+ },
+};
+
+/** A `useState` whose value holds for the session under the item and field. */
+export function usePanelState<T>(item: string, field: string, initial: T): [T, (v: T) => void] {
+ const stored = usePanelStore((s) => s.items[item]?.[field]);
+ const set = useCallback((v: T) => panelState.set(item, field, v), [item, field]);
+ return [stored === undefined ? initial : (stored as T), set];
+}
+
+/**
+ * Scroll memory for a panel's scroller: the viewport lands where it was left
+ * and every scroll writes the new offset. Spread the result onto a
+ * `ScrollArea`. A scroller that shows a different list per tab keys itself
+ * on the tab and names the tab in `field`, so each list keeps its own place.
+ */
+export function useRememberedScroll(item: string, field: string) {
+ const key = `scroll:${field}`;
+ const viewportRef = useCallback(
+ (node: HTMLDivElement | null) => {
+ if (node) node.scrollTop = panelState.get(item, key, 0);
+ },
+ [item, key]
+ );
+ const onViewportScroll = useCallback(
+ (e: UIEvent<HTMLDivElement>) => panelState.set(item, key, e.currentTarget.scrollTop),
+ [item, key]
+ );
+ return { viewportRef, onViewportScroll };
+}
+
+// An item that leaves the document takes its memory with it. Deleting is the
+// only edit that shrinks the element count, so the sweep runs only then, and
+// on a project switch; a drag or a trim never pays for it.
+let lastCount = -1;
+let lastProject: string | null = null;
+useEditor.subscribe((s) => {
+ const count = s.clips.length + s.audioClips.length + s.overlays.length;
+ const switched = s.projectId !== lastProject;
+ const shrank = lastCount >= 0 && count < lastCount;
+ lastCount = count;
+ lastProject = s.projectId;
+ if (!switched && !shrank) return;
+ const live = new Set<string>([PANEL_GLOBAL]);
+ for (const c of s.clips) live.add(c.id);
+ for (const c of s.audioClips) live.add(c.id);
+ for (const o of s.overlays) live.add(o.id);
+ usePanelStore.getState().forget((item) => live.has(item));
+});
diff --git a/site/src/cut/lib/panelViews.ts b/site/src/cut/lib/panelViews.ts
deleted file mode 100644
index a5d04ccc..00000000
--- a/site/src/cut/lib/panelViews.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-"use client";
-
-import { create } from "zustand";
-
-/**
- * Session memory for settings panels: which view each timeline element's
- * panel was left on, keyed per element. Deselecting a segment to look at
- * something and selecting it again lands back on its own view; an element
- * whose panel was never opened starts at the default. In-memory only — a
- * reload starts fresh.
- */
-const usePanelViews = create<{
- views: Record<string, string>;
- set: (key: string, view: string) => void;
-}>((set) => ({
- views: {},
- set: (key, view) => set((s) => ({ views: { ...s.views, [key]: view } })),
-}));
-
-/** A `useState` whose value holds for the session under `key`. */
-export function usePanelView<T extends string>(key: string, initial: T): [T, (v: T) => void] {
- const value = (usePanelViews((s) => s.views[key]) as T | undefined) ?? initial;
- const set = usePanelViews((s) => s.set);
- return [value, (v: T) => set(key, v)];
-}
diff --git a/site/src/cut/lib/removal/brushUi.ts b/site/src/cut/lib/removal/brushUi.ts
index 86f111de..0c7bdb9e 100644
--- a/site/src/cut/lib/removal/brushUi.ts
+++ b/site/src/cut/lib/removal/brushUi.ts
@@ -21,7 +21,8 @@ interface BrushUi {
clipId: string | null;
tool: BrushTool;
size: number;
- open: (clipId: string) => void;
+ /** Opens a session on the clip with the tool its panel remembers. */
+ open: (clipId: string, tool?: BrushTool) => void;
close: () => void;
setTool: (tool: BrushTool) => void;
setSize: (size: number) => void;
@@ -31,7 +32,7 @@ export const useBrushUi = create<BrushUi>((set) => ({
clipId: null,
tool: "brush",
size: BRUSH_SIZE_DEFAULT,
- open: (clipId) => set({ clipId, tool: "brush" }),
+ open: (clipId, tool = "brush") => set({ clipId, tool }),
close: () => set({ clipId: null }),
setTool: (tool) => set({ tool }),
setSize: (size) => set({ size: Math.min(BRUSH_SIZE_MAX, Math.max(BRUSH_SIZE_MIN, size)) }),
diff --git a/site/src/cut/lib/speedCurveUi.ts b/site/src/cut/lib/speedCurveUi.ts
deleted file mode 100644
index 1a495b77..00000000
--- a/site/src/cut/lib/speedCurveUi.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-"use client";
-
-import { create } from "zustand";
-
-/**
- * Which clips have their speed curve open in the strip over the timeline.
- * The Inspector's Speed row opens a clip's curve and the strip closes it.
- * Every clip keeps its own state: selecting another clip hides the strip
- * and leaves the curve open, so coming back to the clip brings the graph
- * back until it is closed. A clip going away drops its entry.
- */
-interface SpeedCurveUi {
- open: ReadonlySet<string>;
- openFor: (clipId: string) => void;
- close: (clipId: string) => void;
-}
-
-export const useSpeedCurveUi = create<SpeedCurveUi>((set) => ({
- open: new Set(),
- openFor: (clipId) => set((s) => ({ open: new Set(s.open).add(clipId) })),
- close: (clipId) =>
- set((s) => {
- if (!s.open.has(clipId)) return s;
- const open = new Set(s.open);
- open.delete(clipId);
- return { open };
- }),
-}));