@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,382 @@
1
+ import {matchRoots,candidates,chain} from '../../public/motion-identity.js';
2
+ import { flowLayout } from '../../public/motion-flow.js';
3
+ import { frameKey } from './motion-flows.mjs';
4
+ import { nativeTextEntry } from '../../public/motion-scene.js';
5
+ export {instanceKeyMatches} from '../../public/motion-identity.js';
6
+ import path from 'node:path';
7
+ import { loadFrame } from './browser.mjs';
8
+ import { buildSource } from './build.mjs';
9
+ import { listSources, relative, loadTokens, sourceDirectories, isFeatureInternal } from './project.mjs';
10
+ import { resolveMotionToken, timingRefs } from './motion.mjs';
11
+
12
+ // Runs inside the frame observation page. Indexes are local to this one observation.
13
+ function observe({ design, nativeTextEntry }) {
14
+ const shell = document.querySelector('[data-adg-frame]').firstElementChild;
15
+ const elements = [shell, ...shell.querySelectorAll('*')],
16
+ indexes = new Map(elements.map((el, i) => [el, i]));
17
+ function hit(el, rect) {
18
+ let left = Math.max(0, rect.left),
19
+ top = Math.max(0, rect.top),
20
+ right = Math.min(innerWidth, rect.right),
21
+ bottom = Math.min(innerHeight, rect.bottom);
22
+ for (let p = el.parentElement; p; p = p.parentElement) {
23
+ const style = getComputedStyle(p),
24
+ bounds = p.getBoundingClientRect();
25
+ if (/hidden|clip|auto|scroll/.test(style.overflowX)) {
26
+ left = Math.max(left, bounds.left);
27
+ right = Math.min(right, bounds.right);
28
+ }
29
+ if (/hidden|clip|auto|scroll/.test(style.overflowY)) {
30
+ top = Math.max(top, bounds.top);
31
+ bottom = Math.min(bottom, bounds.bottom);
32
+ }
33
+ }
34
+ if (right <= left || bottom <= top) return false;
35
+ return [0.5, 0.01, 0.99].some((x) =>
36
+ [0.5, 0.01, 0.99].some((y) =>
37
+ el.contains(document.elementFromPoint(left + (right - left) * x, top + (bottom - top) * y))
38
+ )
39
+ );
40
+ }
41
+ const rows = elements.map((el, i) => {
42
+ const parts = JSON.parse(el.dataset.adgOwners ?? '[]').map((o) => design + '/' + o.source + '#' + o.export);
43
+ const keys = JSON.parse(el.dataset.adgKeys ?? '[]');
44
+ const rect = el.getBoundingClientRect();
45
+ let limitation=null;
46
+ for(let p=el;p && !limitation;p=p.parentElement){
47
+ const style=getComputedStyle(p),b=p.getBoundingClientRect();
48
+ if(style.transform!=='none' && !Number.isFinite(new DOMMatrix(style.transform).inverse().a))limitation='non_invertible';
49
+ else if(style.clipPath!=='none' || p!==el && (
50
+ /hidden|clip|auto|scroll/.test(style.overflowX) && (rect.left<b.left || rect.right>b.right) ||
51
+ /hidden|clip|auto|scroll/.test(style.overflowY) && (rect.top<b.top || rect.bottom>b.bottom)))limitation='clipped';
52
+ }
53
+ const visible =
54
+ rect.width > 0 &&
55
+ rect.height > 0 &&
56
+ el.checkVisibility({ opacityProperty: true, visibilityProperty: true }) &&
57
+ el.getClientRects().length > 0;
58
+ return {
59
+ i,
60
+ parent: indexes.get(el.parentElement) ?? -1,
61
+ parts,
62
+ keys,
63
+ anchor: el.dataset.adgId ?? null,
64
+ box: [rect.x, rect.y, rect.width, rect.height],
65
+ limitation,
66
+ exposed: visible && !el.closest('[inert],[aria-hidden="true"]'),
67
+ pointer: visible && hit(el, rect),
68
+ disabled: el.matches(':disabled,[aria-disabled="true"]'),
69
+ textEntry: !el.readOnly && (el.matches(nativeTextEntry) || (el.hasAttribute('contenteditable') && el.isContentEditable)),
70
+ focusable: false,
71
+ keyboard: false
72
+ };
73
+ });
74
+ // Ask the browser so native controls such as summary and tabindex=-1 behave as authored.
75
+ for (const row of rows) {
76
+ const el = elements[row.i];
77
+ if (row.exposed && !row.disabled && (el.tabIndex >= 0 || el.hasAttribute('tabindex') || el.isContentEditable)) {
78
+ el.focus({ preventScroll: true });
79
+ row.focusable = document.activeElement === el;
80
+ if (row.focusable) el.blur();
81
+ }
82
+ }
83
+ for (const row of rows.toReversed()) {
84
+ row.keyboard ||= row.focusable;
85
+ if (row.parent >= 0 && row.keyboard) rows[row.parent].keyboard = true;
86
+ }
87
+ return rows;
88
+ }
89
+
90
+ export function motionEvaluator(
91
+ config,
92
+ { getPage, getBuild, bindings = [], hasMap = false, flows = new Map(), themes = ['light', 'dark'] } = {}
93
+ ) {
94
+ const builds = new Map(),
95
+ observations = new Map(),
96
+ dispatch = new Map(),
97
+ layouts = new Map();
98
+ const layers = sourceDirectories(config).filter((s) => s !== 'studies'),
99
+ top = layers.at(-1);
100
+ const inventory = new Set(listSources(config.design, sourceDirectories(config)).map((f) => relative(config, f)));
101
+ const tokens = loadTokens(config);
102
+ async function frameAt(ref) {
103
+ if (!inventory.has(ref.source)) return;
104
+ if (!builds.has(ref.source))
105
+ builds.set(
106
+ ref.source,
107
+ getBuild?.(ref.source) ?? buildSource(config, path.join(config.root, ref.source), { write: false })
108
+ );
109
+ return (await builds.get(ref.source)).frames.find((f) => f.name === ref.frame);
110
+ }
111
+ async function observeFrame(ref, frame, theme) {
112
+ const key = JSON.stringify([ref.source, ref.frame, theme]);
113
+ if (!observations.has(key)) {
114
+ const page = await getPage();
115
+ const { x, y, width, height } = await loadFrame(page, frame, theme);
116
+ const rows = await page.evaluate(observe, { design: relative(config, config.design), nativeTextEntry });
117
+ observations.set(key, { box: [x, y, width, height], rows });
118
+ }
119
+ return observations.get(key);
120
+ }
121
+ async function layoutFor(flow, theme) {
122
+ if (!layouts.has(flow)) layouts.set(flow, new Map());
123
+ const byTheme = layouts.get(flow);
124
+ if (!byTheme.has(theme)) {
125
+ const frames = [];
126
+ for (const ref of flow.frames) {
127
+ const frame = await frameAt(ref);
128
+ if (!frame) break;
129
+ frames.push(await observeFrame(ref, frame, theme));
130
+ }
131
+ byTheme.set(theme, frames.length === flow.frames.length ? flowLayout(flow, frames) : null);
132
+ }
133
+ return byTheme.get(theme);
134
+ }
135
+ return async function evaluate(record) {
136
+ const { edge: e, owner } = record,
137
+ problems = new Map(),
138
+ detail = {
139
+ edge: e,
140
+ themes: {},
141
+ bound: bindings.some((b) => b.active && b.design.source === owner && b.design.transition === e.id)
142
+ };
143
+ function issue(code, at, message, theme = null, warning = false) {
144
+ const pointer = record.pointer + at,
145
+ key = JSON.stringify([code, pointer, message]);
146
+ const found = problems.get(key);
147
+ if (found) {
148
+ if (found.theme !== theme) found.theme = null;
149
+ return;
150
+ }
151
+ problems.set(key, {
152
+ code,
153
+ pointer,
154
+ source: record.source,
155
+ transition: e.id,
156
+ frame: e.from.frame,
157
+ theme,
158
+ warning,
159
+ message,
160
+ ...(record.locations[pointer] ?? record.locations[record.pointer])
161
+ });
162
+ }
163
+ const designPath = (ref) => path.relative(config.design, path.join(config.root, ref)).split(path.sep).join('/');
164
+ const layer = (ref) => designPath(ref).split('/')[0];
165
+ if (
166
+ owner !== e.from.source ||
167
+ !layers.includes(layer(owner)) || isFeatureInternal(designPath(owner), layers) ||
168
+ (owner !== e.to.source && !(layer(owner) === top && layer(e.to.source) === top))
169
+ )
170
+ issue('MOTION_LAYER', '/from', 'Declare this edge on its public origin entry. Only surfaces can cross sources.');
171
+ const from = await frameAt(e.from),
172
+ to = await frameAt(e.to);
173
+ for (const [side, f] of [
174
+ ['from', from],
175
+ ['to', to]
176
+ ]) {
177
+ if (!f) issue('MOTION_FRAME_MISSING', '/' + side, 'Missing endpoint ' + e[side].source + '#' + e[side].frame);
178
+ else if (f.proposed && f.proposed !== e.proposed)
179
+ issue('MOTION_STATUS', '/' + side, 'Endpoint proposal scope differs from the edge.');
180
+ }
181
+ if (hasMap && config.check?.lifecycle && !e.proposed && !detail.bound)
182
+ issue('MOTION_BINDING', '/id', 'Current action needs an active implementation binding.');
183
+ for (const [i, u] of (e.unsupported ?? []).entries())
184
+ issue('MOTION_UNSUPPORTED', '/unsupported/' + i, u.effect + ': ' + u.reason, null, true);
185
+ for (const theme of themes) {
186
+ const times = {};
187
+ for (const { pointer, kind, name } of timingRefs(e)) {
188
+ times[pointer] = resolveMotionToken(tokens, theme, name, kind).value;
189
+ if (times[pointer] === null)
190
+ issue(
191
+ 'MOTION_TOKEN',
192
+ pointer,
193
+ 'Expected a project ' + kind + ' token, got ' + JSON.stringify(name ?? null),
194
+ theme
195
+ );
196
+ }
197
+ if (!from || !to) continue;
198
+ const observed = { from: await observeFrame(e.from, from, theme), to: await observeFrame(e.to, to, theme) };
199
+ const rows = { from: observed.from.rows, to: observed.to.rows };
200
+ const matched = matchRoots(rows.from, rows.to);
201
+ for (const conflict of matched.conflicts)
202
+ issue(
203
+ 'MOTION_IDENTITY_AMBIGUOUS',
204
+ '/phases',
205
+ conflict.side + ' repeats an authored instance key for ' + conflict.part + '.',
206
+ theme
207
+ );
208
+ const resolved = [];
209
+ function resolve(side, target, at, missing = 'MOTION_TARGET_MISSING') {
210
+ const list = candidates(rows[side], target);
211
+ if (list.length === 1) {
212
+ resolved.push({ side, target, index: list[0].i });
213
+ return list[0];
214
+ }
215
+ issue(
216
+ list.length ? 'MOTION_IDENTITY_AMBIGUOUS' : missing,
217
+ at,
218
+ side + ' ' + JSON.stringify(target) + ' resolved to ' + list.length + ' elements.',
219
+ theme
220
+ );
221
+ }
222
+ const t = resolve('from', e.trigger.target, '/trigger/target', 'MOTION_TRIGGER_MISSING');
223
+ if (t) {
224
+ if (e.trigger.on === 'input' && (!t.textEntry || !t.focusable))
225
+ issue('MOTION_INPUT_TARGET', '/trigger/target', 'Input requires an editable text-entry control.', theme);
226
+ if (
227
+ !t.exposed ||
228
+ t.disabled ||
229
+ (['click', 'hover'].includes(e.trigger.on) && !t.pointer) ||
230
+ (e.trigger.on === 'focus' && !t.focusable) ||
231
+ (e.trigger.on === 'key' && !e.trigger.target.frame && !t.keyboard)
232
+ )
233
+ issue('MOTION_TRIGGER_MISSING', '/trigger', 'Origin cannot receive ' + e.trigger.on + '.', theme);
234
+ const k = JSON.stringify([e.from.source, e.from.frame, theme, t.i, e.trigger.on, e.trigger.key ?? e.trigger.value]);
235
+ if (dispatch.has(k) && dispatch.get(k) !== e.id)
236
+ issue('MOTION_TRIGGER_CONFLICT', '/trigger', 'Input also dispatches ' + dispatch.get(k) + '.', theme);
237
+ else dispatch.set(k, e.id);
238
+ }
239
+ if (e.focus.target) {
240
+ const f = resolve('to', e.focus.target, '/focus/target', 'MOTION_FOCUS');
241
+ if (f && (!f.exposed || f.disabled || (!f.focusable && !e.focus.target.frame)))
242
+ issue('MOTION_FOCUS', '/focus', 'Destination cannot receive focus.', theme);
243
+ }
244
+ const claims = { from: [], to: [] },
245
+ tracks = [];
246
+ let start = 0;
247
+ for (const [i, phase] of e.phases.entries()) {
248
+ let length = 0;
249
+ for (const [j, track] of phase.entries()) {
250
+ const at = '/phases/' + i + '/' + j,
251
+ duration = times[at + '/duration'] ?? times['/duration'];
252
+ tracks.push({ phase: i, track: j, start, duration, easing: times[at + '/easing'] ?? times['/easing'] });
253
+ length = Math.max(length, duration ?? 0);
254
+ for (const [n, target] of track.targets.entries()) {
255
+ const found = {};
256
+ const sides =
257
+ track.mode === 'exit'
258
+ ? ['from']
259
+ : track.mode === 'enter' && !candidates(rows.from, target).length
260
+ ? ['to']
261
+ : ['from', 'to'];
262
+ for (const side of sides) {
263
+ const p = at + '/targets/' + n,
264
+ row = resolve(side, target, p);
265
+ if (!row) continue;
266
+ found[side] = row;
267
+ const subtree = track.mode !== 'match',
268
+ ancestors = chain(rows[side], row);
269
+ for (const prev of claims[side]) {
270
+ if (
271
+ prev.row === row
272
+ ? track.properties.some((v) => prev.props.includes(v))
273
+ : (prev.subtree && ancestors.includes(prev.row)) ||
274
+ (subtree && chain(rows[side], prev.row).includes(row))
275
+ )
276
+ issue('MOTION_TRACK_CONFLICT', p, 'Overlapping track claims on ' + side + ' endpoint.', theme);
277
+ }
278
+ claims[side].push({ row, subtree, mode: track.mode, props: track.properties, duration });
279
+ }
280
+ if (
281
+ track.mode === 'match' &&
282
+ found.from?.parts.length &&
283
+ found.to &&
284
+ !matched.pairs.some((p) => p.from === found.from.i && p.to === found.to.i)
285
+ )
286
+ issue(
287
+ 'MOTION_IDENTITY_AMBIGUOUS',
288
+ at,
289
+ 'Match track needs the same resolved owner instance in both endpoints.',
290
+ theme
291
+ );
292
+ }
293
+ }
294
+ start += length;
295
+ }
296
+ const excluded = { from: new Set(), to: new Set() };
297
+ for (const side of ['from', 'to']) {
298
+ const subtrees = new Set(claims[side].filter((c) => c.subtree).map((c) => c.row.i));
299
+ for (const row of rows[side]) if (subtrees.has(row.i) || excluded[side].has(row.parent)) excluded[side].add(row.i);
300
+ }
301
+ const implicit = excluded.from.size || excluded.to.size ? matchRoots(rows.from, rows.to, excluded) : matched;
302
+ const flow = flows.get(frameKey(e.from));
303
+ if (flow) {
304
+ const layout = await layoutFor(flow, theme);
305
+ const fromIndex = flow.frames.findIndex((ref) => frameKey(ref) === frameKey(e.from));
306
+ const toIndex = flow.frames.findIndex((ref) => frameKey(ref) === frameKey(e.to));
307
+ const warning = !config.check?.strictMotion;
308
+ if (!layout?.pin)
309
+ issue('MOTION_FLOW_ANCHOR', '/trigger/target', flow.anchor
310
+ ? 'Flow anchor must resolve to one nonempty box in every member frame.'
311
+ : 'No trigger target is present uniquely across the flow. Playback uses an unpinned stage.', theme, warning);
312
+ if (layout && flow.stage && (layout.width > flow.stage.width + 0.01 || layout.height > flow.stage.height + 0.01))
313
+ issue('MOTION_FLOW_STAGE', '/to', 'Flow stage is smaller than the aligned frame union.', theme, warning);
314
+ if (layout?.pin) {
315
+ const { boxes } = layout.pin;
316
+ if ([2, 3].some(axis => Math.abs(boxes[fromIndex][axis] - boxes[toIndex][axis]) > 0.01))
317
+ issue('MOTION_FLOW_ANCHOR', '/to', 'The persistent flow anchor changes size.', theme, warning);
318
+ }
319
+ const positions = ['from', 'to'].map((side, i) => {
320
+ const offset = layout?.offsets[i ? toIndex : fromIndex] ?? [0, 0];
321
+ return offset.map((value, axis) => value - observed[side].box[axis]);
322
+ });
323
+ checkComposition(rows, matched.pairs, excluded, claims, positions,
324
+ (code, message) => issue(code, '/phases', message, theme, warning));
325
+ }
326
+ if (implicit.ambiguous.length)
327
+ issue(
328
+ 'MOTION_IMPLICIT_FADE',
329
+ '/phases',
330
+ implicit.ambiguous.length + ' ambiguous owner groups use fades.',
331
+ theme,
332
+ true
333
+ );
334
+ detail.themes[theme] = { timings: times, tracks, targets: resolved, ...implicit };
335
+ }
336
+ if (detail.themes.dark && JSON.stringify(detail.themes.light) === JSON.stringify(detail.themes.dark))
337
+ detail.themes.dark = { sameAs: 'light' };
338
+ return { detail, findings: [...problems.values()] };
339
+ };
340
+ }
341
+
342
+ function checkComposition(rows, pairs, excluded, claims, positions, issue) {
343
+ const active = (row) => row.box[2] > 0 && row.box[3] > 0;
344
+ const identity = (row) => row.anchor ? '#' + row.anchor : row.parts.at(-1);
345
+ const matched = { from: new Set(), to: new Set() };
346
+ const compare = (left, right) => {
347
+ if (!active(left) || !active(right)) return;
348
+ matched.from.add(left.i);
349
+ matched.to.add(right.i);
350
+ const axes = ['x', 'y'].filter((axis, i) =>
351
+ Math.abs(left.box[i] + positions[0][i] - right.box[i] - positions[1][i]) > 0.01 &&
352
+ !claims.from.some((claim) => claim.row === left && claim.mode === 'match' &&
353
+ claim.props.includes(axis) && claim.duration > 0));
354
+ if (axes.length) issue('MOTION_UNANIMATED_MOVE', identity(left) + ' moves on ' + axes.join('/') + ' without a position track.');
355
+ };
356
+ const replaced = (side, row) => excluded[side].has(row.i) &&
357
+ !claims[side].some((claim) => claim.subtree && claim.row === row);
358
+ for (const pair of pairs) {
359
+ const left = rows.from[pair.from], right = rows.to[pair.to];
360
+ if (!replaced('from', left) && !replaced('to', right)) compare(left, right);
361
+ }
362
+ const anchors = new Set([...rows.from, ...rows.to].flatMap((row) => row.anchor ? [row.anchor] : []));
363
+ for (const anchor of anchors) {
364
+ const [left, right] = ['from', 'to'].map((side) => candidates(rows[side], { anchor }));
365
+ if (left.length === 1 && right.length === 1 &&
366
+ !matched.from.has(left[0].i) && !matched.to.has(right[0].i) &&
367
+ !replaced('from', left[0]) && !replaced('to', right[0])) compare(left[0], right[0]);
368
+ }
369
+ for (const side of ['from', 'to']) {
370
+ const uncovered = new Set();
371
+ for (const row of rows[side]) {
372
+ if (uncovered.has(row.parent)) {
373
+ uncovered.add(row.i);
374
+ continue;
375
+ }
376
+ if (!identity(row) || !active(row) || matched[side].has(row.i) || excluded[side].has(row.i)) continue;
377
+ uncovered.add(row.i);
378
+ issue('MOTION_UNANIMATED_PRESENCE', identity(row) + ' appears only on ' + side +
379
+ ' without ' + (side === 'from' ? 'an exit' : 'an enter') + ' track.');
380
+ }
381
+ }
382
+ }
@@ -0,0 +1,105 @@
1
+ // Authoring provenance survives reduced-motion capture, hidden elements and inactive variants.
2
+ import { parse, generate, walk, ident, lexer } from 'css-tree';
3
+ import { parseFragment } from 'parse5';
4
+ import { resolveMotionToken } from './motion.mjs';
5
+
6
+ const sheetCache = new WeakMap();
7
+ const governed =
8
+ /^(?:-webkit-)?(?:transition|animation)(?:$|-(?:duration|delay|timing-function|property|name)$)|^--tw-(?:duration|ease)$/;
9
+ function declarations(ast, emit, classes = []) {
10
+ if (!classes.length && ast.type === 'Rule' && ast.prelude.type === 'SelectorList') {
11
+ // An outer selector owns its declarations, including any nested group/peer conditions.
12
+ for (const selector of ast.prelude.children) {
13
+ let first;
14
+ walk(selector, {
15
+ visit: 'ClassSelector',
16
+ enter(node) {
17
+ first ??= ident.decode(node.name);
18
+ }
19
+ });
20
+ if (first) classes = [...classes, first];
21
+ }
22
+ }
23
+ if (ast.type === 'Declaration') {
24
+ const prop = ast.property.startsWith('--') ? ast.property : ast.property.toLowerCase();
25
+ if (governed.test(prop)) emit(classes, prop, generate(ast.value));
26
+ }
27
+ for (const child of ast.children ?? []) declarations(child, emit, classes);
28
+ if (ast.block) declarations(ast.block, emit, classes);
29
+ }
30
+ function utilities(built) {
31
+ if (sheetCache.has(built)) return sheetCache.get(built);
32
+ const rules = new Map();
33
+ const css = built.cssBeforeTokens ?? built.css ?? '';
34
+ if (/(?:transition|animation|--tw-(?:duration|ease))\s*[-:]/i.test(css)) {
35
+ declarations(parse(css), (classes, prop, value) => {
36
+ for (const cls of classes) {
37
+ if (!rules.has(cls)) rules.set(cls, []);
38
+ rules.get(cls).push([prop, value]);
39
+ }
40
+ });
41
+ }
42
+ sheetCache.set(built, rules);
43
+ return rules;
44
+ }
45
+ function split(value, separator) {
46
+ let depth = 0,
47
+ start = 0;
48
+ const parts = [];
49
+ for (let i = 0; i < value.length; i++) {
50
+ if (value[i] === '(') depth++;
51
+ if (value[i] === ')') depth--;
52
+ if (!depth && separator.test(value[i])) {
53
+ if (i > start) parts.push(value.slice(start, i));
54
+ start = i + 1;
55
+ }
56
+ }
57
+ if (start < value.length) parts.push(value.slice(start));
58
+ return parts.map((p) => p.trim()).filter(Boolean);
59
+ }
60
+
61
+ export function sourceMotion(built, frame, tokens, theme) {
62
+ // Most frames have no authored motion. Do not parse the large generated preflight for them.
63
+ if (!/(?:animat|transition|duration|delay|ease|timing-function)/i.test(frame.html)) return [];
64
+ const rules = utilities(built),
65
+ messages = new Set();
66
+ function check(prop, value, origin, utility = false) {
67
+ const finding = (reason) => messages.add(origin + ' (' + prop + ': ' + value + '): ' + reason);
68
+ const name = prop.replace(/^-webkit-/, '');
69
+ const duration = name.endsWith('duration') || name.endsWith('delay'),
70
+ easing = name.endsWith('timing-function') || name === '--tw-ease';
71
+ const active =
72
+ name === 'animation' || name === 'animation-name' || name === 'transition-property' || name === 'transition';
73
+ if (active && !/^(none|initial|unset)$/i.test(value)) finding('Declare the motion on a frame edge.');
74
+ if (name === 'animation' && /^var\(--animate-[\w-]+\)$/.test(value)) return;
75
+ if (!duration && !easing && !['animation', 'transition'].includes(name)) return;
76
+ for (const item of split(value, /,/)) {
77
+ const list = duration || easing ? [item] : split(item, /\s/);
78
+ for (const word of list) {
79
+ if (utility && /^var\(--tw-(duration|ease),/.test(word)) continue; // Tailwind's shared default, separate authored utility checked below.
80
+ let kind = duration ? 'duration' : easing ? 'easing' : null;
81
+ const ref = /^var\(\s*(--[\w-]+)\s*\)$/.exec(word);
82
+ if (ref && !kind) {
83
+ if (['duration', 'easing'].some((k) => resolveMotionToken(tokens, theme, ref[1], k).value !== null)) continue;
84
+ finding('Shorthand variable must resolve to a project timing token.');
85
+ continue;
86
+ }
87
+ if (!kind && (/^[+-]?(?:\d|\.\d).*m?s$/i.test(word) || lexer.matchType('easing-function', word).matched))
88
+ kind = 'timing';
89
+ if (kind && !(ref && resolveMotionToken(tokens, theme, ref[1], kind).value !== null))
90
+ finding('Use a project motion token for ' + kind + '.');
91
+ }
92
+ }
93
+ }
94
+ function visit(node) {
95
+ for (const { name, value } of node.attrs ?? []) {
96
+ if (name === 'class')
97
+ for (const cls of value.split(/\s+/)) for (const [prop, v] of rules.get(cls) ?? []) check(prop, v, cls, true);
98
+ if (name === 'style' && /(?:transition|animat|--tw-(?:duration|ease))/i.test(value))
99
+ declarations(parse(value, { context: 'declarationList' }), (_, prop, v) => check(prop, v, 'style'));
100
+ }
101
+ for (const child of node.childNodes ?? []) visit(child);
102
+ }
103
+ visit(parseFragment(frame.html));
104
+ return [...messages];
105
+ }
@@ -0,0 +1,95 @@
1
+ export const frameKey = ({ source, frame }) => JSON.stringify([source, frame]);
2
+
3
+ // Connectivity is undirected. Direction is retained on the edges for playback.
4
+ export function motionFlows(records, declarations) {
5
+ const incident = new Map(), byFrame = new Map(), members = new Map(), findings = [];
6
+ const outgoing = new Set();
7
+ for (const { edge } of records) {
8
+ outgoing.add(frameKey(edge.from));
9
+ for (const ref of [edge.from, edge.to]) {
10
+ const key = frameKey(ref);
11
+ if (!incident.has(key)) incident.set(key, []);
12
+ incident.get(key).push(edge);
13
+ }
14
+ }
15
+ for (const [key] of incident) {
16
+ if (byFrame.has(key)) continue;
17
+ const queue = [key], frames = new Map(), edges = new Set();
18
+ const flow = { frames: [], triggers: [] };
19
+ byFrame.set(key, flow);
20
+ for (const current of queue) {
21
+ for (const edge of incident.get(current)) {
22
+ edges.add(edge);
23
+ for (const ref of [edge.from, edge.to]) {
24
+ const id = frameKey(ref);
25
+ frames.set(id, ref);
26
+ if (byFrame.has(id)) continue;
27
+ byFrame.set(id, flow);
28
+ queue.push(id);
29
+ }
30
+ }
31
+ }
32
+ flow.frames = [...frames.values()];
33
+ const destinations = new Set([...edges].map((edge) => frameKey(edge.to)));
34
+ flow.start = flow.frames.find((ref) => !destinations.has(frameKey(ref))) ?? incident.get(key)[0].from;
35
+ members.set(flow, [...edges]);
36
+ }
37
+ const declared = new Set(), ends = new Set();
38
+ for (const { declaration, source, pointer, locations } of declarations) {
39
+ const flow = byFrame.get(frameKey(declaration.start));
40
+ const message = !flow
41
+ ? 'Flow start must be an endpoint of a transition.'
42
+ : declared.has(flow) ? 'Declare one flow per connected component.' : null;
43
+ if (message) {
44
+ findings.push({
45
+ code: 'MOTION_FLOW_SCHEMA', source, pointer, frame: declaration.start.frame,
46
+ theme: null, message, ...(locations[pointer] ?? locations[''])
47
+ });
48
+ continue;
49
+ }
50
+ Object.assign(flow, declaration);
51
+ declared.add(flow);
52
+ for (const [index, ref] of (declaration.ends ?? []).entries()) {
53
+ const key = frameKey(ref), at = pointer + '/ends/' + index;
54
+ const problem = byFrame.get(key) !== flow ? 'An end state must belong to the declared flow.'
55
+ : outgoing.has(key) ? 'An end state cannot have outgoing transitions.'
56
+ : ends.has(key) ? 'Declare each end state once.' : null;
57
+ if (problem) {
58
+ findings.push({ code: 'MOTION_FLOW_SCHEMA', source, pointer: at, frame: ref.frame,
59
+ theme: null, message: problem, ...(locations[at] ?? locations[pointer]) });
60
+ } else ends.add(key);
61
+ }
62
+ }
63
+ for (const [flow, edges] of members) {
64
+ if (flow.anchor) continue;
65
+ const start = frameKey(flow.start);
66
+ const ordered = [...edges.filter((edge) => frameKey(edge.from) === start),
67
+ ...edges.filter((edge) => frameKey(edge.from) !== start)];
68
+ const triggers = new Map();
69
+ for (const { trigger: { target } } of ordered) {
70
+ if (!target.frame) triggers.set(JSON.stringify(target), target);
71
+ }
72
+ flow.triggers = [...triggers.values()];
73
+ }
74
+ const deadEnds = new Set([...byFrame.keys()].filter(key => !outgoing.has(key) && !ends.has(key)));
75
+ return { byFrame, findings, deadEnds };
76
+ }
77
+
78
+ // Use the first selected incoming edge to locate each dead end in its sidecar.
79
+ export function deadEndFindings(graph, records, strictMotion) {
80
+ const reported = new Set(), findings = [];
81
+ for (const { valid, edge, source, pointer, locations } of records) {
82
+ if (!valid) continue;
83
+ const ref = edge.to, key = frameKey(ref);
84
+ if (!graph.deadEnds.has(key) || reported.has(key)) continue;
85
+ reported.add(key);
86
+ const at = pointer + '/to';
87
+ findings.push({
88
+ code: 'MOTION_FLOW_DEAD_END', source, pointer: at, frame: ref.frame, theme: null,
89
+ warning: !strictMotion,
90
+ message: ref.source + '#' + ref.frame + ' has no outgoing transition. Add an action or declare it in the flow’s ends.',
91
+ ...(locations[at] ?? locations[pointer])
92
+ });
93
+ }
94
+ return findings;
95
+ }
@@ -0,0 +1,87 @@
1
+ import { labelResolver } from './motion-label.mjs';
2
+ import { canonicalBytes } from './impact-proof.mjs';
3
+ import { frameKey } from './motion-flows.mjs';
4
+ import { motionRows } from './motion.mjs';
5
+ import { targetsFor, usesTiming } from './motion-queries.mjs';
6
+ import { parseTokens } from './tokens.mjs';
7
+
8
+ export async function impactedEdges(views, query, themes, assessments, explain, expanded) {
9
+ const git = query.kind === 'git',
10
+ ids = new Set(views.flatMap((v) => [...v.motion.ids.keys()]));
11
+ const output = [];
12
+ const labels = views.map(v => labelResolver(v.config,source=>v.built.get(source) ?? v.index.materialize(source)));
13
+ const tokenMaps = new Map();
14
+ const tokens = (v) => {
15
+ if (!tokenMaps.has(v)) tokenMaps.set(v, parseTokens(v.tokenBytes.toString()));
16
+ return tokenMaps.get(v);
17
+ };
18
+ for (const id of [...ids].sort()) {
19
+ const reasons = new Set(),
20
+ records = views.map((v) => motionRows(v.motion.ids.get(id) ?? [])[0]);
21
+ let kind = 'candidate';
22
+ if (git) {
23
+ kind = !records[0] ? 'added' : !records[1] ? 'removed' : 'changed';
24
+ const declarations = records.map((r, i) => r && canonicalBytes({
25
+ owner: r.owner, edge: r.edge,
26
+ flow: r.valid ? views[i].motion.flows.get(frameKey(r.edge.from)) : null,
27
+ deadEnd: r.valid && views[i].motion.deadEnds.has(frameKey(r.edge.to))
28
+ }));
29
+ if (declarations[0] !== declarations[1]) reasons.add('declaration');
30
+ const selectors = views.map((v) =>
31
+ canonicalBytes(
32
+ v.map.mappings
33
+ .filter((m) => m.design.some((d) => d.transition === id))
34
+ .map((m) => canonicalBytes(m.implementation))
35
+ .sort()
36
+ )
37
+ );
38
+ if (
39
+ views[0].config.check?.lifecycle !== views[1].config.check?.lifecycle ||
40
+ views[0].map.present !== views[1].map.present
41
+ )
42
+ reasons.add('binding');
43
+ if (selectors[0] !== selectors[1]) reasons.add('binding');
44
+ }
45
+ views.forEach((view, i) => {
46
+ const r = records[i];
47
+ if (!r) return;
48
+ if (view.motionBindingHits?.has(id)) reasons.add('binding');
49
+ if (query.kind === 'source' && !query.part && query.sources.includes(r.source)) reasons.add('declaration');
50
+ if (!r.valid) return;
51
+ const edge = r.edge;
52
+ if (
53
+ (query.kind === 'token' || git) &&
54
+ view.motionTokenHits?.some((hit) => usesTiming(edge, tokens(view), [hit.token], hit.themes))
55
+ )
56
+ reasons.add('timing_token');
57
+ for (const side of ['from', 'to']) {
58
+ const ref = edge[side],
59
+ facts = view.facts.get(ref.source),
60
+ frame = facts?.frames.find((f) => f.name === ref.frame);
61
+ if (git) {
62
+ const prior = views[1 - i].facts.get(ref.source)?.frames.find((f) => f.name === ref.frame);
63
+ if (frame?.proposed !== prior?.proposed) reasons.add('endpoint');
64
+ }
65
+ if (query.kind === 'source' && query.part) {
66
+ if (
67
+ frame?.parts.some((p) => p.source === query.sources[0] && p.part === query.part) ||
68
+ targetsFor(edge, side).some((t) => t.part === query.sources[0] + '#' + query.part)
69
+ )
70
+ reasons.add('part');
71
+ continue;
72
+ }
73
+ if (query.kind === 'source' && query.sources.includes(ref.source)) reasons.add('endpoint');
74
+ if (
75
+ themes.some((theme) => {
76
+ const a = assessments.get(JSON.stringify([ref.source, ref.frame, theme]));
77
+ return a?.candidate && (!git || a.disposition !== 'proven_unaffected');
78
+ })
79
+ )
80
+ reasons.add('endpoint');
81
+ }
82
+ });
83
+ const side = records.findLastIndex(Boolean);
84
+ if (reasons.size) output.push({ id, kind, ...(expanded ? {label:await labels[side](records[side])} : {}), ...(explain ? { reasons: [...reasons].sort() } : {}) });
85
+ }
86
+ return output;
87
+ }