@hyperframes/core 0.9.102 → 0.9.104

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 (40) hide show
  1. package/dist/atomicFile.d.ts +1 -0
  2. package/dist/atomicFile.js +1 -1
  3. package/dist/compiler/compositionScoping.js +3 -3
  4. package/dist/compiler/svgIdNamespacing.js +2 -2
  5. package/dist/fonts/authoredGoogleFonts.js +2 -2
  6. package/dist/fonts/deterministicFonts.js +2 -2
  7. package/dist/generated/position-edits-render-inline.js +1 -1
  8. package/dist/generated/runtime-inline.js +1 -1
  9. package/dist/hyperframe.runtime.iife.js +71 -71
  10. package/dist/index.d.ts +1 -1
  11. package/dist/runtime/domRealm.d.ts +1 -0
  12. package/dist/runtime/domRealm.js +3 -0
  13. package/dist/runtime/editing/canvasKeys.d.ts +63 -0
  14. package/dist/runtime/editing/canvasKeys.js +471 -0
  15. package/dist/runtime/editing/pausedFrames.js +7 -7
  16. package/dist/runtime/editing/removeElements.d.ts +10 -0
  17. package/dist/runtime/editing/removeElements.js +35 -0
  18. package/dist/runtime/editing/stageAct.d.ts +116 -0
  19. package/dist/runtime/editing/stageAct.js +531 -0
  20. package/dist/runtime/editing/stageGhost.d.ts +10 -0
  21. package/dist/runtime/editing/stageGhost.js +64 -0
  22. package/dist/runtime/editing/stageMeasure.d.ts +5 -0
  23. package/dist/runtime/editing/stageMeasure.js +35 -1
  24. package/dist/runtime/editing/textEdit.d.ts +14 -0
  25. package/dist/runtime/editing/textEdit.js +67 -9
  26. package/dist/runtime/editing/transformValues.d.ts +6 -0
  27. package/dist/runtime/editing/transformValues.js +39 -0
  28. package/dist/runtime/editing/watchGeometry.js +8 -8
  29. package/dist/runtime/editingGestureStart.d.ts +2 -0
  30. package/dist/runtime/editingGestureStart.js +1 -1
  31. package/dist/runtime/editingPort.d.ts +35 -3
  32. package/dist/runtime/editingPort.js +78 -16
  33. package/dist/runtime/playbackHealth.d.ts +8 -1
  34. package/dist/runtime/playbackHealth.js +118 -18
  35. package/dist/runtime/runtimePort.d.ts +21 -0
  36. package/dist/runtime/runtimePort.js +122 -0
  37. package/dist/runtime/types.d.ts +18 -0
  38. package/dist/studioPreviewMark.d.ts +1 -0
  39. package/dist/studioPreviewMark.js +1 -0
  40. package/package.json +4 -4
@@ -0,0 +1,116 @@
1
+ import { type EditingRect } from "../editingElement.js";
2
+ import { type StageActGhost } from "./stageGhost.js";
3
+ export declare const MAX_STAGE_ACTS = 64;
4
+ /** A deferred hold stops watching for its elements after this, so a run that never ends leaves no observer. */
5
+ export declare const STAGE_HOLD_WATCH_MS = 30000;
6
+ export declare const STAGE_ACT_STYLES: readonly ["color", "background-color", "background-image", "font-size", "opacity", "box-shadow", "transform", "filter"];
7
+ export declare const STAGE_ACT_BORROWS: readonly ["color", "background-color", "background-image", "font-size", "opacity", "box-shadow", "transform", "filter", "translate", "scale", "rotate"];
8
+ export type StageActStyle = (typeof STAGE_ACT_STYLES)[number];
9
+ export type StageActBorrow = (typeof STAGE_ACT_BORROWS)[number];
10
+ /** One frame of an act. `translate`, `scale` and `rotate` move the element's own values, never replace them. */
11
+ export interface StageActDraw {
12
+ translate?: [number, number];
13
+ scale?: number;
14
+ rotate?: number;
15
+ styles?: Partial<Record<StageActStyle, string>>;
16
+ /** Graphemes of a typed act shown so far; the caret shows until all are. */
17
+ typed?: number;
18
+ }
19
+ export interface StageActTarget {
20
+ key: string;
21
+ hfId: string | null;
22
+ }
23
+ /** An element held in its before look: `borrow` names every property its draws may write and its restore puts back. */
24
+ export type StageActElementHold = StageActTarget & {
25
+ borrow: StageActBorrow[];
26
+ draw: StageActDraw;
27
+ typing?: {
28
+ hidden: boolean;
29
+ };
30
+ };
31
+ /** A removed element stood back as a ghost from markup relayed out of the frame it left. */
32
+ export type StageActGhostHold = {
33
+ key: string;
34
+ ghost: {
35
+ markup: string;
36
+ box: EditingRect;
37
+ };
38
+ draw: StageActDraw;
39
+ };
40
+ export type StageActHold = StageActElementHold | StageActGhostHold;
41
+ export type StageActParams = {
42
+ op: "hold";
43
+ acts: StageActHold[];
44
+ deferred: boolean;
45
+ caretColor: string;
46
+ } | {
47
+ op: "frame";
48
+ draws: {
49
+ key: string;
50
+ draw: StageActDraw;
51
+ }[];
52
+ } | {
53
+ op: "ready";
54
+ keys: string[];
55
+ } | {
56
+ op: "restore";
57
+ keys: string[] | null;
58
+ } | {
59
+ op: "capture";
60
+ targets: StageActTarget[];
61
+ };
62
+ export interface StageActHeld {
63
+ key: string;
64
+ rect: EditingRect;
65
+ textStart: {
66
+ x: number;
67
+ y: number;
68
+ } | null;
69
+ chars: number;
70
+ }
71
+ export interface StageActRect {
72
+ key: string;
73
+ rect: EditingRect;
74
+ }
75
+ export type StageActResult = {
76
+ op: "hold";
77
+ held: StageActHeld[];
78
+ } | {
79
+ op: "frame";
80
+ rects: StageActRect[];
81
+ } | {
82
+ op: "ready";
83
+ held: StageActHeld[];
84
+ } | {
85
+ op: "restore";
86
+ restored: number;
87
+ } | {
88
+ op: "capture";
89
+ ghosts: StageActGhost[];
90
+ };
91
+ export type StageActReadyEvent = {
92
+ v: number;
93
+ event: "stage-act-ready";
94
+ held: StageActHeld[];
95
+ };
96
+ export type StageInputEvent = {
97
+ v: number;
98
+ event: "stage-input";
99
+ type: (typeof STAGE_INPUTS)[number];
100
+ key: string | null;
101
+ metaKey: boolean;
102
+ ctrlKey: boolean;
103
+ };
104
+ declare const STAGE_INPUTS: readonly ["pointerdown", "drop", "keydown"];
105
+ /** A colour as computed styles give it, with no reference out of the frame (`url`, `var`, `attr`). */
106
+ export declare const isStageColour: (value: unknown) => value is string;
107
+ export declare function readStageRect(value: unknown): EditingRect | null;
108
+ /** One `stage-act` request off the wire, or null: an over-cap list, a value outside its grammar, an unknown field. */
109
+ export declare function parseStageActParams(params: unknown): StageActParams | null;
110
+ /** Gives every held element back and stops watching; the agent's dispose and a new hold call it. */
111
+ export declare function endStageAct(): void;
112
+ export declare function stageAct(params: StageActParams, port: MessagePort, version: number, doc?: Document): StageActResult;
113
+ export declare function readStageActHeld(value: unknown): StageActHeld | null;
114
+ export declare function stageActReadyEvent(data: unknown, version: number): StageActReadyEvent | null;
115
+ export declare function stageInputEvent(data: unknown, version: number): StageInputEvent | null;
116
+ export {};
@@ -0,0 +1,531 @@
1
+ // Studio's stage acts inside a sealed frame: hold an element's before look, apply the parent's draws, give it back.
2
+ // The parent owns every motion and easing; the frame only borrows named properties, writes validated values and
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";
5
+ import { MAX_DRAFT_PX, MAX_ELEMENT_TEXT } from "../editingElement.js";
6
+ import { listenFrameKeydown } from "./canvasKeys.js";
7
+ import { captureStageGhosts, inertStageGhost, MAX_STAGE_GHOST_MARKUP, } from "./stageGhost.js";
8
+ import { locateStageKey, paintedOnStage } from "./stageMeasure.js";
9
+ import { rotateBy, scaleBy, translateBy } from "./transformValues.js";
10
+ export const MAX_STAGE_ACTS = 64;
11
+ const MAX_STAGE_FONT_PX = 4_096;
12
+ const MAX_STAGE_TURN_DEG = 3_600;
13
+ const MAX_STAGE_SCALE = 100;
14
+ /** A deferred hold stops watching for its elements after this, so a run that never ends leaves no observer. */
15
+ export const STAGE_HOLD_WATCH_MS = 30_000;
16
+ const MAX_STYLE_VALUE = 512;
17
+ const MAX_KEY = 1_024;
18
+ const MAX_INPUT_KEY = 32;
19
+ export const STAGE_ACT_STYLES = [
20
+ "color",
21
+ "background-color",
22
+ "background-image",
23
+ "font-size",
24
+ "opacity",
25
+ "box-shadow",
26
+ "transform",
27
+ "filter",
28
+ ];
29
+ const TRANSFORMS = ["translate", "scale", "rotate"];
30
+ export const STAGE_ACT_BORROWS = [...STAGE_ACT_STYLES, ...TRANSFORMS];
31
+ const STAGE_INPUTS = ["pointerdown", "drop", "keydown"];
32
+ const STAGE_POINTER_INPUTS = ["pointerdown", "drop"];
33
+ const isFields = (value) => Object.prototype.toString.call(value) === "[object Object]";
34
+ const onlyKeys = (value, allowed) => Object.keys(value).every((key) => allowed.includes(key));
35
+ const isKey = (value) => typeof value === "string" && value.length > 0 && value.length <= MAX_KEY;
36
+ const isFiniteIn = (value, max) => typeof value === "number" && Number.isFinite(value) && Math.abs(value) <= max;
37
+ const list = (value, max) => Array.isArray(value) && value.length <= max ? value : null;
38
+ const COLOUR_FUNCTIONS = "rgba?|hsla?|hwb|lab|lch|oklab|oklch|color";
39
+ const COLOUR = new RegExp(`^(#[0-9a-f]{3,8}|[a-z]+|(${COLOUR_FUNCTIONS})\\([a-z0-9 .,%/+-]*\\))$`, "i");
40
+ // Functions a drawn value may call: colours, the spread's gradient, a turn, a drop shadow, own-value maths.
41
+ const VALUE_FUNCTIONS = new RegExp(`^(${COLOUR_FUNCTIONS}|radial-gradient|rotate|drop-shadow|calc)$`, "i");
42
+ /** A colour as computed styles give it, with no reference out of the frame (`url`, `var`, `attr`). */
43
+ export const isStageColour = (value) => typeof value === "string" && value.length <= MAX_STYLE_VALUE && COLOUR.test(value.trim());
44
+ function isDrawnValue(value) {
45
+ if (value.length > MAX_STYLE_VALUE || !/^[a-z0-9 .,%#()+\-/]*$/i.test(value))
46
+ return false;
47
+ for (const [, name] of value.matchAll(/([a-z-]*)\(/gi))
48
+ if (!VALUE_FUNCTIONS.test(name ?? ""))
49
+ return false;
50
+ return true;
51
+ }
52
+ const STYLE_CHECKS = {
53
+ color: isStageColour,
54
+ "background-color": isStageColour,
55
+ "background-image": (value) => value === "none" || (value.startsWith("radial-gradient(") && isDrawnValue(value)),
56
+ "font-size": (value) => {
57
+ const px = /^(\d+(\.\d+)?)px$/.exec(value);
58
+ return px !== null && Number(px[1]) > 0 && Number(px[1]) <= MAX_STAGE_FONT_PX;
59
+ },
60
+ opacity: (value) => /^\d*\.?\d+$/.test(value) && Number(value) <= 1,
61
+ "box-shadow": isDrawnValue,
62
+ transform: isDrawnValue,
63
+ filter: isDrawnValue,
64
+ };
65
+ /** The table's own entry for `name`, never one inherited from Object (a field named `constructor`). */
66
+ const ownEntry = (table, name) => Object.hasOwn(table, name) ? table[name] : undefined;
67
+ /** Every entry parsed, or null when any is not. */
68
+ const allParsed = (entries) => entries?.every((entry) => entry !== null) ? entries : null;
69
+ function parseStyles(value) {
70
+ if (!isFields(value))
71
+ return null;
72
+ const valid = Object.entries(value).every(([name, css]) => {
73
+ const check = ownEntry(STYLE_CHECKS, name);
74
+ return check !== undefined && typeof css === "string" && check(css);
75
+ });
76
+ return valid ? value : null;
77
+ }
78
+ const DRAW_FIELDS = {
79
+ translate: (value) => {
80
+ const pair = list(value, 2);
81
+ return pair?.length === 2 && pair.every((n) => isFiniteIn(n, MAX_DRAFT_PX)) ? pair : null;
82
+ },
83
+ scale: (value) => (isFiniteIn(value, MAX_STAGE_SCALE) && value >= 0 ? value : null),
84
+ rotate: (value) => (isFiniteIn(value, MAX_STAGE_TURN_DEG) ? value : null),
85
+ typed: (value) => Number.isSafeInteger(value) && value >= 0 && value <= MAX_ELEMENT_TEXT
86
+ ? value
87
+ : null,
88
+ styles: parseStyles,
89
+ };
90
+ function parseDraw(value) {
91
+ if (!isFields(value))
92
+ return null;
93
+ const draw = {};
94
+ for (const [name, field] of Object.entries(value)) {
95
+ if (field === undefined)
96
+ continue;
97
+ const parsed = ownEntry(DRAW_FIELDS, name)?.(field) ?? null;
98
+ if (parsed === null)
99
+ return null;
100
+ draw[name] = parsed;
101
+ }
102
+ return draw;
103
+ }
104
+ export function readStageRect(value) {
105
+ if (!isFields(value))
106
+ return null;
107
+ const { x, y, width, height } = value;
108
+ if (![x, y, width, height].every((n) => isFiniteIn(n, MAX_DRAFT_PX)))
109
+ return null;
110
+ return { x, y, width, height };
111
+ }
112
+ const parseTarget = (value) => isFields(value) &&
113
+ onlyKeys(value, ["key", "hfId"]) &&
114
+ isKey(value.key) &&
115
+ (value.hfId === null || isKey(value.hfId))
116
+ ? { key: value.key, hfId: value.hfId }
117
+ : null;
118
+ const parseBorrow = (value) => {
119
+ const names = list(value, STAGE_ACT_BORROWS.length);
120
+ return names?.every((name) => STAGE_ACT_BORROWS.includes(name))
121
+ ? names
122
+ : null;
123
+ };
124
+ /** Absent is undefined; present must be `{ hidden: boolean }`. */
125
+ const parseTyping = (value) => {
126
+ if (value === undefined)
127
+ return undefined;
128
+ return isFields(value) && onlyKeys(value, ["hidden"]) && typeof value.hidden === "boolean"
129
+ ? { hidden: value.hidden }
130
+ : null;
131
+ };
132
+ function parseGhostHold(value) {
133
+ if (!onlyKeys(value, ["key", "ghost", "draw"]) || !isKey(value.key) || !isFields(value.ghost))
134
+ return null;
135
+ const { markup, box } = value.ghost;
136
+ const rect = readStageRect(box);
137
+ const draw = parseDraw(value.draw);
138
+ if (typeof markup !== "string" || markup.length > MAX_STAGE_GHOST_MARKUP)
139
+ return null;
140
+ return rect && draw && { key: value.key, ghost: { markup, box: rect }, draw };
141
+ }
142
+ function parseHold(value) {
143
+ if (!isFields(value))
144
+ return null;
145
+ if ("ghost" in value)
146
+ return parseGhostHold(value);
147
+ if (!onlyKeys(value, ["key", "hfId", "borrow", "draw", "typing"]))
148
+ return null;
149
+ const target = parseTarget({ key: value.key, hfId: value.hfId });
150
+ const borrow = parseBorrow(value.borrow);
151
+ const draw = parseDraw(value.draw);
152
+ const typing = parseTyping(value.typing);
153
+ if (!target || !borrow || !draw || typing === null)
154
+ return null;
155
+ return { ...target, borrow, draw, ...(typing && { typing }) };
156
+ }
157
+ const parseFrameDraw = (entry) => {
158
+ if (!isFields(entry) || !onlyKeys(entry, ["key", "draw"]) || !isKey(entry.key))
159
+ return null;
160
+ const draw = parseDraw(entry.draw);
161
+ return draw && { key: entry.key, draw };
162
+ };
163
+ const keyList = (value) => {
164
+ const keys = list(value, MAX_STAGE_ACTS);
165
+ return keys?.every(isKey) ? keys : null;
166
+ };
167
+ const OP_PARSERS = {
168
+ hold: (params) => {
169
+ const acts = allParsed(list(params.acts, MAX_STAGE_ACTS)?.map(parseHold));
170
+ const { deferred, caretColor } = params;
171
+ if (!onlyKeys(params, ["op", "acts", "deferred", "caretColor"]) || !acts)
172
+ return null;
173
+ if (typeof deferred !== "boolean" || !isStageColour(caretColor))
174
+ return null;
175
+ // A key held twice would borrow its own first draw and restore that, not the element's values.
176
+ if (new Set(acts.map((act) => act.key)).size !== acts.length)
177
+ return null;
178
+ return { op: "hold", acts, deferred, caretColor };
179
+ },
180
+ frame: (params) => {
181
+ const draws = allParsed(list(params.draws, MAX_STAGE_ACTS)?.map(parseFrameDraw));
182
+ return onlyKeys(params, ["op", "draws"]) && draws ? { op: "frame", draws } : null;
183
+ },
184
+ ready: (params) => {
185
+ const keys = keyList(params.keys);
186
+ return onlyKeys(params, ["op", "keys"]) && keys ? { op: "ready", keys } : null;
187
+ },
188
+ restore: (params) => {
189
+ const keys = params.keys === null ? null : keyList(params.keys);
190
+ if (!onlyKeys(params, ["op", "keys"]) || (keys === null && params.keys !== null))
191
+ return null;
192
+ return { op: "restore", keys };
193
+ },
194
+ capture: (params) => {
195
+ const targets = allParsed(list(params.targets, MAX_STAGE_ACTS)?.map(parseTarget));
196
+ return onlyKeys(params, ["op", "targets"]) && targets ? { op: "capture", targets } : null;
197
+ },
198
+ };
199
+ /** One `stage-act` request off the wire, or null: an over-cap list, a value outside its grammar, an unknown field. */
200
+ export function parseStageActParams(params) {
201
+ if (!isFields(params) || typeof params.op !== "string")
202
+ return null;
203
+ return ownEntry(OP_PARSERS, params.op)?.(params) ?? null;
204
+ }
205
+ let session = null;
206
+ const rectOf = (element) => {
207
+ const { x, y, width, height } = element.getBoundingClientRect();
208
+ return { x, y, width, height };
209
+ };
210
+ function ownValue(element, name) {
211
+ const inline = element.style.getPropertyValue(name);
212
+ return (inline ||
213
+ (element.ownerDocument.defaultView?.getComputedStyle(element).getPropertyValue(name) ?? ""));
214
+ }
215
+ function borrow(style, names) {
216
+ const kept = names.map((name) => [style.getPropertyValue(name), style.getPropertyPriority(name)]);
217
+ return () => names.forEach((name, i) => style.setProperty(name, ...kept[i]));
218
+ }
219
+ function textStartOf(nodes) {
220
+ const range = nodes[0].ownerDocument.createRange();
221
+ range.setStart(nodes[0], 0);
222
+ range.setEnd(nodes.at(-1), nodes.at(-1).length);
223
+ const box = range.getBoundingClientRect?.();
224
+ return box && box.width > 0 ? { x: box.x, y: box.y + box.height / 2 } : null;
225
+ }
226
+ /** Empties the element's own text behind a hidden caret; `draw` types it back by whole graphemes. */
227
+ function typedText(element, hidden, caretColor) {
228
+ const nodes = [...element.childNodes].filter((node) => node.nodeType === 3);
229
+ const full = nodes.map((node) => node.data);
230
+ const text = full.join("");
231
+ if (!text.trim())
232
+ return null;
233
+ const letters = [...new Intl.Segmenter().segment(text)].map(({ segment }) => segment);
234
+ const textStart = textStartOf(nodes);
235
+ const show = hidden ? borrow(element.style, ["opacity"]) : () => { };
236
+ if (hidden)
237
+ element.style.setProperty("opacity", "0");
238
+ const caret = element.ownerDocument.createElement("i");
239
+ Object.assign(caret.style, {
240
+ display: "inline-block",
241
+ width: "2px",
242
+ height: "0.9em",
243
+ marginLeft: "2px",
244
+ verticalAlign: "-0.08em",
245
+ background: caretColor,
246
+ visibility: "hidden",
247
+ });
248
+ for (const node of nodes)
249
+ node.data = "";
250
+ // Held empty, the unseen caret keeps it a box: the runtime's layout pass sizes a 0 px clip 100% and it stays.
251
+ nodes[0].after(caret);
252
+ return {
253
+ letters: letters.length,
254
+ textStart,
255
+ type: (n) => {
256
+ show();
257
+ nodes[0].data = letters.slice(0, n).join("");
258
+ caret.style.visibility = "";
259
+ if (n < letters.length)
260
+ nodes[0].after(caret);
261
+ else
262
+ caret.remove();
263
+ },
264
+ restore: () => {
265
+ show();
266
+ caret.remove();
267
+ nodes.forEach((node, i) => (node.data = full[i]));
268
+ },
269
+ };
270
+ }
271
+ function holdElement(element, key, act, caretColor) {
272
+ // Its own values and borrowed properties are read before any write, typing's included.
273
+ const own = Object.fromEntries(TRANSFORMS.map((name) => [name, ownValue(element, name)]));
274
+ const borrowed = new Set(act.borrow);
275
+ const giveBack = borrow(element.style, act.borrow);
276
+ const typing = act.typing ? typedText(element, act.typing.hidden, caretColor) : null;
277
+ if (act.typing && !typing)
278
+ return null;
279
+ const apply = (draw) => {
280
+ const write = (name, value) => borrowed.has(name) && element.style.setProperty(name, value);
281
+ if (draw.translate)
282
+ write("translate", translateBy(own.translate, ...draw.translate));
283
+ if (draw.scale !== undefined)
284
+ write("scale", scaleBy(own.scale, draw.scale));
285
+ if (draw.rotate !== undefined)
286
+ write("rotate", rotateBy(own.rotate, draw.rotate));
287
+ for (const [name, value] of Object.entries(draw.styles ?? {}))
288
+ write(name, value);
289
+ if (draw.typed !== undefined)
290
+ typing?.type(draw.typed);
291
+ };
292
+ apply(act.draw);
293
+ return {
294
+ info: () => ({
295
+ key,
296
+ rect: rectOf(element),
297
+ textStart: typing?.textStart ?? null,
298
+ chars: typing?.letters ?? 0,
299
+ }),
300
+ apply,
301
+ restore: () => {
302
+ giveBack();
303
+ typing?.restore();
304
+ },
305
+ };
306
+ }
307
+ function holdGhost(doc, key, ghost, draw) {
308
+ const node = doc.body && inertStageGhost(doc, ghost.markup);
309
+ if (!node)
310
+ return null;
311
+ Object.assign(node.style, {
312
+ position: "fixed",
313
+ margin: "0",
314
+ left: `${ghost.box.x}px`,
315
+ top: `${ghost.box.y}px`,
316
+ translate: "none",
317
+ pointerEvents: "none",
318
+ });
319
+ node.setAttribute("aria-hidden", "true");
320
+ doc.body.appendChild(node);
321
+ const apply = (next) => {
322
+ if (next.translate)
323
+ node.style.setProperty("translate", translateBy("none", ...next.translate));
324
+ if (next.scale !== undefined)
325
+ node.style.setProperty("scale", scaleBy("none", next.scale));
326
+ for (const [name, value] of Object.entries(next.styles ?? {}))
327
+ node.style.setProperty(name, value);
328
+ };
329
+ apply(draw);
330
+ return {
331
+ info: () => ({ key, rect: rectOf(node), textStart: null, chars: 0 }),
332
+ apply,
333
+ restore: () => node.remove(),
334
+ };
335
+ }
336
+ /** Holds `act` now; "later" while a deferred element is not on the stage yet; null when it cannot be held. */
337
+ function tryHold(doc, act, deferred, caretColor) {
338
+ if ("ghost" in act)
339
+ return holdGhost(doc, act.key, act.ghost, act.draw);
340
+ const element = locateStageKey(doc, act);
341
+ const onStage = element?.style && paintedOnStage(element);
342
+ if (!onStage && deferred)
343
+ return "later";
344
+ if (!element?.style)
345
+ return null;
346
+ return holdElement(element, act.key, act, caretColor);
347
+ }
348
+ /** Gives every held element back and stops watching; the agent's dispose and a new hold call it. */
349
+ export function endStageAct() {
350
+ const open = session;
351
+ session = null;
352
+ if (!open)
353
+ return;
354
+ open.stop();
355
+ for (const held of open.held.values())
356
+ held.restore();
357
+ }
358
+ function holdWaiting(open, doc, keys) {
359
+ const now = [];
360
+ for (const [key, act] of open.waiting) {
361
+ if (keys && !keys.includes(key))
362
+ continue;
363
+ const held = tryHold(doc, act, true, open.caretColor);
364
+ if (held === "later")
365
+ continue;
366
+ open.waiting.delete(key);
367
+ if (!held)
368
+ continue;
369
+ open.held.set(key, held);
370
+ now.push(held.info());
371
+ }
372
+ return now;
373
+ }
374
+ /** Those of `keys` held now, already or just: asked again after a lost reply, it still reports them. */
375
+ function readyNow(open, doc, keys) {
376
+ const already = keys.flatMap((key) => {
377
+ const held = open.held.get(key);
378
+ return held ? [held.info()] : [];
379
+ });
380
+ return [...already, ...holdWaiting(open, doc, keys)];
381
+ }
382
+ function start(doc, params, port, version) {
383
+ endStageAct();
384
+ const view = doc.defaultView;
385
+ const open = {
386
+ port,
387
+ caretColor: params.caretColor,
388
+ held: new Map(),
389
+ waiting: new Map(),
390
+ stop: () => { },
391
+ };
392
+ session = open;
393
+ const held = [];
394
+ for (const act of params.acts) {
395
+ const one = tryHold(doc, act, params.deferred, params.caretColor);
396
+ if (one === "later")
397
+ open.waiting.set(act.key, act);
398
+ else if (one) {
399
+ open.held.set(act.key, one);
400
+ held.push(one.info());
401
+ }
402
+ }
403
+ // The person's press, drop or key in the frame: the parent decides whether it edits and ends the run.
404
+ const onInput = (event) => {
405
+ const key = event instanceof KeyboardEvent ? event.key.slice(0, MAX_INPUT_KEY) : null;
406
+ const { metaKey = false, ctrlKey = false } = event;
407
+ postOnPort(port, { v: version, event: "stage-input", type: event.type, key, metaKey, ctrlKey });
408
+ };
409
+ const stopInputs = view ? listenStageInputs(view, onInput) : () => { };
410
+ // Observer callbacks run before the frame paints: an element its seek reveals is held before it shows.
411
+ const watch = open.waiting.size > 0 && view
412
+ ? new view.MutationObserver(() => {
413
+ const now = holdWaiting(open, doc);
414
+ if (now.length > 0)
415
+ postOnPort(port, { v: version, event: "stage-act-ready", held: now });
416
+ if (open.waiting.size === 0)
417
+ watch?.disconnect();
418
+ })
419
+ : null;
420
+ watch?.observe(doc.documentElement, { attributes: true, childList: true, subtree: true });
421
+ const cap = watch && view ? view.setTimeout(() => watch.disconnect(), STAGE_HOLD_WATCH_MS) : 0;
422
+ open.stop = () => {
423
+ watch?.disconnect();
424
+ if (cap)
425
+ view?.clearTimeout(cap);
426
+ stopInputs();
427
+ };
428
+ return { op: "hold", held };
429
+ }
430
+ function listenStageInputs(view, onInput) {
431
+ for (const type of STAGE_POINTER_INPUTS)
432
+ view.addEventListener(type, onInput, true);
433
+ const stopKeys = listenFrameKeydown(view, onInput);
434
+ return () => {
435
+ for (const type of STAGE_POINTER_INPUTS)
436
+ view.removeEventListener(type, onInput, true);
437
+ stopKeys();
438
+ };
439
+ }
440
+ export function stageAct(params, port, version, doc = document) {
441
+ if (params.op === "capture")
442
+ return { op: "capture", ghosts: captureStageGhosts(doc, params.targets) };
443
+ if (params.op === "hold")
444
+ return start(doc, params, port, version);
445
+ const open = session?.port === port ? session : null;
446
+ if (params.op === "frame") {
447
+ const drawn = params.draws.flatMap(({ key, draw }) => {
448
+ const held = open?.held.get(key);
449
+ held?.apply(draw);
450
+ return held ? [held] : [];
451
+ });
452
+ // Every write lands before any box is read, so the frame lays out once for the whole draw.
453
+ return {
454
+ op: "frame",
455
+ rects: drawn.map((held) => {
456
+ const { key, rect } = held.info();
457
+ return { key, rect };
458
+ }),
459
+ };
460
+ }
461
+ if (params.op === "ready")
462
+ return { op: "ready", held: open ? readyNow(open, doc, params.keys) : [] };
463
+ if (!open)
464
+ return { op: "restore", restored: 0 };
465
+ if (params.keys === null) {
466
+ const restored = open.held.size;
467
+ endStageAct();
468
+ return { op: "restore", restored };
469
+ }
470
+ let restored = 0;
471
+ for (const key of params.keys) {
472
+ open.waiting.delete(key);
473
+ const held = open.held.get(key);
474
+ if (!held)
475
+ continue;
476
+ open.held.delete(key);
477
+ held.restore();
478
+ restored += 1;
479
+ }
480
+ if (open.held.size === 0 && open.waiting.size === 0)
481
+ endStageAct();
482
+ return { op: "restore", restored };
483
+ }
484
+ // ---- the parent's reads of what the frame pushes
485
+ const readTextStart = (value) => {
486
+ if (value === null)
487
+ return null;
488
+ if (!isFields(value) || !isFiniteIn(value.x, MAX_DRAFT_PX) || !isFiniteIn(value.y, MAX_DRAFT_PX))
489
+ return undefined;
490
+ return { x: value.x, y: value.y };
491
+ };
492
+ export function readStageActHeld(value) {
493
+ if (!isFields(value) || !isKey(value.key))
494
+ return null;
495
+ const rect = readStageRect(value.rect);
496
+ const textStart = readTextStart(value.textStart);
497
+ const { chars } = value;
498
+ if (!rect || textStart === undefined || !Number.isSafeInteger(chars))
499
+ return null;
500
+ if (chars < 0 || chars > MAX_ELEMENT_TEXT)
501
+ return null;
502
+ return { key: value.key, rect, textStart, chars: chars };
503
+ }
504
+ export function stageActReadyEvent(data, version) {
505
+ if (!isFields(data) || data.v !== version || data.event !== "stage-act-ready")
506
+ return null;
507
+ const entries = list(data.held, MAX_STAGE_ACTS);
508
+ const held = entries?.map(readStageActHeld);
509
+ if (!held?.every((one) => one !== null))
510
+ return null;
511
+ return { v: version, event: "stage-act-ready", held };
512
+ }
513
+ export function stageInputEvent(data, version) {
514
+ if (!isFields(data) || data.v !== version || data.event !== "stage-input")
515
+ return null;
516
+ const { type, key, metaKey, ctrlKey } = data;
517
+ if (!STAGE_INPUTS.includes(type))
518
+ return null;
519
+ if (key !== null && !(typeof key === "string" && key.length <= MAX_INPUT_KEY))
520
+ return null;
521
+ if (typeof metaKey !== "boolean" || typeof ctrlKey !== "boolean")
522
+ return null;
523
+ return {
524
+ v: version,
525
+ event: "stage-input",
526
+ type: type,
527
+ key,
528
+ metaKey,
529
+ ctrlKey,
530
+ };
531
+ }
@@ -0,0 +1,10 @@
1
+ import type { StageActTarget } from "./stageAct.js";
2
+ export declare const MAX_STAGE_GHOST_MARKUP = 65536;
3
+ export interface StageActGhost {
4
+ key: string;
5
+ markup: string;
6
+ }
7
+ /** Each target's subtree as markup, its computed look written on its root; one over the cap is left out. */
8
+ export declare function captureStageGhosts(doc: Document, targets: readonly StageActTarget[]): StageActGhost[];
9
+ /** Parses relayed markup inert and strips what could run, navigate or load as a document; null unless one element. */
10
+ export declare function inertStageGhost(doc: Document, markup: string): HTMLElement | null;