@hyperframes/studio 0.9.40 → 0.9.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/assets/{codec-BPK_2CLL.js → codec-B_mpbc4w.js} +1 -1
  2. package/dist/assets/{hyperframes-player-D7qTTDIp.js → hyperframes-player-Dvi3I_mv.js} +1 -1
  3. package/dist/assets/{index-CdA00Ybn.js → index-B5ExwsOp.js} +146 -146
  4. package/dist/assets/{index-QS-DuxAU.js → index-BrFm9Y5k.js} +1 -1
  5. package/dist/assets/{pausedVideoDecoder-Byzz98Gb.js → pausedVideoDecoder-MHQ57yZ6.js} +1 -1
  6. package/dist/{chunk-KF6YVXJP.js → chunk-4QQMX4BX.js} +6 -3
  7. package/dist/{chunk-VZ5MD32A.js → chunk-GVW7AU57.js} +190 -254
  8. package/dist/{chunk-AV2PV7NE.js → chunk-VHV2ZDKY.js} +4 -40
  9. package/dist/{domEditingLayers-4KRREI5C.js → domEditingLayers-SA5KLSSS.js} +4 -2
  10. package/dist/index.d.ts +4 -0
  11. package/dist/index.html +1 -1
  12. package/dist/index.js +898 -551
  13. package/dist/player.js +2 -2
  14. package/package.json +8 -8
  15. package/src/components/editor/DomEditOverlay.tsx +3 -15
  16. package/src/components/editor/clickAfterPreventedPress.test.tsx +17 -1
  17. package/src/components/editor/domEditOverlayBasis.ts +7 -2
  18. package/src/components/editor/domEditOverlayCrop.test.ts +1 -1
  19. package/src/components/editor/domEditOverlayCrop.ts +17 -3
  20. package/src/components/editor/domEditOverlayGeometry.ts +64 -139
  21. package/src/components/editor/domEditSelectionRules.ts +138 -0
  22. package/src/components/editor/domEditing.test.ts +6 -28
  23. package/src/components/editor/domEditingDom.preview.test.ts +3 -3
  24. package/src/components/editor/domEditingDom.ts +3 -76
  25. package/src/components/editor/domEditingElement.ts +19 -240
  26. package/src/components/editor/domEditingGroups.ts +0 -31
  27. package/src/components/editor/domEditingLayers.ts +95 -100
  28. package/src/components/editor/domEditingRootLayer.ts +35 -30
  29. package/src/components/editor/domEditingTypes.ts +4 -0
  30. package/src/components/editor/previewGestureStarts.ts +73 -10
  31. package/src/components/editor/previewOverlayRects.test.ts +316 -0
  32. package/src/components/editor/previewOverlayRects.ts +123 -0
  33. package/src/components/editor/previewPointerTargets.test.ts +260 -0
  34. package/src/components/editor/previewSelection.test.ts +481 -0
  35. package/src/components/editor/previewSelection.ts +472 -0
  36. package/src/components/editor/probeSourceElement.ts +19 -1
  37. package/src/components/editor/propertyPanelFill.tsx +5 -1
  38. package/src/components/editor/useDomEditOverlayRects.ts +80 -1
  39. package/src/components/editor/useInlineTextEditing.tsx +1 -6
  40. package/src/hooks/domSelectionTestHarness.ts +1 -1
  41. package/src/hooks/useDomEditSession.test.tsx +23 -1
  42. package/src/hooks/useDomEditSession.ts +2 -1
  43. package/src/hooks/useDomSelection.ts +61 -47
  44. package/src/hooks/useGsapSelectionHandlers.test.tsx +17 -0
  45. package/src/hooks/useGsapSelectionHandlers.ts +2 -1
  46. package/src/hooks/usePreviewInteraction.test.ts +10 -2
  47. package/src/hooks/usePreviewInteraction.ts +5 -4
  48. package/src/hooks/useStudioSelectionPublisher.test.tsx +50 -0
  49. package/src/hooks/useStudioSelectionPublisher.ts +9 -7
  50. package/src/player/lib/previewChannel.ts +4 -3
  51. package/src/player/lib/previewElements.ts +112 -3
  52. package/src/styles/hex-baseline.json +1 -2
  53. package/src/utils/studioHelpers.ts +0 -13
  54. package/src/utils/studioPreviewHelpers.test.ts +8 -8
  55. package/src/utils/studioPreviewHelpers.ts +26 -242
  56. package/src/components/editor/domEditOverlayTransform.ts +0 -126
@@ -0,0 +1,481 @@
1
+ // @vitest-environment happy-dom
2
+
3
+ import React, { act } from "react";
4
+ import { createRoot } from "react-dom/client";
5
+ import { afterEach, describe, expect, it, vi } from "vitest";
6
+ import { EDITING_ELEMENT_HANDLE, MAX_ELEMENT_TEXT } from "@hyperframes/core/runtime/editing-port";
7
+ // The frame's real runtime agent, serving the opaque frame from this document.
8
+ import { installEditingAgent } from "../../../../core/src/runtime/editingAgent";
9
+ import {
10
+ findElementForSelection,
11
+ findElementForTimelineElement,
12
+ resolveDomEditSelection,
13
+ type DomEditSelection,
14
+ } from "./domEditing";
15
+ import { setCompositionSourceMap } from "./domEditingDom";
16
+ import { domEditSelectionToFacts } from "./domEditingLayers";
17
+ import {
18
+ findPreviewElementForSelection,
19
+ findPreviewElementForTimelineElement,
20
+ resolvePreviewSelection,
21
+ type PreviewSelectionOptions,
22
+ } from "./previewSelection";
23
+ import {
24
+ describePreviewElements,
25
+ previewElementsAtPoint,
26
+ type PreviewElement,
27
+ } from "../../player/lib/previewElements";
28
+ import { detachedFakeIframe } from "../../player/hooks/timelinePlayerTestHarness";
29
+ import { installReactActEnvironment } from "../../hooks/domSelectionTestHarness";
30
+ import { useDomSelection } from "../../hooks/useDomSelection";
31
+ import type { TimelineElement } from "../../player";
32
+
33
+ installReactActEnvironment();
34
+
35
+ const selectLog = vi.hoisted(() => ({ on: null as null | ((event: string) => void) }));
36
+ vi.mock("../../utils/selectDebug", () => ({
37
+ logSelect: (event: string) => selectLog.on?.(event),
38
+ }));
39
+
40
+ const closers: Array<() => void> = [];
41
+ afterEach(() => {
42
+ closers.splice(0).forEach((close) => close());
43
+ setCompositionSourceMap(new Map());
44
+ document.body.innerHTML = "";
45
+ delete (document as { elementsFromPoint?: unknown }).elementsFromPoint;
46
+ });
47
+
48
+ /** A frame Studio scripts directly; its document is this one. */
49
+ function liveFrame(): HTMLIFrameElement {
50
+ const iframe = detachedFakeIframe({});
51
+ Object.defineProperty(iframe, "contentDocument", { value: document });
52
+ return iframe;
53
+ }
54
+
55
+ /** A frame Studio cannot read, whose runtime is the real editing agent over this document. */
56
+ function opaqueFrame(): HTMLIFrameElement {
57
+ const frame: Record<string, unknown> = {};
58
+ const iframe = detachedFakeIframe(frame);
59
+ Object.defineProperty(iframe, "contentDocument", { value: null });
60
+ Object.defineProperty(frame, "document", {
61
+ get: () => {
62
+ throw new DOMException("blocked", "SecurityError");
63
+ },
64
+ });
65
+ const parent = {
66
+ postMessage: (data: unknown, _origin: string, ports: MessagePort[]) =>
67
+ window.dispatchEvent(
68
+ new MessageEvent("message", { source: frame as unknown as Window, data, ports }),
69
+ ),
70
+ } as unknown as Window;
71
+ const agent = installEditingAgent(parent);
72
+ frame.postMessage = (data: unknown) =>
73
+ window.dispatchEvent(new MessageEvent("message", { source: parent, data }));
74
+ closers.push(() => agent.dispose());
75
+ return iframe;
76
+ }
77
+
78
+ const CONTEXT: PreviewSelectionOptions = {
79
+ activeCompositionPath: "index.html",
80
+ isMasterView: false,
81
+ };
82
+
83
+ /** The selection both paths agree on: everything but the element itself and its text fields. */
84
+ function shared(selection: DomEditSelection | null) {
85
+ if (!selection) return null;
86
+ const { element: _element, handle: _handle, textFields: _fields, ...rest } = selection;
87
+ // Read off the description only when `element` is a stand-in; checked on their own below.
88
+ const { hasAudio: _audio, src: _src, ...compared } = rest;
89
+ return compared;
90
+ }
91
+
92
+ /** The opaque frame's description of `element`, as a hit-test would hand it over. */
93
+ async function describedOnOpaque(iframe: HTMLIFrameElement, element: Element) {
94
+ Object.defineProperty(document, "elementsFromPoint", {
95
+ configurable: true,
96
+ value: () => [element],
97
+ });
98
+ const [hit] = (await previewElementsAtPoint(iframe, 0, 0)) ?? [];
99
+ const [described] = (await describePreviewElements(iframe, [hit!.handle])) ?? [];
100
+ return described!;
101
+ }
102
+
103
+ async function bothPaths(element: HTMLElement, options: PreviewSelectionOptions = CONTEXT) {
104
+ const opaque = opaqueFrame();
105
+ const live = await resolveDomEditSelection(element, options);
106
+ const remote = await resolvePreviewSelection(
107
+ opaque,
108
+ await describedOnOpaque(opaque, element),
109
+ options,
110
+ );
111
+ return { live, remote, opaque };
112
+ }
113
+
114
+ const NAMES = ["id", "data-hf-id", "data-pick", "data-composition-id"];
115
+ const nameOf = (element: Element) =>
116
+ NAMES.map((name) => element.getAttribute(name)).find(Boolean) ?? null;
117
+ const named = (element: PreviewElement) =>
118
+ NAMES.map((name) => element.attributes.find(([key]) => key === name)?.[1]).find(Boolean) ?? null;
119
+
120
+ const FIXTURE = `
121
+ <div data-composition-id="main" data-width="1920" data-height="1080">
122
+ <div data-hf-group="outer" id="outer-wrap">
123
+ <div data-hf-group="inner"><p class="member" data-hf-id="m1" style="left: 4px; border-radius: 8px">Member</p></div>
124
+ </div>
125
+ <div class="clip scene" id="scene"><span class="inner"><b>bold</b></span></div>
126
+ <div class="clip" data-composition-src="compositions/a.html" id="host"><span id="in-host">in</span></div>
127
+ <div data-timeline-locked><p id="locked" data-start="2" style="border-radius: 8px">Locked</p></div>
128
+ <i class="tile" id="t-index"></i>
129
+ <div data-composition-file="compositions/cards.html"><i class="tile"></i><i class="tile" data-pick="t2"></i></div>
130
+ <p id="plain"><b>no selector here</b></p>
131
+ </div>
132
+ <div id="bg" style="width: 1920px; height: 1080px"></div>`;
133
+
134
+ describe("opaque frame selections match same-origin ones", () => {
135
+ it.each([
136
+ ["a group member at the top level selects the outermost group", "[data-hf-id=m1]", {}],
137
+ ["a clip's child, preferring the clip ancestor, selects the clip", "b", { clip: true }],
138
+ ["a host clip is not taken for its child", "#in-host", { clip: true }],
139
+ ["an element with no selector walks up to its addressable parent", "#plain b", {}],
140
+ ["a timeline-locked element is selected as locked", "#locked", {}],
141
+ ["a class match counts its index within its own file", "[data-pick=t2]", {}],
142
+ ["a body child sitting on the root counts as the composition root", "#bg", {}],
143
+ ])("%s", async (_name, selector, flags: { clip?: boolean }) => {
144
+ document.body.innerHTML = FIXTURE;
145
+ const { live, remote } = await bothPaths(document.querySelector<HTMLElement>(selector)!, {
146
+ ...CONTEXT,
147
+ preferClipAncestor: flags.clip,
148
+ });
149
+ expect(live).not.toBeNull();
150
+ expect(shared(remote)).toEqual(shared(live));
151
+ expect(remote!.handle).toMatch(EDITING_ELEMENT_HANDLE);
152
+ expect(remote!.tagName).toBe(live!.element.tagName.toLowerCase());
153
+ });
154
+
155
+ it("covers the cases each rule decides", async () => {
156
+ document.body.innerHTML = FIXTURE;
157
+ const pick = async (selector: string, clip = false) =>
158
+ (await bothPaths(document.querySelector<HTMLElement>(selector)!, {
159
+ ...CONTEXT,
160
+ preferClipAncestor: clip,
161
+ }))!.remote!;
162
+ expect((await pick("[data-hf-id=m1]")).selector).toBe("#outer-wrap");
163
+ expect((await pick("b", true)).id).toBe("scene");
164
+ expect((await pick("#in-host", true)).id).toBe("in-host");
165
+ expect((await pick("#plain b")).id).toBe("plain");
166
+ expect(await pick("#locked")).toMatchObject({
167
+ isInsideLockedComposition: true,
168
+ inlineStyles: { "border-radius": "8px" },
169
+ dataAttributes: { start: "2" },
170
+ label: "Locked",
171
+ });
172
+ expect(await pick("[data-pick=t2]")).toMatchObject({
173
+ sourceFile: "compositions/cards.html",
174
+ selectorIndex: 1,
175
+ });
176
+ expect((await pick("#bg")).capabilities).toMatchObject({
177
+ canCrop: false,
178
+ canApplyManualOffset: false,
179
+ });
180
+ expect((await pick("#plain")).capabilities.canApplyManualOffset).toBe(true);
181
+ });
182
+
183
+ it("follows a drilled-into group: its nested group, then its children, else the top level", async () => {
184
+ document.body.innerHTML = FIXTURE;
185
+ const member = document.querySelector<HTMLElement>("[data-hf-id=m1]")!;
186
+ const opaque = opaqueFrame();
187
+ const described = await describedOnOpaque(opaque, member);
188
+ const outerLive = document.querySelector<HTMLElement>('[data-hf-group="outer"]')!;
189
+ const innerLive = document.querySelector<HTMLElement>('[data-hf-group="inner"]')!;
190
+ // On an opaque frame the drilled-into group is the stand-in of an earlier selection.
191
+ const outerRemote = (await resolvePreviewSelection(opaque, described, CONTEXT))!.element;
192
+ const innerRemote = (await resolvePreviewSelection(opaque, described, {
193
+ ...CONTEXT,
194
+ activeGroupElement: outerRemote,
195
+ }))!.element;
196
+ const cases: Array<[HTMLElement | null, HTMLElement | null, string]> = [
197
+ [outerLive, outerRemote, '[data-hf-group="inner"]'],
198
+ [innerLive, innerRemote, ".member"],
199
+ [document.querySelector<HTMLElement>("#scene"), null, "#outer-wrap"],
200
+ ];
201
+ for (const [activeLive, activeRemote, selector] of cases) {
202
+ const live = await resolveDomEditSelection(member, {
203
+ ...CONTEXT,
204
+ activeGroupElement: activeLive,
205
+ });
206
+ const remote = await resolvePreviewSelection(opaque, described, {
207
+ ...CONTEXT,
208
+ activeGroupElement: activeRemote ?? document.createElement("div"),
209
+ });
210
+ expect(live!.selector).toBe(selector);
211
+ expect(shared(remote)).toEqual(shared(live));
212
+ }
213
+ });
214
+
215
+ it.each([
216
+ [
217
+ "by selector and index in its own file",
218
+ { selector: ".tile", selectorIndex: 1, sourceFile: "compositions/cards.html" },
219
+ ],
220
+ ["by id", { id: "t-index", sourceFile: "index.html" }],
221
+ ["by hf id", { hfId: "m1" }],
222
+ ["nothing for a selector with no match", { selector: ".missing" }],
223
+ ["nothing for an invalid selector", { selector: "p[" }],
224
+ ])("finds an element for a selection %s", async (_name, selection) => {
225
+ document.body.innerHTML = FIXTURE;
226
+ const live = findElementForSelection(document, selection, "index.html");
227
+ const found = await findPreviewElementForSelection(opaqueFrame(), selection, "index.html");
228
+ expect(live === null ? null : nameOf(live)).toBe(found === null ? null : found && named(found));
229
+ if (selection.selector !== ".missing" && selection.selector !== "p[")
230
+ expect(live).not.toBeNull();
231
+ });
232
+
233
+ it.each([
234
+ [
235
+ "a clip by selector",
236
+ { id: "x", selector: ".tile", selectorIndex: 1, sourceFile: "compositions/cards.html" },
237
+ false,
238
+ "t2",
239
+ ],
240
+ ["the root, from the active composition, outside the master view", { id: "x" }, false, "main"],
241
+ ["nothing in the master view without a DOM target", { id: "x" }, true, null],
242
+ ])("finds a timeline element: %s", async (_name, element, isMasterView, expected) => {
243
+ document.body.innerHTML = FIXTURE;
244
+ const options = { activeCompositionPath: "index.html", isMasterView };
245
+ const live = findElementForTimelineElement(document, element, options);
246
+ const found = await findPreviewElementForTimelineElement(opaqueFrame(), element, options);
247
+ expect(live && nameOf(live)).toBe(expected);
248
+ expect(found && named(found)).toBe(expected);
249
+ });
250
+ });
251
+
252
+ describe("opaque frame selection handles", () => {
253
+ it("gives a selection an inert, tag-only stand-in, the same one for a handle", async () => {
254
+ document.body.innerHTML = FIXTURE;
255
+ const { remote, opaque } = await bothPaths(document.querySelector<HTMLElement>("#locked")!);
256
+ const again = await resolvePreviewSelection(
257
+ opaque,
258
+ await describedOnOpaque(opaque, document.querySelector("#locked")!),
259
+ { ...CONTEXT, previous: remote },
260
+ );
261
+ expect(again!.element).toBe(remote!.element);
262
+ expect(remote!.element.tagName).toBe("P");
263
+ expect(remote!.element.attributes).toHaveLength(0);
264
+ expect(remote!.element.textContent).toBe("");
265
+ expect(remote!.element.ownerDocument.defaultView).toBeNull();
266
+ expect(remote!.element.ownerDocument).not.toBe(document);
267
+ });
268
+
269
+ it("builds nothing for a removed element, and finds nothing the runtime cannot name", async () => {
270
+ document.body.innerHTML = FIXTURE;
271
+ const opaque = opaqueFrame();
272
+ const locked = document.querySelector("#locked")!;
273
+ const described = await describedOnOpaque(opaque, locked);
274
+ // A description whose parent is not the element its runtime names as the parent.
275
+ const unlinked = { ...described, parent: described.handle };
276
+ expect(await resolvePreviewSelection(opaque, unlinked, CONTEXT)).toBeNull();
277
+ expect(await resolvePreviewSelection(opaque, described, CONTEXT)).not.toBeNull();
278
+ locked.remove();
279
+ expect(await resolvePreviewSelection(opaque, described, CONTEXT)).toBeNull();
280
+ const stale = {
281
+ ...described,
282
+ handle: described.handle.replace(/^[0-9a-f]{16}/, "f".repeat(16)),
283
+ };
284
+ expect(await resolvePreviewSelection(opaque, stale, CONTEXT)).toBeNull();
285
+ });
286
+
287
+ it("says it cannot tell when the frame has no editing agent", async () => {
288
+ vi.useFakeTimers();
289
+ try {
290
+ const frame: Record<string, unknown> = { postMessage: () => {} };
291
+ const iframe = detachedFakeIframe(frame);
292
+ const pending = findPreviewElementForSelection(iframe, { id: "plain" }, "index.html");
293
+ await vi.advanceTimersByTimeAsync(2_000);
294
+ expect(await pending).toBeUndefined();
295
+ } finally {
296
+ vi.useRealTimers();
297
+ }
298
+ });
299
+
300
+ it("says it cannot tell when a capped query does not reach the index", async () => {
301
+ document.body.innerHTML = "<i class='n'></i>".repeat(2_049);
302
+ const found = await findPreviewElementForSelection(
303
+ opaqueFrame(),
304
+ { selector: ".n", selectorIndex: 2_048 },
305
+ "index.html",
306
+ );
307
+ expect(found).toBeUndefined();
308
+ });
309
+ });
310
+
311
+ describe("opaque frame selections read only what arrived whole", () => {
312
+ it("reads audio and src off the description, not the tag-only stand-in", async () => {
313
+ document.body.innerHTML = `<div data-composition-id="main" data-width="1920" data-height="1080">
314
+ <video id="muted" muted src="a.mp4"></video><video id="silent" data-has-audio="false"></video>
315
+ <video id="loud" src="b.mp4"></video><img id="pic" src="pic.png"></div>`;
316
+ for (const [id, audible] of [
317
+ ["muted", false],
318
+ ["silent", false],
319
+ ["loud", true],
320
+ ] as const) {
321
+ const { live, remote } = await bothPaths(document.getElementById(id)!);
322
+ expect(domEditSelectionToFacts(live!).hasAudio).toBe(audible);
323
+ expect(domEditSelectionToFacts(remote!).hasAudio).toBe(audible);
324
+ }
325
+ const { remote } = await bothPaths(document.getElementById("pic")!);
326
+ expect(remote!.src).toBe("pic.png");
327
+ expect(remote!.element.getAttribute("src")).toBeNull();
328
+ });
329
+
330
+ it("builds nothing when an attribute or inline style was cut, and is not stopped by long text", async () => {
331
+ const chain = JSON.stringify(Array.from({ length: 200 }, (_, i) => ({ id: `node-${i}` })));
332
+ document.body.innerHTML = `<div data-composition-id="main" data-width="1920" data-height="1080">
333
+ <p id="fx" data-audio-fx='${chain}'>fx</p>
334
+ <p id="bg-img" style="background-image: url(data:image/png;base64,${"A".repeat(3000)})">i</p>
335
+ <p id="essay">${"y".repeat(MAX_ELEMENT_TEXT + 5)}</p></div>`;
336
+ for (const id of ["fx", "bg-img"]) {
337
+ const { live, remote } = await bothPaths(document.getElementById(id)!);
338
+ expect(live).not.toBeNull();
339
+ expect(remote).toBeNull();
340
+ }
341
+ const essay = await bothPaths(document.getElementById("essay")!);
342
+ expect(essay.remote).toMatchObject({ id: "essay", selector: "#essay" });
343
+ });
344
+
345
+ it("selects an image with a short data: src, and not one whose data: src was cut", async () => {
346
+ const icon = `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"><rect/></svg>`;
347
+ document.body.innerHTML = `<div data-composition-id="main" data-width="1920" data-height="1080">
348
+ <img id="icon"><img id="photo" src="data:image/png;base64,${"A".repeat(3000)}"></div>`;
349
+ document.getElementById("icon")!.setAttribute("src", icon);
350
+ const short = await bothPaths(document.getElementById("icon")!);
351
+ expect(shared(short.remote)).toEqual(shared(short.live));
352
+ expect(short.remote!.src).toBe(icon);
353
+ const long = await bothPaths(document.getElementById("photo")!);
354
+ expect(long.live).not.toBeNull();
355
+ expect(long.remote).toBeNull();
356
+ });
357
+
358
+ it("builds nothing when the frame cannot read computed styles or the composition root", async () => {
359
+ document.body.innerHTML = FIXTURE;
360
+ const opaque = opaqueFrame();
361
+ const locked = await describedOnOpaque(opaque, document.querySelector("#locked")!);
362
+ const bg = await describedOnOpaque(opaque, document.querySelector("#bg")!);
363
+ expect(await resolvePreviewSelection(opaque, bg, CONTEXT)).not.toBeNull();
364
+
365
+ const styles = vi.spyOn(window, "getComputedStyle").mockImplementation(() => {
366
+ throw new Error("parked");
367
+ });
368
+ expect(await resolvePreviewSelection(opaque, locked, CONTEXT)).toBeNull();
369
+ styles.mockRestore();
370
+
371
+ const query = document.querySelectorAll.bind(document);
372
+ const roots = vi.spyOn(document, "querySelectorAll").mockImplementation((selector: string) => {
373
+ if (selector === "[data-composition-id]") throw new Error("reloading");
374
+ return query(selector);
375
+ });
376
+ expect(await resolvePreviewSelection(opaque, bg, CONTEXT)).toBeNull();
377
+ roots.mockRestore();
378
+ });
379
+ });
380
+
381
+ describe("useDomSelection on an opaque frame", () => {
382
+ function renderSelection(iframe: HTMLIFrameElement) {
383
+ let hook: ReturnType<typeof useDomSelection> | null = null;
384
+ function Harness() {
385
+ hook = useDomSelection({
386
+ projectId: null,
387
+ activeCompPath: "index.html",
388
+ isMasterView: false,
389
+ compIdToSrc: new Map(),
390
+ captionEditMode: false,
391
+ previewIframeRef: { current: iframe },
392
+ timelineElements: [],
393
+ getTimelineSelectionSet: () => new Set(),
394
+ setSelectedTimelineElementId: vi.fn(),
395
+ setTimelineSelectionSet: vi.fn(),
396
+ setRightCollapsed: vi.fn(),
397
+ setRightPanelTab: vi.fn(),
398
+ previewIframe: iframe,
399
+ refreshKey: 0,
400
+ rightPanelTab: "design",
401
+ });
402
+ return null;
403
+ }
404
+ const host = document.createElement("div");
405
+ const root = createRoot(host);
406
+ act(() => root.render(React.createElement(Harness)));
407
+ closers.push(() => act(() => root.unmount()));
408
+ return () => hook!;
409
+ }
410
+
411
+ const clip = (selector: string) =>
412
+ ({
413
+ id: "c",
414
+ selector,
415
+ selectorIndex: 0,
416
+ sourceFile: "index.html",
417
+ }) as unknown as TimelineElement;
418
+
419
+ it("selects a timeline clip, refreshes it, and drops it once the frame no longer has it", async () => {
420
+ document.body.innerHTML = FIXTURE;
421
+ const liveHook = renderSelection(liveFrame());
422
+ const hook = renderSelection(opaqueFrame());
423
+ await act(() => liveHook().handleTimelineElementSelect(clip("#locked")));
424
+ await act(() => hook().handleTimelineElementSelect(clip("#locked")));
425
+ const selected = hook().domEditSelection!;
426
+ expect(selected.handle).toMatch(EDITING_ELEMENT_HANDLE);
427
+ expect(shared(selected)).toEqual(shared(liveHook().domEditSelection));
428
+
429
+ document.querySelector<HTMLElement>("#locked")!.style.left = "12px";
430
+ await act(() => hook().refreshDomEditSelectionFromPreview(selected));
431
+ expect(hook().domEditSelection!.inlineStyles.left).toBe("12px");
432
+ expect(hook().domEditSelection!.element).toBe(selected.element);
433
+
434
+ document.querySelector("#locked")!.remove();
435
+ await act(() => hook().refreshDomEditSelectionFromPreview(hook().domEditSelection!));
436
+ expect(hook().domEditSelection).toBeNull();
437
+ });
438
+
439
+ it("re-finds every group member on refresh", async () => {
440
+ document.body.innerHTML = FIXTURE;
441
+ const hook = renderSelection(opaqueFrame());
442
+ await act(() => hook().handleTimelineElementSelect(clip("#locked")));
443
+ const first = hook().domEditSelection!;
444
+ await act(() => hook().handleTimelineElementSelect(clip("#plain")));
445
+ const second = hook().domEditSelection!;
446
+ act(() => hook().applyDomSelection(first, { additive: true }));
447
+ expect(hook().domEditGroupSelections).toHaveLength(2);
448
+
449
+ document.querySelector("#locked")!.remove();
450
+ await act(() => hook().refreshDomEditSelectionFromPreview(first));
451
+ expect(hook().domEditGroupSelections.map((s) => s.id)).toEqual(["plain"]);
452
+ expect(hook().domEditSelection!.handle).toBe(second.handle);
453
+ });
454
+
455
+ it("leaves a group the user changed while its refresh was reading the frame", async () => {
456
+ document.body.innerHTML = FIXTURE;
457
+ const hook = renderSelection(opaqueFrame());
458
+ await act(() => hook().handleTimelineElementSelect(clip("#plain")));
459
+ const plain = hook().domEditSelection!;
460
+ await act(() => hook().handleTimelineElementSelect(clip("#locked")));
461
+ const locked = hook().domEditSelection!;
462
+ act(() => hook().applyDomSelection(plain, { additive: true }));
463
+ await act(() => hook().handleTimelineElementSelect(clip("#scene")));
464
+ const scene = hook().domEditSelection!;
465
+ act(() => hook().applyDomSelection(locked, { additive: true }));
466
+ act(() => hook().applyDomSelection(plain, { additive: true }));
467
+
468
+ // The primary is gone, so the refresh re-reads the group; meanwhile the user picks one clip.
469
+ document.querySelector("#plain")!.remove();
470
+ selectLog.on = (event) => {
471
+ if (event === "refresh-lost") hook().applyDomSelection(scene, { revealPanel: false });
472
+ };
473
+ try {
474
+ await act(() => hook().refreshDomEditSelectionFromPreview(hook().domEditSelection!));
475
+ } finally {
476
+ selectLog.on = null;
477
+ }
478
+ expect(hook().domEditSelection!.id).toBe("scene");
479
+ expect(hook().domEditGroupSelections.map((s) => s.id)).toEqual(["scene"]);
480
+ });
481
+ });