@hyperframes/studio 0.9.39 → 0.9.40

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.
@@ -0,0 +1,167 @@
1
+ // @vitest-environment happy-dom
2
+
3
+ import { afterEach, describe, expect, it, vi } from "vitest";
4
+ import type { EditingElementDescription } from "@hyperframes/core/runtime/editing-port";
5
+ import {
6
+ describePreviewElements,
7
+ previewElementSelectorIndex,
8
+ previewElementSourceFile,
9
+ previewElementsAtPoint,
10
+ readPreviewElement,
11
+ type PreviewElement,
12
+ } from "./previewElements";
13
+ import { AGENT_PROBE_MS, previewComputedStyles } from "./previewChannel";
14
+ import {
15
+ getSelectorIndex,
16
+ getSourceFileForElement,
17
+ setCompositionSourceMap,
18
+ } from "../../components/editor/domEditingDom";
19
+ import { detachedFakeIframe, serveEditingRequests } from "../hooks/timelinePlayerTestHarness";
20
+
21
+ const closers: Array<() => void> = [];
22
+ afterEach(() => {
23
+ closers.splice(0).forEach((close) => close());
24
+ setCompositionSourceMap(new Map());
25
+ document.body.innerHTML = "";
26
+ });
27
+
28
+ /** A frame Studio cannot read; `answer` is its runtime, or it has none. */
29
+ function opaqueFrame(answer?: (kind: string, params: unknown) => unknown) {
30
+ const frame: Record<string, unknown> = { postMessage: () => {} };
31
+ const iframe = detachedFakeIframe(frame);
32
+ Object.defineProperty(iframe, "contentDocument", { value: null });
33
+ Object.defineProperty(frame, "document", {
34
+ get: () => {
35
+ throw new DOMException("blocked", "SecurityError");
36
+ },
37
+ });
38
+ const handed = vi.fn(answer ?? (() => null));
39
+ if (answer) closers.push(serveEditingRequests(frame, handed));
40
+ return { iframe, handed };
41
+ }
42
+
43
+ const NO_SOURCE = { file: null, compositionId: null, originalCompositionId: null };
44
+
45
+ const LOAD = "0123456789abcdef";
46
+ const h = (n: number) => `${LOAD}:${n}`;
47
+
48
+ function described(n: number, extra: Partial<EditingElementDescription> = {}) {
49
+ return {
50
+ handle: h(n),
51
+ parent: null,
52
+ tag: "div",
53
+ id: null,
54
+ selector: null,
55
+ matchesBefore: null,
56
+ source: NO_SOURCE,
57
+ locked: false,
58
+ attributes: [["data-hf-id", `hf-${n}`]],
59
+ inlineStyles: { left: "4px" },
60
+ text: "",
61
+ children: [{ text: "Hi" }, { handle: h(n + 1) }],
62
+ rect: { x: 1, y: 2, width: 3, height: 4 },
63
+ truncated: false,
64
+ ...extra,
65
+ } as EditingElementDescription;
66
+ }
67
+
68
+ describe("readPreviewElement", () => {
69
+ it("takes a description with the wire shape and refuses anything off it", () => {
70
+ expect(readPreviewElement(described(1))).toEqual(described(1));
71
+ for (const bad of [
72
+ null,
73
+ [],
74
+ described(1, { handle: 1 as never }),
75
+ described(1, { handle: "1" }),
76
+ described(1, { handle: `${LOAD}:0` }),
77
+ described(1, { handle: `${LOAD.toUpperCase()}:1` }),
78
+ described(1, { parent: "x" }),
79
+ described(1, { tag: 1 as never }),
80
+ described(1, { source: { file: 1 } as never }),
81
+ described(1, { locked: "yes" as never }),
82
+ described(1, { attributes: [["a"]] as never }),
83
+ described(1, { inlineStyles: { left: 4 } as never }),
84
+ described(1, { children: [{ node: {} }] as never }),
85
+ described(1, { matchesBefore: [{ source: NO_SOURCE, count: -1 }] }),
86
+ described(1, { rect: { x: Number.NaN, y: 0, width: 0, height: 0 } }),
87
+ described(1, { truncated: undefined as never }),
88
+ ]) {
89
+ expect(readPreviewElement(bad)).toBeNull();
90
+ }
91
+ });
92
+ });
93
+
94
+ describe("element requests over an opaque frame's port", () => {
95
+ it("asks for the stack under a point and keeps only well-formed entries", async () => {
96
+ const hit = { handle: h(1), tag: "p", rect: { x: 1, y: 2, width: 3, height: 4 } };
97
+ const bad = [
98
+ { ...hit, handle: "x" },
99
+ { ...hit, tag: 1 },
100
+ { ...hit, rect: { x: 1 } },
101
+ ];
102
+ const { iframe, handed } = opaqueFrame(() => ({ elements: [hit, ...bad] }));
103
+ expect(await previewElementsAtPoint(iframe, 10, 20)).toEqual([hit]);
104
+ expect(handed).toHaveBeenCalledWith("elements-at-point", { x: 10, y: 20 });
105
+ });
106
+
107
+ it("describes handles in order, with null for a gone element or a mismatched entry", async () => {
108
+ let reply: unknown = { elements: [described(2), null, described(9)] };
109
+ const { iframe, handed } = opaqueFrame(() => reply);
110
+ const asked = [h(2), h(3), h(4)];
111
+ expect(await describePreviewElements(iframe, asked)).toEqual([described(2), null, null]);
112
+ expect(handed).toHaveBeenCalledWith("describe", { handles: asked });
113
+ reply = { elements: [described(2)] };
114
+ expect(await describePreviewElements(iframe, [h(2), h(3)])).toBeNull();
115
+ handed.mockClear();
116
+ expect(await describePreviewElements(iframe, [])).toBeNull();
117
+ expect(await describePreviewElements(iframe, Array(257).fill(h(1)))).toBeNull();
118
+ expect(handed).not.toHaveBeenCalled();
119
+ });
120
+
121
+ it("gives up after the agent probe when the frame's runtime has no editing agent", async () => {
122
+ const { iframe } = opaqueFrame();
123
+ const started = Date.now();
124
+ const answers = await Promise.all([
125
+ previewComputedStyles(iframe, "#a", ["color"]),
126
+ previewElementsAtPoint(iframe, 1, 1),
127
+ describePreviewElements(iframe, [h(1)]),
128
+ ]);
129
+ expect(answers).toEqual([null, null, null]);
130
+ expect(Date.now() - started).toBeLessThan(AGENT_PROBE_MS + 500);
131
+ });
132
+ });
133
+
134
+ describe("source file and selector index from a description", () => {
135
+ it("answers what Studio reads off the frame's own element", () => {
136
+ setCompositionSourceMap(new Map([["card", "cards.html"]]));
137
+ document.body.innerHTML = `
138
+ <div class="tile"></div>
139
+ <div data-composition-file="cards.html"><div class="tile"></div></div>
140
+ <div data-composition-id="card__hf2" data-hf-original-composition-id="card">
141
+ <div class="tile"></div><div class="tile"></div>
142
+ </div>`;
143
+ const target = document.querySelectorAll<HTMLElement>(".tile")[3]!;
144
+ const element = readPreviewElement(
145
+ described(7, {
146
+ selector: ".tile",
147
+ source: { file: null, compositionId: "card__hf2", originalCompositionId: "card" },
148
+ // As the runtime counts the matches before it: one per distinct source.
149
+ matchesBefore: [
150
+ { source: NO_SOURCE, count: 1 },
151
+ { source: { ...NO_SOURCE, file: "cards.html" }, count: 1 },
152
+ {
153
+ source: { file: null, compositionId: "card__hf2", originalCompositionId: "card" },
154
+ count: 1,
155
+ },
156
+ ],
157
+ }),
158
+ ) as PreviewElement;
159
+ const { sourceFile } = getSourceFileForElement(target, "index.html");
160
+ expect(previewElementSourceFile(element, "index.html")).toBe(sourceFile);
161
+ expect(sourceFile).toBe("cards.html");
162
+ const index = getSelectorIndex(document, target, ".tile", sourceFile, "index.html");
163
+ expect(previewElementSelectorIndex(element, "index.html")).toBe(index);
164
+ expect(index).toBe(2);
165
+ expect(previewElementSelectorIndex({ ...element, matchesBefore: null }, null)).toBeUndefined();
166
+ });
167
+ });
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Elements of a preview frame Studio cannot script, by the handles its runtime gives them. A handle
3
+ * names an element for one load of the frame; after the frame loads again, describe it afresh.
4
+ */
5
+ import {
6
+ EDITING_ELEMENT_HANDLE,
7
+ MAX_DESCRIBE_HANDLES,
8
+ type EditingElementDescription,
9
+ type EditingElementHit,
10
+ type EditingElementSource,
11
+ } from "@hyperframes/core/runtime/editing-port";
12
+ import { resolveElementSourceFile } from "../../components/editor/domEditingDom";
13
+ import { previewRequest } from "./previewChannel";
14
+
15
+ declare const checked: unique symbol;
16
+ /** A description that passed `readPreviewElement`. Only that function makes one. */
17
+ export type PreviewElement = EditingElementDescription & { readonly [checked]: true };
18
+ export type PreviewElementHit = EditingElementHit & { readonly [checked]: true };
19
+
20
+ type Fields = Record<string, unknown>;
21
+ const isFields = (value: unknown): value is Fields =>
22
+ typeof value === "object" && value !== null && !Array.isArray(value);
23
+ const isHandle = (value: unknown) =>
24
+ typeof value === "string" && EDITING_ELEMENT_HANDLE.test(value);
25
+ const isText = (value: unknown) => typeof value === "string";
26
+ const isTextOrNull = (value: unknown) => value === null || typeof value === "string";
27
+ const isCount = (value: unknown) => Number.isSafeInteger(value) && (value as number) >= 0;
28
+
29
+ const isSource = (value: unknown): value is EditingElementSource =>
30
+ isFields(value) &&
31
+ isTextOrNull(value.file) &&
32
+ isTextOrNull(value.compositionId) &&
33
+ isTextOrNull(value.originalCompositionId);
34
+
35
+ const isTextRecord = (value: unknown) => isFields(value) && Object.values(value).every(isText);
36
+
37
+ function hasPlainFields(value: Fields): boolean {
38
+ const { matchesBefore, attributes, children } = value;
39
+ const groupsOk =
40
+ matchesBefore === null ||
41
+ (Array.isArray(matchesBefore) &&
42
+ matchesBefore.every((g) => isFields(g) && isSource(g.source) && isCount(g.count)));
43
+ const attributesOk =
44
+ Array.isArray(attributes) &&
45
+ attributes.every((a) => Array.isArray(a) && a.length === 2 && a.every(isText));
46
+ const childrenOk =
47
+ Array.isArray(children) &&
48
+ children.every((c) => isFields(c) && (isHandle(c.handle) || isText(c.text)));
49
+ return groupsOk && attributesOk && childrenOk && typeof value.truncated === "boolean";
50
+ }
51
+
52
+ function readHit(value: unknown): PreviewElementHit | null {
53
+ if (!isFields(value) || !isHandle(value.handle) || !isText(value.tag)) return null;
54
+ const { rect } = value;
55
+ const rectOk = isFields(rect) && [rect.x, rect.y, rect.width, rect.height].every(Number.isFinite);
56
+ return rectOk ? (value as unknown as PreviewElementHit) : null;
57
+ }
58
+
59
+ /** Frame data checked against `EditingElementDescription`; null when any field is off. */
60
+ export function readPreviewElement(value: unknown): PreviewElement | null {
61
+ if (!readHit(value) || !isFields(value)) return null;
62
+ if (value.parent !== null && !isHandle(value.parent)) return null;
63
+ if (!isTextOrNull(value.id) || !isTextOrNull(value.selector)) return null;
64
+ if (!isSource(value.source) || typeof value.locked !== "boolean") return null;
65
+ if (!isTextRecord(value.inlineStyles) || !isText(value.text)) return null;
66
+ return hasPlainFields(value) ? (value as unknown as PreviewElement) : null;
67
+ }
68
+
69
+ /** The elements under a frame viewport point, topmost first; null when the runtime cannot answer. */
70
+ export async function previewElementsAtPoint(
71
+ iframe: HTMLIFrameElement,
72
+ x: number,
73
+ y: number,
74
+ ): Promise<PreviewElementHit[] | null> {
75
+ const reply = await previewRequest(iframe, "elements-at-point", { x, y });
76
+ const elements: unknown = reply?.elements;
77
+ if (!Array.isArray(elements)) return null;
78
+ return elements.map(readHit).filter((element) => element !== null);
79
+ }
80
+
81
+ /**
82
+ * One entry per handle, in order: null for an element the frame no longer has. The whole answer is
83
+ * null when the runtime cannot answer, or when there are no handles or more than the runtime takes.
84
+ */
85
+ export async function describePreviewElements(
86
+ iframe: HTMLIFrameElement,
87
+ handles: readonly string[],
88
+ ): Promise<Array<PreviewElement | null> | null> {
89
+ if (!handles.length || handles.length > MAX_DESCRIBE_HANDLES) return null;
90
+ const reply = await previewRequest(iframe, "describe", { handles: [...handles] });
91
+ const elements: unknown = reply?.elements;
92
+ if (!Array.isArray(elements) || elements.length !== handles.length) return null;
93
+ return elements.map((entry, index) => {
94
+ const element = readPreviewElement(entry);
95
+ return element?.handle === handles[index] ? element : null;
96
+ });
97
+ }
98
+
99
+ /** `getSourceFileForElement` for the frame's own element. */
100
+ export function previewElementSourceFile(
101
+ element: PreviewElement,
102
+ activeCompositionPath: string | null,
103
+ ): string {
104
+ return resolveElementSourceFile(element.source, activeCompositionPath);
105
+ }
106
+
107
+ /** `getSelectorIndex` for the frame's own element; undefined when the runtime could not count. */
108
+ export function previewElementSelectorIndex(
109
+ element: PreviewElement,
110
+ activeCompositionPath: string | null,
111
+ ): number | undefined {
112
+ if (!element.selector?.startsWith(".") || !element.matchesBefore) return undefined;
113
+ const file = previewElementSourceFile(element, activeCompositionPath);
114
+ return element.matchesBefore
115
+ .filter((group) => resolveElementSourceFile(group.source, activeCompositionPath) === file)
116
+ .reduce((sum, group) => sum + group.count, 0);
117
+ }