The detailed rules behind Faency's components: styling internals, naming, typing, tests and known pitfalls. Start with CONTRIBUTING.md, and come here when you need the details.
- Styling Internals
- Naming
- Variants
- Polymorphic Components and Radix Parts
- Component Theme Tokens
- Patterns
- Tests
- Exports and Breaking Changes
- Troubleshooting
styles/
├── tokens.css.ts # Theme contract (design token definitions)
├── themes.css.ts # Light/dark theme classes, one per theme × primary color
├── themeContext.tsx # FaencyProvider and useFaencyTheme
├── cssProps.ts # `CSSProps` and `CSS` types for the `css` prop
├── cssRule.ts # `css` prop to inline styles, or to a <style> rule for selectors
├── useInlineStyle.ts # Turns `css` + `style` into the element's style object
├── cx.ts # Class name joiner
├── resolveColor.ts # Resolves `$token` color props (Meter, Spinner) to tokens
├── breakpoints.css.ts # Media queries (mobile–desktop, hover, motion, dark, light)
├── polymorphic.ts # Polymorphic component types
├── createPolymorphicPart.tsx # Factory for Radix parts that take `as`
├── recipeVariants.ts # RecipeVariantProps and splitVariants
├── stateLayers.ts # Hover/active colors as background-image layers
├── styleRule.ts # styleRule, globalStyleRules, keyframesRule (also public via vanilla.ts)
├── types.ts # Shared prop types (spacing, size tokens, …)
├── textVariants.css.ts # Shared text variant definitions
├── utils.css.ts # Utility recipes
└── index.ts # Barrel for some of the files above
- vanilla-extract generates static CSS at build time. The vite.config.ts build uses
preserveModules, so each component ships its own JS and CSS file. FaencyProviderapplies the theme class for the resolved theme and primary color todocument.body, and mounts the Radix Tooltip provider. Every component needs it:useInlineStylecallsuseFaencyTheme(), which throws outside the provider.- Storybook wraps every story in
FaencyProviderin .storybook/preview.jsx, and its theme toggle switches light and dark for all stories.
Every component supports css. Add CSSProps to its props, then:
const mergedStyles = useInlineStyle(css, style);
return <Component className={cx(recipeClass, className)} style={mergedStyles} {...props} />;useInlineStyleresolves thecssprop with the same rules asstyleRule()and mergesstyleover it. Don't resolvecssby hand.useInlineStyleinserts thecssobject as a rule into a<style data-faency>tag, and returns a--faency-<hash>custom property that the rule's[style*="…"]selector matches. So the returned style must reach the element as is: don't rebuild it or pick properties out of it. In tests, read the result withstyleOf(element)fromstyles/styleOf.ts.- The rule's plain properties have specificity (0,1,2): they beat a single class but lose to state selectors such as
.x:hover(0,2,0). Keep base styles at one class. To beat another component's base in any stylesheet order, use'&:not(_)'(0,1,1), not'&&', which would also beatcss. - Pass values that change often, such as a dragged width, through a
createVar()set withassignInlineVars, not throughcss: each distinctcssobject adds a rule. cxjoins class names and skips empty ones. Use it rather than template strings or.join(' ').CSSPropsaccepts both shorthands (p,m) and full names (padding,margin).- A prop that takes a
cssobject itself, such asrootCss, is typedCSSProps['css'], notCSSProps(see Textarea.tsx). Anas anyin a test usually points to this mistake.
| File | Holds |
|---|---|
ComponentName.tsx |
The component |
ComponentName.css.ts |
Styles and recipes |
ComponentName.test.tsx |
Tests |
ComponentName.stories.tsx |
Stories |
ComponentName.theme.ts |
Component theme tokens, if needed |
index.ts |
The component's exports |
In code (see Text.tsx):
- Props type
TextProps, componentText,displayName'Text' - For polymorphic components, the internal type is
TextComponentand the implementationTextComponentImpl - Recipes are camelCase with a
Recipesuffix:textRecipe,buttonRecipe
Radix parts re-exported unwrapped (export const Popover = PopoverPrimitive.Root) get no …Props alias; consumers use React.ComponentProps<typeof Popover>. Add a …Props type once the part is wrapped.
Type variant props with RecipeVariantProps from styles/recipeVariants.ts, not RecipeVariants from @vanilla-extract/recipes:
// Bad: includes undefined, so `extends` or `Omit<…, never>` silently drops every variant prop
type MyComponentVariants = RecipeVariants<typeof myComponentRecipe>;
// Good: numeric keys ('1', '2', ...) also accept numbers, e.g. size={2}
type MyComponentVariants = RecipeVariantProps<typeof myComponentRecipe>;
interface MyComponentOwnProps extends MyComponentVariants, CSSProps {}Take the variant props out with splitVariants instead of listing them by hand. It reads the variant names from the recipe, so a variant added later reaches the class and never lands on the DOM. It also turns numbers into their string keys, since recipes match compound variants with ===:
({ as, className, css, style, ...rest }: MyComponentProps<C>, ref) => {
const [variants, props] = splitVariants(myComponentRecipe, rest);
const recipeClass = myComponentRecipe(variants);When you call a recipe with hand-picked or default values, pass the string key (size: '2'); a number is a type error.
A broken variant type drops the props silently instead of failing, so add a valid line and an invalid @ts-expect-error line (e.g. variant="nope") for each component to styles/componentVariantProps.test.tsx. yarn typecheck checks it in CI.
When a recipe has variants, put all base styles (font sizes, dimensions…) in the recipe's base, not in a separate style(), or they can be missed when variants are applied (see Heading.css.ts).
Components take the polymorphic as prop unless their element is fixed: form controls (Input, TextField, Textarea), lists (Ul, Ol, Li) and table parts. See Badge.tsx:
- Use
PolymorphicComponentProps<C, OwnProps>from styles/polymorphic.ts for the props type - Cast the implementation to the
PolymorphicComponenttype
Radix parts that render an element (triggers, items, anchors) take as instead of exposing asChild. Internally they pass asChild to the Radix primitive and render the as element inside it, so the Radix behavior lands on that element. Build them with createPolymorphicPart, which also handles css, style and a base class:
export const DropdownMenuItem = createPolymorphicPart<'div', DropdownMenuItemOwnProps>(
DropdownMenuPrimitive.Item,
{ displayName: 'DropdownMenuItem', className: dropdownMenuItem },
);Parts that don't take as omit asChild from their props. See Popover.tsx and DropdownMenu.tsx.
A component with its own colors keeps them in ComponentName.theme.ts, as plain light and dark objects such as textLightTheme / textDarkTheme (see Text.theme.ts).
-
Add the token names to the
colorsobject in styles/tokens.css.ts (flat, not nested) -
Spread the objects into the light and dark colors in styles/themes.css.ts:
import { badgeDarkTheme, badgeLightTheme } from '@/components/Badge/Badge.theme'; const lightSemanticColors = { // ... ...badgeLightTheme, };
-
Use them as
tokens.colors.<name>in the.css.tsfile
Values that depend on runtime colors (e.g. textInvalid, from the red scale) are set directly in styles/themes.css.ts.
Draw state colors as background-image layers with stateLayers, not on ::before or ::after. A consumer's background-color then keeps the states, and the pseudo-elements stay free for consumers. From Button.css.ts:
selectors: {
'&:focus-visible': { backgroundImage: stateLayers(HOVER_LAYER) },
'&:active, &:hover:active': { backgroundImage: stateLayers(PRESSED_LAYER) },
},
'@media': {
[breakpoints.hover]: {
selectors: { '&:hover': { backgroundImage: stateLayers(HOVER_LAYER) } },
},
},Wrap :hover in breakpoints.hover from breakpoints.css.ts, so touch screens don't keep the hover after a tap. Use the breakpoints values rather than writing media queries by hand.
style() only allows selectors that target the element itself (&:hover, &::before). Selectors for children or siblings (& > div, & h1) throw Invalid selector, so use globalStyle() for them:
export const skeleton = style({
selectors: { '&:not(:empty)': { maxWidth: 'fit-content' } },
});
globalStyle(`${skeleton}:not(:empty) > *`, { visibility: 'hidden' });Text-like components with the same variants as Text import them from styles/textVariants.css.ts (see Label.css.ts and Blockquote.css.ts). Don't use them when the component needs different variant behavior.
const { colors, resolvedTheme } = useFaencyTheme();Every component has a ComponentName.test.tsx covering:
- Rendering and the element type
- Every variant prop
className,style,css(with tokens), andcssmerged withstyleas, if supported- Ref forwarding and HTML attribute pass-through
- Accessibility with
jest-axe - Light and dark themes
- Variant prop types, in styles/componentVariantProps.test.tsx
Input.test.tsx is the model to follow. The basic shape:
const renderWithTheme = (ui: React.ReactElement) => render(<FaencyProvider>{ui}</FaencyProvider>);
it('should have no accessibility violations', async () => {
const { container } = renderWithTheme(<Component>Content</Component>);
expect(await axe(container)).toHaveNoViolations();
});
it('should apply size variants', () => {
(['small', 'medium', 'large'] as const).forEach((size) => {
const { container, unmount } = renderWithTheme(<Component size={size}>Content</Component>);
expect(container.firstChild).toBeInTheDocument();
unmount(); // otherwise the next render finds several elements
});
});- Always render inside
FaencyProvider - Query Radix parts by their real role (e.g.
role="radio"for ButtonSwitch items) - Pin the clock in tests that depend on today's date (see DateTimePicker.test.tsx)
yarn test:ciruns with--silent, which hidesconsole.error; useyarn testto see warnings
- Export the component, its parts and props types from the component's
index.ts(see components/Button/index.ts) - Add them to the root index.ts too: it uses explicit named exports, no
export * - A change to an existing API or styling that consumers must react to needs a major release (a
BREAKING CHANGE:footer) and an entry in MIGRATION.md
Use tokens from styles/tokens.css.ts instead of hard-coded values, and check that the tree is wrapped in FaencyProvider.
Check that the component destructures both css and style and passes useInlineStyle(css, style) to the element's style.
Warning: The current testing environment is not configured to support act(...) fires when setState runs after an await in an event handler, and that microtask resolves outside an active act(). RTL's act sets IS_REACT_ACT_ENVIRONMENT only for its own duration, so a handler like await clipboard.writeText() → setState() that resolves later triggers the warning.
For a click-then-assert test, use waitFor after the click, which suppresses the warning while it polls:
await userEvent.click(button);
await waitFor(() => expect(button).toHaveTextContent('Copied!'));For a fake-timer test, click with fireEvent (synchronous), then drain the microtask queue inside act, so the promise resolves while the flag is still set:
jest.useFakeTimers({ legacyFakeTimers: true }); // modern timers also fake queueMicrotask, which React 18 needs
await act(async () => {
fireEvent.click(button);
await Promise.resolve();
});
expect(button).toHaveTextContent('Copied!');
act(() => jest.advanceTimersByTime(1500));
expect(button).toHaveTextContent('Copy');Add afterEach(() => jest.useRealTimers()): axe uses setTimeout and hangs if timers are still faked.
What does not work:
- Setting
global.IS_REACT_ACT_ENVIRONMENT = trueinjest.setup.js: RTL restores the flag after eachact await act(async () => { await userEvent.click(button); await Promise.resolve() }):userEventalready processes microtasks between its steps, so the promise resolves during the click, too early for the extraPromise.resolve()to help