@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
@@ -1,5 +1,5 @@
1
1
  {
2
- "total": 226,
2
+ "total": 223,
3
3
  "files": {
4
4
  "packages/studio/src/captions/components/CaptionOverlay.tsx": 5,
5
5
  "packages/studio/src/captions/components/CaptionTimeline.tsx": 11,
@@ -18,7 +18,6 @@
18
18
  "packages/studio/src/components/editor/SnapGuideOverlay.tsx": 3,
19
19
  "packages/studio/src/components/editor/Transform3DCube.tsx": 5,
20
20
  "packages/studio/src/components/editor/colorValue.ts": 3,
21
- "packages/studio/src/components/editor/domEditingElement.ts": 1,
22
21
  "packages/studio/src/components/editor/gradientValue.ts": 6,
23
22
  "packages/studio/src/components/editor/panelTokens.ts": 4,
24
23
  "packages/studio/src/components/editor/propertyPanelColor.tsx": 7,
@@ -103,19 +103,6 @@ export function isManualGeometryStyleProperty(property: string): boolean {
103
103
  return property === "left" || property === "top" || property === "width" || property === "height";
104
104
  }
105
105
 
106
- export function getEventTargetElement(target: EventTarget | null): HTMLElement | null {
107
- if (!target || typeof target !== "object") return null;
108
- const maybeNode = target as {
109
- nodeType?: number;
110
- parentElement?: Element | null;
111
- };
112
- if (maybeNode.nodeType === 1) return target as HTMLElement;
113
- if (maybeNode.nodeType === 3 && maybeNode.parentElement) {
114
- return maybeNode.parentElement as HTMLElement;
115
- }
116
- return null;
117
- }
118
-
119
106
  export function shouldIgnoreHistoryShortcut(target: EventTarget | null): boolean {
120
107
  return isTypingTarget(target);
121
108
  }
@@ -138,7 +138,7 @@ describe("getPreviewTargetFromPointer", () => {
138
138
  stubRect(headline, domRect(44, 44, 220, 48));
139
139
  doc.elementsFromPoint = () => [headline, mask, block, scene];
140
140
 
141
- expect(getPreviewTargetFromPointer(iframe, 80, 64, "index.html")).toBe(headline);
141
+ expect(getPreviewTargetFromPointer(iframe, 80, 64)).toBe(headline);
142
142
  iframe.remove();
143
143
  });
144
144
 
@@ -156,12 +156,12 @@ describe("getPreviewTargetFromPointer", () => {
156
156
  return [headline, scene];
157
157
  };
158
158
  // First call runs the once-per-document inheritance probe, a body mutation.
159
- expect(getPreviewTargetFromPointer(iframe, 80, 64, "index.html")).toBe(headline);
159
+ expect(getPreviewTargetFromPointer(iframe, 80, 64)).toBe(headline);
160
160
  const observer = new MutationObserver(() => {});
161
161
  observer.observe(doc, { subtree: true, childList: true, attributes: true });
162
162
 
163
- expect(getPreviewTargetFromPointer(iframe, 80, 64, "index.html")).toBe(headline);
164
- expect(getAllPreviewTargetsFromPointer(iframe, 80, 64, "index.html")).toEqual([headline]);
163
+ expect(getPreviewTargetFromPointer(iframe, 80, 64)).toBe(headline);
164
+ expect(getAllPreviewTargetsFromPointer(iframe, 80, 64)).toEqual([headline]);
165
165
  const mutations = observer.takeRecords();
166
166
  observer.disconnect();
167
167
 
@@ -197,7 +197,7 @@ describe("getPreviewTargetFromPointer", () => {
197
197
  stubRect(overlay, domRect(0, 0, 360, 260));
198
198
  doc.elementsFromPoint = () => [overlay, overlayParent, headline, scene];
199
199
 
200
- expect(getPreviewTargetFromPointer(iframe, 80, 64, "index.html")).toBe(headline);
200
+ expect(getPreviewTargetFromPointer(iframe, 80, 64)).toBe(headline);
201
201
 
202
202
  iframe.remove();
203
203
  });
@@ -227,7 +227,7 @@ describe("getPreviewTargetFromPointer", () => {
227
227
  stubRect(clickableChild, domRect(40, 40, 80, 24));
228
228
  doc.elementsFromPoint = () => [clickableChild, overlayParent, scene];
229
229
 
230
- expect(getPreviewTargetFromPointer(iframe, 60, 50, "index.html")).toBe(clickableChild);
230
+ expect(getPreviewTargetFromPointer(iframe, 60, 50)).toBe(clickableChild);
231
231
 
232
232
  iframe.remove();
233
233
  });
@@ -256,7 +256,7 @@ describe("getPreviewTargetFromPointer", () => {
256
256
 
257
257
  // Before the fix the video was full-bleed-excluded and the picker fell through
258
258
  // to the backdrop (or null). It must now return the video itself.
259
- expect(getPreviewTargetFromPointer(iframe, 200, 150, "index.html")).toBe(hero);
259
+ expect(getPreviewTargetFromPointer(iframe, 200, 150)).toBe(hero);
260
260
 
261
261
  iframe.remove();
262
262
  });
@@ -281,7 +281,7 @@ describe("getPreviewTargetFromPointer", () => {
281
281
  stubRect(headline, domRect(40, 40, 160, 48));
282
282
  doc.elementsFromPoint = () => [headline, wrapper, scene];
283
283
 
284
- expect(getPreviewTargetFromPointer(iframe, 80, 64, "index.html")).toBe(headline);
284
+ expect(getPreviewTargetFromPointer(iframe, 80, 64)).toBe(headline);
285
285
 
286
286
  iframe.remove();
287
287
  });
@@ -1,232 +1,21 @@
1
- import type { DomEditViewport } from "../components/editor/domEditing";
2
1
  import {
3
- getDomLayerPatchTarget,
4
- isElementComputedVisible,
5
- resolveAllVisualDomEditTargets,
6
- } from "../components/editor/domEditingElement";
7
- import { isHtmlElement } from "../components/editor/domEditingDom";
8
- import { getEventTargetElement } from "./studioHelpers";
2
+ compositionPoint,
3
+ coversComposition,
4
+ pointerTarget,
5
+ pointerTargets,
6
+ } from "@hyperframes/core/runtime/editing-port";
9
7
 
10
- interface PreviewLocalPointer {
11
- x: number;
12
- y: number;
13
- viewport: DomEditViewport;
14
- }
15
-
16
- // An element is "full-bleed" when its box spans nearly the whole composition on
17
- // BOTH axes. Such elements (scene wrappers, backdrops) are excluded from canvas
18
- // click-picking so a click lands on inner content — or deselects on empty area —
19
- // instead of grabbing the giant container. The Layers panel still selects them.
20
- // ponytail: pure size heuristic; tighten the ratio if decorative full-bleed art
21
- // should remain canvas-selectable.
22
- const FULL_BLEED_RATIO = 0.95;
23
-
24
- // Media leaves (a hero/background video, a full-bleed image, an <svg>/<canvas>
25
- // backdrop) ARE the content a user clicks — they must stay canvas-selectable even
26
- // at full-bleed. Only empty containers (scene wrappers, layout backdrops) get
27
- // excluded. Without this, a full-bleed <video> is skipped and the click lands on
28
- // whatever sits behind it — the reported "can't select videos / selects the layer
29
- // behind" bug (and the "needs a second click" symptom, where the first click
30
- // resolves through the video to nothing and only the hover fallback recovers).
31
- const FULL_BLEED_SELECTABLE_MEDIA_TAGS = new Set(["video", "img", "canvas", "svg"]);
32
-
33
- export function coversComposition(
34
- elRect: { width: number; height: number },
35
- viewport: DomEditViewport,
36
- ): boolean {
37
- if (viewport.width <= 1 || viewport.height <= 1) return false;
38
- return (
39
- elRect.width / viewport.width >= FULL_BLEED_RATIO &&
40
- elRect.height / viewport.height >= FULL_BLEED_RATIO
41
- );
42
- }
43
-
44
- function isFullBleedTarget(el: HTMLElement, viewport: DomEditViewport): boolean {
45
- if (FULL_BLEED_SELECTABLE_MEDIA_TAGS.has(el.tagName.toLowerCase())) return false;
46
- return coversComposition(el.getBoundingClientRect(), viewport);
47
- }
48
-
49
- function resolvePreviewLocalPointer(
50
- iframe: HTMLIFrameElement,
51
- doc: Document,
52
- win: Window,
53
- clientX: number,
54
- clientY: number,
55
- ): PreviewLocalPointer | null {
56
- const iframeRect = iframe.getBoundingClientRect();
57
- const root =
58
- doc.querySelector<HTMLElement>("[data-composition-id]") ?? doc.documentElement ?? null;
59
- const rootRect = root?.getBoundingClientRect();
60
- const rootWidth = rootRect?.width || win.innerWidth;
61
- const rootHeight = rootRect?.height || win.innerHeight;
62
- if (!rootWidth || !rootHeight) return null;
63
-
64
- const scaleX = iframeRect.width / rootWidth;
65
- const scaleY = iframeRect.height / rootHeight;
66
- return {
67
- x: (clientX - iframeRect.left) / scaleX,
68
- y: (clientY - iframeRect.top) / scaleY,
69
- viewport: { width: rootWidth, height: rootHeight },
70
- };
71
- }
72
-
73
- const pointerEventsInheritanceFallbackByDocument = new WeakMap<Document, boolean>();
74
-
75
- function needsPointerEventsInheritanceFallback(doc: Document, win: Window): boolean {
76
- const cached = pointerEventsInheritanceFallbackByDocument.get(doc);
77
- if (cached !== undefined) return cached;
78
-
79
- const parent = doc.createElement("div");
80
- const child = doc.createElement("div");
81
- parent.style.pointerEvents = "none";
82
- parent.appendChild(child);
83
- const host = doc.body ?? doc.documentElement;
84
- if (!host) return false;
85
-
86
- host.appendChild(parent);
87
- const needsFallback = win.getComputedStyle(child).pointerEvents !== "none";
88
- parent.remove();
89
- pointerEventsInheritanceFallbackByDocument.set(doc, needsFallback);
90
- return needsFallback;
91
- }
92
-
93
- // Own declared pointer-events value, via computed style rather than inline
94
- // style, so a CSS-class opt-in/opt-out (not just an inline style attribute)
95
- // is honored when walking back down from a pointer-events:none ancestor.
96
- function hasOwnPointerEventsOverride(el: HTMLElement, win: Window): boolean {
97
- const value = win.getComputedStyle(el).pointerEvents;
98
- return value !== "" && value !== "inherit" && value !== "unset";
99
- }
100
-
101
- function inheritsPointerEventsNoneFromAncestor(el: HTMLElement, win: Window): boolean {
102
- let current = el.parentElement;
103
- while (current) {
104
- if (win.getComputedStyle(current).pointerEvents === "none") {
105
- let descendant: HTMLElement | null = el;
106
- while (descendant && descendant !== current) {
107
- if (hasOwnPointerEventsOverride(descendant, win)) {
108
- return win.getComputedStyle(descendant).pointerEvents === "none";
109
- }
110
- descendant = descendant.parentElement;
111
- }
112
- return true;
113
- }
114
- current = current.parentElement;
115
- }
116
- return false;
117
- }
118
-
119
- function hasAuthorPointerEventsNone(el: HTMLElement): boolean {
120
- const win = el.ownerDocument.defaultView;
121
- if (!win) return false;
122
- if (win.getComputedStyle(el).pointerEvents === "none") return true;
123
- if (!needsPointerEventsInheritanceFallback(el.ownerDocument, win)) return false;
124
- return inheritsPointerEventsNoneFromAncestor(el, win);
125
- }
126
-
127
- function collectPointerEventsNoneTargets(
128
- elements: Iterable<Element | null | undefined>,
129
- ): WeakSet<HTMLElement> {
130
- const disabled = new WeakSet<HTMLElement>();
131
- for (const entry of elements) {
132
- if (isHtmlElement(entry) && hasAuthorPointerEventsNone(entry)) {
133
- disabled.add(entry);
134
- }
135
- }
136
- return disabled;
137
- }
138
-
139
- // Shared tail of both pointer resolvers: hit-test candidates minus elements the
140
- // author hid from hit-testing via pointer-events:none.
141
- function filterAuthorInteractiveTargets(
142
- elements: Element[],
143
- activeCompositionPath: string | null,
144
- ): HTMLElement[] {
145
- const pointerEventsNoneTargets = collectPointerEventsNoneTargets(elements);
146
- return resolveAllVisualDomEditTargets(elements, { activeCompositionPath }).filter(
147
- (el) => !pointerEventsNoneTargets.has(el),
148
- );
149
- }
8
+ // One canvas hit-test for Studio and the runtime that answers it for a frame Studio cannot script.
9
+ export { coversComposition };
150
10
 
151
- // Animated group members can move outside their wrapper's static layout box, so
152
- // the empty space inside a group's *visual* bounds (the member-union the overlay
153
- // draws) doesn't hit-test to the group via elementsFromPoint. Recover it: if the
154
- // point falls within a group's live member-union rect, return that wrapper.
155
- // Innermost (smallest-area) group wins for nested groups.
156
- // fallow-ignore-next-line complexity
157
- function findGroupAtPoint(doc: Document, x: number, y: number): HTMLElement | null {
158
- let best: HTMLElement | null = null;
159
- let bestArea = Infinity;
160
- for (const group of Array.from(doc.querySelectorAll<HTMLElement>("[data-hf-group]"))) {
161
- let left = Infinity;
162
- let top = Infinity;
163
- let right = -Infinity;
164
- let bottom = -Infinity;
165
- for (const member of Array.from(group.children)) {
166
- const r = member.getBoundingClientRect();
167
- if (r.width === 0 && r.height === 0) continue;
168
- left = Math.min(left, r.left);
169
- top = Math.min(top, r.top);
170
- right = Math.max(right, r.right);
171
- bottom = Math.max(bottom, r.bottom);
172
- }
173
- if (right < left || x < left || x > right || y < top || y > bottom) continue;
174
- const area = (right - left) * (bottom - top);
175
- if (area < bestArea) {
176
- bestArea = area;
177
- best = group;
178
- }
179
- }
180
- return best;
181
- }
182
-
183
- // fallow-ignore-next-line complexity
11
+ /** The element a press at a client point picks in a frame Studio can script, or null. */
184
12
  export function getPreviewTargetFromPointer(
185
13
  iframe: HTMLIFrameElement,
186
14
  clientX: number,
187
15
  clientY: number,
188
- activeCompositionPath: string | null,
189
16
  ): HTMLElement | null {
190
- let doc: Document | null = null;
191
- let win: Window | null = null;
192
- try {
193
- doc = iframe.contentDocument;
194
- win = iframe.contentWindow;
195
- } catch {
196
- return null;
197
- }
198
- if (!doc || !win) return null;
199
-
200
- const localPointer = resolvePreviewLocalPointer(iframe, doc, win, clientX, clientY);
201
- if (!localPointer) return null;
202
-
203
- // Hit-test without touching the preview document: any style added here, even
204
- // briefly, restyles every element in the film on each click and hover.
205
- if (typeof doc.elementsFromPoint === "function") {
206
- const elements = doc.elementsFromPoint(localPointer.x, localPointer.y);
207
- const candidates = filterAuthorInteractiveTargets(elements, activeCompositionPath);
208
- const visualTarget =
209
- candidates.find((el) => !isFullBleedTarget(el, localPointer.viewport)) ?? null;
210
- if (visualTarget) return visualTarget;
211
- }
212
-
213
- // No element hit (e.g. empty space inside an animated group's overlay) — fall
214
- // back to the group whose member-union contains the point, so the whole group
215
- // area is hoverable/selectable, not just where a member currently sits.
216
- const groupHit = findGroupAtPoint(doc, localPointer.x, localPointer.y);
217
- if (
218
- groupHit &&
219
- !hasAuthorPointerEventsNone(groupHit) &&
220
- getDomLayerPatchTarget(groupHit, activeCompositionPath)
221
- )
222
- return groupHit;
223
-
224
- const fallback = getEventTargetElement(doc.elementFromPoint(localPointer.x, localPointer.y));
225
- if (!fallback || !getDomLayerPatchTarget(fallback, activeCompositionPath)) return null;
226
- if (hasAuthorPointerEventsNone(fallback)) return null;
227
- if (!isElementComputedVisible(fallback)) return null;
228
- if (isFullBleedTarget(fallback, localPointer.viewport)) return null;
229
- return fallback;
17
+ const local = framePointer(iframe, clientX, clientY);
18
+ return local && pointerTarget(local.doc, local.point);
230
19
  }
231
20
 
232
21
  /** Returns all independently-selectable elements at the pointer (topmost first). */
@@ -234,33 +23,28 @@ export function getAllPreviewTargetsFromPointer(
234
23
  iframe: HTMLIFrameElement,
235
24
  clientX: number,
236
25
  clientY: number,
237
- activeCompositionPath: string | null,
238
26
  ): HTMLElement[] {
27
+ const local = framePointer(iframe, clientX, clientY);
28
+ return local ? pointerTargets(local.doc, local.point) : [];
29
+ }
30
+
31
+ /** Where a client point falls in `iframe`, as fractions of its box; the frame maps them onto its composition. */
32
+ export function framePointFraction(iframe: HTMLIFrameElement, clientX: number, clientY: number) {
33
+ const rect = iframe.getBoundingClientRect();
34
+ return { x: (clientX - rect.left) / rect.width, y: (clientY - rect.top) / rect.height };
35
+ }
36
+
37
+ function framePointer(iframe: HTMLIFrameElement, clientX: number, clientY: number) {
239
38
  let doc: Document | null = null;
240
- let win: Window | null = null;
241
39
  try {
242
40
  doc = iframe.contentDocument;
243
- win = iframe.contentWindow;
244
41
  } catch {
245
- return [];
246
- }
247
- if (!doc || !win) return [];
248
-
249
- const localPointer = resolvePreviewLocalPointer(iframe, doc, win, clientX, clientY);
250
- if (!localPointer) return [];
251
-
252
- if (typeof doc.elementsFromPoint === "function") {
253
- const elements = doc.elementsFromPoint(localPointer.x, localPointer.y);
254
- return filterAuthorInteractiveTargets(elements, activeCompositionPath).filter(
255
- (el) => !isFullBleedTarget(el, localPointer.viewport),
256
- );
42
+ return null;
257
43
  }
258
- const fallback = getEventTargetElement(doc.elementFromPoint(localPointer.x, localPointer.y));
259
- if (!fallback || !getDomLayerPatchTarget(fallback, activeCompositionPath)) return [];
260
- if (hasAuthorPointerEventsNone(fallback)) return [];
261
- if (!isElementComputedVisible(fallback)) return [];
262
- if (isFullBleedTarget(fallback, localPointer.viewport)) return [];
263
- return [fallback];
44
+ if (!doc?.defaultView) return null;
45
+ const { x, y } = framePointFraction(iframe, clientX, clientY);
46
+ const point = compositionPoint(doc, x, y);
47
+ return point && { doc, point };
264
48
  }
265
49
 
266
50
  function objectLike(value: unknown): object | null {
@@ -1,126 +0,0 @@
1
- /**
2
- * One walk from an element up to its composition root, composing the transform
3
- * it actually paints under.
4
- *
5
- * The overlay measures an element's angle in two places — the selection box and
6
- * the crop frame — and they need different arithmetic: one works in DOMMatrix
7
- * because it goes on to transform corner points, the other in plain 2D
8
- * components because it only needs an angle and a scale. What they must never
9
- * differ on is *which* transforms count and in what order, because when they
10
- * disagree the chrome disagrees with itself: the selection box drawn at one
11
- * angle and the crop outline at another, on the same element.
12
- *
13
- * So the walk lives here once and takes the arithmetic as a parameter. Adding
14
- * an individual property CSS grew later — `translate`, `scale` — means adding
15
- * one step here and one method to each algebra, rather than finding both walks
16
- * and hoping.
17
- */
18
-
19
- /** The composition's own root; the walk stops there rather than at the document. */
20
- const COMPOSITION_ROOT_ATTR = "data-composition-id";
21
-
22
- /**
23
- * The arithmetic the walk needs, whatever the caller's matrix type is.
24
- *
25
- * `fromTransform` returns null for a transform the caller cannot use — a
26
- * perspective matrix, say — which aborts the walk rather than composing a
27
- * matrix that describes something other than what is painted.
28
- */
29
- export interface PlanarTransformOps<M> {
30
- identity(): M;
31
- fromTransform(value: string): M | null;
32
- fromRotate(degrees: number): M;
33
- /** `outer` applied around `inner`, as an ancestor composes over a child. */
34
- compose(outer: M, inner: M): M;
35
- }
36
-
37
- /**
38
- * The planar rotation in the CSS `rotate` property, in degrees.
39
- *
40
- * Computes to `none`, an angle (`-22deg`), or an axis plus an angle
41
- * (`0 0 1 -22deg`). Only a rotation about z stays in the overlay's plane; any
42
- * other axis is 3D and reports 0, which leaves the caller on its axis-aligned
43
- * fallback rather than drawing a box at a plausible-looking wrong angle.
44
- */
45
- export function individualRotateDegrees(value: string | undefined): number {
46
- if (!value || value === "none") return 0;
47
- const parts = value.trim().split(/\s+/);
48
- const angle = parts.at(-1);
49
- if (!angle?.endsWith("deg")) return 0;
50
- if (parts.length === 4) {
51
- const [x, y, z] = parts;
52
- if (Number(x) !== 0 || Number(y) !== 0 || Math.abs(Number(z)) !== 1) return 0;
53
- const deg = Number.parseFloat(angle);
54
- return Number.isFinite(deg) ? deg * Math.sign(Number(z)) : 0;
55
- }
56
- if (parts.length !== 1) return 0;
57
- const deg = Number.parseFloat(angle);
58
- return Number.isFinite(deg) ? deg : 0;
59
- }
60
-
61
- /** One node's own contribution, with the individual properties applied before
62
- * `transform` the way CSS does. Null when the node's transform is unusable. */
63
- function ownNodeTransform<M>(
64
- node: HTMLElement,
65
- ops: PlanarTransformOps<M>,
66
- getStyle: (node: HTMLElement) => CSSStyleDeclaration | null,
67
- ): M | null {
68
- const style = getStyle(node);
69
- if (!style) return null;
70
- const transform = style.transform;
71
- const own = transform && transform !== "none" ? ops.fromTransform(transform) : ops.identity();
72
- if (!own) return null;
73
- const spin = individualRotateDegrees(style.rotate);
74
- return spin === 0 ? own : ops.compose(ops.fromRotate(spin), own);
75
- }
76
-
77
- /**
78
- * The element's transform composed with every ancestor's, up to the composition
79
- * root.
80
- *
81
- * Within a node, CSS applies the individual properties before `transform`, so
82
- * `rotate` composes on the left of it. Between nodes, an ancestor applies
83
- * outside its child. Null means some node's transform was unusable and the
84
- * caller should fall back rather than guess.
85
- *
86
- * `memo` holds each node's COMPOSED chain, for a caller walking many elements
87
- * in one synchronous pass.
88
- *
89
- * A chain is `chain(parent)` composed with the node's own, so siblings share
90
- * everything above them and the whole tree costs one style read and one
91
- * compose per node instead of one per node PER DESCENDANT. Valid only for the
92
- * length of one pass, which is why the caller owns it: nothing here writes to
93
- * the DOM, so nothing can move under it, and it is dropped before anything
94
- * else runs. Omitted, every call composes its own chain from scratch.
95
- */
96
- export function composeElementTransform<M>(
97
- element: HTMLElement,
98
- ops: PlanarTransformOps<M>,
99
- getStyle: (node: HTMLElement) => CSSStyleDeclaration | null,
100
- memo?: Map<HTMLElement, M | null>,
101
- ): M | null {
102
- const pending: HTMLElement[] = [];
103
- // `undefined` means nothing on the way up was already composed, so the chain
104
- // starts from identity. A memoized `null` is an answer, not a miss: some node
105
- // above carries a transform this algebra cannot represent.
106
- let above: M | null | undefined;
107
- for (let node: HTMLElement | null = element; node; node = node.parentElement) {
108
- above = memo?.get(node);
109
- if (above !== undefined) break;
110
- pending.push(node);
111
- if (node.hasAttribute(COMPOSITION_ROOT_ATTR)) break;
112
- }
113
-
114
- let acc: M | null = above === undefined ? ops.identity() : above;
115
- for (let i = pending.length - 1; i >= 0; i -= 1) {
116
- const node = pending[i]!;
117
- if (acc !== null) {
118
- const own = ownNodeTransform(node, ops, getStyle);
119
- // The ancestors' chain is the OUTER of the pair, as an ancestor applies
120
- // around its child.
121
- acc = own === null ? null : ops.compose(acc, own);
122
- }
123
- memo?.set(node, acc);
124
- }
125
- return acc;
126
- }