@hyperframes/core 0.9.103 → 0.9.106

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 (37) hide show
  1. package/dist/compiler/compositionScoping.js +3 -3
  2. package/dist/compiler/htmlDocument.js +9 -2
  3. package/dist/compiler/svgIdNamespacing.js +2 -2
  4. package/dist/fonts/authoredGoogleFonts.js +2 -2
  5. package/dist/fonts/deterministicFonts.js +14 -12
  6. package/dist/fonts/fontDiagnostics.d.ts +3 -0
  7. package/dist/fonts/fontDiagnostics.js +32 -1
  8. package/dist/generated/runtime-inline.js +1 -1
  9. package/dist/hyperframe.runtime.iife.js +69 -69
  10. package/dist/runtime/drawnBox.d.ts +5 -0
  11. package/dist/runtime/drawnBox.js +5 -0
  12. package/dist/runtime/editing/canvasKeys.d.ts +0 -1
  13. package/dist/runtime/editing/canvasKeys.js +4 -28
  14. package/dist/runtime/editing/dragChrome.d.ts +32 -0
  15. package/dist/runtime/editing/dragChrome.js +154 -0
  16. package/dist/runtime/editing/pausedFrames.js +7 -7
  17. package/dist/runtime/editing/softReload.js +4 -2
  18. package/dist/runtime/editing/stageAct.js +3 -2
  19. package/dist/runtime/editing/textEdit.js +4 -3
  20. package/dist/runtime/editing/watchGeometry.js +8 -8
  21. package/dist/runtime/editing/watchPointer.d.ts +26 -0
  22. package/dist/runtime/editing/watchPointer.js +105 -0
  23. package/dist/runtime/editingDraft.d.ts +3 -2
  24. package/dist/runtime/editingDraft.js +13 -8
  25. package/dist/runtime/editingDraftEnd.d.ts +1 -0
  26. package/dist/runtime/editingElement.d.ts +4 -0
  27. package/dist/runtime/editingGeometry.js +1 -4
  28. package/dist/runtime/editingHandles.d.ts +0 -5
  29. package/dist/runtime/editingHandles.js +7 -0
  30. package/dist/runtime/editingPort.d.ts +22 -3
  31. package/dist/runtime/editingPort.js +63 -8
  32. package/dist/runtime/mediaProxy.js +78 -7
  33. package/dist/runtime/runtimePort.d.ts +21 -0
  34. package/dist/runtime/runtimePort.js +122 -0
  35. package/dist/studioPreviewMark.d.ts +2 -0
  36. package/dist/studioPreviewMark.js +2 -0
  37. package/package.json +4 -4
@@ -4,6 +4,11 @@
4
4
  */
5
5
  import type { StylableElement as Styled } from "./domRealm.js";
6
6
  export declare const SIZE_PROPERTIES: readonly ["box-sizing", "width", "height", "min-width", "min-height", "max-width", "max-height"];
7
+ export declare function layoutOf(element: Element): {
8
+ width: number;
9
+ height: number;
10
+ };
11
+ export declare const DRAFT_DRAWN: readonly ["translate", "rotate", "transform", "box-sizing", "width", "height", "min-width", "min-height", "max-width", "max-height"];
7
12
  export declare const PROBE_PX = 100;
8
13
  export declare const MIN_PROBE_RESPONSE = 0.01;
9
14
  /** Frame px its centre moves per px of drawn width, `a, b`, and height, `c, d`; null when it has no box. */
@@ -7,6 +7,11 @@ export const SIZE_PROPERTIES = [
7
7
  "max-width",
8
8
  "max-height",
9
9
  ];
10
+ export function layoutOf(element) {
11
+ const { offsetWidth = 0, offsetHeight = 0 } = element;
12
+ return { width: offsetWidth, height: offsetHeight };
13
+ }
14
+ export const DRAFT_DRAWN = ["translate", "rotate", "transform", ...SIZE_PROPERTIES];
10
15
  export const PROBE_PX = 100;
11
16
  export const MIN_PROBE_RESPONSE = 0.01;
12
17
  /** "calc(50% + 2px) 4px" as its top-level parts. */
@@ -52,7 +52,6 @@ export type CanvasKeyActionEvent = {
52
52
  export declare function parseArmCanvasKeys(params: unknown): ArmCanvasKeysParams | null;
53
53
  export declare function parseResolveCanvasKeyAction(params: unknown): ResolveCanvasKeyActionParams | null;
54
54
  export declare function canvasKeyActionEvent(data: unknown, version: number): CanvasKeyActionEvent | null;
55
- export declare function createRuntimeChannel(): MessageChannel;
56
55
  export declare function listenFrameKeydown(view: Window, listener: (event: KeyboardEvent) => void): () => void;
57
56
  /**
58
57
  * Installs capture-first window key listeners in opaque-origin Studio preview frames only (never
@@ -3,6 +3,7 @@ import { matchCombo, parseCombo } from "../../keyCombo.js";
3
3
  import { capturePageIn, markedForStudio } from "../../studioPreviewMark.js";
4
4
  import { swallow } from "../diagnostics.js";
5
5
  import { isDomNode, isElementNode, isStylableElement } from "../domRealm.js";
6
+ import { postOnPort } from "../runtimePort.js";
6
7
  import { drawDrafts } from "../editingDraft.js";
7
8
  import { EDITING_ELEMENT_HANDLE, MAX_DESCRIBE_HANDLES, } from "../editingElement.js";
8
9
  import { gsapPosition } from "../editingGestureStart.js";
@@ -142,31 +143,6 @@ const nativePreventDefault = typeof Event !== "undefined" ? Event.prototype.prev
142
143
  const nativeIsTrustedGetter = typeof Event !== "undefined"
143
144
  ? Object.getOwnPropertyDescriptor(Event.prototype, "isTrusted")?.get
144
145
  : undefined;
145
- const NativeMessageChannel = typeof MessageChannel !== "undefined" ? MessageChannel : null;
146
- const nativePortPostMessage = (() => {
147
- if (!NativeMessageChannel)
148
- return null;
149
- try {
150
- const probe = new NativeMessageChannel();
151
- const post = Object.getPrototypeOf(probe.port1)?.postMessage;
152
- probe.port1.close();
153
- probe.port2.close();
154
- return typeof post === "function" ? post : null;
155
- }
156
- catch {
157
- return null;
158
- }
159
- })();
160
- export function createRuntimeChannel() {
161
- const Ctor = NativeMessageChannel ?? MessageChannel;
162
- return new Ctor();
163
- }
164
- function postRuntimePort(port, message) {
165
- if (nativePortPostMessage)
166
- nativePortPostMessage.call(port, message);
167
- else
168
- port.postMessage(message);
169
- }
170
146
  function stopEvent(event) {
171
147
  if (nativeStopImmediatePropagation)
172
148
  nativeStopImmediatePropagation.call(event);
@@ -249,7 +225,7 @@ function runLocalDelete(state) {
249
225
  }
250
226
  const actionId = ++lastActionId;
251
227
  pendingDeletes.set(actionId, detached);
252
- postRuntimePort(state.port, {
228
+ postOnPort(state.port, {
253
229
  v: state.version,
254
230
  event: "canvas-key-action",
255
231
  action: "delete",
@@ -288,7 +264,7 @@ function runLocalNudge(state, nudge, dx, dy) {
288
264
  if (gsap)
289
265
  baseGsap[handle] = { x: gsap.x, y: gsap.y };
290
266
  const actionId = ++lastActionId;
291
- postRuntimePort(state.port, {
267
+ postOnPort(state.port, {
292
268
  v: state.version,
293
269
  event: "canvas-key-action",
294
270
  action: "nudge",
@@ -304,7 +280,7 @@ function runLocalNudge(state, nudge, dx, dy) {
304
280
  });
305
281
  }
306
282
  function forwardTrustedKey(state, event) {
307
- postRuntimePort(state.port, {
283
+ postOnPort(state.port, {
308
284
  v: state.version,
309
285
  event: "key",
310
286
  key: {
@@ -0,0 +1,32 @@
1
+ export type EditingDragChromeTag = "div" | "span" | "svg" | "path";
2
+ /** One node of Studio's chrome: `look` is its computed paint, set once; `children` in document order. */
3
+ export type EditingDragChromeNode = {
4
+ tag: EditingDragChromeTag;
5
+ look: Record<string, string>;
6
+ attrs?: Record<string, string>;
7
+ children?: EditingDragChromeNode[];
8
+ };
9
+ /** `place` is each node's inline style this step, in document order; `origin` and `scale` map overlay px
10
+ * to the frame's (frame = (overlay - origin) / scale). `nodes` (re)mounts the copy; null clears it. */
11
+ export type EditingDragChrome = {
12
+ origin: {
13
+ x: number;
14
+ y: number;
15
+ };
16
+ scale: {
17
+ x: number;
18
+ y: number;
19
+ };
20
+ place: Array<Record<string, string>>;
21
+ nodes?: EditingDragChromeNode[];
22
+ } | null;
23
+ export declare const MAX_DRAG_CHROME_NODES = 64;
24
+ export declare const MAX_DRAG_CHROME_BYTES = 32768;
25
+ /** The chrome a draft request carries, or undefined when it is malformed or over the caps. */
26
+ export declare function parseDragChrome(value: unknown): EditingDragChrome | undefined;
27
+ export declare const isDragChromeHost: (element: Element) => boolean;
28
+ /** Mounts, places or clears the chrome in the drafts' turn; false when this place fits no mounted copy. */
29
+ export declare function drawDragChrome(chrome: EditingDragChrome): boolean;
30
+ export declare function clearDragChrome(): void;
31
+ /** Runs `read` with the chrome host out of the document, so nothing it reads carries it. */
32
+ export declare function withoutDragChrome<T>(read: () => T): T;
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Studio's selection chrome painted inside a sealed frame during a drag, in the same turn as the layer's draft.
3
+ * Studio owns the look (a copy sent as data); it lives in a closed shadow root that exists only during the drag.
4
+ */
5
+ const isPlainRecord = (value) => Object.prototype.toString.call(value) === "[object Object]";
6
+ export const MAX_DRAG_CHROME_NODES = 64;
7
+ export const MAX_DRAG_CHROME_BYTES = 32_768;
8
+ const MAX_DEPTH = 6;
9
+ const MAX_PROPS = 48;
10
+ const TAGS = ["div", "span", "svg", "path"];
11
+ const ATTRS = [
12
+ "d",
13
+ "viewBox",
14
+ "fill",
15
+ "stroke",
16
+ "stroke-width",
17
+ "stroke-linecap",
18
+ "stroke-linejoin",
19
+ "width",
20
+ "height",
21
+ ];
22
+ const PROP_NAME = /^-?[a-z][a-z0-9-]{0,63}$/;
23
+ // Paint only: nothing in the copy may make the frame fetch, nor a CSS escape that spells a fetch.
24
+ const FETCHES = /\\|url\(|image\(|image-set\(|src\(/i;
25
+ const isText = (value, max) => typeof value === "string" && value.length <= max;
26
+ function isMap(value, name) {
27
+ if (!isPlainRecord(value))
28
+ return false;
29
+ const entries = Object.entries(value);
30
+ return (entries.length <= MAX_PROPS &&
31
+ entries.every(([key, v]) => name(key) && isText(v, 512) && !FETCHES.test(v)));
32
+ }
33
+ const isStyleMap = (value) => isMap(value, (key) => PROP_NAME.test(key));
34
+ function nodesWithin(nodes, depth, count) {
35
+ if (!Array.isArray(nodes) || depth > MAX_DEPTH)
36
+ return false;
37
+ return nodes.every((node) => {
38
+ if (!isPlainRecord(node) || ++count.n > MAX_DRAG_CHROME_NODES)
39
+ return false;
40
+ const { tag, look, attrs, children, ...rest } = node;
41
+ return (!Object.keys(rest).length &&
42
+ TAGS.includes(tag) &&
43
+ isStyleMap(look) &&
44
+ (attrs === undefined || isMap(attrs, (key) => ATTRS.includes(key))) &&
45
+ (children === undefined || nodesWithin(children, depth + 1, count)));
46
+ });
47
+ }
48
+ const isPair = (value, positive) => isPlainRecord(value) &&
49
+ Object.keys(value).sort().join() === "x,y" &&
50
+ [value.x, value.y].every((n) => Number.isFinite(n) && (!positive || n > 0));
51
+ /** The chrome a draft request carries, or undefined when it is malformed or over the caps. */
52
+ export function parseDragChrome(value) {
53
+ if (value === null)
54
+ return null;
55
+ if (!isPlainRecord(value))
56
+ return undefined;
57
+ const { origin, scale, place, nodes, ...rest } = value;
58
+ const count = { n: 0 };
59
+ const valid = [
60
+ !Object.keys(rest).length,
61
+ isPair(origin, false),
62
+ isPair(scale, true),
63
+ Array.isArray(place) && place.length <= MAX_DRAG_CHROME_NODES && place.every(isStyleMap),
64
+ nodes === undefined ||
65
+ (nodesWithin(nodes, 1, count) && JSON.stringify(nodes).length <= MAX_DRAG_CHROME_BYTES),
66
+ ];
67
+ return valid.includes(false) ? undefined : value;
68
+ }
69
+ const SVG_NS = "http://www.w3.org/2000/svg";
70
+ const HOST_MARKS = [
71
+ "data-hf-ignore",
72
+ "data-hyperframes-ignore",
73
+ "data-hyperframes-picker-ignore",
74
+ "data-layout-ignore",
75
+ ];
76
+ let host = null;
77
+ let plane = null;
78
+ let placed = [];
79
+ let looks = [];
80
+ export const isDragChromeHost = (element) => element === host;
81
+ function build(node, into) {
82
+ const element = node.tag === "svg" || node.tag === "path"
83
+ ? document.createElementNS(SVG_NS, node.tag)
84
+ : document.createElement(node.tag);
85
+ for (const [name, value] of Object.entries(node.attrs ?? {}))
86
+ element.setAttribute(name, value);
87
+ placed.push(element);
88
+ looks.push(node.look);
89
+ into.appendChild(element);
90
+ for (const child of node.children ?? [])
91
+ build(child, element);
92
+ }
93
+ function mount(nodes) {
94
+ clearDragChrome();
95
+ host = document.createElement("div");
96
+ for (const mark of HOST_MARKS)
97
+ host.setAttribute(mark, "");
98
+ host.setAttribute("aria-hidden", "true");
99
+ host.style.cssText =
100
+ "all:initial;position:fixed;inset:0;pointer-events:none;z-index:2147483647;overflow:visible";
101
+ const root = host.attachShadow({ mode: "closed" });
102
+ plane = document.createElement("div");
103
+ plane.style.cssText = "position:absolute;left:0;top:0;transform-origin:0 0";
104
+ root.appendChild(plane);
105
+ for (const node of nodes)
106
+ build(node, plane);
107
+ document.documentElement.appendChild(host);
108
+ }
109
+ function writeStyle(element, props) {
110
+ for (const [name, value] of Object.entries(props))
111
+ element.style.setProperty(name, value);
112
+ }
113
+ /** Mounts, places or clears the chrome in the drafts' turn; false when this place fits no mounted copy. */
114
+ export function drawDragChrome(chrome) {
115
+ if (chrome === null) {
116
+ clearDragChrome();
117
+ return true;
118
+ }
119
+ if (chrome.nodes)
120
+ mount(chrome.nodes);
121
+ if (!plane || chrome.place.length !== placed.length)
122
+ return false;
123
+ const { origin, scale } = chrome;
124
+ plane.style.transform = `scale(${1 / scale.x}, ${1 / scale.y}) translate(${-origin.x}px, ${-origin.y}px)`;
125
+ placed.forEach((element, i) => {
126
+ element.removeAttribute("style");
127
+ writeStyle(element, looks[i]);
128
+ writeStyle(element, chrome.place[i]);
129
+ element.style.setProperty("pointer-events", "none", "important");
130
+ });
131
+ return true;
132
+ }
133
+ export function clearDragChrome() {
134
+ host?.remove();
135
+ host = plane = null;
136
+ placed = [];
137
+ looks = [];
138
+ }
139
+ /** Runs `read` with the chrome host out of the document, so nothing it reads carries it. */
140
+ export function withoutDragChrome(read) {
141
+ const mounted = host;
142
+ if (!mounted?.isConnected)
143
+ return read();
144
+ const html = document.documentElement;
145
+ const next = mounted.nextSibling;
146
+ mounted.remove();
147
+ try {
148
+ return read();
149
+ }
150
+ finally {
151
+ if (host === mounted)
152
+ html.insertBefore(mounted, next?.parentNode === html ? next : null);
153
+ }
154
+ }
@@ -1,6 +1,7 @@
1
1
  // Paused video frames for a frame Studio cannot script: the runtime asks over a port Studio handed it, and Studio
2
2
  // decodes. An ask names a path on the frame's own server and the proxy options it played, never a URL: Studio
3
3
  // resolves it against its own project before reading anything.
4
+ import { closePort, onPortMessage, postOnPort } from "../runtimePort.js";
4
5
  import { sourceFactsOfSrc } from "../mediaSourceLookup.js";
5
6
  import { isMessageList } from "../protocol.js";
6
7
  /** The query options the runtime's media proxy adds to a src; any other key never leaves the frame. */
@@ -95,21 +96,20 @@ export function portPausedVideoProvider(port) {
95
96
  if (isRecord(frame))
96
97
  frame.image?.close?.();
97
98
  };
98
- port.onmessage = (event) => {
99
- const reply = event.data;
99
+ onPortMessage(port, (reply) => {
100
100
  const entry = isRecord(reply) && isId(reply.id) ? pending.get(reply.id) : undefined;
101
101
  if (!entry)
102
102
  return closeImages(reply);
103
103
  pending.delete(reply.id);
104
104
  entry.resolve(reply);
105
- };
105
+ });
106
106
  const ask = (message, signal) => new Promise((resolve, reject) => {
107
107
  if (disposed)
108
108
  return reject(aborted());
109
109
  const onAbort = () => {
110
110
  if (!pending.delete(message.id))
111
111
  return;
112
- port.postMessage({ type: "abort", id: message.id });
112
+ postOnPort(port, { type: "abort", id: message.id });
113
113
  reject(aborted());
114
114
  };
115
115
  pending.set(message.id, {
@@ -120,7 +120,7 @@ export function portPausedVideoProvider(port) {
120
120
  reject,
121
121
  });
122
122
  signal?.addEventListener("abort", onAbort, { once: true });
123
- port.postMessage(message);
123
+ postOnPort(port, message);
124
124
  });
125
125
  const provider = {
126
126
  async decode(requests, signal) {
@@ -167,10 +167,10 @@ export function portPausedVideoProvider(port) {
167
167
  entry.reject(aborted());
168
168
  pending.clear();
169
169
  try {
170
- port.postMessage({ type: "close" });
170
+ postOnPort(port, { type: "close" });
171
171
  }
172
172
  catch { }
173
- port.close();
173
+ closePort(port);
174
174
  window.removeEventListener("pagehide", onPageHide);
175
175
  },
176
176
  };
@@ -208,10 +208,12 @@ function verifyTimelinesPopulated(win, targetKeys) {
208
208
  // GSAP masks a folded CSS translate/rotate/scale with `none`, and a tween writes what it animates
209
209
  // inline; a fresh load has only what the file authors. Opacity has its own restore.
210
210
  export function restoreAuthoredStyle(style, authored, tweened) {
211
- style.transform = authored?.transform ?? "";
211
+ for (const prop of ["transform", "translate", "rotate", "scale"]) {
212
+ style.setProperty(prop, authored?.getPropertyValue(prop) ?? "", authored?.getPropertyPriority(prop) ?? "");
213
+ }
212
214
  if (!authored)
213
215
  return;
214
- for (const prop of ["translate", "rotate", "scale", ...tweened]) {
216
+ for (const prop of tweened) {
215
217
  if (prop === "opacity")
216
218
  continue;
217
219
  style.setProperty(prop, authored.getPropertyValue(prop), authored.getPropertyPriority(prop));
@@ -1,6 +1,7 @@
1
1
  // Studio's stage acts inside a sealed frame: hold an element's before look, apply the parent's draws, give it back.
2
2
  // The parent owns every motion and easing; the frame only borrows named properties, writes validated values and
3
3
  // reports boxes, so a sealed act paints what an open one does without the parent touching the frame's document.
4
+ import { postOnPort } from "../runtimePort.js";
4
5
  import { MAX_DRAFT_PX, MAX_ELEMENT_TEXT } from "../editingElement.js";
5
6
  import { listenFrameKeydown } from "./canvasKeys.js";
6
7
  import { captureStageGhosts, inertStageGhost, MAX_STAGE_GHOST_MARKUP, } from "./stageGhost.js";
@@ -403,7 +404,7 @@ function start(doc, params, port, version) {
403
404
  const onInput = (event) => {
404
405
  const key = event instanceof KeyboardEvent ? event.key.slice(0, MAX_INPUT_KEY) : null;
405
406
  const { metaKey = false, ctrlKey = false } = event;
406
- port.postMessage({ v: version, event: "stage-input", type: event.type, key, metaKey, ctrlKey });
407
+ postOnPort(port, { v: version, event: "stage-input", type: event.type, key, metaKey, ctrlKey });
407
408
  };
408
409
  const stopInputs = view ? listenStageInputs(view, onInput) : () => { };
409
410
  // Observer callbacks run before the frame paints: an element its seek reveals is held before it shows.
@@ -411,7 +412,7 @@ function start(doc, params, port, version) {
411
412
  ? new view.MutationObserver(() => {
412
413
  const now = holdWaiting(open, doc);
413
414
  if (now.length > 0)
414
- port.postMessage({ v: version, event: "stage-act-ready", held: now });
415
+ postOnPort(port, { v: version, event: "stage-act-ready", held: now });
415
416
  if (open.waiting.size === 0)
416
417
  watch?.disconnect();
417
418
  })
@@ -1,5 +1,6 @@
1
1
  // `text-edit`: one in-place text editing session in the frame, for a parent that cannot script it.
2
2
  // It edits only an element it handed a handle for, and lets out nothing but text markup.
3
+ import { postOnPort } from "../runtimePort.js";
3
4
  import { EDITING_ELEMENT_HANDLE } from "../editingElement.js";
4
5
  import { elementForHandle } from "../editingHandles.js";
5
6
  import { isDomNode, isStylableElement } from "../domRealm.js";
@@ -347,7 +348,7 @@ function start(handle, caret, hostTakesAway, port, version) {
347
348
  return;
348
349
  const selection = selectionIn(editable);
349
350
  const caret = caretOf(open);
350
- port.postMessage({ v: version, event: "text-edit-selection", handle, selection, caret });
351
+ postOnPort(port, { v: version, event: "text-edit-selection", handle, selection, caret });
351
352
  },
352
353
  };
353
354
  const endInFrame = () => {
@@ -355,12 +356,12 @@ function start(handle, caret, hostTakesAway, port, version) {
355
356
  return;
356
357
  const ended = close(true);
357
358
  if (ended)
358
- port.postMessage({ v: version, event: "text-edit-ended", handle, ...ended });
359
+ postOnPort(port, { v: version, event: "text-edit-ended", handle, ...ended });
359
360
  };
360
361
  const stopListening = listen(editable, endInFrame, open.report);
361
362
  const stopFollowing = followCaret(editable, open);
362
363
  const stopPassing = hostTakesAway
363
- ? passAway(editable, (away) => port.postMessage({ v: version, event: "text-edit-away", handle, ...away }))
364
+ ? passAway(editable, (away) => postOnPort(port, { v: version, event: "text-edit-away", handle, ...away }))
364
365
  : () => { };
365
366
  open.stop = () => {
366
367
  stopListening();
@@ -1,5 +1,6 @@
1
1
  // `watch-geometry`: the frame pushes the named elements' `geometry` fields once per animation frame,
2
2
  // stamped on the clock both windows share, until an empty list, the page hiding, or the parent's release.
3
+ import { portMap, postOnPort } from "../runtimePort.js";
3
4
  import { EDITING_ELEMENT_HANDLE, MAX_DRAFT_PX, MAX_ELEMENT_ENTRIES, MAX_ELEMENT_VALUE, } from "../editingElement.js";
4
5
  import { swallow } from "../diagnostics.js";
5
6
  import { elementGeometry } from "../editingGeometry.js";
@@ -54,12 +55,12 @@ export function geometryEvent(data, version) {
54
55
  return null;
55
56
  return elements.every((e) => e === null || isGeometry(e)) ? { at, elements } : null;
56
57
  }
57
- const watches = new Map();
58
+ const watches = portMap();
58
59
  let wireVersion = 0;
59
60
  function pushTo(port, handles, at) {
60
61
  const { elements } = elementGeometry(handles, undefined);
61
62
  try {
62
- port.postMessage({ v: wireVersion, event: "geometry", at, elements });
63
+ postOnPort(port, { v: wireVersion, event: "geometry", at, elements });
63
64
  }
64
65
  catch {
65
66
  watches.delete(port);
@@ -70,8 +71,7 @@ function push() {
70
71
  observing = false;
71
72
  const at = performance.timeOrigin + performance.now();
72
73
  try {
73
- for (const [port, handles] of watches)
74
- pushTo(port, handles, at);
74
+ watches.forEach((handles, port) => pushTo(port, handles, at));
75
75
  }
76
76
  catch (err) {
77
77
  swallow("watchGeometry.push", err);
@@ -88,16 +88,16 @@ let observing = false;
88
88
  let nextFrame = 0;
89
89
  function observeThisFrame() {
90
90
  nextFrame = 0;
91
- if (!watches.size)
91
+ if (!watches.size())
92
92
  return;
93
93
  observer ??= new ResizeObserver(push);
94
94
  observer.observe(document.documentElement);
95
95
  observing = true;
96
96
  }
97
97
  function schedule() {
98
- if (watches.size && !nextFrame && !observing)
98
+ if (watches.size() && !nextFrame && !observing)
99
99
  nextFrame = requestAnimationFrame(observeThisFrame);
100
- if (watches.size)
100
+ if (watches.size())
101
101
  return;
102
102
  if (nextFrame)
103
103
  cancelAnimationFrame(nextFrame);
@@ -118,7 +118,7 @@ const stopAll = () => stopWatchingGeometry();
118
118
  export function watchGeometry(port, { handles }, version) {
119
119
  if (!handles.length)
120
120
  watches.delete(port);
121
- else if (watches.has(port) || watches.size < MAX_GEOMETRY_WATCHERS)
121
+ else if (watches.has(port) || watches.size() < MAX_GEOMETRY_WATCHERS)
122
122
  watches.set(port, handles);
123
123
  else
124
124
  throw new Error(`at most ${MAX_GEOMETRY_WATCHERS} ports may watch geometry`);
@@ -0,0 +1,26 @@
1
+ import { type EditingElementHit } from "../editingElement.js";
2
+ export declare const MAX_POINTER_WATCHERS = 8;
3
+ export declare const MAX_POINT_SEQ: number;
4
+ /** `point` is in fractions of the root's box, as `pointer-targets` takes it; null stops the watch. */
5
+ export type WatchPointerParams = {
6
+ point: {
7
+ x: number;
8
+ y: number;
9
+ } | null;
10
+ seq?: number;
11
+ };
12
+ /** `at` is `performance.timeOrigin + performance.now()` in the frame when it hit-tested. */
13
+ export type EditingPointerEvent = {
14
+ at: number;
15
+ target: EditingElementHit | null;
16
+ stack: EditingElementHit[];
17
+ seq?: number;
18
+ };
19
+ export declare function parseWatchPointer(params: unknown): WatchPointerParams | null;
20
+ /** One pushed message off the port, or null for anything with a field it does not allow. */
21
+ export declare function pointerEvent(data: unknown, version: number): EditingPointerEvent | null;
22
+ /** Stops `port`'s watch, or every watch when no port is named. */
23
+ export declare function stopWatchingPointer(port?: MessagePort): void;
24
+ export declare function watchPointer(port: MessagePort, { point, seq }: WatchPointerParams, version: number): {
25
+ watching: boolean;
26
+ };
@@ -0,0 +1,105 @@
1
+ // `watch-pointer`: while the parent's pointer rests on the frame, the frame hit-tests that point each animation frame
2
+ // and pushes the `pointer-targets` answer only when it changes, until a null point, pagehide, or the release. A hidden
3
+ // page pauses it.
4
+ import { portMap, postOnPort } from "../runtimePort.js";
5
+ import { EDITING_ELEMENT_HANDLE, MAX_ELEMENT_VALUE, MAX_POINT_STACK, } from "../editingElement.js";
6
+ import { swallow } from "../diagnostics.js";
7
+ import { pointerTargetsAt } from "../editingTargets.js";
8
+ export const MAX_POINTER_WATCHERS = 8;
9
+ export const MAX_POINT_SEQ = 2 ** 31 - 1;
10
+ const isRecord = (value) => Object.prototype.toString.call(value) === "[object Object]";
11
+ const keysAre = (value, keys) => isRecord(value) && Object.keys(value).sort().join() === keys;
12
+ const finite = (value) => Number.isFinite(value);
13
+ const isSeq = (value) => Number.isSafeInteger(value) && value >= 0 && value <= MAX_POINT_SEQ;
14
+ const seqOf = (fields) => (isSeq(fields.seq) ? { seq: fields.seq } : {});
15
+ export function parseWatchPointer(params) {
16
+ if (!keysAre(params, "point") && !(keysAre(params, "point,seq") && isSeq(params.seq)))
17
+ return null;
18
+ const { point } = params;
19
+ if (point === null)
20
+ return { point: null };
21
+ return keysAre(point, "x,y") && finite(point.x) && finite(point.y)
22
+ ? { point: { x: point.x, y: point.y }, ...seqOf(params) }
23
+ : null;
24
+ }
25
+ const isHit = (value) => keysAre(value, "handle,rect,tag") &&
26
+ typeof value.handle === "string" &&
27
+ EDITING_ELEMENT_HANDLE.test(value.handle) &&
28
+ typeof value.tag === "string" &&
29
+ value.tag.length <= MAX_ELEMENT_VALUE &&
30
+ keysAre(value.rect, "height,width,x,y") &&
31
+ [value.rect.x, value.rect.y, value.rect.width, value.rect.height].every(finite);
32
+ /** One pushed message off the port, or null for anything with a field it does not allow. */
33
+ export function pointerEvent(data, version) {
34
+ const tagged = keysAre(data, "at,event,seq,stack,target,v") && isSeq(data.seq);
35
+ if ((!tagged && !keysAre(data, "at,event,stack,target,v")) || data.v !== version)
36
+ return null;
37
+ const { at, target, stack } = data;
38
+ if (data.event !== "pointer-targets" || !finite(at) || !Array.isArray(stack))
39
+ return null;
40
+ if (stack.length > MAX_POINT_STACK || !stack.every(isHit))
41
+ return null;
42
+ return target === null || isHit(target) ? { at, target, stack, ...seqOf(data) } : null;
43
+ }
44
+ const watches = portMap();
45
+ let wireVersion = 0;
46
+ let nextFrame = 0;
47
+ function check(port, watch, at) {
48
+ const { target, stack } = pointerTargetsAt(watch.x, watch.y);
49
+ const answer = JSON.stringify([target, stack]);
50
+ if (answer === watch.last)
51
+ return;
52
+ watch.last = answer;
53
+ try {
54
+ const seq = watch.seq === undefined ? {} : { seq: watch.seq };
55
+ postOnPort(port, { v: wireVersion, event: "pointer-targets", at, target, stack, ...seq });
56
+ }
57
+ catch {
58
+ watches.delete(port);
59
+ }
60
+ }
61
+ function checkAll() {
62
+ nextFrame = 0;
63
+ const at = performance.timeOrigin + performance.now();
64
+ try {
65
+ watches.forEach((watch, port) => check(port, watch, at));
66
+ }
67
+ catch (err) {
68
+ swallow("watchPointer.check", err);
69
+ }
70
+ finally {
71
+ schedule();
72
+ }
73
+ }
74
+ function schedule() {
75
+ if (watches.size() && !document.hidden) {
76
+ nextFrame ||= requestAnimationFrame(checkAll);
77
+ return;
78
+ }
79
+ if (nextFrame)
80
+ cancelAnimationFrame(nextFrame);
81
+ nextFrame = 0;
82
+ }
83
+ /** Stops `port`'s watch, or every watch when no port is named. */
84
+ export function stopWatchingPointer(port) {
85
+ if (port)
86
+ watches.delete(port);
87
+ else
88
+ watches.clear();
89
+ schedule();
90
+ }
91
+ const stopAll = () => stopWatchingPointer();
92
+ export function watchPointer(port, { point, seq }, version) {
93
+ if (!point)
94
+ watches.delete(port);
95
+ else if (watches.has(port) || watches.size() < MAX_POINTER_WATCHERS)
96
+ watches.set(port, { x: point.x, y: point.y, last: null, seq });
97
+ else
98
+ throw new Error(`at most ${MAX_POINTER_WATCHERS} ports may watch the pointer`);
99
+ wireVersion = version;
100
+ window.addEventListener("pagehide", stopAll);
101
+ // A hidden page checks nothing; its watch resumes when shown, so the parent never holds an answer it thinks is live.
102
+ document.addEventListener("visibilitychange", schedule);
103
+ schedule();
104
+ return { watching: point !== null };
105
+ }
@@ -1,5 +1,6 @@
1
1
  import type { EditingDraftReply } from "./editingDraftEnd.js";
2
2
  import type { EditingDraft } from "./editingPort.js";
3
+ import { type EditingDragChrome } from "./editing/dragChrome.js";
3
4
  export declare function rebaseDrawnPosition(element: Element, props: Record<string, unknown>): void;
4
- /** Applies each draft in order; one for an element this load no longer has is skipped. */
5
- export declare function drawDrafts(drafts: readonly EditingDraft[]): EditingDraftReply;
5
+ /** Applies each draft in order, then `chrome`; one for an element this load no longer has is skipped. */
6
+ export declare function drawDrafts(drafts: readonly EditingDraft[], chrome?: EditingDragChrome): EditingDraftReply;