@hyperframes/studio 0.9.38 → 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.
Files changed (50) hide show
  1. package/dist/assets/{codec-Dz2VdhdD.js → codec-BPK_2CLL.js} +1 -1
  2. package/dist/assets/{hyperframes-player-BkaWdGLq.js → hyperframes-player-D7qTTDIp.js} +1 -1
  3. package/dist/assets/{index-BJTCbv8z.css → index-4VGEAZyf.css} +1 -1
  4. package/dist/assets/{index-DsNxqAwr.js → index-CdA00Ybn.js} +145 -145
  5. package/dist/assets/{index-DONaC7VF.js → index-QS-DuxAU.js} +1 -1
  6. package/dist/assets/{pausedVideoDecoder-BGN2jKrN.js → pausedVideoDecoder-Byzz98Gb.js} +1 -1
  7. package/dist/{chunk-63DH4LRB.js → chunk-AV2PV7NE.js} +15 -68
  8. package/dist/chunk-FQ3VRKMC.js +148 -0
  9. package/dist/{chunk-YKBN653R.js → chunk-KF6YVXJP.js} +258 -1
  10. package/dist/{chunk-45KKBU63.js → chunk-VZ5MD32A.js} +1 -1
  11. package/dist/{domEditingLayers-7Q56QAU5.js → domEditingLayers-4KRREI5C.js} +2 -2
  12. package/dist/index.d.ts +3 -85
  13. package/dist/index.html +2 -2
  14. package/dist/index.js +321 -341
  15. package/dist/keys-CaWcxUST.d.ts +86 -0
  16. package/dist/keys.d.ts +1 -0
  17. package/dist/keys.js +11 -0
  18. package/dist/player.js +2 -2
  19. package/dist/styles.css +1 -1
  20. package/package.json +12 -8
  21. package/src/components/editor/DomEditGestureReadout.test.tsx +204 -20
  22. package/src/components/editor/DomEditGestureReadout.tsx +36 -18
  23. package/src/components/editor/InlineTextToolbar.tsx +2 -2
  24. package/src/components/editor/domEditGestureReadoutPlacement.ts +144 -0
  25. package/src/components/editor/domEditGestureReadoutState.ts +18 -8
  26. package/src/components/editor/domEditingDom.ts +23 -104
  27. package/src/components/editor/useDomEditCompositionRect.ts +13 -4
  28. package/src/components/editor/useDomEditOverlayGestures.ts +1 -1
  29. package/src/components/editor/usePreviewCompositionRect.test.tsx +39 -0
  30. package/src/hooks/elementPickerStyles.ts +53 -0
  31. package/src/hooks/useElementPicker.test.ts +83 -3
  32. package/src/hooks/useElementPicker.ts +27 -66
  33. package/src/keys.test.ts +53 -0
  34. package/src/keys.ts +11 -0
  35. package/src/player/components/Player.tsx +2 -0
  36. package/src/player/components/studioKeyDefaults.ts +68 -0
  37. package/src/player/components/studioShortcuts.ts +2 -67
  38. package/src/player/hooks/playbackAdapterResolution.ts +15 -0
  39. package/src/player/hooks/previewMessageRouter.manifest.test.ts +67 -0
  40. package/src/player/hooks/previewMessageRouter.ts +38 -8
  41. package/src/player/hooks/timelinePlayerTestHarness.ts +26 -1
  42. package/src/player/hooks/useShadowPreviewReload.ts +4 -1
  43. package/src/player/hooks/useTimelinePlayer.ts +5 -9
  44. package/src/player/lib/bridgePlayback.ts +156 -0
  45. package/src/player/lib/previewChannel.test.ts +260 -0
  46. package/src/player/lib/previewChannel.ts +115 -0
  47. package/src/player/lib/previewElements.test.ts +167 -0
  48. package/src/player/lib/previewElements.ts +117 -0
  49. package/src/player/sceneSwap.test.ts +12 -0
  50. package/src/player/sceneSwap.ts +2 -0
@@ -3,11 +3,15 @@
3
3
  * selector utilities, and composition source resolution.
4
4
  * No imports from other domEditing* modules — safe to import from anywhere.
5
5
  */
6
- import {
7
- PREVIEW_VIDEO_FRAME_ATTR,
8
- PREVIEW_VIDEO_CANVAS_ATTR,
9
- } from "@hyperframes/core/studio-preview-mark";
6
+ import { getLogicalOpacity } from "@hyperframes/core/studio-preview-mark";
10
7
  import { COLOR_GRADING_SOURCE_HIDDEN_ATTR } from "@hyperframes/core/color-grading";
8
+ import {
9
+ buildStableSelector,
10
+ escapeCssString,
11
+ getPreferredClassSelector,
12
+ readElementSource,
13
+ type EditingElementSource,
14
+ } from "@hyperframes/core/runtime/editing-port";
11
15
  import { getSourceScopedSelectorIndex } from "../../utils/sourceScopedSelectorIndex";
12
16
  import { CURATED_STYLE_PROPERTIES } from "./domEditingTypes";
13
17
 
@@ -38,17 +42,9 @@ export function isEditableTextLeaf(el: HTMLElement): boolean {
38
42
  return isTextBearingTag(el.tagName.toLowerCase()) && el.children.length === 0;
39
43
  }
40
44
 
41
- /** The preview canvas keeps the source's authored opacity while its native pixels are hidden. */
42
- export function getLogicalOpacity(el: Element, computed: CSSStyleDeclaration): string {
43
- const overlay = el.previousElementSibling;
44
- if (
45
- el.hasAttribute(PREVIEW_VIDEO_FRAME_ATTR) &&
46
- overlay?.localName === "canvas" &&
47
- overlay.hasAttribute(PREVIEW_VIDEO_CANVAS_ATTR)
48
- )
49
- return el.ownerDocument.defaultView?.getComputedStyle(overlay).opacity ?? computed.opacity;
50
- return computed.opacity;
51
- }
45
+ export { getLogicalOpacity };
46
+ // One addressing rule for Studio and the runtime that describes elements to it.
47
+ export { buildStableSelector, escapeCssString };
52
48
 
53
49
  /** Does this node render AT ALL, ignoring what it inherits? Sole owner of the
54
50
  * rule; the walk below only decides which nodes to ask it about. */
@@ -184,33 +180,24 @@ export function getCompositionSourceMapRevision(): number {
184
180
  return compositionSourceMapRevision;
185
181
  }
186
182
 
187
- function sourceFromCompositionId(ownerRoot: HTMLElement | null): string | undefined {
188
- if (!ownerRoot || compositionSourceMap.size === 0) return undefined;
189
- // The runtime may rename the mounted id to a runtime-unique one, preserving the
190
- // authored id on `data-hf-original-composition-id` — prefer that, then the current id.
191
- const authored = ownerRoot.getAttribute("data-hf-original-composition-id");
192
- const current = ownerRoot.getAttribute("data-composition-id");
193
- return (
194
- (authored ? compositionSourceMap.get(authored) : undefined) ??
195
- (current ? compositionSourceMap.get(current) : undefined)
196
- );
183
+ /** The source file `source` names (see `EditingElementSource`), with this project's composition map. */
184
+ export function resolveElementSourceFile(
185
+ source: EditingElementSource,
186
+ activeCompositionPath: string | null,
187
+ ): string {
188
+ const { file, compositionId, originalCompositionId } = source;
189
+ const mapped = compositionSourceMap.size
190
+ ? ((originalCompositionId ? compositionSourceMap.get(originalCompositionId) : undefined) ??
191
+ (compositionId ? compositionSourceMap.get(compositionId) : undefined))
192
+ : undefined;
193
+ return file ?? mapped ?? activeCompositionPath ?? "index.html";
197
194
  }
198
195
 
199
196
  export function getSourceFileForElement(
200
197
  el: HTMLElement,
201
198
  activeCompositionPath: string | null,
202
199
  ): { sourceFile: string; compositionPath: string } {
203
- const sourceHost = findClosestByAttribute(el, ["data-composition-file", "data-composition-src"]);
204
- const ownerRoot = findClosestByAttribute(el, ["data-composition-id"]);
205
- const sourceFile =
206
- sourceHost?.getAttribute("data-composition-file") ??
207
- sourceHost?.getAttribute("data-composition-src") ??
208
- ownerRoot?.getAttribute("data-composition-file") ??
209
- ownerRoot?.getAttribute("data-composition-src") ??
210
- sourceFromCompositionId(ownerRoot) ??
211
- activeCompositionPath ??
212
- "index.html";
213
-
200
+ const sourceFile = resolveElementSourceFile(readElementSource(el), activeCompositionPath);
214
201
  return {
215
202
  sourceFile,
216
203
  compositionPath: sourceFile,
@@ -241,49 +228,6 @@ export function normalizeTimelineCompositionSource(value: string | undefined): s
241
228
 
242
229
  // ─── CSS escaping ─────────────────────────────────────────────────────────────
243
230
 
244
- function escapeCssIdentifier(value: string): string {
245
- const css = globalThis.CSS as { escape?: (input: string) => string } | undefined;
246
- if (typeof css?.escape === "function") return css.escape(value);
247
-
248
- if (value === "-") return "\\-";
249
-
250
- let escaped = "";
251
- for (let index = 0; index < value.length; index += 1) {
252
- const char = value[index] ?? "";
253
- const code = char.charCodeAt(0);
254
- if (code === 0) {
255
- escaped += "�";
256
- continue;
257
- }
258
-
259
- const isDigit = code >= 48 && code <= 57;
260
- const isUpperAlpha = code >= 65 && code <= 90;
261
- const isLowerAlpha = code >= 97 && code <= 122;
262
- const isControl = (code >= 1 && code <= 31) || code === 127;
263
- const isLeadingDigit = index === 0 && isDigit;
264
- const isSecondDigitAfterDash = index === 1 && value.startsWith("-") && isDigit;
265
- if (isControl || isLeadingDigit || isSecondDigitAfterDash) {
266
- escaped += `\\${code.toString(16)} `;
267
- continue;
268
- }
269
- if (isUpperAlpha || isLowerAlpha || isDigit || char === "-" || char === "_" || code >= 128) {
270
- escaped += char;
271
- continue;
272
- }
273
- escaped += `\\${char}`;
274
- }
275
- return escaped;
276
- }
277
-
278
- export function escapeCssString(value: string): string {
279
- return value
280
- .replace(/\\/g, "\\\\")
281
- .replace(/"/g, '\\"')
282
- .replace(/\n/g, "\\a ")
283
- .replace(/\r/g, "\\d ")
284
- .replace(/\f/g, "\\c ");
285
- }
286
-
287
231
  export function querySelectorAllSafely(doc: Document, selector: string): Element[] {
288
232
  try {
289
233
  return Array.from(doc.querySelectorAll(selector));
@@ -306,31 +250,6 @@ function humanizeIdentifier(value: string): string {
306
250
 
307
251
  // ─── CSS selector building ────────────────────────────────────────────────────
308
252
 
309
- export function buildStableSelector(el: HTMLElement): string | undefined {
310
- if (el.id) return `#${escapeCssIdentifier(el.id)}`;
311
-
312
- const compositionId = el.getAttribute("data-composition-id");
313
- if (compositionId) return `[data-composition-id="${escapeCssString(compositionId)}"]`;
314
-
315
- // Group wrappers carry no id/class; their data-hf-group value is the unique,
316
- // stable handle the source mutations write — use it so the wrapper is
317
- // selectable, patchable (move/scale), and addressable for ungroup.
318
- const group = el.getAttribute("data-hf-group");
319
- if (group) return `[data-hf-group="${escapeCssString(group)}"]`;
320
-
321
- return getPreferredClassSelector(el);
322
- }
323
-
324
- function getPreferredClassSelector(el: HTMLElement): string | undefined {
325
- const classes = Array.from(el.classList)
326
- .map((value) => value.trim())
327
- .filter(Boolean);
328
- if (classes.length === 0) return undefined;
329
- const preferred =
330
- classes.find((value) => value !== "clip" && !value.startsWith("__hf-")) ?? classes[0];
331
- return preferred ? `.${escapeCssIdentifier(preferred)}` : undefined;
332
- }
333
-
334
253
  // fallow-ignore-next-line complexity
335
254
  export function buildElementLabel(el: HTMLElement): string {
336
255
  const compositionId =
@@ -1,6 +1,8 @@
1
1
  import { useState, type RefObject } from "react";
2
2
  import { useMountEffect } from "../../hooks/useMountEffect";
3
3
  import { subscribeOverlayFrame } from "./overlayFrameLoop";
4
+ import { previewStageSize } from "../../player/lib/bridgePlayback";
5
+ import { previewFrameOpaque } from "../../player/lib/previewChannel";
4
6
 
5
7
  export interface DomEditCompositionRect {
6
8
  left: number;
@@ -23,6 +25,16 @@ function sameRect(a: DomEditCompositionRect, b: DomEditCompositionRect): boolean
23
25
  );
24
26
  }
25
27
 
28
+ function declaredCompositionSize(iframe: HTMLIFrameElement): { width: number; height: number } {
29
+ if (previewFrameOpaque(iframe)) return previewStageSize(iframe) ?? { width: NaN, height: NaN };
30
+ const doc = iframe.contentDocument;
31
+ const root = doc?.querySelector<HTMLElement>("[data-composition-id]") ?? doc?.documentElement;
32
+ return {
33
+ width: Number.parseFloat(root?.getAttribute("data-width") ?? ""),
34
+ height: Number.parseFloat(root?.getAttribute("data-height") ?? ""),
35
+ };
36
+ }
37
+
26
38
  export function useDomEditCompositionRect({
27
39
  iframeRef,
28
40
  overlayRef,
@@ -50,10 +62,7 @@ export function useDomEditCompositionRect({
50
62
  const left = iRect.left - oRect.left;
51
63
  const top = iRect.top - oRect.top;
52
64
  if (iRect.width <= 0 || iRect.height <= 0) return;
53
- const doc = iframe.contentDocument;
54
- const root = doc?.querySelector<HTMLElement>("[data-composition-id]") ?? doc?.documentElement;
55
- const dw = Number.parseFloat(root?.getAttribute("data-width") ?? "");
56
- const dh = Number.parseFloat(root?.getAttribute("data-height") ?? "");
65
+ const { width: dw, height: dh } = declaredCompositionSize(iframe);
57
66
  const scaleX = dw > 0 ? iRect.width / dw : 1;
58
67
  const scaleY = dh > 0 ? iRect.height / dh : 1;
59
68
  const next = { left, top, width: iRect.width, height: iRect.height, scaleX, scaleY };
@@ -165,7 +165,7 @@ export function createDomEditOverlayGestureHandlers(opts: UseDomEditOverlayGestu
165
165
  actualAngle: g.actualRotation,
166
166
  snap: e.shiftKey,
167
167
  });
168
- readout.updateGestureReadoutAngle(g.readout, rotated.angle);
168
+ readout.updateGestureReadoutAngle(g.readout, rotated.angle, g.actualRotation);
169
169
  applyRotationDraft(sel.element, rotated.angle, g.plainRotation);
170
170
  return;
171
171
  }
@@ -9,6 +9,7 @@ import {
9
9
  type PreviewCompositionRect,
10
10
  } from "./usePreviewCompositionRect";
11
11
  import { usePlayerStore } from "../../player/store/playerStore";
12
+ import { watchPreviewFrame } from "../../player/lib/bridgePlayback";
12
13
 
13
14
  (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
14
15
 
@@ -103,4 +104,42 @@ describe("usePreviewCompositionRect", () => {
103
104
  });
104
105
  probe.unmount();
105
106
  });
107
+
108
+ it("scales an opaque frame by the size its runtime posts, only from the frame's own origin", async () => {
109
+ const frame = {};
110
+ Object.defineProperty(frame, "document", {
111
+ get: () => {
112
+ throw new DOMException("blocked", "SecurityError");
113
+ },
114
+ });
115
+ const iframe = boxed(document.createElement("iframe"), [110, 70, 960, 540]);
116
+ iframe.setAttribute("sandbox", "allow-scripts");
117
+ Object.defineProperty(iframe, "contentWindow", { value: frame });
118
+ Object.defineProperty(iframe, "contentDocument", { value: null });
119
+ watchPreviewFrame(iframe);
120
+ const stageSize = (width: number, origin: string) =>
121
+ window.dispatchEvent(
122
+ new MessageEvent("message", {
123
+ source: frame as Window,
124
+ origin,
125
+ data: { source: "hf-preview", type: "stage-size", width, height: 1080 },
126
+ }),
127
+ );
128
+ stageSize(1920, "null");
129
+ stageSize(960, window.location.origin);
130
+ const probe = mountProbe();
131
+ await act(async () => {
132
+ probe.setIframe(iframe);
133
+ await settle();
134
+ });
135
+ expect(probe.read()).toEqual({
136
+ left: 100,
137
+ top: 50,
138
+ width: 960,
139
+ height: 540,
140
+ scaleX: 0.5,
141
+ scaleY: 0.5,
142
+ });
143
+ probe.unmount();
144
+ });
106
145
  });
@@ -0,0 +1,53 @@
1
+ import { getLogicalOpacity } from "../components/editor/domEditingDom";
2
+
3
+ export const PICKED_STYLE_PROPERTIES = [
4
+ "position",
5
+ "top",
6
+ "left",
7
+ "right",
8
+ "bottom",
9
+ "width",
10
+ "height",
11
+ "margin-top",
12
+ "margin-right",
13
+ "margin-bottom",
14
+ "margin-left",
15
+ "padding-top",
16
+ "padding-right",
17
+ "padding-bottom",
18
+ "padding-left",
19
+ "font-size",
20
+ "font-weight",
21
+ "font-family",
22
+ "color",
23
+ "background-color",
24
+ "background",
25
+ "opacity",
26
+ "border-radius",
27
+ "transform",
28
+ "z-index",
29
+ ];
30
+
31
+ /** Read a subset of computed styles from an element in the iframe */
32
+ export function readComputedStyles(
33
+ iframe: HTMLIFrameElement,
34
+ selector: string,
35
+ ): Record<string, string> {
36
+ const styles: Record<string, string> = {};
37
+ try {
38
+ const doc = iframe.contentDocument;
39
+ const el = doc?.querySelector(selector);
40
+ if (!el) return styles;
41
+ const computed = iframe.contentWindow?.getComputedStyle(el);
42
+ if (!computed) return styles;
43
+
44
+ for (const prop of PICKED_STYLE_PROPERTIES) {
45
+ const val =
46
+ prop === "opacity" ? getLogicalOpacity(el, computed) : computed.getPropertyValue(prop);
47
+ if (val) styles[prop] = val;
48
+ }
49
+ } catch {
50
+ /* cross-origin */
51
+ }
52
+ return styles;
53
+ }
@@ -5,6 +5,7 @@ import { ensureHfIds } from "@hyperframes/parsers/hf-ids";
5
5
  import { runtimeProtocolMetadata } from "@hyperframes/core/runtime/protocol";
6
6
  import { afterEach, describe, expect, it, vi } from "vitest";
7
7
  import { useElementPicker } from "./useElementPicker";
8
+ import { serveEditingRequests } from "../player/hooks/timelinePlayerTestHarness";
8
9
 
9
10
  // As the host leaves it on disk: hf-ids pinned, no element ids.
10
11
  const SAVED = ensureHfIds(`<!doctype html><html><body>
@@ -20,12 +21,13 @@ afterEach(() => {
20
21
  vi.restoreAllMocks();
21
22
  });
22
23
 
23
- // The runtime's element-picked message, posted by `from`.
24
- const picked = (from: Window | null, selector: string) =>
24
+ // The runtime's element-picked message, posted by `from`, from this page's origin unless told otherwise.
25
+ const picked = (from: Window | null, selector: string, origin = window.location.origin) =>
25
26
  act(() => {
26
27
  window.dispatchEvent(
27
28
  new MessageEvent("message", {
28
29
  source: from,
30
+ origin,
29
31
  data: {
30
32
  source: "hf-preview",
31
33
  type: "element-picked",
@@ -36,11 +38,16 @@ const picked = (from: Window | null, selector: string) =>
36
38
  );
37
39
  });
38
40
 
39
- const pickerMessage = (from: Window | null, data: Record<string, unknown>) =>
41
+ const pickerMessage = (
42
+ from: Window | null,
43
+ data: Record<string, unknown>,
44
+ origin = window.location.origin,
45
+ ) =>
40
46
  act(() => {
41
47
  window.dispatchEvent(
42
48
  new MessageEvent("message", {
43
49
  source: from,
50
+ origin,
44
51
  data: {
45
52
  source: "hf-preview",
46
53
  ...data,
@@ -483,3 +490,76 @@ describe("a pick across a reload that swaps the preview frame", () => {
483
490
  expect(picker().pickedElement).toBeNull();
484
491
  });
485
492
  });
493
+
494
+ describe("messages from the picked frame's origin only", () => {
495
+ it("ignores a pick posted by the preview's window from an origin it cannot have", () => {
496
+ const { iframe, picker } = mountPicker({ "index.html": SAVED });
497
+ picked(iframe.contentWindow, "h1.foreign", "https://elsewhere.example");
498
+ picked(iframe.contentWindow, "h1.opaque", "null");
499
+ expect(picker().pickedElement?.selector).toBe("h1");
500
+ });
501
+ });
502
+
503
+ describe("a pick in a frame Studio cannot read", () => {
504
+ /** A sandboxed frame: its window refuses reads, and its runtime answers editing requests. */
505
+ function opaquePreview(answer: (kind: string, params: unknown) => unknown) {
506
+ const frame: Record<string, unknown> = {};
507
+ Object.defineProperty(frame, "document", {
508
+ get: () => {
509
+ throw new DOMException("blocked", "SecurityError");
510
+ },
511
+ });
512
+ const iframe = document.createElement("iframe");
513
+ iframe.setAttribute("sandbox", "allow-scripts");
514
+ Object.defineProperty(iframe, "contentWindow", { value: frame });
515
+ Object.defineProperty(iframe, "contentDocument", { value: null });
516
+ const close = serveEditingRequests(frame, answer);
517
+ let api: ReturnType<typeof useElementPicker> | null = null;
518
+ function Harness() {
519
+ api = useElementPicker({ current: iframe });
520
+ return null;
521
+ }
522
+ root = createRoot(document.createElement("div"));
523
+ act(() => root?.render(React.createElement(Harness)));
524
+ return { frame: frame as unknown as Window, close, picker: () => api! };
525
+ }
526
+
527
+ it("takes the picked element's computed styles from its runtime", async () => {
528
+ const asked: unknown[] = [];
529
+ const { frame, close, picker } = opaquePreview((kind, params) => {
530
+ asked.push({ kind, params });
531
+ return { styles: { color: "rgb(1, 2, 3)", opacity: "0.5", injected: "x" } };
532
+ });
533
+ try {
534
+ picked(frame, "h1.title", "null");
535
+ expect(picker().pickedElement?.computedStyles).toEqual({});
536
+ await vi.waitFor(() =>
537
+ expect(picker().pickedElement?.computedStyles).toEqual({
538
+ color: "rgb(1, 2, 3)",
539
+ opacity: "0.5",
540
+ }),
541
+ );
542
+ expect(asked).toEqual([
543
+ {
544
+ kind: "computed-styles",
545
+ params: {
546
+ selector: "h1.title",
547
+ properties: expect.arrayContaining(["color", "opacity"]),
548
+ },
549
+ },
550
+ ]);
551
+ } finally {
552
+ close();
553
+ }
554
+ });
555
+
556
+ it("ignores a pick from the frame's window that does not come from an opaque origin", () => {
557
+ const { frame, close, picker } = opaquePreview(() => ({ styles: {} }));
558
+ try {
559
+ picked(frame, "h1", window.location.origin);
560
+ expect(picker().pickedElement).toBeNull();
561
+ } finally {
562
+ close();
563
+ }
564
+ });
565
+ });
@@ -12,7 +12,10 @@ import {
12
12
  postRuntimeControlMessage,
13
13
  } from "../player/lib/runtimeProtocol";
14
14
  import { compositionPathOfPreviewUrl } from "../player/components/CompositionThumbnail";
15
- import { getLogicalOpacity, getSourceFileForElement } from "../components/editor/domEditingDom";
15
+ import { frameOrigins } from "../player/lib/bridgePlayback";
16
+ import { previewComputedStyles, previewFrameOpaque } from "../player/lib/previewChannel";
17
+ import { PICKED_STYLE_PROPERTIES, readComputedStyles } from "./elementPickerStyles";
18
+ import { getSourceFileForElement } from "../components/editor/domEditingDom";
16
19
  import {
17
20
  createElementPickerHoverLabel,
18
21
  type ElementPickerHoverInfo,
@@ -173,7 +176,19 @@ function useElementPickerSession(
173
176
  setPickedElement(null);
174
177
  }, []);
175
178
 
176
- const windowsThatWerePrimary = useRef(new WeakSet<MessageEventSource>());
179
+ const originsOfWindowsThatWerePrimary = useRef(new WeakMap<MessageEventSource, string[]>());
180
+
181
+ const showPicked = useCallback((next: PickedElement, iframe: HTMLIFrameElement) => {
182
+ pickedElementRef.current = next;
183
+ setPickedElement(next);
184
+ if (!previewFrameOpaque(iframe)) return;
185
+ void previewComputedStyles(iframe, next.selector, PICKED_STYLE_PROPERTIES).then((styles) => {
186
+ if (!styles || pickedElementRef.current !== next) return;
187
+ const filled = { ...next, computedStyles: styles };
188
+ pickedElementRef.current = filled;
189
+ setPickedElement(filled);
190
+ });
191
+ }, []);
177
192
 
178
193
  useEffect(() => {
179
194
  if (!isPickMode) return;
@@ -204,13 +219,14 @@ function useElementPickerSession(
204
219
  const activeIframe = getActiveIframe();
205
220
  if (!activeIframe) return;
206
221
  if (!e.source) return;
207
- if (e.source === iframeRef.current?.contentWindow)
208
- windowsThatWerePrimary.current.add(e.source);
209
- else if (
210
- e.source !== activeIframe.contentWindow &&
211
- !windowsThatWerePrimary.current.has(e.source)
212
- )
213
- return;
222
+ const primary = iframeRef.current;
223
+ if (primary && e.source === primary.contentWindow)
224
+ originsOfWindowsThatWerePrimary.current.set(e.source, frameOrigins(primary));
225
+ const origins =
226
+ e.source === activeIframe.contentWindow
227
+ ? frameOrigins(activeIframe)
228
+ : originsOfWindowsThatWerePrimary.current.get(e.source);
229
+ if (!origins?.includes(e.origin)) return;
214
230
 
215
231
  if (data.type === "element-hovered") {
216
232
  if (e.source !== activeIframe.contentWindow || !isPickModeRef.current) return;
@@ -220,9 +236,7 @@ function useElementPickerSession(
220
236
  }
221
237
 
222
238
  if (data.type === "element-picked" && data.elementInfo) {
223
- const next = toPickedElement(data.elementInfo, activeIframe);
224
- pickedElementRef.current = next;
225
- setPickedElement(next);
239
+ showPicked(toPickedElement(data.elementInfo, activeIframe), activeIframe);
226
240
  pickStartSelectionRef.current = undefined;
227
241
  isPickModeRef.current = false;
228
242
  clearHover();
@@ -230,11 +244,7 @@ function useElementPickerSession(
230
244
  } else if (data.type === "element-pick-candidates") {
231
245
  // Multiple candidates at click point — pick the first one
232
246
  const el = data.candidates?.[data.selectedIndex ?? 0];
233
- if (el) {
234
- const next = toPickedElement(el, activeIframe);
235
- pickedElementRef.current = next;
236
- setPickedElement(next);
237
- }
247
+ if (el) showPicked(toPickedElement(el, activeIframe), activeIframe);
238
248
  }
239
249
 
240
250
  if (data.type === "pick-mode-cancelled") {
@@ -549,52 +559,3 @@ function patchByHfId(
549
559
  const before = path ? files[path] : undefined;
550
560
  return path && before ? { path, before, after: applyPatchByTarget(before, { hfId }, op) } : null;
551
561
  }
552
-
553
- /** Read a subset of computed styles from an element in the iframe */
554
- function readComputedStyles(iframe: HTMLIFrameElement, selector: string): Record<string, string> {
555
- const styles: Record<string, string> = {};
556
- try {
557
- const doc = iframe.contentDocument;
558
- const el = doc?.querySelector(selector);
559
- if (!el) return styles;
560
- const computed = iframe.contentWindow?.getComputedStyle(el);
561
- if (!computed) return styles;
562
-
563
- const props = [
564
- "position",
565
- "top",
566
- "left",
567
- "right",
568
- "bottom",
569
- "width",
570
- "height",
571
- "margin-top",
572
- "margin-right",
573
- "margin-bottom",
574
- "margin-left",
575
- "padding-top",
576
- "padding-right",
577
- "padding-bottom",
578
- "padding-left",
579
- "font-size",
580
- "font-weight",
581
- "font-family",
582
- "color",
583
- "background-color",
584
- "background",
585
- "opacity",
586
- "border-radius",
587
- "transform",
588
- "z-index",
589
- ];
590
-
591
- for (const prop of props) {
592
- const val =
593
- prop === "opacity" ? getLogicalOpacity(el, computed) : computed.getPropertyValue(prop);
594
- if (val) styles[prop] = val;
595
- }
596
- } catch {
597
- /* cross-origin */
598
- }
599
- return styles;
600
- }
@@ -0,0 +1,53 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { dirname, join, relative, resolve, sep } from "node:path";
3
+ import ts from "typescript";
4
+ import { describe, expect, it } from "vitest";
5
+
6
+ const src = import.meta.dirname;
7
+
8
+ /** Every file `entry` reaches through static imports and re-exports, with any package it names. */
9
+ function importGraph(entry: string): { files: string[]; packages: string[] } {
10
+ const files = new Set<string>();
11
+ const packages = new Set<string>();
12
+ const visit = (file: string) => {
13
+ if (files.has(file)) return;
14
+ files.add(file);
15
+ for (const { fileName } of ts.preProcessFile(readFileSync(file, "utf8")).importedFiles) {
16
+ if (!fileName.startsWith(".")) {
17
+ packages.add(fileName);
18
+ continue;
19
+ }
20
+ const base = resolve(dirname(file), fileName);
21
+ visit(
22
+ [`${base}.ts`, `${base}.tsx`, join(base, "index.ts")].find((f) => ts.sys.fileExists(f))!,
23
+ );
24
+ }
25
+ };
26
+ visit(join(src, entry));
27
+ return {
28
+ files: [...files].map((f) => relative(src, f).split(sep).join("/")).sort(),
29
+ packages: [...packages],
30
+ };
31
+ }
32
+
33
+ describe("@hyperframes/studio/keys", () => {
34
+ it("imports only the key helpers: no package and no editor module", () => {
35
+ expect(importGraph("keys.ts")).toEqual({
36
+ files: [
37
+ "keys.ts",
38
+ "player/components/studioCombo.ts",
39
+ "player/components/studioKeyDefaults.ts",
40
+ ],
41
+ packages: [],
42
+ });
43
+ });
44
+
45
+ it("is a published subpath sharing the defaults the root entry exports", async () => {
46
+ const pkg = JSON.parse(readFileSync(join(src, "../package.json"), "utf8"));
47
+ expect(pkg.exports["./keys"].import).toBe("./src/keys.ts");
48
+ expect(pkg.publishConfig.exports["./keys"].import).toBe("./dist/keys.js");
49
+ const keys = await import("./keys");
50
+ const shortcuts = await import("./player/components/studioShortcuts");
51
+ expect(keys.DEFAULT_STUDIO_KEYS).toBe(shortcuts.DEFAULT_STUDIO_KEYS);
52
+ });
53
+ });
package/src/keys.ts ADDED
@@ -0,0 +1,11 @@
1
+ export {
2
+ matchCombo,
3
+ parseCombo,
4
+ type Combo,
5
+ type ComboEvent,
6
+ } from "./player/components/studioCombo";
7
+ export {
8
+ DEFAULT_STUDIO_KEYS,
9
+ type StudioKeyAction,
10
+ type StudioKeys,
11
+ } from "./player/components/studioKeyDefaults";
@@ -8,6 +8,7 @@ import { HyperframesLoader } from "../../components/ui";
8
8
  import { usePlayerStore } from "../store/playerStore";
9
9
  import { announcePreviewDocumentLoaded } from "../sceneSwap";
10
10
  import type { IframeWindow } from "../lib/playbackTypes";
11
+ import { watchPreviewFrame } from "../lib/bridgePlayback";
11
12
  // Importing "@hyperframes/player" registers a class extending HTMLElement at
12
13
  // module load, which throws under SSR, hence the dynamic import behind a
13
14
  // `typeof window` guard. Kicking it here rather than in the mount effect puts
@@ -353,6 +354,7 @@ export const Player = forwardRef<HTMLIFrameElement, PlayerProps>(
353
354
  loadIdRef.current += 1;
354
355
  player.setAttribute("src", src);
355
356
  container.appendChild(player);
357
+ watchPreviewFrame(iframe);
356
358
 
357
359
  enableInteractiveIframe(player);
358
360