zgui
Component library

Tokens and theming

Theme the zgui component library with ThemeProvider, light and dark schemes, themes written as CSS, presets and run-time switching, plus a reference of all 141 design tokens.

zgui-ui-tokens holds the design tokens the component library is styled with, and ThemeProvider, which installs them in a window. Every token is a CSS custom property starting with --zui-. Component sheets read tokens with var() and never name a concrete colour, so you re-theme the whole library by changing token values.

Cargo.toml
[dependencies]
zgui-ui-tokens = "0.1"
use zgui_ui_tokens::prelude::*;

The crate depends only on zgui, so you can also use it without zgui-ui: the tokens plus your own css! sheets make a complete design system.

Apply a theme

Wrap your interface in a ThemeProvider. It installs the tokens as a style sheet and renders a single display: contents element.

view! {
    ThemeProvider(scheme = ColorScheme::System) {
        App()
    }
}
PropTypeDefault
lightSignal<Theme, LocalStorage>, intoTheme::light()
darkSignal<Theme, LocalStorage>, intoTheme::dark()
schemeSignal<ColorScheme, LocalStorage>, intoColorScheme::System
childrenChildrenrequired

light and dark are two independent slots: the theme used when the scheme is light, and the one used when it is dark. Pass a signal to make a slot switchable. scheme decides which slots are written to the sheet:

ColorSchemeSheet contents
Lightthe light theme only
Darkthe dark theme only
Systemthe light theme, then the dark theme inside @media (prefers-color-scheme: dark)

With System, nothing is resolved in Rust. The media query follows the window's light or dark preference: the desktop's, or the one set with app().with_theme(…) or WindowHandle::set_theme(…) (see Theming).

zgui-ui never installs tokens itself. Without a provider, or custom properties you declare yourself, every component's var(--zui-…) resolves to nothing and the components render unstyled.

Where the tokens are declared

ProviderDeclares onSheet name
the first in a window:rootzgui-ui-theme (THEME_SHEET)
a nested one, number N.zui-theme-Nzgui-ui-theme-N
  • The outermost provider declares on :root, so menus, dialogs and toasts are themed even though they are portalled onto overlay bands outside the provider's subtree.
  • A nested provider themes only its own subtree. Portalled surfaces opened from inside it still use the root tokens.
  • The tokens are a style sheet at the author origin, not inline styles, so your own rules can override them.
  • Unmounting a provider removes its sheet.

Write a theme

A theme is a set of CSS values, so the easiest way to write one is in CSS. Theme::with_css applies custom property declarations on top of a base theme:

let mocha = Theme::dark().with_css(
    "--zui-color-background: #1e1e2e;
     --zui-color-primary: #cba6f7;
     --zui-radius-base: 8px;
     --zui-space-base: 3.5px;
     --zui-shadow-sm: none;
     --zui-type-family-sans: 'Readex Pro';",
);

view! {
    ThemeProvider(dark = mocha, scheme = ColorScheme::Dark) {
        App()
    }
}
  • Unknown property names are ignored, as in a style sheet. Comments are skipped, a wrapping :root { … } is accepted, and the trailing semicolon is optional.
  • apply_css(&mut self, text) does the same in place and returns how many declarations matched a token. set(property, value) sets one token and reports whether it exists.
  • The set of tokens is fixed: you cannot add a ninth group. Declare tokens of your own as ordinary custom properties in your own sheet (see Add your own tokens).
  • Declarations::push refuses a value containing ;, {, } or /* (a debug assertion; in release builds the token is dropped), so a value supplied at run time cannot break the sheet.

Start from a preset

Preset lists the themes the library ships, each built with with_css:

PresetCharacter
Base (default)the default tokens: neutral, near-monochrome, soft corners
Oceanblue, wider corners, slower and softer motion
Emberwarm orange, tight corners, the fastest motion
Terminalgreen, square corners, no motion (all durations zero)
Midnightviolet, very round corners, long and gentle motion
ThemeProvider(light = Preset::Ocean.light(), dark = Preset::Midnight.dark()) {
    App()
}

To build a theme picker, use Preset::ALL, name(), label() and from_name().

Switch themes at run time

To changeDo thisWhat changes
the schemewrite the scheme signalwhich slot is written to the sheet
a whole slotwrite the light or dark signalthat slot's theme
some tokensuse_theme()?.themes().patch(…)only the token groups that differ
one contexta rule in your own sheetyour rule, if it wins the cascade

Each of the first three replaces the theme sheet once, keeping its place in the cascade. A patch that changes no token does not touch the document.

#[component]
fn Page() -> impl IntoView {
    let scheme = RwSignal::new_local(ColorScheme::Light);
    let dark_theme = RwSignal::new_local(Preset::Base.dark());

    view! {
        ThemeProvider(scheme = scheme, dark = dark_theme) {
            Switch(
                default_checked = false,
                on_change = UnsyncCallback::new(move |on: bool| {
                    scheme.set(if on { ColorScheme::Dark } else { ColorScheme::Light })
                }),
                a11y:label = "Dark mode"
            )
            Button(on:click = move |_| dark_theme.set(Preset::Midnight.dark())) {"Midnight"}
        }
    }
}

To patch tokens from anywhere below a provider:

use zgui::reactive::Patch;

let theme = use_theme().expect("inside a ThemeProvider");
let mut next = Themes::defaults();
next.light.color.primary = "oklch(0.55 0.22 264)".to_owned();
theme.themes().patch(next);

Code that reads one token group is not notified when another group changes.

A theme switch restyles the whole document, and changing spacing or type tokens also re-runs layout and text shaping. Treat it as an occasional event. For changes on every frame, toggle a class or set a custom property on one element instead. See Theming and the cost model.

Override tokens in CSS

Re-tinting the library takes five declarations:

:root {
    --zui-color-primary: oklch(0.55 0.22 264);
    --zui-color-primary-foreground: oklch(0.985 0 0);
    --zui-color-accent: oklch(0.95 0.03 264);
    --zui-color-accent-foreground: oklch(0.4 0.16 264);
    --zui-color-ring: oklch(0.55 0.22 264);
}

Your override must win the cascade against the theme sheet. Both are author sheets, and the theme sheet is installed when the provider mounts, after app().with_stylesheet(…) sheets. A rule of yours on :root ties on specificity and loses on order. Either pass the values to ThemeProvider as a theme (with_css), or use a more specific selector. Declaring the override on your own container also works through inheritance, but portalled surfaces are not inside that container.

Add your own tokens

Declare them in your own sheet. Define them in terms of the library's tokens where it makes sense; they then follow both schemes automatically.

:root {
    --app-sidebar-width: 260px;
    --app-code-background: var(--zui-scale-neutral-3);
}
.sidebar { width: var(--app-sidebar-width); background-color: var(--zui-color-card); }

The library also reads a few properties that neither the theme nor the provider declares. Set them yourself; there is no theme rule to override.

PropertyRead byWhen undeclared
--zui-icon-sm, -md, -lg, -xlthe icon sheet, per size; set on a container to size the icons under it12px, 16px, 20px, 24px
--zui-icon-sizeone icon's width and height; each icon declares it, so set it on the iconthe size token for its size
--zui-overlay-depthoverlay z-indexwritten by the overlay components
--zui-surface-placeoverlay surface transform; a dialog writes it to centre itselfno offset
--zui-surface-enter-*, --zui-surface-exit-* (-x, -y, -scale, -opacity, -duration, -ease)overlay surface entrance and exit; set them on .zui-surface0px, 0px, 0.95, 0, --zui-motion-duration-normal, ease; an anchored surface slides 8px towards its trigger
--zui-popper-available-width, -heightthe maximum size of menus, select lists, popovers and date pickerswritten by Popper: the room between the anchor and the window's edge

For example, :root { --zui-icon-md: 18px } makes every default-size icon larger. See Icons.

Read tokens in Rust

You rarely need to, because components work entirely in CSS. When you need a value in Rust (a chart colour, a duration), use_theme() returns the nearest ThemeContext, or None outside a provider.

ThemeContext methodReturns
themes()Store<Themes>: the light and dark themes, readable group by group
scheme()the scheme signal (a System scheme is reported as System)
selector()":root" or ".zui-theme-N"

Token reference

Each group is a Rust struct of String fields (a token is a CSS value) with light() and dark() defaults. A Theme holds one of each group.

GroupTheme fieldPrefixTokens
ScaleTokensscale--zui-scale-24
ColorTokenscolor--zui-color-43
ControlTokenscontrol--zui-color-control-11
SpacingTokensspace--zui-space-8
RadiusTokensradius--zui-radius-10
TypeTokenstypography--zui-type-26
ShadowTokensshadow--zui-shadow-9
MotionTokensmotion--zui-motion-10

Every group has PROPERTIES (its custom property names, in field order), light(), dark(), declare(), pairs() and set(property, value). Theme::properties() lists all 141 names.

Spacing, radii, type, shadows and motion are the same in both schemes; only colours differ.

Semantic colours

These are the tokens components use. All names start with --zui-color-, and values are written in oklch().

TokenLightDark
backgroundoklch(1 0 0)oklch(0.145 0 0)
foregroundoklch(0.145 0 0)oklch(0.985 0 0)
card, popoveroklch(1 0 0)oklch(0.205 0 0)
card-foreground, popover-foregroundoklch(0.145 0 0)oklch(0.985 0 0)
tooltipvar(--zui-color-foreground)same
tooltip-foregroundvar(--zui-color-background)same
tooltip-bordervar(--zui-color-tooltip)same
primaryoklch(0.205 0 0)oklch(0.922 0 0)
primary-foregroundoklch(0.985 0 0)oklch(0.205 0 0)
secondary, muted, accentoklch(0.97 0 0)oklch(0.269 0 0)
secondary-foreground, accent-foregroundoklch(0.205 0 0)oklch(0.985 0 0)
muted-foregroundoklch(0.556 0 0)oklch(0.708 0 0)
destructiveoklch(0.577 0.245 27.325)oklch(0.704 0.191 22.216)
destructive-foregroundoklch(0.97 0.01 17)oklch(0.58 0.22 27)
dangervar(--zui-color-destructive)same
successoklch(0.627 0.194 149.214)oklch(0.723 0.219 149.579)
success-foregroundoklch(0.982 0.018 155.826)oklch(0.266 0.065 152.934)
warningoklch(0.769 0.188 70.08)oklch(0.828 0.189 84.429)
warning-foregroundoklch(0.279 0.077 45.635)same
infooklch(0.546 0.245 262.881)oklch(0.707 0.165 254.624)
info-foregroundoklch(0.97 0.014 254.604)oklch(0.282 0.091 267.935)
borderoklch(0.922 0 0)oklch(1 0 0 / 10%)
inputoklch(0.922 0 0)oklch(1 0 0 / 15%)
ringoklch(0.708 0 0)oklch(0.556 0 0)
scrimoklch(0 0 0 / 50%)same
chart-1 … chart-5oklch(0.87 0 0), 0.556, 0.439, 0.371, 0.269 (all achromatic)same
sidebar, sidebar-foreground, sidebar-primary, sidebar-primary-foreground, sidebar-accent, sidebar-accent-foreground, sidebar-border, sidebar-ringthe sidebar's own paletteits own dark set
  • The brand tint is five tokens: primary and its foreground (solid calls to action), accent and its foreground (hovered rows, highlighted menu items), and ring (the focus ring).
  • The status tones destructive, success, warning and info each have a foreground for text on their fill. They are separate from the tint, so re-branding does not recolour a warning. Toast icons use them.
  • danger is an alias for destructive, so you can make a message redder than a destructive button.
  • A tooltip inverts the page by default. Set the three tooltip tokens to give it its own colours.
  • Chart colours are the same in both schemes, so a series keeps its colour.

Control colours

ControlTokens holds the few colours where a control uses a different token in each scheme, not just a different value. They are part of the theme rather than a @media (prefers-color-scheme) rule, so they follow a fixed ColorScheme instead of the desktop setting.

Token (--zui-color-control-…)LightDark
ring-invaliddestructive at 20%destructive at 40%
destructive-filldestructivedestructive at 60%
ghost-hoveraccentaccent at 50%
outline-borderborderinput
outline-hoveraccentinput at 50%
switch-offinputinput at 80%
switch-thumbbackgroundforeground
switch-thumb-onbackgroundprimary-foreground
tab-inkforeground at 60%muted-foreground
tab-fillbackgroundinput at 30%
tab-bordertransparentinput

"At N%" means color-mix(in oklab, var(--zui-color-…) N%, transparent). Outlined buttons, toggles and fields have no fill at rest; they take the colour of the surface behind them.

Colour ramps

--zui-scale-neutral-1 … -12 and --zui-scale-accent-1 … -12. The semantic colours do not use the ramps; they are there for graded series and your own sheets.

StepsUse
1–2page and surface backgrounds
3–5component backgrounds: rest, hover, pressed
6–8borders: subtle, normal, hover
9–10solid fill, solid fill on hover
11–12text: normal and high contrast

The dark ramps are tuned to keep each step's contrast; they are not the light ramps reversed. accent-9 (#0090ff) is the same in both schemes.

Spacing and radii

Both scales are multiples of one base value, so one declaration re-spaces or re-rounds the whole interface: set --zui-space-base or --zui-radius-base.

TokenValueTypical use
--zui-space-base4pxthe unit
--zui-space-xsbase × 1icon to label
--zui-space-smbase × 2inside a dense control
--zui-space-mdbase × 3inside a normal control
--zui-space-lgbase × 4inside a surface, between groups
--zui-space-xlbase × 6between page sections
--zui-space-2xlbase × 8around page content
--zui-space-3xlbase × 12between major window regions
TokenValueTypical use
--zui-radius-base10pxthe unit
--zui-radius-none0pxsquare
--zui-radius-smbase × 0.6checkbox, dense badge
--zui-radius-mdbase × 0.8button, input, menu item
--zui-radius-lgbasecard, popover, dialog
--zui-radius-xlbase × 1.4sheet, drawer
--zui-radius-2xl, -3xl, -4xlbase × 1.8, 2.2, 2.6larger panels
--zui-radius-full9999pxpill or circle

The derived steps are calc() expressions over the base; none and full are fixed values.

Type

AxisTokensValues
family--zui-type-family-sans, -monoGeist, ui-sans-serif, system-ui, sans-serif; "Geist Mono", ui-monospace, SFMono-Regular, Menlo, monospace
size--zui-type-size-xs … -3xl12px, 14px, 16px, 18px, 20px, 24px, 30px
line height--zui-type-leading-xs … -3xl16px, 20px, 24px, 28px, 28px, 32px, 36px
weight--zui-type-weight-normal, -medium, -semibold, -bold400, 500, 600, 700
letter spacing--zui-type-tracking-tighter, -tight, -normal, -wide, -wider, -widest-0.05em, -0.025em, 0em, 0.025em, 0.05em, 0.1em

The size steps are xs, sm, md, lg, xl, 2xl and 3xl. Pair each size with the line height of the same name. Sizes are absolute pixels and independent of the spacing base, so larger text does not also enlarge every gap.

Shadows and motion

TokenUse
--zui-shadow-noneflat
--zui-shadow-2xshairline under an edge
--zui-shadow-xsslightly raised control
--zui-shadow-smcard
--zui-shadow-mdpopover, menu
--zui-shadow-lgdialog, sheet
--zui-shadow-xldragged item
--zui-shadow-2xlhighest
--zui-shadow-insetpressed-in well
TokenValue
--zui-motion-duration-none / -fast / -normal / -slow / -slower / -slowest0ms, 100ms, 150ms, 200ms, 300ms, 500ms
--zui-motion-ease-standardcubic-bezier(0.4, 0, 0.2, 1)
--zui-motion-ease-outcubic-bezier(0, 0, 0.2, 1)
--zui-motion-ease-incubic-bezier(0.4, 0, 1, 1)
--zui-motion-ease-linearlinear, for repeating animations

Next

On this page