@whzxc/agent-design-gallery 0.14.1 → 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 (111) hide show
  1. package/README.md +29 -16
  2. package/package.json +2 -1
  3. package/public/access.css +15 -2
  4. package/public/app.js +1284 -521
  5. package/public/arrangement-worker.js +7 -7
  6. package/public/arrangement.js +35 -30
  7. package/public/assets.js +85 -48
  8. package/public/auth.js +59 -4
  9. package/public/boards.js +129 -0
  10. package/public/comment-anchors.js +50 -0
  11. package/public/comments.css +400 -0
  12. package/public/comments.js +1106 -0
  13. package/public/context-menu.js +97 -0
  14. package/public/frame-identity.js +51 -14
  15. package/public/hub.css +25 -3
  16. package/public/hub.html +10 -2
  17. package/public/hub.js +127 -23
  18. package/public/icons.js +9 -0
  19. package/public/index.html +26 -10
  20. package/public/instance-actions.js +9 -2
  21. package/public/layout.js +156 -86
  22. package/public/motion-flow.js +28 -0
  23. package/public/motion-identity.js +100 -0
  24. package/public/motion-paint.js +332 -0
  25. package/public/motion-scene.js +165 -0
  26. package/public/motion-specimens.js +335 -0
  27. package/public/player.css +270 -0
  28. package/public/player.js +753 -0
  29. package/public/recent-updates.js +535 -0
  30. package/public/selection.js +1 -1
  31. package/public/style.css +91 -154
  32. package/public/switcher.css +5 -4
  33. package/public/switcher.js +109 -34
  34. package/public/token-catalog.js +8 -3
  35. package/public/tokens.css +20 -1
  36. package/public/view-boards.css +131 -0
  37. package/public/view-boards.js +350 -0
  38. package/public/view-route.js +1 -2
  39. package/src/boards/board.mjs +30 -0
  40. package/src/boards/motion-board.mjs +202 -0
  41. package/src/boards/token-board.mjs +200 -0
  42. package/src/cli-output.mjs +10 -5
  43. package/src/cli.mjs +89 -35
  44. package/src/comments.mjs +293 -0
  45. package/src/http.mjs +7 -5
  46. package/src/hub/project-link.mjs +41 -0
  47. package/src/hub/registry.mjs +5 -0
  48. package/src/hub.mjs +14 -10
  49. package/src/link.mjs +13 -1
  50. package/src/recent-frames.mjs +295 -0
  51. package/src/recent-history.mjs +100 -0
  52. package/src/recent-job.mjs +63 -0
  53. package/src/recent-worker.mjs +171 -0
  54. package/src/server.mjs +285 -110
  55. package/src/service.mjs +46 -12
  56. package/src/toolkit/arch-git.mjs +8 -14
  57. package/src/toolkit/arch.mjs +3 -2
  58. package/src/toolkit/asset-rules.mjs +24 -1
  59. package/src/toolkit/browser.mjs +1 -13
  60. package/src/toolkit/build-store.mjs +9 -1
  61. package/src/toolkit/build-worker.mjs +6 -0
  62. package/src/toolkit/build.mjs +22 -16
  63. package/src/toolkit/commands.mjs +105 -9
  64. package/src/toolkit/compare.mjs +13 -11
  65. package/src/toolkit/config.mjs +2 -2
  66. package/{public/review.js → src/toolkit/diff-document.mjs} +137 -43
  67. package/src/toolkit/diff-inputs.mjs +97 -52
  68. package/src/toolkit/diff.mjs +198 -43
  69. package/src/toolkit/frame-declarations.mjs +36 -0
  70. package/src/toolkit/git-blobs.mjs +50 -0
  71. package/src/toolkit/impact-inputs.mjs +11 -19
  72. package/src/toolkit/impact-selection.mjs +27 -12
  73. package/src/toolkit/impact.mjs +49 -15
  74. package/src/toolkit/implementation-map.mjs +17 -6
  75. package/src/toolkit/input-generation.mjs +15 -0
  76. package/src/toolkit/inspect-output.mjs +1 -1
  77. package/src/toolkit/inspect.d.ts +9 -1
  78. package/src/toolkit/inspect.mjs +25 -1
  79. package/src/toolkit/motion-check.mjs +382 -0
  80. package/src/toolkit/motion-css.mjs +105 -0
  81. package/src/toolkit/motion-flows.mjs +95 -0
  82. package/src/toolkit/motion-impact.mjs +87 -0
  83. package/src/toolkit/motion-inventory.mjs +202 -0
  84. package/src/toolkit/motion-label.mjs +111 -0
  85. package/src/toolkit/motion-patterns.mjs +216 -0
  86. package/src/toolkit/motion-primitives.mjs +94 -0
  87. package/src/toolkit/motion-queries.mjs +169 -0
  88. package/src/toolkit/motion.mjs +300 -0
  89. package/src/toolkit/move-pairing.mjs +140 -0
  90. package/src/toolkit/owner.mjs +19 -6
  91. package/src/toolkit/play-endpoint.mjs +66 -0
  92. package/src/toolkit/project-index.mjs +4 -4
  93. package/src/toolkit/recent-structure.mjs +201 -0
  94. package/src/toolkit/results.mjs +3 -3
  95. package/src/toolkit/review-document.mjs +440 -0
  96. package/src/toolkit/review-embed-document.mjs +671 -0
  97. package/src/toolkit/review-filmstrip.mjs +76 -0
  98. package/src/toolkit/review-groups.mjs +29 -0
  99. package/src/toolkit/review-motion-card.mjs +51 -0
  100. package/src/toolkit/review-motion.mjs +159 -0
  101. package/src/toolkit/review-observation.mjs +131 -0
  102. package/src/toolkit/review-playback.js +123 -0
  103. package/src/toolkit/review-sheet.mjs +125 -0
  104. package/src/toolkit/review-specimens.mjs +60 -0
  105. package/src/toolkit/review.mjs +240 -0
  106. package/src/toolkit/runtime.mjs +8 -2
  107. package/src/toolkit/theme.mjs +16 -0
  108. package/src/viewer-cache.mjs +48 -12
  109. package/public/annotations.js +0 -816
  110. package/public/labels.js +0 -122
  111. package/src/annotations.mjs +0 -238
@@ -0,0 +1,76 @@
1
+ import { build } from 'esbuild';
2
+ import { createHash } from 'node:crypto';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { launch } from './browser.mjs';
5
+ import { canonicalBytes } from './impact-proof.mjs';
6
+
7
+ const hash = value => createHash('sha256').update(value).digest('hex');
8
+
9
+ export function assetStore() {
10
+ const assets = Object.create(null);
11
+ return { assets, put(value) {
12
+ const key = hash(typeof value === 'string' ? value : canonicalBytes(value));
13
+ assets[key] ??= value;
14
+ return key;
15
+ } };
16
+ }
17
+
18
+ export async function withFilmstrip(theme, store, work) {
19
+ const bundle = await build({ entryPoints: [fileURLToPath(new URL('./review-playback.js', import.meta.url))],
20
+ bundle: true, format: 'iife', globalName: 'reviewPlayback', minify: true, write: false });
21
+ const script = bundle.outputFiles[0].text.trim();
22
+ const environment = { colorScheme: theme, reducedMotion: 'no-preference', deviceScaleFactor: 1, locale: 'en-US', timezoneId: 'UTC' };
23
+ const browser = await launch();
24
+ try {
25
+ const page = await browser.newPage(environment);
26
+ await page.setContent('<style>*{margin:0}iframe{display:block;border:0}</style>');
27
+ await page.addScriptTag({ content: script });
28
+ await page.evaluate(async () => { window.stageFrame = await reviewPlayback.createStage(document.body); });
29
+ const capture = async () => {
30
+ const image = await page.locator('iframe').screenshot({ animations: 'disabled', caret: 'hide' });
31
+ return { image: store.put('data:image/png;base64,' + image.toString('base64')),
32
+ width: image.readUInt32BE(16), height: image.readUInt32BE(20) };
33
+ };
34
+ const endpoints = new Map(), samples = new Map(), loaded = new Set();
35
+ async function load(key) {
36
+ const endpoint = store.assets[key];
37
+ const entries = Object.fromEntries([key, endpoint.html, ...endpoint.styles].filter(k => !loaded.has(k)).map(k => [k, store.assets[k]]));
38
+ await page.evaluate(entries => Object.assign(window.motionAssets ??= {}, entries), entries);
39
+ Object.keys(entries).forEach(k => loaded.add(k));
40
+ }
41
+ async function endpoint(key) {
42
+ if (!endpoints.has(key)) {
43
+ await load(key);
44
+ const rows = await page.evaluate(async ({ key, theme }) => {
45
+ const scene = motionAssets[key];
46
+ const stage = await reviewPlayback.showEndpoint(stageFrame, scene, motionAssets, theme);
47
+ return reviewPlayback.identities(stage, scene.design);
48
+ }, { key, theme });
49
+ endpoints.set(key, { rows, ...await capture() });
50
+ }
51
+ return endpoints.get(key);
52
+ }
53
+ async function filmstrip(side) {
54
+ const key = hash(canonicalBytes([side.from, side.to, side.edge, environment, browser.version(), hash(script)]));
55
+ if (samples.has(key)) return samples.get(key);
56
+ const opening = await endpoint(side.from), final = await endpoint(side.to);
57
+ const info = await page.evaluate(async ({ side, theme }) => {
58
+ window.paint?.dispose();
59
+ window.paint = await reviewPlayback.prepare(stageFrame, side, motionAssets, theme);
60
+ return { duration: paint?.duration ?? 0, boundaries: paint?.boundaries ?? [], fallback: paint?.fallback };
61
+ }, { side, theme });
62
+ const { duration, boundaries, fallback } = info;
63
+ const sample = ({ image, width, height }, ms, state) => ({ image, width, height, ms, state });
64
+ const strip = [sample(opening, 0, 'From')];
65
+ for (const ms of [...new Set([duration / 2, ...boundaries])].filter(ms => ms > 0 && ms < duration).sort((a,b) => a-b)) {
66
+ await page.evaluate(p => paint.seek(p), ms / duration);
67
+ strip.push(sample(await capture(), ms, ''));
68
+ }
69
+ strip.push(sample(final, duration, 'To'));
70
+ const result = { duration, fallback, samples: strip };
71
+ samples.set(key, result);
72
+ return result;
73
+ }
74
+ return await work({ endpoint, filmstrip, script });
75
+ } finally { await browser.close(); }
76
+ }
@@ -0,0 +1,29 @@
1
+ /** Group inherited changes without copying their frame entries or image payloads. */
2
+ export function groupReview(review) {
3
+ const changed = review.sections?.changed ?? [];
4
+ const byCause = new Map();
5
+ let direct = 0;
6
+ for (const frame of changed) {
7
+ if (frame.change?.kind !== 'inherited') {
8
+ direct++;
9
+ continue;
10
+ }
11
+ const causes = [...new Set(frame.change.causes)].sort();
12
+ const key = JSON.stringify(causes);
13
+ if (!byCause.has(key)) byCause.set(key, { causes, frames: [] });
14
+ byCause.get(key).frames.push(frame);
15
+ }
16
+ const area = frame => Math.max(0, ...frame.themes.map(row => row.differentPixels ?? 0));
17
+ const groups = [...byCause.values()].map(group => {
18
+ // Preserve source order for equal areas, including the two middle members.
19
+ const ordered = group.frames.map(frame => ({ frame, area: area(frame) }))
20
+ .sort((a, b) => a.area - b.area);
21
+ const middle = Math.floor(ordered.length / 2);
22
+ const medianArea = ordered.length % 2 ? ordered[middle].area
23
+ : (ordered[middle - 1].area + ordered[middle].area) / 2;
24
+ const representative = group.frames.reduce((selected, frame) =>
25
+ Math.abs(area(frame) - medianArea) < Math.abs(area(selected) - medianArea) ? frame : selected);
26
+ return { ...group, representative, outliers: group.frames.filter(frame => area(frame) > 2 * medianArea), medianArea };
27
+ });
28
+ return { ...review, counts: { ...review.counts, direct, inherited: changed.length - direct }, groups };
29
+ }
@@ -0,0 +1,51 @@
1
+ import { escape } from './html.mjs';
2
+ const esc = value => escape(value ?? '');
3
+ const ref = r => r ? r.source + '#' + r.frame : 'Unknown endpoint';
4
+ const target = t => t?.anchor ?? (t?.part ? t.part + (t.key == null ? '' : ' · ' + t.key) : 'frame');
5
+ const focus = f => typeof f === 'object' ? target(f?.target) : ({
6
+ 'restore-trigger': 'restore trigger, or frame when unavailable', preserve: 'preserve focus, or frame when unavailable'
7
+ }[f] ?? f);
8
+
9
+ export function motionCard(card, index, assets) {
10
+ const sheet = !!assets;
11
+ const sideHtml = name => {
12
+ const side = card[name];
13
+ if (!side) return '';
14
+ const edge = side.edge;
15
+ const label = name === 'before' ? 'Before' : 'After';
16
+ const fallback = [side.fallback, ...(edge.unsupported ?? []).map(u => u.effect + ' · ' + u.reason)].filter(Boolean);
17
+ return `<section class="motion-side"><h4>${label} · ${esc(edge.label ?? card.id)}</h4>
18
+ <div>${esc(edge.gesture ?? edge.trigger?.on)} · ${esc(target(edge.trigger?.target))} · ${edge.proposed ? 'Proposed · ' + esc(edge.proposed) : 'Current'}</div>
19
+ <code>${esc(ref(edge.from))} → ${esc(ref(edge.to))}</code>
20
+ <div>Focus · ${esc(focus(edge.focus))}</div>
21
+ ${side.error ? '<p role="alert">Partial · ' + esc(side.error) + '</p>' : `<div>${esc(edge.duration)} · ${side.duration} ms</div>
22
+ ${fallback.length ? '<p>' + esc(fallback.join(' · ')) + '</p>' : ''}
23
+ <div class="filmstrip">${side.samples.map(s => `<figure><img ${sheet ? 'src="' + assets[s.image] + '"' : 'data-image="' + s.image + '"'} alt="${label} at ${s.ms} ms"><figcaption>${s.state} ${s.ms} ms</figcaption></figure>`).join('')}</div>
24
+ ${sheet ? '' : `<div class="motion-controls"><button data-play="${name}">Play ${name}</button><button data-preview="${name}">Preview ${name}</button><output data-elapsed="${name}">0 ms</output></div>`}`}
25
+ </section>`;
26
+ };
27
+ const control = !sheet && (card.before?.samples || card.after?.samples);
28
+ return `<article class="frame-card motion-card" data-motion="${index}" data-edge="${esc(card.id)}">
29
+ <header class="card-head"><h3>${esc(card.after?.edge.label ?? card.before?.edge.label ?? card.id)}</h3><span>${esc(card.kind)}</span></header>
30
+ <div class="motion-content"><code>${esc(card.id)}</code> · ${esc(card.reasons.join(' · '))}
31
+ <div class="motion-sides">${sideHtml('before')}${sideHtml('after')}</div>
32
+ ${control ? `<label class="motion-controls">Seek both sides <input type="range" min="0" max="100" value="0"></label>
33
+ <div class="motion-stage"><img class="motion-cover" hidden alt="Source endpoint"></div><div role="status"></div>` : ''}</div></article>`;
34
+ }
35
+
36
+ export const motionStyle = `
37
+ .motion-card code,.motion-card h4 {overflow-wrap:anywhere}
38
+ .motion-content {padding:12px}
39
+ .motion-sides {display:grid;grid-template-columns:repeat(auto-fit,minmax(min(270px,100%),1fr));gap:12px}
40
+ .motion-side {min-width:0}
41
+ .motion-card h4 {margin:10px 0 4px}
42
+ .filmstrip {display:flex;flex-wrap:wrap;gap:6px;margin:8px 0}
43
+ .filmstrip figure {min-width:0;flex:1 1 70px;margin:0}
44
+ .filmstrip img {width:100%;height:80px;object-fit:contain}
45
+ .filmstrip figcaption {font-size:11px;text-align:center}
46
+ .motion-controls {display:flex;align-items:center;flex-wrap:wrap;gap:8px;margin:8px 0}
47
+ .motion-controls button {border:1px solid var(--line);border-radius:6px;background:var(--panel);color:inherit;padding:4px 9px;cursor:pointer}
48
+ .motion-stage {position:relative;overflow:hidden}
49
+ .motion-stage iframe,.motion-cover {position:absolute;inset:0;border:0;transform-origin:top left;pointer-events:none}
50
+ .motion-cover {z-index:1}
51
+ `;
@@ -0,0 +1,159 @@
1
+ import { canonicalBytes } from './impact-proof.mjs';
2
+ import { relative } from './project.mjs';
3
+ import { parseTokens } from './tokens.mjs';
4
+ import { playbackEdge } from './play-endpoint.mjs';
5
+ import { timingRefs } from './motion.mjs';
6
+ import { assetStore, withFilmstrip } from './review-filmstrip.mjs';
7
+
8
+ const equal = (a, b) => canonicalBytes(a) === canonicalBytes(b);
9
+ const sides = ['before', 'after'];
10
+ const refKey = ref => JSON.stringify([ref.source, ref.frame]);
11
+
12
+ // Impact owns the per-revision indexes. Preserve incident IDs even when a failed
13
+ // source was removed from the static comparison inventory on both sides.
14
+ export function reviewEdgeCandidates({ views, motionIds, data, assessments }, theme) {
15
+ const ids = new Set(motionIds);
16
+ const failed = new Set(data.failures.map(f => f.source));
17
+ for (const view of views) for (const { edge, valid } of view.motion.records) {
18
+ if (!valid) continue;
19
+ for (const ref of [edge.from, edge.to]) {
20
+ if (failed.has(ref.source)) ids.add(edge.id);
21
+ // Unassessed frames can change even without a lexical impact seed.
22
+ const assessment = assessments.get(JSON.stringify([ref.source, ref.frame, theme]));
23
+ if (assessment?.disposition !== 'render') continue;
24
+ const [a, b] = views.map(v => v.built.get(ref.source));
25
+ const [first, last] = [a, b].map(build => build?.frames.find(f => f.name === ref.frame));
26
+ if (a?.css !== b?.css || first?.html !== last?.html || first?.width !== last?.width ||
27
+ first?.height !== last?.height || first?.proposed !== last?.proposed) ids.add(edge.id);
28
+ }
29
+ }
30
+ return [...ids].map(id => views.map(v => v.motion.ids.get(id)?.[0]));
31
+ }
32
+
33
+ function revision(view, side, store, failures, theme) {
34
+ const tokens = parseTokens(view.tokenBytes.toString()), design = relative(view.config, view.config.design);
35
+ const cache = new Map();
36
+ const buildFailures = new Map(failures.filter(f => f.side === side).map(f => [f.source, f.message]));
37
+ async function endpoint(ref) {
38
+ const key = refKey(ref);
39
+ if (cache.has(key)) return cache.get(key);
40
+ if (buildFailures.has(ref.source)) throw Error(buildFailures.get(ref.source));
41
+ const built = view.built.get(ref.source) ?? await view.index.materialize(ref.source);
42
+ const frame = built.frames.find(f => f.name === ref.frame);
43
+ if (!frame) throw Error('Missing frame ' + ref.frame);
44
+ const result = { frame, hash: store.put({ frame: ref.frame, design, width: frame.width, height: frame.height,
45
+ html: store.put(frame.html), styles: [built.cssBeforeTokens, built.tokenCss, built.cssAfterTokens].map(store.put) }) };
46
+ cache.set(key, result);
47
+ return result;
48
+ }
49
+ return async record => {
50
+ if (!record) return;
51
+ const { edge, owner } = record;
52
+ let source = owner;
53
+ try {
54
+ if (!record.valid) throw Error('Invalid transition declaration: ' + edge.id);
55
+ source = edge.from.source;
56
+ const from = await endpoint(edge.from);
57
+ source = edge.to.source;
58
+ const to = await endpoint(edge.to);
59
+ source = owner;
60
+ const resolved = playbackEdge(edge, from.frame, tokens, theme, design);
61
+ const timings = Object.fromEntries(timingRefs(edge).map(({ name, pointer }) => [name, resolved.timings[pointer]]));
62
+ return { from: from.hash, to: to.hash, edge: resolved,
63
+ endpointStatus: [from.frame.proposed, to.frame.proposed].map(v => v ?? 'current'), timings };
64
+ } catch (error) {
65
+ if (!failures.some(f => f.source === source && f.side === side))
66
+ failures.push({ source, side, code: 'SOURCE_BUILD_FAILED', message: error.message });
67
+ return { edge, error: side + ' · ' + source + ' · ' + error.message };
68
+ }
69
+ };
70
+ }
71
+
72
+ export async function reviewMotion(session, candidates, model, comparisons, theme) {
73
+ if (!candidates.length) return;
74
+ const store = assetStore(), failures = model.failures;
75
+ const readers = session.views.map((v, i) => revision(v, i === 0 ? 'base' : 'current', store, failures, theme));
76
+ const moves = new Map([...model.movePairs, ...comparisons.filter(r => r.previousSource)].map(({before, after}) =>
77
+ [refKey(before), {source: after.source, frame: after.frame}]));
78
+ const relocate = ref => ref && (moves.get(refKey(ref)) ?? ref);
79
+ // Qualify part selectors by a relocated source only when established moves
80
+ // agree on its new owner. Frame references always use their exact pair.
81
+ const owners = new Map();
82
+ for (const [ref, to] of moves) {
83
+ const [source] = JSON.parse(ref);
84
+ if (!owners.has(source)) owners.set(source, new Set());
85
+ owners.get(source).add(to.source);
86
+ }
87
+ const relocatePart = part => {
88
+ const [source, name] = part.split('#');
89
+ const paths = owners.get(source);
90
+ return paths?.size === 1 ? [...paths][0] + '#' + name : part;
91
+ };
92
+ const normalize = edge => JSON.parse(JSON.stringify({ ...edge, from: relocate(edge.from), to: relocate(edge.to) },
93
+ (key, value) => key === 'part' && typeof value === 'string' ? relocatePart(value) : value));
94
+ const pending = [];
95
+ for (const records of candidates) {
96
+ const versions = await Promise.all(records.map((r, i) => readers[i](r)));
97
+ const [a, b] = versions;
98
+ if (a && b && !a.error && !b.error && a.from === b.from && a.to === b.to &&
99
+ equal(a.endpointStatus, b.endpointStatus) && equal(a.edge, b.edge)) continue;
100
+ pending.push({records, versions});
101
+ }
102
+ if (!pending.length) return;
103
+ const cards = [];
104
+ return withFilmstrip(theme, store, async renderer => {
105
+ for (const {records, versions} of pending) {
106
+ const [old, next] = records.map(r => r?.edge);
107
+ const reasons = [], kind = !old ? 'added' : !next ? 'removed' : 'changed';
108
+ const former = old && normalize(old);
109
+ if (!equal(former, next)) reasons.push('Direct declaration');
110
+ const [a, b] = versions;
111
+ if (a?.error || b?.error) reasons.push('Incomplete endpoint');
112
+ if (a?.timings && b?.timings) {
113
+ const changed = Object.keys(a.timings).filter(k => k in b.timings && a.timings[k] !== b.timings[k]).sort();
114
+ if (changed.length) reasons.push('Inherited timing · ' + changed.join(', '));
115
+ if (equal(former.trigger, next.trigger) && a.edge.gesture !== b.edge.gesture) reasons.push('Inherited trigger name');
116
+ if (!equal(a.endpointStatus, b.endpointStatus)) reasons.push('Inherited endpoint status');
117
+ for (const end of ['from', 'to']) {
118
+ if (a[end] === b[end] || !equal(relocate(old[end]), next[end])) continue;
119
+ const first = await renderer.endpoint(a[end]), last = await renderer.endpoint(b[end]);
120
+ const rows = first.rows.map(row => ({
121
+ ...row, parts: row.parts.map(relocatePart),
122
+ keys: row.keys.map(key => key.owner ? { ...key, owner: relocatePart(key.owner) } : key)
123
+ }));
124
+ if (first.image !== last.image || !equal(rows, last.rows)) reasons.push('Inherited ' + end + ' endpoint');
125
+ }
126
+ }
127
+ if (!reasons.length) continue;
128
+ const record = records[1] ?? records[0];
129
+ const card = { id: record.edge.id, owner: record.owner, kind, reasons };
130
+ for (const [i, version] of versions.entries()) {
131
+ if (!version) continue;
132
+ if (!version.error) {
133
+ try { Object.assign(version, await renderer.filmstrip(version)); }
134
+ catch (error) {
135
+ const side = i === 0 ? 'base' : 'current', source = version.edge.from.source;
136
+ version.error = side + ' · ' + source + ' · ' + error.message;
137
+ failures.push({ source, side, code: 'SOURCE_BUILD_FAILED', message: error.message });
138
+ }
139
+ }
140
+ card[sides[i]] = version;
141
+ }
142
+ cards.push(card);
143
+ }
144
+ if (!cards.length) return;
145
+ cards.sort((a, b) => a.owner.localeCompare(b.owner,'en') || a.id.localeCompare(b.id,'en'));
146
+ // Keep only assets referenced by final cards. Candidate observations are disposable.
147
+ const live = new Set();
148
+ for (const card of cards) for (const name of sides) {
149
+ const side = card[name];
150
+ if (!side?.samples) continue;
151
+ for (const key of [side.from, side.to]) {
152
+ const endpoint = store.assets[key];
153
+ for (const id of [key, endpoint.html, ...endpoint.styles]) live.add(id);
154
+ }
155
+ for (const sample of side.samples) live.add(sample.image);
156
+ }
157
+ return { cards, assets: Object.fromEntries([...live].map(k => [k, store.assets[k]])), theme, script: renderer.script };
158
+ });
159
+ }
@@ -0,0 +1,131 @@
1
+ /** Collect post-layout paint inputs in the design document. Runs inside Chromium. */
2
+ export async function observeFrame() {
3
+ await document.fonts.ready;
4
+ await Promise.allSettled([...document.images].map(image => image.decode()));
5
+ const root = document.querySelector('[data-adg-frame]');
6
+ const { relativeBox, textRects, reads } = globalThis.__adgFramePrimitives;
7
+ const { style: styleFor, rect: rectFor } = reads();
8
+ const origin = rectFor(root), paints = [], uncertain = new Set();
9
+ const box = rect => relativeBox(rect, origin);
10
+ const onscreen = rect => rect.width > 0 && rect.height > 0 && rect.right > origin.left && rect.left < origin.right &&
11
+ rect.bottom > origin.top && rect.top < origin.bottom;
12
+ const typography = ['color', 'font-family', 'font-size', 'font-style', 'font-weight', 'font-stretch', 'font-feature-settings',
13
+ 'font-variation-settings', 'font-optical-sizing', 'font-kerning', 'font-variant', 'text-transform', 'text-shadow',
14
+ 'letter-spacing', 'word-spacing', 'text-decoration-line', 'text-decoration-color', 'text-decoration-style',
15
+ 'text-decoration-thickness', 'text-underline-offset', 'text-overflow', 'direction', 'writing-mode',
16
+ '-webkit-text-fill-color', '-webkit-text-stroke-width', '-webkit-text-stroke-color'];
17
+ const composition = ['transform', 'opacity', 'z-index', 'overflow-x', 'overflow-y', 'filter', 'backdrop-filter',
18
+ 'mix-blend-mode', 'clip-path', 'mask-image', 'perspective', 'isolation', 'object-fit', 'object-position'];
19
+ const svgPaint = ['fill', 'fill-opacity', 'fill-rule', 'stroke', 'stroke-width', 'stroke-opacity', 'stroke-linecap',
20
+ 'stroke-linejoin', 'stroke-miterlimit', 'stroke-dasharray', 'stroke-dashoffset', 'paint-order', 'vector-effect',
21
+ 'opacity', 'transform', 'color', 'visibility', 'display', 'stop-color', 'stop-opacity', 'flood-color', 'flood-opacity',
22
+ 'clip-path', 'mask-image', 'filter', 'x', 'y', 'cx', 'cy', 'r', 'rx', 'ry', 'd'];
23
+ const properties = (style, names) => Object.fromEntries(names.map(name => [name, style.getPropertyValue(name)]));
24
+ const transparent = color => color === 'rgba(0, 0, 0, 0)' || color === 'transparent';
25
+ const sides = ['top', 'right', 'bottom', 'left'];
26
+ const radii = ['border-top-left-radius', 'border-top-right-radius', 'border-bottom-right-radius', 'border-bottom-left-radius'];
27
+ function colorsAndBorders(style) {
28
+ const result = {};
29
+ if (!transparent(style.backgroundColor)) result['background-color'] = style.backgroundColor;
30
+ if (style.backgroundImage !== 'none') Object.assign(result, properties(style, ['background-image', 'background-size',
31
+ 'background-position', 'background-repeat', 'background-origin', 'background-clip', 'background-blend-mode', 'background-attachment']));
32
+ for (const side of sides) {
33
+ const prefix = `border-${side}`;
34
+ const width = style.getPropertyValue(`${prefix}-width`);
35
+ const color = style.getPropertyValue(`${prefix}-color`);
36
+ if (parseFloat(width) && !transparent(color)) {
37
+ result[prefix] = [width, style.getPropertyValue(`${prefix}-style`), color].join(' ');
38
+ }
39
+ }
40
+ if (style.boxShadow !== 'none') result['box-shadow'] = style.boxShadow;
41
+ if (style.outlineStyle !== 'none' && parseFloat(style.outlineWidth) && !transparent(style.outlineColor)) {
42
+ Object.assign(result, properties(style, ['outline-width', 'outline-style', 'outline-color', 'outline-offset']));
43
+ }
44
+ if (Object.keys(result).length) Object.assign(result, properties(style, radii));
45
+ return result;
46
+ }
47
+
48
+ function flags(style, node) {
49
+ for (const property of ['filter', 'backdrop-filter', 'mix-blend-mode', 'clip-path', 'mask-image', 'border-image-source', 'perspective']) {
50
+ const value = style.getPropertyValue(property);
51
+ if (value && !['none', 'normal'].includes(value)) uncertain.add(property);
52
+ }
53
+ if (style.backgroundImage.includes('url(') && !style.backgroundImage.includes('data:')) uncertain.add('external background');
54
+ if (style.clip !== 'auto' || style.backgroundClip === 'text' || style.contentVisibility !== 'visible') uncertain.add('clipping');
55
+ if (node.matches('canvas,video,iframe,object,embed,foreignObject,svg use')) uncertain.add(node.localName);
56
+ }
57
+
58
+ function add(kind, rect, values) {
59
+ paints.push({ kind, box: box(rect), values });
60
+ }
61
+
62
+ function svg(node) {
63
+ const children = [node, ...node.querySelectorAll('*')];
64
+ const ids = new Map(children.filter(child => child.id).map((child, index) => [child.id, `ref-${index}`]));
65
+ const normalize = text => text.replace(/#([^\s)'";]+)/g, (raw, id) => ids.has(id) ? `#${ids.get(id)}` : raw);
66
+ return children.map(child => {
67
+ const style = styleFor(child);
68
+ flags(style, child);
69
+ const attrs = [...child.attributes].filter(({ name }) => name !== 'class' && name !== 'style' && name !== 'id' &&
70
+ name !== 'role' && !name.startsWith('data-') && !name.startsWith('aria-'));
71
+ const attributes = Object.fromEntries(attrs.map(({ name, value }) => [name, normalize(value)]).sort(([a], [b]) => a.localeCompare(b)));
72
+ const text = /^(text|tspan|textPath)$/.test(child.localName) ? child.textContent : undefined;
73
+ const appearance = Object.fromEntries(svgPaint.map(name => [name, normalize(style.getPropertyValue(name))]));
74
+ return [child.localName, attributes, appearance, text];
75
+ });
76
+ }
77
+
78
+ function visit(node) {
79
+ const style = styleFor(node);
80
+ if (style.display === 'none' || style.opacity === '0') return;
81
+ if (style.contentVisibility === 'hidden') { uncertain.add('clipping'); return; }
82
+ const rect = rectFor(node);
83
+ const visible = style.visibility === 'visible' && onscreen(rect);
84
+ if (!visible && style.visibility === 'visible' && (style.boxShadow !== 'none' || style.outlineStyle !== 'none' || style.filter !== 'none')) {
85
+ uncertain.add('off-frame paint');
86
+ }
87
+ if (visible) {
88
+ flags(style, node);
89
+ const paint = colorsAndBorders(style);
90
+ if (Object.keys(paint).length) add('paint', rect, paint);
91
+ if (node instanceof SVGSVGElement) {
92
+ add('svg', rect, { vector: svg(node), ...properties(style, composition) });
93
+ return;
94
+ }
95
+ if (node instanceof HTMLImageElement) {
96
+ const content = node.currentSrc || node.src;
97
+ if (content && !content.startsWith('data:')) uncertain.add('external image');
98
+ if (!node.complete || !node.naturalWidth) uncertain.add('image decode');
99
+ add('image', rect, { content, intrinsic: [node.naturalWidth, node.naturalHeight], ...properties(style, composition) });
100
+ }
101
+ if (node.matches('input,textarea,select,progress,meter')) {
102
+ uncertain.add('native control');
103
+ add('control', rect, { type: node.type, value: node.type === 'password' ? '' : node.value,
104
+ placeholder: node.placeholder, checked: node.checked, ...properties(style, typography) });
105
+ }
106
+ if (style.transform !== 'none' || style.opacity !== '1' || style.zIndex !== 'auto' || style.isolation === 'isolate' ||
107
+ style.overflowX !== 'visible' || style.overflowY !== 'visible' || style.filter !== 'none' || style.clipPath !== 'none') {
108
+ add('compositing', rect, { ...properties(style, composition), ...properties(style, radii) });
109
+ }
110
+ for (const pseudo of ['::before', '::after', '::marker']) {
111
+ const appearance = getComputedStyle(node, pseudo);
112
+ if (appearance.content === 'none' || appearance.content === 'normal') continue;
113
+ if (appearance.display === 'none') continue;
114
+ flags(appearance, node);
115
+ uncertain.add('generated content');
116
+ add(pseudo, rect, { content: appearance.content, ...colorsAndBorders(appearance), ...properties(appearance, typography),
117
+ ...properties(appearance, ['position', 'width', 'height', 'inset', 'transform', 'opacity']) });
118
+ }
119
+ }
120
+ for (const child of node.childNodes) {
121
+ if (child.nodeType === Node.ELEMENT_NODE) visit(child);
122
+ if (child.nodeType === Node.TEXT_NODE && child.textContent.trim() && style.visibility === 'visible') {
123
+ const lines = textRects(child).rects.filter(onscreen);
124
+ if (lines.length) add('text', lines[0], { text: child.textContent, lines: lines.map(box), ...properties(style, typography) });
125
+ }
126
+ }
127
+ }
128
+ if ([...document.styleSheets].some(sheet => [...sheet.cssRules].some(rule => rule instanceof CSSFontFaceRule))) uncertain.add('embedded or external font');
129
+ visit(root);
130
+ return { size: { width: origin.width, height: origin.height }, paints, uncertain: [...uncertain].sort() };
131
+ }
@@ -0,0 +1,123 @@
1
+ // Bundled into the standalone report and used by the filmstrip renderer.
2
+ import { createStage, mountScene, observeScene, readySceneResources } from '../../public/motion-scene.js';
3
+ import { preparePaint, playTimeline } from '../../public/motion-paint.js';
4
+
5
+ export { createStage };
6
+
7
+ export async function showEndpoint(frame, endpoint, assets, theme) {
8
+ const doc = frame.contentDocument;
9
+ const size = (width, height) => Object.assign(frame.style, { width: width + 'px', height: height + 'px' });
10
+ size(endpoint.width || 1600, endpoint.height || 1200);
11
+ const stage = await mountScene(doc, {
12
+ ...endpoint, html: assets[endpoint.html], css: endpoint.styles.map(key => assets[key]).join('')
13
+ }, theme);
14
+ const rect = stage.getBoundingClientRect();
15
+ size(endpoint.width || Math.max(1, Math.ceil(rect.width)), endpoint.height || Math.max(1, Math.ceil(rect.height)));
16
+ await readySceneResources(doc);
17
+ return stage;
18
+ }
19
+
20
+ export async function prepare(frame, side, assets, theme) {
21
+ const from = assets[side.from], to = assets[side.to];
22
+ const origin = await showEndpoint(frame, from, assets, theme);
23
+ const first = side.edge.unsupported ? null : observeScene(origin, from.design, true);
24
+ const stage = await showEndpoint(frame, to, assets, theme);
25
+ return first ? preparePaint(stage, first, observeScene(stage, to.design, true), side.edge) : null;
26
+ }
27
+
28
+ export function identities(stage, design) {
29
+ return observeScene(stage, design).map(({ box, parts, keys, anchor, parent }) => ({
30
+ box, parts, anchor, parent,
31
+ keys: keys.map(({ owner, ...key }) => owner
32
+ ? { ...key, owner: [design, owner.source].filter(Boolean).join('/') + '#' + owner.export }
33
+ : key)
34
+ }));
35
+ }
36
+
37
+ export function mountReport() {
38
+ const data = JSON.parse(document.querySelector('#motion-data').textContent);
39
+ let active, pending = Promise.resolve(), generation = 0;
40
+ async function activate(card, sideName, play, ticket) {
41
+ if (ticket !== generation) return;
42
+ active?.stop?.();
43
+ active?.paint?.dispose();
44
+ active?.frame?.remove();
45
+ if (active) {
46
+ active.card.querySelector('.motion-cover').hidden = true;
47
+ active.card.querySelector('.motion-stage').style.height = '';
48
+ active.card.querySelector('[role=status]').textContent = '';
49
+ }
50
+ active?.fit?.disconnect();
51
+ active = null;
52
+ const side = data.cards[card.dataset.motion][sideName];
53
+ const host = card.querySelector('.motion-stage');
54
+ const frame = await createStage(host);
55
+ frame.inert = true;
56
+ if (ticket !== generation) { frame.remove(); return; }
57
+ const state = active = { frame, sideName, card };
58
+ card.querySelector('[role=status]').textContent = sideName === 'before' ? 'Previewing before' : 'Previewing after';
59
+ // A new selection can arrive while the sandbox waits for fonts.
60
+ const paint = await prepare(frame, side, data.assets, data.theme);
61
+ if (ticket !== generation) { paint?.dispose(); return; }
62
+ state.paint = paint;
63
+ const endWidth = frame.offsetWidth, endHeight = frame.offsetHeight;
64
+ const cover = card.querySelector('.motion-cover');
65
+ const first = side.samples[0];
66
+ cover.src = data.assets[first.image];
67
+ const draw = p => {
68
+ const atStart = p === 0 || (!side.duration && p < 1);
69
+ cover.hidden = !atStart;
70
+ frame.style.visibility = atStart ? 'hidden' : 'visible';
71
+ paint?.seek(p);
72
+ const w = atStart ? first.width : endWidth, h = atStart ? first.height : endHeight;
73
+ const scale = Math.min(1, host.clientWidth / w, 400 / h);
74
+ host.style.height = Math.ceil(h * scale) + 'px';
75
+ frame.style.transform = 'scale(' + scale + ')';
76
+ cover.style.width = w * scale + 'px';
77
+ };
78
+ state.draw = draw;
79
+ const slider = card.querySelector('input');
80
+
81
+ state.fit = new ResizeObserver(() => draw(Number(card.dataset[sideName] || 0)));
82
+ state.fit.observe(host.parentElement);
83
+ function advance(p) {
84
+ card.dataset[sideName] = p;
85
+ card.querySelector('[data-elapsed="' + sideName + '"]').value = elapsed(side.duration * p);
86
+ draw(p);
87
+ }
88
+ draw(Number(card.dataset[sideName] || 0));
89
+ if (play) {
90
+ advance(0);
91
+ if (side.duration) state.stop = playTimeline(side.duration, 0, 1, advance, () => {});
92
+ else advance(1);
93
+ }
94
+ slider.setAttribute('aria-valuetext', slider.value + '%');
95
+ }
96
+ function elapsed(value) { return Number(value.toFixed(2)) + ' ms'; }
97
+ for (const card of document.querySelectorAll('[data-motion]')) {
98
+ const model = data.cards[card.dataset.motion];
99
+ for (const image of card.querySelectorAll('[data-image]')) image.src = data.assets[image.dataset.image];
100
+ const start = (side, play) => {
101
+ const ticket = ++generation;
102
+ pending = pending.then(() => activate(card, side, play, ticket)).catch(err => {
103
+ if (ticket === generation) card.querySelector('[role=status]').textContent = err.message;
104
+ });
105
+ };
106
+ for (const button of card.querySelectorAll('[data-play],[data-preview]')) {
107
+ button.onclick = () => start(button.dataset.play ?? button.dataset.preview, button.hasAttribute('data-play'));
108
+ }
109
+ if (!card.querySelector('input')) continue;
110
+ card.querySelector('input').oninput = event => {
111
+ const p = event.target.valueAsNumber / 100;
112
+ for (const name of ['before', 'after']) {
113
+ const side = model[name];
114
+ if (!side?.samples) continue;
115
+ card.dataset[name] = p;
116
+ card.querySelector('[data-elapsed="' + name + '"]').value = elapsed(side.duration * p);
117
+ }
118
+ event.target.setAttribute('aria-valuetext', event.target.value + '%');
119
+ if (active?.card === card && active.draw) { active.stop?.(); active.draw(p); }
120
+ else start(model.after?.samples ? 'after' : 'before', false);
121
+ };
122
+ }
123
+ }