@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.
package/jumps-core.mjs ADDED
@@ -0,0 +1,191 @@
1
+ // One-frame snaps and drift, shared by film.mjs (every film) and jumps.mjs.
2
+ //
3
+ // record() runs in the page on the stage element: it records the box of
4
+ // every visible element on the stage each animation frame, into
5
+ // window.__frames. analyse() reports any element whose position or size
6
+ // changes by more than 2px in one frame while it was still the frame before
7
+ // and after (a snap), and neighbors that keep their size but not their gap
8
+ // while gliding (drift: they run on different curves). Things that appear or
9
+ // disappear are not snaps (fades handle those). Carets are skipped; mark
10
+ // anything else that should step with data-snap. Frames where a Camera
11
+ // moves skip what is inside it.
12
+
13
+ export function record(stage, options = {}) {
14
+ const { key, ms = Infinity } = typeof options === 'number' ? { ms: options } : options
15
+ const ids = new WeakMap()
16
+ let n = 0
17
+ const label = (el) => {
18
+ const cls = (el.getAttribute('class') || el.tagName.toLowerCase()).split(' ')[0]
19
+ const text = (el.textContent || '').trim().slice(0, 18)
20
+ return `${cls}${text ? ` "${text}"` : ''}`
21
+ }
22
+ const id = (el) => {
23
+ if (!ids.has(el)) ids.set(el, { n: n++, name: label(el) })
24
+ return ids.get(el)
25
+ }
26
+ const frames = []
27
+ if (key) window.__ssVerification.stages[key].frames = frames
28
+ else window.__frames = frames
29
+ const t0 = performance.now()
30
+ const tick = () => {
31
+ if (window.__ssVerification?.stopped || !stage.isConnected) return
32
+ try {
33
+ const box = stage.getBoundingClientRect()
34
+ const s = box.width / stage.offsetWidth || 1
35
+ const items = []
36
+ const cameras = [...stage.querySelectorAll('.ss-camera')]
37
+ const movingCameras = cameras.filter((cam) => document.getAnimations().some((x) => x.playState === 'running' && (x.effect?.target === cam || x.effect?.target === cam.parentElement)))
38
+ for (const el of stage.querySelectorAll('*')) {
39
+ const r = el.getBoundingClientRect()
40
+ if (r.width * r.height < 16) continue
41
+ // Carets step a letter at a time, and data-snap marks anything else
42
+ // that is meant to step
43
+ if (el.closest('[data-snap], [data-typing], .ss-caret, .ss-field__caret, .ss-term__caret')) continue
44
+ // The cursor's glyph swaps shape (arrow, hand, crosshair) by design
45
+ if (el.parentElement?.closest('.ss-cursor')) continue
46
+ // Inside a Camera while it moves, everything scales and slides together
47
+ // on purpose: not a jump, and no gap holds still
48
+ if (movingCameras.some((cam) => cam.contains(el))) continue
49
+ const cs = getComputedStyle(el)
50
+ if (cs.visibility === 'hidden') continue
51
+ // A wrapper that paints nothing and clips nothing can't be seen to jump:
52
+ // only what it holds can, and that is checked on its own (a Roll
53
+ // re-forming around the digits that change, with every glyph in place)
54
+ const paints = (cs.backgroundColor !== 'rgba(0, 0, 0, 0)' && cs.backgroundColor !== 'transparent') || cs.backgroundImage !== 'none' || parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth) + parseFloat(cs.borderLeftWidth) + parseFloat(cs.borderRightWidth) > 0 || cs.boxShadow !== 'none' || cs.overflowX !== 'visible' || cs.overflowY !== 'visible'
55
+ const ownText = [...el.childNodes].some((c) => c.nodeType === 3 && c.textContent.trim())
56
+ if (!paints && !ownText && el.children.length && el.tagName.toLowerCase() !== 'svg') continue
57
+ // Invisible through any ancestor's opacity counts as invisible: a reset
58
+ // inside a faded-out parent is not a jump anyone sees
59
+ let alpha = 1
60
+ for (let p = el; p && p !== stage && alpha > 0.02; p = p.parentElement) alpha *= +getComputedStyle(p).opacity
61
+ if (alpha <= 0.02) continue
62
+ const { n, name } = id(el)
63
+ // Stage units, so a scaled stage reports the design's pixels
64
+ // The parent and the next sibling, for the drift check
65
+ const pid = el.parentElement ? id(el.parentElement).n : -1
66
+ // Only neighbors in flow: a satellite, toast or keycap row floats over
67
+ // its siblings rather than sitting in a column with them
68
+ const sib = el.nextElementSibling
69
+ const inFlow = (e) => !/absolute|fixed/.test(getComputedStyle(e).position)
70
+ const next = sib && inFlow(el) && inFlow(sib) ? id(sib).n : -1
71
+ const typing = !!el.closest('[data-typing], .ss-field__chars, .ss-field__placeholder, .ss-kb__callout, .ss-kb__suggest, .ss-roll')
72
+ // Geometry cannot decide whether an instant text/icon change is intended.
73
+ const words = [...el.childNodes].filter((c) => c.nodeType === 3).map((c) => c.textContent).join('')
74
+ const drawing = el.tagName.toLowerCase() === 'svg' ? el.innerHTML : ''
75
+ const content = typing ? null : `${words}|${drawing}`
76
+ items.push([n, name, (r.left - box.left) / s, (r.top - box.top) / s, r.width / s, r.height / s, pid, next, content])
77
+ }
78
+ frames.push({ t: performance.now() - t0, mark: stage.dataset.mark, items, cameraMoving: movingCameras.length })
79
+ if (performance.now() - t0 < ms) requestAnimationFrame(tick)
80
+ } catch (error) {
81
+ if (window.__ssVerification) window.__ssVerification.errors.push(`box recorder ${key || ''}: ${error.message}`)
82
+ else throw error
83
+ }
84
+ }
85
+ requestAnimationFrame(tick)
86
+ }
87
+
88
+ export function analyse(frames, slow = 1) {
89
+ if (!Array.isArray(frames)) throw new TypeError('The jump scan requires recorded frames')
90
+ const at = frames.map((f) => new Map(f.items.map((i) => [i[0], i])))
91
+ // A frame that came late (the page busy, as when film takes a screenshot)
92
+ // carries several frames of gliding at once: it can't tell a snap from a
93
+ // glide, so frames around a stall are not judged
94
+ const dts = frames.slice(1).map((fr, i) => fr.t - frames[i].t).sort((a, b) => a - b)
95
+ const frameMs = dts[Math.floor(dts.length / 2)] || 16.7
96
+ const late = (f) => f > 0 && frames[f].t - frames[f - 1].t > frameMs * 1.6
97
+ const found = new Map()
98
+ for (let f = 2; f < frames.length - 1; f++) {
99
+ if (late(f - 1) || late(f) || late(f + 1)) continue
100
+ for (const [n, it] of at[f]) {
101
+ const a = at[f - 2].get(n), b = at[f - 1].get(n), c = at[f + 1].get(n)
102
+ if (!a || !b || !c) continue
103
+ for (const [k, ax] of [['x', 2], ['y', 3], ['width', 4], ['height', 5]]) {
104
+ const d = it[ax] - b[ax]
105
+ const calm = Math.max(Math.abs(b[ax] - a[ax]), Math.abs(c[ax] - it[ax]), 0.4)
106
+ if (Math.abs(d) > 2 && Math.abs(d) > 3 * calm) {
107
+ // One line per element and axis: the first time, and how often
108
+ const key = `${n}:${k}`
109
+ const prev = found.get(key)
110
+ if (prev) prev.count++
111
+ else found.set(key, { id: n, parent: it[6], t: frames[f].t, mark: frames[f].mark, name: it[1], k, d, count: 1 })
112
+ }
113
+ }
114
+ }
115
+ }
116
+ // Drift: neighbors in a column that glide out of step. Two siblings that
117
+ // both keep their size should keep the gap between them; a gap that wobbles
118
+ // for several frames means one runs on a different curve (a timestamp gliding
119
+ // slower than the messages around it). New arrivals are left out: they are
120
+ // meant to move differently while they come in.
121
+ const born = new Map()
122
+ frames.forEach((fr, f) => fr.items.forEach((i) => born.has(i[0]) || born.set(i[0], f)))
123
+ const drift = new Map()
124
+ for (let f = 1; f < frames.length; f++) {
125
+ if (late(f)) continue
126
+ for (const [n, it] of at[f]) {
127
+ const nx = it[7] >= 0 ? at[f].get(it[7]) : null
128
+ const pa = at[f - 1].get(n), pb = nx && at[f - 1].get(nx[0])
129
+ if (!nx || !pa || !pb) continue
130
+ if (f - born.get(n) < 45 || f - born.get(nx[0]) < 45) continue
131
+ const held = Math.abs(it[5] - pa[5]) < 0.3 && Math.abs(nx[5] - pb[5]) < 0.3
132
+ const dg = nx[3] - (it[3] + it[5]) - (pb[3] - (pa[3] + pa[5]))
133
+ if (!held || Math.abs(dg) <= 1) continue
134
+ const key = `${n}>${nx[0]}`
135
+ const d = drift.get(key) ?? { t: frames[f].t, mark: frames[f].mark, a: it[1], b: nx[1], max: 0, count: 0 }
136
+ d.max = Math.max(d.max, Math.abs(dg))
137
+ d.count++
138
+ drift.set(key, d)
139
+ }
140
+ }
141
+
142
+ // Anchor drift: an open popover or menu whose top edge moves while its
143
+ // height changes (a filtered list re-centering the box). An open surface
144
+ // holds its anchor; the list grows and shrinks downward from it
145
+ const anchored = new Map()
146
+ for (let f = 1; f < frames.length; f++) {
147
+ if (late(f)) continue
148
+ for (const [n, it] of at[f]) {
149
+ if (!/^ss-(popover|menu|sheet)\b/.test(it[1]) || f - born.get(n) < 30) continue
150
+ const p = at[f - 1].get(n)
151
+ if (!p) continue
152
+ const dy = it[3] - p[3], dh = it[5] - p[5]
153
+ if (Math.abs(dy) < 0.3 || Math.abs(dh) < 0.3) continue
154
+ const a = anchored.get(n) ?? { t: frames[f].t, mark: frames[f].mark, name: it[1], y: 0, h: 0, count: 0 }
155
+ a.y += dy; a.h += dh; a.count++
156
+ anchored.set(n, a)
157
+ }
158
+ }
159
+ const anchors = [...anchored.values()].filter((a) => Math.abs(a.y) >= 1)
160
+
161
+ // A parent's snap drags its children with it: report the outermost only
162
+ const lines = [...found.values()].sort((p, q) => p.t - q.t)
163
+ const kept = []
164
+ for (const l of lines) {
165
+ if (kept.some((s) => s.id === l.parent && Math.abs(s.t - l.t) < 40 && s.k === l.k && Math.abs(s.d - l.d) < 0.6)) continue
166
+ kept.push(l)
167
+ }
168
+
169
+ const drifts = [...drift.values()].filter((d) => d.count >= 4)
170
+ const t = (ms) => (ms / 1000 / slow).toFixed(2)
171
+ return [
172
+ ...anchors.map((a) => `anchor drift: ${a.name} moves ${a.y > 0 ? 'down' : 'up'} ${Math.abs(a.y).toFixed(1)}px while its height changes by ${a.h.toFixed(0)}px (from ${t(a.t)}s${a.mark ? ` [${a.mark}]` : ''}); an open popover holds its top edge and its list grows and shrinks downward, so anchor it by its top, never center it`),
173
+ ...drifts.map((d) => `drift: ${d.a} and ${d.b} glide out of step (gap changes up to ${d.max.toFixed(1)}px a frame, ${d.count} frames from ${t(d.t)}s${d.mark ? ` [${d.mark}]` : ''})`),
174
+ ...kept.map((l) => `jump: ${l.name} ${l.k} ${l.d > 0 ? '+' : ''}${l.d.toFixed(1)}px in one frame at ${t(l.t)}s${l.mark ? ` [${l.mark}]` : ''}${l.count > 1 ? `, ${l.count} times` : ''}`),
175
+ ]
176
+ }
177
+
178
+ export function contentChanges(frames, slow = 1) {
179
+ const seen = new Map()
180
+ const found = new Map()
181
+ for (const frame of frames) {
182
+ for (const item of frame.items) {
183
+ const old = seen.get(item[0])
184
+ if (old && item[8] != null && old[8] != null && item[8] !== old[8] && item.slice(2, 6).every((n, i) => Math.abs(n - old[i + 2]) < 0.5) && !found.has(item[0])) {
185
+ found.set(item[0], `same-box content change: ${item[1]} changes text or drawing at ${(frame.t / 1000 / slow).toFixed(2)}s${frame.mark ? ` [${frame.mark}]` : ''}; inspect the transition in motion (geometry alone cannot judge it)`)
186
+ }
187
+ seen.set(item[0], item)
188
+ }
189
+ }
190
+ return [...found.values()]
191
+ }
package/jumps.mjs ADDED
@@ -0,0 +1,68 @@
1
+ #!/usr/bin/env node
2
+ // Record every visible Stage from its first rendered frame, on any host page.
3
+ // Geometry detects snaps/drift; same-box text/icon changes require visual review.
4
+ import { launch } from './browser.mjs'
5
+ import { record, analyse, contentChanges } from './jumps-core.mjs'
6
+ import { instrumentationSource, coverage, reportResult, printCoverage } from './verification.mjs'
7
+ import { mkdirSync, writeFileSync } from 'node:fs'
8
+ import { dirname, resolve } from 'node:path'
9
+
10
+ const args = process.argv.slice(2)
11
+ const options = { ms: 20000, width: 1280, select: null, report: null, strict: false }
12
+ let url
13
+ try {
14
+ for (let i = 0; i < args.length; i++) {
15
+ const arg = args[i]
16
+ if (arg === '--help') { console.log('usage: node scripts/jumps.mjs <url> [--ms 20000] [--width 1280] [--select ".demo"] [--report report.json] [--strict]'); process.exit(0) }
17
+ if (arg === '--strict') options.strict = true
18
+ else if (/^--(ms|width|select|report)$/.test(arg)) {
19
+ if (!args[i + 1] || args[i + 1].startsWith('--')) throw new Error(`${arg} requires a value`)
20
+ options[arg.slice(2)] = args[++i]
21
+ } else if (arg.startsWith('--') || url) throw new Error(`unexpected argument: ${arg}`)
22
+ else url = arg
23
+ }
24
+ if (!url) throw new Error('a URL is required; use --help')
25
+ for (const name of ['ms', 'width']) {
26
+ options[name] = Number(options[name])
27
+ if (!Number.isInteger(options[name]) || options[name] <= 0) throw new Error(`--${name} must be a positive integer`)
28
+ }
29
+ } catch (error) { console.error(`jumps: ${error.message}`); process.exit(2) }
30
+ const browser = await launch()
31
+ const page = await browser.newPage({ viewport: { width: options.width, height: 900 } })
32
+ const errors = []
33
+ page.on('pageerror', (error) => errors.push(`page: ${error.message}`))
34
+ page.on('response', (response) => { if (response.status() >= 400 && !/\/favicon\./.test(response.url())) errors.push(`resource: ${response.status()} ${response.url()}`) })
35
+ await page.addInitScript({ content: instrumentationSource(record, options.select) })
36
+ let snapshot
37
+ try {
38
+ await page.goto(url, { waitUntil: 'domcontentloaded' })
39
+ await page.waitForFunction(() => Object.keys(window.__ssVerification.stages).length || window.__ssVerification.errors.length, null, { timeout: 30000 })
40
+ const started = await page.evaluate(() => window.__ssVerification)
41
+ if (started.errors.length) throw new Error(started.errors.join('; '))
42
+ const token = Math.random().toString(36)
43
+ await page.evaluate((token) => { window.__ssVerification.token = token }, token)
44
+ await page.waitForTimeout(options.ms)
45
+ snapshot = await page.evaluate(() => { window.__ssVerification.stopped = true; return window.__ssVerification })
46
+ if (snapshot.token !== token) errors.push('page navigated during recording; rerun after changes settle')
47
+ } catch (error) { errors.push(error.message) }
48
+ await browser.close()
49
+
50
+ const stages = Object.entries(snapshot?.stages || {}).map(([key, stage]) => ({
51
+ key, label: stage.label,
52
+ coverage: coverage(stage.frames, { requestedMs: options.ms }),
53
+ findings: analyse(stage.frames), manual: contentChanges(stage.frames),
54
+ }))
55
+ const result = reportResult({ stages, errors: [...errors, ...(snapshot?.errors || [])], strict: options.strict })
56
+ for (const stage of stages) {
57
+ printCoverage(stage.key, stage.coverage)
58
+ for (const line of stage.findings) console.log(`[${stage.key}] ${line}`)
59
+ for (const line of stage.manual) console.log(`[${stage.key}] manual: ${line}`)
60
+ }
61
+ for (const error of result.errors) console.error(`incomplete: ${error}`)
62
+ console.log(`jumps: ${result.status}; visual motion review is still required`)
63
+ if (options.report) {
64
+ const path = resolve(options.report)
65
+ mkdirSync(dirname(path), { recursive: true })
66
+ writeFileSync(path, JSON.stringify(result, null, 2) + '\n')
67
+ }
68
+ process.exitCode = result.exitCode
@@ -0,0 +1,164 @@
1
+ // Runs in the browser. Deliberately checks CSS box constraints, not glyph ink
2
+ // centering or the visual balance of arbitrary shapes. Shared by film and layout.
3
+ export function auditLayout(root) {
4
+ const findings = [], deferred = [], manual = []
5
+ const checked = { controls: 0, paddedContainers: 0, compositionCrops: 0 }
6
+ const px = (value) => parseFloat(value) || 0
7
+ const round = (value) => Math.round(value * 100) / 100
8
+ const name = (el) => `${el.tagName.toLowerCase()}${el.id ? `#${el.id}` : typeof el.className === 'string' && el.className.trim() ? '.' + el.className.trim().split(/\s+/).join('.') : ''}`
9
+ const all = [root, ...root.querySelectorAll('*')]
10
+ const animations = document.getAnimations().filter((a) => a.playState === 'running')
11
+ const geometry = /^(?:transform|translate|rotate|scale|width|height|minWidth|maxWidth|minHeight|maxHeight|blockSize|inlineSize|gridTemplateRows|gridTemplateColumns|flexBasis|gap|rowGap|columnGap|padding.*|margin.*|top|left|right|bottom)$/
12
+ const moving = (el) => animations.some((a) => {
13
+ const target = a.effect?.target
14
+ // Only motion of this box or an ancestor. A spinning descendant cannot
15
+ // excuse a broken outer control or a compressed window's bottom gutter.
16
+ return target instanceof Element && (target === el || target.contains(el)) &&
17
+ a.effect.getKeyframes().some((frame) => Object.keys(frame).some((property) => geometry.test(property)))
18
+ })
19
+ const visible = (el) => {
20
+ const r = el.getBoundingClientRect()
21
+ if (r.width < 1 || r.height < 1 || r.bottom <= 0 || r.right <= 0 || r.top >= innerHeight || r.left >= innerWidth) return false
22
+ for (let a = el; a; a = a.parentElement) {
23
+ const cs = getComputedStyle(a)
24
+ if (cs.display === 'none' || cs.visibility === 'hidden' || Number(cs.opacity) < .05) return false
25
+ }
26
+ return true
27
+ }
28
+ const inFlow = (el, boundary) => {
29
+ for (let a = el; a && a !== boundary; a = a.parentElement) {
30
+ if (['absolute', 'fixed'].includes(getComputedStyle(a).position)) return false
31
+ }
32
+ return true
33
+ }
34
+ const control = (el) => el.matches('button, [role="button"], [data-layout-control]') ||
35
+ typeof el.className === 'string' && el.className.split(/\s+/).some((cls) => /(?:^|[-_])(?:button|btn)(?:$|[-_])/.test(cls))
36
+ const metrics = (el) => {
37
+ const cs = getComputedStyle(el), r = el.getBoundingClientRect()
38
+ // Computed sizes retain fractions; offsetHeight rounds them. Remove an
39
+ // axis-aligned stage scale without inventing an error from that rounding.
40
+ const w = px(cs.width) + (cs.boxSizing === 'border-box' ? 0 : px(cs.paddingLeft) + px(cs.paddingRight) + px(cs.borderLeftWidth) + px(cs.borderRightWidth))
41
+ const h = px(cs.height) + (cs.boxSizing === 'border-box' ? 0 : px(cs.paddingTop) + px(cs.paddingBottom) + px(cs.borderTopWidth) + px(cs.borderBottomWidth))
42
+ return { cs, r, sx: w > 0 ? r.width / w : 1, sy: h > 0 ? r.height / h : 1, h: h || r.height }
43
+ }
44
+ const add = (rule, el, message, evidence) => findings.push({ rule, element: name(el), message: `layout: ${name(el)} ${message}`, evidence })
45
+ for (const el of all.filter(control)) {
46
+ if (!visible(el)) continue
47
+ if (moving(el)) { deferred.push(`${name(el)}: control geometry is moving`); continue }
48
+ const { cs, r, sx, sy, h } = metrics(el)
49
+ if (cs.writingMode !== 'horizontal-tb') { deferred.push(`${name(el)}: non-horizontal writing mode`); continue }
50
+ // A label trimmed to its letters (text-box: trim-both cap alphabetic) is
51
+ // meant to be shorter than its line box; its parent holds the padding
52
+ if (cs.textBoxTrim && cs.textBoxTrim !== 'none') continue
53
+ const atoms = []
54
+ let movingText = false
55
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT)
56
+ for (let text; (text = walker.nextNode());) {
57
+ if (!text.textContent.trim() || !visible(text.parentElement) || !inFlow(text.parentElement, el)) continue
58
+ movingText ||= moving(text.parentElement)
59
+ const range = document.createRange(); range.selectNodeContents(text)
60
+ const line = px(getComputedStyle(text.parentElement).lineHeight)
61
+ for (const box of range.getClientRects()) {
62
+ if (box.width < .1 || box.height < .1) continue
63
+ const height = Math.max(box.height / sy, line)
64
+ atoms.push({ left: box.left, right: box.right, top: (box.top + box.bottom) / 2 - height * sy / 2, bottom: (box.top + box.bottom) / 2 + height * sy / 2 })
65
+ }
66
+ }
67
+ for (const child of el.querySelectorAll('svg, img, canvas')) {
68
+ if (visible(child) && inFlow(child, el)) {
69
+ const box = child.getBoundingClientRect(), style = getComputedStyle(child)
70
+ // A rotated plus still occupies its authored 24px layout box. Its
71
+ // 34px axis-aligned drawing envelope is a contour, not extra layout
72
+ // height. Treat contours as visual review, never as a padding defect.
73
+ const height = px(style.height) + (style.boxSizing === 'border-box' ? 0 : px(style.paddingTop) + px(style.paddingBottom) + px(style.borderTopWidth) + px(style.borderBottomWidth))
74
+ atoms.push({ left: box.left, right: box.right, top: (box.top + box.bottom - height * sy) / 2, bottom: (box.top + box.bottom + height * sy) / 2 })
75
+ }
76
+ }
77
+ if (!atoms.length) continue
78
+ checked.controls++
79
+ // A label's outgoing/incoming copies may overlap inside one clipped line.
80
+ // Their moving paint bounds are not extra layout rows. Still enforce the
81
+ // tallest authored line (so motion cannot hide height+padding overflow),
82
+ // but defer the full union and edge judgment until the text has settled.
83
+ const contentHeight = movingText
84
+ ? Math.max(...atoms.map(a => (a.bottom - a.top) / sy))
85
+ : (Math.max(...atoms.map((a) => a.bottom)) - Math.min(...atoms.map((a) => a.top))) / sy
86
+ const top = px(cs.paddingTop), bottom = px(cs.paddingBottom)
87
+ const borders = px(cs.borderTopWidth) + px(cs.borderBottomWidth)
88
+ const needed = contentHeight + top + bottom + borders
89
+ // A full line box must fit even when its ink looks optically centered.
90
+ // One CSS pixel of tolerance covers font metrics and fractional rounding.
91
+ if (needed > h + 1) add('control-block-fit', el,
92
+ `is ${round(h)}px high but its content, padding and borders need ${round(needed)}px`,
93
+ { height: round(h), contentHeight: round(contentHeight), paddingTop: top, paddingBottom: bottom, borders, requiredHeight: round(needed) })
94
+ if (movingText) { deferred.push(`${name(el)}: text is moving; checked minimum line fit, deferred combined bounds`); continue }
95
+ const left = px(cs.paddingLeft), right = px(cs.paddingRight)
96
+ const leftGap = (Math.min(...atoms.map((a) => a.left)) - r.left) / sx - px(cs.borderLeftWidth)
97
+ const rightGap = (r.right - Math.max(...atoms.map((a) => a.right))) / sx - px(cs.borderRightWidth)
98
+ // Narrow evidence: near-zero CSS padding AND visible content against that
99
+ // edge, with a real inset at the opposite edge. Ordinary optical 1–2px
100
+ // adjustments, icon-only buttons and asymmetric dropdown affordances pass.
101
+ if ((left <= 1 && right >= 6 && leftGap <= 2 && rightGap >= 5) ||
102
+ (right <= 1 && left >= 6 && rightGap <= 2 && leftGap >= 5)) {
103
+ add('control-edge-inset', el, `puts content ${round(leftGap)}px from the left and ${round(rightGap)}px from the right (CSS padding ${left}px / ${right}px)`,
104
+ { paddingLeft: left, paddingRight: right, leftGap: round(leftGap), rightGap: round(rightGap) })
105
+ }
106
+ }
107
+ for (const el of all) {
108
+ if (control(el) || !el.children.length || !visible(el) || el.matches('html, body, .ss-stage, .ss-fit') || el.closest('[data-crop]')) continue
109
+ const { cs, r, sy } = metrics(el)
110
+ const padding = px(cs.paddingBottom)
111
+ if (padding < 6 || cs.display === 'inline' || ['auto', 'scroll'].includes(cs.overflowY)) continue
112
+ const children = [...el.children].filter((child) => visible(child) && inFlow(child, el))
113
+ if (!children.length) continue
114
+ const last = children.reduce((a, b) => a.getBoundingClientRect().bottom > b.getBoundingClientRect().bottom ? a : b)
115
+ if (moving(el) || moving(last)) { deferred.push(`${name(el)}: bottom content geometry is moving`); continue }
116
+ let edge = r.bottom - px(cs.borderBottomWidth) * sy, boundary = el
117
+ // Respect the closest real frame, including .ss-window. Stage/viewport
118
+ // crops are composition choices and do not redefine a body's padding.
119
+ for (let a = el.parentElement; a && a !== root.parentElement; a = a.parentElement) {
120
+ if (a.matches('.ss-stage, .ss-fit') || a.hasAttribute('data-crop')) break
121
+ const ac = getComputedStyle(a)
122
+ if (['auto', 'scroll'].includes(ac.overflowY)) break
123
+ if (['hidden', 'clip'].includes(ac.overflowY)) {
124
+ const ar = a.getBoundingClientRect(), asy = metrics(a).sy
125
+ const lower = ar.bottom - px(ac.borderBottomWidth) * asy
126
+ if (lower < edge) { edge = lower; boundary = a }
127
+ }
128
+ if (a === root) break
129
+ }
130
+ checked.paddedContainers++
131
+ const available = (edge - last.getBoundingClientRect().bottom) / sy
132
+ if (available < padding - 2) add('container-block-inset', el,
133
+ `leaves ${round(available)}px below its last child inside ${name(boundary)}, short of its ${padding}px bottom padding`,
134
+ { paddingBottom: padding, availableBottom: round(available), boundary: name(boundary), lastChild: name(last) })
135
+ }
136
+ // A deliberate outer crop does not excuse a second, unexplained cut inside
137
+ // it. A complete small window is fine; only a window actually crossing the
138
+ // inner Stage's clip is a candidate. Transparent object margins are ignored.
139
+ for (const window of all.filter(el => el.matches('.ss-window') && visible(el))) {
140
+ const stage = window.closest('.ss-stage')
141
+ const tile = stage?.parentElement?.closest('[data-crop]')
142
+ if (!stage || !tile || !root.contains(tile)) continue
143
+ if (moving(window) || moving(stage)) { deferred.push(`${name(window)}: composition crop geometry is moving`); continue }
144
+ const w = window.getBoundingClientRect(), s = stage.getBoundingClientRect(), t = tile.getBoundingClientRect(), cs = getComputedStyle(stage)
145
+ checked.compositionCrops++
146
+ const axes = []
147
+ if (['hidden', 'clip'].includes(cs.overflowX) && w.right > s.right + 2 && t.right > s.right + 4) axes.push('right')
148
+ if (['hidden', 'clip'].includes(cs.overflowY) && w.bottom > s.bottom + 2 && t.bottom > s.bottom + 4) axes.push('bottom')
149
+ if (axes.length) add('nested-composition-crop', window,
150
+ `is cut at the inner Stage's ${axes.join(' and ')} edge before the outer composition ends; inspect this internal crop`,
151
+ { axes, stage: name(stage), tile: name(tile), rightRemainder: round(t.right - s.right), bottomRemainder: round(t.bottom - s.bottom) })
152
+ }
153
+ const frames = all.filter((el) => el.tagName === 'IFRAME' && visible(el)).length
154
+ if (frames) manual.push(`${frames} visible iframe(s) were not inspected; check their direct content URLs separately.`)
155
+ manual.push('This snapshot checks box fit and authored insets; inspect optical centering, shape contours, interaction states and motion visually.')
156
+ return { findings, checked, deferred: [...new Set(deferred)], manual }
157
+ }
158
+
159
+ export function layoutResult(scopes, errors = [], strict = false) {
160
+ const count = scopes.reduce((n, scope) => n + scope.checked.controls + scope.checked.paddedContainers + (scope.checked.compositionCrops || 0), 0)
161
+ const incomplete = errors.length > 0 || count === 0 || scopes.some((scope) => scope.deferred.length > 0)
162
+ const issues = scopes.some((scope) => scope.findings.length > 0)
163
+ return { status: incomplete ? 'inconclusive' : issues ? 'issues' : 'no-issues-detected', exitCode: incomplete ? 2 : strict && issues ? 1 : 0, scopes, errors: count ? errors : [...errors, 'no supported visible controls or padded containers were checked'], manualReviewRequired: true }
164
+ }
package/layout.mjs ADDED
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env node
2
+ // Check actual box fit in a host page, including controls outside a Stage.
3
+ import { launch } from './browser.mjs'
4
+ import { auditLayout, layoutResult } from './layout-core.mjs'
5
+ import { mkdirSync, writeFileSync } from 'node:fs'
6
+ import { dirname, resolve } from 'node:path'
7
+
8
+ const args = process.argv.slice(2)
9
+ const options = { select: 'body', width: 1280, delay: 300, report: null, screenshot: null, strict: false }
10
+ let url
11
+ try {
12
+ for (let i = 0; i < args.length; i++) {
13
+ const arg = args[i]
14
+ if (arg === '--help') { console.log('usage: node scripts/layout.mjs <url> [--select body] [--width 1280] [--delay 300] [--report layout.json] [--screenshot layout.png] [--strict]\nChecks visible controls and padded containers in this document at one snapshot. Iframes need a separate direct URL check. Exit 2 = incomplete; --strict exits 1 for findings. The optional screenshot captures the 1000px-high viewport. No motion approval.'); process.exit(0) }
15
+ if (arg === '--strict') options.strict = true
16
+ else if (/^--(select|width|delay|report|screenshot)$/.test(arg)) {
17
+ if (!args[i + 1] || args[i + 1].startsWith('--')) throw new Error(`${arg} requires a value`)
18
+ options[arg.slice(2)] = args[++i]
19
+ } else if (arg.startsWith('--') || url) throw new Error(`unexpected argument: ${arg}`)
20
+ else url = arg
21
+ }
22
+ if (!url) throw new Error('a URL is required; use --help')
23
+ for (const name of ['width', 'delay']) {
24
+ options[name] = Number(options[name])
25
+ if (!Number.isInteger(options[name]) || options[name] < (name === 'width' ? 1 : 0)) throw new Error(`--${name} must be ${name === 'width' ? 'a positive' : 'a nonnegative'} integer`)
26
+ }
27
+ } catch (error) { console.error(`layout: ${error.message}`); process.exit(2) }
28
+ const browser = await launch()
29
+ const page = await browser.newPage({ viewport: { width: options.width, height: 1000 } })
30
+ const errors = [], scopes = []
31
+ page.on('pageerror', (error) => errors.push(`page: ${error.message}`))
32
+ page.on('response', (response) => { if (response.status() >= 400 && !/\/favicon\./.test(response.url())) errors.push(`resource: ${response.status()} ${response.url()}`) })
33
+ try {
34
+ await page.goto(url, { waitUntil: 'domcontentloaded' })
35
+ await page.locator(options.select).first().waitFor({ state: 'visible', timeout: 10000 })
36
+ await page.evaluate(() => document.fonts.ready)
37
+ await page.waitForTimeout(options.delay)
38
+ for (const root of await page.locator(options.select).all()) {
39
+ if (await root.isVisible()) scopes.push({ selector: options.select, ...await root.evaluate(auditLayout) })
40
+ }
41
+ if (options.screenshot) {
42
+ const path = resolve(options.screenshot)
43
+ mkdirSync(dirname(path), { recursive: true })
44
+ await page.screenshot({ path })
45
+ console.log(`layout screenshot: ${path}`)
46
+ }
47
+ } catch (error) { errors.push(error.message) }
48
+ await browser.close()
49
+ const result = layoutResult(scopes, errors, options.strict)
50
+ result.viewport = { width: options.width, height: 1000 }
51
+ result.url = url
52
+ for (const scope of scopes) {
53
+ console.log(`layout coverage: ${scope.checked.controls} controls, ${scope.checked.paddedContainers} padded containers`)
54
+ for (const finding of scope.findings) console.log(finding.message)
55
+ for (const deferred of scope.deferred) console.log(`incomplete: ${deferred}`)
56
+ for (const manual of scope.manual) console.log(`manual: ${manual}`)
57
+ }
58
+ for (const error of result.errors) console.error(`incomplete: ${error}`)
59
+ console.log(`layout: ${result.status}; this snapshot is not visual approval`)
60
+ if (options.report) {
61
+ const path = resolve(options.report)
62
+ mkdirSync(dirname(path), { recursive: true })
63
+ writeFileSync(path, JSON.stringify(result, null, 2) + '\n')
64
+ }
65
+ process.exitCode = result.exitCode