@hyperframes/core 0.9.84 → 0.9.86

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,39 @@
1
+ import type { RuntimeDeterministicAdapter, RuntimeTimelineLike } from "../types.js";
2
+ type GsapAdapterDeps = {
3
+ getTimeline: () => RuntimeTimelineLike | null;
4
+ };
5
+ /**
6
+ * Re-renders a timeline already at `t`, silently, from just below (above at 0) so same-time steps apply in authored
7
+ * order. That step skips a keyframed tween at its start and undoes from-values of tweens starting within it: redo both.
8
+ */
9
+ export declare function rerenderGsapTimelineAt(timeline: {
10
+ totalTime: (time: number, suppressEvents?: boolean) => unknown;
11
+ totalDuration?: () => number;
12
+ getChildren?: RuntimeTimelineLike["getChildren"];
13
+ }, t: number, structure?: GsapStructureKey): void;
14
+ export declare function gsapTimelineOf(timeline: object): object;
15
+ export declare function seekGsapTimeline(timeline: RuntimeTimelineLike, t: number, suppressEvents: boolean, structure?: GsapStructureKey, renderFps?: number): boolean;
16
+ export declare function redrawGsapTimelineAt(timeline: RuntimeTimelineLike, t: number, structure?: GsapStructureKey): void;
17
+ export type GsapStructureKey = {
18
+ owner: object;
19
+ version: string;
20
+ };
21
+ export type GsapPlaced = {
22
+ _start?: number;
23
+ _ts?: number;
24
+ _repeat?: number;
25
+ parent?: GsapPlaced | null;
26
+ getChildren?: unknown;
27
+ totalDuration?: () => number;
28
+ };
29
+ export declare function holdLandingMarks(timeline: {
30
+ getChildren?: RuntimeTimelineLike["getChildren"];
31
+ }, structure?: GsapStructureKey): () => void;
32
+ export declare function holdFrameMarks({ scenes, root, structureOf, }: {
33
+ scenes: RuntimeTimelineLike[];
34
+ root: RuntimeTimelineLike | null;
35
+ structureOf: (timeline: RuntimeTimelineLike) => GsapStructureKey | undefined;
36
+ }): (landBack: () => void) => void;
37
+ export declare function muteDiscreteCallbacks(timelines: RuntimeTimelineLike[]): () => void;
38
+ export declare function createGsapAdapter(deps: GsapAdapterDeps): RuntimeDeterministicAdapter;
39
+ export {};
@@ -0,0 +1,469 @@
1
+ import { authoredOrderOf } from "./gsapAuthoredOrder.js";
2
+ /**
3
+ * Re-renders a timeline already at `t`, silently, from just below (above at 0) so same-time steps apply in authored
4
+ * order. That step skips a keyframed tween at its start and undoes from-values of tweens starting within it: redo both.
5
+ */
6
+ export function rerenderGsapTimelineAt(timeline, t, structure) {
7
+ timeline.totalDuration?.();
8
+ const children = timeline.getChildren?.(false, true, true) ?? [];
9
+ const marked = landingMarksOf(timeline, structure, t).map((child) => [child, child.ratio, child._zTime, child._act]);
10
+ const skipped = childrenStartingAfter(children, t).map((child) => [child, child._ts]);
11
+ const parents = new Set();
12
+ for (const [child] of skipped) {
13
+ for (let parent = child.parent; parent && !parents.has(parent); parent = parent.parent)
14
+ parents.add(parent);
15
+ }
16
+ const lengths = [...parents].map((parent) => [parent, parent._dur, parent._tDur, parent._end, parent._dirty]);
17
+ for (const [child] of skipped)
18
+ child._ts = 0;
19
+ try {
20
+ renderOntoInAuthoredOrder(timeline, children, t, structure);
21
+ }
22
+ finally {
23
+ for (const [child, timeScale] of skipped)
24
+ child._ts = timeScale;
25
+ for (const [parent, dur, tDur, end, dirty] of lengths) {
26
+ Object.assign(parent, { _dur: dur, _tDur: tDur, _end: end, _dirty: dirty });
27
+ }
28
+ }
29
+ for (const [child, ratio, zTime, active] of marked) {
30
+ child.ratio = ratio;
31
+ child._zTime = zTime;
32
+ child._act = active;
33
+ }
34
+ }
35
+ function renderOntoInAuthoredOrder(timeline, children, t, structure) {
36
+ const below = t >= REDRAW_STEP;
37
+ timeline.totalTime(below ? t - REDRAW_STEP : t + REDRAW_STEP, true);
38
+ primeTweensStartingAt(children, t, below ? REDRAW_STEP : 0);
39
+ timeline.totalTime(t, true);
40
+ const own = structure ?? ownStructureOf(children);
41
+ if (!below) {
42
+ reapplyStepsInAuthoredOrder(timeline, own, t);
43
+ }
44
+ else if (own) {
45
+ settleOverlapsEndedBetween(own.owner, t - REDRAW_STEP, t, own.version);
46
+ }
47
+ }
48
+ function ownStructureOf(children) {
49
+ const owner = children[0]?.parent;
50
+ return owner ? { owner, version: "" } : undefined;
51
+ }
52
+ function reapplyStepsInAuthoredOrder(timeline, structure, t) {
53
+ if (!structure)
54
+ return;
55
+ for (const step of stepsAt(timeline, structure, t)) {
56
+ const { ratio, _zTime, _act } = step;
57
+ step.render(0, true, true);
58
+ Object.assign(step, { ratio, _zTime, _act });
59
+ }
60
+ }
61
+ function gsapNeverRendered(timeline) {
62
+ const own = timeline;
63
+ const [child] = "_first" in own
64
+ ? own._first
65
+ ? [own._first]
66
+ : []
67
+ : (timeline.getChildren?.(false, true, true) ?? []);
68
+ const rendered = child?.parent;
69
+ return rendered !== undefined && !rendered._initted;
70
+ }
71
+ const lastRenderSeek = new WeakMap();
72
+ const sharedPropertySpans = new WeakMap();
73
+ const NOT_PROPERTIES = new Set([
74
+ "duration",
75
+ "ease",
76
+ "delay",
77
+ "repeat",
78
+ "repeatDelay",
79
+ "yoyo",
80
+ "yoyoEase",
81
+ "repeatRefresh",
82
+ "stagger",
83
+ "overwrite",
84
+ "immediateRender",
85
+ "lazy",
86
+ "id",
87
+ "paused",
88
+ "reversed",
89
+ "callbackScope",
90
+ "runBackwards",
91
+ "data",
92
+ "inherit",
93
+ "defaults",
94
+ "parent",
95
+ ]);
96
+ const EVERY_PROPERTY = new Set(["keyframes", "startAt", "transform"]);
97
+ const SAME_PROPERTY = {
98
+ scaleX: "scale",
99
+ scaleY: "scale",
100
+ autoAlpha: "opacity",
101
+ rotate: "rotation",
102
+ };
103
+ function propertiesWritten({ startAt, ...vars }) {
104
+ const to = ownPropertiesWritten(vars);
105
+ if (startAt === undefined)
106
+ return to;
107
+ const from = startAt && typeof startAt === "object"
108
+ ? ownPropertiesWritten(startAt)
109
+ : null;
110
+ return to && from && new Set([...to, ...from]);
111
+ }
112
+ function ownPropertiesWritten(vars) {
113
+ const properties = new Set();
114
+ for (const key of Object.keys(vars)) {
115
+ if (EVERY_PROPERTY.has(key))
116
+ return null;
117
+ if (!key.startsWith("on") && !NOT_PROPERTIES.has(key))
118
+ properties.add(SAME_PROPERTY[key] ?? key);
119
+ }
120
+ return properties;
121
+ }
122
+ function spanOnParent([start, length], parent) {
123
+ const speed = Number(parent._ts);
124
+ if (!speed)
125
+ return null;
126
+ const [from, span] = parent._repeat || speed < 0
127
+ ? [0, Number(parent.totalDuration?.() ?? Infinity)]
128
+ : [start, length];
129
+ return [Number(parent._start) + from / Math.abs(speed), span / Math.abs(speed)];
130
+ }
131
+ export function gsapTimelineOf(timeline) {
132
+ return timeline.__hfReal ?? timeline;
133
+ }
134
+ function writeOf(tween, timeline) {
135
+ const owner = gsapTimelineOf(timeline);
136
+ let span = [Number(tween._start), Number(tween.totalDuration?.() ?? 0)];
137
+ for (let parent = tween.parent; span && parent && parent !== owner; parent = parent.parent) {
138
+ span = spanOnParent(span, parent);
139
+ }
140
+ return (span && {
141
+ start: span[0],
142
+ end: span[0] + span[1],
143
+ properties: propertiesWritten(tween.vars ?? {}),
144
+ order: authoredOrderOf(tween, owner),
145
+ });
146
+ }
147
+ function spansWhereTweensShareAProperty(timeline) {
148
+ const writes = new Map();
149
+ for (const child of timeline.getChildren?.(true, true, false) ?? []) {
150
+ const tween = child;
151
+ const write = writeOf(tween, timeline);
152
+ if (!write)
153
+ continue;
154
+ for (const target of tween.targets?.() ?? [])
155
+ writes.set(target, [...(writes.get(target) ?? []), write]);
156
+ }
157
+ return [...writes.values()].flatMap(overlapsOnOneTarget);
158
+ }
159
+ function sharesAProperty(a, b) {
160
+ return !a.properties || !b.properties || [...a.properties].some((p) => b.properties.has(p));
161
+ }
162
+ function writtenBefore(a, b) {
163
+ return a.order !== undefined && b.order !== undefined && a.order < b.order;
164
+ }
165
+ function overlapsOnOneTarget(writes) {
166
+ const spans = [];
167
+ writes.sort((x, y) => x.start - y.start);
168
+ writes.forEach((first, i) => {
169
+ for (const second of writes.slice(i + 1)) {
170
+ if (second.start >= first.end)
171
+ break;
172
+ if (sharesAProperty(first, second))
173
+ spans.push({
174
+ laterStart: second.start,
175
+ sharedEnd: Math.min(first.end, second.end),
176
+ earlierEnd: first.end,
177
+ laterIsSet: second.end === second.start && !writtenBefore(second, first),
178
+ });
179
+ }
180
+ });
181
+ return spans;
182
+ }
183
+ function overlapSpansOf(timeline, version) {
184
+ let cached = sharedPropertySpans.get(timeline);
185
+ if (cached?.version !== version) {
186
+ cached = { version, spans: spansWhereTweensShareAProperty(timeline) };
187
+ sharedPropertySpans.set(timeline, cached);
188
+ }
189
+ return cached.spans;
190
+ }
191
+ const OVERLAP_RESTART = 1e-4;
192
+ function settleOverlapsEndedBetween(timeline, from, to, version) {
193
+ if (!(to > from))
194
+ return;
195
+ let restart = Infinity;
196
+ for (const { laterStart, earlierEnd, laterIsSet } of overlapSpansOf(timeline, version)) {
197
+ if (laterIsSet && earlierEnd > from && earlierEnd <= to)
198
+ restart = Math.min(restart, laterStart);
199
+ }
200
+ if (restart === Infinity || restart >= from)
201
+ return;
202
+ timeline.totalTime?.(Math.max(0, restart - OVERLAP_RESTART), true);
203
+ timeline.totalTime?.(to, true);
204
+ }
205
+ function framesSkippedSinceLastSeek(timeline, t, fps, version = "") {
206
+ const last = lastRenderSeek.get(timeline);
207
+ lastRenderSeek.set(timeline, t);
208
+ const skipped = last === undefined ? Math.floor(t * fps + 1e-6) : Math.ceil((t - last) * fps - 1e-6) - 1;
209
+ if (skipped < 1)
210
+ return [];
211
+ const replay = new Set();
212
+ for (const { laterStart: from, sharedEnd: to } of overlapSpansOf(timeline, version)) {
213
+ const nearest = Math.max(1, Math.ceil((t - to) * fps - 1e-6) - 1);
214
+ const farthest = Math.min(skipped, Math.floor((t - from) * fps + 1e-6) + 1);
215
+ for (let back = nearest; back <= farthest; back++)
216
+ replay.add(back);
217
+ }
218
+ return [...replay].sort((x, y) => y - x).map((back) => t - back / fps);
219
+ }
220
+ function landOn(timeline, t, suppressEvents, version) {
221
+ const from = Number(timeline.totalTime?.());
222
+ timeline.totalTime?.(t, suppressEvents);
223
+ settleOverlapsEndedBetween(timeline, from, t, version);
224
+ return from;
225
+ }
226
+ export function seekGsapTimeline(timeline, t, suppressEvents, structure, renderFps) {
227
+ if (typeof timeline.totalTime !== "function") {
228
+ if (typeof timeline.seek === "function")
229
+ timeline.seek(t, suppressEvents);
230
+ return false;
231
+ }
232
+ const version = structure?.version ?? "";
233
+ if (renderFps) {
234
+ for (const time of framesSkippedSinceLastSeek(timeline, t, renderFps, version)) {
235
+ landOn(timeline, time, suppressEvents, version);
236
+ }
237
+ }
238
+ const from = landOn(timeline, t, suppressEvents, version);
239
+ if (t < from && structure)
240
+ reapplyStepsInAuthoredOrder(timeline, structure, t);
241
+ if (from !== t || !gsapNeverRendered(timeline))
242
+ return false;
243
+ redrawGsapTimelineAt(timeline, t, structure);
244
+ return true;
245
+ }
246
+ export function redrawGsapTimelineAt(timeline, t, structure) {
247
+ if (typeof timeline.totalTime !== "function")
248
+ return;
249
+ rerenderGsapTimelineAt({
250
+ totalTime: timeline.totalTime.bind(timeline),
251
+ totalDuration: timeline.totalDuration?.bind(timeline),
252
+ getChildren: timeline.getChildren?.bind(timeline),
253
+ }, t, structure);
254
+ }
255
+ const PLAYHEAD_FLOAT_NOISE = 1e-6;
256
+ function childrenStartingAfter(children, time, found = []) {
257
+ for (const child of children) {
258
+ if (child.startTime() > time + PLAYHEAD_FLOAT_NOISE)
259
+ found.push(child);
260
+ else if (child.getChildren && child.endTime() >= time)
261
+ childrenStartingAfter(child.getChildren(false, true, true), child.time(), found);
262
+ }
263
+ return found;
264
+ }
265
+ function childrenWithLandingMarksIn(timeline) {
266
+ return (timeline.getChildren?.(true, true, true) ?? []).filter((child) => {
267
+ const animation = child;
268
+ return typeof animation.getChildren === "function" || animation.totalDuration?.() === 0;
269
+ });
270
+ }
271
+ const landingMarksCache = new WeakMap();
272
+ const LANDING_MARK_REACH = 0.05;
273
+ function startOnOwner(child, owner) {
274
+ const timeline = gsapTimelineOf(owner);
275
+ let at = Number(child._start);
276
+ for (let parent = child.parent; parent && parent !== timeline; parent = parent.parent) {
277
+ if (parent._repeat || !parent._ts)
278
+ return null;
279
+ at = Number(parent._start) + at / parent._ts;
280
+ }
281
+ return Number.isFinite(at) ? at : null;
282
+ }
283
+ function placeLandingMarks(timeline, structure) {
284
+ const placed = { version: structure.version, always: [], points: [] };
285
+ for (const mark of childrenWithLandingMarksIn(timeline)) {
286
+ const child = mark;
287
+ const at = typeof child.getChildren === "function" ? null : startOnOwner(child, structure.owner);
288
+ if (at === null)
289
+ placed.always.push(mark);
290
+ else
291
+ placed.points.push({ at, mark });
292
+ }
293
+ placed.points.sort((a, b) => a.at - b.at);
294
+ return placed;
295
+ }
296
+ function firstPointFrom(points, time) {
297
+ let lo = 0;
298
+ let hi = points.length;
299
+ while (lo < hi) {
300
+ const mid = (lo + hi) >> 1;
301
+ if (points[mid].at < time)
302
+ lo = mid + 1;
303
+ else
304
+ hi = mid;
305
+ }
306
+ return lo;
307
+ }
308
+ function placedLandingMarks(timeline, structure) {
309
+ let placed = landingMarksCache.get(structure.owner);
310
+ if (placed?.version !== structure.version) {
311
+ placed = placeLandingMarks(timeline, structure);
312
+ landingMarksCache.set(structure.owner, placed);
313
+ }
314
+ return placed;
315
+ }
316
+ function stepsAt(timeline, structure, t) {
317
+ const { points } = structure.version
318
+ ? placedLandingMarks(timeline, structure)
319
+ : placeLandingMarks(timeline, structure);
320
+ const steps = [];
321
+ for (let i = firstPointFrom(points, t - PLAYHEAD_FLOAT_NOISE); i < points.length; i++) {
322
+ if (points[i].at > t + PLAYHEAD_FLOAT_NOISE)
323
+ break;
324
+ steps.push(points[i].mark);
325
+ }
326
+ return steps;
327
+ }
328
+ export function holdLandingMarks(timeline, structure) {
329
+ const placed = structure ? placedLandingMarks(timeline, structure) : null;
330
+ const marks = placed
331
+ ? [...placed.always, ...placed.points.map((point) => point.mark)]
332
+ : childrenWithLandingMarksIn(timeline);
333
+ const held = marks.map((mark) => [mark, mark.ratio, mark._zTime, mark._act]);
334
+ return () => {
335
+ for (const [mark, ratio, zTime, active] of held) {
336
+ mark.ratio = ratio;
337
+ mark._zTime = zTime;
338
+ mark._act = active;
339
+ }
340
+ };
341
+ }
342
+ export function holdFrameMarks({ scenes, root, structureOf, }) {
343
+ const rootLandsLast = root ? [...scenes, root] : scenes;
344
+ const marks = rootLandsLast.map((timeline) => holdLandingMarks(timeline, structureOf(timeline)));
345
+ return (landBack) => {
346
+ landBack();
347
+ for (const timeline of rootLandsLast) {
348
+ if (timeline.totalTime && !structureOf(timeline)) {
349
+ rerenderGsapTimelineAt({
350
+ totalTime: timeline.totalTime.bind(timeline),
351
+ totalDuration: timeline.totalDuration?.bind(timeline),
352
+ getChildren: timeline.getChildren?.bind(timeline),
353
+ }, Number(timeline.totalTime()));
354
+ }
355
+ }
356
+ for (const put of marks)
357
+ put();
358
+ };
359
+ }
360
+ const DISCRETE_CALLBACKS = ["onStart", "onComplete", "onReverseComplete", "onRepeat"];
361
+ const noOpInPlaceOfCallback = () => { };
362
+ function eachAnimationIn(animation, visit) {
363
+ visit(animation);
364
+ for (const child of (animation.getChildren?.(false, true, true) ?? []))
365
+ eachAnimationIn(child, visit);
366
+ if (animation.timeline)
367
+ eachAnimationIn(animation.timeline, visit);
368
+ }
369
+ export function muteDiscreteCallbacks(timelines) {
370
+ const held = [];
371
+ for (const timeline of timelines) {
372
+ eachAnimationIn(gsapTimelineOf(timeline), ({ vars }) => {
373
+ if (!vars)
374
+ return;
375
+ for (const name of DISCRETE_CALLBACKS) {
376
+ if (typeof vars[name] !== "function" || vars[name] === noOpInPlaceOfCallback)
377
+ continue;
378
+ held.push([vars, name, vars[name]]);
379
+ vars[name] = noOpInPlaceOfCallback;
380
+ }
381
+ });
382
+ }
383
+ return () => {
384
+ for (const [vars, name, callback] of held)
385
+ vars[name] = callback;
386
+ };
387
+ }
388
+ function landingMarksOf(timeline, structure, t) {
389
+ if (!structure)
390
+ return childrenWithLandingMarksIn(timeline);
391
+ const placed = placedLandingMarks(timeline, structure);
392
+ const { points } = placed;
393
+ const near = [...placed.always];
394
+ const last = t + LANDING_MARK_REACH;
395
+ for (let i = firstPointFrom(points, t - LANDING_MARK_REACH); i < points.length; i++) {
396
+ if (points[i].at > last)
397
+ break;
398
+ near.push(points[i].mark);
399
+ }
400
+ return near;
401
+ }
402
+ const BELOW_GSAP_TIME_RESOLUTION = 2e-8;
403
+ const REDRAW_STEP = 0.001;
404
+ const playsForward = (value) => {
405
+ const animation = value;
406
+ return (typeof animation?.render === "function" &&
407
+ typeof animation.startTime === "function" &&
408
+ typeof animation.paused === "function" &&
409
+ typeof animation.timeScale === "function" &&
410
+ animation.timeScale() > 0 &&
411
+ !animation.paused());
412
+ };
413
+ function primedAtItsStart(tween) {
414
+ if (tween.vars?.keyframes) {
415
+ tween.render(BELOW_GSAP_TIME_RESOLUTION, true);
416
+ tween.render(-BELOW_GSAP_TIME_RESOLUTION, true);
417
+ }
418
+ if (tween._startAt)
419
+ tween._startAt.render(BELOW_GSAP_TIME_RESOLUTION, true, true);
420
+ return Boolean(tween.vars?.keyframes || tween._startAt);
421
+ }
422
+ function primeTweensStartingAt(children, time, stepBelowInTheirTime) {
423
+ for (const child of children.filter(playsForward)) {
424
+ const local = (time - child.startTime()) * child.timeScale();
425
+ if (Math.abs(local) < 1e-9 && primedAtItsStart(child))
426
+ continue;
427
+ if (local > 0)
428
+ primeStartedTween(child, local, stepBelowInTheirTime * child.timeScale());
429
+ }
430
+ }
431
+ function primeStartedTween(child, local, stepBelow) {
432
+ if (local < stepBelow && child._startAt)
433
+ child._startAt.render(BELOW_GSAP_TIME_RESOLUTION, true, true);
434
+ const nested = child.getChildren ? child : child.timeline;
435
+ if (nested?.getChildren && local <= child.totalDuration()) {
436
+ primeTweensStartingAt(nested.getChildren(false, true, true), local, stepBelow);
437
+ }
438
+ }
439
+ export function createGsapAdapter(deps) {
440
+ return {
441
+ name: "gsap",
442
+ discover: () => { },
443
+ seek: (ctx) => {
444
+ const timeline = deps.getTimeline();
445
+ if (!timeline)
446
+ return;
447
+ timeline.pause();
448
+ const safeTime = Math.max(0, Number(ctx.time) || 0);
449
+ const suppressEvents = ctx.suppressEvents === true;
450
+ if (typeof timeline.totalTime === "function") {
451
+ timeline.totalTime(safeTime, suppressEvents);
452
+ rerenderGsapTimelineAt({
453
+ totalTime: timeline.totalTime.bind(timeline),
454
+ totalDuration: timeline.totalDuration?.bind(timeline),
455
+ getChildren: timeline.getChildren?.bind(timeline),
456
+ }, safeTime);
457
+ }
458
+ else {
459
+ timeline.seek(safeTime, suppressEvents);
460
+ }
461
+ },
462
+ pause: () => {
463
+ const timeline = deps.getTimeline();
464
+ if (!timeline)
465
+ return;
466
+ timeline.pause();
467
+ },
468
+ };
469
+ }
@@ -0,0 +1,5 @@
1
+ import type { GsapPlaced } from "./gsap.js";
2
+ /** Numbers every child a timeline adds with `to`, `from`, `fromTo` and `set` by when the film wrote it. */
3
+ export declare function stampAuthoredOrder(gsap: object | undefined): void;
4
+ /** When the film wrote the child of `owner` holding `tween`; undefined for a film built before the runtime loaded. */
5
+ export declare function authoredOrderOf(tween: GsapPlaced, owner: object): number | undefined;
@@ -0,0 +1,27 @@
1
+ const ADDERS = ["to", "from", "fromTo", "set"];
2
+ let written = 0;
3
+ /** Numbers every child a timeline adds with `to`, `from`, `fromTo` and `set` by when the film wrote it. */
4
+ export function stampAuthoredOrder(gsap) {
5
+ const core = gsap?.core;
6
+ const proto = core?.Timeline?.prototype;
7
+ if (!proto || proto._hfStamped)
8
+ return;
9
+ proto._hfStamped = true;
10
+ for (const name of ADDERS) {
11
+ const add = proto[name];
12
+ proto[name] = function (...args) {
13
+ const result = add.apply(this, args);
14
+ if (this._recent && this._recent._hfAuthored === undefined)
15
+ this._recent._hfAuthored = ++written;
16
+ return result;
17
+ };
18
+ }
19
+ }
20
+ /** When the film wrote the child of `owner` holding `tween`; undefined for a film built before the runtime loaded. */
21
+ export function authoredOrderOf(tween, owner) {
22
+ let order;
23
+ for (let node = tween; node && node !== owner; node = node.parent) {
24
+ order = node._hfAuthored ?? order;
25
+ }
26
+ return order;
27
+ }
@@ -1,4 +1,5 @@
1
1
  import { type EditingElementHandle } from "../editingElement.js";
2
+ import { MAX_EDIT_VALUE } from "./textMarkup.js";
2
3
  export type ElementEditEntry = [name: string, value: string | null];
3
4
  export type StyleEditEntry = [name: string, value: string | null, priority?: "important"];
4
5
  export type EditElementParams = {
@@ -6,6 +7,7 @@ export type EditElementParams = {
6
7
  styles: StyleEditEntry[];
7
8
  attributes: ElementEditEntry[];
8
9
  html?: string;
10
+ expect?: string;
9
11
  };
10
12
  export type EditElementResult = {
11
13
  applied: boolean;
@@ -14,9 +16,9 @@ export type EditElementResult = {
14
16
  html?: string;
15
17
  };
16
18
  export declare const MAX_EDIT_ENTRIES = 64;
17
- export declare const MAX_EDIT_VALUE = 200000;
18
- /** Markup a text field writes: text in inline text tags, no URL, no handler. */
19
+ export { MAX_EDIT_VALUE };
19
20
  export declare function isTextMarkup(html: string): boolean;
21
+ export declare const openTextEdits: WeakSet<Element>;
20
22
  export declare function parseEditElement(params: unknown): EditElementParams | null;
21
23
  /** Draws nothing it could not put back: `src` off media, a too-long value, or non-text markup. */
22
24
  export declare function editElement(params: EditElementParams): EditElementResult;
@@ -3,38 +3,21 @@
3
3
  import { EDITING_ELEMENT_HANDLE } from "../editingElement.js";
4
4
  import { elementForHandle } from "../editingHandles.js";
5
5
  import { isStylableElement } from "../domRealm.js";
6
+ import { DATA_ATTRIBUTE, holdsOnlyTextMarkup, MAX_EDIT_VALUE } from "./textMarkup.js";
6
7
  export const MAX_EDIT_ENTRIES = 64;
7
- export const MAX_EDIT_VALUE = 200_000;
8
+ export { MAX_EDIT_VALUE };
8
9
  const STYLE_NAME = /^(?:-?[a-z][a-z0-9-]*|--[\w\u0080-\uffff-]+)$/;
9
- const DATA_ATTRIBUTE = /^data-[a-z0-9_-]+$/;
10
10
  const PANEL_ATTRIBUTES = new Set(["loop", "muted", "alt", "title", "src"]);
11
11
  const MEDIA_TAGS = new Set(["img", "video", "audio"]);
12
12
  const isAttributeName = (name) => DATA_ATTRIBUTE.test(name) || PANEL_ATTRIBUTES.has(name);
13
- const TEXT_TAGS = new Set([
14
- "span",
15
- "strong",
16
- "b",
17
- "em",
18
- "i",
19
- "u",
20
- "s",
21
- "br",
22
- "sub",
23
- "sup",
24
- "small",
25
- ]);
26
- const TEXT_ATTRIBUTES = new Set(["class", "id", "style", "title", "lang", "dir"]);
27
- /** Markup a text field writes: text in inline text tags, no URL, no handler. */
28
13
  export function isTextMarkup(html) {
29
14
  if (html.length > MAX_EDIT_VALUE)
30
15
  return false;
31
16
  const holder = document.createElement("template");
32
17
  holder.innerHTML = html;
33
- return Array.from(holder.content.querySelectorAll("*")).every((el) => TEXT_TAGS.has(el.localName) &&
34
- el
35
- .getAttributeNames()
36
- .every((name) => TEXT_ATTRIBUTES.has(name) || DATA_ATTRIBUTE.test(name)));
18
+ return holdsOnlyTextMarkup(holder.content);
37
19
  }
20
+ export const openTextEdits = new WeakSet();
38
21
  const isValue = (value) => value === null || (typeof value === "string" && value.length <= MAX_EDIT_VALUE);
39
22
  function entries(value, valid) {
40
23
  if (!Array.isArray(value) || value.length > MAX_EDIT_ENTRIES)
@@ -48,28 +31,44 @@ const styleEntry = ([name, value, priority, ...rest]) => typeof name === "string
48
31
  (priority === undefined || priority === "important") &&
49
32
  rest.length === 0;
50
33
  const attributeEntry = ([name, value, ...rest]) => typeof name === "string" && isAttributeName(name) && isValue(value) && rest.length === 0;
34
+ const EDIT_KEYS = new Set([
35
+ "attributes,handle,styles",
36
+ "attributes,handle,html,styles",
37
+ "attributes,expect,handle,html,styles",
38
+ ]);
39
+ const isOptionalMarkup = (value) => value === undefined || (typeof value === "string" && value.length <= MAX_EDIT_VALUE);
40
+ const markupFieldsOk = (html, expect) => isOptionalMarkup(html) &&
41
+ isOptionalMarkup(expect) &&
42
+ (expect === undefined || html !== undefined);
51
43
  export function parseEditElement(params) {
52
44
  if (Object.prototype.toString.call(params) !== "[object Object]")
53
45
  return null;
54
46
  const record = params;
55
47
  const keys = Object.keys(record).sort().join();
56
- if (keys !== "attributes,handle,styles" && keys !== "attributes,handle,html,styles")
48
+ if (!EDIT_KEYS.has(keys))
57
49
  return null;
58
- const { handle, html } = record;
50
+ const { handle, html, expect } = record;
59
51
  if (typeof handle !== "string" || !EDITING_ELEMENT_HANDLE.test(handle))
60
52
  return null;
61
- if (html !== undefined && (typeof html !== "string" || html.length > MAX_EDIT_VALUE))
53
+ if (!markupFieldsOk(html, expect))
62
54
  return null;
63
55
  const styles = entries(record.styles, styleEntry);
64
56
  const attributes = entries(record.attributes, attributeEntry);
65
57
  if (!styles || !attributes)
66
58
  return null;
67
- return html === undefined ? { handle, styles, attributes } : { handle, styles, attributes, html };
59
+ const parsed = { handle, styles, attributes };
60
+ if (html !== undefined)
61
+ parsed.html = html;
62
+ if (expect !== undefined)
63
+ parsed.expect = expect;
64
+ return parsed;
68
65
  }
69
66
  const NOT_APPLIED = { applied: false, styles: [], attributes: [] };
70
- function refused(element, attributes, html) {
67
+ function refused(element, { attributes, html, expect }) {
71
68
  if (attributes.some(([name]) => name === "src") && !MEDIA_TAGS.has(element.localName))
72
69
  return true;
70
+ if (expect !== undefined && (openTextEdits.has(element) || element.innerHTML !== expect))
71
+ return true;
73
72
  return html !== undefined && !(isTextMarkup(element.innerHTML) && isTextMarkup(html));
74
73
  }
75
74
  function valuesBefore(element, { styles, attributes, html }) {
@@ -103,7 +102,7 @@ function draw(element, { styles, attributes, html }) {
103
102
  /** Draws nothing it could not put back: `src` off media, a too-long value, or non-text markup. */
104
103
  export function editElement(params) {
105
104
  const element = elementForHandle(params.handle);
106
- if (!isStylableElement(element) || refused(element, params.attributes, params.html))
105
+ if (!isStylableElement(element) || refused(element, params))
107
106
  return NOT_APPLIED;
108
107
  const before = valuesBefore(element, params);
109
108
  if (![...before.styles, ...before.attributes].every(([, value]) => isValue(value)))