@sloppy-ai/verify 0.0.0-stage → 1.1.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.
@@ -0,0 +1,2120 @@
1
+ // The per-shot checks film.mjs runs inside the page: clips, padding, framing,
2
+ // touching, satellites and the rest. One named function per detector, each
3
+ // returning its findings, all built on one color parser, one surface test and
4
+ // one ancestor-visibility walk. film.mjs injects them with filmChecksSource()
5
+ // (the verification.mjs pattern: Function.toString into an init script), so
6
+ // every function here is self-contained: no module-scope state, only the
7
+ // other functions in this file and the DOM.
8
+ //
9
+ // Order matters: a stage's findings are keyed by first appearance, so
10
+ // checkStage calls the detectors in the order film.mjs always has.
11
+
12
+ // ---- Primitives -----------------------------------------------------------
13
+
14
+ // The one color parser: a computed color to its channels and alpha, or null
15
+ // when it is not one. Chrome serializes color-mix() results as
16
+ // color(srgb r g b / a), so that form is read as well as rgb()/rgba().
17
+ export function rgbaOf(color) {
18
+ const m = color && color.match(/rgba?\(([^)]+)\)|color\(srgb\s+([^)]+)\)/)
19
+ if (!m) return null
20
+ const p = (m[1] ?? m[2]).split(/[ ,/]+/).filter(Boolean)
21
+ return { r: Number(p[0]), g: Number(p[1]), b: Number(p[2]), a: p.length > 3 ? parseFloat(p[3]) : 1 }
22
+ }
23
+
24
+ // Alpha of a color, or the fallback when it does not parse. Call sites state
25
+ // their own fallback: most treat an unparsed background as painting nothing
26
+ // (0); the icon check treats an unparsed stroke as opaque (1), so an unknown
27
+ // paint is not reported as translucent.
28
+ export function alphaOf(color, fallback) {
29
+ const c = rgbaOf(color)
30
+ return c ? c.a : fallback
31
+ }
32
+
33
+ // The one surface test: a background with alpha over minAlpha, a shadow, and
34
+ // when asked an image or a top border (styled: only a border with a style).
35
+ // The thresholds below (0.02, 0.03, 0.05) are each check's own, kept as they
36
+ // were. A computed box-shadow is 'none' or a value, so the shadow test reads
37
+ // the same at every site.
38
+ export function paintsSurface(cs, { minAlpha = 0.05, image = false, border = false, styled = false, shadow = true } = {}) {
39
+ if (alphaOf(cs.backgroundColor, 0) > minAlpha) return true
40
+ if (image && cs.backgroundImage !== 'none') return true
41
+ if (border && parseFloat(cs.borderTopWidth) > 0 && (!styled || cs.borderTopStyle !== 'none')) return true
42
+ return shadow && !!cs.boxShadow && cs.boxShadow !== 'none'
43
+ }
44
+ // A fill or shadow (the near-tangent, pill and padding checks)
45
+ function surface(cs) { return paintsSurface(cs) }
46
+ // A fill, image, border or shadow (the card and container checks)
47
+ function visible(n) { return paintsSurface(getComputedStyle(n), { minAlpha: 0.02, image: true, border: true }) }
48
+ // A fill, shadow or top border (the framing and touching checks)
49
+ function hasSurface(cs) { return paintsSurface(cs, { border: true }) }
50
+
51
+ // The one ancestor walk: nothing hidden from the node up to and including
52
+ // the stage, and at least half opaque through every layer. With clipped,
53
+ // also not clipped away by an overflow-hidden ancestor (a counter's strip of
54
+ // figures outside its one-line window, a track scrolled past its mask).
55
+ export function visibleThrough(n, root, clipped = false) {
56
+ let f = 1
57
+ const r = clipped ? n.getBoundingClientRect() : null
58
+ for (let a = n; a && a !== root.parentElement; a = a.parentElement) {
59
+ const c = getComputedStyle(a)
60
+ if (c.display === 'none' || c.visibility === 'hidden') return false
61
+ f *= Number(c.opacity)
62
+ if (clipped && a !== n && /hidden|clip/.test(c.overflowX + c.overflowY)) {
63
+ const b = a.getBoundingClientRect()
64
+ if (r.bottom <= b.top + 0.5 || r.top >= b.bottom - 0.5 || r.right <= b.left + 0.5 || r.left >= b.right - 0.5) return false
65
+ }
66
+ }
67
+ return f >= 0.5
68
+ }
69
+ function painted(n, root) { return visibleThrough(n, root) }
70
+ function shown(n, root) { return visibleThrough(n, root, true) }
71
+
72
+ // Opacity through every layer from the node up to (not including) stop
73
+ function fadeThrough(n, stop) {
74
+ let o = 1
75
+ for (let a = n; a && a !== stop; a = a.parentElement) o *= Number(getComputedStyle(a).opacity)
76
+ return o
77
+ }
78
+
79
+ // tag.first-class "first words"
80
+ function labelOf(n) {
81
+ const cls = typeof n.className === 'string' ? n.className.trim().split(/\s+/)[0] : ''
82
+ const text = (n.textContent || '').trim().slice(0, 24)
83
+ return `${n.tagName.toLowerCase()}${cls ? '.' + cls : ''}${text ? ` "${text}"` : ''}`
84
+ }
85
+ // tag.first-class, for svg too
86
+ function tagOf(n) {
87
+ const cls = typeof n.className === 'string' ? n.className.trim().split(/\s+/)[0] : (n.className?.baseVal || '').split(/\s+/)[0]
88
+ return `${n.tagName.toLowerCase()}${cls ? '.' + cls : ''}`
89
+ }
90
+ function px(v) { return Math.round(v) }
91
+ // 1-4px apart, in stage px
92
+ function nearTangent(d) { return d > 0.75 && d <= 3 }
93
+
94
+ // ---- Stage context --------------------------------------------------------
95
+
96
+ // What every detector reads: the stage, its box, scale and fidelity, and the
97
+ // camera's state when it has one
98
+ function stageContext(root) {
99
+ const S = root.getBoundingClientRect()
100
+ const cam = root.querySelector('.ss-camera')
101
+ const zoomView = cam?.parentElement?.hasAttribute('data-zoomed') ? cam.parentElement : null
102
+ // The focus on screen, mapped through the zoom
103
+ const focusRect = (() => {
104
+ if (!zoomView?.dataset.focus) return null
105
+ const [fx, fy, fw, fh] = zoomView.dataset.focus.split(',').map(Number)
106
+ const c = cam.getBoundingClientRect()
107
+ const k = c.width / cam.offsetWidth
108
+ return { left: c.left + fx * k, top: c.top + fy * k, right: c.left + (fx + fw) * k, bottom: c.top + (fy + fh) * k, k }
109
+ })()
110
+ const scale = S.width / root.offsetWidth || 1
111
+ const specimen = !!(root.closest('[data-specimen]') || root.querySelector('[data-specimen]'))
112
+ const fidelity = (root.closest('[data-fidelity]') || root.querySelector('[data-fidelity]'))?.getAttribute('data-fidelity') || 'standard'
113
+ const gridish = '.ss-cursor, .ss-keys, .ss-kb, svg, .ss-chart, .ss-code, .ss-keyboard, [role="grid"], .ss-sheet, .ss-calendar, [data-grid]'
114
+ return { root, S, cam, zoomView, focusRect, scale, specimen, fidelity, gridish }
115
+ }
116
+
117
+ // A Camera part way through a move: everything in it scales and slides, so
118
+ // no frame of the move is judged (the motion checks watch it). A settled
119
+ // zoom is judged against the camera's own crop.
120
+ function cameraMoving(cam) {
121
+ return !!cam && document.getAnimations().some((x) => x.playState === 'running' && (x.effect?.target === cam || x.effect?.target === cam.parentElement))
122
+ }
123
+
124
+ // ---- Clips and padding ----------------------------------------------------
125
+
126
+ // Marks sliced by an overflow container whose cutting edge is inside the
127
+ // stage. Leaf elements only (text spans, dots, avatars, icons).
128
+ function detectClipped({ root, S }) {
129
+ const out = []
130
+ for (const n of root.querySelectorAll('*')) {
131
+ if (n.closest('.ss-roll, .ss-count, .ss-cursor, .ss-keys') || (n.closest('svg') && n.tagName.toLowerCase() !== 'svg')) continue
132
+ if (n.children.length && n.tagName.toLowerCase() !== 'svg') continue
133
+ const r = n.getBoundingClientRect()
134
+ if (r.width < 2 || r.height < 2) continue
135
+ const cs = getComputedStyle(n)
136
+ if (cs.visibility === 'hidden' || Number(cs.opacity) === 0) continue
137
+ for (let a = n.parentElement; a && root.contains(a); a = a.parentElement) {
138
+ const o = getComputedStyle(a)
139
+ if (Number(o.opacity) === 0 || a.hasAttribute('data-crop')) break
140
+ const c = a.getBoundingClientRect()
141
+ const visW = Math.min(r.right, c.right) - Math.max(r.left, c.left)
142
+ const visH = Math.min(r.bottom, c.bottom) - Math.max(r.top, c.top)
143
+ if (visW <= 0 || visH <= 0) break
144
+ const cuts = []
145
+ if (o.overflowX !== 'visible') {
146
+ if (r.left < c.left - 0.5 && c.left > S.left + 2) cuts.push(`left by ${Math.round(c.left - r.left)}px`)
147
+ if (r.right > c.right + 0.5 && c.right < S.right - 2) cuts.push(`right by ${Math.round(r.right - c.right)}px`)
148
+ }
149
+ if (o.overflowY !== 'visible') {
150
+ if (r.top < c.top - 0.5 && c.top > S.top + 2) cuts.push(`top by ${Math.round(c.top - r.top)}px`)
151
+ if (r.bottom > c.bottom + 0.5 && c.bottom < S.bottom - 2) cuts.push(`bottom by ${Math.round(r.bottom - c.bottom)}px`)
152
+ }
153
+ if (cuts.length) {
154
+ out.push(`${labelOf(n)} clipped ${cuts.join(', ')} by ${labelOf(a).split(' "')[0]}`)
155
+ break
156
+ }
157
+ if (a === root) break
158
+ }
159
+ }
160
+ return out
161
+ }
162
+
163
+ // Content in a surface's padding: a leaf that runs into (or past) the
164
+ // padding of the card, tile or panel holding it, overflow visible or
165
+ // not. A fixed-width bar in a narrow card is the usual cause. Elements
166
+ // pulled out on purpose with a negative margin (full-bleed rows) pass.
167
+ function detectPaddingRunIns({ root }) {
168
+ const out = []
169
+ for (const n of root.querySelectorAll('*')) {
170
+ if (n.closest('.ss-roll, .ss-count, .ss-cursor, .ss-keys, svg') && n.tagName.toLowerCase() !== 'svg') continue
171
+ if (n.children.length && n.tagName.toLowerCase() !== 'svg') continue
172
+ const r = n.getBoundingClientRect()
173
+ if (r.width < 2 || r.height < 2) continue
174
+ const ncs = getComputedStyle(n)
175
+ if (ncs.visibility === 'hidden' || Number(ncs.opacity) === 0 || ncs.position === 'absolute' || ncs.position === 'fixed') continue
176
+ // Faded with its container (a card not shown yet, a row still opening)
177
+ if (fadeThrough(n, root) < 0.5) continue
178
+ // Spinning or animating leaves: their box swells as they turn (the motion checks judge them)
179
+ if (ncs.animationName !== 'none' || (ncs.transform !== 'none' && !/^matrix\(1, 0, 0, 1,/.test(ncs.transform))) continue
180
+ let floated = false
181
+ for (let a = n.parentElement; a && root.contains(a) && a !== root; a = a.parentElement) {
182
+ const o = getComputedStyle(a)
183
+ // Past an out-of-flow layer (a popover hanging from a card) the
184
+ // containers above don't own its padding: it is laid over them
185
+ if (floated) break
186
+ floated = o.position === 'absolute' || o.position === 'fixed'
187
+ // Pulled out on purpose, or zoomed (its rects are in another scale)
188
+ if (parseFloat(o.marginLeft) < 0 || parseFloat(o.marginRight) < 0 || parseFloat(o.marginTop) < 0 || (o.zoom && o.zoom !== '1' && o.zoom !== 'normal')) break
189
+ const c = a.getBoundingClientRect()
190
+ // Already hidden by something that clips it (rows scrolled away)
191
+ if (o.overflowX !== 'visible' || o.overflowY !== 'visible') {
192
+ if (r.bottom <= c.top + 1 || r.top >= c.bottom - 1 || r.right <= c.left + 1 || r.left >= c.right - 1) break
193
+ }
194
+ // Padding at the scale the surface is drawn (a phone screen is scaled down)
195
+ const k = a.offsetWidth ? c.width / a.offsetWidth : 1
196
+ const pad = ['Top', 'Right', 'Bottom', 'Left'].map((p) => parseFloat(o['padding' + p]) * k)
197
+ if (!surface(o) || Math.max(...pad) < 4 * k) continue
198
+ // An icon tile or chip centers its glyph by design; its padding is not a gutter
199
+ if (a.offsetWidth < 48 && a.offsetHeight < 48) break
200
+ const sides = []
201
+ if (pad[0] >= 4 * k && r.top < c.top + pad[0] - 2) sides.push('top')
202
+ if (pad[1] >= 4 * k && r.right > c.right - pad[1] + 2) sides.push('right')
203
+ if (pad[2] >= 4 * k && r.bottom > c.bottom - pad[2] + 2) sides.push('bottom')
204
+ if (pad[3] >= 4 * k && r.left < c.left + pad[3] - 2) sides.push('left')
205
+ if (sides.length) out.push(`uneven: ${labelOf(n).split(' "')[0]} runs into the ${sides.join(' and ')} padding of ${labelOf(a).split(' "')[0]}`)
206
+ break
207
+ }
208
+ }
209
+ return out
210
+ }
211
+
212
+ // Covered copy: on a press, the cursor's glyph sits over the label it
213
+ // clicks so the words can't be read. Aim inside the target but off its
214
+ // text ({ at, x: 0.85, y: 0.6 }). Judged on the drawn glyph, not its box.
215
+ function detectCoveredCopy({ root }) {
216
+ const out = []
217
+ const cur = root.querySelector('.ss-cursor[data-pressed]')
218
+ const hit = root.querySelector('[data-pressed]:not(.ss-cursor)')
219
+ if (!cur || !hit) return out
220
+ let g = null
221
+ for (const c of cur.querySelectorAll('svg')) {
222
+ const cs = getComputedStyle(c)
223
+ if (cs.display === 'none' || Number(cs.opacity) === 0) continue
224
+ const b = c.getBoundingClientRect()
225
+ if (b.width < 2) continue
226
+ // The glyph's ink fills roughly the middle of its box
227
+ const ix = b.width * 0.2
228
+ const iy = b.height * 0.15
229
+ g = { l: b.left + ix, r: b.right - ix, t: b.top + iy, b: b.bottom - iy }
230
+ break
231
+ }
232
+ const walker = document.createTreeWalker(hit, NodeFilter.SHOW_TEXT)
233
+ for (let t = g && walker.nextNode(); t; t = walker.nextNode()) {
234
+ if (!t.textContent.trim() || Number(getComputedStyle(t.parentElement).opacity) === 0) continue
235
+ const rg = document.createRange()
236
+ rg.selectNodeContents(t)
237
+ const b = rg.getBoundingClientRect()
238
+ if (b.width < 1) continue
239
+ const w = Math.max(0, Math.min(b.right, g.r) - Math.max(b.left, g.l))
240
+ const h = Math.max(0, Math.min(b.bottom, g.b) - Math.max(b.top, g.t))
241
+ if (w * h > b.width * b.height * 0.12) {
242
+ out.push(`covers: the cursor sits on "${t.textContent.trim().slice(0, 24)}" as it presses; aim off the label`)
243
+ break
244
+ }
245
+ }
246
+ return out
247
+ }
248
+
249
+ // Lopsided pills: a pill or button whose content sits off-center (a
250
+ // padding sized for an icon that isn't there). Judged on the content's
251
+ // box, so an x with its own hover circle counts as its circle.
252
+ function detectLopsidedPills({ root, scale }) {
253
+ const out = []
254
+ const pills = [...root.querySelectorAll('*')].filter((n) => {
255
+ if (n.closest('.ss-cursor, .ss-keys')) return false
256
+ const cs = getComputedStyle(n)
257
+ if (!surface(cs) || cs.visibility === 'hidden' || Number(cs.opacity) === 0) return false
258
+ const r = n.getBoundingClientRect()
259
+ // Its own scale (a notification inside a scaled phone screen)
260
+ const k = n.offsetWidth ? r.width / n.offsetWidth : scale
261
+ // A pill, or any rounded control (a chip, a button) whose content
262
+ // should sit centered in it
263
+ const control = n.matches('button, [role=button], [data-target]') || /chip|btn|button|tag|pill|badge/i.test(typeof n.className === 'string' ? n.className : '')
264
+ const round = parseFloat(cs.borderTopLeftRadius) * k >= r.height / 2 - 1 || (control && parseFloat(cs.borderTopLeftRadius) >= 4)
265
+ return r.height >= 14 * k && r.height <= 44 * k && r.width > r.height && round && n.childNodes.length > 0
266
+ })
267
+ // A text field reads from its left on purpose (a search box, a composer,
268
+ // a comment field): only pills that center their content are judged
269
+ const field = (p) => p.matches('input, textarea, [contenteditable], [role=textbox], [role=searchbox]') || !!p.querySelector('input, textarea, [contenteditable], .ss-field__placeholder, .ss-field__caret, .ss-field__chars') || /field|input|search|compos|reply|comment/i.test(p.className && typeof p.className === 'string' ? p.className : '')
270
+ // A menu row or list option reads from its left too, its fill spanning the row
271
+ const row = (p) => p.matches('[role=menuitem], [role=option], [role=menuitemradio], [role=menuitemcheckbox], .ss-menu__item') || !!p.parentElement?.closest('[role=menu], [role=listbox]')
272
+ for (const p of pills) {
273
+ if (field(p) || row(p)) continue
274
+ const r = p.getBoundingClientRect()
275
+ let l = Infinity
276
+ let rt = -Infinity
277
+ // Bare text counts as content too (a badge's label)
278
+ // Faded out anywhere up to the pill (a States option not showing) isn't content
279
+ const hid = (e) => { for (let a = e; a && a !== p; a = a.parentElement) if (Number(getComputedStyle(a).opacity) < 0.05) return true; return false }
280
+ const walker = document.createTreeWalker(p, NodeFilter.SHOW_TEXT)
281
+ for (let t = walker.nextNode(); t; t = walker.nextNode()) {
282
+ if (!t.textContent.trim() || hid(t.parentElement)) continue
283
+ const rg = document.createRange()
284
+ rg.selectNodeContents(t)
285
+ const b = rg.getBoundingClientRect()
286
+ if (b.width < 1) continue
287
+ l = Math.min(l, b.left)
288
+ rt = Math.max(rt, b.right)
289
+ }
290
+ for (const c of p.querySelectorAll('*')) {
291
+ if (c.children.length && c.tagName.toLowerCase() !== 'svg') continue
292
+ if (c.closest('svg') && c.tagName.toLowerCase() !== 'svg') continue
293
+ const b = c.getBoundingClientRect()
294
+ const ccs = getComputedStyle(c)
295
+ // A knob or thumb is placed on purpose (a switch, a slider)
296
+ if (b.width < 1 || Number(ccs.opacity) === 0 || ccs.position === 'absolute' || hid(c)) continue
297
+ l = Math.min(l, b.left)
298
+ rt = Math.max(rt, b.right)
299
+ }
300
+ if (!isFinite(l)) continue
301
+ const off = Math.abs(l - r.left - (r.right - rt)) / scale
302
+ if (off > 3) out.push(`lopsided: ${labelOf(p).split(' "')[0]}${(p.textContent || '').trim() ? ` "${p.textContent.trim().slice(0, 20)}"` : ''} has ${Math.round((l - r.left) / scale)}px on the left and ${Math.round((r.right - rt) / scale)}px on the right${parseFloat(getComputedStyle(p).flexGrow) > 0 ? '; it is stretched by flex-grow to fill its row, so let it hug its content (flex: none) and fix any overflow by fitting the content, not widening the container' : ''}`)
303
+ }
304
+ return out
305
+ }
306
+
307
+ // ---- Near-tangents --------------------------------------------------------
308
+
309
+ // The raised surfaces the near-tangent checks compare: each with the box
310
+ // that is visible of it, nested twins (a phone's band and glass) dropped
311
+ function collectSurfaces({ root, scale }) {
312
+ const surfs = [...root.querySelectorAll('*')].filter((n) => {
313
+ if (n.closest('.ss-cursor, .ss-keys, .ss-kb, svg')) return false
314
+ const cs = getComputedStyle(n)
315
+ // Faded out through a parent counts as faded: a parked popup isn't a surface anyone sees
316
+ if (!surface(cs) || cs.visibility === 'hidden' || fadeThrough(n, root.parentElement) < 0.5 || cs.position === 'fixed') return false
317
+ // Tilted (a lifted card): its box is never 'almost aligned' with anything
318
+ if (cs.transform !== 'none' && !/^matrix\(1, 0, 0, 1,/.test(cs.transform)) return false
319
+ const r = n.getBoundingClientRect()
320
+ return r.width >= 40 * scale && r.height >= 24 * scale
321
+ })
322
+ .map((n) => {
323
+ // What is visible: the box cut by every clipping ancestor (a panel running off its card)
324
+ const b = n.getBoundingClientRect()
325
+ let r = { left: b.left, right: b.right, top: b.top, bottom: b.bottom }
326
+ for (let a = n.parentElement; a && root.contains(a); a = a.parentElement) {
327
+ const o = getComputedStyle(a)
328
+ if (o.overflowX === 'visible' && o.overflowY === 'visible') continue
329
+ const c = a.getBoundingClientRect()
330
+ r = { left: Math.max(r.left, c.left), right: Math.min(r.right, c.right), top: Math.max(r.top, c.top), bottom: Math.min(r.bottom, c.bottom) }
331
+ }
332
+ return { n, r }
333
+ })
334
+ .filter((s) => s.r.right - s.r.left > 8 && s.r.bottom - s.r.top > 8)
335
+ // One object, one report: drop a surface nested in another of nearly the same box (a phone's band and glass)
336
+ const same = (a, b) => Math.abs(a.left - b.left) < 8 * scale && Math.abs(a.right - b.right) < 8 * scale && Math.abs(a.top - b.top) < 8 * scale && Math.abs(a.bottom - b.bottom) < 8 * scale
337
+ return surfs.filter((s) => !surfs.some((o) => o !== s && o.n.contains(s.n) && same(o.r, s.r)))
338
+ }
339
+
340
+ // Near-tangents: a surface edge 1-4px from the stage's reads as an
341
+ // accident: align them, or part them clearly.
342
+ function detectEdgeTangents({ S, scale }, surfs) {
343
+ const out = []
344
+ for (const { n, r } of surfs) {
345
+ const e = [['left', r.left - S.left], ['right', S.right - r.right], ['top', r.top - S.top], ['bottom', S.bottom - r.bottom]].filter(([, d]) => nearTangent(d / scale))
346
+ if (e.length) out.push(`near-tangent: ${labelOf(n).split(' "')[0]} sits ${Math.round(e[0][1] / scale)}px from the stage's ${e[0][0]} edge`)
347
+ }
348
+ return out
349
+ }
350
+
351
+ // A crop nobody made: something runs past the stage but nothing up to the
352
+ // stage clips it, so it ends wherever the host page happens to cut it,
353
+ // often a few pixels short of a card's edge with its corners showing
354
+ function detectUnclipped({ root, S, scale }, surfs) {
355
+ const out = []
356
+ const stageClips = (() => { const o = getComputedStyle(root); return o.overflowX !== 'visible' || o.overflowY !== 'visible' })()
357
+ if (stageClips) return out
358
+ for (const { n, r } of surfs) {
359
+ const past = [['right', r.right - S.right], ['bottom', r.bottom - S.bottom], ['left', S.left - r.left], ['top', S.top - r.top]].filter(([, d]) => d / scale > 4)
360
+ if (past.length) {
361
+ out.push(`unclipped: ${labelOf(n).split(' "')[0]} runs ${Math.round(past[0][1] / scale)}px past the stage's ${past[0][0]} edge and nothing clips it; give the stage overflow: hidden so the crop is yours`)
362
+ break
363
+ }
364
+ }
365
+ return out
366
+ }
367
+
368
+ // Placeholder lines stacked tighter than text lines would be: a bar
369
+ // stands in for a line of text, so a pair 1-3px apart reads as one smudge
370
+ function detectTightBars({ root, scale }) {
371
+ const out = []
372
+ const bars = [...root.querySelectorAll('.ss-bar')].filter((e) => {
373
+ const r = e.getBoundingClientRect()
374
+ for (let a = e; a && a !== root; a = a.parentElement) if (Number(getComputedStyle(a).opacity) < 0.1) return false
375
+ return r.height / scale <= 9 && r.width / scale > 20
376
+ })
377
+ outer: for (const a of bars)
378
+ for (const c of bars) {
379
+ if (a === c) continue
380
+ const A = a.getBoundingClientRect(), C = c.getBoundingClientRect()
381
+ const k = a.offsetHeight ? A.height / a.offsetHeight : scale
382
+ const gap = (C.top - A.bottom) / k
383
+ const h = Math.min(A.height, C.height) / k
384
+ if (gap >= 0 && gap < h * 0.8 && Math.min(A.right, C.right) - Math.max(A.left, C.left) > 10 && Math.abs(A.left - C.left) < 3) {
385
+ out.push(`tight lines: placeholder bars in ${labelOf(a.parentElement).split(' "')[0]} are ${gap.toFixed(1)}px apart; bars stand in for lines of text, so keep the lines' pitch (about the bar's height plus 6-8px)`)
386
+ break outer
387
+ }
388
+ }
389
+ return out
390
+ }
391
+
392
+ // Two corners on one edge: a rounded clip inside another clip of nearly the
393
+ // same box with a different radius cuts a second curve into what runs off
394
+ function detectDoubleCorner({ root }) {
395
+ const out = []
396
+ const clips = []
397
+ for (let a = root; a && clips.length < 6; a = a.parentElement) {
398
+ const o = getComputedStyle(a)
399
+ if (o.overflowX !== 'visible' || o.overflowY !== 'visible') clips.push({ a, r: a.getBoundingClientRect(), rad: parseFloat(o.borderTopLeftRadius) || parseFloat(o.borderBottomRightRadius) || 0 })
400
+ }
401
+ for (let i = 0; i + 1 < clips.length; i++) {
402
+ const A = clips[i], B = clips[i + 1]
403
+ const flush = ['left', 'right', 'top', 'bottom'].filter((k) => Math.abs(A.r[k] - B.r[k]) <= 2).length
404
+ if (flush >= 2 && A.rad > 0 && Math.abs(A.rad - B.rad) > 1) {
405
+ out.push(`double corner: ${labelOf(A.a).split(' "')[0]} rounds ${Math.round(A.rad)}px inside a ${Math.round(B.rad)}px clip that shares its edges; give one of them the corner`)
406
+ break
407
+ }
408
+ }
409
+ return out
410
+ }
411
+
412
+ // Near-tangents: two surfaces whose parallel edges sit 1-4px apart
413
+ function detectPairTangents({ root, scale }, surfs) {
414
+ const out = []
415
+ const seen = new Set()
416
+ for (let i = 0; i < surfs.length; i++)
417
+ for (let j = i + 1; j < surfs.length; j++) {
418
+ const A = surfs[i], B = surfs[j]
419
+ if (A.n.contains(B.n) || B.n.contains(A.n)) continue
420
+ // Inside a floating layer laid over the other (a popover's field over
421
+ // a table): different layers, so only the layer's own edge can graze it,
422
+ // and that pair is checked on its own
423
+ const over = (x, y) => {
424
+ for (let p = x.parentElement; p && p !== root; p = p.parentElement) {
425
+ if (p.contains(y)) return false
426
+ if (!/absolute|fixed/.test(getComputedStyle(p).position)) continue
427
+ const P = p.getBoundingClientRect(), Y = y.getBoundingClientRect()
428
+ if (P.left < Y.right && P.right > Y.left && P.top < Y.bottom && P.bottom > Y.top) return true
429
+ }
430
+ return false
431
+ }
432
+ if (over(A.n, B.n) || over(B.n, A.n)) continue
433
+ // Items of one list keep their own rhythm
434
+ // (messages of one thread are one list, though each sits in its own row)
435
+ const thread = A.n.closest('.ss-thread')
436
+ const sibs = A.n.parentElement === B.n.parentElement || (!!thread && thread === B.n.closest('.ss-thread'))
437
+ const a = A.r, b = B.r
438
+ const ov = (p, q, P, Q) => Math.min(q, Q) - Math.max(p, P) > 8 * scale
439
+ const pairs = []
440
+ if (ov(a.top, a.bottom, b.top, b.bottom)) pairs.push(['left', a.left - b.left], ['right', a.right - b.right], ['side', b.left - a.right], ['side', a.left - b.right])
441
+ if (ov(a.left, a.right, b.left, b.right)) pairs.push(['top', a.top - b.top], ['bottom', a.bottom - b.bottom], ['gap', b.top - a.bottom], ['gap', a.top - b.bottom])
442
+ const hit = pairs.find(([k, d]) => nearTangent(Math.abs(d) / scale) && !(sibs && (k === 'gap' || k === 'side')))
443
+ if (!hit) continue
444
+ const key = `${labelOf(A.n)}|${labelOf(B.n)}`
445
+ if (seen.has(key)) continue
446
+ seen.add(key)
447
+ const what = hit[0] === 'side' || hit[0] === 'gap' ? 'are only' : `${hit[0]} edges are`
448
+ out.push(`near-tangent: ${labelOf(A.n).split(' "')[0]} and ${labelOf(B.n).split(' "')[0]} ${what} ${Math.round(Math.abs(hit[1]) / scale)}px apart`)
449
+ }
450
+ return out
451
+ }
452
+
453
+ // ---- Icons, lists and rows ------------------------------------------------
454
+
455
+ // Translucent icons: strokes that overlap or meet paint darker (an
456
+ // onion-skin look). Icons must be one opaque color.
457
+ function detectTranslucentIcons({ root, S }) {
458
+ const out = []
459
+ for (const svg of root.querySelectorAll('svg')) {
460
+ if (svg.closest('.ss-connector, .ss-spinner, .ss-check, .ss-cursor, .ss-keys, .ss-phone__glyphs')) continue
461
+ const r = svg.getBoundingClientRect()
462
+ // Visible and icon-sized: a drawing (an illustration, a faded-out
463
+ // layer) blends its own strokes on purpose
464
+ const k = S.width / root.offsetWidth || 1
465
+ if (r.width < 6 * k || r.width > 40 * k || r.height > 40 * k || r.width / r.height > 2 || r.height / r.width > 2) continue
466
+ if (fadeThrough(svg, root.parentElement) < 0.5 || getComputedStyle(svg).visibility === 'hidden') continue
467
+ for (const shape of svg.querySelectorAll('path, circle, line, polyline, polygon, rect, ellipse')) {
468
+ const cs = getComputedStyle(shape)
469
+ // An unparsed paint is taken as opaque, so only a known alpha is reported
470
+ const strokeA = cs.stroke !== 'none' ? alphaOf(cs.stroke, 1) * parseFloat(cs.strokeOpacity) : 1
471
+ const fillA = cs.fill !== 'none' ? alphaOf(cs.fill, 1) * parseFloat(cs.fillOpacity) : 1
472
+ if (strokeA < 0.99 || fillA < 0.99) {
473
+ out.push(`translucent icon: ${labelOf(svg.parentElement ?? svg).split(' "')[0]} > svg${svg.getAttribute('class') ? '.' + svg.getAttribute('class').split(' ')[0] : ''} (use an opaque color such as --ss-icon, or opacity on the whole svg)`)
474
+ break
475
+ }
476
+ }
477
+ }
478
+ return out
479
+ }
480
+
481
+ // Skeleton ladder: a column of six or more rows with no words in them
482
+ // reads as a wireframe, whatever the hero is doing
483
+ function detectSkeletonLadder({ root, S, specimen, fidelity, gridish }) {
484
+ const out = []
485
+ for (const n of specimen ? [] : root.querySelectorAll('*')) {
486
+ if (n.children.length < 4 || n.closest(gridish) || !painted(n, root)) continue
487
+ const cs = getComputedStyle(n)
488
+ if (!/flex|grid|block/.test(cs.display) || (cs.display.includes('flex') && cs.flexDirection !== 'column')) continue
489
+ // A grid of cells (a sheet, a calendar, a board) is not a column of rows
490
+ if (cs.display.includes('grid') && cs.gridTemplateColumns.split(' ').length >= 3) continue
491
+ // Rows the crop cuts are the list running off, not a ladder
492
+ const kids = [...n.children].filter((k) => { const r = k.getBoundingClientRect(); return r.height >= 16 && r.width >= 60 && painted(k, root) && r.bottom <= S.bottom + 1 && r.top >= S.top - 1 })
493
+ if (kids.length < 4) continue
494
+ // A grid, a sheet or a calendar: rows made of cells, not lines of text
495
+ if (kids.every((k) => k.children.length >= 4)) continue
496
+ // Bars are the product's filler. The list the story touches (it holds a
497
+ // target) is judged; so is a still whose frame is mostly this one list.
498
+ // Every other column of bars is furniture and fine
499
+ // Fidelity sets the bar: minimal is all bars by design; standard shows
500
+ // words where they carry meaning, so only the story's list with no
501
+ // words at all, or a still that is one bar list, is a ladder;
502
+ // realistic is real content everywhere, so any list in frame that is
503
+ // mostly bars is
504
+ if (fidelity !== 'realistic') break
505
+ const wordy = (k) => [...k.querySelectorAll('*'), k].some((e) => !e.closest('.ss-bar') && [...e.childNodes].some((t) => t.nodeType === 3 && t.textContent.trim().length > 1))
506
+ let run = 0, best = 0, blank = 0, words = 0
507
+ for (const k of kids) { const w = wordy(k); run = w ? 0 : run + 1; best = Math.max(best, run); if (w) words++; else blank++ }
508
+ if (fidelity === 'realistic' && blank >= 3 && blank > words) out.push(`skeleton ladder: ${blank} of ${kids.length} rows inside ${labelOf(n).split(' "')[0]} have no words in them at realistic fidelity, where content is real everywhere; give the rows in frame words (Text filler shows them at this fidelity) or drop to standard`)
509
+ }
510
+ return out
511
+ }
512
+
513
+ // Loose list: rows in a column with more air between them than they are
514
+ // tall, a list stretched to fill a pane
515
+ function detectLooseList({ root, S, specimen, gridish }) {
516
+ const out = []
517
+ for (const n of specimen ? [] : root.querySelectorAll('*')) {
518
+ if (n.children.length < 3 || n.closest(gridish) || !painted(n, root)) continue
519
+ const cs = getComputedStyle(n)
520
+ if (!/flex|grid|block/.test(cs.display) || (cs.display.includes('flex') && cs.flexDirection !== 'column')) continue
521
+ if (/^(MAIN|SECTION|ARTICLE|HEADER|FOOTER|FORM)$/.test(n.tagName) || n.classList.contains('ss-thread')) continue
522
+ const rows = [...n.children].map((k) => k.getBoundingClientRect()).filter((r) => r.height >= 14 && r.height <= 64 && r.width >= 100 && r.bottom <= S.bottom + 1 && r.top >= S.top - 1)
523
+ if (rows.length < 3) continue
524
+ // Alike in size, or they are sections, not rows
525
+ const hs = rows.map((r) => r.height), ws = rows.map((r) => r.width)
526
+ if (Math.max(...hs) > Math.min(...hs) * 1.5 || Math.max(...ws) > Math.min(...ws) * 1.3) continue
527
+ rows.sort((a, b) => a.top - b.top)
528
+ const heights = rows.map((r) => r.height).sort((a, b) => a - b), gaps = rows.slice(1).map((r, i) => r.top - rows[i].bottom).sort((a, b) => a - b)
529
+ const h = heights[Math.floor(heights.length / 2)], g = gaps[Math.floor(gaps.length / 2)]
530
+ if (g > Math.max(24, h)) out.push(`loose list: rows inside ${labelOf(n).split(' "')[0]} sit ${Math.round(g)}px apart for ${Math.round(h)}px of row; a list keeps its rows a few pixels apart (the row's padding carries the air) and fills its pane with more rows, not more space`)
531
+ }
532
+ return out
533
+ }
534
+
535
+ // Tight control: a button or chip with no air between it and the field,
536
+ // text or card edge above it (a Comment button sitting on the textarea)
537
+ function detectTightControl({ root, S, specimen }) {
538
+ const out = []
539
+ // A fill, a styled top border or a shadow
540
+ const surfaced = (cs) => paintsSurface(cs, { minAlpha: 0.02, border: true, styled: true })
541
+ for (const n of specimen ? [] : root.querySelectorAll('button, [role="button"], [class*="btn"], [class*="button"]')) {
542
+ if (n.closest('.ss-cursor, .ss-keys, .ss-kb, svg, .ss-window__bar, .ss-phone__status') || !painted(n, root) || n.querySelector('button')) continue
543
+ const cs = getComputedStyle(n)
544
+ if (!surfaced(cs)) continue
545
+ const r = n.getBoundingClientRect()
546
+ if (r.width < 24 || r.height < 16 || r.top < S.top || r.bottom > S.bottom) continue
547
+ if (n.getAnimations({ subtree: true }).some((x) => x.playState === 'running')) continue
548
+ // The nearest painted box whose bottom sits just above this control, overlapping it horizontally
549
+ let worst = null
550
+ for (const d of root.querySelectorAll('*')) {
551
+ if (d === n || d.contains(n) || n.contains(d) || d.closest('.ss-cursor, .ss-keys, svg') || !painted(d, root)) continue
552
+ const ds = getComputedStyle(d)
553
+ if (!surfaced(ds) && !(parseFloat(ds.borderBottomWidth) > 0) && !/^(INPUT|TEXTAREA)$/.test(d.tagName)) continue
554
+ const b = d.getBoundingClientRect()
555
+ if (b.width < 24 || b.height < 12 || b.bottom > r.top + 1 || b.bottom < r.top - 8) continue
556
+ if (Math.min(b.right, r.right) - Math.max(b.left, r.left) < 16) continue
557
+ if (d.contains(n) || d.getBoundingClientRect().height > r.height * 6 && d.contains(n)) continue
558
+ const gap = r.top - b.bottom
559
+ if (!worst || gap < worst.gap) worst = { d, gap }
560
+ }
561
+ if (worst && worst.gap < 8) { out.push(`tight control: ${labelOf(n)} sits ${worst.gap.toFixed(1)}px under ${labelOf(worst.d)}; a button keeps 8px or more from the field, line or card edge above it`); break }
562
+ }
563
+ return out
564
+ }
565
+
566
+ // Invented mark: a real company's name beside a one-letter tile in a
567
+ // brand color. A real name takes its real mark from the kit, or no name
568
+ function detectInventedMark({ root, specimen }) {
569
+ const out = []
570
+ const BRANDS = /\b(chase|wells fargo|bank of america|citi|citibank|barclays|hsbc|monzo|revolut|wise|capital one|goldman|jpmorgan|stripe|paypal|visa|mastercard|amex|american express|slack|figma|notion|linear|github|gitlab|vercel|netlify|shopify|dropbox|google|gmail|apple|microsoft|amazon|aws|spotify|netflix|uber|lyft|airbnb|zoom|discord|twitter|meta|facebook|instagram|tiktok|openai|anthropic)\b/i
571
+ for (const n of specimen ? [] : root.querySelectorAll('*')) {
572
+ if (n.children.length || n.closest('.ss-brand, svg, .ss-cursor, .ss-keys, .ss-avatar') || !painted(n, root)) continue
573
+ const t = (n.textContent || '').trim()
574
+ if (!/^[A-Z0-9]$/.test(t)) continue
575
+ const r = n.getBoundingClientRect(); if (r.width < 14 || r.width > 44 || r.height < 14 || r.height > 44) continue
576
+ // The tile is the letter's own box or its parent
577
+ const tile = [n, n.parentElement].find((e) => { if (!e) return false; const bg = rgbaOf(getComputedStyle(e).backgroundColor); if (!bg || bg.a < 0.5) return false; return Math.max(bg.r, bg.g, bg.b) - Math.min(bg.r, bg.g, bg.b) > 60 })
578
+ if (!tile) continue
579
+ const row = tile.parentElement
580
+ const words = row ? (row.textContent || '').replace(t, ' ') : ''
581
+ const hit = words.match(BRANDS)
582
+ if (hit) { out.push(`invented mark: a "${t}" tile in a brand color stands beside "${hit[0]}", a real company; a real name takes its real mark from kit/brands, or the scene names a company the kit has or a fictional one with the neutral initial tile`); break }
583
+ }
584
+ return out
585
+ }
586
+
587
+ // Near aligned: two lines of words stacked in one card whose left edges
588
+ // miss each other by a few pixels (a body indented by the field's inset
589
+ // under a name on the avatar's column): neither one column nor an indent
590
+ function detectNearAligned({ root, specimen }) {
591
+ const out = []
592
+ for (const n of specimen ? [] : root.querySelectorAll('*')) {
593
+ if (n.children.length < 2 || n.closest('.ss-cursor, .ss-keys, .ss-kb, svg, .ss-code, .ss-term, .ss-chart, table, [role="grid"]') || !painted(n, root)) continue
594
+ const cs = getComputedStyle(n)
595
+ if (!/flex|grid|block/.test(cs.display) || (cs.display.includes('flex') && cs.flexDirection !== 'column')) continue
596
+ if (n.getAnimations({ subtree: true }).some((x) => x.playState === 'running' && !(x.effect?.getTiming?.().iterations === Infinity))) continue
597
+ const firstWords = (k) => { for (const e of [k, ...k.querySelectorAll('*')]) { if (e.closest('svg, .ss-avatar, .ss-bar, .ss-draft[data-editing]') || getComputedStyle(e).display === 'none' || getComputedStyle(e).visibility === 'hidden') continue; if ([...e.childNodes].some((t) => t.nodeType === 3 && t.textContent.trim().length > 1)) { const r = e.getBoundingClientRect(); if (r.width > 8 && getComputedStyle(e).textAlign !== 'center' && getComputedStyle(e).textAlign !== 'right') return { e, r } } } return null }
598
+ // Only a small card (a comment, a note): a head line over a body line on one surface
599
+ if (!visible(n) || n.children.length > 4) continue
600
+ const kids = [...n.children].filter((k) => painted(k, root) && k.getBoundingClientRect().height >= 10)
601
+ for (let i = 1; i < kids.length; i++) {
602
+ const a = firstWords(kids[i - 1]), b = firstWords(kids[i])
603
+ if (!a || !b) continue
604
+ const d = Math.abs(a.r.left - b.r.left)
605
+ // A head line with an avatar, and a body starting under the avatar instead of under the name
606
+ const av = kids[i - 1].querySelector('.ss-avatar, [class*="avatar"]')
607
+ if (av && d > 14 && b.r.left < a.r.left) {
608
+ const ar = av.getBoundingClientRect()
609
+ if (Math.abs(b.r.left - ar.left) <= 4 && ar.right <= a.r.left + 2) { out.push(`avatar alignment: ${labelOf(b.e)} starts under the avatar in ${labelOf(n).split(' "')[0]}, not under ${labelOf(a.e)}; a body under an avatar row starts at the name's edge`); i = kids.length; continue }
610
+ }
611
+ if (d < 3 || d > 14) continue
612
+ // Both start in the container's left half and overlap horizontally
613
+ const nr = n.getBoundingClientRect()
614
+ if (a.r.left > nr.left + nr.width / 2 || b.r.left > nr.left + nr.width / 2) continue
615
+ if (Math.min(a.r.right, b.r.right) - Math.max(a.r.left, b.r.left) < 20) continue
616
+ out.push(`near aligned: ${labelOf(a.e)} and ${labelOf(b.e)} start ${d.toFixed(1)}px apart in ${labelOf(n).split(' "')[0]}; lines in a card share one left edge, or one is indented on purpose by a column (an avatar's width and gap), never by a few pixels`)
617
+ i = kids.length
618
+ }
619
+ }
620
+ return out
621
+ }
622
+
623
+ // Uneven inset: a bar, pill or row of controls whose last child sits much
624
+ // closer to the right edge than the first sits from the left (an Approve
625
+ // button against a window corner, a chevron jammed in a date pill)
626
+ function detectUnevenInset({ root, S, specimen }) {
627
+ const out = []
628
+ for (const n of specimen ? [] : root.querySelectorAll('*')) {
629
+ if (n.children.length < 2 || n.closest('.ss-cursor, .ss-keys, .ss-kb, .ss-phone__status, svg, .ss-chart') || !painted(n, root)) continue
630
+ const br = n.getBoundingClientRect()
631
+ if (br.width < 120 || br.height < 24 || br.height > 80 || br.right > S.right + 1 || br.left < S.left - 1) continue
632
+ const cs = getComputedStyle(n)
633
+ // A fill (over 0.03), a top border or a shadow
634
+ const surfaced = paintsSurface(cs, { minAlpha: 0.03, border: true })
635
+ // A bar is the top strip of a window; a pill is any surfaced row of controls
636
+ const win = n.closest('.ss-window')
637
+ const isBar = win && br.top - win.getBoundingClientRect().top < 64 && br.width >= win.getBoundingClientRect().width * 0.8
638
+ if (!surfaced && !isBar) continue
639
+ const kids = [...n.children].filter((d) => { const r = d.getBoundingClientRect(); return r.width >= 6 && r.height >= 6 && painted(d, root) })
640
+ if (kids.length < 2) continue
641
+ const rows = new Set(kids.map((d) => Math.round(d.getBoundingClientRect().top / 8)))
642
+ if (rows.size > 1) continue
643
+ const leftIn = Math.min(...kids.map((d) => d.getBoundingClientRect().left)) - br.left
644
+ const rightIn = br.right - Math.max(...kids.map((d) => d.getBoundingClientRect().right))
645
+ // Only a row whose children fill it: a left-aligned row with free space on the right is a layout, not a miss
646
+ const fill = (Math.max(...kids.map((d) => d.getBoundingClientRect().right)) - Math.min(...kids.map((d) => d.getBoundingClientRect().left))) / br.width
647
+ if (fill < 0.7) continue
648
+ const lo = Math.min(leftIn, rightIn), hi = Math.max(leftIn, rightIn)
649
+ if (hi >= 16 && lo >= 0 && lo < hi * 0.55 && hi - lo >= 6) { out.push(`uneven inset: ${labelOf(n).split(' "')[0]} holds its children ${Math.round(leftIn)}px from its left edge and ${Math.round(rightIn)}px from its right; a bar, pill or row of controls keeps one inset at both ends`); break }
650
+ }
651
+ return out
652
+ }
653
+
654
+ // Mixed icons: filled and outline glyphs side by side in one nav, list or
655
+ // toolbar. One family, one construction
656
+ function detectMixedIcons({ root, specimen }) {
657
+ const out = []
658
+ const kind = (svg) => {
659
+ const shapes = [...svg.querySelectorAll('path, rect, circle, ellipse, polygon, line, polyline')]
660
+ if (!shapes.length) return null
661
+ let filled = 0, stroked = 0
662
+ for (const s of shapes) {
663
+ const c = getComputedStyle(s)
664
+ const hasFill = c.fill !== 'none' && !/rgba\(0, 0, 0, 0\)/.test(c.fill)
665
+ const hasStroke = c.stroke !== 'none' && parseFloat(c.strokeWidth) > 0
666
+ if (hasStroke && !hasFill) stroked++
667
+ else if (hasFill && !hasStroke) filled++
668
+ }
669
+ if (filled && !stroked) return 'filled'
670
+ if (stroked && !filled) return 'outline'
671
+ return null
672
+ }
673
+ for (const n of specimen ? [] : root.querySelectorAll('nav, aside, ul, [role="list"], [role="toolbar"], .ss-window__side')) {
674
+ if (n.closest('.ss-cursor, .ss-keys, .ss-kb, .ss-chart')) continue
675
+ const icons = [...n.querySelectorAll('svg')].filter((s) => { const r = s.getBoundingClientRect(); return r.width >= 10 && r.width <= 32 && r.height >= 10 && r.height <= 32 && !s.closest('.ss-check, .ss-spinner, .ss-toggle, .ss-brand, .ss-avatar, .ss-phone__glyphs') && painted(s, root) })
676
+ if (icons.length < 3) continue
677
+ const kinds = icons.map(kind).filter(Boolean)
678
+ const f = kinds.filter((k) => k === 'filled').length, o = kinds.filter((k) => k === 'outline').length
679
+ if (f && o && Math.min(f, o) >= 1 && f + o >= 3) { out.push(`mixed icons: ${labelOf(n).split(' "')[0]} has ${f} filled and ${o} outline glyphs side by side; icons share one family and one construction, filled or outline, not both`); break }
680
+ }
681
+ return out
682
+ }
683
+
684
+ // Emoji icon: an emoji standing in for an icon (a row's lead, a tab, a
685
+ // tile). Emoji are content: a reaction, a message, a sticker
686
+ function detectEmojiIcon({ root, specimen }) {
687
+ const out = []
688
+ const emojiRe = /^(?:\p{Extended_Pictographic}|\p{Emoji_Presentation})(?:\uFE0F|\u200D\p{Extended_Pictographic}|[\u{1F3FB}-\u{1F3FF}])*$/u
689
+ for (const n of specimen ? [] : root.querySelectorAll('*')) {
690
+ if (n.children.length || n.closest('.ss-cursor, .ss-keys, .ss-kb, svg, .ss-bubble, .ss-tapback, .ss-reaction, .ss-thread, [data-emoji], .ss-notification__body, .ss-message')) continue
691
+ const t = (n.textContent || '').trim()
692
+ if (!t || t.length > 3 || !emojiRe.test(t)) continue
693
+ const r = n.getBoundingClientRect()
694
+ if (r.width < 8 || r.height < 8 || !painted(n, root)) continue
695
+ // Standing alone in a small box beside words, or in a tab or tile: an icon's seat
696
+ const box = n.parentElement
697
+ const br = box ? box.getBoundingClientRect() : r
698
+ const seat = box && br.width <= 56 && br.height <= 56 && !/\p{L}/u.test((box.textContent || '').replace(t, ''))
699
+ const row = box && box.parentElement
700
+ const besideWords = row && /\p{L}{3,}/u.test(row.textContent || '')
701
+ if (seat && besideWords) { out.push(`emoji icon: ${labelOf(n)} stands where an icon belongs (a ${Math.round(br.width)}px seat beside words); emoji are content (a reaction, a message), icons are drawn, one family tinted to the look`); break }
702
+ }
703
+ return out
704
+ }
705
+
706
+ // Fat row: a one-line row in a list drawn three or four times taller than
707
+ // its own words (a sidebar item 110px tall), air inside the row instead of
708
+ // rows in the list
709
+ function detectFatRow({ root, S, specimen, gridish }) {
710
+ const out = []
711
+ for (const n of specimen ? [] : root.querySelectorAll('*')) {
712
+ if (n.children.length < 3 || n.closest(gridish) || !painted(n, root)) continue
713
+ const cs = getComputedStyle(n)
714
+ if (!/flex|grid|block/.test(cs.display) || (cs.display.includes('flex') && cs.flexDirection !== 'column')) continue
715
+ if (cs.display.includes('grid') && cs.gridTemplateColumns.split(' ').length >= 2) continue
716
+ let fat = 0, rows = 0, worst = null
717
+ for (const k of n.children) {
718
+ const r = k.getBoundingClientRect()
719
+ if (r.height < 16 || r.width < 100 || r.bottom > S.bottom + 1 || r.top < S.top - 1 || !painted(k, root)) continue
720
+ const leaves = [...k.querySelectorAll('*'), k].filter((e) => [...e.childNodes].some((t) => t.nodeType === 3 && t.textContent.trim()))
721
+ if (!leaves.length || k.querySelector('.ss-bar, .ss-chart, svg + svg, textarea, input')) continue
722
+ const tops = new Set(leaves.map((e) => Math.round(e.getBoundingClientRect().top / 6)))
723
+ if (tops.size > 1 || k.textContent.trim().length < 4) continue
724
+ rows++
725
+ const fs = Math.max(...leaves.map((e) => parseFloat(getComputedStyle(e).fontSize) || 14))
726
+ const tw = Math.max(...leaves.map((e) => e.getBoundingClientRect().width))
727
+ if (tw < r.width * 0.4 || r.width < 120) continue
728
+ if (r.height > fs * 3.4 && r.height > 48) { fat++; if (!worst || r.height > worst.h) worst = { k, h: r.height, fs } }
729
+ }
730
+ if (rows >= 3 && fat >= 2) out.push(`fat row: ${labelOf(worst.k)} is ${Math.round(worst.h)}px tall for one ${Math.round(worst.fs)}px line (${fat} of ${rows} rows in ${labelOf(n).split(' "')[0]} are); a one-line row is its words plus 8 to 12px of padding each side, and a list fills its pane with more rows, not taller ones`)
731
+ }
732
+ return out
733
+ }
734
+
735
+ // Empty pane: a window pane, sidebar, column or phone screen whose
736
+ // painted content stops well above its visible bottom: a void
737
+ function detectEmptyPane({ root, S, specimen, fidelity }) {
738
+ const out = []
739
+ for (const n of specimen || root.querySelectorAll('.ss-phone, .ss-window').length > 1 ? [] : root.querySelectorAll('.ss-phone__screen, .ss-phone__content, .ss-window__body, .ss-window aside, .ss-window nav, [data-pane]')) {
740
+ if (!painted(n, root) || n.closest('.ss-cursor')) continue
741
+ const r = n.getBoundingClientRect()
742
+ const bottom = Math.min(r.bottom, S.bottom), top = Math.max(r.top, S.top)
743
+ if (bottom - top < 120 || r.width < 80) continue
744
+ // Clipped away by its own window (a side panel slid shut): not in frame
745
+ let vis = { left: r.left, right: r.right }
746
+ for (let a = n.parentElement; a && a !== root; a = a.parentElement) {
747
+ const o = getComputedStyle(a)
748
+ if (o.overflowX !== 'visible' || o.overflowY !== 'visible') { const c = a.getBoundingClientRect(); vis.left = Math.max(vis.left, c.left); vis.right = Math.min(vis.right, c.right) }
749
+ }
750
+ if (vis.right - vis.left < r.width * 0.5) continue
751
+ let low = top
752
+ for (const d of n.querySelectorAll('*')) {
753
+ if (d.closest('.ss-cursor, .ss-keys, .ss-phone__home, .ss-phone__status, .ss-phone__island, .ss-phone__glyphs, .ss-phone__time-bar')) continue
754
+ const dr = d.getBoundingClientRect()
755
+ if (dr.width < 4 || dr.height < 4 || dr.top >= bottom) continue
756
+ const cs = getComputedStyle(d)
757
+ const text = [...d.childNodes].some((t) => t.nodeType === 3 && t.textContent.trim())
758
+ // A fill or an image, shadows aside
759
+ const filled = paintsSurface(cs, { minAlpha: 0.02, image: true, shadow: false })
760
+ const inked = filled || d.tagName === 'svg' || d.tagName === 'IMG' || text
761
+ if (!inked || !painted(d, root)) continue
762
+ // A container's own fill is the pane's surface, not content: only a
763
+ // leaf fill (a bar, a disc, a tile) or something small counts
764
+ const paneBg = getComputedStyle(n).backgroundColor
765
+ if (filled && !text && d.tagName !== 'svg' && d.tagName !== 'IMG' && d.children.length && dr.height > (bottom - top) * 0.25 && (cs.backgroundColor === paneBg || dr.height >= (bottom - top) * 0.9)) continue
766
+ if (dr.height >= (bottom - top) * 0.9 && cs.backgroundColor === paneBg) continue
767
+ low = Math.max(low, Math.min(dr.bottom, bottom))
768
+ }
769
+ const gap = bottom - low
770
+ const tol = fidelity === 'realistic' ? 0.3 : fidelity === 'minimal' ? 0.75 : 0.65
771
+ if (gap > Math.max(100, (bottom - top) * tol)) out.push(`empty pane: ${labelOf(n).split(' "')[0]} has ${Math.round(gap)}px of nothing under its last content (${Math.round((gap / (bottom - top)) * 100)}% of its height); fill it with more of the product (rows, a card, the next section) or crop the pane so its content runs off the edge`)
772
+ }
773
+ return out
774
+ }
775
+
776
+ // Tight inset: typeset words sitting almost on a surface's own edge (an
777
+ // hours column 5px from the window's side). Bars and icons may bleed;
778
+ // words keep the container's inset
779
+ function detectTightInset({ root, S, specimen }) {
780
+ const out = []
781
+ for (const n of root.querySelectorAll('*')) {
782
+ if (!n.children.length || n.closest('.ss-cursor, .ss-keys, .ss-kb, svg') || n.hasAttribute('data-crop')) continue
783
+ const isWindow = /^(ss-window|ss-window__body|ss-window__main|ss-window__side|ss-phone__screen|ss-phone__content)$/.test([...n.classList].find((c) => /^ss-(window|phone)/.test(c)) || '')
784
+ const ncs = getComputedStyle(n)
785
+ const card = !isWindow && visible(n) && (ncs.boxShadow !== 'none' || parseFloat(ncs.borderTopWidth) > 0) && parseFloat(ncs.borderTopLeftRadius) >= 6
786
+ if ((!isWindow && !card) || specimen) continue
787
+ const r = n.getBoundingClientRect()
788
+ if (r.width < 160 || r.height < 48 || n.closest('.ss-seg, .ss-segmented, [role="tablist"]') || /seg|tab|pill|chip|toolbar/i.test(typeof n.className === 'string' ? n.className : '')) continue
789
+ if (n.getAnimations({ subtree: true }).some((x) => x.playState === 'running')) continue
790
+ for (const d of n.querySelectorAll('*')) {
791
+ if (d.children.length || !d.textContent.trim() || d.closest('svg, .ss-cursor, .ss-keys, .ss-kb, .ss-bar, .ss-count, [data-crop], .ss-phone__status, .ss-phone__time-bar, .ss-lock, .ss-notification, .ss-island') || !painted(d, root)) continue
792
+ // Only words whose nearest surface is this one
793
+ let a = d.parentElement, owner = null
794
+ while (a && a !== n) { if (visible(a) || a.classList.contains('ss-window') || a.classList.contains('ss-phone__screen')) { owner = a; break } a = a.parentElement }
795
+ if (owner) continue
796
+ const dr = d.getBoundingClientRect()
797
+ if (dr.width < 6 || dr.height < 6) continue
798
+ const left = dr.left - r.left, right = r.right - dr.right
799
+ if (left >= 0 && left < 8 && dr.left > S.left + 2) { out.push(`tight inset: ${labelOf(d)} sits ${left.toFixed(1)}px from the left edge of ${labelOf(n).split(' "')[0]}; words keep the container's inset (12px or more on a row, card or window), only filler bleeds`); break }
800
+ if (right >= 0 && right < 8 && dr.right < S.right - 2) { out.push(`tight inset: ${labelOf(d)} sits ${right.toFixed(1)}px from the right edge of ${labelOf(n).split(' "')[0]}; words keep the container's inset (12px or more on a row, card or window), only filler bleeds`); break }
801
+ }
802
+ }
803
+ return out
804
+ }
805
+
806
+ // Uneven padding: a visible container, fully in the stage, whose content
807
+ // sits much closer to its top or bottom edge than to its side. Cards and
808
+ // tiles only: not the kit's window panes or phone chrome, and not specimen
809
+ // sheets. Inside a phone the screen's cards and tiles are judged like any
810
+ // other; only the phone's own chrome is not
811
+ // Paints something you can see at its own edge: a fill, a border or a shadow
812
+ // that isn't transparent (a transparent ring waiting to fade in is nothing)
813
+ function inkedBox(cs) {
814
+ const seen = (c) => (c.match(/rgba?\([^)]*\)/g) || []).some((x) => alphaOf(x, 1) > 0.05)
815
+ return alphaOf(cs.backgroundColor, 0) > 0.05 || (parseFloat(cs.borderTopWidth) > 0 && alphaOf(cs.borderTopColor, 1) > 0.05) || (cs.boxShadow !== 'none' && seen(cs.boxShadow))
816
+ }
817
+
818
+ function detectUnevenPadding({ root, S, specimen }) {
819
+ const out = []
820
+ if (specimen) return out
821
+ for (const n of root.querySelectorAll('*')) {
822
+ if (!n.children.length || n.hasAttribute('data-crop') || n.closest('.ss-cursor, .ss-keys, .ss-kb, svg, .ss-phone__status, .ss-phone__island, .ss-phone__home, .ss-phone__glyphs') || /(^| )ss-(window|phone)/.test([...n.classList].join(' '))) continue
823
+ const r = n.getBoundingClientRect()
824
+ if (r.height < 44 || r.width < 44 || r.left < S.left || r.right > S.right || r.top < S.top || r.bottom > S.bottom) continue
825
+ // The plate or scene wrapper that is most of the stage is framing (a gutter), judged elsewhere
826
+ if (r.width * r.height >= S.width * S.height * 0.85) continue
827
+ const cs = getComputedStyle(n)
828
+ if (Number(cs.opacity) < 0.95) continue
829
+ // A clip-path draws a smaller card than the box (an expanding card held
830
+ // in its slot): the box's edges aren't the card's, so padding can't be read
831
+ if (cs.clipPath && cs.clipPath !== 'none') continue
832
+ // Mid-transition (an entrance slide, a fade) isn't a layout: judge it at rest
833
+ const idle = (x) => x.effect?.target?.closest?.('.ss-spinner, .ss-check__arc, .ss-caret, .ss-field__caret, .ss-term__caret, [class*="caret"]') || (x.effect?.getTiming?.().iterations === Infinity)
834
+ if (n.getAnimations({ subtree: true }).some((x) => x.playState === 'running' && !idle(x))) continue
835
+ // The kit's popover paints its surface on ::before, so it reads as bare to visible()
836
+ if (!visible(n) && !n.matches('.ss-popover')) continue
837
+ let u = null
838
+ let svgOnly = true, leaves = 0
839
+ for (const d of n.querySelectorAll('*')) {
840
+ const figure = d.matches('.ss-count, .ss-roll')
841
+ if (d.closest('.ss-count, .ss-roll') && !figure) continue
842
+ // A box drawn on a container (a draft's typing ring) is content at its own edge
843
+ const dcs = d.children.length ? getComputedStyle(d) : null
844
+ const ringed = !!dcs && alphaOf(dcs.backgroundColor, 0) <= 0.05 && /inset/.test(dcs.boxShadow) && !/inline/.test(dcs.display) && d.getBoundingClientRect().height >= 28 && inkedBox(dcs)
845
+ if (d.children.length && d.tagName.toLowerCase() !== 'svg' && !figure && !ringed) continue
846
+ if (d.closest('svg') && d.tagName.toLowerCase() !== 'svg') continue
847
+ const dr = d.getBoundingClientRect()
848
+ const ds = getComputedStyle(d)
849
+ if (dr.width < 2 || dr.height < 2 || ds.visibility === 'hidden' || Number(ds.opacity) === 0) continue
850
+ // Faded out through a parent (a States option not showing) isn't content anyone sees
851
+ let faded = false
852
+ for (let a = d.parentElement; a && a !== n; a = a.parentElement) if (Number(getComputedStyle(a).opacity) < 0.05) { faded = true; break }
853
+ if (faded) continue
854
+ // Wholly outside the box it is an overlay or a hidden piece, not content; an illustration
855
+ // straddling the edge (a mascot on a card's rim) is clamped to the box
856
+ if (dr.bottom <= r.top || dr.top >= r.bottom || dr.right <= r.left || dr.left >= r.right) continue
857
+ leaves++; if (d.tagName.toLowerCase() !== 'svg') svgOnly = false
858
+ // A bare text box (a label with its own padding) is judged by its words, not its box
859
+ let ink = dr
860
+ if (!visible(d) && d.firstChild && [...d.childNodes].every((t) => t.nodeType === 3) && d.textContent.trim()) { const rg = document.createRange(); rg.selectNodeContents(d); const tr = rg.getBoundingClientRect(); if (tr.width > 0) ink = { left: Math.max(tr.left, dr.left), right: Math.min(tr.right, dr.right), top: Math.max(tr.top, dr.top), bottom: Math.min(tr.bottom, dr.bottom) } }
861
+ const box = d.tagName.toLowerCase() === 'svg' || d.closest('.ss-chart, canvas, img, picture') ? { left: Math.max(dr.left, r.left), right: Math.min(dr.right, r.right), top: Math.max(dr.top, r.top), bottom: Math.min(dr.bottom, r.bottom) } : ink
862
+ u = u ? { l: Math.min(u.l, box.left), r: Math.max(u.r, box.right), t: Math.min(u.t, box.top), b: Math.max(u.b, box.bottom) } : { l: box.left, r: box.right, t: box.top, b: box.bottom }
863
+ }
864
+ if (!u) continue
865
+ // An icon tile or a chip (a small box) is sized by eye, not padded
866
+ if (r.width < 80 && r.height < 80) continue
867
+ // An edge the container's own clip hides (a card running off its tile) is not judged
868
+ let vis = { top: r.top, bottom: r.bottom }
869
+ for (let a = n.parentElement; a && a !== root; a = a.parentElement) {
870
+ const o = getComputedStyle(a)
871
+ if (o.overflowY === 'visible' && !a.hasAttribute('data-crop')) continue
872
+ const c = a.getBoundingClientRect(); vis.top = Math.max(vis.top, c.top); vis.bottom = Math.min(vis.bottom, c.bottom)
873
+ }
874
+ const topHidden = vis.top > r.top + 1, bottomHidden = vis.bottom < r.bottom - 1
875
+ const L = u.l - r.left, T = u.t - r.top, B = r.bottom - u.b
876
+ if (L < 8) continue
877
+ const tight = []
878
+ // A gap a quarter short of the side and at least 3px off reads as a
879
+ // miss, not a choice (14px under a button with 24px at the side)
880
+ // Past the edge counts too: a pill hanging off a card's bottom is the worst case of no padding
881
+ // A quarter of the side inset short, or past the edge by more than 4px
882
+ const short = (v) => (v >= 0 ? v < L * 0.7 && L - v >= 4 : v < -4)
883
+ // Equal top and bottom of 8px or more on a wide, short card is a proportion, not a miss
884
+ // So is a bar or strip (a header, a toolbar): wide and short, its vertical padding is set by its height
885
+ const proportion = (Math.abs(T - B) < 2 && Math.min(T, B) >= 6) || (r.height < 72 && r.width > r.height * 4 && Math.abs(T - B) <= 3)
886
+ if (!proportion && !bottomHidden && short(B)) tight.push(`bottom ${Math.round(B)}px`)
887
+ if (!proportion && !topHidden && short(T)) tight.push(`top ${Math.round(T)}px`)
888
+ if (tight.length) out.push(`uneven padding: ${labelOf(n).split(' "')[0]} has ${tight.join(', ')} against ${Math.round(L)}px at the side; a card pads its content the same on every side (the outer radius is the inner radius plus the padding)`)
889
+ }
890
+ return out
891
+ }
892
+
893
+ // Uneven gutters: a card or device sitting wholly inside a surfaced tile,
894
+ // panel or plate with different gaps to the sides it doesn't bleed past
895
+ // (68px left, 211px right, 33px below). Either it bleeds off an edge or
896
+ // it keeps one gutter; the top is left out, since copy often sits above
897
+ function detectUnevenGutters({ root, specimen }) {
898
+ const out = []
899
+ for (const c of specimen ? [] : root.querySelectorAll('*')) {
900
+ if (c.closest('.ss-cursor, .ss-keys, .ss-kb, svg, .ss-popover, .ss-toast') || !visible(c) || !painted(c, root)) continue
901
+ // Cards inside an app's own panes are its layout; only a card, window or phone set on a tile or plate is framed
902
+ if (c.parentElement?.closest('.ss-window, .ss-phone')) continue
903
+ const cr = c.getBoundingClientRect()
904
+ if (cr.width < 120 || cr.height < 60) continue
905
+ // A satellite or overlay laid over another surface (a card straddling a window) is composed, not set on a tile
906
+ const under = document.elementsFromPoint(cr.left + cr.width / 2, cr.top + cr.height / 2)
907
+ if (under.some((e) => e !== c && !e.contains(c) && !c.contains(e) && visible(e) && e.getBoundingClientRect().width >= 40)) continue
908
+ // The surface it sits on may be outside the stage: a bento tile holding a stage per picture
909
+ let p = c.parentElement
910
+ while (p && p !== document.body && !visible(p)) p = p.parentElement
911
+ if (!p || p === document.body) continue
912
+ const pr = p.getBoundingClientRect()
913
+ // The window or phone filling its plate is framing, judged elsewhere; a row in a list is a layout
914
+ if (cr.width > pr.width * 0.92 || cr.width < pr.width * 0.3) continue
915
+ // Cut by any clip on the way up (an invisible stage, a cropped tile): a bleed, a deliberate crop
916
+ let cut = false
917
+ for (let a = c.parentElement; a && a !== document.body; a = a.parentElement) {
918
+ if (getComputedStyle(a).overflow === 'visible') { if (a === p) break; continue }
919
+ const ar = a.getBoundingClientRect()
920
+ if (cr.left < ar.left - 1 || cr.right > ar.right + 1 || cr.bottom > ar.bottom + 1) { cut = true; break }
921
+ if (a === p) break
922
+ }
923
+ if (cut) continue
924
+ const vis = { left: pr.left, right: pr.right, bottom: pr.bottom }
925
+ const gaps = { left: cr.left - vis.left, right: vis.right - cr.right, bottom: vis.bottom - cr.bottom }
926
+ // Any edge at or past the visible edge is a bleed: a deliberate crop
927
+ if (Object.values(gaps).some((g) => g <= 1)) continue
928
+ const lo = Math.min(gaps.left, gaps.right, gaps.bottom), hi = Math.max(gaps.left, gaps.right, gaps.bottom)
929
+ if (hi - lo >= 14 && hi > lo * 1.6) out.push(`uneven gutters: ${labelOf(c).split(' "')[0]} sits ${Math.round(gaps.left)}px from the left of ${labelOf(p).split(' "')[0]}, ${Math.round(gaps.right)}px from the right and ${Math.round(gaps.bottom)}px from the bottom; bleed it off an edge, or keep one gutter on every side it doesn't bleed`)
930
+ }
931
+ return out
932
+ }
933
+
934
+ // Pill inset: a pill or chip inside a small rounded field, button or bar
935
+ // sits the same distance from the side as from the top and bottom
936
+ function detectPillInset({ root, specimen }) {
937
+ const out = []
938
+ for (const c of specimen ? [] : root.querySelectorAll('*')) {
939
+ if (c.closest('.ss-cursor, .ss-keys, .ss-kb, svg, table, [role="grid"]') || !visible(c) || !painted(c, root)) continue
940
+ const cr = c.getBoundingClientRect()
941
+ const cs = getComputedStyle(c)
942
+ if (cr.height < 14 || cr.height > 40 || parseFloat(cs.borderTopLeftRadius) < cr.height * 0.4) continue
943
+ if (c.getAnimations({ subtree: true }).some((x) => x.playState === 'running' && !(x.effect?.getTiming?.().iterations === Infinity))) continue
944
+ let p = c.parentElement
945
+ while (p && p !== root && !visible(p)) p = p.parentElement
946
+ if (!p || p === root) continue
947
+ const pr = p.getBoundingClientRect()
948
+ if (pr.height > 52 || pr.height < cr.height + 4 || parseFloat(getComputedStyle(p).borderTopLeftRadius) < 4) continue
949
+ const v = ((cr.top - pr.top) + (pr.bottom - cr.bottom)) / 2
950
+ const l = cr.left - pr.left, r = pr.right - cr.right
951
+ const side = l <= r ? l : r
952
+ // Only a pill at one end of a field, button or bar: a tag in the middle of a row is a layout
953
+ if (side < 0 || v < 0 || side > Math.max(24, v * 3)) continue
954
+ if (Math.abs(side - v) >= 3.5 && Math.max(side, v) > Math.min(side, v) * 1.5) out.push(`uneven inset: ${labelOf(c).split(' "')[0]} sits ${Math.round(side)}px from the ${l <= r ? 'left' : 'right'} of ${labelOf(p).split(' "')[0]} but ${Math.round(v)}px from its top and bottom; a pill inside a field or button keeps one inset all round`)
955
+ }
956
+ return out
957
+ }
958
+
959
+ // Tight stack: two different lines of text stacked with no leading between
960
+ // them (a name over a preview, a title over a description). Ink to ink
961
+ // under 5px reads as one broken block, whatever the line boxes say.
962
+ function detectTightStack({ root }) {
963
+ const out = []
964
+ // A line of text, not a row: nothing beside the words (no bar, avatar
965
+ // or icon), and no taller than a line or two
966
+ const textLeaf = (d) => d.querySelectorAll('*').length <= 4 && d.textContent.trim().length > 1 && !d.querySelector('svg, img, .ss-bar, .ss-avatar, .ss-facepile, [data-target]') && !d.closest('svg, .ss-cursor, .ss-keys, .ss-kb, .ss-count, .ss-roll, .ss-code, .ss-term') && d.getBoundingClientRect().height <= parseFloat(getComputedStyle(d).fontSize) * 3.2
967
+ const seen = new Set()
968
+ // A line wrapped in a States or a slot still has a first line someone
969
+ // sees: judge that, so a preview that swaps its words is still a line
970
+ const showing = (d) => { for (let a = d; a && a !== root; a = a.parentElement) { const c = getComputedStyle(a); if (Number(c.opacity) < 0.05 || c.visibility === 'hidden' || c.display === 'none') return false } return true }
971
+ const leafOf = (d) => {
972
+ if (getComputedStyle(d).display === 'inline') return null
973
+ if (textLeaf(d)) return d
974
+ if (d.querySelector('svg, img') || d.closest('svg, .ss-cursor, .ss-keys, .ss-kb, .ss-count, .ss-roll, .ss-code')) return null
975
+ const r = d.getBoundingClientRect()
976
+ if (r.height > 40) return null
977
+ return [...d.querySelectorAll('*')].find((e) => textLeaf(e) && showing(e) && e.getBoundingClientRect().width >= 8) || null
978
+ }
979
+ for (const n of root.querySelectorAll('*')) {
980
+ if (n.closest('.ss-cursor, .ss-keys, .ss-kb, svg, .ss-code') || !painted(n, root)) continue
981
+ const kids = [...n.children].map(leafOf).filter(Boolean)
982
+ if (kids.length < 2 || kids.length > 3) continue
983
+ for (let i = 1; i < kids.length; i++) {
984
+ const a = kids[i - 1], b = kids[i]
985
+ if (seen.has(b)) continue
986
+ const ar = a.getBoundingClientRect(), br = b.getBoundingClientRect()
987
+ if (ar.width < 8 || br.width < 8 || br.top < ar.bottom - 1 || Math.min(ar.right, br.right) - Math.max(ar.left, br.left) < 8) continue
988
+ // Judge the first words of each line, not a wrapper row (a name beside its time)
989
+ const lead_el = (d) => [d, ...d.querySelectorAll('*')].find((e) => [...e.childNodes].some((t) => t.nodeType === 3 && t.textContent.trim())) || d
990
+ const ca = getComputedStyle(lead_el(a)), cb = getComputedStyle(lead_el(b))
991
+ if (ca.fontSize === cb.fontSize && ca.color === cb.color && ca.fontWeight === cb.fontWeight) continue
992
+ const lead = (c) => Math.max(0, (parseFloat(c.lineHeight) || parseFloat(c.fontSize) * 1.2) - parseFloat(c.fontSize)) / 2
993
+ const ink = (br.top - ar.bottom) + lead(ca) + lead(cb)
994
+ if (ink < 3) {
995
+ seen.add(b)
996
+ out.push(`tight stack: ${labelOf(a)} sits ${ink.toFixed(1)}px of ink above ${labelOf(b)}; a name over its preview, a title over its description, wants 4 to 6px of ink between the lines (a 1.3 line height and a 2px gap), with the row's padding carrying the air`)
997
+ } else if (ink > 10 && parseFloat(ca.fontSize) < 15 && n.getBoundingClientRect().height < 80) {
998
+ seen.add(b)
999
+ out.push(`loose stack: ${labelOf(a)} sits ${ink.toFixed(1)}px of ink above ${labelOf(b)}; a name and its preview are one item, 4 to 6px of ink apart, and the row's padding carries the air, not the gap between the lines`)
1000
+ }
1001
+ }
1002
+ }
1003
+ return out
1004
+ }
1005
+
1006
+ // Kit override: the example's own stylesheet reaching into a kit part
1007
+ // (.ss-row__dot, .ss-tapback, .ss-bubble) to move or resize it. The
1008
+ // part's geometry is the kit's; what the example may style is its own
1009
+ // classes and the hooks the part documents (tokens, props)
1010
+ function detectKitOverride() {
1011
+ const out = []
1012
+ const hits = []
1013
+ for (const sheet of document.styleSheets) {
1014
+ const owner = sheet.ownerNode
1015
+ const id = owner?.getAttribute?.('data-vite-dev-id') || owner?.getAttribute?.('href') || ''
1016
+ if (!id || /\/kit\/|\/playground\//.test(id)) continue
1017
+ let rules
1018
+ try { rules = sheet.cssRules } catch { continue }
1019
+ // Nested rules (`.em { & .ss-row__dot {} }`) carry both a selector and
1020
+ // children. Only the selector's subject (its last compound) counts: an
1021
+ // example styling its own class under `.ss-stage[data-layout]` is fine.
1022
+ // An inner part (.ss-row__dot) may not be moved or sized at all; a
1023
+ // whole part (.ss-toast) may be placed, but not padded, sized or respaced
1024
+ const inner = /\.ss-[a-z0-9-]+__[a-z0-9_-]+/
1025
+ // The parts whose geometry the skill guarantees; the window's chrome, a
1026
+ // States slot or a Swap layer are the author's to shape
1027
+ const guarded = /\.ss-(row|tapback|bubble|facepile|avatar|stamp|receipt|toast|check|kb|keyboard|phone__(status|home|island|screen))/
1028
+ const subject = (sel) => sel.split(',')[0].trim().replace(/^&\s*/, '').split(/\s+(?![^(]*\))|>|\+|~/).filter(Boolean).pop() || ''
1029
+ const walk = (list) => { for (const r of list) {
1030
+ if (r.selectorText && r.style) {
1031
+ const subj = subject(r.selectorText).replace(/::?[a-z-]+(\([^)]*\))?/g, '')
1032
+ const css = r.style.cssText
1033
+ const sized = /(^|[^-])(padding|width|height|gap|font-size|line-height|min-width|min-height)\s*:/.test(css)
1034
+ const moved = /(^|[^-])(top|left|right|bottom|transform|position|inset)\s*:/.test(css)
1035
+ if (/\.ss-(bar|text)\b/.test(subj)) continue
1036
+ // The example's own class on the same element: a variant the author owns
1037
+ if (!inner.test(subj) && /\.(?!ss-)[a-z][a-z0-9-]*\.ss-|\.ss-[a-z0-9-]+\.(?!ss-)[a-z]/.test(subj)) continue
1038
+ if (!guarded.test(subj)) continue
1039
+ if ((inner.test(subj) && (sized || moved)) || (/\.ss-/.test(subj) && sized)) hits.push(r.selectorText.trim().replace(/^&\s*/, '').slice(0, 60))
1040
+ }
1041
+ if (r.cssRules) walk(r.cssRules)
1042
+ } }
1043
+ walk(rules)
1044
+ }
1045
+ for (const sel of [...new Set(hits)].slice(0, 6)) out.push(`kit override: ${sel} is restyled by the example's own CSS (position, size or spacing); a kit part's geometry is the kit's. Style your own class, pass the part's props, or set its tokens`)
1046
+ return out
1047
+ }
1048
+
1049
+ // Clipped glyph: an icon whose drawing runs past its own viewBox (or whose
1050
+ // box clips it), so a stroke is cut off
1051
+ function detectClippedGlyph({ root }) {
1052
+ const out = []
1053
+ for (const svg of root.querySelectorAll('svg[viewBox]')) {
1054
+ if (svg.closest('.ss-cursor, .ss-keys, .ss-kb, .ss-chart, .ss-connector, .ss-check, .ss-spinner, .ss-icon, .ss-window__bar, .ss-phone, .ss-toggle')) continue
1055
+ const r = svg.getBoundingClientRect()
1056
+ if (r.width < 8 || r.width > 160 || r.height > 160) continue
1057
+ let box
1058
+ try { box = svg.getBBox() } catch { continue }
1059
+ const vb = (svg.getAttribute('viewBox') || '').split(/[\s,]+/).map(Number)
1060
+ if (vb.length !== 4 || !box.width) continue
1061
+ const over = Math.max(vb[0] - box.x, vb[1] - box.y, (box.x + box.width) - (vb[0] + vb[2]), (box.y + box.height) - (vb[1] + vb[3]))
1062
+ const stroke = parseFloat(getComputedStyle(svg.querySelector('path, circle, rect, line, polyline, polygon') || svg).strokeWidth) || 0
1063
+ if (over > stroke / 2 + 0.25) out.push(`clipped glyph: ${labelOf(svg.parentElement ?? svg).split(' "')[0]} > svg draws ${over.toFixed(1)} units past its viewBox, so a stroke is cut off; fit the drawing inside the box`)
1064
+ }
1065
+ return out
1066
+ }
1067
+
1068
+ // Unsized text: words inside a window that took the stage's 16px baseline
1069
+ // because the demo never sized them. Found by nudging the baseline for one
1070
+ // read: text that follows it was never given a size of its own
1071
+ function detectUnsizedText({ root }) {
1072
+ const out = []
1073
+ const els = [...root.querySelectorAll('.ss-window *')].filter((n) => !n.closest('svg, .ss-cursor, .ss-keys, .ss-kb, .ss-window__bar') && [...n.childNodes].some((t) => t.nodeType === 3 && t.textContent.trim()) && painted(n, root))
1074
+ const before = els.map((n) => getComputedStyle(n).fontSize)
1075
+ const was = root.style.fontSize
1076
+ root.style.fontSize = '17px'
1077
+ const after = els.map((n) => getComputedStyle(n).fontSize)
1078
+ root.style.fontSize = was
1079
+ const seen = new Set()
1080
+ els.forEach((n, i) => {
1081
+ if (before[i] !== '16px' || after[i] !== '17px') return
1082
+ const label = labelOf(n)
1083
+ if (seen.has(label)) return
1084
+ seen.add(label)
1085
+ out.push(`unsized text: ${label} is 16px only because nothing sized it, the stage's baseline, not the product's; app text inside a window is about 12 to 14px, so give it a size`)
1086
+ })
1087
+ return out
1088
+ }
1089
+
1090
+ // Unit wrapped: a big number whose short unit (ft, ms, %) fell to its own
1091
+ // line, because the number was sized for the tile without it
1092
+ function detectUnitWrapped({ root }) {
1093
+ const out = []
1094
+ for (const n of root.querySelectorAll('*')) {
1095
+ if (n.closest('svg, .ss-cursor, .ss-keys, .ss-kb, .ss-count, .ss-roll') || !painted(n, root)) continue
1096
+ if (parseFloat(getComputedStyle(n).fontSize) < 28) continue
1097
+ const own = [...n.childNodes].find((t) => t.nodeType === 3 && t.textContent.trim().length >= 2)
1098
+ if (!own) continue
1099
+ for (const u of n.children) {
1100
+ const txt = u.textContent.trim()
1101
+ if (!txt || txt.length > 4 || u.querySelector('*')) continue
1102
+ const range = document.createRange(); range.selectNodeContents(own)
1103
+ const num = range.getBoundingClientRect(), ur = u.getBoundingClientRect()
1104
+ if (ur.width < 2 || ur.height < 2) continue
1105
+ if (ur.top >= num.bottom - 2) out.push(`unit wrapped: "${txt}" fell under ${labelOf(n)}; a stat is one line, so size the number to its tile with the unit on (or put the unit in the lead line) and keep the pair nowrap`)
1106
+ }
1107
+ }
1108
+ return out
1109
+ }
1110
+
1111
+ // Onion skin: two siblings with a translucent fill overlapping, so the
1112
+ // overlap paints darker (avatars in a pile, chips, cards)
1113
+ function detectOnionSkin({ root }) {
1114
+ const out = []
1115
+ const alphaFill = (d) => alphaOf(getComputedStyle(d).backgroundColor, 0)
1116
+ const reported = new Set()
1117
+ for (const n of root.querySelectorAll('*')) {
1118
+ if (n.closest('svg, .ss-cursor, .ss-keys, .ss-kb, .ss-facepile') || !painted(n, root)) continue
1119
+ // Judged at rest: a bar fading out over the one fading in is a crossfade, not a fill
1120
+ const settled = (d) => fadeThrough(d, root) >= 0.95 && !d.getAnimations({ subtree: true }).some((x) => x.playState === 'running')
1121
+ const kids = [...n.children].filter((d) => { const a = alphaFill(d); return a > 0.02 && a < 0.98 && !d.closest('.ss-facepile') && settled(d) })
1122
+ for (let i = 0; i < kids.length; i++) for (let j = i + 1; j < kids.length; j++) {
1123
+ const a = kids[i].getBoundingClientRect(), b = kids[j].getBoundingClientRect()
1124
+ if (a.width < 6 || b.width < 6) continue
1125
+ const ox = Math.min(a.right, b.right) - Math.max(a.left, b.left), oy = Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top)
1126
+ if (ox > 2 && oy > 2 && !reported.has(kids[j])) {
1127
+ reported.add(kids[j])
1128
+ out.push(`onion skin: ${labelOf(kids[i])} and ${labelOf(kids[j])} overlap with a see-through fill, so the overlap paints darker; a pile of faces is the kit's Facepile, and anything else that overlaps takes an opaque fill (--ss-fill)`)
1129
+ }
1130
+ }
1131
+ }
1132
+ return out
1133
+ }
1134
+
1135
+ // Tight mark: a small dot (an unread marker, a status) jammed against the
1136
+ // box beside it, or sitting outside the row that owns it
1137
+ function detectTightMark({ root }) {
1138
+ const out = []
1139
+ for (const n of root.querySelectorAll('*')) {
1140
+ if (n.children.length || n.closest('.ss-cursor, .ss-keys, .ss-kb, svg, .ss-check, .ss-spinner, .ss-avatar')) continue
1141
+ const r = n.getBoundingClientRect()
1142
+ if (r.width < 4 || r.width > 10 || r.height < 4 || r.height > 10 || Math.abs(r.width - r.height) > 1) continue
1143
+ const cs = getComputedStyle(n)
1144
+ if (parseFloat(cs.borderRadius) < r.width / 2 - 0.5 || alphaOf(cs.backgroundColor, 0) < 0.5 || !painted(n, root)) continue
1145
+ if (n.closest('.ss-chart, .ss-menu, .ss-badge, .ss-toast, .ss-notification, .ss-phone__glyphs, .ss-segmented, .ss-toggle, .ss-window__bar, .ss-window__lights, .ss-seg')) continue
1146
+ const row = n.parentElement
1147
+ if (!row) continue
1148
+ for (const c of row.children) {
1149
+ if (c === n || c.closest('.ss-cursor')) continue
1150
+ const cr = c.getBoundingClientRect()
1151
+ if (cr.width < 8 || cr.height < 8 || !painted(c, root)) continue
1152
+ const vert = Math.min(r.bottom, cr.bottom) - Math.max(r.top, cr.top)
1153
+ if (vert <= 0) continue
1154
+ const gap = Math.max(cr.left - r.right, r.left - cr.right)
1155
+ if (gap >= 0 && gap < 5) { out.push(`tight mark: ${labelOf(n)} is ${gap.toFixed(1)}px from ${labelOf(c)}; a status dot keeps 6px or more from the avatar or text beside it`); break }
1156
+ }
1157
+ const rr = row.getBoundingClientRect()
1158
+ if (visible(row) && (r.left < rr.left + 1 || r.right > rr.right - 1)) out.push(`tight mark: ${labelOf(n)} sits outside ${labelOf(row)}'s fill; a status dot stays inside the row's own inset`)
1159
+ }
1160
+ return out
1161
+ }
1162
+
1163
+ // Row rhythm: a stack of lines (a name over a subtitle) repeated down a
1164
+ // list, some real text and some placeholder bars. Every copy leaves the
1165
+ // same air between its marks, or the real row and the skeletons beside it
1166
+ // read as two different designs.
1167
+ function detectRowRhythm({ root, scale }) {
1168
+ const out = []
1169
+ const stacks = new Map()
1170
+ for (const n of root.querySelectorAll('*')) {
1171
+ const kids = [...n.children].filter((c) => { const b = c.getBoundingClientRect(); return b.height >= 1 && Number(getComputedStyle(c).opacity) > 0 })
1172
+ if (kids.length < 2 || !n.className || typeof n.className !== 'string') continue
1173
+ // Its own scale (inside a Camera's zoom, a scaled phone)
1174
+ const k = n.offsetWidth ? n.getBoundingClientRect().width / n.offsetWidth : scale
1175
+ // Lines, not boxes: a column of cards, a card's head over its plot, is
1176
+ // a stack of surfaces; only a text line or a bar (or a row holding
1177
+ // bars, judged by the bars) counts as a line
1178
+ const line = (c) => {
1179
+ if (c.classList.contains('ss-bar')) return c.getBoundingClientRect()
1180
+ if (c.children.length === 0 && (c.textContent || '').trim()) return c.getBoundingClientRect()
1181
+ if (surface(getComputedStyle(c)) || (c.textContent || '').trim()) return null
1182
+ const bars = [...c.querySelectorAll('.ss-bar')].map((x) => x.getBoundingClientRect())
1183
+ if (!bars.length) return null
1184
+ return { left: Math.min(...bars.map((x) => x.left)), top: Math.min(...bars.map((x) => x.top)), bottom: Math.max(...bars.map((x) => x.bottom)), height: Math.max(...bars.map((x) => x.bottom)) - Math.min(...bars.map((x) => x.top)) }
1185
+ }
1186
+ const a = line(kids[0])
1187
+ const b = line(kids[1])
1188
+ if (!a || !b || a.height > 24 * k || b.height > 24 * k) continue
1189
+ // Stacked and left-aligned, the way a block of lines sits
1190
+ if (Math.abs(a.left - b.left) > 1 || b.top < a.bottom - 1) continue
1191
+ const key = n.className.split(' ')[0]
1192
+ // Judged on the ink, not the boxes: a bar is all ink, a line of text
1193
+ // about its cap height around the line's middle. Equal pitch is wrong:
1194
+ // thin bars at a text line's pitch leave a much wider gap
1195
+ const ink = (c, r) => {
1196
+ if ((c.textContent || '').trim()) { const h = parseFloat(getComputedStyle(c).fontSize) * 0.36 * k; const m = r.top + r.height / 2; return { t: m - h, b: m + h } }
1197
+ return { t: r.top, b: r.bottom }
1198
+ }
1199
+ const gap = (ink(kids[1], b).t - ink(kids[0], a).b) / k
1200
+ stacks.set(key, [...(stacks.get(key) ?? []), { gap, real: (n.textContent || '').trim().length > 0 }])
1201
+ }
1202
+ for (const [key, list] of stacks) {
1203
+ if (list.length < 3 || !list.some((x) => x.real) || list.every((x) => x.real)) continue
1204
+ const real = list.filter((x) => x.real).map((x) => x.gap)
1205
+ const fake = list.filter((x) => !x.real).map((x) => x.gap)
1206
+ const r = real.reduce((s, v) => s + v, 0) / real.length
1207
+ const f = fake.reduce((s, v) => s + v, 0) / fake.length
1208
+ if (Math.abs(r - f) > 1.5) out.push(`tight lines: .${key} leaves ${Math.round(r)}px between the lines' ink in a real row and ${Math.round(f)}px between the bars in a placeholder row; match the air between the marks, not the line pitch`)
1209
+ }
1210
+ return out
1211
+ }
1212
+
1213
+ // Half-pixel glyphs: an icon centered in a box whose spare room is odd sits
1214
+ // on a half pixel. While the box scales it draws there; when the motion
1215
+ // ends it is snapped to a whole pixel and hops sideways (an 11px X in a
1216
+ // 20px circle). Only boxes that scale or transition, where the hop shows.
1217
+ function detectHalfPixelGlyph({ root }) {
1218
+ const out = []
1219
+ for (const g of root.querySelectorAll('svg')) {
1220
+ if (g.closest('.ss-cursor, .ss-keys') || g.parentElement?.closest('svg')) continue
1221
+ const box = g.parentElement
1222
+ if (!box || !shown(g, root)) continue
1223
+ const moves = (c) => (c.transitionDuration.split(',').some((d) => parseFloat(d) > 0) && /all|transform|scale/.test(c.transitionProperty)) || c.animationName !== 'none'
1224
+ let host = null
1225
+ for (let a = box, i = 0; a && i < 3 && a !== root; a = a.parentElement, i++) if (moves(getComputedStyle(a))) { host = a; break }
1226
+ if (!host) continue
1227
+ const bc = getComputedStyle(box)
1228
+ if (!/flex|grid/.test(bc.display)) continue
1229
+ const gw = g.width?.baseVal?.value || g.getBoundingClientRect().width
1230
+ const gh = g.height?.baseVal?.value || g.getBoundingClientRect().height
1231
+ const iw = box.clientWidth - parseFloat(bc.paddingLeft) - parseFloat(bc.paddingRight)
1232
+ const ih = box.clientHeight - parseFloat(bc.paddingTop) - parseFloat(bc.paddingBottom)
1233
+ const odd = (room) => Number.isInteger(room) && Math.abs(room) % 2 === 1
1234
+ if (!Number.isInteger(gw) || !Number.isInteger(iw)) continue
1235
+ if (odd(iw - gw) || odd(ih - gh)) {
1236
+ const even = gw % 2 ? `${gw - 1} or ${gw + 1}px` : `${gw}px in an even box`
1237
+ out.push(`half-pixel glyph: a ${gw}px ${tagOf(g)} centered in the ${iw}x${ih} ${tagOf(box)} sits on a half pixel, so it draws there while ${tagOf(host)} moves and hops sideways when it settles; size it ${even} (even inside even)`)
1238
+ }
1239
+ }
1240
+ return out
1241
+ }
1242
+
1243
+ // Squeezed boxes: a fixed-size flex item (an icon button, a chip) that its
1244
+ // row shrinks narrower than it was set. Measured by letting it not shrink.
1245
+ function detectSqueezed({ root }) {
1246
+ const out = []
1247
+ for (const n of root.querySelectorAll('*')) {
1248
+ if (n.closest('.ss-cursor, .ss-keys, .ss-kb, svg')) continue
1249
+ const p = n.parentElement
1250
+ if (!p || !/flex/.test(getComputedStyle(p).display)) continue
1251
+ const cs = getComputedStyle(n)
1252
+ // A Bar line gives way in a narrow row by design (Bar shrink)
1253
+ if (cs.flexShrink === '0' || cs.position === 'absolute' || !hasSurface(cs) || !shown(n, root) || n.matches('.ss-bar[data-shrink]')) continue
1254
+ if ((n.textContent || '').trim().length > 3) continue
1255
+ const now = n.getBoundingClientRect()
1256
+ if (now.width < 8 || now.width > 120) continue
1257
+ const was = n.style.flexShrink
1258
+ n.style.flexShrink = '0'
1259
+ const full = n.getBoundingClientRect().width
1260
+ n.style.flexShrink = was
1261
+ if (full - now.width >= 1.5) out.push(`squeezed: ${tagOf(n)} is set ${Math.round(full)}px wide but its flex row shrinks it to ${Math.round(now.width)}px${Math.abs(full - now.height) < 1.5 ? ', narrower than it is tall' : ''}; give it flex: none`)
1262
+ }
1263
+ return out
1264
+ }
1265
+
1266
+ // ---- Framing --------------------------------------------------------------
1267
+
1268
+ // What the framing checks share: the crop the viewer actually sees (the
1269
+ // stage, cut again by anything around it that hides overflow), what is in
1270
+ // flight, and the hero (the largest window or phone)
1271
+ function frameContext(ctx) {
1272
+ const { root, S, specimen } = ctx
1273
+ const V = { left: S.left, top: S.top, right: S.right, bottom: S.bottom }
1274
+ for (let a = root.parentElement; a && a !== document.documentElement; a = a.parentElement) {
1275
+ const o = getComputedStyle(a)
1276
+ if (o.overflowX === 'visible' && o.overflowY === 'visible') continue
1277
+ const c = a.getBoundingClientRect()
1278
+ if (o.overflowX !== 'visible') { V.left = Math.max(V.left, c.left); V.right = Math.min(V.right, c.right) }
1279
+ if (o.overflowY !== 'visible') { V.top = Math.max(V.top, c.top); V.bottom = Math.min(V.bottom, c.bottom) }
1280
+ }
1281
+ // Running transitions and animations: a box on its way in (a satellite
1282
+ // rising into place) is judged where it settles, not in flight
1283
+ const busy = new Set(document.getAnimations().filter((x) => x.playState === 'running').map((x) => x.effect && x.effect.target).filter(Boolean))
1284
+ // A receded window (faded back while another comes forward) is still the
1285
+ // hero: the window over it is a satellite
1286
+ const heroes = [...root.querySelectorAll('.ss-window, .ss-phone')].filter((w) => !w.parentElement.closest('.ss-window, .ss-phone') && (shown(w, root) || w.hasAttribute('data-receded')))
1287
+ const hero = specimen ? null : heroes.sort((x, y) => shownArea(y.getBoundingClientRect(), V) - shownArea(x.getBoundingClientRect(), V))[0]
1288
+ return { ...ctx, V, busy, hero, gutter: null }
1289
+ }
1290
+
1291
+ // A box cut by its own clipping ancestors inside the stage (a scrolling
1292
+ // list, a terminal hiding its lower lines): what is left is what the
1293
+ // stage's crop can cut. Null when nothing of it shows.
1294
+ function ownClip(n, r0, root) {
1295
+ const r = { left: r0.left, right: r0.right, top: r0.top, bottom: r0.bottom, width: r0.width, height: r0.height }
1296
+ for (let a = n.parentElement; a && a !== root; a = a.parentElement) {
1297
+ const o = getComputedStyle(a)
1298
+ if (o.overflowX === 'visible' && o.overflowY === 'visible') continue
1299
+ const c = a.getBoundingClientRect()
1300
+ if (o.overflowX !== 'visible') { r.left = Math.max(r.left, c.left); r.right = Math.min(r.right, c.right) }
1301
+ if (o.overflowY !== 'visible') { r.top = Math.max(r.top, c.top); r.bottom = Math.min(r.bottom, c.bottom) }
1302
+ }
1303
+ return r.right - r.left < 2 || r.bottom - r.top < 2 ? null : r
1304
+ }
1305
+ function animating(n, busy, root) { for (let a = n; a && a !== root; a = a.parentElement) if (busy.has(a)) return true; return false }
1306
+ function shownArea(r, V) { return Math.max(0, Math.min(r.right, V.right) - Math.max(r.left, V.left)) * Math.max(0, Math.min(r.bottom, V.bottom) - Math.max(r.top, V.top)) }
1307
+ // A satellite: an absolute surface with its own shadow, or a phone (its
1308
+ // positioned wrapper carries no shadow of its own)
1309
+ function satellite(n, root) {
1310
+ if (!shown(n, root)) return false
1311
+ if (n.classList?.contains('ss-phone')) return true
1312
+ const c = getComputedStyle(n)
1313
+ return c.position === 'absolute' && !!c.boxShadow && c.boxShadow !== 'none'
1314
+ }
1315
+
1316
+ // Framing, judged in the visible crop. The hero: whole, with even margins;
1317
+ // or bled off the right and bottom only (a corner bleed) with the same
1318
+ // gutter above as to its left; or a centered phone bled off the bottom
1319
+ // only, even at the sides. Returns the findings and the gutter the rest of
1320
+ // the framing checks measure from (null when the hero sets none).
1321
+ // 'SAT_SIDE' in the findings marks a satellite straddling the hero's side.
1322
+ function detectHeroFraming({ root, V, busy, hero, zoomView }) {
1323
+ const out = []
1324
+ let gutter = null
1325
+ // Twin satellites: two of about one width straddling the same hero edge read as a stack of cards
1326
+ const twinSatellites = (edge) => {
1327
+ if (!hero) return
1328
+ const sats = [...root.querySelectorAll('*')].filter((n) => !hero.contains(n) && !n.contains(hero) && !n.closest('.ss-cursor, .ss-keys, .ss-kb, svg') && satellite(n, root) && !n.classList.contains('ss-phone'))
1329
+ const crossing = sats.filter((n) => { const b = n.getBoundingClientRect(); return b.width >= 120 && b.left < edge - 4 && b.right > edge + 4 })
1330
+ for (let i = 0; i < crossing.length; i++) for (let j = i + 1; j < crossing.length; j++) {
1331
+ if (crossing[i].contains(crossing[j]) || crossing[j].contains(crossing[i])) continue
1332
+ const a = crossing[i].getBoundingClientRect(), b = crossing[j].getBoundingClientRect()
1333
+ if (Math.abs(a.width - b.width) < Math.max(a.width, b.width) * 0.25 && Math.abs(a.left - b.left) < 40) { out.push(`framing: twin satellites: ${labelOf(crossing[i])} and ${labelOf(crossing[j])} are two cards of one width on the same hero edge, a stack; a second satellite is a different kind and size (a small system banner, a chip, an annotation with a connector), or one of them goes`); return }
1334
+ }
1335
+ }
1336
+ if (!zoomView && hero && !animating(hero, busy, root) && shownArea(hero.getBoundingClientRect(), V) > 0.2 * (V.right - V.left) * (V.bottom - V.top)) {
1337
+ const r = hero.getBoundingClientRect()
1338
+ const m = { left: r.left - V.left, top: r.top - V.top, right: V.right - r.right, bottom: V.bottom - r.bottom }
1339
+ const bled = Object.keys(m).filter((k) => m[k] < -1)
1340
+ const name = tagOf(hero)
1341
+ let wrong = bled.filter((k) => k === 'left' || k === 'top')
1342
+ // A phone may run off the top when the crop falls in its content: its
1343
+ // status bar is gone with it (framing.md, Phones)
1344
+ if (hero.classList?.contains('ss-phone') && wrong.includes('top')) {
1345
+ const status = hero.querySelector('.ss-phone__status, .ss-phone__time, .ss-island, .ss-phone__island')
1346
+ if (!status || status.getBoundingClientRect().bottom <= V.top + 1) wrong = wrong.filter((k) => k !== 'top')
1347
+ }
1348
+ if (wrong.length) out.push(`framing: ${name} is cut on the ${wrong.join(' and ')} (${wrong.map((k) => `${px(-m[k])}px`).join(', ')}); the top-left holds the chrome that says what this is, so a window bleeds off the right and bottom only`)
1349
+ // Near misses and slivers: an edge just short of the crop, or just past
1350
+ // it, reads as a mistake. Pull it in to a full gutter, or run it well past.
1351
+ const g0 = Math.max(m.top, 16)
1352
+ for (const k of ['right', 'bottom']) {
1353
+ if (m[k] >= 0.5 && m[k] < g0 * 0.75) out.push(`framing: ${name} ends ${px(m[k])}px short of the ${k} edge; give it a full gutter (${px(g0)}px) or run it well past the edge so it is clearly masked`)
1354
+ if (m[k] < -1 && m[k] > -24) out.push(`framing: ${name} runs only ${px(-m[k])}px past the ${k} edge, which reads as a mistake, not a bleed; pull it inside or run it well past`)
1355
+ }
1356
+ // Proportions: a desktop window reads as its device, landscape. Whole,
1357
+ // it is clearly wider than tall; bled, what shows is at least square.
1358
+ // A chromeless Window (a document, an invoice) is a page, and a page is portrait
1359
+ if (hero.classList.contains('ss-window') && [...hero.querySelectorAll('.ss-window__lights')].some((l) => l.getBoundingClientRect().width > 0 && shown(l, root))) {
1360
+ const vw = Math.min(r.right, V.right) - Math.max(r.left, V.left)
1361
+ const vh = Math.min(r.bottom, V.bottom) - Math.max(r.top, V.top)
1362
+ const whole = !bled.length
1363
+ if ((whole && vw / vh < 1.25) || (!whole && vw / vh < 1)) out.push(`framing: ${name} shows ${px(vw)}x${px(vh)}, ${whole ? 'nearly square' : 'narrower than tall'} for a desktop window; change the crop (bleed it) or the layout rather than squash the app`)
1364
+ }
1365
+ if (!bled.length) {
1366
+ gutter = Math.min(m.left, m.top)
1367
+ // A hero's window carries the frame: it bleeds off an edge or fills
1368
+ // the stage. Whole, centered, with air on four sides, it floats
1369
+ const stageW = V.right - V.left, stageH = V.bottom - V.top
1370
+ if (!root.querySelector('[data-specimen], [data-unframed]') && !root.closest('[data-specimen], [data-unframed]') && stageW >= 560 && Math.min(m.left, m.right, m.top, m.bottom) >= 12 && (r.right - r.left) * (r.bottom - r.top) < stageW * stageH * 0.82) out.push(`framing: ${name} floats whole in the stage with ${px(m.left)}/${px(m.right)}/${px(m.top)}/${px(m.bottom)}px of air around it; a hero's window bleeds off one or two edges with one gutter, or fills the stage, so the product carries the frame (see examples/hero-demo, examples/chat-diff)`)
1371
+ if (Math.abs(m.left - m.right) > 2 || Math.abs(m.top - m.bottom) > 2) out.push(`framing: ${name} is whole but off center (left ${px(m.left)}, right ${px(m.right)}, top ${px(m.top)}, bottom ${px(m.bottom)}px in the visible crop); a whole window gets even margins`)
1372
+ } else if (!wrong.length && bled.includes('right')) {
1373
+ gutter = m.top
1374
+ // A satellite living in the left column (straddling the window's
1375
+ // left edge, at any point in the loop) is why that column is wider:
1376
+ // noted here, and the equal-gutter line is dropped for the whole film
1377
+ const straddles = [...root.querySelectorAll('*')].some((n) => {
1378
+ if (hero.contains(n) || n.contains(hero) || n.closest('.ss-cursor, .ss-keys, .ss-kb, svg')) return false
1379
+ if (!satellite(n, root)) return false
1380
+ const b = n.getBoundingClientRect()
1381
+ return b.left < r.left - 4 && b.right > r.left + 4 && b.bottom > r.top && b.top < V.bottom
1382
+ })
1383
+ if (straddles) out.push('SAT_SIDE')
1384
+ twinSatellites(r.left)
1385
+ // A hero inside one cell of a grid (a bento tile among tiles) takes the tile's own padding, not the stage's gutter
1386
+ const cell = hero.closest('[data-crop]')
1387
+ const inTile = !!cell && cell !== root && !!cell.parentElement && [...cell.parentElement.children].filter((c) => c.hasAttribute('data-crop')).length >= 2
1388
+ if (!inTile && Math.abs(m.top - m.left) > 2) out.push(`framing: corner bleed with a ${px(m.top)}px gutter above ${name} but ${px(m.left)}px to its left, as seen in the final crop; one gutter, the same on both (check any wrapper that trims the stage)`)
1389
+ } else if (!wrong.length) {
1390
+ gutter = m.top
1391
+ // The same waiver for a satellite on either side of a window bled off
1392
+ // the bottom (a phone beside a dashboard)
1393
+ const straddles = [...root.querySelectorAll('*')].some((n) => {
1394
+ if (hero.contains(n) || n.contains(hero) || n.closest('.ss-cursor, .ss-keys, .ss-kb, svg')) return false
1395
+ if (!satellite(n, root)) return false
1396
+ const b = n.getBoundingClientRect()
1397
+ // Only on the side with the wider column: that is what it explains
1398
+ const edge = m.left > m.right ? r.left : r.right
1399
+ return b.left < edge - 4 && b.right > edge + 4 && b.bottom > r.top && b.top < V.bottom
1400
+ })
1401
+ if (straddles) out.push('SAT_SIDE')
1402
+ twinSatellites(m.left > m.right ? r.left : r.right)
1403
+ if (Math.abs(m.left - m.right) > 2) out.push(`framing: ${name} runs off the bottom but sits off center (left ${px(m.left)}, right ${px(m.right)}px); bled off the bottom alone it is centered with equal side gutters. Run it off the right as well (a corner bleed, the default), center it, or fill the wider column with a satellite straddling that edge (a device pair)`)
1404
+ }
1405
+ }
1406
+ return { out, gutter }
1407
+ }
1408
+
1409
+ // Satellites: other raised surfaces near an edge sit one gutter from it
1410
+ function detectSatelliteGutters({ root, V, busy, hero, gutter }) {
1411
+ const out = []
1412
+ if (!(gutter !== null && gutter > 4)) return out
1413
+ for (const n of root.querySelectorAll('*')) {
1414
+ if (n === hero || hero?.contains(n) || n.contains(hero) || n.closest('.ss-cursor, .ss-keys, .ss-kb, svg, .ss-popover')) continue
1415
+ const cs = getComputedStyle(n)
1416
+ if (cs.position !== 'absolute' || !cs.boxShadow || cs.boxShadow === 'none' || !shown(n, root) || animating(n, busy, root)) continue
1417
+ const r = n.getBoundingClientRect()
1418
+ if (r.width * r.height < 0.03 * (V.right - V.left) * (V.bottom - V.top)) continue
1419
+ const d = { left: r.left - V.left, top: r.top - V.top, right: V.right - r.right, bottom: V.bottom - r.bottom }
1420
+ const [edge, dist] = Object.entries(d).filter(([, v]) => v >= 0).sort((x, y) => x[1] - y[1])[0] ?? []
1421
+ if (edge && dist < gutter * 1.6 && Math.abs(dist - gutter) > 2) out.push(`framing: satellite ${tagOf(n)} sits ${px(dist)}px from the ${edge} edge where the gutter is ${px(gutter)}px; satellites keep the one gutter`)
1422
+ }
1423
+ return out
1424
+ }
1425
+
1426
+ // Other boxes (cards, panels, a dashed frame) obey the same edges: a
1427
+ // full gutter in, or well past. Contents of the hero bleed with it.
1428
+ // Pushed in, everything round the focus is cropped by design.
1429
+ function detectBoxEdges({ root, V, busy, hero, gutter, zoomView }) {
1430
+ const out = []
1431
+ if (zoomView) return out
1432
+ const near = gutter && gutter > 4 ? gutter * 0.75 : 12
1433
+ for (const n of root.querySelectorAll('*')) {
1434
+ if (n === hero || hero?.contains(n) || n.contains(hero) || n.closest('.ss-cursor, .ss-keys, .ss-kb, svg, .ss-popover, [data-crop]')) continue
1435
+ const cs = getComputedStyle(n)
1436
+ if (!(hasSurface(cs) || cs.borderTopStyle === 'dashed') || !shown(n, root) || animating(n, busy, root)) continue
1437
+ const r = n.getBoundingClientRect()
1438
+ if (r.width * r.height < 0.03 * (V.right - V.left) * (V.bottom - V.top)) continue
1439
+ if (n.parentElement && n.parentElement !== root && n.parentElement.closest('[class]') && hasSurface(getComputedStyle(n.parentElement))) continue
1440
+ const d = { left: r.left - V.left, top: r.top - V.top, right: V.right - r.right, bottom: V.bottom - r.bottom }
1441
+ for (const [k, v] of Object.entries(d)) {
1442
+ if (v >= 0.5 && v < near) out.push(`framing: ${tagOf(n)} ends ${px(v)}px short of the ${k} edge; give it a full gutter or run it well past so it is masked`)
1443
+ else if (v < -1 && v > -24) out.push(`framing: ${tagOf(n)} runs only ${px(-v)}px past the ${k} edge, a sliver that reads as a mistake; pull it inside or run it well past`)
1444
+ }
1445
+ }
1446
+ return out
1447
+ }
1448
+
1449
+ // A column bled off the right that shows only a sliver (a details pane
1450
+ // whose divider lands near the edge): too thin to read as UI, it reads
1451
+ // as a mistake. Show enough of it to read, or none.
1452
+ function detectSliverColumn({ root, V, busy, zoomView }) {
1453
+ const out = []
1454
+ if (zoomView) return out
1455
+ for (const n of root.querySelectorAll('*')) {
1456
+ if (n.closest('.ss-cursor, .ss-keys, .ss-kb, svg, [data-crop], .ss-count') || !shown(n, root) || animating(n, busy, root)) continue
1457
+ const cs = getComputedStyle(n)
1458
+ if (!(hasSurface(cs) || parseFloat(cs.borderLeftWidth) > 0)) continue
1459
+ const r = n.getBoundingClientRect()
1460
+ const vis = V.right - r.left
1461
+ if (r.height < 0.3 * (V.bottom - V.top) || r.right < V.right + 1 || vis < 1 || r.width < vis + 8) continue
1462
+ const k = n.offsetWidth ? r.width / n.offsetWidth : 1
1463
+ if (vis / k < 56) { out.push(`framing: only ${px(vis / k)}px of ${tagOf(n)} shows at the right edge, a sliver too thin to read as UI; move its edge in so a readable part of it shows (a third or more), or past the crop so none does`); break }
1464
+ }
1465
+ return out
1466
+ }
1467
+
1468
+ // What the story opens or brings in (a popover, menu, toast, tooltip,
1469
+ // sheet, notification) sits wholly inside the stage, a gutter from every
1470
+ // edge, on every frame it shows. Place the trigger so it has room, or
1471
+ // open it the other way; never let the crop take it.
1472
+ function detectOverlayRoom({ root, S, V, hero, gutter, zoomView }) {
1473
+ const out = []
1474
+ const OVERLAY = '.ss-popover, .ss-menu, .ss-toast, .ss-notification, [role=menu], [role=tooltip], [role=dialog], [role=status], [data-overlay]'
1475
+ // Pushed in, the edges feather: clear of the feather as well
1476
+ const room = Math.max(gutter && gutter > 4 ? gutter : 16, zoomView ? (Number(zoomView.dataset.feather) || 0) * (S.width / root.offsetWidth || 1) + 4 : 0)
1477
+ for (const n of root.querySelectorAll(OVERLAY)) {
1478
+ if (n.parentElement?.closest(OVERLAY) || !shown(n, root)) continue
1479
+ const r = n.getBoundingClientRect()
1480
+ if (r.width < 8 || r.height < 8) continue
1481
+ const d = { top: r.top - V.top, left: r.left - V.left, right: V.right - r.right, bottom: V.bottom - r.bottom }
1482
+ const [edge, v] = Object.entries(d).sort((x, y) => x[1] - y[1])[0]
1483
+ // Inside a window that bleeds through that edge, the popover needs air, not the hero's gutter
1484
+ const hr = hero ? hero.getBoundingClientRect() : null
1485
+ const heroBleeds = hr && (edge === 'top' ? hr.top < V.top - 2 : edge === 'left' ? hr.left < V.left - 2 : edge === 'right' ? hr.right > V.right + 2 : hr.bottom > V.bottom + 2)
1486
+ const need = heroBleeds && hero.contains(n) ? 16 : room
1487
+ if (v < need - 2) out.push(`framing: ${tagOf(n)} opens ${v < 0 ? 'past' : 'within a gutter of'} the stage's ${edge} edge; what the story opens sits wholly inside, a gutter (${px(need)}px) clear, so place its trigger where it has room or open it the other way`)
1488
+ // Keycaps showing over what is open (a short stage, a menu reaching the bottom)
1489
+ for (const k of root.querySelectorAll('.ss-keys')) {
1490
+ if (Number(getComputedStyle(k).opacity) < 0.5) continue
1491
+ for (const c of k.children) {
1492
+ const b = c.getBoundingClientRect()
1493
+ if (b.width < 4 || !(b.left < r.right + 6 && b.right > r.left - 6 && b.top < r.bottom + 6 && b.bottom > r.top - 6)) continue
1494
+ // Riding the popover's bottom edge (center on or below it) is a placement; inside it is a collision
1495
+ if ((b.top + b.bottom) / 2 >= r.bottom - 2) continue
1496
+ out.push(`framing: keycaps overlap ${tagOf(n)}; move them clear (Stage keys="top", "bottom-left" or "bottom-right") or give the stage the room`)
1497
+ break
1498
+ }
1499
+ }
1500
+ }
1501
+ return out
1502
+ }
1503
+
1504
+ // Text never touches a neighboring box. A label beside its field, a
1505
+ // value beside its icon: a fixed gap holds them apart, never leftover
1506
+ // space (space-between with no gap, a full row, the label 1px off).
1507
+ // A parent with its own gap is the fixed gap, so only overlaps count there.
1508
+ function detectTouchingText({ root }) {
1509
+ const out = []
1510
+ for (const n of root.querySelectorAll('*')) {
1511
+ if (n.closest('.ss-cursor, .ss-keys, .ss-kb, svg')) continue
1512
+ const texts = [...n.childNodes].filter((c) => c.nodeType === 3 && c.textContent.trim())
1513
+ if (!texts.length || !shown(n, root)) continue
1514
+ const range = document.createRange()
1515
+ range.setStart(texts[0], 0)
1516
+ range.setEnd(texts[texts.length - 1], texts[texts.length - 1].length)
1517
+ let t = range.getBoundingClientRect()
1518
+ // Text cut by its own box (an ellipsis) only paints inside that box
1519
+ const ns = getComputedStyle(n)
1520
+ if (ns.overflowX !== 'visible') {
1521
+ const nb = n.getBoundingClientRect()
1522
+ t = new DOMRect(Math.max(t.left, nb.left), t.top, Math.min(t.right, nb.right) - Math.max(t.left, nb.left), t.height)
1523
+ }
1524
+ if (t.width < 2) continue
1525
+ const p = n.parentElement
1526
+ const pairs = [...(p ? [...p.children].filter((c) => c !== n).map((c) => [c, p]) : []), ...[...n.children].map((c) => [c, n])]
1527
+ for (const [c, holder] of pairs) {
1528
+ const cc = getComputedStyle(c)
1529
+ if (cc.display === 'inline' || cc.position === 'absolute' || c.closest('.ss-cursor') || !shown(c, root)) continue
1530
+ // Turning or scaled (a spinner): its drawn box swells past its slot,
1531
+ // so the slot is judged by the gap, not the ink
1532
+ if (cc.transform !== 'none' || c.getAnimations().some((x) => x.playState === 'running')) continue
1533
+ // A Roll's own pieces (the rolling part and the text around it) are one run of text
1534
+ if (n.closest('.ss-roll, .ss-count') && c.closest('.ss-roll, .ss-count')) continue
1535
+ // An empty cell (a gutter column with nothing in it on this line) paints nothing to touch
1536
+ if (!hasSurface(cc) && c.tagName.toLowerCase() !== 'svg' && !(c.textContent || '').trim() && !c.querySelector('svg, img, .ss-bar')) continue
1537
+ // A repeated set (a facepile, a row of chips) is spaced by design
1538
+ if (tagOf(c) === tagOf(n) && typeof n.className === 'string' && n.className) continue
1539
+ // A bare cell (a grid column, a span of words) is judged by its words,
1540
+ // a surface (a field, a chip) by its box
1541
+ let b = c.getBoundingClientRect()
1542
+ if (!hasSurface(cc) && c.tagName !== 'svg' && (c.textContent || '').trim()) {
1543
+ const rr = document.createRange()
1544
+ rr.selectNodeContents(c)
1545
+ b = rr.getBoundingClientRect()
1546
+ }
1547
+ if (b.width < 4 || b.height < 4 || c.contains(n)) continue
1548
+ // On one line: overlapping and centered alike (a big clock's glyph box
1549
+ // reaches up past the date above it without sharing its line)
1550
+ const sameLine = Math.min(t.bottom, b.bottom) - Math.max(t.top, b.top) > 0.5 * Math.min(t.height, b.height) && Math.abs((t.top + t.bottom) / 2 - (b.top + b.bottom) / 2) < 0.5 * Math.min(t.height, b.height)
1551
+ if (!sameLine) continue
1552
+ const d = b.left >= t.right - 1 ? b.left - t.right : t.left >= b.right - 1 ? t.left - b.right : -1
1553
+ const fixed = parseFloat(getComputedStyle(holder).columnGap) >= 4
1554
+ if (d < 5 && !(fixed && d >= 2)) out.push(`touching: ${tagOf(n)} "${n.textContent.trim().slice(0, 18)}" is ${d < 0 ? 'overlapping' : `${px(d)}px from`} ${tagOf(c)}; text never touches a neighboring box, so hold the pair apart with a fixed gap (gap: 8-12px), not leftover space`)
1555
+ }
1556
+ }
1557
+ return out
1558
+ }
1559
+
1560
+ // A ring drawn on a pseudo-element (a field's focus outline as its own
1561
+ // layer, so the text never moves) is invisible to the box checks: it is
1562
+ // measured here from the element and the pseudo's insets. It must sit in
1563
+ // space its field owns: never over a neighbor's words, and never past the
1564
+ // card it sits in.
1565
+ // A Draft moved so its typed words line up with the name above, which
1566
+ // leaves its box hanging past that column: the box's edge belongs on it
1567
+ function detectDraftHang({ root }) {
1568
+ const out = []
1569
+ for (const box of root.querySelectorAll('.ss-draft[data-editing] > .ss-draft__box')) {
1570
+ if (!visibleThrough(box, root)) continue
1571
+ const b = box.getBoundingClientRect()
1572
+ const words = box.querySelector('.ss-draft__typed, .ss-draft__ph')
1573
+ if (!words) continue
1574
+ const range = document.createRange()
1575
+ range.selectNodeContents(words)
1576
+ const w = [...range.getClientRects()].find((x) => x.width > 0) ?? words.getBoundingClientRect()
1577
+ let card = box.parentElement
1578
+ for (let i = 0; card && i < 8; i++, card = card.parentElement) {
1579
+ const cs = getComputedStyle(card)
1580
+ if (cs.boxShadow !== 'none' || (cs.backgroundColor !== 'rgba(0, 0, 0, 0)' && cs.backgroundColor !== 'transparent')) break
1581
+ }
1582
+ if (!card) continue
1583
+ const walk = document.createTreeWalker(card, NodeFilter.SHOW_TEXT)
1584
+ for (let t = walk.nextNode(); t; t = walk.nextNode()) {
1585
+ // Words, not an avatar's initial: a full-width box's words may happen to line up with that
1586
+ if (t.textContent.trim().length < 2 || box.contains(t) || t.parentElement.closest('.ss-avatar') || !visibleThrough(t.parentElement, root)) continue
1587
+ const r = document.createRange()
1588
+ r.selectNodeContents(t)
1589
+ const tr = r.getBoundingClientRect()
1590
+ if (tr.bottom > b.top + 1 || tr.width < 8) continue
1591
+ const hang = tr.left - b.left
1592
+ if (hang >= 1.5 && hang <= 24 && Math.abs(w.left - tr.left) <= 2) {
1593
+ out.push(`uneven inset: the Draft's box hangs ${Math.round(hang)}px left of the column "${t.textContent.trim().slice(0, 20)}" starts; put the Draft in that column (no margin shift while editing) so the box's edge sits on it and the words pad inside`)
1594
+ break
1595
+ }
1596
+ }
1597
+ }
1598
+ return out
1599
+ }
1600
+
1601
+ // A message or comment under its author's name (an avatar beside it): from the name's baseline
1602
+ // to the body's capitals at least the body's own size (the comment golds
1603
+ // sit at 1.1 to 1.5 times). A one-line preview in a list row (nowrap,
1604
+ // truncated) is a denser thing and stays with the tight stack check.
1605
+ function detectBylineGap({ root }) {
1606
+ const out = []
1607
+ const lines = (t) => { const r = document.createRange(); r.selectNodeContents(t); return [...r.getClientRects()].filter((x) => x.width > 0 && x.height > 0) }
1608
+ const texts = []
1609
+ const walk = document.createTreeWalker(root, NodeFilter.SHOW_TEXT)
1610
+ for (let t = walk.nextNode(); t; t = walk.nextNode()) {
1611
+ const el = t.parentElement
1612
+ if (!el || t.textContent.trim().length < 2 || el.closest('.ss-cursor, .ss-keys, .ss-kb, svg, .ss-code, .ss-term, .ss-draft__size, .ss-draft__ph, .ss-count, .ss-roll, .ss-notification') || !visibleThrough(el, root)) continue
1613
+ const ls = lines(t)
1614
+ if (!ls.length) continue
1615
+ const cs = getComputedStyle(el)
1616
+ texts.push({ t, el, cs, first: ls[0], last: ls.at(-1), size: parseFloat(cs.fontSize), weight: Number(cs.fontWeight) || 400 })
1617
+ }
1618
+ const seen = new Set()
1619
+ for (const b of texts) {
1620
+ if (b.t.textContent.trim().length < 16 || b.size > 18 || b.cs.whiteSpace === 'nowrap' || b.cs.textOverflow === 'ellipsis' || seen.has(b.el)) continue
1621
+ let name = null
1622
+ for (const n of texts) {
1623
+ if (n === b || n.weight < 600 || n.weight <= b.weight || Math.abs(n.first.left - b.first.left) > 2) continue
1624
+ if (n.last.bottom > b.first.top + 1 || n.last.bottom < b.first.top - b.size * 2.2) continue
1625
+ if (!name || n.last.bottom > name.last.bottom) name = n
1626
+ }
1627
+ if (!name) continue
1628
+ // An author has an avatar just left of the name (a round face 16 to 48px); a title over its subtitle doesn't
1629
+ const midY = (name.first.top + name.first.bottom) / 2
1630
+ // (by geometry: the stage's layers often take no pointer events, so hit-testing can't find it)
1631
+ let near = name.el
1632
+ for (let i = 0; i < 4 && near.parentElement && near !== root; i++) near = near.parentElement
1633
+ const face = [...near.querySelectorAll('*')].some((e) => { const r = e.getBoundingClientRect(); if (r.width < 16 || r.width > 48 || Math.abs(r.width - r.height) > 2 || r.right > name.first.left - 2 || r.right < name.first.left - 44 || r.top > midY || r.bottom < midY) return false; const br = getComputedStyle(e).borderTopLeftRadius; return br.endsWith('%') ? parseFloat(br) >= 40 : parseFloat(br) >= r.width * 0.4 })
1634
+ if (!face) continue
1635
+ // Em boxes to ink: the name's baseline sits about 0.21em above its box's foot, the body's capitals 0.27em below its top
1636
+ const base = name.last.bottom - (name.last.height - name.size) / 2 - name.size * 0.21
1637
+ const cap = b.first.top + (b.first.height - b.size) / 2 + b.size * 0.27
1638
+ const gap = cap - base
1639
+ if (gap < b.size * 0.95 && gap > -b.size) {
1640
+ seen.add(b.el)
1641
+ out.push(`tight stack: ${labelOf(b.el)} sits ${gap.toFixed(1)}px under its name ${labelOf(name.el)} (baseline to capitals); a message under its author wants at least its own size there (${Math.round(b.size)}px), so give the body a few px more top margin`)
1642
+ }
1643
+ }
1644
+ return out
1645
+ }
1646
+
1647
+ function detectPseudoRing({ root }) {
1648
+ const out = []
1649
+ const seen = new Set()
1650
+ const ink = (c) => { const m = c.match(/rgba?\(([^)]+)\)/g); return !!m && m.some((x) => { const v = x.slice(x.indexOf('(') + 1, -1).split(',').map(Number); return v.length < 4 || v[3] > 0.05 }) }
1651
+ for (const n of root.querySelectorAll('*')) {
1652
+ // A ring around words (a field): an icon's or a track's own ring is something else
1653
+ if (n.closest('.ss-cursor, .ss-keys, .ss-kb, svg') || !shown(n, root) || !(n.textContent || '').trim()) continue
1654
+ // The ring as a pseudo-element, or as an empty child span of its own
1655
+ const layers = [...['::before', '::after'].map((w) => [getComputedStyle(n, w), `${tagOf(n)}${w}`, true]),
1656
+ ...[...n.children].filter((c) => !c.children.length && !(c.textContent || '').trim()).map((c) => [getComputedStyle(c), tagOf(c), false])]
1657
+ for (const [ps, label, pseudo] of layers) {
1658
+ if ((pseudo && (ps.content === 'none' || ps.content === 'normal')) || ps.position !== 'absolute' || parseFloat(ps.opacity) < 0.3 || ps.display === 'none') continue
1659
+ const ring = (ps.boxShadow !== 'none' && ink(ps.boxShadow)) || (parseFloat(ps.borderTopWidth) > 0 && ink(ps.borderTopColor))
1660
+ if (!ring || getComputedStyle(n).position === 'static') continue
1661
+ const E = n.getBoundingClientRect()
1662
+ const ins = ['top', 'right', 'bottom', 'left'].map((k) => ps[k].endsWith('px') ? parseFloat(ps[k]) : NaN)
1663
+ // Only a ring drawn outside its element (a field's outline as its own layer); an overlay's own border sits over the page by design
1664
+ if (ins.some(Number.isNaN) || !ins.some((v) => v < 0) || ins.some((v) => v < -16) || n.closest('.ss-popover, .ss-menu, .ss-toast')) continue
1665
+ // An outer shadow ring (a soft halo) paints its spread beyond the box
1666
+ const spread = Math.max(0, ...(ps.boxShadow === 'none' ? [] : ps.boxShadow.split(/,(?![^(]*\))/).filter((x) => !/inset/.test(x)).map((x) => parseFloat((x.replace(/rgba?\([^)]*\)/, '').trim().split(/\s+/)[3]) || '0'))))
1667
+ const R = { left: E.left + ins[3] - spread, top: E.top + ins[0] - spread, right: E.right - ins[1] + spread, bottom: E.bottom - ins[2] + spread }
1668
+ if (R.right - R.left < 8 || R.bottom - R.top < 8) continue
1669
+ // Words of a neighbor under the ring
1670
+ const box = n.parentElement?.parentElement || n.parentElement
1671
+ let hit = null
1672
+ if (box) {
1673
+ const walk = document.createTreeWalker(box, NodeFilter.SHOW_TEXT)
1674
+ for (let t = walk.nextNode(); t && !hit; t = walk.nextNode()) {
1675
+ if (!t.textContent.trim() || n.contains(t) || !shown(t.parentElement, root)) continue
1676
+ const r = document.createRange()
1677
+ r.selectNodeContents(t)
1678
+ for (const b of r.getClientRects()) {
1679
+ if (b.width < 2) continue
1680
+ if (Math.min(b.right, R.right) - Math.max(b.left, R.left) > 1 && Math.min(b.bottom, R.bottom) - Math.max(b.top, R.top) > -2) { hit = t.textContent.trim().slice(0, 18); break }
1681
+ }
1682
+ }
1683
+ }
1684
+ // Past the card it sits in
1685
+ let past = null
1686
+ for (let a = n.parentElement; a && a !== root; a = a.parentElement) {
1687
+ const as = getComputedStyle(a)
1688
+ if (!hasSurface(as) && as.overflowX === 'visible') continue
1689
+ const A = a.getBoundingClientRect()
1690
+ const over = Math.max(A.left - R.left, R.right - A.right, A.top - R.top, R.bottom - A.bottom)
1691
+ if (over > 0.5) past = { a, over }
1692
+ break
1693
+ }
1694
+ // Off its column: the ring's edge a few px outside the column the field
1695
+ // sits in (the name's left edge, the buttons' right), toward the card
1696
+ let off = null
1697
+ const col = n.parentElement
1698
+ if (col) {
1699
+ const cs = getComputedStyle(col)
1700
+ const C = col.getBoundingClientRect()
1701
+ const k = C.width / (col.offsetWidth || C.width)
1702
+ const cl = C.left + (parseFloat(cs.paddingLeft) + parseFloat(cs.borderLeftWidth)) * k
1703
+ const cr = C.right - (parseFloat(cs.paddingRight) + parseFloat(cs.borderRightWidth)) * k
1704
+ const l = cl - (R.left + spread), r = (R.right - spread) - cr
1705
+ if (l > 1.5 && l <= 24 * k) off = { side: 'left', d: l / k }
1706
+ else if (r > 1.5 && r <= 24 * k) off = { side: 'right', d: r / k }
1707
+ }
1708
+ const key = label
1709
+ if (seen.has(key)) continue
1710
+ if (hit) { seen.add(key); out.push(`spills its slot: the ring on ${label} runs into "${hit}"; a ring drawn as its own layer needs room its field owns (a margin that grows with it), never a neighbor's words`) }
1711
+ else if (off) { seen.add(key); out.push(`uneven inset: the ring on ${label} hangs ${px(off.d)}px past its column on the ${off.side}; inset the field by the ring's reach (or pad the field itself) so the box's edges sit on the column: the name's left edge, the buttons' right`) }
1712
+ else if (past) { seen.add(key); out.push(`spills its slot: the ring on ${label} runs ${px(past.over)}px past ${tagOf(past.a)}; inset the field so its ring stays inside the card`) }
1713
+ }
1714
+ }
1715
+ return out
1716
+ }
1717
+
1718
+ // Placeholders follow the text rule: a bar (a line or a disc) never runs
1719
+ // into or under a neighbor on its line (a name bar under an absolute
1720
+ // avatar disc in a card's corner). Neighbors are any box near it in its
1721
+ // card, absolutely positioned ones included.
1722
+ function detectTouchingBars({ root }) {
1723
+ const out = []
1724
+ const noted = new Set()
1725
+ for (const bar of root.querySelectorAll('.ss-bar')) {
1726
+ if (bar.closest('.ss-cursor, .ss-keys') || !shown(bar, root)) continue
1727
+ const B = bar.getBoundingClientRect()
1728
+ if (B.width < 4 || B.height < 2) continue
1729
+ let box = bar.parentElement
1730
+ for (let i = 0; box && box !== root && i < 4 && !hasSurface(getComputedStyle(box)); i++) box = box.parentElement
1731
+ if (!box || box === root) box = bar.parentElement?.parentElement ?? root
1732
+ for (const c of box.querySelectorAll('*')) {
1733
+ if (c === bar || c.contains(bar) || bar.contains(c) || c.closest('.ss-cursor, .ss-keys') || (c.parentElement?.closest('svg'))) continue
1734
+ const leaf = c.classList.contains('ss-bar') || c.tagName.toLowerCase() === 'svg' || !c.children.length || (hasSurface(getComputedStyle(c)) && c.querySelectorAll('*').length <= 4)
1735
+ if (!leaf || !shown(c, root)) continue
1736
+ let b = c.getBoundingClientRect()
1737
+ if ((c.textContent || '').trim() && !c.classList.contains('ss-bar') && !hasSurface(getComputedStyle(c))) {
1738
+ const rr = document.createRange()
1739
+ rr.selectNodeContents(c)
1740
+ b = rr.getBoundingClientRect()
1741
+ }
1742
+ if (b.width < 4 || b.height < 4) continue
1743
+ // A box this bar sits inside (a tinted row) or one round it is its ground, not a neighbor
1744
+ if (b.left <= B.left + 1 && b.right >= B.right - 1 && b.top <= B.top + 1 && b.bottom >= B.bottom - 1) continue
1745
+ if (B.left <= b.left + 1 && B.right >= b.right - 1 && B.top <= b.top + 1 && B.bottom >= b.bottom - 1 && !c.classList.contains('ss-bar')) continue
1746
+ const shared = Math.min(B.bottom, b.bottom) - Math.max(B.top, b.top) > 0.5 * Math.min(B.height, b.height)
1747
+ if (!shared) continue
1748
+ const d = b.left >= B.right - 0.5 ? b.left - B.right : B.left >= b.right - 0.5 ? B.left - b.right : -1
1749
+ if (d >= 6) continue
1750
+ const key = `${tagOf(box)}|${tagOf(c)}`
1751
+ if (noted.has(key)) continue
1752
+ noted.add(key)
1753
+ out.push(`touching: placeholder ${tagOf(bar)} in ${tagOf(box)} is ${d < 0 ? 'running into' : `${px(d)}px from`} ${tagOf(c)}${getComputedStyle(c).position === 'absolute' ? ' (absolutely positioned)' : ''}; a bar is text, so size it to the room left beside its neighbor or put both in a flex row with a gap`)
1754
+ }
1755
+ }
1756
+ return out
1757
+ }
1758
+
1759
+ // One theme per scene: a large near-black box (a build log, a code block)
1760
+ // inside a light window reads as a hole. A terminal window is its own frame.
1761
+ function detectDarkSlab({ root }) {
1762
+ const out = []
1763
+ // Relative luminance of an opaque enough fill, null for none
1764
+ const lum = (color) => {
1765
+ const c = rgbaOf(color)
1766
+ if (!c || c.a < 0.6) return null
1767
+ const f = (v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4 }
1768
+ return 0.2126 * f(c.r) + 0.7152 * f(c.g) + 0.0722 * f(c.b)
1769
+ }
1770
+ for (const w of root.querySelectorAll('.ss-window')) {
1771
+ if (w.matches('[data-chrome="terminal"]') || !shown(w, root)) continue
1772
+ const g = lum(getComputedStyle(w).backgroundColor)
1773
+ if (g === null || g < 0.6) continue
1774
+ const W = w.getBoundingClientRect()
1775
+ for (const n of w.querySelectorAll('*')) {
1776
+ const l = lum(getComputedStyle(n).backgroundColor)
1777
+ if (l === null || l > 0.06 || !shown(n, root)) continue
1778
+ const r = n.getBoundingClientRect()
1779
+ if (r.width * r.height < 0.06 * W.width * W.height || r.height < 40) continue
1780
+ // A slab holds UI text (a log's lines); a dark block of a slide
1781
+ // or an image is the document's content, not the app's chrome
1782
+ if (!(n.textContent || '').trim()) continue
1783
+ out.push(`dark slab: ${tagOf(n)} is a near-black box inside the light ${tagOf(w)}; one theme per scene, so a log or code block in a light UI is a light surface (the well or a tinted panel, mono text in the normal inks); a dark panel belongs in a dark scene or a terminal window of its own`)
1784
+ break
1785
+ }
1786
+ }
1787
+ return out
1788
+ }
1789
+
1790
+ // A satellite whose edge lands just by the window's traffic lights reads
1791
+ // as a near miss: cover them clearly or clear them by a gutter
1792
+ function detectLightsTangent({ root }) {
1793
+ const out = []
1794
+ for (const l of root.querySelectorAll('.ss-window__lights')) {
1795
+ if (!shown(l, root)) continue
1796
+ const L = l.getBoundingClientRect()
1797
+ for (const n of root.querySelectorAll('*')) {
1798
+ if (n.contains(l) || l.contains(n) || n.closest('.ss-window')?.contains(l) || n.closest('.ss-cursor, .ss-keys, .ss-kb, svg')) continue
1799
+ const cs = getComputedStyle(n)
1800
+ if (cs.position !== 'absolute' || !cs.boxShadow || cs.boxShadow === 'none' || !shown(n, root)) continue
1801
+ const r = n.getBoundingClientRect()
1802
+ if (r.width * r.height < 2000) continue
1803
+ const overlapsY = r.bottom > L.top - 6 && r.top < L.bottom + 6
1804
+ const overlapsX = r.right > L.left - 6 && r.left < L.right + 6
1805
+ const gaps = [overlapsY && Math.abs(r.left - L.right), overlapsY && Math.abs(r.right - L.left), overlapsX && Math.abs(r.top - L.bottom), overlapsX && Math.abs(r.bottom - L.top)].filter((g) => g !== false)
1806
+ const g = Math.min(...gaps)
1807
+ if (gaps.length && g < 6) out.push(`near-tangent: ${tagOf(n)}'s edge lands ${px(g)}px from the window's traffic lights; cover the chrome clearly or clear it by a gutter`)
1808
+ }
1809
+ }
1810
+ return out
1811
+ }
1812
+
1813
+ // Shadows live on the shape with the outline. A wrapper that casts its
1814
+ // own shadow round a rounder child (a phone) shows its tighter corners
1815
+ // past the child's curves as a pale halo, and doubles the shadow.
1816
+ function detectShadowHalo({ root }) {
1817
+ const out = []
1818
+ for (const n of root.querySelectorAll('*')) {
1819
+ const cs = getComputedStyle(n)
1820
+ if (!cs.boxShadow || cs.boxShadow === 'none' || n.closest('.ss-cursor, .ss-keys, .ss-kb, svg') || !shown(n, root)) continue
1821
+ const r = n.getBoundingClientRect()
1822
+ if (r.width < 24 || r.height < 24) continue
1823
+ const rad = parseFloat(cs.borderTopLeftRadius) || 0
1824
+ for (const c of n.children) {
1825
+ const b = c.getBoundingClientRect()
1826
+ if (Math.abs(b.left - r.left) > 3 || Math.abs(b.top - r.top) > 3 || Math.abs(b.width - r.width) > 6 || Math.abs(b.height - r.height) > 6) continue
1827
+ const cc = getComputedStyle(c)
1828
+ const crad = Math.max(parseFloat(cc.borderTopLeftRadius) || 0, ...[...c.querySelectorAll(':scope > svg rect, :scope > svg path')].slice(0, 1).map((x) => parseFloat(x.getAttribute('rx')) || 0))
1829
+ if (crad > rad + 2) {
1830
+ out.push(`framing: ${tagOf(n)} casts a shadow with ${px(rad)}px corners round ${tagOf(c)}, whose outline is rounded ${px(crad)}px, so its corners show past the curve as a halo${cc.boxShadow && cc.boxShadow !== 'none' ? ' and the shadow is doubled' : ''}; put the shadow on the shape itself (drop the wrapper's) or match the radius`)
1831
+ break
1832
+ }
1833
+ }
1834
+ }
1835
+ return out
1836
+ }
1837
+
1838
+ // A settled zoom: what the camera pushed in on sits wholly in its crop,
1839
+ // clear of the feathered edge (a focus the zoom can't fit, or a pad
1840
+ // smaller than the feather, leaves the subject fading out at the edge)
1841
+ function detectFocusFeather({ root, S, V, zoomView, focusRect }) {
1842
+ const out = []
1843
+ if (!focusRect) return out
1844
+ const f = (Number(zoomView.dataset.feather) || 0) * (S.width / root.offsetWidth || 1)
1845
+ const d = { left: focusRect.left - V.left, top: focusRect.top - V.top, right: V.right - focusRect.right, bottom: V.bottom - focusRect.bottom }
1846
+ const [edge, v] = Object.entries(d).sort((x, y) => x[1] - y[1])[0]
1847
+ if (v < f - 1) out.push(`framing: the camera's focus sits ${px(v)}px from the ${edge} edge of its crop, inside the ${px(f)}px feather; zoomed in, what it pushed in on is whole and clear of the soft edge, so raise pad, lower max or focus on a smaller rect`)
1848
+ return out
1849
+ }
1850
+
1851
+ // The story's own marks never cut: anything it aims at. Judged at rest: a
1852
+ // control part way through its own opening is moving. A target is judged
1853
+ // when the story is at it (the cursor on or beside it); one prepared for a
1854
+ // later beat may still sit below the crop
1855
+ function detectTargetsCut({ root, V, busy, focusRect }) {
1856
+ const out = []
1857
+ const inFocus = (r) => !focusRect || (r.right > focusRect.left && r.left < focusRect.right && r.bottom > focusRect.top && r.top < focusRect.bottom)
1858
+ const curEl = root.querySelector('.ss-cursor')
1859
+ const curR = curEl && shown(curEl, root) ? curEl.getBoundingClientRect() : null
1860
+ const nearCursor = (r) => !curR || (curR.right > r.left - 24 && curR.left < r.right + 24 && curR.bottom > r.top - 24 && curR.top < r.bottom + 24)
1861
+ for (const n of window.__ssStill ? [] : root.querySelectorAll('[data-target]')) {
1862
+ if (n.closest('.ss-cursor') || !shown(n, root) || animating(n, busy, root)) continue
1863
+ const r0 = n.getBoundingClientRect()
1864
+ if (!nearCursor(r0)) continue
1865
+ if (r0.width < 4 || r0.height < 4 || r0.width > 260 * (focusRect?.k ?? 1) || r0.height > 120 * (focusRect?.k ?? 1) || !inFocus(r0)) continue
1866
+ // Hidden by its own scroller is the scroller's business, not the crop's
1867
+ const r = ownClip(n, r0, root)
1868
+ if (!r || r.bottom - r.top < r0.height - 1 || r.right - r.left < r0.width - 1) continue
1869
+ const out1 = r.left < V.left - 1 || r.top < V.top - 1 || r.right > V.right + 1 || r.bottom > V.bottom + 1
1870
+ const in1 = r.right > V.left + 2 && r.left < V.right - 2 && r.bottom > V.top + 2 && r.top < V.bottom - 2
1871
+ if (out1 && in1) out.push(`framing: target ${tagOf(n)}${n.dataset.target ? ` "${n.dataset.target}"` : ''} is cut by the crop; what the story touches stays whole in frame`)
1872
+ }
1873
+ return out
1874
+ }
1875
+
1876
+ // Real words never cut by the crop: only filler bleeds
1877
+ function detectWordsCut({ root, V, busy, zoomView }) {
1878
+ const out = []
1879
+ for (const n of root.querySelectorAll('*')) {
1880
+ if (n.closest('.ss-cursor, .ss-keys, .ss-kb, svg, [data-crop], .ss-count')) continue
1881
+ const texts = [...n.childNodes].filter((c) => c.nodeType === 3 && c.textContent.trim().length > 1)
1882
+ if (!texts.length || !shown(n, root) || animating(n, busy, root) || zoomView) continue
1883
+ // The words themselves, not the block they sit in
1884
+ const range = document.createRange()
1885
+ range.setStart(texts[0], 0)
1886
+ range.setEnd(texts[texts.length - 1], texts[texts.length - 1].length)
1887
+ const r0 = range.getBoundingClientRect()
1888
+ if (r0.width < 4) continue
1889
+ // What its own clipping boxes leave (lines a terminal hides below its
1890
+ // edge are inside the window, not cut by the stage)
1891
+ const r = { left: r0.left, right: r0.right, top: r0.top, bottom: r0.bottom }
1892
+ for (let a = n; a && a !== root; a = a.parentElement) {
1893
+ const o = getComputedStyle(a)
1894
+ if (o.overflowX === 'visible' && o.overflowY === 'visible') continue
1895
+ const c = a.getBoundingClientRect()
1896
+ if (o.overflowX !== 'visible') { r.left = Math.max(r.left, c.left); r.right = Math.min(r.right, c.right) }
1897
+ if (o.overflowY !== 'visible') { r.top = Math.max(r.top, c.top); r.bottom = Math.min(r.bottom, c.bottom) }
1898
+ }
1899
+ if (r.right - r.left < 4 || r.bottom - r.top < 2) continue
1900
+ const cutR = r.left < V.right - 2 && r.right > V.right + 1
1901
+ let cutB = r.top < V.bottom - 2 && r.bottom > V.bottom + 1
1902
+ const cutL = r.right > V.left + 2 && r.left < V.left - 1
1903
+ // A single line of a list, a diff or a terminal running off the bottom
1904
+ // edge its window bleeds through is the product continuing, not a slice
1905
+ if (cutB) {
1906
+ const fs = parseFloat(getComputedStyle(n).fontSize) || 14
1907
+ const win = n.closest('.ss-window, .ss-phone')
1908
+ const wb = win ? win.getBoundingClientRect().bottom : 0
1909
+ if (win && wb > V.bottom + 2 && r0.bottom - r0.top <= fs * 1.7) cutB = false
1910
+ }
1911
+ if (cutR || cutB || cutL) out.push(`framing: real words ${tagOf(n)} "${n.textContent.trim().slice(0, 20)}" are cut by the crop; only filler bleeds, so pull them inside or make them a placeholder`)
1912
+ }
1913
+ return out
1914
+ }
1915
+
1916
+ // Controls cut by the crop: a button or chip half off the stage's edge.
1917
+ // Filler running off is the point of a bleed; an action is read whole or
1918
+ // not at all, so a sliced one looks like a mistake.
1919
+ function detectControlsCut({ root, V, zoomView }) {
1920
+ const out = []
1921
+ for (const n of root.querySelectorAll('[data-target], [role=button], button, [class*="btn"], [class*="button"], *')) {
1922
+ if (n.closest('.ss-cursor, .ss-keys, .ss-kb, svg') || n === root || zoomView) continue
1923
+ const cs = getComputedStyle(n)
1924
+ const r = n.getBoundingClientRect()
1925
+ const systemObject = n.matches('.ss-notification, .ss-toast, .ss-menu, .ss-popover, [class*="notification"], [class*="toast"]')
1926
+ if (r.width < 12 || r.height < 12 || (!systemObject && (r.height > 56 || r.width > 220))) continue
1927
+ const named = systemObject || n.hasAttribute('data-target') || n.getAttribute('role') === 'button' || n.tagName === 'BUTTON' || /btn|button/i.test(typeof n.className === 'string' ? n.className : '')
1928
+ // Unnamed, it has to look like a button: a rounded surface wider than
1929
+ // tall, with a word or an icon on it (an avatar or a dot is filler)
1930
+ const label = (n.textContent || '').trim()
1931
+ const chip = hasSurface(cs) && parseFloat(cs.borderTopLeftRadius) >= 4 && n.querySelectorAll('*').length <= 6 && r.width > r.height * 1.3 && (label.length >= 2 || !!n.querySelector('svg'))
1932
+ if (!named && !chip) continue
1933
+ const cut = []
1934
+ if (r.left < V.right - 2 && r.right > V.right + 2) cut.push(['right', r.right - V.right, r.width])
1935
+ if (r.top < V.bottom - 2 && r.bottom > V.bottom + 2) cut.push(['bottom', r.bottom - V.bottom, r.height])
1936
+ if (r.right > V.left + 2 && r.left < V.left - 2) cut.push(['left', V.left - r.left, r.width])
1937
+ if (!cut.length || !shown(n, root)) continue
1938
+ // Cut by its own scroller first (a list row below the fold): not the crop's cut
1939
+ const own = ownClip(n, r, root)
1940
+ if (!own || own.bottom - own.top < r.height - 1 || own.right - own.left < r.width - 1) continue
1941
+ // A parent chip already reported covers its children
1942
+ if (out.some((f) => f.startsWith('cut by the crop') && n.parentElement && f.includes(tagOf(n.parentElement)))) continue
1943
+ const [edge, off, size] = cut[0]
1944
+ // Siblings of its kind running off the same edge: the row bleeds, as filler does
1945
+ const offEdge = (s) => edge === 'right' ? s.getBoundingClientRect().right > V.right + 2 : edge === 'left' ? s.getBoundingClientRect().left < V.left - 2 : s.getBoundingClientRect().bottom > V.bottom + 2
1946
+ const kin = typeof n.className === 'string' && n.className ? [...root.querySelectorAll('.' + n.className.trim().split(/\s+/).join('.'))].filter((s) => s !== n && offEdge(s)) : []
1947
+ if (kin.length >= 1 && !n.hasAttribute('data-target')) continue
1948
+ const win = n.closest('.ss-window, .ss-phone')
1949
+ if (win && off <= 10 && !n.hasAttribute('data-target') && offEdge(win)) continue
1950
+ out.push(`cut by the crop: ${tagOf(n)} runs off the stage's ${edge} edge (${Math.round(off)}px of its ${Math.round(size)}px); filler can bleed but an action reads whole or not at all, so bring it inside the crop or remove it`)
1951
+ }
1952
+ return out
1953
+ }
1954
+
1955
+ // ---- Per-shot entry points ------------------------------------------------
1956
+
1957
+ // Every check for one shot of one stage, in the order film.mjs has always
1958
+ // reported them. ['CAMERA_MOVING'] while a Camera is mid-move; 'SAT_SIDE'
1959
+ // among the findings when a satellite straddles the hero's side.
1960
+ export function checkStage(root) {
1961
+ const ctx = stageContext(root)
1962
+ if (cameraMoving(ctx.cam)) return ['CAMERA_MOVING']
1963
+ const out = []
1964
+ out.push(...detectClipped(ctx))
1965
+ out.push(...detectPaddingRunIns(ctx))
1966
+ out.push(...detectCoveredCopy(ctx))
1967
+ out.push(...detectLopsidedPills(ctx))
1968
+ const surfs = collectSurfaces(ctx)
1969
+ out.push(...detectEdgeTangents(ctx, surfs))
1970
+ out.push(...detectUnclipped(ctx, surfs))
1971
+ out.push(...detectTightBars(ctx))
1972
+ out.push(...detectDoubleCorner(ctx))
1973
+ out.push(...detectPairTangents(ctx, surfs))
1974
+ out.push(...detectTranslucentIcons(ctx))
1975
+ out.push(...detectSkeletonLadder(ctx))
1976
+ out.push(...detectLooseList(ctx))
1977
+ out.push(...detectTightControl(ctx))
1978
+ out.push(...detectInventedMark(ctx))
1979
+ out.push(...detectNearAligned(ctx))
1980
+ out.push(...detectUnevenInset(ctx))
1981
+ out.push(...detectMixedIcons(ctx))
1982
+ out.push(...detectEmojiIcon(ctx))
1983
+ out.push(...detectFatRow(ctx))
1984
+ out.push(...detectEmptyPane(ctx))
1985
+ out.push(...detectTightInset(ctx))
1986
+ out.push(...detectUnevenPadding(ctx))
1987
+ out.push(...detectUnevenGutters(ctx))
1988
+ out.push(...detectPillInset(ctx))
1989
+ out.push(...detectTightStack(ctx))
1990
+ out.push(...detectKitOverride(ctx))
1991
+ out.push(...detectClippedGlyph(ctx))
1992
+ out.push(...detectUnitWrapped(ctx))
1993
+ out.push(...detectUnsizedText(ctx))
1994
+ out.push(...detectOnionSkin(ctx))
1995
+ out.push(...detectTightMark(ctx))
1996
+ out.push(...detectRowRhythm(ctx))
1997
+ out.push(...detectHalfPixelGlyph(ctx))
1998
+ out.push(...detectSqueezed(ctx))
1999
+ const frame = frameContext(ctx)
2000
+ const hero = detectHeroFraming(frame)
2001
+ out.push(...hero.out)
2002
+ frame.gutter = hero.gutter
2003
+ out.push(...detectSatelliteGutters(frame))
2004
+ out.push(...detectBoxEdges(frame))
2005
+ out.push(...detectSliverColumn(frame))
2006
+ out.push(...detectOverlayRoom(frame))
2007
+ out.push(...detectTouchingText(frame))
2008
+ out.push(...detectPseudoRing(frame))
2009
+ out.push(...detectDraftHang(frame))
2010
+ out.push(...detectBylineGap(frame))
2011
+ out.push(...detectTouchingBars(frame))
2012
+ out.push(...detectDarkSlab(frame))
2013
+ out.push(...detectLightsTangent(frame))
2014
+ out.push(...detectShadowHalo(frame))
2015
+ out.push(...detectFocusFeather(frame))
2016
+ out.push(...detectTargetsCut(frame))
2017
+ out.push(...detectWordsCut(frame))
2018
+ out.push(...detectControlsCut(frame))
2019
+ return out
2020
+ }
2021
+
2022
+ // Phone widths: the smallest visible text as drawn, through every scale.
2023
+ // Null when nothing is under 9.5px.
2024
+ export function smallestText(root) {
2025
+ let min = null
2026
+ for (const el of root.querySelectorAll('*')) {
2027
+ if (!(el instanceof HTMLElement) || !el.offsetWidth) continue
2028
+ if (![...el.childNodes].some((c) => c.nodeType === 3 && c.textContent.trim())) continue
2029
+ // An avatar's initial or a key's glyph is a mark, not a line to read
2030
+ if (el.textContent.trim().length <= 2) continue
2031
+ const cs = getComputedStyle(el)
2032
+ if (cs.visibility === 'hidden' || el.closest('[aria-hidden="true"], .ss-cursor')) continue
2033
+ if (fadeThrough(el, root.parentElement) < 0.5) continue
2034
+ const r = el.getBoundingClientRect()
2035
+ const S = root.getBoundingClientRect()
2036
+ if (r.right < S.left || r.left > S.right || r.bottom < S.top || r.top > S.bottom) continue
2037
+ const px = parseFloat(cs.fontSize) * (r.width / el.offsetWidth)
2038
+ if (!min || px < min.px) min = { px, el: `${el.tagName.toLowerCase()}${el.classList[0] ? '.' + el.classList[0] : ''} "${el.textContent.trim().slice(0, 20)}"` }
2039
+ }
2040
+ return min && min.px < 9.5 ? min : null
2041
+ }
2042
+
2043
+ // A control that spills the slot it was laid out in: its box runs past its
2044
+ // parent, or closes the declared gap to the box beside it. A flex or grid
2045
+ // slot only lets that happen when content outgrows it (a chip opening, a
2046
+ // label swapping), and the eye reads it as the field shoving its neighbor.
2047
+ // Overlays (absolute, fixed) and anything that opens as the story are laid
2048
+ // out on their own, so they never match.
2049
+ export function detectSpills(root) {
2050
+ const out = []
2051
+ const S = root.getBoundingClientRect()
2052
+ const name = (e) => `${e.tagName.toLowerCase()}${e.classList[0] ? '.' + e.classList[0] : ''}`
2053
+ // Its own walk: more than half opaque (not at least half), and only the
2054
+ // element's own visibility, as this check has always judged it
2055
+ const seen = (e) => fadeThrough(e, root.parentElement) > 0.5 && getComputedStyle(e).visibility !== 'hidden'
2056
+ const inFlow = (e) => !/^(absolute|fixed)$/.test(getComputedStyle(e).position) && !e.closest('.ss-cursor, [aria-hidden="true"]')
2057
+ const control = (e) => {
2058
+ const r = e.getBoundingClientRect()
2059
+ if (r.height < 18 || r.height > 56 || r.width < 24) return false
2060
+ return /^(BUTTON|INPUT|TEXTAREA|SELECT)$/.test(e.tagName) || e.hasAttribute('data-target') ||
2061
+ /(^|[-_\s])(field|input|btn|button|control|chip|pill|search|select)/i.test(typeof e.className === 'string' ? e.className : '')
2062
+ }
2063
+ const scaled = (e) => { for (let a = e; a && a !== root; a = a.parentElement) { const t = getComputedStyle(a).transform; if (t && t !== 'none' && !/^matrix\(1, 0, 0, 1,/.test(t)) return true; const sc = getComputedStyle(a).scale; if (sc && sc !== 'none' && sc !== '1') return true } return false }
2064
+ const flagged = new Set()
2065
+ for (const el of root.querySelectorAll('*')) {
2066
+ if (!(el instanceof HTMLElement) || !el.offsetWidth || !control(el) || !inFlow(el) || !seen(el)) continue
2067
+ const p = el.parentElement
2068
+ if (!p || p === root) continue
2069
+ const pc = getComputedStyle(p)
2070
+ if (pc.overflowX !== 'visible' || /^(inline|contents)$/.test(pc.display)) continue
2071
+ const r = el.getBoundingClientRect(), pr = p.getBoundingClientRect()
2072
+ if (r.right < S.left || r.left > S.right || pr.width < 24 || scaled(el)) continue
2073
+ const ml = parseFloat(getComputedStyle(el).marginLeft), mr = parseFloat(getComputedStyle(el).marginRight)
2074
+ if (ml < 0 || mr < 0) continue
2075
+ const over = Math.max(r.right - pr.right, pr.left - r.left)
2076
+ if (over >= 3) { flagged.add(p); out.push(`spills its slot: ${name(el)} runs ${Math.round(over)}px past ${name(p)}, the width it was laid out in; give the slot room for its widest state, or let the content clip inside the box (minmax(0, 1fr), min-width: 0), never the box grow into its neighbor`) }
2077
+ }
2078
+ for (const row of root.querySelectorAll('*')) {
2079
+ if (!(row instanceof HTMLElement) || !row.offsetWidth) continue
2080
+ const cs = getComputedStyle(row)
2081
+ if (!/flex/.test(cs.display) || !/^row/.test(cs.flexDirection)) continue
2082
+ const gap = parseFloat(cs.columnGap)
2083
+ if (!(gap >= 4)) continue
2084
+ const kids = [...row.children].filter((k) => k instanceof HTMLElement && k.offsetWidth && inFlow(k) && seen(k))
2085
+ if (kids.length < 2 || scaled(row)) continue
2086
+ const extent = (k) => {
2087
+ const r = k.getBoundingClientRect()
2088
+ let L = r.left, R = r.right
2089
+ for (const d of k.querySelectorAll('*')) if (d instanceof HTMLElement && d.offsetWidth && control(d) && inFlow(d)) { const q = d.getBoundingClientRect(); L = Math.min(L, q.left); R = Math.max(R, q.right) }
2090
+ return { L, R, k }
2091
+ }
2092
+ const xs = kids.map(extent)
2093
+ for (let i = 0; i + 1 < xs.length; i++) {
2094
+ const a = xs[i], b = xs[i + 1]
2095
+ const g = b.L - a.R
2096
+ if (g > gap - 3 || [...flagged].some((f) => a.k.contains(f) || b.k.contains(f))) continue
2097
+ if (!control(a.k) && !a.k.querySelector('*')) continue
2098
+ out.push(`spills its slot: ${name(a.k)} comes ${Math.round(g)}px from ${name(b.k)} in ${name(row)}, which sets a ${Math.round(gap)}px gap; something inside it outgrew its slot and closed the gap`)
2099
+ }
2100
+ }
2101
+ return out
2102
+ }
2103
+
2104
+ // ---- Injection ------------------------------------------------------------
2105
+
2106
+ // The script film.mjs installs in the page: every function above, scoped
2107
+ // together so they see each other, exposed as window.__ssFilmChecks
2108
+ export function filmChecksSource() {
2109
+ const fns = [
2110
+ rgbaOf, alphaOf, paintsSurface, inkedBox, surface, visible, hasSurface, visibleThrough, painted, shown, fadeThrough, labelOf, tagOf, px, nearTangent,
2111
+ stageContext, cameraMoving,
2112
+ detectClipped, detectPaddingRunIns, detectCoveredCopy, detectLopsidedPills,
2113
+ collectSurfaces, detectEdgeTangents, detectUnclipped, detectTightBars, detectDoubleCorner, detectPairTangents,
2114
+ detectTranslucentIcons, detectSkeletonLadder, detectLooseList, detectTightControl, detectInventedMark, detectNearAligned, detectUnevenInset, detectMixedIcons, detectEmojiIcon, detectFatRow, detectEmptyPane, detectTightInset, detectUnevenPadding, detectUnevenGutters, detectPillInset, detectTightStack, detectKitOverride, detectClippedGlyph, detectUnitWrapped, detectUnsizedText, detectOnionSkin, detectTightMark, detectRowRhythm, detectHalfPixelGlyph, detectSqueezed,
2115
+ frameContext, ownClip, animating, shownArea, satellite,
2116
+ detectHeroFraming, detectSatelliteGutters, detectBoxEdges, detectSliverColumn, detectOverlayRoom, detectTouchingText, detectPseudoRing, detectDraftHang, detectBylineGap, detectTouchingBars, detectDarkSlab, detectLightsTangent, detectShadowHalo, detectFocusFeather, detectTargetsCut, detectWordsCut, detectControlsCut,
2117
+ checkStage, smallestText, detectSpills,
2118
+ ]
2119
+ return `(() => {\n${fns.map((fn) => fn.toString()).join('\n')}\nwindow.__ssFilmChecks = { checkStage, smallestText, detectSpills, detectDraftHang, detectUnevenPadding, stageContext, detectTightStack, detectBylineGap }\n})()`
2120
+ }