Skip to Content
vitus·labs
Guides

Building a Design System

Step by step from design tokens to a Button and a Card built with rocketstyle, attrs and elements, with generated Storybook stories.

This guide builds a small component library: a theme with design tokens, a few base primitives, a Button with states, sizes and pseudo states, and a Card that composes Element's three slots. The result is exported from one entry point, and its stories are generated with rocketstories.

Packages used: core, styler connector, unistyle, elements, attrs, rocketstyle, rocketstories.

npm install @vitus-labs/core @vitus-labs/styler @vitus-labs/connector-styler @vitus-labs/unistyle @vitus-labs/elements @vitus-labs/attrs @vitus-labs/rocketstyle @vitus-labs/hooks
src/ui/
├── init.ts        # init() side effect
├── theme.ts       # design tokens
├── Provider.tsx   # theme + mode provider
├── rocket.ts      # shared rocketstyle factory + theme → CSS helper
├── primitives.ts  # attrs-based primitives
├── Button.tsx
├── Card.tsx
└── index.ts       # public entry point

1. Initialize the engine

src/ui/init.ts
import * as connector from '@vitus-labs/connector-styler'
import { init } from '@vitus-labs/core'

init({ ...connector, component: 'div', textComponent: 'span' })

Every component module imports ./init for its side effect, so the engine is configured whichever module loads first. On Next.js these are all 'use client' modules — never import the engine from a server component. See SSR & Static Export.

2. Define the tokens

The theme is a plain object. rootSize and breakpoints drive unistyle: numbers become rem (16 → 1rem with rootSize: 16) and responsive values become mobile-first @media rules. Everything else is your vocabulary:

src/ui/theme.ts
export const theme = {
  rootSize: 16,
  breakpoints: { xs: 0, sm: 576, md: 768, lg: 992, xl: 1200 },

  fontFamily: {
    base: 'Inter, system-ui, sans-serif',
  },
  fontSize: { sm: 13, md: 15, lg: 17 },
  space: { xs: 4, sm: 8, md: 16, lg: 24, xl: 32 },
  radii: { sm: 4, md: 8, lg: 12, pill: 999 },
  color: {
    white: '#ffffff',
    gray50: '#f9fafb',
    gray200: '#e5e7eb',
    gray800: '#1f2937',
    gray900: '#111827',
    blue400: '#60a5fa',
    blue600: '#2563eb',
    blue700: '#1d4ed8',
    red400: '#f87171',
    red600: '#dc2626',
    red700: '#b91c1c',
  },
} as const

export type Theme = typeof theme

3. Provide the theme

Rocketstyle's Provider passes theme and mode to every rocketstyle component. Unistyle's Provider (passed as provider) adds the breakpoint helpers that responsive values need:

src/ui/Provider.tsx
'use client'

import './init'
import { Provider } from '@vitus-labs/rocketstyle'
import { Provider as UnistyleProvider } from '@vitus-labs/unistyle'
import type { ReactNode } from 'react'
import { theme } from './theme'

export function UIProvider({
  mode = 'light',
  children,
}: {
  mode?: 'light' | 'dark'
  children: ReactNode
}) {
  return (
    <Provider provider={UnistyleProvider} theme={theme} mode={mode}>
      {children}
    </Provider>
  )
}

Switching mode and following the OS preference are covered in Theming & Dark Mode.

4. A shared factory and a theme-to-CSS helper

Rocketstyle computes a theme object, $rocketstyle, per render: the base theme merged with the active dimensions. It does not emit CSS by itself. .styles() decides how $rocketstyle becomes CSS.

Unistyle's makeItResponsive + styles turn a theme object into CSS. They know 170+ properties, expand shorthands such as paddingX, convert numbers to rem and handle responsive values. One shared helper covers every component. It also maps hover / focus / active / disabled sub-objects to real CSS pseudo selectors, so no JavaScript hover tracking or re-render is needed:

src/ui/rocket.ts
import './init'
import { rocketstyle } from '@vitus-labs/rocketstyle'
import { makeItResponsive, styles } from '@vitus-labs/unistyle'

/** One factory for the whole library: boolean shorthands on (`<Button primary lg>`). */
export const rs = rocketstyle({ useBooleans: true })

type CssFn = (...args: any[]) => any

/**
 * $rocketstyle → CSS via unistyle's property map. Pseudo-state
 * sub-objects become CSS selectors; `disabled` comes last so it wins.
 */
export const themeToCss = (css: CssFn) => css`
  ${({ $rocketstyle }: { $rocketstyle: Record<string, any> }) => {
    const { hover, focus, active, disabled, ...base } = $rocketstyle
    const toCss = (theme: Record<string, any>) =>
      makeItResponsive({ theme, styles, css })

    return css`
      ${toCss(base)};
      ${hover ? css`&:hover { ${toCss(hover)}; }` : ''};
      ${focus ? css`&:focus-visible { ${toCss(focus)}; }` : ''};
      ${active ? css`&:active { ${toCss(active)}; }` : ''};
      ${disabled ? css`&:disabled { ${toCss(disabled)}; }` : ''};
    `
  }};
`

This is the same pattern this site uses for its landing page components.

Pseudo states: CSS selectors or $rocketstate

Rocketstyle also exposes pseudo state to .styles() as $rocketstate.pseudo (hover, focus, pressed, active, disabled, readOnly). active, disabled and readOnly come from props. hover, focus and pressed are tracked automatically only on components with .config({ provider: true }), which also share them with consumer children. Use CSS selectors (as above) for a component's own hover and focus styles. Use $rocketstate.pseudo when a parent's state must restyle its children. See Provider & Consumer.

5. Base primitives with attrs

Use attrs for components that only need default props and no dimensions. These are thin presets over Element and Text:

src/ui/primitives.ts
import './init'
import { attrs } from '@vitus-labs/attrs'
import { Element, Text } from '@vitus-labs/elements'

/** Full-width flex row: children pushed to both ends. */
export const Bar = attrs({ name: 'Bar', component: Element }).attrs({
  block: true,
  // no before/after slots → the root takes the content* layout props
  contentDirection: 'inline',
  contentAlignX: 'spaceBetween',
  contentAlignY: 'center',
})

/** Semantic heading. `level` picks the tag and never reaches the DOM. */
export const Heading = attrs({ name: 'Heading', component: Text }).attrs<{
  level?: 1 | 2 | 3 | 4
}>(({ level = 2 }) => ({ tag: `h${level}` as const }), { filter: ['level'] })

/** Paragraph text. */
export const Paragraph = attrs({ name: 'Paragraph', component: Text }).attrs({
  paragraph: true,
})

Props merge as priority attrs → attrs → explicit props, so <Bar contentAlignY="top"> still overrides the preset.

Simple vs. compound Element

An Element without beforeContent / afterContent renders a single wrapper, and that wrapper takes the contentDirection / contentAlignX / contentAlignY props (contentDirection defaults to 'rows'). direction / alignX / alignY lay out the slots once side content is present. See Element: DOM Structure.

6. A Button with dimensions

The default dimensions are states → state, sizes → size, variants → variant, multiple → multiple, and the transform dimension modifiers → modifier. Each becomes a chain method. With useBooleans, every option is also a boolean prop:

src/ui/Button.tsx
'use client'

import './init'
import { Element } from '@vitus-labs/elements'
import { rs, themeToCss } from './rocket'

export const Button = rs({ name: 'Button', component: Element })
  .attrs({
    tag: 'button',
    type: 'button',
    alignX: 'center', // slots, when an icon is passed
    alignY: 'center',
    contentAlignX: 'center', // the label
    gap: 8,
  })
  // base theme: shared by every state and size
  .theme((t, mode) => ({
    fontFamily: t.fontFamily.base,
    fontWeight: 600,
    lineHeight: 1,
    borderRadius: t.radii.md,
    borderWidth: 1,
    borderStyle: 'solid',
    borderColor: 'transparent',
    backgroundColor: mode(t.color.gray50, t.color.gray800),
    color: mode(t.color.gray900, t.color.white),
    cursor: 'pointer',
    transition: 'background-color .15s ease, border-color .15s ease',
    hover: { backgroundColor: mode(t.color.gray200, t.color.gray900) },
    focus: { outline: `2px solid ${t.color.blue600}`, outlineOffset: 2 },
    active: { transform: 'translateY(1px)' },
    disabled: { opacity: 0.5, cursor: 'not-allowed', transform: 'none' },
  }))
  // state: color intent
  .states((t, mode) => ({
    primary: {
      backgroundColor: mode(t.color.blue600, t.color.blue400),
      color: mode(t.color.white, t.color.gray900),
      hover: { backgroundColor: mode(t.color.blue700, t.color.blue600) },
    },
    danger: {
      backgroundColor: mode(t.color.red600, t.color.red400),
      color: mode(t.color.white, t.color.gray900),
      hover: { backgroundColor: mode(t.color.red700, t.color.red600) },
    },
  }))
  // size: spacing + type scale (numbers → rem)
  .sizes((t) => ({
    sm: { fontSize: t.fontSize.sm, paddingX: 12, paddingY: 6 },
    md: { fontSize: t.fontSize.md, paddingX: 16, paddingY: 10 },
    lg: { fontSize: t.fontSize.lg, paddingX: 24, paddingY: 14 },
  }))
  // variant: shape
  .variants((t) => ({
    pill: { borderRadius: t.radii.pill },
    square: { borderRadius: 0 },
  }))
  // modifier: derived from whatever state is active, applied last
  .modifiers({
    outlined: (current) => ({
      backgroundColor: 'transparent',
      color: current.backgroundColor,
      borderColor: current.backgroundColor,
      hover: { backgroundColor: 'transparent', color: current.hover?.backgroundColor },
    }),
  })
  .styles(themeToCss)
<Button>Default</Button>
<Button state="primary" size="lg">Save</Button>
<Button primary lg>Save</Button>               {/* boolean shorthand */}
<Button danger outlined pill>Delete</Button>   {/* state + modifier + variant */}
<Button primary disabled>Saving…</Button>      {/* :disabled styles */}
<Button primary beforeContent={<PlusIcon />}>New</Button>

How it resolves:

  • $rocketstyle = base theme, then the active state, size and variant in that order, then the outlined transform. The transform receives the theme accumulated so far. See Transform Dimensions.
  • mode(light, dark) values are resolved for the provider's mode.
  • disabled is not a dimension. It reaches the <button>, so the :disabled styles apply and the browser blocks clicks. Don't name dimension options after DOM props you also pass: a truthy disabled prop would activate an option called disabled.
  • beforeContent / afterContent are Element slots, and gap spaces them from the label.

7. A Card that composes Element

Element has three slots: beforeContent, content (children) and afterContent. With direction: 'rows' they stack into a header, body and footer:

src/ui/Card.tsx
'use client'

import './init'
import { Element } from '@vitus-labs/elements'
import { rs, themeToCss } from './rocket'

export const Card = rs({ name: 'Card', component: Element })
  .attrs({
    block: true,
    direction: 'rows', // before / content / after stacked vertically
    alignX: 'block', // stretch every slot to full width
    alignY: 'top',
    gap: 16, // space between the slots
  })
  .theme((t, mode) => ({
    padding: t.space.lg,
    borderRadius: t.radii.lg,
    borderWidth: 1,
    borderStyle: 'solid',
    borderColor: mode(t.color.gray200, t.color.gray800),
    backgroundColor: mode(t.color.white, t.color.gray900),
    color: mode(t.color.gray900, t.color.white),
  }))
  .variants({
    elevated: {
      borderColor: 'transparent',
      boxShadow: '0 8px 24px rgba(0, 0, 0, 0.08)',
    },
    flat: { borderColor: 'transparent' },
  })
  .styles(themeToCss)
import { Bar, Button, Card, Heading, Paragraph } from '@/ui'

<Card
  elevated
  beforeContent={<Heading level={3}>Pro plan</Heading>}
  afterContent={
    <Bar>
      <Paragraph>$12 / month</Paragraph>
      <Button primary>Upgrade</Button>
    </Bar>
  }
>
  <Paragraph>Unlimited projects, priority support and SSO.</Paragraph>
</Card>

.theme() and dimension methods accept a plain object as well as a callback (as with .variants() above).

Element passes every slot through core's render(), so beforeContent can be an element, a component or a render function. If a card has no side content, Element renders a single wrapper with no inner slots. See Element: DOM Structure.

8. Export the library

src/ui/index.ts
export { Button } from './Button'
export { Card } from './Card'
export { Bar, Heading, Paragraph } from './primitives'
export { UIProvider } from './Provider'
export { theme } from './theme'

Each component is a regular React component and stays chainable. Consumers can create local variants without forking:

const CompactButton = Button.attrs({ size: 'sm' }).sizes({ sm: { paddingX: 8 } })
const DangerZoneCard = Card.theme((t) => ({ borderColor: t.color.red600 }))

Each chain call returns a new component, and the original is never mutated.

For typing a library's public props, see Rocketstyle Types.

9. Generate stories

Rocketstories reads a rocketstyle component's dimensions and writes the Storybook stories for you. Wrap stories in the same providers with a small decorator:

.storybook/ThemeDecorator.tsx
import { Provider } from '@vitus-labs/rocketstyle'
import { Provider as UnistyleProvider } from '@vitus-labs/unistyle'
import { theme } from '../src/ui/theme'

export const ThemeDecorator = (Story) => (
  <Provider provider={UnistyleProvider} mode="light" theme={theme}>
    <Story />
  </Provider>
)
src/ui/Button.stories.tsx
import { init } from '@vitus-labs/rocketstories'
import { ThemeDecorator } from '../../.storybook/ThemeDecorator'
import { Button } from './Button'
import { theme } from './theme'

const storyOf = init({ theme, decorators: [ThemeDecorator] })

const stories = storyOf(Button).attrs({ label: 'Button' })

export default stories.init

export const Default = stories.main() // controls for every dimension + pseudo states
export const States = stories.dimension('state')
export const Sizes = stories.dimension('size')
export const Modifiers = stories.dimension('modifier')

stories.init is a property, not a method. dimension() takes the prop name ('state', not 'states').

Next steps

Edit on GitHub

Last updated on

On this page