# Theming

The whole palette is generated by [Glaze](https://github.com/tenphi/glaze) from a handful of seeds, one per **zone**: the accent, the base, and each of the four status themes. Those seeds are tunable at runtime — change one and every token re-resolves, in light, dark, and high-contrast schemes at once.

Every zone takes the same seed, and it comes in two forms: a **color**, which is usually what you actually have, or the **numbers** behind one. Never both — a zone is seeded one way or the other. See [One seed, two ways to spell it](#one-seed-two-ways-to-spell-it).

```ts
import { setPaletteConfig } from '@cube-dev/ui-kit';

setPaletteConfig({
  accent: '#2F5BFF',
  themes: { danger: '#b91c1c' },
});

// The same shape, said in numbers.
setPaletteConfig({
  accent: { hue: 210, saturation: 72 },
  themes: { danger: { hue: 12 } },
});
```

With no configuration set, the palette is exactly the one the kit ships — the defaults below are the shipped seeds, and a snapshot test pins every resolved value so this stays true.

## What is tunable

Every zone below takes a `PaletteSeed`: either a color string, or `{ hue?, saturation? }`.

| Option | Scope | Default |
| --- | --- | --- |
| `accent` | The **accent** zone — the brand. Drives the `accent-*` family on every theme, `primary` / `purple` / `special`, and the brand-tinted `focus`, loading faces and disabled chip. | `{ hue: 280.3 }` |
| `accent` as a color | Contributes hue, chroma **and tone**, so the brand fill renders as the color you passed. Its chroma reaches the accent family through Glaze's `from`, not through the zone's seed. | unset |
| `accent.saturation` | Seed saturation (0–100) for the `default` theme, and the fallback every status theme inherits. Setting it **turns `pastel` off**, which is the path it belongs to. | `100` |
| `base` | The **base** zone — the neutral chrome: `surface` and its ladder, the `surface-text*` ramp, `border`, `placeholder`. Omit it and the zone follows the accent. | follows `accent` |
| `base` as a color | Contributes hue **and saturation**, clipped to 50; its tone is discarded. | unset |
| `base.saturation` | Seed saturation (0–100) of the base zone, on the same scale as the accent's. The shipped chrome is `12`. | `(accent's chroma) × 0.12` |
| `themes.<status>` | Seed for `success` / `danger` / `warning` / `note`. | `156.9` / `23.1` / `84.3` / `302.3` |
| `themes.<status>` as a color | All three components, and its chroma **does** become the theme's seed — unlike the accent's. See [Status themes](#status-themes). | unset |
| `themes.code.saturation` | Saturation for the `code-*` syntax family. Hues are fixed, it takes no color, and it does **not** inherit the accent's saturation nor track its default. | `80` |
| `surfaceMode` | Global. `'tinted'` moves the neutral surface ramp two tones off the end of the tone scale, which is what gives the base saturation room to reach the page surface. | `'neutral'` |
| `pastel` | Global. Relaxes the sRGB-safe chroma limit, and **pins the accent's saturation to 100**. Wins wherever both are set. Every theme except `code`. | `true` |
| `contrastLevel` | Global. `'auto'`, or a manual `0`–`100` level. | `'auto'` |

### The setter replaces

`setPaletteConfig()` works like `useState`, not like `glaze.configure()`: the config you pass **is** the config, resolved against the shipped defaults. Nothing accumulates, so removing a customization means removing it from the object:

```ts
setPaletteConfig({ accent: { hue: 200 }, base: { hue: 60 } });
setPaletteConfig({ accent: { hue: 200 } }); // `base` is gone — follows accent again
```

That is what makes the config safe to keep in your own state and re-apply: the same object twice does the same thing as once, and `<Root palette>` can un-set a field by no longer passing it.

To change one field of the config already in place — a slider in a settings UI — pass an updater. It receives the config **as written**, sparse, so spreading it preserves which fields are pinned and which still inherit:

```ts
// A zone holds ONE seed, so a one-field control spreads that seed too — writing a bare
// `{ hue }` would unpin the saturation beside it.
setPaletteConfig((config) => ({
  ...config,
  accent: { ...config.accent, saturation: 55 },
}));

// Nested seeds need their own spread as well, or the other themes go with them.
setPaletteConfig((config) => ({
  ...config,
  themes: { ...config.themes, warning: { saturation: 95 } },
}));
```

`resetPaletteConfig()` drops all tuning at once — the same as `setPaletteConfig({})`, just easier to read at a call site.

### One seed, two ways to spell it

Every zone takes the same `PaletteSeed`, and it comes in two forms:

```ts
type PaletteSeed = string | { hue?: number; saturation?: number };
```

A string is a color — anything Glaze parses: hex, `rgb()`, `hsl()`, `okhsl()`, `okhst()`, `oklch()`. CSS color keywords (`rebeccapurple`) are not supported; an unparseable value warns once and falls back to the numeric path.

**The union is the exclusivity.** A zone is seeded one way or the other — there is no precedence rule to learn, and no way to write a hue that half-overrides a hex. A patch that switches form therefore _replaces_ rather than merges; layering happens within a path:

```ts
setPaletteConfig({ accent: '#2F5BFF' });
// A number arriving next to that takes the zone over, tone and all.
setPaletteConfig((config) => ({ ...config, accent: { hue: 300 } }));
```

#### The zones

- **Accent** (`accent`) — the `accent-*` family on every theme, `primary` / `purple` / `special`, plus `focus`, the loading faces and the disabled chip. Its saturation is also the fallback every status theme inherits.
- **Base** (`base`) — the neutral chrome: `surface` and its ladder, the `surface-text*` ramp, `border`, `placeholder`.
- **Status** (`themes.success` / `danger` / `warning` / `note`) — one seed each. See [Status themes](#status-themes).
- **Syntax** (`themes.code`) — the exception: a saturation and nothing else. See [The `code-*` family is the exception](#the-code--family-is-the-exception).

Omit `base` and the chrome follows the accent, so out of the box the greys carry a faint tint of the brand. Seed it to decouple them — a warm grey UI under a cool blue brand:

```ts
setPaletteConfig({ accent: { hue: 235 }, base: { hue: 60 } });
```

Only the `default` theme is affected. A colored theme's tinted `surface` deliberately follows _its own_ hue, because a danger banner should read as red.

#### What a color contributes, per zone

The same string means slightly different things by zone, and the differences are the point:

```ts
setPaletteConfig({ accent: '#2F5BFF', base: '#7A7269' });
```

- **Accent** — hue, chroma **and tone**. The tone is what makes the brand fill actually _be_ your color. Without it the fill is authored as a fixed tone step off white, so every accent hue lands at roughly the same lightness — a yellow brand comes out olive. The chroma reaches the accent family through Glaze's `from` rather than through the zone's seed, which is what stops a brand from re-chromatising the chrome and all four status themes.
- **Base** — hue and saturation; the **tone is discarded**, because the chrome's own lightness ladder is the design. A base color says which way the greys lean and how far, not how dark they are.
- **Status** — hue, chroma and tone, and its chroma **does** become that theme's seed. Nothing inherits from a status theme, so there is nothing to re-chromatise, and moving the seed is what keeps the banner in proportion to the button.

The base color's saturation is **clipped to 50**. Naming a base color says "the chrome _is_ this color", so it lands near it rather than at the 12% share it would otherwise inherit — but a fully saturated chrome stops being chrome, and the base colors begin to converge above 25 anyway (see [Tinted surfaces](#tinted-surfaces)). The tuner's manual slider shares the same ceiling, so the two routes agree on what the top of the range means. A base **number** is not clipped: a number is the more specific instruction.

```ts
setPaletteConfig({ base: '#6e7076' }); // near-grey in, near-grey chrome out
setPaletteConfig({ base: '#FFD400' }); // saturation 100 in, clipped to 50
setPaletteConfig({ base: { saturation: 100 }, pastel: false }); // 100 stays 100
```

### A color seed is a request

The palette renders the color you asked for, and moves it only as far as it has to. Two things can make it move.

First, **exactness is scoped to the light, normal-contrast variant.** That is the one that reproduces your color. Dark and high contrast adapt, as every other color in the palette does — they are different pages, and a brand pinned across all four would be less faithful, not more. What holds everywhere is the floor below.

**The fill answers to two constraints, and they are different sizes.** The `#white` label it carries needs **APCA Lc 45** — text strength, because it is text. The page it sits on needs only **Lc 25**, because a solid fill is a shape, not text, and Lc 25 is what the palette's own shipped fill achieves against a dark page. Both are floors rather than targets: a brand already past them is emitted exactly as given, and one that misses moves only as far as the nearer requires.

Sizing those two the same is a mistake worth naming, because this palette made it. In light `surface` **is** white, so one measurement is both constraints at once and Lc 45 looks right for the pair. In dark the page is near-black and the same number becomes a demand that a filled shape reach text contrast against it — which nothing in the palette meets, the shipped fill included. Since a floor can only lighten, the surplus flattened the dark half of the tone axis onto a single value: every brand darker than the floor came out the same colour. The page floor is now sized for a shape and the label is guaranteed separately, by a cap on the seed's tone.

They are APCA rather than WCAG on purpose. A single WCAG ratio means two different things depending on the scheme: measured across twelve hues, a fill sitting exactly at 3:1 comes out at Lc 56 in light but only Lc 23 in dark. That is why light brands kept getting crushed while dark ones sailed through the same rule. **A consequence to state plainly: the emitted fill can sit below WCAG 3:1.** `#0EA5E9` renders at 2.77:1 against a white page and is correct there — the Lc is the guarantee, not the ratio.

**The brand text keeps the brand's tone too, and so it can sit below WCAG AA.** Links (`#accent-text-soft` at rest, `#accent-text` on hover) and the selected labels of `outline`, `outline-2` and `clear` items solve against **APCA Lc 60** at rest and **Lc 75** on hover. Those floors are low on purpose: a customer who seeds the palette with a brand color expects to see that color in its links, and a higher floor would darken a light brand's link away from it. The cost is the ratio. In light mode at normal contrast, a bright brand's links measure about 4.0–4.4:1 on white and its selected labels about 3.4–4.4:1 on their fills, below the 4.5:1 of WCAG AA. Hover, keyboard focus, dark and both high-contrast variants measure above 4.5:1. The palette with no color seed solves the same text against a WCAG floor and meets AA everywhere. When AA matters more than the exact tone, seed a darker shade of the brand. The selected labels sit on fills darker than white, so the seed needs about 6:1 on white rather than 4.5:1: `#4f46e5` (6.3:1) passes everywhere, while `#0b6bcb` (5.3:1) still leaves its `outline` and `outline-2` labels at 4.4:1 and 4.1:1.

High contrast does **not** escalate the page floor. It is a request for separation over brand, but not for separation from the page: the same fill carries the label, and driving it off the page drives the label off it. The shipped ladder makes the same trade and lands the other side of it, ending up with _less_ page separation in high contrast than in normal, because it darkens the fill toward its label. What does escalate is the label cap, which searches the high-contrast variants too.

**`pastel` caps chroma.** The flat, hue-independent ceiling is what makes pastel even across hues, and it sits below where a saturated color would land, so under it a color seed can never resolve to itself: `#EF4444` renders `#c47069`. Under pastel the color contributes its hue and its tone; turn pastel off to get its chroma too.

All of it applies per zone. A status color answers to the same two constraints on its own `#<theme>-accent-surface`, including the label cap — every `type="primary"` item on a status theme paints `#white` on that fill too, so a pale `danger` color is pulled down rather than shipped as a white label on white.

Read the result back from the tokens themselves — `#accent-surface` is the fill, `#accent-text-soft` the rest link color — or watch the requested/resolved chips in the [Theme builder](#theme-builder).

### One saturation scale per theme

Saturation is _not_ split per token, deliberately: a zone's `saturation` is its theme's **seed**, and every color's own `saturation` is a 0–1 factor of it. `surface` sits at `0.12`, `border` at `0.175`, the text ramp at `0.2`, the accent family at ~`1.0`.

So a theme has one saturation _scale_, and everything on it keeps its proportions: turning the seed down mutes the brand fills and the neutral tint together, in the ratios the palette was designed around. That is the point — the relationship between a subtle surface tint and a saturated accent is part of the design, not something to tune per token. It is also why a status **color** takes over its theme's seed rather than reaching only its fill: chroma arriving absolutely through `from` while the seed stayed put is exactly how those ratios come apart.

The one seam is the **base zone**, and it is the same seam its own hue opens: the chrome is the one family whose job is _not_ to look like the brand. `base.saturation` gives it its own seed, on the same 0–100 scale, so a vivid accent over near-grey chrome — or a muted accent over visibly warm chrome — is one number rather than a choice between them:

```ts
setPaletteConfig({ accent: { saturation: 90 }, base: { saturation: 3 } });
```

Unset, it takes `0.12` — `surface`'s own factor — of whatever the accent zone carries: its seed saturation, or an accent color's own chroma when one is set. So leaving it alone reproduces the shipped palette exactly, a muted accent still mutes the chrome along with everything else, and a near-grey brand hex leaves near-grey chrome rather than 12% of a saturation nobody asked for. A base color overrides all of that with its own, clipped to 50.

**The shipped value is `12`** — a faint tint is what a neutral surface _is_ — so the interesting range is the low end. The base colors keep their proportions to one another until the highest of them (`0.475`, `surface-inverse`) hits the top of the scale, around `25`; past that they converge.

Note the asymmetry with the accent's saturation: writing the base's does **not** turn `pastel` off. How much hue the chrome carries says nothing about which chroma space the palette is in.

### Tinted surfaces

A neutral `surface` sits at the extreme of the tone scale — pure white in light, the darkest step the dark tone window allows in dark. Chroma needs distance from the extreme to exist at all, so on a light page `surface` is white whatever the base saturation asks for. The base seed reaches `surface-2`…`surface-4`, `border`, `placeholder` and the text ramp, and stops at the page itself.

`surfaceMode: 'tinted'` moves the whole ramp two tones inward:

```ts
setPaletteConfig({ surfaceMode: 'tinted', base: { saturation: 25 } });
```

Two tones is not a lightness change you would name — it is _room_. Everything below `surface` is positioned relative to it, so the ladder, the borders and the text ramp all follow, and the text's `['AA','AAA']` floors re-solve against the new background rather than drifting. The `code-*` family follows too: its mirrored `surface` exists to be the page, so it tracks both the tone and the base seed.

**The tinted surfaces move with it.** A status theme's `surface` — and a runtime tint's, from `getColorTheme()` — is authored as an offset from the page's rather than as an absolute tone, and that offset is exactly the two tones `tinted` shifts by. Anchored absolutely they would land on the page's own new tone and a `note` banner would stop reading as a banner at all; anchored to the page they keep the separation the offset was chosen for, in both schemes. They also pick up a little more chroma there, being further from the extreme — so `tinted` makes a status surface easier to see, not harder.

The tint stays subtle by construction. Near white the sRGB gamut has very little chroma to give, so `tinted` buys a surface that reads as warm or cool rather than one that reads as colored — which is the whole ask. For a genuinely colored panel, reach for a status theme's `surface` instead.

All of which describes the `pastel: false` path. Under `pastel` there is still one seed and it is pinned to `100`, because a flat chroma ceiling is the whole mechanism and a second scale on top of it would only undo the evenness. So there are two paths:

```ts
setPaletteConfig({ pastel: true }); // even across hues; saturation is 100, full stop
setPaletteConfig({ accent: { saturation: 65 } }); // your scale, per-hue ceiling
```

Note the second line does not mention `pastel`. **Setting the accent's `saturation` turns pastel off**, because tuning a saturation is the non-pastel path by definition — so you pick a path by asking for what you want from it, not by setting a flag first. A _color_ does not answer that question and does not turn pastel off: `accent: '#FFD400'` on its own still resolves under the flat ceiling, contributing its hue and tone but not its chroma.

State `pastel` only to override that. It is the coarser of the two choices — a color space rather than a value on one — so it wins wherever both are set, and a saturation it shadows is ignored with a dev-mode warning. The number is **kept** rather than dropped, though: it stays in the sparse config, so turning pastel back off restores it.

### The `code-*` family is the exception

Syntax colors are their own theme with their own seed, so neither the brand hue nor the palette saturation reaches them. Hues are absolute literals — a brand re-seeded toward green would otherwise collide `code-string` with `code-number` (156°) — and the saturation is fixed at `80` rather than inheriting, so muting the app cannot wash out a code block. That `80` is its own constant (`DEFAULT_CODE_SATURATION`), deliberately not the palette default it once shared a value with: the app seed moved to `100` with the pastel palette and the syntax colors stayed put, which is the whole point of them not inheriting. `pastel` skips them for the same reason: it lowers the chroma ceiling far enough to take `code-keyword` from ~0.19 to ~0.07, collapsing the spread that keeps the syntax hues apart.

So `themes.code.saturation` is the only thing that moves them. Tune it on its own:

```ts
setPaletteConfig({ themes: { code: { saturation: 60 } } });
```

They are still _adaptive_: each one is anchored to the real `surface` with an `['AA','AAA']` floor, so they re-solve for light, dark and high contrast. Only hue and saturation are pinned.

That separate seed is also a hard requirement, not a preference: a Glaze colour can never exceed its own theme seed, and four of these sit at factor `1.0`. Inside a default theme seeded below `80` they simply could not hold their chroma — which is also why the pinned seed is a floor to respect rather than a number to tidy up.

### Inherited vs pinned

Every zone's seed starts out **inheriting**: the base zone follows the accent until something seeds it, and a status theme's saturation tracks the accent's. Moving the accent hue therefore appears to move the base hue too — they are not linked, the base zone simply has no value of its own yet.

Writing a seed pins it; leaving it out of the config unpins it, so it inherits again:

```ts
setPaletteConfig({ base: { hue: 60 } }); // pin
setPaletteConfig((config) => ({ ...config, accent: { hue: 235 } })); // base stays at 60
setPaletteConfig({ accent: { hue: 235 } }); // base dropped — follows again → 235

// Same thing from inside an updater, when the rest of the config must survive.
setPaletteConfig(({ base, ...config }) => config);
```

A zone is therefore **three-state**, and one field answers all three: absent and it inherits, an object and it is pinned to numbers, a string and it is derived from a color. A settings UI reads the sparse config to know which of its own controls is in charge:

```ts
const input = getPaletteConfigInput();
const accentMode = typeof input.accent === 'string' ? 'color' : 'numbers';
const baseIsOwn = input.base !== undefined;
```

`base: {}` and no `base` at all resolve to the same colors, but they are not the same config — one has a seed of its own that pins nothing, the other has no seed. The two read back differently and both count as changes, because that distinction is exactly what a **Follow accent / Own** control is.

Swapping one form for the other counts as a change even when the numbers agree — an `accent: { hue: 45 }` replaced by a color that derives hue 45 resolves identically, but the UI still has to re-render to move its mode control. So does replacing one unparseable string with another, which is why the colors are compared by value rather than by presence.

An explicit `{ hue: undefined }` inside a seed is equivalent to omitting the field; neither is a value.

`getPaletteConfig()` resolves everything, which loses that distinction — it cannot tell you whether `100` was chosen or inherited, and it always reports flat numbers whichever way a zone was seeded. `getPaletteConfigInput()` returns the sparse config as set, which is what a settings UI needs to render an inherited value as inherited and offer a way back:

```ts
const seed = getPaletteConfigInput().base;
const pinnedHue = typeof seed === 'object' ? seed.hue : undefined;
```

Pinning a field to the value it already inherited resolves to the same colors but still counts as a change, so a UI reading the sparse config re-renders. Re-applying an _already pinned_ value is a true no-op and costs nothing.

## Palette playground

Drag the brand hue and watch the accent ramp, the neutral surfaces, the buttons, the borders and the shadows move together. Nothing re-renders: every color in the kit compiles to a CSS custom property, so re-seeding replaces a single rule on `body` and the browser repaints.

Two things worth noticing while you tune:

- The **neutral** surfaces carry saturation factors of 0.10–0.175, so they read as a faint tint of the brand hue. That is where the saturation seed is legible — the solid accents hide it.
- The **syntax** colors do not move at all — they are their own theme with their own seed, so neither the accent hue nor the saturation reaches them.

## Status themes

Each status theme is a Glaze `extend()` of the default theme with its own seed, so tuning one moves only its own `#<theme>-*` family.

That seed is a `PaletteSeed` like any other, so `danger` can be the red your product already ships rather than a hue you reverse-engineered from it:

```ts
setPaletteConfig({ themes: { danger: '#b91c1c', success: { hue: 150 } } });
```

A status color behaves like the brand's in the ways that matter — the light, normal-contrast fill reproduces it, dark and high contrast adapt, and the softened APCA floors apply instead of the white-anchored ladder's WCAG ones, including the cap that keeps the `#white` label on a `type="primary"` button readable.

**One thing is deliberately different: its chroma becomes the theme's seed.** An accent color's does not, because all four status themes inherit the accent's saturation and raising it would re-chromatise every one of them. Nothing inherits from a status theme, so there is nothing to protect — and moving the seed is what holds the rest of the theme in proportion to the fill. The tinted banner surface, the border and the text ramp are authored as factors of the seed (`0.2`, `0.3`, `0.25`), so with the seed left at `100` beside a muted fill the banner would read as fully tinted under a washed-out button. Moving it keeps the shipped `1.0 : 0.2 : 0.3 : 0.25` ratio exactly, and Alert's own fill and border (`0.6` each, the fill `0.4` in dark) follow the same way.

Two consequences worth stating. A vivid status color under a muted palette gives one vivid theme beside muted siblings — that is the point of naming a color. And under `pastel` the flat ceiling can hold the fill below the color's own chroma while the banner still sits at `0.2` of it, so the ratio drifts slightly; turn pastel off for an exact color, exactly as with the brand.

A muted seed _beside_ an accent color is not expressible, because the zone is seeded one way or the other: a color there leaves the inherited saturation at its default. Mute the status themes individually if you want that.

## Contrast level

By default contrast is a two-tier switch: normal colors plus a separate high-contrast set, selected by `<html data-contrast="high">` or a `prefers-contrast: more` preference.

A manual `contrastLevel` adds a 0–100 slider that positions the **normal** colors, for a product that wants to offer its own contrast control. Level `0` is the shipped palette and `100` is the high-contrast one, bit for bit, so the slider interpolates between exactly what the two tiers already ship.

The two **compose**; the slider does not replace the switch. The high-contrast tier stays the true high-contrast resolution at every level — identical to what `'auto'` emits — so `data-contrast="high"` and `prefers-contrast: more` keep working and escalate on top of wherever the slider has put the baseline.

The one exception is level `100`: there the normal colors already _are_ the high-contrast ones, so a second tier would only duplicate them and a single light/dark set is emitted.

Because level `0` reproduces `'auto'` exactly, tier included, shipping the slider and defaulting it off costs a consumer nothing.

## Theme builder

The `Theme Builder` story puts the whole config behind controls and renders the result into a single region, with one line drawn through the middle of the page: **the left column is the theme, the two switches over the preview are the viewing conditions.** Everything on the left writes to the palette config and would ship with the product; **Light / Dark** and **Normal / High contrast** write nothing at all — the same theme renders in all four combinations, and moving between them is how you check a theme rather than how you change one.

Those two switches start on whatever the surrounding page is already showing and keep following it until you press one, after which they are yours. There is no `Auto` option to press: `Auto` means "follow the OS" — a _preference_ — and the preview resolves to flat token values, which can only express one concrete variant. Following is the default behaviour rather than a third choice.

On the theme side, the panel is grouped by **what a knob reaches** rather than by what it is named after: **Global** for the ones that govern both zones — `pastel`, the accent saturation, `surfaceMode` and `contrastLevel` — then **Accent** and **Base** for the ones that do not. `surfaceMode` files under Global despite moving the _base_ surfaces, because the status themes' tinted surfaces follow it too, and so does the mirrored surface the syntax palette solves against.

Those headings are also why the field labels are bare. `Seeded by` and `Hue` appear in both zones, and the heading above them is what says which — repeating it in every label was two words of noise on every line of a narrow column.

The **contrast level** needs no on/off switch: level `0` and `'auto'` are output-identical, tier included, so the slider at rest _is_ the shipped palette.

Status themes are four chips on one line rather than eight sliders. Each chip is a `theme="current"` `Button` colored by its own theme with a [ColorSwatch](./components/fields/ColorSwatch.md) of its accent, so the group answers the question you actually have — do these four still read as four different things — at a glance; press one to open its hue and saturation. The hue is not printed on the chip: it belongs to the slider that sets it, and carrying it there cost the whole row, since `success — 157°` is wide enough that four of them have to stack.

**Reset**, **Export** and **JSON** sit at the top of the column, not the bottom. The one button you reach for when an experiment goes wrong should not be behind the controls that caused it. `Export` opens the config as a `setPaletteConfig()` call to copy; `JSON` downloads `palette.json` on the press, with no intermediate state worth a second click. Both carry the config _as written_ rather than the resolved one, so an inherited `base` stays inherited instead of being frozen to whatever the accent happened to be.

Every caveat on the panel is an **InfoBadge** beside the control it qualifies rather than a paragraph under it. A tuner is a dense column of controls, and prose between them pushes the next knob off the screen to explain something you need once.

### Three states, one tab bar

An unlabelled tab bar spans the top of the panel, and everything below reads as the state it has selected:

|  | **Pastel** | **Advanced** | **Color** |
| --- | --- | --- | --- |
| **Accent** | Hue | Hue + Saturation | Color (hue+chroma+tone) |
| **Base** | Hue, or _Follow accent_ | Hue + Saturation, or _Follow accent_ | Color, or _Follow accent_ |
| **Status** | Hue | Hue + Saturation | Color |
| **Syntax** | Saturation | Saturation | Saturation |

`Advanced` and `Color` are the **same chroma space** — the per-hue ceiling — and differ only in what you hand it. `Pastel` is the other space, and it takes hues because a flat ceiling has nothing to do with a color.

It began as two controls, a `pastel` switch and a per-zone **Seeded by**, which described a 2×2 grid with one impossible cell: pastel cannot honour a color, so one of the two spent its life disabled. Three tabs spend three buttons on the three reachable states, and make Pastel → Color one press instead of two. The bar carries no label, because naming it would mean finding a word for "the palette" — and both candidates, _Mode_ and _Surfaces_, are spoken for further down.

Two rules follow from it:

- **`pastel` gates saturation.** It is one flat, hue-independent ceiling, which is what makes the palette even across hues and what leaves nothing for a saturation scale to do. There is no saturation control in that state except the syntax one, which `pastel` never reaches.
- **A derived control is not shown.** Whatever a seed already supplies, its slider goes away rather than sitting on screen disabled. A disabled slider under a color seed is a read-out dressed as a control, and it cost two rows to repeat what the color field above it already said.

The base zone keeps its own **Follow accent | Own**, which is orthogonal to the tabs: it is about whether the chrome has a seed at all, not about how a seed is spelled.

Every transition hands the incoming controls the values the outgoing ones were displaying, so switching changes who is in charge without repainting on the way. Leaving `Color` therefore pins each zone at what its color derived and drops the hex — including on the way to `Pastel`, which cannot honour a color at all. Status themes pin their **hue** only: a saturation pinned on the way out would survive into `Pastel`, where it is inert but still in effect, and that is not a state to manufacture on a tab press.

The two halves of the way _in_ differ, and both are deliberate. The brand zones open on a fixed sample hex, so the flip changes which control is in charge rather than reading the page back to itself. The four status themes convert instead — each to the fill it is already emitting — because four sample hexes would repaint every banner on a tab press, and a status theme's identity is a _meaning_ a sample color has no business overwriting. Coming from `Advanced`, the same chroma space, that conversion lands the banner back where it was; coming from `Pastel` the palette repaints regardless, since the tabs turn `pastel` off and a change of chroma space is the one thing no hand-over can carry across.

In color mode the panel shows where the color actually landed — **Accent Fill** and **Accent Text**, the two tokens the seed's tone reaches. The requested color is not repeated beside them: the field above holds it, with a swatch of its own.

The **preset** buttons show which one is active, and stop showing it the moment you touch a control. The setter replaces rather than merges, so a preset is either the whole config or it is not the config at all; anything else would claim a theme is still `Ocean` after you had re-seeded half of it.

The preview deliberately shows all three surface levels with their own text ramps (`#surface-text`, `#surface-2-text`, `#surface-3-text`), because a theme that looks fine on the page surface can fall apart two panels deep.

## Previewing a theme in a region

`setPaletteConfig()` re-themes the whole document, which is no use for a theme picker — you want several themes visible at once, or a dark preview inside a light page. `renderColorTokens()` does that: it resolves the palette for **one** config and **one** scheme and returns flat literal values, ready to apply to a subtree through a tasty `tokens` prop.

```tsx
import { renderColorTokens, tasty } from '@cube-dev/ui-kit';

const Region = tasty({ styles: { fill: '#surface', color: '#surface-text' } });

const preview = useMemo(
  () => renderColorTokens({ accent: { hue: 210 }, scheme: 'dark' }),
  [],
);

<Region tokens={preview}>…everything in here renders in that theme…</Region>;
```

The reason this needs its own API: the document palette emits **state maps** (`{ '': …, '@dark': …, '@hc': … }`), so a page can only ever show one scheme at a time — that is what `@dark` means. Collapsing the palette to a chosen scheme removes the conditionality, so several themes can coexist.

| Option | Meaning |
| --- | --- |
| every `PaletteConfig` field | merged over the **current** config, so `{ scheme: 'dark' }` previews the active theme in dark |
| `scheme` | `'light'` (default) or `'dark'` |
| `highContrast` | resolve that scheme's high-contrast variant. Default `false` |

Nothing is applied globally — the live palette and the stored config are untouched, so previews are safe to render anywhere.

Note the one place the merge/replace split matters: this call **layers** over the live config, unlike `setPaletteConfig()`, which replaces. A preview means "the theme in use, but in dark", so the fields it does not mention have to come from the current palette rather than from the defaults. `resolvePaletteConfig()` layers the same way.

Notes:

- Real components work inside a region. Every color in the kit compiles to a CSS custom property, so overriding those properties on one element re-colors its whole subtree with no scheme attribute and no second `<Root>`.
- The legacy aliases come along **by reference** (`'#dark': '#surface-text'`), and so do the shadow tokens and scrollbar colors, whose values embed a palette color. Tasty re-declares them on the region so each `var()` resolves against the region's own values; resolving them up front would freeze them to the outer theme instead.
- Typography, spacing, sizes and layout are **not** included — nothing in their values references a color, so the region inherits them from `<Root>`.
- `contrastLevel` works per region, so the whole 0–100 ramp can be shown at once — something a document cannot do, since it is only ever at one level. Level `0` reproduces the normal tier and `100` the high-contrast tier exactly, in both schemes. `highContrast: true` still returns the genuine high-contrast resolution at any level below `100`, because the level moves the baseline and the tier escalates from where `'auto'` would put it; at `100` the two coincide and it returns the same colors as the normal variant. Note that tokens carrying a contrast _floor_ (most text) can sit still over part of the ramp — the floor is solved, not approximated, so the value only moves once the interpolated target does. Tokens positioned by a plain tone pair, like `#border`, step at every level.
- Resolving a palette costs a few milliseconds. The last config is memoized, but `useMemo` on the caller side if you drive it from state.

`renderPaletteTokens()` is the same thing without the aliases and companion tokens, if you want only the Glaze palette.

## Reading and reacting to the config

```tsx
import {
  DEFAULT_PALETTE_CONFIG,
  getPaletteConfig,
  resetPaletteConfig,
  setPaletteConfig,
  subscribePaletteConfig,
  usePaletteConfig,
} from '@cube-dev/ui-kit';

// In React — `useState`-style (including the replacing setter), and re-renders
// on change. `palette` is the resolved config; the updater's argument is sparse.
const [palette, setPalette] = usePaletteConfig();

setPalette((config) => ({ ...config, accent: { ...config.accent, hue: 200 } }));

// Outside React.
getPaletteConfig(); // every field resolved to a concrete value
subscribePaletteConfig(() => {
  /* … */
});
```

`getPaletteConfig()` always returns the fully resolved form, so `getPaletteConfig().themes.danger.saturation` is a number even if nobody ever set it. `DEFAULT_PALETTE_CONFIG` is the shipped baseline in the same shape.

## Reading the ambient scheme

The palette config is what the app _asked for_; the scheme and contrast tier are what the viewer is _seeing_ — `<html data-scheme>` / `prefers-color-scheme`, and `<html data-contrast>` / `prefers-contrast`. They are not part of the config, so `getPaletteConfig()` says nothing about them:

```tsx
import { useHighContrast, useScheme } from '@cube-dev/ui-kit';

const scheme = useScheme(); // 'light' | 'dark'
const isHighContrast = useHighContrast(); // boolean
```

Both resolve exactly as the `@dark` / `@hc` states do — attribute opt-in first, media query only when the attribute is absent — and re-render when either input changes. Outside React: `resolveScheme()`, `resolveHighContrast()` and `subscribeScheme(listener)`, which fires on a change to either condition.

Reach for these only where CSS cannot go. Styling belongs in a state map (`{ '': …, '@dark': …, '@hc': … }`), which repaints on a scheme flip with no re-render at all. What the states cannot reach is a surface that takes values rather than CSS — a Vega spec, a CodeMirror or Monaco theme, an iframe — or a control whose value _is_ the condition, like the Light/Dark and Normal/High-contrast selectors over the [theme builder](#theme-builder).

Note the distinction from `contrastLevel`: the level is a config seed the app supplies and can read back, while high contrast is a viewing condition the document is in. They also pair up — `renderColorTokens({ scheme, highContrast })` takes both, so a region can be previewed in the conditions the page is actually showing.

## `<Root palette>`

`<Root>` accepts the same config as a prop. The first mount applies it during render, so the first paint (and SSR output) is already correct. A later change applies in a layout effect, which still lands before paint and does not update other components while `<Root>` renders, so the prop alone is enough — there is no need to call `setPaletteConfig()` before changing it:

```tsx
<Root palette={{ accent: userBrandColor }}>
  <App />
</Root>
```

Because the setter replaces, the prop describes the **whole** palette: drop a field from the object and that customization goes away on the next render, which is what you want from a declarative prop.

Removing the prop entirely is the one thing that does _not_ reset the palette — `<Root>` with no `palette` leaves whatever is configured alone, so that the common case cannot clobber a host's imperative `setPaletteConfig()` call. Pass `palette={{}}` if you do want the default.

This is a convenience wrapper over `setPaletteConfig()`, not a separate scope. **The palette is process-global** — Glaze's own config is, and so is the single `body` rule the tokens are injected into. One palette per process, not per tree and not per request:

- Two `<Root>`s with different `palette` props will fight over the same tokens.
- `<Root>`'s layout effect runs after its descendants' layout effects in the same commit, so a `setPaletteConfig()` call from a descendant's layout effect in a commit that also mounts `<Root>` or changes its `palette` loses to the prop. Call it from a passive effect or an event handler instead. A `<Root>` that mounts while another tree is already rendered also applies its palette during its first render, which updates that tree mid-render and makes React warn.
- Under SSR, apply the palette in code that runs on **both** server and client. A client-only `setPaletteConfig` disposes and replaces the server-rendered token block on the first render, which is visible as a flash. Per-request palettes are not supported.

## Caveats

**`pastel` is a redesign, not a filter — in either direction.** It changes every resolved color outside the `code-*` family, and the shipped palette is now pastel (`pastel: true`, seed `100`), so it is `pastel: false` that is the departure. The two spaces want different seeds: pastel equalizes the chroma ceiling across hues, where the non-pastel one is per-hue and lets warm hues run further. Flipping the flag alone therefore re-tunes nothing — a seed picked in one space lands somewhere else in the other, and the warm statuses move most. Re-tune the seeds alongside it, in whichever direction you flip.

It also owns the accent's `saturation` outright — pinned to `100`, so a number passed _explicitly alongside_ it is inert and warned about (a number passed on its own turns pastel off instead). And it caps a color seed short of itself: the ceiling sits below where a saturated color lands, so `#EF4444` resolves to `#c47069`. Both are visible in the [Theme builder](#theme-builder), the first as a disabled slider and the second as the requested/resolved chips.

**Re-seeding costs about 10 ms.** Rebuilding the eight themes and re-solving ~156 tokens across four scheme variants is not free, though it is inside a frame. A manual `contrastLevel` costs the same — it runs the same four passes — except at level `100`, which skips the two high-contrast ones because the normal pass already produced those values. Setting the config to a value it already holds is free — it does not even bump the version. If you are driving it from a slider, let the input coalesce to frames (a pointer-driven `onChange` already does) rather than writing on every event.

**If you call Glaze directly, tell the kit.** `glaze.configure({ darkTone })` and friends invalidate Glaze's own caches, but the kit's token maps are memoized against the palette config version:

```ts
import { glaze, invalidatePaletteTokens } from '@cube-dev/ui-kit';

glaze.configure({ darkDesaturation: 0.2 });
invalidatePaletteTokens(); // only needed once the kit is already mounted
```

`contrastLevel` is the one field the kit writes to Glaze's global config, and it only ever does so if you asked for a level. A host that sets its own `glaze.configure({ contrastLevel })` and never passes `contrastLevel` here keeps it.

**Some things are not tunable at all.** Tasty locks its configuration on the first style injection, so the `@dark` / `@hc` / `@reduced-motion` state definitions (set in `Root`) are fixed for the lifetime of the page. Only token _values_ stay mutable — which is all re-seeding needs.

## See also

- [Colors](./Colors.md) — how to pair surfaces with foregrounds, and what each token family is for.
- [Usage](./Usage.md) — the full token reference.
