@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,202 @@
1
+ import path from 'node:path';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
4
+ import { parse as parseJs } from '@babel/parser';
5
+ import { generate, parse as parseCss, walk } from 'css-tree';
6
+ import { CliError } from '../cli-output.mjs';
7
+ import { loadMotionPatterns, motionPatternFile } from './motion-patterns.mjs';
8
+ import { readMotion } from './motion.mjs';
9
+
10
+ const extension = /\.(?:[cm]?[jt]sx?|css)$/;
11
+ const excluded = new Set(['node_modules','vendor','dist','build','out','coverage','output','test','tests','__tests__']);
12
+ const codeFile = name => extension.test(name) && !/\.(?:d\.ts|(?:spec|test)\.[cm]?[jt]sx?)$/.test(name) &&
13
+ !name.split('/').some(part => part.startsWith('.') || excluded.has(part));
14
+ const sourcePath = (config, name) => path.relative(config.root, name).split(path.sep).join('/');
15
+ const keyName = node => node?.name ?? node?.value;
16
+ const none = /^(?:none|initial|unset|inherit|revert(?:-layer)?|0(?:m?s)?)(?:\s*!important)?$/i;
17
+ const cssMotion = /^(?:-webkit-)?(?:animation|transition)(?:-[a-z-]+)?$/i;
18
+ const jsxMotion = new Set(['layout','layoutId','animate','whileHover','whileTap','whileDrag','whileFocus','whileInView','exit','variants']);
19
+ const importsFromMotion = /^(?:motion(?:\/(?:react(?:-client)?|mini))?|framer-motion)$/;
20
+ const motionExports = new Set(['AnimatePresence','animate','useAnimate','useSpring','spring']);
21
+
22
+ function codeFiles(config) {
23
+ try {
24
+ const output = execFileSync('git', ['ls-files','-z','--cached','--others','--exclude-standard','--','.'],
25
+ { cwd: config.root, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024, stdio: ['ignore','pipe','ignore'] });
26
+ return [...new Set(output.split('\0').filter(codeFile))].sort();
27
+ } catch {
28
+ const visit = directory => readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
29
+ if (entry.name.startsWith('.') || excluded.has(entry.name)) return [];
30
+ const full = path.join(directory, entry.name);
31
+ return entry.isDirectory() ? visit(full) : entry.isFile() ? [sourcePath(config, full)] : [];
32
+ });
33
+ return visit(config.root).filter(codeFile).sort();
34
+ }
35
+ }
36
+
37
+ function scanCss(source, record, firstLine = 1, context, location) {
38
+ const ast = parseCss(source, { context: context ?? 'stylesheet', positions: true });
39
+ const lineOf = node => firstLine + node.loc.start.line - 1;
40
+ const seen = new Set();
41
+ walk(ast, {
42
+ enter(node) {
43
+ if (node.type === 'Atrule' && /^(?:-webkit-)?keyframes$/i.test(node.name) && node.prelude)
44
+ record('keyframes:' + generate(node.prelude), lineOf(node), location);
45
+ if (node.type !== 'Declaration' || !cssMotion.test(node.property) || none.test(generate(node.value))) return;
46
+ if (this.atrule?.name === 'media' && /prefers-reduced-motion:reduce/.test(generate(this.atrule.prelude)) &&
47
+ /^(?:0(?:\.0+)?m?s|0?\.01ms)$/.test(generate(node.value))) return;
48
+ const selector = this.rule?.prelude ? generate(this.rule.prelude) : null;
49
+ const name = node.property.replace(/^-webkit-/i, '').toLowerCase().split('-')[0];
50
+ const match = selector ? 'css:' + selector : 'style:' + name;
51
+ const line = this.rule ? lineOf(this.rule) : lineOf(node);
52
+ const id = JSON.stringify([match, this.rule?.loc.start.offset ?? node.loc.start.offset]);
53
+ if (!seen.has(id)) { seen.add(id); record(match, line, location); }
54
+ },
55
+ });
56
+ }
57
+
58
+ function scanJs(source, file, record) {
59
+ const extension = path.extname(file);
60
+ const ts = /[cm]?tsx?$/.test(extension);
61
+ const plugins = [...(ts ? ['typescript'] : []), ...(!ts || extension === '.tsx' ? ['jsx'] : [])], bindings = new Map();
62
+ const { program } = parseJs(source, { sourceType: 'unambiguous', plugins, errorRecovery: true });
63
+ for (const node of program.body) if (node.type === 'ImportDeclaration' && importsFromMotion.test(node.source.value)) {
64
+ for (const specifier of node.specifiers) bindings.set(specifier.local.name,
65
+ specifier.type === 'ImportNamespaceSpecifier' ? '*' : keyName(specifier.imported) ?? 'motion');
66
+ }
67
+ const binding = node => {
68
+ if (node?.type === 'Identifier' || node?.type === 'JSXIdentifier') return bindings.get(node.name);
69
+ if (['MemberExpression','JSXMemberExpression'].includes(node?.type) &&
70
+ bindings.get(keyName(node.object)) === '*') return keyName(node.property);
71
+ };
72
+ const motionTag = node => {
73
+ if (['motion','m','Reorder'].includes(binding(node))) return true;
74
+ return node?.type === 'JSXMemberExpression' && motionTag(node.object);
75
+ };
76
+ function visit(node, scopes = [], inMotion = false, inStyle = false) {
77
+ if (typeof node?.type !== 'string') return;
78
+ const scope = /^(?:FunctionDeclaration|ClassDeclaration|VariableDeclarator|ObjectMethod|ClassMethod)$/.test(node.type)
79
+ ? keyName(node.id ?? node.key) : null;
80
+ if (typeof scope === 'string') scopes = [...scopes, scope];
81
+ const { start: { line } } = node.loc;
82
+ const add = match => record(match, line, scopes);
83
+ if (node.type === 'JSXOpeningElement') {
84
+ if (binding(node.name) === 'AnimatePresence') add('motion:AnimatePresence');
85
+ for (const attr of node.attributes) {
86
+ const name = keyName(attr.name);
87
+ if (motionTag(node.name) && jsxMotion.has(name) && attr.value?.expression?.value !== false)
88
+ record('motion:' + name, attr.loc.start.line, scopes);
89
+ if (typeof name === 'string' && name.startsWith('data-')) record('attribute:' + name, attr.loc.start.line, scopes, false);
90
+ if (name === 'style' && typeof attr.value?.value === 'string') scanCss(attr.value.value, record, attr.loc.start.line, 'declarationList', scopes);
91
+ }
92
+ inMotion ||= motionTag(node.name);
93
+ }
94
+ if (node.type === 'CallExpression') {
95
+ const name = binding(node.callee);
96
+ if (motionExports.has(name) && name !== 'AnimatePresence') add('motion:' + name);
97
+ if (node.callee.type === 'MemberExpression') {
98
+ const method = keyName(node.callee.property);
99
+ if (method === 'animate') record('web:animate', line, scopes, false);
100
+ if (method === 'spring') record('call:spring', line, scopes, false);
101
+ }
102
+ inMotion ||= motionExports.has(name);
103
+ }
104
+ if (node.type === 'ObjectProperty') {
105
+ const name = keyName(node.key), value = node.value;
106
+ if (name === 'type' && value?.value === 'spring') record('motion:spring', line, scopes, inMotion || (bindings.size > 0 && scopes.some(name => /spring|transition/i.test(name))));
107
+ if (typeof name === 'string' && cssMotion.test(name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase())) &&
108
+ (typeof value?.value === 'string' ? !none.test(value.value) : inStyle || value?.type === 'TemplateLiteral'))
109
+ add('style:' + name);
110
+ }
111
+ if (node.type === 'TemplateLiteral') {
112
+ const css = node.quasis.map(part => part.value.raw).join('var(--dynamic)');
113
+ if (/@(?:-webkit-)?keyframes\s|\b(?:animation|transition)\s*[-:]/i.test(css) && css.includes('{'))
114
+ scanCss(css, record, line, undefined, scopes);
115
+ }
116
+ inStyle ||= node.type === 'JSXAttribute' && keyName(node.name) === 'style';
117
+ for (const [key, child] of Object.entries(node)) {
118
+ if (['loc','comments','tokens','errors','leadingComments','trailingComments','innerComments'].includes(key)) continue;
119
+ if (Array.isArray(child)) child.forEach(item => visit(item, scopes, inMotion, inStyle));
120
+ else visit(child, scopes, inMotion, inStyle);
121
+ }
122
+ }
123
+ visit(program);
124
+ }
125
+
126
+ export function scanMotion(config, catalog = loadMotionPatterns(config), graph = readMotion(config), { mappedOnly = false } = {}) {
127
+ const declaration = sourcePath(config, path.join(config.design, motionPatternFile));
128
+ const consumers = new Map([...catalog.patterns.keys()].map(id => [id, []]));
129
+ const issues = [];
130
+ const issue = (code, source, message, line = null) => issues.push({ code, source, message, line, column: null });
131
+ const mappings = new Map();
132
+ for (const [id, pattern] of catalog.patterns) {
133
+ for (const frame of pattern.frames ?? []) {
134
+ const file = path.join(config.root, frame.source);
135
+ if (file.startsWith(config.design + path.sep) && existsSync(file)) consumers.get(id).push({ type: 'frame', ...frame });
136
+ else issue('MOTION_CONSUMER_MISSING', declaration, id + ' frame source does not exist in the design directory: ' + frame.source + '.');
137
+ }
138
+ for (const ref of pattern.consumers ?? []) {
139
+ if (!mappings.has(ref.file)) mappings.set(ref.file, []);
140
+ mappings.get(ref.file).push({ ...ref, id, hits: 0 });
141
+ }
142
+ }
143
+ for (const record of graph.records) {
144
+ if (!record.valid || !record.pattern) continue;
145
+ consumers.get(record.pattern.id)?.push({ type: 'edge', id: record.edge.id, ...record.edge.from,
146
+ sidecar: record.source, line: record.locations[record.pointer + '/pattern']?.line ?? record.locations[record.pointer]?.line ?? 1 });
147
+ }
148
+ // Check never follows symlinks or scans ignored/untracked dependencies.
149
+ const root = realpathSync(config.root);
150
+ let animations = 0, unmapped = 0, unused = 0;
151
+ for (const name of mappedOnly ? [...mappings.keys()].filter(codeFile).sort() : codeFiles(config)) {
152
+ if (name === sourcePath(config, path.join(config.design, 'tokens.css'))) continue;
153
+ const full = path.join(root, name);
154
+ try {
155
+ if (!lstatSync(full, { throwIfNoEntry: false })?.isFile() || realpathSync(full) !== full) continue;
156
+ const source = readFileSync(full, 'utf8');
157
+ if (!/animat|transition|keyframes|framer-motion|['"]motion(?:\/|['"])|spring|data-/i.test(source)) continue;
158
+ const refs = mappings.get(name) ?? [];
159
+ const sites = new Map();
160
+ const record = (match, line, within = [], required = true) => {
161
+ const key = JSON.stringify([match, line, within]);
162
+ if (!sites.has(key) || required) sites.set(key, { match, line, within, required });
163
+ };
164
+ if (name.endsWith('.css')) scanCss(source, record);
165
+ else scanJs(source, name, record);
166
+ for (const { match, line, within, required } of sites.values()) {
167
+ const hits = refs.filter(ref => ref.match === match && (!ref.within || within.includes(ref.within)));
168
+ if (required || hits.length) animations++;
169
+ if (!hits.length && required) {
170
+ unmapped++;
171
+ if (!mappedOnly) issue('MOTION_UNMAPPED', name, 'Map ' + match + (within.length ? ' within ' + within.at(-1) : '') + ' to a motion pattern.', line);
172
+ }
173
+ for (const ref of hits) ref.hits++;
174
+ for (const id of new Set(hits.map(ref => ref.id))) consumers.get(id).push({ type: 'code', source: name, line, match });
175
+ }
176
+ } catch (error) {
177
+ if (!mappedOnly) issue('MOTION_SCAN_FAILED', name, 'Could not scan source: ' + error.message.split('\n')[0]);
178
+ }
179
+ }
180
+ for (const [file, refs] of mappings) for (const ref of refs) if (!ref.hits)
181
+ issue('MOTION_CONSUMER_MISSING', declaration, ref.id + ' consumer did not match ' + file + ' (' + ref.match + ').');
182
+ for (const id of catalog.declared) if (!consumers.get(id).length &&
183
+ !catalog.variants.get(id)?.some(variant => consumers.get(variant).length)) {
184
+ unused++;
185
+ issue('MOTION_UNUSED', declaration, 'Pattern ' + id + ' has no consumers.');
186
+ }
187
+ return { consumers, issues, animations, unmapped, unused };
188
+ }
189
+
190
+ export function motionCodeExcerpt(config, catalog, source, line) {
191
+ if (!source || !Number.isSafeInteger(line) || line < 1) return null;
192
+ const isEdge = source.endsWith('.motion.json');
193
+ const graph = isEdge ? readMotion(config) : { records: [] };
194
+ const linked = [...scanMotion(config, catalog, graph, { mappedOnly: true }).consumers.values()].flat();
195
+ if (!linked.some(ref => ref.line === line && (isEdge ? ref.type === 'edge' && ref.sidecar === source :
196
+ ref.type === 'code' && ref.source === source))) return null;
197
+ const full = path.join(realpathSync(config.root), source);
198
+ if (realpathSync(full) !== full) return null;
199
+ const lines = readFileSync(full, 'utf8').split(/\r?\n/);
200
+ return lines.slice(Math.max(0, line - 4), line + 3).map((text, index) =>
201
+ [Math.max(1, line - 3) + index, text.slice(0, 500)]);
202
+ }
@@ -0,0 +1,111 @@
1
+ import path from 'node:path';
2
+ import { existsSync } from 'node:fs';
3
+ import { parseFragment } from 'parse5';
4
+ import { candidates } from '../../public/motion-identity.js';
5
+ import { relative } from './project.mjs';
6
+ import { buildSource } from './build.mjs';
7
+
8
+ function targetName(html, design, target) {
9
+ if (!html || target.frame) return '';
10
+ const rows = [],
11
+ ids = new Map();
12
+ function visit(node, parent) {
13
+ if (!node.tagName) return;
14
+ const attrs = Object.fromEntries(node.attrs.map((a) => [a.name, a.value]));
15
+ const i = rows.length;
16
+ const parts = JSON.parse(attrs['data-adg-owners'] ?? '[]').map(
17
+ (o) => [design, o.source].filter(Boolean).join('/') + '#' + o.export
18
+ );
19
+ rows.push({
20
+ i,
21
+ parent,
22
+ node,
23
+ attrs,
24
+ parts,
25
+ keys: JSON.parse(attrs['data-adg-keys'] ?? '[]'),
26
+ anchor: attrs['data-adg-id']
27
+ });
28
+ if (attrs.id) ids.set(attrs.id, node);
29
+ for (const child of node.childNodes) visit(child, i);
30
+ }
31
+ for (const node of parseFragment(html).childNodes) visit(node, -1);
32
+ const hits = candidates(rows, target);
33
+ if (hits.length !== 1) return '';
34
+ const [row] = hits;
35
+ function contents(node, referenced = false) {
36
+ if (!node) return '';
37
+ if (!node.tagName) return node.value ?? '';
38
+ const attrs = Object.fromEntries(node.attrs.map((attr) => [attr.name, attr.value]));
39
+ if (!referenced && (attrs.hidden !== undefined || attrs['aria-hidden'] === 'true')) return '';
40
+ if (attrs['aria-label']) return attrs['aria-label'];
41
+ if (node.tagName === 'img') return attrs.alt ?? '';
42
+ return node.childNodes.map((child) => contents(child, referenced)).join('');
43
+ }
44
+ const a = row.attrs;
45
+ const labelled = (a['aria-labelledby'] ?? '')
46
+ .split(/\s+/)
47
+ .map((id) => contents(ids.get(id), true))
48
+ .join(' ')
49
+ .trim();
50
+ const labels = a.id ? rows.filter((r) => r.node.tagName === 'label' && r.attrs.for === a.id) : [];
51
+ for (let p = rows[row.parent]; p; p = rows[p.parent]) {
52
+ if (p.node.tagName === 'label' && !p.attrs.for) { labels.push(p); break; }
53
+ }
54
+ return (
55
+ labelled ||
56
+ a['aria-label'] ||
57
+ labels.map((r) => contents(r.node)).join(' ') ||
58
+ a.alt ||
59
+ (row.node.tagName === 'input' && ['button', 'submit', 'reset'].includes(a.type) ? a.value : '') ||
60
+ contents(row.node) ||
61
+ a.title ||
62
+ a.placeholder ||
63
+ ''
64
+ )
65
+ .trim()
66
+ .replace(/\s+/g, ' ');
67
+ }
68
+
69
+ export function edgePresentation(edge, html, design) {
70
+ const t = edge.trigger;
71
+ const name = t.on === 'key' ? '' : targetName(html, design, t.target);
72
+ const target = name ? '“' + name + '”' : t.target.frame ? 'this frame' : 'the highlighted element';
73
+ const key =
74
+ {
75
+ Escape: 'Esc',
76
+ ArrowUp: 'Up Arrow',
77
+ ArrowDown: 'Down Arrow',
78
+ ArrowRight: 'Right Arrow',
79
+ ArrowLeft: 'Left Arrow',
80
+ ' ': 'Space'
81
+ }[t.key] ?? t.key;
82
+ const gesture = {
83
+ click: 'Click ' + target,
84
+ hover: 'Hover over ' + target,
85
+ focus: 'Focus ' + target,
86
+ key: 'Press ' + key,
87
+ input: 'Enter “' + (t.value ?? '') + '” in ' + target
88
+ }[t.on];
89
+ return { label: edge.label ?? gesture, gesture };
90
+ }
91
+
92
+ export function labelResolver(
93
+ config,
94
+ getBuild = (source) => buildSource(config, path.join(config.root, source), { write: false })
95
+ ) {
96
+ const builds = new Map();
97
+ return async (record) => {
98
+ if (!record?.valid) return record?.edge?.label;
99
+ const e = record.edge;
100
+ if (e.label) return e.label;
101
+ if (e.trigger.on === 'key' || !existsSync(path.join(config.root, e.from.source)))
102
+ return edgePresentation(e, null, '').label;
103
+ if (!builds.has(e.from.source)) builds.set(e.from.source, getBuild(e.from.source));
104
+ const built = await builds.get(e.from.source);
105
+ return edgePresentation(
106
+ e,
107
+ built?.frames.find((f) => f.name === e.from.frame)?.html,
108
+ relative(config, config.design)
109
+ ).label;
110
+ };
111
+ }
@@ -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
+ }