@whzxc/agent-design-gallery 0.14.1 → 0.15.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 (62) hide show
  1. package/README.md +26 -16
  2. package/package.json +1 -1
  3. package/public/access.css +15 -2
  4. package/public/app.js +708 -483
  5. package/public/arrangement-worker.js +7 -7
  6. package/public/arrangement.js +35 -30
  7. package/public/assets.js +60 -38
  8. package/public/auth.js +59 -4
  9. package/public/boards.js +124 -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 +26 -2
  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 +2 -0
  19. package/public/index.html +13 -9
  20. package/public/instance-actions.js +9 -2
  21. package/public/layout.js +156 -86
  22. package/public/selection.js +1 -1
  23. package/public/style.css +74 -152
  24. package/public/switcher.css +5 -4
  25. package/public/switcher.js +109 -34
  26. package/public/token-catalog.js +8 -3
  27. package/public/tokens.css +14 -1
  28. package/public/view-route.js +0 -1
  29. package/src/boards/board.mjs +30 -0
  30. package/src/boards/token-board.mjs +196 -0
  31. package/src/cli-output.mjs +8 -5
  32. package/src/cli.mjs +49 -29
  33. package/src/comments.mjs +293 -0
  34. package/src/http.mjs +2 -3
  35. package/src/hub/project-link.mjs +41 -0
  36. package/src/hub/registry.mjs +5 -0
  37. package/src/hub.mjs +14 -10
  38. package/src/link.mjs +13 -1
  39. package/src/server.mjs +57 -93
  40. package/src/service.mjs +46 -12
  41. package/src/toolkit/arch.mjs +3 -2
  42. package/src/toolkit/asset-rules.mjs +24 -1
  43. package/src/toolkit/commands.mjs +12 -7
  44. package/{public/review.js → src/toolkit/diff-document.mjs} +137 -43
  45. package/src/toolkit/diff-inputs.mjs +66 -30
  46. package/src/toolkit/diff.mjs +181 -39
  47. package/src/toolkit/impact-selection.mjs +25 -10
  48. package/src/toolkit/impact.mjs +32 -12
  49. package/src/toolkit/move-pairing.mjs +140 -0
  50. package/src/toolkit/project-index.mjs +2 -2
  51. package/src/toolkit/results.mjs +1 -1
  52. package/src/toolkit/review-document.mjs +435 -0
  53. package/src/toolkit/review-groups.mjs +29 -0
  54. package/src/toolkit/review-observation.mjs +131 -0
  55. package/src/toolkit/review-sheet.mjs +117 -0
  56. package/src/toolkit/review-specimens.mjs +60 -0
  57. package/src/toolkit/review.mjs +140 -0
  58. package/src/toolkit/runtime.mjs +1 -1
  59. package/src/toolkit/theme.mjs +16 -0
  60. package/public/annotations.js +0 -816
  61. package/public/labels.js +0 -122
  62. package/src/annotations.mjs +0 -238
package/public/labels.js DELETED
@@ -1,122 +0,0 @@
1
- import { icon } from './icons.js';
2
- // Retain screen-sized text; pure pans translate one layer until the camera settles.
3
- export function overlaps(a, b) {
4
- return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y;
5
- }
6
- // Candidate y is a text center; collision bounds include optional caption padding.
7
- export function placeLabels(candidates, obstacles, width, height, measure) {
8
- const occupied = [...obstacles], result = [];
9
- const sized = candidate => {
10
- const parts = candidate.parts.map(part => ({ ...part, width: measure(part) + (part.copyText === undefined || part.copyIcon === false ? 0 : 16) }));
11
- const w = parts.reduce((sum, p) => sum + p.width + (p.gap ?? 0), 0) + (candidate.paddingRight ?? 0);
12
- const h = candidate.height ?? Math.max(...parts.map(p => p.size)) * 1.2;
13
- return { ...candidate, parts, width: w, height: h, y: candidate.y - h / 2 };
14
- };
15
- const fits = label => {
16
- const box = label.within;
17
- return label.width <= label.slot && label.x >= 0 && label.y >= 0 && label.x + label.width <= width && label.y + label.height <= height &&
18
- (!box || (label.x >= box.x && label.y > box.y + 2 && label.x + label.width < box.x + box.width && label.y + label.height <= box.y + box.height)) &&
19
- !occupied.some(box => overlaps(label, box));
20
- };
21
- for (const batch of candidates) {
22
- const labels = (Array.isArray(batch) ? batch : [batch]).map(candidate => {
23
- let parts = candidate.parts, label = sized(candidate);
24
- while (!fits(label) && parts.some(p => p.optional)) {
25
- const last = parts.findLastIndex(p => p.optional);
26
- parts = parts.filter((_, i) => i !== last);
27
- label = sized({...candidate, parts});
28
- }
29
- if (!fits(label) && parts.some(p => p.copyText !== undefined)) {
30
- label = sized({...candidate,parts:parts.map(p => p.copyText === undefined ? p : {...p,copyIcon:false})});
31
- }
32
- return label;
33
- });
34
- if (labels.some((label, i) => !fits(label) || labels.slice(0, i).some(other => overlaps(label, other)))) continue;
35
- occupied.push(...labels); result.push(...labels);
36
- }
37
- return result;
38
- }
39
- export class Labels {
40
- constructor(root, onCopyError, onSelect) {
41
- this.root = root;
42
- this.onCopyError = onCopyError;
43
- this.onSelect = onSelect;
44
- this.layer = document.createElement('div');
45
- this.layer.className = 'label-layer';
46
- root.append(this.layer);
47
- this.anchor = null;
48
- this.nodes = new Map();
49
- this.metrics = new Map();
50
- this.context = document.createElement('canvas').getContext('2d');
51
- }
52
- pan(view) {
53
- if (!this.anchor || view.scale !== this.anchor.scale ||
54
- (this.pinned && (view.x !== this.anchor.x || view.y !== this.anchor.y)) ||
55
- Math.abs(view.x - this.anchor.x) > 32 || Math.abs(view.y - this.anchor.y) > 32) return false;
56
- this.layer.style.transform = `translate(${view.x - this.anchor.x}px,${view.y - this.anchor.y}px)`;
57
- return true;
58
- }
59
- update(candidates, obstacles, width, height, font, view) {
60
- this.anchor = { ...view };
61
- this.layer.style.transform = 'translate(0px,0px)';
62
- const shown = new Set();
63
- const measure = part => {
64
- const spec = `${part.weight ?? 400} ${part.size}px ${font}`, key = spec + '|' + part.text;
65
- if (!this.metrics.has(key)) { this.context.font = spec; this.metrics.set(key, this.context.measureText(part.text).width); }
66
- return this.metrics.get(key);
67
- };
68
- const placed = placeLabels(candidates, obstacles, width, height, measure);
69
- this.pinned = placed.some(label => label.pinned);
70
- for (const label of placed) {
71
- shown.add(label.id);
72
- let node = this.nodes.get(label.id);
73
- if (!node) { node = document.createElement('div'); node.className = 'canvas-label'; this.nodes.set(label.id, node); this.layer.append(node); }
74
- const signature = JSON.stringify(label.parts.map(({color,weight,width,...part})=>part));
75
- if (node.dataset.signature !== signature) {
76
- node.replaceChildren(...label.parts.map(part => {
77
- const span = document.createElement(part.copyText !== undefined ? 'button' : part.timestamp ? 'time' : 'span'); span.textContent = part.text;
78
- if (part.copyText !== undefined) {
79
- span.type = 'button';
80
- span.className = 'label-copy';
81
- if (part.selection) {
82
- span.dataset.sourcePath=part.selection.path;
83
- if (part.selection.form!==undefined) span.dataset.form=part.selection.form;
84
- }
85
- const glyph = document.createElement('span'); glyph.className = 'label-copy-icon';
86
- glyph.hidden = part.copyIcon === false;
87
- const feedback = copied => {
88
- span.toggleAttribute('data-copied', copied);
89
- glyph.innerHTML = icon(copied ? 'check' : 'copy', 12);
90
- span.setAttribute('aria-label', copied ? `Copied ${part.copyText}` : `Copy ${part.copyText} name`);
91
- span.title = copied ? 'Copied' : 'Copy name';
92
- };
93
- feedback(false); span.append(glyph);
94
- for (const event of ['pointerdown','pointerup','dblclick']) span.addEventListener(event, e => e.stopPropagation());
95
- span.onkeydown = e => {if (e.key === 'Enter' || e.key === ' ') e.stopPropagation()};
96
- let timer;
97
- span.onclick = async e => {
98
- e.stopPropagation();
99
- if (part.selection && !e.target.closest('.label-copy-icon')) this.onSelect?.(part.selection);
100
- try {
101
- await navigator.clipboard.writeText(part.copyText);
102
- this.onCopyError?.(null);
103
- feedback(true);clearTimeout(timer);timer=setTimeout(()=>feedback(false),1200);
104
- } catch (error) {this.onCopyError?.(error)}
105
- };
106
- }
107
- if (part.timestamp) {span.dateTime = part.timestamp;span.title = part.title;span.style.pointerEvents = 'auto'}
108
- Object.assign(span.style, { fontSize: `${part.size}px`, fontWeight: part.weight ?? 400, color: part.color, marginLeft: `${part.gap ?? 0}px` });
109
- return span;
110
- }));
111
- node.dataset.signature = signature;
112
- }
113
- for (const [i,part] of label.parts.entries()) Object.assign(node.children[i].style,{fontSize:`${part.size}px`,fontWeight:part.weight??400,color:part.color,marginLeft:`${part.gap??0}px`});
114
- if (node.hidden) node.hidden = false;
115
- node.style.transform = `translate(${label.x}px,${label.y}px)`;
116
- const height = `${label.height}px`;
117
- if (node.style.height !== height) node.style.height = height;
118
- }
119
- for (const [id, node] of this.nodes) if (!shown.has(id) && !node.hidden) node.hidden = true;
120
- }
121
- clear() { this.layer.replaceChildren(); this.nodes.clear(); this.metrics.clear(); this.anchor = null; }
122
- }
@@ -1,238 +0,0 @@
1
- import { readFile, mkdir, rename, writeFile } from 'node:fs/promises';
2
- import { existsSync } from 'node:fs';
3
- import { createHash, randomUUID } from 'node:crypto';
4
- import { execFileSync } from 'node:child_process';
5
- import path from 'node:path';
6
- import { CliError } from './cli-output.mjs';
7
- import { defaultStateDirectory } from './hub/registry.mjs';
8
- import { relative } from './toolkit/project.mjs';
9
-
10
- const queues = new Map();
11
- const validStatuses = ['open', 'addressed', 'resolved'];
12
-
13
- export function annotationFile(project, state = defaultStateDirectory) {
14
- return path.join(state, 'annotations', createHash('sha256').update(path.resolve(project)).digest('hex') + '.json');
15
- }
16
-
17
- function gitHead(project) {
18
- try {
19
- return execFileSync('git', ['rev-parse', 'HEAD'], { cwd: project, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() || null;
20
- } catch {
21
- return null;
22
- }
23
- }
24
-
25
- function validateElement(element) {
26
- if (element === null || element === undefined) return null;
27
- if (typeof element !== 'object' || Array.isArray(element) ||
28
- typeof element.id !== 'string' || !element.id.trim() ||
29
- typeof element.owner !== 'object' || !element.owner || Array.isArray(element.owner) ||
30
- typeof element.owner.source !== 'string' || !element.owner.source.trim() ||
31
- !(element.owner.export === null || (typeof element.owner.export === 'string' && element.owner.export.trim())) ||
32
- !['x', 'y'].every(k => Number.isFinite(element[k]) && element[k] >= 0 && element[k] <= 1)) {
33
- throw new CliError('USAGE_INVALID', 'Provide a valid element anchor with id, owner and normalized x/y coordinates.');
34
- }
35
- return {
36
- id: element.id.trim(),
37
- owner: { source: element.owner.source.trim(), export: element.owner.export === null ? null : element.owner.export.trim() },
38
- x: element.x,
39
- y: element.y,
40
- };
41
- }
42
-
43
- function normalizeRow(row) {
44
- return {
45
- ...row,
46
- element: row.element ?? null,
47
- replies: Array.isArray(row.replies) ? row.replies : [],
48
- status: validStatuses.includes(row.status) ? row.status : 'open',
49
- };
50
- }
51
-
52
- export async function annotations(project, state, action = 'list', payload = {}) {
53
- const file = annotationFile(project, state);
54
- const previous = queues.get(file) ?? Promise.resolve();
55
- const operation = previous.catch(() => {}).then(async () => {
56
- let rows;
57
- try { rows = JSON.parse(await readFile(file, 'utf8')); }
58
- catch (e) { if (e.code !== 'ENOENT') throw new CliError('STATE_INVALID', `Cannot read annotations: ${e.message}`); rows = []; }
59
- if (!Array.isArray(rows)) throw new CliError('STATE_INVALID', 'Cannot read annotations: expected a JSON array.');
60
- rows = rows.map(normalizeRow);
61
- if (action === 'list') {
62
- const status = payload.status ?? 'all';
63
- if (![...validStatuses, 'all'].includes(status)) throw new CliError('USAGE_INVALID', 'Choose --status=open, addressed, resolved or all.');
64
- return status === 'all' ? rows : rows.filter(r => r.status === status);
65
- }
66
- let row = rows.find(r => r.id === payload.id);
67
- if (action !== 'create' && !row) throw new CliError('USAGE_INVALID', 'Annotation not found. List annotations to choose an ID.');
68
- if (action === 'read') return row;
69
- const now = new Date().toISOString();
70
- if (action === 'create' || action === 'update') {
71
- const value = { ...row, ...payload };
72
- if (typeof value.note !== 'string' || !value.note.trim() || value.note.length > 10000 ||
73
- typeof value.source !== 'string' || !value.source ||
74
- typeof value.frame !== 'string' || !value.frame ||
75
- !['x', 'y'].every(k => Number.isFinite(value[k]) && value[k] >= 0 && value[k] <= 1)) {
76
- throw new CliError('USAGE_INVALID', 'Provide a note, source, frame and normalized x/y coordinates.');
77
- }
78
- const element = validateElement(Object.hasOwn(payload, 'element') ? payload.element : row?.element ?? null);
79
- const fields = { note: value.note, source: value.source, frame: value.frame, x: value.x, y: value.y, element };
80
- if (row) {
81
- Object.assign(row, fields, { updatedAt: now });
82
- } else {
83
- row = {
84
- ...fields,
85
- id: randomUUID(),
86
- number: Math.max(0, ...rows.map(r => r.number)) + 1,
87
- replies: [],
88
- revision: gitHead(project),
89
- status: 'open',
90
- createdAt: now,
91
- updatedAt: now,
92
- };
93
- rows.push(row);
94
- }
95
- } else if (action === 'reply') {
96
- if (typeof payload.message !== 'string' || !payload.message.trim() || payload.message.length > 10000) {
97
- throw new CliError('USAGE_INVALID', 'Provide a non-empty --message up to 10000 characters.');
98
- }
99
- const author = payload.author ?? 'agent';
100
- if (!['user', 'agent'].includes(author)) throw new CliError('USAGE_INVALID', 'Reply author must be user or agent.');
101
- row.replies = [...row.replies, { author, message: payload.message.trim(), at: now }];
102
- row.updatedAt = now;
103
- } else if (action === 'address') {
104
- if (typeof payload.message !== 'string' || !payload.message.trim() || payload.message.length > 10000) {
105
- throw new CliError('USAGE_INVALID', 'Provide a non-empty --message explaining what was addressed.');
106
- }
107
- row.replies = [...row.replies, { author: 'agent', message: payload.message.trim(), at: now }];
108
- row.status = 'addressed';
109
- row.updatedAt = now;
110
- } else if (action === 'resolve') {
111
- Object.assign(row, { status: 'resolved', updatedAt: now });
112
- } else if (action === 'reopen') {
113
- Object.assign(row, { status: 'open', updatedAt: now });
114
- } else if (action === 'delete') {
115
- rows = rows.filter(r => r.id !== payload.id);
116
- } else {
117
- throw new CliError('USAGE_INVALID', 'Unknown annotation action.');
118
- }
119
- await mkdir(path.dirname(file), { recursive: true });
120
- const temp = file + '.' + randomUUID();
121
- await writeFile(temp, JSON.stringify(rows, null, 2));
122
- await rename(temp, file);
123
- return row;
124
- });
125
- queues.set(file, operation);
126
- try { return await operation; } finally { if (queues.get(file) === operation) queues.delete(file); }
127
- }
128
-
129
- function toProjectPath(config, candidate) {
130
- if (!candidate) return null;
131
- const inDesign = path.join(config.design, candidate);
132
- if (existsSync(inDesign)) return relative(config, inDesign);
133
- const inRoot = path.join(config.root, candidate);
134
- if (existsSync(inRoot)) return relative(config, inRoot);
135
- const prefix = path.relative(config.root, config.design).split(path.sep).join('/');
136
- if (!prefix || candidate === prefix || candidate.startsWith(prefix + '/')) return candidate;
137
- return path.posix.join(prefix, candidate);
138
- }
139
-
140
- const quoteShell = value => /^[A-Za-z0-9_./:=+-]+$/.test(value) ? value : `'${String(value).replace(/'/g, `'\\''`)}'`;
141
-
142
- export async function readAnnotationContext(config, state, id) {
143
- const row = await annotations(config.root, state, 'read', { id });
144
- const sourcePath = toProjectPath(config, row.source);
145
- const ownerSourcePath = row.element?.owner?.source ? toProjectPath(config, row.element.owner.source) : null;
146
- const head = gitHead(config.root);
147
- let stale = true, frameBox = null, elementBox = null;
148
- const fullFile = path.join(config.root, sourcePath);
149
- if (sourcePath?.endsWith('.tsx') && existsSync(fullFile)) {
150
- const [{ buildSource }, { frameDocument }, { launch, browserTask }, { installFramePrimitives }, { elementIdentities }] = await Promise.all([
151
- import('./toolkit/build.mjs'),
152
- import('./toolkit/frame-document.mjs'),
153
- import('./toolkit/browser.mjs'),
154
- import('./toolkit/frame-primitives.mjs'),
155
- import('./toolkit/frame-identity.mjs'),
156
- ]);
157
- let browser;
158
- try {
159
- const built = await buildSource(config, fullFile, { write: false });
160
- const frame = built.frames.find(f => f.name === row.frame);
161
- if (frame) {
162
- browser = await launch();
163
- const page = await browserTask(browser, () => browser.newPage({
164
- viewport: { width: frame.width ?? 1600, height: frame.height ?? 1200 },
165
- locale: 'en-US', timezoneId: 'UTC', deviceScaleFactor: 1,
166
- }));
167
- await page.setContent(frameDocument(frame, 'light', built.css), { waitUntil: 'load' });
168
- await page.evaluate(() => document.fonts.ready);
169
- await page.addScriptTag({ content: `${installFramePrimitives}; installFramePrimitives();` });
170
- const observed = await page.evaluate(() => {
171
- const shell = document.querySelector('[data-adg-frame]'), root = shell?.firstElementChild;
172
- if (!root || shell.children.length !== 1) return null;
173
- const { inventory, relativeBox, reads, identityNode } = globalThis.__adgFramePrimitives;
174
- const origin = shell.getBoundingClientRect(), { elements, paths, neutralCandidates } = inventory(root);
175
- const { style, rect } = reads();
176
- const box = r => relativeBox(r, origin, true);
177
- function clipped(node) {
178
- const nr = rect(node);
179
- let left = Math.max(nr.left, origin.left), right = Math.min(nr.right, origin.right);
180
- let top = Math.max(nr.top, origin.top), bottom = Math.min(nr.bottom, origin.bottom);
181
- for (let p = node; p && p !== shell; p = p.parentElement) {
182
- const s = style(p);
183
- if (s.display === 'none' || (p === node && s.visibility !== 'visible') || Number(s.opacity) === 0) return null;
184
- if (p !== node && s.display !== 'inline') {
185
- const cr = rect(p);
186
- if (/(hidden|clip|scroll|auto)/.test(s.overflowX)) { left = Math.max(left, cr.left); right = Math.min(right, cr.right); }
187
- if (/(hidden|clip|scroll|auto)/.test(s.overflowY)) { top = Math.max(top, cr.top); bottom = Math.min(bottom, cr.bottom); }
188
- }
189
- }
190
- return right > left && bottom > top ? box({ left, right, top, bottom }) : null;
191
- }
192
- const identities = [], boxes = {};
193
- for (const node of elements) {
194
- const p = paths.get(node), own = JSON.parse(node.getAttribute('data-adg-owners') ?? '[]');
195
- identities.push(identityNode(node, p, paths.get(node.parentElement) ?? null, own, style(node), neutralCandidates.has(node)));
196
- boxes[p] = clipped(node);
197
- }
198
- return { frameBox: { x: 0, y: 0, width: origin.width, height: origin.height }, identities, boxes };
199
- });
200
- if (observed) {
201
- frameBox = observed.frameBox;
202
- if (!row.element) {
203
- stale = false;
204
- } else {
205
- const assigned = elementIdentities(observed.identities, { source: sourcePath, frame: frame.name });
206
- const hit = assigned.find(item => item.id === row.element.id);
207
- const box = hit ? observed.boxes[hit.path] : null;
208
- if (box) {
209
- stale = false;
210
- elementBox = box;
211
- }
212
- }
213
- }
214
- }
215
- } catch {
216
- stale = true;
217
- } finally {
218
- await browser?.close();
219
- }
220
- }
221
- const inspectElementFlag = row.element?.id && !stale ? ` --element=${quoteShell(row.element.id)}` : '';
222
- return {
223
- ...row,
224
- project: config.root,
225
- sourcePath,
226
- ownerSourcePath,
227
- export: row.element?.owner?.export ?? null,
228
- elementId: row.element?.id ?? null,
229
- stale,
230
- frameBox,
231
- elementBox,
232
- head,
233
- commands: {
234
- inspect: `adg inspect ${quoteShell(sourcePath)} --frame=${quoteShell(row.frame)}${inspectElementFlag} --json`,
235
- render: `adg render ${quoteShell(sourcePath)} --frame=${quoteShell(row.frame)} --json`,
236
- },
237
- };
238
- }