From 655b12a232bfb009781e0c5f6506547d7f8fdbcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 29 Oct 2026 13:28:45 +0100 Subject: [PATCH 1/8] Design-token standard proposal (draft for approval) Co-Authored-By: Claude Opus 5.5 --- docs/dev/design-tokens-proposal.md | 326 +++++++++++++++++++++++++++++ 1 file changed, 326 insertions(+) create mode 100644 docs/dev/design-tokens-proposal.md diff --git a/docs/dev/design-tokens-proposal.md b/docs/dev/design-tokens-proposal.md new file mode 100644 index 0000000..0042b36 --- /dev/null +++ b/docs/dev/design-tokens-proposal.md @@ -0,0 +1,326 @@ +# Design tokens: proposal (draft for approval) + +Status: **proposal, nothing built yet.** Branch `claude/design-tokens-95806d`. +Consumers: the shared block library, the project starter, the reference site and `ipal-doctor`. + +## 1. Goal and the one rule + +Every client site should share the same set of design decisions (the token *names*, scale, structure, +dark mode, motion, breakpoints) and differ only in **values** (the brand). Components (the block library, +plugin UI, project sections) read only tokens. A new brand means a new `DESIGN.md` and one tokens file. +Nobody edits a component. + +Main rule check (CLAUDE.md): every file is opt-in, every value can be overridden in the project's +`:root`, the plugin's components keep their hard-coded fallbacks (so a site without tokens looks the same +as today), and building blocks are exported (names, defaults, helpers), not only finished files. + +## 2. What already exists (reuse, don't duplicate) + +| Already shipped | What it gives | In this standard | +|---|---|---| +| `fluid.css` / `fluid-wide.css` | `--ipal-fs-sm…display`, `--ipal-space-gap/gutter/section`, `--ipal-measure`, `--ipal-container(-wide)`, `--ipal-hero-min-h`, `*-fit` height helpers | **Stays the type and space scale.** Two additive variables (`--ipal-fs-xs`, `--ipal-fs-h4`) and two spaces (`--ipal-space-section-sm`, `--ipal-space-stack`) are added to both files, plus `--ipal-container-narrow`. No rename. | +| CookieBanner / CookieButton colour vars | `--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 with a `-dark` twin | **These names become the canonical colour roles.** The `-dark` twins stay as legacy aliases (section 5.3). | +| Lightbox `--ipal-lightbox-*` | component-scoped variables | Unchanged. Defaults change to read the global tokens (`--ipal-lightbox-duration: var(--ipal-duration, 200ms)`). | +| Stats chart `--ipal-series-1` | admin chart colour | Unchanged (admin, not the site). | +| Theme (``, `useTheme`, ``, key `theme`, `data-theme` on ``, `data-theme-switching`) | sets the theme before first paint | **Tokens switch on `[data-theme=dark]`.** The Tailwind `dark:` variant and the switching transition move from copy-paste in theme.md into the shipped preset. | +| Accessibility widget (`data-a11y-*` on ``, CSS copied from accessibility.md) | mechanism only | Optional `a11y.css` that works through tokens (section 9). | +| AGENT.md §6.11 / section-code.md "Styles" / ipal-setup stage 5 | ad-hoc `@theme` with `--color-primary` etc. and `--ipal-primary: var(--color-primary)` | Replaced by the standard. The plugin vars become the source, and Tailwind maps to them, not the other way round. | + +## 3. The token set + +All names are `--ipal--`. The colour group drops the word "color", to keep the names that +ship today. **Bold** = new. + +### 3.1 Colour roles (switch with the theme) + +| Token | Role | Neutral default light / dark | Tailwind utility | +|---|---|---|---| +| **`--ipal-bg`** | page background | `#fff` / `#0a0a0a` | `bg-bg` | +| `--ipal-surface` | card, panel, banner | `#fff` / `#171717` | `bg-surface` | +| **`--ipal-surface-muted`** | alternate section (`settings.background = muted`) | `#f5f5f5` / `#141414` | `bg-surface-muted` | +| **`--ipal-surface-raised`** | header, popover, dropdown | `#fff` / `#1f1f1f` | `bg-surface-raised` | +| **`--ipal-surface-inverse`** | inverted section (`settings.background = inverted`) | `#171717` / `#f5f5f5` | `bg-inverse` | +| `--ipal-text` | body text | `#404040` / `#d4d4d4` | `text-fg` | +| `--ipal-text-strong` | headings, labels | `#171717` / `#f5f5f5` | `text-fg-strong` | +| `--ipal-text-muted` | captions, meta | `#737373` / `#a3a3a3` | `text-fg-muted` | +| **`--ipal-text-inverse`** | text on `surface-inverse` | `#f5f5f5` / `#171717` | `text-on-inverse` | +| `--ipal-border` | dividers, inputs, cards | `#e5e5e5` / `#262626` | `border-border` | +| **`--ipal-border-strong`** | input focus-less border, emphasis | `#d4d4d4` / `#404040` | `border-border-strong` | +| `--ipal-primary` | brand: main buttons, key accents | `#2563eb` / `#3b82f6` | `bg-primary`, `text-primary` | +| `--ipal-primary-hover` | hover of the above | derived (5.4) | `hover:bg-primary-hover` | +| `--ipal-primary-text` | text/icon on `primary` | `#fff` / `#fff` | `text-on-primary` | +| **`--ipal-secondary`** (+ `-hover`, `-text`) | optional second brand colour | = neutral `text-strong` | `bg-secondary`, `text-on-secondary` | +| **`--ipal-accent`** (+ `-text`) | highlight, badge, decoration | = `primary` | `bg-accent`, `text-on-accent` | +| **`--ipal-link`** (+ `-hover`) | links in running text | = `primary` | `text-link` | +| `--ipal-hover` | neutral hover (ghost button, row) | `#f5f5f5` / `#262626` | `bg-hover` | +| **`--ipal-focus`** | focus ring | = `primary` | `ring-focus`, `outline-focus` | +| **`--ipal-overlay`** | scrim behind dialogs, hero image overlay | `rgb(0 0 0 / .5)` / `rgb(0 0 0 / .65)` | `bg-overlay` | +| **`--ipal-success`**, **`-warning`**, **`-danger`**, **`-info`** | state text / icon | green-700 / amber-700 / red-700 / blue-700 (light), 400 shades (dark) | `text-danger` … | +| **`--ipal-success-surface`** … | tinted state background | 50 shades (light), 950 shades (dark) | `bg-danger-surface` … | + +A project sets at minimum `primary` and maybe `secondary`/`accent`. Everything else has a neutral default, +which is enough for a consistent site. + +### 3.2 Typography + +| Token | Default | Utility | +|---|---|---| +| **`--ipal-font-body`** | `var(--font-body, ui-sans-serif, system-ui, sans-serif)` | `font-body` (also `font-sans`) | +| **`--ipal-font-heading`** | `var(--font-heading, var(--ipal-font-body))` | `font-heading` | +| **`--ipal-font-mono`** | `ui-monospace, monospace` | `font-mono` | +| `--ipal-fs-xs`**(new)** · `sm` · `base` · `lg` · `h4`**(new)** · `h3` · `h2` · `h1` · `display` | fluid.css / fluid-wide.css | `text-xs` … `text-display`, `text-lead` = `lg` | +| **`--ipal-lh-body`** / **`--ipal-lh-heading`** | `1.6` / `1.15` | `leading-body`, `leading-heading` | +| **`--ipal-fw-body`** / **`--ipal-fw-heading`** | `400` / `650` | `font-heading` sets weight via base layer | +| **`--ipal-tracking-heading`** | `-0.01em` | `tracking-heading` | + +Font slots: `next/font` exposes `variable: '--font-body'` and `'--font-heading'` on `` (not ``). These +two names are fixed by the standard, so every layout looks the same. Today sites use `--font-display` (3 sites), +`--font-heading` (2), `--font-sans`; the standard picks `--font-heading` and `--font-body`. Never repeat the family +name as a literal in `@theme` (two sites do; the literal silently wins or loses depending on layers). At most 2 families × 2–3 weights (§6.11b). + +### 3.3 Space + +The fluid scale (`--ipal-space-section`, `-gap`, `-gutter`) plus **`--ipal-space-section-sm`** (half a section, +1.5→3.75rem) and **`--ipal-space-stack`** (heading → content, 1→1.5rem). Utilities: `py-section`, +`py-section-sm`, `gap-gap`, `px-gutter`, `space-y-stack`, `mt-stack`. Small fixed steps stay Tailwind's +default 0.25rem scale. The standard adds no second numeric scale. + +### 3.4 Shape, depth, layout, motion + +| Group | Tokens | Defaults | Utilities | +|---|---|---|---| +| Radius | `--ipal-radius` (existing = controls: buttons, inputs), **`--ipal-radius-sm`**, **`--ipal-radius-card`**, **`--ipal-radius-media`**, **`--ipal-radius-full`** | `0.375rem`, `0.25rem`, `0.75rem`, `0.5rem`, `9999px` | `rounded-control`, `rounded-sm`, `rounded-card`, `rounded-media`, `rounded-full` | +| Shadow | **`--ipal-shadow-sm`**, **`-md`**, **`-lg`** | soft neutral; dark theme uses lower-alpha black + a 1px border-tinted ring | `shadow-sm/md/lg` | +| Container | `--ipal-container` (80rem), `--ipal-container-wide` (96rem), **`--ipal-container-narrow`** (48rem), `--ipal-measure` (68ch) | existing | `max-w-container`, `max-w-container-wide`, `max-w-narrow`, `max-w-measure` | +| Breakpoints | standard: `sm 40rem · md 48rem · lg 64rem · xl 80rem · 2xl 96rem` (Tailwind defaults). A project may *add* one (e.g. `xs 24rem`) as a recorded deviation, never move an existing one | CSS vars can't be used in `@media`; exported as TS constants | `sm:` … `2xl:`, container queries `@md:` | +| Motion | **`--ipal-duration-fast`** 150ms, **`--ipal-duration`** 250ms, **`--ipal-duration-slow`** 400ms, **`--ipal-ease-out`** `cubic-bezier(.22,1,.36,1)` (the curve ecogenica and saydiamonds already share), **`--ipal-ease-in-out`** `cubic-bezier(.65,0,.35,1)` | all durations `0ms` under `prefers-reduced-motion: reduce` and `html[data-a11y-motion=off]` | `duration-fast`, `duration-base`, `duration-slow`, `ease-out`, `ease-in-out` | +| Layers | **`--ipal-z-header`** 40, **`--ipal-z-overlay`** 50, **`--ipal-z-toast`** 60 (cookie banner, lightbox keeps its own 1000) | | `z-header` … | +| Focus | **`--ipal-focus-width`** 2px, **`--ipal-focus-offset`** 2px | | used by the base layer's `:focus-visible` | + +## 4. Format: what the plugin ships + +New package exports. All opt-in, each importable on its own: + +| Export | Content | +|---|---| +| `@intecion/ipal-kit/tokens.css` | **neutral defaults** for every token in section 3: `:root` (light), `[data-theme=dark]` (dark), the legacy `-dark` aliases, reduced-motion zeroing. Imports nothing. | +| `@intecion/ipal-kit/tailwind.css` | Tailwind 4 preset: `@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *))`, one `@theme inline { … }` that maps every utility in section 3 to its `--ipal-*` var, the theme-switch transition (`[data-theme-switching]`), and a tiny `@layer base` (`body` bg/text/font, headings font/weight/tracking, `:focus-visible` ring). | +| `@intecion/ipal-kit/fluid.css`, `fluid-wide.css` | unchanged role, + the 5 new variables | +| `@intecion/ipal-kit/a11y.css` (optional) | section 9 | +| `@intecion/ipal-kit` (root): `IPAL_TOKENS`, `ipalVar(name)`, `IPAL_BREAKPOINTS`, type `IpalTokenName`, `defineTokens()`, `tokensToCss()`, `contrastReport()` | TS building blocks: names → `var(--ipal-…)` strings for inline styles/charts, the breakpoint numbers for `sizes=` and `matchMedia`, the brand object (5.1) and its compilers | +| `bin: ipal-tokens` | `src/design/tokens.ts` → `src/design/tokens.css` (+ `--check` for CI / `ipal-doctor`) | + +A project that does not use Tailwind (saydiamonds today) imports `tokens.css` alone and writes `var(--ipal-…)` +in its own CSS. No Tailwind 3 preset: every Tailwind site is on v4 (survey, section 10). + +Project `styles.css` with the standard: + +```css +@import "tailwindcss"; +@import "@intecion/ipal-kit/fluid.css"; /* or fluid-wide.css */ +@import "@intecion/ipal-kit/tokens.css"; /* neutral defaults */ +@import "@intecion/ipal-kit/tailwind.css"; /* utilities, dark variant, base */ +@import "../../design/tokens.css"; /* the brand: generated, overrides the defaults */ +@source "../../../node_modules/@intecion/ipal-kit/dist/**/*.js"; +``` + +Order matters only for the last line: the brand file comes after the defaults. + +## 5. How a project sets its brand + +### 5.1 One tokens file (recommended: TypeScript source) + +```ts +// src/design/tokens.ts: the ONLY file you edit to rebrand +import { defineTokens } from '@intecion/ipal-kit' + +export const tokens = defineTokens({ + color: { + light: { primary: 'oklch(0.55 0.17 250)', accent: 'oklch(0.78 0.15 85)', bg: 'oklch(0.99 0 0)' }, + dark: { primary: 'oklch(0.70 0.15 250)', bg: 'oklch(0.16 0.01 250)' }, // missing keys → derived (5.4) + }, + font: { heading: 'var(--font-heading)', fwHeading: 700 }, + radius: { control: '999px', card: '1.25rem' }, + fluid: 'wide', // fluid.css (1280) or fluid-wide.css (1920): the site imports that file + // optional: rewrite the fluid scale from min → max pairs (replaces intecion's scripts/fluid-tokens.py) + fs: { h1: ['2.25rem', '4rem'], display: ['2.75rem', '5.5rem'] }, + theme: 'both', // 'light' | 'dark' | 'both'; 'dark' = dark values in :root (architekt: dark-only site) +}) +``` + +`pnpm exec ipal-tokens` writes `src/design/tokens.css` (committed, header "generated, do not edit") and +prints a **WCAG contrast report** for every text/surface pair (`text` on `bg`, `primary-text` on `primary`, +`text-inverse` on `surface-inverse`, `link` on `bg` …) in both themes. AA failure = non-zero exit. +`ipal-tokens --check` fails when the CSS is stale. `ipal-doctor` runs it. + +Why TS and not hand-written CSS: one typed object, validation of names (a typo is a TS error, not a silent +missing colour), the contrast check, and the same values available where CSS variables don't work: +`next/og` images, e-mail templates, `manifest` `theme_color` / ``. + +The CLI turns `fs` / `space` pairs into the same `clamp()` maths as fluid.css for the chosen range, so nobody +writes a clamp by hand and no project keeps its own generator script. + +**Alternative (decision 1):** the brand file is plain CSS (`src/design/tokens.css` written by hand, +`:root { … }` + `[data-theme=dark] { … }`). No CLI and no build step, but also no validation, no contrast +check and no values for OG/e-mail. Both forms produce the same variables, so a project may pick either. +The question is which one the starter and the agent guide use by default. + +### 5.2 `DESIGN.md` template + +The starter ships `DESIGN.md` with fixed sections, so every project describes the same things: + +1. **Brand in one sentence**, audience, the one memorable element (where the boldness goes) +2. **Colour**: table of the roles from 3.1 the brand sets (name, value light/dark, where it is used), with contrast results pasted from `ipal-tokens` +3. **Type**: the two families, weights, `fs` overrides (if any), heading style +4. **Shape and depth**: radii, shadow use, borders vs. shadows +5. **Layout**: fluid vs. fluid-wide, container widths, section rhythm, alignment +6. **Motion**: what moves and why (max one orchestrated moment), reduced-motion behaviour +7. **Imagery and icons**: photo style, focal points, lucide set +8. **Theme**: light only / dark only / both + default (`Site settings → Theme`) +9. **Deviations from the standard**: every override of a default, with the reason + +Rule: `DESIGN.md` is the human source; `src/design/tokens.ts` is its machine form. They must agree. +`ipal-doctor` warns when a role is in one and not the other. + +### 5.3 Dark mode and the legacy `-dark` names + +- `` sets `data-theme` before paint (unchanged). `tokens.css` flips every colour role under + `[data-theme=dark]`. Components write `bg-surface text-fg`, never `dark:bg-…` for colours. +- `dark:` stays available for non-colour differences (e.g. swap a logo image). +- Without `` (no theme in the project) the site is light. An optional + `@media (prefers-color-scheme: dark) { :root:not([data-theme=light]) { … } }` block is emitted only when + `defineTokens({ theme: { followSystemWithoutScript: true } })`. +- Legacy: CookieBanner/CookieButton read `dark:bg-[var(--ipal-surface-dark,#171717)]`. `tokens.css` defines + each `--ipal--dark` as the dark value, so those components already follow the brand in both themes + with no component change. In a later major version, plugin components switch to the new single names and the `-dark` + aliases are deprecated (kept, documented). +- One storage key, `theme` (theme.md). Nothing token-specific is stored. + +### 5.4 Derived values + +Unset hover/state tints are derived in CSS with `color-mix(in oklch, …)`: +`--ipal-primary-hover: color-mix(in oklch, var(--ipal-primary), black 12%)` (dark theme: `white 12%`), +`--ipal-link: var(--ipal-primary)`, `--ipal-focus: var(--ipal-primary)`. A project overrides any of them. +`color-mix` is Baseline 2023, which every browser we target supports. + +## 6. Components never change for a brand + +- Block library, starter primitives (`Button`, `Section`, `SectionHeader`, `Card`) and plugin components use + only the utilities/vars in section 3. +- `Section` maps `settings.background`: `default → bg-bg text-fg`, `muted → bg-surface-muted`, + `inverted → bg-inverse text-on-inverse` (and a scoped override so nested text tokens read inverse). +- `Button` variants map to `primary` / `secondary` / ghost (`hover`) / link, `rounded-control`, + `duration-fast ease-out`. +- Brand-specific looks that tokens can't express use a **variant** (§6.0 rule 5), never a fork. +- `ipal-audit` already errors on hex in classes. It gains: `dark:(bg|text|border)-` on colour utilities in + `src/blocks` (warning), `style={{ color: '#…' }}`, and raw `var(--color-…)` from older setups. + +## 7. `ext-frontend-design` and `DESIGN.md` + +The vendored skill already states "`DESIGN.md` tokens win". With the standard, its role is: + +- **Allowed:** proposing the brand direction (its "4–6 named colours, type, layout, principles" plan), but the + output is written into `DESIGN.md` + `src/design/tokens.ts`, mapped onto the fixed roles in 3.1, after the owner + approves it. Its "avoid generic defaults" critique applies to the *values* and to the composition inside + block variants. +- **Not allowed:** new token names, colours or fonts in components, extra motion beyond section 3.4, layout + systems outside the containers/fluid scale. +- The skill's override note gets one line: "Map your palette onto the `--ipal-*` roles; do not invent new ones. + Missing role → plugin gap." + +## 8. Changes to docs and skills (when building) + +- New `docs/design-tokens.md` (module doc: every token, defaults, utilities, the CLI, TS exports, turn off/override/extend). +- AGENT.md §6.11 / §6.11a / §7 table / §12 map: replace the ad-hoc `@theme` example with the standard. +- `ipal-setup` stage 5, `ipal-block` `section-code.md` "Styles", `ipal-site`, `ipal-reference` (`api.md`: new exports, bin, CSS files), `ipal-audit` checks, `ipal-upgrade` (migration steps). +- theme.md: the `@custom-variant` + transition move into `tailwind.css` (copy-paste remains documented for projects without the preset). consent.md / lightbox.md: point to the global tokens. +- `DESIGN.md` template under `docs/agent/skills/ipal-setup/resources/`. + +## 9. Accessibility tie-in (optional `a11y.css`) + +The a11y widget's CSS (now copy-paste) ships as `@intecion/ipal-kit/a11y.css` and works through tokens: +readable font → `--ipal-font-body/heading` swap; no animations → durations `0ms`; underlined links on +`--ipal-link`; text size stays `html { font-size }` (the fluid scale is rem-based, so it scales). Still opt-in; +the widget itself remains optional (accessibility.md). + +## 10. Migration of existing sites + +### 10.1 How the seven sites style things today (survey 2026-10-29, read-only) + +| Site | ipal-kit | Stack | Colour names | Dark mode | Fonts | Radius | Container | Fluid scale | +|---|---|---|---|---|---|---|---|---| +| architektimprezpl | 1.14.6 | TW4 `@theme` | `--color-bg/surface/surface-2/text/text-muted/accent-primary` + `--background/--foreground`, hex | dark-only, no toggle | local Excon → `--font-display`, `--font-body` | `0` (`rounded-none` ×52) | `max-w-7xl` | fluid.css imported, unused | +| coastalclimatesupplycomau | 1.14.1 | TW4 `@theme static` + `tokens.css` + many inline `style` | `--color-brand-*`, 13× `--color-surface-*`, 8× `--color-border-*`, hex | none | Inter / Montserrat (`--font-yankee` declared, never loaded) | 6px (banner only) | `--ccs-content-max-width` 1600px | own px `--ccs-*` clamp scale; clamp in ~60 TSX files | +| ecogenicacouk | 1.14.1 | TW4 tokens + 21 plain-CSS partials | `--color-primary/accent/background/foreground/muted/surface/border`, hex + oklch | none | Plex Sans `--font-body`, Archivo `--font-display` | 0 | `.container` 1440px | documented `@theme inline` map, plus many ad-hoc clamps | +| intecioncom | 1.14.6 | TW4 `@theme` + `@utility` | brand `--color-primary/lime/navy` + semantic `--color-surface*/fg/edge/accent`, hex | **yes**: `data-theme`, ipal `ThemeSwitcher`, key `theme`; 119 `dark:` | Outfit / Inter / Roboto Mono → `--font-heading/sans/mono` | `.75rem` + arbitrary 14–20px | `--ipal-container` 91.875rem / wide 118.75rem | fluid-wide.css, overridden by a Figma generator script | +| saydiamondspl | 1.11.0 | **no Tailwind**: plain CSS `@layer`, `.ui-*` | unprefixed `--ink/--paper/--burgundy/--gold/--line`, hex | none | Cormorant / Jakarta / JetBrains → `--font-display/body/utility` | 0–2px scale | 1360px | own Utopia `--step-*` / `--space-*` | +| thecleanteampl | ^1.12.2 | TW4 `@theme` + `@apply` components | `--color-primary/accent/dark/light/gray`, hex | none | Franklin / Signika → `--font-body/heading` (on ``) | 9999px | `.container` = `max-w-7xl` | fluid.css mapped, h1–h3 overridden (display < h1) | +| vanstevpl | 1.12.2 | TW4, fonts only in `@theme` | **none**: `text-[#E5680E]` ×49 etc. | none | Poppins / Roboto → `--font-sans`, `--font-button` | `.5rem` vs `rounded-none` ×51 | `max-w-7xl` / `container` | none | + +### 10.2 What differs, and what the standard fixes + +- **Five colour vocabularies** (shadcn-like, semantic surface/fg/edge, brand-prefixed, unprefixed, none). + `--color-accent` is a different role on every site. → One role set (3.1). The brand colours keep their own + names only inside `tokens.ts` comments and `DESIGN.md`. +- **Six sites redefine `--ipal-*-dark` = light values** only to stop the cookie banner going dark. → + `tokens.css` sets them from the theme; the workaround disappears. +- **Dark mode on one site only**, and it repeats colours with 119 `dark:` classes. → Roles flip on their own. +- **The fluid scale is imported but ignored on 2 sites, missing on 2, hand-generated on 1.** → `fs` pairs in + `tokens.ts` replace private scales and scripts. +- **Font var names**: `--font-display` vs `--font-heading`, `--font-sans` vs `--font-body`; set on `` on one site. → Fixed slots. +- **Radius lives only in `--ipal-radius`, and markup contradicts it.** → Semantic radii, used by components. +- **Containers**: 80rem ×3, 1360/1440/1600px, intecion's 91.875rem. → `--ipal-container` per brand (a value, not a rule). +- **Motion**: two sites have tokens with different names but the same curve. → `--ipal-duration-*` / `--ipal-ease-*`. +- **ipal-kit versions** range from 1.11.0 to 1.14.6, and one site uses a caret. Any migration starts with `ipal-upgrade` to the release that ships the tokens. + +### 10.3 Migration path (per site, opt-in, never forced) + +Adoption is **additive**: importing `tokens.css` + `tailwind.css` changes nothing visible until a site maps +its brand. The Tailwind utilities the preset adds (`bg-surface`, `text-fg`, `rounded-card` …) do not collide +with stock Tailwind names, except `shadow-sm/md/lg` and `rounded-sm/full`, which become token-driven but +default to the same Tailwind values. + +Per site: +1. `ipal-upgrade` to the token release; add the 4 imports (4) and `src/design/tokens.ts`. +2. **Map**: write the brand into `tokens.ts` from the site's current `@theme` (colours → roles, fonts → slots, + radius, container, fluid pairs). Keep the old `--color-*` names as **aliases** to `--ipal-*` in a marked + `/* legacy, remove after migration */` block, so no component breaks on day one. +3. Delete the `--ipal-*-dark` workaround block. +4. Replace hard-coded values and old utilities file by file (`ipal-audit` lists them); new blocks from the + shared library already use the standard. +5. Remove the legacy alias block when `ipal-audit` shows no old names. Write `DESIGN.md` from the template. + +Suggested order and effort (decision 5): + +| Site | Effort | Why | +|---|---|---| +| intecioncom | S–M | already semantic + `data-theme` + fluid-wide; mostly renames and dropping `dark:` colour classes; its generator becomes `fs` pairs. **Good pilot**, as it's the team's own site | +| thecleanteampl | S | small palette, fluid mapped; fix font vars on ``, display < h1 | +| ecogenicacouk | M | shadcn-like names map 1:1; the work is the 21 partials' ad-hoc clamps | +| architektimprezpl | M | dark-only → `theme: 'dark'`; spectrum/ember decorative colours stay project-only (deviation) | +| vanstevpl | M | no tokens at all: 49+ hex classes to replace, but a simple brand | +| coastalclimatesupplycomau | L | 13 surfaces / 8 borders to collapse, inline styles, own px scale | +| saydiamondspl | L | no Tailwind; 1.11.0. Adopt `tokens.css` only (map `--ink/--paper/…` onto roles); keep its CSS architecture | + +Nothing in these repos is edited by this proposal. + +## 11. Decisions for the owner + +1. **Brand source:** `src/design/tokens.ts` + `ipal-tokens` CLI generating `tokens.css`, with a contrast check and + values for OG/e-mail (**recommended**), or a hand-written `src/design/tokens.css` only. The var names and paths are the same either way. +2. **Utility names:** the plugin's own (`bg-bg`, `text-fg`, `text-fg-muted`, `bg-surface-muted`, `text-on-primary`) + (**recommended**: they match the vars CookieBanner already ships and intecion's semantic names), or shadcn-style + (`bg-background`, `text-foreground`, `bg-muted`, `text-muted-foreground`, `text-primary-foreground`), which only + ecogenica resembles and no site uses with shadcn/ui. +3. **Colour format in defaults and the starter:** oklch (**recommended**: even steps for the derived hovers) or + hex. Projects may write any CSS colour either way. +4. **Default fluid range for new sites:** `fluid.css` (to 1280) or `fluid-wide.css` (to 1920). Only intecion uses wide; + recommendation: fluid-wide, so 1440/1920 monitors aren't left with empty margins. +5. **Migration:** pilot on intecioncom, then the rest one by one when each site is next touched (**recommended**), + or a scheduled sweep. Includes whether coastal/saydiamonds migrate at all. +6. **Plugin components switch to the single-name tokens** (drop `dark:[var(--ipal-*-dark)]`) in this release with + the `-dark` aliases kept, or wait for a major version. Recommendation: this release. With the aliases, nothing breaks. +7. **`a11y.css`** as a shipped file (section 9): yes / not now. + +Agreed with: the block library (`design-tokens-names.md` in the shared notes), the starter and the reference site +(`design-tokens-wiring.md`). From 9286468ce9e94816f12fe073946184357dff4e79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 29 Oct 2026 13:30:10 +0100 Subject: [PATCH 2/8] Design tokens proposal: inverse surface scope Co-Authored-By: Claude Opus 5.5 --- docs/dev/design-tokens-proposal.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/docs/dev/design-tokens-proposal.md b/docs/dev/design-tokens-proposal.md index 0042b36..539ec5e 100644 --- a/docs/dev/design-tokens-proposal.md +++ b/docs/dev/design-tokens-proposal.md @@ -208,7 +208,19 @@ Unset hover/state tints are derived in CSS with `color-mix(in oklch, …)`: - Block library, starter primitives (`Button`, `Section`, `SectionHeader`, `Card`) and plugin components use only the utilities/vars in section 3. - `Section` maps `settings.background`: `default → bg-bg text-fg`, `muted → bg-surface-muted`, - `inverted → bg-inverse text-on-inverse` (and a scoped override so nested text tokens read inverse). + `inverted → bg-inverse` + `data-surface="inverse"` (agreed with the block library). +- **Inverse scope** (`tailwind.css` / `tokens.css`): `[data-surface=inverse]` re-maps the roles that nested content + reads, so cards, rich text, links and focus rings need no inverse variants: + `--ipal-text` and `--ipal-text-strong` → `--ipal-text-inverse`; + `--ipal-text-muted` → `color-mix(in oklch, var(--ipal-text-inverse) 72%, var(--ipal-surface-inverse))`; + `--ipal-border` / `-strong` → the same mix at 18% / 30%; + `--ipal-surface` and `--ipal-hover` → the mix at 8% / 12% (a card inside stays a step off the background); + `--ipal-link` → **`--ipal-link-inverse`**; `--ipal-focus` → **`--ipal-focus-inverse`**. + Both new tokens default to `--ipal-text-inverse`, and a brand may set them. It also sets `color-scheme` to the + opposite of the theme, so form controls match. `primary` / `accent` are not re-mapped: the `ipal-tokens` + contrast report checks `primary` on `surface-inverse` and warns. `data-surface="muted"` exists as a hook, + but re-maps nothing by default. The contrast report checks every text role on `surface-muted` too, so a + failing brand is caught there instead. - `Button` variants map to `primary` / `secondary` / ghost (`hover`) / link, `rounded-control`, `duration-fast ease-out`. - Brand-specific looks that tokens can't express use a **variant** (§6.0 rule 5), never a fork. From 18075bb7df2064998e9ed7d45e120805f215d774 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 29 Oct 2026 13:30:37 +0100 Subject: [PATCH 3/8] Design tokens proposal: record approved decisions Co-Authored-By: Claude Opus 5.5 --- docs/dev/design-tokens-proposal.md | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/docs/dev/design-tokens-proposal.md b/docs/dev/design-tokens-proposal.md index 539ec5e..3466fc0 100644 --- a/docs/dev/design-tokens-proposal.md +++ b/docs/dev/design-tokens-proposal.md @@ -1,6 +1,7 @@ # Design tokens: proposal (draft for approval) -Status: **proposal, nothing built yet.** Branch `claude/design-tokens-95806d`. +Status: **approved 2026-10-29 (all recommendations in section 11 accepted); not built yet.** Building starts when +the coordinator confirms all five designs are consistent. Branch `claude/design-tokens-95806d`. Consumers: the shared block library, the project starter, the reference site and `ipal-doctor`. ## 1. Goal and the one rule @@ -316,7 +317,23 @@ Suggested order and effort (decision 5): Nothing in these repos is edited by this proposal. -## 11. Decisions for the owner +## 11. Decisions (approved 2026-10-29) + +The owner accepted every recommendation: + +| # | Decision | +|---|---| +| 1 | Brand source: `src/design/tokens.ts` + the `ipal-tokens` CLI generating `src/design/tokens.css` | +| 2 | Utility names: the plugin's own (`bg-bg`, `text-fg`, `text-fg-muted`, `bg-surface-muted`, `text-on-primary` …) | +| 3 | Colour format: oklch in the defaults and the starter (any CSS colour still accepted) | +| 4 | Default scale for new sites: `fluid-wide.css` | +| 5 | Migration: intecioncom pilot, then each site when it is next touched | +| 6 | Plugin components move to the single token names in this release; the `-dark` aliases stay | +| 7 | Ship `@intecion/ipal-kit/a11y.css` | + +Also agreed with the block library: the inverse scope (`data-surface="inverse"`, section 6). + +### Options as proposed 1. **Brand source:** `src/design/tokens.ts` + `ipal-tokens` CLI generating `tokens.css`, with a contrast check and values for OG/e-mail (**recommended**), or a hand-written `src/design/tokens.css` only. The var names and paths are the same either way. From 500c534bc9f98567a86c3b8fcb60b4cfb4de0390 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 29 Oct 2026 13:30:58 +0100 Subject: [PATCH 4/8] Design tokens proposal: fluid-wide in the styles.css example Co-Authored-By: Claude Opus 5.5 --- docs/dev/design-tokens-proposal.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/dev/design-tokens-proposal.md b/docs/dev/design-tokens-proposal.md index 3466fc0..139f81c 100644 --- a/docs/dev/design-tokens-proposal.md +++ b/docs/dev/design-tokens-proposal.md @@ -118,7 +118,7 @@ Project `styles.css` with the standard: ```css @import "tailwindcss"; -@import "@intecion/ipal-kit/fluid.css"; /* or fluid-wide.css */ +@import "@intecion/ipal-kit/fluid-wide.css"; /* default for new sites (decision 4); or fluid.css */ @import "@intecion/ipal-kit/tokens.css"; /* neutral defaults */ @import "@intecion/ipal-kit/tailwind.css"; /* utilities, dark variant, base */ @import "../../design/tokens.css"; /* the brand: generated, overrides the defaults */ From 9511b12d19b465d745175abde6d4bf916f1df0cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 29 Oct 2026 13:52:37 +0100 Subject: [PATCH 5/8] Design tokens: tokens.css, tailwind.css, a11y.css and the TS token module tokens.css (neutral --ipal-* defaults, light/dark, inverse scope, reduced motion) is generated from src/modules/tokens/catalog.ts. tailwind.css maps the utilities. New @intecion/ipal-kit/tokens entry: IPAL_TOKENS, ipalVar, IPAL_BREAKPOINTS, defineTokens, tokensToCss, contrastReport, fluidClamp. fluid.css / fluid-wide.css gain fs-xs, fs-h4, space-stack, space-section-sm. Co-Authored-By: Claude Opus 5.5 --- package.json | 10 +- src/exports/tokens.ts | 7 ++ src/index.ts | 2 + src/modules/tokens/catalog.ts | 139 +++++++++++++++++++++++++ src/modules/tokens/color.ts | 178 +++++++++++++++++++++++++++++++++ src/modules/tokens/contrast.ts | 69 +++++++++++++ src/modules/tokens/css.ts | 106 ++++++++++++++++++++ src/modules/tokens/define.ts | 123 +++++++++++++++++++++++ src/modules/tokens/fluid.ts | 59 +++++++++++ src/modules/tokens/index.ts | 11 ++ src/modules/tokens/names.ts | 27 +++++ src/styles/a11y.css | 62 ++++++++++++ src/styles/fluid-wide.css | 4 + src/styles/fluid.css | 4 + src/styles/tailwind.css | 154 ++++++++++++++++++++++++++++ src/styles/tokens.css | 161 +++++++++++++++++++++++++++++ 16 files changed, 1115 insertions(+), 1 deletion(-) create mode 100644 src/exports/tokens.ts create mode 100644 src/modules/tokens/catalog.ts create mode 100644 src/modules/tokens/color.ts create mode 100644 src/modules/tokens/contrast.ts create mode 100644 src/modules/tokens/css.ts create mode 100644 src/modules/tokens/define.ts create mode 100644 src/modules/tokens/fluid.ts create mode 100644 src/modules/tokens/index.ts create mode 100644 src/modules/tokens/names.ts create mode 100644 src/styles/a11y.css create mode 100644 src/styles/tailwind.css create mode 100644 src/styles/tokens.css diff --git a/package.json b/package.json index d9cf0ca..8e5004b 100644 --- a/package.json +++ b/package.json @@ -49,8 +49,16 @@ "types": "./dist/exports/env.d.ts", "default": "./dist/exports/env.js" }, + "./tokens": { + "import": "./dist/exports/tokens.js", + "types": "./dist/exports/tokens.d.ts", + "default": "./dist/exports/tokens.js" + }, "./fluid.css": "./dist/styles/fluid.css", - "./fluid-wide.css": "./dist/styles/fluid-wide.css" + "./fluid-wide.css": "./dist/styles/fluid-wide.css", + "./tokens.css": "./dist/styles/tokens.css", + "./tailwind.css": "./dist/styles/tailwind.css", + "./a11y.css": "./dist/styles/a11y.css" }, "main": "./dist/index.js", "types": "./dist/index.d.ts", diff --git a/src/exports/tokens.ts b/src/exports/tokens.ts new file mode 100644 index 0000000..50f9312 --- /dev/null +++ b/src/exports/tokens.ts @@ -0,0 +1,7 @@ +/** + * Entry point: @intecion/ipal-kit/tokens + * + * Design tokens with no Payload, React or Next import — safe in src/design/tokens.ts, + * the `ipal-tokens` CLI, next/og images and e-mail templates. docs/design-tokens.md. + */ +export * from '../modules/tokens/index.js' diff --git a/src/index.ts b/src/index.ts index 1de0439..6e12c2f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -382,6 +382,8 @@ export { isTheme, isThemeSetting, LEGACY_THEME_STORAGE_KEY, THEME_ATTRIBUTE, THE export type { Theme, ThemeConfig, ThemeSetting } from './modules/theme/index.js' // Imported from the file, not the turnstile barrel — that one re-exports verify, // which imports 'server-only'. +export { defineTokens, IPAL_BREAKPOINTS, IPAL_TOKENS, ipalVar } from './modules/tokens/index.js' +export type { IpalTokenName, TokensInput } from './modules/tokens/index.js' export { getTurnstileConfig } from './modules/turnstile/config.js' export type { TurnstileConfig } from './modules/turnstile/config.js' export { ipalKit } from './plugin.js' diff --git a/src/modules/tokens/catalog.ts b/src/modules/tokens/catalog.ts new file mode 100644 index 0000000..01443a9 --- /dev/null +++ b/src/modules/tokens/catalog.ts @@ -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)' }, + surface: { dark: 'oklch(0.205 0 0)', light: 'oklch(1 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)' }, + 'surface-inverse': { dark: 'oklch(0.97 0 0)', light: 'oklch(0.205 0 0)' }, + text: { dark: 'oklch(0.87 0 0)', light: 'oklch(0.371 0 0)' }, + 'text-strong': { dark: 'oklch(0.97 0 0)', light: 'oklch(0.205 0 0)' }, + 'text-muted': { dark: 'oklch(0.708 0 0)', light: 'oklch(0.53 0 0)' }, + 'text-inverse': { dark: 'oklch(0.205 0 0)', light: 'oklch(0.97 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)' }, + // darker in both themes: the text on primary stays readable on hover + '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)' }, + accent: { dark: 'var(--ipal-primary)', light: 'var(--ipal-primary)' }, + 'accent-text': { dark: 'var(--ipal-primary-text)', light: 'var(--ipal-primary-text)' }, + 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)' }, + hover: { dark: 'oklch(0.269 0 0)', light: 'oklch(0.97 0 0)' }, + focus: { dark: 'var(--ipal-link)', light: 'var(--ipal-link)' }, + 'focus-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)' }, + 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)' }, + 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)' }, + 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)' }, +} as const satisfies Record + +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> = { + text: 'var(--ipal-text-inverse)', + 'text-strong': 'var(--ipal-text-inverse)', + 'text-muted': onInverse(72), + border: onInverse(18), + 'border-strong': onInverse(30), + surface: onInverse(8), + hover: onInverse(12), + link: 'var(--ipal-link-inverse)', + focus: 'var(--ipal-focus-inverse)', +} + +/** Theme-independent tokens. Key = token name without `--ipal-`. */ +export const STATIC_DEFAULTS = { + // next/font slots: variable '--font-family-body' / '--font-family-heading' on . Not --font-body: + // that name is Tailwind's font-body utility key, which maps back to these tokens (a var() cycle). + '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)', + 'lh-body': '1.6', + 'lh-heading': '1.15', + 'fw-body': '400', + 'fw-heading': '650', + 'tracking-heading': '-0.01em', + radius: '0.375rem', + 'radius-sm': '0.25rem', + 'radius-card': '0.75rem', + 'radius-media': '0.5rem', + 'radius-full': '9999px', + 'shadow-sm': '0 1px 2px 0 oklch(0 0 0 / 0.06), 0 1px 3px 0 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-lg': '0 16px 32px -8px oklch(0 0 0 / 0.14), 0 4px 8px -4px oklch(0 0 0 / 0.08)', + 'container-narrow': '48rem', + 'duration-fast': '150ms', + duration: '250ms', + 'duration-slow': '400ms', + 'ease-out': 'cubic-bezier(0.22, 1, 0.36, 1)', + 'ease-in-out': 'cubic-bezier(0.65, 0, 0.35, 1)', + 'z-header': '40', + 'z-overlay': '50', + 'z-toast': '60', + 'focus-width': '2px', + 'focus-offset': '2px', +} as const + +/** Dark-theme shadows: deeper black plus a hairline ring, since a soft grey shadow vanishes on dark. */ +export const DARK_SHADOWS = { + 'shadow-sm': '0 1px 2px 0 oklch(0 0 0 / 0.4), 0 0 0 1px oklch(1 0 0 / 0.04)', + 'shadow-md': '0 4px 8px -2px oklch(0 0 0 / 0.5), 0 0 0 1px oklch(1 0 0 / 0.05)', + 'shadow-lg': '0 16px 32px -8px oklch(0 0 0 / 0.6), 0 0 0 1px oklch(1 0 0 / 0.06)', +} 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 = ColorRole | FluidToken | StaticToken | `${(typeof LEGACY_DARK_ROLES)[number]}-dark` + +/** Standard breakpoints in rem (Tailwind 4 defaults). CSS variables can't be used in `@media`. */ +export const IPAL_BREAKPOINTS = { sm: 40, md: 48, lg: 64, xl: 80, '2xl': 96 } as const diff --git a/src/modules/tokens/color.ts b/src/modules/tokens/color.ts new file mode 100644 index 0000000..96e6766 --- /dev/null +++ b/src/modules/tokens/color.ts @@ -0,0 +1,178 @@ +/** + * 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 = { + 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 ? { args: m[2], name: m[1].toLowerCase() } : 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 m = /^(.*?)\s+(\d*\.?\d+)%$/.exec(s) + return m ? { color: m[1], pct: Number(m[2]) / 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) +} diff --git a/src/modules/tokens/contrast.ts b/src/modules/tokens/contrast.ts new file mode 100644 index 0000000..e4142c2 --- /dev/null +++ b/src/modules/tokens/contrast.ts @@ -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 = resolved[theme] + const inverse: Record = { ...colors, ...INVERSE_SCOPE } + const check = (map: Record, 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'))] + }) +} diff --git a/src/modules/tokens/css.ts b/src/modules/tokens/css.ts new file mode 100644 index 0000000..52a3838 --- /dev/null +++ b/src/modules/tokens/css.ts @@ -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 + +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 , + * 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 => { + const range = input.fluid === 'standard' ? 'standard' : 'wide' + const pairs = (prefix: string, map: Record = {}) => + 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): 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 after @intecion/ipal-kit/tokens.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 = 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' +} diff --git a/src/modules/tokens/define.ts b/src/modules/tokens/define.ts new file mode 100644 index 0000000..d4d725f --- /dev/null +++ b/src/modules/tokens/define.ts @@ -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> + +/** + * 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 } + 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, readonly [RemValue, RemValue]>> + /** Which fluid file the site imports: `'wide'` = fluid-wide.css (grows to 1920px, the default for new sites). */ + fluid?: FluidRange + 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 + shadow?: { lg?: string; md?: string; sm?: string } + space?: Partial, readonly [RemValue, RemValue]>> + /** `'both'` (default): light + dark. `'light'` / `'dark'`: a one-theme site; the other theme never applies. */ + theme?: 'both' | 'dark' | 'light' +} + +type FluidSizeName

= 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, known: Record, 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(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 + +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 { + const out: Record = {} + 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 +} diff --git a/src/modules/tokens/fluid.ts b/src/modules/tokens/fluid.ts new file mode 100644 index 0000000..32cce8d --- /dev/null +++ b/src/modules/tokens/fluid.ts @@ -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-xs': [0.75, 0.8125], + 'fs-sm': [0.875, 0.9375], + 'fs-base': [1, 1.125], + 'fs-lg': [1.125, 1.375], + 'fs-h4': [1.125, 1.5], + 'fs-h3': [1.25, 1.75], + 'fs-h2': [1.5, 2.5], + 'fs-h1': [2, 3.5], + 'fs-display': [2.5, 4.5], + 'space-stack': [1, 1.5], + 'space-gap': [1, 2], + 'space-gutter': [1, 2.5], + 'space-section-sm': [1.5, 3.75], + 'space-section': [3, 7.5], +} as const satisfies Record + +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+)\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)` +} diff --git a/src/modules/tokens/index.ts b/src/modules/tokens/index.ts new file mode 100644 index 0000000..fc79e50 --- /dev/null +++ b/src/modules/tokens/index.ts @@ -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' diff --git a/src/modules/tokens/names.ts b/src/modules/tokens/names.ts new file mode 100644 index 0000000..97b8296 --- /dev/null +++ b/src/modules/tokens/names.ts @@ -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, +) + +/** `var(--ipal-)`, 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})` +} diff --git a/src/styles/a11y.css b/src/styles/a11y.css new file mode 100644 index 0000000..e35ab5a --- /dev/null +++ b/src/styles/a11y.css @@ -0,0 +1,62 @@ +/* + * @intecion/ipal-kit/a11y.css — the CSS for the accessibility widget's attributes + * (data-a11y-* on , set by ; docs/accessibility.md). + * Optional: import it only on a site that shows . Works through the + * design tokens: the readable font swaps --ipal-font-body/-heading, "no animations" + * zeroes the --ipal-duration-* tokens (tokens.css) and stops every other animation. + * Override any value after the import, e.g. --ipal-font-readable. + */ + +:root { + --ipal-font-readable: Verdana, Tahoma, "Segoe UI", sans-serif; +} + +/* Text size: the fluid scale is in rem, so everything grows with the root size */ +html[data-a11y-text="1"] { font-size: 112.5%; } +html[data-a11y-text="2"] { font-size: 125%; } +html[data-a11y-text="3"] { font-size: 150%; } + +/* Line spacing */ +html[data-a11y-line="1"] { --ipal-lh-body: 1.8; --ipal-lh-heading: 1.45; } +html[data-a11y-line="2"] { --ipal-lh-body: 2.2; --ipal-lh-heading: 1.7; } +html[data-a11y-line="1"] body * { line-height: 1.8 !important; } +html[data-a11y-line="2"] body * { line-height: 2.2 !important; } + +/* Contrast and grayscale: one filter value per combination (filter values do not stack) */ +html[data-a11y-contrast="high"] { filter: contrast(1.4); } +html[data-a11y-grayscale="on"] { filter: grayscale(1); } +html[data-a11y-contrast="high"][data-a11y-grayscale="on"] { filter: contrast(1.4) grayscale(1); } +html[data-a11y-contrast="inverted"] { filter: invert(1) hue-rotate(180deg); } +html[data-a11y-contrast="inverted"][data-a11y-grayscale="on"] { filter: invert(1) hue-rotate(180deg) grayscale(1); } +html[data-a11y-contrast="inverted"] img, +html[data-a11y-contrast="inverted"] video, +html[data-a11y-contrast="inverted"] picture { + filter: invert(1) hue-rotate(180deg); /* media keep their own colours */ +} + +/* Underlined links */ +html[data-a11y-underline="on"] a { text-decoration: underline !important; } + +/* Readable font */ +html[data-a11y-font="readable"] { + --ipal-font-body: var(--ipal-font-readable); + --ipal-font-heading: var(--ipal-font-readable); + letter-spacing: 0.02em; +} +html[data-a11y-font="readable"] body * { font-family: var(--ipal-font-readable) !important; } + +/* No animations (the duration tokens are zeroed in tokens.css) */ +html[data-a11y-motion="reduce"] *, +html[data-a11y-motion="reduce"] *::before, +html[data-a11y-motion="reduce"] *::after { + animation-duration: 0.001ms !important; + animation-iteration-count: 1 !important; + scroll-behavior: auto !important; + transition-duration: 0.001ms !important; +} + +/* Big cursor */ +html[data-a11y-cursor="big"], +html[data-a11y-cursor="big"] * { + cursor: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='48' height='48' viewBox='0 0 24 24'%3E%3Cpath d='M4 2l16 11-7 1.5 4 7.5-3 1.5-4-7.5L4 21z' fill='black' stroke='white' stroke-width='1.5'/%3E%3C/svg%3E") 4 2, auto !important; +} diff --git a/src/styles/fluid-wide.css b/src/styles/fluid-wide.css index bae1bf6..24feeab 100644 --- a/src/styles/fluid-wide.css +++ b/src/styles/fluid-wide.css @@ -13,15 +13,19 @@ * any variable in the project's :root. */ :root { + --ipal-fs-xs: clamp(0.75rem, 0.7356rem + 0.0641vw, 0.8125rem); /* 0.75→0.8125rem · fine print, legal (since 1.15.0) */ --ipal-fs-sm: clamp(0.875rem, 0.8606rem + 0.0641vw, 0.9375rem); /* 0.875→0.9375rem · small print, captions */ --ipal-fs-base: clamp(1rem, 0.9712rem + 0.1282vw, 1.125rem); /* 1→1.125rem · body text */ --ipal-fs-lg: clamp(1.125rem, 1.0673rem + 0.2564vw, 1.375rem); /* 1.125→1.375rem · lead / intro */ + --ipal-fs-h4: clamp(1.125rem, 1.0385rem + 0.3846vw, 1.5rem); /* 1.125→1.5rem · h4, card titles (since 1.15.0) */ --ipal-fs-h3: clamp(1.25rem, 1.1346rem + 0.5128vw, 1.75rem); /* 1.25→1.75rem · h3 */ --ipal-fs-h2: clamp(1.5rem, 1.2692rem + 1.0256vw, 2.5rem); /* 1.5→2.5rem · h2 — section headings */ --ipal-fs-h1: clamp(2rem, 1.6538rem + 1.5385vw, 3.5rem); /* 2→3.5rem · h1 — page heading */ --ipal-fs-display: clamp(2.5rem, 2.0385rem + 2.0513vw, 4.5rem); /* 2.5→4.5rem · hero / display */ + --ipal-space-stack: clamp(1rem, 0.8846rem + 0.5128vw, 1.5rem); /* 1→1.5rem · heading → content (since 1.15.0) */ --ipal-space-gap: clamp(1rem, 0.7692rem + 1.0256vw, 2rem); /* 1→2rem · gap between items in a section */ --ipal-space-gutter: clamp(1rem, 0.6538rem + 1.5385vw, 2.5rem); /* 1→2.5rem · container side padding */ + --ipal-space-section-sm: clamp(1.5rem, 0.9808rem + 2.3077vw, 3.75rem); /* 1.5→3.75rem · compact section: CTA band, logos (since 1.15.0) */ --ipal-space-section: clamp(3rem, 1.9615rem + 4.6154vw, 7.5rem); /* 3→7.5rem · vertical padding of a section */ } diff --git a/src/styles/fluid.css b/src/styles/fluid.css index 4c1d717..26f7aee 100644 --- a/src/styles/fluid.css +++ b/src/styles/fluid.css @@ -24,15 +24,19 @@ * @intecion/ipal-kit/fluid-wide.css instead: same variables, scaled 360 → 1920px. */ :root { + --ipal-fs-xs: clamp(0.75rem, 0.7255rem + 0.1087vw, 0.8125rem); /* 0.75→0.8125rem · fine print, legal (since 1.15.0) */ --ipal-fs-sm: clamp(0.875rem, 0.8505rem + 0.1087vw, 0.9375rem); /* 0.875→0.9375rem · small print, captions */ --ipal-fs-base: clamp(1rem, 0.9511rem + 0.2174vw, 1.125rem); /* 1→1.125rem · body text */ --ipal-fs-lg: clamp(1.125rem, 1.0272rem + 0.4348vw, 1.375rem); /* 1.125→1.375rem · lead / intro */ + --ipal-fs-h4: clamp(1.125rem, 0.9783rem + 0.6522vw, 1.5rem); /* 1.125→1.5rem · h4, card titles (since 1.15.0) */ --ipal-fs-h3: clamp(1.25rem, 1.0543rem + 0.8696vw, 1.75rem); /* 1.25→1.75rem · h3 */ --ipal-fs-h2: clamp(1.5rem, 1.1087rem + 1.7391vw, 2.5rem); /* 1.5→2.5rem · h2 — section headings */ --ipal-fs-h1: clamp(2rem, 1.413rem + 2.6087vw, 3.5rem); /* 2→3.5rem · h1 — page heading */ --ipal-fs-display: clamp(2.5rem, 1.7174rem + 3.4783vw, 4.5rem); /* 2.5→4.5rem · hero / display */ + --ipal-space-stack: clamp(1rem, 0.8043rem + 0.8696vw, 1.5rem); /* 1→1.5rem · heading → content (since 1.15.0) */ --ipal-space-gap: clamp(1rem, 0.6087rem + 1.7391vw, 2rem); /* 1→2rem · gap between items in a section */ --ipal-space-gutter: clamp(1rem, 0.413rem + 2.6087vw, 2.5rem); /* 1→2.5rem · container side padding */ + --ipal-space-section-sm: clamp(1.5rem, 0.6196rem + 3.913vw, 3.75rem); /* 1.5→3.75rem · compact section: CTA band, logos (since 1.15.0) */ --ipal-space-section: clamp(3rem, 1.2391rem + 7.8261vw, 7.5rem); /* 3→7.5rem · vertical padding of a section */ } diff --git a/src/styles/tailwind.css b/src/styles/tailwind.css new file mode 100644 index 0000000..99745a5 --- /dev/null +++ b/src/styles/tailwind.css @@ -0,0 +1,154 @@ +/* + * @intecion/ipal-kit/tailwind.css — Tailwind 4 preset for the --ipal-* design tokens + * (docs/design-tokens.md). Import after "tailwindcss" and tokens.css: + * + * @import "tailwindcss"; + * @import "@intecion/ipal-kit/fluid-wide.css"; + * @import "@intecion/ipal-kit/tokens.css"; + * @import "@intecion/ipal-kit/tailwind.css"; + * @import "../../design/tokens.css"; + * + * `@theme inline` makes every utility read the --ipal-* variable where it is used, so a + * scope that re-maps a token (dark theme, data-surface="inverse") reaches every utility. + * Colours switch with the theme on their own: no dark: variant for colours. + */ + +/* dark: follows (data-theme on ), not the device setting */ +@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *)); + +@theme inline { + --color-bg: var(--ipal-bg); + --color-surface: var(--ipal-surface); + --color-surface-muted: var(--ipal-surface-muted); + --color-surface-raised: var(--ipal-surface-raised); + --color-inverse: var(--ipal-surface-inverse); + --color-on-inverse: var(--ipal-text-inverse); + --color-fg: var(--ipal-text); + --color-fg-strong: var(--ipal-text-strong); + --color-fg-muted: var(--ipal-text-muted); + --color-border: var(--ipal-border); + --color-border-strong: var(--ipal-border-strong); + --color-primary: var(--ipal-primary); + --color-primary-hover: var(--ipal-primary-hover); + --color-on-primary: var(--ipal-primary-text); + --color-secondary: var(--ipal-secondary); + --color-secondary-hover: var(--ipal-secondary-hover); + --color-on-secondary: var(--ipal-secondary-text); + --color-accent: var(--ipal-accent); + --color-on-accent: var(--ipal-accent-text); + --color-link: var(--ipal-link); + --color-link-hover: var(--ipal-link-hover); + --color-hover: var(--ipal-hover); + --color-focus: var(--ipal-focus); + --color-overlay: var(--ipal-overlay); + --color-success: var(--ipal-success); + --color-success-surface: var(--ipal-success-surface); + --color-warning: var(--ipal-warning); + --color-warning-surface: var(--ipal-warning-surface); + --color-danger: var(--ipal-danger); + --color-danger-surface: var(--ipal-danger-surface); + --color-info: var(--ipal-info); + --color-info-surface: var(--ipal-info-surface); + + --font-sans: var(--ipal-font-body); + --font-body: var(--ipal-font-body); + --font-heading: var(--ipal-font-heading); + --font-mono: var(--ipal-font-mono); + + --text-xs: var(--ipal-fs-xs); + --text-sm: var(--ipal-fs-sm); + --text-base: var(--ipal-fs-base); + --text-lg: var(--ipal-fs-lg); + --text-lead: var(--ipal-fs-lg); + --text-lead--line-height: var(--ipal-lh-body); + --text-h4: var(--ipal-fs-h4); + --text-h4--line-height: var(--ipal-lh-heading); + --text-h3: var(--ipal-fs-h3); + --text-h3--line-height: var(--ipal-lh-heading); + --text-h2: var(--ipal-fs-h2); + --text-h2--line-height: var(--ipal-lh-heading); + --text-h1: var(--ipal-fs-h1); + --text-h1--line-height: var(--ipal-lh-heading); + --text-display: var(--ipal-fs-display); + --text-display--line-height: var(--ipal-lh-heading); + --leading-body: var(--ipal-lh-body); + --leading-heading: var(--ipal-lh-heading); + --tracking-heading: var(--ipal-tracking-heading); + + --spacing-stack: var(--ipal-space-stack); + --spacing-gap: var(--ipal-space-gap); + --spacing-gutter: var(--ipal-space-gutter); + --spacing-section-sm: var(--ipal-space-section-sm); + --spacing-section: var(--ipal-space-section); + + --radius-control: var(--ipal-radius); + --radius-sm: var(--ipal-radius-sm); + --radius-card: var(--ipal-radius-card); + --radius-media: var(--ipal-radius-media); + + --shadow-sm: var(--ipal-shadow-sm); + --shadow-md: var(--ipal-shadow-md); + --shadow-lg: var(--ipal-shadow-lg); + + --container-container: var(--ipal-container); + --container-container-wide: var(--ipal-container-wide); + --container-narrow: var(--ipal-container-narrow); + --container-measure: var(--ipal-measure); + + --ease-out: var(--ipal-ease-out); + --ease-in-out: var(--ipal-ease-in-out); +} + +/* Durations and layers have no theme namespace in Tailwind 4: plain utilities. */ +@utility duration-fast { + transition-duration: var(--ipal-duration-fast); +} +@utility duration-base { + transition-duration: var(--ipal-duration); +} +@utility duration-slow { + transition-duration: var(--ipal-duration-slow); +} +@utility z-header { + z-index: var(--ipal-z-header); +} +@utility z-overlay { + z-index: var(--ipal-z-overlay); +} +@utility z-toast { + z-index: var(--ipal-z-toast); +} + +@layer base { + body { + background-color: var(--ipal-bg); + color: var(--ipal-text); + font-family: var(--ipal-font-body); + font-weight: var(--ipal-fw-body); + line-height: var(--ipal-lh-body); + } + h1, h2, h3, h4, h5, h6 { + color: var(--ipal-text-strong); + font-family: var(--ipal-font-heading); + font-weight: var(--ipal-fw-heading); + letter-spacing: var(--ipal-tracking-heading); + line-height: var(--ipal-lh-heading); + } + /* a scope that re-maps the text roles (data-surface="inverse") also sets its own text colour */ + [data-surface] { + color: var(--ipal-text); + } + :focus-visible { + outline: var(--ipal-focus-width) solid var(--ipal-focus); + outline-offset: var(--ipal-focus-offset); + } +} + +/* Smooth colours only at the moment the theme switches (applyTheme sets data-theme-switching). */ +[data-theme-switching] *, +[data-theme-switching] *::before, +[data-theme-switching] *::after { + transition-duration: var(--ipal-duration) !important; + transition-property: background-color, border-color, color, fill, stroke !important; + transition-timing-function: var(--ipal-ease-in-out) !important; +} diff --git a/src/styles/tokens.css b/src/styles/tokens.css new file mode 100644 index 0000000..e0e37e1 --- /dev/null +++ b/src/styles/tokens.css @@ -0,0 +1,161 @@ +/* + * @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 , + * 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. + */ + +:root { + --ipal-bg: oklch(1 0 0); + --ipal-surface: oklch(1 0 0); + --ipal-surface-muted: oklch(0.97 0 0); + --ipal-surface-raised: oklch(1 0 0); + --ipal-surface-inverse: oklch(0.205 0 0); + --ipal-text: oklch(0.371 0 0); + --ipal-text-strong: oklch(0.205 0 0); + --ipal-text-muted: oklch(0.53 0 0); + --ipal-text-inverse: oklch(0.97 0 0); + --ipal-border: oklch(0.922 0 0); + --ipal-border-strong: oklch(0.87 0 0); + --ipal-primary: oklch(0.546 0.245 262.881); + --ipal-primary-hover: color-mix(in oklch, var(--ipal-primary), black 12%); + --ipal-primary-text: oklch(1 0 0); + --ipal-secondary: var(--ipal-text-strong); + --ipal-secondary-hover: color-mix(in oklch, var(--ipal-secondary), white 18%); + --ipal-secondary-text: var(--ipal-text-inverse); + --ipal-accent: var(--ipal-primary); + --ipal-accent-text: var(--ipal-primary-text); + --ipal-link: var(--ipal-primary); + --ipal-link-hover: color-mix(in oklch, var(--ipal-link), var(--ipal-text-strong) 30%); + --ipal-link-inverse: var(--ipal-text-inverse); + --ipal-hover: oklch(0.97 0 0); + --ipal-focus: var(--ipal-link); + --ipal-focus-inverse: var(--ipal-text-inverse); + --ipal-overlay: oklch(0 0 0 / 0.5); + --ipal-success: oklch(0.527 0.154 150.069); + --ipal-success-surface: oklch(0.982 0.018 155.826); + --ipal-warning: oklch(0.555 0.163 48.998); + --ipal-warning-surface: oklch(0.987 0.022 95.277); + --ipal-danger: oklch(0.505 0.213 27.518); + --ipal-danger-surface: oklch(0.971 0.013 17.38); + --ipal-info: oklch(0.488 0.243 264.376); + --ipal-info-surface: oklch(0.97 0.014 254.604); + --ipal-font-body: var(--font-family-body, ui-sans-serif, system-ui, sans-serif); + --ipal-font-heading: var(--font-family-heading, var(--ipal-font-body)); + --ipal-font-mono: var(--font-family-mono, ui-monospace, SFMono-Regular, Menlo, monospace); + --ipal-lh-body: 1.6; + --ipal-lh-heading: 1.15; + --ipal-fw-body: 400; + --ipal-fw-heading: 650; + --ipal-tracking-heading: -0.01em; + --ipal-radius: 0.375rem; + --ipal-radius-sm: 0.25rem; + --ipal-radius-card: 0.75rem; + --ipal-radius-media: 0.5rem; + --ipal-radius-full: 9999px; + --ipal-shadow-sm: 0 1px 2px 0 oklch(0 0 0 / 0.06), 0 1px 3px 0 oklch(0 0 0 / 0.08); + --ipal-shadow-md: 0 4px 8px -2px oklch(0 0 0 / 0.08), 0 2px 4px -2px oklch(0 0 0 / 0.06); + --ipal-shadow-lg: 0 16px 32px -8px oklch(0 0 0 / 0.14), 0 4px 8px -4px oklch(0 0 0 / 0.08); + --ipal-container-narrow: 48rem; + --ipal-duration-fast: 150ms; + --ipal-duration: 250ms; + --ipal-duration-slow: 400ms; + --ipal-ease-out: cubic-bezier(0.22, 1, 0.36, 1); + --ipal-ease-in-out: cubic-bezier(0.65, 0, 0.35, 1); + --ipal-z-header: 40; + --ipal-z-overlay: 50; + --ipal-z-toast: 60; + --ipal-focus-width: 2px; + --ipal-focus-offset: 2px; + color-scheme: light; +} + +:root[data-theme="dark"] { + --ipal-bg: oklch(0.145 0 0); + --ipal-surface: oklch(0.205 0 0); + --ipal-surface-muted: oklch(0.18 0 0); + --ipal-surface-raised: oklch(0.235 0 0); + --ipal-surface-inverse: oklch(0.97 0 0); + --ipal-text: oklch(0.87 0 0); + --ipal-text-strong: oklch(0.97 0 0); + --ipal-text-muted: oklch(0.708 0 0); + --ipal-text-inverse: oklch(0.205 0 0); + --ipal-border: oklch(0.269 0 0); + --ipal-border-strong: oklch(0.371 0 0); + --ipal-primary: oklch(0.546 0.245 262.881); + --ipal-primary-hover: color-mix(in oklch, var(--ipal-primary), black 12%); + --ipal-primary-text: oklch(1 0 0); + --ipal-secondary: var(--ipal-text-strong); + --ipal-secondary-hover: color-mix(in oklch, var(--ipal-secondary), black 12%); + --ipal-secondary-text: var(--ipal-text-inverse); + --ipal-accent: var(--ipal-primary); + --ipal-accent-text: var(--ipal-primary-text); + --ipal-link: color-mix(in oklch, var(--ipal-primary), white 40%); + --ipal-link-hover: color-mix(in oklch, var(--ipal-link), var(--ipal-text-strong) 30%); + --ipal-link-inverse: var(--ipal-text-inverse); + --ipal-hover: oklch(0.269 0 0); + --ipal-focus: var(--ipal-link); + --ipal-focus-inverse: var(--ipal-text-inverse); + --ipal-overlay: oklch(0 0 0 / 0.65); + --ipal-success: oklch(0.792 0.209 151.711); + --ipal-success-surface: oklch(0.266 0.065 152.934); + --ipal-warning: oklch(0.828 0.189 84.429); + --ipal-warning-surface: oklch(0.279 0.077 45.635); + --ipal-danger: oklch(0.704 0.191 22.216); + --ipal-danger-surface: oklch(0.258 0.092 26.042); + --ipal-info: oklch(0.707 0.165 254.624); + --ipal-info-surface: oklch(0.282 0.091 267.935); + --ipal-shadow-sm: 0 1px 2px 0 oklch(0 0 0 / 0.4), 0 0 0 1px oklch(1 0 0 / 0.04); + --ipal-shadow-md: 0 4px 8px -2px oklch(0 0 0 / 0.5), 0 0 0 1px oklch(1 0 0 / 0.05); + --ipal-shadow-lg: 0 16px 32px -8px oklch(0 0 0 / 0.6), 0 0 0 1px oklch(1 0 0 / 0.06); + --ipal-surface-dark: var(--ipal-surface); + --ipal-border-dark: var(--ipal-border); + --ipal-text-dark: var(--ipal-text); + --ipal-text-strong-dark: var(--ipal-text-strong); + --ipal-text-muted-dark: var(--ipal-text-muted); + --ipal-primary-dark: var(--ipal-primary); + --ipal-primary-hover-dark: var(--ipal-primary-hover); + --ipal-primary-text-dark: var(--ipal-primary-text); + --ipal-hover-dark: var(--ipal-hover); + color-scheme: dark; +} + +/* Inverted section (settings.background = inverted): content inside reads the inverse roles. */ + +[data-surface="inverse"] { + --ipal-text: var(--ipal-text-inverse); + --ipal-text-strong: var(--ipal-text-inverse); + --ipal-text-muted: color-mix(in oklch, var(--ipal-text-inverse) 72%, var(--ipal-surface-inverse)); + --ipal-border: color-mix(in oklch, var(--ipal-text-inverse) 18%, var(--ipal-surface-inverse)); + --ipal-border-strong: color-mix(in oklch, var(--ipal-text-inverse) 30%, var(--ipal-surface-inverse)); + --ipal-surface: color-mix(in oklch, var(--ipal-text-inverse) 8%, var(--ipal-surface-inverse)); + --ipal-hover: color-mix(in oklch, var(--ipal-text-inverse) 12%, var(--ipal-surface-inverse)); + --ipal-link: var(--ipal-link-inverse); + --ipal-focus: var(--ipal-focus-inverse); + --ipal-link-hover: var(--ipal-link-inverse); + color-scheme: dark; +} + +:root[data-theme="dark"] [data-surface="inverse"] { + color-scheme: light; +} + +/* No motion for people who asked for none (the a11y widget's "no animations" too). */ + +@media (prefers-reduced-motion: reduce) { + html:root { + --ipal-duration-fast: 0ms; + --ipal-duration: 0ms; + --ipal-duration-slow: 0ms; + } +} + +html[data-a11y-motion="reduce"] { + --ipal-duration-fast: 0ms; + --ipal-duration: 0ms; + --ipal-duration-slow: 0ms; +} From ca8e93eaf4c48a3e44ac531277c2fa33987d6672 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 29 Oct 2026 13:55:59 +0100 Subject: [PATCH 6/8] Design tokens: ipal-tokens CLI, components on single names, templates, tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- bin/ipal-tokens.mjs | 13 ++ .../skills/ipal-setup/resources/DESIGN.md | 48 +++++ .../skills/ipal-setup/resources/tokens.ts | 27 +++ docs/lightbox.md | 3 +- package.json | 3 +- src/modules/consent/CookieBanner.tsx | 29 +-- src/modules/consent/CookieButton.tsx | 11 +- src/modules/lightbox/LightboxDialog.tsx | 2 +- src/modules/tokens/cli.ts | 91 +++++++++ src/modules/tokens/css.ts | 2 +- test/designTokens.test.ts | 185 ++++++++++++++++++ 11 files changed, 391 insertions(+), 23 deletions(-) create mode 100755 bin/ipal-tokens.mjs create mode 100644 docs/agent/skills/ipal-setup/resources/DESIGN.md create mode 100644 docs/agent/skills/ipal-setup/resources/tokens.ts create mode 100644 src/modules/tokens/cli.ts create mode 100644 test/designTokens.test.ts diff --git a/bin/ipal-tokens.mjs b/bin/ipal-tokens.mjs new file mode 100755 index 0000000..02b7945 --- /dev/null +++ b/bin/ipal-tokens.mjs @@ -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))) diff --git a/docs/agent/skills/ipal-setup/resources/DESIGN.md b/docs/agent/skills/ipal-setup/resources/DESIGN.md new file mode 100644 index 0000000..9e48864 --- /dev/null +++ b/docs/agent/skills/ipal-setup/resources/DESIGN.md @@ -0,0 +1,48 @@ +# DESIGN.md — + +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 +. 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): +``` + +``` + +## 3. Type +Body: (`--font-family-body`). Headings: (`--font-family-heading`). +Max 2 families × 2–3 weights, `subsets: ['latin', 'latin-ext']`. Scale overrides (`fs`): . +Heading style: . + +## 4. Shape and depth +Radius: control <…>, card <…>, media <…>. Depth: . + +## 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: . + +## 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, . + +## 8. Theme +, default (Site settings → Theme), toggle . + +## 9. Deviations from the standard +Every override of a default, and every project-only token or breakpoint, with the reason: +- diff --git a/docs/agent/skills/ipal-setup/resources/tokens.ts b/docs/agent/skills/ipal-setup/resources/tokens.ts new file mode 100644 index 0000000..91c7aac --- /dev/null +++ b/docs/agent/skills/ipal-setup/resources/tokens.ts @@ -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 + 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' }, +}) diff --git a/docs/lightbox.md b/docs/lightbox.md index 8d12a11..2b9de6e 100644 --- a/docs/lightbox.md +++ b/docs/lightbox.md @@ -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); } diff --git a/package.json b/package.json index 8e5004b..0de639d 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/modules/consent/CookieBanner.tsx b/src/modules/consent/CookieBanner.tsx index 2d25362..a63f31d 100644 --- a/src/modules/consent/CookieBanner.tsx +++ b/src/modules/consent/CookieBanner.tsx @@ -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 = { @@ -128,7 +131,7 @@ const defaults: Required = { 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 = { 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}`, diff --git a/src/modules/consent/CookieButton.tsx b/src/modules/consent/CookieButton.tsx index 9167daa..8d173cb 100644 --- a/src/modules/consent/CookieButton.tsx +++ b/src/modules/consent/CookieButton.tsx @@ -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 ( ) diff --git a/src/modules/lightbox/LightboxDialog.tsx b/src/modules/lightbox/LightboxDialog.tsx index e4bf8bb..c1320b8 100644 --- a/src/modules/lightbox/LightboxDialog.tsx +++ b/src/modules/lightbox/LightboxDialog.tsx @@ -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)) diff --git a/src/modules/tokens/cli.ts b/src/modules/tokens/cli.ts new file mode 100644 index 0000000..491f231 --- /dev/null +++ b/src/modules/tokens/cli.ts @@ -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 { + 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 { + 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 + } +} diff --git a/src/modules/tokens/css.ts b/src/modules/tokens/css.ts index 52a3838..734cf1d 100644 --- a/src/modules/tokens/css.ts +++ b/src/modules/tokens/css.ts @@ -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] diff --git a/test/designTokens.test.ts b/test/designTokens.test.ts new file mode 100644 index 0000000..ad3d428 --- /dev/null +++ b/test/designTokens.test.ts @@ -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"/) + }) +}) From cf205c59efc5669f85f59ee09eb0f7015ba5e59c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 29 Oct 2026 14:00:31 +0100 Subject: [PATCH 7/8] Design tokens: docs, agent guide, skills, audit checks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - docs/design-tokens.md (new module page), README index, CHANGELOG - AGENT.md §0b row 19, §6.11 rewritten for the standard, §6.11a, §7, §10, §12, §14 - ipal-setup stage 5, ipal-block section-code (Section with data-surface, Button, card on token utilities), ipal-site phase 8, ipal-reference (+ api.md /tokens section), ipal-upgrade 1.15.0 note, ipal-audit SKILL + audit.sh token checks - theme.md, consent.md, accessibility.md (a11y.css), lightbox.md, PROGRAMISTA §2.5 - /tokens entry lists its exports explicitly; docs coverage test includes it Co-Authored-By: Claude Opus 5.5 --- docs/CHANGELOG.md | 18 ++ docs/README.md | 1 + docs/accessibility.md | 10 +- docs/agent/AGENT.md | 46 +++-- docs/agent/skills/ipal-audit/SKILL.md | 6 + docs/agent/skills/ipal-audit/scripts/audit.sh | 29 +++ docs/agent/skills/ipal-block/SKILL.md | 4 +- .../ipal-block/resources/section-code.md | 64 +++--- docs/agent/skills/ipal-reference/SKILL.md | 3 +- .../skills/ipal-reference/resources/api.md | 26 ++- docs/agent/skills/ipal-setup/SKILL.md | 39 ++-- docs/agent/skills/ipal-site/SKILL.md | 6 +- docs/agent/skills/ipal-upgrade/SKILL.md | 7 + docs/consent.md | 11 +- docs/design-tokens.md | 186 ++++++++++++++++++ docs/dev/PROGRAMISTA.md | 5 + docs/theme.md | 6 +- src/exports/tokens.ts | 24 ++- test/docsConsistency.test.ts | 1 + 19 files changed, 415 insertions(+), 77 deletions(-) create mode 100644 docs/design-tokens.md diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index ef7af35..97027c4 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -13,6 +13,15 @@ once there are more than 20. Database names follow one rule, and seeding a live site touches only the records you name. ### New +- **Design-token standard** ([design-tokens.md](./design-tokens.md)): one set of `--ipal-*` names for every site, + only the values differ per brand. `@intecion/ipal-kit/tokens.css` (neutral defaults, light/dark on `data-theme`, + `[data-surface="inverse"]` scope, reduced motion), `@intecion/ipal-kit/tailwind.css` (Tailwind 4 preset: `bg-surface`, + `text-fg`, `text-on-primary`, `py-section`, `rounded-card`, `duration-fast`…), `@intecion/ipal-kit/a11y.css` (the + accessibility widget's CSS through the tokens). New entry `@intecion/ipal-kit/tokens` (`defineTokens`, `tokensToCss`, + `contrastReport`, `fluidClamp`, `IPAL_TOKENS`, `ipalVar`, `IPAL_BREAKPOINTS` …; the first four names also from the root). + New bin `ipal-tokens`: `src/design/tokens.ts` → `src/design/tokens.css` + WCAG contrast check (`--check` for CI). + Templates `DESIGN.md` and `tokens.ts` in `ipal-setup/resources`. `ipal-audit` checks the standard. +- `fluid.css` / `fluid-wide.css`: `--ipal-fs-xs`, `--ipal-fs-h4`, `--ipal-space-stack`, `--ipal-space-section-sm`. - **Database name rule:** `_prod` / `_dev` (e.g. `acmepl_prod`), docs/deployment.md. `ipalEnvRules({ databaseName: true })` (domain from `NEXT_PUBLIC_SERVER_URL`, skipped on localhost) or `{ databaseName: { domain, warn } }` checks `DATABASE_URI` and **warns only** — never fails startup. Default off. @@ -22,6 +31,12 @@ Database names follow one rule, and seeding a live site touches only the records `skip (not listed)`. The seed templates (`ipal-site`, `ipal-form`) read it. ### Changed +- **Cookie banner / button colours** read the single token names (`--ipal-surface`, `--ipal-text` …) instead of + `dark:` + `--ipal-*-dark`. With `tokens.css` they switch with the theme. Without it, the built-in fallback follows the + page's `color-scheme` (`light-dark()`): a site without a dark theme no longer gets a dark banner on a dark-mode + device. A `-dark` variable a site still sets is used as the dark fallback. The secondary button's dark fallback text + is `#d4d4d4` (was `#e5e5e5`). +- Lightbox fade: `--ipal-lightbox-duration` defaults to `var(--ipal-duration, 200ms)`; new `--ipal-lightbox-easing`. - **A full seed of a live database is refused:** a run without `only` / `SEED_ONLY` against `NODE_ENV=production` or a non-local database now throws (with the steps to follow). Dry runs (`SEED_DRY_RUN=1`) are never refused. Allow it only with the owner's explicit OK: `IPAL_SEED_ALLOW_FULL=1` or `guard: { allowFull: true }`; `guard: false` turns @@ -34,6 +49,9 @@ Database names follow one rule, and seeding a live site touches only the records 2. Optional: name the databases `_prod` / `_dev` and add `ipalEnvRules({ databaseName: true })` to see a warning when `DATABASE_URI` points elsewhere. Existing databases need not be renamed. 3. Seed scripts copied from older templates: take the new `SEED_ONLY` handling from `ipal-site` / `ipal-form`. +4. Optional: adopt the design-token standard (design-tokens.md → "Migrating an existing site"; **ipal-upgrade**). A + site that styles the cookie banner only through `--ipal-*-dark` for its dark theme and does not adopt `tokens.css`: + check the banner in the dark theme (the dark fallback now needs `color-scheme: dark`, which `` sets). ## 1.14.6 diff --git a/docs/README.md b/docs/README.md index bf4a847..92ac451 100644 --- a/docs/README.md +++ b/docs/README.md @@ -50,6 +50,7 @@ API details — one file per module: | Stats in the admin panel (no cookies; visitor history with consent) | [stats.md](./stats.md) | | Auto-slug | [slug.md](./slug.md) | | Light / dark theme, switcher | [theme.md](./theme.md) | +| Design tokens (`--ipal-*`, `tokens.css`, `tailwind.css`, `ipal-tokens`, DESIGN.md) | [design-tokens.md](./design-tokens.md) | | R2, `buildImagesConfig`, `MediaPreconnect`, `YouTubeEmbed` | [storage.md](./storage.md) | | Turnstile | [turnstile.md](./turnstile.md) | | Admin panel white-label | [white-label.md](./white-label.md) | diff --git a/docs/accessibility.md b/docs/accessibility.md index 27d8c1e..138ffc8 100644 --- a/docs/accessibility.md +++ b/docs/accessibility.md @@ -75,8 +75,14 @@ the plugin only needs `A11yTexts` for the current locale. ## 2. CSS that reacts to the attributes (MANDATORY — project) -The widget sets attributes on ``. Without this CSS nothing happens. Copy it -into the project's global CSS (adapt it to the design): +The widget sets attributes on ``. Without CSS for them nothing happens. + +**Ready file (1.15.0):** `@import "@intecion/ipal-kit/a11y.css";` in `styles.css` — the rules below, working through +the design tokens ([design-tokens.md](./design-tokens.md)): the readable font swaps `--ipal-font-body/-heading` (set +`--ipal-font-readable` to change it), "no animations" zeroes the `--ipal-duration-*` tokens, contrast + grayscale +combine, the big cursor is built in. Check: tick each option in the widget and see the page change. + +Or copy this into the project's global CSS (adapt it to the design): ```css /* Text size */ diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index d8304a6..145af36 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -183,6 +183,7 @@ site), **P** = a test in the panel. Full code: PROGRAMISTA.md §2. | 16 | **Nothing hardcoded** | every text, link, image, file, company data from the panel; domains and keys from `.env` (§2) | — | A, P | | 17 | **Content** | one h1, the answer at the start of each section, facts, internal links, FAQ from real questions, `aiSummary`, sameAs, consistent company data (§0c) | — | S, P | | 18 | **Scaling** | `fluid.css` / `fluid-wide.css`, hero on `--ipal-hero-min-h`, the screen list in §6.11a (including 1366×768) | — | A, browser | +| 19 | **Design tokens** | `DESIGN.md` + `src/design/tokens.ts` → `pnpm exec ipal-tokens` → `src/design/tokens.css`; `styles.css` imports `fluid-wide.css`, `tokens.css`, `tailwind.css`, the brand file (§6.11); fonts in `--font-family-body` / `--font-family-heading` | `defineTokens`, `ipal-tokens` | A (`ipal-tokens --check`), browser (both themes) | **Turnstile works by itself:** both keys in the panel (or env) → the widget shows, and `submitForm` **requires** a token; no keys → no widget, the form works. @@ -866,25 +867,37 @@ upload + ``; **a fixed set of UI icons** → a `select` field with names a `lucide-react` map in `src/components/icons/` (names in a separate file, so the block config does not import React). Code: [section-code.md](./skills/ipal-block/resources/section-code.md). **Never** SVG pasted into a section's JSX. -### 6.11 Styles +### 6.11 Styles — the design-token standard ([design-tokens.md](../design-tokens.md)) -- Tailwind in components; colors and fonts as **tokens** in `styles.css` (`@theme`) - from the `DESIGN.md` source. In components only tokens (`bg-primary`), **never** - `bg-[#ff6600]` or hex. -- Map the plugin's tokens to the project: `--ipal-primary: var(--color-primary)`. -- Fluid typography and spacing: `@import "@intecion/ipal-kit/fluid.css"` + mapping in - `@theme` (`text-h1`, `py-section`, `px-gutter` — PROGRAMISTA §2.5). Do not write `clamp()` - in components; other values from `DESIGN.md` → override the `--ipal-*` variables in `:root`. +Every site uses the same `--ipal-*` token names and Tailwind utilities; only the values differ per brand. +- **The brand lives in two files:** `DESIGN.md` (human, template `ipal-setup/resources/DESIGN.md`) and + `src/design/tokens.ts` (`defineTokens` from `@intecion/ipal-kit/tokens`, template `ipal-setup/resources/tokens.ts`). + `pnpm exec ipal-tokens` writes `src/design/tokens.css` (commit it) and fails on a WCAG AA contrast error. + Never edit the generated file; never put brand values in `styles.css` or in a component. +- **`styles.css` is the same on every site:** `@import "tailwindcss"`, `@intecion/ipal-kit/fluid-wide.css` (or + `fluid.css`), `@intecion/ipal-kit/tokens.css`, `@intecion/ipal-kit/tailwind.css`, `../../design/tokens.css` (last), `@source` of the plugin's dist. +- **Components use only the utilities from the preset:** `bg-bg`, `bg-surface`, `bg-surface-muted`, `bg-inverse`, + `text-fg`, `text-fg-strong`, `text-fg-muted`, `text-on-primary`, `border-border`, `bg-primary hover:bg-primary-hover`, + `text-link`, `outline-focus`, `text-h1`…`text-display`, `py-section`, `px-gutter`, `gap-gap`, `rounded-control`, + `rounded-card`, `shadow-sm`, `max-w-container`, `duration-fast ease-out`. **Never** hex, `bg-[#…]`, `var(--color-…)`, + or `dark:` for colours (the roles switch with `data-theme` themselves). `dark:` only for non-colour differences. +- **Inverted section:** `

` with `settings.background = inverted` → `bg-inverse` + `data-surface="inverse"`; + content inside keeps `text-fg` / `text-link` (the scope re-maps them). +- Fonts via `next/font` with `variable: '--font-family-body'` / `'--font-family-heading'` on `` (not + `--font-body`: a `var()` cycle with the `font-body` utility). Max 2 families. +- Values a CSS variable can't reach (`next/og`, e-mail, `theme-color`): `resolveColors(tokens)` from `@/design/tokens`. + In inline styles / charts: `IPAL_TOKENS.primary` or `ipalVar('primary')`; breakpoints in JS: `IPAL_BREAKPOINTS`. +- A missing role every site would need → **ipal-plugin-gap**; a project-only decorative colour → `styles.css` below the + imports + `DESIGN.md` → Deviations. - JSON-LD only via `` from `/rsc` — never your own `