Mixins / foldkit-mixins
Style: appearance as data
Style is pure data. It never touches the DOM.
Every piece takes Declarations: camelCase CSS properties (typed by
csstype) and custom properties, each a
string. A misspelled or kebab-case property in an object literal is a type
error; the compiler writes the kebab-case name. Values are not checked, so
var(...) and light-dark(...) pass through.
Wherever a slot's piece is taken (forSlots, slots, forCapability, a
recipeFor definition) and in compose, when, whenInput and perItem, a
piece may also be written short: a declarations object means
Style.self(declarations), a list means Style.compose(...list), and {} is
Style.empty. So [Style.class('card'), { padding: '1rem' }] is
Style.compose(Style.class('card'), Style.self({ padding: '1rem' })). A
StyleValue carries a brand, so a declarations object is never mistaken for
one.
| Primitive | Meaning |
|---|---|
Style.class(...) | Class tokens |
Style.inline({...}) | Inline declarations |
Style.compose(...) | Concatenate classes; later declarations win per property |
Style.when(condition, piece) | Apply a piece when an authoring-time boolean holds |
Style.whenInput(predicate, piece) | Apply a piece from the view input at render time |
Style.recipe({ base, variants, defaults, compound }) | Single-slot factory returning selection => StyleValue |
Style.recipeFor(Slots)({ base, variants, defaults, compound }) | Multi-slot recipe with .style, .extend, and .add |
Style.perItem(item => piece) / Style.stagger({ stepMs }) | Per-item style piece; stagger sets --fk-index delay |
Style.forCapability(Slots)(capability, piece) | Attach one piece to every public slot matching a capability |
Style.slots(pieces, options?) / Style.slot(slotOptions, piece) | Declare an app's Slots directly from its style ({ slots, style }) |
Style.install(css) | Append a <style> element in <head> once for css |
Style.self / pseudo / media / supports / container / nest | Rule-based styles scoped to the slot's class (&) |
Style.keyframes / global | Class-independent CSS rules |
Theme.define / Theme.ref(theme) / variables | Typed tokens, var(--fk-*) refs, and inline CSS variables |
Theme.lightDark(light, dark) / Theme.compose(base, over) | Color-scheme light-dark() tokens and merged themes |
Theme.root(theme, { omit?, colorScheme? }) / Theme.scoped(...) | Emit :root or scoped CSS custom properties (foldkit-mixins/theme) |
Theme.schemeScript / chooseScheme / currentScheme | Head script and Effect to apply and persist light/dark |
Theme.knobScript / Theme.chooseKnobs | Head script and Effect to apply and persist knob overrides |
Theme.make / Theme.standard / Theme.fluidType | Build theme knobs, expand standard tokens, or scale fluid type |
Theme.tokens / Theme.breakpointWidths(theme) | Standard scale tokens and pixel widths (foldkit-mixins/theme) |
Layers.define(names) / Layers.standard | Typed CSS @layer order (foldkit-mixins/layers) |
Style.stylesheet(...) | Combine NamedStyles and global CSS into one <style> block |
For multi-slot recipes, Style.recipeFor lets a variant slot omit or null-unset a defaulted piece, .extend(patch) layers adjustments onto existing axes, .add(more) defines new axes or values (A look a shipped recipe lacks), and .style(selection?, options?) resolves Style.forSlots(Slots)(recipe(selection), options) in one call.
Theme.tokens ships the standard spacing, type, reading, radius, motion, width, border, shadow, and breakpoint scales, plus icon (default 2px Heroicons outline masks, replaceable via Icons.tokens(pack)), safe (env(safe-area-inset-*) when viewport-fit=cover is set), and overlay.scrim (a 45% backdrop veil over the page's base). Layers.standard declares reset, tokens, theme, defaults, components, layouts, variants, utilities, app; Layers.in(name, piece) wraps unlayered CSS in a layer (raising style:relayered if a piece already lives in another layer), and Style.stylesheet hoists the layer order first (raising style:conflicting-layer-order on mismatched orders and style:unlayered-rule on unlayered rules).
A selection is a plain object of pieces. A base slot needs no fallback when one recipe's look goes on
another element (Recipes.Button({ tone: 'neutral' }).button), and leaving a piece out of one use
is destructuring:
import { DialogSlots, Recipes } from 'foldkit-mixins-ui'
const { closeButton: _corner, ...dialogPieces } = Recipes.Dialog({ size: 'sm' })
const PlainDialogStyle = Style.forSlots(DialogSlots)(dialogPieces)Leaving out a style does not leave out the element: the view still draws the close button wherever
it puts dialog.closeButton, now without the recipe's look.
Rule-based Style compiles to one deterministic class (an FNV-1a hash of canonical rule text) plus CSS as data:
const CardStyle = Style.forSlots(FieldSlots)({
root: Style.compose(
Style.class('card'),
Style.pseudo(':hover', { boxShadow: '0 1px 2px' }),
Style.media('(min-width: 40rem)', { gridTemplateColumns: '1fr 1fr' }),
),
})
CardStyle.css
Style.stylesheet(FieldStyle, CardStyle)Equal rules share a class, so server and client derive the same class and CSS. A rule piece
inside Style.whenInput compiles to its class like any other; the class is static and only its
presence follows the input, and its CSS is in Style.stylesheet whether or not the condition
ever holds. Drawn, it is injected like any other class.
Prefer rule pieces for a state. An inline shorthand beside a conditional inline
longhand of it (an inline border and a whenInput borderColor, either way
round) is refused when the style is defined, with
mixins:inline-shorthand-conflict: the renderer drops a property by clearing
it, so clearing borderColor also cleared the color border set, and the
element kept a currentColor border after the state ended.
An inline declaration beats every rule, layers included, so a conditional rule for the same
property in the same composition never applies: Style.compose(Style.inline({ padding: '1.75rem' }),
Style.media('(max-width: 30rem)', { padding: '1rem' })) is refused when composed, with
mixins:dead-conditional-rule naming the property, the condition and the fix, which is to put the
base in Style.self. It is a development-time check, like mixins:inline-shorthand-conflict
beside it: Vite folds import.meta.env.DEV away in a production build, so neither check nor its
text reaches a page (a build without Vite's import.meta.env skips them too). A media, pseudo, nest, container, supports or states rule, and a rule inside
whenInput, counts, as does a shorthand against its longhand (padding and paddingInline, either
way round); a rule marked !important beats inline and passes. An inline declaration that exists
only when the view chooses it or per item is not known when the style is defined, and two Styles
attached to one slot meet only as classes and inline text, so neither is checked.
Beyond self, pseudo, media, supports, container and nest, the rule pieces are:
Style.states({ open: { opacity: '1' } })compiles to&[data-state="open"], for Behaviors that writedata-state;whenInputwhen the view knows,stateswhen the DOM does;Style.responsive(breakpoints, { md: { display: 'flex' } }), named breakpoints from the record you pass, so a misspelled one is a type error; a breakpoint is a media query or a whole at-rule, such as'@container page (min-width: 48rem)';Style.at('@container builder (max-width: 40rem)', Style.pseudo('[data-open="false"]', { … }))puts a piece's rules inside an at-rule, where no one constructor does; a class, a piece chosen when drawn, global CSS or a rule already inside an at-rule throws there;Style.enter({ opacity: '0' }), a@starting-stylerule the element animates from, withStyle.allowDiscretewhendisplaytakes part;Style.vars({ '--gap': '1rem' })andStyle.viewTransitionName('hero'), declarations;Style.grid({ areas: [['header', 'header'], ['nav', 'main']], columns, rows, gap }), a grid template with typed areas:.stylefor the container and.area('main')for a child, where a name the template lacks is a type error and a ragged template raisesmixins:ragged-grid-areas. Both are rules, not inline declarations, so a later layer can override the template;Selector.attr,not,is,child,descendant,sibling,siblingsbuild the selector stringspseudoandnesttake. Each takes a selector list: every top-level selector is scoped to the class (:is(a, b)is not split), and a selector that writes&places the class itself (nest('[data-open] &')).
A look a shipped recipe lacks
A recipe from a design system has the axes and values its author chose. An application changes it in two ways, and neither forks it:
.extend(patch)adjusts what the recipe has: more pieces on its base or on one of its values, another default, another compound. An axis or a value the recipe lacks is a type error there, so a misspelt axis cannot become a new one..add(more)gives it what it lacks: a value on an axis it has, or a new axis. A value the axis already has is refused, in the type and withmixins:recipe-value-exists.
Both return a recipe, so .extend, .add, .style and a null selection work on the
result, and neither changes the recipe it was called on.
import { Capability, Slot, Slots, Style } from 'foldkit-mixins'
const ButtonSlots = Slots.define({
button: Slot.make({ capability: Capability.Interactive }),
})
// What a design system ships.
const Button = Style.recipeFor(ButtonSlots)({
base: { button: Style.self({ borderRadius: '6px' }) },
variants: {
tone: {
accent: { button: Style.self({ background: 'royalblue', color: 'white' }) },
neutral: { button: Style.self({ background: 'gainsboro' }) },
},
},
defaults: { tone: 'accent' },
})
// What an application adds: a tone the recipe has no word for, and a new axis.
const AppButton = Button.add({
tone: { brand: { button: Style.self({ background: 'rebeccapurple', color: 'white' }) } },
width: { full: { button: Style.self({ inlineSize: '100%' }) } },
})
// `.style` selects and makes the view's Style in one call; `.style()` is the defaults.
export const Brand = AppButton.style({ tone: 'brand', width: 'full' })
export const Accent = AppButton.style()
// The same in two calls, for when the pieces are composed first.
export const Spelled = Style.forSlots(ButtonSlots)(AppButton({ tone: 'brand', width: 'full' }))
// @ts-expect-error `accent` is the recipe's own: adjust it with `extend`.
Button.add({ tone: { accent: { button: Style.self({ background: 'navy' }) } } })
// @ts-expect-error `extend` adds no axis.
Button.extend({ variants: { width: { full: { button: Style.self({ inlineSize: '100%' }) } } } })An added axis has no default: AppButton() above is the recipe as shipped. Give it one with
AppButton.extend({ defaults: { width: 'full' } }). The values are style pieces like any
recipe's, so a module that calls add is still one the build can
ship as data.
Themes as typed knobs
foldkit-mixins/theme extends the root Theme with the pieces a page ships. A theme is a typed
set of knob values: only what it changes, every other knob at its default.
Theme.make checks each value against its knob (Knobs.standard, grouped by concern: accent,
surface, state, shape, type, icon, motion, shadow, menu, feedback, code,
chart, scales),
so a misspelt knob or a choice outside its options is a type error and a number out of its range
throws where the theme is made. A theme is pipeable: Theme.set changes some knobs, and
Theme.describe gives it a title and a description for a list of themes.
import { Layers } from 'foldkit-mixins'
import { Theme } from 'foldkit-mixins/theme'
const cobalt = Theme.make({
accent: { hue: 235, chroma: 0.225, lightness: 55 },
surface: { saturation: 0, contrast: 24 },
shape: { radius: 1.8, density: 1.1, controls: 'pill' },
menu: { panel: 'inverted' },
}).pipe(Theme.describe({ title: 'Cobalt' }))
const cobaltDense = cobalt.pipe(Theme.set({ shape: { density: 0.9 } }))
const sheet = Style.stylesheet(
Layers.standard.declare,
Layers.standard.in('theme', Theme.root(Theme.standard(cobaltDense))),
)Theme.make writes nothing itself: Theme.variables(theme) is the knob variables it declares
(the values it sets, and each unset knob's default or the expression it follows, such as the
neutrals following the accent's hue), and Theme.standard(theme) is every shipped token with
them, which Theme.root declares: the derivations are the same CSS for every theme, so a theme is
only its knobs. A knob of an
application's own is a Knob kind (Knob.number, percent, length, angle, choice,
font, schemed), and Theme.make(knobs, values) takes a set of them. Every knob is a variable, choices
too: an option is the CSS its variables hold, so shadow.relief: 'bevel' writes the bevelled
shadow lists and motion.easing: 'spring' writes the spring curve, and each switches at runtime
as a number does.
Each knob carries a title, a description and its default, so a control can be drawn from
it; Knobs.schema(Knobs.standard) is the Schema of a theme's values (a Model field, a decoded
URL), Theme.print(theme) writes a theme's Theme.make({ … }) source, only the knobs that differ
from their defaults, and Theme.fonts names the font stacks a type.body knob may take. An editor
reaches a knob by its path, typed by it: Knobs.paths(knobs) lists them, Knobs.at(knobs,
'shape.radius') is the knob, and Knobs.valueAt and Knobs.withValue read and set one value of a
theme, checked by its knob; a schemed knob's light and dark are knobs of their own, each with its
range. /create is drawn this way.
Type is still by default. type.fluid (0 to 1) says how much larger every size grows between
type.viewportMin and type.viewportMax: 0 is today's fixed scale, 1 uses the whole range,
and the growth is larger the further a step stands above the body. The fluid token group is
ratio (the viewport's place in that range, 0 to 1) and progress (that place at the theme's
strength); Theme.fluidType({ min, max }) writes the same blend for one value, so a heading reads
its size from the page's range instead of a clamp() with a vw in it. A range of its own is
Theme.fluidType({ min, max, viewport: { min: '500px', max: '1000px' } }).
Reading is its own group: reading.measure is a length in ch (65 by default) that caps
Prose and the body, lead and quote levels of Typography; reading.headingWrap and
reading.bodyWrap choose balance, pretty or wrap; and reading.align is start,
center, end or justify. Prose.style({ measure, align }) still overrides them for one
container.
A frame narrower than the window measures its own width: Theme.containerFluidProgress() is
the progress of the nearest container-type: inline-size ancestor, for setting
--fk-fluid-progress on its contents, and Theme.fluidType({ min, max, container: true })
uses it directly. /create's previews and the CMS hero are drawn this way.
Typography's display, title and subtitle grow with the same progress, their leading
growing with their size: Theme.role('display', { fluid: true }). The interface roles
body, caption and micro stay on the control ladder, so a button's or a field's words do
not outgrow its height.
Themes are installed by name, the names being a record's keys:
import { Schema } from 'effect'
import { AppStyle } from 'foldkit-mixins/app'
import { Themes } from 'foldkit-mixins/theme'
const themes = Themes.make({ cobalt, cobaltDense }, { initial: 'cobalt' })
const { t, stylesheet } = AppStyle.make({ themes })
const Model = Schema.Struct({ theme: themes.Name })The root declares the palette's derivations with the initial theme's knobs, and each other theme
writes only its knobs under :root[data-theme="name"], the same element, where every token
re-derives from them. Which theme shows is the Model's fact (themes.Name decodes the field),
and Themes.apply(themes, name) is the Command's effect that shows it. To keep a reader's choice,
Themes.choose(themes, name, key?) shows it and keeps the name in localStorage (the initial
theme keeps nothing), and Themes.script(themes, key?) is the text of a head <script> that shows
the kept one before the first paint, on the attribute apply writes: a name no theme has, and
storage that throws, leave the initial theme. The Model's field still starts at the initial theme
on a static page, so restore it from the same key (Mirror.kv); on a page rendered per request,
read it from a cookie into the Model instead (see foldkit-ssr). A token resolves where it
is declared, so knobs set below the root change nothing derived from them there:
Theme.scope(theme, '.marketing') declares the derivations again under the selector, which
Theme.scoped's token overrides do not. AppStyle.make({ theme }) takes one theme, and its
tokens an application's own groups beside the shipped ones. See the theme knobs guide for the full design.
Following another tab
Themes.choose and Theme.chooseScheme write this tab's localStorage, and another tab hears
that as a storage event. themeChanges(themes) and schemeChanges() are Streams of
what another tab chose, decoded as the head scripts decode it: a name no theme has, a removed key
and anything else read as the initial theme or 'system'. The writing tab hears nothing. They are
named exports, not members of Themes or Theme, so a page that reads neither ships no storage
listener. They
apply nothing, because the Model owns the choice: map each to a Message, and let update store
it and answer with the Command that shows it.
import { Schema, Stream } from 'effect'
import { defineMessageUnion } from 'foldkit/message'
import * as Subscription from 'foldkit/subscription'
import { schemeChanges, themeChanges, Themes } from 'foldkit-mixins/theme'
const Followed = defineMessageUnion({
ThemeFollowed: { name: themes.Name },
SchemeFollowed: { scheme: Schema.Literals(['system', 'light', 'dark']) },
})
type Shown = { readonly theme: typeof themes.Name.Type }
export const followed = Subscription.make<Shown, typeof Followed.Type>()(() => ({
theme: Subscription.persistentEntry(
themeChanges(themes).pipe(Stream.map(name => Followed.ThemeFollowed({ name }))),
),
scheme: Subscription.persistentEntry(
schemeChanges().pipe(Stream.map(scheme => Followed.SchemeFollowed({ scheme }))),
),
}))On ThemeFollowed, update sets the Model's field and returns Themes.apply(themes, name); on
SchemeFollowed it returns Theme.chooseScheme(scheme). Kept knobs have no stream:
Theme.chooseKnobs stores CSS variable declarations, which do not map back to a theme's knobs.
Switching themes in a page with no style compiler
Themes.make compiles the themes, so a page built with foldkit-mixins/vite's modules, which
ships no style compiler, cannot import it. The functions that only show, keep and hear a theme
need no compiled theme: foldkit-mixins/theme/runtime exports them (the same functions as
Themes.apply, Themes.choose, Themes.script and themeChanges) over ThemeNames, the
names, the initial name and the root attribute, which a compiled Themes already is. A page
without the compiler declares its own, typed by a type-only import of the compiled set so the
names cannot drift in type. foldkit-mixins/theme/knob-data holds each range knob of
Knobs.standard as plain data, one named export per knob (shapeDensity is { name: 'shape.density',
title, variable, unit, min, max, step, default }; a knob with a light and a dark value is two,
accentChromaLight and accentChromaDark), for a panel's sliders. A page keeps only the knobs it
imports; knobData, the same entries by name (knobData['shape.density']), is for a panel that
draws every knob. The module is precomputed from Knobs.standard so runtime themes never need the knob schema builder.
import { Effect, Stream } from 'effect'
import { shapeDensity } from 'foldkit-mixins/theme/knob-data'
import {
applyTheme,
chooseTheme,
themeChanges,
themeScript,
type ThemeNames,
} from 'foldkit-mixins/theme/runtime'
type Look = 'cobalt' | 'cobaltDense'
const looks: ThemeNames<Look> = {
names: ['cobalt', 'cobaltDense'],
initial: 'cobalt',
attribute: 'data-theme',
}
// A Command's effects: the Model's field owns the chosen name, these only show it.
export const show = (name: Look): Effect.Effect<void> => applyTheme(looks, name)
export const keep = (name: Look): Effect.Effect<void> => chooseTheme(looks, name)
// A Subscription's stream: another tab's choice, for `update` to store and answer with `show`.
export const followed: Stream.Stream<Look> = themeChanges(looks)
// The text of the head `<script>`, which shows the kept theme before the first paint.
export const head: string = themeScript(looks)
export const density = shapeDensityA name that is not one of names is a type error at a call. One read from storage, which nothing
validated, never reaches a call: the head script leaves the initial theme, and themeChanges
emits the initial theme, exactly as for a compiled set. Neither entry imports style code, so
modules accepts a page that imports only these.
The server's first render of the scheme
A server that builds the Model per request reads the browser's hint with
schemeOfHint(request.headers.get('sec-ch-prefers-color-scheme')), which is
Option.some('light' | 'dark') or Option.none(). A browser sends the hint only after a
response asks for it, so send COLOR_SCHEME_HINT_HEADERS on pages: Accept-CH opts in,
Critical-CH has the browser retry the first request with the hint, and Vary keeps a cache
from serving one scheme's page to the other. Both are exported from foldkit-mixins/theme.
What the palette derives
Theme.standard(theme) holds typed tokens for surfaces, text, outlines, and the accent, secondary,
tertiary and feedback families, derived from the theme's knobs. Only the knob group holds literals; every other value is a CSS
expression over other tokens (oklch(from …), color-mix(), light-dark()), so the browser does
the derivation and one knob override recolors everything below it. A derived color takes its hue
from the palette's hue tokens (hue.neutral, hue.accent), never from the color it starts from,
and the palette mixes in OKLab: a grey's hue is powerless, engines read it differently (Chromium
keeps the hue a grey was written with, others read 0, a red), and an OKLCH mix or added chroma
carries it into the result. Mix tokens of your own the same way, color-mix(in oklab, …). Each family (accent,
secondary, tertiary, success, warning, error, info) is one shape: a fill, default,
lighter in a dark scheme; hover and active (darker, and active more vivid by 0.05 of chroma, at most
twice its own, so a grey fill stays grey when pressed); subtle, a tint of it on the base; outline, a
line in it that stands off the base; and two text colors named for where they go: on-fill is
text on that fill (near white on a mid accent), and ink is text in the family's color on the
base surface, dark enough to read in a light scheme and light enough in a dark one. Colored text
is ink, never default. The surfaces are the base at a few lightnesses with its chroma, so a
panel and a sidebar read as the page's own color, in the accent's hue unless surface.hue gives
them one of their own (a base color: a warm stone under a blue accent); bedrock is the deepest of them in both
schemes, and the focus ring, outline.focus, is the accent. The syntax group colors code by
the kinds a tokenizer names (syntax-keyword is --fk-syntax-keyword, as
foldkit-richtext-code and its Shiki adapter name them): keyword, function and type in
the accent, secondary and tertiary hues, string, number and property in the success,
warning and info hues, all at one lightness per scheme and the code.chroma knob's chroma, and
operator, punctuation and comment in the text's own grey. The chart group is a chart's
series colors, chart-1 to chart-5 as shadcn names them: the dataviz reference palette's first
five slots in its order, so neighbors stay apart under protan and deutan vision, each a fixed turn
of hue from the chart-h knob at a lightness and chroma set for that hue in each scheme. Seven
color scales, red, orange, yellow, green, teal, blue and purple, are for what no
role names (a tag's color, an illustration, a status of the application's own): steps 1 (near
white) to 10 (near black) share one lightness ladder, so red-6 is as light as blue-6 and a
step means the same contrast in every hue, with chroma swelling toward the middle and thinning
at both ends, where a vivid near-white or near-black falls out of gamut; wash-1 to wash-4
mix step 6 into surface.base at 8, 16, 28 and 44%, so a tinted ground follows the scheme and
the surface knobs. Each hue is a knob (red-h), and scale-c scales every step's chroma
(--fk-blue-wash-2, ref.blue['6']). The popup group is a menu's
panel (surface, ink, blur) and its lit row (highlight, press, highlight-ink):
menu.highlight: 'bold' lights the row in the accent's fill, and menu.panel draws the panel
as the page's own raised surface (default), inverted (the other scheme's surface and text) or
translucent over a blur, as shadcn's menu options do. The selection group is selected text,
which Defaults.body paints with :where(*)::selection: background is the accent over whatever
the text sits on (28% in a light scheme, 40% in a dark one, so the text stays at AA), ink is
currentColor so a link or a syntax token keeps its colour, and fill-background is the deeper
accent for text on the accent's own fill, where the tint would be the fill: such a surface sets
--fk-selection-background to it beside its fill. Override like any token,
Theme.compose(theme, { selection: { background: 'rebeccapurple' } }); an application's own
::selection rule wins. A lit row takes its ink from the surface
it is on: a popup panel sets --_fk-row-highlight, --_fk-row-press and
--_fk-row-highlight-ink on itself, and a row outside one (an inline Command) reads the plain-*
tokens, the text's own films or the accent.
Each is a 0-or-1 knob (popup-bold, popup-invert) blended by color-mix, so an override
switches it live. The state group is what a state lays over the surface under it, a mix of the
element's own text color (hover, and press at 1.75 of it; tint and tint-hover, a
see-through fill; edge, a hairline inside an image), so it reads at any elevation and on any
band; its amounts are knob variables (state-hover, state-tint, state-tint-dark,
image-edge), and a theme sets the hover's, and the press's with it, with
surface.hoverStrength (4% to 24%, 12% by default); a disabled control fades by
state.disabledOpacity (Disabled, 0.3 to 0.7, half by default). Theme.nested(outer, inset,
border?) is the radius of a surface inset in another, so their corners are concentric. A
container that pads its children can publish that instead: spread Theme.nests(radius, inset,
border?) beside its own radius and padding, and Theme.nested() with no arguments on any
descendant (a row, a pill, a highlight, a focus ring) reads it. Outside such a container it is
square. Theme.concentric({ min, max }) is a control's corner read the same way, the container's
corner less its inset kept between min and max, and max outside any: foldkit-mixins-ui's
buttons and fields take concentric({ min: sm, max: md }), and its Card, Dialog, Toast and Alert
nests, so a button in a card rounds with the card. A control that nests its own parts sets
'--fk-control-corner': 'inherit' after nests, or it reads the corner it publishes.
Theme.raise(offset) lifts an element offset levels above the raised element holding it (or the
page, level 1), capped at 8, and Theme.raisedSurface() is its background at that level: a popover
opened in a dialog lands above the dialog with nothing passed. In a light scheme the first two
levels step toward white and the rest stay there, so shadow carries elevation; in a dark scheme
each level is an even step lighter.
Theme.tokens is the
non-color scales, with space and radius multiplied by the density and radius-factor knobs.
Its motion group is three tiers, fast, moderate and slow (80, 160 and 240ms, for hover and
fades, popups and tabs, dialogs), each with a quicker -exit for dismissals, all multiplied by the
motion knob. sheet and sheet-exit time a Sheet's slide: they read the slow tier until a theme
sets them. A duration of something that moves or resizes also multiplies by knob.travel,
which Defaults.reset sets to 0 under prefers-reduced-motion: the thing stops travelling, and its
fade still plays.
A theme reaches the page as pieces, and the page chooses the layers:
import { Layers, Slot, Slots, Capability, Style } from 'foldkit-mixins'
import { Theme } from 'foldkit-mixins/theme'
const L = Layers.standard
const theme = Theme.standard(Theme.make({ accent: { hue: 280, chroma: 0.15, lightness: 60 } }))
const t = Theme.ref(theme) // t.surface.base is 'var(--fk-surface-base)'; a missing name is a type error
const PageSlots = Slots.define({ root: Slot.make({ capability: Capability.Container }) })
// Born in the app layer: the view attaches this same value, so its classes are the sheet's.
const PageStyle = Style.forSlots(PageSlots)(
{ root: Style.self({ background: t.surface.base, color: t.text.default }) },
{ layer: L.layer('app') },
)
export const sheet = Style.stylesheet(
L.declare,
L.in('theme', Theme.root(theme)),
PageStyle,
)Once the sheet declares an order, every rule in it must sit in one of its layers: an unlayered
rule would beat all of them, app included, so Style.stylesheet refuses it with
style:unlayered-rule. A slot style takes its layer when it is compiled, with the layer
option; a layout or recipe it composes keeps the layer it was already given. L.in takes only
bare pieces: a layer is part of a rule's identity, so layering a finished style would copy it
under new class names that no view attaches.
Theme.root declares every token once, at :root; its omit leaves out tokens a rule of
another layer already declared. Which theme is active is a Model fact: Themes.make below names
them. A scheme the browser picks needs nothing, because the light-dark() values follow it. A scheme the user picks is a
color-scheme override on the root, which must be in place before the first paint or a reader
who chose dark sees one light frame: Theme.schemeScript(key?) is the text of a head <script>
that applies the one kept in localStorage, Theme.chooseScheme(scheme, key?) ('light',
'dark' or 'system') is a Command's Effect that applies and keeps a choice, and
Theme.currentScheme() reads back what is applied, for the Model once the browser takes the page
over (the docs site does it in its SSR plan's boot).
Knob values a reader set, as on a theme-making page, need the same: Theme.knobScript({ key?,
selector? }) is the text of a head <script> that applies the knob variables kept in
localStorage to selector (:root by default), and Theme.chooseKnobs(theme, { base, key?,
selector? }) is a Command's Effect that applies theme's and keeps them. Both write one
unlayered rule in one <style> element, so it beats the layered theme, an inline style still
beats it, and the Command replaces what the script wrote rather than handing over from it. What is
kept is the variables that differ from base, with KNOBS_FORMAT: an entry of another format, a
property that is not a knob, and storage that throws are ignored, and the base theme keeps
nothing. A token derives where it is declared, so a selector other than :root must declare the
tokens too (Theme.scope). On a page rendered per request, put the theme in the Model from a
cookie instead (see foldkit-ssr). The palette
needs relative color syntax and light-dark() (Chrome 123, Firefox 128, Safari 17.5).
Style.responsive(Theme.tokens.breakpoint, { md: { … } }) and
Theme.breakpointWidths(Theme.tokens) (for the Breakpoints bundle) name the same breakpoints;
a query that is not a plain min-width raises theme:unparseable-breakpoint.
Theme.inContainer('page', Theme.tokens.breakpoint) is the same breakpoints measured on the
container named page rather than the window: an editor's preview frame, narrow in a wide
window, then draws a look as a narrow screen would. An element must be that container
(containerType: 'inline-size', containerName: 'page').
States
One owner per interactive state, so every component on a page agrees and a theme moves them together:
| State | Drawn by | Chosen by |
|---|---|---|
| hover | the hover ink as a film over what is under it | surface.hover (the ink), surface.hoverStrength (how much) |
| press | the same ink at 1.75 of the hover's strength | surface.hoverStrength |
| selected / current | accent.subtle; a popup's lit row by menu.highlight | accent.*, menu.highlight |
| focus | one outline token, one offset | accent.hue |
| disabled | one fade, and nothing else changes | state.disabledOpacity |
A fluid highlight — one highlight that glides from item to item — is the hover: it lays the
same film from the same ink, so a fluid list and a plain one on a page hover alike, and it
deepens to the press while its item is held. Popups keep their own highlight, and a Card
lightens a dark page as it darkens a light one, both by design. foldkit-mixins-ui names the
pieces: unfilledHover, pressedHover, hover(), focusRing and disabled.
Layout
foldkit-mixins/layout ships the common arrangements as pieces: Layout.stack, cluster,
split, sidebar, switcher, reel, center, frame, pad, and autoGrid, plus
Layout.intrinsic (a stack child as wide as its content; one that sets a width keeps it
anyway) and Layout.aside (the sidebar child). Each compiles to rule text that is the same for every caller and reads --fk-l-*
variables with token fallbacks; the options only write those variables inline, so ten stacks
with ten gaps are one rule and ten inline declarations. The pieces are unlayered; put them in
layouts:
import { Layers, Style } from 'foldkit-mixins'
import { Layout } from 'foldkit-mixins/layout'
const L = Layers.standard
const CardStyle = Style.forSlots(CardSlots)({
root: L.in('layouts', Layout.stack({ gap: 'var(--fk-space-sm)' })),
actions: L.in('layouts', Layout.cluster({ justify: 'end' })),
})split adapts to its container by default (container-type: inline-size and a @container
query); { contain: false } uses @media on the viewport instead. Its breakpoint and
stack's split index are in the rule text, because a query cannot read a variable, so each
distinct value is its own class. sidebar and switcher are flex math and need no query.
Defaults and prose
foldkit-mixins/defaults is the baseline plain HTML gets before any slot is styled: Defaults.reset
(box model, media, form-control fonts, reduced motion) and body, headings, links, code,
controls, composed as Defaults.all (everything except reset). Native checkboxes, radios and
sliders take the accent (accent-color), selected text is the accent's tint, kbd is a raised
key and hr one quiet line. Each is element-selector CSS
under :where() over --fk-* tokens with a fallback, so a class rule always beats it and it reads
with or without a theme. Headings are text-overt unless a container sets --fk-heading: a band
drawn in its own color writes Style.vars({ '--fk-heading': 'currentColor' }) and the headings
inside take its color, with no rule on the heading. foldkit-mixins-ui's unfilled buttons read
--fk-ink the same way. foldkit-mixins/prose is the longform contract: Prose.style({ measure?,
leading?, rhythm? }) is one class for every caller (the rhythm between unlike elements: heading to
paragraph, list to paragraph, around figures) whose options are --fk-prose-* variables on the
element. Its measure and line height are a rule reading those variables, so a later layer can
override them. Both are unlayered; the page places them:
import { Layers, Style } from 'foldkit-mixins'
import { Defaults } from 'foldkit-mixins/defaults'
import { Prose } from 'foldkit-mixins/prose'
const L = Layers.standard
const Article = Style.forSlots(ArticleSlots)({ body: L.in('components', Prose.style({ measure: '60ch' })) })
export const sheet = Style.stylesheet(
L.declare,
L.in('reset', Defaults.reset),
L.in('defaults', Defaults.all),
Article,
)An application's own look
Everything above serves two kinds of author. A component or design system publishes a
contract (ButtonSlots) that others style with Style.forSlots. An application mostly styles
its own markup: Slots nobody else attaches to, one theme, one layer, one page sheet. For
that case the contract, the style and the setup can each be written once:
| You are... | Use |
|---|---|
| styling a contract someone published | Style.forSlots(ButtonSlots)(pieces, options) |
| taking a published recipe's look as it ships | Recipes.Button.style(selection, options) |
| declaring your own Slots and their look | Style.slots(pieces, options) |
fixing theme, app layer and page sheet for one application | AppStyle.make from foldkit-mixins/app |
| writing a token-backed declaration in a word | Utilities from foldkit-mixins/utilities |
import { Event, Style, SlotView } from 'foldkit-mixins'
import { AppStyle } from 'foldkit-mixins/app'
import { Theme } from 'foldkit-mixins/theme'
import { Utilities as U } from 'foldkit-mixins/utilities'
// The theme's tokens, their references, the app layer and the page sheet.
const { t, slots, forSlots, stylesheet } = AppStyle.make({
theme: Theme.make({ accent: { hue: 260, chroma: 0.21, lightness: 62 } }),
colorScheme: 'light',
})
// Each key is a Container slot with that piece; Style.slot gives a slot options.
export const Page = slots({
root: [U.p('lg'), U.bg('surface.base')],
count: [U.textCenter, U.font('bold'), { fontSize: '3.75rem', color: t.text.default }],
form: Style.slot({ events: [Event.Submit] }, [U.flex, U.gap('sm')]),
})
export const Counter = SlotView.forMessages<never>()
.define(Page.slots, (count: number, slots, h) =>
h.main(slots.root.attrs(), [h.p(slots.count.attrs(), [String(count)])]),
)
.pipe(Style.attach(Page.style))
// In the browser entry, before the application runs:
Style.install(stylesheet)A published contract takes the same layer through the kit's forSlots, as
forSlots(ButtonSlots)(Recipes.Button()) with foldkit-mixins-ui, and a recipe's .style
takes it as an option: Recipes.Button.style({}, { layer: L.layer('app') }), with L from
AppStyle.make. The shipped pieces keep their components and variants layers either way;
the layer places what the application's own .extend added with none.
What each call does:
AppStyle.makecomputes, once:themeisTheme.compose(Theme.tokens, palette),tisTheme.ref(theme),LisLayers.standard, andstylesheetis the text of the layer order,Defaults.reset, the tokens, the palette andDefaults.body(plus anyglobalpieces, in thedefaultslayer). The text is built lazily whenstylesheetis first read (destructuringstylesheetreads it), so a browser loading CSS from a static file can skip destructuring it. Your Foldkit Model tracks the user's chosen scheme or theme, andStyle.installwrites the stylesheet to the DOM (Themes as typed knobs).slots(pieces)isStyle.slots(pieces, { layer: L.layer('app') }), andforSlotsisStyle.forSlotswith the same layer: the options take aname, never a layer. Both compile once, where they are defined.Style.slotsreturns{ slots, style }:slotsis the contract (Slots.defineof aContainerper key, or theStyle.slotoptions, which default toContainertoo and are neverhidden), andstyletheNamedStylea view attaches. A slot with no look takes{}. The view still decides the markup; the contract only names what it may draw.Style.install(stylesheet)is the one call that touches the DOM. The sheet holds no slot class: a Slot's CSS is injected when it first draws.
Utilities are one-idea pieces whose steps are the shipped scales' token names, so an invalid
step is a type error and the value still follows the density knob and theme overrides:
p, px, py, m, mx, my, gap (a space step or '0'; margins also 'auto'), text
(size), font (weight), leading, rounded (radius), color and bg (a palette
color as 'group.name'), items and justify ('between' is space-between), and the
constants flex, column, grid, block, hidden, wFull, textCenter, uppercase,
truncate, srOnly, pointer and selectNone, scriptedOnly and plainOnly(display) (the
pair for a page in a browser running no scripts: a control only a script drives is hidden there,
and its plain stand-in, display: none until then, is shown as display; put scriptedOnly last
in a slot's pieces so it wins over a width's display), and scrollFade(axis), a scroller's content dissolving
toward an edge with more to scroll (a scroll-driven mask: the true ends stay crisp until something
is past them, and a browser without scroll timelines gets no fade), scrollDivider(axis) with
scrollTimeline(axis), a hairline at each edge with more past it, drawn on a positioned parent's
::before and ::after (the fade's mask would erase a line inside the scroller) from the timeline
the scroller names, where the browser has timeline-scope, and steady(weight), room for a
label at a heavier weight, read from the element's data-label, so turning bold moves nothing
beside it, and busyReveal, busy text said only once a wait is noticeable: on an element marked
aria-busy="true" it fades in after 0.6s, so a read answered sooner never flashes a "Loading…";
the element renders from the start, holding its space, and without aria-busy the piece does
nothing, so one status Slot also says "Nothing here." plainly. Its fade follows the motion knob;
its delay does not, or a still theme would bring the flash back. Each is a Style.self rule, unlayered, so it takes the
layer of the style it is composed into, and a plain declaration after it wins per property. A
value off the scale is a plain declaration ({ fontSize: '3.75rem' }); a color outside
the palette's groups is read through t.