@whzxc/agent-design-gallery 0.14.0 → 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 (64) 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/build-worker.mjs +6 -2
  44. package/src/toolkit/build.mjs +4 -2
  45. package/src/toolkit/commands.mjs +12 -7
  46. package/{public/review.js → src/toolkit/diff-document.mjs} +137 -43
  47. package/src/toolkit/diff-inputs.mjs +66 -30
  48. package/src/toolkit/diff.mjs +181 -39
  49. package/src/toolkit/impact-selection.mjs +25 -10
  50. package/src/toolkit/impact.mjs +32 -12
  51. package/src/toolkit/move-pairing.mjs +140 -0
  52. package/src/toolkit/project-index.mjs +2 -2
  53. package/src/toolkit/results.mjs +1 -1
  54. package/src/toolkit/review-document.mjs +435 -0
  55. package/src/toolkit/review-groups.mjs +29 -0
  56. package/src/toolkit/review-observation.mjs +131 -0
  57. package/src/toolkit/review-sheet.mjs +117 -0
  58. package/src/toolkit/review-specimens.mjs +60 -0
  59. package/src/toolkit/review.mjs +140 -0
  60. package/src/toolkit/runtime.mjs +1 -1
  61. package/src/toolkit/theme.mjs +16 -0
  62. package/public/annotations.js +0 -816
  63. package/public/labels.js +0 -122
  64. package/src/annotations.mjs +0 -238
@@ -0,0 +1,131 @@
1
+ /** Collect post-layout paint inputs in the design document. Runs inside Chromium. */
2
+ export async function observeFrame() {
3
+ await document.fonts.ready;
4
+ await Promise.allSettled([...document.images].map(image => image.decode()));
5
+ const root = document.querySelector('[data-adg-frame]');
6
+ const { relativeBox, textRects, reads } = globalThis.__adgFramePrimitives;
7
+ const { style: styleFor, rect: rectFor } = reads();
8
+ const origin = rectFor(root), paints = [], uncertain = new Set();
9
+ const box = rect => relativeBox(rect, origin);
10
+ const onscreen = rect => rect.width > 0 && rect.height > 0 && rect.right > origin.left && rect.left < origin.right &&
11
+ rect.bottom > origin.top && rect.top < origin.bottom;
12
+ const typography = ['color', 'font-family', 'font-size', 'font-style', 'font-weight', 'font-stretch', 'font-feature-settings',
13
+ 'font-variation-settings', 'font-optical-sizing', 'font-kerning', 'font-variant', 'text-transform', 'text-shadow',
14
+ 'letter-spacing', 'word-spacing', 'text-decoration-line', 'text-decoration-color', 'text-decoration-style',
15
+ 'text-decoration-thickness', 'text-underline-offset', 'text-overflow', 'direction', 'writing-mode',
16
+ '-webkit-text-fill-color', '-webkit-text-stroke-width', '-webkit-text-stroke-color'];
17
+ const composition = ['transform', 'opacity', 'z-index', 'overflow-x', 'overflow-y', 'filter', 'backdrop-filter',
18
+ 'mix-blend-mode', 'clip-path', 'mask-image', 'perspective', 'isolation', 'object-fit', 'object-position'];
19
+ const svgPaint = ['fill', 'fill-opacity', 'fill-rule', 'stroke', 'stroke-width', 'stroke-opacity', 'stroke-linecap',
20
+ 'stroke-linejoin', 'stroke-miterlimit', 'stroke-dasharray', 'stroke-dashoffset', 'paint-order', 'vector-effect',
21
+ 'opacity', 'transform', 'color', 'visibility', 'display', 'stop-color', 'stop-opacity', 'flood-color', 'flood-opacity',
22
+ 'clip-path', 'mask-image', 'filter', 'x', 'y', 'cx', 'cy', 'r', 'rx', 'ry', 'd'];
23
+ const properties = (style, names) => Object.fromEntries(names.map(name => [name, style.getPropertyValue(name)]));
24
+ const transparent = color => color === 'rgba(0, 0, 0, 0)' || color === 'transparent';
25
+ const sides = ['top', 'right', 'bottom', 'left'];
26
+ const radii = ['border-top-left-radius', 'border-top-right-radius', 'border-bottom-right-radius', 'border-bottom-left-radius'];
27
+ function colorsAndBorders(style) {
28
+ const result = {};
29
+ if (!transparent(style.backgroundColor)) result['background-color'] = style.backgroundColor;
30
+ if (style.backgroundImage !== 'none') Object.assign(result, properties(style, ['background-image', 'background-size',
31
+ 'background-position', 'background-repeat', 'background-origin', 'background-clip', 'background-blend-mode', 'background-attachment']));
32
+ for (const side of sides) {
33
+ const prefix = `border-${side}`;
34
+ const width = style.getPropertyValue(`${prefix}-width`);
35
+ const color = style.getPropertyValue(`${prefix}-color`);
36
+ if (parseFloat(width) && !transparent(color)) {
37
+ result[prefix] = [width, style.getPropertyValue(`${prefix}-style`), color].join(' ');
38
+ }
39
+ }
40
+ if (style.boxShadow !== 'none') result['box-shadow'] = style.boxShadow;
41
+ if (style.outlineStyle !== 'none' && parseFloat(style.outlineWidth) && !transparent(style.outlineColor)) {
42
+ Object.assign(result, properties(style, ['outline-width', 'outline-style', 'outline-color', 'outline-offset']));
43
+ }
44
+ if (Object.keys(result).length) Object.assign(result, properties(style, radii));
45
+ return result;
46
+ }
47
+
48
+ function flags(style, node) {
49
+ for (const property of ['filter', 'backdrop-filter', 'mix-blend-mode', 'clip-path', 'mask-image', 'border-image-source', 'perspective']) {
50
+ const value = style.getPropertyValue(property);
51
+ if (value && !['none', 'normal'].includes(value)) uncertain.add(property);
52
+ }
53
+ if (style.backgroundImage.includes('url(') && !style.backgroundImage.includes('data:')) uncertain.add('external background');
54
+ if (style.clip !== 'auto' || style.backgroundClip === 'text' || style.contentVisibility !== 'visible') uncertain.add('clipping');
55
+ if (node.matches('canvas,video,iframe,object,embed,foreignObject,svg use')) uncertain.add(node.localName);
56
+ }
57
+
58
+ function add(kind, rect, values) {
59
+ paints.push({ kind, box: box(rect), values });
60
+ }
61
+
62
+ function svg(node) {
63
+ const children = [node, ...node.querySelectorAll('*')];
64
+ const ids = new Map(children.filter(child => child.id).map((child, index) => [child.id, `ref-${index}`]));
65
+ const normalize = text => text.replace(/#([^\s)'";]+)/g, (raw, id) => ids.has(id) ? `#${ids.get(id)}` : raw);
66
+ return children.map(child => {
67
+ const style = styleFor(child);
68
+ flags(style, child);
69
+ const attrs = [...child.attributes].filter(({ name }) => name !== 'class' && name !== 'style' && name !== 'id' &&
70
+ name !== 'role' && !name.startsWith('data-') && !name.startsWith('aria-'));
71
+ const attributes = Object.fromEntries(attrs.map(({ name, value }) => [name, normalize(value)]).sort(([a], [b]) => a.localeCompare(b)));
72
+ const text = /^(text|tspan|textPath)$/.test(child.localName) ? child.textContent : undefined;
73
+ const appearance = Object.fromEntries(svgPaint.map(name => [name, normalize(style.getPropertyValue(name))]));
74
+ return [child.localName, attributes, appearance, text];
75
+ });
76
+ }
77
+
78
+ function visit(node) {
79
+ const style = styleFor(node);
80
+ if (style.display === 'none' || style.opacity === '0') return;
81
+ if (style.contentVisibility === 'hidden') { uncertain.add('clipping'); return; }
82
+ const rect = rectFor(node);
83
+ const visible = style.visibility === 'visible' && onscreen(rect);
84
+ if (!visible && style.visibility === 'visible' && (style.boxShadow !== 'none' || style.outlineStyle !== 'none' || style.filter !== 'none')) {
85
+ uncertain.add('off-frame paint');
86
+ }
87
+ if (visible) {
88
+ flags(style, node);
89
+ const paint = colorsAndBorders(style);
90
+ if (Object.keys(paint).length) add('paint', rect, paint);
91
+ if (node instanceof SVGSVGElement) {
92
+ add('svg', rect, { vector: svg(node), ...properties(style, composition) });
93
+ return;
94
+ }
95
+ if (node instanceof HTMLImageElement) {
96
+ const content = node.currentSrc || node.src;
97
+ if (content && !content.startsWith('data:')) uncertain.add('external image');
98
+ if (!node.complete || !node.naturalWidth) uncertain.add('image decode');
99
+ add('image', rect, { content, intrinsic: [node.naturalWidth, node.naturalHeight], ...properties(style, composition) });
100
+ }
101
+ if (node.matches('input,textarea,select,progress,meter')) {
102
+ uncertain.add('native control');
103
+ add('control', rect, { type: node.type, value: node.type === 'password' ? '' : node.value,
104
+ placeholder: node.placeholder, checked: node.checked, ...properties(style, typography) });
105
+ }
106
+ if (style.transform !== 'none' || style.opacity !== '1' || style.zIndex !== 'auto' || style.isolation === 'isolate' ||
107
+ style.overflowX !== 'visible' || style.overflowY !== 'visible' || style.filter !== 'none' || style.clipPath !== 'none') {
108
+ add('compositing', rect, { ...properties(style, composition), ...properties(style, radii) });
109
+ }
110
+ for (const pseudo of ['::before', '::after', '::marker']) {
111
+ const appearance = getComputedStyle(node, pseudo);
112
+ if (appearance.content === 'none' || appearance.content === 'normal') continue;
113
+ if (appearance.display === 'none') continue;
114
+ flags(appearance, node);
115
+ uncertain.add('generated content');
116
+ add(pseudo, rect, { content: appearance.content, ...colorsAndBorders(appearance), ...properties(appearance, typography),
117
+ ...properties(appearance, ['position', 'width', 'height', 'inset', 'transform', 'opacity']) });
118
+ }
119
+ }
120
+ for (const child of node.childNodes) {
121
+ if (child.nodeType === Node.ELEMENT_NODE) visit(child);
122
+ if (child.nodeType === Node.TEXT_NODE && child.textContent.trim() && style.visibility === 'visible') {
123
+ const lines = textRects(child).rects.filter(onscreen);
124
+ if (lines.length) add('text', lines[0], { text: child.textContent, lines: lines.map(box), ...properties(style, typography) });
125
+ }
126
+ }
127
+ }
128
+ if ([...document.styleSheets].some(sheet => [...sheet.cssRules].some(rule => rule instanceof CSSFontFaceRule))) uncertain.add('embedded or external font');
129
+ visit(root);
130
+ return { size: { width: origin.width, height: origin.height }, paints, uncertain: [...uncertain].sort() };
131
+ }
@@ -0,0 +1,117 @@
1
+ import { groupReview } from './review-groups.mjs';
2
+ import { renderReviewFailures } from './diff-document.mjs';
3
+ import { browserTask, readyResources } from './browser.mjs';
4
+
5
+ const escapeHtml = value => String(value ?? '').replace(/[&<>"']/g, char => (
6
+ { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[char]
7
+ ));
8
+
9
+ export function reviewSheetHtml(review, theme, frameOrder = [], designDirs = { before: 'design', after: 'design' }) {
10
+ const order = new Map(frameOrder.map((row, index) => [JSON.stringify([row.source, row.frame]), index]));
11
+ const compare = (a, b) => a.source.localeCompare(b.source, 'en') ||
12
+ (order.get(JSON.stringify([a.source, a.frame])) ?? 0) - (order.get(JSON.stringify([b.source, b.frame])) ?? 0);
13
+ const grouped = groupReview(review);
14
+ const added = [...review.sections.added].sort(compare);
15
+ const direct = review.sections.changed.filter(entry => entry.change?.kind !== 'inherited').sort(compare);
16
+ const removed = [...review.sections.removed].sort(compare);
17
+ const groups = grouped.groups.map(group => ({ ...group, outliers: group.outliers.filter(entry => entry !== group.representative) }));
18
+ const representativeByFrame = new Map(groups.map(group => [group.representative, group]));
19
+ const outliers = groups.flatMap(group => group.outliers);
20
+ const changed = [...direct, ...groups.flatMap(group => [group.representative, ...group.outliers])];
21
+ const [firstAdded, ...otherAdded] = added;
22
+ const [firstDirect, ...otherDirect] = direct;
23
+ const priority = new Map([firstAdded, firstDirect, ...representativeByFrame.keys(), ...otherAdded, ...otherDirect,
24
+ ...outliers].filter(Boolean).slice(0, 12).map((entry, index) => [entry, index]));
25
+ const frameCount = entry => {
26
+ const group = representativeByFrame.get(entry);
27
+ return group ? group.frames.length - group.outliers.length : 1;
28
+ };
29
+ const name = (entry, dir) => {
30
+ const source = dir && entry.source.startsWith(`${dir}/`) ? entry.source.slice(dir.length + 1) : entry.source;
31
+ return `<code>${escapeHtml(source.replace(/\.[^./]+$/, ''))}#${escapeHtml(entry.frame)}</code>`;
32
+ };
33
+ const card = entry => {
34
+ const row = entry.themes.find(row => row.theme === theme);
35
+ const capture = side => {
36
+ const src = row?.images?.[side];
37
+ const sizeInfo = row?.[`${side}Size`];
38
+ const width = sizeInfo && sizeInfo.width * Math.min(1, 480 / sizeInfo.height);
39
+ const size = Number.isFinite(width) && width > 0 ? ` style="width:${width}px"` : '';
40
+ const image = src?.startsWith('data:image/png;base64,') ? `<img src="${escapeHtml(src)}" alt=""${size}>` : '';
41
+ return `<div class="capture">${image}</div>`;
42
+ };
43
+ const images = entry.status === 'added' ? capture('after') :
44
+ `${capture('before')}<span class="arrow" aria-hidden="true">→</span>${capture('after')}`;
45
+ const others = (representativeByFrame.get(entry)?.frames.length ?? 1) - 1;
46
+ return `<article data-source="${escapeHtml(entry.source)}" data-frame="${escapeHtml(entry.frame)}" data-priority="${priority.get(entry)}" data-frame-count="${frameCount(entry)}"><div class="label">${name(entry, designDirs.after)}${others ? `<span>+${others}</span>` : ''}</div><div class="images">${images}</div></article>`;
47
+ };
48
+ const section = (label, entries, render, list = 'div') => entries.length ?
49
+ `<section class="${label.toLowerCase()}"><h2>${label}</h2><${list} class="cells">${entries.map(render).join('')}</${list}></section>` : '';
50
+ const more = [...added, ...changed].filter(entry => !priority.has(entry)).reduce((sum, entry) => sum + frameCount(entry), 0);
51
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>${escapeHtml(review.label)}</title>
52
+ <style>
53
+ :root { color-scheme:light; --canvas:#f5f5f3; --text:#20211f; --muted:#575953; --border:#d0d1cc; }
54
+ .added { --accent:#235c38; --edge:#95b89f; }
55
+ .changed { --accent:#76500f; --edge:#c5ad77; }
56
+ .removed { --accent:#923a3a; --edge:#c89595; }
57
+ @media (prefers-color-scheme: dark) {
58
+ :root { color-scheme:dark; --canvas:#121212; --text:#efefed; --muted:#b3b3ae; --border:#52534e; }
59
+ .added { --accent:#a4d5ae; --edge:#557a60; }
60
+ .changed { --accent:#edd097; --edge:#8d7547; }
61
+ .removed { --accent:#e9aaaa; --edge:#925e5e; }
62
+ }
63
+ * { box-sizing:border-box; }
64
+ body { margin:0; padding:24px; width:1600px; max-width:100%; background:var(--canvas); color:var(--text); font:16px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif; }
65
+ header { max-height:3800px; overflow:hidden; }
66
+ .review-failures { padding:16px; border:1px solid var(--border); border-radius:8px; margin-top:16px; overflow-wrap:anywhere; }
67
+ h1 { margin:0; font-size:26px; }
68
+ h2 { margin:0 0 8px; color:var(--accent); font-size:18px; }
69
+ body > section { margin-top:16px; }
70
+ code { font-family:ui-monospace,Menlo,Consolas,monospace; overflow-wrap:anywhere; }
71
+ .cells { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px; align-items:start; margin:0; padding:0; list-style:none; }
72
+ .cells > * { min-width:0; padding:8px 12px; border:1px solid var(--edge); border-radius:8px; font-size:14px; }
73
+ .label { display:flex; gap:10px; align-items:baseline; font-weight:600; }
74
+ .label span { flex:none; }
75
+ .images { display:flex; align-items:center; gap:8px; margin-top:8px; }
76
+ .capture { flex:1; min-width:0; }
77
+ .changed .capture:first-child img { margin-inline-start:auto; }
78
+ .arrow { color:var(--muted); flex:none; font-size:20px; line-height:1; }
79
+ img { display:block; max-width:100%; height:auto; max-height:480px; object-fit:contain; object-position:left top; }
80
+ footer { margin-top:12px; color:var(--muted); }
81
+ </style></head><body data-theme="${escapeHtml(theme)}">
82
+ <header><h1>${escapeHtml(review.label)}</h1>${renderReviewFailures(review.failures)}</header>
83
+ ${section('Added', added.filter(entry => priority.has(entry)), card)}
84
+ ${section('Changed', changed.filter(entry => priority.has(entry)), card)}
85
+ ${section('Removed', removed, entry => `<li data-frame="${escapeHtml(entry.frame)}" data-removed>${name(entry, designDirs.before)}</li>`, 'ul')}
86
+ <footer data-more="${more}"${more ? '' : ' hidden'}>${more ? `+${more} more in the review page` : ''}</footer>
87
+ </body></html>`;
88
+ }
89
+
90
+ export async function renderReviewSheet(browser, review, theme, file, frameOrder, designDirs) {
91
+ const page = await browserTask(browser, () => browser.newPage({ viewport: { width: 1600, height: 900 }, deviceScaleFactor: 2, colorScheme: theme, reducedMotion: 'reduce' }));
92
+ try {
93
+ await browserTask(browser, async () => {
94
+ await page.setContent(reviewSheetHtml(review, theme, frameOrder, designDirs));
95
+ await page.evaluate(readyResources);
96
+ await page.evaluate(() => {
97
+ const footer = document.querySelector('footer');
98
+ const removed = [...document.querySelectorAll('[data-removed]')].reverse();
99
+ const cells = [...document.querySelectorAll('[data-priority]')]
100
+ .sort((a, b) => Number(b.dataset.priority) - Number(a.dataset.priority));
101
+ let more = Number(footer.dataset.more);
102
+ for (const entry of [...removed, ...cells]) {
103
+ if (document.body.getBoundingClientRect().height <= 4000) break;
104
+ const grid = entry.parentElement;
105
+ entry.remove();
106
+ if (!grid.childElementCount) grid.closest('section').remove();
107
+ more += Number(entry.dataset.frameCount ?? 1);
108
+ footer.dataset.more = more;
109
+ footer.textContent = `+${more} more in the review page`;
110
+ footer.hidden = false;
111
+ }
112
+ });
113
+ await page.locator('body').screenshot({ path: file, animations: 'disabled', caret: 'hide' });
114
+ });
115
+ return { path: file, theme };
116
+ } finally { await page.close(); }
117
+ }
@@ -0,0 +1,60 @@
1
+ import * as css from 'css-tree';
2
+ import { parseFragment, serialize } from 'parse5';
3
+
4
+ export function compileSpecimens({ built, theme }) {
5
+ const properties = new Set(), styles = new Map(), templates = [];
6
+ function scopedUnits(ast) {
7
+ css.walk(ast, { visit: 'Dimension', enter(node, item) {
8
+ if (/^[sld]?v(w|h|min|max)$/i.test(node.unit)) {
9
+ const unit = node.unit.toLowerCase().replace(/^[sld]/, '');
10
+ item.data = css.parse(`calc(${node.value} * var(--review-${unit}))`, { context: 'value' }).children.first;
11
+ }
12
+ } });
13
+ return ast;
14
+ }
15
+ function compileStyle(source) {
16
+ if (styles.has(source)) return styles.get(source).index;
17
+ const ast = scopedUnits(css.parse(source));
18
+ css.walk(ast, (node, item, list) => {
19
+ if (node.type === 'Atrule' && node.name === 'property') {
20
+ properties.add(css.generate(node));
21
+ list.remove(item);
22
+ } else if (node.type === 'PseudoClassSelector' && ['root', 'host'].includes(node.name) && !node.children) {
23
+ item.data = { type: 'ClassSelector', name: 'review-root' };
24
+ } else if (node.type === 'TypeSelector' && ['html', 'body'].includes(node.name)) {
25
+ node.name = node.name === 'html' ? 'review-document' : 'review-body';
26
+ }
27
+ });
28
+ const index = styles.size;
29
+ styles.set(source, { index, text: css.generate(ast) });
30
+ return index;
31
+ }
32
+ function compileFrame(ref, size, side) {
33
+ if (!ref) return null;
34
+ const source = built[side].get(ref.source);
35
+ const frame = source?.frames.find(frame => frame.name === ref.frame);
36
+ if (!frame || !size) throw Error(`Missing ${side} source for ${ref.source}#${ref.frame}`);
37
+ const fragment = parseFragment(frame.html);
38
+ function scopeInlineStyles(node) {
39
+ const style = node.attrs?.find(attr => attr.name === 'style');
40
+ if (style && /[\d.]v(?:h|w|min|max)\b|[\d.][sld]v(?:h|w|min|max)\b/i.test(style.value)) {
41
+ style.value = css.generate(scopedUnits(css.parse(style.value, { context: 'declarationList' })));
42
+ }
43
+ for (const child of node.childNodes ?? []) scopeInlineStyles(child);
44
+ }
45
+ scopeInlineStyles(fragment);
46
+ const index = templates.length;
47
+ const { width, height } = size;
48
+ const widthStyle = frame.width ? `width:${frame.width}px;` : 'width:max-content;';
49
+ const heightStyle = frame.height ? `height:${frame.height}px;` : '';
50
+ const name = frame.name.replaceAll('&', '&amp;').replaceAll('"', '&quot;');
51
+ templates.push(`<template id="frame-${index}"><review-document class="review-root" data-theme="${theme}"><review-body><div data-adg-frame="${name}" style="${widthStyle}${heightStyle}">${serialize(fragment)}</div></review-body></review-document></template>`);
52
+ const defaults = source.cssAfterTokens;
53
+ // Drop only the backdrop appended by ADG. Authored element and stylesheet paint stays intact.
54
+ const stylesheet = defaults && source.css.endsWith(defaults)
55
+ ? source.css.slice(0, -defaults.length) + defaults.replaceAll(';background:var(--canvas)', '')
56
+ : source.css;
57
+ return { template: index, style: compileStyle(stylesheet), width, height };
58
+ }
59
+ return { compileFrame, assets: () => ({ properties: [...properties], styles: [...styles.values()].map(style => style.text), templates }) };
60
+ }
@@ -0,0 +1,140 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { existsSync } from 'node:fs';
3
+ import { mkdir, rename, rm, writeFile } from 'node:fs/promises';
4
+ import { availableParallelism } from 'node:os';
5
+ import path from 'node:path';
6
+ import { CliError } from '../cli-output.mjs';
7
+ import { hubProjectURL } from '../hub/project-link.mjs';
8
+ import { previewTarget, previewURL } from '../link.mjs';
9
+ import { launch, loadFrame } from './browser.mjs';
10
+ import { diff } from './diff.mjs';
11
+ import { installFramePrimitives } from './frame-primitives.mjs';
12
+ import { impactRowKey, withImpacted } from './impact-selection.mjs';
13
+ import { readGroups } from './project.mjs';
14
+ import { reviewDocument } from './review-document.mjs';
15
+ import { observeFrame } from './review-observation.mjs';
16
+ import { compileSpecimens } from './review-specimens.mjs';
17
+ import { resolveThemes } from './theme.mjs';
18
+
19
+ const identity = ({ source, frame }) => JSON.stringify([source, frame]);
20
+ const abbreviations = { adg: 'ADG', ai: 'AI', api: 'API', hpc: 'HPC', html: 'HTML', llm: 'LLM', macos: 'macOS', mcp: 'MCP', pdf: 'PDF', scnet: 'SCNet', ui: 'UI' };
21
+
22
+ function readable(value, titleCase = false) {
23
+ return value.split(/[-_]+/).map((part, index) => abbreviations[part.toLowerCase()] ?? (index === 0 || titleCase
24
+ ? part.charAt(0).toUpperCase() + part.slice(1) : part)).join(' ');
25
+ }
26
+
27
+ function sourceLocator(config, viewer) {
28
+ const design = path.relative(config.root, config.design).split(path.sep).join('/');
29
+ const chapters = new Map();
30
+ for (const { title, assets } of readGroups(config.design, config.sources)) for (const asset of assets) {
31
+ if (!chapters.has(asset)) chapters.set(asset, title);
32
+ }
33
+ return ({ source, frame }, removed = false) => {
34
+ const architecture = source.endsWith('.mmd');
35
+ const asset = architecture ? source : path.posix.relative(design, source);
36
+ const parts = asset.split('/'), layer = architecture ? 'arch' : parts[0];
37
+ const filename = parts.at(-1);
38
+ const title = filename === 'index.tsx' ? parts.at(-2) : filename.replace(/\.(tsx|svg|mmd)$/, '');
39
+ const target = !removed ? { asset, frame } : existsSync(path.join(config.root, source)) ? { asset } : { layer };
40
+ return { layer: architecture ? 'Architecture' : readable(layer, true), chapter: chapters.get(asset), title: readable(title, true),
41
+ frame: readable(frame), href: viewer ? previewURL(viewer.href, previewTarget(target)).href : null };
42
+ };
43
+ }
44
+
45
+ async function observeUnchanged(session, theme) {
46
+ const key = row => impactRowKey(row, theme);
47
+ const candidates = session.chosen.filter(row => row.status === 'matched' && session.scheduled(row, theme) &&
48
+ row.source.endsWith('.tsx') && !session.assessments.get(key(row))?.unassessedReasons?.length);
49
+ const skipped = new Set();
50
+ if (!candidates.length) return skipped;
51
+ const browser = await launch();
52
+ try {
53
+ const parents = new Set(session.chosen.filter(row => row.status === 'added' && row.after.parent).map(row => key(row.after.parent)));
54
+ const prepared = await session.diffInputs.buildFrames({ browser, deferParts: true });
55
+ const eligible = new Set(candidates.map(key));
56
+ const frames = prepared.frames.filter(row => eligible.has(key(row)) && !parents.has(key(row)));
57
+ const context = await browser.newContext({ deviceScaleFactor: 2, locale: 'en-US', timezoneId: 'UTC' });
58
+ const pages = await Promise.all(Array.from({ length: Math.min(4, availableParallelism(), frames.length) }, () => context.newPage()));
59
+ let index = 0;
60
+ await Promise.all(pages.map(async page => {
61
+ async function read(frame) {
62
+ await loadFrame(page, frame, theme);
63
+ await page.evaluate(installFramePrimitives);
64
+ return page.evaluate(observeFrame);
65
+ }
66
+ while (index < frames.length) {
67
+ const row = frames[index++];
68
+ try {
69
+ const before = await read(row.before);
70
+ if (before.uncertain.length) continue;
71
+ const after = await read(row.after);
72
+ if (!after.uncertain.length && JSON.stringify(before) === JSON.stringify(after)) skipped.add(key(row));
73
+ } catch (error) {
74
+ if (!browser.isConnected()) throw error;
75
+ // Unobserved frames remain eligible for pixel comparison.
76
+ }
77
+ }
78
+ }));
79
+ return skipped;
80
+ } finally {
81
+ await browser.close();
82
+ }
83
+ }
84
+
85
+ /** Generate a standalone, single-theme review without starting a viewer. */
86
+ export async function review(config, values, { log = console.log } = {}) {
87
+ const started = performance.now();
88
+ const [theme] = resolveThemes(values.theme ?? 'system');
89
+ const destination = path.resolve(config.root, values.out ?? path.join(config.output, 'review.html'));
90
+ const projectURL = values['viewer-url'] ?? await hubProjectURL(config.root);
91
+ const viewer = projectURL ? previewURL(projectURL, previewTarget({})) : null;
92
+ if (viewer) viewer.search = '';
93
+ const locate = sourceLocator(config, viewer);
94
+ const options = { base: values.base, theme, impacted: true, json: true };
95
+ let model, built, skipped;
96
+ const { data, warnings } = await withImpacted(config, [], options, 'diff', async session => {
97
+ skipped = values.exact ? new Set() : await observeUnchanged(session, theme);
98
+ const buildFrames = session.diffInputs.buildFrames, scheduled = session.scheduled;
99
+ session.diffInputs.buildFrames = async options => (built = await buildFrames(options));
100
+ session.scheduled = (row, theme) => scheduled(row, theme) && !skipped.has(impactRowKey(row, theme));
101
+ try {
102
+ return await diff(config, [], options, { session, reviewOnly: true, onReview: value => { model = value; } });
103
+ } catch (error) {
104
+ if (error.code !== 'DIFF_FAILED' && !error.partialSourceFailures) throw error;
105
+ return { data: error.data, warnings: error.warnings };
106
+ } finally {
107
+ session.scheduled = scheduled;
108
+ }
109
+ });
110
+
111
+ const { compileFrame, assets } = compileSpecimens({ built, theme });
112
+ const comparisons = new Map(data.comparisons.filter(row => row.theme === theme).map(row => [identity(row), row]));
113
+ const cards = [...model.sections.added, ...model.sections.changed].map((entry, index) => {
114
+ const row = comparisons.get(identity(entry));
115
+ const changed = entry.status === 'changed';
116
+ const before = changed ? compileFrame(row.before, row.beforeSize, 'before') : null;
117
+ const after = compileFrame(row.after, row.afterSize, 'after');
118
+ const difference = changed ? entry.themes.find(item => item.theme === theme)?.images.difference : null;
119
+ return { index, source: entry.source, frame: entry.frame, status: entry.status, change: entry.change, origin: locate(entry),
120
+ previousOrigin: entry.previousSource && locate(row.before), before, after, difference, differentPixels: row.pixels?.differentPixels };
121
+ });
122
+ const report = { title: model.label, theme, base: model.base.sha, head: model.current.head, counts: model.counts, cards,
123
+ groups: data.review.groups, removed: model.sections.removed.map(entry => ({ ...entry, origin: locate(entry, true) })),
124
+ moved: model.movePairs.map(({ before, after }) => ({ before: locate(before, true), after: locate(after) })), failures: model.failures };
125
+ const html = reviewDocument(report, assets());
126
+ const temporary = `${destination}.${randomUUID()}.tmp`;
127
+ await mkdir(path.dirname(destination), { recursive: true });
128
+ try {
129
+ await writeFile(temporary, html);
130
+ await rename(temporary, destination);
131
+ } finally {
132
+ await rm(temporary, { force: true });
133
+ }
134
+ const result = { path: destination, base: model.base, current: model.current, theme, counts: model.counts, groups: data.review.groups,
135
+ mode: values.exact ? 'exact' : 'hybrid', structureMatches: skipped.size, pixelComparisons: data.summary.comparisons,
136
+ complete: model.complete, failures: model.failures, bytes: Buffer.byteLength(html), generationMs: performance.now() - started };
137
+ if (!values.json) log(`${destination}\n${result.counts.added} added, ${result.counts.changed} changed, ${result.counts.removed} removed, ${result.counts.moved} moved.`);
138
+ if (!result.complete) throw new CliError('SOURCE_BUILD_FAILED', 'Review contains source build failures.', { data: result, warnings });
139
+ return { data: result, warnings };
140
+ }
@@ -12,7 +12,7 @@ export function children(value) {
12
12
  export function attributes(props) {
13
13
  return Object.entries(props).filter(([key, value]) => !['children', 'key', '__source'].includes(key) && value != null && value !== false).map(([key, value]) => {
14
14
  if (/^on/i.test(key) || key === 'className' || key === 'dangerouslySetInnerHTML') throw Error(`Forbidden attribute ${key}; use static markup and class`);
15
- if (key === 'style' && typeof value === 'object') value = Object.entries(value).map(([name, v]) => `${name.startsWith('--') ? name : name.replace(/[A-Z]/g, c => '-' + c.toLowerCase())}:${typeof v === 'number' && !/^(opacity|zIndex|fontWeight|lineHeight|flex|flexGrow|flexShrink|order|gridColumn|gridRow|scale)$/.test(name) && !name.startsWith('--') ? v + 'px' : v}`).join(';');
15
+ if (key === 'style' && typeof value === 'object') value = Object.entries(value).filter(([, v]) => v !== undefined && v !== null && v !== false).map(([name, v]) => `${name.startsWith('--') ? name : name.replace(/[A-Z]/g, c => '-' + c.toLowerCase())}:${typeof v === 'number' && !/^(opacity|zIndex|fontWeight|lineHeight|flex|flexGrow|flexShrink|order|gridColumn|gridRow|scale)$/.test(name) && !name.startsWith('--') ? v + 'px' : v}`).join(';');
16
16
  return ` ${key}="${escape(value === true ? '' : value)}"`;
17
17
  }).join('');
18
18
  }
@@ -0,0 +1,16 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { CliError } from '../cli-output.mjs';
3
+
4
+ export function systemTheme({ platform = process.platform, readAppearance = () => execFileSync('defaults', ['read', '-g', 'AppleInterfaceStyle'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }) } = {}) {
5
+ if (platform !== 'darwin') return 'light';
6
+ try { return readAppearance().trim() === 'Dark' ? 'dark' : 'light'; }
7
+ catch { return 'light'; }
8
+ }
9
+
10
+ export function resolveThemes(option = 'both', readSystemTheme = systemTheme) {
11
+ if (!['both', 'light', 'dark', 'system'].includes(option)) {
12
+ throw new CliError('USAGE_INVALID', 'Choose --theme=both, light, dark, or system.');
13
+ }
14
+ if (option === 'both') return ['light', 'dark'];
15
+ return [option === 'system' ? readSystemTheme() : option];
16
+ }