Design tokens: ipal-tokens CLI, components on single names, templates, tests

- bin ipal-tokens: src/design/tokens.ts → src/design/tokens.css, --check, WCAG
  contrast report (fails on AA errors; --report, --warn-only)
- CookieBanner / CookieButton read the single --ipal-* roles; the fallback follows
  color-scheme via light-dark() and still honours the legacy -dark variables
- lightbox fade reads --ipal-duration / --ipal-ease-out
- DESIGN.md and tokens.ts templates in ipal-setup/resources

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-29 13:55:59 +01:00
co-authored by Claude Opus 5.5
parent 9511b12d19
commit ca8e93eaf4
11 changed files with 391 additions and 23 deletions
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env node
// ipal-tokens — the brand's design tokens: src/design/tokens.ts → src/design/tokens.css,
// plus a WCAG contrast check (docs/design-tokens.md).
// pnpm exec ipal-tokens → write src/design/tokens.css, print the contrast report
// pnpm exec ipal-tokens --check → fail when the CSS is out of date (CI, ipal-doctor)
// pnpm exec ipal-tokens --in x.ts --out y.css --warn-only
import { dirname, join } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
const pkgRoot = join(dirname(fileURLToPath(import.meta.url)), '..')
const { runTokensCli } = await import(pathToFileURL(join(pkgRoot, 'dist', 'modules', 'tokens', 'cli.js')).href)
process.exit(await runTokensCli(process.argv.slice(2)))
@@ -0,0 +1,48 @@
# DESIGN.md — <client name>
The human source of the look. Its machine form is `src/design/tokens.ts`; the two must agree
(`ipal-doctor` compares them). Values go into `tokens.ts`, never into components.
Sections are fixed: fill every one, write "default" where the brand keeps the standard.
## 1. Brand in one sentence
<what the site is, for whom, the feeling>. Audience: <…>.
The one memorable element (where the boldness goes): <…>. Everything else stays quiet.
## 2. Colour
| Role (`--ipal-*`) | Light | Dark | Used for |
|---|---|---|---|
| primary | oklch(…) | (carried over) | main buttons, key accents |
| secondary | default | default | second button |
| accent | default (= primary) | | badges, highlights |
| bg / surface / surface-muted | default | default | page, cards, alternate sections |
Contrast (paste `pnpm exec ipal-tokens --report`; every ✗ fixed before launch):
```
<report>
```
## 3. Type
Body: <family> <weights> (`--font-family-body`). Headings: <family> <weight> (`--font-family-heading`).
Max 2 families × 2–3 weights, `subsets: ['latin', 'latin-ext']`. Scale overrides (`fs`): <none | h1 2.25→4rem …>.
Heading style: <case, tracking, weight>.
## 4. Shape and depth
Radius: control <…>, card <…>, media <…>. Depth: <borders | shadow-sm on cards | none>.
## 5. Layout
Scale: fluid-wide (default) | fluid. Container <80rem>, narrow <48rem> (legal, articles), measure 68ch.
Section rhythm: py-section; compact bands py-section-sm. Alignment: <left | centred hero only>.
## 6. Motion
What moves and why (max one orchestrated moment): <…>. Durations: default (fast 150 / base 250 / slow 400 ms).
Reduced motion: every duration token is 0 ms; nothing essential is animated.
## 7. Imagery and icons
Photo style: <…>. Focal points set in Media. Icons: lucide set, <stroke width>.
## 8. Theme
<light only | dark only | both>, default <light | dark | system> (Site settings → Theme), toggle <yes | no>.
## 9. Deviations from the standard
Every override of a default, and every project-only token or breakpoint, with the reason:
- <none>
@@ -0,0 +1,27 @@
// src/design/tokens.ts — the ONLY file you edit to rebrand the site (docs/design-tokens.md).
// After every change: `pnpm exec ipal-tokens` → writes src/design/tokens.css (commit it) and prints
// the WCAG contrast check (`--report` prints every pair for DESIGN.md → Colour).
// Leave out anything the brand does not change: the neutral defaults in @intecion/ipal-kit/tokens.css apply.
import { defineTokens } from '@intecion/ipal-kit/tokens'
export const tokens = defineTokens({
theme: 'both', // 'light' | 'dark' | 'both' — must match Site settings → Theme
fluid: 'wide', // the fluid file styles.css imports: 'wide' = fluid-wide.css (default), 'standard' = fluid.css
color: {
light: {
primary: 'oklch(0.5 0.17 250)', // [TO FILL: brand colour from DESIGN.md]
// secondary: 'oklch(…)', accent: 'oklch(…)', bg: 'oklch(…)', surface-muted: 'oklch(…)'
},
dark: {
// primary carries over from light when left out; set a lighter one if the report fails
},
},
font: {
// next/font in the root layout: variable '--font-family-body' / '--font-family-heading' on <html>
fwHeading: 650,
},
radius: { control: '0.5rem', card: '0.75rem' },
// fs: { h1: ['2.25rem', '4rem'] }, // min → max; the clamp() is computed for the fluid range
// space: { section: ['3rem', '8rem'] },
// container: { default: '80rem' },
})
+2 -1
View File
@@ -153,7 +153,8 @@ Out of the box the viewer is styled inline from CSS variables — override them
| `--ipal-lightbox-inset` | `1rem` |
| `--ipal-lightbox-caption-color` | `inherit` |
| `--ipal-lightbox-caption-size` | `0.95rem` |
| `--ipal-lightbox-duration` | `200ms` (fade; none with reduced motion) |
| `--ipal-lightbox-duration` | `var(--ipal-duration, 200ms)` (fade; none with reduced motion) |
| `--ipal-lightbox-easing` | `var(--ipal-ease-out, ease)` |
```css
:root { --ipal-lightbox-backdrop: rgb(15 23 42 / 0.95); --ipal-lightbox-control-bg: var(--color-brand); }
+2 -1
View File
@@ -63,7 +63,8 @@
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"bin": {
"ipal-skills": "bin/ipal-skills.mjs"
"ipal-skills": "bin/ipal-skills.mjs",
"ipal-tokens": "bin/ipal-tokens.mjs"
},
"files": [
"dist",
+16 -13
View File
@@ -88,9 +88,10 @@ export type CookieBannerClassNames = {
}
/**
* Colours and radius come from CSS custom properties with built-in fallbacks,
* so the banner looks right with no setup, and re-skinning per client means
* declaring a few variables — no imports, no props, no specificity fights:
* Colours and radius come from the design tokens (docs/design-tokens.md) with
* built-in fallbacks, so the banner looks right with no setup, and re-skinning
* per client means declaring a few variables — no imports, no props, no
* specificity fights:
*
* ```css
* :root {
@@ -99,22 +100,24 @@ export type CookieBannerClassNames = {
* }
* ```
*
* Available: --ipal-surface, --ipal-border, --ipal-text, --ipal-text-strong,
* Read: --ipal-surface, --ipal-border, --ipal-text, --ipal-text-strong,
* --ipal-text-muted, --ipal-primary, --ipal-primary-hover, --ipal-primary-text,
* --ipal-hover, --ipal-radius. Each has a `-dark` counterpart used under
* Tailwind's `dark:` variant (e.g. --ipal-surface-dark).
* --ipal-hover, --ipal-radius. With @intecion/ipal-kit/tokens.css they switch
* with the theme on their own. Without it, the fallback follows the page's
* color-scheme (light-dark()) and the legacy `-dark` variables
* (e.g. --ipal-surface-dark) still set the dark fallback.
*
* Layout stays in Tailwind: spacing and flow aren't things a brand changes, and
* exposing them as tokens would mean re-inventing CSS one variable at a time.
* For a different layout use classNames (every element has a slot).
*/
const surface = 'bg-[var(--ipal-surface,#fff)] dark:bg-[var(--ipal-surface-dark,#171717)]'
const border = 'border-[var(--ipal-border,#e5e5e5)] dark:border-[var(--ipal-border-dark,#262626)]'
const surface = 'bg-[var(--ipal-surface,light-dark(#fff,var(--ipal-surface-dark,#171717)))]'
const border = 'border-[var(--ipal-border,light-dark(#e5e5e5,var(--ipal-border-dark,#262626)))]'
const radius = 'rounded-[var(--ipal-radius,0.375rem)]'
const accent = 'text-[var(--ipal-primary,#2563eb)]'
const bodyText = 'text-[var(--ipal-text,#404040)] dark:text-[var(--ipal-text-dark,#d4d4d4)]'
const strongText = 'text-[var(--ipal-text-strong,#171717)] dark:text-[var(--ipal-text-strong-dark,#f5f5f5)]'
const mutedText = 'text-[var(--ipal-text-muted,#737373)] dark:text-[var(--ipal-text-muted-dark,#a3a3a3)]'
const bodyText = 'text-[var(--ipal-text,light-dark(#404040,var(--ipal-text-dark,#d4d4d4)))]'
const strongText = 'text-[var(--ipal-text-strong,light-dark(#171717,var(--ipal-text-strong-dark,#f5f5f5)))]'
const mutedText = 'text-[var(--ipal-text-muted,light-dark(#737373,var(--ipal-text-muted-dark,#a3a3a3)))]'
const primaryBg = 'bg-[var(--ipal-primary,#2563eb)]'
const defaults: Required<CookieBannerClassNames> = {
@@ -128,7 +131,7 @@ const defaults: Required<CookieBannerClassNames> = {
categoryCard: `flex flex-col gap-3 ${radius} border p-4 ${border}`,
categoryDescription: `text-xs ${mutedText}`,
categoryTitle: `text-sm font-medium ${strongText}`,
closeButton: `shrink-0 ${radius} p-1 ${mutedText} hover:bg-[var(--ipal-hover,#f5f5f5)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]`,
closeButton: `shrink-0 ${radius} p-1 ${mutedText} hover:bg-[var(--ipal-hover,light-dark(#f5f5f5,var(--ipal-hover-dark,#262626)))]`,
content: 'flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between',
control: 'mt-1 h-4 w-4 shrink-0 accent-[var(--ipal-primary,#2563eb)]',
controlThumb: 'pointer-events-none inline-block size-5 rounded-full bg-white shadow transition-transform translate-x-0.5 data-[checked=true]:translate-x-[1.375rem]',
@@ -148,7 +151,7 @@ const defaults: Required<CookieBannerClassNames> = {
rejectButton: '',
root: `fixed inset-x-0 bottom-0 z-50 border-t p-4 shadow-lg ${surface} ${border}`,
saveButton: '',
secondaryButton: `${radius} px-3 py-1.5 text-sm font-medium text-[var(--ipal-text,#404040)] hover:bg-[var(--ipal-hover,#f5f5f5)] dark:text-[var(--ipal-text-dark,#e5e5e5)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]`,
secondaryButton: `${radius} px-3 py-1.5 text-sm font-medium text-[var(--ipal-text,light-dark(#404040,var(--ipal-text-dark,#d4d4d4)))] hover:bg-[var(--ipal-hover,light-dark(#f5f5f5,var(--ipal-hover-dark,#262626)))]`,
settingsActions: 'flex justify-end gap-2',
settingsButton: '',
settingsDescription: `text-sm ${bodyText}`,
+5 -6
View File
@@ -9,9 +9,9 @@ import { useIsMounted } from './useIsMounted.js'
* after deciding (GDPR: withdrawing consent must be as easy as giving it).
* Hidden while the banner is showing.
*
* Colours follow the same CSS custom properties as CookieBanner
* (--ipal-surface, --ipal-border, --ipal-hover, --ipal-text), so a client's
* palette applies to both without touching either component. Pass className to
* Colours follow the same design tokens as CookieBanner (--ipal-surface,
* --ipal-border, --ipal-hover, --ipal-text), so a client's palette applies to
* both without touching either component. Pass className to
* replace the styling outright.
*/
export function CookieButton({ className }: { className?: string } = {}) {
@@ -26,8 +26,7 @@ export function CookieButton({ className }: { className?: string } = {}) {
const cls =
className ??
'fixed bottom-4 left-4 z-40 flex h-11 w-11 items-center justify-center rounded-full border shadow-md transition-colors ' +
'bg-[var(--ipal-surface,#fff)] border-[var(--ipal-border,#e5e5e5)] hover:bg-[var(--ipal-hover,#f5f5f5)] ' +
'dark:bg-[var(--ipal-surface-dark,#171717)] dark:border-[var(--ipal-border-dark,#262626)] dark:hover:bg-[var(--ipal-hover-dark,#262626)]'
'bg-[var(--ipal-surface,light-dark(#fff,var(--ipal-surface-dark,#171717)))] border-[var(--ipal-border,light-dark(#e5e5e5,var(--ipal-border-dark,#262626)))] hover:bg-[var(--ipal-hover,light-dark(#f5f5f5,var(--ipal-hover-dark,#262626)))]'
return (
<button
@@ -40,7 +39,7 @@ export function CookieButton({ className }: { className?: string } = {}) {
>
<Cookie
aria-hidden="true"
className="h-5 w-5 text-[var(--ipal-text,#525252)] dark:text-[var(--ipal-text-dark,#d4d4d4)]"
className="h-5 w-5 text-[var(--ipal-text,light-dark(#525252,var(--ipal-text-dark,#d4d4d4)))]"
/>
</button>
)
+1 -1
View File
@@ -195,7 +195,7 @@ export function LightboxDialog({
const style = (key: keyof typeof STYLES, extra?: CSSProperties): CSSProperties | undefined =>
unstyled ? undefined : { ...(key === 'close' || key === 'next' || key === 'previous' ? STYLES.button : {}), ...STYLES[key], ...extra }
const motion = prefersReducedMotion()
const dialogStyle = style('dialog', motion ? undefined : { opacity: visible ? 1 : 0, transition: `opacity ${v('duration', '200ms')} ease` })
const dialogStyle = style('dialog', motion ? undefined : { opacity: visible ? 1 : 0, transition: `opacity ${v('duration', 'var(--ipal-duration, 200ms)')} ${v('easing', 'var(--ipal-ease-out, ease)')}` })
const canPrev = loop || current > 0
const canNext = loop || current < total - 1
const step = (delta: number) => onIndexChange(lightboxIndex(current, delta, total, loop))
+91
View File
@@ -0,0 +1,91 @@
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, relative, resolve } from 'node:path'
import { pathToFileURL } from 'node:url'
import { contrastReport, type ContrastRow } from './contrast.js'
import { tokensToCss } from './css.js'
import { defineTokens, type TokensInput } from './define.js'
export const TOKENS_CLI_USAGE = `Usage: ipal-tokens [--in src/design/tokens.ts] [--out src/design/tokens.css] [--check] [--report] [--warn-only]
Generates the brand CSS from the tokens file and checks WCAG contrast.
--check fail when the CSS file is out of date (CI, ipal-doctor); writes nothing
--report print every checked pair (for DESIGN.md), not only the failures
--warn-only report contrast failures without failing`
type Log = (line: string) => void
function arg(args: string[], name: string, fallback: string): string {
const i = args.indexOf(name)
const value = i >= 0 ? args[i + 1] : undefined
if (i >= 0 && (!value || value.startsWith('-'))) {throw new Error(`${name} needs a path`)}
return value ?? fallback
}
/** Contrast rows as aligned text lines; failures marked ✗ (error) or ! (warning). */
export function formatContrastReport(rows: ContrastRow[]): string[] {
return rows.map((r) => {
const mark = r.pass ? '✓' : r.level === 'warn' ? '!' : '✗'
const ratio = r.ratio === null ? 'n/a (colour not parsed)' : `${r.ratio.toFixed(2)}:1`
const where = `${r.theme}${r.scope === 'inverse' ? ' · inverse' : ''}`
return `${mark} ${`${r.fg} on ${r.bg}`.padEnd(36)} ${ratio.padEnd(10)} min ${r.min}:1 (${where})`
})
}
async function loadTokens(file: string): Promise<TokensInput> {
if (file.endsWith('.json')) {return JSON.parse(readFileSync(file, 'utf8')) as TokensInput}
try {
const mod = (await import(pathToFileURL(file).href)) as { default?: TokensInput; tokens?: TokensInput }
const tokens = mod.tokens ?? mod.default
if (!tokens) {throw new Error(`${file} must export \`tokens\` (or a default export)`)}
return tokens
} catch (error) {
if ((error as { code?: string }).code === 'ERR_UNKNOWN_FILE_EXTENSION') {
throw new Error(`this Node cannot import .ts files: use Node 22.18+ (or run with --experimental-strip-types)`)
}
throw error
}
}
/** The `ipal-tokens` command. Returns the exit code. */
export async function runTokensCli(args: string[], { cwd = process.cwd(), log = console.log }: { cwd?: string; log?: Log } = {}): Promise<number> {
if (args.includes('--help') || args.includes('-h')) {
log(TOKENS_CLI_USAGE)
return 0
}
try {
const input = resolve(cwd, arg(args, '--in', 'src/design/tokens.ts'))
const output = resolve(cwd, arg(args, '--out', 'src/design/tokens.css'))
if (!existsSync(input)) {
log(`ipal-tokens: ${relative(cwd, input)} not found (copy the template from .agents/skills/ipal-setup/resources/tokens.ts)`)
return 1
}
const tokens = defineTokens(await loadTokens(input))
const css = tokensToCss(tokens, { source: relative(cwd, input) })
const current = existsSync(output) ? readFileSync(output, 'utf8') : null
let code = 0
if (args.includes('--check')) {
if (current !== css) {
log(`✗ ${relative(cwd, output)} is out of date — run \`pnpm exec ipal-tokens\``)
code = 1
} else {log(`✓ ${relative(cwd, output)} is up to date`)}
} else if (current !== css) {
mkdirSync(dirname(output), { recursive: true })
writeFileSync(output, css)
log(`wrote ${relative(cwd, output)}`)
} else {log(`${relative(cwd, output)} unchanged`)}
const rows = contrastReport(tokens)
const errors = rows.filter((r) => !r.pass && r.level === 'error')
const shown = args.includes('--report') ? rows : rows.filter((r) => !r.pass || r.ratio === null)
log(`\nWCAG contrast: ${rows.filter((r) => r.pass && r.ratio !== null).length} of ${rows.length} pairs pass${args.includes('--report') ? ' (paste into DESIGN.md → Colour)' : ''}`)
for (const line of formatContrastReport(shown)) {log(` ${line}`)}
if (errors.length) {
log(`\n${errors.length} pair(s) below the WCAG AA minimum${args.includes('--warn-only') ? ' (--warn-only: not failing)' : ''}`)
if (!args.includes('--warn-only')) {code = 1}
}
return code
} catch (error) {
log(`ipal-tokens: ${(error as Error).message}`)
return 1
}
}
+1 -1
View File
@@ -81,7 +81,7 @@ export function tokensToCss(input: TokensInput, { source = 'src/design/tokens.ts
const { dark, light } = resolveColors(input)
const header = `/*
* GENERATED by \`ipal-tokens\` from ${source} — do not edit; change ${source} and run
* \`pnpm exec ipal-tokens\`. Import it after @intecion/ipal-kit/tokens.css.
* \`pnpm exec ipal-tokens\`. Import it in styles.css after @intecion/ipal-kit/tokens.css (and tailwind.css).
*/`
const statics = Object.entries(staticOverrides(input))
const parts = [header]
+185
View File
@@ -0,0 +1,185 @@
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { afterEach, beforeEach, describe, expect, test } from 'vitest'
import { runTokensCli } from '../src/modules/tokens/cli.js'
import {
COLOR_DEFAULTS,
contrastRatio,
contrastReport,
defaultTokensCss,
defineTokens,
FLUID_SCALE,
fluidClamp,
IPAL_BREAKPOINTS,
IPAL_TOKENS,
ipalVar,
parseColor,
resolveColors,
tokensToCss,
} from '../src/modules/tokens/index.js'
const root = path.resolve(import.meta.dirname, '..')
const read = (rel: string) => readFileSync(path.join(root, rel), 'utf8')
describe('shipped CSS files', () => {
test('tokens.css is generated from the catalogue (UPDATE_TOKENS_CSS=1 rewrites it)', () => {
const file = path.join(root, 'src/styles/tokens.css')
if (process.env.UPDATE_TOKENS_CSS === '1') {writeFileSync(file, defaultTokensCss())}
expect(readFileSync(file, 'utf8')).toBe(defaultTokensCss())
})
test.each([
['src/styles/fluid.css', 'standard'],
['src/styles/fluid-wide.css', 'wide'],
] as const)('%s matches the fluid scale', (file, range) => {
const css = read(file)
for (const [name, [min, max]] of Object.entries(FLUID_SCALE)) {
expect(css, name).toContain(`--ipal-${name}: ${fluidClamp(min, max, range)};`)
}
})
test('every --ipal-* the preset and a11y.css read is defined by tokens.css or fluid.css', () => {
const defined = new Set([...`${read('src/styles/tokens.css')}${read('src/styles/fluid.css')}${read('src/styles/a11y.css')}`.matchAll(/(--ipal-[a-z0-9-]+):/g)].map((m) => m[1]))
const used = [...`${read('src/styles/tailwind.css')}${read('src/styles/a11y.css')}`.matchAll(/var\((--ipal-[a-z0-9-]+)/g)].map((m) => m[1])
expect([...new Set(used)].filter((name) => !defined.has(name))).toEqual([])
})
test('the preset maps every colour role and keeps the dark variant on data-theme', () => {
const preset = read('src/styles/tailwind.css')
// link-inverse / focus-inverse are read through the inverse scope, not by a utility
for (const role of Object.keys(COLOR_DEFAULTS).filter((r) => r !== 'link-inverse' && r !== 'focus-inverse')) {
expect(preset, role).toContain(`var(--ipal-${role})`)
}
expect(preset).toContain('@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));')
expect(preset).toContain('@theme inline')
})
test('the neutral defaults pass every WCAG pair', () => {
expect(contrastReport().filter((r) => !r.pass || r.ratio === null)).toEqual([])
})
})
describe('plugin components read the single token names', () => {
test.each(['src/modules/consent/CookieBanner.tsx', 'src/modules/consent/CookieButton.tsx'])('%s has no dark: colour variant', (file) => {
const src = read(file)
expect(src).not.toMatch(/dark:(?:hover:)?(?:bg|text|border)-\[var\(--ipal-/)
expect(src).toContain('light-dark(')
})
})
describe('colour maths', () => {
test('parses hex, rgb, hsl, oklch and named colours', () => {
expect(parseColor('#fff')).toEqual({ a: 1, b: 1, g: 1, r: 1 })
expect(parseColor('rgb(255 0 0 / 50%)')).toMatchObject({ a: 0.5, r: 1 })
expect(parseColor('rgb(0, 0, 255)')).toMatchObject({ b: 1, r: 0 })
expect(parseColor('hsl(0 0% 100%)')).toMatchObject({ b: 1, g: 1, r: 1 })
const ok = parseColor('oklch(1 0 0)')!
expect(ok.r).toBeCloseTo(1, 3)
expect(parseColor('nonsense')).toBeNull()
})
test('resolves var() and color-mix(in oklch)', () => {
const lookup = (name: string) => ({ 'ipal-primary': '#000' })[name]
expect(parseColor('var(--ipal-primary)', lookup)).toMatchObject({ r: 0 })
expect(parseColor('var(--missing, #fff)', lookup)).toMatchObject({ r: 1 })
const grey = parseColor('color-mix(in oklch, black, white 50%)')!
expect(grey.r).toBeGreaterThan(0.3)
expect(grey.r).toBeLessThan(0.7)
})
test('contrast ratio follows WCAG 2', () => {
expect(contrastRatio(parseColor('#000')!, parseColor('#fff')!)).toBeCloseTo(21, 5)
expect(contrastRatio(parseColor('#767676')!, parseColor('#fff')!)).toBeCloseTo(4.54, 2)
})
})
describe('fluidClamp', () => {
test('reproduces the fluid.css formula', () => {
expect(fluidClamp(1, 1.125)).toBe('clamp(1rem, 0.9511rem + 0.2174vw, 1.125rem)')
expect(fluidClamp('16px', '18px', 'wide')).toBe('clamp(1rem, 0.9712rem + 0.1282vw, 1.125rem)')
expect(fluidClamp(2, 2)).toBe('2rem')
})
})
describe('defineTokens / tokensToCss', () => {
test('rejects an unknown role instead of dropping it silently', () => {
expect(() => defineTokens({ color: { light: { primay: 'red' } as never } })).toThrow(/unknown colour role "primay"/)
expect(() => defineTokens({ fs: { huge: [1, 2] } as never })).toThrow(/unknown fs size/)
})
test('emits only what the brand changes; brand roles carry over to dark', () => {
const css = tokensToCss(defineTokens({ color: { light: { bg: 'oklch(0.99 0.01 90)', primary: '#0a6' } }, fs: { h1: [2, 4] }, radius: { card: '1rem' } }))
const [rootBlock, darkBlock] = css.split(':root[data-theme="dark"]')
expect(rootBlock).toContain('--ipal-primary: #0a6;')
expect(rootBlock).toContain('--ipal-bg: oklch(0.99 0.01 90);')
expect(rootBlock).toContain('--ipal-radius-card: 1rem;')
expect(rootBlock).toContain(`--ipal-fs-h1: ${fluidClamp(2, 4, 'wide')};`)
expect(rootBlock).not.toContain('--ipal-surface:')
expect(darkBlock).toContain('--ipal-primary: #0a6;')
expect(darkBlock).not.toContain('--ipal-bg')
})
test('a one-theme site pins every role on both selectors', () => {
const tokens = defineTokens({ color: { dark: { bg: '#070707' } }, theme: 'dark' })
const { dark, light } = resolveColors(tokens)
expect(light).toEqual(dark)
const css = tokensToCss(tokens)
expect(css).toContain('color-scheme: dark;')
expect(css.match(/--ipal-bg: #070707;/g)).toHaveLength(2)
expect(contrastReport(tokens).every((r) => r.theme === 'dark')).toBe(true)
})
test('the contrast report fails a low-contrast brand', () => {
const rows = contrastReport({ color: { light: { primary: '#ffeb3b', 'primary-text': '#ffffff' } } })
expect(rows.find((r) => r.theme === 'light' && r.fg === 'primary-text' && r.bg === 'primary')).toMatchObject({ pass: false })
})
})
describe('names', () => {
test('IPAL_TOKENS and ipalVar give var() strings', () => {
expect(IPAL_TOKENS.primary).toBe('var(--ipal-primary)')
expect(IPAL_TOKENS['fs-h1']).toBe('var(--ipal-fs-h1)')
expect(IPAL_TOKENS['surface-dark']).toBe('var(--ipal-surface-dark)')
expect(ipalVar('surface', '#fff')).toBe('var(--ipal-surface, #fff)')
expect(IPAL_BREAKPOINTS.md).toBe(48)
})
})
describe('ipal-tokens CLI', () => {
let dir: string
let lines: string[]
const log = (line: string) => lines.push(line)
beforeEach(() => {
dir = mkdtempSync(path.join(tmpdir(), 'ipal-tokens-'))
lines = []
})
afterEach(() => rmSync(dir, { force: true, recursive: true }))
test('writes the CSS, then --check passes; a stale file fails --check', async () => {
writeFileSync(path.join(dir, 'tokens.json'), JSON.stringify({ color: { light: { primary: '#1d4ed8' } } }))
const args = ['--in', 'tokens.json', '--out', 'out/tokens.css']
expect(await runTokensCli(args, { cwd: dir, log })).toBe(0)
expect(readFileSync(path.join(dir, 'out/tokens.css'), 'utf8')).toContain('--ipal-primary: #1d4ed8;')
expect(await runTokensCli([...args, '--check'], { cwd: dir, log })).toBe(0)
writeFileSync(path.join(dir, 'out/tokens.css'), '/* old */')
expect(await runTokensCli([...args, '--check'], { cwd: dir, log })).toBe(1)
expect(lines.join('\n')).toMatch(/out of date/)
})
test('fails on a contrast error unless --warn-only', async () => {
writeFileSync(path.join(dir, 'tokens.json'), JSON.stringify({ color: { light: { primary: '#ffeb3b' } } }))
const args = ['--in', 'tokens.json', '--out', 'tokens.css']
expect(await runTokensCli(args, { cwd: dir, log })).toBe(1)
expect(lines.join('\n')).toMatch(/✗ primary-text on primary/)
expect(await runTokensCli([...args, '--warn-only'], { cwd: dir, log })).toBe(0)
})
test('a missing tokens file or an unknown role is an error, not a crash', async () => {
expect(await runTokensCli([], { cwd: dir, log })).toBe(1)
writeFileSync(path.join(dir, 'tokens.json'), JSON.stringify({ color: { light: { brand: 'red' } } }))
expect(await runTokensCli(['--in', 'tokens.json'], { cwd: dir, log })).toBe(1)
expect(lines.join('\n')).toMatch(/unknown colour role "brand"/)
})
})