Getting started
Theming
Define a theme with defineTheme, derive a brand preset from one hex color, switch schemes and surface styles, and override tokens through the cascade.
A theme is a plain object. The library compiles it to CSS once at build time (the same object always gives the same CSS) and injects it before any stylesheet, so there is no per-render style work and no flash.
// src/lib/theme.ts
import type { ThemeOptions } from "@codeatlasdev/ui/vite";
export const theme: ThemeOptions = {
presets: [{ id: "acme", color: "#2563eb" }],
defaultPreset: "acme",
defaultScheme: "system",
defaultStyle: "solid",
fonts: { body: "Geist, system-ui, sans-serif" },
radius: 0.8,
density: "comfortable",
overrides: { light: { "--ca-card-padding": "16px" } },
};
Pass the same object to caThemeHandle and caThemePlugin (SvelteKit), caUI (Astro) or themeHead (custom setups), see Installation. ThemeOptions is Partial<ThemeDefinition>, so every field is optional.
Options
| Option | Default | Description |
|---|---|---|
presets |
[] |
Brand presets generated from a hex color. Built-in presets are always available. |
defaultPreset |
"amber" |
Preset used until the user picks one. Must be a built-in or one of presets. |
defaultScheme |
"dark" |
"light", "dark" or "system". bunx @codeatlasdev/ui init scaffolds "system". |
defaultStyle |
"solid" |
Surface material: "solid", "flat", "frosted", "glass", "outlined", "neumorphic", "clay", "tonal" or "chrome". Solid is the sober default; glass is the opt-in liquid look. |
fonts |
{} |
body, mono and display. Each is a font stack string or a self-hosted font descriptor (@font-face, preload, metric-matched fallback), see Performance. They set --ca-font-sans, --ca-font-mono and --ca-font-display. |
radius |
0.8 |
Multiplier applied to the --ca-radius-xs to --ca-radius-xl scale (0.8 makes --ca-radius-md 8px) and to --ca-radius-round, so 0 also squares swatches, active pips, dots and chips. |
density |
"comfortable" |
"compact" (0.75), "comfortable" (1), "airy" (1.25) or a number. Scales the --ca-space-* tokens, so padding, gaps and page spacing follow. |
paper |
"plain" |
Page background: "plain", "mesh" (brand glow, drawn by the glass and frosted styles), "grid", "dots" or "lines". Flat patterns are drawn in --ca-outline-subtle, so they follow the preset and scheme. |
iconStroke |
1.75 |
Lucide stroke width. |
controlRadius |
"md" |
Corner role of buttons, fields and chips: "xs", "sm", "md", "lg", "xl" or "pill". |
border |
{ width: 1, strong: 2 } |
Border weights in px (--ca-border-width, --ca-border-width-strong). |
elevation |
"soft" |
How shadows are drawn: "soft", "none", "hard" (offset, no blur) or "glow". |
typography |
{} |
scale, weights (heading defaults to 600), headingTracking, headingCase, displayTracking, displayLeading, labelTracking, labelCase, lineHeight and measure. |
type |
{} |
The type scale by role: title, heading, body, label, caption, num, each with size, leading, tracking and weight. Overrides the role everywhere, library components included. See Typography. |
motion |
{} |
scale (multiplier on every duration), easing ("standard", "emphasized", "spring", "linear" or "steps") and enter ("default" or "none"). enter: "none" makes dialogs, drawers, sheets, menus, popovers, tooltips and toasts appear and leave in place while hover and focus color transitions keep scale (it sets --ca-enter-scale: 0); MotionStage demos render their final state. |
noise |
0 |
Film-grain over the page background, from 0 to 0.12. |
components |
{} |
Component tokens of button, iconButton, kbd, avatar, field, textArea, card, segmented and emptyState. |
overrides |
{} |
Raw --ca-* token overrides, per scheme (light, dark). Prefer preset role colors (below) for palettes. |
defineTheme(options) resolves the options (defaults, validation) and themeCSS(resolved) returns the CSS string. You rarely call them yourself; the integrations do. Invalid input fails the build: a preset id that clashes with a built-in, a color that is not #rrggbb, or a defaultPreset that does not exist.
Presets
Eight OKLCH presets ship with the package: amber, ocean, crimson, cyan, violet, emerald, rose and slate. One attribute switches the whole app:
<html data-preset="ocean" class="dark">
In code, use the store:
import { colorScheme } from "@codeatlasdev/ui";
colorScheme.setPreset("violet");
colorScheme.presets; // every valid id: built-ins plus your brand presets
Brand preset from a hex color
Give the library your logo color and it derives hue, chroma and lightness in OKLCH, then emits the complete light and dark token set (brand, surfaces, text, outlines, surface tints). Charts use the hex as their first series color.
export const theme: ThemeOptions = {
presets: [{ id: "acme", color: "#2563eb", label: "Acme" }],
defaultPreset: "acme",
};
Caution
Values stored by the user that your theme does not know are discarded and removed from storage. If you rename or delete a brand preset, returning users fall back to defaultPreset instead of seeing a broken theme.
Porting a palette by role
To bring an existing palette (a terminal or editor theme) into a preset, set role colors per scheme. Unset roles keep the generated value; a per-scheme brand regenerates that scheme’s brand ramp, and background also drives <meta name="theme-color">. Roles are scoped to the preset, so switching presets and theme islands keep working.
presets: [{
id: "tokyo",
color: "#7aa2f7",
colors: {
light: { brand: "#34548a" },
dark: { background: "#1a1b26", surface: "#232430", text: "#c0caf5", border: "#565f89", error: "#f7768e" },
},
}],
Roles: brand, brandFill, brandFillHover, brandContrast, background, sunken, surface, overlay, text, textSecondary, textHint, textDisabled, borderSubtle, border, borderStrong, success, warning, info, error. Except brand (#rrggbb), a role is any CSS color: #rrggbb, rgb(), oklch(1 0 0 / 0.62), color-mix(in oklab, white 10%, transparent), or { color: "#fff", alpha: 0.1 }. A translucent role follows the surface behind it instead of being flattened onto one background, so keep alpha in the theme, not in a hex computed by hand. A value that is not a single CSS color (red; --x: 1) throws at build time.
caThemePlugin and caUI print a warning at startup when a text, textSecondary or textHint you set is under 4.5:1 on any of the four surfaces after compositing its alpha over that surface. Colors the build cannot evaluate (var(), other keywords) are skipped. The generated palette guarantees AA; hand-picked roles are measured, not corrected.
Importing an existing design system
bunx @codeatlasdev/ui tokens import src/app.css --out src/lib/theme.ts reads the custom properties of a CSS file (one rule per theme: :root, .dark, [data-theme="paper"]) or a { theme: { token: color } } JSON, in hex, rgb(), hsl() or oklch() with or without alpha, and writes a theme.ts with one preset per theme. Presets take opaque #rrggbb, so a translucent token is composited over its theme’s background, listed as flattened, and every text pair under 4.5:1 and outline under 3:1 is reported:
flattened app textSecondary: alpha 0.35 over background -> #5e6064
app textSecondary on background: 2.98:1, below 4.5:1
--map <json> maps roles to token names (default: the shadcn names), --out refuses to overwrite without --force, --strict exits 1 on a failing pair. A role the source lacks is listed as missing and keeps the generated value; var() and color-mix() are listed as unresolved. A Tailwind config is JavaScript: export its colors to CSS or JSON first.
Brand-colored buttons and field size
The generated primary button darkens the brand until white text reaches AA. A product with a dark, brand-forward area can ask for the brand itself as the fill, with dark text, and a smaller field font, per preset. No app CSS and no repeated [data-preset] selectors: the roles are emitted with the same selectors as the other roles.
presets: [{
id: "night",
color: "#f27636",
colors: {
dark: {
brandFill: "#f27636", // Button variant="filled" background
brandFillHover: "#f5934f", // hover and pressed
brandContrast: "#1a1208", // text on brandFill
},
},
sizes: { inputFontSize: "0.875rem" }, // both schemes
}],
caThemePlugin (SvelteKit, Vite) and caUI (Astro) print a warning at startup when brandContrast on brandFill is under 4.5:1 (a role left unset is measured from the generated one). sizes.inputFontSize takes a plain length (px, rem, em); touch devices and screens under 900px still get max(16px, …), so iOS Safari does not zoom into focused fields, and the 44px touch targets do not change.
Domain tokens: status, tier, channel
Colors that are not UI roles (funnel status, lead score tier, contact channel, map pins) belong to the preset too, so they follow the scheme and the preset with no parallel stylesheet. Declare them under tokens as group → name → color; one value serves both schemes, or give { light, dark }.
presets: [{
id: "app",
color: "#3b82f6",
tokens: {
status: { new: { dark: "oklch(0.76 0.11 245)", light: "oklch(0.45 0.14 245)" }, won: "oklch(0.7 0.13 155)" },
channel: { whatsapp: "#25d366" },
},
}],
tokens.status.new emits --ca-token-status-new plus two derived tokens per scheme: --ca-token-status-new-subtle (a 16% tint, for a badge or row background) and --ca-token-status-new-contrast (white or ink, whichever reads at 4.5:1 on the token). Group and name match [a-z][a-z0-9-]*; anything else throws. To type the names, augment the registry once: declare module "@codeatlasdev/ui" { interface CaTokenRegistry { "status.new": true } }.
Canvas, WebGL and map code cannot read oklch(). tokenRgba("status.new") (from @codeatlasdev/ui or @codeatlasdev/ui/tokens) returns [r, g, b, a] for a domain token, any --ca-* custom property or a CSS color, within 1/255 of what CSS paints. Read it inside a $derived or $effect together with colorScheme.resolved, or call onTokensChange(fn) outside Svelte; both re-run on scheme and preset changes. It replaces the 1×1-canvas helper an app would write.
Status tokens
Pills colored by --ca-token-status-*, and a canvas colored with tokenRgba. Toggle the theme: both follow.
- New 18
- Won 9
- Lost 4
Code
Sketchbook style and hand-drawn marks
designStyle("sketchbook", { ... }) is a journal look: grid paper, serif display, square outlined cards with hard shadows. It pairs with the opt-in marks stylesheet:
import "@codeatlasdev/ui/styles/marks.css";
<span class="ca-mark-underline">already knows.</span>
<p class="ca-mark-note">A margin note with a sketched arrow.</p>
Marks are SVG masks painted with --ca-mark-color (brand by default); swap the shapes with --ca-mark-scribble and --ca-mark-arrow. In forced-colors mode they paint in CanvasText.
Editorial tokens
For marketing and editorial pages the kit ships the pieces a cover needs, so none of them is local CSS:
| Token | Value | Use |
|---|---|---|
--ca-font-size-display-hero |
clamp(3.75rem, min(15vw, 21dvh), 13.5rem) |
One-screen headline, 60px to 216px, capped by viewport height. Pair it with --ca-display-tracking and --ca-display-leading (typography.displayTracking, typography.displayLeading). |
--ca-ease-out-expo |
cubic-bezier(0.16, 1, 0.3, 1) |
Entrances that start fast and settle. |
--ca-ease-out-quart |
cubic-bezier(0.25, 1, 0.5, 1) |
Softer entrances, the strike draw. |
--ca-ease-in-out-quart |
cubic-bezier(0.76, 0, 0.24, 1) |
Symmetric moves. |
--ca-grain-opacity, --ca-grain-size |
0.08, 160px |
Strength and tile of <Surface grain>. |
--ca-highlight-color, --ca-strike-color |
brand tint, error | Colors of Highlight and StrikeThrough. |
<Highlight animated> and <StrikeThrough animated> render their final state under prefers-reduced-motion: reduce. --ca-font-mono starts with the system monospace (ui-monospace, SF Mono, Menlo, Consolas) because the kit does not load JetBrains Mono; set fonts.mono to use another.
Schemes
defaultScheme: "system" follows the operating system, including live changes while the page is open. The init script also keeps <meta name="theme-color"> in sync with the preset’s surface color.
colorScheme.preference; // "light" | "dark" | "system"
colorScheme.resolved; // "light" | "dark" (system already resolved)
colorScheme.isDark; // boolean
colorScheme.setPreference("system");
colorScheme.toggle(); // flips resolved light and dark
Surface styles
data-style on <html> swaps the material of every surface at once.
| Style | Look |
|---|---|
solid |
Default. No blur, opaque surfaces, plain page, hairline edges, no glow. Keeps soft neutral shadows. |
flat |
No blur, no mesh, no glow, no drop shadows: separation comes from borders. |
frosted |
Less blur, calmer mesh background. |
glass |
Opt-in. Strong blur and saturation, translucent tints, brand mesh, glow and rim light (the look of the liquid recipe). |
outlined |
Border-defined opaque surfaces with no elevation. Used by the swiss, brutalism, terminal and sketchbook recipes. |
neumorphic |
One base color extruded by paired light and dark shadows. Low contrast: use it for showcases, not dense data UIs. |
clay |
Soft, inflated opaque surfaces. |
tonal |
Surfaces tinted with the brand hue and soft elevation (Material 3 style). |
chrome |
Glossy gradient with a metallic rim and brand glow. Blur stays on. |
colorScheme.setStyle("glass");
The liquid recipe
liquid is one of the design recipes: glass surfaces over a three-hue mesh, glow on selected states, round corners (10px controls), 2px icons, bold headings and hue-tinted shadows. It is what earlier versions looked like and is opt-in:
import { designStyle } from "@codeatlasdev/ui/vite";
import type { ThemeOptions } from "@codeatlasdev/ui/vite";
export const theme: ThemeOptions = designStyle("liquid", {
presets: [{ id: "acme", color: "#2563eb" }],
defaultPreset: "acme",
defaultScheme: "dark",
});
designStyle("default") is the default recipe (solid). designStyle, DESIGN_STYLES and mergeTheme are plain data, so a theme.ts shared with vite.config imports them in Node from @codeatlasdev/ui/vite (@codeatlasdev/ui/astro exports them too). The root and @codeatlasdev/ui/kit also export them, but they pull in Svelte files that vite.config cannot load. To migrate an app that relied on the old defaults, use designStyle("liquid", { ... }), or set defaultStyle: "glass" yourself.
Other design styles
DESIGN_STYLES maps each id to { id, label, description, taxonomy, theme }. designStyle(id, overrides) returns that recipe’s theme with your overrides merged on top, and mergeTheme(a, b) merges two partial themes (b wins). The ids are default, liquid, swiss, brutalism, neumorphism, glassmorphism, material, fluent, apple, bento, claymorphism, y2k, editorial, terminal and sketchbook. Each recipe only sets the design knobs from the options table (material, radius, border, elevation, typography, motion, icon stroke, paper).
Users on prefers-reduced-transparency: reduce get opaque surfaces regardless of the style.
The colorScheme store
Call colorScheme.init() once in the root layout (inside onMount). It re-applies the state to <html>, follows OS scheme changes and keeps the browser chrome color in sync. It is idempotent and returns a cleanup function.
| Member | Description |
|---|---|
preference, resolved, preset, style, isDark, presets |
Reactive getters (Svelte 5 $state). |
setPreference(pref), toggle() |
Change the scheme. |
setPreset(id), setStyle(style) |
Change preset or surface style. |
setTokens(vars) |
Runtime token overrides, see below. |
init() |
Start listeners. Returns cleanup. |
All choices persist in localStorage (ca-scheme, ca-preset, ca-style). Storage errors in private mode are ignored, and the values are validated against the theme before use.
Runtime tokens
setTokens writes your --ca-* variables to a single <style id="ca-runtime-tokens">, persists them and replays them in the init script before first paint. Use it for user-defined themes such as an imported editor theme. Keys must match --ca-*; values containing {, }, < or ; are dropped.
The init script is one synchronous inline <script> (under 1 kB gzip) that reads storage with every access guarded: a blocked, full or corrupt localStorage falls back to the theme’s defaults on the first frame, never an unthemed page. It sets ca-init on <html> (transitions off) and removes it two frames after the first paint, so nothing animates on load. It carries no eval or inline handler, so a CSP nonce or hash on that one tag is enough.
colorScheme.setTokens({ "--ca-brand-main": "#ff5500", "--ca-radius-md": "14px" });
colorScheme.setTokens({}); // clear
Theme islands
Put data-theme-scope="light" or "dark" on any element to re-apply that scheme’s tokens inside it, regardless of the page scheme. Useful for a dark hero on a light page or a light preview inside a dark editor.
<section data-theme-scope="dark">
<!-- dark tokens here, on any page -->
</section>
Add data-preset to switch the palette as well, on the same element or on a wrapper. The nearest preset wins, even when the page uses your brand preset:
<div data-preset="violet">
<section data-theme-scope="dark"><!-- violet, dark --></section>
</div>
Islands also feed the browser chrome color when they touch the top edge, see Mobile.
Cascade and overriding tokens
global.css declares its layers up front:
@layer ca.reset, ca.tokens, ca.themes, ca.base, ca.materials, ca.utilities, ca.components;
Every component stylesheet is wrapped in @layer ca.components, the last kit layer. Your app CSS is unlayered, and unlayered rules beat every layer regardless of specificity or import order. Overriding therefore never needs !important or a doubled class, for tokens and for component rules alike:
/* app.css: no !important, no .ca-btn.ca-btn */
:root {
--ca-card-padding: 16px;
--ca-radius-lg: 18px;
}
.ca-btn:disabled { opacity: 0.3; }
.ca-tf__wrap { border-radius: 4px; }
.ca-dialog__body { padding: 0; }
ca.reset is the first layer and holds three rules. Native controls use the page font instead of the browser’s (Arial on Chromium/Windows): button, input, select, textarea { font: inherit }. Every interactive shape gets a pointer cursor: button, a[href], label[for], summary, [role=button], [role=tab], [role=option] and [role=menuitem*], so a custom clickable tile never shows the arrow. :disabled and [aria-disabled=true] get not-allowed. Every component and every app rule outranks all three, so .tile { cursor: grab } just works:
/* app.css: a tile that is not a button */
.tile { cursor: grab; }
Give a clickable tile role="button" (or make it a <button>) rather than a bare div with onclick: it gets the pointer, the keyboard contract and the right role at once.
If your own CSS lives in a layer (for example Tailwind’s @layer components), declare it after the kit’s order statement so it ranks higher: @layer ca.reset, ca.tokens, ca.themes, ca.base, ca.materials, ca.utilities, ca.components, app;.
Important beats layers, in reverse
A declaration marked !important inside a layer outranks an unlayered normal one. The kit therefore avoids !important in component CSS; the few left only beat inline styles the component sets itself (the indeterminate Progress width, the AppShell content margin while the sidebar animates), prefers-reduced-motion, and the focus ring in base.css. To override one of those, use !important in your own unlayered rule.
For per-scheme overrides prefer overrides in the theme object, which is emitted for both :root and theme islands.
Note
The ca-* BEM classes (.ca-btn, .ca-dialog__body, …) are public API. Targeting them from app CSS is supported, and renaming one is a breaking change. Which ones, per component, along with its scoped variables and data-* hooks, is generated: list_parts("Button") in the MCP server, the Parts / Variables / Data attributes lines of API.md, or dist/parts.json. A ca-x-* class and every @keyframes name is internal. bunx @codeatlasdev/ui workarounds --strict exits 1 when your CSS selects a .ca-* name that is not a stable part.
Component tokens
A component token is a custom property a component reads before its own default. One naming convention for every component, so nobody writes a selector against a ca-* class:
--ca-<component>-<property>: the component, every size and part (--ca-btn-font-weight).--ca-<component>-<size or part>-<property>: one size or part; it wins over the form above (--ca-btn-lg-font-weight,--ca-icon-btn-size-sm).<component>is the class stem (btn,icon-btn,kbd,avatar,tf,ta,card,seg,empty); a token shared by a family uses its name (--ca-field-gapforTextFieldandTextArea).<property>is spelled like the CSS it drives:font-weight,line-height,gap,padding-x,size.
Values are plain CSS. Unset, a component draws what it always drew. Set them on :root, on a wrapper (no :global(.ca-*)) or in the theme, where mergeTheme merges per block and size:
export const theme = {
components: {
button: { weight: 600, gap: "var(--ca-space-2)", ghostBorderWidth: "0px", sm: { paddingX: "var(--ca-space-3)" } },
iconButton: { size: { sm: "36px" } },
kbd: { size: "var(--ca-space-5)" },
avatar: { fallbackSize: "0.75rem" },
field: { gap: "var(--ca-space-1-5)" }, // TextField and TextArea
textArea: { minHeight: "var(--ca-space-16)" }, // the visible box, border included
card: { border: "1px solid var(--ca-outline-subtle)", shadow: "none" },
segmented: { itemPaddingX: "var(--ca-space-3)" },
emptyState: { titleSize: "1rem" },
},
};
The 44px touch targets stay unless you set --ca-btn-touch-height or --ca-icon-btn-touch-size. Each component page lists its tokens under “Tokens”; get_component returns them as tokens.
Dialogs, drawers and the scrim
Since 2.0.0 (the release that dropped bits-ui) .ca-overlay is the modal <dialog> itself, not a separate backdrop element. Dialog, AlertDialog, Drawer, Sheet, CommandPalette and DocsSearch all render dialog.ca-overlay, the panel classes (.ca-dialog, .ca-drawer, …) place it, and the scrim is its ::backdrop. A rule written for the old overlay element now paints the panel:
/* before: darkened the scrim element. now: makes every dialog and drawer see-through */
.ca-overlay { background-color: rgb(0 0 0 / .3); backdrop-filter: none; }
Style the scrim through its two tokens, or target the pseudo-element:
:root {
--ca-scrim-color: rgb(0 0 0 / .3);
--ca-scrim-blur: none; /* default: blur(4px) saturate(180%) */
}
/* or, for a single rule */
dialog.ca-overlay::backdrop { background: rgb(0 0 0 / .3); }
--ca-scrim-color is set per preset and scheme; --ca-scrim-blur: none drops the blur on every modal at once. Search your app CSS for .ca-overlay when upgrading from 1.x and move each rule to ::backdrop (scrim) or to the panel class (.ca-dialog, .ca-drawer) if it was meant for the surface.
Glass and frosted styles: blur rules
Only the glass and frosted styles (and material="glass" | "frosted" | "liquid" surfaces) blur. When you do blur, two CSS properties silently kill backdrop-filter:
will-change: transformon the same element or an ancestor.position: absolutechildren inside anisolation: isolateparent.
Keep backdrop-filter on the element that composites directly against the page.