Skip to content

AI-native design editor. Open-source Figma alternative.

21.2 KB
Raw Blame

OpenPencil design authoring

This reference describes scene creation, not React DOM output. Use the render tool for JSX strings, or import Frame, Text, and other authoring exports from @open-pencil/design-jsx and render them with renderTree from @open-pencil/core/design-jsx in library code. Library exports are not automatically globals in agent eval; use only the bindings exposed by that execution environment.

Composition and layout

  • flex="row" / flex="col" enables auto-layout. Use it for content; reserve explicit x/y or position="absolute" for intentional overlays and artwork. Without layout, children share the origin unless positioned.
  • w / h accept pixels, "hug" (content-sized), or "fill" (available space in a supported layout parent). Use Hug for notes, cards, and long pages instead of guessing heights. Fixed viewport sizes and artwork geometry are intentional exceptions.
  • gap controls spacing. p, px, py, and pt/pr/pb/pl control padding; longhands override shorthands. There is no margin shorthand.
  • justify="start"|"end"|"center"|"between" controls the primary axis; items="start"|"end"|"center"|"stretch"|"baseline" controls the cross axis. Distribution needs available space: between cannot create extra room in a Hug container.
  • grow distributes available space. Avoid circular Hug/Fill dependencies and redundant fixed widths on growing children. Keep Fill sizing through intermediate containers that should stretch.
  • For wrapping text in a column, prefer w="fill"; fixed-width text can use textAutoResize="height". maxLines / truncate are intentional truncation, not fixes for accidental overflow.
  • wrap and rowGap enable wrapped flex rows. grid, columns, and rows enable grid (for example columns="1fr 200px 1fr" or columns="repeat(7, 1fr)"); tracks are fr, pixel lengths, auto, repeat(), and minmax(), which grows like its maximum. Grid children use colStart, rowStart, colSpan, and rowSpan. The current grid gap shorthand takes precedence over columnGap and rowGap.
  • flow="auto"|"ltr"|"rtl" controls container flow; text dir controls writing direction. Preserve these separately.
  • Outside auto-layout, and for position="absolute" children, constraints={{ horizontal, vertical }} sets how a layer follows its parent's resizing, with Figma's values in lowercase: "min", "center", "max", "stretch", or "scale". minW, maxW, minH, and maxH bound a layer's size. visible={false} hides a layer and locked locks it.
  • Use measured node bounds and the existing arrange tool for independent artboards: pack for a page of screens, spread when generated layers overlap. Prefer layout constraints to calculating child coordinates; ordinary JavaScript arithmetic is appropriate when real geometry calculations are needed.

Paint, text, and artwork

  • bg / fill, stroke, and text color accept colors and supported variable references. Set colors explicitly for predictable contrast. fills accepts structured paints; gradient helpers include linearGradient, radialGradient, angularGradient, and diamondGradient, each taking an array of stops and optional { opacity, transform }: fills={[linearGradient([['#3b82f6', 0], ['#8b5cf6', 1]])]}. Without a transform a linear gradient runs left to right and the others are centred; transform is Figma's gradientTransform, mapping the layer's unit square onto gradient space. Write it as the plugin API's rows, as export does: linearGradient(stops, { transform: [[0, 1, 0], [-1, 0, 1]] }) runs top to bottom. A paint written as an object takes its gradientTransform and imageTransform as rows too; the matrix fields { m00, m01, m02, m10, m11, m12 } are accepted as well.
  • shader(effects, { opacity, visible, blendMode }) fills a layer with a shader from the shaders library: an array of effects such as bg={shader([{ type: 'Aurora', props: { speed: 2 } }])}, or a preset as shaders.com exports it, { components: [...] }. The canvas shows the shader's first frame, preview plays it, and files and other formats keep that frame as an image.
  • stroke describes one stroke, refined by strokeWidth, strokeAlign ("inside", "center", "outside"), strokeDash, strokeCap, and strokeJoin. strokes takes several, as objects with color, weight, align, dash, cap, join, and visible; strokeWeights={{ top, right, bottom, left }} sets per-side widths. dashPattern sets the node's own dash pattern, separate from the per-stroke strokeDash.
  • rounded and roundedTL/roundedTR/roundedBL/roundedBR control corners. strokeWidth, opacity, rotate, and blendMode control appearance. overflow="hidden" clips content; do not hide accidental text overflow to make a broken layout appear correct.
  • rotate turns a layer by degrees, and flipX and flipY reflect it across its centre before it turns, as the canvas places it. Star takes points and innerRadius (0–1, how deep its points go); Polygon takes points. Ellipse draws an arc or a donut with startAngle and endAngle in degrees, clockwise from three o'clock (0 to 360 by default), and innerRadius (0–1, the hole): <Ellipse w={80} h={80} startAngle={0} endAngle={270} innerRadius={0.6} />.
  • effects accepts structured effects such as dropShadow, innerShadow, and layerBlur. shadow takes a CSS box-shadow list, such as shadow="0 4 8 #0002, inset 0 1 0 #fff", and blur a layer blur radius; both are convenient shorthands. Effect helpers take radius, as Figma's effects do; when a JSX string is rendered, an option a paint or effect helper does not support is reported as a warning.
  • Text content belongs inside Text. Use size, font, weight, italic, lineHeight, letterSpacing, textAlign, textAlignVertical, textDecoration, and textCase. Decorations take CSS's names and values: textDecorationStyle (solid, dotted, wavy), textDecorationColor (currentColor follows the text), textDecorationThickness and textUnderlineOffset (pixels or auto), and textDecorationSkipInk. fontFeatures turns OpenType features on or off by tag (fontFeatures={{ tnum: true, liga: false }}), fontVariations sets variable-font axes by tag (fontVariations={{ wght: 650 }}), and lang names the text's language (lang="de") for shaping and font fallback. A variable font's optical size follows the font size unless fontOpticalSizing="none", as in CSS; only then does an opsz in fontVariations apply. lineHeight="auto" follows the font, and fills={[]} paints no text. Verify fonts actually load before judging dimensions; do not assume every font is available.
  • Span styles some characters of a Text, or of a Sticky's body, a Shape's label, or a Connector's label, with Text's own prop names: size, font, weight, italic, color, fills, lineHeight, letterSpacing, textDecoration, the decoration details, fontFeatures, fontVariations, lang, and textCase; a span's fontFeatures and fontVariations replace the text's rather than adding to them, and fontOpticalSizing is set on the Text for all of it. href links its characters to a URL without changing how they look. Spans nest; the inner one wins. Paragraph writes one paragraph: list="ordered" or list="unordered" makes it a list item nested at level 1–5, and spacing, listSpacing, and indent override the Text's paragraphSpacing, listSpacing, and paragraphIndent for it; hangingList on the Text hangs list markers outside the text box. A Text holds only Paragraphs or none; without them, a line break in its text still starts a paragraph.
  • Text markdown reads its text, children or text, as Markdown over the Text's own style, as FigJam styles typed Markdown: # and ## headings bold at 2.5× and 1.5× its size, deeper ones bold at its size, all at a 150% line height; **bold**, *italic*, ~~strike~~, `code` in Roboto Mono, [links](url), - and 1. lists, and > quotes in italic. Write multiline Markdown as a template literal, <Text markdown>{`...`}</Text>, since JSX folds the line breaks of plain children, and escape a code span's backticks in it as \`; the indent its lines share is left out. It holds no Span or Paragraph.
  • Icon uses an Iconify name, size, and color. Prefer icons to emoji when reliable vector output is needed. Image fills belong on appropriate leaf shapes, not containers whose children must remain visible.
  • Pick artwork by where it comes from. A known icon is an Icon by its Iconify name. A shape you draw yourself is a Vector with its path in SVG syntax, <Vector d="M11 2L4 11h5l-1 7 7-9h-5z" bg={designVar(…)} />: one layer, styled with the same props as any other, so its fills can use variables, stack, and take strokeAlign and effects. fillRule="evenodd" cuts holes. An open path with a stroke stays open, a line; with only a bg it fills as if closed. Given w and h, the path is drawn in that box as written, as an icon is in its view box; without them the layer fits the path. paths takes several paths as export writes them, each { windingRule, data } with NONZERO, EVENODD, or NONE for an open path: paths={[{ windingRule: "EVENODD", data: "M0 0L10 0L10 10Z" }]}. Inline <svg> is for artwork copied from elsewhere: it draws the SVG's shapes, a frame with a layer per shape in the SVG's own colours, and leaves out its text, so do not use it for a shape you will style or bind, nor for text.
  • Sticky makes a FigJam sticky note whose text is its body: <Sticky color="yellow" author="Ada">Ship it</Sticky>. color takes a FigJam palette name (white, gray, red, orange, yellow, green, teal, blue, violet, pink) or any colour, author signs it (authorVisible={false} hides the line), wide makes it 416 wide instead of 240, textSize is small, medium, large, extraLarge, or huge, typeface is simple, bookish, technical, or scribbled, and scale scales the whole note. A note sizes itself; it takes no w, h, fills, or layout props.
  • Shape makes a FigJam shape with text whose text is its label: <Shape kind="diamond" bg="#FFC943">Valid?</Shape>. kind is square (default), ellipse, diamond, rounded_rectangle, parallelogram_right, eng_database, or another FigJam shape, written in lowercase. w and h are the size it is given (176 by default); it grows taller to fit its label, never wider, so a word too long for it breaks. truncate keeps its height and cuts the label off with "…" instead, as FigJam does once a shape's height is set. bg, stroke, strokeWidth, rounded (6 by default; a rounded_rectangle keeps its corners at 0.4 of its shorter side, as FigJam does), and rotate style it as any layer; the label is centred in the shape and takes the same textSize and typeface as Sticky.
  • Connector draws a FigJam connector that follows the layers it joins: <Connector from="Start" to="Done">Next</Connector>. from and to name layers of the same JSX, take a ref() a layer is marked with (const card = ref(), then <Frame ref={card}> and from={card}), or give { x, y } points in the connector's parent; fromSide/toSide (top, right, bottom, left) fix the side it attaches by, line is elbowed (default), straight, or curved, and startCap/endCap take the same caps as strokeCap: none, round, square, arrow_lines, arrow_equilateral, triangle_filled, diamond_filled, or circle_filled (it starts with none and ends with arrow_lines). Its text is the label; stroke, strokeWidth, and dashPattern style the line. When layers share a name, join them by ref(); a name more than one layer has joins the first, with a warning.
  • Design JSX props are the portable authoring interface. Some CSS-style aliases are supported, but this is not a browser CSS engine; do not assume arbitrary HTML, classes, or styles work.

Variables and components

  • defineVars('Theme', { Page: '#FFFFFF', Radius: 12 }, { mode: 'Light' }) defines a collection in the file's variables table and returns its variables by name, such as theme.Page. Each value is the variable's value in the first mode, named by mode (Mode 1 without one): strings are colors, numbers FLOAT, booleans BOOLEAN, and another collection's variable makes an alias, such as palette['Gray/900']. defineMode(theme, 'Dark', { Page: '#111111' }) adds a mode with the values that differ; the rest keep the first mode's. A render that binds any of the variables creates the collection with all its modes, or updates the one with that name, so running the JSX again changes values instead of adding collections.
  • designVar('name-or-id') refers to a variable the document already has; a missing one is an error. When more than one collection has a variable of that name, name the collection too, as designMode does: designVar('Theme', 'Line').
  • COLOR references work in paint props. FLOAT references work in w, h, gap, padding, corner radii, strokeWidth, opacity, text size/fontSize, lineHeight, and letterSpacing. Grid columnGap/rowGap and wrapped flex rowGap also support FLOAT references; grid gap overrides both axis-specific gaps. Use numbers or FLOAT references for these scalar props, not CSS unit strings; the one exception is lineHeight and letterSpacing, which also take a percent of the font size such as "150%" that follows the size when it changes.
  • mode={dark} shows a layer and its children in a mode, as the Appearance panel's variable mode control does; a list pins several collections, and designMode('Theme', 'Dark') names a mode of a collection the document already has, by the collection's ID when several share its name. Without mode, a layer inherits its parent's.
  • Variables bind real graph fields, not copied values. Layout resolves scalar variables in the mode the layer is created in, its own or inherited; it does not lay content out again after a later mode switch. Verify resulting geometry as well as paint when changing modes. Missing or incorrectly typed scalar variables are errors.
  • bind maps supported scene-field paths to variable IDs or references when no shorthand exists. Use semantic tokens consistently rather than declaring unused collections.
  • Build repeated or computed content with JavaScript inside {} rather than writing each item out: {days.map((day) => <Text>{day}</Text>)}, {Array.from({ length: 35 }, (_, i) => <Frame>…</Frame>)}, and conditionals. Statements such as const weeks = … may come first and then end with return and the JSX, as a component's body does: const weeks = 5 on one line, return <Frame>…</Frame> on the next.
  • A reusable JavaScript function shares source code, not component identity. Use Component, ComponentSet, and Instance for editable main components and linked instances.
  • Instance resolves an existing component through of, component, or componentId, by name or ID. When components share a name, mark the one you mean with a ref() and pass it: const card = ref(), then <Component name="Card" ref={card}> and <Instance of={card} />. A swap property's default and values take a ref() the same way: of={property('Icon', card)}, Icon={card}. Component-set children named variant=Primary, for example, define variants that can be selected when instantiating the set; a value the set does not have is an error. A variant property named like a layer prop, such as visible, keeps the prop's meaning, so select such a variant by naming it: <Instance of="visible=false" />.
  • property(name, defaultValue) binds a field of a component's layer to a component property, created on first use: text={property('Message', 'Hi')} on a Text makes a TEXT property, visible={property('Pinned', true)} a BOOLEAN one, and of={property('Icon', 'Star')} on an Instance an INSTANCE_SWAP one whose default is the component of names. The property belongs to the nearest Component, or to its ComponentSet for a variant, so the same name in each variant binds one property; one name with two types or two defaults is an error.
  • An Instance sets text, boolean, and swap properties by name, the way it picks a variant: <Instance of="Note" State="Done" Message="Updated review" Pinned={false} />. properties takes the same values keyed by property ID or name, for names that are not JSX identifiers or that design JSX already uses, such as name. Only instances accept properties.
  • exposed on an Instance in a component shows that instance's own properties on the component's instances, as Figma's "Expose properties from nested instances" does; the instance's component needs properties to expose. An outer instance gives an exposed instance its variant and properties as an object under the exposed layer's name: <Instance of="Card" Title="Welcome" Action={{ Variant: 'Secondary', Label: 'Save' }} />, or properties={{ Action: { … } }}.
  • Instance assignments take true / false or the native 'true' / 'false' for BOOLEAN properties, and a component's name, ID, or ref() for swaps, as of does, whether set as a prop or in properties. Assignments persist through component synchronization; unknown IDs and invalid values fail rather than silently creating inert overrides. Select variants through component-set variant props, not through instance property assignments.
  • An exported Instance has no children: its layers are its component's. What it changes in them is in overrides, keyed by the layer's name in the component and the scene field, with the field's value: overrides={{ 'Dot:fills': [...] }}. A name several of its layers share is an error; a key that names no layer, a field an instance cannot override, or a value of another kind is skipped with a warning. Change per-instance content through properties rather than overrides. An instance whose changes cannot be written that way exports as the Frame it draws.
  • Reuse existing local or library components before recreating them. Keep meaningful text, visibility, and swap properties exposed rather than hand-editing cloned child nodes.
  • Explicit instance w / h replace the inherited sizing mode on that axis; omitted dimensions retain the main component's sizing. Authored overrides survive component synchronization. Distinguish those placement constraints from the main component's default size, and verify actual bounds in narrower parents. Do not compensate for a sizing mismatch with guessed heights, clipping, or manually positioned siblings.

Controls

  • A main component can behave as a Reka UI control in preview and code. Write it with Reka's names: Switch.Root is the component (a component set when its children are Component variants), and each Reka part is the slot that draws it, such as Switch.Thumb, Slider.Track, Slider.Range, Slider.Thumb, Progress.Track, Progress.Indicator, Tabs.List, Collapsible.Trigger, or NumberField.Increment. Parts in different variants share one slot.
  • The root names the properties that hold its values: modelValue (open on Collapsible.Root), disabled, for form controls (fields, switches, checkboxes, radios) invalid, and, for text fields, filled, as a variant or boolean property name, or { property, on, off } when the variant values are not named like On and Off. states names the variant property that draws default, hover, pressed, focus, disabled, and, for form controls, invalid (a value named Invalid or Error); a slider, progress bar, or number field takes min, max, step, and defaultValue.
  • TextField.Input, Textarea.Input, and NumberField.Input are the text layers whose text becomes the field's text property. Tabs.Trigger goes in Tabs.List; Tabs.Content panels may sit directly under Tabs.Root, the first showing. A part with children and no flex, display, w, or h of its own stacks them in a column that hugs them.
  • A group's item component is written on its own (RadioGroup.Item, ToggleGroup.Item, Accordion.Item with its Accordion.Trigger and Accordion.Content); the group's root then lists items as <RadioGroup.Item of={radioId} />.
  • A tab trigger with a selected look of its own is a Tabs.Tab component, written on its own with modelValue naming its selected variant property; Tabs.Root then lists its tabs as <Tabs.Tab of={tabId} />, which go in the list as plain Tabs.Triggers do, and each shows its selected variant while its tab is chosen.
<Switch.Root name="Switch" modelValue="State" states="Interaction">
  <Component name="State=Off, Interaction=Default" w={44} h={24} rounded={12} bg="#D0D4DA">
    <Switch.Thumb x={2} y={2} w={20} h={20} rounded={10} bg="#FFFFFF" />
  </Component>
  <Component name="State=On, Interaction=Default" w={44} h={24} rounded={12} bg="#3B6CF6">
    <Switch.Thumb x={22} y={2} w={20} h={20} rounded={10} bg="#FFFFFF" />
  </Component>
</Switch.Root>

Verification

Inspect structure and actual rendered output. Node counts and describe diagnostics do not establish visual fidelity. Check wrapping with longer content, narrower containers, component edits, and relevant modes. Resolve overflow and contrast problems at their source. Reuse IDs returned by creation tools rather than repeatedly searching for the same nodes.

The examples below are executed by the authoring-reference tests. Create the named variables before running a variable-bound example.