@luci-dev/capture 0.5.8 → 0.7.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.
Files changed (98) hide show
  1. package/README.md +1 -1
  2. package/dist/a11y.d.ts +3 -2
  3. package/dist/a11y.d.ts.map +1 -1
  4. package/dist/a11y.js +85 -13
  5. package/dist/a11y.js.map +1 -1
  6. package/dist/color.d.ts.map +1 -1
  7. package/dist/color.js +40 -8
  8. package/dist/color.js.map +1 -1
  9. package/dist/component.d.ts +22 -5
  10. package/dist/component.d.ts.map +1 -1
  11. package/dist/component.js +160 -46
  12. package/dist/component.js.map +1 -1
  13. package/dist/dom.d.ts +8 -6
  14. package/dist/dom.d.ts.map +1 -1
  15. package/dist/dom.js +99 -11
  16. package/dist/dom.js.map +1 -1
  17. package/dist/font.d.ts.map +1 -1
  18. package/dist/font.js +17 -3
  19. package/dist/font.js.map +1 -1
  20. package/dist/icon.js +12 -12
  21. package/dist/icon.js.map +1 -1
  22. package/dist/luci-capture.js +7098 -2681
  23. package/dist/model.d.ts +6 -7
  24. package/dist/model.d.ts.map +1 -1
  25. package/dist/model.js +13 -4
  26. package/dist/model.js.map +1 -1
  27. package/dist/page.d.ts +17 -3
  28. package/dist/page.d.ts.map +1 -1
  29. package/dist/page.js +287 -16
  30. package/dist/page.js.map +1 -1
  31. package/dist/responsive.d.ts +3 -1
  32. package/dist/responsive.d.ts.map +1 -1
  33. package/dist/responsive.js +23 -3
  34. package/dist/responsive.js.map +1 -1
  35. package/dist/section.d.ts +2 -1
  36. package/dist/section.d.ts.map +1 -1
  37. package/dist/section.js +28 -18
  38. package/dist/section.js.map +1 -1
  39. package/dist/spacing.d.ts +2 -0
  40. package/dist/spacing.d.ts.map +1 -1
  41. package/dist/spacing.js +50 -8
  42. package/dist/spacing.js.map +1 -1
  43. package/dist/states.d.ts +6 -0
  44. package/dist/states.d.ts.map +1 -1
  45. package/dist/states.js +81 -12
  46. package/dist/states.js.map +1 -1
  47. package/dist/text.d.ts +7 -1
  48. package/dist/text.d.ts.map +1 -1
  49. package/dist/text.js +175 -26
  50. package/dist/text.js.map +1 -1
  51. package/dist/ui/check.d.ts +14 -0
  52. package/dist/ui/check.d.ts.map +1 -1
  53. package/dist/ui/check.js +71 -55
  54. package/dist/ui/check.js.map +1 -1
  55. package/dist/ui/devSettings.d.ts +67 -2
  56. package/dist/ui/devSettings.d.ts.map +1 -1
  57. package/dist/ui/devSettings.js +152 -7
  58. package/dist/ui/devSettings.js.map +1 -1
  59. package/dist/ui/index.d.ts +6 -2
  60. package/dist/ui/index.d.ts.map +1 -1
  61. package/dist/ui/index.js +6 -2
  62. package/dist/ui/index.js.map +1 -1
  63. package/dist/ui/mount.d.ts +15 -1
  64. package/dist/ui/mount.d.ts.map +1 -1
  65. package/dist/ui/mount.js +5 -0
  66. package/dist/ui/mount.js.map +1 -1
  67. package/dist/ui/onSpec.d.ts +61 -0
  68. package/dist/ui/onSpec.d.ts.map +1 -0
  69. package/dist/ui/onSpec.js +516 -0
  70. package/dist/ui/onSpec.js.map +1 -0
  71. package/dist/ui/projectLabel.d.ts +11 -0
  72. package/dist/ui/projectLabel.d.ts.map +1 -0
  73. package/dist/ui/projectLabel.js +15 -0
  74. package/dist/ui/projectLabel.js.map +1 -0
  75. package/dist/ui/remap.d.ts.map +1 -1
  76. package/dist/ui/remap.js +7 -3
  77. package/dist/ui/remap.js.map +1 -1
  78. package/dist/ui/specWatcher.d.ts +79 -0
  79. package/dist/ui/specWatcher.d.ts.map +1 -0
  80. package/dist/ui/specWatcher.js +702 -0
  81. package/dist/ui/specWatcher.js.map +1 -0
  82. package/dist/ui/styles.d.ts +4 -1
  83. package/dist/ui/styles.d.ts.map +1 -1
  84. package/dist/ui/styles.js +343 -2
  85. package/dist/ui/styles.js.map +1 -1
  86. package/dist/ui/toolbar.d.ts +15 -1
  87. package/dist/ui/toolbar.d.ts.map +1 -1
  88. package/dist/ui/toolbar.js +233 -64
  89. package/dist/ui/toolbar.js.map +1 -1
  90. package/dist/ui/tools.d.ts +5 -4
  91. package/dist/ui/tools.d.ts.map +1 -1
  92. package/dist/ui/tools.js +44 -13
  93. package/dist/ui/tools.js.map +1 -1
  94. package/dist/ui/updateBanner.d.ts +13 -0
  95. package/dist/ui/updateBanner.d.ts.map +1 -0
  96. package/dist/ui/updateBanner.js +105 -0
  97. package/dist/ui/updateBanner.js.map +1 -0
  98. package/package.json +3 -3
@@ -0,0 +1,702 @@
1
+ /**
2
+ * Changed-component watcher & 2-width On spec runner (v0.7, Brief 01 req. 5, 6, 7, 8).
3
+ *
4
+ * - Watches DOM and stylesheet mutations (debounced 250ms) and reload baselines in sessionStorage.
5
+ * - Re-checks ONLY changed components (plus components currently in drift) using one shared
6
+ * liveSnapshot(doc) per batch so typical checks stay well under 2 seconds.
7
+ * - Checks at 2 widths (project breakpoints from .luci/design/ when present, else 375px and 1440px),
8
+ * skipping the second width when no media queries style the component and reusing a warm hidden
9
+ * same-origin iframe when media queries do apply (with graceful fallback if framing is blocked).
10
+ * - Enforces "prefer No rule over a wrong verdict": ambiguous matches never guess.
11
+ */
12
+ import { DEFAULT_SPEC_WIDTHS, evaluateSpecVerdict, readComponentFile } from '@luci-dev/format/capture';
13
+ import { componentType } from '../component.js';
14
+ import { LUCI_UI_ATTRIBUTE } from '../dom.js';
15
+ import { pageComponents } from '../page.js';
16
+ import { LUCI_FRAME_NAME, mediaQueriesFor } from '../responsive.js';
17
+ import { captureComponent, checkAgainst, liveSnapshot, readComponentStates } from './tools.js';
18
+ const WATCH_PROPS = [
19
+ 'color', 'background-color', 'opacity', 'box-shadow',
20
+ 'border-top-color', 'border-right-color', 'border-bottom-color', 'border-left-color',
21
+ 'border-top-width', 'border-right-width', 'border-bottom-width', 'border-left-width',
22
+ 'border-top-left-radius', 'border-top-right-radius', 'border-bottom-right-radius', 'border-bottom-left-radius',
23
+ 'font-family', 'font-size', 'font-weight', 'line-height', 'letter-spacing',
24
+ 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
25
+ 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
26
+ 'gap', 'display', 'flex-direction', 'align-items', 'justify-content'
27
+ ];
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) {
31
+ 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)
36
+ 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);
41
+ }
42
+ }
43
+ const sorted = [...widths].sort((a, b) => a - b);
44
+ if (sorted.length >= 2) {
45
+ return [sorted[0], sorted[sorted.length - 1]];
46
+ }
47
+ return [DEFAULT_SPEC_WIDTHS[0], DEFAULT_SPEC_WIDTHS[1]];
48
+ }
49
+ const LANDMARK_LABELS = {
50
+ header: 'Header',
51
+ footer: 'Footer',
52
+ nav: 'Navigation',
53
+ main: 'Main',
54
+ aside: 'Aside'
55
+ };
56
+ /**
57
+ * 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).
61
+ */
62
+ export function displayNameForElement(el, entry, ruleName) {
63
+ if (ruleName?.trim())
64
+ return ruleName.trim();
65
+ const explicit = el.getAttribute('data-component') || el.getAttribute('aria-label');
66
+ if (explicit?.trim())
67
+ return explicit.trim();
68
+ const labelledBy = el.getAttribute('aria-labelledby');
69
+ if (labelledBy && el.ownerDocument) {
70
+ const labelText = labelledBy
71
+ .split(/\s+/)
72
+ .map(id => el.ownerDocument.getElementById(id)?.textContent?.trim() ?? '')
73
+ .filter(Boolean)
74
+ .join(' ')
75
+ .replace(/\s+/g, ' ')
76
+ .slice(0, 40);
77
+ if (labelText)
78
+ return labelText;
79
+ }
80
+ const tag = el.tagName.toLowerCase();
81
+ const landmark = LANDMARK_LABELS[tag];
82
+ if (landmark)
83
+ return landmark;
84
+ const heading = el.querySelector('h1, h2, h3, h4, h5, h6');
85
+ const rawText = (heading
86
+ ? (heading.innerText || heading.textContent || '')
87
+ : (el.innerText || el.textContent || '')).trim().replace(/\s+/g, ' ');
88
+ if (rawText)
89
+ return rawText.slice(0, 40);
90
+ return componentType(entry);
91
+ }
92
+ const normalizeName = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
93
+ function parseRuleSelector(markdown) {
94
+ const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(markdown)?.[1];
95
+ if (!fm)
96
+ return undefined;
97
+ const m = /^selector:\s*(.+)$/m.exec(fm);
98
+ return m?.[1]?.trim().replace(/^["']|["']$/g, '') || undefined;
99
+ }
100
+ function componentIdFor(selector, pageUrl) {
101
+ try {
102
+ const u = new URL(pageUrl);
103
+ return `${selector}::${u.pathname}`;
104
+ }
105
+ catch {
106
+ return `${selector}::/`;
107
+ }
108
+ }
109
+ function elementFingerprint(win, el) {
110
+ const cs = win.getComputedStyle(el);
111
+ const parts = [];
112
+ for (const prop of WATCH_PROPS)
113
+ parts.push(cs.getPropertyValue(prop).trim());
114
+ const r = el.getBoundingClientRect();
115
+ parts.push(`${Math.round(r.width * 2) / 2}x${Math.round(r.height * 2) / 2}`);
116
+ parts.push((el.textContent ?? '').trim().replace(/\s+/g, ' ').slice(0, 120));
117
+ return parts.join('|');
118
+ }
119
+ function isLuciNode(node) {
120
+ for (let n = node; n; n = n.parentNode) {
121
+ if (n instanceof Element) {
122
+ const tag = n.tagName.toLowerCase();
123
+ if (n.hasAttribute(LUCI_UI_ATTRIBUTE) || tag.startsWith('luci-'))
124
+ return true;
125
+ if (n.tagName === 'IFRAME' && n.name === LUCI_FRAME_NAME)
126
+ return true;
127
+ }
128
+ }
129
+ return false;
130
+ }
131
+ function isLuciMutation(m) {
132
+ if (isLuciNode(m.target))
133
+ return true;
134
+ if (m.type === 'childList') {
135
+ const nodes = [...Array.from(m.addedNodes), ...Array.from(m.removedNodes)];
136
+ if (nodes.length > 0 && nodes.every(n => isLuciNode(n)))
137
+ return true;
138
+ }
139
+ return false;
140
+ }
141
+ /**
142
+ * Unambiguously match a live DOM element to a saved component rule (Approved Question 4).
143
+ * 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).
146
+ */
147
+ export function matchRuleForElement(el, entry, rules, explicitBindings) {
148
+ const componentRules = rules.filter(r => !r.file.includes('.collection.') && !r.file.includes('.system.'));
149
+ if (componentRules.length === 0)
150
+ return { rule: null, ambiguous: false };
151
+ // 1. Explicit selector binding
152
+ const boundFile = explicitBindings.get(entry.selector);
153
+ if (boundFile) {
154
+ const clean = boundFile.replace(/^\.luci\/design\//, '');
155
+ const found = componentRules.find(r => r.file === clean);
156
+ if (found)
157
+ return { rule: found, ambiguous: false };
158
+ }
159
+ // 2. Frontmatter selector match
160
+ const selectorMatches = componentRules.filter(r => {
161
+ const sel = r.selector || parseRuleSelector(r.markdown);
162
+ if (!sel)
163
+ return false;
164
+ if (sel === entry.selector)
165
+ return true;
166
+ try {
167
+ return el.matches(sel);
168
+ }
169
+ catch {
170
+ return false;
171
+ }
172
+ });
173
+ if (selectorMatches.length === 1)
174
+ return { rule: selectorMatches[0], ambiguous: false };
175
+ if (selectorMatches.length > 1)
176
+ 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') ||
181
+ el.getAttribute('aria-label') ||
182
+ '');
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)
188
+ return { rule: null, ambiguous: true };
189
+ }
190
+ return { rule: null, ambiguous: false };
191
+ }
192
+ function findBySelector(doc, selector) {
193
+ if (!selector.includes(' >> ')) {
194
+ try {
195
+ return doc.querySelector(selector);
196
+ }
197
+ catch {
198
+ return null;
199
+ }
200
+ }
201
+ const parts = selector.split(' >> ');
202
+ let cur = doc;
203
+ for (const part of parts) {
204
+ try {
205
+ const next = cur.querySelector(part);
206
+ if (!next)
207
+ return null;
208
+ cur = next.shadowRoot ?? next;
209
+ }
210
+ catch {
211
+ return null;
212
+ }
213
+ }
214
+ return cur instanceof Element ? cur : null;
215
+ }
216
+ /** Capture a live DOM element as a fresh .design.md string (used by "Update rule"). */
217
+ export async function captureElementRuleMarkdown(el, doc = el.ownerDocument) {
218
+ const live = liveSnapshot(doc);
219
+ let entry = null;
220
+ for (let n = el; n && !entry; n = n.parentElement)
221
+ entry = live.entryFor(n);
222
+ if (!entry)
223
+ return null;
224
+ const { states } = await readComponentStates(live, entry);
225
+ const res = captureComponent(live, entry, {}, { states });
226
+ return res.ok ? res.output.markdown : null;
227
+ }
228
+ function loadBaselines(win, key) {
229
+ try {
230
+ const raw = win.sessionStorage.getItem(key);
231
+ if (!raw)
232
+ return {};
233
+ const parsed = JSON.parse(raw);
234
+ return parsed && typeof parsed === 'object' ? parsed : {};
235
+ }
236
+ catch {
237
+ return {};
238
+ }
239
+ }
240
+ function saveBaselines(win, key, map) {
241
+ try {
242
+ win.sessionStorage.setItem(key, JSON.stringify(map));
243
+ }
244
+ catch {
245
+ // sessionStorage unavailable (e.g., private mode / sandbox)
246
+ }
247
+ }
248
+ function readBuiltSpec(live, entry) {
249
+ const cap = captureComponent(live, entry, {}, { states: [] });
250
+ if (!cap.ok)
251
+ return null;
252
+ const parsed = readComponentFile(cap.output.markdown);
253
+ return parsed.ok ? parsed.value : null;
254
+ }
255
+ const waitFrames = (win, n = 2) => new Promise(resolve => {
256
+ const step = (left) => (left ? win.requestAnimationFrame(() => step(left - 1)) : resolve());
257
+ step(n);
258
+ });
259
+ /**
260
+ * Start watching the page for component changes and running On spec checks (~2s target).
261
+ */
262
+ export function startSpecWatcher(options) {
263
+ const doc = options.doc ?? document;
264
+ const win = doc.defaultView ?? window;
265
+ const debounceMs = options.debounceMs ?? 250;
266
+ const frameTimeoutMs = options.frameTimeoutMs ?? 1500;
267
+ const storageKey = options.storageKey ?? SPEC_BASELINES_KEY;
268
+ const explicitBindings = new Map();
269
+ const latestById = new Map();
270
+ const selectorById = new Map();
271
+ let baselines = loadBaselines(win, `${storageKey}:${win.location.pathname}`);
272
+ let warmFrame = null;
273
+ let warmFrameUrl = '';
274
+ let warmFrameReady = false;
275
+ let warmFrameBlocked = false;
276
+ let stopped = false;
277
+ let timer = null;
278
+ let running = false;
279
+ let rerunRequested = false;
280
+ let suppressingMutations = false;
281
+ let observer = null;
282
+ /**
283
+ * Suppress MutationObserver callbacks while Luci probes element states (`readComponentStates`
284
+ * toggles inline `style`/`disabled`) or mounts its hidden width iframe, and drain any queued
285
+ * records before re-enabling so self-induced mutations never re-trigger an infinite loop.
286
+ */
287
+ async function withMutedObserver(fn) {
288
+ suppressingMutations = true;
289
+ try {
290
+ return await fn();
291
+ }
292
+ finally {
293
+ observer?.takeRecords();
294
+ suppressingMutations = false;
295
+ }
296
+ }
297
+ const destroyWarmFrame = () => {
298
+ if (warmFrame) {
299
+ warmFrame.remove();
300
+ warmFrame = null;
301
+ warmFrameUrl = '';
302
+ warmFrameReady = false;
303
+ }
304
+ };
305
+ /** Lazily create or resize one hidden same-origin iframe to avoid full page reloads per HMR. */
306
+ async function getWarmFrameDoc(width) {
307
+ if (warmFrameBlocked || stopped)
308
+ return null;
309
+ const url = win.location.href;
310
+ if (!warmFrame || warmFrameUrl !== url) {
311
+ destroyWarmFrame();
312
+ warmFrameUrl = url;
313
+ warmFrameReady = false;
314
+ const iframe = doc.createElement('iframe');
315
+ iframe.name = LUCI_FRAME_NAME;
316
+ iframe.setAttribute(LUCI_UI_ATTRIBUTE, '1');
317
+ iframe.setAttribute('aria-hidden', 'true');
318
+ iframe.tabIndex = -1;
319
+ iframe.style.cssText = `position:fixed;left:-10000px;top:0;width:${width}px;height:900px;border:0;visibility:hidden;pointer-events:none;`;
320
+ warmFrame = iframe;
321
+ const loaded = await new Promise(resolve => {
322
+ const timeout = setTimeout(() => resolve(false), frameTimeoutMs);
323
+ iframe.onload = () => { clearTimeout(timeout); resolve(true); };
324
+ iframe.onerror = () => { clearTimeout(timeout); resolve(false); };
325
+ iframe.src = url;
326
+ doc.body.appendChild(iframe);
327
+ });
328
+ if (!loaded) {
329
+ warmFrameBlocked = true;
330
+ destroyWarmFrame();
331
+ return null;
332
+ }
333
+ try {
334
+ const fdoc = iframe.contentDocument;
335
+ if (!fdoc || !fdoc.body) {
336
+ warmFrameBlocked = true;
337
+ destroyWarmFrame();
338
+ return null;
339
+ }
340
+ warmFrameReady = true;
341
+ }
342
+ catch {
343
+ warmFrameBlocked = true;
344
+ destroyWarmFrame();
345
+ return null;
346
+ }
347
+ }
348
+ if (!warmFrame || !warmFrameReady)
349
+ return null;
350
+ warmFrame.style.width = `${width}px`;
351
+ const fwin = warmFrame.contentWindow;
352
+ if (fwin)
353
+ await waitFrames(fwin, 2);
354
+ try {
355
+ return warmFrame.contentDocument;
356
+ }
357
+ catch {
358
+ warmFrameBlocked = true;
359
+ destroyWarmFrame();
360
+ return null;
361
+ }
362
+ }
363
+ async function evaluateBatch(runOpts = {}) {
364
+ if (stopped)
365
+ return [];
366
+ if (running) {
367
+ rerunRequested = true;
368
+ return [...latestById.values()];
369
+ }
370
+ running = true;
371
+ try {
372
+ const rules = await options.loadRules();
373
+ const widths = extractProjectWidths(rules);
374
+ const existing = options.existingVerdicts?.() ?? [];
375
+ for (const prev of existing) {
376
+ if (!latestById.has(prev.id)) {
377
+ latestById.set(prev.id, prev);
378
+ selectorById.set(prev.id, prev.selector);
379
+ }
380
+ }
381
+ const live = liveSnapshot(doc);
382
+ const pageUrl = win.location.href;
383
+ const pagePath = (() => { try {
384
+ return new URL(pageUrl).pathname;
385
+ }
386
+ catch {
387
+ return '/';
388
+ } })();
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];
391
+ // Discover candidate elements: explicitly bound selectors + saved rule selectors + pageComponents()
392
+ const seenEls = new Set();
393
+ const candidates = [];
394
+ const addCandidate = (el) => {
395
+ if (!el || isLuciNode(el) || seenEls.has(el))
396
+ return;
397
+ const entry = live.entryFor(el);
398
+ if (entry) {
399
+ seenEls.add(el);
400
+ candidates.push({ el, entry });
401
+ }
402
+ };
403
+ for (const sel of explicitBindings.keys()) {
404
+ addCandidate(findBySelector(doc, sel));
405
+ }
406
+ for (const rule of rules) {
407
+ if (rule.file.includes('.collection.') || rule.file.includes('.system.'))
408
+ continue;
409
+ const sel = rule.selector || parseRuleSelector(rule.markdown);
410
+ if (!sel)
411
+ continue;
412
+ if (sel.includes(' >> ')) {
413
+ addCandidate(findBySelector(doc, sel));
414
+ }
415
+ else {
416
+ try {
417
+ const matched = Array.from(doc.querySelectorAll(sel)).slice(0, 10);
418
+ for (const el of matched)
419
+ addCandidate(el);
420
+ }
421
+ catch {
422
+ // ignore invalid CSS selector in a rule file
423
+ }
424
+ }
425
+ }
426
+ for (const entry of pageComponents(live.snapshot)) {
427
+ addCandidate(live.nodes[entry.id] ?? null);
428
+ }
429
+ const nextBaselines = { ...baselines };
430
+ const dirty = [];
431
+ const matchedRuleIds = new Set();
432
+ const changedIds = new Set();
433
+ const hasPriorBaselines = Object.keys(baselines).length > 0;
434
+ for (const { el, entry } of candidates) {
435
+ const id = componentIdFor(entry.selector, pageUrl);
436
+ const fp = elementFingerprint(win, el);
437
+ const prevFp = baselines[id];
438
+ nextBaselines[id] = fp;
439
+ const prevVerdict = latestById.get(id);
440
+ const match = matchRuleForElement(el, entry, rules, explicitBindings);
441
+ const changed = prevFp !== undefined && prevFp !== fp;
442
+ const isFirstRun = !hasPriorBaselines || prevVerdict === undefined;
443
+ if (match.rule !== null)
444
+ matchedRuleIds.add(id);
445
+ if (changed)
446
+ changedIds.add(id);
447
+ // Only evaluate elements that match a saved rule, genuinely changed on the page, or hit an ambiguous rule collision.
448
+ // 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)) ||
450
+ changed ||
451
+ match.ambiguous;
452
+ if (shouldCheck) {
453
+ dirty.push({ el, entry, id, match });
454
+ }
455
+ }
456
+ // Prune stale entries on the current page whose rule was deleted/no longer matches,
457
+ // or untouched "no-rule" entries from earlier sessions.
458
+ let pruned = false;
459
+ for (const [id, prev] of Array.from(latestById.entries())) {
460
+ if (!id.endsWith(`::${pagePath}`))
461
+ continue;
462
+ const staleRule = Boolean(prev.ruleFile) && !matchedRuleIds.has(id);
463
+ const staleNoRule = prev.state === 'no-rule' && !changedIds.has(id) && (Boolean(runOpts.forceAll) || !hasPriorBaselines);
464
+ if (staleRule || staleNoRule) {
465
+ latestById.delete(id);
466
+ selectorById.delete(id);
467
+ pruned = true;
468
+ }
469
+ }
470
+ baselines = nextBaselines;
471
+ saveBaselines(win, `${storageKey}:${win.location.pathname}`, baselines);
472
+ if (dirty.length === 0) {
473
+ if (pruned)
474
+ options.onVerdicts([...latestById.values()], widths, { replace: true });
475
+ return [...latestById.values()];
476
+ }
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;
482
+ const updated = [];
483
+ 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`;
491
+ }
492
+ }
493
+ const checkedAt = new Date().toISOString();
494
+ for (const item of dirty) {
495
+ const { el, entry, id, match } = item;
496
+ const prev = latestById.get(id);
497
+ const displayName = displayNameForElement(el, entry, match.rule?.name);
498
+ if (!match.rule) {
499
+ const verdict = {
500
+ id,
501
+ name: displayName,
502
+ selector: entry.selector,
503
+ page: pageUrl,
504
+ ruleFile: null,
505
+ state: 'no-rule',
506
+ checkedAt,
507
+ widthsChecked: [liveWidth],
508
+ matches: 0,
509
+ differences: [],
510
+ fixRounds: 0,
511
+ needsHuman: false
512
+ };
513
+ latestById.set(id, verdict);
514
+ selectorById.set(id, entry.selector);
515
+ updated.push(verdict);
516
+ continue;
517
+ }
518
+ const ruleFile = `.luci/design/${match.rule.file}`;
519
+ const choice = {
520
+ label: `${match.rule.name} (${match.rule.type})`,
521
+ file: ruleFile,
522
+ markdown: match.rule.markdown
523
+ };
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
556
+ });
557
+ let combinedDiffs = [...primary.differences];
558
+ let totalMatches = primary.matches;
559
+ let finalState = primary.state;
560
+ const widthsChecked = [liveWidth];
561
+ let note;
562
+ 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);
567
+ }
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);
592
+ }
593
+ }
594
+ if (combinedDiffs.length > 0 && finalState === 'on-spec') {
595
+ finalState = prev?.excuse ? 'excused' : 'drift';
596
+ }
597
+ }
598
+ }
599
+ }
600
+ else if (hasMq && frameBlockedNote) {
601
+ note = frameBlockedNote;
602
+ }
603
+ widthsChecked.sort((a, b) => a - b);
604
+ const verdict = {
605
+ id,
606
+ name: displayName,
607
+ selector: entry.selector,
608
+ page: pageUrl,
609
+ ruleFile: finalState === 'no-rule' ? null : ruleFile,
610
+ state: finalState,
611
+ checkedAt,
612
+ widthsChecked,
613
+ matches: totalMatches,
614
+ differences: combinedDiffs,
615
+ fixRounds: finalState === 'on-spec' ? 0 : (prev?.fixRounds ?? 0),
616
+ needsHuman: finalState === 'drift' ? Boolean(prev?.needsHuman) : false,
617
+ lastBlockedAt: finalState === 'drift' ? (prev?.lastBlockedAt ?? null) : null,
618
+ ...(note ? { note } : {}),
619
+ ...(finalState === 'excused' && prev?.excuse ? { excuse: prev.excuse } : {})
620
+ };
621
+ latestById.set(id, verdict);
622
+ selectorById.set(id, entry.selector);
623
+ updated.push(verdict);
624
+ }
625
+ });
626
+ if (updated.length > 0 || pruned) {
627
+ options.onVerdicts([...latestById.values()], widths, pruned ? { replace: true } : undefined);
628
+ }
629
+ return [...latestById.values()];
630
+ }
631
+ finally {
632
+ running = false;
633
+ if (rerunRequested && !stopped) {
634
+ rerunRequested = false;
635
+ scheduleCheck();
636
+ }
637
+ }
638
+ }
639
+ function scheduleCheck() {
640
+ if (stopped)
641
+ return;
642
+ if (timer)
643
+ clearTimeout(timer);
644
+ timer = setTimeout(() => {
645
+ timer = null;
646
+ void evaluateBatch();
647
+ }, debounceMs);
648
+ }
649
+ observer = new MutationObserver(mutations => {
650
+ if (stopped || suppressingMutations)
651
+ return;
652
+ const meaningful = mutations.some(m => !isLuciMutation(m));
653
+ if (meaningful)
654
+ scheduleCheck();
655
+ });
656
+ if (doc.body) {
657
+ observer.observe(doc.body, {
658
+ subtree: true,
659
+ childList: true,
660
+ attributes: true,
661
+ attributeFilter: ['class', 'style', 'disabled', 'aria-disabled', 'data-state'],
662
+ characterData: true
663
+ });
664
+ }
665
+ if (doc.head) {
666
+ observer.observe(doc.head, { subtree: true, childList: true, characterData: true, attributes: true });
667
+ }
668
+ const onSheetLoad = (e) => {
669
+ const t = e.target;
670
+ if (t && t.tagName === 'LINK')
671
+ scheduleCheck();
672
+ };
673
+ doc.addEventListener('load', onSheetLoad, true);
674
+ return {
675
+ run: (runOpts) => evaluateBatch(runOpts),
676
+ bindRule(selector, ruleFile) {
677
+ explicitBindings.set(selector, ruleFile);
678
+ },
679
+ verdictForElement(el) {
680
+ for (const [id, sel] of selectorById.entries()) {
681
+ try {
682
+ if (el.matches(sel) || el.closest(sel) === el) {
683
+ return latestById.get(id) ?? null;
684
+ }
685
+ }
686
+ catch {
687
+ // ignore invalid selectors
688
+ }
689
+ }
690
+ return null;
691
+ },
692
+ stop() {
693
+ stopped = true;
694
+ if (timer)
695
+ clearTimeout(timer);
696
+ observer?.disconnect();
697
+ doc.removeEventListener('load', onSheetLoad, true);
698
+ destroyWarmFrame();
699
+ }
700
+ };
701
+ }
702
+ //# sourceMappingURL=specWatcher.js.map