@var-ui/core
v0.1.1
Published
Framework-agnostic design tokens and component styles for var-ui
Downloads
667
Readme
@var-ui/core
Framework-agnostic design tokens and recipes used by the docs site, @var-ui/react, and example apps.
This is a library package (not a standalone app). Import it from apps or the docs site; styles register as side effects when modules load.
Quick start
import {
button,
layout,
layoutUtility,
text,
designTokens,
defaultThemeClassName,
} from '@var-ui/core';
// Register styles at build time via `@var-ui/core/styles` (see TypeStyles setup below).
document.body.className = defaultThemeClassName; // `theme-var-ui-default`
element.className = button({ intent: 'primary' });
// `layout` — multi-pane page shell recipe; `layoutUtility` — legacy docs stack/section helpersCustom themes return a DesignTheme from createDesignTheme({ name: 'acme' }) — use
theme.className the same way. See Theme surfaces.
TypeStyles extraction
Add a build entry that side-effect-imports the styles bundle, then point
@typestyles/vite at it:
// typestyles-entry.ts
import '@var-ui/core/styles';
// Optional: custom theme presets and app-owned styles.component() modules
import './acme-theme';// vite.config.ts
import typestylesVite from '@typestyles/vite';
export default defineConfig({
plugins: [typestylesVite({ extract: { modules: ['typestyles-entry.ts'] } })],
});@var-ui/core/styles registers every component recipe, base HTML styles, layout
utilities, and the built-in default theme surface. For tree-shaken fixture apps that
only use a few components, import the recipes you need instead (see
examples/bundle-fixtures).
Syntax highlighting is app-owned: use color.code tokens and wire them to your
highlighter (see Syntax highlighting below).
See examples/vite-app and examples/astro-app for full workspace setups.
Key exports
| Area | Exports |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| Themes | createDesignTheme, disposeDesignTheme, DEFAULT_THEME_NAME, defaultThemeClassName, SURFACE_ATTRIBUTE, mergeThemeOverrides |
| Tokens | designTokens, tokens, tokenValues, generateColors, lightSyntaxValues, darkSyntaxValues |
| Customization | extendTokens, when, themeWhen, themeableComponents, defineFonts, groteskMono |
| TypeStyles | typestyles, styles, global |
| Types | DesignTheme, DesignThemeConfig, DesignThemePreset, ThemeComponentsConfig, OverrideConfigFor, … |
Recipe inventory
Every recipe follows the c.vars() override contract and
emits stable public class names.
| Category | Recipes |
| -------------- | ------------------------------------------------------------------------------------------------------------------ |
| Actions | button, linkButton, link |
| Data input | textField, textAreaField, checkbox, radio, switchStyles, select, field (+ fieldChrome helper) |
| Feedback | alert, banner, badge, spinner, skeleton, progressBar, statusDot |
| Layout | stack, grid, section, center, aspectRatio, divider, layout (shell), layoutUtility/text utilities |
| Content | heading, textBlock, kbd, emptyState, codeBlock, proseContent, steps, fileTree |
| Containers | card, carousel, thumbnail, avatar, avatarGroup |
| Overlay | dialog, overlay, commandPalette, tabs |
| Icons | icon recipe + IconName union / iconNameList (glyphs live in @var-ui/icons) |
Token layers
Tokens are declared once via tokens.declare(tokenSchema) and exposed as designTokens
(aliases: tokens). Default values live in tokenValues; the built-in theme surface
registers them on package load.
| Export | Role |
| -------------- | -------------------------------------------------------------------- |
| designTokens | All registered token refs (palette, space, color, stroke, …) |
| tokens | Alias for designTokens (the tokens.declare handle) |
| tokenValues | Default registered values (DesignThemePreset.tokens base) |
Token namespaces (expanded)
| Namespace | Keys (indicative) | Notes |
| ---------------------------- | --------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| palette | 39 families × 10 steps | Fixed primitive ramp |
| space | 0–20 (non-contiguous) | Layout spacing |
| size.control / size.icon | sm, md, lg | Control heights + icon box |
| breakpoint | sm–xl | Mode-invariant media-query widths |
| zIndex | base … max | Stacking scale |
| opacity | disabled, muted | Shared opacity semantics |
| letterSpacing | tight, normal, wide, caps | Typography rhythm |
| color.* | semantic UI colors | Full tree via tokens.declare; default light face in tokenValues.color, dark patches via colorMode |
| color.code | syntax-highlighting palette | Semantic groups for app-owned highlighter wiring; aliases lightSyntaxValues / darkSyntaxValues for theme presets |
| shadow.elevation | low, med, high | Soft elevation (alongside brutalist shadow.xs–xl) |
| stroke | default, strong | Border shorthand (fixed) |
Theme overrides example:
createDesignTheme({
tokens: {
size: { control: { md: '36px' } },
zIndex: { toast: 600 },
color: {
background: { popover: designTokens.color.palette['sand-1'] },
},
},
});Non-goals: no tokens.components.*, chart/data palette, or Astryx-style communication hue tables — recipes compose global color.* instead.
Theme values accept token-ref leaves: raw CSS ('#0064E0', '16px') or refs into registered tokens (designTokens.color.palette['sky-7'], designTokens.radius.lg). Refs stringify to var(--var-ui-…) in emitted CSS.
Note: syntax-highlighting colors live under color.code (--var-ui-color-code-*), not a
top-level syntax namespace. There is no codeBlock token namespace — the codeBlock recipe
reads semantic color.* plus Tier 1 c.vars().
Theme surfaces
Themes are thin wrappers around TypeStyles tokens.createTheme. Class names use the
configured scope: theme-var-ui-<name> (e.g. theme-var-ui-default).
Runtime themes
createDesignTheme is supported in the browser. Calling it again with the same name
replaces the surface (theme editors). disposeDesignTheme(name) unregisters it.
@typestyles/vite extract still covers recipes + the default theme. User-authored
themes inject at runtime.
Default theme
Import @var-ui/core/styles in your typestyles extraction entry to register the
built-in default surface (createDesignTheme({ name: 'default' })). Use the class name
directly at runtime:
| Export | Value | Role |
| ----------------------- | ------------------------ | -------------------------------------------- |
| DEFAULT_THEME_NAME | 'default' | Built-in theme name |
| defaultThemeClassName | 'theme-var-ui-default' | Class for the pre-registered default surface |
Additional palette themes (forest, rose, amber, Windows 95, …) are not bundled exports —
copy examples from docs/src/themes/ in the docs repo.
Authoring a theme
createDesignTheme merges a preset, token patches, ambient color mode, and optional
component overrides:
from— optionalDesignThemePreset({ tokens?, colorMode?, fonts? }); defaults to built-intokenValues+ dark color modetokens— mode-invariant overrides (lightcolorface lives here by default)colorMode— ambient{ light?, dark? }color patches (compiled tolight-dark())generateColors— optional helper to build{ light, dark }color trees from an accentmodes/extend/components/fonts— extra TypeStyles modes, custom tokens, typed recipe overrides,@font-facerules
import {
createDesignTheme,
designTokens,
generateColors,
tokenValues,
type DesignThemePreset,
} from '@var-ui/core';
// Reusable preset (spread into createDesignTheme)
export const acmePreset: DesignThemePreset = {
tokens: {
color: {
accent: {
default: designTokens.color.palette['sky-7'],
hover: designTokens.color.palette['sky-8'],
},
},
radius: { md: designTokens.radius.lg },
},
};
// Accent-generated color mode
const { light, dark } = generateColors({ accent: '#7c3aed' });
export const acmeTheme = createDesignTheme({
name: 'acme',
from: acmePreset, // optional; built-in defaults apply when omitted
colorMode: { light, dark },
components: {
button: (t) => ({
base: { borderRadius: t.radius.lg.var },
}),
},
});
// acmeTheme.className → `theme-var-ui-acme`What createDesignTheme compiles to
typestyles.tokens.createTheme(name, {
base: { ...mergedModeInvariantTokens, color: lightColor },
colorMode: {
light: { color: mergedLightColorPatch },
dark: { color: mergedDarkColorPatch },
},
modes: [...extraModes],
});
// Optional per-recipe overrides:
styles.override(recipe, overrideConfig, {
selectorPrefix: `.${theme.className}`,
layer: 'overrides',
});Each return value is a DesignTheme: ThemeSurface (className, name, string coercion)
plus tokens (built-in refs merged with any extend namespaces).
Ambient light / dark mode
Dark overrides follow OS preference unless data-mode="light" or data-mode="dark" is set on
the same element that carries the theme class. Only the color tree (including
color.code) flips; radius, fontSize, etc. stay on base.
Fixed-tone surfaces (SURFACE_ATTRIBUTE)
Import SURFACE_ATTRIBUTE ('data-surface') from @var-ui/core. Global color-scheme
rules for data-surface="light" and data-surface="dark" are registered in runtime.ts
on package load — no theme option required.
Mark a subtree to pin light or dark chrome regardless of ambient mode:
<div class="theme-var-ui-default" data-mode="light">
<article data-surface="dark" class="var-ui-card-root">…</article>
</div>Keep wrappers scoped tightly — nested subtrees cannot "reset" to ambient mode without an explicit opposite surface marker.
Note:
surfacesonDesignThemeConfigis deprecated and has no effect. UseSURFACE_ATTRIBUTEmarkers and the global rules above instead.
Astro (no React context)
Use a tiny inline script to set one palette class on document.documentElement and data-mode for light/dark/system:
---
import { defaultThemeClassName } from '@var-ui/core';
---
<script is:inline define:vars={{ themeClass: defaultThemeClassName }}>
const key = 'theme-mode';
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
const stored = localStorage.getItem(key);
const mode =
stored === 'light' || stored === 'dark' || stored === 'system'
? stored
: prefersDark
? 'dark'
: 'light';
document.documentElement.classList.add(themeClass);
if (mode === 'system') {
document.documentElement.removeAttribute('data-mode');
} else {
document.documentElement.setAttribute('data-mode', mode);
}
</script>import.meta.env.SSR stays irrelevant: the snippet runs in the browser only. Swap
defaultThemeClassName for another theme's className when you change brand themes.
Theming helpers
Prefer createDesignTheme with an optional from preset. Use generateColors when you want
an accent-generated color tree:
import { createDesignTheme, generateColors, tokenValues } from '@var-ui/core';
const { light, dark } = generateColors({ accent: '#7c3aed' });
export const acme = createDesignTheme({
name: 'acme',
from: { tokens: tokenValues }, // optional; this is the implicit default
colorMode: { light, dark },
});generateColors returns { light, dark } (DesignColorValues patches, including code).
That shape plugs straight into colorMode. For advanced merges, mergeThemeOverrides is
available (aliased as deepMergeThemeOverrides) — it is not a second theme API. Use extend / components for custom tokens and
typed recipe restyles via styles.override.
Authoring recipes
Component recipes expose themeable surface colors (background, border, foreground) as
component-scoped CSS custom properties via c.vars() in the recipe callback:
- Register colors with
{ value, syntax: '<color>' }(seebutton.ts). - Use
v.background.var(etc.) in base styles; assign variants with[v.background.name]: tokenValue. - Layout, spacing, and type scale stay as direct token references unless a theme need appears.
This is the primary override surface (Tier 1) — values inherit through nested .theme-*
boundaries without @scope or extra cascade tricks.
Customizing components
Tier 1 — component-scoped CSS variables (preferred)
Override a recipe's registered vars in theme CSS or createDesignTheme overrides. Example
for buttons on a custom theme:
.theme-var-ui-acme .var-ui-button {
/* component-scoped vars from c.vars() — exact names match the recipe */
--var-ui-button-background: var(--var-ui-color-accent-default);
--var-ui-button-foreground: var(--var-ui-color-text-on-accent);
}Tier 2 — plain CSS against semantic class names
When a property was not exposed as a var, target the public class name directly. For a single theme region, a later cascade layer wins:
@layer utilities {
.theme-var-ui-acme .var-ui-card-root {
box-shadow: var(--var-ui-shadow-lg);
}
}Tier 2 — nested conflicting themes (styles.scope())
When two theme regions nest and both override the same component, use TypeStyles'
styles.scope() so proximity — not source order — decides the winner (@scope requires
Chrome 118+, Firefox 128+, Safari 17.4+):
import { styles } from '@var-ui/core';
styles.scope({ root: '.theme-var-ui-windows-95', layer: 'utilities' }, 'button-base', {
borderColor: 'var(--color-border-strong)',
backgroundColor: 'var(--color-background-subtle)',
});See TypeStyles theming docs for engine details.
Public class name contract
Semantic class names emitted by styles.component() / styles.class() in this package are
public API. Consumers may target them with plain CSS or styles.scope(). Renaming a
namespace or variant key is a semver-major change for @var-ui/core.
Guard accidental renames with a committed snapshot:
cd packages/core
pnpm exec typestyles snapshot --writeAdding class names is free; removing or renaming requires a major bump and a deliberate
snapshot --write. CI enforces this via @typestyles/no-removed-public-classname.
Extending tokens safely
- New primitive or semantic keys — Add values under
src/tokens/, extendDesignTokens/DesignThemeTokenValues, and include them intokenSchema+tokenValues. - Theme-level patches — Prefer
createDesignTheme({ from, tokens, colorMode, modes }). Code-block chrome uses Tier 1c.vars()/components, not a dedicated token namespace. - Breaking renames — Avoid renaming existing CSS custom properties; add aliases if you must migrate consumers gradually.
CodeBlock copy helper pattern
Use the codeBlock recipe with data-* hooks so any framework (or vanilla JS) can attach clipboard behavior:
<div class="...codeBlock('root')" data-codeblock>
<div class="...codeBlock('header')" data-codeblock-header>
<div class="...codeBlock('actions')">
<button
type="button"
class="...codeBlock('copyButton') ...codeBlock('copyButtonIdle')"
data-codeblock-copy
data-copy-label="Copy code"
data-copied-label="Copied"
aria-label="Copy code"
>
Copy
</button>
<span
class="...codeBlock('feedback') ...codeBlock('feedbackInline')"
data-codeblock-feedback
role="status"
aria-live="polite"
></span>
</div>
</div>
<pre><code>...</code></pre>
</div>Minimal behavior:
- On
[data-codeblock-copy]click, read text from the closest code element and write tonavigator.clipboard. - Toggle
data-copiedordata-erroron the button for visual state styles. - Set button
aria-labeltoCopiedon success, and restore toCopy codeafter a timeout. - Announce status text through
[data-codeblock-feedback](role="status"+aria-live="polite").
Syntax highlighting
var-ui defines semantic color.code tokens (--var-ui-color-code-*) but does
not ship highlighter-specific CSS. Map those variables to whatever toolchain you use
(highlight.js selectors, a Shiki theme, Prism, etc.) so highlighted output matches
your design system in light and dark mode.
lightSyntaxValues / darkSyntaxValues are aliases for theme presets.
| Token | Meaning |
| --------------------------------- | ---------------------------------------------------- |
| base | Default foreground |
| keyword | Keywords, types, language_* |
| title | Titles, class names, function names |
| attr | Attributes, numbers, operators, variables, selectors |
| string | Strings, regexps |
| builtIn | Built-ins, symbols |
| comment | Comments, doc formulas |
| name | XML tags, pseudo-selectors |
| section | Headings |
| bullet | List bullets |
| addition / additionBackground | Diff additions (foreground / wash) |
| deletion / deletionBackground | Diff deletions (foreground / wash) |
Defaults ship in tokenValues.color.code (light face) and the built-in dark colorMode
patch. Override via theme colorMode or a from preset's tokens.color / colorMode.dark.
The documentation site includes a reference highlight.js
mapping in docs/src/styles/codeHighlight.ts.
Learn more
@var-ui/react— React wrappers for these recipes- Design system guide — patterns for building your own
- Documentation site — primary consumer of this package
Prose / docs content primitives (proseContent)
Long-form markdown helpers live in proseContent from @var-ui/core. Put proseContent('root') on the element that wraps rendered HTML.
Covered primitives:
| Primitive | Markdown / HTML | Notes |
| ----------------- | ---------------------------------- | -------------------------------------------------------------------------- |
| Blockquote | > … | Tinted panel + accent border |
| kbd | <kbd>Ctrl</kbd> | Keyboard cap styling |
| Badge | <span data-docs-badge>New</span> | Optional data-docs-badge-tone: success, warning, danger, info |
| Table | GFM tables | For wide tables wrap with <div class="…proseContent('tableWrap')"> |
| Divider | --- → <hr> | Themed horizontal rule |
| Heading links | h1–h6 | Apps can inject <a data-prose-heading-anchor> permalinks (see docs site) |
Docs site composes proseContent('root') with site overrides and passes a custom
createDesignTheme surface so semantic --var-ui-color-* tracks the shell.
Admonition-style callouts (markdown-only)
GFM does not have native admonitions. Options:
Alertrecipe — Prefer Astro/React components (alert+Alert.astro/Alert.tsx) forinfo|success|warning|danger|tipwith solid/subtle modes.Blockquote convention — Use a leading label line:
> **Note** > Short supporting copy in plain markdown.Style tweaks for
blockquote > p:first-child strongcan be added in your app if you want label colors per keyword.Raw HTML —
<div data-alert …>is not defined; use thealert()classes from the design system or the component wrappers above.
