Raven-1/ui-web/scripts/check-css.mjs
Dizhan Xue 4edb838579
fix(ui-web): drop the initial-letter tile and draw an unmarked entrance plain (#724)
## Summary

The memory page drew every detail header behind a coloured square
holding the title's first character, upper-cased. A CJK title has no
initial, so the square showed one Chinese character as though it were
one, and the title then sat 48px right of the DETAIL label and the body
under it.

Two surfaces could still draw that tile, and both lose it:

- the memory detail header, which now takes no mark at all, so its title
  lines up with the section beneath it;
- ChannelMark's fallback, for an id the mark table has no file for or a
  file that fails to load, which now draws a plain mark on the same
  plate mail and Matrix already use. Its `name` prop went with the tile,
  since nothing else read it, so the row's name can no longer reach a
  component that must choose by channel id.

SetupRow's Tile was the last producer, so `.pmtile` leaves page.css with
its eight tints and the five per-container size rules, and check-css
loses the allowlist entry that let it carry literal colours.

Both CSS gates read their expected geometry off `.pmtile`'s own rule, so
each now states what it guards directly: the channel mark declares a
whole box that neither of its slots overrides, and an agent mark gets a
whole square box in every slot that resizes it. That is weaker than what
it replaces -- the channel mark's box was pinned against the tile's one
rule, so resizing the tile moved the guard with it -- and there is no
longer a second rule to derive it from. The agent-mark slots are now
read off the stylesheet rather than hand-listed, which the test's own
"every slot" wording had been claiming without checking.

Deliberately not done, and left for a separate decision: `SetupRow.tsx`
has had no call site since schedules, channels and memory moved into the
settings dialog and TwoPane replaced its row. This change removes the
last live export from that file, so the whole module and its `.surow`
rules are now unreferenced. Deleting a component is a wider call than
removing a tile, so it stays.

Scope worth stating: the channel fallback is close to unreachable in
practice. tests/test_ui_channel_marks.py asserts that the mark table
plus the generic set equals the adapter set and that every named file
ships, so an unknown id cannot occur for a real channel and a 404 cannot
occur at build time. What remains is a browser failing to decode a file
that is present. The user-visible change is therefore the memory page;
the fallback is the same defect fixed where it could recur.

The plain mark's glyph is a judgement call. It is a neutral outline on
the existing inset plate, matching the envelope's stroke weight, chosen
over an empty plate because an empty one reads as a broken image.

## Type

- [x] Fix
- [ ] Feature
- [ ] Docs
- [ ] CI / tooling
- [ ] Refactor
- [ ] Other

## Verification

Run in a worktree at this branch's head, rebased onto main after the
chat-view change landed. That change adds a dependency, so this worktree
was given its own node_modules rather than a link to another checkout's;
`npx tsc --noEmit -p tsconfig.json --listFiles` confirms the compiler
read this tree's copies of the edited files.

- `npx tsc --noEmit -p tsconfig.json` -- exit 0, no errors.
- `./node_modules/.bin/eslint .` -- exit 0, with the four pre-existing
  `react-hooks/exhaustive-deps` warnings. The one in ConnectionsPage.tsx
  is at line 566; the lines edited here are 175 and 227.
- `vitest run --no-file-parallelism scripts/gates src/components
  src/features/memory src/features/connections` -- 324 of 326 passed.
  Both failures are in scripts/gates/boot-order.test.mjs, which fails
  three at a clean detached origin/main under the same command, so this
  head's set is a strict subset of the base's. 0 introduced.
- `vitest run` (the whole suite, as CI runs it) -- 246 of 2880 failed
  here against 262 of 2880 at origin/main, and the two sets differ in
  both directions: 14 fail only here, 30 only there. That is this box's
  node-26 localStorage artifact rather than a regression, and all 14 sit
  in files this change does not touch. At the granularity where the
  result is stable -- one file, its own process, a fresh storage db --
  head and base are identical: src/state/session/registry.test.ts gives
  3 failed and 25 passed, three runs of three, on each.
- `uv run --frozen --all-extras pytest tests/test_ui_channel_marks.py
  -q` -- 7 passed. This one matters because it regex-parses
  ChannelMark.tsx and asserts the mark table still equals the adapter
  set.
- `node scripts/check-class-namespace.mjs`, `node
  scripts/check-css.mjs`, `node scripts/check-page.mjs` -- all OK. Two
  namespace pins were lowered in the same change, since removing the
  class put both lists under their budget.
- `npm run build` then `python3 build.py` -- built, boot-snapshot 290
  and 289 nodes matching golden, and the page 3,714 bytes smaller than
  the same two steps produce at origin/main.
- `make check-large-files`, `make check-source-language`,
  `scripts/check_commit_messages.py origin/main..HEAD` -- all exit 0.

Both rewritten gates were mutation-proved rather than assumed: dropping
`border-radius` from `.channel-mark` reddens the first, adding a
`.two-pane-head .channel-mark` override reddens the second, and dropping
`border-radius` from `.pmdhead > .agent-mark` reddens the agent-mark
one. The stylesheet was restored from HEAD after each and `git diff
HEAD` confirmed empty.

Rendering was checked in headless Chrome against the real stylesheet and
the real icon files, in both themes, because happy-dom applies no
stylesheet and none of the above can see a pixel. The before state was
generated from origin/main's own copy of the component rather than
hand-written.

- [x] Relevant tests pass locally
- [x] Relevant lint / type checks pass locally
- [ ] User-facing docs or screenshots are updated when needed

No doc names the tile, and the repo does not carry screenshots for this
surface.

## Risk

User-visible, and only in appearance. A memory detail header loses its
coloured square and its title moves 48px left to line up with the text
below it. An entrance whose icon cannot be drawn shows a neutral outline
instead of a coloured letter; every entrance that ships a mark is
unaffected.

No behaviour, data or wire shape changes. `ChannelMark` loses a required
prop, which is a compile error at any missed call site rather than a
silent one, and both call sites are in this diff.

Rollback is a revert of this pull request; nothing persists and nothing
migrates.

One note for whoever lands second: an open pull request also edits
page.css and check-class-namespace.mjs. It touches neither the pins
lowered here nor any `.pmtile` rule, so the overlap is textual only.

- [x] Security impact considered
- [x] Backward compatibility considered
- [x] Rollback path is clear for risky changes

## Related Issues

N/A

---------

Co-authored-by: Claude (claude-opus-5[1m]) <noreply@anthropic.com>
2026-09-23 17:52:50 +08:00

161 lines
7.0 KiB
JavaScript

// Color-token gate for the page stylesheet. Zero dependencies, same contract
// as check-page.mjs: runnable in CI with nothing installed.
//
// node ui-web/scripts/check-css.mjs
//
// Rule: a color literal -- #hex, rgb()/rgba(), hsl()/hsla() -- may appear only
// 1. on a line that defines a custom property (`--token: ...`), which is
// where every theme's palette is written; or
// 2. in a rule the allowlist below names, where the literal IS the design:
// theme-preview swatches render their theme's own colors as data, mask
// images address a luminance ramp rather than a color, and one
// color-mix() derives a rim from structural white; or
// 3. inside a shadow, filter or gradient AND carrying an alpha component,
// which is what makes it a ramp over whatever is behind it rather than a
// color chosen for one theme.
// Everything else must go through var(--token). This is what keeps "which
// color is this role" answerable in one place per theme.
//
// The check is deliberately position-independent. An earlier version exempted
// everything above the first ordinary rule, on the theory that the token
// blocks live at the top -- which made the gate depend on where a rule sits
// rather than on what it says: a colored rule written above the reset passed,
// and the identical rule at the end of the file failed. The `--token:` guard
// already covers every definition wherever it appears, so there is nothing
// for a region to add.
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
const path = join(fileURLToPath(new URL('..', import.meta.url)), 'src', 'styles', 'page.css')
const css = readFileSync(path, 'utf8')
const lines = css.split('\n')
// Properties whose literals paint a ramp rather than name a role: a shadow is
// black at 6%, not a theme color. The exemption is NOT the property alone --
// `box-shadow: 0 0 0 2px #b4402f` is a role color frozen to one theme, and a
// focus ring or invalid-field outline is written as a shadow more often than
// as a border. What earns the exemption is the alpha: a literal that carries
// one is a ramp over whatever is behind it, and every such literal in this
// file has one today.
const RAMP_PROPS = /^(box-shadow|text-shadow|filter|backdrop-filter|-webkit-backdrop-filter)$/
// Selectors and values that carry a literal on purpose. Checked before the
// ramp rule, since a couple of them are opaque by design. Additions here are
// review-visible.
const ALLOW = [
/\.thpick\b/, // theme picker light/dark preview miniatures
/color-mix\(in oklab, #fff/, // structural rim derivation
/mask(-image)?\s*:/, // alpha ramps addressed by luminance, not color
/-webkit-mask(-image)?\s*:/,
]
// Two objects, one pattern, and they must stay that way: a global regex makes
// `.test()` a stateful reader -- it writes `lastIndex` and the next call
// resumes from there -- so sharing one with the scan below silently skipped
// any declaration shorter than the offset the previous one left behind.
const LITERAL = /#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?)\s*\(/
const LITERAL_G = new RegExp(LITERAL.source, 'g')
// Does every literal in this value carry an alpha component? `rgba()/hsla()`
// and the `rgb(r g b / a)` slash form do by construction; a hex does when it
// is 4 or 8 digits. Anything else is opaque, which means it is a color choice.
const allLiteralsHaveAlpha = (decl) => {
LITERAL_G.lastIndex = 0
for (let m; (m = LITERAL_G.exec(decl)); ) {
const hit = m[0]
if (hit.startsWith('#')) {
const digits = hit.slice(1).length
if (digits !== 4 && digits !== 8) return false
continue
}
if (/^(rgba|hsla)/.test(hit)) continue
// rgb(/hsl(: alpha only via the slash form, inside this call's parens.
const close = decl.indexOf(')', m.index)
if (close < 0 || !decl.slice(m.index, close).includes('/')) return false
}
return true
}
// Scanned declaration by declaration rather than line by line: a `box-shadow`
// often wraps across three lines, and a line-based reader sees the wrapped
// tail as an anonymous literal with no property attached to judge it by.
const noComments = css.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' '))
const lineOf = (index) => noComments.slice(0, index).split('\n').length
const offenders = []
// A stack, not one string: a rule nested in `@media` has two enclosing
// selectors and the inner one is the one that says what the rule is for.
// Reading only the outermost made every rule inside a media block look like
// it was selected by the media query.
const stack = []
let buf = ''
let bufAt = 0
const flush = () => {
const decl = buf.trim()
buf = ''
if (!decl || !LITERAL.test(decl)) return
const colon = decl.indexOf(':')
const prop = colon < 0 ? '' : decl.slice(0, colon).trim()
if (prop.startsWith('--')) return // a token definition, wherever it sits
const where = stack.join(' ')
if (ALLOW.some((re) => re.test(where) || re.test(decl))) return
if ((RAMP_PROPS.test(prop) || /gradient\(/.test(decl)) && allLiteralsHaveAlpha(decl)) return
offenders.push(`${lineOf(bufAt)}: ${stack[stack.length - 1].trim().slice(0, 44)} { ${decl.slice(0, 66)} }`)
}
// Quote-aware: a `;` inside a quoted value does not end a declaration. Without
// this a data-URI token (`url('data:image/svg+xml;utf8,...')`) is cut in two,
// the tail is judged as its own declaration with `utf8,<svg` for a property,
// and the failure tells the reader to use a token on a line that already is
// one. `url()` is the only unquoted construct that could hide a `;`, and this
// file always quotes it.
let quote = ''
for (let i = 0; i < noComments.length; i++) {
const ch = noComments[i]
if (quote) {
if (ch === quote && noComments[i - 1] !== '\\') quote = ''
buf += ch
continue
}
if (ch === "'" || ch === '"') {
quote = ch
buf += ch
} else if (ch === '{') {
stack.push(buf.trim())
buf = ''
} else if (ch === '}') {
flush()
stack.pop()
buf = ''
} else if (ch === ';') {
flush()
} else {
if (!buf.trim()) bufAt = i
buf += ch
}
}
// The overlay ladder: any fixed-surface layer must come from a --z token.
// Component-internal stacking stays literal but small; the threshold keeps
// the two regimes from blurring.
for (let i = 0; i < lines.length; i++) {
const line = lines[i]
const m = line.match(/z-index:\s*(-?\d+)/)
if (!m) continue
if (/--z-[a-z-]+\s*:/.test(line)) continue // ladder definition
if (/z-index:\s*var\(/.test(line)) continue
if (Math.abs(parseInt(m[1], 10)) >= 10) {
offenders.push(`${i + 1}: raw overlay z-index -- use the --z ladder: ${line.trim().slice(0, 80)}`)
}
}
if (offenders.length) {
console.error(`check-css: ${offenders.length} raw color literal(s) outside the token contract:`)
for (const o of offenders) console.error(' ' + o)
console.error('Use var(--token) (define the token per theme block), or add the rule to the allowlist in this script with a reason.')
process.exit(1)
}
console.log('check-css: OK (color literals confined to tokens and the literal-by-design allowlist)')