|
| 1 | +/** |
| 2 | + * ObjectUI |
| 3 | + * Copyright (c) 2024-present ObjectStack Inc. |
| 4 | + * |
| 5 | + * This source code is licensed under the MIT license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. |
| 7 | + */ |
| 8 | + |
| 9 | +/** |
| 10 | + * `Empty`'s base classes are override-friendly, and carry no inert border |
| 11 | + * (objectui#8525). |
| 12 | + * |
| 13 | + * ## What was wrong |
| 14 | + * |
| 15 | + * The container's base string read `… rounded-lg border-dashed p-6 … md:p-12`. |
| 16 | + * |
| 17 | + * * `md:p-12` is a different tailwind-merge VARIANT from any unprefixed |
| 18 | + * padding a caller passes, so `cn()` kept it next to `px-3 py-8`, and from |
| 19 | + * 768px up the `md:` rule won the cascade. Three app-shell sites that wrote |
| 20 | + * "less padding" (`ConversationsSidebar` `px-3 py-8`, `AuditPanel` `py-10` |
| 21 | + * twice) got the full 48px back on every desktop viewport — the card |
| 22 | + * measured 118.8px with and without the override, identical. Even a full |
| 23 | + * `p-4` lost: tailwind-merge dropped `p-6` for it and `md:p-12` survived. |
| 24 | + * * `border-dashed` sets `border-style` only. Preflight zeroes `border-width` |
| 25 | + * on every element and nothing at any of the 44 call sites supplied a |
| 26 | + * width, so the class drew nothing. Ruled: REMOVE it; ⛔ never add a width |
| 27 | + * here — a frame around every empty state is a product-wide visual decision |
| 28 | + * nobody has made, and it gets its own card if anyone wants it. |
| 29 | + * |
| 30 | + * ## The instrument, and why this is not a class-string pin |
| 31 | + * |
| 32 | + * The class attribute is read off the REAL component (RTL render). The CSS the |
| 33 | + * workspace Tailwind emits for exactly those classes is built through the public |
| 34 | + * compiler with explicit candidates and `base` pinned to the repo root, on the |
| 35 | + * shipped `@theme` (`packages/components/src/index.css`, the block every |
| 36 | + * consuming app loads). No source is scanned, so the reading does not depend on |
| 37 | + * the cwd Tailwind is launched from — this repo's scanning compiles do. |
| 38 | + * |
| 39 | + * A small cascade evaluator then walks that stylesheet in source order and |
| 40 | + * answers, per padding side and per viewport width, WHICH declaration wins. |
| 41 | + * Every selector here is one class inside one `@layer`, so source order is the |
| 42 | + * whole cascade: the evaluator implements no specificity and refuses any |
| 43 | + * selector it cannot map back to one class. The control below shows it |
| 44 | + * reproduces the defect on the OLD base shape, so a green reading on the new |
| 45 | + * shape is a measurement and not an inert instrument. |
| 46 | + * |
| 47 | + * Values are spacing units (`p-6` → 6). `12` on every side at 768px for a site |
| 48 | + * with NO override is the non-regression axis — the caricature that drops |
| 49 | + * `md:p-12` outright makes every override "win" and fails exactly there. `8` on |
| 50 | + * the block axis at 768px for `px-3 py-8` is the fix. |
| 51 | + */ |
| 52 | + |
| 53 | +import { describe, it, expect } from 'vitest'; |
| 54 | +import fs from 'node:fs'; |
| 55 | +import path from 'node:path'; |
| 56 | +import { fileURLToPath } from 'node:url'; |
| 57 | +import { render } from '@testing-library/react'; |
| 58 | +import { compile } from 'tailwindcss'; |
| 59 | +import { Empty } from '../custom/empty'; |
| 60 | + |
| 61 | +const here = path.dirname(fileURLToPath(import.meta.url)); |
| 62 | +const repoRoot = path.resolve(here, '../../../..'); |
| 63 | + |
| 64 | +/** The shipped `@theme` block, as `headerColor.test.ts` reads it. */ |
| 65 | +function themeBlock(): string { |
| 66 | + const css = fs.readFileSync(path.join(repoRoot, 'packages/components/src/index.css'), 'utf8'); |
| 67 | + const start = css.indexOf('@theme {'); |
| 68 | + expect(start, 'components/src/index.css should declare a @theme block').toBeGreaterThan(-1); |
| 69 | + let depth = 0; |
| 70 | + for (let i = css.indexOf('{', start); i < css.length; i++) { |
| 71 | + if (css[i] === '{') depth++; |
| 72 | + else if (css[i] === '}' && --depth === 0) return css.slice(start, i + 1); |
| 73 | + } |
| 74 | + throw new Error('unterminated @theme block'); |
| 75 | +} |
| 76 | + |
| 77 | +/** |
| 78 | + * One compiler per file. `build()` is cumulative on a compiler instance, so the |
| 79 | + * stylesheet grows across calls — harmless, because the evaluator applies only |
| 80 | + * the rules whose class is on the element it evaluates, as a browser would. |
| 81 | + */ |
| 82 | +let compilerPromise: ReturnType<typeof compile> | undefined; |
| 83 | +async function buildCss(candidates: string[]): Promise<string> { |
| 84 | + compilerPromise ??= (async () => { |
| 85 | + const twEntry = path.join(repoRoot, 'node_modules/tailwindcss/index.css'); |
| 86 | + const twDir = path.dirname(fs.realpathSync(twEntry)); |
| 87 | + return compile(`@import "tailwindcss";\n${themeBlock()}\n`, { |
| 88 | + base: repoRoot, |
| 89 | + loadStylesheet: async (id: string, base: string) => { |
| 90 | + const file = id === 'tailwindcss' |
| 91 | + ? path.join(twDir, 'index.css') |
| 92 | + : id.startsWith('tailwindcss/') |
| 93 | + ? path.join(twDir, id.slice('tailwindcss/'.length)) |
| 94 | + : path.resolve(base, id); |
| 95 | + return { base: path.dirname(file), path: file, content: fs.readFileSync(file, 'utf8') }; |
| 96 | + }, |
| 97 | + }); |
| 98 | + })(); |
| 99 | + return (await compilerPromise).build(candidates); |
| 100 | +} |
| 101 | + |
| 102 | +/** The class list the real component puts in the DOM for a given override. */ |
| 103 | +function classesOf(className?: string): string[] { |
| 104 | + const { container, unmount } = render(<Empty className={className} />); |
| 105 | + const el = container.querySelector('[data-slot="empty"]'); |
| 106 | + expect(el, 'Empty renders its data-slot="empty" container').not.toBeNull(); |
| 107 | + const classes = (el!.getAttribute('class') ?? '').split(/\s+/).filter(Boolean); |
| 108 | + unmount(); |
| 109 | + return classes; |
| 110 | +} |
| 111 | + |
| 112 | +// --------------------------------------------------------------------------- |
| 113 | +// A cascade evaluator for single-class utilities in one layer. |
| 114 | +// --------------------------------------------------------------------------- |
| 115 | + |
| 116 | +interface Rule { className: string; media: string[]; decls: Array<[string, string]> } |
| 117 | + |
| 118 | +/** Walk `css` and return every single-class rule inside `@layer utilities`, in source order. */ |
| 119 | +function utilityRules(css: string): Rule[] { |
| 120 | + const rules: Rule[] = []; |
| 121 | + const walk = (src: string, media: string[], inUtilities: boolean) => { |
| 122 | + let i = 0; |
| 123 | + while (i < src.length) { |
| 124 | + const open = src.indexOf('{', i); |
| 125 | + if (open === -1) break; |
| 126 | + let head = src.slice(i, open).replace(/\/\*[\s\S]*?\*\//g, '').trim(); |
| 127 | + const segs = head.split(/[;}]/); |
| 128 | + head = segs[segs.length - 1].trim(); |
| 129 | + let depth = 1; |
| 130 | + let j = open + 1; |
| 131 | + while (j < src.length && depth > 0) { |
| 132 | + if (src[j] === '{') depth++; |
| 133 | + else if (src[j] === '}') depth--; |
| 134 | + j++; |
| 135 | + } |
| 136 | + const body = src.slice(open + 1, j - 1); |
| 137 | + if (head.startsWith('@layer')) { |
| 138 | + walk(body, media, inUtilities || /^@layer\s+utilities\b/.test(head)); |
| 139 | + } else if (head.startsWith('@media')) { |
| 140 | + walk(body, [...media, head.slice('@media'.length).trim()], inUtilities); |
| 141 | + } else if (head.startsWith('@')) { |
| 142 | + // @property / @keyframes / @supports … — nothing here reads them. |
| 143 | + } else if (inUtilities && head) { |
| 144 | + if (!head.startsWith('.') || /[\s>+~,]|(?<!\\):/.test(head.slice(1).replace(/\\./g, 'x'))) { |
| 145 | + throw new Error(`evaluator cannot map selector to one class: ${head}`); |
| 146 | + } |
| 147 | + const className = head.slice(1).replace(/\\(.)/g, '$1'); |
| 148 | + const decls = body |
| 149 | + .replace(/\/\*[\s\S]*?\*\//g, '') |
| 150 | + .split(';') |
| 151 | + .map((d) => d.trim()) |
| 152 | + .filter(Boolean) |
| 153 | + .map((d): [string, string] => { |
| 154 | + const k = d.indexOf(':'); |
| 155 | + return [d.slice(0, k).trim(), d.slice(k + 1).trim()]; |
| 156 | + }); |
| 157 | + rules.push({ className, media, decls }); |
| 158 | + } |
| 159 | + i = j; |
| 160 | + } |
| 161 | + }; |
| 162 | + walk(css, [], false); |
| 163 | + return rules; |
| 164 | +} |
| 165 | + |
| 166 | +/** Does every media condition hold at `widthPx`? Refuses shapes it does not know. */ |
| 167 | +function mediaHolds(media: string[], widthPx: number): boolean { |
| 168 | + return media.every((m) => { |
| 169 | + const ge = m.match(/\(\s*width\s*>=\s*([\d.]+)(rem|px)\s*\)/); |
| 170 | + if (ge) return widthPx >= Number(ge[1]) * (ge[2] === 'rem' ? 16 : 1); |
| 171 | + const lt = m.match(/\(\s*width\s*<\s*([\d.]+)(rem|px)\s*\)/); |
| 172 | + if (lt) return widthPx < Number(lt[1]) * (lt[2] === 'rem' ? 16 : 1); |
| 173 | + const min = m.match(/min-width:\s*([\d.]+)(rem|px)/); |
| 174 | + if (min) return widthPx >= Number(min[1]) * (min[2] === 'rem' ? 16 : 1); |
| 175 | + throw new Error(`evaluator cannot read media query: ${m}`); |
| 176 | + }); |
| 177 | +} |
| 178 | + |
| 179 | +type Side = 'top' | 'right' | 'bottom' | 'left'; |
| 180 | +type Sides = Record<Side, number>; |
| 181 | +const SIDES_OF: Record<string, Side[]> = { |
| 182 | + 'padding': ['top', 'right', 'bottom', 'left'], |
| 183 | + 'padding-inline': ['left', 'right'], |
| 184 | + 'padding-block': ['top', 'bottom'], |
| 185 | + 'padding-top': ['top'], |
| 186 | + 'padding-right': ['right'], |
| 187 | + 'padding-bottom': ['bottom'], |
| 188 | + 'padding-left': ['left'], |
| 189 | + 'padding-inline-start': ['left'], |
| 190 | + 'padding-inline-end': ['right'], |
| 191 | +}; |
| 192 | + |
| 193 | +/** |
| 194 | + * The padding a browser would compute for an element carrying `classes`, at |
| 195 | + * `widthPx`, in spacing units — from the winning declaration per side after a |
| 196 | + * source-order walk of the rules that match the element. |
| 197 | + */ |
| 198 | +function computedPadding(css: string, classes: string[], widthPx: number): Sides { |
| 199 | + const onElement = new Set(classes); |
| 200 | + const env = new Map<string, string>(); |
| 201 | + const raw: Partial<Record<Side, string>> = {}; |
| 202 | + for (const rule of utilityRules(css)) { |
| 203 | + if (!onElement.has(rule.className) || !mediaHolds(rule.media, widthPx)) continue; |
| 204 | + for (const [prop, value] of rule.decls) { |
| 205 | + if (prop.startsWith('--')) env.set(prop, value); |
| 206 | + else if (prop in SIDES_OF) for (const side of SIDES_OF[prop]) raw[side] = value; |
| 207 | + } |
| 208 | + } |
| 209 | + const resolve = (side: Side): number => { |
| 210 | + let value = raw[side]; |
| 211 | + if (value === undefined) throw new Error(`no padding declaration reached side "${side}" at ${widthPx}px`); |
| 212 | + value = value.replace(/var\((--[\w-]+)\)/g, (token, name: string) => { |
| 213 | + // `--spacing` is the theme token the unit regex below reads verbatim; every |
| 214 | + // other custom property must have been set on this element. |
| 215 | + if (name === '--spacing') return token; |
| 216 | + const v = env.get(name); |
| 217 | + if (v === undefined) throw new Error(`"${name}" is consumed but never set on this element at ${widthPx}px`); |
| 218 | + return v; |
| 219 | + }); |
| 220 | + const units = value.match(/^calc\(var\(--spacing\) \* ([\d.]+)\)$/); |
| 221 | + if (units) return Number(units[1]); |
| 222 | + if (/^0(px)?$/.test(value)) return 0; |
| 223 | + throw new Error(`evaluator cannot read a padding value: ${value}`); |
| 224 | + }; |
| 225 | + return { top: resolve('top'), right: resolve('right'), bottom: resolve('bottom'), left: resolve('left') }; |
| 226 | +} |
| 227 | + |
| 228 | +const all = (n: number): Sides => ({ top: n, right: n, bottom: n, left: n }); |
| 229 | + |
| 230 | +/** Every default breakpoint, one pixel either side, plus a phone and a desktop. */ |
| 231 | +const LADDER = [320, 639, 640, 767, 768, 1023, 1024, 1279, 1280, 1535, 1536, 1920]; |
| 232 | + |
| 233 | +/** The `md` breakpoint in px, read from the theme through the same compiler. */ |
| 234 | +async function mdPx(): Promise<number> { |
| 235 | + const rule = utilityRules(await buildCss(['md:hidden'])).find((r) => r.className === 'md:hidden'); |
| 236 | + expect(rule?.media, 'md:hidden is emitted under one media query').toHaveLength(1); |
| 237 | + const m = rule!.media[0].match(/\(\s*width\s*>=\s*([\d.]+)(rem|px)\s*\)/); |
| 238 | + expect(m, `md media query has a readable threshold: ${rule!.media[0]}`).not.toBeNull(); |
| 239 | + return Number(m![1]) * (m![2] === 'rem' ? 16 : 1); |
| 240 | +} |
| 241 | + |
| 242 | +async function paddingAcrossLadder(override?: string): Promise<Array<{ width: number; sides: Sides }>> { |
| 243 | + const classes = classesOf(override); |
| 244 | + const css = await buildCss(classes); |
| 245 | + return LADDER.map((width) => ({ width, sides: computedPadding(css, classes, width) })); |
| 246 | +} |
| 247 | + |
| 248 | +describe('Empty — the padding default and every override, cascade-evaluated on the emitted CSS', () => { |
| 249 | + it('the evaluator itself reproduces the defect on the OLD base shape (control)', async () => { |
| 250 | + // `p-6 … md:p-12` with a caller's `px-3 py-8`, as tailwind-merge left it: |
| 251 | + // at md the base wins on every side. A green run on the new shape below |
| 252 | + // therefore means the shape changed, not that the instrument is inert. |
| 253 | + const old = ['p-6', 'md:p-12', 'px-3', 'py-8']; |
| 254 | + const css = await buildCss(old); |
| 255 | + const md = await mdPx(); |
| 256 | + expect(computedPadding(css, old, md - 1)).toEqual({ top: 8, right: 3, bottom: 8, left: 3 }); |
| 257 | + expect(computedPadding(css, old, md)).toEqual(all(12)); |
| 258 | + }); |
| 259 | + |
| 260 | + it('a site with NO override still gets 6 below md and 12 at and above it (the non-regression axis)', async () => { |
| 261 | + const md = await mdPx(); |
| 262 | + for (const { width, sides } of await paddingAcrossLadder(undefined)) { |
| 263 | + expect(sides, `no override at ${width}px`).toEqual(all(width >= md ? 12 : 6)); |
| 264 | + } |
| 265 | + }); |
| 266 | + |
| 267 | + it('`px-3 py-8` (ConversationsSidebar) wins on every side at every width', async () => { |
| 268 | + for (const { width, sides } of await paddingAcrossLadder('px-3 py-8')) { |
| 269 | + expect(sides, `px-3 py-8 at ${width}px`).toEqual({ top: 8, right: 3, bottom: 8, left: 3 }); |
| 270 | + } |
| 271 | + }); |
| 272 | + |
| 273 | + it('`py-10` (AuditPanel) wins on the block axis at every width, and the inline axis keeps the responsive default', async () => { |
| 274 | + const md = await mdPx(); |
| 275 | + for (const { width, sides } of await paddingAcrossLadder('py-10')) { |
| 276 | + const inline = width >= md ? 12 : 6; |
| 277 | + expect(sides, `py-10 at ${width}px`).toEqual({ top: 10, right: inline, bottom: 10, left: inline }); |
| 278 | + } |
| 279 | + }); |
| 280 | + |
| 281 | + it('a full `p-4` wins on every side at every width', async () => { |
| 282 | + for (const { width, sides } of await paddingAcrossLadder('p-4')) { |
| 283 | + expect(sides, `p-4 at ${width}px`).toEqual(all(4)); |
| 284 | + } |
| 285 | + }); |
| 286 | + |
| 287 | + it('a caller can still be responsive itself: `p-2 md:p-4` reads 2 below md and 4 at and above it', async () => { |
| 288 | + const md = await mdPx(); |
| 289 | + for (const { width, sides } of await paddingAcrossLadder('p-2 md:p-4')) { |
| 290 | + expect(sides, `p-2 md:p-4 at ${width}px`).toEqual(all(width >= md ? 4 : 2)); |
| 291 | + } |
| 292 | + }); |
| 293 | + |
| 294 | + it('a prefixed-only override keeps the default below its breakpoint: `md:p-3` reads 6 then 3', async () => { |
| 295 | + const md = await mdPx(); |
| 296 | + for (const { width, sides } of await paddingAcrossLadder('md:p-3')) { |
| 297 | + expect(sides, `md:p-3 at ${width}px`).toEqual(all(width >= md ? 3 : 6)); |
| 298 | + } |
| 299 | + }); |
| 300 | +}); |
| 301 | + |
| 302 | +describe('Empty — the mechanism, as rendered', () => { |
| 303 | + it('no padding utility in the base classes carries a variant prefix', () => { |
| 304 | + // A `VARIANT:p*-` token in the base is exactly what an unprefixed override |
| 305 | + // cannot beat through `cn()`; the responsive default has to travel some |
| 306 | + // other way (today: a custom property). |
| 307 | + const prefixedPadding = classesOf(undefined).filter((token) => { |
| 308 | + const bare = token.replace(/^(?:[^\s:[\]]+:)+/, ''); |
| 309 | + return bare !== token && /^-?p[xytrblse]?-/.test(bare); |
| 310 | + }); |
| 311 | + expect(prefixedPadding).toEqual([]); |
| 312 | + }); |
| 313 | + |
| 314 | + it('a caller\'s override tokens reach the DOM untouched', () => { |
| 315 | + for (const override of ['px-3 py-8', 'py-10', 'p-4']) { |
| 316 | + const classes = classesOf(override); |
| 317 | + for (const token of override.split(' ')) expect(classes, override).toContain(token); |
| 318 | + } |
| 319 | + }); |
| 320 | +}); |
| 321 | + |
| 322 | +describe('Empty — the border half', () => { |
| 323 | + it('control: on this workspace build `border-dashed` alone is style-only, `border` carries the width, and preflight zeroes every border', async () => { |
| 324 | + const css = await buildCss(['border-dashed', 'border']); |
| 325 | + const rules = utilityRules(css); |
| 326 | + const dashed = rules.find((r) => r.className === 'border-dashed')!; |
| 327 | + const border = rules.find((r) => r.className === 'border')!; |
| 328 | + expect(dashed.decls.map(([k]) => k)).toContain('border-style'); |
| 329 | + expect(dashed.decls.some(([k]) => /width$/.test(k) || k === 'border')).toBe(false); |
| 330 | + expect(border.decls.some(([k, v]) => k === 'border-width' && v === '1px')).toBe(true); |
| 331 | + // preflight: `*, ::after, ::before, … { … border: 0 solid; }` |
| 332 | + expect(css).toMatch(/\*,\s*::after,\s*::before[^{]*\{[^}]*\bborder:\s*0 solid\b/); |
| 333 | + }); |
| 334 | + |
| 335 | + it('the base classes never declare a border-style without a border-width (the inert-frame class of defect)', async () => { |
| 336 | + const classes = classesOf(undefined); |
| 337 | + const rules = utilityRules(await buildCss(classes)).filter((r) => classes.includes(r.className)); |
| 338 | + const styleSetters = rules.filter((r) => r.decls.some(([k]) => /^border(-\w+)?-style$/.test(k))).map((r) => r.className); |
| 339 | + const widthSetters = rules.filter((r) => r.decls.some(([k]) => /^border(-[\w-]+)?-width$/.test(k) || k === 'border')).map((r) => r.className); |
| 340 | + expect(styleSetters.length === 0 || widthSetters.length > 0, `style ${styleSetters} without width`).toBe(true); |
| 341 | + }); |
| 342 | + |
| 343 | + it('carries no border utility today — the former `border-dashed` was inert, and a frame is a design change with its own card', () => { |
| 344 | + // The ADR-0049 remove branch. A future deliberate frame updates this pin |
| 345 | + // together with the card that decides it; it does not arrive by accident. |
| 346 | + expect(classesOf(undefined).filter((token) => /^border(-|$)/.test(token))).toEqual([]); |
| 347 | + }); |
| 348 | +}); |
0 commit comments