@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,216 @@
1
+ import path from 'node:path';
2
+ import { readFileSync } from 'node:fs';
3
+ import { CliError } from '../cli-output.mjs';
4
+ import { parseTokens } from './tokens.mjs';
5
+ import { milliseconds, motionPrimitives, tokenValue, validMotionEasing } from './motion-primitives.mjs';
6
+
7
+ const roleDefaults = {
8
+ 'duration-base': '--adg-motion-base',
9
+ 'duration-fast': '--adg-motion-fast',
10
+ 'duration-loop': '--adg-motion-loop',
11
+ 'easing-enter': '--adg-motion-enter',
12
+ 'easing-exit': '--adg-motion-exit',
13
+ 'easing-loop': '--adg-motion-linear',
14
+ 'spring-small': '--motion-spring-small',
15
+ 'distance-small': '--motion-distance-small',
16
+ 'scale-small': '--motion-scale-small',
17
+ 'stagger-small': '--motion-stagger-small',
18
+ };
19
+ const timing = { duration: 'duration-base', easing: 'easing-enter' };
20
+ const exit = { duration: 'duration-fast', easing: 'easing-exit' };
21
+ const distance = 'distance-small';
22
+ const make = (kind, action, effect, properties, parameters = timing, extra = {}) => ({
23
+ kind, action, effect, properties, parameters, interrupt: 'finish',
24
+ reduced: kind === 'ambient' || kind === 'continuous' ? 'static' : 'instant', ...extra,
25
+ });
26
+ const basePatterns = {
27
+ fade: make('transition', 'enter', 'fade', ['opacity'], timing, { exit }),
28
+ 'expand-collapse': make('layout', 'resize', 'expand', ['height', 'opacity'], timing, { exit }),
29
+ 'size-transition': make('layout', 'resize', 'size', ['width', 'height']),
30
+ slide: make('transition', 'enter', 'slide', ['x', 'opacity'], { ...timing, distance }, { exit }),
31
+ 'spring-pop': make('transition', 'enter', 'pop', ['scale', 'opacity'], { spring: 'spring-small', scale: 'scale-small' }),
32
+ 'crossfade-replace': make('transition', 'replace', 'crossfade', ['opacity']),
33
+ follow: make('continuous', 'follow', 'follow', ['x', 'y'], timing, { interrupt: 'retarget' }),
34
+ 'avoid-reflow': make('layout', 'avoid', 'avoid', ['x', 'y'], timing, { interrupt: 'retarget' }),
35
+ stagger: make('transition', 'enter', 'stagger', ['opacity', 'y'], { ...timing, distance, stagger: 'stagger-small' }),
36
+ 'ambient-loop': make('ambient', 'loop', 'pulse', ['opacity', 'scale'], {
37
+ duration: 'duration-loop', easing: 'easing-loop', scale: 'scale-small',
38
+ }, { interrupt: 'cancel' }),
39
+ };
40
+ const effects = new Set([...Object.values(basePatterns).map(pattern => pattern.effect), 'aurora', 'shimmer', 'spin']);
41
+ const actions = { transition: ['enter', 'exit', 'replace'], layout: ['resize', 'reflow', 'avoid'], continuous: ['follow'], ambient: ['loop'] };
42
+ const parameterKeys = new Set(['duration', 'easing', 'spring', 'distance', 'scale', 'stagger', 'fromOpacity']);
43
+ const object = value => value && typeof value === 'object' && !Array.isArray(value);
44
+ const idPattern = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
45
+ const tokenPattern = /^--[\w-]+$/;
46
+ const portable = value => typeof value === 'string' && value.split('/').every(part => part && part !== '.' && part !== '..' && !/[\\:\x00-\x1f]/.test(part));
47
+ export const motionPatternFile = 'motion-patterns.json';
48
+
49
+ function projectFile(config, name, fallback) {
50
+ try { return readFileSync(path.join(config.design, name), 'utf8'); }
51
+ catch (error) { if (error.code === 'ENOENT') return fallback; throw error; }
52
+ }
53
+
54
+ function mergeParameters(base, overrides = {}) {
55
+ const result = { ...base, ...overrides };
56
+ if (overrides.spring !== undefined) {
57
+ delete result.duration;
58
+ delete result.easing;
59
+ } else if (overrides.duration !== undefined || overrides.easing !== undefined) delete result.spring;
60
+ return result;
61
+ }
62
+
63
+ function validParameter(primitives, theme, key, token) {
64
+ const value = tokenValue(primitives.tokens, theme, token);
65
+ switch (key) {
66
+ case 'spring': return Object.hasOwn(primitives.springs[theme], token);
67
+ case 'duration':
68
+ case 'stagger': return Number.isFinite(milliseconds(value));
69
+ case 'distance': return /^-?(?:\d+(?:\.\d+)?|\.\d+)(?:px|rem|em|%)$/.test(value ?? '');
70
+ case 'scale': return /^\+?(?:\d+(?:\.\d+)?|\.\d+)$/.test(value ?? '') && Number.isFinite(Number(value));
71
+ default: return validMotionEasing(value);
72
+ }
73
+ }
74
+
75
+ export function loadMotionPatterns(config, authored) {
76
+ const invalid = message => { throw new CliError('CONFIG_INVALID', motionPatternFile + ': ' + message); };
77
+ let document;
78
+ try { document = JSON.parse(projectFile(config, motionPatternFile, '{"version":1}')); }
79
+ catch (error) { invalid(error.message); }
80
+ if (!object(document) || document.version !== 1 ||
81
+ (document.patterns !== undefined && !object(document.patterns)) ||
82
+ (document.roles !== undefined && !object(document.roles)) ||
83
+ Object.keys(document).some(key => !['version', 'patterns', 'roles'].includes(key)))
84
+ invalid('Expected version 1 with optional roles and patterns objects.');
85
+
86
+ const css = authored ? null : projectFile(config, 'tokens.css', null);
87
+ authored ??= css ? parseTokens(css) : {light: new Map(), dark: new Map()};
88
+ const primitives = motionPrimitives(authored);
89
+ const roles = { ...roleDefaults };
90
+ for (const [role, token] of Object.entries(document.roles ?? {})) {
91
+ if (!Object.hasOwn(roleDefaults, role) || typeof token !== 'string' || !tokenPattern.test(token))
92
+ invalid('Invalid motion role ' + role + '.');
93
+ const kind = role.split('-')[0];
94
+ const inputs = kind === 'spring' ? [token + '-duration', token + '-bounce'] : [token];
95
+ const authoredPrimitives = { ...primitives, tokens: authored };
96
+ if (!['light','dark'].every(theme =>
97
+ inputs.every(name => tokenValue(authored, theme, name) !== undefined) &&
98
+ validParameter(authoredPrimitives, theme, kind, token)))
99
+ invalid(role + ' needs an authored ' + kind + ' token valid in both themes: ' + token + '.');
100
+ roles[role] = token;
101
+ }
102
+ const resolveRoles = params => Object.fromEntries(Object.entries(params).map(([key, role]) => [key, roles[role]]));
103
+ const patterns = new Map(), variants = new Map();
104
+ const declarations = Object.entries(document.patterns ?? {});
105
+ const parameterFields = ['parameters','enter','exit'];
106
+ const consumerFields = ['consumers','frames'];
107
+ const shapeFields = ['kind','action','effect','properties','interrupt','reduced'];
108
+ function validateParameters(id, values) {
109
+ if (!object(values) || Object.keys(values).some(key => !parameterKeys.has(key))) invalid(id + ' has unknown parameters.');
110
+ if (Object.hasOwn(values, 'spring') && (Object.hasOwn(values, 'duration') || Object.hasOwn(values, 'easing')))
111
+ invalid(id + ' cannot combine spring with duration or easing in the same parameter set.');
112
+ for (const [key, value] of Object.entries(values)) {
113
+ if (key === 'fromOpacity') {
114
+ if (!(Number.isFinite(value) && value >= 0 && value <= 1)) invalid(id + ' has an invalid fromOpacity.');
115
+ } else if (typeof value !== 'string' || !tokenPattern.test(value) ||
116
+ !['light','dark'].every(theme => validParameter(primitives, theme, key, value))) {
117
+ invalid(id + ' needs a valid ' + key + ' token in both themes: ' + value + '.');
118
+ }
119
+ }
120
+ }
121
+ function declare(id, entry, base) {
122
+ const pattern = { ...base, ...entry, consumers: entry.consumers, frames: entry.frames };
123
+ for (const dir of parameterFields) {
124
+ if (entry[dir] !== undefined) validateParameters(id, entry[dir]);
125
+ if (dir === 'parameters' || base?.[dir] || entry[dir]) pattern[dir] = mergeParameters(base?.[dir], entry[dir]);
126
+ }
127
+ if (!Object.hasOwn(actions, pattern.kind) || !actions[pattern.kind].includes(pattern.action) || !effects.has(pattern.effect) ||
128
+ !['finish','retarget','cancel'].includes(pattern.interrupt) || !['instant','static'].includes(pattern.reduced) ||
129
+ !Array.isArray(pattern.properties) || !pattern.properties.length ||
130
+ pattern.properties.some(prop => typeof prop !== 'string' || !/^(?:--)?[a-zA-Z][\w-]*$/.test(prop)) ||
131
+ new Set(pattern.properties).size !== pattern.properties.length) invalid(id + ' needs a supported kind, action, effect, properties, interrupt and reduced policy.');
132
+ if (pattern.consumers !== undefined && (!Array.isArray(pattern.consumers) || pattern.consumers.some(ref =>
133
+ !object(ref) || Object.keys(ref).some(key => !['file','match','within'].includes(key)) || !portable(ref.file) ||
134
+ typeof ref.match !== 'string' || !/^(?:css|keyframes|motion|style|attribute|web|call):.+$/.test(ref.match) ||
135
+ (ref.within !== undefined && (typeof ref.within !== 'string' || !ref.within.trim()))))) invalid(id + ' has an invalid code consumer.');
136
+ if (pattern.frames !== undefined && (!Array.isArray(pattern.frames) || pattern.frames.some(ref =>
137
+ !object(ref) || Object.keys(ref).some(key => !['source','frame'].includes(key)) || !portable(ref.source) ||
138
+ !ref.source.endsWith('.tsx') || typeof ref.frame !== 'string' || !ref.frame.trim()))) invalid(id + ' has an invalid frame consumer.');
139
+ for (const direction of ['enter', 'exit']) {
140
+ const resolved = patternParameters(pattern, direction);
141
+ if (!resolved.spring && !(resolved.duration && resolved.easing)) invalid(id + ' requires duration and easing or a spring.');
142
+ }
143
+ patterns.set(id, pattern);
144
+ }
145
+ for (const [id, entry] of declarations) {
146
+ if (!idPattern.test(id) || !object(entry)) invalid('Invalid pattern ' + id + '.');
147
+ if (Object.hasOwn(entry, 'extends')) {
148
+ if (Object.hasOwn(basePatterns, id) || typeof entry.extends !== 'string' || !Object.hasOwn(basePatterns, entry.extends) ||
149
+ Object.keys(entry).some(key => !['extends', ...parameterFields, ...consumerFields].includes(key)))
150
+ invalid(id + ' must extend a built-in and declare only parameter overrides and its own consumers.');
151
+ } else if (Object.keys(entry).some(key => ![...parameterFields, ...consumerFields, ...shapeFields].includes(key))) {
152
+ invalid(id + ' has unknown fields.');
153
+ }
154
+ }
155
+ for (const [id, pattern] of Object.entries(basePatterns)) {
156
+ declare(id, Object.hasOwn(document.patterns ?? {}, id) ? document.patterns[id] : {}, {
157
+ ...pattern, parameters: resolveRoles(pattern.parameters),
158
+ ...(pattern.exit ? { exit: resolveRoles(pattern.exit) } : {}),
159
+ });
160
+ variants.set(id, []);
161
+ }
162
+ for (const [id, entry] of declarations) {
163
+ if (variants.has(id)) continue;
164
+ declare(id, entry, patterns.get(entry.extends));
165
+ if (entry.extends) variants.get(entry.extends).push(id);
166
+ }
167
+ return { ...primitives, patterns, variants, declared: declarations.map(([id]) => id) };
168
+ }
169
+
170
+ export function patternParameters(pattern, direction) {
171
+ return mergeParameters(pattern.parameters, pattern[direction]);
172
+ }
173
+
174
+ // Compile into the existing discrete player contract. Continuous and ambient
175
+ // behavior has no finite pair of endpoints, so those patterns stay board/code only.
176
+ export function patternEdge(edge, catalog, issue) {
177
+ const { pattern: ref, ...fields } = edge;
178
+ const selected = object(ref) && typeof ref.id === 'string' ? catalog.patterns.get(ref.id) : null;
179
+ if (!selected || Object.keys(ref).some(key => !['id','direction','targets'].includes(key)) ||
180
+ (ref.direction !== undefined && !['enter','exit','replace'].includes(ref.direction))) {
181
+ issue('MOTION_PATTERN_INVALID', '/pattern', 'Choose a declared pattern, optional enter/exit/replace direction and explicit targets.');
182
+ return edge;
183
+ }
184
+ if (['phases','duration','easing','interrupt','reduced'].some(key => Object.hasOwn(fields, key))) {
185
+ issue('MOTION_PATTERN_INVALID', '/pattern', 'A pattern supplies phases, timing, interrupt and reduced motion.');
186
+ return edge;
187
+ }
188
+ const direction = ref.direction ?? selected.action;
189
+ let mode, properties;
190
+ if (selected.kind === 'layout' || selected.effect === 'slide' || selected.effect === 'pop') {
191
+ if (!['layout','transition'].includes(selected.kind) || selected.action === 'avoid') {
192
+ issue('MOTION_PATTERN_INVALID', '/pattern', 'Layout avoidance needs live siblings, outside the discrete edge contract.');
193
+ return edge;
194
+ }
195
+ mode = 'match';
196
+ properties = selected.properties.filter(prop => ['x','y','width','height','opacity'].includes(prop));
197
+ if (selected.effect === 'pop' && selected.properties.includes('scale')) properties = [...new Set([...properties,'width','height'])];
198
+ } else if (selected.kind === 'transition' && ['fade','crossfade'].includes(selected.effect)) {
199
+ mode = direction === 'replace' ? 'crossfade' : direction;
200
+ properties = ['opacity'];
201
+ } else {
202
+ issue('MOTION_PATTERN_INVALID', '/pattern', 'This pattern needs continuous, ambient or stagger behavior beyond a discrete edge.');
203
+ return edge;
204
+ }
205
+ if (selected.interrupt !== 'finish' || selected.reduced !== 'instant') {
206
+ issue('MOTION_PATTERN_INVALID', '/pattern', 'A discrete edge requires finish interruption and instant reduced motion.');
207
+ return edge;
208
+ }
209
+ const parameters = patternParameters(selected, direction);
210
+ const duration = parameters.spring ? parameters.spring + '-duration' : parameters.duration;
211
+ const easing = parameters.spring ?? parameters.easing;
212
+ return { ...fields, duration, easing, interrupt: 'finish', reduced: 'instant', phases: [[{
213
+ mode, properties, targets: ref.targets,
214
+ ...(mode === 'enter' && parameters.fromOpacity !== undefined ? { fromOpacity: parameters.fromOpacity } : {}),
215
+ }]] };
216
+ }
@@ -0,0 +1,94 @@
1
+ import { lexer } from 'css-tree';
2
+ import { CliError } from '../cli-output.mjs';
3
+
4
+ const defaults = {
5
+ '--adg-motion-fast': '140ms',
6
+ '--adg-motion-base': '220ms',
7
+ '--adg-motion-loop': '1600ms',
8
+ '--adg-motion-enter': 'cubic-bezier(.2,.75,.25,1)',
9
+ '--adg-motion-exit': 'cubic-bezier(.4,0,.8,.35)',
10
+ '--adg-motion-linear': 'linear',
11
+ '--motion-distance-small': '20px',
12
+ '--motion-scale-small': '.85',
13
+ '--motion-stagger-small': '55ms',
14
+ '--motion-spring-small-duration': '360ms',
15
+ '--motion-spring-small-bounce': '.14',
16
+ };
17
+
18
+ export function tokenValue(tokens, theme, token) {
19
+ const visited = new Set();
20
+ while (!visited.has(token)) {
21
+ visited.add(token);
22
+ const value = (theme === 'dark' ? tokens.dark.get(token) : undefined) ?? tokens.light.get(token);
23
+ const alias = /^var\(\s*(--[\w-]+)\s*\)$/.exec(value ?? '');
24
+ if (!alias) return value;
25
+ token = alias[1];
26
+ }
27
+ }
28
+
29
+ export function milliseconds(value) {
30
+ const match = /^(\d+(?:\.\d+)?|\.\d+)(ms|s)$/.exec(value ?? '');
31
+ return match ? Number(match[1]) * (match[2] === 's' ? 1000 : 1) : NaN;
32
+ }
33
+
34
+ export function validMotionEasing(value) {
35
+ if (!value) return false;
36
+ const linear = /^linear\(([^()]*)\)$/i.exec(value);
37
+ if (linear) {
38
+ const number = '[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[eE][+-]?\\d+)?';
39
+ const stop = new RegExp('^(?:' + number + '(?:\\s+' + number + '%){0,2}|(?:' + number + '%\\s+){1,2}' + number + ')$');
40
+ const points = linear[1].split(',');
41
+ return points.length >= 2 && points.every(point => stop.test(point.trim()));
42
+ }
43
+ if (!lexer.matchType('easing-function', value).matched) return false;
44
+ const steps = /^steps\(\s*(\d+)\s*(?:,\s*([\w-]+)\s*)?\)$/i.exec(value);
45
+ return !steps || Number(steps[1]) >= (steps[2]?.toLowerCase() === 'jump-none' ? 2 : 1);
46
+ }
47
+
48
+ // Sample a normalized damped unit step. Bounce is the first overshoot fraction.
49
+ export function springEasing(bounce) {
50
+ const log = Math.log(bounce || .001);
51
+ const damping = bounce ? -log / Math.hypot(Math.PI, log) : 1;
52
+ const omega = 7 / damping;
53
+ const frequency = omega * Math.sqrt(1 - damping ** 2);
54
+ const points = Array.from({ length: 33 }, (_, i) => {
55
+ const t = i / 32;
56
+ if (i === 32) return 1;
57
+ const wave = frequency
58
+ ? Math.cos(frequency * t) + 7 / frequency * Math.sin(frequency * t)
59
+ : 1 + 7 * t;
60
+ return Number((1 - Math.exp(-7 * t) * wave).toFixed(5));
61
+ });
62
+ return 'linear(' + points.join(', ') + ')';
63
+ }
64
+
65
+ export function motionPrimitives(authored, { base = true } = {}) {
66
+ const light = new Map([...(base ? Object.entries(defaults) : []), ...authored.light]);
67
+ const dark = new Map(authored.dark);
68
+ const defaultTokens = new Set(base ? Object.keys(defaults).filter(name => !authored.light.has(name)) : []);
69
+ const tokens = { light, dark };
70
+ const names = [...light.keys()].flatMap(name => {
71
+ const match = /^(--motion-spring-[\w-]+)-(?:duration|bounce)$/.exec(name);
72
+ return match ? [match[1]] : [];
73
+ });
74
+ const springs = { light: {}, dark: {} }, generated = { light: new Map(), dark: new Map() };
75
+ for (const name of new Set(names)) {
76
+ for (const theme of ['light', 'dark']) {
77
+ const duration = milliseconds(tokenValue(tokens, theme, name + '-duration'));
78
+ const rawBounce = tokenValue(tokens, theme, name + '-bounce');
79
+ const bounce = Number(rawBounce);
80
+ if (!(duration > 0 && Number.isFinite(duration) && rawBounce && bounce >= 0 && bounce <= .8))
81
+ throw new CliError('TOKENS_INVALID', name + ' needs a positive duration and a bounce between 0 and .8 in ' + theme + '.');
82
+ const easing = springEasing(bounce);
83
+ springs[theme][name] = { duration, bounce, easing };
84
+ if (theme === 'light' || easing !== springs.light[name].easing) generated[theme].set(name, easing);
85
+ }
86
+ }
87
+ for (const theme of ['light', 'dark']) for (const [name, easing] of generated[theme]) tokens[theme].set(name, easing);
88
+ return { tokens, springs, generated, defaultTokens };
89
+ }
90
+
91
+ export function motionTokenCss(tokens) {
92
+ const block = (selector, values) => selector + ' {\n' + [...values].map(([key, value]) => ' ' + key + ': ' + value + ';').join('\n') + '\n}';
93
+ return block(':root', tokens.light) + '\n' + block(':root[data-theme="dark"]', tokens.dark) + '\n';
94
+ }
@@ -0,0 +1,169 @@
1
+ import { labelResolver } from './motion-label.mjs';
2
+ import path from 'node:path';
3
+ import { CliError } from '../cli-output.mjs';
4
+ import { listSources, relative, selectSources, sourceDirectories, loadTokens } from './project.mjs';
5
+ import { loadImplementationMap, validateImplementationMap } from './implementation-map.mjs';
6
+ import { readMotion, motionRows, motionSummary, resolveMotionToken, timingRefs } from './motion.mjs';
7
+ import { motionEvaluator } from './motion-check.mjs';
8
+ import { buildSource } from './build.mjs';
9
+ import { launch } from './browser.mjs';
10
+
11
+ async function labeled(config,records) {
12
+ const label = labelResolver(config);
13
+ return Promise.all(records.map(async r=>({id:r.edge.id,label:await label(r)})));
14
+ }
15
+ export function targetsFor(edge, side) {
16
+ return [
17
+ ...(side === 'from' ? [edge.trigger.target] : edge.focus.target ? [edge.focus.target] : []),
18
+ ...edge.phases
19
+ .flat()
20
+ .filter((track) => side === 'from' || track.mode !== 'exit')
21
+ .flatMap((t) => t.targets)
22
+ ];
23
+ }
24
+ export function usesTiming(edge, tokens, names, themes) {
25
+ return timingRefs(edge).some((ref) =>
26
+ themes.some((theme) => resolveMotionToken(tokens, theme, ref.name, ref.kind).names.some((name) => names.includes(name)))
27
+ );
28
+ }
29
+ export async function tokenEdges(config, values, data) {
30
+ const graph = readMotion(config);
31
+ if (!graph.records.length) {
32
+ motionSummary(data, [], values.transitions);
33
+ return;
34
+ }
35
+ const tokens = loadTokens(config),
36
+ themes = values.theme && values.theme !== 'both' ? [values.theme] : ['light', 'dark'];
37
+ const records = motionRows(graph.records.filter((r) => r.valid && usesTiming(r.edge, tokens, [values.token], themes)));
38
+ motionSummary(
39
+ data,
40
+ values.transitions ? await labeled(config,records) : records.map(r=>r.edge.id),
41
+ values.transitions
42
+ );
43
+ }
44
+ export async function boundEdges(config, bindings, data, expanded = false) {
45
+ const active = (bindings ?? []).filter((b) => b.active);
46
+ let ids = active.map((b) => b.design.transition);
47
+ if (data.query.kind === 'part') {
48
+ const { source, part } = data.query;
49
+ if (!part) ids = active.filter((b) => b.design.source === source).map((b) => b.design.transition);
50
+ else if (ids.length) {
51
+ const allowed = new Set(ids);
52
+ ids = readMotion(config)
53
+ .records.filter(
54
+ (r) =>
55
+ r.valid &&
56
+ allowed.has(r.edge.id) &&
57
+ ['from', 'to'].some((side) => targetsFor(r.edge, side).some((t) => t.part === source + '#' + part))
58
+ )
59
+ .map((r) => r.edge.id);
60
+ }
61
+ }
62
+ const unique = [...new Set(ids)].sort();
63
+ motionSummary(data, expanded && unique.length ? await labeled(config,motionRows(readMotion(config).records.filter(r=>unique.includes(r.edge?.id)))) : unique, expanded);
64
+ }
65
+ async function behaviorMap(config, owner) {
66
+ const map = await loadImplementationMap(config);
67
+ const validated = await validateImplementationMap(config, map, {
68
+ targetFilter: (target) => target.transition && target.source === owner,
69
+ sources: listSources(config.design, sourceDirectories(config)).map((f) => relative(config, f))
70
+ });
71
+ return { map, ...validated };
72
+ }
73
+ export async function transitionQuery(config, command, args, values, log) {
74
+ const graph = readMotion(config);
75
+ const data = {
76
+ project: config.root,
77
+ complete: true,
78
+ motionVersion: 1,
79
+ mode: values.transitions ? 'transitions' : 'transition'
80
+ };
81
+ const label = labelResolver(config);
82
+ if (values.transitions) {
83
+ const [file] = selectSources(config, args, { write: false }),
84
+ source = relative(config, file);
85
+ const built = await buildSource(config, file, { write: false });
86
+ if (!built.frames.some((f) => f.name === values.frame))
87
+ throw new CliError('FRAME_NOT_FOUND', 'Unknown frame ' + values.frame);
88
+ const rows = motionRows(
89
+ graph.records.filter(
90
+ (r) => r.valid && [r.edge.from, r.edge.to].some((ref) => ref.source === source && ref.frame === values.frame)
91
+ )
92
+ );
93
+ motionSummary(
94
+ data,
95
+ await Promise.all(rows.map(async (r) => ({
96
+ id: r.edge.id, label:await label(r), from:r.edge.from, to:r.edge.to, input:r.edge.trigger.on,
97
+ ...(r.edge.proposed ? { proposed:r.edge.proposed } : {})
98
+ }))),
99
+ true
100
+ );
101
+ } else {
102
+ const records = graph.ids.get(values.transition) ?? [];
103
+ if (!records.length) throw new CliError('MOTION_EDGE_NOT_FOUND', 'Unknown transition ' + values.transition + '.');
104
+ if (records.length !== 1)
105
+ throw new CliError('SOURCE_BUILD_FAILED', 'Conflicting transition ID ' + values.transition + '; run adg check.');
106
+ const [r] = records,
107
+ validated = await behaviorMap(config, r.owner);
108
+ const bindings = validated.transitionBindings.filter((b) => b.active && b.design.transition === r.edge.id);
109
+ data.label = await label(r);
110
+ if (command === 'owner') {
111
+ data.query = { kind: 'transition', id: r.edge.id };
112
+ data.bindings = bindings.map((b) => ({
113
+ selector: b.implementation,
114
+ files: b.files,
115
+ anchorLine: b.anchorLine,
116
+ pointer: b.pointer
117
+ }));
118
+ data.mappingFindings = validated.findings;
119
+ } else {
120
+ data.findings = graph.findings.filter(
121
+ (f) => f.source === r.source && (f.pointer === r.pointer || f.pointer.startsWith(r.pointer + '/'))
122
+ );
123
+ data.edge = r.edge;
124
+ if (r.valid) {
125
+ let browser, page;
126
+ try {
127
+ const evaluate = motionEvaluator(config, {
128
+ flows: graph.flows,
129
+ bindings,
130
+ hasMap: validated.map.present,
131
+ themes: values.theme && values.theme !== 'both' ? [values.theme] : ['light', 'dark'],
132
+ getPage: async () => {
133
+ browser ??= await launch();
134
+ return (page ??= await browser.newPage());
135
+ }
136
+ });
137
+ for (const peer of graph.records) {
138
+ if (
139
+ peer !== r &&
140
+ peer.valid &&
141
+ peer.edge.from.source === r.edge.from.source &&
142
+ peer.edge.from.frame === r.edge.from.frame
143
+ )
144
+ await evaluate(peer);
145
+ }
146
+ const { detail, findings } = await evaluate(r);
147
+ data.bound = detail.bound;
148
+ data.themes = detail.themes;
149
+ data.findings.push(...findings);
150
+ if (!values.explain)
151
+ for (const facts of Object.values(data.themes)) {
152
+ if (facts.limitations)
153
+ facts.limitations = Object.fromEntries(
154
+ [...new Set(facts.limitations.map((l) => l.reason))].map((reason) => [
155
+ reason,
156
+ facts.limitations.filter((l) => l.reason === reason).length
157
+ ])
158
+ );
159
+ for (const k of ['pairs', 'targets', 'tracks', 'ambiguous', 'conflicts']) delete facts[k];
160
+ }
161
+ } finally {
162
+ await browser?.close();
163
+ }
164
+ }
165
+ }
166
+ }
167
+ if (!values.json) log(JSON.stringify(data, null, 2));
168
+ return { data, warnings: [] };
169
+ }