Merge claude/design-tokens-build: design tokens (tokens.css, tailwind.css, ipal-tokens)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -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}`,
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* The design-token catalogue: every `--ipal-*` token, its neutral default and the
|
||||
* Tailwind utility it maps to. `tokens.css` (the shipped defaults) is generated from
|
||||
* this file — see test/designTokens.test.ts — so names and values live in one place.
|
||||
*/
|
||||
|
||||
/** A colour role: a value per theme. Values may reference other tokens (`var(--ipal-…)`). */
|
||||
export type ColorDefault = { dark: string; light: string }
|
||||
|
||||
/** Colour roles that switch with the theme. Key = token name without `--ipal-`. */
|
||||
export const COLOR_DEFAULTS = {
|
||||
bg: { dark: 'oklch(0.145 0 0)', light: 'oklch(1 0 0)' },
|
||||
border: { dark: 'oklch(0.269 0 0)', light: 'oklch(0.922 0 0)' },
|
||||
'border-strong': { dark: 'oklch(0.371 0 0)', light: 'oklch(0.87 0 0)' },
|
||||
primary: { dark: 'oklch(0.546 0.245 262.881)', light: 'oklch(0.546 0.245 262.881)' },
|
||||
surface: { dark: 'oklch(0.205 0 0)', light: 'oklch(1 0 0)' },
|
||||
'surface-inverse': { dark: 'oklch(0.97 0 0)', light: 'oklch(0.205 0 0)' },
|
||||
'surface-muted': { dark: 'oklch(0.18 0 0)', light: 'oklch(0.97 0 0)' },
|
||||
'surface-raised': { dark: 'oklch(0.235 0 0)', light: 'oklch(1 0 0)' },
|
||||
text: { dark: 'oklch(0.87 0 0)', light: 'oklch(0.371 0 0)' },
|
||||
'text-inverse': { dark: 'oklch(0.205 0 0)', light: 'oklch(0.97 0 0)' },
|
||||
'text-muted': { dark: 'oklch(0.708 0 0)', light: 'oklch(0.53 0 0)' },
|
||||
'text-strong': { dark: 'oklch(0.97 0 0)', light: 'oklch(0.205 0 0)' },
|
||||
// darker in both themes: the text on primary stays readable on hover
|
||||
accent: { dark: 'var(--ipal-primary)', light: 'var(--ipal-primary)' },
|
||||
'accent-text': { dark: 'var(--ipal-primary-text)', light: 'var(--ipal-primary-text)' },
|
||||
danger: { dark: 'oklch(0.704 0.191 22.216)', light: 'oklch(0.505 0.213 27.518)' },
|
||||
'danger-surface': { dark: 'oklch(0.258 0.092 26.042)', light: 'oklch(0.971 0.013 17.38)' },
|
||||
focus: { dark: 'var(--ipal-link)', light: 'var(--ipal-link)' },
|
||||
'focus-inverse': { dark: 'var(--ipal-text-inverse)', light: 'var(--ipal-text-inverse)' },
|
||||
hover: { dark: 'oklch(0.269 0 0)', light: 'oklch(0.97 0 0)' },
|
||||
info: { dark: 'oklch(0.707 0.165 254.624)', light: 'oklch(0.488 0.243 264.376)' },
|
||||
'info-surface': { dark: 'oklch(0.282 0.091 267.935)', light: 'oklch(0.97 0.014 254.604)' },
|
||||
link: { dark: 'color-mix(in oklch, var(--ipal-primary), white 40%)', light: 'var(--ipal-primary)' },
|
||||
'link-hover': {
|
||||
dark: 'color-mix(in oklch, var(--ipal-link), var(--ipal-text-strong) 30%)',
|
||||
light: 'color-mix(in oklch, var(--ipal-link), var(--ipal-text-strong) 30%)',
|
||||
},
|
||||
'link-inverse': { dark: 'var(--ipal-text-inverse)', light: 'var(--ipal-text-inverse)' },
|
||||
overlay: { dark: 'oklch(0 0 0 / 0.65)', light: 'oklch(0 0 0 / 0.5)' },
|
||||
'primary-hover': {
|
||||
dark: 'color-mix(in oklch, var(--ipal-primary), black 12%)',
|
||||
light: 'color-mix(in oklch, var(--ipal-primary), black 12%)',
|
||||
},
|
||||
'primary-text': { dark: 'oklch(1 0 0)', light: 'oklch(1 0 0)' },
|
||||
secondary: { dark: 'var(--ipal-text-strong)', light: 'var(--ipal-text-strong)' },
|
||||
'secondary-hover': {
|
||||
dark: 'color-mix(in oklch, var(--ipal-secondary), black 12%)',
|
||||
light: 'color-mix(in oklch, var(--ipal-secondary), white 18%)',
|
||||
},
|
||||
'secondary-text': { dark: 'var(--ipal-text-inverse)', light: 'var(--ipal-text-inverse)' },
|
||||
success: { dark: 'oklch(0.792 0.209 151.711)', light: 'oklch(0.527 0.154 150.069)' },
|
||||
'success-surface': { dark: 'oklch(0.266 0.065 152.934)', light: 'oklch(0.982 0.018 155.826)' },
|
||||
warning: { dark: 'oklch(0.828 0.189 84.429)', light: 'oklch(0.555 0.163 48.998)' },
|
||||
'warning-surface': { dark: 'oklch(0.279 0.077 45.635)', light: 'oklch(0.987 0.022 95.277)' },
|
||||
} as const satisfies Record<string, ColorDefault>
|
||||
|
||||
export type ColorRole = keyof typeof COLOR_DEFAULTS
|
||||
|
||||
/**
|
||||
* Roles the cookie banner / button shipped before the standard, each with a `-dark`
|
||||
* twin. The twins stay as aliases (set in the dark theme) for project CSS that reads them.
|
||||
*/
|
||||
export const LEGACY_DARK_ROLES = [
|
||||
'surface', 'border', 'text', 'text-strong', 'text-muted', 'primary', 'primary-hover', 'primary-text', 'hover',
|
||||
] as const satisfies readonly ColorRole[]
|
||||
|
||||
/**
|
||||
* What `[data-surface="inverse"]` re-maps, so content inside an inverted section
|
||||
* (cards, rich text, links, focus rings) stays readable without inverse variants.
|
||||
*/
|
||||
const onInverse = (percent: number) => `color-mix(in oklch, var(--ipal-text-inverse) ${percent}%, var(--ipal-surface-inverse))`
|
||||
export const INVERSE_SCOPE: Partial<Record<ColorRole, string>> = {
|
||||
border: onInverse(18),
|
||||
'border-strong': onInverse(30),
|
||||
focus: 'var(--ipal-focus-inverse)',
|
||||
hover: onInverse(12),
|
||||
link: 'var(--ipal-link-inverse)',
|
||||
surface: onInverse(8),
|
||||
text: 'var(--ipal-text-inverse)',
|
||||
'text-muted': onInverse(72),
|
||||
'text-strong': 'var(--ipal-text-inverse)',
|
||||
}
|
||||
|
||||
/** Theme-independent tokens. Key = token name without `--ipal-`. */
|
||||
export const STATIC_DEFAULTS = {
|
||||
// next/font slots: variable '--font-family-body' / '--font-family-heading' on <html>. Not --font-body:
|
||||
// that name is Tailwind's font-body utility key, which maps back to these tokens (a var() cycle).
|
||||
'container-narrow': '48rem',
|
||||
duration: '250ms',
|
||||
'duration-fast': '150ms',
|
||||
'duration-slow': '400ms',
|
||||
'ease-in-out': 'cubic-bezier(0.65, 0, 0.35, 1)',
|
||||
'ease-out': 'cubic-bezier(0.22, 1, 0.36, 1)',
|
||||
'focus-offset': '2px',
|
||||
'focus-width': '2px',
|
||||
'font-body': 'var(--font-family-body, ui-sans-serif, system-ui, sans-serif)',
|
||||
'font-heading': 'var(--font-family-heading, var(--ipal-font-body))',
|
||||
'font-mono': 'var(--font-family-mono, ui-monospace, SFMono-Regular, Menlo, monospace)',
|
||||
'fw-body': '400',
|
||||
'fw-heading': '650',
|
||||
'lh-body': '1.6',
|
||||
'lh-heading': '1.15',
|
||||
radius: '0.375rem',
|
||||
'radius-card': '0.75rem',
|
||||
'radius-full': '9999px',
|
||||
'radius-media': '0.5rem',
|
||||
'radius-sm': '0.25rem',
|
||||
'shadow-lg': '0 16px 32px -8px oklch(0 0 0 / 0.14), 0 4px 8px -4px oklch(0 0 0 / 0.08)',
|
||||
'shadow-md': '0 4px 8px -2px oklch(0 0 0 / 0.08), 0 2px 4px -2px oklch(0 0 0 / 0.06)',
|
||||
'shadow-sm': '0 1px 2px 0 oklch(0 0 0 / 0.06), 0 1px 3px 0 oklch(0 0 0 / 0.08)',
|
||||
'tracking-heading': '-0.01em',
|
||||
'z-header': '40',
|
||||
'z-overlay': '50',
|
||||
'z-toast': '60',
|
||||
} as const
|
||||
|
||||
/** Dark-theme shadows: deeper black plus a hairline ring, since a soft grey shadow vanishes on dark. */
|
||||
export const DARK_SHADOWS = {
|
||||
'shadow-lg': '0 16px 32px -8px oklch(0 0 0 / 0.6), 0 0 0 1px oklch(1 0 0 / 0.06)',
|
||||
'shadow-md': '0 4px 8px -2px oklch(0 0 0 / 0.5), 0 0 0 1px oklch(1 0 0 / 0.05)',
|
||||
'shadow-sm': '0 1px 2px 0 oklch(0 0 0 / 0.4), 0 0 0 1px oklch(1 0 0 / 0.04)',
|
||||
} as const
|
||||
|
||||
export type StaticToken = keyof typeof STATIC_DEFAULTS
|
||||
|
||||
/** Tokens fluid.css / fluid-wide.css define (the type and space scale). */
|
||||
export const FLUID_TOKENS = [
|
||||
'fs-xs', 'fs-sm', 'fs-base', 'fs-lg', 'fs-h4', 'fs-h3', 'fs-h2', 'fs-h1', 'fs-display',
|
||||
'space-stack', 'space-gap', 'space-gutter', 'space-section-sm', 'space-section',
|
||||
'measure', 'container', 'container-wide', 'hero-min-h', 'fs-display-fit', 'fs-h1-fit', 'space-section-fit',
|
||||
] as const
|
||||
|
||||
export type FluidToken = (typeof FLUID_TOKENS)[number]
|
||||
|
||||
export type IpalTokenName = `${(typeof LEGACY_DARK_ROLES)[number]}-dark` | ColorRole | FluidToken | StaticToken
|
||||
|
||||
/** Standard breakpoints in rem (Tailwind 4 defaults). CSS variables can't be used in `@media`. */
|
||||
export const IPAL_BREAKPOINTS = { '2xl': 96, lg: 64, md: 48, sm: 40, xl: 80 } as const
|
||||
@@ -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 = (line: string) => process.stdout.write(`${line}\n`) }: { 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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
/**
|
||||
* Just enough colour maths for the token contrast check: parse the CSS colours a
|
||||
* tokens file uses (hex, rgb(), hsl(), oklch(), white/black, color-mix(in oklch, …)),
|
||||
* resolve var() references, and compute the WCAG 2 contrast ratio.
|
||||
*/
|
||||
|
||||
/** sRGB, channels 0–1, plus alpha. */
|
||||
export type Rgba = { a: number; b: number; g: number; r: number }
|
||||
|
||||
type Oklch = { a: number; c: number; h: number; l: number }
|
||||
|
||||
const NAMED: Record<string, Rgba> = {
|
||||
black: { a: 1, b: 0, g: 0, r: 0 },
|
||||
transparent: { a: 0, b: 0, g: 0, r: 0 },
|
||||
white: { a: 1, b: 1, g: 1, r: 1 },
|
||||
}
|
||||
|
||||
const clamp01 = (n: number) => Math.min(1, Math.max(0, n))
|
||||
const toLinear = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)
|
||||
const fromLinear = (c: number) => (c <= 0.0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - 0.055)
|
||||
|
||||
function oklchToRgb({ a, c, h, l }: Oklch): Rgba {
|
||||
const hr = (h * Math.PI) / 180
|
||||
const A = c * Math.cos(hr)
|
||||
const B = c * Math.sin(hr)
|
||||
const l_ = (l + 0.3963377774 * A + 0.2158037573 * B) ** 3
|
||||
const m_ = (l - 0.1055613458 * A - 0.0638541728 * B) ** 3
|
||||
const s_ = (l - 0.0894841775 * A - 1.291485548 * B) ** 3
|
||||
return {
|
||||
a,
|
||||
b: clamp01(fromLinear(-0.0041960863 * l_ - 0.7034186147 * m_ + 1.707614701 * s_)),
|
||||
g: clamp01(fromLinear(-1.2684380046 * l_ + 2.6097574011 * m_ - 0.3413193965 * s_)),
|
||||
r: clamp01(fromLinear(4.0767416621 * l_ - 3.3077115913 * m_ + 0.2309699292 * s_)),
|
||||
}
|
||||
}
|
||||
|
||||
function rgbToOklch({ a, b, g, r }: Rgba): Oklch {
|
||||
const [R, G, B] = [toLinear(r), toLinear(g), toLinear(b)]
|
||||
const l_ = Math.cbrt(0.4122214708 * R + 0.5363325363 * G + 0.0514459929 * B)
|
||||
const m_ = Math.cbrt(0.2119034982 * R + 0.6806995451 * G + 0.1073969566 * B)
|
||||
const s_ = Math.cbrt(0.0883024619 * R + 0.2817188376 * G + 0.6299787005 * B)
|
||||
const L = 0.2104542553 * l_ + 0.793617785 * m_ - 0.0040720468 * s_
|
||||
const A = 1.9779984951 * l_ - 2.428592205 * m_ + 0.4505937099 * s_
|
||||
const Bb = 0.0259040371 * l_ + 0.7827717662 * m_ - 0.808675766 * s_
|
||||
const h = (Math.atan2(Bb, A) * 180) / Math.PI
|
||||
return { a, c: Math.hypot(A, Bb), h: h < 0 ? h + 360 : h, l: L }
|
||||
}
|
||||
|
||||
function hslToRgb(h: number, s: number, l: number, a: number): Rgba {
|
||||
const k = (n: number) => (n + h / 30) % 12
|
||||
const f = (n: number) => l - s * Math.min(l, 1 - l) * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1))
|
||||
return { a, b: f(4), g: f(8), r: f(0) }
|
||||
}
|
||||
|
||||
/** Split a function's arguments on top-level commas (or spaces / slash when there are no commas). */
|
||||
function splitArgs(inner: string): string[] {
|
||||
const parts: string[] = []
|
||||
let depth = 0
|
||||
let current = ''
|
||||
for (const ch of inner) {
|
||||
if (ch === '(') {depth++}
|
||||
if (ch === ')') {depth--}
|
||||
if (ch === ',' && depth === 0) {
|
||||
parts.push(current.trim())
|
||||
current = ''
|
||||
} else {current += ch}
|
||||
}
|
||||
parts.push(current.trim())
|
||||
return parts
|
||||
}
|
||||
|
||||
const num = (s: string, percentOf = 1) => (s.endsWith('%') ? (Number(s.slice(0, -1)) / 100) * percentOf : Number(s))
|
||||
|
||||
/** `r g b / a` or `r, g, b, a` → numbers. */
|
||||
function channels(inner: string): string[] {
|
||||
return inner.includes(',') ? splitArgs(inner) : inner.replace('/', ' ').trim().split(/\s+/)
|
||||
}
|
||||
|
||||
function functionCall(value: string): { args: string; name: string } | null {
|
||||
const m = /^([a-z-]+)\((.*)\)$/is.exec(value.trim())
|
||||
return m ? { name: m[1].toLowerCase(), args: m[2] } : null
|
||||
}
|
||||
|
||||
/** Value lookup for var(): returns the raw CSS value of a token, or undefined. */
|
||||
export type TokenLookup = (name: string) => string | undefined
|
||||
|
||||
/**
|
||||
* Parse a CSS colour to sRGB. `lookup` resolves `var(--name)`; unknown syntax or an
|
||||
* unresolved var returns null (the contrast check then skips the pair).
|
||||
*/
|
||||
export function parseColor(value: string, lookup: TokenLookup = () => undefined, depth = 0): null | Rgba {
|
||||
if (depth > 20) {return null}
|
||||
const v = value.trim()
|
||||
const named = NAMED[v.toLowerCase()]
|
||||
if (named) {return named}
|
||||
const hex = /^#([0-9a-f]{3,8})$/i.exec(v)
|
||||
if (hex) {
|
||||
const h = hex[1].length <= 4 ? [...hex[1]].map((c) => c + c).join('') : hex[1]
|
||||
if (h.length !== 6 && h.length !== 8) {return null}
|
||||
const at = (i: number) => parseInt(h.slice(i, i + 2), 16) / 255
|
||||
return { a: h.length === 8 ? at(6) : 1, b: at(4), g: at(2), r: at(0) }
|
||||
}
|
||||
const call = functionCall(v)
|
||||
if (!call) {return null}
|
||||
if (call.name === 'var') {
|
||||
const [name, fallback] = (() => {
|
||||
const [first, ...rest] = splitArgs(call.args)
|
||||
return [first, rest.join(',')]
|
||||
})()
|
||||
const found = lookup(name.replace(/^--/, ''))
|
||||
if (found !== undefined) {return parseColor(found, lookup, depth + 1)}
|
||||
return fallback ? parseColor(fallback, lookup, depth + 1) : null
|
||||
}
|
||||
if (call.name === 'color-mix') {return mix(call.args, lookup, depth)}
|
||||
const parts = channels(call.args)
|
||||
const alpha = parts[3] !== undefined ? num(parts[3]) : 1
|
||||
if (call.name === 'rgb' || call.name === 'rgba') {
|
||||
return { a: alpha, b: num(parts[2], 255) / 255, g: num(parts[1], 255) / 255, r: num(parts[0], 255) / 255 }
|
||||
}
|
||||
if (call.name === 'hsl' || call.name === 'hsla') {
|
||||
return hslToRgb(Number(parts[0].replace('deg', '')), num(parts[1]), num(parts[2]), alpha)
|
||||
}
|
||||
if (call.name === 'oklch') {
|
||||
return oklchToRgb({ a: alpha, c: num(parts[1], 0.4), h: Number(parts[2]) || 0, l: num(parts[0]) })
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** `color-mix(in oklch, A [p%], B [q%])`. Other interpolation spaces are mixed in oklch too. */
|
||||
function mix(args: string, lookup: TokenLookup, depth: number): null | Rgba {
|
||||
const [, first, second] = splitArgs(args)
|
||||
if (!first || !second) {return null}
|
||||
const side = (s: string) => {
|
||||
const cut = s.lastIndexOf(' ')
|
||||
const pct = s.slice(cut + 1)
|
||||
return cut > 0 && /^(?:\d+(?:\.\d+)?|\.\d+)%$/.test(pct) ? { color: s.slice(0, cut).trim(), pct: Number(pct.slice(0, -1)) / 100 } : { color: s, pct: undefined }
|
||||
}
|
||||
const a = side(first)
|
||||
const b = side(second)
|
||||
const pa = a.pct ?? (b.pct !== undefined ? 1 - b.pct : 0.5)
|
||||
const pb = b.pct ?? 1 - pa
|
||||
const ca = parseColor(a.color, lookup, depth + 1)
|
||||
const cb = parseColor(b.color, lookup, depth + 1)
|
||||
if (!ca || !cb || pa + pb === 0) {return null}
|
||||
const wa = pa / (pa + pb)
|
||||
const x = rgbToOklch(ca)
|
||||
const y = rgbToOklch(cb)
|
||||
// achromatic colours have no meaningful hue: take the other one's
|
||||
const hx = x.c < 1e-4 ? y.h : x.h
|
||||
const hy = y.c < 1e-4 ? x.h : y.h
|
||||
let dh = hy - hx
|
||||
if (dh > 180) {dh -= 360}
|
||||
if (dh < -180) {dh += 360}
|
||||
return oklchToRgb({
|
||||
a: x.a * wa + y.a * (1 - wa),
|
||||
c: x.c * wa + y.c * (1 - wa),
|
||||
h: hx + dh * (1 - wa),
|
||||
l: x.l * wa + y.l * (1 - wa),
|
||||
})
|
||||
}
|
||||
|
||||
/** Composite a translucent colour over an opaque background. */
|
||||
export function over(fg: Rgba, bg: Rgba): Rgba {
|
||||
const a = fg.a
|
||||
return { a: 1, b: fg.b * a + bg.b * (1 - a), g: fg.g * a + bg.g * (1 - a), r: fg.r * a + bg.r * (1 - a) }
|
||||
}
|
||||
|
||||
/** WCAG 2 relative luminance. */
|
||||
export function luminance({ b, g, r }: Rgba): number {
|
||||
return 0.2126 * toLinear(r) + 0.7152 * toLinear(g) + 0.0722 * toLinear(b)
|
||||
}
|
||||
|
||||
/** WCAG 2 contrast ratio (1–21). A translucent foreground is composited over the background. */
|
||||
export function contrastRatio(fg: Rgba, bg: Rgba): number {
|
||||
const solidBg = bg.a < 1 ? over(bg, NAMED.white) : bg
|
||||
const solidFg = fg.a < 1 ? over(fg, solidBg) : fg
|
||||
const [hi, lo] = [luminance(solidFg), luminance(solidBg)].sort((x, y) => y - x)
|
||||
return (hi + 0.05) / (lo + 0.05)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { type ColorRole, INVERSE_SCOPE } from './catalog.js'
|
||||
import { contrastRatio, parseColor } from './color.js'
|
||||
import { resolveColors, type TokensInput } from './define.js'
|
||||
|
||||
/** One checked pair. `level: 'warn'` pairs are reported but do not fail the check. */
|
||||
export type ContrastRow = {
|
||||
bg: string
|
||||
fg: string
|
||||
level: 'error' | 'warn'
|
||||
min: number
|
||||
pass: boolean
|
||||
/** null = a colour could not be parsed (reported, not failed). */
|
||||
ratio: null | number
|
||||
scope: 'default' | 'inverse'
|
||||
theme: 'dark' | 'light'
|
||||
}
|
||||
|
||||
type Pair = { bg: ColorRole; fg: ColorRole; level?: 'warn'; min: number }
|
||||
|
||||
/** Text 4.5:1 (WCAG 1.4.3 AA), focus rings and UI parts 3:1 (1.4.11). */
|
||||
const PAIRS: Pair[] = [
|
||||
...(['bg', 'surface', 'surface-muted', 'surface-raised'] as const).flatMap((bg) => [
|
||||
{ bg, fg: 'text' as const, min: 4.5 },
|
||||
{ bg, fg: 'text-strong' as const, min: 4.5 },
|
||||
{ bg, fg: 'text-muted' as const, min: 4.5 },
|
||||
{ bg, fg: 'link' as const, min: 4.5 },
|
||||
]),
|
||||
{ bg: 'primary', fg: 'primary-text', min: 4.5 },
|
||||
{ bg: 'primary-hover', fg: 'primary-text', min: 4.5 },
|
||||
{ bg: 'secondary', fg: 'secondary-text', min: 4.5 },
|
||||
{ bg: 'accent', fg: 'accent-text', min: 4.5 },
|
||||
{ bg: 'surface-inverse', fg: 'text-inverse', min: 4.5 },
|
||||
{ bg: 'surface-inverse', fg: 'link-inverse', min: 4.5 },
|
||||
{ bg: 'bg', fg: 'focus', min: 3 },
|
||||
{ bg: 'surface-inverse', fg: 'focus-inverse', min: 3 },
|
||||
{ bg: 'surface-inverse', fg: 'primary', level: 'warn', min: 3 },
|
||||
...(['success', 'warning', 'danger', 'info'] as const).flatMap((state) => [
|
||||
{ bg: 'bg' as const, fg: state, min: 4.5 },
|
||||
{ bg: `${state}-surface` as const, fg: state, min: 4.5 },
|
||||
]),
|
||||
]
|
||||
|
||||
/** Content inside an inverted section: muted text and links on the inverse surface. */
|
||||
const INVERSE_PAIRS: Pair[] = [
|
||||
{ bg: 'surface-inverse', fg: 'text-muted', min: 4.5 },
|
||||
{ bg: 'surface', fg: 'text', min: 4.5 },
|
||||
{ bg: 'surface', fg: 'link', min: 4.5 },
|
||||
]
|
||||
|
||||
/**
|
||||
* WCAG contrast for every text/background pair the token roles promise, in each
|
||||
* theme and inside the inverse scope. `ipal-tokens` prints it and fails on an error row.
|
||||
*/
|
||||
export function contrastReport(input: TokensInput = {}): ContrastRow[] {
|
||||
const themes = input.theme === 'light' || input.theme === 'dark' ? [input.theme] : (['light', 'dark'] as const)
|
||||
const resolved = resolveColors(input)
|
||||
return themes.flatMap((theme) => {
|
||||
const colors: Record<string, string> = resolved[theme]
|
||||
const inverse: Record<string, string> = { ...colors, ...INVERSE_SCOPE }
|
||||
const check = (map: Record<string, string>, scope: ContrastRow['scope']) => (pair: Pair): ContrastRow => {
|
||||
const lookup = (name: string) => (name.startsWith('ipal-') ? map[name.slice(5)] : undefined)
|
||||
const fg = parseColor(map[pair.fg], lookup)
|
||||
const bg = parseColor(map[pair.bg], lookup)
|
||||
const ratio = fg && bg ? Math.round(contrastRatio(fg, bg) * 100) / 100 : null
|
||||
return { bg: pair.bg, fg: pair.fg, level: pair.level ?? 'error', min: pair.min, pass: ratio === null || ratio >= pair.min, ratio, scope, theme }
|
||||
}
|
||||
return [...PAIRS.map(check(colors, 'default')), ...INVERSE_PAIRS.map(check(inverse, 'inverse'))]
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import {
|
||||
COLOR_DEFAULTS,
|
||||
type ColorRole,
|
||||
DARK_SHADOWS,
|
||||
INVERSE_SCOPE,
|
||||
LEGACY_DARK_ROLES,
|
||||
STATIC_DEFAULTS,
|
||||
} from './catalog.js'
|
||||
import { resolveColors, staticOverrides, type TokensInput } from './define.js'
|
||||
import { fluidClamp, type RemValue } from './fluid.js'
|
||||
|
||||
/** The dark theme. Two parts so it beats a brand's plain `:root` (the brand file comes later). */
|
||||
export const DARK_SELECTOR = ':root[data-theme="dark"]'
|
||||
export const INVERSE_SELECTOR = '[data-surface="inverse"]'
|
||||
|
||||
type Entries = Iterable<readonly [string, string]>
|
||||
|
||||
function block(selector: string, entries: Entries, indent = ''): string {
|
||||
const lines = [...entries].map(([name, value]) => `${indent} ${name === 'color-scheme' ? name : `--ipal-${name}`}: ${value};`)
|
||||
return lines.length ? `${indent}${selector} {\n${lines.join('\n')}\n${indent}}` : ''
|
||||
}
|
||||
|
||||
const colorEntries = (theme: 'dark' | 'light'): Entries =>
|
||||
Object.entries(COLOR_DEFAULTS).map(([role, v]) => [role, v[theme]] as const)
|
||||
|
||||
const legacyAliases: Entries = LEGACY_DARK_ROLES.map((role) => [`${role}-dark`, `var(--ipal-${role})`] as const)
|
||||
|
||||
const reducedMotion: Entries = [
|
||||
['duration-fast', '0ms'],
|
||||
['duration', '0ms'],
|
||||
['duration-slow', '0ms'],
|
||||
]
|
||||
|
||||
/** The inverse scope: what nested content reads inside `data-surface="inverse"`. */
|
||||
const inverseEntries: Entries = [
|
||||
...Object.entries(INVERSE_SCOPE).map(([role, value]) => [role, value] as const),
|
||||
['link-hover', 'var(--ipal-link-inverse)'],
|
||||
['color-scheme', 'dark'],
|
||||
]
|
||||
|
||||
/** The content of `@intecion/ipal-kit/tokens.css`: neutral defaults for every token. */
|
||||
export function defaultTokensCss(): string {
|
||||
return [
|
||||
`/*
|
||||
* @intecion/ipal-kit/tokens.css — neutral defaults for every --ipal-* design token
|
||||
* (generated from src/modules/tokens/catalog.ts; docs/design-tokens.md).
|
||||
*
|
||||
* Light values on :root, dark values on :root[data-theme="dark"] (set by <ThemeScript>,
|
||||
* storage key "theme"). A brand overrides them in src/design/tokens.css, generated by
|
||||
* \`ipal-tokens\` from src/design/tokens.ts and imported after this file.
|
||||
* Components read only the role names, never "-dark": the roles switch with the theme.
|
||||
* The type and space scale is in fluid.css / fluid-wide.css — import one of them as well.
|
||||
*/`,
|
||||
block(':root', [...colorEntries('light'), ...Object.entries(STATIC_DEFAULTS), ['color-scheme', 'light']]),
|
||||
block(DARK_SELECTOR, [...colorEntries('dark'), ...Object.entries(DARK_SHADOWS), ...legacyAliases, ['color-scheme', 'dark']]),
|
||||
`/* Inverted section (settings.background = inverted): content inside reads the inverse roles. */`,
|
||||
block(INVERSE_SELECTOR, inverseEntries),
|
||||
block(`${DARK_SELECTOR} ${INVERSE_SELECTOR}`, [['color-scheme', 'light']]),
|
||||
`/* No motion for people who asked for none (the a11y widget's "no animations" too). */`,
|
||||
`@media (prefers-reduced-motion: reduce) {\n${block('html:root', reducedMotion, ' ')}\n}`,
|
||||
block('html[data-a11y-motion="reduce"]', reducedMotion),
|
||||
].join('\n\n') + '\n'
|
||||
}
|
||||
|
||||
const fluidEntries = (input: TokensInput): Array<readonly [string, string]> => {
|
||||
const range = input.fluid === 'standard' ? 'standard' : 'wide'
|
||||
const pairs = (prefix: string, map: Record<string, readonly [RemValue, RemValue] | undefined> = {}) =>
|
||||
Object.entries(map).flatMap(([key, pair]) => (pair ? [[`${prefix}${key}`, fluidClamp(pair[0], pair[1], range)] as const] : []))
|
||||
return [...pairs('fs-', input.fs), ...pairs('space-', input.space)]
|
||||
}
|
||||
|
||||
const changed = (theme: 'dark' | 'light', colors: Record<ColorRole, string>): Entries =>
|
||||
Object.entries(colors).filter(([role, value]) => COLOR_DEFAULTS[role as ColorRole][theme] !== value)
|
||||
|
||||
/**
|
||||
* The brand's CSS: only what differs from the defaults in tokens.css. This is what
|
||||
* `ipal-tokens` writes to src/design/tokens.css.
|
||||
*/
|
||||
export function tokensToCss(input: TokensInput, { source = 'src/design/tokens.ts' }: { source?: string } = {}): string {
|
||||
const theme = input.theme ?? 'both'
|
||||
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 in styles.css after @intecion/ipal-kit/tokens.css (and tailwind.css).
|
||||
*/`
|
||||
const statics = Object.entries(staticOverrides(input))
|
||||
const parts = [header]
|
||||
if (theme === 'both') {
|
||||
parts.push(block(':root', [...changed('light', light), ...statics, ...fluidEntries(input)]))
|
||||
// brand roles set only for light carry over to dark (resolveColors); other roles keep the dark defaults
|
||||
parts.push(block(DARK_SELECTOR, changed('dark', dark)))
|
||||
} else {
|
||||
// one theme: every role pinned on both selectors, so a stray data-theme can't switch it
|
||||
const all = Object.entries(light)
|
||||
const scheme = ['color-scheme', theme] as const
|
||||
const shadowSource: Record<string, string> = theme === 'dark' ? DARK_SHADOWS : STATIC_DEFAULTS
|
||||
const shadows = Object.entries({
|
||||
...Object.fromEntries(Object.entries(shadowSource).filter(([name]) => name.startsWith('shadow-'))),
|
||||
...Object.fromEntries(statics.filter(([name]) => name.startsWith('shadow-'))),
|
||||
})
|
||||
parts.push(block(':root', [...all, ...statics, ...shadows, ...fluidEntries(input), scheme]))
|
||||
parts.push(block(DARK_SELECTOR, [...all, ...shadows, scheme]))
|
||||
parts.push(block(INVERSE_SELECTOR, [['color-scheme', theme === 'dark' ? 'light' : 'dark']]))
|
||||
}
|
||||
return parts.filter(Boolean).join('\n\n') + '\n'
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { COLOR_DEFAULTS, type ColorRole, type StaticToken } from './catalog.js'
|
||||
import { FLUID_SCALE, type FluidRange, type FluidSize, type RemValue } from './fluid.js'
|
||||
|
||||
/** Colour values per role — any CSS colour (oklch recommended), or a `var(--ipal-…)` reference. */
|
||||
export type ColorInput = Partial<Record<ColorRole, string>>
|
||||
|
||||
/**
|
||||
* A project's brand, in `src/design/tokens.ts`. Everything is optional: what is left
|
||||
* out keeps the neutral default from `@intecion/ipal-kit/tokens.css`.
|
||||
*/
|
||||
export type TokensInput = {
|
||||
color?: {
|
||||
/** Dark-theme values. A brand role (primary, secondary, accent, link, *-text) set only in `light` carries over. */
|
||||
dark?: ColorInput
|
||||
light?: ColorInput
|
||||
}
|
||||
container?: { default?: string; measure?: string; narrow?: string; wide?: string }
|
||||
/** Which fluid file the site imports: `'wide'` = fluid-wide.css (grows to 1920px, the default for new sites). */
|
||||
fluid?: FluidRange
|
||||
font?: {
|
||||
body?: string
|
||||
fwBody?: number | string
|
||||
fwHeading?: number | string
|
||||
heading?: string
|
||||
lhBody?: number | string
|
||||
lhHeading?: number | string
|
||||
mono?: string
|
||||
trackingHeading?: string
|
||||
}
|
||||
/** Rewrite fluid sizes from min → max pairs (rem or px); the clamp() is computed for the `fluid` range. */
|
||||
fs?: Partial<Record<FluidSizeName<'fs-'>, readonly [RemValue, RemValue]>>
|
||||
motion?: { base?: string; easeInOut?: string; easeOut?: string; fast?: string; slow?: string }
|
||||
radius?: { card?: string; control?: string; media?: string; sm?: string }
|
||||
/** Any other `--ipal-*` value (name without `--ipal-`), e.g. `{ 'hero-min-h': 'min(100svh, 60rem)' }`. */
|
||||
raw?: Record<string, string>
|
||||
shadow?: { lg?: string; md?: string; sm?: string }
|
||||
space?: Partial<Record<FluidSizeName<'space-'>, readonly [RemValue, RemValue]>>
|
||||
/** `'both'` (default): light + dark. `'light'` / `'dark'`: a one-theme site; the other theme never applies. */
|
||||
theme?: 'both' | 'dark' | 'light'
|
||||
}
|
||||
|
||||
type FluidSizeName<P extends string> = FluidSize extends infer K ? (K extends `${P}${infer R}` ? R : never) : never
|
||||
|
||||
/** Roles whose light value carries over to dark when the brand sets no dark value. */
|
||||
export const BRAND_ROLES: readonly ColorRole[] = [
|
||||
'primary', 'primary-text', 'secondary', 'secondary-text', 'accent', 'accent-text',
|
||||
]
|
||||
|
||||
function check(keys: Iterable<string>, known: Record<string, unknown>, where: string) {
|
||||
for (const key of keys) {
|
||||
if (!(key in known)) {throw new Error(`ipal-kit tokens: unknown ${where} "${key}"`)}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare the brand. Returns the input unchanged after checking every name, so a
|
||||
* typo fails here (and in TypeScript) instead of silently missing from the CSS.
|
||||
*/
|
||||
export function defineTokens<T extends TokensInput>(input: T): T {
|
||||
check(Object.keys(input.color?.light ?? {}), COLOR_DEFAULTS, 'colour role')
|
||||
check(Object.keys(input.color?.dark ?? {}), COLOR_DEFAULTS, 'colour role')
|
||||
check(Object.keys(input.fs ?? {}).map((k) => `fs-${k}`), FLUID_SCALE, 'fs size')
|
||||
check(Object.keys(input.space ?? {}).map((k) => `space-${k}`), FLUID_SCALE, 'space size')
|
||||
if (input.theme && !['both', 'dark', 'light'].includes(input.theme)) {
|
||||
throw new Error(`ipal-kit tokens: theme must be 'both', 'light' or 'dark'`)
|
||||
}
|
||||
return input
|
||||
}
|
||||
|
||||
export type ResolvedColors = Record<ColorRole, string>
|
||||
|
||||
const defaultsFor = (theme: 'dark' | 'light') =>
|
||||
Object.fromEntries(Object.entries(COLOR_DEFAULTS).map(([role, v]) => [role, v[theme]])) as ResolvedColors
|
||||
|
||||
/**
|
||||
* The colour values each theme ends up with (defaults + brand), as the CSS cascade
|
||||
* would produce them. A one-theme site gets the same map for both.
|
||||
*/
|
||||
export function resolveColors(input: TokensInput): { dark: ResolvedColors; light: ResolvedColors } {
|
||||
const light = { ...defaultsFor('light'), ...input.color?.light }
|
||||
const carried = Object.fromEntries(
|
||||
BRAND_ROLES.filter((role) => input.color?.light?.[role] && !input.color?.dark?.[role]).map((role) => [role, input.color!.light![role]!]),
|
||||
)
|
||||
const dark = { ...defaultsFor('dark'), ...carried, ...input.color?.dark }
|
||||
if (input.theme === 'light') {return { dark: light, light }}
|
||||
if (input.theme === 'dark') {return { dark, light: dark }}
|
||||
return { dark, light }
|
||||
}
|
||||
|
||||
/** Theme-independent values the brand sets, as token name → CSS value. */
|
||||
export function staticOverrides(input: TokensInput): Partial<Record<StaticToken, string>> & Record<string, string> {
|
||||
const out: Record<string, string> = {}
|
||||
const put = (name: string, value: number | string | undefined) => {
|
||||
if (value !== undefined) {out[name] = String(value)}
|
||||
}
|
||||
const { container = {}, font = {}, motion = {}, radius = {}, shadow = {} } = input
|
||||
put('font-body', font.body)
|
||||
put('font-heading', font.heading)
|
||||
put('font-mono', font.mono)
|
||||
put('fw-body', font.fwBody)
|
||||
put('fw-heading', font.fwHeading)
|
||||
put('lh-body', font.lhBody)
|
||||
put('lh-heading', font.lhHeading)
|
||||
put('tracking-heading', font.trackingHeading)
|
||||
put('radius', radius.control)
|
||||
put('radius-sm', radius.sm)
|
||||
put('radius-card', radius.card)
|
||||
put('radius-media', radius.media)
|
||||
put('shadow-sm', shadow.sm)
|
||||
put('shadow-md', shadow.md)
|
||||
put('shadow-lg', shadow.lg)
|
||||
put('container', container.default)
|
||||
put('container-wide', container.wide)
|
||||
put('container-narrow', container.narrow)
|
||||
put('measure', container.measure)
|
||||
put('duration-fast', motion.fast)
|
||||
put('duration', motion.base)
|
||||
put('duration-slow', motion.slow)
|
||||
put('ease-out', motion.easeOut)
|
||||
put('ease-in-out', motion.easeInOut)
|
||||
for (const [name, value] of Object.entries(input.raw ?? {})) {put(name.replace(/^--ipal-/, ''), value)}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* The clamp() maths behind fluid.css / fluid-wide.css: a value that grows linearly
|
||||
* from `min` at the smallest viewport to `max` at the largest, in rem (browser zoom
|
||||
* and user font size keep working, WCAG 1.4.4).
|
||||
*/
|
||||
|
||||
/** Viewport ranges in px: fluid.css stops growing at 1280, fluid-wide.css at 1920. */
|
||||
export const FLUID_RANGES = {
|
||||
standard: { from: 360, to: 1280 },
|
||||
wide: { from: 360, to: 1920 },
|
||||
} as const
|
||||
|
||||
export type FluidRange = keyof typeof FLUID_RANGES
|
||||
|
||||
/** A size in rem: `1.5`, `'1.5rem'` or `'24px'`. */
|
||||
export type RemValue = number | string
|
||||
|
||||
/** min → max (rem) of every fluid size the plugin ships. fluid.css and fluid-wide.css are this table. */
|
||||
export const FLUID_SCALE = {
|
||||
'fs-base': [1, 1.125],
|
||||
'fs-display': [2.5, 4.5],
|
||||
'fs-h1': [2, 3.5],
|
||||
'fs-h2': [1.5, 2.5],
|
||||
'fs-h3': [1.25, 1.75],
|
||||
'fs-h4': [1.125, 1.5],
|
||||
'fs-lg': [1.125, 1.375],
|
||||
'fs-sm': [0.875, 0.9375],
|
||||
'fs-xs': [0.75, 0.8125],
|
||||
'space-gap': [1, 2],
|
||||
'space-gutter': [1, 2.5],
|
||||
'space-section': [3, 7.5],
|
||||
'space-section-sm': [1.5, 3.75],
|
||||
'space-stack': [1, 1.5],
|
||||
} as const satisfies Record<string, readonly [number, number]>
|
||||
|
||||
export type FluidSize = keyof typeof FLUID_SCALE
|
||||
|
||||
const ROOT_PX = 16
|
||||
|
||||
export function toRem(value: RemValue): number {
|
||||
if (typeof value === 'number') {return value}
|
||||
const m = /^\s*(-?(?:\d+(?:\.\d+)?|\.\d+))\s*(?:(rem|px)\s*)?$/.exec(value)
|
||||
if (!m) {throw new Error(`ipal-kit tokens: "${value}" is not a size in rem or px`)}
|
||||
return m[2] === 'px' ? Number(m[1]) / ROOT_PX : Number(m[1])
|
||||
}
|
||||
|
||||
const fmt = (n: number) => String(Number(n.toFixed(4)))
|
||||
|
||||
/** `clamp(min, intercept + slope·vw, max)` for the given viewport range. */
|
||||
export function fluidClamp(min: RemValue, max: RemValue, range: FluidRange = 'standard'): string {
|
||||
const lo = toRem(min)
|
||||
const hi = toRem(max)
|
||||
if (lo === hi) {return `${fmt(lo)}rem`}
|
||||
const { from, to } = FLUID_RANGES[range]
|
||||
const slope = (hi - lo) / ((to - from) / ROOT_PX)
|
||||
const intercept = lo - slope * (from / ROOT_PX)
|
||||
const [small, large] = lo < hi ? [lo, hi] : [hi, lo]
|
||||
return `clamp(${fmt(small)}rem, ${fmt(intercept)}rem + ${fmt(slope * 100)}vw, ${fmt(large)}rem)`
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export { COLOR_DEFAULTS, FLUID_TOKENS, INVERSE_SCOPE, IPAL_BREAKPOINTS, LEGACY_DARK_ROLES, STATIC_DEFAULTS } from './catalog.js'
|
||||
export type { ColorRole, IpalTokenName } from './catalog.js'
|
||||
export { contrastRatio, parseColor } from './color.js'
|
||||
export { contrastReport } from './contrast.js'
|
||||
export type { ContrastRow } from './contrast.js'
|
||||
export { DARK_SELECTOR, defaultTokensCss, INVERSE_SELECTOR, tokensToCss } from './css.js'
|
||||
export { defineTokens, resolveColors } from './define.js'
|
||||
export type { ColorInput, TokensInput } from './define.js'
|
||||
export { FLUID_RANGES, FLUID_SCALE, fluidClamp } from './fluid.js'
|
||||
export type { FluidRange, RemValue } from './fluid.js'
|
||||
export { IPAL_TOKENS, ipalVar } from './names.js'
|
||||
@@ -0,0 +1,27 @@
|
||||
import {
|
||||
COLOR_DEFAULTS,
|
||||
FLUID_TOKENS,
|
||||
type IpalTokenName,
|
||||
LEGACY_DARK_ROLES,
|
||||
STATIC_DEFAULTS,
|
||||
} from './catalog.js'
|
||||
|
||||
const NAMES = [
|
||||
...Object.keys(COLOR_DEFAULTS),
|
||||
...FLUID_TOKENS,
|
||||
...Object.keys(STATIC_DEFAULTS),
|
||||
...LEGACY_DARK_ROLES.map((role) => `${role}-dark`),
|
||||
] as IpalTokenName[]
|
||||
|
||||
/**
|
||||
* Every token as a ready `var(--ipal-…)` string, keyed by name without the prefix —
|
||||
* for inline styles, charts, canvas or a styleguide page: `IPAL_TOKENS.primary`.
|
||||
*/
|
||||
export const IPAL_TOKENS = Object.freeze(
|
||||
Object.fromEntries(NAMES.map((name) => [name, `var(--ipal-${name})`])) as Record<IpalTokenName, string>,
|
||||
)
|
||||
|
||||
/** `var(--ipal-<name>)`, with an optional fallback: `ipalVar('surface', '#fff')`. */
|
||||
export function ipalVar(name: IpalTokenName, fallback?: string): string {
|
||||
return fallback === undefined ? `var(--ipal-${name})` : `var(--ipal-${name}, ${fallback})`
|
||||
}
|
||||
Reference in New Issue
Block a user