@whzxc/agent-design-gallery 0.9.0 → 0.13.1
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.
- package/README.md +19 -3
- package/package.json +4 -1
- package/public/annotations.js +816 -0
- package/public/app.js +245 -12
- package/public/assets.js +4 -13
- package/public/frame-identity.js +223 -0
- package/public/icons.js +1 -0
- package/public/index.html +3 -0
- package/public/selection.js +1 -1
- package/public/style.css +72 -2
- package/src/annotations.mjs +238 -0
- package/src/cli-output.mjs +49 -2
- package/src/cli.mjs +83 -12
- package/src/http.mjs +2 -1
- package/src/hub/instances.mjs +1 -1
- package/src/hub/registry.mjs +1 -1
- package/src/hub.mjs +2 -2
- package/src/server.mjs +59 -11
- package/src/service.mjs +1 -1
- package/src/toolkit/arch-git.mjs +19 -0
- package/src/toolkit/arch-overlay.mjs +1 -1
- package/src/toolkit/asset-rules.mjs +42 -3
- package/src/toolkit/build-store.mjs +5 -3
- package/src/toolkit/build-worker.mjs +5 -2
- package/src/toolkit/build.mjs +36 -14
- package/src/toolkit/commands.mjs +85 -22
- package/src/toolkit/config.mjs +8 -6
- package/src/toolkit/diff-inputs.mjs +5 -5
- package/src/toolkit/diff.mjs +18 -11
- package/src/toolkit/document.mjs +6 -6
- package/src/toolkit/frame-document.mjs +6 -0
- package/src/toolkit/frame-facets.mjs +167 -0
- package/src/toolkit/frame-identity.mjs +100 -0
- package/src/toolkit/frame-observation.mjs +147 -0
- package/src/toolkit/frame-primitives.mjs +85 -0
- package/src/toolkit/html.mjs +1 -0
- package/src/toolkit/impact-eligibility.mjs +136 -0
- package/src/toolkit/impact-inputs.mjs +52 -0
- package/src/toolkit/impact-output.mjs +46 -0
- package/src/toolkit/impact-proof.mjs +67 -0
- package/src/toolkit/impact-selection.mjs +96 -0
- package/src/toolkit/impact.mjs +382 -0
- package/src/toolkit/implementation-query.mjs +53 -0
- package/src/toolkit/input-generation.mjs +51 -0
- package/src/toolkit/inspect-encoding.mjs +459 -0
- package/src/toolkit/inspect-observation.mjs +56 -0
- package/src/toolkit/inspect-output.mjs +169 -0
- package/src/toolkit/inspect-styles.mjs +34 -0
- package/src/toolkit/inspect.d.ts +118 -0
- package/src/toolkit/inspect.mjs +125 -0
- package/src/toolkit/owner-observation.mjs +23 -189
- package/src/toolkit/owner-search.mjs +2 -2
- package/src/toolkit/owner.mjs +37 -45
- package/src/toolkit/part-diff.mjs +2 -0
- package/src/toolkit/part-snapshot.mjs +15 -23
- package/src/toolkit/project-index.mjs +100 -22
- package/src/toolkit/project.mjs +52 -6
- package/src/toolkit/results.mjs +2 -2
- package/src/toolkit/runtime.d.ts +7 -5
- package/src/toolkit/runtime.mjs +20 -7
- package/src/toolkit/token-reachability.mjs +71 -0
|
@@ -4,11 +4,15 @@ import os from 'node:os';
|
|
|
4
4
|
import { indexDigest } from './index-store.mjs';
|
|
5
5
|
import { CliError } from '../cli-output.mjs';
|
|
6
6
|
import { loadFrame, browserTask, readyResources } from './browser.mjs';
|
|
7
|
-
import {
|
|
7
|
+
import { frameDocument } from './frame-document.mjs';
|
|
8
|
+
import { collectOwnerObservation, installFramePrimitives } from './frame-observation.mjs';
|
|
9
|
+
import { elementIdentities } from './frame-identity.mjs';
|
|
10
|
+
export { collectOwnerObservation } from './frame-observation.mjs';
|
|
8
11
|
import { installColorResolver } from './owner-colors.mjs';
|
|
9
12
|
|
|
10
13
|
export const normalizeOwnerText = text => text.normalize('NFC').replace(/\p{White_Space}+/gu, ' ').trim();
|
|
11
14
|
const contexts = new WeakMap();
|
|
15
|
+
const preparedPages = new WeakSet();
|
|
12
16
|
|
|
13
17
|
export function occurrenceContext(observation, occurrence) {
|
|
14
18
|
if (!contexts.has(observation)) contexts.set(observation, new Map(observation.nodes.map(node => [node.path, node])));
|
|
@@ -20,19 +24,32 @@ export function occurrenceContext(observation, occurrence) {
|
|
|
20
24
|
if (!owners.length && node.owners?.length) owners.push(...node.owners.map(owner => ({ ...owner, distance })));
|
|
21
25
|
node = byPath.get(node.parentPath); distance++;
|
|
22
26
|
}
|
|
23
|
-
return { ...occurrence, ancestors: occurrence.ancestors ?? ancestors, owners: occurrence.owners ?? owners, box: occurrence.box ?? byPath.get(path)?.box, distance: owners[0]?.distance ?? distance };
|
|
27
|
+
return { ...occurrence, ...(byPath.get(path)?.elementId ? {elementId:byPath.get(path).elementId} : {}), ancestors: occurrence.ancestors ?? ancestors, owners: occurrence.owners ?? owners, box: occurrence.box ?? byPath.get(path)?.box, distance: owners[0]?.distance ?? distance };
|
|
24
28
|
}
|
|
25
29
|
|
|
26
30
|
export async function observeOwnerFrame(index, source, built, frame, theme, environment, getPage, tokens) {
|
|
27
|
-
|
|
31
|
+
const observed=await index.observation(source, built, frame, theme, environment, async () => {
|
|
28
32
|
const page = await getPage();
|
|
29
|
-
const rendered = { ...frame, document: value =>
|
|
33
|
+
const rendered = { ...frame, document: value => frameDocument(frame,value,built.css) };
|
|
30
34
|
await loadFrame(page, rendered, theme);
|
|
31
35
|
return browserTask(page.context().browser(), async () => {
|
|
32
|
-
await page.evaluate(readyResources);
|
|
33
|
-
|
|
36
|
+
await page.evaluate(readyResources);
|
|
37
|
+
if (!preparedPages.has(page)) {
|
|
38
|
+
await page.evaluate(installColorResolver); await page.evaluate(installFramePrimitives);
|
|
39
|
+
preparedPages.add(page);
|
|
40
|
+
}
|
|
41
|
+
const observation=await settleOwnerObservation(() => page.evaluate(collectOwnerObservation, { tokens, theme }), () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(resolve))));
|
|
42
|
+
if(observation.identities){
|
|
43
|
+
const ids=new Map(elementIdentities(observation.identities,{source,frame:frame.name},{metadata:false}).map(n=>[n.path,n]));
|
|
44
|
+
for(const node of observation.nodes){node.elementId=ids.get(node.path).id;}
|
|
45
|
+
delete observation.identities;
|
|
46
|
+
}
|
|
47
|
+
return observation;
|
|
34
48
|
});
|
|
35
49
|
});
|
|
50
|
+
// A rich shared hit retains raw identity inputs for inspect; owner projects the same addresses.
|
|
51
|
+
if(observed.identities){const ids=new Map(elementIdentities(observed.identities,{source,frame:frame.name},{metadata:false}).map(n=>[n.path,n.id]));for(const node of observed.nodes)node.elementId=ids.get(node.path);}
|
|
52
|
+
return observed;
|
|
36
53
|
}
|
|
37
54
|
|
|
38
55
|
export function collectOwnerPalette({ tokens }) {
|
|
@@ -76,189 +93,6 @@ export async function observationEnvironment() {
|
|
|
76
93
|
return indexDigest(JSON.stringify({ platform: process.platform, release: os.release(), arch: process.arch, locale: 'en-US', timezone: 'UTC', deviceScaleFactor: 1, files: files.sort() }));
|
|
77
94
|
}
|
|
78
95
|
|
|
79
|
-
/** Browser-side projection: provenance roots and authored references, no raster work. */
|
|
80
|
-
export function collectOwnerObservation({ tokens, theme }) {
|
|
81
|
-
const frame = document.querySelector('[data-adg-frame]'), root = frame?.firstElementChild;
|
|
82
|
-
if (!root || frame.children.length !== 1) throw Error('Ownership observation requires exactly one frame root.');
|
|
83
|
-
const origin = frame.getBoundingClientRect(), elements = [root, ...root.querySelectorAll('*')], paths = new Map(elements.map((node, i) => [node, String(i)]));
|
|
84
|
-
const tokenNames = new Set(tokens.map(token => token.name));
|
|
85
|
-
const definitions = new Map(tokens.map(token => [token.name, token.values.find(value => value.theme === theme).declaration]));
|
|
86
|
-
const box = rect => ({ x: rect.left - origin.left, y: rect.top - origin.top, width: Math.max(0, rect.right - rect.left), height: Math.max(0, rect.bottom - rect.top) });
|
|
87
|
-
const styleCache = new Map(), declarations = new Map(), rectCache = new Map();
|
|
88
|
-
const rect = node => { if (!rectCache.has(node)) rectCache.set(node, node.getBoundingClientRect()); return rectCache.get(node); };
|
|
89
|
-
const style = node => { if (!styleCache.has(node)) styleCache.set(node, getComputedStyle(node)); return styleCache.get(node); };
|
|
90
|
-
function clipped(node, r = rect(node), includeSelf = false) {
|
|
91
|
-
let left = Math.max(r.left, origin.left), right = Math.min(r.right, origin.right), top = Math.max(r.top, origin.top), bottom = Math.min(r.bottom, origin.bottom);
|
|
92
|
-
for (let p = node; p; p = p.parentElement) {
|
|
93
|
-
const s = style(p); if (s.display === 'none' || p === node && s.visibility !== 'visible' || Number(s.opacity) === 0) return null;
|
|
94
|
-
if ((p !== node || includeSelf) && s.display !== 'inline') {
|
|
95
|
-
const r = rect(p);
|
|
96
|
-
if (/(hidden|clip|scroll|auto)/.test(s.overflowX)) { left = Math.max(left, r.left); right = Math.min(right, r.right); }
|
|
97
|
-
if (/(hidden|clip|scroll|auto)/.test(s.overflowY)) { top = Math.max(top, r.top); bottom = Math.min(bottom, r.bottom); }
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
return right > left && bottom > top ? box({ left, right, top, bottom }) : null;
|
|
101
|
-
}
|
|
102
|
-
const rules = [];
|
|
103
|
-
function visitRules(list, containers = [], parents = []) {
|
|
104
|
-
for (const rule of list) {
|
|
105
|
-
if (rule instanceof CSSMediaRule && !matchMedia(rule.conditionText).matches || rule instanceof CSSSupportsRule && !CSS.supports(rule.conditionText)) continue;
|
|
106
|
-
const nested = typeof CSSContainerRule !== 'undefined' && rule instanceof CSSContainerRule ? [...containers, rule.cssText.slice(0, rule.cssText.indexOf('{'))] : containers;
|
|
107
|
-
let resolved = parents;
|
|
108
|
-
if (rule.selectorText && rule.style) {
|
|
109
|
-
const own = selectors(rule.selectorText);
|
|
110
|
-
resolved = parents.length ? parents.flatMap(parent => own.map(selector => selector.includes('&') ? selector.replaceAll('&', `:is(${parent})`) : `${parent} ${selector}`)) : own;
|
|
111
|
-
if ([...rule.style].some(property => rule.style.getPropertyValue(property).includes('var('))) rules.push({ selectors: resolved, style: rule.style, containers });
|
|
112
|
-
}
|
|
113
|
-
if (rule.cssRules) visitRules(rule.cssRules, nested, resolved);
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
for (const sheet of document.styleSheets) visitRules(sheet.cssRules);
|
|
117
|
-
function selectors(text) {
|
|
118
|
-
const out = []; let start = 0, depth = 0, quote = '';
|
|
119
|
-
for (let i = 0; i < text.length; i++) {
|
|
120
|
-
const char = text[i];
|
|
121
|
-
if (quote) { if (char === '\\') i++; else if (char === quote) quote = ''; }
|
|
122
|
-
else if (char === '"' || char === "'") quote = char;
|
|
123
|
-
else if (char === '(' || char === '[') depth++;
|
|
124
|
-
else if (char === ')' || char === ']') depth--;
|
|
125
|
-
else if (char === ',' && !depth) { out.push(text.slice(start, i)); start = i + 1; }
|
|
126
|
-
}
|
|
127
|
-
return [...out, text.slice(start)].map(value => value.trim());
|
|
128
|
-
}
|
|
129
|
-
const probe = document.createElement('style'); document.head.append(probe);
|
|
130
|
-
function containerActive(node, conditions) {
|
|
131
|
-
if (!conditions.length) return true;
|
|
132
|
-
const previous = node.getAttribute('data-adg-owner-probe');
|
|
133
|
-
try {
|
|
134
|
-
node.setAttribute('data-adg-owner-probe', 'active');
|
|
135
|
-
probe.textContent = conditions.reduceRight((inner, condition) => `${condition}{${inner}}`, '[data-adg-owner-probe="active"]{--adg-owner-condition:1!important}');
|
|
136
|
-
return getComputedStyle(node).getPropertyValue('--adg-owner-condition').trim() === '1';
|
|
137
|
-
} finally { probe.textContent = ''; if (previous === null) node.removeAttribute('data-adg-owner-probe'); else node.setAttribute('data-adg-owner-probe', previous); }
|
|
138
|
-
}
|
|
139
|
-
function declarationsFor(node, pseudo = '') {
|
|
140
|
-
const key = pseudo ? `${paths.get(node)}${pseudo}` : node;
|
|
141
|
-
if (declarations.has(key)) return declarations.get(key);
|
|
142
|
-
const result = [];
|
|
143
|
-
for (const rule of rules) {
|
|
144
|
-
const matched = rule.selectors.some(selector => {
|
|
145
|
-
const suffix = /::(before|after)\b/.exec(selector);
|
|
146
|
-
if ((suffix ? `::${suffix[1]}` : '') !== pseudo) return false;
|
|
147
|
-
try { return node.matches(selector.replace(/::(?:before|after)\b/g, '')); } catch { return false; }
|
|
148
|
-
});
|
|
149
|
-
if (matched && containerActive(node, rule.containers)) for (const property of rule.style) result.push({ property, declaration: rule.style.getPropertyValue(property) });
|
|
150
|
-
}
|
|
151
|
-
if (!pseudo) for (const property of node.style) result.push({ property, declaration: node.style.getPropertyValue(property) });
|
|
152
|
-
declarations.set(key, result); return result;
|
|
153
|
-
}
|
|
154
|
-
function variables(expression, fallback = false) {
|
|
155
|
-
const result = []; const regex = /var\(\s*(--[\w-]+)/g; let match;
|
|
156
|
-
while ((match = regex.exec(expression))) {
|
|
157
|
-
let depth = 1, comma = -1, end = regex.lastIndex;
|
|
158
|
-
for (; end < expression.length && depth; end++) {
|
|
159
|
-
if (expression[end] === '(') depth++; else if (expression[end] === ')') depth--;
|
|
160
|
-
else if (expression[end] === ',' && depth === 1 && comma < 0) comma = end;
|
|
161
|
-
}
|
|
162
|
-
result.push({ name: match[1], fallback });
|
|
163
|
-
if (comma >= 0) result.push(...variables(expression.slice(comma + 1, end - 1), true));
|
|
164
|
-
regex.lastIndex = end;
|
|
165
|
-
}
|
|
166
|
-
return result;
|
|
167
|
-
}
|
|
168
|
-
const inherited = /^(?:color|font(?:-.+)?|line-height|letter-spacing|word-spacing|text-align|text-indent|text-transform|visibility|cursor|fill|stroke(?:-.+)?)$/;
|
|
169
|
-
const nodes = [], references = [], paints = [], texts = [], groups = [];
|
|
170
|
-
const normalize = value => value.normalize('NFC').replace(/\p{White_Space}+/gu, ' ').trim();
|
|
171
|
-
function paint(style, property, node, bounds, pseudo = '') {
|
|
172
|
-
const computed = style.getPropertyValue(property);
|
|
173
|
-
if (!computed || computed === 'none') return;
|
|
174
|
-
const values = property.includes('shadow') || property === 'background-image'
|
|
175
|
-
? computed.match(/(?:rgba?|hsla?|oklch|oklab|lab|lch|color(?:-mix)?)\((?:[^()]|\([^()]*\))*\)|#[\da-f]{3,8}\b/gi) ?? [] : [computed];
|
|
176
|
-
for (const value of values) {
|
|
177
|
-
const rgba = globalThis.__adgOwnerColor(value);
|
|
178
|
-
if (rgba?.[3]) paints.push({ path: paths.get(node) + pseudo, ownerPath: paths.get(node), box: bounds, property, computed: value, rgba });
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
function fragment(node) {
|
|
182
|
-
const parent = node.parentElement;
|
|
183
|
-
if (!parent || parent.closest('script,style,input,textarea,select')) return null;
|
|
184
|
-
const range = document.createRange(); range.selectNodeContents(node);
|
|
185
|
-
const rects = [...range.getClientRects()]; if (!rects.length) return null;
|
|
186
|
-
const extent = { left: Math.min(...rects.map(r => r.left)), right: Math.max(...rects.map(r => r.right)), top: Math.min(...rects.map(r => r.top)), bottom: Math.max(...rects.map(r => r.bottom)) };
|
|
187
|
-
const bounds = clipped(parent, extent, true); if (!bounds) return null;
|
|
188
|
-
const clipRect = r => {
|
|
189
|
-
const left = Math.max(r.left, origin.left + bounds.x), right = Math.min(r.right, origin.left + bounds.x + bounds.width), top = Math.max(r.top, origin.top + bounds.y), bottom = Math.min(r.bottom, origin.top + bounds.y + bounds.height);
|
|
190
|
-
return right > left && bottom > top ? box({ left, right, top, bottom }) : null;
|
|
191
|
-
};
|
|
192
|
-
const boxes = rects.map(clipRect).filter(Boolean);
|
|
193
|
-
if (!boxes.length) return null;
|
|
194
|
-
let raw = node.data;
|
|
195
|
-
if (rects.some(r => r.left < origin.left + bounds.x - .5 || r.right > origin.left + bounds.x + bounds.width + .5 || r.top < origin.top + bounds.y - .5 || r.bottom > origin.top + bounds.y + bounds.height + .5)) {
|
|
196
|
-
raw = '';
|
|
197
|
-
for (let i = 0; i < node.length; i++) { range.setStart(node, i); range.setEnd(node, i + 1); if ([...range.getClientRects()].some(r => clipRect(r))) raw += node.data[i]; }
|
|
198
|
-
}
|
|
199
|
-
const transform = style(parent).textTransform;
|
|
200
|
-
const rendered = transform === 'uppercase' ? raw.toLocaleUpperCase(document.documentElement.lang || 'en') : transform === 'lowercase' ? raw.toLocaleLowerCase(document.documentElement.lang || 'en') : transform === 'capitalize' ? raw.replace(/\b\p{L}/gu, value => value.toLocaleUpperCase(document.documentElement.lang || 'en')) : raw;
|
|
201
|
-
return { parent, raw, rendered, elementPath: `${paths.get(parent)}/text-${[...parent.childNodes].indexOf(node)}`, text: raw, boxes };
|
|
202
|
-
}
|
|
203
|
-
function textGroup(node) {
|
|
204
|
-
for (let p = node; p && p !== frame; p = p.parentElement) if (p.matches('button,a,label,input,textarea,select,text') || !['inline','contents'].includes(style(p).display)) return p;
|
|
205
|
-
return root;
|
|
206
|
-
}
|
|
207
|
-
try {
|
|
208
|
-
for (const node of elements) {
|
|
209
|
-
const bounds = clipped(node);
|
|
210
|
-
const own = JSON.parse(node.getAttribute('data-adg-owners') ?? '[]');
|
|
211
|
-
nodes.push({ path: paths.get(node), parentPath: paths.get(node.parentElement) ?? null, box: bounds, owners: own });
|
|
212
|
-
if (!bounds) continue;
|
|
213
|
-
const customs = new Map();
|
|
214
|
-
for (let p = node; p; p = p.parentElement) for (const declaration of declarationsFor(p)) if (declaration.property.startsWith('--') && !customs.has(declaration.property)) customs.set(declaration.property, declaration.declaration);
|
|
215
|
-
function expand(name, property, declaration, via = [], fallback = false) {
|
|
216
|
-
if (via.includes(name)) return;
|
|
217
|
-
if (tokenNames.has(name)) references.push({ path: paths.get(node), token: name, property, declaration, via,
|
|
218
|
-
matchKind: fallback ? 'token_fallback_reference' : via.length ? 'token_alias_reference' : 'token_reference' });
|
|
219
|
-
const expression = tokenNames.has(name) ? definitions.get(name) : customs.get(name);
|
|
220
|
-
if (expression) for (const variable of variables(expression)) expand(variable.name, property, declaration, [...via, name], fallback || variable.fallback);
|
|
221
|
-
}
|
|
222
|
-
for (const pseudo of ['', '::before', '::after']) {
|
|
223
|
-
const s = pseudo ? getComputedStyle(node, pseudo) : style(node);
|
|
224
|
-
if (pseudo && (['none', 'normal'].includes(s.content) || s.display === 'none' || s.visibility !== 'visible' || Number(s.opacity) === 0)) continue;
|
|
225
|
-
const active = [...declarationsFor(node, pseudo)];
|
|
226
|
-
if (!pseudo && (own.length || node === root)) for (let p = node.parentElement; p; p = p.parentElement) active.push(...declarationsFor(p).filter(d => inherited.test(d.property)));
|
|
227
|
-
for (const { property, declaration } of active) if (!property.startsWith('--')) for (const variable of variables(declaration)) expand(variable.name, property, declaration, [], variable.fallback);
|
|
228
|
-
const hasText = pseudo ? !['""', "''", 'none', 'normal'].includes(s.content) : node.matches('input,textarea,select') ? !!String(node.value || node.placeholder || [...(node.selectedOptions ?? [])].map(option => option.text).join('')).trim() : [...node.childNodes].some(n => n.nodeType === 3 && n.textContent.trim() && fragment(n));
|
|
229
|
-
if (hasText && !(node instanceof SVGElement)) paint(!pseudo && node.matches('input,textarea') && !node.value && node.placeholder ? getComputedStyle(node, '::placeholder') : s, 'color', node, bounds, pseudo);
|
|
230
|
-
paint(s, 'background-color', node, bounds, pseudo);
|
|
231
|
-
for (const side of ['top','right','bottom','left']) if (parseFloat(s.getPropertyValue(`border-${side}-width`)) > 0 && s.getPropertyValue(`border-${side}-style`) !== 'none') paint(s, `border-${side}-color`, node, bounds, pseudo);
|
|
232
|
-
if (parseFloat(s.outlineWidth) > 0 && s.outlineStyle !== 'none') paint(s, 'outline-color', node, bounds, pseudo);
|
|
233
|
-
if (node instanceof SVGElement && /^(path|rect|circle|ellipse|polygon|polyline|line|text|tspan)$/.test(node.localName) && (!/^(text|tspan)$/.test(node.localName) || hasText)) { paint(s, 'fill', node, bounds, pseudo); if (parseFloat(s.strokeWidth) > 0) paint(s, 'stroke', node, bounds, pseudo); }
|
|
234
|
-
for (const property of ['box-shadow','text-shadow','background-image']) if (property !== 'text-shadow' || hasText) paint(s, property, node, bounds, pseudo);
|
|
235
|
-
if (pseudo && !/\b(?:url|attr|counter)\(/.test(s.content)) {
|
|
236
|
-
const raw = [...s.content.matchAll(/"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)'/g)].map(match => (match[1] ?? match[2]).replace(/\\([\da-f]{1,6})\s?|\\(.)/gi, (_, hex, char) => hex ? String.fromCodePoint(parseInt(hex, 16) || 0xfffd) : char)).join('');
|
|
237
|
-
if (normalize(raw)) texts.push({ path: paths.get(node) + pseudo, ownerPath: paths.get(node), raw, normalized: normalize(raw), fragments: [{ elementPath: paths.get(node) + pseudo, text: raw, boxes: [bounds] }] });
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
if (node.matches('input,textarea,select') && !(node.matches('input[type=password]') && node.value)) {
|
|
241
|
-
const raw = node.matches('select') ? [...node.selectedOptions].map(option => option.text).join(' ') : node.value || node.placeholder || '';
|
|
242
|
-
if (normalize(raw)) texts.push({ path: `${paths.get(node)}/value`, ownerPath: paths.get(node), raw, normalized: normalize(raw), fragments: [{ elementPath: `${paths.get(node)}/value`, text: raw, boxes: [bounds] }] });
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
|
246
|
-
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
|
247
|
-
const f = fragment(node); if (!f) continue;
|
|
248
|
-
const group = textGroup(f.parent);
|
|
249
|
-
if (groups.at(-1)?.[0] !== group) groups.push([group, []]);
|
|
250
|
-
groups.at(-1)[1].push(f);
|
|
251
|
-
}
|
|
252
|
-
for (const [group, fragments] of groups) {
|
|
253
|
-
const raw = fragments.map(f => f.raw).join(''), normalized = normalize(fragments.map(f => f.rendered).join(''));
|
|
254
|
-
if (!normalized) continue;
|
|
255
|
-
let common = fragments[0].parent;
|
|
256
|
-
while (common && !fragments.every(f => common.contains(f.parent))) common = common.parentElement;
|
|
257
|
-
texts.push({ path: `${paths.get(group)}/run-${texts.length}`, ownerPath: paths.get(common ?? group), raw, normalized, fragments: fragments.map(({ elementPath, text, boxes }) => ({ elementPath, text, boxes })) });
|
|
258
|
-
}
|
|
259
|
-
return { nodes, references: [...new Map(references.map(ref => [JSON.stringify(ref), ref])).values()], texts, paints };
|
|
260
|
-
} finally { probe.remove(); }
|
|
261
|
-
}
|
|
262
96
|
|
|
263
97
|
export async function settleOwnerObservation(read, wait, now = () => performance.now()) {
|
|
264
98
|
const start = now(); let previous = JSON.stringify(await read());
|
|
@@ -98,7 +98,7 @@ export async function searchOwner(config, values, { log = console.log, openIndex
|
|
|
98
98
|
const detail = query.kind === 'text' ? { kind: 'text', raw: match.raw, normalized: match.normalized, fragments: match.fragments }
|
|
99
99
|
: query.kind === 'color' ? { kind: 'paint', property: match.property, computed: match.computed, rgba: match.rgba, usage: 'computed_value' }
|
|
100
100
|
: { kind: 'reference', token: match.token, property: match.property, declaration: match.declaration, via: match.via, usage: 'authored_reference' };
|
|
101
|
-
const evidence = { matchKind: kind, frame: ref, theme, elementPath: match.path, boxes: query.kind === 'text' ? match.fragments.flatMap(f => f.boxes) : ctx.box ? [ctx.box] : [], owners, detail };
|
|
101
|
+
const evidence = { matchKind: kind, frame: ref, theme, elementPath: match.path, ...(ctx.elementId ? {elementId:ctx.elementId} : {}), boxes: query.kind === 'text' ? match.fragments.flatMap(f => f.boxes) : ctx.box ? [ctx.box] : [], owners, detail };
|
|
102
102
|
const scope = new Set(ctx.ancestors);
|
|
103
103
|
for (const fragment of match.fragments ?? []) for (const ancestor of occurrenceContext(observation, { path: fragment.elementPath }).ancestors) scope.add(ancestor);
|
|
104
104
|
const references = query.kind === 'token' ? [match] : query.kind === 'color'
|
|
@@ -113,7 +113,7 @@ export async function searchOwner(config, values, { log = console.log, openIndex
|
|
|
113
113
|
const key = JSON.stringify([target.source, target.part]);
|
|
114
114
|
if (!rows.has(key)) rows.set(key, { source: target.source, part: target.part, matchKind: kind, rank, frames: [], tokens: [], evidence: [] });
|
|
115
115
|
const row = rows.get(key); if (compareRanks(rank, row.rank) < 0) { row.rank = rank; row.matchKind = kind; }
|
|
116
|
-
if (!row.frames.some(f => f.source === source && f.frame === frame.name && f.theme === theme)) row.frames.push({ ...ref, theme, locale: frame.locale ?? null });
|
|
116
|
+
if (!row.frames.some(f => f.source === source && f.frame === frame.name && f.theme === theme)) row.frames.push({ ...ref, theme, locale: frame.locale ?? null, proposed: frame.proposed ?? null });
|
|
117
117
|
row.evidence.push(evidence);
|
|
118
118
|
if (query.kind === 'text') row.authoredIn = orderAuthoredIn([...(row.authoredIn ?? []), ...evidence.authoredIn], [row.source, ...row.frames.map(frame => frame.source)]);
|
|
119
119
|
for (const reference of references) {
|
package/src/toolkit/owner.mjs
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
|
-
import { readFile
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { CliError, nextActions } from '../cli-output.mjs';
|
|
4
4
|
import { openProjectIndex } from './project-index.mjs';
|
|
5
|
-
import { loadImplementationMap, implementationFiles } from './implementation-map.mjs';
|
|
6
|
-
import {
|
|
5
|
+
import { loadImplementationMap, implementationFiles, validateImplementationMap } from './implementation-map.mjs';
|
|
6
|
+
import { regionAt } from './owner-locators.mjs';
|
|
7
|
+
import { normalizeFileQuery, implementationScope } from './implementation-query.mjs';
|
|
7
8
|
import { launch, loadFrame, readyResources, browserTask } from './browser.mjs';
|
|
8
9
|
import { observeOwnerFrame, observeOwnerPalette, occurrenceContext, observationEnvironment } from './owner-observation.mjs';
|
|
9
10
|
import { commandFailure, cleanup } from './results.mjs';
|
|
10
|
-
import { escape } from './
|
|
11
|
+
import { escape } from './html.mjs';
|
|
11
12
|
import { indexDigest } from './index-store.mjs';
|
|
13
|
+
import { buildSource } from './build.mjs';
|
|
14
|
+
import { listSources, sourceDirectories, selectSources, relative } from './project.mjs';
|
|
12
15
|
|
|
13
16
|
export const compareRanks = (a, b) => { for (let i = 0; i < Math.max(a.length, b.length); i++) if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) - (b[i] ?? 0); return 0; };
|
|
14
17
|
export const compareNames = (a, b) => { const x = [...(a ?? '')], y = [...(b ?? '')]; for (let i = 0; i < Math.min(x.length, y.length); i++) if (x[i] !== y[i]) return x[i].codePointAt(0) - y[i].codePointAt(0); return x.length - y.length; };
|
|
@@ -20,42 +23,40 @@ export function fileRank(selector, locator = null) {
|
|
|
20
23
|
return [2, -(prefix < 0 ? selector.glob.length : prefix), selector.glob.split('/').filter(segment => /[?*]/.test(segment)).length, -selector.glob.replace(/[?*]/g, '').length, rank];
|
|
21
24
|
}
|
|
22
25
|
|
|
23
|
-
async function normalizeFileQuery(config, values) {
|
|
24
|
-
const root = await realpath(config.root), input = values.file;
|
|
25
|
-
if (typeof input !== 'string' || !input.trim()) throw new CliError('USAGE_INVALID', 'Set one nonempty --file input.');
|
|
26
|
-
let absolute = path.resolve(root, input);
|
|
27
|
-
if (path.isAbsolute(input) && !/[?*]/.test(input)) {
|
|
28
|
-
try { absolute = await realpath(input); } catch (error) { if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw error; throw new CliError('OWNER_INPUT_NOT_FOUND', 'Ownership input does not name an existing file or directory.'); }
|
|
29
|
-
}
|
|
30
|
-
const relative = path.relative(root, absolute).split(path.sep).join('/');
|
|
31
|
-
if (relative === '..' || relative.startsWith('../') || path.isAbsolute(relative)) throw new CliError('USAGE_INVALID', 'Ownership input must stay inside the project root.');
|
|
32
|
-
let pathKind, normalized = relative;
|
|
33
|
-
if (/[?*]/.test(relative)) {
|
|
34
|
-
if (!portablePath(relative, { glob: true })) throw new CliError('USAGE_INVALID', 'Use a POSIX glob with *, ? and whole-segment **.');
|
|
35
|
-
pathKind = 'glob';
|
|
36
|
-
} else {
|
|
37
|
-
let info;
|
|
38
|
-
try { info = await stat(absolute); } catch (error) { if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw error; throw new CliError('OWNER_INPUT_NOT_FOUND', 'Ownership input does not name an existing file or directory.'); }
|
|
39
|
-
const physical = path.relative(root, await realpath(absolute));
|
|
40
|
-
if (physical === '..' || physical.startsWith('..' + path.sep) || path.isAbsolute(physical)) throw new CliError('USAGE_INVALID', 'Ownership input resolves outside the project root.');
|
|
41
|
-
if (!info.isFile() && !info.isDirectory()) throw new CliError('USAGE_INVALID', 'Choose a regular implementation file or directory.');
|
|
42
|
-
pathKind = info.isDirectory() ? 'directory' : 'file';
|
|
43
|
-
if (pathKind === 'directory') normalized = relative ? relative + '/' : './';
|
|
44
|
-
}
|
|
45
|
-
const line = values.line === undefined ? null : Number(values.line), symbol = values.symbol ?? null;
|
|
46
|
-
if ((line !== null || symbol !== null) && pathKind !== 'file') throw new CliError('USAGE_INVALID', '--line and --symbol require a single file.');
|
|
47
|
-
const text = line !== null || symbol !== null ? await readFile(absolute, 'utf8') : null;
|
|
48
|
-
if (line !== null && (!Number.isSafeInteger(line) || line < 1 || line > sourceLineCount(text))) throw new CliError('USAGE_INVALID', '--line must name an existing 1-based line in the implementation file.');
|
|
49
|
-
if (values.theme !== undefined && !['both', 'light', 'dark'].includes(values.theme)) throw new CliError('USAGE_INVALID', 'Use --theme=both, light or dark.');
|
|
50
|
-
return { query: { kind: 'file', input, normalized, pathKind, line, symbol, contains: false, locale: null, themes: !values.theme || values.theme === 'both' ? ['light', 'dark'] : [values.theme], rgba: null }, text };
|
|
51
|
-
}
|
|
52
26
|
|
|
53
27
|
function bindingKind(selector, query) {
|
|
54
28
|
return selector.symbol && query.symbol && query.line === null ? 'mapping_symbol' : selector.symbol && query.line !== null ? 'mapping_symbol_region'
|
|
55
29
|
: selector.file ? 'mapping_file' : selector.directory ? 'mapping_directory' : 'mapping_glob';
|
|
56
30
|
}
|
|
57
31
|
|
|
32
|
+
async function ownerPart(config, values, { log = console.log } = {}) {
|
|
33
|
+
const raw = values.part, split = raw.indexOf('#'), sourceInput = split < 0 ? raw : raw.slice(0, split), part = split < 0 ? null : raw.slice(split + 1);
|
|
34
|
+
if (!sourceInput.trim() || (part !== null && !part.trim())) throw new CliError('USAGE_INVALID', 'Use --part=<source> or --part=<source>#<Export>.');
|
|
35
|
+
const selected = selectSources(config, [sourceInput], { write: false });
|
|
36
|
+
const source = relative(config, selected[0]), designSource = source;
|
|
37
|
+
const data = { project: config.root, complete: false, query: { kind: 'part', input: raw, normalized: raw, source, part }, region: null, owners: [], tokens: [], ambiguous: false, tokenAmbiguous: false, matchedImplementationFiles: [], mappingFindings: [], coverage: { discoveredSources: listSources(config.design, sourceDirectories(config)).length, builtSources: 0, requestedObservations: 0, completedObservations: 0, mappingState: 'absent', activeBindings: 0, excludedBindings: 0, domain: 'tsx' } };
|
|
38
|
+
const map = await loadImplementationMap(config);
|
|
39
|
+
data.coverage.mappingState = map.present ? 'valid' : 'absent';
|
|
40
|
+
if (!map.present) { data.complete = true; const missingWarning = { code: 'OWNER_MAPPING_MISSING', message: 'Add implementation.json to declare implementation ownership.', next: [] }; return { data, warnings: [missingWarning] }; }
|
|
41
|
+
const validated = await validateImplementationMap(config, map, { sources: listSources(config.design, sourceDirectories(config)).map(file => relative(config, file)), getBuild: target => buildSource(config, path.join(config.root, target), { write: false, allowLegacy: false }) });
|
|
42
|
+
data.mappingFindings = validated.findings; data.coverage.mappingState = validated.findings.length ? 'stale' : 'valid';
|
|
43
|
+
const warnings = validated.findings.length ? [{ code: 'OWNER_MAPPING_STALE', message: 'Repair the reported implementation mapping findings, then repeat the query.', next: [] }] : [];
|
|
44
|
+
for (const binding of validated.bindings.filter(binding => binding.active && binding.design.source === designSource && (part === null ? binding.design.part === undefined : binding.design.part === part))) {
|
|
45
|
+
data.coverage.activeBindings++;
|
|
46
|
+
const selector = binding.implementation;
|
|
47
|
+
const implementations = binding.files.map(file => ({ file, symbol: selector.symbol ?? null, region: binding.anchorLine === null ? null : (validated.regions[file] ?? []).find(region => region.line === binding.anchorLine) ?? null }));
|
|
48
|
+
const row = { source, part, matchKind: 'mapping_part', rank: fileRank(selector, 'mapping_symbol'), frames: binding.frames.map(frame => ({ source, frame, theme: null, locale: null, proposed: null })), tokens: [], evidence: [], implementation: selector };
|
|
49
|
+
for (const implementation of implementations) row.evidence.push({ matchKind: 'mapping_part', frame: null, theme: null, elementPath: null, boxes: [], owners: [], detail: { kind: 'mapping', file: map.source, pointer: binding.pointer, implementation: implementation.file, selector, symbol: selector.symbol ?? null, region: implementation.region } });
|
|
50
|
+
data.owners.push(row);
|
|
51
|
+
}
|
|
52
|
+
data.complete = true;
|
|
53
|
+
if (!data.owners.length) warnings.push({ code: 'OWNER_NO_MATCH', message: 'No implementation binding matched the requested design part.', next: [] });
|
|
54
|
+
if (!values.json) for (const row of data.owners) log(`${row.source}${row.part ? `#${row.part}` : ''} [${row.matchKind}] ${row.evidence.map(e => e.detail.implementation).join(', ')}`);
|
|
55
|
+
return { data, warnings };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
58
|
export async function owner(config, values, { log = console.log, openIndex = openProjectIndex, launchBrowser = launch, environment = observationEnvironment } = {}) {
|
|
59
|
+
if (values.part !== undefined) return ownerPart(config, values, { log });
|
|
59
60
|
if (values.file === undefined) return (await import('./owner-search.mjs')).searchOwner(config, values, { log, openIndex, launchBrowser, environment });
|
|
60
61
|
const { query, text } = await normalizeFileQuery(config, values);
|
|
61
62
|
const data = { project: config.root, complete: false, query, region: null, owners: [], tokens: [], ambiguous: false, tokenAmbiguous: false, matchedImplementationFiles: [], mappingFindings: [],
|
|
@@ -73,17 +74,8 @@ export async function owner(config, values, { log = console.log, openIndex = ope
|
|
|
73
74
|
const map = await loadImplementationMap(config);
|
|
74
75
|
data.coverage.mappingState = map.present ? 'valid' : 'absent';
|
|
75
76
|
index = await openIndex(config, { stateDirectory: values['state-dir'] }); data.coverage.discoveredSources = index.inventory.tsx.length;
|
|
76
|
-
const
|
|
77
|
-
const queryRegion = text === null ? null : regionAt(symbolRegions(text, query.normalized, mapSelectors), query.line ?? 1);
|
|
77
|
+
const { mappingIndices, region: queryRegion } = implementationScope(map, query, text, files);
|
|
78
78
|
if (query.line !== null && queryRegion) data.region = { boundaryLine: queryRegion.line, symbol: queryRegion.symbol, mapped: queryRegion.mapped.length > 0, nextBoundaryLine: queryRegion.nextBoundaryLine };
|
|
79
|
-
const mappingIndices = new Set();
|
|
80
|
-
map.mappings.forEach((mapping, i) => {
|
|
81
|
-
const s = mapping.implementation;
|
|
82
|
-
if (!files.some(file => selectorMatches(s, file))) return;
|
|
83
|
-
if (s.symbol && query.symbol !== null && s.symbol !== query.symbol) return;
|
|
84
|
-
if (s.symbol && query.line !== null && (queryRegion?.line !== resolveLocator(text, s).line || !queryRegion?.mapped.includes(s.symbol))) return;
|
|
85
|
-
mappingIndices.add(i);
|
|
86
|
-
});
|
|
87
79
|
const validated = await index.mappings({ map, mappingIndices, implementationSelection: files, onFinding: finding => { data.mappingFindings.push(finding); data.coverage.mappingState = 'stale'; } });
|
|
88
80
|
data.mappingFindings = validated.findings;
|
|
89
81
|
data.coverage.mappingState = !map.present ? 'absent' : validated.findings.length ? 'stale' : 'valid';
|
|
@@ -111,7 +103,7 @@ export async function owner(config, values, { log = console.log, openIndex = ope
|
|
|
111
103
|
for (const implementation of binding.files) {
|
|
112
104
|
const boundary = binding.anchorLine === null ? null : regionAt(validated.regions[implementation] ?? [], binding.anchorLine);
|
|
113
105
|
const matches = roots.length ? roots : [null];
|
|
114
|
-
for (const node of matches) row.evidence.push({ matchKind: kind, frame: ref, theme, elementPath: node?.path ?? null, boxes: node ? [node.box] : [], owners: node ? projectOwners(node.owners) : [],
|
|
106
|
+
for (const node of matches) row.evidence.push({ matchKind: kind, frame: ref, theme, elementPath: node?.path ?? null, ...(node?.elementId ? {elementId:node.elementId} : {}), boxes: node ? [node.box] : [], owners: node ? projectOwners(node.owners) : [],
|
|
115
107
|
detail: { kind: 'mapping', file: map.source, pointer: binding.pointer, implementation, selector: binding.implementation, locatorMatched: query.line === null && query.symbol === null ? null : !!binding.implementation.symbol,
|
|
116
108
|
anchorLine: binding.anchorLine, nextBoundaryLine: boundary?.nextBoundaryLine ?? null } });
|
|
117
109
|
}
|
|
@@ -135,7 +127,7 @@ export async function owner(config, values, { log = console.log, openIndex = ope
|
|
|
135
127
|
for (const { row, binding } of task.bindings) {
|
|
136
128
|
const roots = binding.design.part ? observation.nodes.filter(node => node.box && node.owners.some(owner => projectOwners([owner]).some(part => part.source === row.source && part.part === row.part))) : observation.nodes.filter(node => node.path === '0' && node.box);
|
|
137
129
|
if (row.part && !roots.length) warn('OWNER_PART_UNOBSERVED', 'The declared part has no painted occurrence in a bound frame; inspect its authored coverage.');
|
|
138
|
-
if (!row.frames.some(frame => frame.source === ref.source && frame.frame === ref.frame && frame.theme === task.theme)) row.frames.push({ ...ref, theme: task.theme, locale: frame.locale ?? null });
|
|
130
|
+
if (!row.frames.some(frame => frame.source === ref.source && frame.frame === ref.frame && frame.theme === task.theme)) row.frames.push({ ...ref, theme: task.theme, locale: frame.locale ?? null, proposed: frame.proposed ?? null });
|
|
139
131
|
addMapping(row, binding, ref, task.theme, roots);
|
|
140
132
|
for (const rawReference of observation.references) {
|
|
141
133
|
const reference = occurrenceContext(observation, rawReference);
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { installFramePrimitives } from './frame-observation.mjs';
|
|
1
2
|
import { loadTokens } from './project.mjs';
|
|
2
3
|
import { loadFrame, readyResources } from './browser.mjs';
|
|
3
4
|
import { collectPartSnapshot, normalizeSnapshot, snapshotFindings, settlePart } from './part-snapshot.mjs';
|
|
@@ -25,6 +26,7 @@ export function partContext(built, inputs, scale, themes, clock) {
|
|
|
25
26
|
}
|
|
26
27
|
|
|
27
28
|
async function readSnapshot(page, args) {
|
|
29
|
+
await page.evaluate(installFramePrimitives);
|
|
28
30
|
const snapshot = await page.evaluate(collectPartSnapshot, args);
|
|
29
31
|
if (snapshot.referenceError) throw new CliError('DIFF_REFERENCE_INVALID', snapshot.referenceError);
|
|
30
32
|
if (snapshot.unsupported.length) {
|
|
@@ -10,13 +10,13 @@ export async function collectPartSnapshot({ selector, tokens, scale, ref, theme
|
|
|
10
10
|
if (roots.length !== 1) return { referenceError: `Expected one target for ${selector ?? 'the part root'}, found ${roots.length}.` };
|
|
11
11
|
const root = roots[0], origin = root.getBoundingClientRect(), frameBox = frame.getBoundingClientRect();
|
|
12
12
|
if (!origin.width || !origin.height || getComputedStyle(root).visibility !== 'visible') return { referenceError: 'The parent/part target must be visible.' };
|
|
13
|
-
const
|
|
14
|
-
const box = rect => (
|
|
13
|
+
const { inventory,relativeBox,reads,styleRules,textRects }=globalThis.__adgFramePrimitives;
|
|
14
|
+
const box = rect => relativeBox(rect,origin);
|
|
15
15
|
const cssCrop = { x: origin.x - frameBox.x, y: origin.y - frameBox.y, width: origin.width, height: origin.height };
|
|
16
16
|
const left = Math.floor(cssCrop.x * scale), top = Math.floor(cssCrop.y * scale);
|
|
17
17
|
const deviceCrop = { x: left, y: top, width: Math.ceil((cssCrop.x + origin.width) * scale) - left, height: Math.ceil((cssCrop.y + origin.height) * scale) - top };
|
|
18
18
|
const fractionalOrigin = { x: cssCrop.x * scale - left, y: cssCrop.y * scale - top };
|
|
19
|
-
const nodes
|
|
19
|
+
const {elements:nodes,paths}=inventory(root), {style:styleFor,rect:rectFor}=reads();
|
|
20
20
|
const ids = new Map(nodes.filter(node => node.id).map(node => [node.id, `node-${paths.get(node)}`]));
|
|
21
21
|
const unsupported = [], resources = [], resourceCache = new Map(), decoded = new Map();
|
|
22
22
|
const internalIds = value => value.replace(/url\(["']?#([^)'"\s]+)["']?\)/g, (_, id) => `url(#${ids.get(id) ?? id})`);
|
|
@@ -67,18 +67,10 @@ export async function collectPartSnapshot({ selector, tokens, scale, ref, theme
|
|
|
67
67
|
};
|
|
68
68
|
const paintProperty = property => /color|background|fill|stroke|shadow|opacity|filter|blend|mask|clip-path/.test(property);
|
|
69
69
|
const ignored = /^(?:--|animation|transition|cursor$|pointer-events$|user-select$|touch-action$|scroll-behavior$|caret-color$)/;
|
|
70
|
-
const tokenRules
|
|
71
|
-
const visitRules = rules => {
|
|
72
|
-
for (const rule of rules) {
|
|
73
|
-
if (rule instanceof CSSMediaRule && !matchMedia(rule.conditionText).matches || rule instanceof CSSSupportsRule && !CSS.supports(rule.conditionText)) continue;
|
|
74
|
-
if (rule.selectorText && rule.style) tokenRules.push(rule);
|
|
75
|
-
if (rule.cssRules) visitRules(rule.cssRules);
|
|
76
|
-
}
|
|
77
|
-
};
|
|
78
|
-
for (const sheet of document.styleSheets) visitRules(sheet.cssRules);
|
|
70
|
+
const tokenRules=styleRules().map(item=>item.rule);
|
|
79
71
|
const elements = [], texts = [], rasters = [], edgeBoxes = [];
|
|
80
72
|
for (const node of nodes) {
|
|
81
|
-
const path = paths.get(node), style =
|
|
73
|
+
const path = paths.get(node), style = styleFor(node), rect = rectFor(node);
|
|
82
74
|
inspectPaint(style, path);
|
|
83
75
|
if (node.matches('canvas,video,object,embed,foreignObject')) unsupported.push({ path, property: 'paint', value: node.localName });
|
|
84
76
|
const computedStyle = await normalizeStyle(style), layout = {}, paint = {};
|
|
@@ -118,8 +110,7 @@ export async function collectPartSnapshot({ selector, tokens, scale, ref, theme
|
|
|
118
110
|
owners: JSON.parse(node.getAttribute('data-adg-owners') ?? '[]') });
|
|
119
111
|
for (const [index, child] of [...node.childNodes].entries()) {
|
|
120
112
|
if (child.nodeType !== 3 || !child.textContent.trim()) continue;
|
|
121
|
-
const
|
|
122
|
-
const lines = [...range.getClientRects()].map(rect => ({ text: child.textContent, box: box(rect) }));
|
|
113
|
+
const lines = textRects(child).rects.map(rect => ({ text: child.textContent, box: box(rect) }));
|
|
123
114
|
texts.push({ path: `${path}/text-${index}`, parentPath: path, text: child.textContent, lines });
|
|
124
115
|
edgeBoxes.push(...lines.map(line => line.box));
|
|
125
116
|
}
|
|
@@ -208,15 +199,16 @@ export async function collectPartSnapshot({ selector, tokens, scale, ref, theme
|
|
|
208
199
|
frameAligned: selector !== null || cssCrop.x === 0 && cssCrop.y === 0 && origin.width === frameBox.width && origin.height === frameBox.height };
|
|
209
200
|
}
|
|
210
201
|
|
|
211
|
-
export function
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
const comma = content.indexOf(',');
|
|
216
|
-
content = content.slice(0, comma).includes(';base64') ? Buffer.from(content.slice(comma + 1), 'base64') : Buffer.from(decodeURIComponent(content.slice(comma + 1)));
|
|
217
|
-
}
|
|
218
|
-
resource.contentIdentity = createHash('sha256').update(content).digest('hex');
|
|
202
|
+
export function resourceContentIdentity(content) {
|
|
203
|
+
if (content.startsWith('data:')) {
|
|
204
|
+
const comma=content.indexOf(',');
|
|
205
|
+
content=content.slice(0,comma).includes(';base64') ? Buffer.from(content.slice(comma+1),'base64') : Buffer.from(decodeURIComponent(content.slice(comma+1)));
|
|
219
206
|
}
|
|
207
|
+
return createHash('sha256').update(content).digest('hex');
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export function normalizeSnapshot(snapshot) {
|
|
211
|
+
for(const resource of snapshot.resources)resource.contentIdentity=resourceContentIdentity(resource.contentIdentity);
|
|
220
212
|
return snapshot;
|
|
221
213
|
}
|
|
222
214
|
|