@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,23 +26,46 @@
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
- declare const VIRTUAL_CLOCK_SCRIPT = "(() => {\n if (window.__vlmkitClock) return;\n const FRAME_MS = 1000 / 60;\n const nativePerfNow = performance.now.bind(performance);\n const NativeDate = Date;\n // Virtual 0 is document start; Date keeps the real wall-clock date at that instant.\n const epochAtZero = NativeDate.now() - nativePerfNow();\n let now = 0;\n let lastFrame = 0;\n let seq = 0;\n let rafQueue = [];\n const timers = new Map();\n\n Object.defineProperty(performance, \"now\", { value: () => now, configurable: true, writable: true });\n\n function VirtualDate(...args) {\n if (!new.target) return new NativeDate(epochAtZero + now).toString();\n return args.length === 0 ? new NativeDate(epochAtZero + now) : new NativeDate(...args);\n }\n VirtualDate.prototype = NativeDate.prototype;\n VirtualDate.now = () => Math.floor(epochAtZero + now);\n VirtualDate.parse = NativeDate.parse;\n VirtualDate.UTC = NativeDate.UTC;\n window.Date = VirtualDate;\n\n window.requestAnimationFrame = (callback) => {\n const id = ++seq;\n rafQueue.push({ id, callback });\n return id;\n };\n window.cancelAnimationFrame = (id) => {\n rafQueue = rafQueue.filter((entry) => entry.id !== id);\n };\n\n const schedule = (callback, delay, args, interval) => {\n const id = ++seq;\n const ms = Math.max(0, Number(delay) || 0);\n timers.set(id, { due: now + ms, callback, args, interval: interval ? Math.max(1, ms) : 0 });\n return id;\n };\n window.setTimeout = (callback, delay, ...args) => schedule(callback, delay, args, false);\n window.setInterval = (callback, delay, ...args) => schedule(callback, delay, args, true);\n window.clearTimeout = (id) => { timers.delete(id); };\n window.clearInterval = (id) => { timers.delete(id); };\n\n // A throwing callback must not stop the clock for everything else on the page.\n const errors = [];\n const invoke = (callback, args) => {\n try {\n if (typeof callback === \"function\") callback(...args);\n else if (typeof callback === \"string\") (0, eval)(callback);\n } catch (error) {\n errors.push(String((error && error.message) || error));\n }\n };\n\n const nextTimer = () => {\n let best = null;\n for (const [id, timer] of timers) if (best === null || timer.due < best[1].due) best = [id, timer];\n return best;\n };\n\n // Microtasks between steps, so a promise chain started by one callback settles before the\n // next callback runs \u2014 the order it would have had on a real clock.\n const drain = () => Promise.resolve().then(() => undefined);\n\n async function advanceTo(target) {\n let guard = 0;\n while (guard++ < 100000) {\n const timer = nextTimer();\n const frameAt = lastFrame + FRAME_MS;\n const timerAt = timer ? timer[1].due : Infinity;\n const at = Math.min(frameAt, timerAt);\n if (at > target) break;\n now = Math.max(now, at);\n if (timer && timerAt <= frameAt) {\n const [id, entry] = timer;\n if (entry.interval) entry.due += entry.interval;\n else timers.delete(id);\n invoke(entry.callback, entry.args || []);\n } else {\n lastFrame = frameAt;\n const queue = rafQueue;\n rafQueue = [];\n for (const entry of queue) invoke(entry.callback, [now]);\n }\n await drain();\n }\n now = Math.max(now, target);\n const waits = [];\n window.dispatchEvent(new CustomEvent(\"vlmkit:seek\", {\n detail: { timeMs: now, waitUntil: (promise) => { waits.push(promise); } },\n }));\n await Promise.all(waits.map((p) => Promise.resolve(p).catch(() => undefined)));\n await drain();\n return now;\n }\n\n window.__vlmkitClock = {\n now: () => now,\n advanceTo,\n errors,\n pending: () => ({ timers: timers.size, frames: rafQueue.length }),\n };\n})()";
36
+ export declare const VIRTUAL_CLOCK_SCRIPT = "(() => {\n if (window.__vlmkitClock) return;\n const nativePerfNow = performance.now.bind(performance);\n const nativeFrame = window.requestAnimationFrame.bind(window);\n const nativeSetTimeout = window.setTimeout.bind(window);\n const NativeDate = Date;\n // Virtual 0 is document start; Date keeps the real wall-clock date at that instant.\n const epochAtZero = NativeDate.now() - nativePerfNow();\n let now = 0;\n // Frames are counted, not accumulated: frame n is at (n * 1000) / 60. Adding 1000/60 per frame\n // drifts above the boundary (frame 6 summed to 100.00000000000001), so advanceTo(100) ran 5\n // frames, not 6 — and 500 and 2000, on the --timeline default grid, each missed one.\n let frames = 0;\n const frameTime = (n) => (n * 1000) / 60;\n let seq = 0;\n let rafQueue = [];\n const timers = new Map();\n\n Object.defineProperty(performance, \"now\", { value: () => now, configurable: true, writable: true });\n\n function VirtualDate(...args) {\n if (!new.target) return new NativeDate(epochAtZero + now).toString();\n return args.length === 0 ? new NativeDate(epochAtZero + now) : new NativeDate(...args);\n }\n VirtualDate.prototype = NativeDate.prototype;\n VirtualDate.now = () => Math.floor(epochAtZero + now);\n VirtualDate.parse = NativeDate.parse;\n VirtualDate.UTC = NativeDate.UTC;\n window.Date = VirtualDate;\n\n window.requestAnimationFrame = (callback) => {\n const id = ++seq;\n rafQueue.push({ id, callback });\n return id;\n };\n window.cancelAnimationFrame = (id) => {\n rafQueue = rafQueue.filter((entry) => entry.id !== id);\n };\n\n // Timer nesting, as the HTML timer initialization steps have it: a timer scheduled while a\n // timer callback runs is one level deeper than that callback's, and one scheduled from deeper\n // than level 5 waits at least 4ms. Chromium 141 on the real clock ran six nested\n // setTimeout(f, 0) at once and each later one ~4ms after the last, and setInterval(f, 0) the\n // same. Unclamped, a self-rescheduling setTimeout(f, 0) was a timer due now at every step:\n // advanceTo spun to its step guard every frame and rAF never ran.\n let level = 0;\n const clamp = (ms, parentLevel) => (parentLevel > 5 && ms < 4 ? 4 : ms);\n const schedule = (callback, delay, args, repeat) => {\n const id = ++seq;\n const ms = Math.max(0, Number(delay) || 0);\n timers.set(id, { due: now + clamp(ms, level), delay: ms, level: level + 1, callback, args, repeat });\n return id;\n };\n window.setTimeout = (callback, delay, ...args) => schedule(callback, delay, args, false);\n window.setInterval = (callback, delay, ...args) => schedule(callback, delay, args, true);\n window.clearTimeout = (id) => { timers.delete(id); };\n window.clearInterval = (id) => { timers.delete(id); };\n\n // The page's vlmkit:seek listeners on window, each (listener, capture) once as the DOM keeps\n // them: a second add of the same pair is a no-op there, and so is one with an aborted signal.\n const SEEK = \"vlmkit:seek\";\n const seekKeys = new WeakMap();\n // One key object per (listener, capture) pair -> { once } while it is registered.\n const seekListeners = new Map();\n const seekKey = (listener, options) => {\n const capture = typeof options === \"boolean\" ? options : Boolean(options && options.capture);\n if (!seekKeys.has(listener)) seekKeys.set(listener, [{}, {}]);\n return seekKeys.get(listener)[capture ? 1 : 0];\n };\n const isSeekListener = (self, type, listener) =>\n type === SEEK && (self === window || self == null) &&\n (typeof listener === \"function\" || (typeof listener === \"object\" && listener !== null));\n const nativeAdd = window.addEventListener;\n const nativeRemove = window.removeEventListener;\n window.addEventListener = function (type, listener, options) {\n const opts = options && typeof options === \"object\" ? options : {};\n if (isSeekListener(this, type, listener) && !(opts.signal && opts.signal.aborted)) {\n const key = seekKey(listener, options);\n if (!seekListeners.has(key)) {\n const entry = { once: Boolean(opts.once) };\n seekListeners.set(key, entry);\n if (opts.signal) {\n opts.signal.addEventListener(\"abort\", () => {\n if (seekListeners.get(key) === entry) seekListeners.delete(key);\n }, { once: true });\n }\n }\n }\n return nativeAdd.call(this, type, listener, options);\n };\n window.removeEventListener = function (type, listener, options) {\n if (isSeekListener(this, type, listener)) seekListeners.delete(seekKey(listener, options));\n return nativeRemove.call(this, type, listener, options);\n };\n\n // The page time a cross-document navigation began at. On Chromium 141 beforeunload is\n // dispatched inside the call that navigates (location.href =, reload(), a link's click()) and\n // not for a same-document one, so a caller holding the clock across the navigation can start\n // the next document's time there.\n let leftAt = null;\n nativeAdd.call(window, \"beforeunload\", () => { leftAt = now; }, true);\n\n // A throwing callback must not stop the clock for everything else on the page.\n const errors = [];\n // How many animation-frame callbacks and timer runs the clock has made: a value a timer updates\n // once a second (a live price) is not motion, and read \"script-driven motion\" under reduce.\n const runs = { frames: 0, timers: 0 };\n const invoke = (callback, args) => {\n try {\n if (typeof callback === \"function\") callback(...args);\n else if (typeof callback === \"string\") (0, eval)(callback);\n } catch (error) {\n errors.push(String((error && error.message) || error));\n }\n };\n\n const nextTimer = () => {\n let best = null;\n for (const [id, timer] of timers) if (best === null || timer.due < best[1].due) best = [id, timer];\n return best;\n };\n\n // Microtasks between steps, so a promise chain started by one callback settles before the\n // next callback runs — the order it would have had on a real clock.\n const drain = () => Promise.resolve().then(() => undefined);\n\n async function advanceTo(target) {\n let guard = 0;\n while (guard++ < 100000) {\n const timer = nextTimer();\n const frameAt = frameTime(frames + 1);\n const timerAt = timer ? timer[1].due : Infinity;\n const at = Math.min(frameAt, timerAt);\n if (at > target) break;\n now = Math.max(now, at);\n if (timer && timerAt <= frameAt) {\n const [id, entry] = timer;\n // An interval's next run is a task of its own, one level deeper than this one.\n const runLevel = entry.level;\n if (entry.repeat) {\n entry.due += clamp(entry.delay, runLevel);\n entry.level = runLevel + 1;\n } else timers.delete(id);\n level = runLevel;\n runs.timers += 1;\n invoke(entry.callback, entry.args || []);\n // Microtasks the callback queued are part of its task, so what they schedule nests too.\n await drain();\n level = 0;\n } else {\n frames += 1;\n const queue = rafQueue;\n rafQueue = [];\n if (queue.length > 0) runs.frames += 1;\n for (const entry of queue) invoke(entry.callback, [now]);\n await drain();\n }\n }\n now = Math.max(now, target);\n const waits = [];\n window.dispatchEvent(new CustomEvent(SEEK, {\n detail: { timeMs: now, waitUntil: (promise) => { waits.push(promise); } },\n }));\n // A once listener is gone after the dispatch; the DOM drops it without a removeEventListener.\n for (const [key, entry] of seekListeners) if (entry.once) seekListeners.delete(key);\n await Promise.all(waits.map((p) => Promise.resolve(p).catch(() => undefined)));\n await drain();\n return now;\n }\n\n window.__vlmkitClock = {\n now: () => now,\n advanceTo,\n errors,\n runs: () => ({ ...runs }),\n // What is still to come. intervals: how many of the timers repeat; latestTimerMs: the due time\n // of the last one-shot timer, or null; seekListeners: the page's vlmkit:seek listeners on\n // window, so a caller can tell a page that draws on seek from a still one.\n pending: () => {\n let intervals = 0;\n let latestTimerMs = null;\n for (const timer of timers.values()) {\n if (timer.repeat) intervals += 1;\n else if (latestTimerMs === null || timer.due > latestTimerMs) latestTimerMs = timer.due;\n }\n return { timers: timers.size, frames: rafQueue.length, intervals, seekListeners: seekListeners.size, latestTimerMs };\n },\n // The page time at which this document began to navigate away, or null; reading it clears it.\n takeLeftAt: () => {\n const at = leftAt;\n leftAt = null;\n return at;\n },\n // Once the browser has next rendered, on the real clock: true, or false after maxMs. A Web\n // Animation's finish event is dispatched there, before the frame's rAF callbacks (Chromium\n // 141), and nothing else runs it: a page that does no rendering of its own got its onfinish\n // several instants after the seek that ended the animation. Bounded, as every wait on\n // rendering is: a page can starve rAF.\n rendered: (maxMs = 250) => new Promise((resolve) => {\n nativeFrame(() => resolve(true));\n nativeSetTimeout(() => resolve(false), maxMs);\n }),\n };\n})()";
31
37
  /**
32
38
  * Every animation held from the instant it begins, with that instant recorded, so the whole
33
- * page can be put at one moment of its timeline: `window.__vlmkitSeekTimeline(t)` seeks every
34
- * held animation to `t - startAt`, and `__vlmkitTimelineAnimations()` lists what is held for
35
- * picking instants. Used by `check integrity --timeline` together with `VIRTUAL_CLOCK_SCRIPT`,
36
- * which holds the script half of the same moment.
37
- *
38
- * `startAt` is read off the virtual clock when one is installed (the page time a script that
39
- * started the animation saw), else `performance.now()`. CSS animations and transitions run on
40
- * `document.timeline`, which is real time: one that starts at load is caught at `transitionrun`
41
- * / `animationstart` with the page clock still at 0, and its own `currentTime` already counts
42
- * its delay, so `t - 0` is right. One a script starts later is caught when the browser next
43
- * renders, which can be after the virtual clock has moved on — its `startAt` is then late by up
44
- * to the advance that started it. That bound is the honest limit of seeking CSS by page time.
39
+ * page can be put at one moment of its timeline: `window.__vlmkitSeekTimeline(t)` puts every
40
+ * held animation at `anchor + (t - anchorAt) * playbackRate` (clamped to its effect), and
41
+ * `__vlmkitTimelineAnimations()` lists what is held for picking instants. Used by
42
+ * `check integrity --timeline`, `check flash` and the frames capture (`openHeldTimeline`) together
43
+ * with `VIRTUAL_CLOCK_SCRIPT`, which holds the script half of the same moment.
44
+ *
45
+ * A seek that takes a held animation to its end (or, run backwards, to 0) ends it with the native
46
+ * `finish()`, so its `finished` promise resolves and its `finish` event fires, as on a real clock:
47
+ * a page that waits on one to start the next (`await intro.finished`, `onfinish`) is otherwise
48
+ * never shown its next stage. What it starts there begins at that end on the page clock. A later
49
+ * seek to before the end pauses it and puts it back.
50
+ *
51
+ * What a seek leaves alone: an animation at rate 0, one the page paused (until the page plays it —
52
+ * then it is held again from where it was), one the page ended with `finish()` or that was found
53
+ * finished after the clock had moved, and one that is cancelled (setting `currentTime` would
54
+ * revive it). One found finished while the clock is still at 0 ran out in the real time load took
55
+ * (a long task, a declarative shadow root whose start event nobody heard) and is held from 0.
56
+ * The page's own writes (`currentTime`, `startTime`, `playbackRate`, `reverse()`,
57
+ * `updatePlaybackRate()`) re-anchor a held animation at the page time they were made.
58
+ * Animations inside open shadow roots are held too (`document.getAnimations()` leaves them out,
59
+ * and their start events are not composed), and SMIL — which runs on each outermost `<svg>`'s own
60
+ * timeline — is paused and put at the same page time with `setCurrentTime`.
61
+ *
62
+ * The page time an animation begins at is read off the virtual clock when one is installed (the
63
+ * page time a script that started the animation saw), else `performance.now()`. CSS animations and
64
+ * transitions run on `document.timeline`, which is real time: one that starts at load is caught at
65
+ * `transitionrun` / `animationstart` with the page clock still at 0, and its own `currentTime`
66
+ * already counts its delay, so `t - 0` is right. One a script starts later is caught when the
67
+ * browser next renders, which can be after the virtual clock has moved on — its start is then late
68
+ * by up to the advance that started it. That bound is the honest limit of seeking CSS by page time.
45
69
  */
46
- declare const HOLD_TIMELINE_SCRIPT = "(() => {\n if (window.__vlmkitTimeline) return;\n const held = [];\n window.__vlmkitTimeline = held;\n const clockNow = () => (window.__vlmkitClock ? window.__vlmkitClock.now() : performance.now());\n const hold = (anim) => {\n if (!anim || held.some((h) => h.anim === anim)) return;\n held.push({ anim, startAt: clockNow() });\n try { anim.pause(); } catch {}\n };\n const onStart = (event) => {\n const target = event.target;\n if (!target || !target.getAnimations) return;\n for (const anim of target.getAnimations()) hold(anim);\n };\n document.addEventListener(\"animationstart\", onStart, true);\n document.addEventListener(\"transitionrun\", onStart, true);\n const nativeAnimate = Element.prototype.animate;\n Element.prototype.animate = function (...args) {\n const anim = nativeAnimate.apply(this, args);\n hold(anim);\n return anim;\n };\n window.__vlmkitSeekTimeline = (t) => {\n // Late arrivals first: anything running that the events missed (an animation already in\n // its active phase when the listeners attached) is held at the instant it is found.\n if (document.getAnimations) for (const anim of document.getAnimations()) hold(anim);\n for (const h of held) {\n try { h.anim.currentTime = Math.max(0, t - h.startAt); } catch {}\n }\n };\n window.__vlmkitTimelineAnimations = () => held.map((h) => {\n let timing = {};\n try { timing = h.anim.effect && h.anim.effect.getComputedTiming ? h.anim.effect.getComputedTiming() : {}; } catch {}\n return {\n startMs: h.startAt + (timing.delay || 0),\n durationMs: typeof timing.duration === \"number\" ? timing.duration : 0,\n iterations: Number.isFinite(timing.iterations) ? timing.iterations : null,\n };\n });\n})()";
47
- //#endregion
48
- export { HOLD_TIMELINE_SCRIPT, VIRTUAL_CLOCK_SCRIPT };
70
+ export declare const HOLD_TIMELINE_SCRIPT = "(() => {\n if (window.__vlmkitTimeline) return;\n // { anim, anchor, anchorAt, startAt, pagePaused, cancelled, endedByHold, endedAt }: at page time\n // t a held animation is at anchor + (t - anchorAt) * playbackRate of its local time, clamped to\n // [0, its effect's end]. startAt, for the callers that attribute motion, is the page time its\n // local time was 0 at when it runs forwards (anchorAt - anchor / rate), and the page time it\n // began running backwards from its anchor when it does not. endedByHold: a seek ended it\n // (finish()), at page time endedAt, so its finished state is the hold's, not the page's.\n const held = [];\n window.__vlmkitTimeline = held;\n const entries = new WeakMap();\n const clockNow = () => (window.__vlmkitClock ? window.__vlmkitClock.now() : performance.now());\n const proto = Animation.prototype;\n const nativePause = proto.pause;\n const nativePlay = proto.play;\n const nativeCancel = proto.cancel;\n const nativeFinish = proto.finish;\n const nativeReverse = proto.reverse;\n const nativeUpdateRate = proto.updatePlaybackRate;\n const nativeListen = EventTarget.prototype.addEventListener;\n const accessor = (name) => Object.getOwnPropertyDescriptor(proto, name);\n const currentTimeAccessor = accessor(\"currentTime\");\n const rateAccessor = accessor(\"playbackRate\");\n const startTimeAccessor = accessor(\"startTime\");\n const setCurrent = (anim, ms) => currentTimeAccessor.set.call(anim, ms);\n // Only what runs on the document timeline has a time to seek to: a scroll-driven animation's\n // times are percentages, and pausing one froze a reading-progress bar for good.\n const timeBased = (anim) =>\n typeof DocumentTimeline !== \"undefined\" && anim.timeline instanceof DocumentTimeline;\n // The local time its effect ends at (Infinity when it repeats forever; 0 with no effect).\n const endOf = (anim) => {\n try {\n const end = anim.effect ? anim.effect.getComputedTiming().endTime : 0;\n return typeof end === \"number\" ? end : Infinity;\n } catch { return Infinity; }\n };\n const local = (h, t) => h.anchor + (t - h.anchorAt) * h.anim.playbackRate;\n // Run to its end at page time t: past its effect's end forwards, or back to 0 backwards. One that\n // repeats forever only ends backwards (finish() refuses it forwards).\n const reached = (h, t, end) => {\n const rate = h.anim.playbackRate;\n if (rate > 0) return Number.isFinite(end) && local(h, t) >= end;\n return rate < 0 && local(h, t) <= 0;\n };\n // Where the page clock puts a held animation, ending nothing. A rate of 0 is the page's: it stays.\n const place = (h, t, end = endOf(h.anim)) => {\n if (h.anim.playbackRate === 0) return;\n try { setCurrent(h.anim, Math.min(Math.max(local(h, t), 0), end)); } catch {}\n };\n // While a held animation's end is delivered to the page — its finished promise's reactions, its\n // finish event — what the page starts begins at that end on the page clock, not at the later\n // instant the seek had reached (a coarse sweep started a second stage up to a whole step late).\n // { at, clock }: good while the clock still reads clock, and swept in the task after, since\n // the finish event is dispatched when the browser next renders, after the seek has returned.\n let origin = null;\n const sweep = new MessageChannel();\n sweep.port1.onmessage = () => { origin = null; };\n const startNow = () => {\n const now = clockNow();\n return origin !== null && origin.clock === now ? origin.at : now;\n };\n const adopt = (h) => {\n if (!h.endedByHold || h.endedAt === null) return;\n origin = { at: h.endedAt, clock: clockNow() };\n sweep.port2.postMessage(0);\n };\n // Our reaction on the finished promise the page will wait on, registered before the page can\n // register its own (the animate wrapper runs first), so it runs first when the promise resolves.\n // Each time the animation leaves its finished state the promise is a new one.\n const watch = (h) => {\n try {\n const promise = h.anim.finished;\n if (promise === h.watched) return;\n h.watched = promise;\n promise.then(() => adopt(h), () => {});\n } catch {}\n };\n // Paused where it is, with any pending playback rate applied: reverse() and updatePlaybackRate()\n // leave the new rate pending until the next frame (Chromium 141: playbackRate still read 1 after\n // reverse()), and writing currentTime completes the pause, and applies it, at once.\n const pauseHere = (anim) => {\n try { nativePause.call(anim); } catch {}\n const current = anim.currentTime;\n if (typeof current !== \"number\") return 0;\n try { setCurrent(anim, current); } catch {}\n return current;\n };\n // Animations the page ended itself with finish(): the page's, at any page time.\n const pageFinished = new WeakSet();\n // Held again from where it is now, at the page time it is now: after the page let it run, or\n // moved it. Every rate but 0 is taken over; one at rate 0 does not move, and is left running.\n const takeOver = (h) => {\n if (h.anim.playbackRate !== 0) h.anchor = pauseHere(h.anim);\n else h.anchor = typeof h.anim.currentTime === \"number\" ? h.anim.currentTime : 0;\n h.anchorAt = clockNow();\n h.pagePaused = false;\n h.cancelled = false;\n h.endedByHold = false;\n pageFinished.delete(h.anim);\n watch(h);\n };\n // anchored: its currentTime is the page's choice (new Animation() played, synchronously);\n // otherwise it was found by an event or a sweep, after real time ran, and it begins where found.\n const hold = (anim, anchored = false) => {\n if (!anim || entries.has(anim) || !timeBased(anim)) return;\n const state = anim.playState;\n const at = startNow();\n const h = {\n anim,\n anchor: 0,\n anchorAt: at,\n get startAt() {\n const rate = this.anim.playbackRate;\n return rate > 0 ? this.anchorAt - this.anchor / rate : this.anchorAt;\n },\n // One the page has already paused (a scrubber, animation-play-state: paused) is the page's.\n pagePaused: state === \"paused\",\n cancelled: false,\n endedByHold: false,\n endedAt: null,\n watched: null,\n };\n entries.set(anim, h);\n held.push(h);\n watch(h);\n try { nativeListen.call(anim, \"finish\", () => adopt(h)); } catch {}\n // Found finished while the clock is still at 0: it ran out in the real time load took, and is\n // held from 0 like a running one. Found finished later, it is the page's.\n const restart = state === \"finished\" && clockNow() === 0 && !pageFinished.has(anim);\n if ((state !== \"running\" && !restart) || anim.playbackRate === 0) return;\n const current = pauseHere(anim);\n if (anchored) h.anchor = current;\n else if (anim.playbackRate < 0) {\n // Run backwards it starts from its end, where play() would rewind it to.\n const end = endOf(anim);\n h.anchor = Number.isFinite(end) ? end : current;\n }\n // Put at its page time now when that is not where it was found: one that ran out at load, and\n // one started at a held animation's end that the clock has already passed.\n if (restart || at !== clockNow()) place(h, clockNow());\n };\n // A held animation whose time the hold keeps: not paused or finished by the page, not cancelled\n // or idle. Placing one the page finished would undo its finish().\n const live = (h) => {\n if (!h || h.pagePaused || h.cancelled) return false;\n const state = h.anim.playState;\n return state !== \"idle\" && (state !== \"finished\" || h.endedByHold);\n };\n // The page's own pause and play are seen: a held animation the page pauses is placed at the\n // page's present first (its currentTime is only as fresh as the last seek), then left to the\n // page; one it plays is taken over again from where that leaves it. An animation built with\n // new Animation() is held when the page first plays it.\n proto.pause = function () {\n const h = entries.get(this);\n if (h && !h.pagePaused && !h.cancelled && this.playState !== \"idle\") {\n if (live(h)) place(h, clockNow());\n h.pagePaused = true;\n h.endedByHold = false;\n }\n return nativePause.call(this);\n };\n proto.play = function () {\n const h = entries.get(this);\n if (live(h)) place(h, clockNow());\n const result = nativePlay.call(this);\n if (h) takeOver(h);\n else hold(this, true);\n return result;\n };\n proto.finish = function () {\n pageFinished.add(this);\n const h = entries.get(this);\n if (h) h.endedByHold = false;\n return nativeFinish.call(this);\n };\n // The page's own writes are seen too: one that moves a held animation holds it again from where\n // the write leaves it, at the page time the page made it. Without this a strobe the page set to\n // its end and reversed (currentTime = 2000; playbackRate = -1) sat where the hold had it. One the\n // page had finished and now sets running again (currentTime = 0) is taken over at once, not left\n // to run on the real clock until the next seek.\n const moved = (anim, change) => {\n const h = entries.get(anim);\n const wasLive = live(h);\n if (wasLive) place(h, clockNow());\n const result = change();\n if (wasLive || (h && !h.pagePaused && !h.cancelled && anim.playState === \"running\")) takeOver(h);\n return result;\n };\n for (const [name, desc] of [[\"currentTime\", currentTimeAccessor], [\"playbackRate\", rateAccessor], [\"startTime\", startTimeAccessor]]) {\n if (!desc || !desc.set) continue;\n Object.defineProperty(proto, name, {\n ...desc,\n set(value) { moved(this, () => desc.set.call(this, value)); },\n });\n }\n proto.reverse = function () {\n return moved(this, () => nativeReverse.call(this));\n };\n // On a held animation the new rate is set at once: it is paused, where updatePlaybackRate() and\n // a playbackRate write do the same, except that updatePlaybackRate() leaves it pending a frame.\n proto.updatePlaybackRate = function (rate) {\n if (!live(entries.get(this))) return nativeUpdateRate.call(this, rate);\n return moved(this, () => { rateAccessor.set.call(this, rate); });\n };\n // animationstart and transitionrun are not composed, so each open shadow root is listened to\n // on its own: the ones a script attaches as it attaches them, declarative ones when found.\n const listening = new WeakSet();\n const onStart = (event) => {\n const target = event.target;\n if (!target || !target.getAnimations) return;\n for (const anim of target.getAnimations()) hold(anim);\n };\n const listen = (root) => {\n if (listening.has(root)) return;\n listening.add(root);\n root.addEventListener(\"animationstart\", onStart, true);\n root.addEventListener(\"transitionrun\", onStart, true);\n };\n listen(document);\n const nativeAttachShadow = Element.prototype.attachShadow;\n Element.prototype.attachShadow = function (...args) {\n const root = nativeAttachShadow.apply(this, args);\n if (root && root.mode === \"open\") listen(root);\n return root;\n };\n const nativeAnimate = Element.prototype.animate;\n Element.prototype.animate = function (...args) {\n const anim = nativeAnimate.apply(this, args);\n hold(anim);\n return anim;\n };\n // document.getAnimations() leaves out shadow trees: every open root, at any depth.\n const openRoots = () => {\n const out = [];\n const walk = (root) => {\n for (const el of root.querySelectorAll(\"*\")) {\n if (el.shadowRoot) { out.push(el.shadowRoot); walk(el.shadowRoot); }\n }\n };\n walk(document);\n return out;\n };\n // SMIL runs on each outermost <svg>'s own timeline, which begins when that svg is inserted\n // (Chromium 141: 0 right after insertion) — at load for one in the page. Each is paused and\n // put at its page time when found, so its startAt is the page time it was found at.\n const SMIL = \"animate, animateTransform, animateMotion, set\";\n const svgs = [];\n const svgSeen = new WeakSet();\n const placeSvg = (s, t) => {\n try {\n s.svg.pauseAnimations();\n s.svg.setCurrentTime(Math.max(0, t - s.startAt) / 1000);\n } catch {}\n };\n // Late arrivals: anything the events missed is held at the instant it is found. A CSS animation\n // still in its delay has fired no animationstart, so both readers sweep: the list read after\n // advanceTo(0) holds everything that exists then. One a script starts later is held by the seek\n // that first finds it.\n const collectLate = () => {\n const roots = openRoots();\n if (document.getAnimations) for (const anim of document.getAnimations()) hold(anim);\n for (const root of roots) {\n listen(root);\n if (root.getAnimations) for (const anim of root.getAnimations()) hold(anim);\n }\n for (const root of [document, ...roots]) {\n for (const svg of root.querySelectorAll(\"svg\")) {\n if (svg.ownerSVGElement || svgSeen.has(svg) || !svg.querySelector(SMIL)) continue;\n svgSeen.add(svg);\n const s = { svg, startAt: clockNow() };\n svgs.push(s);\n placeSvg(s, s.startAt);\n }\n }\n };\n // Once paused through the API a CSS animation outlives its animation-name; the name is compared\n // escaped too, since computed style serialises slide:in as slide\\:in.\n const nameGone = (anim) => {\n if (typeof anim.animationName !== \"string\" || !anim.effect || !anim.effect.target) return false;\n try {\n const listed = getComputedStyle(anim.effect.target, anim.effect.pseudoElement || null)\n .animationName.split(\",\").map((n) => n.trim());\n const escaped = typeof CSS !== \"undefined\" && CSS.escape ? CSS.escape(anim.animationName) : anim.animationName;\n return !listed.includes(anim.animationName) && !listed.includes(escaped);\n } catch { return false; }\n };\n // Every state is read before any animation is moved: playState and computed style each bring\n // style up to date, and read after a currentTime write they recomputed it once per animation:\n // 120 seeks of 150 dealt cards took 855ms that way and ~170ms read first (114ms before these\n // checks existed). Each effect's end is read with them; with that, and each card's finish() at\n // its end, 120 seeks of another 150-card CSS deal measured ~130ms before and ~180ms after.\n //\n // Returns how many animations it ended: their finish events are dispatched when the browser next\n // renders (the clock's rendered()), and what those start can itself end before t.\n window.__vlmkitSeekTimeline = (t) => {\n collectLate();\n const zero = clockNow() === 0;\n let ended = 0;\n const states = held.map((h) => {\n if (h.cancelled) return { state: \"cancelled\", end: 0 };\n const state = h.anim.playState;\n if (state !== \"idle\" && nameGone(h.anim)) return { state: \"gone\", end: 0 };\n return { state, end: state === \"idle\" ? 0 : endOf(h.anim) };\n });\n held.forEach((h, i) => {\n const { state, end } = states[i];\n if (state === \"cancelled\") return;\n // Never revive: setting currentTime on a cancelled (idle) animation brings it back. One the\n // page cancelled, or a CSS one whose element no longer lists its name, is cancelled for good\n // and stays in the list for the callers that attribute motion to it.\n if (state === \"idle\" || state === \"gone\") {\n if (state === \"gone\") { try { nativeCancel.call(h.anim); } catch {} }\n h.cancelled = true;\n return;\n }\n if (state === \"running\") {\n // Running again by a route no wrapper sees (animation-play-state, a changed effect): take\n // it over.\n takeOver(h);\n } else if (state === \"finished\") {\n if (h.endedByHold) {\n // Ended by an earlier seek: it stays ended while the page time is past its end, and a\n // seek back before it (check flash attributes a window at its middle) pauses it and puts\n // it back, instead of letting it run on the real clock.\n if (reached(h, t, end)) return;\n try { nativePause.call(h.anim); } catch {}\n h.endedByHold = false;\n watch(h);\n place(h, t, end);\n return;\n }\n // Ended by the page (finish()), or found finished after the clock moved: the page's.\n // Finished while the clock is still at 0, it ran out during load: held from 0.\n if (h.pagePaused || !zero || pageFinished.has(h.anim)) return;\n h.anchor = h.anim.playbackRate < 0 && Number.isFinite(end) ? end : 0;\n h.anchorAt = 0;\n try { nativePause.call(h.anim); } catch {}\n watch(h);\n }\n if (h.pagePaused || h.anim.playbackRate === 0) return;\n if (!reached(h, t, end)) {\n place(h, t, end);\n return;\n }\n // At or past its end: ended natively, so finished resolves and onfinish / finish listeners\n // run; what they start begins at this end (adopt). A CSS animation's animationend is the\n // phase change, which finish() makes once, as a seek past the end did before.\n const rate = h.anim.playbackRate;\n h.endedAt = Math.max(h.anchorAt, h.anchorAt + ((rate > 0 ? end : 0) - h.anchor) / rate);\n h.endedByHold = true;\n watch(h);\n try {\n nativeFinish.call(h.anim);\n ended += 1;\n } catch {\n h.endedByHold = false;\n place(h, t, end);\n }\n });\n for (const s of svgs) placeSvg(s, t);\n return ended;\n };\n // A SMIL clock value that is a plain number (seconds unless a unit says otherwise), else null.\n const clockValue = (text) => {\n const m = /^\\s*(\\d+(?:\\.\\d+)?|\\.\\d+)(ms|s|min|h)?\\s*$/.exec(text || \"\");\n return m ? Number(m[1]) * { ms: 1, s: 1000, min: 60000, h: 3600000 }[m[2] || \"s\"] : null;\n };\n // begin / dur / repeatCount / repeatDur read off the element; what is not a plain number\n // (an event or syncbase begin, an indefinite or absent dur) is listed as repeating from 0.\n const smilTiming = (el, startAt) => {\n const unknown = { startMs: 0, durationMs: 0, iterations: null };\n const begin = el.hasAttribute(\"begin\") ? clockValue(el.getAttribute(\"begin\")) : 0;\n const dur = clockValue(el.getAttribute(\"dur\"));\n if (begin === null || dur === null) return unknown;\n let iterations = 1;\n const count = el.getAttribute(\"repeatCount\");\n if (count !== null) {\n if (count.trim() === \"indefinite\") iterations = null;\n else if (Number(count) > 0) iterations = Number(count);\n else return unknown;\n }\n const repeatDur = el.getAttribute(\"repeatDur\");\n if (repeatDur !== null && repeatDur.trim() !== \"indefinite\") {\n const span = clockValue(repeatDur);\n if (span === null || !(dur > 0)) return unknown;\n iterations = iterations === null ? span / dur : Math.min(iterations, span / dur);\n } else if (repeatDur !== null && count === null) iterations = null;\n return { startMs: startAt + begin, durationMs: dur, iterations };\n };\n window.__vlmkitTimelineAnimations = () => {\n collectLate();\n const out = held.map((h) => {\n let timing = {};\n try { timing = h.anim.effect && h.anim.effect.getComputedTiming ? h.anim.effect.getComputedTiming() : {}; } catch {}\n const delay = typeof timing.delay === \"number\" ? timing.delay : 0;\n const duration = typeof timing.duration === \"number\" ? timing.duration : 0;\n const iterations = Number.isFinite(timing.iterations) ? timing.iterations : null;\n const rate = h.anim.playbackRate;\n if (!(rate < 0)) {\n // Local times on the page's clock: at rate 2 a 1000ms animation takes 500ms of page time.\n const speed = rate > 0 ? rate : 1;\n return { startMs: h.startAt + delay / speed, durationMs: duration / speed, iterations };\n }\n // Run backwards from its anchor, it plays its active phase from there down to its delay:\n // it enters it once its local time falls below the active phase's end.\n const speed = -rate;\n const activeEnd = delay + (typeof timing.activeDuration === \"number\" ? timing.activeDuration : 0);\n return {\n startMs: h.anchorAt + Math.max(0, h.anchor - activeEnd) / speed,\n durationMs: duration / speed,\n iterations: duration > 0 ? Math.max(0, Math.min(h.anchor, activeEnd) - delay) / duration : 0,\n };\n });\n for (const s of svgs) for (const el of s.svg.querySelectorAll(SMIL)) out.push(smilTiming(el, s.startAt));\n return out;\n };\n})()";
71
+ //#endregion