@kutur-kit/foldkit-stylex
StyleX for every @foldkit/ui component: typed styles per part and state, and the CSS each component needs to work.
StyleX for @foldkit/ui components. Most apps use @kutur-kit/foldkit-stylex-theme, which styles every component through this package; use this package on its own for a look of your own. Wrap a component's view once with typed styles for each of its parts, written as functions of the part's state, and the package adds the CSS each component needs to work: the backdrop that covers the page, the panel's z-index, the hidden closed dialog and the like. It ships no colors, spacing or fonts.
Tested with the lowest versions in peerDependencies; a daily job tests the latest @foldkit/ui.
pnpm add @kutur-kit/foldkit-stylex@alpha '@stylexjs/stylex@~0.19.1'
pnpm add -D '@stylexjs/unplugin@~0.19.1' 'unplugin@^2.3.11'The ranges are the peer ranges: pnpm otherwise installs the latest release, which strict peers reject once it falls outside them. unplugin is a peer of @stylexjs/unplugin; installs with strict peers fail without it.
Setup
Put foldkitStylex() before foldkit() in vite.config.ts, in place of any other CSS or StyleX plugin. It takes StyleX's plugin options except styleResolution:
import { foldkit } from "@foldkit/vite-plugin";
import { foldkitStylex } from "@kutur-kit/foldkit-stylex/vite";
import { defineConfig } from "vite";
export default defineConfig({
plugins: [foldkitStylex(), foldkit()],
});With server rendering, keep Foldkit's options as they are: foldkit({ ssr: { serverEntry: "/src/entry.server.ts", clientEntry: "/src/entry.ts", build: true } }).
Vitest needs the same plugin. create-foldkit-app keeps vitest.config.ts separate, so add it there too:
import { foldkitStylex } from "@kutur-kit/foldkit-stylex/vite";
import { defineConfig } from "vitest/config";
export default defineConfig({
plugins: [foldkitStylex()],
test: { environment: "happy-dom" },
});StyleX appends its rules, this package's included, to a stylesheet the page already links. Import one from the client entry (import "./styles.css"), or link it from index.html in a single-page app. Put page-wide settings there, not on your view's root, because anchored panels render outside it:
:root {
color-scheme: light dark;
font-family: system-ui, sans-serif;
}| If you skip | What happens |
|---|---|
foldkitStylex() in vitest.config.ts | Every test file fails with a message that names the config. |
foldkitStylex() in vite.config.ts, using StyleX's own plugin | The browser console shows the same message and the page does not hydrate. |
| The stylesheet | vite build fails with a message that asks for one. |
Never add a Class to a part's bundle
Foldkit keeps one Class per element, the last one. @foldkit/ui's docs append classes to the bundles toView receives; with this package that replaces the part's styles and the CSS it needs to work:
// Wrong: the button loses its styles.
toView: ({ button }) => h.button([...button, h.Class("ring")], ["Details"]);Put the styles in that part's entry instead:
const popoverView = PopoverStyle.view(Popover.view, { button: styles.ring });The lint preset reports the first form.
Style a component
Wrap @foldkit/ui's view once, at module scope, and use the result where you used the view. Each key of the styles object is a part; its value is StyleX styles or a function of the part's state:
import type { Update } from "foldkit";
import type { Html, HtmlBuilder } from "foldkit/html";
import { Checkbox } from "@foldkit/ui";
import { CheckboxStyle, sx } from "@kutur-kit/foldkit-stylex";
import * as stylex from "@stylexjs/stylex";
import { Schema } from "effect";
import { defineMessageUnion } from "foldkit/message";
export const Model = Schema.Struct({ isChecked: Schema.Boolean });
export type Model = typeof Model.Type;
export const Message = defineMessageUnion({ ToggledTerms: { isChecked: Schema.Boolean } });
export type Message = typeof Message.Type;
export const init = (): Update.Return<Model, Message> => ({ model: { isChecked: false } });
export const update = (_model: Model, message: Message): Update.Return<Model, Message> =>
Message.match<Update.Return<Model, Message>>(message, {
ToggledTerms: ({ isChecked }) => ({ model: { isChecked } }),
});
const styles = stylex.create({
row: { display: "flex", alignItems: "center", gap: 8 },
box: {
display: "grid",
placeItems: "center",
inlineSize: 24,
blockSize: 24,
padding: 0,
borderWidth: 2,
borderStyle: "solid",
borderColor: "currentColor",
backgroundColor: "transparent",
color: "inherit",
},
checked: {
backgroundColor: {
default: "black",
":hover": { default: null, "@media (hover: hover)": "dimgray" },
},
color: "white",
},
disabled: { opacity: 0.5 },
tick: { opacity: 0 },
ticked: { opacity: 1 },
});
const checkboxView = CheckboxStyle.view(Checkbox.view, {
checkbox: (state) => [
styles.box,
state.isChecked && styles.checked,
state.isDisabled && styles.disabled,
],
});
export const view = (model: Model, h: HtmlBuilder<Message>): Html =>
checkboxView(
{
id: "terms",
isChecked: model.isChecked,
onToggle: (isChecked) => Message.ToggledTerms({ isChecked }),
toView: ({ checkbox, label }) =>
h.div(
[sx(styles.row)],
[
h.button(
[...checkbox],
[h.span([sx(styles.tick, model.isChecked && styles.ticked)], ["✓"])],
),
h.label([...label], ["I accept the terms"]),
],
),
},
h,
);Submodel components such as Popover and Dialog take the wrapped view in h.submodel({ view: popoverView, ... }); toView gets bundles that already carry their styles. Components with class name inputs, such as Listbox, take their styles the same way, and their class name inputs and the className of itemToConfig no longer compile.
More styles objects after the first layer on top of it, property by property: PopoverStyle.view(Popover.view, look, { panel: styles.wide }). StyleX applies a longhand over its shorthand whatever the order, so a later padding over an earlier paddingInline fails to compile and names the longhand to set, except inside ::before and other pseudo-elements (see Limitations).
A module that puts its own styles first and lets callers add more keeps these checks on the callers' styles with XStyle.Layers<List, Before>: it checks each styles object in List against those in Before and those before it in List. The theme's restyle is built this way:
const look = {
panel: (state) => [styles.panel, state.isClosed && styles.closed],
} satisfies PopoverStyle.Styles;
export const restyle = <const List extends ReadonlyArray<PopoverStyle.Styles>>(
...layers: PopoverStyle.Layers<List, [typeof look]>
) => PopoverStyle.view(Popover.view, look, ...layers);State
A part's state is typed: autocomplete lists every flag and a misspelt one does not compile. Flags are named after the @foldkit/ui field that sets the matching data-* attribute, and agree with it in every state:
isVisibleis true while a panel is open and while it plays its leave animation.isClosedis true where @foldkit/ui setsdata-closed: the first frame of the enter animation and the leave animation. Puttransition*on the base style and the closed values underisClosed; a fade on!isVisiblenever plays, becauseisVisiblestays true while leaving.isDisabledmeans disabled whether @foldkit/ui uses the nativedisabledattribute oraria-disabled, so do not style:disabled.
Later entries win: in [styles.box, state.isChecked && styles.checked, state.isDisabled && styles.disabled] the disabled style wins over the checked one. Put pseudo-classes inside a variant, and :hover under @media (hover: hover), because touch browsers keep :hover after a tap: checked: { backgroundColor: { default: "black", ":hover": { default: null, "@media (hover: hover)": "dimgray" } } }. StyleX takes no condition under a chained key such as ":hover:not(:focus-visible)" or a stylex.when key, so put that key under "@media (hover: hover)" instead. Style focus with ":focus-visible".
Toast entries are the one exception: every entry shares one class, so style them with ":is([data-closed])" and ":is([data-swipe])", and style variants on your own element inside entryToView.
Portals
Anchored panels and backdrops render in Foldkit's portal root at the start of <body>, or inside the containing <dialog>. They inherit from <body>, not from your view's root: set color, and fonts unless they are on :root, on the portaled parts. Custom properties set on the panel part reach the panel; ones set on an ancestor of the trigger do not.
Your own elements
sx(...styles) turns StyleX styles into the one Class an element keeps. Pass every style of the element to one call, conditions included, and put it last in the attribute list:
h.div([h.Id("row"), sx(styles.row, isActive && styles.active)], children);sx and the parts take static styles only. For a runtime value, set a custom property with h.Style({ "--progress": `${value}%` }) and read it with var(--progress) in a static style.
What the package sets
| Component | Before your styles | After your styles, only in their state |
|---|---|---|
| Popover, Listbox, Menu, Combobox, DatePicker | the wrapper around the trigger position: relative; the backdrop position: fixed; inset: 0; the panel z-index: 10 | |
| Popover | the arrow centred on the panel edge that faces the trigger and turned to point at it | |
| Dialog | color: inherit on the <dialog>; the backdrop covers the viewport; the panel position: relative | display: none on the <dialog> while not visible |
| FileDrop | the input visually hidden, in place of @foldkit/ui's Tailwind sr-only class | |
| Tabs | display: none on each inactive panel | |
| Tooltip | the panel z-index: 10 |
Your value wins for the properties set before your styles. A part cannot set the properties @foldkit/ui writes inline or those this package needs, such as the panel's position or the slider thumb's transform, nor a property that overlaps or works with one of them, such as inset over top or bottom with top: the types reject them with a message that says where to style instead.
Draw Popover's arrow pointing up in a square box; the package centres it and turns it.
Errors you may see
Each message is the last line of the error.
| Mistake | Last line |
|---|---|
{ panel: s.absolute } on Popover, in a list of any depth, or in a style that also sets a token | "@foldkit/ui sets position inline on this part. Floating UI positions the panel and caps its height; size and scroll an element inside it." |
maxHeight on Listbox items | "@foldkit/ui sets maxHeight inline on this part. Floating UI positions the panel and caps its height; size and scroll an element inside it." |
zIndex on Popover button | "@foldkit/ui sets zIndex inline on this part. It is set only while the panel is open, so a class value would apply only while it is closed. Layer the trigger with zIndex on wrapper, and position an element of your own inside or around it." |
transform on Slider thumb | "@foldkit/ui sets transform inline on this part. Its position follows the value; use scale for press feedback." |
width on Meter fill or Progress indicator | "@foldkit/ui sets width inline on this part. Its width follows the value; style its height and color." |
pointerEvents on Tooltip panel | "@foldkit/ui sets pointerEvents inline on this part. A tooltip is not interactive; put interactive content in a Popover." |
padding on VirtualList container | "@foldkit/ui sets padding inline on this part. The list scrolls and measures this element; style its size, border and background, and space rows inside itemToView." |
userSelect on a DragAndDrop draggable | "@foldkit/ui sets userSelect inline on this part. Dragging by pointer and touch relies on it; style the element's look." |
rowGap on Toast container, or another property that overlaps one @foldkit/ui sets inline | "@foldkit/ui sets bottom, display, flexDirection, gap, left, padding, pointerEvents, position, right, top, transform and zIndex inline on this part, and rowGap overlaps what it sets. Style each entry instead." |
flexWrap on Toast container, or another property that works with one @foldkit/ui sets inline | "@foldkit/ui sets bottom, display, flexDirection, gap, left, padding, pointerEvents, position, right, top, transform and zIndex inline on this part, and flexWrap works together with them, so a value of yours would change what they do. Style each entry instead." |
position on Popover wrapper | "@kutur-kit/foldkit-stylex sets position on this part so the component works. Inside a <dialog>, @foldkit/ui moves the backdrop next to this wrapper, so it stays positioned. To place the component, position an element of your own around it." |
translate on Popover arrow, in any styles object | "@kutur-kit/foldkit-stylex sets translate on this part so the component works. It is centred on the panel edge that faces the trigger; draw it pointing up in a square box." |
inset on Popover arrow | "@kutur-kit/foldkit-stylex sets bottom, left, position, right, rotate, top and translate on this part so the component works, and inset overlaps what it sets. It is centred on the panel edge that faces the trigger; draw it pointing up in a square box." |
padding in a styles object after one that sets paddingInline | "An earlier styles object sets paddingInline on this part, which StyleX applies over padding whatever the order. Set paddingInline in this styles object too." |
gap on DatePicker calendar.grid after columnGap and rowGap | "An earlier styles object sets columnGap and rowGap on this part, which StyleX applies over gap whatever the order. Set columnGap and rowGap in this styles object too." |
const look: PopoverStyle.Styles, or a parameter of that type, passed to the view | "These styles have a type annotation, which hides the properties they set from this view's checks. Write satisfies instead of the annotation, and pass the styles to the view where they are written." |
| A dynamic style on a part | "Pass a static style: a part takes classes only, because @foldkit/ui owns its inline style. For a runtime value, set a custom property with h.Style on your own element around the part and read it with var() in the part's styles; a portaled panel inherits from none of your elements, so set it on an element you render inside the panel and style that element." |
A dynamic style in sx | "Pass static styles only. For a runtime value, set a custom property with h.Style({ '--x': value }) and read it with var(--x) in a static style." |
{ pannel: ... } | Did you mean to write 'panel'? |
{ panel: ..., pannel: ... } or { ...look, pannel: ... } | "pannel names no part, so its styles would reach no element. Write arrow, backdrop, button, panel or wrapper." |
calendar: { cell: ..., cellButon: ... } on DatePicker | "cellButon names no part, so its styles would reach no element. Write cell, cellButton, columnHeader, grid, headerRow, headingButton, nextMonthButton, nextPageButton, previousMonthButton, previousPageButton, root or week." |
{ panel: ... } on Listbox | "Listbox calls its panel items: put these styles under items." |
{ panel: ... } on Menu | "Menu calls its panel items: put these styles under items." |
{ panel: ... } on Combobox | "Combobox calls its panel items: put these styles under items." |
{ thumb: ... } on Switch | "Switch renders no thumb part: draw it inside the button with sx(...)" |
{ button: ... } on DatePicker | "DatePicker calls its button trigger: put these styles under trigger." |
{ cell: ... } on DatePicker | "DatePicker styles its calendar under calendar: put these styles under calendar.cell." |
{ input: ... } on FileDrop | "FileDrop's input is visually hidden: style root, with ':has(:focus-visible)' for keyboard focus." |
{ row: ... } on VirtualList | "VirtualList's rows take no class: style the element itemToView returns, which fills its row." |
{ panel: [s.base, s.opn] }, with a style stylex.create did not define | Property 'opn' does not exist on type |
state.isHighlighted on a Listbox item | Property 'isHighlighted' does not exist on type 'ItemState'. |
nav: () => ... on Nav, or a function on a Toast or VirtualList container | "This part has one class in every state, so pass its styles, not a function of state." |
entry: (state) => ... on Toast | "@foldkit/ui gives every entry one class, so entry takes no state. Style each variant on your own element inside entryToView, from entry.variant." |
PopoverStyle.view(Dialog.view) | Property 'maybeFocusSelector' is missing |
buttonClassName: "trigger" | '"Style the button part through styles; this package sets buttonClassName."' |
className in itemToConfig | '"Style items through the item part of styles."' |
className in groupToHeading | '"Style group headings through the heading part of styles."' |
buttonAttributes: [h.AriaLabel(...)], or another *Attributes list not built with childAttributes | Type '{ readonly _tag: "AriaLabel"; readonly value: string; }' is missing the following properties from type |
| An installed @foldkit/ui whose Popover lost a part this release styles | "This @kutur-kit/foldkit-stylex release does not support the installed @foldkit/ui: Popover changed RenderInfo.arrow. Pin @foldkit/ui to an earlier version, or update @kutur-kit/foldkit-stylex once a release supports it." |
| The same for a renamed or retyped state field or tag, here Slider's | "This @kutur-kit/foldkit-stylex release does not support the installed @foldkit/ui: Slider changed Model.dragState. Pin @foldkit/ui to an earlier version, or update @kutur-kit/foldkit-stylex once a release supports it." |
| The same for a renamed transition state, here Listbox's | "This @kutur-kit/foldkit-stylex release does not support the installed @foldkit/ui: Listbox changed Model.animation. Pin @foldkit/ui to an earlier version, or update @kutur-kit/foldkit-stylex once a release supports it." |
The same for a renamed toView, here Calendar's | "This @kutur-kit/foldkit-stylex release does not support the installed @foldkit/ui: Calendar changed ViewInputs.toView. Pin @foldkit/ui to an earlier version, or update @kutur-kit/foldkit-stylex once a release supports it." |
The same for a renamed itemToConfig | "This @kutur-kit/foldkit-stylex release does not support the installed @foldkit/ui: Listbox changed ViewInputs.itemToConfig. Pin @foldkit/ui to an earlier version, or update @kutur-kit/foldkit-stylex once a release supports it." |
The same for a renamed content in what itemToConfig returns, or a field it newly requires | "This @kutur-kit/foldkit-stylex release does not support the installed @foldkit/ui: Listbox changed ItemConfig.accepts. Pin @foldkit/ui to an earlier version, or update @kutur-kit/foldkit-stylex once a release supports it." |
| An installed @foldkit/ui whose Toast view requires a new input | Property 'motion' is missing in type |
foldkitStylex({ styleResolution: ... }) | Object literal may only specify known properties, and 'styleResolution' does not exist in type |
Components
| Component | Wrap | Parts | State |
|---|---|---|---|
| Animation | AnimationStyle.view(Animation.view, styles) | element | isShowing, isClosed |
| Button | ButtonStyle.view(Button.view, styles) | button | isDisabled |
| Calendar | CalendarStyle.view(Calendar.view, styles) | root, previousMonthButton, nextMonthButton, previousPageButton, nextPageButton, headingButton, grid, headerRow, columnHeader, week, cell, cellButton | viewMode; cells and their buttons: isSelected, isFocused, isToday, isOutsideMonth, isDisabled |
| Checkbox | CheckboxStyle.view(Checkbox.view, styles) | checkbox, label, description | isChecked, isIndeterminate, isDisabled, isReadOnly |
| Combobox | ComboboxStyle.view(Cities.view, styles), ComboboxStyle.Multi.view(Tags.view, styles) | wrapper, inputWrapper, input, button, backdrop, items, itemsScroll, item, group, heading, separator | isVisible, isClosed, isDisabled, isReadOnly, isInvalid; items: isActive, isSelected, isDisabled, isReadOnly |
| DatePicker | DatePickerStyle.view(DatePicker.view, styles) | wrapper, trigger, backdrop, panel, calendar | isVisible, isClosed, isDisabled; calendar takes Calendar's styles |
| Dialog | DialogStyle.view(Dialog.view, styles) | dialog, backdrop, panel, title, description, closeButton | isVisible, isClosed |
| Disclosure | DisclosureStyle.view(Disclosure.view, styles) | button, panel | isOpen, isDisabled |
| DragAndDrop | DragAndDropStyle.draggable(DragAndDrop.draggable, styles) | draggable | isDragging, isDragged |
| Fieldset | FieldsetStyle.view(Fieldset.view, styles) | fieldset, legend, description | isDisabled |
| FileDrop | FileDropStyle.view(FileDrop.view, styles) | root | isDragOver, isDisabled |
| HoverIntent | HoverIntentStyle.view(HoverIntent.view, styles) | trigger, panel | isVisible |
| Input | InputStyle.view(Input.view, styles) | input, label, description | isDisabled, isReadOnly, isInvalid |
| Listbox | ListboxStyle.view(Languages.view, styles), ListboxStyle.Multi.view(Tags.view, styles) | wrapper, button, backdrop, items, itemsScroll, item, group, heading, separator | isVisible, isClosed, isDisabled, isReadOnly, isInvalid; items: isActive, isSelected, isDisabled, isReadOnly |
| Menu | MenuStyle.view(Actions.view, styles) | wrapper, button, backdrop, items, itemsScroll, item, group, heading, separator | isVisible, isClosed, isButtonDisabled; items: isActive, isDisabled |
| Meter | MeterStyle.view(Meter.view, styles) | meter, label, fill | value, min, max, low, high, optimum |
| Nav | NavStyle.view(Nav.view, styles) | nav, link | links: isCurrent, index |
| Popover | PopoverStyle.view(Popover.view, styles) | wrapper, button, panel, backdrop, arrow | isVisible, isClosed, isDisabled |
| Progress | ProgressStyle.view(Progress.view, styles) | progress, label, track, indicator | isIndeterminate, isComplete, value, min, max |
| RadioGroup | RadioGroupStyle.view(Plans.view, styles) | group, option, label, description | orientation, isDisabled, isReadOnly; options: isSelected, isDisabled, isReadOnly, index |
| Select | SelectStyle.view(Select.view, styles) | select, label, description | isDisabled, isInvalid |
| Slider | SliderStyle.view(Slider.view, styles) | root, label, track, filledTrack, thumb | isDragging, isDisabled, isReadOnly, orientation |
| Switch | SwitchStyle.view(Switch.view, styles) | button, label, description | isChecked, isDisabled, isReadOnly |
| Tabs | TabsStyle.view(Sections.view, styles) | tablist, tab, panel | orientation; tabs and panels: isActive, isDisabled, index |
| Textarea | TextareaStyle.view(Textarea.view, styles) | textarea, label, description | isDisabled, isReadOnly, isInvalid |
| Toast | ToastStyle.view(Toast.view, styles) | container, entry, dismiss | dismiss: variant |
| Tooltip | TooltipStyle.view(Tooltip.view, styles) | trigger, panel | isVisible, isDisabled |
| VirtualList | VirtualListStyle.view(VirtualList.view<Issue>(), styles) | container | none |
Combobox, Listbox, Menu and Tabs wrap the view of a Combobox.create(), Listbox.create(), Menu.create() or Tabs.create() bundle declared at module scope, and Toast the view of a Toast.make() module. wrapper is the element around a trigger that toView gets for Popover; Combobox, Listbox and Menu render their own. Combobox, Listbox and Menu render itemsScroll and separator only when they are styled. Combobox renders button only when buttonContent is set and items only while an item matches, and anchors the panel to inputWrapper. Toast's container and entry take styles without state.
Switch and Disclosure leave the thumb and the chevron to you: draw them inside button with sx(...), from isChecked or isOpen. Disclosure's animatePanel wraps panel in two elements with no hook, which animate its height for 200 ms and clip its shadow and outline. A disabled Button keeps its element enabled, so a disabled type: "submit" button still submits its form.
HoverIntent and Nav render no elements: spread their bundles on your own. The wrapped Nav view takes no h, as Nav.view does, and nav takes styles without state. HoverIntent sets no data-* attribute; to fade its panel, keep the panel rendered and hide it with visibility: hidden while not isVisible, so the hidden panel takes no hover. Tooltip has no leave animation: render its panel while isVisible.
Calendar hands toView the bundles of the grid on show: days, months or years. Match on their _tag in toView and on viewMode in styles to lay out each grid. The heading text has an id but no bundle; put it inside headingButton in the day and month grids, and on its own element in the year grid, which has no heading button. @foldkit/ui marks a cell's state on cell, not on cellButton, so style the button from its flags. isFocused is the keyboard cursor while the grid has focus: the grid keeps DOM focus, so no cell matches :focus-visible. DatePicker renders its calendar in the panel through toCalendarView and styles it from calendar, which takes the same styles as CalendarStyle.view. It puts the trigger in a div inside wrapper that takes no class, so a flex or grid layout on wrapper arranges that div, not the trigger.
A disabled Fieldset disables the native controls inside it, but their components do not see it: pass its isDisabled to each one so their flags and hooks agree.
RadioGroup wraps the view of a RadioGroup.create() bundle declared at module scope; draw each radio mark inside option with sx(...), from isSelected. Meter and Progress give each part the numbers @foldkit/ui renders, the value held between min and max. @foldkit/ui derives no region from Meter's low, high and optimum, so compare value with them. Progress sets no width on indicator while indeterminate: size it then with minInlineSize.
Animation styles the element it renders around content. Put transition* on the base style and the closed values under isClosed; for keyframe animations, run the enter one on the base style and the leave one while not isShowing. With animateSize, the element stays rendered while hidden, with isClosed set, inside two elements with no hook that animate its height for 200 ms.
DragAndDrop has no view: wrap DragAndDrop.draggable once and call the result where you called it. isDragging is true on every draggable of the model while one is dragged, isDragged only on that one, and neither while a press has not yet passed the activation threshold. droppable and sortable set no class or style: put sx(...) after them. Style the pointer ghost on your own element, with h.Style from DragAndDrop.ghostStyle(model) and sx(...).
FileDrop hides its input visually, so style keyboard focus on root with ":has(:focus-visible)", which a mouse click does not match. VirtualList wraps the view VirtualList.view<Item>() returns. Its rows take no class and stretch the element itemToView returns to their height, so style that element.
Lint
The /foldkit-stylex preset of @kutur-kit/oxc reports what the types cannot see: a second Class on an element, a Class or Style on a part's bundle or in a *Attributes input, sx(...) before a spread, a @foldkit/ui view used without its wrapper, condition keys that never match or rank differently than written, :hover styles outside @media (hover: hover), styles objects and arrays of them annotated or cast with as instead of checked with satisfies, and StyleX's own Vite plugin. It also turns on StyleX's ESLint rules.
pnpm add -D @kutur-kit/oxc@alpha 'oxlint@~1.94.0' '@stylexjs/eslint-plugin@~0.19.1'Extend it in oxlint.config.ts:
import foldkitStylex from "@kutur-kit/oxc/foldkit-stylex";
import { defineConfig } from "oxlint";
export default defineConfig({ extends: [foldkitStylex] });Or in .oxlintrc.json, which extends configs by path:
{ "extends": ["./node_modules/@kutur-kit/oxc/dist/foldkit-stylex.json"] }Testing
Assert flags through the attributes @foldkit/ui sets, never through generated class names, which change with every style edit:
Scene.scene(
{ update, view },
Scene.given(model),
Scene.click(Scene.role("checkbox")),
Scene.expect(Scene.role("checkbox")).toHaveAttr("data-checked"),
);Check accessibility in a browser
happy-dom computes no styles or layout, so these checks run in Chromium. @kutur-kit/foldkit-stylex/testing exports audit, which checks the page as it is, and recordMotion, which logs what moves for it. axe-core checks the rest: text contrast, names, roles and ARIA.
| Rule | Checks | Cannot see |
|---|---|---|
edge | A control's most contrasting border, fill or shown mark, and an icon button's mark, reach 3:1 (WCAG 1.4.11); a hairline field shows a fill | Image and gradient backdrops, reported as unmeasured; positioned siblings behind |
focus | Keyboard focus shows, uncovered, as an outline or box-shadow ring of 3:1, at kit a 2px outline (2.4.7, 1.4.11, 2.4.11) | The same backdrops |
target | 24px targets, or at AA smaller ones whose 24px circles meet no other target; at kit 44px under a coarse pointer (2.5.8, 2.5.5); links in a line of text are exempt | |
reflow | No sideways scrolling, and no fixed box or its content past the viewport's edge (1.4.10) | Content that an overflow: hidden ancestor cuts at the edge; text past the edge in a fixed box that holds it directly, such as a nowrap banner |
clipped | No cut-off text, with or without 1.4.12's spacing | |
motion | No CSS transition or animation longer than a frame moves anything under reduced motion (2.3.3) | element.animate() and smooth scrolling |
state | States stay visible under forced colors (1.4.1) | A label that vanishes under forced colors once the browser replaces its fill, such as color.onAccent on color.accent in a part without forcedColorAdjust: "none" |
unmeasured | An edge, mark or focus ring over an image or gradient backdrop, which audit cannot measure: check its 3:1 by eye |
variations holds one browser context per axis: light, dark, reduced motion, forced colors in each scheme, 320px wide and touch, a 320px phone whose coarse pointer raises the target rule to 44px. With @vitest/browser-playwright, make each a browser instance:
instances: variations.map(({ name, viewport, ...contextOptions }) => ({
browser: "chromium",
name,
viewport,
provider: playwright({ contextOptions }),
})),Call recordMotion before the app renders. Under Vitest, foldkitStylex() makes the compiled modules insert their CSS, so audit measures the app's look. The 24px checkbox above passes at WCAG 2.2 AA:
import { audit, recordMotion } from "@kutur-kit/foldkit-stylex/testing";
import { Runtime } from "foldkit";
import { expect, onTestFinished, test } from "vitest";
import { page } from "vitest/browser";
import { Model, init, update, view } from "./checkbox.ts";
recordMotion();
test("the terms checkbox", async () => {
const container = document.body.appendChild(document.createElement("div"));
container.id = "terms-app";
const app = Runtime.embed(Runtime.makeElement({ Model, init, update, view, container }));
onTestFinished(app.dispose);
const checkbox = page.getByRole("checkbox", { name: "I accept the terms" });
await checkbox.click();
// The look the app ships has loaded, so audit measures it rather than bare markup.
expect(getComputedStyle(checkbox.element()).blockSize).toBe("24px");
expect(await audit({ level: "AA" })).toEqual([]);
});In Playwright Test, projects: variations.map(({ name, ...use }) => ({ name, use })), then add recordMotion as an init script, which runs again on every navigation. page.setContent drops it: call page.evaluate(recordMotion) after it.
test.beforeEach(({ page }) => page.addInitScript(recordMotion));
test("checkout", async ({ page }) => {
await page.goto("/checkout");
expect(await page.evaluate(audit, { exclude: "#payment-frame" })).toEqual([]);
});audit waits for animations to end, so call it before axe. It hides the focus events it causes from the app and restores focus and scroll. Options:
root: what to check, plus the panels it names inaria-controls. Defaultbody.exclude: subtrees to skip. They still cover what lies under them.level:"kit"(default) adds 2px outlines,motion, a focus change other than an outline or box-shadow ring, whichauditcannot measure, and 24px targets without 2.5.8's spacing exception, 44px under a finger (2.5.5);"AA"checks WCAG 2.2 AA.hairline: a selector of text fields that rest at a faint edge on a fill of their own and turn the edge to 3:1 on hover, with a focus outline on focus, as many design systems draw text fields; it may also name read-only wells, which take no input and so no hover edge, marked by their fill alone. Below 3:1,edgethen asks them only for a fill of at least 1.05:1 against what is behind it, since the fill is what marks them at rest. Under forced colors the fill turns to the background, so there they need a 3:1 edge again.auditcannot hover, so check the hover edge's color where you set it. Pass it only for such fields: it is a design exception, not a fix.
A finding holds its rule, the element it is at and a message saying what to change; filter by rule to drop one. Filtering by edge or focus keeps the unmeasured findings, which name what audit could not check: check those by eye before you drop them.
Requirements
- @foldkit/ui and foldkit 0.170. A daily job tests each later release, and the range widens once one passes.
- StyleX 0.19.1 or a later 0.19 release, Vite 8.3.6 or later below 9 and Effect 4.1.2 or a later 4.x release.
foldkitStylex()in every Vite and Vitest config that loads the package.- StyleX's default
styleResolution. The layer checks follow its precedence, sofoldkitStylex()does not take the option.
Limitations
- Vitest started with a mode other than
testloads StyleX's Vite plugin, whose dev server keeps Vitest from exiting. - A popover nested in another popover's panel with
portal: falseplaces its arrow by the outer panel's side, because the arrow follows the nearest Popover panel'sdata-placement. - A
transform,filterorcontainer-typeon an ancestor of an anchored component confines its fixed backdrop to that ancestor. - Inactive tab panels are always hidden, so two mounted panels cannot cross-fade.
- The checks read styles passed to a view as separate arguments. Styles spread from an untyped array, as in
PopoverStyle.view(Popover.view, ...looks), are checked part by part but not against each other or earlier layers. An array typed with anXStyle.Stylestype is not checked at all, which the lint preset reports. A value typedanyis not checked. - In one list of styles, such as a part's
[base, styles.pad]or the arguments ofsx, or inside a pseudo-element such as::before, StyleX still applies an earlier longhand over a later shorthand, with no error: set the longhand. light-dark()colors stay as written for browsers without it, which then show no color for them.
Migration from foldstylex
| foldstylex | This package |
|---|---|
sxAttrs(h, ...styles) | sx(...styles), last in the attribute list |
A wrapper module per component, such as Button.view with variant keys | XStyle.view(X.view, styles) around @foldkit/ui's own view; variants are your own styles chosen in a state function |
styledViewInputs(model, config) | The wrapped view in h.submodel |
":is([data-checked])" keys | (state) => [styles.box, state.isChecked && styles.checked] |
@foldstylex/tokens | @kutur-kit/foldkit-stylex-theme, or your own defineVars |
stylex.vite() and aliases to package sources | foldkitStylex() |