Theme example
import { signal } from "@fierst/aster";
import { setTheme, THEME_PRESETS } from "./ui/theme";
import { Badge } from "./ui/badge";
import "./example.css";
export default function* Example() {
const selected = signal(THEME_PRESETS.findIndex((seed) => seed.id === "emerald"));
const seeds = THEME_PRESETS;
for (;;)
yield (
<section class="sample">
<header>
<h2>Edition accent</h2>
<p>Apply the next registry seed to this print label.</p>
</header>
<div class="split">
<Badge tone="primary">{seeds[selected()].label}</Badge>
<button
onClick={() => {
selected.set((selected() + 1) % seeds.length);
setTheme({ preset: seeds[selected()].id }, false);
}}
>
Change seed
</button>
</div>
<div class="ink-strip"></div>
</section>
);
}
@media screen and (prefers-reduced-motion: no-preference) {
#example button:is(.v-primary, .v-secondary):enabled {
transition: transform 120ms ease-out;
}
#example button:is(.v-primary, .v-secondary):enabled:active {
transform: scale(0.98);
}
}
@media (prefers-reduced-motion: reduce) {
#example button:is(.v-primary, .v-secondary):enabled:active {
transition: none;
transform: none;
}
}
* {
box-sizing: border-box;
}
:root {
--example-seed: var(--aster-primary);
--example-secondary-text: var(--aster-on-surface-subtle);
}
body {
--aster-primary: color-mix(in srgb, var(--example-seed) 84%, var(--aster-on-surface));
--aster-on-surface-subtle: color-mix(in srgb, var(--example-secondary-text) 84%, var(--aster-on-surface));
--aster-input-border: color-mix(in srgb, var(--aster-on-surface) 55%, var(--aster-surface));
margin: 0;
padding: clamp(0.8rem, 4vw, 1.5rem);
color: var(--aster-on-surface);
background: var(--aster-surface-muted);
font: 1rem/1.5 var(--aster-font-sans);
}
#example {
display: grid;
gap: 0.8rem;
min-width: 0;
align-content: start;
}
#example > button,
.sample > button {
justify-self: start;
}
.sample,
.tile {
background: var(--aster-surface);
border: 1px solid var(--aster-border);
border-radius: var(--aster-radius-lg);
}
.sample {
display: grid;
gap: 0.8rem;
padding: clamp(0.85rem, 3vw, 1.35rem);
box-shadow: var(--aster-shadow-xs);
min-width: 0;
}
.tile {
padding: 1rem;
min-width: 0;
}
h2,
h3,
p,
dl,
ul {
margin-block: 0;
}
h2,
h3 {
letter-spacing: -0.025em;
line-height: 1.2;
}
h2 {
font-size: 1.25rem;
}
h3 {
font-size: 1rem;
}
.sample > header,
.identity > div,
.receipt {
display: grid;
gap: 0.25rem;
}
.sample > header p,
.tile p,
small {
color: var(--aster-on-surface-muted);
}
small {
font-size: 0.82rem;
}
.split,
.actions,
.identity {
display: flex;
align-items: center;
gap: 0.65rem;
flex-wrap: wrap;
}
.split {
justify-content: space-between;
padding-block: 0.4rem;
border-bottom: 1px solid var(--aster-border);
}
.split:last-child {
border-bottom: 0;
}
.metric {
font-size: 2rem;
letter-spacing: -0.06em;
}
.facts {
display: grid;
grid-template-columns: max-content 1fr;
gap: 0.45rem 1rem;
}
.facts dt {
color: var(--aster-on-surface-muted);
}
.facts dd {
margin: 0;
font-weight: 600;
}
.type-sample {
font:
2rem/1.2 Georgia,
serif;
}
.listing {
padding-inline-start: 1.25rem;
}
.ink-strip {
height: 1.2rem;
background: var(--aster-primary);
border-radius: var(--aster-radius-sm);
}
.ink-proof {
display: grid;
gap: 0.15rem;
border-left: 0.6rem solid;
padding-left: 0.8rem;
}
.ink-proof strong {
font-size: 1.25rem;
letter-spacing: 0.06em;
}
.glyph {
display: inline-grid;
place-items: center;
width: 2rem;
height: 2rem;
border-radius: var(--aster-radius-sm);
color: var(--aster-on-primary-subtle);
background: var(--aster-primary-subtle);
}
.cover-box {
width: min(100%, 18rem);
}
.cover {
display: flex;
min-height: 7.5rem;
height: 100%;
padding: 1rem 1.25rem;
flex-direction: column;
justify-content: space-between;
gap: 1.6rem;
color: #fff;
background: repeating-linear-gradient(150deg, transparent 0 8px, #fff2 8px 9px), #204a48;
}
.cover strong {
font:
italic 2.45rem/1 Georgia,
serif;
}
.cover span {
font: 0.78rem var(--aster-font-mono);
}
.cover.grove {
background-color: #3d4b27;
}
.cover.dune {
background-color: #7c4428;
}
button:not([class]),
.entry {
font: inherit;
font-size: 0.875rem;
padding: 0.45rem 0.8rem;
border: 1px solid var(--aster-border-strong);
border-radius: var(--aster-radius-control);
background: var(--aster-surface);
color: var(--aster-on-surface);
}
button:not([class]) {
cursor: pointer;
font-weight: 600;
}
button:not([class]):hover:enabled {
background: var(--aster-primary-subtle);
}
button:disabled {
cursor: default;
}
:focus-visible {
outline: 2px solid var(--aster-primary);
outline-offset: 3px;
}
output:not(:empty) {
display: block;
color: var(--aster-on-primary-subtle);
font-weight: 600;
font-size: 0.9rem;
}
Site-owned component source and scoped styles
// AsterUI — Reactive Theme Controller & Cross-Browser Overlay Primitives
import { signal } from '@fierst/aster';
export type ThemeMode = 'system' | 'light' | 'dark';
export type ThemePreset = 'zinc' | 'blue' | 'emerald' | 'violet' | 'rose' | 'amber';
export type ThemeRadius = 'none' | 'sm' | 'md' | 'lg';
export type ThemeDensity = 'compact' | 'comfortable';
export interface ThemeConfig {
mode: ThemeMode;
preset: ThemePreset;
radius: ThemeRadius;
density: ThemeDensity;
customHue?: number;
}
export const THEME_PRESETS: readonly {
id: ThemePreset;
label: string;
hue: number;
swatch: string;
}[] = [
{ id: 'zinc', label: 'Zinc', hue: 285, swatch: '#18181b' },
{ id: 'blue', label: 'Blue', hue: 255, swatch: '#2563eb' },
{ id: 'emerald', label: 'Emerald', hue: 158, swatch: '#059669' },
{ id: 'violet', label: 'Violet', hue: 285, swatch: '#7c3aed' },
{ id: 'rose', label: 'Rose', hue: 16, swatch: '#e11d48' },
{ id: 'amber', label: 'Amber', hue: 55, swatch: '#d97706' },
];
export const themeState = signal<ThemeConfig>({
mode: 'system',
preset: 'blue',
radius: 'md',
density: 'comfortable',
});
function applyToRoot(cfg: ThemeConfig) {
if (typeof document === 'undefined') return;
const el = document.documentElement;
el.dataset.asterMode = cfg.mode;
el.dataset.asterPreset = cfg.preset;
el.dataset.asterRadius = cfg.radius;
el.dataset.asterDensity = cfg.density;
if (cfg.customHue !== undefined) {
el.style.setProperty('--aster-seed-hue', String(cfg.customHue));
if (cfg.preset === 'zinc') {
el.style.setProperty('--aster-seed-chroma', '0.20');
} else {
el.style.removeProperty('--aster-seed-chroma');
}
} else {
el.style.removeProperty('--aster-seed-hue');
el.style.removeProperty('--aster-seed-chroma');
}
}
export function setTheme(patch: Partial<ThemeConfig>, persist = true): void {
const next: ThemeConfig = { ...themeState.peek(), ...patch };
themeState.set(next);
applyToRoot(next);
if (persist && typeof window !== 'undefined') {
try {
window.localStorage.setItem('aster-ui-theme', JSON.stringify(next));
} catch {}
}
}
export function initTheme(defaults: Partial<ThemeConfig> = {}): ThemeConfig {
let saved: Partial<ThemeConfig> = {};
if (typeof window !== 'undefined') {
try {
const raw = window.localStorage.getItem('aster-ui-theme');
if (raw) saved = JSON.parse(raw);
} catch {}
}
const merged: ThemeConfig = { ...themeState.peek(), ...defaults, ...saved };
themeState.set(merged);
applyToRoot(merged);
return merged;
}
/**
* Cross-browser viewport-clamped anchor positioning for native `[popover]` elements.
* Resets UA `[popover]` `inset: 0; margin: auto` (preventing Safari collapse/stretch),
* flips cleanly above the trigger when bottom space is tight, and clamps within viewport.
*/
export function positionPopover(
trigger: HTMLElement | null | undefined,
pop: HTMLElement | null | undefined,
opts: { align?: 'start' | 'end'; gap?: number; matchWidth?: boolean } = {},
): void {
if (!trigger || !pop || typeof window === 'undefined') return;
const gap = opts.gap ?? 6;
const pad = 12;
const vw = window.innerWidth;
const vh = window.innerHeight;
const tr = trigger.getBoundingClientRect();
pop.style.position = 'fixed';
pop.style.inset = 'auto';
pop.style.right = 'auto';
pop.style.bottom = 'auto';
pop.style.margin = '0';
if (opts.matchWidth) {
pop.style.minWidth = `${Math.round(Math.min(tr.width, vw - pad * 2))}px`;
}
const pr = pop.getBoundingClientRect();
const pw = pr.width || 280;
const ph = pr.height || 220;
let left = opts.align === 'end' ? tr.right - pw : tr.left;
left = Math.max(pad, Math.min(left, vw - pw - pad));
const spaceBelow = vh - tr.bottom - gap - pad;
const spaceAbove = tr.top - gap - pad;
let top: number;
let maxH: number;
if (spaceBelow >= ph || spaceBelow >= spaceAbove) {
top = tr.bottom + gap;
maxH = Math.max(140, spaceBelow);
} else {
maxH = Math.max(140, spaceAbove);
top = Math.max(pad, tr.top - gap - Math.min(ph, maxH));
}
pop.style.left = `${Math.round(left)}px`;
pop.style.top = `${Math.round(top)}px`;
pop.style.maxHeight = `${Math.round(maxH)}px`;
}
/** Move focus among enabled menu items, including wrapping at either end. */
export function navigateMenu(event: KeyboardEvent): void {
const items = Array.from(
(event.currentTarget as HTMLElement).querySelectorAll<HTMLButtonElement>(
'[role="menuitem"]:enabled',
),
);
if (!items.length) return;
const index = items.indexOf(event.target as HTMLButtonElement);
let next: number;
switch (event.key) {
case 'Home':
next = 0;
break;
case 'End':
next = items.length - 1;
break;
case 'ArrowDown':
next = (index + 1) % items.length;
break;
case 'ArrowUp':
next = index <= 0 ? items.length - 1 : index - 1;
break;
default:
return;
}
event.preventDefault();
items[next].focus();
}
Choose a starting theme
Call initTheme() once in the browser entry before mounting. Its defaults are system mode, blue preset, medium radius and comfortable density. CSS works before JavaScript runs. For a specific first paint, render the corresponding attributes on the document root, for example <html data-aster-mode="dark" data-aster-preset="violet">. If your server knows the user's preferences, use the same values on both sides. The controller stores state in a module-level signal, so keep per-request preferences in the rendered HTML during SSR.
| Preset | Seed hue | Seed chroma |
|---|---|---|
| zinc | 285 | 0.006 |
| blue | 255 | 0.20 |
| emerald | 158 | 0.16 |
| violet | 285 | 0.20 |
| rose | 16 | 0.20 |
| amber | 55 | 0.18 |
THEME_PRESETS supplies each preset's id, display label, hue and swatch for a picker. The zinc preset has explicit monochrome primary roles. Use a chromatic preset as the base for a custom accent.
Switch and remember preferences
import { THEME_PRESETS, initTheme, setTheme, themeState } from './ui/theme';
initTheme({ preset: 'emerald' }); // A saved preference takes precedence.
export function* ThemePicker() {
for (;;) {
const current = themeState();
yield (
<fieldset>
<legend>Appearance</legend>
{(['system', 'light', 'dark'] as const).map((mode) => (
<button
type="button"
aria-pressed={current.mode === mode}
onClick={() => setTheme({ mode })}
>
{mode}
</button>
))}
{THEME_PRESETS.map(({ id, label }) => (
<button
type="button"
aria-pressed={current.preset === id && current.customHue === undefined}
onClick={() => setTheme({ preset: id, customHue: undefined })}
>
{label}
</button>
))}
</fieldset>
);
}
}system follows the OS via prefers-color-scheme, including later OS changes. Explicit light and dark modes override it. setTheme(patch) merges fields, updates the signal and root attributes, and writes the entire configuration to local storage under aster-ui-theme. setTheme(patch, false) applies a temporary change. The next persisted change saves the then-current configuration. Use themeState() for reactive reads and themeState.peek() for snapshots. Apply changes through setTheme so the DOM and storage stay in sync.
initTheme(defaults) merges current state, supplied defaults, then saved values and returns the result. Storage access and JSON parse failures are tolerated. To restore factory settings and remember them, call setTheme({ mode: 'system', preset: 'blue', radius: 'md', density: 'comfortable', customHue: undefined }).
Build a custom theme
For a user-selected accent, supply a numeric hue in degrees. Clearing customHue restores the preset seed. Radius options are none, sm, md, and lg (control radii 0, 6, 8 and 12 px). Density options are compact (0.9) and comfortable (1). Coarse pointers use dedicated control sizes.
setTheme({ preset: 'blue', customHue: 205, radius: 'lg', density: 'compact' });For a named brand, add an application stylesheet after the theme import. The library defines its defaults in CSS cascade layers. Keep your brand rules unlayered. Put the seed on the root where the derived tokens are computed. Give your brand its own attribute, leaving the typed preset field available to the controller.
:root[data-brand='lagoon'] {
--aster-seed-hue: 205;
--aster-seed-chroma: 0.14;
--aster-neutral-tint: 0.006;
--aster-font-sans: system-ui, sans-serif;
}setTheme({ preset: 'blue', customHue: undefined });
document.documentElement.dataset.brand = 'lagoon';
// Return to the selected built-in preset:
delete document.documentElement.dataset.brand;Persist the application-owned brand separately if users can select it. A controller-set custom hue is an inline CSS property and takes precedence over stylesheet seeds. To add a preset to your owned copy itself, extend ThemePreset, add its id/label/hue/swatch to THEME_PRESETS, and add its :root[data-aster-preset='…'] seed rules in theme.css.
Use semantic roles in app CSS, for example background: var(--aster-surface) and color: var(--aster-on-surface). The seed drives OKLCH-derived roles where supported. The stylesheet also defines static sRGB fallbacks. For an exact brand color across browsers override the semantic roles directly, including hover, foreground, subtle fill/ink, border and focus ring. Provide dark values for both explicit dark mode and system dark mode. Verify contrast, focus, disabled controls and chart labels under each mode. Individual components can also define local styling; edit their owned source for exceptions.
The shared stylesheet defines global box sizing, body colors and typography, modal scroll locking and popover surfaces. It adjusts borders for increased contrast, transition durations for reduced motion, and touch control sizes for coarse pointers. Open the theme reference for the token inventory, or inspect the theme manifest for the CSS and controller source in this release.