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, IAPL_BREAKPOINTS, IAPL_TOKENS, iaplVar, 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') // *-inverse roles are read through the inverse scope, not by a utility const scoped = ['link-inverse', 'focus-inverse', 'primary-inverse', 'primary-inverse-text'] for (const role of Object.keys(COLOR_DEFAULTS).filter((r) => !scoped.includes(r))) { 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(1) expect(css).toContain(':root, [data-theme="light"], :root[data-theme="dark"], [data-theme="dark"] {') expect(contrastReport(tokens).every((r) => r.theme === 'dark')).toBe(true) }) test('themes switch on any element, not only ', () => { const defaults = defaultTokensCss() expect(defaults).toContain(':root, [data-theme="light"] {') expect(defaults).toContain(':root[data-theme="dark"], [data-theme="dark"] {') const css = tokensToCss({ color: { dark: { bg: '#111' }, light: { bg: '#fefefe' } } }) expect(css).toMatch(/:root, \[data-theme="light"\] \{\n {2}--ipal-bg: #fefefe;/) expect(css).toMatch(/:root\[data-theme="dark"\], \[data-theme="dark"\] \{\n {2}--ipal-bg: #111;/) }) test('primary is re-mapped inside an inverted section and checked there', () => { expect(defaultTokensCss()).toMatch(/\[data-surface="inverse"\] \{[^}]*--ipal-primary: var\(--ipal-primary-inverse\);/) const darkBrand = { color: { light: { primary: 'oklch(0.3 0.08 150)' } } } const warn = contrastReport(darkBrand).find((r) => r.scope === 'inverse' && r.fg === 'primary' && r.theme === 'light') expect(warn).toMatchObject({ level: 'warn', pass: false }) // the dark theme's inverse surface is light: there the dark brand colour works again const fixed = contrastReport({ color: { dark: { 'primary-inverse': 'oklch(0.3 0.08 150)', 'primary-inverse-text': 'oklch(0.98 0 0)' }, light: { ...darkBrand.color.light, 'primary-inverse': 'oklch(0.85 0.1 150)', 'primary-inverse-text': 'oklch(0.2 0.05 150)' }, }, }) expect(fixed.filter((r) => r.scope === 'inverse' && !r.pass)).toEqual([]) }) 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('IAPL_TOKENS and iaplVar give var() strings', () => { expect(IAPL_TOKENS.primary).toBe('var(--ipal-primary)') expect(IAPL_TOKENS['fs-h1']).toBe('var(--ipal-fs-h1)') expect(IAPL_TOKENS['surface-dark']).toBe('var(--ipal-surface-dark)') expect(iaplVar('surface', '#fff')).toBe('var(--ipal-surface, #fff)') expect(IAPL_BREAKPOINTS.md).toBe(48) }) }) describe('iapl-tokens CLI', () => { let dir: string let lines: string[] const log = (line: string) => lines.push(line) beforeEach(() => { dir = mkdtempSync(path.join(tmpdir(), 'iapl-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('a file generated before 1.17.0 (header names `ipal-tokens`) is up to date; a changed value is not', 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) const file = path.join(dir, 'out/tokens.css') const old = readFileSync(file, 'utf8').replaceAll('iapl-tokens', 'ipal-tokens') expect(old).toContain('GENERATED by `ipal-tokens`') writeFileSync(file, old) expect(await runTokensCli([...args, '--check'], { cwd: dir, log })).toBe(0) expect(readFileSync(file, 'utf8')).toBe(old) // --check writes nothing writeFileSync(file, old.replace('#1d4ed8', '#000000')) expect(await runTokensCli([...args, '--check'], { cwd: dir, log })).toBe(1) }) 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"/) }) })