@luci-dev/capture 0.7.1 → 0.8.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 (44) hide show
  1. package/dist/component.d.ts.map +1 -1
  2. package/dist/component.js +35 -13
  3. package/dist/component.js.map +1 -1
  4. package/dist/dom.js +3 -3
  5. package/dist/dom.js.map +1 -1
  6. package/dist/layout.js +1 -1
  7. package/dist/layout.js.map +1 -1
  8. package/dist/luci-capture.js +4769 -1470
  9. package/dist/ui/devSettings.d.ts.map +1 -1
  10. package/dist/ui/devSettings.js +5 -9
  11. package/dist/ui/devSettings.js.map +1 -1
  12. package/dist/ui/figmaPanel.d.ts +80 -0
  13. package/dist/ui/figmaPanel.d.ts.map +1 -0
  14. package/dist/ui/figmaPanel.js +290 -0
  15. package/dist/ui/figmaPanel.js.map +1 -0
  16. package/dist/ui/index.d.ts +3 -2
  17. package/dist/ui/index.d.ts.map +1 -1
  18. package/dist/ui/index.js +2 -1
  19. package/dist/ui/index.js.map +1 -1
  20. package/dist/ui/mount.d.ts +7 -1
  21. package/dist/ui/mount.d.ts.map +1 -1
  22. package/dist/ui/mount.js +11 -2
  23. package/dist/ui/mount.js.map +1 -1
  24. package/dist/ui/onSpec.d.ts +34 -1
  25. package/dist/ui/onSpec.d.ts.map +1 -1
  26. package/dist/ui/onSpec.js +313 -30
  27. package/dist/ui/onSpec.js.map +1 -1
  28. package/dist/ui/specWatcher.d.ts +31 -10
  29. package/dist/ui/specWatcher.d.ts.map +1 -1
  30. package/dist/ui/specWatcher.js +825 -146
  31. package/dist/ui/specWatcher.js.map +1 -1
  32. package/dist/ui/styles.d.ts +3 -3
  33. package/dist/ui/styles.d.ts.map +1 -1
  34. package/dist/ui/styles.js +79 -12
  35. package/dist/ui/styles.js.map +1 -1
  36. package/dist/ui/toolbar.d.ts +18 -0
  37. package/dist/ui/toolbar.d.ts.map +1 -1
  38. package/dist/ui/toolbar.js +95 -17
  39. package/dist/ui/toolbar.js.map +1 -1
  40. package/dist/ui/tools.d.ts +6 -1
  41. package/dist/ui/tools.d.ts.map +1 -1
  42. package/dist/ui/tools.js +18 -2
  43. package/dist/ui/tools.js.map +1 -1
  44. package/package.json +3 -3
@@ -9,9 +9,9 @@
9
9
  * same-origin iframe when media queries do apply (with graceful fallback if framing is blocked).
10
10
  * - Enforces "prefer No rule over a wrong verdict": ambiguous matches never guess.
11
11
  */
12
- import { DEFAULT_SPEC_WIDTHS, evaluateSpecVerdict, readComponentFile } from '@luci-dev/format/capture';
12
+ import { DEFAULT_SPEC_WIDTHS, SPEC_REASON_MESSAGES, evaluateSpecVerdict, formatWidthNotCheckedNote, readComponentFile } from '@luci-dev/format/capture';
13
13
  import { componentType } from '../component.js';
14
- import { LUCI_UI_ATTRIBUTE } from '../dom.js';
14
+ import { LUCI_UI_ATTRIBUTE, selectorFor } from '../dom.js';
15
15
  import { pageComponents } from '../page.js';
16
16
  import { LUCI_FRAME_NAME, mediaQueriesFor } from '../responsive.js';
17
17
  import { captureComponent, checkAgainst, liveSnapshot, readComponentStates } from './tools.js';
@@ -26,24 +26,80 @@ const WATCH_PROPS = [
26
26
  'gap', 'display', 'flex-direction', 'align-items', 'justify-content'
27
27
  ];
28
28
  export const SPEC_BASELINES_KEY = 'luci.onSpec.baselines';
29
- /** Extract project breakpoint pair [narrow, wide] from saved design files, else [375, 1440]. */
30
- export function extractProjectWidths(rules) {
29
+ function readRuleResponsiveWidths(markdown) {
30
+ const resp = /##\s+Responsive\b([\s\S]*?)(?:\n##\s|$)/i.exec(markdown)?.[1];
31
+ if (!resp)
32
+ return null;
31
33
  const widths = new Set();
32
- for (const r of rules) {
33
- // Match "## Responsive" widths lines or table headers like "375px", "768px", "1280px", "1440px"
34
- const resp = /##\s+Responsive\b([\s\S]*?)(?:\n##\s|$)/i.exec(r.markdown)?.[1];
35
- if (!resp)
34
+ const addWidth = (raw) => {
35
+ const n = Number(raw);
36
+ if (n >= 320 && n <= 2560)
37
+ widths.add(n);
38
+ };
39
+ for (const rawLine of resp.replace(/\r\n/g, '\n').split('\n')) {
40
+ const line = rawLine.trim();
41
+ if (!line)
36
42
  continue;
37
- for (const m of resp.matchAll(/\b(\d{3,4})px\b/g)) {
38
- const n = Number(m[1]);
39
- if (n >= 320 && n <= 2560)
40
- widths.add(n);
43
+ // Table column widths: only the header row ("| Part | Property | 375px | 1280px |"), never table body values
44
+ if (/^\|\s*(?:Part|Place)\s*\|\s*Property\s*\|/i.test(line)) {
45
+ const cols = line.split('|').map(c => c.trim()).filter(Boolean).slice(2);
46
+ for (const col of cols) {
47
+ const m = /^(\d{3,4})px$/i.exec(col);
48
+ if (m?.[1])
49
+ addWidth(m[1]);
50
+ }
51
+ break;
52
+ }
53
+ // Figma frame note: "- Checked at 1440px (this width came from the Figma frame)."
54
+ const figmaNote = /^-\s*Checked at\s+(\d{3,4})px\b.*\bFigma frame\b/i.exec(line);
55
+ if (figmaNote?.[1]) {
56
+ addWidth(figmaNote[1]);
57
+ break;
58
+ }
59
+ // Multi-width rule without responsive differences: "- Nothing in it changes at 375px and 1280px."
60
+ if (/^-\s*Nothing in it changes at\s+/i.test(line)) {
61
+ for (const m of line.matchAll(/\b(\d{3,4})px\b/g))
62
+ addWidth(m[1]);
63
+ break;
41
64
  }
42
65
  }
43
66
  const sorted = [...widths].sort((a, b) => a - b);
44
- if (sorted.length >= 2) {
45
- return [sorted[0], sorted[sorted.length - 1]];
67
+ return sorted.length >= 1 ? sorted : null;
68
+ }
69
+ function readBaselineSystemWidths(rules) {
70
+ const baselineRules = rules.filter(r => r.scope === 'system' || r.file.includes('.system.') || /^project\.system\./.test(r.file));
71
+ const widths = new Set();
72
+ for (const r of baselineRules) {
73
+ for (const w of readRuleResponsiveWidths(r.markdown) ?? [])
74
+ widths.add(w);
75
+ }
76
+ const sorted = [...widths].sort((a, b) => a - b);
77
+ return sorted.length >= 1 ? sorted : null;
78
+ }
79
+ /** Extract stated check widths for one rule: its own ## Responsive section first, then baseline system breakpoints, else [375, 1440]. */
80
+ export function extractRuleWidths(rule, baselineFallback) {
81
+ const own = readRuleResponsiveWidths(rule.markdown);
82
+ if (own)
83
+ return own;
84
+ if (baselineFallback && baselineFallback.length >= 1)
85
+ return [...baselineFallback];
86
+ return [DEFAULT_SPEC_WIDTHS[0], DEFAULT_SPEC_WIDTHS[1]];
87
+ }
88
+ /** Extract breakpoint widths: baseline system files first if stored, then rule ## Responsive sections, else [375, 1440]. */
89
+ export function extractProjectWidths(rules) {
90
+ const baseline = readBaselineSystemWidths(rules);
91
+ if (baseline)
92
+ return baseline;
93
+ const widths = new Set();
94
+ for (const r of rules) {
95
+ for (const w of readRuleResponsiveWidths(r.markdown) ?? [])
96
+ widths.add(w);
46
97
  }
98
+ const sorted = [...widths].sort((a, b) => a - b);
99
+ if (sorted.length >= 2)
100
+ return [sorted[0], sorted[sorted.length - 1]];
101
+ if (sorted.length === 1)
102
+ return sorted;
47
103
  return [DEFAULT_SPEC_WIDTHS[0], DEFAULT_SPEC_WIDTHS[1]];
48
104
  }
49
105
  const LANDMARK_LABELS = {
@@ -53,18 +109,27 @@ const LANDMARK_LABELS = {
53
109
  main: 'Main',
54
110
  aside: 'Aside'
55
111
  };
112
+ const looksLikeSelector = (value) => /^[.#\[]|[>+~:]|\s/.test(value.trim());
56
113
  /**
57
114
  * Clean human-readable label for a live component in On spec lists and Spec reports.
58
- * Prefers saved rule name, explicit data-component / aria-label / aria-labelledby, then
59
- * landmark names (avoiding mashed-together child textContent on header/footer/nav),
60
- * then clean visible text (innerText when available, falling back to textContent).
115
+ * Order: component name (data-component, React/Vue root, non-selector Figma component),
116
+ * then rule name, then aria-label / landmark / heading / text, then CSS selector.
61
117
  */
62
- export function displayNameForElement(el, entry, ruleName) {
118
+ export function displayNameForElement(el, entry, ruleName, figmaComponent) {
119
+ const dataComp = el.getAttribute('data-component')?.trim();
120
+ if (dataComp)
121
+ return dataComp;
122
+ const fwName = readNearestFrameworkComponentName(el)[0]?.trim();
123
+ if (fwName)
124
+ return fwName;
125
+ const cleanFigmaComp = figmaComponent?.trim();
126
+ if (cleanFigmaComp && !looksLikeSelector(cleanFigmaComp))
127
+ return cleanFigmaComp;
63
128
  if (ruleName?.trim())
64
129
  return ruleName.trim();
65
- const explicit = el.getAttribute('data-component') || el.getAttribute('aria-label');
66
- if (explicit?.trim())
67
- return explicit.trim();
130
+ const ariaLabel = el.getAttribute('aria-label')?.trim();
131
+ if (ariaLabel)
132
+ return ariaLabel;
68
133
  const labelledBy = el.getAttribute('aria-labelledby');
69
134
  if (labelledBy && el.ownerDocument) {
70
135
  const labelText = labelledBy
@@ -87,7 +152,7 @@ export function displayNameForElement(el, entry, ruleName) {
87
152
  : (el.innerText || el.textContent || '')).trim().replace(/\s+/g, ' ');
88
153
  if (rawText)
89
154
  return rawText.slice(0, 40);
90
- return componentType(entry);
155
+ return entry.selector || componentType(entry);
91
156
  }
92
157
  const normalizeName = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
93
158
  function parseRuleSelector(markdown) {
@@ -138,14 +203,362 @@ function isLuciMutation(m) {
138
203
  }
139
204
  return false;
140
205
  }
206
+ const isFigmaRule = (r) => {
207
+ if (r.origin && r.origin !== 'figma')
208
+ return false;
209
+ const mdOrigin = /^origin:\s*([a-z-]+)\b/m.exec(r.markdown)?.[1];
210
+ if (mdOrigin)
211
+ return mdOrigin === 'figma';
212
+ return r.origin === 'figma' || /^figma-com\./.test(r.file);
213
+ };
214
+ const isUnboundFigmaRule = (r) => isFigmaRule(r) && (r.figmaStatus === 'orphaned' || r.figmaStatus === 'unmatched' || r.figmaStatus === 'waiting-for-build' || r.figmaStatus === 'skipped');
215
+ function polishFigmaDifferences(diffs, rule) {
216
+ if (!isFigmaRule(rule))
217
+ return diffs;
218
+ const blocked = new Set((rule.unconfirmedTokens ?? []).map(t => t.trim()).filter(Boolean));
219
+ return diffs.map(d => {
220
+ let expected = d.expected;
221
+ let comment = d.comment;
222
+ for (const tok of blocked) {
223
+ const esc = tok.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
224
+ const parensRx = new RegExp(`\\s*\\(\`?${esc}\`?\\)`, 'g');
225
+ expected = expected.replace(parensRx, '').trim();
226
+ comment = comment.replace(parensRx, '').trim();
227
+ const bareRx = new RegExp(`\\s*${esc}`, 'g');
228
+ expected = expected.replace(bareRx, '').trim();
229
+ comment = comment.replace(bareRx, '').trim();
230
+ }
231
+ const tokenMatch = /\((--[A-Za-z0-9_-]+)\)/.exec(expected);
232
+ const tokenHint = tokenMatch && !blocked.has(tokenMatch[1]) ? `, token ${tokenMatch[1]}` : '';
233
+ if (!comment.includes(rule.file)) {
234
+ comment = `${comment} (Figma rule ${rule.file}${tokenHint})`;
235
+ }
236
+ return { ...d, expected, comment };
237
+ });
238
+ }
239
+ function findNearestReactOwner(el) {
240
+ const rec = el;
241
+ for (const key of Object.keys(rec)) {
242
+ if (!key.startsWith('__reactFiber$') && !key.startsWith('__reactInternalInstance$'))
243
+ continue;
244
+ let fiber = rec[key];
245
+ let steps = 0;
246
+ while (fiber && steps++ < 12) {
247
+ const t = fiber.type;
248
+ if (typeof t === 'function' || (typeof t === 'object' && t !== null)) {
249
+ const n = t.displayName || t.name;
250
+ if (n && /^[A-Z]/.test(n)) {
251
+ return { fiber, name: n };
252
+ }
253
+ }
254
+ fiber = fiber.return;
255
+ }
256
+ }
257
+ return null;
258
+ }
259
+ function readNearestFrameworkComponentName(el) {
260
+ const ownReact = findNearestReactOwner(el);
261
+ if (ownReact) {
262
+ const parentReact = el.parentElement ? findNearestReactOwner(el.parentElement) : null;
263
+ // An internal child element shares the same nearest owner fiber as its parent; only the component's own root matches it
264
+ if (parentReact && parentReact.fiber === ownReact.fiber)
265
+ return [];
266
+ return [ownReact.name];
267
+ }
268
+ const rec = el;
269
+ const vue = rec.__vueParentComponent;
270
+ if (vue) {
271
+ const parentVue = el.parentElement?.__vueParentComponent;
272
+ if (parentVue && parentVue === vue)
273
+ return [];
274
+ const n = vue.type?.__name || vue.type?.name;
275
+ return n ? [n] : [];
276
+ }
277
+ return [];
278
+ }
279
+ const PRIORITY_DATA_ATTRS = [
280
+ 'data-component',
281
+ 'data-testid',
282
+ 'data-test-id',
283
+ 'data-slot',
284
+ 'data-qa',
285
+ 'data-cy',
286
+ 'data-name',
287
+ 'data-section',
288
+ 'data-part',
289
+ 'data-id'
290
+ ];
291
+ const IGNORED_DATA_ATTR_RE = /^data-(?:luci-|state$|open$|active$|selected$|checked$|disabled$|expanded$|orientation$|side$|align$|index$|row$|col$|key$|radix-|headlessui-|reactid$|v-)/i;
292
+ const UTILITY_CLASS_WORDS = new Set([
293
+ 'block', 'inline', 'inline-block', 'flex', 'inline-flex', 'grid', 'inline-grid', 'table', 'contents',
294
+ 'hidden', 'visible', 'invisible', 'collapse', 'static', 'fixed', 'absolute', 'relative', 'sticky',
295
+ 'isolate', 'truncate', 'antialiased', 'subpixel-antialiased', 'italic', 'not-italic', 'underline',
296
+ 'overline', 'line-through', 'no-underline', 'uppercase', 'lowercase', 'capitalize', 'normal-case',
297
+ 'sr-only', 'not-sr-only', 'container', 'prose', 'group', 'peer', 'grow', 'shrink', 'border',
298
+ 'rounded', 'shadow', 'ring', 'outline', 'transition', 'transform', 'filter', 'blur', 'invert',
299
+ 'sepia', 'grayscale', 'resize', 'clearfix'
300
+ ]);
301
+ const UTILITY_CLASS_PREFIX_RE = /^-?(?:p|px|py|pt|pr|pb|pl|ps|pe|m|mx|my|mt|mr|mb|ml|ms|me|w|h|size|min-w|max-w|min-h|max-h|gap|gap-x|gap-y|space-x|space-y|inset|inset-x|inset-y|top|right|bottom|left|start|end|basis|z|order|col-span|col-start|col-end|row-span|row-start|row-end|auto-cols|auto-rows|items|justify|content|self|place|float|clear|object|overflow|overscroll|aspect|columns|font|text|leading|tracking|align|whitespace|break|hyphens|indent|decoration|underline-offset|list|line-clamp|bg|from|via|to|divide|outline|ring|opacity|mix-blend|bg-blend|blur|brightness|contrast|drop-shadow|grayscale|hue-rotate|invert|saturate|sepia|backdrop|transition|duration|ease|delay|animate|scale|rotate|translate|skew|origin|accent|appearance|cursor|caret|scroll|snap|touch|select|will-change|fill|stroke)-/;
302
+ const UTILITY_AMBIGUOUS_PREFIX_RE = /^(?:flex-(?:row|col|wrap|nowrap|1|auto|initial|none|grow|shrink)|grid-(?:cols|rows|flow)-|box-(?:border|content)|(?:border|shadow)-(?:0|2|4|8|x|y|t|r|b|l|s|e|none|sm|md|lg|xl|2xl|inner|solid|dashed|dotted|double|hidden|collapse|separate|spacing|transparent|current|inherit|black|white|slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)(?:-|$)|rounded-(?:none|sm|md|lg|xl|2xl|3xl|full|t|r|b|l|tl|tr|br|bl|s|e|ss|se|ee|es)(?:-|$))/;
303
+ const LANDMARK_TAGS = new Set(['header', 'footer', 'nav', 'main', 'aside']);
304
+ const GENERIC_CONTAINER_TAGS = new Set(['div', 'span']);
305
+ function looksHashedToken(value) {
306
+ if (/^(?:css|sc|emotion|svelte|astro|jsx|styled)-[a-z0-9_-]+$/i.test(value)) {
307
+ return true;
308
+ }
309
+ if (/^[0-9a-f]{7,}$/i.test(value))
310
+ return true;
311
+ // CSS-module suffixes like Card_root__a1b2c or foo_bar_a1b2c (not BEM block__element like metrics-section__intro)
312
+ const dunderAt = value.lastIndexOf('__');
313
+ if (dunderAt > 0) {
314
+ const tail = value.slice(dunderAt + 2);
315
+ const hasDigitOrMixed = /\d/.test(tail) || (/[a-z]/.test(tail) && /[A-Z]/.test(tail));
316
+ const headLooksCssModule = /^[A-Z][A-Za-z0-9]*_[A-Za-z0-9_]+$/.test(value.slice(0, dunderAt));
317
+ if (tail.length >= 4 && (hasDigitOrMixed || headLooksCssModule))
318
+ return true;
319
+ return false;
320
+ }
321
+ if (/_(?=[A-Za-z0-9]{5,}$)(?=.*\d|.*[A-Z].*[a-z])[A-Za-z0-9]{5,}$/.test(value)) {
322
+ return true;
323
+ }
324
+ return /\d{3,}|[a-z]+[A-Z0-9][a-zA-Z0-9]{4,}/.test(value) && /\d/.test(value);
325
+ }
326
+ function isSemanticClass(cls) {
327
+ if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(cls))
328
+ return false;
329
+ if (looksHashedToken(cls))
330
+ return false;
331
+ if (UTILITY_CLASS_WORDS.has(cls))
332
+ return false;
333
+ if (UTILITY_CLASS_PREFIX_RE.test(cls))
334
+ return false;
335
+ if (UTILITY_AMBIGUOUS_PREFIX_RE.test(cls))
336
+ return false;
337
+ return true;
338
+ }
339
+ function escapeCssAttrValue(value) {
340
+ return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
341
+ }
342
+ function queryMatches(root, selector) {
343
+ try {
344
+ return Array.from(root.querySelectorAll(selector));
345
+ }
346
+ catch {
347
+ return [];
348
+ }
349
+ }
350
+ function collectStableDataSelectors(el) {
351
+ const out = [];
352
+ const seen = new Set();
353
+ const addAttr = (name) => {
354
+ if (seen.has(name) || IGNORED_DATA_ATTR_RE.test(name))
355
+ return;
356
+ const raw = el.getAttribute(name);
357
+ if (!raw)
358
+ return;
359
+ const val = raw.trim();
360
+ if (!val || val.length > 80 || /[\r\n]/.test(val))
361
+ return;
362
+ if (looksHashedToken(val) && name !== 'data-component')
363
+ return;
364
+ seen.add(name);
365
+ out.push(`[${name}="${escapeCssAttrValue(val)}"]`);
366
+ };
367
+ for (const attr of PRIORITY_DATA_ATTRS)
368
+ addAttr(attr);
369
+ for (const attr of Array.from(el.attributes)) {
370
+ if (attr.name.startsWith('data-'))
371
+ addAttr(attr.name);
372
+ }
373
+ return out;
374
+ }
375
+ function stableAncestorTokens(el, root) {
376
+ const tokens = [];
377
+ let cur = el.parentElement;
378
+ let steps = 0;
379
+ while (cur && steps++ < 6) {
380
+ const tag = cur.tagName.toLowerCase();
381
+ if (tag === 'body' || tag === 'html')
382
+ break;
383
+ if (cur.id && /^[A-Za-z][\w-]*$/.test(cur.id) && !looksHashedToken(cur.id)) {
384
+ const idSel = `#${cur.id}`;
385
+ if (queryMatches(root, idSel).length === 1)
386
+ tokens.push(idSel);
387
+ }
388
+ const dataSels = collectStableDataSelectors(cur);
389
+ if (dataSels.length > 0)
390
+ tokens.push(dataSels[0]);
391
+ const semClasses = Array.from(cur.classList).filter(isSemanticClass);
392
+ if (semClasses.length > 0)
393
+ tokens.push(`.${semClasses[0]}`);
394
+ if (LANDMARK_TAGS.has(tag) && queryMatches(root, tag).length === 1) {
395
+ tokens.push(tag);
396
+ }
397
+ cur = cur.parentElement;
398
+ }
399
+ return [...new Set(tokens)];
400
+ }
401
+ function stableSelectorInner(el, root, opts) {
402
+ const isUnique = (sel) => {
403
+ const found = queryMatches(root, sel);
404
+ return found.length === 1 && found[0] === el;
405
+ };
406
+ const ancestors = stableAncestorTokens(el, root);
407
+ // 1. Stable data-* attributes (unique first, then narrowed/repeated)
408
+ const dataSels = collectStableDataSelectors(el);
409
+ let fallbackDataSel;
410
+ for (const sel of dataSels) {
411
+ const found = queryMatches(root, sel);
412
+ if (!found.includes(el))
413
+ continue;
414
+ if (found.length === 1)
415
+ return { selector: sel, isStable: true };
416
+ if (!fallbackDataSel) {
417
+ let best = sel;
418
+ let bestCount = found.length;
419
+ for (const anc of ancestors) {
420
+ const scoped = `${anc} ${sel}`;
421
+ const scopedFound = queryMatches(root, scoped);
422
+ if (scopedFound.includes(el) && scopedFound.length < bestCount) {
423
+ best = scoped;
424
+ bestCount = scopedFound.length;
425
+ if (bestCount === 1)
426
+ break;
427
+ }
428
+ }
429
+ fallbackDataSel = best;
430
+ }
431
+ }
432
+ // 2. Stable non-hashed #id
433
+ if (el.id && /^[A-Za-z][\w-]*$/.test(el.id) && !looksHashedToken(el.id) && isUnique(`#${el.id}`)) {
434
+ return { selector: `#${el.id}`, isStable: true };
435
+ }
436
+ // 3. Repeated/scoped stable data-* attribute (e.g. [data-component="MetricCard"] or [data-slot="card"])
437
+ if (fallbackDataSel) {
438
+ return { selector: fallbackDataSel, isStable: true };
439
+ }
440
+ // 4. Semantic CSS class(es)
441
+ const classes = Array.from(el.classList).filter(isSemanticClass);
442
+ const tag = el.tagName.toLowerCase();
443
+ if (classes.length > 0) {
444
+ const normComp = opts.componentName ? normalizeName(opts.componentName).replace(/\s+/g, '') : '';
445
+ const isModifier = (cls) => cls.includes('--');
446
+ const matchesAllCopies = (cls) => {
447
+ const m = queryMatches(root, `.${cls}`);
448
+ return m.length > 1 && m.includes(el);
449
+ };
450
+ if (opts.componentName) {
451
+ const sharedNonModifiers = classes.filter(c => !isModifier(c) && matchesAllCopies(c));
452
+ if (sharedNonModifiers.length > 0) {
453
+ const compMatch = normComp
454
+ ? sharedNonModifiers.find(c => normalizeName(c).replace(/\s+/g, '') === normComp)
455
+ : undefined;
456
+ return { selector: `.${compMatch ?? sharedNonModifiers[0]}`, isStable: true };
457
+ }
458
+ }
459
+ const preferredOrder = [
460
+ ...classes.filter(c => !isModifier(c)),
461
+ ...classes.filter(isModifier)
462
+ ];
463
+ for (const cls of preferredOrder) {
464
+ if (isUnique(`.${cls}`))
465
+ return { selector: `.${cls}`, isStable: true };
466
+ }
467
+ if (preferredOrder.length >= 2) {
468
+ const combo = `.${preferredOrder[0]}.${preferredOrder[1]}`;
469
+ if (isUnique(combo))
470
+ return { selector: combo, isStable: true };
471
+ }
472
+ for (const cls of preferredOrder) {
473
+ if (isUnique(`${tag}.${cls}`))
474
+ return { selector: `${tag}.${cls}`, isStable: true };
475
+ }
476
+ const base = `.${preferredOrder[0]}`;
477
+ const baseFound = queryMatches(root, base);
478
+ if (baseFound.includes(el)) {
479
+ let best = base;
480
+ let bestCount = baseFound.length;
481
+ for (const anc of ancestors) {
482
+ const scoped = `${anc} ${base}`;
483
+ const scopedFound = queryMatches(root, scoped);
484
+ if (scopedFound.includes(el) && scopedFound.length < bestCount) {
485
+ best = scoped;
486
+ bestCount = scopedFound.length;
487
+ if (bestCount === 1)
488
+ break;
489
+ }
490
+ }
491
+ return { selector: best, isStable: true };
492
+ }
493
+ }
494
+ // 5. Unique non-generic tag under a stable ancestor (e.g. #hero > button, .plan > h2)
495
+ if (opts.allowAncestorTag && !GENERIC_CONTAINER_TAGS.has(tag)) {
496
+ for (const anc of ancestors) {
497
+ const direct = `${anc} > ${tag}`;
498
+ if (isUnique(direct))
499
+ return { selector: direct, isStable: true };
500
+ const desc = `${anc} ${tag}`;
501
+ if (isUnique(desc))
502
+ return { selector: desc, isStable: true };
503
+ }
504
+ }
505
+ return { isStable: false };
506
+ }
141
507
  /**
142
- * Unambiguously match a live DOM element to a saved component rule (Approved Question 4).
508
+ * Pick a stable match for "Point at it": prefers a component name (data-component or React/Vue root),
509
+ * stable data attribute, id, or semantic class; falls back to positional nth-of-type only as a last resort.
510
+ */
511
+ export function stableMatchForElement(el, root = el.ownerDocument) {
512
+ const dataComp = el.getAttribute('data-component')?.trim() || undefined;
513
+ const fwName = readNearestFrameworkComponentName(el)[0]?.trim() || undefined;
514
+ const component = dataComp || fwName;
515
+ const elRoot = el.getRootNode();
516
+ if (root !== elRoot && elRoot !== el.ownerDocument && 'host' in elRoot && elRoot.host) {
517
+ const host = elRoot.host;
518
+ const hostMatch = stableMatchForElement(host, root);
519
+ const innerSel = stableSelectorInner(el, elRoot, { allowAncestorTag: !component, componentName: component });
520
+ if (innerSel.isStable && innerSel.selector) {
521
+ const hostPart = hostMatch.selector ?? selectorFor(host, root);
522
+ return {
523
+ ...(component ? { component } : {}),
524
+ selector: `${hostPart} >> ${innerSel.selector}`
525
+ };
526
+ }
527
+ if (component)
528
+ return { component };
529
+ return { selector: selectorFor(el, root) };
530
+ }
531
+ const selRes = stableSelectorInner(el, root, { allowAncestorTag: !component, componentName: component });
532
+ if (selRes.isStable && selRes.selector) {
533
+ return {
534
+ ...(component ? { component } : {}),
535
+ selector: selRes.selector
536
+ };
537
+ }
538
+ if (component) {
539
+ return { component };
540
+ }
541
+ return { selector: selectorFor(el, root) };
542
+ }
543
+ /** Return the most stable CSS selector for an element, falling back to selectorFor only as a last resort. */
544
+ export function stableSelectorFor(el, root = el.ownerDocument) {
545
+ return stableMatchForElement(el, root).selector ?? selectorFor(el, root);
546
+ }
547
+ /**
548
+ * Unambiguously match a live DOM element to a saved component rule (Approved Question 4 + Brief 02):
143
549
  * 1. Explicit binding from a previous check/verdict on this route.
144
- * 2. Unique frontmatter selector match.
145
- * 3. Unique component-name / type match (if multiple rules share the type -> ambiguous -> No rule).
550
+ * 2. Unique frontmatter or confirmed Figma selector match.
551
+ * 3. Figma component binding (data-component / aria-label / framework component name) + capture name match.
552
+ * 4. Unique component-name match (if multiple rules share the name -> ambiguous -> No rule).
553
+ * Rules whose Figma layer is orphaned, unmatched, waiting-for-build, or skipped stay "No rule".
146
554
  */
555
+ const isComponentScopeRule = (r) => r.scope !== 'section' &&
556
+ r.scope !== 'system' &&
557
+ !r.file.includes('.collection.') &&
558
+ !r.file.includes('.section.') &&
559
+ !r.file.includes('.system.');
147
560
  export function matchRuleForElement(el, entry, rules, explicitBindings) {
148
- const componentRules = rules.filter(r => !r.file.includes('.collection.') && !r.file.includes('.system.'));
561
+ const componentRules = rules.filter(isComponentScopeRule);
149
562
  if (componentRules.length === 0)
150
563
  return { rule: null, ambiguous: false };
151
564
  // 1. Explicit selector binding
@@ -153,12 +566,18 @@ export function matchRuleForElement(el, entry, rules, explicitBindings) {
153
566
  if (boundFile) {
154
567
  const clean = boundFile.replace(/^\.luci\/design\//, '');
155
568
  const found = componentRules.find(r => r.file === clean);
156
- if (found)
569
+ if (found) {
570
+ if (isUnboundFigmaRule(found))
571
+ return { rule: null, ambiguous: false };
157
572
  return { rule: found, ambiguous: false };
573
+ }
158
574
  }
159
- // 2. Frontmatter selector match
160
- const selectorMatches = componentRules.filter(r => {
161
- const sel = r.selector || parseRuleSelector(r.markdown);
575
+ const eligibleRules = componentRules.filter(r => !isUnboundFigmaRule(r));
576
+ if (eligibleRules.length === 0)
577
+ return { rule: null, ambiguous: false };
578
+ // 2. Frontmatter or confirmed Figma selector match
579
+ const selectorMatches = eligibleRules.filter(r => {
580
+ const sel = r.selector || parseRuleSelector(r.markdown) || r.figmaSelector;
162
581
  if (!sel)
163
582
  return false;
164
583
  if (sel === entry.selector)
@@ -174,18 +593,31 @@ export function matchRuleForElement(el, entry, rules, explicitBindings) {
174
593
  return { rule: selectorMatches[0], ambiguous: false };
175
594
  if (selectorMatches.length > 1)
176
595
  return { rule: null, ambiguous: true };
177
- // 3. Unambiguous explicit component-name match (data-component or aria-label matching rule.name).
178
- // Never guess by generic HTML component type alone (e.g. matching every secondary <button>
179
- // against a primary-button rule): Brief 01 req. 8 "prefer No rule over a wrong verdict".
180
- const elHint = normalizeName(el.getAttribute('data-component') ||
596
+ // 3. Explicit component hint (data-component / aria-label / React or Vue owner name)
597
+ const attrHint = normalizeName(el.getAttribute('data-component') ||
181
598
  el.getAttribute('aria-label') ||
182
599
  '');
183
- if (elHint) {
184
- const nameMatches = componentRules.filter(r => normalizeName(r.name) === elHint);
185
- if (nameMatches.length === 1)
186
- return { rule: nameMatches[0], ambiguous: false };
187
- if (nameMatches.length > 1)
600
+ const fwHints = readNearestFrameworkComponentName(el).map(n => normalizeName(n));
601
+ const hints = [...new Set([attrHint, ...fwHints].filter(Boolean))];
602
+ if (hints.length > 0) {
603
+ const compactHints = hints.map(h => h.replace(/\s+/g, ''));
604
+ const figmaMatches = eligibleRules.filter(r => {
605
+ if (!isFigmaRule(r) || !r.figmaComponent)
606
+ return false;
607
+ const target = normalizeName(r.figmaComponent).replace(/\s+/g, '');
608
+ return compactHints.includes(target);
609
+ });
610
+ if (figmaMatches.length === 1)
611
+ return { rule: figmaMatches[0], ambiguous: false };
612
+ if (figmaMatches.length > 1)
188
613
  return { rule: null, ambiguous: true };
614
+ if (attrHint) {
615
+ const nameMatches = eligibleRules.filter(r => normalizeName(r.name) === attrHint);
616
+ if (nameMatches.length === 1)
617
+ return { rule: nameMatches[0], ambiguous: false };
618
+ if (nameMatches.length > 1)
619
+ return { rule: null, ambiguous: true };
620
+ }
189
621
  }
190
622
  return { rule: null, ambiguous: false };
191
623
  }
@@ -273,6 +705,7 @@ export function startSpecWatcher(options) {
273
705
  let warmFrameUrl = '';
274
706
  let warmFrameReady = false;
275
707
  let warmFrameBlocked = false;
708
+ let warmFrameBaseStyles = new Set();
276
709
  let stopped = false;
277
710
  let timer = null;
278
711
  let running = false;
@@ -300,10 +733,34 @@ export function startSpecWatcher(options) {
300
733
  warmFrame = null;
301
734
  warmFrameUrl = '';
302
735
  warmFrameReady = false;
736
+ warmFrameBaseStyles = new Set();
737
+ }
738
+ };
739
+ /** Sync dynamically added/HMR <style> tags from doc.head into the warm iframe head. */
740
+ const syncMirroredHeadStyles = (fdoc) => {
741
+ const fhead = fdoc.head;
742
+ if (!fhead)
743
+ return;
744
+ for (const old of Array.from(fhead.querySelectorAll('style[data-luci-sync-style]'))) {
745
+ old.remove();
746
+ }
747
+ for (const s of Array.from(doc.head?.querySelectorAll('style') ?? [])) {
748
+ if (isLuciNode(s))
749
+ continue;
750
+ const css = s.textContent ?? '';
751
+ if (!css || warmFrameBaseStyles.has(css))
752
+ continue;
753
+ const clone = fdoc.createElement('style');
754
+ clone.setAttribute(LUCI_UI_ATTRIBUTE, '1');
755
+ clone.setAttribute('data-luci-sync-style', '1');
756
+ if (s.media)
757
+ clone.media = s.media;
758
+ clone.textContent = css;
759
+ fhead.appendChild(clone);
303
760
  }
304
761
  };
305
762
  /** Lazily create or resize one hidden same-origin iframe to avoid full page reloads per HMR. */
306
- async function getWarmFrameDoc(width) {
763
+ async function getWarmFrameDoc(width, waitSelector) {
307
764
  if (warmFrameBlocked || stopped)
308
765
  return null;
309
766
  const url = win.location.href;
@@ -337,6 +794,7 @@ export function startSpecWatcher(options) {
337
794
  destroyWarmFrame();
338
795
  return null;
339
796
  }
797
+ warmFrameBaseStyles = new Set(Array.from(fdoc.querySelectorAll('style')).map(s => s.textContent ?? '').filter(Boolean));
340
798
  warmFrameReady = true;
341
799
  }
342
800
  catch {
@@ -349,16 +807,27 @@ export function startSpecWatcher(options) {
349
807
  return null;
350
808
  warmFrame.style.width = `${width}px`;
351
809
  const fwin = warmFrame.contentWindow;
352
- if (fwin)
353
- await waitFrames(fwin, 2);
810
+ let fdoc = null;
354
811
  try {
355
- return warmFrame.contentDocument;
812
+ fdoc = warmFrame.contentDocument;
356
813
  }
357
814
  catch {
358
815
  warmFrameBlocked = true;
359
816
  destroyWarmFrame();
360
817
  return null;
361
818
  }
819
+ if (!fdoc)
820
+ return null;
821
+ syncMirroredHeadStyles(fdoc);
822
+ if (waitSelector && !findBySelector(fdoc, waitSelector)) {
823
+ const deadline = Date.now() + frameTimeoutMs;
824
+ while (!stopped && Date.now() < deadline && !findBySelector(fdoc, waitSelector)) {
825
+ await new Promise(r => setTimeout(r, 40));
826
+ }
827
+ }
828
+ if (fwin)
829
+ await waitFrames(fwin, 2);
830
+ return fdoc;
362
831
  }
363
832
  async function evaluateBatch(runOpts = {}) {
364
833
  if (stopped)
@@ -370,7 +839,8 @@ export function startSpecWatcher(options) {
370
839
  running = true;
371
840
  try {
372
841
  const rules = await options.loadRules();
373
- const widths = extractProjectWidths(rules);
842
+ const baselineWidths = readBaselineSystemWidths(rules);
843
+ const projectWidths = extractProjectWidths(rules);
374
844
  const existing = options.existingVerdicts?.() ?? [];
375
845
  for (const prev of existing) {
376
846
  if (!latestById.has(prev.id)) {
@@ -386,8 +856,8 @@ export function startSpecWatcher(options) {
386
856
  catch {
387
857
  return '/';
388
858
  } })();
389
- const liveWidth = Math.round(win.innerWidth || widths[1]);
390
- const otherWidth = Math.abs(liveWidth - widths[0]) < Math.abs(liveWidth - widths[1]) ? widths[1] : widths[0];
859
+ const curWidth = Math.round(win.innerWidth || 0);
860
+ const isRealOrigin = win.location.protocol === 'http:' || win.location.protocol === 'https:';
391
861
  // Discover candidate elements: explicitly bound selectors + saved rule selectors + pageComponents()
392
862
  const seenEls = new Set();
393
863
  const candidates = [];
@@ -403,10 +873,19 @@ export function startSpecWatcher(options) {
403
873
  for (const sel of explicitBindings.keys()) {
404
874
  addCandidate(findBySelector(doc, sel));
405
875
  }
876
+ const wantedComponentHints = new Set();
406
877
  for (const rule of rules) {
407
- if (rule.file.includes('.collection.') || rule.file.includes('.system.'))
878
+ if (!isComponentScopeRule(rule))
879
+ continue;
880
+ if (isUnboundFigmaRule(rule))
408
881
  continue;
409
- const sel = rule.selector || parseRuleSelector(rule.markdown);
882
+ if (isFigmaRule(rule) && rule.figmaComponent) {
883
+ wantedComponentHints.add(normalizeName(rule.figmaComponent).replace(/\s+/g, ''));
884
+ }
885
+ if (rule.name) {
886
+ wantedComponentHints.add(normalizeName(rule.name).replace(/\s+/g, ''));
887
+ }
888
+ const sel = rule.selector || parseRuleSelector(rule.markdown) || rule.figmaSelector;
410
889
  if (!sel)
411
890
  continue;
412
891
  if (sel.includes(' >> ')) {
@@ -414,7 +893,7 @@ export function startSpecWatcher(options) {
414
893
  }
415
894
  else {
416
895
  try {
417
- const matched = Array.from(doc.querySelectorAll(sel)).slice(0, 10);
896
+ const matched = Array.from(doc.querySelectorAll(sel)).slice(0, 25);
418
897
  for (const el of matched)
419
898
  addCandidate(el);
420
899
  }
@@ -423,12 +902,31 @@ export function startSpecWatcher(options) {
423
902
  }
424
903
  }
425
904
  }
905
+ if (wantedComponentHints.size > 0) {
906
+ const countByHint = new Map();
907
+ for (const el of live.nodes) {
908
+ if (!el || isLuciNode(el) || seenEls.has(el))
909
+ continue;
910
+ const attrHint = normalizeName(el.getAttribute('data-component') || el.getAttribute('aria-label') || '');
911
+ const fwHints = readNearestFrameworkComponentName(el).map(n => normalizeName(n));
912
+ const compactHints = [...new Set([attrHint, ...fwHints].filter(Boolean))].map(h => h.replace(/\s+/g, ''));
913
+ const matchedHint = compactHints.find(h => wantedComponentHints.has(h));
914
+ if (!matchedHint)
915
+ continue;
916
+ const count = countByHint.get(matchedHint) ?? 0;
917
+ if (count >= 25)
918
+ continue;
919
+ countByHint.set(matchedHint, count + 1);
920
+ addCandidate(el);
921
+ }
922
+ }
426
923
  for (const entry of pageComponents(live.snapshot)) {
427
924
  addCandidate(live.nodes[entry.id] ?? null);
428
925
  }
429
926
  const nextBaselines = { ...baselines };
430
927
  const dirty = [];
431
928
  const matchedRuleIds = new Set();
929
+ const matchedEls = new Set();
432
930
  const changedIds = new Set();
433
931
  const hasPriorBaselines = Object.keys(baselines).length > 0;
434
932
  for (const { el, entry } of candidates) {
@@ -440,28 +938,83 @@ export function startSpecWatcher(options) {
440
938
  const match = matchRuleForElement(el, entry, rules, explicitBindings);
441
939
  const changed = prevFp !== undefined && prevFp !== fp;
442
940
  const isFirstRun = !hasPriorBaselines || prevVerdict === undefined;
443
- if (match.rule !== null)
941
+ if (match.rule !== null) {
444
942
  matchedRuleIds.add(id);
943
+ matchedEls.add(el);
944
+ }
445
945
  if (changed)
446
946
  changedIds.add(id);
447
947
  // Only evaluate elements that match a saved rule, genuinely changed on the page, or hit an ambiguous rule collision.
448
948
  // Never dump every untouched element on the page as "No rule" on initial load or Re-check.
449
- const shouldCheck = (match.rule !== null && (Boolean(runOpts.forceAll) || changed || prevVerdict?.state === 'drift' || isFirstRun)) ||
949
+ const shouldCheck = (match.rule !== null && (Boolean(runOpts.forceAll) || changed || prevVerdict?.state === 'drift' || prevVerdict?.state === 'no-rule' || isFirstRun)) ||
450
950
  changed ||
451
951
  match.ambiguous;
452
952
  if (shouldCheck) {
453
- dirty.push({ el, entry, id, match });
953
+ const ruleWidths = match.rule ? extractRuleWidths(match.rule, baselineWidths) : [];
954
+ dirty.push({ el, entry, id, match, ruleWidths });
454
955
  }
455
956
  }
456
- // Prune stale entries on the current page whose rule was deleted/no longer matches,
457
- // or untouched "no-rule" entries from earlier sessions.
957
+ // Prune stale entries on the current page whose element vanished,
958
+ // or transition removed/orphaned/unbound rules into visible "No rule" rows (kept while on the page).
458
959
  let pruned = false;
960
+ const unboundFigmaFiles = new Set(rules.filter(r => isUnboundFigmaRule(r)).map(r => r.file));
459
961
  for (const [id, prev] of Array.from(latestById.entries())) {
460
962
  if (!id.endsWith(`::${pagePath}`))
461
963
  continue;
964
+ const staleEl = findBySelector(doc, prev.selector);
965
+ const stillOnPage = Boolean(staleEl);
966
+ const prevCleanRule = prev.ruleFile ? prev.ruleFile.replace(/^\.luci\/design\//, '') : null;
967
+ if (prevCleanRule && unboundFigmaFiles.has(prevCleanRule)) {
968
+ if (!stillOnPage || (staleEl && matchedEls.has(staleEl))) {
969
+ latestById.delete(id);
970
+ selectorById.delete(id);
971
+ }
972
+ else {
973
+ latestById.set(id, {
974
+ ...prev,
975
+ ruleFile: null,
976
+ state: 'no-rule',
977
+ matches: 0,
978
+ differences: [],
979
+ fixRounds: 0,
980
+ needsHuman: false,
981
+ reason: 'missing-rule',
982
+ matchedRuleFile: prev.ruleFile ?? prev.matchedRuleFile,
983
+ hadRule: true,
984
+ note: undefined,
985
+ excuse: null
986
+ });
987
+ }
988
+ pruned = true;
989
+ continue;
990
+ }
462
991
  const staleRule = Boolean(prev.ruleFile) && !matchedRuleIds.has(id);
992
+ if (staleRule) {
993
+ if (!stillOnPage || (staleEl && matchedEls.has(staleEl))) {
994
+ latestById.delete(id);
995
+ selectorById.delete(id);
996
+ }
997
+ else {
998
+ latestById.set(id, {
999
+ ...prev,
1000
+ ruleFile: null,
1001
+ state: 'no-rule',
1002
+ matches: 0,
1003
+ differences: [],
1004
+ fixRounds: 0,
1005
+ needsHuman: false,
1006
+ reason: 'missing-rule',
1007
+ matchedRuleFile: prev.ruleFile ?? prev.matchedRuleFile,
1008
+ hadRule: true,
1009
+ note: undefined,
1010
+ excuse: null
1011
+ });
1012
+ }
1013
+ pruned = true;
1014
+ continue;
1015
+ }
463
1016
  const staleNoRule = prev.state === 'no-rule' && !changedIds.has(id) && (Boolean(runOpts.forceAll) || !hasPriorBaselines);
464
- if (staleRule || staleNoRule) {
1017
+ if (staleNoRule && !(prev.hadRule && stillOnPage)) {
465
1018
  latestById.delete(id);
466
1019
  selectorById.delete(id);
467
1020
  pruned = true;
@@ -471,31 +1024,54 @@ export function startSpecWatcher(options) {
471
1024
  saveBaselines(win, `${storageKey}:${win.location.pathname}`, baselines);
472
1025
  if (dirty.length === 0) {
473
1026
  if (pruned)
474
- options.onVerdicts([...latestById.values()], widths, { replace: true });
1027
+ options.onVerdicts([...latestById.values()], projectWidths, { replace: true });
475
1028
  return [...latestById.values()];
476
1029
  }
477
- // Check which dirty ruled elements actually have media queries targeting them
478
- const needsSecondWidth = dirty.filter(d => d.match.rule !== null && mediaQueriesFor(d.el).length > 0);
479
- let frameDoc = null;
480
- let frameLive = null;
481
- let frameBlockedNote;
1030
+ // Evaluate each ruled component at its own stated widths (e.g. Figma frame width or [375, 1440] default),
1031
+ // NEVER assuming other widths match just because no @media rule matched at the current viewport.
1032
+ const neededWidths = [...new Set(dirty.flatMap(d => d.ruleWidths))].sort((a, b) => a - b);
1033
+ const needsWarmFrames = isRealOrigin && dirty.some(d => d.match.rule !== null);
1034
+ const missingWidths = needsWarmFrames ? neededWidths.filter(w => w !== curWidth) : [];
1035
+ const frameByWidth = new Map();
1036
+ let frameBlocked = false;
482
1037
  const updated = [];
483
1038
  await withMutedObserver(async () => {
484
- if (needsSecondWidth.length > 0) {
485
- frameDoc = await getWarmFrameDoc(otherWidth);
486
- if (frameDoc) {
487
- frameLive = liveSnapshot(frameDoc);
488
- }
489
- else {
490
- frameBlockedNote = `Checked at ${liveWidth}px only — frame blocked`;
1039
+ if (missingWidths.length > 0) {
1040
+ const sampleSelector = dirty.find(d => d.match.rule !== null)?.entry.selector;
1041
+ for (const w of missingWidths) {
1042
+ const fdoc = await getWarmFrameDoc(w, sampleSelector);
1043
+ if (fdoc) {
1044
+ frameByWidth.set(w, { doc: fdoc, live: liveSnapshot(fdoc) });
1045
+ }
1046
+ else {
1047
+ frameBlocked = true;
1048
+ }
491
1049
  }
492
1050
  }
493
1051
  const checkedAt = new Date().toISOString();
1052
+ const evaluateAtWidth = async (targetLive, targetEntry, w, choice, ruleFile, ambiguousRule, excuse, variantLayer) => {
1053
+ const checkRes = await checkAgainst(targetLive, targetEntry, choice, undefined, variantLayer ? { variantLayer } : undefined);
1054
+ if (!checkRes.ok)
1055
+ return { ok: false, message: checkRes.message };
1056
+ const builtSpec = readBuiltSpec(targetLive, targetEntry);
1057
+ const evaluated = evaluateSpecVerdict({
1058
+ ruleFile,
1059
+ ambiguousRule,
1060
+ design: checkRes.design,
1061
+ built: builtSpec,
1062
+ result: checkRes.result,
1063
+ stylesReadable: targetLive.snapshot.stylesReadable,
1064
+ excuse,
1065
+ width: w
1066
+ });
1067
+ return { ok: true, evaluated, variant: checkRes.result.variant };
1068
+ };
494
1069
  for (const item of dirty) {
495
- const { el, entry, id, match } = item;
1070
+ const { el, entry, id, match, ruleWidths } = item;
496
1071
  const prev = latestById.get(id);
497
- const displayName = displayNameForElement(el, entry, match.rule?.name);
1072
+ const displayName = displayNameForElement(el, entry, match.rule?.name, match.rule?.figmaComponent);
498
1073
  if (!match.rule) {
1074
+ const reason = match.ambiguous ? 'ambiguous-rule' : 'missing-rule';
499
1075
  const verdict = {
500
1076
  id,
501
1077
  name: displayName,
@@ -504,11 +1080,14 @@ export function startSpecWatcher(options) {
504
1080
  ruleFile: null,
505
1081
  state: 'no-rule',
506
1082
  checkedAt,
507
- widthsChecked: [liveWidth],
1083
+ widthsChecked: [],
508
1084
  matches: 0,
509
1085
  differences: [],
510
1086
  fixRounds: 0,
511
- needsHuman: false
1087
+ needsHuman: false,
1088
+ reason,
1089
+ ...(prev?.ruleFile || prev?.hadRule ? { hadRule: true, ...(prev.ruleFile ?? prev.matchedRuleFile ? { matchedRuleFile: prev.ruleFile ?? prev.matchedRuleFile } : {}) } : {}),
1090
+ ...(match.ambiguous ? { note: SPEC_REASON_MESSAGES['ambiguous-rule'] } : {})
512
1091
  };
513
1092
  latestById.set(id, verdict);
514
1093
  selectorById.set(id, entry.selector);
@@ -521,92 +1100,169 @@ export function startSpecWatcher(options) {
521
1100
  file: ruleFile,
522
1101
  markdown: match.rule.markdown
523
1102
  };
524
- const liveCheck = await checkAgainst(live, entry, choice);
525
- if (!liveCheck.ok) {
526
- const verdict = {
527
- id,
528
- name: displayName,
529
- selector: entry.selector,
530
- page: pageUrl,
531
- ruleFile: null,
532
- state: 'no-rule',
533
- checkedAt,
534
- widthsChecked: [liveWidth],
535
- matches: 0,
536
- differences: [],
537
- fixRounds: 0,
538
- needsHuman: false,
539
- note: liveCheck.message
540
- };
541
- latestById.set(id, verdict);
542
- selectorById.set(id, entry.selector);
543
- updated.push(verdict);
544
- continue;
545
- }
546
- const builtSpec = readBuiltSpec(live, entry);
547
- const primary = evaluateSpecVerdict({
548
- ruleFile,
549
- ambiguousRule: match.ambiguous,
550
- design: liveCheck.design,
551
- built: builtSpec,
552
- result: liveCheck.result,
553
- stylesReadable: live.snapshot.stylesReadable,
554
- excuse: prev?.excuse ?? null,
555
- width: liveWidth
1103
+ const matchingLayerBindings = (match.rule.variantBindings ?? []).filter(b => {
1104
+ if (b.selector === entry.selector)
1105
+ return true;
1106
+ try {
1107
+ return el.matches(b.selector);
1108
+ }
1109
+ catch {
1110
+ return false;
1111
+ }
556
1112
  });
557
- let combinedDiffs = [...primary.differences];
558
- let totalMatches = primary.matches;
559
- let finalState = primary.state;
560
- const widthsChecked = [liveWidth];
561
- let note;
1113
+ const boundVariantLayer = matchingLayerBindings.length === 1
1114
+ ? { fileKey: matchingLayerBindings[0].fileKey, nodeId: matchingLayerBindings[0].nodeId }
1115
+ : undefined;
562
1116
  const hasMq = mediaQueriesFor(el).length > 0;
563
- if (!hasMq) {
564
- // No media queries apply to this element -> styles are identical across both widths (0ms fast path).
565
- if (!widthsChecked.includes(otherWidth))
566
- widthsChecked.push(otherWidth);
1117
+ let combinedDiffs = [];
1118
+ let totalMatches = 0;
1119
+ let finalState = 'on-spec';
1120
+ const widthsChecked = [];
1121
+ let checkedVariant;
1122
+ let note;
1123
+ let verdictReason;
1124
+ // Synthetic about:blank documents cannot load hidden iframes of themselves; evaluate live directly,
1125
+ // and count a width as checked only when live actually matches that rule's stated width.
1126
+ const liveMatchForRule = ruleWidths.includes(curWidth) ? curWidth : null;
1127
+ if (!isRealOrigin) {
1128
+ const evalWidth = liveMatchForRule ?? ruleWidths[ruleWidths.length - 1] ?? DEFAULT_SPEC_WIDTHS[1];
1129
+ const liveEval = await evaluateAtWidth(live, entry, evalWidth, choice, ruleFile, match.ambiguous, prev?.excuse ?? null, boundVariantLayer);
1130
+ if (!liveEval.ok) {
1131
+ const verdict = {
1132
+ id,
1133
+ name: displayName,
1134
+ selector: entry.selector,
1135
+ page: pageUrl,
1136
+ ruleFile: null,
1137
+ state: 'no-rule',
1138
+ checkedAt,
1139
+ widthsChecked: [],
1140
+ matches: 0,
1141
+ differences: [],
1142
+ fixRounds: 0,
1143
+ needsHuman: false,
1144
+ reason: 'inconclusive',
1145
+ matchedRuleFile: ruleFile,
1146
+ note: liveEval.message
1147
+ };
1148
+ latestById.set(id, verdict);
1149
+ selectorById.set(id, entry.selector);
1150
+ updated.push(verdict);
1151
+ continue;
1152
+ }
1153
+ const ev = liveEval.evaluated;
1154
+ checkedVariant = liveEval.variant;
1155
+ finalState = ev.state;
1156
+ totalMatches = ev.matches;
1157
+ combinedDiffs = [...ev.differences];
1158
+ verdictReason = ev.reason;
1159
+ if (finalState === 'no-rule' && ev.reason && ev.reason !== 'excused') {
1160
+ note = ev.reason === 'low-confidence-match' && !isFigmaRule(match.rule)
1161
+ ? "This element doesn't look like the saved rule."
1162
+ : SPEC_REASON_MESSAGES[ev.reason];
1163
+ }
1164
+ if (finalState !== 'no-rule' && liveMatchForRule !== null) {
1165
+ widthsChecked.push(liveMatchForRule);
1166
+ }
567
1167
  }
568
- else if (frameDoc && frameLive && finalState !== 'no-rule') {
569
- const otherEl = findBySelector(frameDoc, entry.selector);
570
- const otherEntry = otherEl ? frameLive.entryFor(otherEl) : null;
571
- if (otherEl && otherEntry) {
572
- const otherCheck = await checkAgainst(frameLive, otherEntry, choice);
573
- if (otherCheck.ok) {
574
- const otherBuilt = readBuiltSpec(frameLive, otherEntry);
575
- const secondary = evaluateSpecVerdict({
576
- ruleFile,
577
- design: otherCheck.design,
578
- built: otherBuilt,
579
- result: otherCheck.result,
580
- stylesReadable: frameLive.snapshot.stylesReadable,
581
- excuse: prev?.excuse ?? null,
582
- width: otherWidth
583
- });
584
- widthsChecked.push(otherWidth);
585
- totalMatches = Math.max(totalMatches, secondary.matches);
586
- const seenDiffKey = new Set(combinedDiffs.map(d => `${d.part}|${d.state ?? ''}|${d.property}|${d.expected}|${d.actual}`));
587
- for (const d of secondary.differences) {
588
- const k = `${d.part}|${d.state ?? ''}|${d.property}|${d.expected}|${d.actual}`;
589
- if (!seenDiffKey.has(k)) {
590
- seenDiffKey.add(k);
591
- combinedDiffs.push(d);
1168
+ else {
1169
+ // Check ONLY this rule's stated widths (e.g. Figma frame width or [375, 1440]), never win.innerWidth unless it matches.
1170
+ const seenDiffKey = new Set();
1171
+ const uncheckedWidths = [];
1172
+ let checkedAny = false;
1173
+ let allNoRule = true;
1174
+ let firstErrMessage;
1175
+ let firstNoRuleReason;
1176
+ for (const w of ruleWidths) {
1177
+ let targetLive = null;
1178
+ let targetEntry = null;
1179
+ if (w === curWidth) {
1180
+ targetLive = live;
1181
+ targetEntry = entry;
1182
+ }
1183
+ else {
1184
+ const frame = frameByWidth.get(w);
1185
+ if (frame) {
1186
+ const frameEl = findBySelector(frame.doc, entry.selector);
1187
+ const fe = frameEl ? frame.live.entryFor(frameEl) : null;
1188
+ if (frameEl && fe) {
1189
+ targetLive = frame.live;
1190
+ targetEntry = fe;
592
1191
  }
593
1192
  }
594
- if (combinedDiffs.length > 0 && finalState === 'on-spec') {
595
- finalState = prev?.excuse ? 'excused' : 'drift';
1193
+ }
1194
+ if (!targetLive || !targetEntry) {
1195
+ uncheckedWidths.push(w);
1196
+ continue;
1197
+ }
1198
+ const evalRes = await evaluateAtWidth(targetLive, targetEntry, w, choice, ruleFile, match.ambiguous, prev?.excuse ?? null, boundVariantLayer);
1199
+ if (!evalRes.ok) {
1200
+ firstErrMessage ??= evalRes.message;
1201
+ uncheckedWidths.push(w);
1202
+ continue;
1203
+ }
1204
+ checkedAny = true;
1205
+ widthsChecked.push(w);
1206
+ if (evalRes.variant)
1207
+ checkedVariant ??= evalRes.variant;
1208
+ const ev = evalRes.evaluated;
1209
+ if (ev.state !== 'no-rule')
1210
+ allNoRule = false;
1211
+ else
1212
+ firstNoRuleReason ??= ev.reason;
1213
+ totalMatches = Math.max(totalMatches, ev.matches);
1214
+ for (const d of ev.differences) {
1215
+ const k = `${d.part}|${d.state ?? ''}|${d.property}|${d.expected}|${d.actual}`;
1216
+ if (!seenDiffKey.has(k)) {
1217
+ seenDiffKey.add(k);
1218
+ combinedDiffs.push(d);
596
1219
  }
597
1220
  }
598
1221
  }
599
- }
600
- else if (hasMq && frameBlockedNote) {
601
- note = frameBlockedNote;
1222
+ if (!checkedAny) {
1223
+ finalState = 'no-rule';
1224
+ if (firstErrMessage) {
1225
+ verdictReason = 'inconclusive';
1226
+ note = firstErrMessage;
1227
+ }
1228
+ else {
1229
+ verdictReason = 'width-not-checked';
1230
+ note = formatWidthNotCheckedNote(uncheckedWidths.length > 0 ? uncheckedWidths : ruleWidths);
1231
+ }
1232
+ }
1233
+ else if (allNoRule) {
1234
+ finalState = 'no-rule';
1235
+ verdictReason = firstNoRuleReason ?? 'missing-rule';
1236
+ if (verdictReason !== 'excused') {
1237
+ note = verdictReason === 'low-confidence-match' && !isFigmaRule(match.rule)
1238
+ ? "This element doesn't look like the saved rule."
1239
+ : SPEC_REASON_MESSAGES[verdictReason];
1240
+ }
1241
+ }
1242
+ else if (combinedDiffs.length > 0) {
1243
+ finalState = prev?.excuse && prev.excuse.reason.trim().length > 0 ? 'excused' : 'drift';
1244
+ if (finalState === 'excused')
1245
+ verdictReason = 'excused';
1246
+ }
1247
+ else {
1248
+ finalState = 'on-spec';
1249
+ }
1250
+ if (checkedAny && uncheckedWidths.length > 0) {
1251
+ note = formatWidthNotCheckedNote(uncheckedWidths);
1252
+ }
1253
+ else if (!checkedAny && frameBlocked && !firstErrMessage) {
1254
+ verdictReason = 'width-not-checked';
1255
+ note = formatWidthNotCheckedNote(uncheckedWidths.length > 0 ? uncheckedWidths : ruleWidths);
1256
+ }
602
1257
  }
603
1258
  widthsChecked.sort((a, b) => a - b);
1259
+ combinedDiffs = polishFigmaDifferences(combinedDiffs, match.rule);
604
1260
  const verdict = {
605
1261
  id,
606
1262
  name: displayName,
607
1263
  selector: entry.selector,
608
1264
  page: pageUrl,
609
- ruleFile: finalState === 'no-rule' ? null : ruleFile,
1265
+ ruleFile: finalState === 'no-rule' && verdictReason !== 'width-not-checked' ? null : ruleFile,
610
1266
  state: finalState,
611
1267
  checkedAt,
612
1268
  widthsChecked,
@@ -615,6 +1271,9 @@ export function startSpecWatcher(options) {
615
1271
  fixRounds: finalState === 'on-spec' ? 0 : (prev?.fixRounds ?? 0),
616
1272
  needsHuman: finalState === 'drift' ? Boolean(prev?.needsHuman) : false,
617
1273
  lastBlockedAt: finalState === 'drift' ? (prev?.lastBlockedAt ?? null) : null,
1274
+ ...(verdictReason ? { reason: verdictReason } : {}),
1275
+ ...(finalState !== 'no-rule' && checkedVariant ? { variant: checkedVariant } : {}),
1276
+ ...(finalState === 'no-rule' && verdictReason === 'low-confidence-match' ? { matchedRuleFile: ruleFile } : {}),
618
1277
  ...(note ? { note } : {}),
619
1278
  ...(finalState === 'excused' && prev?.excuse ? { excuse: prev.excuse } : {})
620
1279
  };
@@ -624,7 +1283,8 @@ export function startSpecWatcher(options) {
624
1283
  }
625
1284
  });
626
1285
  if (updated.length > 0 || pruned) {
627
- options.onVerdicts([...latestById.values()], widths, pruned ? { replace: true } : undefined);
1286
+ const batchWidths = [...new Set(dirty.filter(d => d.ruleWidths.length > 0).flatMap(d => d.ruleWidths))].sort((a, b) => a - b);
1287
+ options.onVerdicts([...latestById.values()], batchWidths.length > 0 ? batchWidths : projectWidths, pruned ? { replace: true } : undefined);
628
1288
  }
629
1289
  return [...latestById.values()];
630
1290
  }
@@ -650,8 +1310,15 @@ export function startSpecWatcher(options) {
650
1310
  if (stopped || suppressingMutations)
651
1311
  return;
652
1312
  const meaningful = mutations.some(m => !isLuciMutation(m));
653
- if (meaningful)
654
- scheduleCheck();
1313
+ if (!meaningful)
1314
+ return;
1315
+ if (warmFrameReady && warmFrame?.contentDocument && doc.head && mutations.some(m => doc.head.contains(m.target))) {
1316
+ try {
1317
+ syncMirroredHeadStyles(warmFrame.contentDocument);
1318
+ }
1319
+ catch { /* ignore */ }
1320
+ }
1321
+ scheduleCheck();
655
1322
  });
656
1323
  if (doc.body) {
657
1324
  observer.observe(doc.body, {
@@ -676,6 +1343,18 @@ export function startSpecWatcher(options) {
676
1343
  bindRule(selector, ruleFile) {
677
1344
  explicitBindings.set(selector, ruleFile);
678
1345
  },
1346
+ unbindRule(selector, ruleFile) {
1347
+ if (selector)
1348
+ explicitBindings.delete(selector);
1349
+ if (ruleFile) {
1350
+ const norm = ruleFile.replace(/^\.luci\/design\//, '');
1351
+ for (const [sel, bound] of Array.from(explicitBindings.entries())) {
1352
+ if (bound.replace(/^\.luci\/design\//, '') === norm) {
1353
+ explicitBindings.delete(sel);
1354
+ }
1355
+ }
1356
+ }
1357
+ },
679
1358
  verdictForElement(el) {
680
1359
  for (const [id, sel] of selectorById.entries()) {
681
1360
  try {