Skip to content

Commit 93ab289

Browse files
feat(studio): let a host app keep paint order in step with timeline rows (#4647)
* feat(studio): let a host app keep paint order in step with timeline rows * docs(studio): say each stacking sync prop overrides separately
1 parent 26bfd38 commit 93ab289

6 files changed

Lines changed: 142 additions & 13 deletions

File tree

‎packages/studio/src/index.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,10 @@ export { parseStyleString, mergeStyleIntoTag, findElementBlock } from "./utils/h
154154
export { usePersistentEditHistory } from "./hooks/usePersistentEditHistory";
155155
export type { UsePersistentEditHistoryOptions } from "./hooks/usePersistentEditHistory";
156156
export { useTimelineEditing } from "./hooks/useTimelineEditing";
157-
export type { UseTimelineEditingOptions } from "./hooks/useTimelineEditingTypes";
157+
export type {
158+
TimelineZIndexReorderCommit,
159+
UseTimelineEditingOptions,
160+
} from "./hooks/useTimelineEditingTypes";
158161
// A host's own waitForPendingDomEditSaves must also call this, or undo/redo
159162
// can race a write still in flight (see useTrackPendingTimelineEdit.ts).
160163
export { flushStudioPendingEdits } from "./utils/studioPendingEdits";

‎packages/studio/src/player/components/TimelineTypes.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,15 @@ import type { TimelineTimeRange } from "../store/rangeSelectionSlice";
44
import type { TimelineDropCallbacks } from "./timelineCallbacks";
55
import type { TimelineTheme } from "./timelineTheme";
66
import type { TimelineEditOverrides } from "./useResolvedTimelineEditCallbacks";
7+
import type { TimelineStackingSyncProps } from "./useTimelineStackingSync";
78

89
export interface TimelineClipRenderContext {
910
priority: "overscan" | "visible" | "interaction";
1011
rich: boolean;
1112
}
1213

13-
export interface TimelineProps extends TimelineDropCallbacks, TimelineEditOverrides {
14+
export interface TimelineProps
15+
extends TimelineDropCallbacks, TimelineEditOverrides, TimelineStackingSyncProps {
1416
/** Project-scoped reset boundary; soft source refreshes retain the same epoch. */
1517
sessionEpoch?: number;
1618
onSeek?: (time: number, options?: { keepPlaying?: boolean }) => void;

‎packages/studio/src/player/components/useTimelineProviderState.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ export function useTimelineProviderState({
7171
canPasteClip,
7272
theme: themeOverrides,
7373
sessionEpoch = 0,
74+
previewIframeRef,
75+
onZIndexReorder,
7476
}: TimelineProps = {}): TimelineContextValue {
7577
const {
7678
onMoveElement,
@@ -184,6 +186,8 @@ export function useTimelineProviderState({
184186
});
185187
const { readClipZIndex, applyStackingPatches, zSyncEnabled } = useTimelineStackingSync({
186188
expandedElementsRef: timelineElementsRef,
189+
previewIframeRef,
190+
onZIndexReorder,
187191
});
188192
const {
189193
draggedClip,

‎packages/studio/src/player/components/useTimelineStackingSync.test.tsx‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,4 +73,50 @@ describe("useTimelineStackingSync", () => {
7373
mocks.actions = null;
7474
iframe.remove();
7575
});
76+
77+
it("uses a host's iframe and commit over Studio's own", async () => {
78+
const studioCommit = vi.fn().mockResolvedValue(undefined);
79+
mocks.actions = {
80+
previewIframeRef: { current: null },
81+
handleDomZIndexReorderCommit: studioCommit,
82+
};
83+
const iframe = document.createElement("iframe");
84+
document.body.appendChild(iframe);
85+
const node = iframe.contentDocument!.createElement("div");
86+
node.id = "a";
87+
iframe.contentDocument!.body.appendChild(node);
88+
const hostCommit = vi.fn().mockResolvedValue(undefined);
89+
const element: TimelineElement = {
90+
id: "a",
91+
key: "a",
92+
tag: "div",
93+
start: 0,
94+
duration: 2,
95+
track: 0,
96+
};
97+
let sync: ReturnType<typeof useTimelineStackingSync> | null = null;
98+
function Harness() {
99+
sync = useTimelineStackingSync({
100+
expandedElementsRef: { current: [element] },
101+
previewIframeRef: { current: iframe },
102+
onZIndexReorder: hostCommit,
103+
});
104+
return null;
105+
}
106+
const root = mountReactHarness(<Harness />);
107+
108+
await act(async () => {
109+
await sync!.applyStackingPatches([{ key: "a", zIndex: 3 }]);
110+
});
111+
112+
expect(sync!.zSyncEnabled).toBe(true);
113+
expect(hostCommit).toHaveBeenCalledWith(
114+
[expect.objectContaining({ element: node, zIndex: 3 })],
115+
undefined,
116+
);
117+
expect(studioCommit).not.toHaveBeenCalled();
118+
act(() => root.unmount());
119+
mocks.actions = null;
120+
iframe.remove();
121+
});
76122
});

‎packages/studio/src/player/components/useTimelineStackingSync.ts‎

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,30 @@ import { useStudioShellContextOptional } from "../../contexts/StudioContext";
55
import { findElementForSelection } from "../../components/editor/domEditingElement";
66
import { readEffectiveZIndex } from "../../components/editor/canvasContextMenuZOrder";
77
import type { StackingPatch } from "./timelineStackingSync";
8+
import type { TimelineZIndexReorderCommit } from "../../hooks/useTimelineEditingTypes";
89

9-
interface UseTimelineStackingSyncInput {
10+
/** With both set, a lane move restacks the preview's z-index to match the rows; each overrides Studio's own. */
11+
export interface TimelineStackingSyncProps {
12+
previewIframeRef?: RefObject<HTMLIFrameElement | null>;
13+
onZIndexReorder?: TimelineZIndexReorderCommit;
14+
}
15+
16+
interface UseTimelineStackingSyncInput extends TimelineStackingSyncProps {
1017
expandedElementsRef: RefObject<TimelineElement[]>;
1118
}
1219

13-
// Lane ↔ stacking unification (research/STAGE3-NEEDED-WIRING.md). Provision the
14-
// two deps commitDraggedClipMove accepts so a lane-change drag also patches the
15-
// edited clip's z-index. Both read the SAME preview iframe + z-order persist path
16-
// the canvas right-click menu / LayersPanel use, so a timeline lane move and a
17-
// menu z-edit produce one shared inline-style commit shape. Optional contexts:
18-
// outside the NLE (standalone <Timeline>) these are null ⇒ deps undefined ⇒ the
19-
// commit's z-sync is a no-op (backward compatible).
20-
export function useTimelineStackingSync({ expandedElementsRef }: UseTimelineStackingSyncInput) {
20+
// Lane ↔ stacking sync: the two deps commitDraggedClipMove takes so a lane-change drag also patches
21+
// z-index, through the same iframe + z persist path the canvas menu and LayersPanel use. Either missing ⇒ no-op.
22+
export function useTimelineStackingSync({
23+
expandedElementsRef,
24+
previewIframeRef,
25+
onZIndexReorder,
26+
}: UseTimelineStackingSyncInput) {
2127
const domEditActions = useDomEditActionsContextOptional();
2228
const shell = useStudioShellContextOptional();
23-
const zSyncPreviewIframeRef = domEditActions?.previewIframeRef ?? null;
24-
const handleDomZIndexReorderCommit = domEditActions?.handleDomZIndexReorderCommit;
29+
const zSyncPreviewIframeRef = previewIframeRef ?? domEditActions?.previewIframeRef ?? null;
30+
const handleDomZIndexReorderCommit =
31+
onZIndexReorder ?? domEditActions?.handleDomZIndexReorderCommit;
2532
const zSyncActiveCompPath = shell?.activeCompPath ?? null;
2633

2734
// Resolve a TimelineElement to its live iframe HTMLElement via the same
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
// @vitest-environment happy-dom
2+
// Mounts the timeline by package name with no Studio shell, as a host app does.
3+
import { act } from "react";
4+
import { expect, it, vi } from "vitest";
5+
import { Timeline, usePlayerStore, type TimelineZIndexReorderCommit } from "@hyperframes/studio";
6+
import { installReactActEnvironment, mountReactHarness } from "./hooks/domSelectionTestHarness";
7+
8+
installReactActEnvironment();
9+
// happy-dom has no layout; the timeline only renders clips inside a sized viewport.
10+
for (const [prop, px] of [
11+
["clientWidth", 1000],
12+
["clientHeight", 400],
13+
["offsetWidth", 1000],
14+
["offsetHeight", 400],
15+
] as const) {
16+
vi.spyOn(HTMLElement.prototype, prop, "get").mockReturnValue(px);
17+
}
18+
19+
const settle = () => act(async () => new Promise((r) => setTimeout(r, 50)));
20+
const pointer = (type: string, clientY: number) =>
21+
new PointerEvent(type, { bubbles: true, button: 0, pointerId: 1, clientX: 150, clientY });
22+
23+
it("restacks the host's preview when a lane move puts a clip below another", async () => {
24+
const iframe = document.createElement("iframe");
25+
document.body.appendChild(iframe);
26+
const doc = iframe.contentDocument!;
27+
// No authored z: DOM order paints tag over title, which matches the rows until the move.
28+
doc.body.innerHTML = '<div id="title"></div><div id="tag"></div><div id="note"></div>';
29+
const clip = (id: string, start: number, duration: number, track: number) =>
30+
({ id, key: id, domId: id, tag: "div", start, duration, track }) as const;
31+
usePlayerStore.setState({
32+
duration: 10,
33+
timelineReady: true,
34+
elements: [clip("title", 0, 4, 1), clip("tag", 0, 4, 0), clip("note", 6, 2, 2)],
35+
});
36+
const commit = vi.fn<TimelineZIndexReorderCommit>(async (entries) => {
37+
for (const e of entries) e.element.style.zIndex = String(e.zIndex);
38+
});
39+
const root = mountReactHarness(
40+
<Timeline
41+
previewIframeRef={{ current: iframe }}
42+
onZIndexReorder={commit}
43+
onMoveElement={async () => {}}
44+
onMoveElements={async () => {}}
45+
/>,
46+
);
47+
await settle();
48+
const tagClip = document.querySelector<HTMLElement>('.timeline-clip[aria-label^="tag,"]')!;
49+
vi.spyOn(tagClip, "getBoundingClientRect").mockReturnValue(new DOMRect(80, 77, 360, 42));
50+
51+
// Drag tag from the top row to the bottom row, clear of note in time.
52+
act(() => void tagClip.dispatchEvent(pointer("pointerdown", 98)));
53+
act(() => {
54+
window.dispatchEvent(pointer("pointermove", 140));
55+
window.dispatchEvent(pointer("pointermove", 194));
56+
});
57+
await act(async () => void window.dispatchEvent(pointer("pointerup", 194)));
58+
await settle();
59+
60+
expect(usePlayerStore.getState().elements.find((e) => e.id === "tag")?.track).toBe(2);
61+
expect(commit).toHaveBeenCalledTimes(1);
62+
expect(commit.mock.calls[0]![0].every((e) => e.element.ownerDocument === doc)).toBe(true);
63+
const z = (id: string) => Number(doc.getElementById(id)!.style.zIndex || 0);
64+
expect(z("title")).toBeGreaterThan(z("tag"));
65+
await act(async () => root.unmount());
66+
usePlayerStore.setState({ elements: [], timelineReady: false });
67+
});

0 commit comments

Comments
 (0)