@mizchi/vlmkit-animation-eval 0.23.2 → 0.24.0

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.
@@ -26,16 +26,27 @@
26
26
  * Pages that draw on demand can also listen for `vlmkit:seek` — dispatched after every
27
27
  * advance with `detail.timeMs` and `detail.waitUntil(promise)` — the same contract as
28
28
  * HyperFrames' `hf-seek`, for a canvas or WebGL scene that renders from an explicit time.
29
+ *
30
+ * `pending()` says what is still to come: timers (and how many repeat), the latest one-shot's
31
+ * due time, queued frames, and the `vlmkit:seek` listeners on `window`. `takeLeftAt()` is the
32
+ * page time at which the document began to navigate away, for a caller holding the clock across
33
+ * a navigation (`openHeldTimeline`). `rendered()` waits, at most 250ms of real time, for the
34
+ * browser's next rendering, where the finish events of animations a seek ended are dispatched.
29
35
  */
30
36
  const VIRTUAL_CLOCK_SCRIPT = `(() => {
31
37
  if (window.__vlmkitClock) return;
32
- const FRAME_MS = 1000 / 60;
33
38
  const nativePerfNow = performance.now.bind(performance);
39
+ const nativeFrame = window.requestAnimationFrame.bind(window);
40
+ const nativeSetTimeout = window.setTimeout.bind(window);
34
41
  const NativeDate = Date;
35
42
  // Virtual 0 is document start; Date keeps the real wall-clock date at that instant.
36
43
  const epochAtZero = NativeDate.now() - nativePerfNow();
37
44
  let now = 0;
38
- let lastFrame = 0;
45
+ // Frames are counted, not accumulated: frame n is at (n * 1000) / 60. Adding 1000/60 per frame
46
+ // drifts above the boundary (frame 6 summed to 100.00000000000001), so advanceTo(100) ran 5
47
+ // frames, not 6 — and 500 and 2000, on the --timeline default grid, each missed one.
48
+ let frames = 0;
49
+ const frameTime = (n) => (n * 1000) / 60;
39
50
  let seq = 0;
40
51
  let rafQueue = [];
41
52
  const timers = new Map();
@@ -61,10 +72,18 @@ const VIRTUAL_CLOCK_SCRIPT = `(() => {
61
72
  rafQueue = rafQueue.filter((entry) => entry.id !== id);
62
73
  };
63
74
 
64
- const schedule = (callback, delay, args, interval) => {
75
+ // Timer nesting, as the HTML timer initialization steps have it: a timer scheduled while a
76
+ // timer callback runs is one level deeper than that callback's, and one scheduled from deeper
77
+ // than level 5 waits at least 4ms. Chromium 141 on the real clock ran six nested
78
+ // setTimeout(f, 0) at once and each later one ~4ms after the last, and setInterval(f, 0) the
79
+ // same. Unclamped, a self-rescheduling setTimeout(f, 0) was a timer due now at every step:
80
+ // advanceTo spun to its step guard every frame and rAF never ran.
81
+ let level = 0;
82
+ const clamp = (ms, parentLevel) => (parentLevel > 5 && ms < 4 ? 4 : ms);
83
+ const schedule = (callback, delay, args, repeat) => {
65
84
  const id = ++seq;
66
85
  const ms = Math.max(0, Number(delay) || 0);
67
- timers.set(id, { due: now + ms, callback, args, interval: interval ? Math.max(1, ms) : 0 });
86
+ timers.set(id, { due: now + clamp(ms, level), delay: ms, level: level + 1, callback, args, repeat });
68
87
  return id;
69
88
  };
70
89
  window.setTimeout = (callback, delay, ...args) => schedule(callback, delay, args, false);
@@ -72,8 +91,55 @@ const VIRTUAL_CLOCK_SCRIPT = `(() => {
72
91
  window.clearTimeout = (id) => { timers.delete(id); };
73
92
  window.clearInterval = (id) => { timers.delete(id); };
74
93
 
94
+ // The page's vlmkit:seek listeners on window, each (listener, capture) once as the DOM keeps
95
+ // them: a second add of the same pair is a no-op there, and so is one with an aborted signal.
96
+ const SEEK = "vlmkit:seek";
97
+ const seekKeys = new WeakMap();
98
+ // One key object per (listener, capture) pair -> { once } while it is registered.
99
+ const seekListeners = new Map();
100
+ const seekKey = (listener, options) => {
101
+ const capture = typeof options === "boolean" ? options : Boolean(options && options.capture);
102
+ if (!seekKeys.has(listener)) seekKeys.set(listener, [{}, {}]);
103
+ return seekKeys.get(listener)[capture ? 1 : 0];
104
+ };
105
+ const isSeekListener = (self, type, listener) =>
106
+ type === SEEK && (self === window || self == null) &&
107
+ (typeof listener === "function" || (typeof listener === "object" && listener !== null));
108
+ const nativeAdd = window.addEventListener;
109
+ const nativeRemove = window.removeEventListener;
110
+ window.addEventListener = function (type, listener, options) {
111
+ const opts = options && typeof options === "object" ? options : {};
112
+ if (isSeekListener(this, type, listener) && !(opts.signal && opts.signal.aborted)) {
113
+ const key = seekKey(listener, options);
114
+ if (!seekListeners.has(key)) {
115
+ const entry = { once: Boolean(opts.once) };
116
+ seekListeners.set(key, entry);
117
+ if (opts.signal) {
118
+ opts.signal.addEventListener("abort", () => {
119
+ if (seekListeners.get(key) === entry) seekListeners.delete(key);
120
+ }, { once: true });
121
+ }
122
+ }
123
+ }
124
+ return nativeAdd.call(this, type, listener, options);
125
+ };
126
+ window.removeEventListener = function (type, listener, options) {
127
+ if (isSeekListener(this, type, listener)) seekListeners.delete(seekKey(listener, options));
128
+ return nativeRemove.call(this, type, listener, options);
129
+ };
130
+
131
+ // The page time a cross-document navigation began at. On Chromium 141 beforeunload is
132
+ // dispatched inside the call that navigates (location.href =, reload(), a link's click()) and
133
+ // not for a same-document one, so a caller holding the clock across the navigation can start
134
+ // the next document's time there.
135
+ let leftAt = null;
136
+ nativeAdd.call(window, "beforeunload", () => { leftAt = now; }, true);
137
+
75
138
  // A throwing callback must not stop the clock for everything else on the page.
76
139
  const errors = [];
140
+ // How many animation-frame callbacks and timer runs the clock has made: a value a timer updates
141
+ // once a second (a live price) is not motion, and read "script-driven motion" under reduce.
142
+ const runs = { frames: 0, timers: 0 };
77
143
  const invoke = (callback, args) => {
78
144
  try {
79
145
  if (typeof callback === "function") callback(...args);
@@ -97,29 +163,41 @@ const VIRTUAL_CLOCK_SCRIPT = `(() => {
97
163
  let guard = 0;
98
164
  while (guard++ < 100000) {
99
165
  const timer = nextTimer();
100
- const frameAt = lastFrame + FRAME_MS;
166
+ const frameAt = frameTime(frames + 1);
101
167
  const timerAt = timer ? timer[1].due : Infinity;
102
168
  const at = Math.min(frameAt, timerAt);
103
169
  if (at > target) break;
104
170
  now = Math.max(now, at);
105
171
  if (timer && timerAt <= frameAt) {
106
172
  const [id, entry] = timer;
107
- if (entry.interval) entry.due += entry.interval;
108
- else timers.delete(id);
173
+ // An interval's next run is a task of its own, one level deeper than this one.
174
+ const runLevel = entry.level;
175
+ if (entry.repeat) {
176
+ entry.due += clamp(entry.delay, runLevel);
177
+ entry.level = runLevel + 1;
178
+ } else timers.delete(id);
179
+ level = runLevel;
180
+ runs.timers += 1;
109
181
  invoke(entry.callback, entry.args || []);
182
+ // Microtasks the callback queued are part of its task, so what they schedule nests too.
183
+ await drain();
184
+ level = 0;
110
185
  } else {
111
- lastFrame = frameAt;
186
+ frames += 1;
112
187
  const queue = rafQueue;
113
188
  rafQueue = [];
189
+ if (queue.length > 0) runs.frames += 1;
114
190
  for (const entry of queue) invoke(entry.callback, [now]);
191
+ await drain();
115
192
  }
116
- await drain();
117
193
  }
118
194
  now = Math.max(now, target);
119
195
  const waits = [];
120
- window.dispatchEvent(new CustomEvent("vlmkit:seek", {
196
+ window.dispatchEvent(new CustomEvent(SEEK, {
121
197
  detail: { timeMs: now, waitUntil: (promise) => { waits.push(promise); } },
122
198
  }));
199
+ // A once listener is gone after the dispatch; the DOM drops it without a removeEventListener.
200
+ for (const [key, entry] of seekListeners) if (entry.once) seekListeners.delete(key);
123
201
  await Promise.all(waits.map((p) => Promise.resolve(p).catch(() => undefined)));
124
202
  await drain();
125
203
  return now;
@@ -129,64 +207,485 @@ const VIRTUAL_CLOCK_SCRIPT = `(() => {
129
207
  now: () => now,
130
208
  advanceTo,
131
209
  errors,
132
- pending: () => ({ timers: timers.size, frames: rafQueue.length }),
210
+ runs: () => ({ ...runs }),
211
+ // What is still to come. intervals: how many of the timers repeat; latestTimerMs: the due time
212
+ // of the last one-shot timer, or null; seekListeners: the page's vlmkit:seek listeners on
213
+ // window, so a caller can tell a page that draws on seek from a still one.
214
+ pending: () => {
215
+ let intervals = 0;
216
+ let latestTimerMs = null;
217
+ for (const timer of timers.values()) {
218
+ if (timer.repeat) intervals += 1;
219
+ else if (latestTimerMs === null || timer.due > latestTimerMs) latestTimerMs = timer.due;
220
+ }
221
+ return { timers: timers.size, frames: rafQueue.length, intervals, seekListeners: seekListeners.size, latestTimerMs };
222
+ },
223
+ // The page time at which this document began to navigate away, or null; reading it clears it.
224
+ takeLeftAt: () => {
225
+ const at = leftAt;
226
+ leftAt = null;
227
+ return at;
228
+ },
229
+ // Once the browser has next rendered, on the real clock: true, or false after maxMs. A Web
230
+ // Animation's finish event is dispatched there, before the frame's rAF callbacks (Chromium
231
+ // 141), and nothing else runs it: a page that does no rendering of its own got its onfinish
232
+ // several instants after the seek that ended the animation. Bounded, as every wait on
233
+ // rendering is: a page can starve rAF.
234
+ rendered: (maxMs = 250) => new Promise((resolve) => {
235
+ nativeFrame(() => resolve(true));
236
+ nativeSetTimeout(() => resolve(false), maxMs);
237
+ }),
133
238
  };
134
239
  })()`;
135
240
  /**
136
241
  * Every animation held from the instant it begins, with that instant recorded, so the whole
137
- * page can be put at one moment of its timeline: `window.__vlmkitSeekTimeline(t)` seeks every
138
- * held animation to `t - startAt`, and `__vlmkitTimelineAnimations()` lists what is held for
139
- * picking instants. Used by `check integrity --timeline` together with `VIRTUAL_CLOCK_SCRIPT`,
140
- * which holds the script half of the same moment.
242
+ * page can be put at one moment of its timeline: `window.__vlmkitSeekTimeline(t)` puts every
243
+ * held animation at `anchor + (t - anchorAt) * playbackRate` (clamped to its effect), and
244
+ * `__vlmkitTimelineAnimations()` lists what is held for picking instants. Used by
245
+ * `check integrity --timeline`, `check flash` and the frames capture (`openHeldTimeline`) together
246
+ * with `VIRTUAL_CLOCK_SCRIPT`, which holds the script half of the same moment.
247
+ *
248
+ * A seek that takes a held animation to its end (or, run backwards, to 0) ends it with the native
249
+ * `finish()`, so its `finished` promise resolves and its `finish` event fires, as on a real clock:
250
+ * a page that waits on one to start the next (`await intro.finished`, `onfinish`) is otherwise
251
+ * never shown its next stage. What it starts there begins at that end on the page clock. A later
252
+ * seek to before the end pauses it and puts it back.
253
+ *
254
+ * What a seek leaves alone: an animation at rate 0, one the page paused (until the page plays it —
255
+ * then it is held again from where it was), one the page ended with `finish()` or that was found
256
+ * finished after the clock had moved, and one that is cancelled (setting `currentTime` would
257
+ * revive it). One found finished while the clock is still at 0 ran out in the real time load took
258
+ * (a long task, a declarative shadow root whose start event nobody heard) and is held from 0.
259
+ * The page's own writes (`currentTime`, `startTime`, `playbackRate`, `reverse()`,
260
+ * `updatePlaybackRate()`) re-anchor a held animation at the page time they were made.
261
+ * Animations inside open shadow roots are held too (`document.getAnimations()` leaves them out,
262
+ * and their start events are not composed), and SMIL — which runs on each outermost `<svg>`'s own
263
+ * timeline — is paused and put at the same page time with `setCurrentTime`.
141
264
  *
142
- * `startAt` is read off the virtual clock when one is installed (the page time a script that
143
- * started the animation saw), else `performance.now()`. CSS animations and transitions run on
144
- * `document.timeline`, which is real time: one that starts at load is caught at `transitionrun`
145
- * / `animationstart` with the page clock still at 0, and its own `currentTime` already counts
146
- * its delay, so `t - 0` is right. One a script starts later is caught when the browser next
147
- * renders, which can be after the virtual clock has moved on — its `startAt` is then late by up
148
- * to the advance that started it. That bound is the honest limit of seeking CSS by page time.
265
+ * The page time an animation begins at is read off the virtual clock when one is installed (the
266
+ * page time a script that started the animation saw), else `performance.now()`. CSS animations and
267
+ * transitions run on `document.timeline`, which is real time: one that starts at load is caught at
268
+ * `transitionrun` / `animationstart` with the page clock still at 0, and its own `currentTime`
269
+ * already counts its delay, so `t - 0` is right. One a script starts later is caught when the
270
+ * browser next renders, which can be after the virtual clock has moved on — its start is then late
271
+ * by up to the advance that started it. That bound is the honest limit of seeking CSS by page time.
149
272
  */
150
273
  const HOLD_TIMELINE_SCRIPT = `(() => {
151
274
  if (window.__vlmkitTimeline) return;
275
+ // { anim, anchor, anchorAt, startAt, pagePaused, cancelled, endedByHold, endedAt }: at page time
276
+ // t a held animation is at anchor + (t - anchorAt) * playbackRate of its local time, clamped to
277
+ // [0, its effect's end]. startAt, for the callers that attribute motion, is the page time its
278
+ // local time was 0 at when it runs forwards (anchorAt - anchor / rate), and the page time it
279
+ // began running backwards from its anchor when it does not. endedByHold: a seek ended it
280
+ // (finish()), at page time endedAt, so its finished state is the hold's, not the page's.
152
281
  const held = [];
153
282
  window.__vlmkitTimeline = held;
283
+ const entries = new WeakMap();
154
284
  const clockNow = () => (window.__vlmkitClock ? window.__vlmkitClock.now() : performance.now());
155
- const hold = (anim) => {
156
- if (!anim || held.some((h) => h.anim === anim)) return;
157
- held.push({ anim, startAt: clockNow() });
158
- try { anim.pause(); } catch {}
285
+ const proto = Animation.prototype;
286
+ const nativePause = proto.pause;
287
+ const nativePlay = proto.play;
288
+ const nativeCancel = proto.cancel;
289
+ const nativeFinish = proto.finish;
290
+ const nativeReverse = proto.reverse;
291
+ const nativeUpdateRate = proto.updatePlaybackRate;
292
+ const nativeListen = EventTarget.prototype.addEventListener;
293
+ const accessor = (name) => Object.getOwnPropertyDescriptor(proto, name);
294
+ const currentTimeAccessor = accessor("currentTime");
295
+ const rateAccessor = accessor("playbackRate");
296
+ const startTimeAccessor = accessor("startTime");
297
+ const setCurrent = (anim, ms) => currentTimeAccessor.set.call(anim, ms);
298
+ // Only what runs on the document timeline has a time to seek to: a scroll-driven animation's
299
+ // times are percentages, and pausing one froze a reading-progress bar for good.
300
+ const timeBased = (anim) =>
301
+ typeof DocumentTimeline !== "undefined" && anim.timeline instanceof DocumentTimeline;
302
+ // The local time its effect ends at (Infinity when it repeats forever; 0 with no effect).
303
+ const endOf = (anim) => {
304
+ try {
305
+ const end = anim.effect ? anim.effect.getComputedTiming().endTime : 0;
306
+ return typeof end === "number" ? end : Infinity;
307
+ } catch { return Infinity; }
308
+ };
309
+ const local = (h, t) => h.anchor + (t - h.anchorAt) * h.anim.playbackRate;
310
+ // Run to its end at page time t: past its effect's end forwards, or back to 0 backwards. One that
311
+ // repeats forever only ends backwards (finish() refuses it forwards).
312
+ const reached = (h, t, end) => {
313
+ const rate = h.anim.playbackRate;
314
+ if (rate > 0) return Number.isFinite(end) && local(h, t) >= end;
315
+ return rate < 0 && local(h, t) <= 0;
316
+ };
317
+ // Where the page clock puts a held animation, ending nothing. A rate of 0 is the page's: it stays.
318
+ const place = (h, t, end = endOf(h.anim)) => {
319
+ if (h.anim.playbackRate === 0) return;
320
+ try { setCurrent(h.anim, Math.min(Math.max(local(h, t), 0), end)); } catch {}
321
+ };
322
+ // While a held animation's end is delivered to the page — its finished promise's reactions, its
323
+ // finish event — what the page starts begins at that end on the page clock, not at the later
324
+ // instant the seek had reached (a coarse sweep started a second stage up to a whole step late).
325
+ // { at, clock }: good while the clock still reads clock, and swept in the task after, since
326
+ // the finish event is dispatched when the browser next renders, after the seek has returned.
327
+ let origin = null;
328
+ const sweep = new MessageChannel();
329
+ sweep.port1.onmessage = () => { origin = null; };
330
+ const startNow = () => {
331
+ const now = clockNow();
332
+ return origin !== null && origin.clock === now ? origin.at : now;
333
+ };
334
+ const adopt = (h) => {
335
+ if (!h.endedByHold || h.endedAt === null) return;
336
+ origin = { at: h.endedAt, clock: clockNow() };
337
+ sweep.port2.postMessage(0);
338
+ };
339
+ // Our reaction on the finished promise the page will wait on, registered before the page can
340
+ // register its own (the animate wrapper runs first), so it runs first when the promise resolves.
341
+ // Each time the animation leaves its finished state the promise is a new one.
342
+ const watch = (h) => {
343
+ try {
344
+ const promise = h.anim.finished;
345
+ if (promise === h.watched) return;
346
+ h.watched = promise;
347
+ promise.then(() => adopt(h), () => {});
348
+ } catch {}
349
+ };
350
+ // Paused where it is, with any pending playback rate applied: reverse() and updatePlaybackRate()
351
+ // leave the new rate pending until the next frame (Chromium 141: playbackRate still read 1 after
352
+ // reverse()), and writing currentTime completes the pause, and applies it, at once.
353
+ const pauseHere = (anim) => {
354
+ try { nativePause.call(anim); } catch {}
355
+ const current = anim.currentTime;
356
+ if (typeof current !== "number") return 0;
357
+ try { setCurrent(anim, current); } catch {}
358
+ return current;
359
+ };
360
+ // Animations the page ended itself with finish(): the page's, at any page time.
361
+ const pageFinished = new WeakSet();
362
+ // Held again from where it is now, at the page time it is now: after the page let it run, or
363
+ // moved it. Every rate but 0 is taken over; one at rate 0 does not move, and is left running.
364
+ const takeOver = (h) => {
365
+ if (h.anim.playbackRate !== 0) h.anchor = pauseHere(h.anim);
366
+ else h.anchor = typeof h.anim.currentTime === "number" ? h.anim.currentTime : 0;
367
+ h.anchorAt = clockNow();
368
+ h.pagePaused = false;
369
+ h.cancelled = false;
370
+ h.endedByHold = false;
371
+ pageFinished.delete(h.anim);
372
+ watch(h);
373
+ };
374
+ // anchored: its currentTime is the page's choice (new Animation() played, synchronously);
375
+ // otherwise it was found by an event or a sweep, after real time ran, and it begins where found.
376
+ const hold = (anim, anchored = false) => {
377
+ if (!anim || entries.has(anim) || !timeBased(anim)) return;
378
+ const state = anim.playState;
379
+ const at = startNow();
380
+ const h = {
381
+ anim,
382
+ anchor: 0,
383
+ anchorAt: at,
384
+ get startAt() {
385
+ const rate = this.anim.playbackRate;
386
+ return rate > 0 ? this.anchorAt - this.anchor / rate : this.anchorAt;
387
+ },
388
+ // One the page has already paused (a scrubber, animation-play-state: paused) is the page's.
389
+ pagePaused: state === "paused",
390
+ cancelled: false,
391
+ endedByHold: false,
392
+ endedAt: null,
393
+ watched: null,
394
+ };
395
+ entries.set(anim, h);
396
+ held.push(h);
397
+ watch(h);
398
+ try { nativeListen.call(anim, "finish", () => adopt(h)); } catch {}
399
+ // Found finished while the clock is still at 0: it ran out in the real time load took, and is
400
+ // held from 0 like a running one. Found finished later, it is the page's.
401
+ const restart = state === "finished" && clockNow() === 0 && !pageFinished.has(anim);
402
+ if ((state !== "running" && !restart) || anim.playbackRate === 0) return;
403
+ const current = pauseHere(anim);
404
+ if (anchored) h.anchor = current;
405
+ else if (anim.playbackRate < 0) {
406
+ // Run backwards it starts from its end, where play() would rewind it to.
407
+ const end = endOf(anim);
408
+ h.anchor = Number.isFinite(end) ? end : current;
409
+ }
410
+ // Put at its page time now when that is not where it was found: one that ran out at load, and
411
+ // one started at a held animation's end that the clock has already passed.
412
+ if (restart || at !== clockNow()) place(h, clockNow());
413
+ };
414
+ // A held animation whose time the hold keeps: not paused or finished by the page, not cancelled
415
+ // or idle. Placing one the page finished would undo its finish().
416
+ const live = (h) => {
417
+ if (!h || h.pagePaused || h.cancelled) return false;
418
+ const state = h.anim.playState;
419
+ return state !== "idle" && (state !== "finished" || h.endedByHold);
420
+ };
421
+ // The page's own pause and play are seen: a held animation the page pauses is placed at the
422
+ // page's present first (its currentTime is only as fresh as the last seek), then left to the
423
+ // page; one it plays is taken over again from where that leaves it. An animation built with
424
+ // new Animation() is held when the page first plays it.
425
+ proto.pause = function () {
426
+ const h = entries.get(this);
427
+ if (h && !h.pagePaused && !h.cancelled && this.playState !== "idle") {
428
+ if (live(h)) place(h, clockNow());
429
+ h.pagePaused = true;
430
+ h.endedByHold = false;
431
+ }
432
+ return nativePause.call(this);
433
+ };
434
+ proto.play = function () {
435
+ const h = entries.get(this);
436
+ if (live(h)) place(h, clockNow());
437
+ const result = nativePlay.call(this);
438
+ if (h) takeOver(h);
439
+ else hold(this, true);
440
+ return result;
441
+ };
442
+ proto.finish = function () {
443
+ pageFinished.add(this);
444
+ const h = entries.get(this);
445
+ if (h) h.endedByHold = false;
446
+ return nativeFinish.call(this);
159
447
  };
448
+ // The page's own writes are seen too: one that moves a held animation holds it again from where
449
+ // the write leaves it, at the page time the page made it. Without this a strobe the page set to
450
+ // its end and reversed (currentTime = 2000; playbackRate = -1) sat where the hold had it. One the
451
+ // page had finished and now sets running again (currentTime = 0) is taken over at once, not left
452
+ // to run on the real clock until the next seek.
453
+ const moved = (anim, change) => {
454
+ const h = entries.get(anim);
455
+ const wasLive = live(h);
456
+ if (wasLive) place(h, clockNow());
457
+ const result = change();
458
+ if (wasLive || (h && !h.pagePaused && !h.cancelled && anim.playState === "running")) takeOver(h);
459
+ return result;
460
+ };
461
+ for (const [name, desc] of [["currentTime", currentTimeAccessor], ["playbackRate", rateAccessor], ["startTime", startTimeAccessor]]) {
462
+ if (!desc || !desc.set) continue;
463
+ Object.defineProperty(proto, name, {
464
+ ...desc,
465
+ set(value) { moved(this, () => desc.set.call(this, value)); },
466
+ });
467
+ }
468
+ proto.reverse = function () {
469
+ return moved(this, () => nativeReverse.call(this));
470
+ };
471
+ // On a held animation the new rate is set at once: it is paused, where updatePlaybackRate() and
472
+ // a playbackRate write do the same, except that updatePlaybackRate() leaves it pending a frame.
473
+ proto.updatePlaybackRate = function (rate) {
474
+ if (!live(entries.get(this))) return nativeUpdateRate.call(this, rate);
475
+ return moved(this, () => { rateAccessor.set.call(this, rate); });
476
+ };
477
+ // animationstart and transitionrun are not composed, so each open shadow root is listened to
478
+ // on its own: the ones a script attaches as it attaches them, declarative ones when found.
479
+ const listening = new WeakSet();
160
480
  const onStart = (event) => {
161
481
  const target = event.target;
162
482
  if (!target || !target.getAnimations) return;
163
483
  for (const anim of target.getAnimations()) hold(anim);
164
484
  };
165
- document.addEventListener("animationstart", onStart, true);
166
- document.addEventListener("transitionrun", onStart, true);
485
+ const listen = (root) => {
486
+ if (listening.has(root)) return;
487
+ listening.add(root);
488
+ root.addEventListener("animationstart", onStart, true);
489
+ root.addEventListener("transitionrun", onStart, true);
490
+ };
491
+ listen(document);
492
+ const nativeAttachShadow = Element.prototype.attachShadow;
493
+ Element.prototype.attachShadow = function (...args) {
494
+ const root = nativeAttachShadow.apply(this, args);
495
+ if (root && root.mode === "open") listen(root);
496
+ return root;
497
+ };
167
498
  const nativeAnimate = Element.prototype.animate;
168
499
  Element.prototype.animate = function (...args) {
169
500
  const anim = nativeAnimate.apply(this, args);
170
501
  hold(anim);
171
502
  return anim;
172
503
  };
173
- window.__vlmkitSeekTimeline = (t) => {
174
- // Late arrivals first: anything running that the events missed (an animation already in
175
- // its active phase when the listeners attached) is held at the instant it is found.
504
+ // document.getAnimations() leaves out shadow trees: every open root, at any depth.
505
+ const openRoots = () => {
506
+ const out = [];
507
+ const walk = (root) => {
508
+ for (const el of root.querySelectorAll("*")) {
509
+ if (el.shadowRoot) { out.push(el.shadowRoot); walk(el.shadowRoot); }
510
+ }
511
+ };
512
+ walk(document);
513
+ return out;
514
+ };
515
+ // SMIL runs on each outermost <svg>'s own timeline, which begins when that svg is inserted
516
+ // (Chromium 141: 0 right after insertion) — at load for one in the page. Each is paused and
517
+ // put at its page time when found, so its startAt is the page time it was found at.
518
+ const SMIL = "animate, animateTransform, animateMotion, set";
519
+ const svgs = [];
520
+ const svgSeen = new WeakSet();
521
+ const placeSvg = (s, t) => {
522
+ try {
523
+ s.svg.pauseAnimations();
524
+ s.svg.setCurrentTime(Math.max(0, t - s.startAt) / 1000);
525
+ } catch {}
526
+ };
527
+ // Late arrivals: anything the events missed is held at the instant it is found. A CSS animation
528
+ // still in its delay has fired no animationstart, so both readers sweep: the list read after
529
+ // advanceTo(0) holds everything that exists then. One a script starts later is held by the seek
530
+ // that first finds it.
531
+ const collectLate = () => {
532
+ const roots = openRoots();
176
533
  if (document.getAnimations) for (const anim of document.getAnimations()) hold(anim);
177
- for (const h of held) {
178
- try { h.anim.currentTime = Math.max(0, t - h.startAt); } catch {}
534
+ for (const root of roots) {
535
+ listen(root);
536
+ if (root.getAnimations) for (const anim of root.getAnimations()) hold(anim);
537
+ }
538
+ for (const root of [document, ...roots]) {
539
+ for (const svg of root.querySelectorAll("svg")) {
540
+ if (svg.ownerSVGElement || svgSeen.has(svg) || !svg.querySelector(SMIL)) continue;
541
+ svgSeen.add(svg);
542
+ const s = { svg, startAt: clockNow() };
543
+ svgs.push(s);
544
+ placeSvg(s, s.startAt);
545
+ }
179
546
  }
180
547
  };
181
- window.__vlmkitTimelineAnimations = () => held.map((h) => {
182
- let timing = {};
183
- try { timing = h.anim.effect && h.anim.effect.getComputedTiming ? h.anim.effect.getComputedTiming() : {}; } catch {}
184
- return {
185
- startMs: h.startAt + (timing.delay || 0),
186
- durationMs: typeof timing.duration === "number" ? timing.duration : 0,
187
- iterations: Number.isFinite(timing.iterations) ? timing.iterations : null,
188
- };
189
- });
548
+ // Once paused through the API a CSS animation outlives its animation-name; the name is compared
549
+ // escaped too, since computed style serialises slide:in as slide\\:in.
550
+ const nameGone = (anim) => {
551
+ if (typeof anim.animationName !== "string" || !anim.effect || !anim.effect.target) return false;
552
+ try {
553
+ const listed = getComputedStyle(anim.effect.target, anim.effect.pseudoElement || null)
554
+ .animationName.split(",").map((n) => n.trim());
555
+ const escaped = typeof CSS !== "undefined" && CSS.escape ? CSS.escape(anim.animationName) : anim.animationName;
556
+ return !listed.includes(anim.animationName) && !listed.includes(escaped);
557
+ } catch { return false; }
558
+ };
559
+ // Every state is read before any animation is moved: playState and computed style each bring
560
+ // style up to date, and read after a currentTime write they recomputed it once per animation:
561
+ // 120 seeks of 150 dealt cards took 855ms that way and ~170ms read first (114ms before these
562
+ // checks existed). Each effect's end is read with them; with that, and each card's finish() at
563
+ // its end, 120 seeks of another 150-card CSS deal measured ~130ms before and ~180ms after.
564
+ //
565
+ // Returns how many animations it ended: their finish events are dispatched when the browser next
566
+ // renders (the clock's rendered()), and what those start can itself end before t.
567
+ window.__vlmkitSeekTimeline = (t) => {
568
+ collectLate();
569
+ const zero = clockNow() === 0;
570
+ let ended = 0;
571
+ const states = held.map((h) => {
572
+ if (h.cancelled) return { state: "cancelled", end: 0 };
573
+ const state = h.anim.playState;
574
+ if (state !== "idle" && nameGone(h.anim)) return { state: "gone", end: 0 };
575
+ return { state, end: state === "idle" ? 0 : endOf(h.anim) };
576
+ });
577
+ held.forEach((h, i) => {
578
+ const { state, end } = states[i];
579
+ if (state === "cancelled") return;
580
+ // Never revive: setting currentTime on a cancelled (idle) animation brings it back. One the
581
+ // page cancelled, or a CSS one whose element no longer lists its name, is cancelled for good
582
+ // and stays in the list for the callers that attribute motion to it.
583
+ if (state === "idle" || state === "gone") {
584
+ if (state === "gone") { try { nativeCancel.call(h.anim); } catch {} }
585
+ h.cancelled = true;
586
+ return;
587
+ }
588
+ if (state === "running") {
589
+ // Running again by a route no wrapper sees (animation-play-state, a changed effect): take
590
+ // it over.
591
+ takeOver(h);
592
+ } else if (state === "finished") {
593
+ if (h.endedByHold) {
594
+ // Ended by an earlier seek: it stays ended while the page time is past its end, and a
595
+ // seek back before it (check flash attributes a window at its middle) pauses it and puts
596
+ // it back, instead of letting it run on the real clock.
597
+ if (reached(h, t, end)) return;
598
+ try { nativePause.call(h.anim); } catch {}
599
+ h.endedByHold = false;
600
+ watch(h);
601
+ place(h, t, end);
602
+ return;
603
+ }
604
+ // Ended by the page (finish()), or found finished after the clock moved: the page's.
605
+ // Finished while the clock is still at 0, it ran out during load: held from 0.
606
+ if (h.pagePaused || !zero || pageFinished.has(h.anim)) return;
607
+ h.anchor = h.anim.playbackRate < 0 && Number.isFinite(end) ? end : 0;
608
+ h.anchorAt = 0;
609
+ try { nativePause.call(h.anim); } catch {}
610
+ watch(h);
611
+ }
612
+ if (h.pagePaused || h.anim.playbackRate === 0) return;
613
+ if (!reached(h, t, end)) {
614
+ place(h, t, end);
615
+ return;
616
+ }
617
+ // At or past its end: ended natively, so finished resolves and onfinish / finish listeners
618
+ // run; what they start begins at this end (adopt). A CSS animation's animationend is the
619
+ // phase change, which finish() makes once, as a seek past the end did before.
620
+ const rate = h.anim.playbackRate;
621
+ h.endedAt = Math.max(h.anchorAt, h.anchorAt + ((rate > 0 ? end : 0) - h.anchor) / rate);
622
+ h.endedByHold = true;
623
+ watch(h);
624
+ try {
625
+ nativeFinish.call(h.anim);
626
+ ended += 1;
627
+ } catch {
628
+ h.endedByHold = false;
629
+ place(h, t, end);
630
+ }
631
+ });
632
+ for (const s of svgs) placeSvg(s, t);
633
+ return ended;
634
+ };
635
+ // A SMIL clock value that is a plain number (seconds unless a unit says otherwise), else null.
636
+ const clockValue = (text) => {
637
+ const m = /^\\s*(\\d+(?:\\.\\d+)?|\\.\\d+)(ms|s|min|h)?\\s*$/.exec(text || "");
638
+ return m ? Number(m[1]) * { ms: 1, s: 1000, min: 60000, h: 3600000 }[m[2] || "s"] : null;
639
+ };
640
+ // begin / dur / repeatCount / repeatDur read off the element; what is not a plain number
641
+ // (an event or syncbase begin, an indefinite or absent dur) is listed as repeating from 0.
642
+ const smilTiming = (el, startAt) => {
643
+ const unknown = { startMs: 0, durationMs: 0, iterations: null };
644
+ const begin = el.hasAttribute("begin") ? clockValue(el.getAttribute("begin")) : 0;
645
+ const dur = clockValue(el.getAttribute("dur"));
646
+ if (begin === null || dur === null) return unknown;
647
+ let iterations = 1;
648
+ const count = el.getAttribute("repeatCount");
649
+ if (count !== null) {
650
+ if (count.trim() === "indefinite") iterations = null;
651
+ else if (Number(count) > 0) iterations = Number(count);
652
+ else return unknown;
653
+ }
654
+ const repeatDur = el.getAttribute("repeatDur");
655
+ if (repeatDur !== null && repeatDur.trim() !== "indefinite") {
656
+ const span = clockValue(repeatDur);
657
+ if (span === null || !(dur > 0)) return unknown;
658
+ iterations = iterations === null ? span / dur : Math.min(iterations, span / dur);
659
+ } else if (repeatDur !== null && count === null) iterations = null;
660
+ return { startMs: startAt + begin, durationMs: dur, iterations };
661
+ };
662
+ window.__vlmkitTimelineAnimations = () => {
663
+ collectLate();
664
+ const out = held.map((h) => {
665
+ let timing = {};
666
+ try { timing = h.anim.effect && h.anim.effect.getComputedTiming ? h.anim.effect.getComputedTiming() : {}; } catch {}
667
+ const delay = typeof timing.delay === "number" ? timing.delay : 0;
668
+ const duration = typeof timing.duration === "number" ? timing.duration : 0;
669
+ const iterations = Number.isFinite(timing.iterations) ? timing.iterations : null;
670
+ const rate = h.anim.playbackRate;
671
+ if (!(rate < 0)) {
672
+ // Local times on the page's clock: at rate 2 a 1000ms animation takes 500ms of page time.
673
+ const speed = rate > 0 ? rate : 1;
674
+ return { startMs: h.startAt + delay / speed, durationMs: duration / speed, iterations };
675
+ }
676
+ // Run backwards from its anchor, it plays its active phase from there down to its delay:
677
+ // it enters it once its local time falls below the active phase's end.
678
+ const speed = -rate;
679
+ const activeEnd = delay + (typeof timing.activeDuration === "number" ? timing.activeDuration : 0);
680
+ return {
681
+ startMs: h.anchorAt + Math.max(0, h.anchor - activeEnd) / speed,
682
+ durationMs: duration / speed,
683
+ iterations: duration > 0 ? Math.max(0, Math.min(h.anchor, activeEnd) - delay) / duration : 0,
684
+ };
685
+ });
686
+ for (const s of svgs) for (const el of s.svg.querySelectorAll(SMIL)) out.push(smilTiming(el, s.startAt));
687
+ return out;
688
+ };
190
689
  })()`;
191
690
  //#endregion
192
691
  export { HOLD_TIMELINE_SCRIPT, VIRTUAL_CLOCK_SCRIPT };