@hyperframes/studio 0.9.41 → 0.9.42

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 (54) hide show
  1. package/dist/assets/{codec-B_mpbc4w.js → codec-CKqLGYc6.js} +1 -1
  2. package/dist/assets/{hyperframes-player-Dvi3I_mv.js → hyperframes-player-DoEYqOIa.js} +1 -1
  3. package/dist/assets/{index-B5ExwsOp.js → index-DLyQ91Ek.js} +160 -160
  4. package/dist/assets/{index-BrFm9Y5k.js → index-s9iqoWnr.js} +1 -1
  5. package/dist/assets/{pausedVideoDecoder-MHQ57yZ6.js → pausedVideoDecoder-B-ReRg6i.js} +1 -1
  6. package/dist/index.d.ts +9 -1
  7. package/dist/index.html +1 -1
  8. package/dist/index.js +1057 -721
  9. package/package.json +10 -10
  10. package/src/components/editor/LayersPanel.opaque.test.ts +176 -0
  11. package/src/components/editor/LayersPanel.tsx +41 -10
  12. package/src/components/editor/domEditInlineText.ts +1 -16
  13. package/src/components/editor/domEditingTypes.ts +7 -1
  14. package/src/components/editor/gestureUndoRevert.ts +18 -1
  15. package/src/components/editor/inlineTextStyleRange.fill.test.ts +129 -0
  16. package/src/components/editor/inlineTextStyleRange.test.ts +0 -82
  17. package/src/components/editor/layerKind.ts +2 -19
  18. package/src/components/editor/layersPanelSort.ts +2 -2
  19. package/src/components/editor/manualEdits.ts +1 -0
  20. package/src/components/editor/manualEditsSnapshot.ts +10 -0
  21. package/src/components/editor/manualOffsetDrag.test.ts +1 -1
  22. package/src/components/editor/manualOffsetDrag.ts +7 -1
  23. package/src/components/editor/marqueeCommit.ts +47 -4
  24. package/src/components/editor/plainTranslate.ts +35 -16
  25. package/src/components/editor/previewDrafts.test.ts +263 -0
  26. package/src/components/editor/previewDrafts.ts +73 -0
  27. package/src/components/editor/previewLayers.test.ts +308 -0
  28. package/src/components/editor/previewLayers.ts +164 -0
  29. package/src/components/editor/previewOverlayRects.ts +27 -0
  30. package/src/components/editor/previewPointerTargets.test.ts +68 -1
  31. package/src/components/editor/previewSelection.ts +55 -11
  32. package/src/components/editor/resizeDraft.ts +38 -0
  33. package/src/components/editor/useDomEditOverlayGestures.ts +2 -2
  34. package/src/components/editor/useLayerDrag.ts +1 -1
  35. package/src/components/nle/NLEPreview.slowBoot.test.ts +0 -1
  36. package/src/hooks/domEditDeleteMembers.test.ts +7 -0
  37. package/src/hooks/domSelectionTimelineMirror.ts +3 -1
  38. package/src/hooks/timelineTimingSync.ts +4 -1
  39. package/src/hooks/useDomSelection.ts +2 -0
  40. package/src/hooks/useEditorSave.test.tsx +22 -1
  41. package/src/hooks/useEditorSave.ts +3 -1
  42. package/src/hooks/usePreviewInteraction.ts +4 -1
  43. package/src/hooks/useProjectFileWriter.ts +7 -3
  44. package/src/hooks/useTimelineSelectionPreviewSync.test.tsx +30 -0
  45. package/src/hooks/useTimelineSelectionPreviewSync.ts +7 -2
  46. package/src/player/lib/layerOrdering.ts +2 -11
  47. package/src/player/lib/previewElements.ts +31 -0
  48. package/src/test-setup.ts +2 -0
  49. package/src/utils/gsapSoftReload.ts +1 -1
  50. package/src/utils/studioFileHistory.ts +1 -1
  51. package/src/utils/studioHelpers.ts +27 -4
  52. package/src/utils/studioSaveDiagnostics.test.ts +34 -0
  53. package/src/utils/studioSaveDiagnostics.ts +35 -6
  54. package/src/utils/timelineCompositionInsert.ts +3 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperframes/studio",
3
- "version": "0.9.41",
3
+ "version": "0.9.42",
4
4
  "description": "",
5
5
  "repository": {
6
6
  "type": "git",
@@ -64,12 +64,12 @@
64
64
  "dockview-react": "8.3.1",
65
65
  "gsap": "^3.13.0",
66
66
  "mediabunny": "^1.65.2",
67
- "@hyperframes/core": "0.9.41",
68
- "@hyperframes/parsers": "0.9.41",
69
- "@hyperframes/player": "0.9.41",
70
- "@hyperframes/sdk": "0.9.41",
71
- "@hyperframes/shader-transitions": "0.9.41",
72
- "@hyperframes/studio-server": "0.9.41"
67
+ "@hyperframes/player": "0.9.42",
68
+ "@hyperframes/parsers": "0.9.42",
69
+ "@hyperframes/shader-transitions": "0.9.42",
70
+ "@hyperframes/core": "0.9.42",
71
+ "@hyperframes/studio-server": "0.9.42",
72
+ "@hyperframes/sdk": "0.9.42"
73
73
  },
74
74
  "devDependencies": {
75
75
  "@tailwindcss/vite": "^4.3.3",
@@ -83,10 +83,10 @@
83
83
  "tailwindcss": "^4.3.3",
84
84
  "tsup": "^8.0.0",
85
85
  "typescript": "^5.0.0",
86
- "vite": "^6.4.2",
87
- "vitest": "^4.1.11",
86
+ "vite": "^6.4.5",
87
+ "vitest": "^4.1.12",
88
88
  "zustand": "^5.0.0",
89
- "@hyperframes/producer": "0.9.41"
89
+ "@hyperframes/producer": "0.9.42"
90
90
  },
91
91
  "peerDependencies": {
92
92
  "react": "19",
@@ -0,0 +1,176 @@
1
+ // @vitest-environment happy-dom
2
+
3
+ import { act, createElement } from "react";
4
+ import { createRoot } from "react-dom/client";
5
+ import { afterEach, expect, it, vi } from "vitest";
6
+ // The frame's real runtime agent, serving the opaque frame from this document.
7
+ import { installEditingAgent } from "../../../../core/src/runtime/editingAgent";
8
+ import { installReactActEnvironment } from "../../hooks/domSelectionTestHarness";
9
+ import { detachedFakeIframe } from "../../player/hooks/timelinePlayerTestHarness";
10
+ import { usePreviewIframeStore } from "../../player/store/previewIframeStore";
11
+ import type { DomEditSelection } from "./domEditing";
12
+ import { LayersPanel } from "./LayersPanel";
13
+ import { announcePreviewDocumentLoaded } from "../../player/sceneSwap";
14
+ import { describePreviewElements, queryPreviewElements } from "../../player/lib/previewElements";
15
+ import { standInFor } from "./previewSelection";
16
+
17
+ installReactActEnvironment();
18
+
19
+ const mocks = vi.hoisted(() => ({
20
+ previewIframeRef: { current: null } as { current: unknown },
21
+ activeGroupElement: null as HTMLElement | null,
22
+ applyDomSelection: vi.fn(),
23
+ setActiveGroupElement: vi.fn(),
24
+ // While set, a layers read waits on it after the frame answers.
25
+ hold: null as Promise<void> | null,
26
+ answered: 0,
27
+ }));
28
+ vi.mock("../../player/lib/previewElements", async (importOriginal) => {
29
+ const actual = await importOriginal<typeof import("../../player/lib/previewElements")>();
30
+ return {
31
+ ...actual,
32
+ previewLayers: async (...args: Parameters<typeof actual.previewLayers>) => {
33
+ const reply = await actual.previewLayers(...args);
34
+ mocks.answered += 1;
35
+ await mocks.hold;
36
+ return reply;
37
+ },
38
+ };
39
+ });
40
+ vi.mock("../../contexts/StudioContext", () => ({
41
+ useStudioShellContextOptional: () => ({
42
+ previewIframeRef: mocks.previewIframeRef,
43
+ activeCompPath: "index.html",
44
+ showToast: vi.fn(),
45
+ }),
46
+ useStudioPlaybackContextOptional: () => ({
47
+ refreshKey: 0,
48
+ compositionLoading: false,
49
+ timelineElements: [],
50
+ isPlaying: false,
51
+ }),
52
+ }));
53
+ vi.mock("../../contexts/DomEditContext", () => ({
54
+ useDomEditContext: () => ({
55
+ domEditSelection: null,
56
+ activeGroupElement: mocks.activeGroupElement,
57
+ applyDomSelection: mocks.applyDomSelection,
58
+ updateDomEditHoverSelection: vi.fn(),
59
+ handleDomZIndexReorderCommit: vi.fn(),
60
+ setActiveGroupElement: mocks.setActiveGroupElement,
61
+ }),
62
+ }));
63
+ vi.mock("../nle/useCanvasZOrderTimelineMirror", () => ({
64
+ useLayerReorderTimelineMirror: () => vi.fn(),
65
+ }));
66
+
67
+ const closers: Array<() => void> = [];
68
+ afterEach(() => {
69
+ closers.splice(0).forEach((close) => close());
70
+ mocks.activeGroupElement = null;
71
+ mocks.hold = null;
72
+ mocks.answered = 0;
73
+ vi.clearAllMocks();
74
+ usePreviewIframeStore.setState({ iframe: null });
75
+ document.body.innerHTML = "";
76
+ });
77
+
78
+ /** A frame Studio cannot read, whose runtime is the real editing agent over this document. */
79
+ function opaqueFrame() {
80
+ const frame: Record<string, unknown> = {};
81
+ const iframe = detachedFakeIframe(frame);
82
+ Object.defineProperty(iframe, "contentDocument", { value: null });
83
+ Object.defineProperty(frame, "document", {
84
+ get: () => {
85
+ throw new DOMException("blocked", "SecurityError");
86
+ },
87
+ });
88
+ const parent = {
89
+ postMessage: (data: unknown, _origin: string, ports: MessagePort[]) =>
90
+ window.dispatchEvent(
91
+ new MessageEvent("message", { source: frame as unknown as Window, data, ports }),
92
+ ),
93
+ } as unknown as Window;
94
+ const agent = installEditingAgent(parent);
95
+ frame.postMessage = (data: unknown) =>
96
+ window.dispatchEvent(new MessageEvent("message", { source: parent, data }));
97
+ closers.push(() => agent.dispose());
98
+ return iframe;
99
+ }
100
+
101
+ it("lists an opaque frame's layers, selects a row, and drills into a group row", async () => {
102
+ document.body.innerHTML = `<main data-composition-id="main">
103
+ <div id="card"><h1 id="title">Hi</h1></div>
104
+ <div id="pair" data-hf-group="pair"><i id="a"></i></div>
105
+ <div id="host" data-composition-src="compositions/intro-card.html"></div></main>`;
106
+ const iframe = opaqueFrame();
107
+ mocks.previewIframeRef.current = iframe;
108
+ usePreviewIframeStore.setState({ iframe });
109
+ const host = document.createElement("div");
110
+ document.body.append(host);
111
+ const root = createRoot(host);
112
+ act(() => root.render(createElement(LayersPanel)));
113
+ closers.push(() => act(() => root.unmount()));
114
+
115
+ const rows = () => [...host.querySelectorAll<HTMLElement>("[data-layer-index]")];
116
+ await vi.waitFor(() => expect(rows()).toHaveLength(5));
117
+ const named = (label: string) => rows().find((r) => r.textContent?.includes(label))!;
118
+ expect(named("Title").querySelector("[data-layer-kind]")!.getAttribute("data-layer-kind")).toBe(
119
+ "text",
120
+ );
121
+ expect(named("pair").title).toBe("This layer can't be reordered");
122
+ const hostIcon = named("Intro").querySelector("[data-layer-kind]")!;
123
+ expect(hostIcon.className).toContain("bg-on");
124
+
125
+ act(() => named("Title").click());
126
+ await vi.waitFor(() => expect(mocks.applyDomSelection).toHaveBeenCalled());
127
+ const picked = mocks.applyDomSelection.mock.calls[0]![0] as DomEditSelection;
128
+ expect(picked).toMatchObject({ id: "title", selector: "#title" });
129
+ expect(picked.handle).toBeTruthy();
130
+
131
+ act(() => void named("pair").dispatchEvent(new MouseEvent("dblclick", { bubbles: true })));
132
+ await vi.waitFor(() => expect(mocks.setActiveGroupElement).toHaveBeenCalledOnce());
133
+ const group = mocks.setActiveGroupElement.mock.calls[0]![0] as HTMLElement;
134
+ expect(group.hasAttribute("data-hf-group")).toBe(false);
135
+ });
136
+
137
+ function renderPanel(iframe: HTMLIFrameElement) {
138
+ mocks.previewIframeRef.current = iframe;
139
+ usePreviewIframeStore.setState({ iframe });
140
+ const host = document.createElement("div");
141
+ document.body.append(host);
142
+ const root = createRoot(host);
143
+ act(() => root.render(createElement(LayersPanel)));
144
+ closers.push(() => act(() => root.unmount()));
145
+ return () =>
146
+ [...host.querySelectorAll<HTMLElement>("[data-layer-index]")].map((r) => r.textContent);
147
+ }
148
+
149
+ it("leaves a drill-in whose group a reload took, rather than list the whole page under it", async () => {
150
+ document.body.innerHTML = `<main data-composition-id="main">
151
+ <div id="card"></div><div id="pair" data-hf-group="pair"><i id="a"></i></div></main>`;
152
+ const iframe = opaqueFrame();
153
+ const [pair] = (await queryPreviewElements(iframe, "#pair"))!.matches;
154
+ const [described] = (await describePreviewElements(iframe, [pair!.handle]))!;
155
+ mocks.activeGroupElement = standInFor(iframe, described!);
156
+ document.getElementById("pair")!.remove();
157
+ const rows = renderPanel(iframe);
158
+ await vi.waitFor(() => expect(mocks.setActiveGroupElement).toHaveBeenCalledWith(null));
159
+ expect(rows()).toEqual([]);
160
+ });
161
+
162
+ it("reads the layers once more when a refresh lands while a read is in flight", async () => {
163
+ document.body.innerHTML = `<main data-composition-id="main"><div id="card"></div></main>`;
164
+ let release!: () => void;
165
+ mocks.hold = new Promise<void>((resolve) => (release = resolve));
166
+ const iframe = opaqueFrame();
167
+ const rows = renderPanel(iframe);
168
+ await vi.waitFor(() => expect(mocks.answered).toBe(1));
169
+ // Past the panel's settle timer, so only the announced refresh can bring the new layer.
170
+ await new Promise((resolve) => setTimeout(resolve, 150));
171
+ // The first read has its answer and is waiting; the page changes and announces it.
172
+ document.querySelector("main")!.insertAdjacentHTML("beforeend", `<div id="late"></div>`);
173
+ act(() => announcePreviewDocumentLoaded(iframe));
174
+ act(() => release());
175
+ await vi.waitFor(() => expect(rows()).toEqual(["Late", "Card"]));
176
+ });
@@ -40,6 +40,10 @@ import { zReorderCoalesceKey } from "../../hooks/useElementLifecycleOps";
40
40
  import { useLayerReorderTimelineMirror } from "../nle/useCanvasZOrderTimelineMirror";
41
41
  import { runZLaneGesture } from "../nle/zLaneGesture";
42
42
  import { useLayerRevealOverride } from "./useLayerRevealOverride";
43
+ import { previewFrameOpaque } from "../../player/lib/previewChannel";
44
+ import { describePreviewElements } from "../../player/lib/previewElements";
45
+ import { collectPreviewLayerItems, layerDataAttribute } from "./previewLayers";
46
+ import { resolvePreviewSelection, selectionDataAttribute } from "./previewSelection";
43
47
 
44
48
  // Rows this panel renders before it stops. A display budget, not a document limit.
45
49
  const LAYERS_PANEL_MAX_ROWS = 80;
@@ -146,9 +150,26 @@ export const LayersPanel = memo(function LayersPanel({ host }: { host?: LayersPa
146
150
  const isMasterView = !activeCompPath || activeCompPath === "index.html";
147
151
 
148
152
  const livePreviewIframe = useLivePreviewIframe();
153
+ // The opaque read in flight; `again` holds a refresh that arrived meanwhile, run once it settles.
154
+ const opaqueRead = useRef<{ again: boolean } | null>(null);
149
155
  const collectLayers = useCallback(() => {
150
156
  const iframe = previewIframeRef.current;
151
157
  if (!iframe) return;
158
+ if (previewFrameOpaque(iframe)) {
159
+ if (opaqueRead.current) return void (opaqueRead.current.again = true);
160
+ const read = { again: false };
161
+ opaqueRead.current = read;
162
+ const scope = { activeCompositionPath: activeCompPath, activeGroupElement };
163
+ void collectPreviewLayerItems(iframe, scope, LAYERS_PANEL_MAX_ROWS).then((reply) => {
164
+ if (opaqueRead.current !== read) return;
165
+ opaqueRead.current = null;
166
+ // A reload took the drilled-into group; leave it as same-origin does below.
167
+ if (reply?.missingGroup) return setActiveGroupElement(null);
168
+ if (reply) setLayers(sortLayersByZIndex(reply.items));
169
+ if (read.again) collectLayers();
170
+ });
171
+ return;
172
+ }
152
173
  let doc: Document | null = null;
153
174
  try {
154
175
  doc = iframe.contentDocument;
@@ -175,6 +196,7 @@ export const LayersPanel = memo(function LayersPanel({ host }: { host?: LayersPa
175
196
  }, [previewIframeRef, activeCompPath, isMasterView, activeGroupElement, setActiveGroupElement]);
176
197
 
177
198
  useEffect(() => {
199
+ opaqueRead.current = null;
178
200
  collectLayers();
179
201
  }, [collectLayers, refreshKey, zEditVersion, livePreviewIframe]);
180
202
 
@@ -210,15 +232,20 @@ export const LayersPanel = memo(function LayersPanel({ host }: { host?: LayersPa
210
232
  }, [collectLayers]);
211
233
 
212
234
  const resolveSelection = useCallback(
213
- (layer: DomEditLayerItem) => {
214
- const doc = previewIframeRef.current?.contentDocument;
215
- const el = liveLayerElement(layer, doc, activeCompPath);
216
- return resolveDomEditSelection(el, {
235
+ async (layer: DomEditLayerItem) => {
236
+ const iframe = previewIframeRef.current;
237
+ const options = {
217
238
  activeCompositionPath: activeCompPath,
218
239
  isMasterView,
219
240
  preferClipAncestor: false,
220
241
  activeGroupElement,
221
- });
242
+ };
243
+ if (layer.preview && iframe) {
244
+ const [described] = (await describePreviewElements(iframe, [layer.preview.handle])) ?? [];
245
+ return described ? resolvePreviewSelection(iframe, described, options) : null;
246
+ }
247
+ const el = liveLayerElement(layer, iframe?.contentDocument, activeCompPath);
248
+ return resolveDomEditSelection(el, options);
222
249
  },
223
250
  [activeCompPath, isMasterView, previewIframeRef, activeGroupElement],
224
251
  );
@@ -228,7 +255,8 @@ export const LayersPanel = memo(function LayersPanel({ host }: { host?: LayersPa
228
255
  const selection = await resolveSelection(layer);
229
256
  if (!selection) return;
230
257
 
231
- let matchedId = findMatchingTimelineElementId(selection, timelineElements);
258
+ const scope = activeCompPath || "index.html";
259
+ let matchedId = findMatchingTimelineElementId(selection, timelineElements, scope);
232
260
 
233
261
  if (!matchedId) {
234
262
  const sourceFile = selection.sourceFile ?? "index.html";
@@ -253,7 +281,7 @@ export const LayersPanel = memo(function LayersPanel({ host }: { host?: LayersPa
253
281
  }
254
282
  }
255
283
  },
256
- [currentTime, resolveSelection, timelineElements],
284
+ [activeCompPath, currentTime, resolveSelection, timelineElements],
257
285
  );
258
286
 
259
287
  const handleSelectLayer = useCallback(
@@ -275,7 +303,7 @@ export const LayersPanel = memo(function LayersPanel({ host }: { host?: LayersPa
275
303
  const handleLayerDoubleClick = useCallback(
276
304
  async (layer: DomEditLayerItem) => {
277
305
  const selection = await resolveSelection(layer);
278
- if (selection?.element.hasAttribute("data-hf-group")) {
306
+ if (selection && selectionDataAttribute(selection, "data-hf-group") !== null) {
279
307
  setActiveGroupElement(selection.element);
280
308
  } else {
281
309
  await handleSelectLayer(layer);
@@ -456,8 +484,11 @@ export const LayersPanel = memo(function LayersPanel({ host }: { host?: LayersPa
456
484
  const draggable = isLayerDraggable(layer);
457
485
  const isCollapsed = collapsed[layer.key] ?? false;
458
486
  const hasChildren = layer.childCount > 0;
459
- const isCompHost = isCompositionHost(layer.element);
460
- const kind = layerKindOf(layer.element, hasChildren);
487
+ const isCompHost = layer.preview
488
+ ? layerDataAttribute(layer, "data-composition-src") !== null ||
489
+ layerDataAttribute(layer, "data-composition-file") !== null
490
+ : isCompositionHost(layer.element);
491
+ const kind = layer.preview?.kind ?? layerKindOf(layer.element, hasChildren);
461
492
  const KindIcon = KIND_ICON[kind];
462
493
  const kindName = kind[0].toUpperCase() + kind.slice(1);
463
494
  const hint = draggable
@@ -1,4 +1,4 @@
1
- import { isRichTextFormattingTag } from "@hyperframes/core/rich-text-sanitize";
1
+ import { hasOnlyFormattingChildren } from "@hyperframes/core/runtime/editing-port";
2
2
  import type { DomEditSelection } from "./domEditingTypes";
3
3
  import { isTextEditableSelection } from "./domEditingLayers";
4
4
 
@@ -53,21 +53,6 @@ export function canEditElementTextInline(element: HTMLElement | null): boolean {
53
53
  return (element.textContent ?? "").trim().length > 0;
54
54
  }
55
55
 
56
- export function hasOnlyFormattingChildren(element: HTMLElement): boolean {
57
- for (const child of Array.from(element.children)) {
58
- if (!isRichTextFormattingTag(child.tagName)) return false;
59
- if (!isHtmlFromAnyWindow(child)) return false;
60
- // Formatting nests, and a structural child hidden inside a span is still
61
- // structural.
62
- if (!hasOnlyFormattingChildren(child as HTMLElement)) return false;
63
- }
64
- return true;
65
- }
66
-
67
- function isHtmlFromAnyWindow(node: Element): boolean {
68
- return node.namespaceURI === "http://www.w3.org/1999/xhtml";
69
- }
70
-
71
56
  /** Where and when a press landed, for recognising the next one as a pair. */
72
57
  export interface PressMark {
73
58
  x: number;
@@ -1,6 +1,6 @@
1
1
  import type { PatchTarget } from "../../utils/sourcePatcher";
2
2
  import type { GsapAnimation } from "@hyperframes/parsers/gsap-parser";
3
- import type { EditingElementHandle } from "@hyperframes/core/runtime/editing-port";
3
+ import type { EditingElementHandle, LayerKind } from "@hyperframes/core/runtime/editing-port";
4
4
 
5
5
  export const CURATED_STYLE_PROPERTIES = [
6
6
  "position",
@@ -112,6 +112,12 @@ export interface DomEditLayerItem {
112
112
  selector?: string;
113
113
  selectorIndex?: number;
114
114
  sourceFile: string;
115
+ preview?: {
116
+ handle: string;
117
+ zIndex: number;
118
+ kind: LayerKind;
119
+ dataAttributes: Record<string, string>;
120
+ };
115
121
  }
116
122
 
117
123
  export interface DomEditContextOptions {
@@ -1,8 +1,11 @@
1
1
  import {
2
2
  captureStudioPathOffset,
3
+ readAppliedStudioPathOffset,
3
4
  restoreStudioPathOffset,
4
5
  type StudioPathOffsetSnapshot,
5
6
  } from "./manualEdits";
7
+ import { readTranslatePx } from "./plainTranslate";
8
+ import { drawPreviewDraft } from "./previewDrafts";
6
9
  import {
7
10
  getOffsetDragGsap,
8
11
  stampGestureBase,
@@ -49,6 +52,16 @@ function showMemberPosition(member: ManualOffsetDragMember, position: MemberPosi
49
52
  stampGestureBase(member.element, member.initialOffset, member.baseGsap);
50
53
  }
51
54
 
55
+ function redrawMemberOnFrame(member: ManualOffsetDragMember): void {
56
+ const { element, initialOffset } = member;
57
+ const offset = member.plainTranslate
58
+ ? readTranslatePx(element)
59
+ : readAppliedStudioPathOffset(element);
60
+ const translate = { x: offset.x - initialOffset.x, y: offset.y - initialOffset.y };
61
+ if (Number.isFinite(translate.x) && Number.isFinite(translate.y) && (translate.x || translate.y))
62
+ drawPreviewDraft(element, { translate });
63
+ }
64
+
52
65
  /** Undo's live revert of a move: its members at gesture start. */
53
66
  export function manualOffsetMoveRevert(members: ManualOffsetDragMember[]): StudioEditRevert {
54
67
  const startPlacement = members.map((member) => placementOf(member.element));
@@ -61,7 +74,11 @@ export function manualOffsetMoveRevert(members: ManualOffsetDragMember[]): Studi
61
74
  placement: startPlacement[i]!,
62
75
  }),
63
76
  );
64
- return () => members.forEach((member, i) => showMemberPosition(member, shown[i]!));
77
+ return () =>
78
+ members.forEach((member, i) => {
79
+ showMemberPosition(member, shown[i]!);
80
+ redrawMemberOnFrame(member);
81
+ });
65
82
  };
66
83
  }
67
84
 
@@ -0,0 +1,129 @@
1
+ // @vitest-environment jsdom
2
+ // happy-dom drops the vendor-prefixed fill property these tests assert on.
3
+
4
+ import { afterEach, describe, expect, it, vi } from "vitest";
5
+ import { applyInlineStyle } from "./inlineTextStyleRange";
6
+
7
+ afterEach(() => {
8
+ vi.restoreAllMocks();
9
+ document.body.innerHTML = "";
10
+ });
11
+
12
+ function mount(html: string): HTMLElement {
13
+ document.body.innerHTML = `<h1>${html}</h1>`;
14
+ return document.body.firstElementChild as HTMLElement;
15
+ }
16
+
17
+ /** Every text node and line break in order, with the offset each one starts at. */
18
+ function charSpans(host: HTMLElement): Array<{ node: Node; from: number; length: number }> {
19
+ const spans: Array<{ node: Node; from: number; length: number }> = [];
20
+ const walker = document.createTreeWalker(host, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
21
+ let seen = 0;
22
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
23
+ const isBreak = node.nodeType === 1 && (node as Element).tagName === "BR";
24
+ if (node.nodeType === 1 && !isBreak) continue;
25
+ const length = isBreak ? 1 : (node.textContent?.length ?? 0);
26
+ spans.push({ node, from: seen, length });
27
+ seen += length;
28
+ }
29
+ return spans;
30
+ }
31
+
32
+ /**
33
+ * A range over the host's text, by character offsets across the whole element.
34
+ *
35
+ * A line break counts as one character, the same way the module does, but is
36
+ * never landed on: a boundary there belongs to the text beside it, which is
37
+ * where a real selection would put it too.
38
+ */
39
+ function rangeOver(host: HTMLElement, start: number, end: number): Range {
40
+ const range = document.createRange();
41
+ const text = charSpans(host).filter((span) => span.node.nodeType === 3);
42
+ const at = (offset: number) => text.find((span) => span.from + span.length >= offset);
43
+ const from = at(start);
44
+ const to = at(end);
45
+ if (from) range.setStart(from.node, start - from.from);
46
+ if (from && to) range.setEnd(to.node, end - to.from);
47
+ return range;
48
+ }
49
+
50
+ /**
51
+ * A colour that does not paint is the same to the user as one that did not save.
52
+ *
53
+ * `-webkit-text-fill-color` inherits and paints the glyph fill, so a composition
54
+ * that sets it on a text element wins over any `color` the editor puts on a run
55
+ * inside it. The run saved correctly and rendered in someone else's colour,
56
+ * which reads as the colour picker being broken.
57
+ */
58
+ describe("applyInlineStyle when something else is painting the glyphs", () => {
59
+ function stubFill(fill: string | null | ((element: HTMLElement) => string | null)) {
60
+ const real = window.getComputedStyle.bind(window);
61
+ vi.spyOn(window, "getComputedStyle").mockImplementation(((element: Element) => {
62
+ const computed = real(element as HTMLElement);
63
+ const resolvedFill = typeof fill === "function" ? fill(element as HTMLElement) : fill;
64
+ return new Proxy(computed, {
65
+ get: (target, key) => {
66
+ if (key === "webkitTextFillColor") return resolvedFill ?? undefined;
67
+ if (key === "color") return (element as HTMLElement).style.color || "rgb(0, 0, 0)";
68
+ return Reflect.get(target, key);
69
+ },
70
+ });
71
+ }) as typeof window.getComputedStyle);
72
+ }
73
+
74
+ it("mirrors the colour into the fill when an ancestor is overpainting", () => {
75
+ const host = mount("Hello world");
76
+ stubFill("rgb(255, 255, 255)");
77
+ applyInlineStyle(rangeOver(host, 6, 11), { color: "rgb(255, 0, 149)" });
78
+
79
+ expect(host.innerHTML).toContain("-webkit-text-fill-color: rgb(255, 0, 149)");
80
+ expect(host.innerHTML).toContain("color: rgb(255, 0, 149)");
81
+ });
82
+
83
+ it("leaves the markup alone when nothing is overpainting", () => {
84
+ const host = mount("Hello world");
85
+ stubFill("rgb(255, 0, 149)");
86
+ applyInlineStyle(rangeOver(host, 6, 11), { color: "rgb(255, 0, 149)" });
87
+
88
+ expect(host.innerHTML).not.toContain("-webkit-text-fill-color");
89
+ expect(host.innerHTML).toContain("color: rgb(255, 0, 149)");
90
+ });
91
+
92
+ it("says nothing about a run that carries no colour", () => {
93
+ const host = mount("Hello world");
94
+ stubFill("rgb(255, 255, 255)");
95
+ applyInlineStyle(rangeOver(host, 6, 11), { "font-weight": "700" });
96
+
97
+ expect(host.innerHTML).not.toContain("-webkit-text-fill-color");
98
+ });
99
+
100
+ it("mirrors only the run whose own ancestor path is overpainting", () => {
101
+ const host = mount(
102
+ '<span data-hf-text-key="child:0" style="color: blue">left</span>' +
103
+ '<span data-hf-text-key="child:1" style="color: green">right</span>',
104
+ );
105
+ stubFill((element) =>
106
+ element.textContent === "left" ? "rgb(255, 255, 255)" : element.style.color,
107
+ );
108
+
109
+ applyInlineStyle(rangeOver(host, 4, 9), { color: "red" });
110
+
111
+ const [left, right] = Array.from(host.querySelectorAll<HTMLElement>("span"));
112
+ expect(left?.style.getPropertyValue("-webkit-text-fill-color")).toBe("blue");
113
+ expect(right?.style.getPropertyValue("-webkit-text-fill-color")).toBe("");
114
+ });
115
+
116
+ it("drops a generated mirror when the ancestor stops overpainting", () => {
117
+ const host = mount("Hello world");
118
+ let overpainted = true;
119
+ stubFill((element) => (overpainted ? "rgb(255, 255, 255)" : element.style.color));
120
+ applyInlineStyle(rangeOver(host, 6, 11), { color: "red" });
121
+ expect(host.innerHTML).toContain("-webkit-text-fill-color");
122
+
123
+ overpainted = false;
124
+ const live = document.getSelection()?.getRangeAt(0);
125
+ if (live) applyInlineStyle(live, { "font-weight": "700" });
126
+
127
+ expect(host.innerHTML).not.toContain("-webkit-text-fill-color");
128
+ });
129
+ });
@@ -621,88 +621,6 @@ describe("applyInlineStyle survives a control that fires repeatedly", () => {
621
621
  expect(document.getSelection()?.toString()).toBe("cde");
622
622
  });
623
623
  });
624
-
625
- /**
626
- * A colour that does not paint is the same to the user as one that did not save.
627
- *
628
- * `-webkit-text-fill-color` inherits and paints the glyph fill, so a composition
629
- * that sets it on a text element wins over any `color` the editor puts on a run
630
- * inside it. The run saved correctly and rendered in someone else's colour,
631
- * which reads as the colour picker being broken.
632
- */
633
- describe("applyInlineStyle when something else is painting the glyphs", () => {
634
- function stubFill(fill: string | null | ((element: HTMLElement) => string | null)) {
635
- const real = window.getComputedStyle.bind(window);
636
- vi.spyOn(window, "getComputedStyle").mockImplementation(((element: Element) => {
637
- const computed = real(element as HTMLElement);
638
- const resolvedFill = typeof fill === "function" ? fill(element as HTMLElement) : fill;
639
- return new Proxy(computed, {
640
- get: (target, key) => {
641
- if (key === "webkitTextFillColor") return resolvedFill ?? undefined;
642
- if (key === "color") return (element as HTMLElement).style.color || "rgb(0, 0, 0)";
643
- return Reflect.get(target, key);
644
- },
645
- });
646
- }) as typeof window.getComputedStyle);
647
- }
648
-
649
- it("mirrors the colour into the fill when an ancestor is overpainting", () => {
650
- const host = mount("Hello world");
651
- stubFill("rgb(255, 255, 255)");
652
- applyInlineStyle(rangeOver(host, 6, 11), { color: "rgb(255, 0, 149)" });
653
-
654
- expect(host.innerHTML).toContain("-webkit-text-fill-color: rgb(255, 0, 149)");
655
- expect(host.innerHTML).toContain("color: rgb(255, 0, 149)");
656
- });
657
-
658
- it("leaves the markup alone when nothing is overpainting", () => {
659
- const host = mount("Hello world");
660
- stubFill("rgb(255, 0, 149)");
661
- applyInlineStyle(rangeOver(host, 6, 11), { color: "rgb(255, 0, 149)" });
662
-
663
- expect(host.innerHTML).not.toContain("-webkit-text-fill-color");
664
- expect(host.innerHTML).toContain("color: rgb(255, 0, 149)");
665
- });
666
-
667
- it("says nothing about a run that carries no colour", () => {
668
- const host = mount("Hello world");
669
- stubFill("rgb(255, 255, 255)");
670
- applyInlineStyle(rangeOver(host, 6, 11), { "font-weight": "700" });
671
-
672
- expect(host.innerHTML).not.toContain("-webkit-text-fill-color");
673
- });
674
-
675
- it("mirrors only the run whose own ancestor path is overpainting", () => {
676
- const host = mount(
677
- '<span data-hf-text-key="child:0" style="color: blue">left</span>' +
678
- '<span data-hf-text-key="child:1" style="color: green">right</span>',
679
- );
680
- stubFill((element) =>
681
- element.textContent === "left" ? "rgb(255, 255, 255)" : element.style.color,
682
- );
683
-
684
- applyInlineStyle(rangeOver(host, 4, 9), { color: "red" });
685
-
686
- const [left, right] = Array.from(host.querySelectorAll<HTMLElement>("span"));
687
- expect(left?.style.getPropertyValue("-webkit-text-fill-color")).toBe("blue");
688
- expect(right?.style.getPropertyValue("-webkit-text-fill-color")).toBe("");
689
- });
690
-
691
- it("drops a generated mirror when the ancestor stops overpainting", () => {
692
- const host = mount("Hello world");
693
- let overpainted = true;
694
- stubFill((element) => (overpainted ? "rgb(255, 255, 255)" : element.style.color));
695
- applyInlineStyle(rangeOver(host, 6, 11), { color: "red" });
696
- expect(host.innerHTML).toContain("-webkit-text-fill-color");
697
-
698
- overpainted = false;
699
- const live = document.getSelection()?.getRangeAt(0);
700
- if (live) applyInlineStyle(live, { "font-weight": "700" });
701
-
702
- expect(host.innerHTML).not.toContain("-webkit-text-fill-color");
703
- });
704
- });
705
-
706
624
  describe("readInlineStyleSpread", () => {
707
625
  it("reports every distinct colour in the selection, in order", () => {
708
626
  const host = mount(
@@ -1,19 +1,2 @@
1
- import { hasOnlyFormattingChildren } from "./domEditInlineText";
2
-
3
- export type LayerKind = "image" | "video" | "audio" | "vector" | "group" | "text" | "shape";
4
-
5
- export function isCompositionHost(el: Element): boolean {
6
- return el.hasAttribute("data-composition-src") || el.hasAttribute("data-composition-file");
7
- }
8
-
9
- /** What a Layers row tells a person an element is: its media tag, a group, text, or else a shape. */
10
- export function layerKindOf(el: Element, hasChildren: boolean): LayerKind {
11
- const tag = el.tagName.toLowerCase();
12
- if (tag === "img" || tag === "picture") return "image";
13
- if (tag === "video") return "video";
14
- if (tag === "audio") return "audio";
15
- if (tag === "svg") return "vector";
16
- if (el.hasAttribute("data-hf-group") || isCompositionHost(el)) return "group";
17
- if (hasOnlyFormattingChildren(el as HTMLElement) && el.textContent?.trim()) return "text";
18
- return hasChildren ? "group" : "shape";
19
- }
1
+ // One kind rule for Studio's Layers rows and the runtime that lists an opaque frame's layers.
2
+ export { isCompositionHost, layerKindOf } from "@hyperframes/core/runtime/editing-port";