Skip to content

Latest commit

 

History

History
289 lines (204 loc) · 14.4 KB

COMPONENT_REFERENCE.md

File metadata and controls

289 lines (204 loc) · 14.4 KB

Component Reference

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

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.
  • FaencyProvider applies the theme class for the resolved theme and primary color to document.body, and mounts the Radix Tooltip provider. Every component needs it: useInlineStyle calls useFaencyTheme(), which throws outside the provider.
  • Storybook wraps every story in FaencyProvider in .storybook/preview.jsx, and its theme toggle switches light and dark for all stories.

The css Prop

Every component supports css. Add CSSProps to its props, then:

const mergedStyles = useInlineStyle(css, style);

return <Component className={cx(recipeClass, className)} style={mergedStyles} {...props} />;
  • useInlineStyle resolves the css prop with the same rules as styleRule() and merges style over it. Don't resolve css by hand.
  • useInlineStyle inserts the css object 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 with styleOf(element) from styles/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 beat css.
  • Pass values that change often, such as a dragged width, through a createVar() set with assignInlineVars, not through css: each distinct css object adds a rule.
  • cx joins class names and skips empty ones. Use it rather than template strings or .join(' ').
  • CSSProps accepts both shorthands (p, m) and full names (padding, margin).
  • A prop that takes a css object itself, such as rootCss, is typed CSSProps['css'], not CSSProps (see Textarea.tsx). An as any in a test usually points to this mistake.

Naming

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, component Text, displayName 'Text'
  • For polymorphic components, the internal type is TextComponent and the implementation TextComponentImpl
  • Recipes are camelCase with a Recipe suffix: 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.


Variants

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).


Polymorphic Components and Radix Parts

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:

  1. Use PolymorphicComponentProps<C, OwnProps> from styles/polymorphic.ts for the props type
  2. Cast the implementation to the PolymorphicComponent type

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.


Component Theme Tokens

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).

  1. Add the token names to the colors object in styles/tokens.css.ts (flat, not nested)

  2. 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,
    };
  3. Use them as tokens.colors.<name> in the .css.ts file

Values that depend on runtime colors (e.g. textInvalid, from the red scale) are set directly in styles/themes.css.ts.


Patterns

Hover and Active States

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.

Child Selectors

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' });

Shared Text Variants

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.

Reading the Theme

const { colors, resolvedTheme } = useFaencyTheme();

Tests

Every component has a ComponentName.test.tsx covering:

  • Rendering and the element type
  • Every variant prop
  • className, style, css (with tokens), and css merged with style
  • as, 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:ci runs with --silent, which hides console.error; use yarn test to see warnings

Exports and Breaking Changes

  1. Export the component, its parts and props types from the component's index.ts (see components/Button/index.ts)
  2. Add them to the root index.ts too: it uses explicit named exports, no export *
  3. 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

Troubleshooting

Theme Not Applied

Use tokens from styles/tokens.css.ts instead of hard-coded values, and check that the tree is wrapped in FaencyProvider.

css Prop Ignored

Check that the component destructures both css and style and passes useInlineStyle(css, style) to the element's style.

act() Warning With Async Event Handlers

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 = true in jest.setup.js: RTL restores the flag after each act
  • await act(async () => { await userEvent.click(button); await Promise.resolve() }): userEvent already processes microtasks between its steps, so the promise resolves during the click, too early for the extra Promise.resolve() to help