Skip to content

Commit bc73c41

Browse files
feat(studio): let a host app mount the timeline toolbar, undo buttons, meters and clipboard (#4629)
* feat(studio): let a host app mount the timeline toolbar, undo buttons, meters and clipboard * test(studio): lock in history button rules and trim duplicate export tests
1 parent 04d56d0 commit bc73c41

11 files changed

Lines changed: 235 additions & 38 deletions

‎packages/studio/src/components/TimelineHistoryButtons.dom.test.tsx‎

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,10 @@ const handleUndo = vi.fn();
1616
const handleRedo = vi.fn();
1717
const trackStudioEvent = vi.fn();
1818

19+
const studioShell = { editHistory, handleUndo, handleRedo };
20+
let shell: typeof studioShell | null = studioShell;
1921
vi.mock("../contexts/StudioContext", () => ({
20-
useStudioShellContext: () => ({ editHistory, handleUndo, handleRedo }),
22+
useStudioShellContextOptional: () => shell,
2123
}));
2224
vi.mock("../utils/studioTelemetry", () => ({ trackStudioEvent }));
2325

@@ -31,6 +33,7 @@ beforeEach(() => {
3133
undoLabel: undefined,
3234
redoLabel: undefined,
3335
});
36+
shell = studioShell;
3437
vi.clearAllMocks();
3538
});
3639

@@ -115,3 +118,37 @@ it("classifies Undo and Redo for the hotkey filters at their new location (KTD13
115118
expect(shouldIgnorePlaybackShortcutTarget(el), label).toBe(true);
116119
}
117120
});
121+
122+
it("takes a host's history props over the shell's", async () => {
123+
editHistory.canUndo = true;
124+
editHistory.redoLabel = "shell move";
125+
const onUndo = vi.fn();
126+
const onRedo = vi.fn();
127+
const host = mount(
128+
<TimelineHistoryButtons
129+
canUndo={false}
130+
canRedo
131+
redoLabel="host trim"
132+
onUndo={onUndo}
133+
onRedo={onRedo}
134+
/>,
135+
);
136+
137+
expect(button(host, "Undo").disabled).toBe(true);
138+
act(() => button(host, "Redo").focus());
139+
await act(async () => {
140+
await new Promise((resolve) => setTimeout(resolve, 0));
141+
});
142+
expect(document.querySelector('[role="tooltip"]')?.textContent).toContain("Redo host trim");
143+
click(button(host, "Redo"));
144+
145+
expect(onRedo).toHaveBeenCalledTimes(1);
146+
expect(handleRedo).not.toHaveBeenCalled();
147+
});
148+
149+
it("keeps a button disabled when it has no handler, whatever canUndo/canRedo say", () => {
150+
shell = null;
151+
const host = mount(<TimelineHistoryButtons canUndo canRedo />);
152+
153+
for (const label of ["Undo", "Redo"]) expect(button(host, label).disabled).toBe(true);
154+
});

‎packages/studio/src/components/TimelineHistoryButtons.tsx‎

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useStudioShellContext } from "../contexts/StudioContext";
1+
import { useStudioShellContextOptional } from "../contexts/StudioContext";
22
import { RotateCcw, RotateCw } from "../icons/SystemIcons";
33
import { trackStudioEvent } from "../utils/studioTelemetry";
44
import { historyTooltipLabel } from "../utils/studioHelpers";
@@ -7,13 +7,14 @@ import { Tooltip } from "./ui";
77

88
interface HistoryButtonProps {
99
action: "undo" | "redo";
10-
enabled: boolean;
10+
can: boolean;
1111
label: string | undefined;
12-
onClick: () => Promise<void> | void;
12+
onClick: (() => Promise<void> | void) | undefined;
1313
}
1414

15-
function HistoryButton({ action, enabled, label, onClick }: HistoryButtonProps) {
15+
function HistoryButton({ action, can, label, onClick }: HistoryButtonProps) {
1616
const Icon = action === "undo" ? RotateCcw : RotateCw;
17+
const enabled = Boolean(onClick) && can;
1718
return (
1819
<Tooltip label={historyTooltipLabel(action, label)}>
1920
<button
@@ -23,7 +24,7 @@ function HistoryButton({ action, enabled, label, onClick }: HistoryButtonProps)
2324
className={enabled ? flatIdle : flatDisabled}
2425
onClick={() => {
2526
trackStudioEvent("toolbar_action", { action });
26-
void onClick();
27+
void onClick?.();
2728
}}
2829
>
2930
<Icon size={16} />
@@ -32,22 +33,33 @@ function HistoryButton({ action, enabled, label, onClick }: HistoryButtonProps)
3233
);
3334
}
3435

35-
/** Undo and Redo, on the one edit-history path the shell already owns. */
36-
export function TimelineHistoryButtons() {
37-
const { editHistory, handleUndo, handleRedo } = useStudioShellContext();
36+
export interface TimelineHistoryButtonsProps {
37+
canUndo?: boolean;
38+
canRedo?: boolean;
39+
undoLabel?: string;
40+
redoLabel?: string;
41+
onUndo?: () => Promise<void> | void;
42+
onRedo?: () => Promise<void> | void;
43+
}
44+
45+
/** Undo and Redo: a host's props win, else the shell's edit history. */
46+
export function TimelineHistoryButtons(props: TimelineHistoryButtonsProps) {
47+
const shell = useStudioShellContextOptional();
48+
const onUndo = props.onUndo ?? shell?.handleUndo;
49+
const onRedo = props.onRedo ?? shell?.handleRedo;
3850
return (
3951
<>
4052
<HistoryButton
4153
action="undo"
42-
enabled={editHistory.canUndo}
43-
label={editHistory.undoLabel}
44-
onClick={handleUndo}
54+
can={props.canUndo ?? shell?.editHistory.canUndo ?? false}
55+
label={props.undoLabel ?? shell?.editHistory.undoLabel}
56+
onClick={onUndo}
4557
/>
4658
<HistoryButton
4759
action="redo"
48-
enabled={editHistory.canRedo}
49-
label={editHistory.redoLabel}
50-
onClick={handleRedo}
60+
can={props.canRedo ?? shell?.editHistory.canRedo ?? false}
61+
label={props.redoLabel ?? shell?.editHistory.redoLabel}
62+
onClick={onRedo}
5163
/>
5264
</>
5365
);

‎packages/studio/src/components/TimelineToolbar.test.tsx‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import { AudioMeterStrip } from "./nle/AudioMeterStrip";
1212
import { TimelineToolbar } from "./TimelineToolbar";
1313

1414
vi.mock("../contexts/StudioContext", () => ({
15-
useStudioShellContext: () => ({
15+
useStudioShellContextOptional: () => ({
1616
previewIframeRef: { current: null },
1717
editHistory: { canUndo: false, canRedo: false },
1818
handleUndo: vi.fn(),
@@ -214,3 +214,11 @@ describe("TimelineToolbar audio meters", () => {
214214
}
215215
});
216216
});
217+
218+
describe("TimelineToolbar add beat", () => {
219+
it("shows Add beat by default, as Studio does", () => {
220+
const { host, root } = renderToolbar();
221+
expect(host.querySelector('button[aria-label="Add beat at playhead"]')).not.toBeNull();
222+
act(() => root.unmount());
223+
});
224+
});

‎packages/studio/src/components/TimelineToolbar.tsx‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import { Tooltip } from "./ui";
1919
import { AudioMetersIcon } from "./icons/AudioMetersIcon";
2020
import { RippleEditIcon } from "./icons/RippleEditIcon";
2121
import { flatActive, flatBtn, flatDisabled, flatIdle } from "./timelineToolbarStyles";
22-
import { TimelineHistoryButtons } from "./TimelineHistoryButtons";
22+
import { TimelineHistoryButtons, type TimelineHistoryButtonsProps } from "./TimelineHistoryButtons";
2323
import { Scissors } from "../icons/SystemIcons";
2424
import type { GsapAnimation } from "@hyperframes/core/gsap-parser";
2525
import type { DomEditSelection } from "./editor/domEditingTypes";
@@ -33,9 +33,11 @@ interface DomEditSessionSlice extends EnableKeyframesSession {
3333
selectedGsapAnimations: GsapAnimation[];
3434
}
3535

36-
interface TimelineToolbarProps {
36+
export interface TimelineToolbarProps {
3737
domEditSession?: DomEditSessionSlice;
3838
onSplitElement?: (element: TimelineElement, splitTime: number) => void;
39+
history?: TimelineHistoryButtonsProps;
40+
showAddBeat?: boolean;
3941
}
4042

4143
interface KeyframeToggleState {
@@ -127,7 +129,12 @@ function useKeyframeToggle(session?: DomEditSessionSlice) {
127129
}
128130

129131
// fallow-ignore-next-line complexity
130-
export function TimelineToolbar({ domEditSession, onSplitElement }: TimelineToolbarProps) {
132+
export function TimelineToolbar({
133+
domEditSession,
134+
onSplitElement,
135+
history,
136+
showAddBeat = true,
137+
}: TimelineToolbarProps) {
131138
const activeTool = usePlayerStore((s) => s.activeTool);
132139
const setActiveTool = usePlayerStore((s) => s.setActiveTool);
133140
const timelineSnapEnabled = usePlayerStore((s) => s.timelineSnapEnabled);
@@ -195,7 +202,7 @@ export function TimelineToolbar({ domEditSession, onSplitElement }: TimelineTool
195202
<div className="border-b border-neutral-800/60">
196203
<div className="flex items-center justify-between px-2 py-0.5">
197204
<div className="flex items-center gap-0.5">
198-
<TimelineHistoryButtons />
205+
<TimelineHistoryButtons {...history} />
199206
<Tooltip label="Selection tool (V)">
200207
<button
201208
type="button"
@@ -416,7 +423,8 @@ export function TimelineToolbar({ domEditSession, onSplitElement }: TimelineTool
416423
);
417424
})()}
418425
{(() => {
419-
// Always rendered (CapCut-style): before beat analysis loads (or when
426+
if (!showAddBeat) return null;
427+
// Rendered whenever shown (CapCut-style): before beat analysis loads (or when
420428
// the project has no analyzed music) the button fades to a disabled
421429
// state instead of unmounting, so the toolbar layout never shifts.
422430
const canAdd = beatAnalysisReady && canAddBeatAt(currentTime);

‎packages/studio/src/components/nle/AudioMeterStrip.test.tsx‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { useAudioMetersVisible } from "../../utils/audioMeterVisibility";
1111
import { SILENT_CHANNEL } from "../../utils/audioMeterMath";
1212
import {
1313
AudioMeterStrip,
14+
type AudioMeterStripProps,
1415
evictGoneMeterState,
1516
followMeterHook,
1617
stepAndPaintStrips,
@@ -20,8 +21,9 @@ import {
2021

2122
const iframe = { contentWindow: null as unknown };
2223
const previewIframeRef = { current: iframe };
24+
let shell: { previewIframeRef: typeof previewIframeRef } | null = { previewIframeRef };
2325
vi.mock("../../contexts/StudioContext", () => ({
24-
useStudioShellContext: () => ({ previewIframeRef }),
26+
useStudioShellContextOptional: () => shell,
2527
}));
2628

2729
const onSetAudioGroupAttributeLive = vi.fn();
@@ -88,6 +90,7 @@ const tick = () => {
8890
};
8991

9092
beforeEach(() => {
93+
shell = { previewIframeRef };
9194
frames = [];
9295
vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => frames.push(cb));
9396
vi.stubGlobal("cancelAnimationFrame", () => {});
@@ -103,11 +106,11 @@ afterEach(() => {
103106
vi.unstubAllGlobals();
104107
});
105108

106-
function mount() {
109+
function mount(props: AudioMeterStripProps = {}) {
107110
const host = document.createElement("div");
108111
document.body.append(host);
109112
const root = createRoot(host);
110-
act(() => root.render(<AudioMeterStrip />));
113+
act(() => root.render(<AudioMeterStrip {...props} />));
111114
roots.push(root);
112115
return { host, root };
113116
}
@@ -177,6 +180,26 @@ describe("AudioMeterStrip", () => {
177180
expect(second.read).toHaveBeenCalled();
178181
});
179182

183+
it("reads a host's preview iframe over the shell's", () => {
184+
usePlayerStore.setState({ elements: [clip({ audioGroup: "vo" })] });
185+
const shellHook = makeHook();
186+
setHook(shellHook);
187+
const hostHook = makeHook();
188+
const hostIframe = { contentWindow: { __hf: { audioMeter: hostHook } } };
189+
mount({ previewIframeRef: { current: hostIframe as unknown as HTMLIFrameElement } });
190+
tick();
191+
expect(hostHook.start).toHaveBeenCalledTimes(1);
192+
expect(shellHook.start).not.toHaveBeenCalled();
193+
});
194+
195+
it("mounts with no shell and no preview iframe", () => {
196+
shell = null;
197+
usePlayerStore.setState({ elements: [clip({ audioGroup: "vo" })] });
198+
const { host } = mount();
199+
tick();
200+
expect(host.querySelector("[data-testid=audio-meter-strip]")).not.toBeNull();
201+
});
202+
180203
it("keeps authored gain 2 above unity and writes exactly 1 at the midpoint", () => {
181204
usePlayerStore.setState({ elements: [clip({ audioGroup: "vo", audioGroupVolume: 2 })] });
182205
const { host } = mount();

‎packages/studio/src/components/nle/AudioMeterStrip.tsx‎

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ import type { StereoLevel } from "@hyperframes/core/runtime/levelTap";
2020
import { usePlayerStore } from "../../player";
2121
import { clampNumber } from "../../utils/studioHelpers";
2222
import { useAudioMetersVisible } from "../../utils/audioMeterVisibility";
23-
import { useStudioShellContext } from "../../contexts/StudioContext";
23+
import { useStudioShellContextOptional } from "../../contexts/StudioContext";
2424
import { useTimelineEditContextOptional } from "../../contexts/TimelineEditContext";
2525
import {
2626
METER_DB_MARKS,
@@ -107,7 +107,7 @@ function useVolumeHandlers(): {
107107

108108
type PreviewWindow = (Window & { __hf?: { audioMeter?: AudioMeterHook } }) | null | undefined;
109109

110-
function readHook(iframe: HTMLIFrameElement | null): AudioMeterHook | null {
110+
function readHook(iframe: HTMLIFrameElement | null | undefined): AudioMeterHook | null {
111111
try {
112112
return (iframe?.contentWindow as PreviewWindow)?.__hf?.audioMeter ?? null;
113113
} catch {
@@ -123,9 +123,8 @@ function paintPeak(el: HTMLElement | null, peak: number): void {
123123
el.style.setProperty("transform", peak >= 1 ? "translateY(1px)" : "none");
124124
}
125125

126-
/** The fill is a fixed green/amber/red backdrop; painting only moves the dark
127-
* mask that covers the unlit top portion, so a loud peak lights the real red
128-
* band instead of tinting a flat colour brighter. */
126+
/** The fill is a fixed green/amber/red backdrop; painting only moves the dark mask that covers the unlit top
127+
* portion, so a loud peak lights the real red band instead of tinting a flat colour brighter. */
129128
function paint(bars: StripBars | undefined, channels: Pair): void {
130129
channels.forEach((ch, i) => {
131130
bars?.[i]?.mask?.style.setProperty("height", `${(1 - ch.level) * 100}%`);
@@ -179,8 +178,13 @@ export function stepAndPaintStrips(
179178
}
180179

181180
/** One rAF loop re-reads the hook off the live preview window, so a reloaded iframe is followed. */
182-
function useMeterLoop(strips: Strip[], bars: RefObject<Map<string | null, StripBars>>) {
183-
const { previewIframeRef } = useStudioShellContext();
181+
function useMeterLoop(
182+
strips: Strip[],
183+
bars: RefObject<Map<string | null, StripBars>>,
184+
iframeRef: RefObject<HTMLIFrameElement | null> | undefined,
185+
) {
186+
const shell = useStudioShellContextOptional();
187+
const previewIframeRef = iframeRef ?? shell?.previewIframeRef;
184188
const stripsRef = useRef(strips);
185189
stripsRef.current = strips;
186190
useEffect(() => {
@@ -190,7 +194,7 @@ function useMeterLoop(strips: Strip[], bars: RefObject<Map<string | null, StripB
190194
const state = new Map<string | null, Pair>();
191195
const tick = (now: number) => {
192196
raf = requestAnimationFrame(tick);
193-
active = followMeterHook(active, readHook(previewIframeRef.current));
197+
active = followMeterHook(active, readHook(previewIframeRef?.current));
194198
const levels = active?.read();
195199
const dt = now - last;
196200
last = now;
@@ -395,22 +399,29 @@ function MeterStrip({
395399
);
396400
}
397401

398-
export const AudioMeterStrip = memo(function AudioMeterStrip() {
402+
export interface AudioMeterStripProps {
403+
/** Pass a stable ref (useRef): a new object each render restarts the meter loop. */
404+
previewIframeRef?: RefObject<HTMLIFrameElement | null>;
405+
}
406+
407+
export const AudioMeterStrip = memo(function AudioMeterStrip({
408+
previewIframeRef,
409+
}: AudioMeterStripProps) {
399410
const visible = useAudioMetersVisible((s) => s.visible);
400411
const projectHasAudio = useProjectHasAudio();
401412
if (!visible || !projectHasAudio) return null;
402-
return <MeterStripBody />;
413+
return <MeterStripBody previewIframeRef={previewIframeRef} />;
403414
});
404415

405-
function MeterStripBody() {
416+
function MeterStripBody({ previewIframeRef }: AudioMeterStripProps) {
406417
const strips = useStrips();
407418
const bars = useRef(new Map<string | null, StripBars>());
408419
const register = useRef((id: string | null, b: StripBars | null) => {
409420
if (b) bars.current.set(id, b);
410421
else bars.current.delete(id);
411422
}).current;
412423
const { onLive, onCommit } = useVolumeHandlers();
413-
useMeterLoop(strips, bars);
424+
useMeterLoop(strips, bars, previewIframeRef);
414425
return (
415426
<div
416427
data-testid="audio-meter-strip"

‎packages/studio/src/components/pointerTargetSize.test.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { CompositionsTab } from "./sidebar/CompositionsTab";
77
import { TimelineToolbar } from "./TimelineToolbar";
88

99
vi.mock("../contexts/StudioContext", () => ({
10-
useStudioShellContext: () => ({
10+
useStudioShellContextOptional: () => ({
1111
editHistory: { canUndo: false, canRedo: false },
1212
handleUndo: vi.fn(),
1313
handleRedo: vi.fn(),

‎packages/studio/src/hooks/useClipboard.source.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,3 +338,14 @@ describe("a copy that fails", () => {
338338
expect(deleted).toEqual([]);
339339
});
340340
});
341+
342+
describe("with no DOM edit session", () => {
343+
it("refuses copy, cut and duplicate when nothing is selected", async () => {
344+
clearSelection();
345+
const { clipboard, deleted } = mountClipboard();
346+
expect(clipboard().handleCopy()).toBe(false);
347+
expect(await clipboard().handleCut()).toBe(false);
348+
expect(await clipboard().handleDuplicate()).toBe(false);
349+
expect(deleted).toEqual([]);
350+
});
351+
});

‎packages/studio/src/hooks/useClipboard.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ interface RecordEditInput {
3333
files: Record<string, { before: string; after: string }>;
3434
}
3535

36-
interface UseClipboardOptions {
36+
export interface UseClipboardOptions {
3737
projectId: string | null;
3838
activeCompPath: string | null;
3939
domEditSelectionRef: React.MutableRefObject<DomEditSelection | null>;

0 commit comments

Comments
 (0)