@whzxc/agent-design-gallery 0.15.0 → 0.16.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.
Files changed (76) hide show
  1. package/README.md +5 -2
  2. package/package.json +2 -1
  3. package/public/app.js +602 -64
  4. package/public/assets.js +25 -10
  5. package/public/boards.js +8 -3
  6. package/public/frame-identity.js +25 -12
  7. package/public/icons.js +7 -0
  8. package/public/index.html +14 -2
  9. package/public/motion-flow.js +28 -0
  10. package/public/motion-identity.js +100 -0
  11. package/public/motion-paint.js +332 -0
  12. package/public/motion-scene.js +165 -0
  13. package/public/motion-specimens.js +335 -0
  14. package/public/player.css +270 -0
  15. package/public/player.js +753 -0
  16. package/public/recent-updates.js +535 -0
  17. package/public/style.css +17 -2
  18. package/public/tokens.css +6 -0
  19. package/public/view-boards.css +131 -0
  20. package/public/view-boards.js +350 -0
  21. package/public/view-route.js +1 -1
  22. package/src/boards/motion-board.mjs +202 -0
  23. package/src/boards/token-board.mjs +9 -5
  24. package/src/cli-output.mjs +3 -1
  25. package/src/cli.mjs +52 -18
  26. package/src/http.mjs +5 -2
  27. package/src/recent-frames.mjs +295 -0
  28. package/src/recent-history.mjs +100 -0
  29. package/src/recent-job.mjs +63 -0
  30. package/src/recent-worker.mjs +171 -0
  31. package/src/server.mjs +229 -18
  32. package/src/toolkit/arch-git.mjs +8 -14
  33. package/src/toolkit/browser.mjs +1 -13
  34. package/src/toolkit/build-store.mjs +9 -1
  35. package/src/toolkit/build-worker.mjs +6 -0
  36. package/src/toolkit/build.mjs +22 -16
  37. package/src/toolkit/commands.mjs +93 -2
  38. package/src/toolkit/compare.mjs +13 -11
  39. package/src/toolkit/config.mjs +2 -2
  40. package/src/toolkit/diff-inputs.mjs +35 -26
  41. package/src/toolkit/diff.mjs +24 -11
  42. package/src/toolkit/frame-declarations.mjs +36 -0
  43. package/src/toolkit/git-blobs.mjs +50 -0
  44. package/src/toolkit/impact-inputs.mjs +11 -19
  45. package/src/toolkit/impact-selection.mjs +2 -2
  46. package/src/toolkit/impact.mjs +17 -3
  47. package/src/toolkit/implementation-map.mjs +17 -6
  48. package/src/toolkit/input-generation.mjs +15 -0
  49. package/src/toolkit/inspect-output.mjs +1 -1
  50. package/src/toolkit/inspect.d.ts +9 -1
  51. package/src/toolkit/inspect.mjs +25 -1
  52. package/src/toolkit/motion-check.mjs +382 -0
  53. package/src/toolkit/motion-css.mjs +105 -0
  54. package/src/toolkit/motion-flows.mjs +95 -0
  55. package/src/toolkit/motion-impact.mjs +87 -0
  56. package/src/toolkit/motion-inventory.mjs +202 -0
  57. package/src/toolkit/motion-label.mjs +111 -0
  58. package/src/toolkit/motion-patterns.mjs +216 -0
  59. package/src/toolkit/motion-primitives.mjs +94 -0
  60. package/src/toolkit/motion-queries.mjs +169 -0
  61. package/src/toolkit/motion.mjs +300 -0
  62. package/src/toolkit/owner.mjs +19 -6
  63. package/src/toolkit/play-endpoint.mjs +66 -0
  64. package/src/toolkit/project-index.mjs +2 -2
  65. package/src/toolkit/recent-structure.mjs +201 -0
  66. package/src/toolkit/results.mjs +2 -2
  67. package/src/toolkit/review-document.mjs +9 -4
  68. package/src/toolkit/review-embed-document.mjs +671 -0
  69. package/src/toolkit/review-filmstrip.mjs +76 -0
  70. package/src/toolkit/review-motion-card.mjs +51 -0
  71. package/src/toolkit/review-motion.mjs +159 -0
  72. package/src/toolkit/review-playback.js +123 -0
  73. package/src/toolkit/review-sheet.mjs +36 -28
  74. package/src/toolkit/review.mjs +131 -31
  75. package/src/toolkit/runtime.mjs +7 -1
  76. package/src/viewer-cache.mjs +48 -12
@@ -0,0 +1,753 @@
1
+ import { icon } from './icons.js';
2
+ import { dataFetch } from './auth.js';
3
+ import { viewURL } from './view-route.js';
4
+ import { candidates } from './motion-identity.js';
5
+ import { createStage, mountScene, observeScene } from './motion-scene.js';
6
+ import { flowLayout } from './motion-flow.js';
7
+ import { preparePaint, playTimeline } from './motion-paint.js';
8
+
9
+ let preference = 'system', hotspots = false;
10
+ try { preference = sessionStorage.getItem('adg-player-reduced') ?? preference; } catch {}
11
+ try { hotspots = localStorage.getItem('adg-player-hotspots') === 'true'; } catch {}
12
+ const exact = (rows, target) => {
13
+ const found = target && candidates(rows, target);
14
+ return found?.length === 1 ? found[0].el : null;
15
+ };
16
+
17
+ export async function openPlayer({ source, frame, theme, invoker }) {
18
+ if (document.querySelector('#motion-player')) return;
19
+ const dialog = document.createElement('dialog');
20
+ dialog.id = 'motion-player';
21
+ dialog.setAttribute('aria-label', 'Play transitions');
22
+ const link = document.createElement('link');
23
+ link.rel = 'stylesheet';
24
+ link.href = new URL('player.css', document.baseURI);
25
+ dialog.innerHTML = `<header class="play-header"><div><span class="play-project">${icon('route', 17)}<b data-control="source"></b></span>
26
+ <button data-control="settings" aria-controls="play-settings" aria-expanded="false">${icon('settings-2', 15)}Playback settings <span data-control="mode"></span></button></div>
27
+ <nav aria-label="Player controls">
28
+ <div class="play-navigation">
29
+ <button data-control="back" aria-keyshortcuts="ArrowLeft" title="Back (←)" disabled>${icon('arrow-left', 14)}Back</button>
30
+ <button data-control="restart" aria-keyshortcuts="R" title="Restart (R)" disabled>${icon('rotate-ccw', 14)}Restart</button>
31
+ <span class="play-end" data-control="end-marker" role="status" aria-hidden="true">End of flow</span>
32
+ </div>
33
+ <button data-control="hotspots" aria-keyshortcuts="H" aria-pressed="false">${icon('scan', 14)}Hotspots</button>
34
+ <button data-control="flow-map" disabled>${icon('map', 14)}Flow map</button>
35
+ <button data-control="flow" aria-controls="play-flow" aria-expanded="false">${icon('route', 14)}Flow</button>
36
+ <button data-control="inspector" aria-controls="play-inspector" aria-expanded="false" disabled>${icon('panel-right', 14)}Transition inspector</button>
37
+ <button data-control="exit">${icon('log-out', 14)}Exit to board</button></nav></header>
38
+ <section id="play-settings" class="play-settings" aria-label="Playback settings" hidden></section>
39
+ <section class="play-stage" aria-label="Frame preview"></section>
40
+ <aside id="play-flow" class="play-rail" aria-label="Flow" hidden><section><small>Current frame</small><h1 data-control="current" aria-live="polite"></h1>
41
+ <small>Path taken</small><p data-control="path"></p><div class="play-history">
42
+ <button data-control="forward" aria-keyshortcuts="ArrowRight">${icon('chevron-right', 14)}<span></span></button>
43
+ </div></section>
44
+ <section><h2>Next actions</h2><p data-control="next-context"></p>
45
+ <div class="play-actions" role="group" aria-label="Outgoing actions"></div></section></aside>
46
+ <section id="play-inspector" class="play-dock" aria-label="Transition inspector" hidden><div class="play-transport">
47
+ <div><small data-control="state"></small><h2 data-control="action"></h2><code data-control="endpoints"></code></div>
48
+ <div><button data-control="pause">Pause transition</button><button data-control="replay">${icon('rotate-ccw', 14)}Replay transition</button></div></div>
49
+ <div class="play-clock"><span>0 ms</span><input data-control="seek" type="range" min="0" max="100" step="1" value="0" aria-label="Transition progress">
50
+ <span data-control="end"></span></div><p data-control="instant"></p>
51
+ <footer><span data-control="duration"></span><span data-control="easing"></span><b data-control="elapsed"></b></footer></section>
52
+ <small role="status"></small>`;
53
+ document.head.append(link);
54
+ document.body.append(dialog);
55
+ dialog.showModal();
56
+ const control = (id) => dialog.querySelector('[data-control="' + id + '"]');
57
+ const stageHost = dialog.querySelector('.play-stage'),
58
+ label = control('current'),
59
+ status = dialog.querySelector(':scope > [role=status]');
60
+ const actions = dialog.querySelector('.play-actions'),
61
+ media = matchMedia('(prefers-reduced-motion: reduce)');
62
+ const controller = new AbortController(),
63
+ signal = controller.signal,
64
+ cache = new Map();
65
+ const history = [],
66
+ future = [],
67
+ focusStack = [],
68
+ panels = [],
69
+ offsets = new Map();
70
+ let prototype, startScene, pin;
71
+ let iframe,
72
+ doc,
73
+ scene,
74
+ stage,
75
+ rows = [],
76
+ active = null,
77
+ last = null,
78
+ busy = true,
79
+ cancelClock,
80
+ run = false,
81
+ progress = 0,
82
+ speed = 1,
83
+ mounted,
84
+ committing = false,
85
+ overlay;
86
+ const reduced = () => preference === 'on' || (preference === 'system' && media.matches);
87
+ function stop() {
88
+ cancelClock?.();
89
+ run = false;
90
+ }
91
+ function exit() {
92
+ stop();
93
+ controller.abort();
94
+ active?.paint?.dispose();
95
+ dialog.close();
96
+ dialog.remove();
97
+ link.remove();
98
+ const caption = document.querySelector(
99
+ '[data-frame-source="' + CSS.escape(source) + '"][data-frame-name="' + CSS.escape(frame) + '"] .caption-play'
100
+ );
101
+ (invoker.isConnected
102
+ ? invoker
103
+ : (caption ?? document.querySelector('#play-frame:not([hidden]),.gallery-viewport'))
104
+ )?.focus({ preventScroll: true });
105
+ }
106
+ control('exit').onclick = exit;
107
+ function dismissPopover() {
108
+ const button = panels.at(-1);
109
+ if (!button) return false;
110
+ button.click();
111
+ button.focus();
112
+ return true;
113
+ }
114
+ dialog.addEventListener('cancel', (e) => {
115
+ e.preventDefault();
116
+ if (!dismissPopover()) exit();
117
+ });
118
+ // Modal keyboard commands never reach board camera or navigation handlers.
119
+ dialog.addEventListener('keydown', (e) => {
120
+ e.stopPropagation();
121
+ if (e.key === 'Escape' && !panels.length && dispatch(e, 'key', stage?.firstElementChild)) return;
122
+ playerKey(e);
123
+ });
124
+ dialog.addEventListener('keyup', (e) => e.stopPropagation());
125
+ control('source').textContent = source
126
+ .split('/')
127
+ .at(-1)
128
+ .replace(/\.tsx$/, '')
129
+ .replace(/-/g, ' ')
130
+ .replace(/^./, (c) => c.toUpperCase());
131
+ function fail(err) {
132
+ if (signal.aborted) return;
133
+ busy = false;
134
+ stop();
135
+ status.textContent = err.message;
136
+ update();
137
+ }
138
+ const currentTheme = () => document.documentElement.dataset.theme || theme;
139
+ async function fetchScene(ref) {
140
+ const key = sceneKey(ref);
141
+ if (!cache.has(key)) {
142
+ const res = await dataFetch('api/play?' + new URLSearchParams({ ...ref, theme, scene: '1' }), { signal });
143
+ if (!res.ok) throw Error((await res.json()).error ?? 'Cannot load frame.');
144
+ cache.set(key, await res.json());
145
+ }
146
+ return cache.get(key);
147
+ }
148
+ const sceneKey = ({ source, frame }) => JSON.stringify([source, frame]);
149
+ const localRef = (ref, design) => ({
150
+ source: design && design !== '.' ? ref.source.slice(design.length + 1) : ref.source,
151
+ frame: ref.frame
152
+ });
153
+ async function prepareStage(initial) {
154
+ const flow = initial.flow ?? { frames: [], triggers: [] };
155
+ const refs = flow.frames.map((ref) => localRef(ref, initial.design));
156
+ const endpoints = refs.length ? await Promise.allSettled(refs.map(fetchScene)) : [{ value: initial }];
157
+ const frames = [];
158
+ for (const { value: endpoint } of endpoints) {
159
+ if (!endpoint || signal.aborted) continue;
160
+ const specimen = await mountScene(doc, endpoint, currentTheme());
161
+ const { x, y, width, height } = specimen.getBoundingClientRect();
162
+ frames.push({ endpoint, box: [x, y, width, height], rows: observeScene(specimen, endpoint.design) });
163
+ }
164
+ if (signal.aborted) throw new DOMException('Player closed', 'AbortError');
165
+ const layout = flowLayout(frames.length < endpoints.length ? { triggers: [] } : flow, frames);
166
+ pin = layout.pin?.target;
167
+ frames.forEach(({ endpoint }, i) => offsets.set(sceneKey(endpoint), layout.offsets[i]));
168
+ startScene = frames.find(({ endpoint }) => flow.start &&
169
+ sceneKey(endpoint) === sceneKey(localRef(flow.start, initial.design)))?.endpoint ?? initial;
170
+ prototype = doc.createElement('div');
171
+ Object.assign(prototype.style, {
172
+ position: 'relative', flex: 'none', margin: 'auto',
173
+ width: Math.max(layout.width, flow.stage?.width ?? 0) + 'px',
174
+ height: Math.max(layout.height, flow.stage?.height ?? 0) + 'px'
175
+ });
176
+ doc.body.replaceChildren(prototype);
177
+ }
178
+ async function show(endpoint) {
179
+ overlay?.remove();
180
+ composing = null;
181
+ const offset = offsets.get(sceneKey(endpoint)) ?? [0, 0];
182
+ stage = await mountScene(doc, endpoint, currentTheme(), { parent: prototype, offset });
183
+ if (signal.aborted) throw new DOMException('Player closed', 'AbortError');
184
+ rows = observeScene(stage, endpoint.design);
185
+ mounted = endpoint;
186
+ hints();
187
+ for (const edge of endpoint.edges) {
188
+ if (edge.trigger.on !== 'input') continue;
189
+ const el = exact(rows, edge.trigger.target);
190
+ if (el?.dataset.playerTextEntry === 'input') el.readOnly = false;
191
+ if (el?.dataset.playerTextEntry === 'editable') el.contentEditable = 'plaintext-only';
192
+ }
193
+ }
194
+ const hotspotButton = control('hotspots');
195
+ hotspotButton.setAttribute('aria-pressed', String(hotspots));
196
+ hotspotButton.onclick = () => {
197
+ hotspots = !hotspots;
198
+ try { localStorage.setItem('adg-player-hotspots', String(hotspots)); } catch {}
199
+ hotspotButton.setAttribute('aria-pressed', String(hotspots));
200
+ hints();
201
+ };
202
+ const flowMap = control('flow-map');
203
+ flowMap.onclick = () => {
204
+ const flow = scene?.flow;
205
+ if (!flow) return;
206
+ const url = viewURL(location.href, 'all');
207
+ url.searchParams.set('view', 'playable');
208
+ url.searchParams.set('flow', flow.id ?? sceneKey(localRef(flow.start, scene.design)));
209
+ location.assign(url);
210
+ };
211
+ function hints() {
212
+ overlay?.remove();
213
+ overlay = null;
214
+ if (!hotspots || !rows.length) return;
215
+ const outlined = new Map();
216
+ for (const edge of mounted?.edges ?? []) {
217
+ const el = exact(rows, edge.trigger.target);
218
+ if (!el) continue;
219
+ if (!outlined.has(el)) outlined.set(el, new Set());
220
+ outlined.get(el).add(edge.label);
221
+ }
222
+ if (!outlined.size) return;
223
+ const { clientWidth: width, clientHeight: height } = doc.documentElement;
224
+ for (const [el, labels] of outlined) {
225
+ const b = el.getBoundingClientRect();
226
+ if (!b.width || !b.height || b.right <= 0 || b.bottom <= 0 || b.left >= width || b.top >= height) continue;
227
+ if (!overlay) {
228
+ overlay = doc.createElement('div');
229
+ overlay.dataset.playerHints = '';
230
+ overlay.inert = true;
231
+ overlay.setAttribute('aria-hidden', 'true');
232
+ Object.assign(overlay.style, {
233
+ position: 'fixed', inset: '0', overflow: 'hidden', pointerEvents: 'none', zIndex: '2147483647'
234
+ });
235
+ doc.body.append(overlay);
236
+ }
237
+ const box = doc.createElement('div'), tag = doc.createElement('span');
238
+ Object.assign(box.style, {
239
+ position: 'absolute',
240
+ left: b.left + 'px',
241
+ top: b.top + 'px',
242
+ width: b.width + 'px',
243
+ height: b.height + 'px',
244
+ outline: '2px dashed var(--accent)'
245
+ });
246
+ const gap = 4;
247
+ Object.assign(tag.style, {
248
+ position: 'absolute',
249
+ width: 'max-content',
250
+ maxWidth: Math.max(0, width - 2 * gap) + 'px',
251
+ boxSizing: 'border-box',
252
+ overflow: 'hidden',
253
+ textOverflow: 'ellipsis',
254
+ whiteSpace: 'nowrap',
255
+ padding: '2px 4px',
256
+ background: 'var(--surface)',
257
+ color: 'var(--text)',
258
+ font: '11px system-ui'
259
+ });
260
+ tag.textContent = [...labels].join(' · ');
261
+ box.append(tag);
262
+ overlay.append(box);
263
+ const measured = tag.getBoundingClientRect();
264
+ const above = b.top - gap - measured.height, below = b.bottom + gap;
265
+ const top = above >= gap ? above : below;
266
+ if (top < gap || top + measured.height > height - gap || width <= 2 * gap) {
267
+ tag.remove();
268
+ continue;
269
+ }
270
+ const left = Math.max(gap, Math.min(b.left, width - gap - measured.width));
271
+ tag.style.left = left - b.left + 'px';
272
+ tag.style.top = top - b.top + 'px';
273
+ }
274
+ }
275
+ let actionFrame, actionsBusy;
276
+ function drawActions(dest) {
277
+ const groups = new Map();
278
+ for (const edge of dest?.edges ?? []) {
279
+ const key = edge.authoredLabel ? 'label:' + edge.label : JSON.stringify(edge.to);
280
+ if (!groups.has(key)) groups.set(key, []);
281
+ groups.get(key).push(edge);
282
+ }
283
+ actions.replaceChildren();
284
+ const names = [...groups.values()].map((edges) => edges[0].label);
285
+ for (const edges of groups.values()) {
286
+ const row = document.createElement('div'),
287
+ name = document.createElement('strong');
288
+ name.textContent = edges[0].label;
289
+ row.append(name);
290
+ if (names.filter((label) => label === edges[0].label).length > 1) {
291
+ const detail = document.createElement('small');
292
+ detail.textContent = 'To ' + edges[0].to.frame;
293
+ row.append(detail);
294
+ }
295
+ const chips = document.createElement('div');
296
+ for (const edge of edges) {
297
+ const chip = document.createElement('button');
298
+ chip.type = 'button';
299
+ chip.dataset.edge = edge.id;
300
+ chip.textContent = edges.some((other) => other !== edge && other.gesture === edge.gesture)
301
+ ? edge.gesture + ' → ' + edge.to.frame
302
+ : edge.gesture;
303
+ chip.setAttribute('aria-label', edge.label + ' · ' + chip.textContent);
304
+ chip.disabled = busy;
305
+ chip.onclick = () => invoke(edge).catch(fail);
306
+ chips.append(chip);
307
+ }
308
+ row.append(chips);
309
+ actions.append(row);
310
+ }
311
+ }
312
+ function clock() {
313
+ const transition = active ?? last;
314
+ if (!transition) return;
315
+ const ms = transition.duration;
316
+ control('seek').value = String(Math.round(progress * 100));
317
+ const at = Math.round(progress * ms) + ' ms';
318
+ control('seek').setAttribute('aria-valuetext', at);
319
+ control('elapsed').textContent = at + ' elapsed';
320
+ }
321
+ function update() {
322
+ const dest = active?.to ?? scene,
323
+ transition = active ?? last;
324
+ label.textContent = scene?.frame ?? 'Loading…';
325
+ control('path').textContent = [...history.map((h) => h.scene.frame), scene?.frame].filter(Boolean).join(' › ');
326
+ const previous = history.at(-1)?.scene.frame, next = future.at(-1)?.scene.frame;
327
+ control('back').disabled = busy || (!previous && !active);
328
+ control('back').title = previous && !active ? 'Back to ' + previous + ' (←)' : 'Back (←)';
329
+ control('forward').hidden = !next;
330
+ control('forward').disabled = busy;
331
+ control('forward').lastElementChild.textContent = next ? 'Forward to ' + next : '';
332
+ control('end-marker').setAttribute('aria-hidden', String(!scene || !!active || busy || !!scene.edges.length));
333
+ control('restart').disabled = busy;
334
+ flowMap.disabled = busy || !scene?.flow;
335
+ control('next-context').textContent = active
336
+ ? 'Continue from ' + dest.frame
337
+ : dest && !dest.edges.length
338
+ ? 'No outgoing actions from this frame.'
339
+ : '';
340
+ if (actionFrame !== dest || actionsBusy !== busy) drawActions(dest);
341
+ actionFrame = dest;
342
+ actionsBusy = busy;
343
+ const inspector = control('inspector');
344
+ if (!transition && panels.includes(inspector)) setPanel(inspector, false);
345
+ inspector.disabled = !transition;
346
+ if (transition) {
347
+ const { edge, instant } = transition;
348
+ control('state').textContent = active ? (run ? 'Playing transition' : 'Paused transition') : 'Last transition';
349
+ control('action').textContent = edge.label;
350
+ control('endpoints').textContent = edge.from.frame + ' → ' + edge.to.frame;
351
+ control('pause').hidden = !active;
352
+ control('pause').innerHTML = run ? icon('pause', 14) + 'Pause transition' : icon('play', 14) + 'Resume transition';
353
+ control('elapsed').hidden = instant;
354
+ control('replay').disabled = busy;
355
+ control('seek').disabled = busy || reduced() || !!edge.unsupported;
356
+ dialog.querySelector('.play-clock').hidden = instant;
357
+ control('instant').textContent = instant ? 'Applied instantly · 0 ms' : '';
358
+ control('duration').textContent = 'Duration ' + edge.duration + ' · ' + edge.timings['/duration'] + ' ms';
359
+ control('easing').textContent = 'Easing ' + edge.easing + ' · ' + edge.timings['/easing'];
360
+ control('end').textContent = transition.duration + ' ms';
361
+ clock();
362
+ }
363
+ control('mode').textContent = reduced() ? 'Reduced motion' : speed + '×';
364
+ for (const b of settings.querySelectorAll('button'))
365
+ b.setAttribute(
366
+ 'aria-pressed',
367
+ String(b.dataset.speed !== undefined ? Number(b.dataset.speed) === speed : b.dataset.reduce === preference)
368
+ );
369
+ hints();
370
+ }
371
+ function focusIdentity(el) {
372
+ const row = rows.find((r) => r.el === el);
373
+ if (!row) return null;
374
+ if (row.anchor) return { anchor: row.anchor };
375
+ if (row.parts.length) {
376
+ let cur = row;
377
+ while (cur && !cur.keys.length) cur = rows[cur.parent];
378
+ return { part: row.parts.at(-1), ...(cur ? { key: cur.keys[0].key } : {}) };
379
+ }
380
+ return row === rows[0] ? { frame: true } : null;
381
+ }
382
+ function focus(target) {
383
+ const el = exact(rows, target) ?? stage.firstElementChild;
384
+ if (el.tabIndex < 0 && !el.hasAttribute('tabindex')) el.tabIndex = -1;
385
+ committing = true;
386
+ try {
387
+ el.focus({ preventScroll: true });
388
+ } finally {
389
+ committing = false;
390
+ }
391
+ }
392
+ function commit() {
393
+ if (!active) return;
394
+ const { edge, to, from, priorFocus, priorStack, paint, replaying } = active;
395
+ stop();
396
+ paint?.dispose();
397
+ active = null;
398
+ history.push({ scene: from, focus: priorFocus, stack: priorStack });
399
+ if (!replaying) future.length = 0;
400
+ if (edge.rememberTrigger === 'replace') focusStack.pop();
401
+ if (edge.rememberTrigger) focusStack.push(edge.trigger.target);
402
+ scene = to;
403
+ last = {
404
+ from,
405
+ edge,
406
+ priorFocus,
407
+ priorStack,
408
+ duration: reduced() ? 0 : (paint?.duration ?? 0),
409
+ instant: reduced() || !!edge.unsupported || !paint?.duration
410
+ };
411
+ progress = 1;
412
+ update();
413
+ const target =
414
+ edge.focus === 'preserve'
415
+ ? priorFocus
416
+ : edge.focus === 'restore-trigger'
417
+ ? focusStack.pop()
418
+ : edge.focus.target;
419
+ focus(target);
420
+ }
421
+ function play() {
422
+ if (!active) return;
423
+ if (reduced() || !active.paint?.duration || progress >= 1) {
424
+ commit();
425
+ return;
426
+ }
427
+ stop();
428
+ run = true;
429
+ update();
430
+ cancelClock = playTimeline(active.paint.duration, progress, speed, p => {
431
+ progress = p;
432
+ active.paint.seek(p);
433
+ clock();
434
+ }, commit);
435
+ }
436
+ async function begin(edge, seek = null, restore = null) {
437
+ busy = true;
438
+ status.textContent = '';
439
+ update();
440
+ const from = scene,
441
+ priorFocus = restore?.priorFocus ?? focusIdentity(doc.activeElement),
442
+ priorStack = [...focusStack];
443
+ let replaced = false;
444
+ try {
445
+ const to = await fetchScene(localRef(edge.to, from.design));
446
+ let first = reduced() || edge.unsupported ? null : observeScene(stage, from.design, true);
447
+ replaced = true;
448
+ await show(to);
449
+ if (!first && !reduced() && !edge.unsupported) {
450
+ await show(from);
451
+ first = observeScene(stage, from.design, true);
452
+ await show(to);
453
+ }
454
+ const instant = reduced() || !!edge.unsupported;
455
+ const paint = instant ? null : preparePaint(stage, first, observeScene(stage, to.design, true), edge, pin);
456
+ active = { edge, from, to, paint, priorFocus, priorStack, replaying: !!restore, duration: paint?.duration ?? 0, instant };
457
+ progress = seek ?? 0;
458
+ busy = false;
459
+ if (edge.unsupported) status.textContent = edge.unsupported.map((u) => u.effect + ' — ' + u.reason).join(' · ');
460
+ if (instant) {
461
+ commit();
462
+ return;
463
+ }
464
+ paint.seek(progress);
465
+ if (seek === null) play();
466
+ else update();
467
+ } catch (error) {
468
+ if (!signal.aborted) {
469
+ if (replaced) await show(from);
470
+ active = null;
471
+ busy = false;
472
+ update();
473
+ if (replaced) focus(priorFocus);
474
+ }
475
+ throw error;
476
+ }
477
+ }
478
+ async function invoke(edge) {
479
+ if (busy) return;
480
+ if (active) commit(); // Finish first, then dispatch the destination's input once.
481
+ if (scene.edges.includes(edge)) await begin(edge);
482
+ }
483
+ async function replay(at = null) {
484
+ if (busy || !(active || last)) return;
485
+ if (active) {
486
+ stop();
487
+ progress = at ?? 0;
488
+ active.paint.seek(progress);
489
+ if (at === null) play();
490
+ else update();
491
+ return;
492
+ }
493
+ const prior = last;
494
+ busy = true;
495
+ update();
496
+ scene = prior.from;
497
+ history.pop();
498
+ focusStack.splice(0, Infinity, ...prior.priorStack);
499
+ await show(scene);
500
+ await begin(prior.edge, at, prior);
501
+ }
502
+ async function visit(entry) {
503
+ stop();
504
+ active?.paint?.dispose();
505
+ active = null;
506
+ last = null;
507
+ progress = 0;
508
+ busy = true;
509
+ status.textContent = '';
510
+ scene = entry.scene;
511
+ focusStack.splice(0, Infinity, ...entry.stack);
512
+ update();
513
+ await show(scene);
514
+ busy = false;
515
+ update();
516
+ focus(entry.focus);
517
+ }
518
+ function step(from, to) {
519
+ if (busy) return;
520
+ if (active) commit();
521
+ const entry = from.pop();
522
+ if (!entry) return;
523
+ to.push({ scene, stack: [...focusStack], focus: focusIdentity(doc.activeElement) });
524
+ visit(entry).catch(fail);
525
+ }
526
+ function initialFocus(endpoint) {
527
+ return endpoint.edges.find((edge) => !edge.trigger.target.frame)?.trigger.target;
528
+ }
529
+ function restart() {
530
+ if (busy || !startScene) return;
531
+ history.length = future.length = 0;
532
+ visit({ scene: startScene, stack: [], focus: initialFocus(startScene) }).catch(fail);
533
+ }
534
+ control('back').onclick = () => step(history, future);
535
+ control('forward').onclick = () => step(future, history);
536
+ control('restart').onclick = restart;
537
+ function playerKey(e) {
538
+ if (e.defaultPrevented || e.repeat || e.ctrlKey || e.metaKey || e.altKey || e.isComposing || composing ||
539
+ e.target.closest?.('input,textarea,select,[contenteditable]:not([contenteditable="false"])')) return;
540
+ if (e.key === 'ArrowLeft') step(history, future);
541
+ else if (e.key === 'ArrowRight') step(future, history);
542
+ else if (e.key.toLowerCase() === 'r') restart();
543
+ else if (e.key.toLowerCase() === 'h') hotspotButton.click();
544
+ else return;
545
+ e.preventDefault();
546
+ }
547
+ control('pause').onclick = () => {
548
+ if (run) {
549
+ stop();
550
+ update();
551
+ } else play();
552
+ };
553
+ control('replay').onclick = () => replay().catch(fail);
554
+ const seek = control('seek');
555
+ seek.oninput = () => replay(Number(seek.value) / 100).catch(fail);
556
+ seek.onkeydown = (e) => {
557
+ if (['PageUp', 'PageDown'].includes(e.key)) {
558
+ e.preventDefault();
559
+ seek.value = Number(seek.value) + (e.key === 'PageUp' ? 10 : -10);
560
+ seek.oninput();
561
+ }
562
+ };
563
+ const settings = dialog.querySelector('.play-settings');
564
+ function setPanel(button, open) {
565
+ const panel = dialog.querySelector('#' + button.getAttribute('aria-controls'));
566
+ panel.hidden = !open;
567
+ button.setAttribute('aria-expanded', String(open));
568
+ if (open) panels.push(button);
569
+ else panels.splice(panels.indexOf(button), 1);
570
+ panels.forEach((toggle, i) => {
571
+ dialog.querySelector('#' + toggle.getAttribute('aria-controls')).style.zIndex = String(2 + i);
572
+ });
573
+ }
574
+ for (const id of ['settings', 'flow', 'inspector']) {
575
+ const button = control(id);
576
+ button.onclick = () => setPanel(button, !panels.includes(button));
577
+ }
578
+ const preferenceChanged = () => {
579
+ if (active && reduced()) commit();
580
+ else update();
581
+ };
582
+ for (const [title, options] of [
583
+ ['Playback speed', ['0.25', '0.5', '1']],
584
+ ['Reduced motion', ['system', 'on', 'off']]
585
+ ]) {
586
+ const field = document.createElement('fieldset'),
587
+ legend = document.createElement('legend');
588
+ legend.textContent = title;
589
+ field.append(legend);
590
+ for (const value of options) {
591
+ const button = document.createElement('button');
592
+ if (title === 'Playback speed') {
593
+ button.dataset.speed = value;
594
+ button.textContent = value + '×';
595
+ button.onclick = () => {
596
+ speed = Number(value);
597
+ if (run) play();
598
+ else update();
599
+ };
600
+ } else {
601
+ button.dataset.reduce = value;
602
+ button.textContent = value[0].toUpperCase() + value.slice(1);
603
+ button.onclick = () => {
604
+ preference = value;
605
+ try { sessionStorage.setItem('adg-player-reduced', value); } catch {}
606
+ preferenceChanged();
607
+ };
608
+ }
609
+ field.append(button);
610
+ }
611
+ settings.append(field);
612
+ }
613
+ media.addEventListener('change', preferenceChanged, { signal });
614
+ let composing;
615
+ const editingValue = (el) => el.value ?? el.innerText;
616
+ function dispatch(event, on, target = event.target) {
617
+ if (
618
+ busy ||
619
+ committing ||
620
+ (on === 'key' && (event.isComposing || composing || event.keyCode === 229)) ||
621
+ event.repeat ||
622
+ event.ctrlKey ||
623
+ event.metaKey ||
624
+ event.altKey
625
+ )
626
+ return;
627
+ const dest = active?.to ?? scene;
628
+ const origin =
629
+ on === 'key' && [doc.body, doc.documentElement, doc].includes(target)
630
+ ? stage?.firstElementChild
631
+ : target;
632
+ for (let node = origin; node && node !== doc; node = node.parentElement) {
633
+ const edge = dest?.edges.find(
634
+ (e) =>
635
+ e.trigger.on === on &&
636
+ (on !== 'key' || event.key === e.trigger.key) &&
637
+ (on !== 'input' || (!event.isComposing && editingValue(node) === e.trigger.value)) &&
638
+ exact(rows, e.trigger.target) === node &&
639
+ (on !== 'hover' || !node.contains(event.relatedTarget))
640
+ );
641
+ if (edge) {
642
+ event.preventDefault();
643
+ invoke(edge).catch(fail);
644
+ return true;
645
+ }
646
+ }
647
+ }
648
+ try {
649
+ iframe = await createStage(stageHost);
650
+ if (signal.aborted) return;
651
+ doc = iframe.contentDocument;
652
+ const boardRoot = document.documentElement, stageRoot = doc.documentElement;
653
+ stageRoot.style.background = 'radial-gradient(var(--player-dot) 1px, transparent 1px) 0 0/20px 20px var(--player-canvas)';
654
+ Object.assign(doc.body.style, { background: 'transparent', margin: '0', minHeight: '100vh' });
655
+ const applyStageTheme = () => {
656
+ const board = getComputedStyle(boardRoot);
657
+ stageRoot.style.setProperty('--player-canvas', board.getPropertyValue('--canvas'));
658
+ stageRoot.style.setProperty('--player-dot', board.getPropertyValue('--dot'));
659
+ const next = currentTheme(), changed = stageRoot.dataset.theme !== next;
660
+ stageRoot.dataset.theme = stageRoot.style.colorScheme = next;
661
+ if (changed && active) commit(); // Frozen transition paint belongs to the previous palette.
662
+ hints();
663
+ };
664
+ applyStageTheme();
665
+ const themeObserver = new MutationObserver(applyStageTheme);
666
+ themeObserver.observe(boardRoot, { attributes: true, attributeFilter: ['data-theme'] });
667
+ signal.addEventListener('abort', () => themeObserver.disconnect(), { once: true });
668
+ doc.addEventListener('compositionstart', (e) => {
669
+ composing = { el: e.target, value: editingValue(e.target) };
670
+ });
671
+ doc.addEventListener('input', (e) => {
672
+ if (!composing) dispatch(e, 'input');
673
+ });
674
+ doc.addEventListener('compositionend', (e) => {
675
+ const prior = composing;
676
+ composing = null;
677
+ if (prior?.el === e.target && prior.value !== editingValue(e.target)) dispatch(e, 'input');
678
+ });
679
+ doc.addEventListener('click', (e) => {
680
+ if (!dispatch(e, 'click')) {
681
+ const edges = (active?.to ?? scene)?.edges ?? [];
682
+ const hits = edges.filter(
683
+ (x) => exact(rows, x.trigger.target)?.contains(e.target) && !x.trigger.target.frame
684
+ );
685
+ if (hits.length && !hits.some((x) => x.trigger.on === 'input'))
686
+ (actions.closest('[hidden]') ? control('flow') : actions.querySelector('[data-edge="' + CSS.escape(hits[0].id) + '"]'))?.focus();
687
+ }
688
+ });
689
+ doc.addEventListener('beforeinput', (e) => {
690
+ if (
691
+ !e.target.closest(
692
+ 'input[data-player-text-entry]:not([readonly]),textarea[data-player-text-entry]:not([readonly]),[contenteditable="plaintext-only"]'
693
+ )
694
+ )
695
+ e.preventDefault();
696
+ });
697
+ doc.addEventListener('scroll', hints, true);
698
+ doc.defaultView.addEventListener('resize', hints);
699
+ for (const [name, input] of [
700
+ ['pointerover', 'hover'],
701
+ ['focusin', 'focus'],
702
+ ['keydown', 'key']
703
+ ])
704
+ doc.addEventListener(
705
+ name,
706
+ (e) => {
707
+ if (name === 'keydown' && e.key === 'Escape' && !e.repeat && !e.isComposing && !composing && dismissPopover()) {
708
+ e.preventDefault();
709
+ return;
710
+ }
711
+ if (dispatch(e, input)) return;
712
+ if (name === 'keydown') {
713
+ const button = e.target.closest?.('[role="button"], a[tabindex]');
714
+ if (button && !e.repeat && !e.isComposing && !composing &&
715
+ ['Enter', ' '].includes(e.key) && dispatch(e, 'click', button)) return;
716
+ playerKey(e);
717
+ }
718
+ if (
719
+ !busy &&
720
+ !e.repeat &&
721
+ !composing &&
722
+ !e.isComposing &&
723
+ e.keyCode !== 229 &&
724
+ name === 'keydown' &&
725
+ e.key === 'Escape'
726
+ ) {
727
+ e.preventDefault();
728
+ exit();
729
+ }
730
+ },
731
+ true
732
+ );
733
+ for (const name of ['click', 'auxclick', 'submit', 'drop', 'dragstart', 'contextmenu'])
734
+ doc.addEventListener(name, (e) => e.preventDefault(), true);
735
+ doc.addEventListener(
736
+ 'pointerdown',
737
+ (e) => {
738
+ if (active) e.preventDefault();
739
+ },
740
+ true
741
+ );
742
+ scene = await fetchScene({ source, frame });
743
+ await prepareStage(scene);
744
+ doc.body.style.display = 'flex';
745
+ await show(scene);
746
+ iframe.style.visibility = 'visible';
747
+ busy = false;
748
+ update();
749
+ focus(initialFocus(scene));
750
+ } catch (err) {
751
+ fail(err);
752
+ }
753
+ }