@hyperframes/core 0.9.42 → 0.9.43

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,16 @@
1
+ /**
2
+ * Gesture drafts for the editing channel. A parent that cannot script the frame draws a drag or a
3
+ * resize here, on the element's inline style, so the preview moves with the pointer. What the
4
+ * element had before its first draft is kept until the parent ends the draft or the frame loads again.
5
+ */
6
+ import { type StylableElement as Styled } from "./domRealm.js";
7
+ import type { EditingDraft } from "./editingPort.js";
8
+ export declare function computedTranslateAxes(element: Styled): string[];
9
+ export declare function movedTranslate([x, y, z]: string[], offset: {
10
+ x: number;
11
+ y: number;
12
+ }): string;
13
+ /** Applies each draft in order; one for an element this load no longer has is skipped. */
14
+ export declare function drawDrafts(drafts: readonly EditingDraft[]): {
15
+ drawn: number;
16
+ };
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Gesture drafts for the editing channel. A parent that cannot script the frame draws a drag or a
3
+ * resize here, on the element's inline style, so the preview moves with the pointer. What the
4
+ * element had before its first draft is kept until the parent ends the draft or the frame loads again.
5
+ */
6
+ import { isStylableElement } from "./domRealm.js";
7
+ import { elementForHandle } from "./editingHandles.js";
8
+ const SIZE_PROPERTIES = [
9
+ "box-sizing",
10
+ "width",
11
+ "height",
12
+ "min-width",
13
+ "min-height",
14
+ "max-width",
15
+ "max-height",
16
+ ];
17
+ const DRAWN = ["translate", ...SIZE_PROPERTIES];
18
+ const before = new WeakMap();
19
+ /** "calc(50% + 2px) 4px" as its top-level parts. */
20
+ function axes(value) {
21
+ const parts = [];
22
+ let depth = 0;
23
+ let part = "";
24
+ for (const char of value.trim()) {
25
+ depth += char === "(" ? 1 : char === ")" ? -1 : 0;
26
+ if (/\s/.test(char) && depth === 0) {
27
+ if (part)
28
+ parts.push(part);
29
+ part = "";
30
+ }
31
+ else
32
+ part += char;
33
+ }
34
+ if (part)
35
+ parts.push(part);
36
+ return parts;
37
+ }
38
+ /** The side a translate's % takes a share of: the box `transform-box` names. */
39
+ function percentSide(computed, size) {
40
+ const [a, b] = size === "width" ? ["left", "right"] : ["top", "bottom"];
41
+ const n = (name) => Number.parseFloat(computed.getPropertyValue(name)) || 0;
42
+ const pad = n(`padding-${a}`) + n(`padding-${b}`) + n(`border-${a}-width`) + n(`border-${b}-width`);
43
+ const content = n(size) - (computed.getPropertyValue("box-sizing") === "border-box" ? pad : 0);
44
+ const box = computed.getPropertyValue("transform-box");
45
+ return box === "content-box" || box === "fill-box" ? content : content + pad;
46
+ }
47
+ /** Each % as the px it is now, so a resize drawn with it does not move the element again. */
48
+ function percentAsPx(axis, side) {
49
+ return axis.replace(/(-?\d*\.?\d+(?:e[-+]?\d+)?)%/gi, (_, n) => `${(Number(n) * side) / 100}px`);
50
+ }
51
+ export function computedTranslateAxes(element) {
52
+ const computed = getComputedStyle(element);
53
+ const translate = computed.getPropertyValue("translate");
54
+ if (!translate || translate === "none")
55
+ return [];
56
+ const sides = [percentSide(computed, "width"), percentSide(computed, "height")];
57
+ return axes(translate).map((axis, i) => (i < 2 ? percentAsPx(axis, sides[i]) : axis));
58
+ }
59
+ function beforeOf(element) {
60
+ let saved = before.get(element);
61
+ if (!saved) {
62
+ const { style } = element;
63
+ saved = {
64
+ inline: DRAWN.map((name) => [
65
+ name,
66
+ style.getPropertyValue(name),
67
+ style.getPropertyPriority(name),
68
+ ]),
69
+ translate: computedTranslateAxes(element),
70
+ };
71
+ before.set(element, saved);
72
+ }
73
+ return saved;
74
+ }
75
+ function restore(element, names) {
76
+ for (const [name, value, priority] of before.get(element)?.inline ?? []) {
77
+ if (!names.includes(name))
78
+ continue;
79
+ if (value)
80
+ element.style.setProperty(name, value, priority);
81
+ else
82
+ element.style.removeProperty(name);
83
+ }
84
+ }
85
+ export function movedTranslate([x = "0px", y = "0px", z], offset) {
86
+ return `calc(${x} + ${offset.x}px) calc(${y} + ${offset.y}px)${z ? ` ${z}` : ""}`;
87
+ }
88
+ function drawTranslate(element, offset) {
89
+ element.style.setProperty("translate", movedTranslate(beforeOf(element).translate, offset));
90
+ }
91
+ function drawSize(element, size) {
92
+ beforeOf(element);
93
+ const { style } = element;
94
+ style.setProperty("box-sizing", "border-box");
95
+ style.setProperty("width", `${size.width}px`);
96
+ style.setProperty("height", `${size.height}px`);
97
+ for (const name of ["min-width", "min-height"])
98
+ style.setProperty(name, "0px");
99
+ for (const name of ["max-width", "max-height"])
100
+ style.setProperty(name, "none");
101
+ }
102
+ function apply(element, draft) {
103
+ if ("end" in draft) {
104
+ if (draft.end === "restore")
105
+ restore(element, DRAWN);
106
+ before.delete(element);
107
+ return;
108
+ }
109
+ if (draft.translate)
110
+ drawTranslate(element, draft.translate);
111
+ else
112
+ restore(element, ["translate"]);
113
+ if (draft.size)
114
+ drawSize(element, draft.size);
115
+ else
116
+ restore(element, SIZE_PROPERTIES);
117
+ }
118
+ /** Applies each draft in order; one for an element this load no longer has is skipped. */
119
+ export function drawDrafts(drafts) {
120
+ let drawn = 0;
121
+ for (const draft of drafts) {
122
+ const element = elementForHandle(draft.handle);
123
+ if (!isStylableElement(element))
124
+ continue;
125
+ apply(element, draft);
126
+ drawn++;
127
+ }
128
+ return { drawn };
129
+ }
@@ -46,6 +46,14 @@ export declare function rotationDegreesFromMatrix(matrix: Pick<DOMMatrix, "a" |
46
46
  * then anchored by matching their bounding box to the element's real one. Null when unmeasurable.
47
47
  */
48
48
  export declare function elementCornerPoints(win: Window, element: HTMLElement, { matrix, cs }: ElementTransformSnapshot): EditingCorners | null;
49
+ export declare function boxOf(element: HTMLElement, memo: Map<HTMLElement, DOMMatrix | null>): EditingElementBox;
50
+ export declare const MAX_SNAP_TARGETS = 80;
51
+ /**
52
+ * The elements a moved box can snap to, in document order below `root`: each rendered element
53
+ * outside `exclude`, not a nested composition's host, and not in a subtree that is hidden. Once
54
+ * `max` are found no further subtree is entered; the children of one being walked are all listed.
55
+ */
56
+ export declare function snapCandidates(root: Element, exclude: ReadonlySet<Element>, max?: number): HTMLElement[];
49
57
  /** One entry per handle, null as in `describe`, and the boxes of `children`'s descendants. */
50
58
  export declare function elementGeometry(handles: readonly EditingElementHandle[], children: EditingElementHandle | undefined): {
51
59
  elements: Array<EditingElementGeometry | null>;
@@ -142,7 +142,7 @@ function clipPathOf(element) {
142
142
  const finiteCorners = (corners) => corners && Object.values(corners).every((p) => Number.isFinite(p.x) && Number.isFinite(p.y))
143
143
  ? corners
144
144
  : null;
145
- function boxOf(element, memo) {
145
+ export function boxOf(element, memo) {
146
146
  const transform = readElementTransformSnapshot(window, element, memo);
147
147
  const turned = transform ? rotationDegreesFromMatrix(transform.matrix) : 0;
148
148
  const angle = Math.abs(turned) < ROTATION_GATE_EPSILON_DEG ? 0 : turned;
@@ -155,6 +155,34 @@ function boxOf(element, memo) {
155
155
  clipPath: clipPathOf(element),
156
156
  };
157
157
  }
158
+ export const MAX_SNAP_TARGETS = 80;
159
+ const NOT_SNAPPED = new Set(["script", "style", "link", "meta", "base", "template", "br", "wbr"]);
160
+ /**
161
+ * The elements a moved box can snap to, in document order below `root`: each rendered element
162
+ * outside `exclude`, not a nested composition's host, and not in a subtree that is hidden. Once
163
+ * `max` are found no further subtree is entered; the children of one being walked are all listed.
164
+ */
165
+ export function snapCandidates(root, exclude, max = MAX_SNAP_TARGETS) {
166
+ const found = [];
167
+ const visible = new Map();
168
+ const visit = (parent) => {
169
+ if (found.length >= max)
170
+ return;
171
+ for (const child of Array.from(parent.children)) {
172
+ if (NOT_SNAPPED.has(child.tagName.toLowerCase()))
173
+ continue;
174
+ if (child.hasAttribute("data-composition-id") || exclude.has(child))
175
+ continue;
176
+ const element = child;
177
+ if (!isElementVisibleThroughAncestors(element, visible))
178
+ continue;
179
+ found.push(element);
180
+ visit(element);
181
+ }
182
+ };
183
+ visit(root);
184
+ return found;
185
+ }
158
186
  /** One entry per handle, null as in `describe`, and the boxes of `children`'s descendants. */
159
187
  export function elementGeometry(handles, children) {
160
188
  const memo = new Map();
@@ -0,0 +1,27 @@
1
+ import type { EditingElementHandle } from "./editingElement.js";
2
+ import { type EditingElementBox, type EditingElementGeometry } from "./editingGeometry.js";
3
+ export interface EditingGestureStart extends EditingElementGeometry {
4
+ /** The transform-free border box a resize grows from. */
5
+ layout: {
6
+ width: number;
7
+ height: number;
8
+ };
9
+ /** Frame px its centre moves per px of translate, columns `a, b` (x) and `c, d` (y); null when it does not move measurably. */
10
+ move: {
11
+ a: number;
12
+ b: number;
13
+ c: number;
14
+ d: number;
15
+ } | null;
16
+ /** Set when GSAP owns its position: its x/y now, and whether a tween with a duration moves it. */
17
+ gsap: {
18
+ x: number;
19
+ y: number;
20
+ moving: boolean;
21
+ } | null;
22
+ }
23
+ /** Each handle's gesture start, null as in `describe`, and the snap boxes of the page around them. */
24
+ export declare function gestureStart(handles: readonly EditingElementHandle[]): {
25
+ elements: Array<EditingGestureStart | null>;
26
+ snap: EditingElementBox[];
27
+ };
@@ -0,0 +1,100 @@
1
+ /**
2
+ * What a drag or resize needs from the frame as it starts, in one read for the editing channel: each
3
+ * pressed element's overlay geometry, layout size, how far it moves per px of translate, and GSAP's
4
+ * x/y when GSAP owns its position; and the boxes it can snap to. A parent that cannot script the
5
+ * frame takes these here rather than off the elements.
6
+ */
7
+ import { isStylableElement } from "./domRealm.js";
8
+ import { computedTranslateAxes, movedTranslate } from "./editingDraft.js";
9
+ import { boxOf, elementGeometry, snapCandidates, MAX_SNAP_TARGETS, } from "./editingGeometry.js";
10
+ import { elementForHandle } from "./editingHandles.js";
11
+ const PROBE_PX = 100;
12
+ const MIN_PROBE_RESPONSE = 0.01;
13
+ /**
14
+ * Frame px the element's centre moves per px of translate a draft draws, one column per axis
15
+ * (`a, b` for x, `c, d` for y): every transform above it applied. Null when it has no box or does
16
+ * not move measurably. Its inline translate is put back as it was.
17
+ */
18
+ function measureMoveResponse(element) {
19
+ const { style } = element;
20
+ const value = style.getPropertyValue("translate");
21
+ const priority = style.getPropertyPriority("translate");
22
+ const base = computedTranslateAxes(element);
23
+ const centre = (offset) => {
24
+ style.setProperty("translate", movedTranslate(base, offset));
25
+ const { left, top, width, height } = element.getBoundingClientRect();
26
+ return width > 0 || height > 0 ? { x: left + width / 2, y: top + height / 2 } : null;
27
+ };
28
+ try {
29
+ const origin = centre({ x: 0, y: 0 });
30
+ const alongX = centre({ x: PROBE_PX, y: 0 });
31
+ const alongY = centre({ x: 0, y: PROBE_PX });
32
+ if (!origin || !alongX || !alongY)
33
+ return null;
34
+ const column = (p) => ({
35
+ x: (p.x - origin.x) / PROBE_PX,
36
+ y: (p.y - origin.y) / PROBE_PX,
37
+ });
38
+ const [x, y] = [column(alongX), column(alongY)];
39
+ const usable = (p) => Number.isFinite(p.x) && Number.isFinite(p.y) && Math.hypot(p.x, p.y) >= MIN_PROBE_RESPONSE;
40
+ return usable(x) && usable(y) ? { a: x.x, b: x.y, c: y.x, d: y.y } : null;
41
+ }
42
+ finally {
43
+ if (value)
44
+ style.setProperty("translate", value, priority);
45
+ else
46
+ style.removeProperty("translate");
47
+ }
48
+ }
49
+ // The channels Studio's move route and drag commit read as GSAP moving an element.
50
+ const POSITION = ["x", "y", "xPercent", "yPercent", "left", "top", "translateX", "translateY"];
51
+ const MOVES = [...POSITION, "motionPath"];
52
+ function carries(vars, channels) {
53
+ if (channels.some((channel) => channel in vars))
54
+ return true;
55
+ const keyframes = vars.keyframes;
56
+ if (!keyframes || typeof keyframes !== "object")
57
+ return false;
58
+ const steps = Array.isArray(keyframes) ? keyframes : [keyframes, ...Object.values(keyframes)];
59
+ return steps.some((step) => !!step &&
60
+ typeof step === "object" &&
61
+ channels.some((channel) => Object.prototype.hasOwnProperty.call(step, channel)));
62
+ }
63
+ function tweensOn(element) {
64
+ const timelines = Object.values(window.__timelines ?? {});
65
+ return timelines.flatMap((timeline) => (timeline?.getChildren?.(true) ?? []).filter((tween) => (tween.targets?.() ?? []).some((target) => target === element || (!!element.id && target?.id === element.id))));
66
+ }
67
+ /** GSAP's x/y when it owns the element's position: it renders its transform, or a tween writes it. */
68
+ function gsapPosition(element) {
69
+ const tweens = tweensOn(element).filter((tween) => tween.vars && carries(tween.vars, MOVES));
70
+ const renders = !!element._gsap?.renderTransform;
71
+ if (!renders && !tweens.length)
72
+ return null;
73
+ // Read only now: asking GSAP for x makes it fold a CSS translate into its transform.
74
+ const read = (axis) => Number(window.gsap?.getProperty?.(element, axis)) || 0;
75
+ const moving = tweens.some((tween) => (tween.duration?.() ?? 0) > 0);
76
+ return { x: read("x"), y: read("y"), moving };
77
+ }
78
+ /** Each handle's gesture start, null as in `describe`, and the snap boxes of the page around them. */
79
+ export function gestureStart(handles) {
80
+ const pressed = handles.map(elementForHandle);
81
+ const { elements } = elementGeometry(handles, undefined);
82
+ const starts = elements.map((geometry, i) => {
83
+ const element = pressed[i];
84
+ if (!geometry || !isStylableElement(element))
85
+ return null;
86
+ const { offsetWidth = 0, offsetHeight = 0 } = element;
87
+ return {
88
+ ...geometry,
89
+ layout: { width: offsetWidth, height: offsetHeight },
90
+ move: measureMoveResponse(element),
91
+ gsap: gsapPosition(element),
92
+ };
93
+ });
94
+ const root = document.querySelector("[data-composition-id]") ?? document.documentElement;
95
+ const exclude = new Set(pressed.filter((element) => !!element));
96
+ const memo = new Map();
97
+ const candidates = snapCandidates(root, exclude).slice(0, MAX_SNAP_TARGETS);
98
+ const snap = candidates.map((element) => boxOf(element, memo));
99
+ return { elements: starts, snap };
100
+ }
@@ -11,10 +11,12 @@
11
11
  */
12
12
  import { type EditingElementDescription, type EditingElementHandle, type EditingElementHit, type EditingElementMatch } from "./editingElement.js";
13
13
  import type { EditingElementBox, EditingElementGeometry } from "./editingGeometry.js";
14
+ import type { EditingGestureStart } from "./editingGestureStart.js";
14
15
  import type { EditingLayer } from "./editingLayers.js";
15
16
  import type { RuntimeTimelineMessage } from "./types.js";
16
17
  export { buildStableSelector, escapeCssString, getPreferredClassSelector, readElementSource, EDITING_ELEMENT_HANDLE, MAX_DESCRIBE_HANDLES, MAX_ELEMENT_ENTRIES, MAX_ELEMENT_TEXT, MAX_ELEMENT_VALUE, MAX_POINT_STACK, MAX_QUERY_MATCHES, MAX_SOURCE_GROUPS, type EditingElementDescription, type EditingElementHandle, type EditingElementHit, type EditingElementMatch, type EditingElementSource, type EditingRect, } from "./editingElement.js";
17
- export { elementCornerPoints, isElementVisibleThroughAncestors, readElementTransformSnapshot, rotationDegreesFromMatrix, MAX_GEOMETRY_CHILDREN, ROTATION_GATE_EPSILON_DEG, type EditingCorner, type EditingCorners, type EditingElementBox, type EditingElementGeometry, type ElementTransformSnapshot, } from "./editingGeometry.js";
18
+ export { elementCornerPoints, isElementVisibleThroughAncestors, readElementTransformSnapshot, rotationDegreesFromMatrix, snapCandidates, MAX_GEOMETRY_CHILDREN, MAX_SNAP_TARGETS, ROTATION_GATE_EPSILON_DEG, type EditingCorner, type EditingCorners, type EditingElementBox, type EditingElementGeometry, type ElementTransformSnapshot, } from "./editingGeometry.js";
19
+ export type { EditingGestureStart } from "./editingGestureStart.js";
18
20
  export { compositionPoint, coversComposition, isDomLayerElement, isInspectableLayerElement, pointerTarget, pointerTargets, resolveAllVisualDomEditTargets, resolveLayerSelector, type EditingLocalPointer, type EditingViewport, } from "./editingTargets.js";
19
21
  export { elementZIndex, hasOnlyFormattingChildren, isCompositionHost, layerKindOf, type EditingLayer, type LayerKind, } from "./editingLayers.js";
20
22
  export { composeElementTransform, individualRotateDegrees, type PlanarTransformOps, } from "./elementTransform.js";
@@ -23,7 +25,7 @@ export declare const EDITING_PROTOCOL_VERSION: 1;
23
25
  export declare const EDITING_CONNECT = "editing-connect";
24
26
  /** Frame to parent, on the window: carries the port in its transfer list. */
25
27
  export declare const EDITING_PORT = "editing-port";
26
- export declare const EDITING_REQUEST_KINDS: readonly ["hello", "runtime-snapshot", "wait-for-seek", "set-loop-start", "computed-styles", "elements-at-point", "pointer-targets", "describe", "ancestors", "query", "geometry", "layers", "draft"];
28
+ export declare const EDITING_REQUEST_KINDS: readonly ["hello", "runtime-snapshot", "wait-for-seek", "set-loop-start", "computed-styles", "elements-at-point", "pointer-targets", "describe", "ancestors", "query", "geometry", "layers", "draft", "gesture-start"];
27
29
  export type EditingRequestKind = (typeof EDITING_REQUEST_KINDS)[number];
28
30
  export interface EditingRuntimeSnapshot {
29
31
  /** The runtime has installed its player API. */
@@ -175,6 +177,15 @@ export interface EditingRequests {
175
177
  drawn: number;
176
178
  };
177
179
  };
180
+ "gesture-start": {
181
+ params: {
182
+ handles: EditingElementHandle[];
183
+ };
184
+ result: {
185
+ elements: Array<EditingGestureStart | null>;
186
+ snap: EditingElementBox[];
187
+ };
188
+ };
178
189
  }
179
190
  export type EditingParams<K extends EditingRequestKind> = EditingRequests[K]["params"];
180
191
  export type EditingResult<K extends EditingRequestKind> = EditingRequests[K]["result"];
@@ -12,7 +12,7 @@
12
12
  import { EDITING_ELEMENT_HANDLE, MAX_DESCRIBE_HANDLES, } from "./editingElement.js";
13
13
  import { wallClearTimeout, wallSetTimeout } from "./wallClock.js";
14
14
  export { buildStableSelector, escapeCssString, getPreferredClassSelector, readElementSource, EDITING_ELEMENT_HANDLE, MAX_DESCRIBE_HANDLES, MAX_ELEMENT_ENTRIES, MAX_ELEMENT_TEXT, MAX_ELEMENT_VALUE, MAX_POINT_STACK, MAX_QUERY_MATCHES, MAX_SOURCE_GROUPS, } from "./editingElement.js";
15
- export { elementCornerPoints, isElementVisibleThroughAncestors, readElementTransformSnapshot, rotationDegreesFromMatrix, MAX_GEOMETRY_CHILDREN, ROTATION_GATE_EPSILON_DEG, } from "./editingGeometry.js";
15
+ export { elementCornerPoints, isElementVisibleThroughAncestors, readElementTransformSnapshot, rotationDegreesFromMatrix, snapCandidates, MAX_GEOMETRY_CHILDREN, MAX_SNAP_TARGETS, ROTATION_GATE_EPSILON_DEG, } from "./editingGeometry.js";
16
16
  export { compositionPoint, coversComposition, isDomLayerElement, isInspectableLayerElement, pointerTarget, pointerTargets, resolveAllVisualDomEditTargets, resolveLayerSelector, } from "./editingTargets.js";
17
17
  export { elementZIndex, hasOnlyFormattingChildren, isCompositionHost, layerKindOf, } from "./editingLayers.js";
18
18
  export { composeElementTransform, individualRotateDegrees, } from "./elementTransform.js";
@@ -35,6 +35,7 @@ export const EDITING_REQUEST_KINDS = [
35
35
  "geometry",
36
36
  "layers",
37
37
  "draft",
38
+ "gesture-start",
38
39
  ];
39
40
  export const MAX_DRAFT_PX = 100_000;
40
41
  export function isPlainRecord(value) {
@@ -158,6 +159,7 @@ const PARAM_PARSERS = {
158
159
  },
159
160
  layers: (params) => noParams(params) ?? layerParams(params),
160
161
  draft: draftList,
162
+ "gesture-start": handleList,
161
163
  };
162
164
  /** Validates one request off the wire. Never throws: anything unusable becomes a typed error. */
163
165
  export function parseEditingRequest(data) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperframes/core",
3
- "version": "0.9.42",
3
+ "version": "0.9.43",
4
4
  "description": "",
5
5
  "repository": {
6
6
  "type": "git",
@@ -445,9 +445,9 @@
445
445
  "linkedom": "^0.18.12",
446
446
  "postcss": "^8.5.8",
447
447
  "wawoff2": "^2.0.1",
448
- "@hyperframes/studio-server": "0.9.42",
449
- "@hyperframes/parsers": "0.9.42",
450
- "@hyperframes/lint": "0.9.42"
448
+ "@hyperframes/lint": "0.9.43",
449
+ "@hyperframes/parsers": "0.9.43",
450
+ "@hyperframes/studio-server": "0.9.43"
451
451
  },
452
452
  "devDependencies": {
453
453
  "@fontsource/archivo-black": "^5.2.8",