scrollbar-styles.client.spec.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. /**
  2. * Scrollbar stylesheet contract, asserted against the CSS text on disk: every
  3. * --dsw-alias-scrollbar-* token design-platform.css defines has a consumer,
  4. * scrollbar.css binds the base-surface pair through the rebindable
  5. * indirection, the width variable mirrors the ::-webkit-scrollbar rule for
  6. * consumers that align beside the bar, and elevated surfaces rebind that
  7. * indirection in complete pairs. The expected token set is scanned out of
  8. * design-platform.css, so adding, renaming, or dropping a scrollbar token
  9. * moves these assertions with it.
  10. */
  11. import { readdirSync, readFileSync } from 'node:fs'
  12. import { join } from 'node:path'
  13. import { fileURLToPath } from 'node:url'
  14. import { describe, expect, it } from 'vitest'
  15. /** One flattened CSS rule: its comma-separated selector parts and its declarations in source order. */
  16. interface CssRule {
  17. selectors: string[]
  18. declarations: [property: string, value: string][]
  19. }
  20. const STYLES = new URL('../src/styles/', import.meta.url)
  21. const PACKAGES_DIR = fileURLToPath(new URL('../../../', import.meta.url))
  22. const read = (name: string): string => readFileSync(fileURLToPath(new URL(name, STYLES)), 'utf8')
  23. const platformCss = read('design-platform.css')
  24. const scrollbarCss = read('scrollbar.css')
  25. /** Body attribute selecting the dark palette; ui-layout's ThemePresenter sets it. */
  26. const DARK_ATTRIBUTE = '[data-ds-dark-theme]'
  27. /** Alias tokens under test: the prefix the elevation pairs share. */
  28. const TOKEN_PREFIX = '--dsw-alias-scrollbar-'
  29. /** Prefix of the rebindable indirection scrollbar.css owns. */
  30. const INDIRECTION_PREFIX = '--dsh-scrollbar-'
  31. /** The one non-token rebind value: a surface that draws no thumb at all. */
  32. const HIDDEN_THUMB = 'transparent'
  33. /** The elevation rebind, spelled per property: value-wholeness, not token shape. */
  34. const ELEVATED_REBIND = new Map([
  35. ['--dsh-scrollbar-thumb', '--dsw-alias-scrollbar-bg-l2'],
  36. ['--dsh-scrollbar-thumb-hover', '--dsw-alias-scrollbar-hover-l2'],
  37. ].map(([property, token]) => [property!, `var(${token!})`]))
  38. /**
  39. * Flatten a stylesheet into rules. Whitespace, declaration order, and trailing
  40. * semicolons are normalized away; nesting and at-rules are not handled, which
  41. * no sheet under test uses for scrollbar declarations.
  42. * @param css - stylesheet text.
  43. * @returns one entry per rule, in source order.
  44. */
  45. function parseRules(css: string): CssRule[] {
  46. const withoutComments = css.replace(/\/\*[\s\S]*?\*\//g, ' ')
  47. const rules: CssRule[] = []
  48. // Destructuring defaults only satisfy noUncheckedIndexedAccess; both groups
  49. // are unconditional in the pattern.
  50. for (const [, selector = '', body = ''] of withoutComments.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
  51. const declarations = body
  52. .split(';')
  53. .map(part => part.trim())
  54. .filter(part => part.includes(':'))
  55. .map((part): [string, string] => {
  56. const colon = part.indexOf(':')
  57. return [part.slice(0, colon).trim(), part.slice(colon + 1).trim()]
  58. })
  59. rules.push({ selectors: selector.split(',').map(part => part.trim()), declarations })
  60. }
  61. return rules
  62. }
  63. /**
  64. * Half-open source span of one at-rule's block, excluding its prelude.
  65. * @param css - stylesheet text.
  66. * @param prelude - exact at-rule prelude to locate, without the opening brace.
  67. * @returns the block's brace offsets, or undefined when the prelude is absent.
  68. */
  69. function atRuleBlock(css: string, prelude: string): { start: number; end: number } | undefined {
  70. const opening = css.indexOf(`${prelude} {`)
  71. if (opening === -1) return undefined
  72. const start = css.indexOf('{', opening)
  73. let depth = 0
  74. for (let index = start; index < css.length; index += 1) {
  75. if (css[index] === '{') depth += 1
  76. else if (css[index] === '}') {
  77. depth -= 1
  78. if (depth === 0) return { start, end: index }
  79. }
  80. }
  81. throw new Error(`unbalanced braces after ${prelude}`)
  82. }
  83. /**
  84. * Custom-property names a value reads.
  85. * @param value - declaration value, possibly with nested var() calls.
  86. * @returns every referenced custom-property name, in source order.
  87. */
  88. function varReferences(value: string): string[] {
  89. return [...value.matchAll(/var\(\s*(--[\w-]+)/g)].map(([, name = '']) => name)
  90. }
  91. /**
  92. * Every CSS file shipped as package source, excluding build output and
  93. * installed dependencies.
  94. * @returns absolute paths of the stylesheets under packages/.
  95. */
  96. function packageStylesheets(): string[] {
  97. const found: string[] = []
  98. const walk = (dir: string): void => {
  99. for (const entry of readdirSync(dir, { withFileTypes: true })) {
  100. const path = join(dir, entry.name)
  101. if (entry.isDirectory()) {
  102. if (entry.name !== 'node_modules' && entry.name !== 'lib' && entry.name !== 'dist') walk(path)
  103. } else if (entry.name.endsWith('.css')) found.push(path)
  104. }
  105. }
  106. walk(PACKAGES_DIR)
  107. return found
  108. }
  109. /**
  110. * Tokens a stylesheet reads through its rendering declarations, following its
  111. * own custom-property definitions transitively so a token reached only through
  112. * an indirection counts. The walk starts from the standard-property
  113. * declarations, so a defined-but-unread indirection contributes nothing.
  114. * @param rules - parsed rules of one stylesheet.
  115. * @returns every `--dsw-*` token the sheet's rendering declarations depend on.
  116. */
  117. function tokensRendered(rules: CssRule[]): Set<string> {
  118. const definitions = new Map<string, string>()
  119. const pending: string[] = []
  120. for (const rule of rules) {
  121. for (const [property, value] of rule.declarations) {
  122. if (property.startsWith('--')) definitions.set(property, value)
  123. else pending.push(value)
  124. }
  125. }
  126. const reached = new Set<string>()
  127. const visited = new Set<string>()
  128. while (pending.length > 0) {
  129. for (const name of varReferences(pending.pop()!)) {
  130. if (name.startsWith('--dsw-')) reached.add(name)
  131. if (visited.has(name)) continue
  132. visited.add(name)
  133. const definition = definitions.get(name)
  134. if (definition !== undefined) pending.push(definition)
  135. }
  136. }
  137. return reached
  138. }
  139. const platformRules = parseRules(platformCss)
  140. const scrollbarRules = parseRules(scrollbarCss)
  141. const sorted = (names: Iterable<string>): string[] => [...names].sort()
  142. /**
  143. * Scrollbar tokens defined by the rules whose selectors carry (or do not
  144. * carry) the dark palette attribute.
  145. * @param dark - true to scan the dark blocks, false to scan the light blocks.
  146. * @returns the scrollbar token names defined there.
  147. */
  148. function definedTokens(dark: boolean): Set<string> {
  149. const names = new Set<string>()
  150. for (const rule of platformRules) {
  151. if (rule.selectors.every(selector => selector.includes(DARK_ATTRIBUTE)) !== dark) continue
  152. for (const [property] of rule.declarations) {
  153. if (property.startsWith(TOKEN_PREFIX)) names.add(property)
  154. }
  155. }
  156. return names
  157. }
  158. const lightTokens = definedTokens(false)
  159. const darkTokens = definedTokens(true)
  160. const allTokens = new Set([...lightTokens, ...darkTokens])
  161. /** Every scrollbar token any package stylesheet references, mapped to the files referencing it. */
  162. const referencedTokens = new Map<string, string[]>()
  163. /** Every indirection property any package stylesheet outside ui-theme declares, mapped to its declaring rules. */
  164. const rebindRules: { file: string; rule: CssRule }[] = []
  165. /**
  166. * What one stylesheet contributes to the elevated-surface question: which
  167. * elevated surfaces it paints, whether any rule scrolls, and whether it
  168. * rebinds. Kept per file rather than per rule because the elevated card and the
  169. * descendant that actually scrolls are separate rules in the same sheet, and
  170. * CSS text does not express which contains which.
  171. */
  172. interface SheetSurfaces {
  173. /** Elevated surface tokens this sheet paints anywhere. */
  174. elevated: Set<string>
  175. /** True when some rule declares `overflow*: auto|scroll`. */
  176. scrolls: boolean
  177. /**
  178. * True when some rule rebinds the indirection to an ELEVATION. A rule that
  179. * only hides the bar (`transparent`) does not count: it states no elevation,
  180. * so a sheet that hides its bars and also scrolls on an elevated surface
  181. * still owes the l2 pair for whatever draws a thumb there.
  182. */
  183. rebindsElevation: boolean
  184. }
  185. const sheetSurfaces = new Map<string, SheetSurfaces>()
  186. /** Properties whose `auto`/`scroll` value makes a rule a scroll container. */
  187. const OVERFLOW_PROPERTIES = ['overflow', 'overflow-x', 'overflow-y']
  188. /** Properties that paint a surface, and so identify the elevation a rule sits on. */
  189. const SURFACE_PROPERTIES = ['background', 'background-color']
  190. /**
  191. * Token families that name a SURFACE — a background an element is drawn on, and
  192. * so something a scrollbar can sit against. `--dsw-alias-button-*`,
  193. * `--dsw-alias-interactive-*`, and `--dsw-alias-markdown-*` reach the same dark
  194. * elevation rungs while naming a control or an inline span, which no scroll
  195. * container renders its bar against (ChatView's floating `.toBottom` pill,
  196. * CodeBlock's banner). Family, not geometry: a floating button legitimately
  197. * carries a radius, a shadow, and a fixed size, so shape cannot separate them.
  198. */
  199. const SURFACE_TOKEN_PATTERN = /^--dsw-(?:alias-bg-|specific-)/
  200. /**
  201. * The palette's own dark elevation ladder, resolved from `design-platform.css`:
  202. * `bg-layer-2` and `bg-layer-3` are the rungs above the base surfaces, and the
  203. * l1/l2 scrollbar split encodes exactly that step. Reading it from the palette
  204. * rather than from the sheets that happen to rebind is what lets the check flag
  205. * a surface NOBODY has rebound yet.
  206. * @returns surface tokens whose dark value sits on an elevated rung.
  207. */
  208. function elevatedRungs(): Set<string> {
  209. const definitions = new Map<string, string>()
  210. for (const rule of platformRules) {
  211. // Dark declarations come later in the sheet and overwrite the light ones,
  212. // which is the palette this distinction exists in.
  213. for (const [property, value] of rule.declarations) definitions.set(property, value)
  214. }
  215. const resolve = (name: string): string => {
  216. const seen = new Set<string>()
  217. let current = name
  218. while (definitions.has(current) && !seen.has(current)) {
  219. seen.add(current)
  220. const value = definitions.get(current)!
  221. const [reference] = varReferences(value)
  222. if (reference === undefined) return value
  223. current = reference
  224. }
  225. return current
  226. }
  227. const rungs = new Set([resolve('--dsw-alias-bg-layer-2'), resolve('--dsw-alias-bg-layer-3')])
  228. const tokens = new Set<string>()
  229. for (const name of definitions.keys()) {
  230. if (SURFACE_TOKEN_PATTERN.test(name) && rungs.has(resolve(name))) tokens.add(name)
  231. }
  232. return tokens
  233. }
  234. const elevatedSurfaces = elevatedRungs()
  235. for (const file of packageStylesheets()) {
  236. const rules = parseRules(readFileSync(file, 'utf8'))
  237. const surfaces: SheetSurfaces = { elevated: new Set(), scrolls: false, rebindsElevation: false }
  238. for (const rule of rules) {
  239. let rebinds = false
  240. let rebindsElevation = false
  241. const ruleSurfaces: string[] = []
  242. for (const [property, value] of rule.declarations) {
  243. if (property.startsWith(INDIRECTION_PREFIX) && file !== fileURLToPath(new URL('scrollbar.css', STYLES))) {
  244. rebinds = true
  245. if (value !== HIDDEN_THUMB) rebindsElevation = true
  246. }
  247. if (OVERFLOW_PROPERTIES.includes(property) && /\b(?:auto|scroll)\b/.test(value)) surfaces.scrolls = true
  248. if (SURFACE_PROPERTIES.includes(property)) ruleSurfaces.push(...varReferences(value))
  249. for (const token of varReferences(value)) {
  250. if (!token.startsWith(TOKEN_PREFIX)) continue
  251. referencedTokens.set(token, [...referencedTokens.get(token) ?? [], file])
  252. }
  253. }
  254. for (const token of ruleSurfaces) {
  255. if (elevatedSurfaces.has(token)) surfaces.elevated.add(token)
  256. }
  257. if (rebinds) rebindRules.push({ file, rule })
  258. if (rebindsElevation) surfaces.rebindsElevation = true
  259. }
  260. sheetSurfaces.set(file, surfaces)
  261. }
  262. describe('design-platform.css scrollbar tokens', () => {
  263. it('defines the same scrollbar token set in the light and the dark block', () => {
  264. // A token present only in the light block silently keeps its light value
  265. // under the dark palette, since the dark block only overrides.
  266. expect(allTokens.size).toBeGreaterThan(0)
  267. expect(sorted(lightTokens)).toEqual(sorted(allTokens))
  268. expect(sorted(darkTokens)).toEqual(sorted(allTokens))
  269. })
  270. it('resolves every scrollbar token to a static scale value, not to another alias', () => {
  271. // The alias layer is the only indirection in the token sheet: an alias
  272. // pointing at a second alias makes the dark override order-dependent.
  273. for (const rule of platformRules) {
  274. for (const [property, value] of rule.declarations) {
  275. if (!property.startsWith(TOKEN_PREFIX)) continue
  276. for (const reference of varReferences(value)) {
  277. expect(reference, `${property}: ${value}`).toMatch(/^--dsw-static-/)
  278. }
  279. }
  280. }
  281. })
  282. })
  283. describe('scrollbar token consumers', () => {
  284. it('every defined scrollbar token is referenced by some package stylesheet', () => {
  285. // Before scrollbar.css existed these tokens had no consumer at all and
  286. // every scroll container rendered the unthemed UA bar. A fifth token, or a
  287. // rename on one side only, leaves the new name unreferenced here.
  288. expect(sorted(referencedTokens.keys())).toEqual(sorted(allTokens))
  289. })
  290. it('every referenced scrollbar token is defined in design-platform.css', () => {
  291. // A dangling var() renders the UA default instead of failing loudly, so a
  292. // rename has to move the reference and the definition together.
  293. for (const [token, files] of referencedTokens) {
  294. expect(allTokens, files.join(', ')).toContain(token)
  295. }
  296. })
  297. })
  298. describe('scrollbar.css base-surface binding', () => {
  299. const rendered = tokensRendered(scrollbarRules)
  300. it('renders the l1 pair through the rebindable indirection', () => {
  301. // l1 is the base-surface default the indirection resolves to; the
  302. // indirection only counts as bound when a rendering declaration reads it.
  303. expect(rendered).toContain(`${TOKEN_PREFIX}bg-l1`)
  304. expect(rendered).toContain(`${TOKEN_PREFIX}hover-l1`)
  305. })
  306. it('routes the standard property and the WebKit thumb through the same indirection', () => {
  307. // A rebind on an elevated container has to move the Firefox and the WebKit
  308. // rendering together, which only holds while both read the same variable.
  309. const declaration = (property: string, selectorPart: string): string | undefined => scrollbarRules
  310. .filter(rule => rule.selectors.includes(selectorPart))
  311. .flatMap(rule => rule.declarations)
  312. .findLast(([name]) => name === property)?.[1]
  313. const thumbColor = declaration('scrollbar-color', 'body')
  314. expect(thumbColor).toBeDefined()
  315. const indirection = varReferences(thumbColor!)[0]
  316. expect(indirection).toBe(`${INDIRECTION_PREFIX}thumb`)
  317. expect(varReferences(declaration('background', '::-webkit-scrollbar-thumb')!)).toEqual([indirection])
  318. })
  319. })
  320. describe('scrollbar.css width variable', () => {
  321. const WIDTH_VARIABLE = `${INDIRECTION_PREFIX}width`
  322. it('defines the width variable on body as a static length', () => {
  323. // The overlay seat compensation reads a fixed number, not a second
  324. // indirection: the mirror check below compares the WebKit rule against
  325. // this value, so a var()-to-var() chain would compare one indirection to
  326. // another instead of pinning the number.
  327. const value = scrollbarRules
  328. .filter(rule => rule.selectors.includes('body'))
  329. .flatMap(rule => rule.declarations)
  330. .findLast(([property]) => property === WIDTH_VARIABLE)?.[1]
  331. expect(value, WIDTH_VARIABLE).toBeDefined()
  332. expect(value, WIDTH_VARIABLE).toMatch(/^\d+(?:\.\d+)?px$/)
  333. })
  334. it('mirrors the ::-webkit-scrollbar width rule with the variable value', () => {
  335. // The compensation stays aligned with the WebKit bar only while both read
  336. // the same number. A change to one side without the other puts the overlay
  337. // seat a band off from Chat on WebKit engines.
  338. const variableValue = scrollbarRules
  339. .filter(rule => rule.selectors.includes('body'))
  340. .flatMap(rule => rule.declarations)
  341. .findLast(([property]) => property === WIDTH_VARIABLE)?.[1]
  342. const webkitWidth = scrollbarRules
  343. .filter(rule => rule.selectors.includes('::-webkit-scrollbar'))
  344. .flatMap(rule => rule.declarations)
  345. .findLast(([property]) => property === 'width')?.[1]
  346. expect(webkitWidth, '::-webkit-scrollbar width').toBeDefined()
  347. expect(webkitWidth).toBe(variableValue)
  348. })
  349. it('every reader of the width variable outside ui-theme references a defined variable', () => {
  350. // The consumer is ConversationRoot's overlay composer seat
  351. // (`right: var(--dsh-scrollbar-width)`); a rename in scrollbar.css without
  352. // the consumer, or a typo in the consumer, leaves the value
  353. // guaranteed-invalid and the seat loses the band. The equal-rectangle e2e
  354. // would catch it only on an engine that draws the bar, so the sheet
  355. // contract states it here.
  356. const defined = new Set(
  357. scrollbarRules
  358. .flatMap(rule => rule.declarations)
  359. .filter(([property]) => property.startsWith(INDIRECTION_PREFIX))
  360. .map(([property]) => property),
  361. )
  362. expect(defined).toContain(WIDTH_VARIABLE)
  363. const readers: string[] = []
  364. for (const file of packageStylesheets()) {
  365. if (file === fileURLToPath(new URL('scrollbar.css', STYLES))) continue
  366. for (const rule of parseRules(readFileSync(file, 'utf8'))) {
  367. for (const [property, value] of rule.declarations) {
  368. for (const name of varReferences(value)) {
  369. if (name === WIDTH_VARIABLE) readers.push(`${file} ${rule.selectors.join(', ')}: ${property}`)
  370. }
  371. }
  372. }
  373. }
  374. expect(readers.length, 'compensation consumer').toBeGreaterThan(0)
  375. })
  376. })
  377. describe('scrollbar.css selectors', () => {
  378. const scrollbarColorSelectors = scrollbarRules
  379. .filter(rule => rule.declarations.some(([property]) => property === 'scrollbar-color'))
  380. .flatMap(rule => rule.selectors)
  381. it('declares scrollbar-color only where the body-scoped tokens are visible', () => {
  382. // design-platform.css defines the alias tokens on `body`, and custom
  383. // properties inherit downward only: the same declaration on `html` or
  384. // `:root` resolves to the guaranteed-invalid value, which computes
  385. // scrollbar-color to `auto` and drops the theming entirely.
  386. expect(scrollbarColorSelectors.length).toBeGreaterThan(0)
  387. for (const selector of scrollbarColorSelectors) {
  388. expect(selector, selector).toMatch(/^body\b/)
  389. }
  390. })
  391. it('defines the indirection where the alias tokens are visible', () => {
  392. const definesIndirection = ([property, value]: [string, string]): boolean =>
  393. property.startsWith(INDIRECTION_PREFIX) && value.includes(TOKEN_PREFIX)
  394. const hosts = scrollbarRules
  395. .filter(rule => rule.declarations.some(definesIndirection))
  396. .flatMap(rule => rule.selectors)
  397. expect(hosts.length).toBeGreaterThan(0)
  398. for (const selector of hosts) expect(selector, selector).toMatch(/^body\b/)
  399. })
  400. it('re-declares the scrollbar properties per element rather than inheriting them', () => {
  401. // scrollbar-width is not an inherited property, and an inherited
  402. // scrollbar-color carries the colour already substituted at `body`, which
  403. // a descendant rebinding the indirection could no longer change.
  404. expect(scrollbarColorSelectors).toContain('body *')
  405. const widthSelectors = scrollbarRules
  406. .filter(rule => rule.declarations.some(([property]) => property === 'scrollbar-width'))
  407. .flatMap(rule => rule.selectors)
  408. expect(widthSelectors).toContain('body *')
  409. })
  410. })
  411. describe('scrollbar.css rendering paths', () => {
  412. /** The gate prelude, spelled exactly as the sheet must spell it for the split to exist. */
  413. const GATE = '@supports not selector(::-webkit-scrollbar)'
  414. const withoutComments = scrollbarCss.replace(/\/\*[\s\S]*?\*\//g, ' ')
  415. const gate = atRuleBlock(withoutComments, GATE)
  416. /** Standard scrollbar properties, the ones whose non-`auto` values suppress the pseudo-elements. */
  417. const STANDARD_PROPERTIES = ['scrollbar-width', 'scrollbar-color']
  418. it('gates the standard properties behind the absence of the WebKit pseudo-element', () => {
  419. // A non-`auto` scrollbar-width or scrollbar-color makes Chromium and
  420. // Safari discard every ::-webkit-scrollbar* rule for that element,
  421. // ::-webkit-scrollbar-thumb:hover included. Declaring both paths
  422. // unconditionally therefore renders the hover token nowhere: the engines
  423. // implementing the hover pseudo-element are exactly the ones the standard
  424. // properties silence, and Firefox has no hover pseudo-element at all.
  425. expect(gate, GATE).toBeDefined()
  426. for (const property of STANDARD_PROPERTIES) {
  427. const offsets = [...withoutComments.matchAll(new RegExp(String.raw`(^|[;{\s])${property}\s*:`, 'g'))]
  428. .map(match => match.index)
  429. expect(offsets.length, property).toBeGreaterThan(0)
  430. for (const offset of offsets) {
  431. expect(offset, `${property} outside ${GATE}`).toBeGreaterThan(gate!.start)
  432. expect(offset, `${property} outside ${GATE}`).toBeLessThan(gate!.end)
  433. }
  434. }
  435. })
  436. it('leaves the WebKit pseudo-element rules outside the gate', () => {
  437. // Gating these in turn would only restate selector matching: an engine
  438. // without the pseudo-elements drops the rules as unknown selectors. Inside
  439. // the gate they would be dropped by the engines that do implement them,
  440. // which is every engine that can render them.
  441. const offsets = [...withoutComments.matchAll(/::-webkit-scrollbar/g)]
  442. .map(match => match.index)
  443. .filter(offset => withoutComments.slice(offset).search(/^[\w:-]*\s*[,{]/) === 0)
  444. expect(offsets.length).toBeGreaterThan(0)
  445. for (const offset of offsets) {
  446. expect(offset > gate!.start && offset < gate!.end, `::-webkit-scrollbar rule inside ${GATE}`).toBe(false)
  447. }
  448. })
  449. it('renders the hover token only through the pseudo-element path', () => {
  450. // The standard path has no hover counterpart — scrollbar-color states one
  451. // thumb colour and the engine derives its own hover treatment — so the
  452. // hover indirection has to be read outside the gate or it renders nowhere.
  453. const hoverOffsets = [...withoutComments.matchAll(new RegExp(String.raw`var\(\s*${INDIRECTION_PREFIX}thumb-hover`, 'g'))]
  454. .map(match => match.index)
  455. expect(hoverOffsets.length).toBeGreaterThan(0)
  456. for (const offset of hoverOffsets) {
  457. expect(offset > gate!.start && offset < gate!.end, 'hover indirection read inside the gate').toBe(false)
  458. }
  459. })
  460. })
  461. describe('elevated surface rebinds', () => {
  462. it('at least one surface rebinds the indirection', () => {
  463. expect(rebindRules.length).toBeGreaterThan(0)
  464. })
  465. it('each rebinding rule sets the thumb and the hover variable together', () => {
  466. // A surface rebinding only the resting colour keeps the l1 hover colour,
  467. // so the elevation is wrong only while the pointer is over the thumb.
  468. for (const { file, rule } of rebindRules) {
  469. const properties = rule.declarations.map(([property]) => property).filter(property => property.startsWith(INDIRECTION_PREFIX))
  470. expect(sorted(properties), `${file} ${rule.selectors.join(', ')}`).toEqual([
  471. `${INDIRECTION_PREFIX}thumb-hover`, `${INDIRECTION_PREFIX}thumb`,
  472. ].sort())
  473. }
  474. })
  475. it('each rebinding rule binds the indirection names scrollbar.css renders', () => {
  476. // A misspelled property name declares an unused variable, and the surface
  477. // silently keeps the base-surface colour.
  478. const rendered = new Set(
  479. scrollbarRules
  480. .flatMap(rule => rule.declarations)
  481. .filter(([property]) => !property.startsWith('--'))
  482. .flatMap(([, value]) => varReferences(value))
  483. .filter(name => name.startsWith(INDIRECTION_PREFIX)),
  484. )
  485. for (const { file, rule } of rebindRules) {
  486. for (const [property] of rule.declarations) {
  487. if (property.startsWith(INDIRECTION_PREFIX)) expect(rendered, `${file}: ${property}`).toContain(property)
  488. }
  489. }
  490. })
  491. it('rebinds the pair to one target: the l2 elevation pair, or transparent', () => {
  492. // The rule as a whole, not each declaration on its own. Per-declaration
  493. // checking accepts a MIXED rule — `thumb: transparent` beside
  494. // `thumb-hover: var(--dsw-alias-scrollbar-hover-l2)` — which repaints the
  495. // bar the moment the pointer reaches it while passing a gate that claims
  496. // the two targets are exclusive.
  497. //
  498. // The elevation half compares the whole value against the pair's canonical
  499. // spelling rather than checking that every token it mentions ends in `-l2`.
  500. // A shape check admits `color-mix(…, var(--dsw-alias-scrollbar-bg-l2) 85%,
  501. // white)` and a crossed pair (the hover token bound to the resting
  502. // property); neither is what the contract says.
  503. for (const { file, rule } of rebindRules) {
  504. const rebinds = rule.declarations.filter(([property]) => property.startsWith(INDIRECTION_PREFIX))
  505. const where = `${file} ${rule.selectors.join(', ')}`
  506. if (rebinds.every(([, value]) => value === HIDDEN_THUMB)) continue
  507. expect(rebinds.some(([, value]) => value === HIDDEN_THUMB), `${where}: mixes ${HIDDEN_THUMB} with an elevation`).toBe(false)
  508. for (const [property, value] of rebinds) {
  509. expect(value, `${where}: ${property}`).toBe(ELEVATED_REBIND.get(property))
  510. }
  511. }
  512. })
  513. it('resolves the elevated surface set from the palette ladder', () => {
  514. // The set has to come from the palette, not from the sheets that happen to
  515. // rebind: derived from rebinds it can only confirm what someone already
  516. // remembered, and a surface nobody has rebound yet — the case the check
  517. // exists for — would define itself as unelevated. Anchoring it here means a
  518. // new palette token on an elevated rung is in scope the moment it is
  519. // defined. `--dsw-specific-tip` is the regression that proved the point: it
  520. // resolves to the same dark rung as the menu surface, and the Todo panel
  521. // scrolled on it unrebound while a rebind-derived set stayed green.
  522. expect(elevatedSurfaces).toContain('--dsw-alias-bg-layer-2')
  523. expect(elevatedSurfaces).toContain('--dsw-alias-bg-layer-3')
  524. expect(elevatedSurfaces).toContain('--dsw-specific-menu')
  525. expect(elevatedSurfaces).toContain('--dsw-specific-input-major')
  526. expect(elevatedSurfaces).toContain('--dsw-specific-tip')
  527. // Base surfaces stay out, or every scroll container would be in scope and
  528. // the check would say nothing.
  529. expect(elevatedSurfaces).not.toContain('--dsw-alias-bg-base')
  530. expect(elevatedSurfaces).not.toContain('--dsw-alias-bg-layer-1')
  531. })
  532. it('every sheet that scrolls on an elevated surface rebinds', () => {
  533. // The failure this closes: a scroll container on an elevated surface that
  534. // nobody remembered to rebind renders the l1 thumb, which differs from l2
  535. // only in the dark palette and only for that one surface — invisible both in
  536. // review and in a light-palette screenshot. Four sheets shipped that way
  537. // (ui-primitives Menu, InputBar, QuestionComposer, TodoPanel) and review
  538. // caught them by hand, which is what this replaces.
  539. //
  540. // Surface-level, not element-level: the elevated card and the descendant
  541. // that scrolls are separate rules, and CSS text does not say which contains
  542. // which. What keeps that from over-reporting is the token FAMILY: only
  543. // `--dsw-alias-bg-*` and `--dsw-specific-*` name a surface, so a floating
  544. // button or an inline code span reaching the same rung is out of scope
  545. // (ChatView's `.toBottom`, CodeBlock's banner). Geometry cannot make that
  546. // call — a floating button carries a radius, a shadow, and a fixed size.
  547. for (const [file, surfaces] of sheetSurfaces) {
  548. if (!surfaces.scrolls || surfaces.rebindsElevation) continue
  549. expect([...surfaces.elevated], `${file} scrolls on an elevated surface without rebinding`).toEqual([])
  550. }
  551. })
  552. })