FacetDocs

React

A design can be written in React. facet react renders the file with your project's own React, without a browser or a dev server, and builds the result into a document the way build --sync does: run it again and only what changed changes.

facet --doc design.facet react render screen.tsx --props data.json
facet --doc design.facet react render screen.tsx --props data.json --watch   # again on every save
facet react render screen.tsx -o screen.json                                 # the build JSON, to read

It needs Node.js 20 or later. The first run installs the tool's packages once. A component is rendered once everything it loads lazily has loaded (React.lazy behind Suspense: an editor, a chart), so the render shows the part itself, not its loading skeleton; with React 17 or earlier it is rendered at once.

The pieces

@facet/react gives the build language as components. A prop is a key of the language, written as the language writes it, so everything on the other pages applies: gap, padding, fill, width="fill", dividers, at, grow.

import { Box, Column, Kit, Row, Span, Text, component } from "@facet/react";

const Switch = component("Switch", { variants: { State: ["Off", "On"] } }, ({ State }) => (
  <Row width={34} height={20} padding={2} cornerRadius={10}
       fill={State === "On" ? "@accent" : "@line"} justify={State === "On" ? "end" : "start"}>
    <Box name="Knob" size={16} cornerRadius={8} fill="#FFFFFF" />
  </Row>
));

export default function Settings({ options }) {
  return (
    <Column name="Settings" width={320} padding={16} gap={12} fill="@paper" color="@ink">
      <Kit font="Inter 14/20" colors={{ ink: "#1A1423", paper: "#FFFFFF", line: "#E4DEE8", accent: "#6E56CF" }} />
      <Text>Awake <Span fontWeight={700}>until 4:30</Span></Text>
      {options.map((option) => (
        <Row key={option.id} width="fill" align="center">
          <Text width="fill">{option.title}</Text>
          <Switch State={option.on ? "On" : "Off"} />
        </Row>
      ))}
    </Column>
  );
}
PieceIs
Row, Column, Grid, Stack, Ring, Framethe containers
Text, Spana text; a Span styles part of it; a component among the words makes it a sentence that wraps around it
Icon, Box, Spacean icon (name="lucide:bell"), a layer with no children, room in a flow: <Space /> fills, <Space size={12} /> is 12 px
Draw with Circle, Ellipse, Rect, Line, Poly, Arc, Path, Plot, Barsa drawing; shapes take at (or d, or values) and their paint
Connect<Connect from="A" to="B">label</Connect>: an arrow between two named layers
Kitthe file's kit, said in the code: colours with modes, type presets, the font, use="facet:basics"
Usea kit part, preset or component by name: <Use chip="Open" />
component(name, { props, variants }, render)a component of the design
Nodeany other node, as JSON

What React gives the design

  • Components are components. component() makes one master in Facet and an instance at every use. props are its text properties ({ Label: "Draft" }), variants its axes, the first value of each the default; a variant is stored as what differs from the default. A variant that adds or removes layers is reported (VARIANT_SHAPE).
  • Tokens live in the code. <Kit> anywhere in the screen is sent with it; nothing is sent separately.
  • Keys. React's key, on a piece or on a component of yours that is mapped over data, is the layer's key: a reordered or renamed row is moved, not replaced.
  • Types. The package types every piece from Facet's own grammar (facet guide types), so a wrong value, a wrong word or a variant a component does not have is a compile error in your editor, when the project has the package's types: a project that installs @facet/react, or a tsconfig.json whose paths point @facet/react at the tool's copy (~/.facet/react/BUILD/src/index.d.ts). A render does not type-check: there a wrong prop is an INPUT_IGNORED warning with the nearest key and the line that wrote it.
  • Source lines. Every layer carries the line that wrote it. Facet's warnings about it end with (source: screen.tsx:42), and facet inspect shows it.
  • Your app's components go in beside Facet's pieces and are read through their CSS (for a Tailwind project, --css names the stylesheet). What the reader does not understand is reported as CSS_UNREAD, never dropped silently.

Options

OptionDoes
--project DIRthe project whose React and packages the file uses (default: the current folder)
--props FILEJSON given to the component as its props
--export NAMErender that export instead of the default one
--page NAMEbuild into that page whatever is showing
--preview PNGwrite a picture of what was built
--watchrender again when the file, the project's sources or the data change
-o FILEwrite the build JSON to a file and build nothing

facet react stories button.stories.tsx reads a Storybook stories file: the component as a set from its variant options, and each story.

The way back

An edit made in Facet to a rendered layer is overwritten by the next render, as with any generator: the source is the truth. To keep the edit, take it back: facet --doc design.facet react source "Options" (a layer's name, its id, or a selector such as "List > Row" when names repeat) prints that layer as Facet holds it now, written with the pieces, and facet inspect (or any warning about it) names the file and line it came from. Paste it there.

<Column name="Options" width="fill" dividers="@line">
  <Row name="Keep the display on" gap={10} padding={[6,4]} align="center" width="fill">
    <Icon name="lucide:monitor" size={15} />
    <Text width="fill">Keep the display on</Text>
    <Use Switch={{"State":"On"}} />
  </Row>
</Column>

A component or a kit part comes back as <Use Name={…} />: swap in your own component's name.

What of the app's CSS is read

App components are read through the project's stylesheet the way a browser reads it: every rule whose selector matches an element counts, not only its own classes. That covers rules for elements (h2, button), children and siblings (.card > p + p, Tailwind's space-y-2, divide-y, *:p-1, [&>svg]:size-4), attributes (data-[state=on]:…, aria-selected:…), position (first:, odd:), what an element holds (has-[>svg]:…), a checked box beside it (peer-checked:…), ids, @layer and !important; the winner is the one a browser would pick.

Breakpoints are answered for one page size, 1280 by 800 unless --viewport says another:

facet react render screen.tsx --viewport 390          # a phone: `md:` rules do not apply
facet react render screen.tsx --viewport 1440x900

What only holds in a state (hover:, focus:, group-hover:) or in the dark scheme is not drawn. What could not be read is said, by rule: CSS_RULE_UNREAD for a pseudo-element (::before, placeholder:), a container query, or a pseudo-class it does not know.

A page from a browser

facet react dom reads a page the way a browser laid it out: it opens the URL or HTML file in headless Chrome (a profile of its own; a Chrome you have open is not touched), asks for every element's computed style and box, and builds from that through the same map.

facet --doc design.facet react dom http://localhost:3000/orders --root main
facet react dom page.html --viewport 390x844 --tree tree.json -o screen.json

--root is a selector for the elements to read (the page's body when left out). A page behind a login is read from a Chrome that is already signed in: start one with a debugging port (or allow remote debugging in chrome://inspect/#remote-debugging) and pass its DevTools address as --attach ws://127.0.0.1:PORT/devtools/browser/…; the page opens in a tab of its own, which is closed when it has been read, and no other tab is looked at. The reader waits until the page has fetched and drawn what it was going to, and takes entrances that are still playing to their end. --shot page.png writes the browser's own picture of what was read, and --assets DIR says where the pictures of its images go. Nothing of the project is needed: no source, no stylesheet. What it cannot know is where a colour came from, so the layers hold colours, not tokens. render --html page.html writes a render as such a page, to see what a browser makes of the same component.

What only the browser knows is said in the tree, so the map needs no font and no stylesheet to place a layer where the page has it:

The tree saysSo the build
each element's boxgives children the room the browser measured, sizes table cells and shares (calc(100% + 2px), min-height: 100%) from it, and places a turned box by the upright box around it
words: the box around an element's own textfills a heading that its container stretched, where another line says how wide the container is
clipped: its content is cut off at its edgegives a truncated label, and a box that cuts what it holds, the width it was measured at (one line with an ellipsis)
::before, ::after and ::marker as elements of their ownbuilds a dot, a rule, a badge in a corner, a bullet or a number where the browser drew it
a shadow root's children and a slot's contentbuilds what a web component lays out
faces: the fonts the browser drew symbols insets an arrow or a sign the page's face lacks in the face that drew it
picture, alone on a clear groundan img, a canvas or a video frame as a picture; with flattened, an element no layer can draw (a filter other than blur, a mask, a clip path, a perspective) as one picture, said with CSS_FLATTENED
painteda background no fill can be (a repeating or conic gradient, blended layers) as a picture of the box's own paint, its children still layers
backgrounds: the pictures a background namesimage fills that cover, contain, tile or sit where background-position puts them, with gradients over them as layers
font-size as drawnuses the size font-size-adjust left, not the one the stylesheet wrote
an svg's paint in its markupdraws a ring or an icon coloured by a class: fill, stroke, width and dashes are written where the stylesheet set them, a colour as sRGB, the text colour as currentColor

Who drew it, every state, and the data behind it

A development build of a React app keeps a record on each element of the component that drew it, the props it was given and where in the code it was made. --components reads them and finds each file and line through the page's own source maps: every layer that a component of the app drew is named for it, and --sources sources.json writes, by layer name, the component, its props, the file that defines it (source) and the line that used it (used), so a change to the layer can go back to its code. A library's components and the framework's are left out. Nothing is added to the app; a production build has no such records and says COMPONENTS_UNKNOWN.

--states puts each element a person can act on (links, buttons, fields, anything with a pointer cursor) in hover, active and focus-visible through DevTools and writes what changes, in it and in what it holds, as its states.

--record DIR keeps every answer to the page's requests for data (not its scripts or pictures, and not the framework's own fetches of rendered components). --replay DIR answers those requests from the folder instead of the network, on any host, so a recording from a signed-in page renders the same on a local development server. --patch patch.json changes answers first: [{"match": "/api/items", "set": {"items[id=a1].status": "done", "total": 0}}] sets each path of the JSON of every answer whose URL holds match ([3] steps into a list by position, [id=a1] into each item whose id starts with a1). An entry with "answer" (and "status") is the answer whole, recorded or not: the reply to a write. One recording and a few patches are every state of a page, read at its real URL, with the app untouched. A request is matched by what it sent (method, path, query and body); one whose body the recording does not hold is answered with the recorded request on that path most like it, field by field, and said (REPLAY_LOOSE): an answer to another request may be of another shape, so if the page shows an error, record it again on this build or answer it with a patch. A read the recording does not hold goes to the network and is said (REPLAY_MISSED); a write it does not hold is never sent: it gets an empty 200 and is said (REPLAY_FAKED). (A recording made before 0.3.189 kept each answer in place of what was sent; its requests match by path, said as REPLAY_LOOSE. Record again to match by body.)

Before the page is read it is woken and held still: lazy pictures are asked for at once, the page is scrolled through a screen at a time and back (what fades in when it is seen is shown), the pictures are waited for (5 s at most), an entrance still playing is taken to its end, and what never ends (a spinner, a marquee, an SVG's own animation, a video) is held at its start, so two reads of a page agree. What a closed shadow root lays out is read as an open one's is; a frame is read through and clipped where the frame shows it, one of another origin through its own DevTools session; a drawing that uses a sprite's symbol or a gradient defined elsewhere in the page holds them; a drawing whose vectors cannot carry what it does (a filter, a picture inside it, words along a path, HTML inside it) is the browser's picture of it (CSS_FLATTENED), and its clip paths draw as masks; an image is its own file at its own size where Facet fits it as the page does (object-fit: cover is fill, contain is fit), else the browser's picture of it; and a closed <details> holds only its summary. The page's own faces come along: each family, weight and style it loaded is decoded from WOFF or WOFF2 into a font file, and goes into Facet's font cache (FONT_SHIPPED), so its words are drawn in the very files the page drew them in. A family Google Fonts does not offer keeps the page's name for it; one it does offer is often another version (blender.org's Inter sets 5% wider than today's), so the page's files go in renamed as the family and the page's host, Inter (blender.org), and the texts the page set in it name that: no other document's Inter changes. --theme dark (or light) reads the page in that colour scheme, as its prefers-color-scheme media queries draw it. Without it a page is read light, whatever the Mac's appearance, so a capture comes out the same at any hour; with --attach it is read as the browser you attached to shows it. --pick brings the page's tab to the front with DevTools' own element picker: what you click is what is read (as --root would name it). --absolute gives up the page's own layout: every box stands where the browser measured it and is as large, as a capture that keeps geometry exactly does; a box drawn at a scale is its layers there, at the scale, not a picture; by default the rows, columns and grids are rebuilt as auto layout, so the design stretches and wraps as the page does. --widths 1440,768,390 reads the page at each width in turn (its media queries answered for that width) and builds one screen for each, named 1440 wide, 768 wide and so on, side by side, each as wide as the width it was read at.

--open SELECTOR opens what it names before the page is read (a menu, a popover, a dialog, a side sheet): pressed with the pointer as a person would. Only if that press changed nothing at all (no element, word or request) is it tried from the keyboard, then by script, so a control that does something is never pressed twice. --click SELECTOR presses once and lets the page settle, with no check: a tab, an action, a toggle. With --each-step the page is read as it opens and again after each step, one screen each, side by side and named for the step (Start, Step 1 · click #more): a flow. Each step's read does the steps before it again from the page as it opens, so every screen comes out the same however often it is read. Give each once for each thing to do, in order; OPEN_FAILED, OPEN_MISSING and CLICK_MISSING say what did not happen, and CLICK_AMBIGUOUS (or OPEN_AMBIGUOUS) names a selector that matched several elements and which one, the first, was pressed.

--tokens names each element's colours by the page's own CSS variables: which declaration won, as DevTools has it, followed through a theme's aliases (--color-muted: var(--muted)) to the one that holds the colour, a tint as muted/50%, and a text colour no rule sets as its parent's. Each name's light and dark values are read too (the dark with the page's dark selector, such as .dark, on <html>). The build refers to them (@muted) and defines them as kit colours with Light and Dark modes, so the page switches theme as the app does. The page's scripts are held still from the read until its colours are named (a page fed by a stream draws itself again), a declaration that names a variable is taken over a base reset listed after it, and each name is kept only where it is the colour the browser painted (a tint by its alpha), so a name is never wrong; what is left is a value. --tokens-in PREFIX refers instead to the document's own variables named PREFIX<name> (@app/muted, with the page's colour as a fallback) and defines none: a design system that holds them as aliases to its roles restyles every captured screen when its mode changes.

facet react dom https://app.example.com/orders --attach ws://… --record rec/          # once, signed in
facet react dom http://localhost:3000/orders --attach ws://… --replay rec/ \
  --patch shipped.json --components --states --sources orders.sources.json -o orders.json

--assemble (on dom or map) turns those records into components, the units a change goes back to. Every component of the app that drew a frame is one set, used once or many times, named after the component whose code drew the layer (a popover or tooltip that only passes on what another component wrote names nothing: the component that wrote it does). Its uses become instances of it:

  • A prop whose values tell their looks apart (variant, size, isActive; two together when one is not enough) is a variant property. A flag a use leaves out is false.
  • Where a prop decides the shape (a button with words, or an icon alone), the template holds every shape's layers, each kept to the values that have it (only); shapes no prop tells apart are told apart by a Shape property.
  • The states read with --states are a State property (Default, Hover, Pressed, Focus), for a control a person presses (a button, a link, a tab, a field).
  • Each drawing is an icon component (Icons/page:NAME-N), so a use that draws another icon swaps it, as it says its own words.
  • Each instance keeps its place and says its own words, icons and the variants of the instances inside it as overrides (a layer inside a nested instance by its path, Settings > Icon), and any fill, colour, stroke or size that differs as its layers' own keys ($nodes).
  • Uses whose own layer is another kind of container (a row in one place, a column in another) are a set each. A prop whose values are prose (a tip, a title) varies by whether it is given (true, false), not by its words.

Components inside components are made first, so a set holds instances of the sets in it. A layer that looks like no variant of its set stays a layer.

Each layer a component drew keeps that component's file and line as its $source, and each instance where it is used when the read knows it, so a change made in Facet goes back to its code: facet where NODE names the components a layer is in, innermost first, each with its file, and the layer as the innermost component's own layer.

Stacking, effects and moves come across as a layer has them: z-index orders a box's children (one below zero goes behind the box its stacking starts at), transform, rotate, scale and translate (a turn, a skew, a scale, a mirror, or a 3D turn without a perspective, which the page shows flat) are the layer's matrix, its words and boxes inside it read upright and drawn through it, with margins that keep the room CSS gave it; only a perspective (or boxes turned in 3D together) is the browser's picture, and a back the page hides (backface-visibility: hidden) is left out; a relative box's offsets are margins that move nothing else, filter: blur() and backdrop-filter: blur() are blur effects, mix-blend-mode is blendMode, an outline is a stroke layer pinned outside the box, visibility: hidden is opacity 0, a box kept for a screen reader (clip: rect(0 0 0 0)) is left out, -webkit-line-clamp is maxLines, and white-space: pre keeps its spaces. Colours in a space wider than sRGB come as the sRGB the screen shows.

Texts of a page read this way are "fractional" (see Text): as wide as the browser measured them. Rows and groups of a table draw no borders unless the table's borders collapse, a grid's align-items is its align, width: max-content with min-width: 100% hugs with a least width, and room an inline run keeps beside itself (margin-left on a span) is a space in its sentence.

Checked on four screens of a running app at 1440 x 900: every layer's box is within 1.5 px of the browser's (185, 248, 620 and 228 boxes), and between 1.0% and 2.2% of pixels differ from the browser's own picture, nearly all of it the edges of letters, which the two rasterisers smooth differently. Colours are still values, not tokens, and nothing is a component yet.

A component as a package to build from

facet --doc design.facet react handoff Chip --out handoff/ writes what a developer, or a smaller model, needs to build the component Chip (a set or a single component) so verify matches it:

  • HANDOFF.md, the brief. It covers the data-part contract, how a build is checked, the rules that keep a build exact (border-box, padding already inside the border, the app's CSS variables, paint order, copying each variant's values rather than deriving a rule), the properties with their defaults, the modes, and every variant's parts with a box and CSS each.
  • handoff.json, the same as data: variants, and parts in tree order. Each part has a box relative to the root, its parent part, its CSS, for a vector its path as SVG, and its code line (source) when the design records one ($source, as dom --components and render write it). The package names the component's code (code): the set's or a variant's own line, else the file most of its parts were written in. The file also holds the variables, each with its value in every mode.
  • variables.css: every variable on :root, and each other mode of its collection under [data-mode="NAME"]. A build that imports it and uses the variables draws every mode.
  • A picture of each variant at 2×, named after it (state-idle.png), and icons/ with each icon as SVG in currentColor (each icon part's color says what it is drawn in).
  • behavior.json, when a statechart is bound to the component: its events, views and plays; slots, the layers its events act on ({"Label": ["PRESS"]}: a press on the part Label sends PRESS); and scenarios, the chart as a table a build can run as it is: each state names the view it shows (a value of the variant property) and where each event leads ("Saving": {"view": "Saving", "on": {"DONE": "Saved", "FAIL": "Idle"}}), with guards and variables already worked out per scenario. A component built on a headless behaviour library takes its state from the table, binds each slot's press to its events, and keeps the look from the variants.

Values bound to variables are written as var(--name, fallback): colours, and also sizes, radii, gaps, padding and opacity, so a mode that changes density changes the build too. A variable is named after the token (@Kit/line is --kit-line); --css-prefix app/ names the tokens under app/ after the app's own variables (@app/text-primary is --text-primary), which is how dom --tokens-in app/ names them. An instance inside the component is one part, named after its layer; its insides are its own component's handoff.

How the CSS keeps the design's geometry:

  • Hugging. A layer that hugs its content across a row or column is fit-content, because auto stretches there.
  • Placement. A layer placed by at, or inside a frame without auto layout, is position: absolute. Its left and top (or its inset, when it is pinned to the parent's edges) are measured as Facet measures them, from the parent's outer edge.
  • Paint order. Beside such a layer, every child has a z-index in Facet's paint order, so a background placed under a label stays under it.

Part names. A layer the design tool named by itself (Frame 1233) has a different number in every variant. Its part is named by its place instead: Lead › Frame 2, its parent's part and then its place among such siblings. That name is the same in every variant, and verify looks for the same name.

A built component against its design

facet --doc design.facet react verify URL --component "Composer/State=Idle, Mode=Light" measures a component a developer (or an agent) built against the component in the document, part by part.

The contract is one name per part. Each layer of the component has a name, and the built markup marks the same part with data-part="Name"; the root takes the component's root layer name. Parts pair by that name alone, never by order or class, so the markup can be structured any way. A name used several times pairs the nth with the nth.

What it measures. Every part's x, y, width and height are taken relative to its own root on each side, then compared. A part is within --tolerance px (0.5 by default) or it is reported with its deltas, worst first. Parts the build does not mark are listed, and so are marked parts the design does not have. Boxes are outer boxes on both sides: a Facet stroke is inside its box, as a CSS border is with box-sizing: border-box, so a bordered box's CSS padding is the Facet padding less the stroke.

Looks and pixels. Each part's fonts, colours and spacing are compared with what the browser computed, a stroke outside the box as an outline. A vector's paint is left to the pixels. --pixels also compares the root's picture with the design's (an isolated shot on --background, #ECECEC by default): at most --pixel-share (2%) of pixels may differ by more than --pixel-threshold (48), after both pictures are softened over 3×3 so edge smoothing does not count.

Modes. --mode Kit=Dark checks the variant in a mode of the design's variables. The design is switched to that mode while it is read and drawn, then put back, and the page should set data-mode to match.

Output. --json FILE (or --report FILE) writes the whole comparison for an eval to score, with both pictures beside it. The command exits 3 when anything is off, missing, or the root is unmarked. The page is read as dom reads it, so --viewport, --attach (a signed-in Chrome), --open and --click work the same; a Storybook story's iframe URL reads one story.

The trees between the render and the build

A render becomes a design in steps, and each step hands the next one file. The cascade finds the CSS in effect on every element and writes the declared tree: the elements, their attributes, and their styles as the stylesheet wrote them. The computed tree is the same elements with every var() replaced, every shorthand taken apart into longhands, lengths in px and each colour's token named. The map reads only the computed tree.

--tree tree.json writes the tree beside the result (the declared one from render, the computed one from dom), and facet react map tree.json builds from either alone, with no project, no React, no stylesheet and no Node at hand. --computed computed.json on map writes the computed tree it mapped:

facet react render screen.tsx --tree tree.json -o screen.json
facet --doc design.facet react map tree.json

So a design that comes out wrong can be looked at in halves: is the tree what the app's CSS says, and is the build what that tree means. tools/facet-react/CONTRACT.md in Facet's source describes every field of both trees.

What it does not do yet

Hover and focus states are not drawn. A component's behavior is passed through as the build language writes it (component(name, { behavior }, render)); React state and effects are not read. Rendering needs Node (the first run installs the tool's packages; a lone file needs no project of its own): Facet does not run React by itself. Everything after the render is Facet's own: what the CSS means is worked out and mapped inside facet, the same way for any tree.

Documentation for Facet 0.3.228-g032727de