--- url: 'https://pairdraw.dev/user-guide/home.md' description: >- Start a design from a prompt, import something that exists, or reopen recent work. --- # Home Home is the first tab when Pairdraw opens (the desktop app and the web app alike). It is where a new design starts and where recent files are listed. Home is a tab, not a document: it stays in front until a document opens, and closing every document brings it back. ## Start from a prompt The field at the top takes a sentence: "A sign-in screen for a banking app, a pricing section, a dashboard…". Choose what it is going to make first — **Landing page**, **Mobile app**, **Web app**, **Slides**, **Dashboard**, or **Something else…** — then write the prompt and press Enter (the send button does the same; Shift+Enter starts a new line). The choice adds that kind's guide when the prompt is sent. The prompt opens a new design and hands the text to its AI chat, so the design arrives on the canvas with the conversation beside it. See [AI chat](/programmable/ai-chat) for models, skills, and prompts. ## Start from something that exists * **Import from Figma** — choose a `.fig` file to open as a document. * **Import from browser** (desktop) — bring a page from the built-in browser onto the canvas as layers. * **Recreate a screenshot** — choose an image and the chat rebuilds it as an editable design. Every import keeps the real document: layers, text, and fills are editable, not a picture. ## Recent files, drafts, and design systems Tabs over the documents switch the place Home lists: * **Recent** — files opened locally and from storage, newest use first by default. Search narrows the list; the sort control changes the order, and the grid/list control changes how it reads. **Open…** opens a file from disk, and **Design** creates a new local design (a build with boards also offers **Board**). * **Drafts** — unsaved documents kept by Recovery. * **Design systems** — start a design with a published library's components. The menu beside the tabs lists the other places: your storage bucket, the Cloud workspaces and shared files of a connected server, and **New workspace** there. [Pairdraw Cloud](/user-guide/pairdraw-cloud) and [Cloud Storage](/user-guide/cloud-storage) describe those places. Each recent card previews the document, with its name and the date it was last used. Click a card to open it; the menu on the card saves a copy or removes it from the list. The number of files Home keeps is set in **Settings → General → Recent files**. Home's gear button opens [Settings](/user-guide/settings). --- --- url: 'https://pairdraw.dev/user-guide/canvas-navigation.md' description: >- Panning, zooming, ruler guides, snapping, and distance measurements in Pairdraw. --- # Canvas Navigation The canvas is your infinite workspace. You can pan and zoom freely to navigate your design. ## Panning Move the visible area of the canvas without affecting any objects. * Space + drag — hold Space and drag anywhere on the canvas * **Middle mouse drag** — press and drag the middle mouse button * **Two-finger trackpad** — swipe with two fingers on a trackpad * Shift + mouse wheel — pan horizontally ## Hand Tool Press H to activate the hand tool for continuous panning. Any drag on the canvas pans the viewport without needing to hold Space. Switch to another tool (e.g., **V** for Select) to deactivate. ## Zooming Zoom in and out centered on your cursor position. * Ctrl + scroll (or ⌘ + scroll on Mac) — scroll up to zoom in, scroll down to zoom out * **Pinch gesture** — pinch on a trackpad to zoom in/out * **Keyboard shortcuts** — see table below For a mouse, turn on **Zoom with scroll wheel** in **Settings → Editor → Navigation** to zoom with the wheel alone; Shift + wheel still pans sideways. **Invert zoom direction** swaps which way the wheel zooms, while a trackpad pinch keeps its own direction. Pinch-to-zoom on UI panels (layers, properties) is prevented so it doesn't accidentally change the browser zoom level. ## Zoom Tool Hold Z and click to zoom in on the pointer, or Option/Alt + click to zoom out; drag to zoom to the area you frame. Releasing Z brings back the tool you had. A quick tap of Z keeps the zoom tool on, and the Hand tool's toolbar menu offers it too. Zoom to fit, to selection, and to 100%, the zoom menu's levels, and the next or previous frame glide to their view instead of jumping. They jump when animations are off, Ultralight mode is on, or the system asks for reduced motion. ## Keyboard Shortcuts | Action | Mac | Windows / Linux | |--------|-----|-----------------| | Pan | Space + drag | Space + drag | | Hand tool | H | H | | Zoom tool | Z | Z | | Zoom in | ⌘+ | Ctrl + + | | Zoom out | ⌘− | Ctrl + − | | Zoom in / out | + / − | + / − | | Zoom to 100% | ⇧0 or ⌘0 | Shift + 0 or Ctrl + 0 | | Zoom to fit | ⇧1 | Shift + 1 | | Zoom to selection | ⇧2 | Shift + 2 | | Zoom to next / previous frame | N / ⇧N | N / Shift + N | | Next / previous page | Page Down / Page Up | Page Down / Page Up | | Pixel grid | ⇧' | Shift + ' | | Snap to pixel grid | ⇧⌘' | Shift + Ctrl + ' | | Rulers | ⇧R | Shift + R | | Multiplayer cursors | ⌥⌘\ | Alt + Ctrl + \ | ## Frames and Pages N selects the next top-level frame on the page and zooms to it; Shift + N goes back. Frames inside sections count, hidden ones do not, and the order runs left to right, then top to bottom, wrapping at the ends. With a layer inside a frame selected, the step starts from that frame. Page Down and Page Up open the next and previous page in the Pages panel's order. ## Pixel Grid Zoomed in far enough that each document pixel covers eight screen pixels (800% on a standard display, 400% on a Retina one), the canvas shows a line at every pixel, as in Figma. Turn it off or on with **View → Pixel Grid**, Shift + ', or **Show pixel grid** in **Settings → Editor**; the choice applies to every open document and is kept between sessions. ## Side Panels The layers panel's toggle sits above the tools at the canvas's left and opens the sidebar, whose tabs show Layers, Assets, Slides, and Design. The Design tab holds the properties panel, which follows the selection while it is showing but never opens itself: selecting a layer leaves the sidebar's tab as you left it. The sidebar stays open or closed, on the view you chose, until you change it, and the canvas takes the room of a closed sidebar, which reopens at the width it had. **View → Layers Panel** and **View → Design Panel** do the same. ⌘\ (Ctrl + \\) still hides every panel at once. The comments list and version history show in the Design tab, so the comment tool and version history switch to it while you use them. ## Ultralight Mode On a slow or battery-powered computer, turn on **Ultralight mode** in **Settings → Editor → Rendering**. It turns off interface animations at once and, after a reload, renders the canvas in tiles at one device pixel per screen pixel and leaves out background blurs and noise, drawing shadows at a lower resolution when zoomed in. Progressive rendering stays on while Ultralight is on. Exported images keep every effect. ## Ruler Guides Rulers are hidden until you turn them on with **View → Rulers** or Shift + R. Then drag from the top ruler for a horizontal guide or the left ruler for a vertical guide. Drop onto the page for a canvas guide, or onto a frame for a guide in that frame's coordinates. * Click a guide to select it; drag it to reposition it or transfer it between the page and a frame. * Hold Option / Alt while dragging an existing guide to duplicate it. * Drag a guide back onto a ruler to remove it, or use its context menu's **Remove guide** action. * Guide changes support undo/redo and are preserved in `.fig` files. ## Snapping Under **View → Preferences**, toggle **Snap to Geometry**, **Snap to Objects**, and **Snap to Pixel Grid** independently. Preferences are saved between sessions. Geometry and object snapping help align vector points, moved layers, and resized edges with nearby geometry, objects, guides, and frame bounds. Alignment lines appear for those targets; pixel-grid rounding does not draw an alignment line for every pixel. With **Snap to Objects** on, a moved layer also snaps to equal spacing: it centers between its two neighbors, or lands as far from a neighbor as two other neighbors in the same row or column are apart. Every gap of that size shows a pink indicator with its size. Resizing does not snap to spacing. With **Snap to Pixel Grid** on, moved layers, resized edges, and drawn layers land on whole pixels at any zoom, even when they started between pixels. A snap to an object or guide wins over the grid. Arrow-key nudges and values typed in the properties panel keep their fractions. Turn on **Snap to half pixels** in **Settings → Editor** to let the pixel grid snap land on half pixels as well, so a 1 px stroke can sit centered on a pixel edge. A board keeps its 16-unit grid. Hold Control during a layer drag to temporarily bypass object and pixel snapping, including on macOS where this is Control, not Command. ## Distance Measurements Select a layer, hold Option on macOS or Alt on Windows/Linux, and hover another layer to see temporary distance measurements. Releasing the modifier clears the overlay; it does not add guides or change the document. ## Command Palette Press ⌘K on macOS or Ctrl + K on Windows/Linux to search editor and application actions. Select a result to run it; unavailable actions remain subject to the current selection and document state. The palette also moves between pages. Before you type, it lists the pages you visited recently in this tab, most recent first, and **Go to page…** opens a list of every page. Typing a page name finds it too. Pages where collaborators or AI agents are working list their names; the Pages panel marks the same pages with their colors. ## Tips * Zooming always targets the cursor position, so point at what you want to see closer. * The hand tool is useful when you need to pan frequently — it stays active until you switch tools. * See [Selection & Manipulation](./selection-and-manipulation) for how to work with objects on the canvas. --- --- url: 'https://pairdraw.dev/user-guide/selection-and-manipulation.md' description: >- Selecting, moving, resizing, rotating, duplicating, and organizing nodes in Pairdraw. --- # Selection & Manipulation Select objects to move, resize, rotate, duplicate, and organize them on the canvas. ## Selecting * **Click** a node to select it (deselects everything else). As in Figma, a click inside a top-level frame selects that frame's direct child, such as a nested frame or a group, rather than the deepest layer; click a top-level frame by its title, anywhere when it is empty, or by its gaps and padding when it has auto layout * **Hover** an auto layout frame to see its direct children outlined with dotted lines; while a single layer is selected, the border of its auto layout parent is dotted * **Double-click** to go one level deeper, or click again inside a selected frame, component, or instance; once a layer is selected, clicks reach its siblings and cousins directly * ⌘ + click (Ctrl + click on Windows and Linux) selects the deepest layer under the cursor; holding ⌘ highlights that layer before you click * Shift + click to add or remove a node from the current selection. A layer and its own parent or child are never selected together, so Shift-clicking one replaces the other * **Double-click a frame's or component's name** above it on the canvas to rename it in place * **Marquee drag** — drag on empty canvas to draw a selection rectangle; intersecting nodes are selected on release. Started inside a top-level frame without auto layout or a section, it selects that container's layers; from the page, a frame or section that holds layers is selected only when fully enclosed * ⌘ + drag (Ctrl + drag on Windows and Linux) draws a marquee that selects the deepest nested layers it touches. It starts where a plain marquee does, on empty canvas or the empty background of a top-level frame or a section; from a layer, or the background of a nested frame, component, or instance, ⌘ + drag selects that layer and moves it. Press or release ⌘ mid-drag to switch between the deep and the plain marquee * ⌘A — select all nodes on the current page * Enter — select the children of the selected layers; on a vector it edits the path and on text it edits the text * Shift + Enter or \ — select the parent of the selected layers * Tab / Shift + Tab — select the next or previous sibling, going down or up the layers panel and wrapping at the ends * **Click empty canvas** — deselect all ## Moving * **Drag** a selected node to move it (all selected nodes move together) * **Arrow keys** — nudge selected nodes by the small nudge, 1 px unless changed * Shift + arrow keys — nudge by the big nudge, 10 px unless changed Set both distances under **Settings → Editor → Nudge**. ## Resizing Selected nodes show 8 resize handles (4 corners + 4 edge midpoints). Drag any handle to resize. * Shift + drag a corner handle to constrain proportions ## Scale Tool Press K, or pick **Scale** from the Move tool's toolbar menu, to scale layers with everything in them: text sizes, strokes, effects, corner radii, and auto layout spacing grow and shrink with the layer, as with Figma's Scale tool. Drag a selection handle to scale from the opposite side, or hold Option/Alt to scale from the center; several selected layers scale together around their joint bounds. While the Scale tool is on, the Design panel shows the selection's width and height, a scale factor, and an anchor grid. Typing a width or height scales the selection proportionally to it; the factor takes `2`, `2x`, or `200%`. The anchor grid picks the point that stays in place. Each scale is one undo step. ## Moving into and out of frames A dragged node lands in the frame under the cursor when you release it, however little of it is inside, and leaves its frame as soon as the cursor does. Groups and locked frames never take dropped nodes, and a component set takes back only its own variants; a node inside a group stays in it unless you drop it on a different frame, and the group resizes to fit what it holds. A group whose last node leaves is removed. Pressing inside a selected frame, group, or component set drags it rather than the node under the cursor. * Shift + drag — lock the move to one axis * Hold Space while dragging — keep the nodes in their current parents * ⌃ + drag (Ctrl + drag on Windows and Linux) — turn off snapping; dropped into an auto-layout frame, the node is positioned absolutely Locked nodes in a selection stay where they are when the rest of it moves. ## Rotating Hover just outside a corner handle to see the rotation cursor. Drag to rotate. * Shift + drag snaps rotation to 15° increments ## Duplicating * Alt + drag (⌥ + drag on Mac) — duplicate the selected node and move the copy * ⌘D — duplicate in place; a lone top-level frame's copy, on the page or in a section, goes into the first free space to its right Duplicates keep their names. Duplicating a main component this way creates an instance of it. ## Pasting ⌘V keeps the copied position. Pasted into a selected frame, nodes keep their offset from the frame they were copied from, and are centered along any axis where they don't fit; nodes that would land out of view are centered in it. Use **Paste here** in the [context menu](./context-menu) to paste at the cursor. ## Deleting Press Backspace or Delete to remove all selected nodes. ## Z-Order Change the stacking order of nodes within their parent: * **]** — bring to front (top of sibling list) * **\[** — send to back (bottom of sibling list) ## Visibility & Lock * ⇧⌘H — toggle visibility. Hidden nodes don't render but stay in the layers panel. * ⇧⌘L — toggle lock. Locked nodes can't be selected or moved on canvas. ## Move to Page Move selected nodes to a different page via the [context menu](./context-menu). The nodes are reparented under the target page's canvas. ## Editing several layers With several layers selected, the properties panel shows what they have in common and reads **Mixed** where they differ; an edit changes all of them in one undo step. * **Layout** shows their sizes, text resizing when text is selected, flow when every layer is a frame, and clip content for the frames among them. When the layers form one row or column, **Spacing** shows the gap between them; typing a value spaces them evenly from the first layer. * **Typography** appears whenever text is selected and changes only the text. * **Stroke** shows the stroke of the layers that have one; editing it strokes every selected layer. * **Selection colors** lists every fill and stroke colour in the selection, including inside frames and groups, most used first. Changing one recolours it everywhere it is used. ## Sections A section takes in the sibling nodes it fully covers when you draw it, move it, or resize it over them. ## Keyboard Shortcuts | Action | Mac | Windows / Linux | |--------|-----|-----------------| | Select all | ⌘A | Ctrl + A | | Duplicate | ⌘D | Ctrl + D | | Duplicate + move | ⌥ + drag | Alt + drag | | Scale tool | K | K | | Move along one axis | ⇧ + drag | Shift + drag | | Keep current parent | Space while dragging | Space while dragging | | Move without snapping | ⌃ + drag | Ctrl + drag | | Delete | ⌫ / Delete | Backspace / Delete | | Nudge 1 px | Arrow keys | Arrow keys | | Nudge 10 px | ⇧ + Arrow keys | Shift + Arrow keys | | Bring to front | ] | ] | | Send to back | \[ | \[ | | Toggle visibility | ⇧⌘H | Shift + Ctrl + H | | Toggle lock | ⇧⌘L | Shift + Ctrl + L | ## Tips * Use the [Layers & Pages](./layers-and-pages) panel to see and reorder nodes when they overlap. * See [Context Menu](./context-menu) for additional actions like grouping and component creation. --- --- url: 'https://pairdraw.dev/user-guide/context-menu.md' description: >- Right-click context menu actions in Pairdraw — clipboard, z-order, grouping, components, and more. --- # Context Menu Right-click on the canvas to open the context menu. If you right-click on a node, it is selected first. Right-clicking on empty canvas clears the selection. ## Copy/Paste as The **Copy/Paste as** submenu offers additional clipboard formats for the selected node(s): | Action | Shortcut (Mac) | Shortcut (Win/Linux) | |--------|----------------|----------------------| | Copy as text | — | — | | Copy as SVG | — | — | | Copy as PNG | ⇧⌘C | Shift + Ctrl + C | | Copy as JSX | — | — | | Copy as HTML | — | — | * **Copy as text** — copies visible text content from the selection * **Copy as SVG** — copies the node tree as SVG markup * **Copy as PNG** — renders at 2× and places on the system clipboard (paste into Slack, Notion, etc.) * **Copy as JSX** — copies the Pairdraw JSX representation for use with `renderJSX()` * **Copy as HTML** — copies an HTML fragment with inline styles and images inlined, ready to paste into a page or an email; it also works in read-only documents ## Run sticky as prompt When only sticky notes are selected and at least one has text, **Run sticky as prompt** sends their text to the document's [AI chat](../programmable/ai-chat), with a reference to each note so the assistant knows which notes it came from. It appears only in documents you can edit. When no model is set up yet, Pairdraw looks for a coding agent on your computer first and opens guided setup when none is found, then sends the prompt. ## Clipboard Actions | Action | Shortcut (Mac) | Shortcut (Win/Linux) | |--------|----------------|----------------------| | Copy | ⌘C | Ctrl + C | | Cut | ⌘X | Ctrl + X | | Paste here | ⌘V | Ctrl + V | | Duplicate | ⌘D | Ctrl + D | | Delete | ⌫ | Backspace / Delete | Clipboard actions are disabled when nothing is selected (except Paste, which is available when the clipboard has content). ## Copy and Paste Properties | Action | Shortcut (Mac) | Shortcut (Win/Linux) | |--------|----------------|----------------------| | Copy properties | ⌥⌘C | Alt + Ctrl + C | | Paste properties | ⌥⌘V | Alt + Ctrl + V | Both are in the **Copy/Paste as** submenu. * **Copy properties** puts the selected layer on the system clipboard the way Figma does, marked so a plain Paste ignores it. * **Paste properties** applies the look of the one layer on the clipboard to every selected layer, locked ones included, in one undo step. It reads a copy made with Copy properties or ordinary Copy, here or in Figma. * The look is fills, strokes, effects, opacity, blend mode, corner radius, and linked styles and variables. Between frames it includes auto layout and layout grids, and between text layers the text style. Position, size, rotation, name, and content never change, and properties a text layer mixes across its characters are left alone. ## Z-Order | Action | Shortcut | |--------|----------| | Bring to front | ] | | Send to back | \[ | Moves the selected node to the top or bottom of its parent's child list. ## Grouping | Action | Shortcut (Mac) | Shortcut (Win/Linux) | |--------|----------------|----------------------| | Group | ⌘G | Ctrl + G | | Ungroup | ⇧⌘G | Shift + Ctrl + G | | Add auto layout | ⇧A | Shift + A | * **Group** requires 2 or more selected nodes * **Ungroup** appears when a group is selected — children are reparented to the group's parent * **Add auto layout** wraps the selection in a new [auto layout](./auto-layout) frame ## Component Actions Component actions are displayed in purple to match the component color theme. | Action | Shortcut (Mac) | Shortcut (Win/Linux) | Available on | |--------|----------------|----------------------|--------------| | Create component | ⌥⌘K | Ctrl + Alt + K | Any selection | | Create component set | — | — | 2+ selected components | | Create instance | — | — | Components (no shortcut) | | Go to main component | — | — | Instances | | Push changes to main component | — | — | Instances with overrides | | Reset all changes | — | — | Instances with overrides | | Detach instance | ⌥⌘B | Ctrl + Alt + B | Instances | See [Components](./components) for details on the component workflow. ## Visibility & Lock | Action | Shortcut (Mac) | Shortcut (Win/Linux) | |--------|----------------|----------------------| | Hide / Show | ⇧⌘H | Shift + Ctrl + H | | Lock / Unlock | ⇧⌘L | Shift + Ctrl + L | The label toggles based on the node's current state (e.g., "Hide" for a visible node, "Show" for a hidden one). ## Move to Page The **Move to page** submenu lists all pages except the current one. Select a page to reparent the selected nodes under that page's canvas. ## Tips * Right-clicking empty canvas gives you access to Paste — useful for placing content at a specific location. * Component actions only appear when relevant (e.g., "Create instance" only for component nodes). * The context menu mirrors the keyboard shortcuts — it's a good way to discover shortcuts you don't know yet. --- --- url: 'https://pairdraw.dev/user-guide/windows.md' description: >- Open several editor windows, see where files and links land, and what quitting asks. --- # More Than One Window The desktop app can show several editor windows at once. Each window is its own editor: its own tabs, documents, selection, and history, with nothing shared but the app itself. ## Opening a Window Choose **File → New Window**. Only the desktop app offers it; a browser tab is always a single window. The new window is empty and looks like any other: the same title and size, and the same page of the app. Only its label differs — the first window is `main`, the next `editor-2`, `editor-3`, and so on, reusing the first free number after a window closes. That label is how the shell and the agent tools tell the windows apart; it is not shown in the title bar. ## Which Window a File Opens In * A file that another window already shows is opened there: that window comes forward with the document's tab, and no second copy opens. * A file that no window shows opens in the focused window. Before any window has focus, as at launch, it goes to `main`. * A file that arrives from outside the app — a file association, launching the app with a path, a recent file, or a file link — follows the same rule: the window that already shows it, else the focused window. * A relative file link goes to the window whose open file path ends with the link's path. When more than one window matches, the focused window decides if it is one of them; otherwise the usual rule applies rather than an arbitrary window. * Cloud links and sign-in callbacks that return through a `pairdraw://` link go to the focused window only, so following one link never happens once per window. Choosing **Open…** inside a window checks the other windows first, as any open does: if one already shows the file, it is focused instead. ## What the Menus Act On The native menu bar follows the focused window: it shows that window's document features and check marks. A menu command — Save, Close Tab, undo, a tool, a view toggle — runs in the focused window only, because the document, tab, and selection it acts on are that window's. **Quit** is the exception: it is the app's, not a window's. ## Quitting with Unsaved Documents Quitting asks every editor window to confirm its own documents, and the app exits when the last one agrees. * Each window prepares its own documents and asks about its own unsaved ones, as closing a window does. * One window declining cancels the quit for every window; answers that arrive after the cancellation are ignored. * A quit confirmation is not the window's own close approval: if another window cancels the quit, this window asks again the next time it is closed. Closing one window asks only about that window's documents. ## Agents and MCP Each window connects to the MCP server on its own, registering its label, and reports every focus change. * A tool call goes to the window that most recently had focus. Before any window reports focus, the only connected window answers; with several, the most recently started one does, so a call never waits for a focus it may not get. * A reply names a document as `:`, such as `editor-2:tab-3`, so two windows' tab ids never collide. A bare tab id means the window that answers the call. * A call that names another window's document fails with **Document "…" is not open in this window**. Focus that window first, then call without a document id or with an id from that window. * Listing documents lists the ones in the focused window. ## What It Does Not Do * It does not move a document between windows: opening it elsewhere focuses the window that already shows it instead. * Windows share no undo, selection, or tabs; a document is edited in the window that has it. * New Window is desktop only, and every window carries the same title, so the title bar does not say which window is which. * On macOS, closing every window leaves the app running, and the dock icon opens a window again. --- --- url: 'https://pairdraw.dev/user-guide/settings.md' description: >- The Settings window, its tabs, and where appearance, the editor, fonts, storage, AI, and diagnostics live. --- # Settings Open Settings with ⌘, (Ctrl+,) or from the app menu and the gear beside Home. The window groups its tabs as the app does: ## App * **General** — interface language, appearance (light, dark, or auto) and the accent colour, Recovery and its drafts, the number of recent files kept, and the name other people see in a shared document. * **Editor** — snapping, arrow-key nudging, canvas navigation, and canvas rendering. * **Plugins** — plugin manifests and their permissions; see [Plugins](/user-guide/plugins). * **Fonts** — system font access, online font providers, and downloaded fonts and fallback packs (desktop); see [Text editing](/user-guide/text-editing). * **Storage** — the S3-compatible bucket used for storage documents and libraries; see [Cloud Storage](/user-guide/cloud-storage). * **Notifications** — notices while an agent works, such as when it needs an answer, and the browser notification permission. * **Cloud** — the Pairdraw Cloud server Home shows, and which server that is when more than one is connected; see [Pairdraw Cloud](/user-guide/pairdraw-cloud). ## AI * **Models** — the model profiles, the Design and Fast tasks, and reasoning and limit settings. * **Tool access** — which tools the built-in AI may call. * **Skills** — uploaded, folder, shared, and built-in skills and their switches, each with the files it reads; see [AI chat](/programmable/ai-chat). * **Prompts** — the prompts and reviews added to the chat. * **Image services** — the image generation, background removal, and vectorize services and their keys. * **MCP** — the local MCP server and its tools, its authentication, and the browser-native WebMCP mode; see [MCP server](/programmable/mcp-server). * **Usage** — token and cost totals, when usage is shown. ## Data & privacy * **Diagnostics** — the app's diagnostics report, logs, and environment details to attach to a bug report. [Privacy](/overview/privacy) lists what the app connects to and when. --- --- url: 'https://pairdraw.dev/user-guide/drawing-shapes.md' description: >- Creating rectangles, ellipses, lines, frames, sections, polygons, and stars in Pairdraw. --- # Drawing Shapes The toolbar at the canvas's left provides tools for creating shapes, frames, and sections. Select a tool, then click and drag on the canvas to draw. ## Toolbar Tools | Tool | Shortcut | Description | |------|----------|-------------| | Rectangle | R | Draws a rectangle | | Ellipse | O | Draws an ellipse | | Line | L | Draws a line | | Frame | F or A | Draws a frame (container for other nodes) | | Section | Shift + S | Draws a section (takes in the siblings it fully covers) | ## Placing Images Choose **File › Place Image…** (⇧⌘K, or Shift + Ctrl + K on Windows and Linux) or click the image button in the toolbar, then pick PNG, JPEG, WebP, GIF, AVIF, or SVG files. They land in the middle of the view, selected, as one step you can undo; an SVG becomes editable layers. The **Sticky note** tool follows Text in the toolbar. It has no key, so N still zooms to the next frame. ## Shapes Flyout The shapes flyout (accessible from the toolbar) includes additional shapes: * **Polygon** — creates a polygon with 3 sides by default (triangle) * **Star** — creates a 5-pointed star with 0.38 inner radius Polygon and Star have no keyboard shortcut — access them from the shapes flyout in the toolbar. ## Customizing the Toolbar Right-click the toolbar and choose **Customize toolbar…**, or open **Settings → Editor**, to change it: * Turn a tool's switch off to hide it. Hidden tools keep their keyboard shortcuts. **Move** is always shown. * Drag a tool to reorder it. Dropped inside a box it joins that flyout; dropped in the gap between boxes it becomes a button of its own; dropped onto another tool, the two share a flyout. * A tool's **⋯** menu moves it up or down, groups it with the tool above, or ungroups it from its flyout. Its grip also moves it with ↑ and ↓. * **Insert icon** runs a command rather than picking a tool, so it can move and hide but not join a flyout. **Reset to default** restores the original layout. Tools added in later versions join their default flyout, so a customized toolbar still gets them. ## Constrained Drawing Hold Shift while dragging to constrain the shape: * Rectangle → square (equal width and height) * Ellipse → circle * Line → snaps to 0°/45°/90° angles ## Shape Properties After drawing a shape, select it to edit its properties in the Design tab of the properties panel. ### Fill Every shape can have a fill. The fill section supports: * **Solid color** — pick via the HSV color picker or type a hex value. The picker lists the document colors, the solid colors already used on the current page, most used first. * **Gradient** — Linear, Radial, Angular, or Diamond with editable gradient stops. While the gradient's picker is open, the canvas shows its handles: drag an end or a radius dot to move it, hold Shift to turn it in 15° steps, and drag a stop's square to slide the stop along the line * **Mesh** — a grid of colored points that blends across the layer. The Mesh tab shows each point: select one to recolor it, or change **Columns** and **Rows** to resample the grid (up to 4 each way). Mesh paints on fills and strokes; `.fig` files keep the grid and show its own color elsewhere, and `.pen` `mesh_gradient` paints import * **Image** — select an image file as the fill, or paste an address in **Image URL** and choose **Load** to fetch a PNG, JPEG, GIF, or WebP image from the web (or a `data:` URL) of up to 64 MB * **Shader** — an animated GLSL shader: start from one of the 21 complete shaders in the gallery, add effects to it, tune a gradient effect's stops or the shape it draws on in the properties panel, or paste a preset copied from shaders.com. Preview plays the shaders on screen; the canvas, files, and other formats keep a still frame. An image fill is placed in one of five modes: **Fill** covers the layer and crops the image, **Fit** shows the whole image inside the layer, **Stretch** stretches the whole image to the layer's proportions, **Crop** lets you choose the part of the image to show, and **Tile** repeats the image. Stretch is stored as a crop of the whole image, as `.pen` files store it and Figma reads it. To crop or reframe an image on the canvas, double-click the layer, press Enter with it selected, or choose **Crop image** from its context menu or its image fill. The whole image shows, faded outside the layer. Drag the layer's corner brackets or edge bars to crop it over the still image, drag the image to move it behind the layer, and drag the image's corner dots to scale it. Hold Shift to keep proportions or move along one axis and Alt to work from the centre. Each drag is one undo step and stores the fill as a crop; Enter, Esc, a double-click, or a click outside the image finishes. Vectors, layers with children, and layers placed by auto layout keep their edges, so on those you can only move and scale the image. ### Shader Mode Shader Mode shows a shader fill large on its own, with play and pause, a phase scrubber, and the shader's settings beside it. Open it with **Open in Shader Mode** in the shader fill picker, or with **View → Shader Mode** while the selection has a shader fill. ### Stroke Add an outline to any shape. Stroke properties include: * **Width** — uniform or per-side (Top/Right/Bottom/Left) via the side selector dropdown * **Color** — solid color with opacity * **Alignment** — Inside, Center, or Outside the shape boundary (clip-based rendering matches Figma behavior) * **Cap style** — None, Round, Square, Arrow Lines, Arrow Equilateral (for open paths) * **Join style** — Miter, Bevel, Round * **Dash pattern** — dash-on/dash-off ### Corner Radius Available for rectangles, frames, components, instances, polygons, and stars. Click the independent corners toggle to set each corner (top-left, top-right, bottom-left, bottom-right) separately; a polygon's or star's corners share one radius, which rounds its inner corners too. On the canvas, hover a selected rectangle to show a handle inside each corner and drag one to round the corners. Equal corners change together and differing ones one at a time; hold ⌥ to swap the two and ⇧ to round to tens. A polygon or star has one radius handle, below its top point, which rounds all of its corners; drag the handle on its next point around the centre to change the point count, and a star's handle on its first inner point towards or away from the centre to change its ratio. The handles hide while the shape is under 108 pixels across on screen; zoom in to reach them. ### Ellipse Arcs Select an ellipse to see its arc in the Appearance section: **Start** is the angle the arc starts at, in degrees; **Sweep** is how much of the full turn it covers, in percent; and **Ratio** is the size of the hole in the middle, as a percentage of the ellipse, for rings and donut charts. Type a value or drag the field; the canvas handles of the ellipse change the same three values. ### Effects Add visual effects from the Effects section: * **Drop Shadow** — offset, blur radius, spread, color * **Inner Shadow** — same controls, rendered inside the shape * **Layer Blur** — blurs the entire node * **Background Blur** — blurs content behind the node * **Foreground Blur** — blurs content in front Click **+** to add an effect. Each effect row is collapsible with inline controls. Toggle the eye icon to enable/disable an effect. ## Frames and Sections **Frames** are containers. Drag shapes into a frame to make them children, or start drawing inside one: a new shape goes into the frame under the point where you start, except locked frames, and joins the end of an auto-layout flow. Drawing a frame over existing nodes puts the unlocked ones it fully covers inside it. New frames clip their content, as in Figma (turn off **Clip content** to let children show outside), and frames support [auto layout](./auto-layout). Select the Frame tool to browse collapsible presets for phones, tablets, desktops, presentations, watches, paper, social media, Figma Community assets, and archived devices in the Design panel. Choosing a preset creates a named frame centered in the viewport and returns to the Select tool. With an existing frame selected, use its Frame preset dropdown to resize it without changing its name. **Sections** are top-level containers that take in the sibling nodes they fully cover when drawn, moved, or resized. They're useful for organizing large canvases into logical areas. Sections display a title pill that you can drag. ## Keyboard Shortcuts | Action | Mac | Windows / Linux | |--------|-----|-----------------| | Rectangle tool | R | R | | Ellipse tool | O | O | | Line tool | L | L | | Frame tool | F or A | F or A | | Section tool | ⇧S | Shift + S | | Constrain to square/circle | Shift + drag | Shift + drag | ## Tips * Sections can only exist at the top level — they can't be nested inside frames. * Use frames with [auto layout](./auto-layout) to build responsive layouts. * [Export](./exporting) individual shapes or groups as images via the properties panel or context menu. --- --- url: 'https://pairdraw.dev/user-guide/text-editing.md' description: >- Creating and editing text with rich formatting, fonts, and inline editing in Pairdraw. --- # Text Editing Create text nodes and edit them directly on the canvas with full rich text support. ## Creating Text Press T to activate the text tool, then click on the canvas. An empty text node appears with a blinking cursor — start typing immediately. ## Inline Editing Double-click any existing text node to enter inline editing mode. A blue outline appears around the text to indicate edit mode. Click outside the text node to commit and exit editing. Text is rendered directly on the canvas — there's no separate text input overlay. ## Cursor Navigation | Action | Mac | Windows / Linux | | ---------------------- | --------------------------------------------------- | --------------------------------------------------------------- | | Move left/right | ← / → | ← / → | | Move up/down | ↑ / ↓ | ↑ / ↓ | | Move by word | ⌥← / ⌥→ | Ctrl + ← / Ctrl + → | | Move to line start/end | ⌘← / ⌘→ | Home / End | Hold Shift with any movement key to extend the selection. ## Text Selection * **Click** inside a text node to position the cursor * **Click + drag** to select a range of text * **Double-click** a word to select it * **Triple-click** to select all text in the node ## Rich Text Formatting Apply formatting to selected text, or toggle the style for the entire node when nothing is selected. | Action | Mac | Windows / Linux | | --------- | ------------------------ | ------------------------------ | | Bold | ⌘B | Ctrl + B | | Italic | ⌘I | Ctrl + I | | Underline | ⌘U | Ctrl + U | Strikethrough is available via the **S** toggle button in the Typography section of the properties panel (no keyboard shortcut — ⌘S is used for Save). Formatting is applied per character. When you type between a bold and regular segment, the new text inherits the style of the preceding segment. The **B / I / U / S** toggle buttons in the Typography section of the properties panel also apply formatting. ## Links Text can link to a web page or an email address, on the whole text or on selected characters. With the layer selected, choose **Add link** in the Typography section of the properties panel, in **Text → Add Link** in the menu bar, or in the canvas menu. The link editor opens under the text: type an address — a bare domain or `name@host` gains its `https://` or `mailto:` — and press Enter to apply it, or Escape to close without changes. The editor also edits the link later and removes it. ⌘-click (Ctrl-click on Windows and Linux) a link on the canvas, or click it in Preview, to open it. ## Editing Operations | Action | Mac | Windows / Linux | | ------------------------- | ------------------------ | -------------------------------------- | | Delete word before cursor | ⌥⌫ | Ctrl + Backspace | | Delete to line start | ⌘⌫ | — | | Cut | ⌘X | Ctrl + X | | Copy | ⌘C | Ctrl + C | | Paste | ⌘V | Ctrl + V | ## Resizing and Truncation The **Resizing** control in the Layout section sets how the text box follows its content: * **Auto width** — the box grows to fit each line on one line (Figma's width-and-height auto-resize). * **Auto height** — the width stays fixed and the box grows taller as the text wraps. * **Fixed size** — the box keeps the size you give it. **Truncation** in the Typography section clips text that overflows the box: **Ending** adds an ellipsis, and **Maximum lines** caps how many lines draw before it truncates. A truncating text keeps its box inside auto layout, so a hugging frame sizes to that box instead of collapsing to zero. ## Font Picker Open the font picker in the Typography section of the properties panel to change the font family. The picker features: * **Search filter** — type to narrow the font list * **Font preview** — each font name is rendered in its own typeface * **Virtual scroll** — handles large font lists efficiently * **Scroll-to-current** — the current font is highlighted when the picker opens ## Font Family Variables A font family can come from a string variable. In the Typography section, choose **Apply variable to font family** beside the family and pick a variable whose value is a font family name. The text then follows the variable: switching the variable's mode, or changing its value, changes the family, and the editor loads the new family's fonts. Picking a font in the font picker detaches the variable and sets that font directly. ## Text on a Path Imported Figma text-on-path layers retain their curved glyph layout. You can edit their text and typography, resize and select them, and save or export the result while preserving the path layout. This is support for existing imported path-text layers, not a separate drawing tool for attaching arbitrary text to a new path. ## Font Weight Change the font weight in the Typography section of the properties panel. Available weights depend on the selected font family (e.g., Regular, Medium, Bold, Black). ## Variable Fonts When the text's font is variable, such as Inter, the Typography section lists its axes (weight, optical size, width, and any others the font has) with the value each is drawn at. Type or drag a value to set it; choosing a weight, slant, or family puts the axes back at that style's own. Optical size reads **Auto** while it follows the font size; set a value, or choose **Fixed** from its menu, to hold it, and **Auto** to follow the size again. ## Font Sources * **Default font** — Inter is loaded automatically * **Desktop app** — system fonts plus enabled Google Fonts, Fontsource, Bunny Fonts, and Fontshare catalogs * **Browser** — system fonts are available in Chrome and Edge with local-font permission. Enabled Fontsource, Bunny Fonts, and Fontshare providers can load online fonts, subject to network access and browser CORS rules; Google Fonts is disabled in the Pairdraw browser app * **Downloaded fonts** — the desktop app caches downloaded faces for reuse on the same machine Allow system font access and choose online providers in **Settings › Fonts**, which the gear next to the font family opens; in the desktop app it also manages downloaded fonts and fallback packs. ## Document Fonts Drop a TTF, OTF, WOFF, or WOFF2 file onto the canvas to add its family to the document itself: the family appears in the font picker, travels inside the `.fig` file, and ships with web and Storybook exports. Fonts the document carries need no install and no provider. ## Missing Fonts and Substitutions When a requested family or style cannot be loaded, Pairdraw displays a warning above the editor instead of silently treating fallback rendering as faithful typography. Expand the warning to see every affected face and its active substitute. Use **Select layers** to locate all affected text nodes, **Replace fonts** to swap a face for one that is available, or **Retry fonts** after changing network access, local-font permission, or provider settings. A style may be synthesized from another loaded face in the same family; a missing family falls back to Inter when available. ## Replacing Fonts **Replace fonts** opens from the missing-fonts warning and from the footer of any font-family menu. It lists every family and style the document uses, with missing faces first and the number of text layers that draw in each. Missing faces are selected by default and point at Inter Regular; any row can be unchecked or pointed at another family and style. Applying replacements changes every place the source face appears — each text layer's own font, every character range that overrides it, and text styles — in one undoable step. Other fonts keep their character ranges. Run **list\_fonts** with `scope: "document"` from an agent to see the faces, and **replace\_fonts** to do the same from a script or MCP client. ## Tips * The font list is preloaded at startup so the picker opens without delay. * IME input (Chinese, Japanese, Korean) is fully supported. * Rich text formatting is preserved when opening and saving .fig files. * See [Components](./components) for how text overrides work in component instances. --- --- url: 'https://pairdraw.dev/user-guide/pen-tool.md' description: Drawing vector paths with bezier curves using the pen tool in Pairdraw. --- # Pen Tool The pen tool creates vector paths using a vector network data model, compatible with Figma's .fig format. ## Activating Press P to activate the pen tool. ## Placing Points * **Click** to place a corner point (straight-line segment) * **Click + drag** to place a curve point with bezier tangent handles — the drag direction and length control the curve shape * **Hold Space** while dragging (without releasing the mouse button) to move the point itself Click multiple points to build a path segment by segment. A preview line extends from the last placed point to your cursor as you move. ## Closing a Path Click on the **first point** of the path to close it into a loop. Closed paths can be filled. ## Open Paths Press Escape to commit the current path as an open path. Open paths render as strokes only — they're not filled. ## Vector Networks Paths in Pairdraw use vector networks — a more flexible model than simple point lists that supports branching paths and complex topology. This is the same model Figma uses, so paths round-trip perfectly in .fig files. ## Pencil Press ⇧P, or pick Pencil from the pen tool's menu in the toolbar, to draw freehand. Each stroke becomes its own vector layer, smoothed into curves you can edit like any other path, and the pencil stays active for the next stroke. * Zoom in to keep more detail: the curve follows your stroke to within a few screen pixels. * Hold Shift to draw straight, horizontally or vertically, from where you pressed it. * End a stroke where it started to close it into a loop. * A stroke goes into the frame that holds all of it, otherwise onto the page. * New strokes contrast with what they are drawn on. Change the stroke of the last one you drew, and the pencil keeps that style. ## Keyboard Shortcuts | Action | Mac | Windows / Linux | |--------|-----|-----------------| | Pen tool | P | P | | Pencil | ⇧P | Shift+P | | Commit open path | Escape | Escape | ## Tips * The preview line always starts from the last placed point — it won't jump to (0,0). * Drag longer when placing a curve point to make the curve wider. * After creating a path, use the properties panel to adjust its fill, stroke, and effects. --- --- url: 'https://pairdraw.dev/user-guide/vector-edit.md' description: >- How to edit vector path geometry: anchors, bezier handles, modifiers, and Pen tool actions in edit mode. --- # Vector Object Editing Vector Object Editing mode lets you change a curve's **geometry**: anchor positions, segment shape, and bezier handles.\ In this mode, you edit the path itself, not standard object transforms. ## Entering the Mode * Select a vector object with the Select tool. * **Double-click the curve**. This activates geometry editing for the selected vector. ## Exiting the Mode * Press Escape. * Click empty space on the canvas. * Or switch to another editing context. ## What Changes in This Mode * The normal transform bounding box is disabled for the object. * Anchor, segment, and handle editing becomes available. * Cursor behavior does not switch to resize/rotate at the layer's bbox corners; it does over the transform box of selected points (see [Transform Selected Points](#transform-selected-points)). ## Basic Actions ### Move an Anchor * Drag an anchor point. * Connected segments and path shape update live in preview. ### Edit a Bezier Handle * Drag a handle on the anchor. * By default, behavior follows the anchor's current handle composition. ### Select and Move a Segment * Click a segment to select it. The segment turns blue and shows a knob at its midpoint; its anchors stay unselected. * Shift + click adds a segment to the selection, or removes a selected one. * Drag a segment to move the two anchors it joins, along with the rest of the selection. ### Select with a Marquee * Drag over empty space to select the anchors inside the rectangle and the segments between them. * Shift + drag adds them to the selection. ### Select a Region * Move the pointer inside a filled area: the region under it is hatched with diagonal lines. * Click inside it to select the region and all of its points; drag to move it. * Shift + click adds the region to the selection. ### Delete Anchors and Segments * Press Delete or Backspace to delete the selection. * A deleted anchor takes its segments with it. * A deleted segment takes only the anchors it leaves unconnected, so deleting the middle segment of a path splits it in two. * Deleting everything deletes the layer. ## Cut, Join, and Reshape | Action | Mac | Windows / Linux | | ---------------------- | ----------------------------------------- | --------------------------------------- | | Cut tool | X | X | | Smooth or corner point | Double-click a point | Double-click a point | | Straighten a segment | Cmd + double-click | Ctrl + double-click | | Bend a segment | Cmd + drag a segment | Ctrl + drag a segment | | Bend, keep neighbours | Cmd + Option + drag | Ctrl + Alt + drag | | Join two end points | Cmd + J | Ctrl + J | | Duplicate points | Option + drag | Alt + drag | | Move points | Arrow keys | Arrow keys | * **Cut tool:** press X, then click a segment to cut it there, or click a point to separate the segments that meet at it. Curves keep their shape, and a closed shape that is cut stops filling. Press X again, Escape, or another tool key to put it down. * **Smooth or corner:** double-click a corner point to give it handles along the line between its neighbours, and double-click a smooth point to remove its handles. * **Straighten:** Cmd/Ctrl + double-click a curved segment to remove both of its handles. * **Join:** select two end points and press Cmd/Ctrl + J. Points in the same place become one point; points apart are joined by a straight segment. Joining the two ends of one path closes and fills it. While a path is being edited, this shortcut joins points instead of opening the chat. * **Duplicate:** hold Option/Alt and drag selected points or segments to drag a copy. A single point's copy stays joined to it, so the drag extends the path. * **Nudge:** the arrow keys move the selected points by the nudge distance set in Settings → Editor, and Shift + arrow by the large nudge distance. * **Bend:** Cmd/Ctrl + drag a segment to bend it so the place you grabbed follows the pointer. A smooth end point stays smooth and its other handle turns with it. Add Option/Alt to leave the handles of the neighbouring segments where they are; the end points then become corners. ## Transform Selected Points When two points or segments are selected, a transform box surrounds them. * Drag a corner or an edge to scale the selected points from the opposite side. Hold Shift to keep proportions and Option/Alt to scale from the centre. * Drag just outside a corner to rotate them around the centre of the box. Hold Shift to rotate in 15° steps. * Points and segments under the pointer stay draggable on top of the box, and each transform undoes in one step. ## Handle Drag Modifiers | Action | Mac | Windows / Linux | | -------------------------------- | ------------------------ | ----------------------- | | Continuous (Smooth / Continuous) | Cmd + drag | Ctrl + drag | | Corner (Independent handles) | Option + drag | Alt + drag | | Direction lock (length only) | Shift + drag | Shift + drag | ### Continuous: Cmd/Ctrl + drag * The active handle is constrained to the same line as the sister handle. * Only the active handle length changes. * Use this for smooth transitions without a corner break. ### Corner: Option/Alt + drag * The active handle is edited independently. * The sister handle stays in place. * Use this to create a sharp corner transition. ### Direction Lock: Shift + drag For anchors with **Continuous** or **Symmetric** composition: * handle direction is locked to the value from **before the current drag started**; * dragging changes only handle length (or lengths, depending on composition). ## Bend Override by Dragging an Anchor When you drag an anchor while holding Cmd/Ctrl, the editor selects the target handle by **segment attachment direction** at that anchor (not by nearest neighbor-point distance).\ This also works on multi-branch vector-web anchors: once resolved, the target handle stays locked for the current drag. ## Using the Pen Tool in Edit Mode With the Pen tool active: * **Click a segment** to insert a new anchor (split segment). * **Click an open-path endpoint** to resume drawing from that point. * **Option/Alt + click an anchor** to delete it (when topology allows). For path creation and closing behavior, see [Pen Tool](./pen-tool.md). ## Practical Workflow 1. Draw a shape with the Pen tool. 2. Double-click the curve to enter Vector Object Editing mode. 3. Move anchors to refine the silhouette. 4. Drag handles: * with Cmd/Ctrl for smooth continuous transitions, * with Option/Alt for independent edits, * with Shift for length-only edits. 5. Press Escape to exit. --- --- url: 'https://pairdraw.dev/user-guide/icons.md' description: >- Search open-source icon sets, insert icons, and swap or recolor them in Pairdraw. --- # Icons Pairdraw searches the open-source icon sets published through [Iconify](https://iconify.design), such as Lucide, Material Symbols, Tabler, and Phosphor. A placed icon remembers which icon it is, so you can swap it for another or change its color later, and exports write it as that icon. Searching and placing icons needs a network connection to the Iconify API. ## Inserting an Icon Open the icon picker in any of these ways: * Click the **Insert icon** button at the end of the toolbar * Choose **Object → Insert Icon…** * Search for **Insert Icon** in the command palette (⌘K) Before you type, the picker shows the icons already placed in this file and the ones you picked lately. Type what you're looking for, such as `arrow` or `heart`, to search every set; each result shows a preview and the set it comes from. Pick one to place it, 24 × 24, in the middle of the view, inside the frame you're editing if you've entered one. The new icon is selected, and ⌘Z removes it in one step. ## Choosing an Icon Set The set button at the end of the search field (**All icon sets** at first) narrows the picker to one set. Sets are grouped by kind, such as Material or Logos; type to find one by name, such as `tabler`. Each set shows how many icons it has. With a set chosen, the picker shows the whole set, loading more as you scroll, and a search looks only in that set. Hover over an icon, or move to it with the arrow keys, to see its name, set, and license below the grid. The picker remembers the set you chose last, and **Swap icon** opens on the set of the icon you're swapping. ## The Icon Section Selecting a placed icon adds an **Icon** section to the Design panel. * **Swap icon** opens the picker and draws the chosen icon in place of the current one. The icon keeps its size, position, and color. * **Icon color** changes the color of the icon's own paths. Icons drawn in several fixed colors, such as brand logos, keep those colors and don't show this field. Material Symbols icons (outlined, rounded, and sharp) also show their font axes: **Weight**, **Filled**, **Grade**, and **Optical size**; a Material Symbols icon keeps them when you swap it. SF Symbols, in the desktop app on macOS 14 or later, show **Weight** from Ultralight to Black, **Scale** (Small, Medium, or Large), and **Rendering** (Monochrome or Hierarchical). Each swap or color change is one undo step; dragging in the color picker undoes as a single change. An icon's glyph can follow a text variable: bind one and switching the variable's mode swaps the drawn icon. The icon redraws on the mode change as one undo step. An icon is a frame of vector paths, named after the icon, such as `cat`, and marked with a smiley in the layer tree. Unlike other frames on the page, it has no title on the canvas, and resizing it scales its paths. Its layers, constraints, effects, and the rest of the Design panel work as they do for any frame. ## Editing an Icon's Paths You can edit an icon's paths like any vector. Once its points, paths, or own colors change, the Icon section says **Modified**: * The icon exports as the paths it now draws rather than by its name, so the edit is kept. * **Reset** (the circular arrow) draws the original icon again, at the same size and color. * Swapping asks first, since a swap draws a new icon and discards the edit. Resizing the icon or changing its color doesn't count as an edit. **Detach icon**, in the Icon section, the canvas menu, or **Object → Detach Icon**, makes an icon plain artwork: it keeps its paths but is no longer swapped, recolored, or exported as an icon. Like every icon command, it's one undo step. ## Icons in Exports * **Design JSX** writes a placed icon as ``. * **HTML** writes it as inline SVG marked with `data-icon`, with its paths painted in `currentColor` and the icon's color set on the ``, so changing that one `color` recolors it. * **SVG and images** draw it like any other vector. Icons placed by AI agents, MCP clients, and design JSX are icons in the same way, so the Icon section works on them too. --- --- url: 'https://pairdraw.dev/user-guide/photos.md' description: Fill a layer with a free stock photo from Unsplash or Pexels in Pairdraw. --- # Photos Pairdraw searches the free photo libraries of [Unsplash](https://unsplash.com) and [Pexels](https://www.pexels.com) from a layer's image fill. Both let anyone use their photos for free, and both ask for an API key to search them, which is free too. The key stays on your device. Searching and using photos needs a network connection to the service you search. ## Filling a Layer with a Photo Draw the frame or shape the photo should fill, then: 1. Open its fill and switch it to **Image**. 2. Choose **Stock photo** in the preview. 3. Before you type, the picker shows the service's own picks: Unsplash's editorial feed or Pexels' curated photos. Type what you're looking for, such as `mountains` or `coffee`; more results load as you scroll. Hover over a photo, or move to it with the arrow keys, to see who took it. 4. Pick one. It becomes the layer's image fill and keeps the fill's scale mode, so **Fill**, **Fit**, **Crop**, and **Tile** work on it as on any image. The service button in the picker's header switches between Unsplash and Pexels. The picker opens on the one you used last, or on one with a key when that one has none. Until a service has a key, the picker says so: choose **Open Settings**, open the service in **Settings → Media**, follow **Get API key** to create one, paste it, and choose **Save**. **Test connection** tries the key you typed, or the saved one, with one request to the service. An Unsplash app has two keys: paste its **Access Key**, not its Secret key. A new Unsplash app allows 50 requests an hour until Unsplash approves it for production; each search, each page of results, and each test counts. Pexels has paused issuing new API keys. If you already have a Pexels key, it still works; otherwise use Unsplash. ## Generating Images with AI With your own key for OpenAI or an OpenAI-compatible service, set up in **Settings → Image services**, you can generate images from a prompt. A generation becomes a new layer, or fills the image fill you are editing. **Settings → Image services** also holds the key for removing or replacing an image layer's background — with your AI image service or with remove.bg — from the canvas menu's **AI image** group, the image fill picker, or the command palette. Removing a background and replacing it with a scene you describe each undo in one step. ## Credits and Keys Unsplash and Pexels ask that photos are credited to the people who took them; the picker names the photographer of each photo. Pairdraw tells Unsplash when one of its photos is used, as its API terms require. Change or remove the keys in **Settings → Media**. The AI chat's stock photo tool uses the same keys. --- --- url: 'https://pairdraw.dev/user-guide/browser.md' description: >- Open a web page beside your document in Pairdraw, then import it, screenshot it, or let the chat work with it. --- # Built-in Browser Pairdraw opens a web page in a window of its own, beside the editor, and brings what it shows onto the canvas: the page or one element as layers, or a picture of it. The window is a separate webview with its own data store, so it holds none of the editor's data, and the page cannot call the editor's commands. ## Opening the Browser Choose the globe icon in the editor's top bar, the one labeled **Open the browser**. Type an address and choose **Open**. The window shows one page at a time: opening another address replaces the page it shows. **Close** closes the window, and the panel then shows no title until you open a page again. The browser opens `http` and `https` addresses only. A bare host gets `https://`, such as `example.com`; a bare loopback host — `localhost` or a `127.` address — gets `http://`, because that is how a local development server answers. A port may follow the host, as in `example.com:8080`. The panel says why it will not open anything else: an empty address, a scheme the browser does not open (`file:`, `javascript:`, `data:`, `blob:`, and custom schemes such as `pairdraw:`), or text that is not an address. The window applies the same rule when the page follows a link or a redirect, and a link that asks for a new window opens nothing. The panel shows the page's title beside its heading once the page has loaded. It has no progress indicator while a page loads, and no message when a load fails; the address stays as you typed it. ## Moving Around a Page **Back**, **Forward**, and **Reload** act on the page's own history, which the window keeps. Back and Forward do nothing when there is nowhere to go, and Reload asks for the page again. ## Zoom and Device Sizes **Zoom out** and **Zoom in** change the page zoom in steps of 25%; the number field takes any value from 25 to 400 and applies what you enter. The zoom is kept for the rest of the session, including across the pages you open. The **Device** menu changes the size of the page's content area: * **Desktop** is the window's own size, and restores the size the window had before a preset. * **Phone, 390 by 844** and **Phone, 412 by 915** are portrait phone sizes. * **Tablet, 820 by 1180** is a portrait tablet size. A preset changes how much page the window shows, not the screen's pixel density: the page keeps the scale of your display, so text and images are not drawn at the density the device would have. ## Importing a Page or an Element **Import page** reads the open page and lays it out on the canvas as styled layers, the same import a page pasted from the web uses. The layers are named after the page's title. **Import element** asks you to click the element in the browser window, then imports that element alone. If you do not click within 30 seconds the pick ends, and cancelling it imports nothing. Both read the browser's own capture. Only that capture is accepted; other HTML is not styled into a second importer. ## Screenshots onto the Canvas The three screenshot buttons put a PNG on the canvas as an image layer, named after the button — **Screenshot of the view**, **Screenshot of the page**, or **Screenshot of an element**: * **Screenshot of the view** is the part of the page the window shows. * **Screenshot of the page** grows the page's view inside the window to the document's size first — up to 2048 by 4096 points — and restores it afterwards. A longer page is cut there. * **Screenshot of an element** asks you to click the element in the browser window, as the element import does. Screenshots are available in the macOS build. ## What the Chat Can Do with the Page The built-in chat works on the page you have open: * It reads a short outline of the page — headings, links, buttons, and fields — or one element by its CSS selector, and gets the element's tag, role, text, and box. * It marks an element as a chip in the chat. The chip names the page; while your pointer is over it and that same address is still open, the element is outlined in the browser window. * It clicks, types into a field, presses a key, scrolls, or waits for an element to appear or for the page to move to another address. * It puts a picture of the view or of the page on the canvas. * It opens another `http` or `https` address in the open window. Reading the page and marking an element change nothing, so they never ask. A change to the page, a screenshot placed on the canvas, and a move to another address ask for **Allow** or **Deny** when **Ask before changes** is on in **Settings → AI**; with it off they run without asking. **Always allow** covers that page's host for the rest of the chat, so an action on another site asks again. A change the page never finishes ends after 10 seconds. The chat cannot open or close the browser window; choose the toolbar's **Open** or **Close** for that, and a call it makes while the window is closed answers with an error. Page text it reads is untrusted content to report, not instructions to follow. ## Limits * The built-in browser is part of the desktop app. A browser tab shows the panel and says why it cannot open a page there. * Screenshots are available in the macOS build only. * Pixel density is not emulated: a device preset changes the page's size, not the screen's scale. * The page has a website data store of its own, kept on disk, so it shares no cookies or storage with your own browser. It is not an incognito window: its cookies stay there between sessions. It still shares nothing with the editor. * The window shows one page, with no tabs and no bookmarks. * Addresses are `http` and `https` only. --- --- url: 'https://pairdraw.dev/user-guide/script-layers.md' description: >- Draw layers with a small JavaScript program that lives in the document, with inputs you can bind to variables. --- # Script Layers A script layer is a layer whose program draws its own children. The program lives in the document, runs in a sandbox, and returns the layers to draw, so a document carries its own code and reads nothing from disk. ## Inserting a Script Layer Choose **Object → Insert Script…**. The layer is placed in the middle of the view as a 320 by 200 container, and it runs a starter program that draws a bar chart. Select a script layer and the design panel shows a **Script layer** section: **Convert to layers** and **Run** at its head, the controls its program declares, and the program itself. Editing the code and leaving the box stores the new program and runs it. ## Drawing with `pencil` A program runs with `pencil` in scope, and its body runs as a function, so it returns the layers it draws. `pencil` has one call per layer kind: * `pencil.frame(props, children)` * `pencil.rect(props, children)` * `pencil.roundedRect(props, children)` * `pencil.ellipse(props, children)` * `pencil.text(props, children)` * `pencil.line(props, children)` * `pencil.node(type, props, children)` for any of those kinds by name Each call returns a description of one layer, and the children array nests layers under it. The program must return one layer or an array of layers; returning nothing is an error. A layer takes: * **Placement and size**: `name`, `x`, `y`, `width`, `height`. * **Paint**: `fill` and `stroke` as any CSS colour the canvas takes, such as `#fff`, `#ffffff`, `#ffffffff`, `rgb(91 115 242)`, or a name, `strokeWeight` (a stroke is drawn only when it is set), `opacity` from 0 to 1, and `radius` for rounded corners. * **Text**, on `pencil.text`: `text`, `fontSize`, `fontWeight`, and `align` as `LEFT`, `CENTER`, or `RIGHT`. * **Layout**, on a frame or a shape: `layout` as `HORIZONTAL` or `VERTICAL`, with `gap` and `padding`, which sizes the layer to its children. ```js /** * @schema * @input bars number = 5 * @input accent color = #5b73f2 */ const heights = [24, 40, 32, 48, 36].slice(0, pencil.inputs.bars) return pencil.frame({ name: 'Chart', width: 320, height: 200 }, [ pencil.rect({ width: 320, height: 200, radius: 12, fill: '#ffffff' }), ...heights.map((bar, index) => pencil.rect({ x: 24 + index * 56, y: 176 - bar * 3, width: 40, height: bar * 3, radius: 6, fill: pencil.inputs.accent }) ) ]) ``` A script draws frames, rectangles, rounded rectangles, ellipses, text, and lines. It cannot make components, instances, or variables, and it cannot read the document it is in. A run is repeatable: `Math.random` is replaced by a generator seeded from the layer and its program, so the same program draws the same layers every time. The rest of `Math` is unchanged. ## Inputs A leading block comment with a `@schema` line declares the controls the panel shows. Each `@input` line adds one, as a name, a kind, and an optional default: ```js /** * @schema * @input title string = "Chart" * @input bars number = 5 * @input dark boolean = false * @input accent color = #5b73f2 * @input size enum(small, medium, large) = medium * @input target ref */ ``` The kinds are `number`, `string`, `boolean`, `color`, `enum`, and `ref`. An `enum` lists its choices in the parentheses and starts at its first choice; a `ref` declares a name with no default and takes no variable. A declared input with no value runs as `0`, an empty string, off, or black, by its kind. Only the leading block comment is read, so an `@input` line inside a string, or below the first statement, declares nothing. The program reads its inputs by name from `pencil.inputs`. ## Binding an Input to a Variable A `number`, `string`, `boolean`, or `color` input can take its value from a document variable instead of its stored one. Choose the ⇄ button beside it (**Bind input to variable**) and pick a variable of the matching type; the variable's value then wins. **Detach variable** returns the input to its stored value. A bound variable that has no value, or whose type does not match the input, stops the run, and the panel and the layer say which input it was. ## Running **Run** runs the stored program again. A script also runs again on its own 300 milliseconds after you resize its layer or change one of its inputs, so the canvas follows the document without another click. A run replaces everything the layer drew before, so the canvas always shows the latest run. The run itself is not an undo step; storing a program, an input value, or a binding is. ## Errors A failing program shows its message under the code box, and the canvas replaces the drawn layers with a red **Script error** frame carrying the same message. The editor stays usable: a program that never finishes ends after 2 seconds with `Script timed out.`, and the next run still works. A run with no layer to draw, or with something that is not a layer, says that instead. ## Limits * A run draws at most 1,000 layers, nested at most 100 deep. * A run has 2 seconds; the sandbox has 5 seconds to start before the run is abandoned. * A program is stored up to 256,000 characters; a longer one is cut when it is saved. * The sandbox is an opaque-origin frame running a worker. `fetch`, `XMLHttpRequest`, `WebSocket`, `EventSource`, and `importScripts` are blocked or absent there, and the app's IndexedDB and Cache Storage are out of reach, so a program reaches neither the network nor the app's storage. * There is no DOM in the sandbox, so a script cannot load images, fonts, or stylesheets. ## Converting to Layers **Convert to layers** replaces the script layer with the layers it drew, in the same place and in one undo step; undo brings the live script back exactly as it was. The drawn layers become ordinary layers you can select and edit. A script that drew nothing leaves nothing behind. ## Saving The program, its input values, and its bindings are saved in the document. In a `.fig` file the layer is written as a frame that records that it is a script, so Figma reads the drawn layers as a plain frame and Pairdraw reads the frame back as a script layer. Opening a document does not run its scripts. A saved script layer shows the layers saved with it and runs when you choose **Run**, change its program, resize it, or change an input. ## The Agent's `script` Tool Agents that use the app's tools have a `script` tool with three actions: `create` places a code layer and runs it, `set_source` replaces a program and runs it, and `run` runs an existing one again. The tool reports the same limits: 1,000 layers per run and 2 seconds, no components, and a `Math.random` seeded from the layer. It needs the app's sandbox, so a headless host answers that script layers are unavailable there. --- --- url: 'https://pairdraw.dev/user-guide/page-snapshots.md' description: >- Keep a picture of a page from the built-in browser as a layer, with its address, and refresh it by hand. --- # Page Snapshots A page snapshot is a layer that holds a picture of a page from the built-in browser, along with the page's address. It is a snapshot, not a live page: the document stores pixels, opening a file never fetches the page, and nothing updates the picture except a refresh you ask for. ## Creating One A snapshot is created by the app's MCP server through the `browser_snapshot` tool, while the desktop app's built-in browser shows a page: * leave `id` out to store the open page as a new layer; * pass `id` to replace that snapshot's picture. The layer lands on the current page at position 0, 0, named after the page's host, sized to the picture's pixels, with the picture as its image fill. Creating one needs the desktop app and an open browser window; in a browser tab, or with the window closed, the call fails with the same sentence the browser tools use. It never opens a window. ## What It Stores The layer keeps, in the document: * **the page address** — the canonical `http` or `https` URL, up to 2,000 characters; * **the viewport size** — the picture's pixels, from 1 to 8,192 on either side; * **the device preset** — the toolbar preset the picture was taken at, such as `desktop` or `iphone-14`, up to 40 characters; an empty or overlong id is stored as `desktop`; * **the time it was refreshed** — an ISO instant, shown in the panel as a local clock reading. The picture itself is a document image, and the layer's image fill draws it as a fill (`FILL` scale mode), so anything that draws an image draws the snapshot. ## The Design Panel Select a snapshot and the design panel shows a **Page snapshot** section: * **Address** — committed when the field loses focus or Enter is pressed, and only when the window would open that address. The same address changes nothing, and a new one is one undo step. Changing the address does not take a new picture; the layer keeps the old one until you refresh. * **Device** — the toolbar's presets. Choosing one saves it on the layer, selects it on the browser toolbar, and resizes the open window to match; the picture stays until you refresh. * **Refresh** and **Open in browser**. * **Last refreshed** with the stored time. ## Refreshing Refresh needs the desktop app's browser window to be open. A closed window stays closed, and the panel says so. * If the window already shows the snapshot's address, Refresh takes a new picture of the view it shows. * Otherwise it moves the window to the stored address and waits up to 10 seconds for the page to finish loading. A load that does not finish, or a picture of a page other than the one that finished loading, leaves the layer exactly as it was. * The new picture replaces the layer's first image fill, and the layer's width, height, device preset, and last-refreshed time update with it, all in one undo step. A second fill you added beside the picture stays. The picture is always the visible view. A full-page picture and a picked element are the screenshot commands, not a snapshot. ## Open in Browser **Open in browser** opens the stored address in the built-in browser window. It does not change the picture, and it needs the desktop app. ## In a Browser Tab, and for a Collaborator In a browser tab the panel still shows the address, device, and time, and the address and device stay editable, but **Refresh** and **Open in browser** are disabled with a note that they need the desktop app. The snapshot is an ordinary layer of the document, so a collaborator who opens it sees the same picture. Nothing fetches the page for them, and nothing refreshes on its own. ## Saving and Export The picture and the page record are both part of the document: the picture is a stored image and the record is the layer's own data. A `.fig` archive keeps them, so a round trip still knows the address, size, preset, refresh time, and picture. A file whose stored address is not an `http` or `https` page opens as a plain image layer, without the snapshot section. Exporting the layer exports the stored picture, as any image fill exports. Figma shows the layer as an image; the page record travels as plugin data the app reads back. ## Limits * There is no automatic refresh and no live page: no scrolling, links, or scripts run in the snapshot. * Creating or refreshing needs the desktop app and an open window; a browser tab can only edit the record. * The picture's stored size is at most 8,192 pixels on either side, and the pixels must be a real image; anything else stores nothing. * Only one window is involved: the address stored is the one captured with the picture, and a refresh refuses rather than storing an address the picture was not of. * The built-in chat's browser tools do not create snapshots; the `browser_snapshot` MCP tool does. --- --- url: 'https://pairdraw.dev/user-guide/variations.md' description: >- Ask for several versions of a layer, compare them side by side, and keep one in place of the original. --- # Variations Variations are copies of one layer, side by side in a section beside it, for comparing directions before you commit to one. Each version is an ordinary frame you can select, edit, and comment on. When you keep one, the original takes its look and stays where it was. ## Asking for Versions * **With AI** — right-click a layer and choose **Variations…**. It turns on **Let it cook** in the chat with its count and its axis (layout or style) as you last set them; say what to explore, such as "calmer, more white space", and send. The agent copies the layer into a section named `Variations · `, names each version by the idea it tries (`V2 · Calmer palette`), and changes each one. Let it cook does the same whenever a message starts from a layer, by naming it or by having it selected. * **By hand** — right-click a layer and choose **Duplicate as variation**. It adds one plain copy to the layer's set, making the set the first time, and selects it. On a version, it copies that version into the same set. Let it cook asks for 2 to 6 versions at a time; agents and scripts may make up to 8 per request. Pages, sections, component sets, and layers inside an instance cannot be varied; select the frame, the variant, or the instance itself. ## Comparing and Keeping One Select the section or any version and the design panel shows a **Variations** section: * **‹ ›** step through the versions and bring each into view; the list jumps straight to one. * **Use this** replaces the original with the selected version in one undo step. The original keeps its id, name, position, and its place in an auto layout parent, so comments, prototype links, and instances of a main component keep pointing at it. Layers the two share by name and type keep their ids too. The section and the other versions are removed. A comment pinned on a version stays where it was pinned: once that version is removed, the pin shows at its last position, as for any deleted layer, and Undo brings the version back under it. * **Go to original** selects the layer the versions vary. * **Discard all** removes the section and every version, in one undo step. When the original was edited after the newest versions were made, the section says so when you select the set; **Use this** still replaces it, and **Undo** brings the edited original back. **Use this** is unavailable, with the reason shown, when the original was deleted, is locked, belongs to a library, or is a different kind of layer than the version (for example an instance whose version was rebuilt as a frame); **Discard all** still works. A main component stays a main component when you use a version: its properties and publishing are kept, and its instances update. Versions never add components: a main component's versions are frames, and main components inside a varied layer are copied as instances of themselves. **Use this** keeps those main components, and every instance of them, as they were; swapping such a stand-in instance to another component inside a version is not carried into the original. ## Files and Agents A set of variations is saved in `.fig` files and reopens as a set. A `.pen` file keeps the versions as plain frames in a frame, without the set. Agents use the same feature through `create_variations`, `list_variations`, and `pick_variation`, and scripts through `pairdraw.createVariations` (see [Scripting](/programmable/cli/scripting)). An agent changes the layers inside each version and keeps the version's own root layer, so the version can still replace the original; it leaves the choice to you unless you ask it to pick or discard. --- --- url: 'https://pairdraw.dev/user-guide/slides.md' description: >- Arrange a page's top-level frames as slides, present them full screen, and export them. --- # Slides The **Slides** tab in the left sidebar turns a page into a presentation. Top-level frames on the page become slides in layer order; there is nothing to add but frames. ## Arrange * Drag a slide to reorder it, or focus it and press Alt with the up or down arrow. Each move is announced with its new position. * The panel names each slide by its number and frame name. An empty page says that top-level frames become slides. ## Present **Present** (⌘↵ where the menu names it) starts from the selected slide, or the first; **Present from this slide** starts at the chosen one. The presentation takes the whole window: * Previous and next slide, with the position shown as "3 of 12". * **Fit to screen** and **Actual size** for the slide. * Esc exits. Presenting hides the panels and the toolbar, so the slide is the only thing on screen. ## Export The same panel exports the slides to **PDF** or **PowerPoint** (`pptx`). Both write one page or slide per frame. The CLI can export a prototype as video; see [Exporting](/user-guide/exporting). --- --- url: 'https://pairdraw.dev/user-guide/shader-mode.md' description: 'Play, scrub, and tune one shader large, with its inputs beside it.' --- # Shader Mode Shader Mode shows a shader at full size, playing on its own, with the document's panels out of the way. Open it from **View → Shader Mode**, or from a shader fill's **Open in Shader Mode** button in the fill picker. The stage has: * The shader, played live. If the GPU or browser cannot run it, the still frame is shown with a notice. * A transport with **Play**/**Pause**, **Back to start**, and a scrubber for the animation phase, showing the time within the shader's duration. * **Shader settings** beside it: the shader's inputs and effects. An input can be bound to a variable with **Bind input**, so the shader follows the document like any other value. * **Done** (or Esc) leaves the mode. Undo and redo still reach the document. In a read-only document the shader plays, but its settings cannot change. Shader fills themselves — presets, effects, and stops — are covered in [Drawing shapes](/user-guide/drawing-shapes#fill). --- --- url: 'https://pairdraw.dev/user-guide/layers-and-pages.md' description: 'Managing layers, pages, and the properties panel in Pairdraw.' --- # Layers & Pages The editor opens on the canvas alone. The tools stand at the canvas's left, with the layers panel's toggle above them, and the zoom sits in the bottom right corner. The sidebar opens on the left, with tabs for Layers, Assets, Slides, and Design, and the AI chat opens in a column of its own on the right; all of them are resizable by dragging their edges. See [Side Panels](./canvas-navigation#side-panels) for when each panel shows. While the AI chat is closed, a prompt at the bottom of the canvas sends what you write to the chat; turn it off with **Prompt on the canvas** in **Settings → Models → Chat**. Escape in the prompt returns to the canvas. ## Layers Panel The layers panel on the left displays the document hierarchy as a tree. ### Tree View Nodes are shown in a collapsible tree. Click the chevron next to a frame, group, or component to expand or collapse its children. ### Drag Reorder Drag layers to reorder them. Nodes higher in the list render on top. ### Visibility Toggle Click the eye icon next to any layer to hide or show it on the canvas. Hidden nodes remain in the tree. ### Rename Double-click a layer name to rename it inline. Press Enter or click away to commit, Escape to cancel. ### Selection Sync Clicking a layer in the panel selects the corresponding node on the canvas, and vice versa. ### Find Layers Press ⌘F (Ctrl + F), choose **Edit → Find Layers…**, or run it from the command palette to search the shown page's layers by name. Picking a result selects that layer and brings it into view. ## Pages Panel The pages panel shows all pages in the document. * **Switch page** — click a page tab to make it active. The canvas switches to that page and restores its viewport position. * **Add page** — click the add button to create a new page * **Delete page** — remove the current page * **Rename page** — double-click the page name for inline editing. Pressing Enter or Escape, or clicking away, commits the rename. Each page has its own canvas and viewport state. ## Slides Panel The slides panel lists the page's top-level frames as numbered slide thumbnails, in layer order. Click a slide to show its frame on the canvas, and drag a slide — or press Alt with an up or down arrow — to reorder it. **Export slides** writes every slide, in order, to one PDF file. ## Present Mode Present shows the page's slides full screen, one at a time. Start it with ⌘/Ctrl + Enter, **View → Present**, or the Present button in the top bar. The arrow keys, Space, Enter, Page Up/Page Down, and the scroll wheel step through the slides; Escape leaves and returns the canvas and keyboard focus to where they were. A slide taller than the screen is shown at 100% and can be scrolled. ## Documents and Recovery Home starts with a prompt: choose what to create above it (a landing page, mobile app, web app, slides, dashboard, or something else), describe it, and Pairdraw opens a new design and sends the prompt to its AI chat with a guide for that kind; example prompts under it fill the prompt with an idea to edit. Below the prompt you can start from a Figma file, from a page in the built-in browser (desktop app), or from a screenshot the agent rebuilds. Tabs switch between **Recent**, **Drafts**, and **Design systems**, and the menu beside them lists the places your Cloud server and storage bucket add. A search field filters the list, **Open…** opens a file, and **Design** starts an empty design. Recent lists recent local documents. Use grid or list view, and sort recent files by **Name**, **Last used**, or **Created**. ⌘/Ctrl-click adds a file to the selection, Shift-click selects a range, and ⌘/Ctrl+A selects every listed file; the selection bar then opens them in separate editor tabs, removes them from Recents, or deletes stored documents. A file's ⋯ menu or right-click menu offers **Remove from Recents**, which forgets the file without deleting it, and **Save As…**, which saves a copy elsewhere. **Design systems** lists the built-in Pairdraw Basics and the component libraries you have published, as Goodies does; picking one opens a new design with that library turned on in the Assets panel. A new design is kept as a draft on this device while you work on it: each change is written shortly after you make it, so closing its tab asks nothing. **Drafts** on Home lists them with a preview; open one to continue it, or pick **Delete draft** from its ⋯ or right-click menu to remove it for good. Saving a draft to a file or to storage, in the editor or with **Save As…** on Home, takes it out of Drafts. Drafts live in this browser profile or desktop installation only, and need **Automatically preserve unsaved work** turned on and a browser that keeps site data. In **Settings → General → Recovery**, **Automatically preserve unsaved work** controls drafts and local recovery copies. With recovery enabled, unsaved documents without a file path remain recoverable even after their tabs close. When Pairdraw offers **Recover unsaved work**, choose **Restore** to reopen a document or **Discard** to remove its recovery copy. A file you opened also keeps a backup of changes it has not been saved with yet, written while autosave is off, or when the window closes before autosave has written them. The next time that file opens, **Recovered changes** offers **Save** to write them into the file, **Save As…** to open them apart and save them as a new file, or **Don’t Save** to keep the file as it is and drop the backup. Closing the dialog keeps the backup for the next time. Saving the file drops its older backups, and in the browser a backup older than the file's last change is not offered. A backup whose file has not opened for a week, for example because the file moved, is also listed in **Recover unsaved work**. Disabling recovery stops automatic preservation and removes recovery copies owned by currently open documents. It does not bulk-delete snapshots from previously closed documents. Recovery is local to this installation/browser profile; it is not a replacement for saving a file, cloud synchronization, or a backup. ## Goodies The gift button in the top bar, **Object → Goodies…**, or the command palette opens Goodies, a collection of things to start from: styles to pin to the AI chat, the design systems you can enable, scripts that land on the canvas as [script layers](./script-layers), and the gallery shaders, which fill the selected layers or a new rectangle. ## Properties Panel The **Design** tab of the left sidebar holds the properties panel, which switches between Design and Code, with [Lint](./checking-designs) as an icon tab beside them. It follows the selection while it is showing; selecting a layer never switches the sidebar to it. ### Design Tab Shows the properties of the selected node(s), organized in sections: * **Appearance** — opacity, corner radius (with independent corner toggle), visibility * **Fill** — solid color, gradients (linear, radial, angular, diamond), image fills, variable bindings * **Stroke** — color, width, cap, join, dash pattern * **Effects** — drop shadow, inner shadow, layer blur, background blur, foreground blur * **Typography** — font family, size, weight, B/I/U/S formatting buttons (visible for text nodes) * **Layout** — [auto layout](./auto-layout) controls (visible for auto-layout frames) * **Export** — scale, format, and export button (see [Exporting](./exporting)) When no nodes are selected, the Design tab shows page-level properties including the canvas background color. ### Code Tab Displays the selection as code with syntax highlighting, line numbers, and a copy button. Choose the output: * **Design JSX** — Pairdraw's component tree, which `renderJSX()` reads back; edit it live and the layers follow * **HTML** — markup styled with plain CSS or Tailwind classes * **Vue** and **React** — components for the selection, styled with CSS or Tailwind While the Code tab is open, it also underlines the design check's errors and warnings on the code of their layers ([Checking Designs](./checking-designs#in-the-code-panel)). ## AI Chat Column The [AI chat](../programmable/ai-chat) creates and changes design elements from natural-language requests. It opens in a column of its own on the right, so the Design tab stays in view while an agent works. Open and close it with the sparkles button among the document's actions in the top bar or with ⌘J; drag its edge to resize it. The column stays open or closed, at the width you left it, across reloads. Configure reusable models and provider connections in Settings, and browse locally saved conversations from the chat's history menu. ## Keyboard Shortcuts | Action | Mac | Windows / Linux | |--------|-----|-----------------| | Open or close the AI chat column | ⌘J | Ctrl + J | | Find layers | ⌘F | Ctrl + F | ## Mobile Layout On mobile and small screens, the side panels are replaced by a swipeable bottom drawer. Tabs at the top of the drawer switch between Layers, Properties, Design, Code, and AI views. The toolbar collapses to a compact horizontal strip with category switching. ## Tips * Panel widths, the AI chat column’s included, are saved automatically and persist across reloads. * Use the layers panel to find overlapping nodes that are hard to click on the canvas. * The [context menu](./context-menu) provides additional actions for selected nodes. * See [Selection & Manipulation](./selection-and-manipulation) for z-order shortcuts (]/\[) and visibility/lock toggles. --- --- url: 'https://pairdraw.dev/user-guide/exporting.md' description: >- Export images, SVG, and .fig subsets, and open .fig or .pen documents in Pairdraw. --- # Exporting Export individual nodes as images or `.fig` subsets, and open full `.fig` or `.pen` documents. ## Image Export Select a node and use the Export section in the properties panel. ### Export Settings * **Scale** — 0.5×, 0.75×, 1×, 1.5×, 2×, 3×, or 4× (hidden for SVG — vectors are resolution-independent) * **Format** — PNG (transparent background), JPG (white background), WEBP (transparent background), SVG (vector), PDF, or HTML **File → Export Selection** exports the selection as PNG, SVG, or `.fig`, and ⇧⌘E exports it as PNG at once. The app does not offer PowerPoint (`.pptx`) or draw.io export. The [CLI](/reference/cli#export) still exports both: `pairdraw export design.fig -f pptx` or `-f drawio`. You can add multiple export settings to export the same node at different scales or formats in one go. A live preview with a checkerboard background shows what will be exported. ### Export Methods | Method | Mac | Windows / Linux | |--------|-----|-----------------| | Keyboard shortcut (PNG) | ⇧⌘E | Shift + Ctrl + E | | File menu | **File → Export Selection** (PNG, SVG, or `.fig`) | **File → Export Selection** (PNG, SVG, or `.fig`) | | Properties panel | Click "Export" button | Click "Export" button | The exported file is saved via a native dialog (desktop) or browser download. ## HTML, PDF, and quality * **JPG and WEBP** rows have a quality field from 1 to 100 (90 when left alone), saved with the layer. * **PDF** with several layers selected makes one PDF with a page per layer, in the order you selected them, each the size of its layer. * **File › Export Frames to PDF…** saves the page's frames as one PDF, a page per frame in layer order, each the size of its frame. Frames inside sections count; loose shapes, text, and groups do not. With layers selected, only those are exported. * **HTML** writes the layer as a web page. The options button next to the format chooses whether to include the HTML scaffold (a whole page, or a fragment to paste into one), CSS or Tailwind styling, embedded images or separate files (saved together in a `.zip`), and whether layer names (`data-name`, on by default) and layer IDs (`data-pairdraw-node-id`, off by default) are written as attributes. The Code panel's HTML view exports the same way, with the styling it shows. * HTML export carries a layer's blend mode as `mix-blend-mode`, as SVG export already does. Linear dodge maps to `plus-lighter`; linear burn exports flat, because Chrome, Edge, and Firefox do not implement `plus-darker`. Normal and pass-through add no blend mode. * In the Code panel, Vue and React components can take icons from Lucide, Heroicons, or Font Awesome instead of Iconify, and React components also from React Icons; an icon the package lacks stays with Iconify. ## Copy/Paste as In addition to file export, you can copy the selection to the clipboard in multiple formats via the context menu (right-click → Copy/Paste as): | Action | Shortcut (Mac) | Shortcut (Win/Linux) | |--------|----------------|----------------------| | Copy as text | — | — | | Copy as SVG | — | — | | Copy as PNG | ⇧⌘C | Shift + Ctrl + C | | Copy as JSX | — | — | * **Copy as text** — copies visible text content from the selection * **Copy as SVG** — copies the selection as SVG markup (paste into code editors, Inkscape, etc.) * **Copy as PNG** — renders at 2× and copies to the clipboard (ready to paste into Slack, Notion, etc.) * **Copy as JSX** — copies the Pairdraw JSX representation (compatible with `renderJSX()`) ## .fig File Operations Pairdraw uses the .fig format for full documents — the same binary format as Figma. ### Opening Files | Action | Mac | Windows / Linux | |--------|-----|-----------------| | Open file | ⌘O | Ctrl + O | A file picker dialog opens, filtered for `.fig` and `.pen` files. On the desktop app, this uses the native OS dialog. You can also drag a `.fig`, `.pen`, or other supported document onto the window; it opens in a new tab. Images and SVG files dropped on the canvas are placed in the document instead, and any other file reports that it can't be opened. A `.pen` document that imports `.pen` libraries opens with the library components it uses, read from the files it names relative to itself, and a save writes those imports back, so a reopened file links the same libraries. In the document they are read-only library components; change them in the library. A browser can't read files beside a document, so there those components show as dashed placeholders and a message names the libraries; open the file in the desktop app or the CLI to load them. The desktop app reads libraries up to two folders above the document but never from your home folder or above it, and not through links; a file dropped onto the window reads none, so open it with File > Open…. The CLI reads libraries inside the working directory. Script and browser nodes, which Pairdraw doesn't run, also open as placeholders that keep their script file or page address. ### Saving Files | Action | Mac | Windows / Linux | |--------|-----|-----------------| | Save | ⌘S | Ctrl + S | | Save As | ⇧⌘S | Shift + Ctrl + S | * **Save** overwrites the currently open file without a dialog * **Save As** opens a save dialog to choose a new location Saved files are compressed and include a thumbnail image for preview in file browsers. With nothing selected, the **Document** section of the Design panel sets how tightly the document is compressed. **Fast** matches Figma's own saves. **Smaller** and **Smallest** make the file smaller and take longer to save, which is most noticeable on large documents and least on files made mostly of images. The choice is stored in the file, and Figma opens all three. ### Round-trip Compatibility Files exported from Pairdraw can be opened in Figma, and vice versa. The .fig format preserves all node types, properties, fills, strokes, effects, vector data, and layout settings. ## Keyboard Shortcuts | Action | Mac | Windows / Linux | |--------|-----|-----------------| | Export selection as PNG | ⇧⌘E | Shift + Ctrl + E | | Copy as PNG | ⇧⌘C | Shift + Ctrl + C | | Open file | ⌘O | Ctrl + O | | Save | ⌘S | Ctrl + S | | Save As | ⇧⌘S | Shift + Ctrl + S | ## Tips * Use 2× or 3× scale when exporting for high-DPI screens. * JPG always uses a white background — use PNG or WEBP if you need transparency. * Use SVG export when you need a vector format for further editing in Illustrator, Inkscape, or code. * The thumbnail in exported .fig files enables preview in file browsers and Figma's file picker. --- --- url: 'https://pairdraw.dev/user-guide/pairdraw-cloud.md' description: >- Keep documents on your team's own Pairdraw Cloud server, share them, and edit them together. --- # Pairdraw Cloud Pairdraw Cloud keeps documents on a server so they follow you across devices and several people can edit them at once. Pairdraw does not run a Cloud service: use a server your team runs itself ([self-hosting guide](/reference/self-hosting-cloud)), or a hosted one when the build you use names it. Cloud is optional: documents on your device and in your own [storage bucket](./cloud-storage) work the same with or without it. ## Connect a Server Open **Settings → Cloud**. **Your team's server** asks for the address your team uses; only a build that names a hosted server with `VITE_PAIRDRAW_OFFICIAL_CLOUD_URL` offers one there too, and otherwise the app contacts no Cloud server until you add one. Pairdraw checks that the address answers as a Pairdraw Cloud server before asking you to sign in, and says when nothing answers, when the address belongs to something else, or when the server runs a version this app doesn't support. The ways to sign in come from the server: Google, Apple, or email and password. * Email and password work right in the dialog, in the desktop app and in the web app at the server's own editor address. **Create an account** asks for your name, email, and a password of at least 8 characters, twice. The server emails you a link; open it, come back to Pairdraw, and signing in finishes by itself. * Google and Apple, and accounts with two-step sign-in, finish in your browser: in the web app at the server's own editor address you come back to the same tab, and the desktop app shows a code to check against the browser's before you approve it. Servers that review new accounts say so before you sign up. Until an administrator approves you, Settings shows that your account is waiting. Each server in **Settings → Cloud** shows who is signed in to it: * **Sign-in expired** keeps your account, so **Sign in** goes back to the same one. * **Account and security** in the server's **…** menu opens the server's own account pages. See [Your Account](#your-account). * **Sign out** ends the session on the server. If the server can't be reached, you stay signed in so you can try again. At the server's own editor address, signing out of that server goes back to its welcome page, unless the server lets you use its editor without an account and you chose to on this browser. * **Disconnect server** signs you out and forgets the server on this device; your documents stay on it, and you can connect again anytime. It warns you when documents still have changes that haven't reached the server, because disconnecting discards them. The desktop app keeps its sign-in in the system credential store. In the browser, a sign-in through the server's page lasts as long as the server's session; a sign-in with a code follows **Settings → General → Remember API keys on this device**. ## Your Account A server's account pages have three parts: * **Profile** shows your picture, name, and email, and your account ID, which an administrator may ask for. **Upload picture**, beside your picture, takes a PNG, JPEG, WebP, or GIF image; drag and zoom it to choose what shows in the circle, and **Remove**, once you confirm, goes back to your initials. **Change name** opens a dialog for your new name. Signing in with Google uses your Google picture until you upload one. The server keeps every picture itself, so pages never load them from Google or anywhere else. **Change email** sends a link to the new address, and your email changes once you open it. The old address gets a note saying which address is taking over. If you signed in a while ago, the server asks for your password first. * **Sign-in and security** links Google or Apple, changes your password, and sets up two-step sign-in with an authenticator app or passkeys. Recovery codes are shown once: copy or download them before you close the dialog. * **Sessions** lists every browser and desktop app signed in to your account, with when each was last active, and your recent sign-ins. Sign out any session you don't recognize, or all of them except the one you're using. The server emails you when your account is signed in from an address it has never been signed in from, and when an authenticator app or a passkey is added or removed. ## Find Documents on Home The places menu beside Home's tabs lists the workspaces of the server Home shows, **Shared with you**, **New workspace**, and your storage bucket, after **Recent**, **Drafts**, and **Design systems**. With more than one server connected, choose which one Home shows with **Show on Home** in Settings. At the server's own editor address, Pairdraw opens on Home, in your first workspace until you pick another place. A workspace lists its documents with where each one stands, how much of the workspace's storage they use, and your role in it. Every account starts with a workspace of its own. **Design** creates a document in the workspace you are looking at, and says which one; in **Shared with you** it creates in your own workspace, and in Recent, or a workspace you can only view, it creates a file on your device. **Shared with you** lists documents people invited you to in workspaces you are not a member of. ## Work in a Team Workspace Every account starts with a workspace of its own. To work with a team, choose **New workspace** in Home's places menu, name the workspace, and you administer it. **Members** in the workspace's header has three tabs: * **Members** lists who is in the workspace and when each person joined. Admins invite people by email as an admin, editor, or viewer, change roles, and remove people. Editors and admins change documents; viewers only look. * **Invited**, for admins, lists invitations nobody has accepted yet, with who sent each one and when it expires. An invitation arrives by email; if the server doesn't send email, copy the invitation link from the dialog and pass it on. Invitations expire after seven days. **Resend** sends one again with a new link, and the earlier link stops working; so does inviting the same address again. * **Settings** renames the workspace, and holds leaving and deleting it. Anyone can leave a workspace, except its last admin: make someone else an admin first. Admins can delete a workspace once it holds no documents. Deleted documents are kept for a while before they are gone for good, and the workspace can be deleted after that. Opening a workspace invitation works like a document invitation: sign in with the invited address, choose **Join workspace**, and Home shows the workspace. ## Save a Document to Cloud Open or create a document, then choose **File → Save to…**. When there is only one place it can go, it is saved there under its current name; with several workspaces, or a storage bucket too, pick one, and the last place you used is chosen first. Workspaces where you can only view are listed but can't be chosen. The Cloud copy opens in the same tab and saves as you work. A file you had open on your device keeps its last saved contents. Saving can fail when the file is over the size the workspace allows, when the workspace is out of space, or when you are offline. Nothing changes on your device in those cases. ## Where a Document Stands A Cloud document saves as you work, and the tab's dot shows edits that haven't reached the server yet, as it does for any file. When something needs you, a status appears beside the name; select it to see the workspace and server, and what you can do next. | State | What it means | | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | **Saved on this device** | You are offline. Your changes are kept here and upload once you are back online. | | **Changed in two places** | Someone saved a newer version while you had changes the server didn't have. | | **Couldn't save** | The server refused the upload. Your changes are safe on this device; **Try again**, or sign in again if your sign-in expired. | | **View only** | You can look, select, copy, and follow others; the document can't be edited, so only Move and Hand are in the toolbar. | ## When a Document Changed in Two Places This happens when you edited a document offline, or before you joined a session, while someone else saved a newer version. Nothing is lost until you choose. Select the status beside the name, then **Choose a version**: * **Keep both** leaves the newer version as it is and saves yours next to it as "(your copy)"; the tab moves to your copy. * **Use the Cloud version** discards the changes on this device and shows the newer version. * **Replace it with your version** uploads yours over the newer one for everyone. **Decide later** keeps both versions until you come back to it. ## Version History Choose **File → Show version history** to list a document's versions in the left sidebar, newest first, as Figma does. While the list is open the document is read-only. * **Current version** is the document as it is now. Named versions show their title, description, who saved them, and when; autosaves, which the server keeps as you work, are titled by their time. The filter shows everyone's versions or only yours, and hides or shows autosaves. * Select a version to look at it. It opens read-only where the document was, while the document itself stays as it is; select **Current version** or close the list to go back. * **File → Save to version history…** (⌥⌘S), or **+** in the list, names the document as it is now with a title and what changed. * A version's **⋯** menu edits or deletes its info, makes a new document from it with **Duplicate**, or brings it back with **Restore this version**. Restoring keeps the state it replaces in the history, closes the list, and moves everyone who has the document open on to the restored version. * **Copy link** in the same menu copies a link that opens the document with that version shown. People who can only view see the history and can copy links, but can't change it. ## Document Links In the web app, the address bar shows the Cloud document you're looking at, and the version you have open in the history, so you can reload or pass the address on. Opening it signs you in to the document's server if needed, then opens the document for anyone with access to it. A link to a server you have never used only names the server; connect to it in **Settings → Cloud** first. ## Share a Document Select **Share** on a Cloud document. * Invite people by email with **Can edit** or **Can view**. They get an email with a link, and the invitation expires after seven days. Change someone's access or remove it from the list. * Everyone in the document's workspace has the access the workspace gives them. * Under **General access**, **Anyone with the link** lets people open the document with **Can view** or **Can edit**. Where the server allows it, they need no account; otherwise they sign in to the server first, and the dialog says which. Some workspaces' plans turn links off, and the dialog says so too. The server keeps only a fingerprint of each link, so a link can be copied only on the device that created it. On other devices, **Reset link** makes a new one you can copy; the old link stops working. ## Open an Invitation An invitation link opens Pairdraw with who invited you, to which document, and on which server. If you have never used that server, Pairdraw warns you to sign in only if you trust it. Sign in with the address the invitation was sent to; if you are signed in as someone else, choose **Use another account**. Once you accept, the document opens and stays under **Shared with you** on Home. Invitation and share links open in the browser. If you use the desktop app, choose **Open in the desktop app** in the invitation, or on the notice that appears after a shared document opens; your browser asks before it switches to the app. ## Edit Together Editing together needs a Cloud document: Pairdraw has no peer-to-peer rooms for documents on your device. Opening a Cloud document joins its live session: everyone who has it open sees each other's cursors and edits as they happen. One person's app saves the document for everyone, so editing together never makes your changes conflict with someone else's. People who open a link without an account, where the server allows it, join under the name Pairdraw gives them, or the one they chose. They edit when the link allows it, but their app never saves to the server; someone signed in who can edit saves for them. ## AI on Cloud When your server offers AI and your workspace's plan includes it, the AI assistant can use models through Cloud instead of a key of your own. In **Settings → Models**, add a model, choose **Pairdraw Cloud** as the provider, and pick the workspace whose plan pays for it; the models and their prices come from the server. **Pairdraw Cloud** is listed while you are signed in to the server Home shows. Each request uses the workspace's AI credits for the month. When they run out, the assistant says so and, if the server bills, offers **Manage plan**. Self-hosted servers run their own AI service with their own models and limits ([self-hosting guide](/reference/self-hosting-cloud#ai)). --- --- url: 'https://pairdraw.dev/user-guide/cloud-storage.md' description: >- Keep documents and component libraries in your own S3-compatible bucket — AWS S3, Backblaze B2, Cloudflare R2, MinIO, and others. --- # Cloud Storage Pairdraw can keep documents in a bucket you own on any S3-compatible service: AWS S3, Backblaze B2, Cloudflare R2, MinIO, and others. There is no Pairdraw server in between; the editor talks to your bucket directly with your own access keys. ## Connect a Bucket Open **Settings → Storage**, select **S3 storage**, and fill in: | Field | What to enter | | --------------------- | --------------------------------------------------------------------------------- | | **Endpoint** | The provider's S3 API URL, including any required path. See the examples below. | | **Bucket** | The bucket name. | | **Region** | Optional. Left empty, it is read from the endpoint, or `us-east-1` when it can't be. | | **Access key ID** | An access key with read, write, list, and delete access to the bucket. | | **Secret access key** | The key's secret. | Endpoint examples: * AWS S3: `https://s3.eu-west-1.amazonaws.com` * Backblaze B2: `https://s3.eu-central-003.backblazeb2.com` * Cloudflare R2: `https://.r2.cloudflarestorage.com` * MinIO: `http://localhost:9000`, or wherever your server listens Select **Test connection** to check the endpoint, keys, and bucket before saving, then **Save**. Pairdraw addresses objects as `{endpoint}/{bucket}/{key}`, so the bucket name never goes into the endpoint. Access keys are kept in the system credential store in the desktop app. In the browser they are encrypted in browser storage, or kept only until you close the session when **Settings → General → Remember API keys on this device** is off. ## Allow the Web App in CORS The browser can only reach a bucket that allows requests from the page's origin, so the web app needs a CORS rule on the bucket. The desktop app sends its requests natively and needs none. Add a rule like this one, with the origins you open Pairdraw from: ```json [ { "AllowedHeaders": ["*"], "AllowedMethods": ["GET", "PUT", "POST", "DELETE", "HEAD"], "AllowedOrigins": ["https://app.example.com"], "ExposeHeaders": ["ETag", "Content-Range", "x-amz-request-id", "x-amz-id-2", "x-amz-version-id"], "MaxAgeSeconds": 3600 } ] ``` Set it in the AWS console under the bucket's **Permissions → Cross-origin resource sharing**, in the Cloudflare dashboard under the R2 bucket's **Settings → CORS policy**, or with your provider's CLI. When the rule is missing, **Test connection** says the browser could not reach the bucket from the current site. ## Save a Document to Storage Open or create a document, then choose **File → Save to…**. With no Cloud workspace to choose from, the document is saved straight into the bucket; otherwise pick the bucket from the list. The tab stays bound to it: **Save** and auto-save now write to storage instead of a local file. A local `.fig` you had open keeps its last saved contents. To open stored documents, select your bucket in the places menu beside Home's tabs. **Design** with the bucket selected creates a document in it. Home lists every document in the bucket with a preview read from the document itself, so listing a large file downloads only its embedded thumbnail. ## How Saving Works Saving writes the document on this device first and uploads it in the background, so editing never waits for the network. If an upload fails or you are offline, it is retried with increasing delays, and pending work resumes when you reconnect or change storage settings. Each document is uploaded whole. When two devices save the same document, the last upload wins. Documents you have opened stay cached on the device for faster reopening, up to 500 MB. Only copies that are fully uploaded are removed when the cache is full, and they are downloaded again the next time you open them. ## Component Libraries The bucket can also hold component libraries. In **Assets → Manage libraries**, switch the source to **Storage** to publish and enable libraries there instead of on this device. Publishing uses conditional writes, so two people publishing the same library at once can't overwrite each other's revision. See [Components](./components#component-libraries) for publishing and updating libraries. ## What's in the Bucket Pairdraw writes only under two prefixes and leaves everything else in the bucket alone: * `pairdraw_storage/canvases/` — each document as `.fig`, with its name and modification time in `.meta.json`. * `pairdraw/libraries/` — each library's `manifest.json` and its published revisions. ## Provider Notes * **Cloudflare R2** needs the exact web app origin in its CORS rule; it does not accept wildcard origins such as `https://*.example.com`. * **MinIO** answers CORS requests from any origin unless you configure otherwise. * **`rclone serve s3`** works with two limits. It rejects CORS preflight requests, so the web app needs a reverse proxy in front of it that answers them; the desktop app does not. It also ignores conditional writes, so concurrent library publishes are not detected. --- --- url: 'https://pairdraw.dev/user-guide/auto-layout.md' description: >- Flex and grid layout in Pairdraw — direction, gap, padding, alignment, child sizing, and CSS Grid tracks. --- # Auto Layout Auto layout positions children automatically within a frame. It supports two modes: **flex** (horizontal/vertical flow) and **grid** (rows and columns with track sizing). ## Enabling Auto Layout * Select a frame and press ⇧A (Shift + A) to toggle auto layout on or off * Select loose nodes (without a parent frame) and press ⇧A to wrap them in a new auto-layout frame When wrapping a selection, nodes are sorted by visual position: left-to-right for horizontal layout, top-to-bottom for vertical. ## Layout Direction Choose how children are arranged: * **Horizontal** — children flow left to right * **Vertical** — children flow top to bottom * **Wrap** — children wrap to the next row/column when they run out of space ## Spacing ### Gap The space between adjacent children. Set a single value that applies between all children. ### Padding The space between the frame edge and its children. Set a uniform value for all sides, or expand to set each side independently (top, right, bottom, left). ## Alignment ### Justify (main axis) Controls how children are distributed along the layout direction: * **Start** — children pack to the beginning * **Center** — children are centered * **End** — children pack to the end * **Space between** — children spread with equal space between them * **Space around** — each child gets an equal share of the free space, half on each side, on top of the gap; choose it from the gap field's menu ### Align (cross axis) Controls how children are positioned perpendicular to the layout direction: * **Start** — children align to the start * **Center** — children are centered * **End** — children align to the end * **Stretch** — children stretch to fill the cross axis ## Child Sizing Each child in an auto-layout frame can have its own sizing mode: * **Fixed** — uses the child's explicit width/height * **Fill** — stretches to fill available space in the parent * **Hug** — shrinks to fit the child's content ## Include Strokes in Layout By default an auto layout frame lays its content out as if no layer had a stroke, as Figma does. Turn on **Include strokes in layout** in the Layout section to make room for strokes: the frame's own stroke pushes its content inward, and the outside strokes of its children take up space between them. A fixed auto-layout frame is never smaller than the room its padding takes, plus the inside strokes it counts when **Include strokes in layout** is on. Setting it smaller grows it to that room, as Figma does. A frame saved smaller than its padding before this change keeps its saved size when the file opens, and grows to its padding on the next edit. ## Drag Reordering Within an auto-layout frame, drag a child to reorder it among its siblings. A visual insertion indicator shows where the child will be dropped. Dragging a node from elsewhere into an auto-layout frame inserts it the same way; in a wrapping frame, it goes into the line under the cursor. Drawing inside an auto-layout frame adds the new node to the end of its flow. Hold ⌃ (Ctrl on Windows and Linux) while dragging to ignore auto layout: the node is dropped where you release it as an absolute-positioned child. ## Properties Panel When an auto-layout frame is selected, the Layout section in the properties panel shows all auto-layout controls: direction, gap, padding, justify, and align. ## On-canvas Handles Select a single flex frame and the canvas shows its padding and gap handles, as Figma does. Hover a padding area or the space between two children to tint it pink; double-click a tinted value to edit it. * Drag a padding area to change that side. Hold ⇧ (Shift) to move the value by the large nudge in Settings → Editor. Hold ⌥ (Alt) to change the opposite side on the same axis, or ⌥⇧ (Alt + Shift) to change all four. * Drag the gap between children to change **Item spacing**. With **Wrap** on, the space between wrapped lines edits **Counter axis spacing**. * Hold ⇧ while dragging a gap to move it by the same large nudge. * Handles hide when a value is zero, when the gap is **Space between**, and on generated frames. An instance can edit its own padding and spacing, recorded as an instance override. A drag previews on the canvas and commits as one undo step. ## Keyboard Shortcuts | Action | Mac | Windows / Linux | | ------------------ | ------------------------ | ------------------------------- | | Toggle auto layout | ⇧A | Shift + A | ## CSS Grid Grid layout arranges children in rows and columns with explicit track sizing. ### Enabling Grid Select a frame with auto layout enabled and click the grid icon in the layout toolbar to switch from flex to grid. ### Track Sizing Define column and row tracks with three sizing modes: * **fr** — fractional unit, divides available space proportionally * **px** — fixed pixel size * **auto** — sizes to fit content Example: three columns of `1fr 200px 1fr` creates a layout with a fixed center column and flexible sides. Set a grid frame to **Hug** to size it to its tracks and gaps. On a hugged axis a fractional (`fr`) track takes its content's size instead of sharing space, and the frame's minimum and maximum still apply. ### Grid Gaps Set separate horizontal (column) and vertical (row) gaps between cells. ### Child Positioning Children are placed into grid cells automatically in row order. You can override placement with column/row start and span values in the child's layout properties. ### JSX and Tailwind Export Grid layouts export to JSX with Tailwind classes: `grid grid-cols-3`, `gap-x-4 gap-y-2`, `col-start-2 row-span-2`. ## Tips * Auto layout recomputes immediately after creation, so the selection bounds update right away. * Nest auto-layout frames for complex responsive layouts (e.g., a vertical frame containing horizontal rows). * Use "Fill" sizing to make a child take up remaining space, like a flex-grow: 1 in CSS. * Use grid for dashboard layouts, galleries, and forms — anything with a two-dimensional structure. * See [Drawing Shapes](./drawing-shapes) for creating the frames that auto layout applies to. * See [Components](./components) for using auto layout within reusable components. --- --- url: 'https://pairdraw.dev/user-guide/components.md' description: >- Creating reusable components, instances, component sets, overrides, and live sync in Pairdraw. --- # Components Components are reusable design elements. Edit the main component and all its instances update automatically. ## Browse Components Open the **Assets** tab in the left panel to browse local components and enabled libraries. Use grid or list view, search by component name, and select a component to see its details. You can insert an asset by clicking it, pressing Enter, or dragging it onto the canvas. Local assets are grouped by source page. Published library assets remain available when their revision has been downloaded, including when the remote provider is temporarily offline. ## Creating a Component Select a frame or group and press ⌥⌘K (Ctrl + Alt + K). The selection becomes a reusable component. Any other layer, or several layers, is wrapped in a new white component at their bounding box, in the topmost layer's place in the layer list; a single wrapped layer gives the component its name. Components display a purple label with a diamond icon above them. ## Component Sets and Variants Select two or more components and choose **Create component set** from the context menu to combine them into a component set — a container with a dashed purple border and 20 px padding around its children, as in Figma. Sets made by scripts with `figma.combineAsVariants()` wrap their components exactly, as Figma's plugin API does. Each component in a set can define values across multiple variant dimensions, such as `Size=Small`, `State=Hover`, and `Theme=Dark`. Pairdraw supports sparse combinations, so a set does not need every possible combination. The top-left variant is the default and is used as the fallback when an update no longer contains an exact combination. Select a component and press **Add variant** in the panel header to turn it into a component set, as Figma does: the component becomes `Property 1=Default` and a copy named `Property 1=Variant2` appears below it. On a set, **Add variant** copies its last variant with the next value. The set's variant properties are rows of its **Properties** list; click one to rename it or to add, rename, drag to reorder, or remove its values. Removing a value variants still use moves them to another value first, and variants that share every value are named in a notice that selects them. ## Component Properties Components and component sets support reusable text, boolean visibility, instance-swap, and slot properties. Select an instance to edit its values without detaching it. Properties and their values are preserved when saving and reopening `.fig` files. To link a layer of a main component to a property, use the link button where its field lives: **Typography** for text content, **Appearance** for visibility, and the instance header for the swapped component. Create a property from the layer's current value or pick an existing one; the field then shows the property instead of its value. Typing into linked text sets the property — its default in the main component, the instance's value in an instance. Select the main component to see its **Properties**. Click a property to rename it, change its default, see and unlink the layers it drives, or delete it, and drag properties to reorder them. **+** adds a text, boolean, or instance-swap property. To show a nested instance's properties on instances of the component, choose **+ → Nested instances** and tick it, as Figma's **Expose properties from nested instances** does. Instances of the component then list its properties under its name. Only an instance whose component has properties can be exposed. ## Slots A slot is a frame of a main component whose content each instance can change. Select a frame inside a main component and choose **Create slot** from the context menu or the Slots section, or select other layers to wrap them in a new slot frame. Slot settings set a description, the components it prefers, and how many items it holds; an instance outside those limits shows a warning. In an instance, add, reorder, and remove a slot's items, or reset it to the component's content. ## Behaviours and Preview A behaviour makes a main component or component set work like a real control, after [Reka UI](https://reka-ui.com)'s primitives: Button, Text field, Textarea, Number field, Toggle, Switch, Checkbox, Radio, Radio group, Toggle group, Slider, Progress, Tabs, Collapsible, or Accordion. Select the component and use **+** in the **Behaviour** section to choose one. The section lists what the control needs: * **Values** — the property that holds each value: a variant or boolean property for On, Checked, Pressed, Open, Filled, or Disabled (with the variant values that mean on and off), a text property for a field's text, or a slider's own minimum, maximum, step, and default. * **Parts** — the slot that draws each part, such as a switch's thumb, a slider's track, range, and thumb, or a tab list. A group's items slot holds instances of its radios, toggles, or collapsibles. * **States** — a variant property whose values draw default, hover, pressed, focus, and disabled. Values named like those states are matched automatically. Rows the control requires come first; the rest are under **More options**. When a component has nothing to bind yet, a row offers to create it: a text layer and text property, Off and On variants, or a slot, and **States** offers **Add state variants**, which adds a Default, Hover, Pressed, Focus, and Disabled variant of the component. A lone main component that gets variants this way becomes a component set, and a slot added to a set appears in every variant. Until the control works, a line under its name says what is still needed; clicking it goes there. Press ⌥⌘↩ (Ctrl + Alt + Enter), choose **View → Preview**, or use the ▶ Preview button in the top bar to preview the canvas. Each top-level layer holding controls runs as live Reka UI components over the canvas, drawn by the component's variants: switches flip, sliders drag, tabs and accordions open, and text fields are real inputs with the browser's caret, selection, and paste. Preview never changes the document or its history. **Reset** puts every control back as designed, and Esc or the pill's close button returns to editing. In split view, each canvas previews on its own. Behaviours are saved in `.fig` files and published with library components. ## Component Libraries A component library publishes reusable components as an immutable revision. Each published asset has stable library, asset, and revision identity, so different instances can remain on different revisions until you explicitly update them. **Pairdraw Basics** is the built-in original set: button, input, badge, card, and avatar components, published as `pairdraw-basics`. It is in the Assets panel without a catalog: enable it there to insert its components, including offline, and it stays after a reload. `pairdraw libraries seed --root ./catalog` still publishes that same set into a filesystem catalog. ### Publish a Library 1. Create the components and component sets you want to share. 2. Open **Assets**, then select **Manage libraries**. 3. Select **Publish library**. 4. Enter a stable library ID and display name. The library ID is locked after the first publication. 5. Optionally search the change list and enter a revision description. 6. Select the added, modified, renamed, or removed assets to include. 7. Confirm the destination and select **Publish library**. On later publications, unchecked changes remain pending. Unchanged assets keep their previous published definitions, and removed definitions remain available while documents still reference their historical revision. ### Enable and Insert Library Assets Open **Assets → Manage libraries** to enable a published library. Its components appear in the Assets panel alongside local components. Insert one by clicking it, using the keyboard, or dragging it onto the canvas. Published definitions are read-only in consuming documents. Edit the source document and publish another revision to change a definition. Instances linked to those definitions remain editable through their component properties and overrides. ### Review and Accept Updates Open **Manage libraries → Updates** to discover newer revisions. Discovery does not modify the document. You can review the current and updated instance side by side, navigate between affected instances, and then update: * The selected instance * All instances of one asset * Instances on the current page * Instances across all pages Pairdraw preserves compatible text, visibility, and instance-swap assignments. If an exact variant no longer exists, the review identifies the top-left fallback before you accept it. Applying an update creates an undo entry. ### Local, Storage, and Offline Use Libraries can use the local browser catalog or a configured storage provider. Remote publication uses immutable revision objects and a conditional latest pointer, preventing two publishers from silently overwriting each other. Downloaded revisions are cached locally. A document can continue rendering and inserting downloaded definitions while offline. Integrity failures are reported instead of being hidden by cached data. ### Saving Consumer Documents Enabled-library bindings and materialized definitions are saved with `.fig` documents. Reopening a consumer file preserves its linked instances and revision identities, even when its remote library is unavailable. ## Creating Instances Right-click a component and select **Create instance** from the context menu. The instance appears 40 px to the right of the source component, visually identical. Instance creation is available only through the context menu — there's no toolbar button. ## Detaching an Instance Select an instance and press ⌥⌘B (Ctrl + Alt + B) to detach it. The instance becomes a regular frame with no link to the original component. All overrides are baked in. ## Convert to Frame Select a main component and press ⌥⌘K (Ctrl + Alt + K), the Create component keys, or choose **Convert to frame** from its context menu, the layer type menu, or **Object › Convert to Frame**, to turn it back into a frame. When the component has instances, a confirmation says how many; converting detaches every instance into a frame that keeps its look, including copies nested in other components' instances. The whole change is one undo step. ## Go to Main Component Right-click an instance and select **Go to main component**. The editor navigates to and selects the main component, switching pages if needed. ## Live Sync When you edit a component, all its instances update automatically, as in Figma: every property an instance does not override follows the component. That covers size, fills, strokes and their weight, alignment, caps, joins, and dashes, effects, opacity, blend mode, corner radii and smoothing, layout settings and grids, clipping, shared styles, and text, from its font and size to letter spacing, line height, case, decoration, alignment, and styled ranges. A layer inside an instance also takes its position, rotation, flips, constraints, and mask from the component. Move or rotate a layer in the component and it moves in every instance. When an instance has a different size than its component, the layer is placed by its constraints, so a layer pinned to the right keeps its distance from the right edge. Inside auto layout, the layout places it. Sync triggers automatically after node updates, moves, and resizes within a component. ## Overrides Instances can override specific properties without breaking the sync link. When a property is overridden on an instance, that property is skipped during sync — other properties continue to update from the main component. ### Overridable Properties A layer inside an instance can override its name, text, styled ranges, and font, every visual and text property listed above, its size, and whether it is visible or locked. Its position, rotation, flips, constraints, and mask cannot be overridden: they always come from the component. Scripts that set its position, rotation, constraints, or mask get Figma's error. Slot content is the instance's own and stays editable. Overrides in a `.fig` file come back as overrides when you open it, and are saved the way Figma writes them. ### Pushing Changes to the Main Component Select an instance, then choose **Push changes to main component** from its header, its context menu, or **Object › Push Changes to Main Component**. The instance's overrides move to the main component, every other instance follows, and this instance stops overriding those fields. Another instance that overrides the same field keeps its value. One undo step restores the main component and every instance. A nested instance's changes move to its own main component, and the enclosing component picks them up through sync. An instance of a library component cannot push changes: the published main component is read-only, so edit the source library instead. ### New Children When you add a child to a component, all existing instances gain a cloned copy automatically. Child order in instances always matches the component. ### Variable Modes An instance, or a layer inside one, that sets the mode of one variable collection keeps that mode and still takes the component's modes for every other collection. Change the main component's density mode and an instance that only switched its theme follows the new density. ### Swapping an Instance Select an instance, a nested one included, and click the swap button in its header to show another component in its place. The list holds every component in the document; one that would contain itself is disabled. A swapped nested instance stays swapped when its enclosing component changes. When the swap is linked to an instance-swap property, the header shows the property instead. ### Replacing a Layer Inside an Instance Copy a layer, select a layer inside an instance, and press ⌥⇧R (Alt + Shift + R) or choose **Replace inside instance** from the Edit or context menu. The copied layer takes the place and position of the selected one as an override of the instance, without detaching it: the rest of the instance keeps following its component, and the replacement stays when the component changes, until the component deletes the layer it replaced. With several layers selected, each gets its own copy. With nothing inside an instance selected, the keys paste to replace. Select the replacement and click **Restore component layer** in its header to bring the component's layer back. Replacements are saved in `.fig` files as Pairdraw plugin data on the instance; Figma shows the component's layer instead. ## Hit Testing Components and instances are opaque containers — clicking on a child selects the component itself, not the child. **Double-click** to enter the component and select children inside it. ## Visual Treatment | Element | Appearance | |---------|------------| | Component label | Purple with diamond icon, always visible | | Instance label | Purple with diamond icon, always visible | | Component set border | Dashed purple outline | ## Keyboard Shortcuts | Action | Mac | Windows / Linux | |--------|-----|-----------------| | Create component | ⌥⌘K | Ctrl + Alt + K | | Detach instance | ⌥⌘B | Ctrl + Alt + B | | Preview | ⌥⌘↩ | Ctrl + Alt + Enter | ## Tips * Editing text inside an instance creates an override — the text won't be overwritten when the component changes. * Use component sets to organize multidimensional variants such as size, state, and theme. * Publish reusable assets from their source document; published definitions are intentionally read-only in consumer documents. * Review updates before accepting them when a revision removes an exact variant combination. * See [Context Menu](./context-menu) for all component-related actions. --- --- url: 'https://pairdraw.dev/user-guide/variables.md' description: 'Design variables, collections, modes, and fill bindings in Pairdraw.' --- # Variables Variables store reusable design tokens — colors, spacing values, and other properties — that can be bound to nodes. Change a variable's value and every node using it updates. ## Opening the Variables Dialog Open it from **View → Variables…**, by searching "Variables" in the command palette, or, with no nodes selected, from the Variables section of the Design tab. **Expand** in the dialog's corner gives it most of the window. The dialog lists the active collection's variables on the left, edits the selected variable or the collection on the right, and shows the stylesheet they produce below. In a narrow window or on a phone it shows one mode at a time, and a variable, the collection settings, or the stylesheet opens over the list with a back button. ## Collections Variables are organized into collections. In a wide dialog they are listed in a sidebar with how many variables each holds; narrower, they are tabs, or a menu on a phone. * **Switch collection** — click it in the sidebar or its tab * **Create collection** — click **+** next to Collections, or the folder button in the toolbar * **Rename or delete** — with no variable selected, the right side edits the collection: change its name, or delete it from the **⋯** menu next to the name * **Switch attribute** — the attribute that turns manually switched modes on, `data-theme` by default for a collection named Theme; type another name, such as `data-color-scheme`, to match an existing codebase ## Modes Each collection can have multiple modes (e.g., Light and Dark). Modes appear as value columns in the list, and a variable has a value for each mode. Manage them in the collection settings: * **Add mode** — click **+** next to Modes * **Rename** — edit the mode's name * **Duplicate, set as default, delete** — use the **⋯** menu next to the mode The default mode is **Always on** and goes in `:root`. Every other mode has **Applies when**, which says when the mode takes over in the exported stylesheet; the CSS it writes is shown underneath: | Applies when | CSS | | --- | --- | | **Switched manually** | the collection's switch attribute set to the mode, such as `[data-theme="dark"]` for a Theme collection's Dark mode | | **System is in dark mode** / **System is in light mode** | `@media (prefers-color-scheme: dark)` / `light` | | **High contrast is on** | `@media (prefers-contrast: more)` | | **Reduced motion is on** | `@media (prefers-reduced-motion: reduce)` | | **Screen is narrower than** / **Screen is wider than** a width | `@media (max-width: 640px)` / `min-width` | | **Container is narrower than** / **Container is wider than** a width | `@container (max-width: 640px)` / `min-width` | | **Custom CSS** | any selector, or a `@media`, `@supports`, or `@container` query | On the canvas, a layer shows a mode when you set the layer to it, whatever the condition. In exported code, a manually switched mode is turned on by adding its attribute to an element, so layers set to it export with that attribute. Layers set to a mode with any other condition, custom selectors included, export with literal values instead of tokens, because the stylesheet, not the layer, decides when that mode applies. ## Managing Variables ### Formula values A number variable's value field takes a number, another variable, or a formula. Start typing a variable's name and pick it from the list, or choose **Use a variable**: it appears as a pill, and the field shows what the formula gives, such as `= 16px`. Pills are stored by ID, so renaming a variable keeps the formula working. True/false, text and color variables keep their switch, text field or color picker; choose **Use a formula** beside one to write a formula instead. * Numbers use `+`, `-`, `*`, `/` and parentheses: `space/base * 4`. * True/false values use `and`, `or` and `not`, and compare numbers with `==`, `!=`, `<`, `<=`, `>` and `>=`: `viewport > 1024 and not loading`. `==` and `!=` also compare text. * Text is written in double quotes, and `+` joins it with other text, a number or a true/false value: `"Hello, " + name`. `text(count)` writes a number as Figma does, with two decimals unless it is whole: `3`, `1.50`. * `if(condition, then, otherwise)` picks between two numbers, texts, true/false values or colors: `if(compact, 8, 16)`, `if(dark, gray/900, #FFFFFF)`. Colors are written as `#RRGGBB`, or `#RRGGBBAA` with opacity. * `truthy(value)` is false for `0`, empty text, and the words `false`, `no` and `off`, and true for anything else, as Figma reads them. * Unknown variables, circular references, mixed types and division by zero are reported when you leave the field, and the saved value stays as it was. The result follows each layer's variable modes and updates bound layers when a variable it uses changes. Formulas use stored units, so lengths are in pixels. The list shows each formula's result; hover the formula icon to read the formula. In the stylesheet, a number formula is written as `calc()` over the variables it uses, such as `calc(var(--spacing-md) * 2 - var(--spacing-base))`, and is declared again in each mode that changes one of them. Formulas that use `if()`, text or true/false values have no CSS form and are left out of the stylesheet. A **CSS expression** replaces the value in CSS alone. Design token files hold each formula's result, with the formula under `$extensions`. Formulas survive copy and paste, sharing, undo and `.fig` saves, and Figma color and opacity expressions keep their variable references. Variables are grouped by the folders in their names (`Brand/Primary` appears as *Primary* under *Brand*), with their CSS name and one value per mode. * **Create variable** — click **Create variable** (or **+**) and pick a type; the new variable opens for editing * **Select** — click a row, or move with the arrow keys and press Enter. Shift-click selects a range, and Cmd-click (Ctrl-click on Windows and Linux) adds or removes one * **Filter** — type in the search bar to filter by name, CSS name, description, or value, such as `--color-brand`, a hex color, or the variable an alias points at, forgiving typos as the command palette does; click a group in the sidebar to show only that group and the groups inside it, or use the filter button to show only some types * **Rename or edit in place** — double-click a name, or a number or text value, in the list * **Right-click** — rename, duplicate, move to a group (or a new one), or delete the selected variables; Delete or Backspace deletes them too * **Reorder** — drag a row; the order is kept in the file * **Several selected** — the right side moves them into a group, duplicates them, or deletes them * **Undo and redo** — Cmd+Z and Cmd+Shift+Z or Cmd+Y (Ctrl on Windows and Linux) work in the dialog as on the canvas, one step per change. Enter commits a field and returns to the list; while a field has text you have not committed, Cmd+Z undoes the typing Selecting a variable edits: * **Name** and **CSS name** — leave the CSS name empty to derive it from the name and scopes, such as `--color-brand-primary`. Type the name without its `--`; a name CSS cannot use is flagged and not saved * **Unit** — for numbers, `px`, `rem`, `%`, `ms`, `s`, `deg`, or none; values are entered in that unit * **Value** (or **Values**, one per mode) — a color opens the color picker. The variable button next to a value points it at another variable of the same type, an alias that follows that variable; **Detach variable** turns it back into the value it showed * **CSS expression** — for numbers, choose **Add CSS expression** in a value's **⋯** menu to write CSS such as `clamp(1rem, 4vw, var(--spacing-md))` instead of the value, while the canvas keeps drawing the value. Token names complete as `var(--name)` and show as pills, the variable button inserts one, and an unclosed function, an unknown token or a value the token's unit does not take is reported when you leave the field. The expression stays when the value changes between a number, a variable and a formula; remove it from the same menu * **Scopes** — which properties the variable is offered for * **Description** * **Hide from publishing** — files that use this one as a library do not see the variable ## Stylesheet The bottom of the dialog shows the active collection as CSS custom properties. The copy button copies the whole document's variables as CSS or as a Tailwind v4 theme, so aliases to other collections resolve. ## Importing and Exporting Design Tokens Variables and styles move between Pairdraw, Figma, and code as [W3C design tokens](https://www.designtokens.org/): * **Export:** in the stylesheet's copy menu, choose **Export as design tokens**. The zip holds one file per collection mode, which Figma imports as a mode; text and effect styles as typography and shadow tokens; and a resolver that combines them for tools such as Style Dictionary * **Import:** click **Import design tokens** in the toolbar and pick token files or a zip. Files from Figma, a resolver with the files it names, and Tokens Studio themes all work * **Choose where it goes:** before anything changes, the dialog shows each collection and mode it found and where it goes: a new collection or mode, an existing one, or nowhere. Variables and styles with the same name are updated and the rest is added; nothing is deleted. It counts what will be added, updated, and skipped, and lists why each skipped token was left out * The import is one step: **Undo** takes it all back * **Command line:** `pairdraw tokens app.fig --import theme.css --write` imports a local stylesheet's custom properties without opening the app; `:root` holds default values and other selectors become modes * **Project folder:** `pairdraw tokens app.fig --project ./app --write` imports CSS variables from a local project folder, including a Tailwind v4 `@theme` and a shadcn/ui `:root` / `.dark` pair as Light and Dark modes. JavaScript config such as `tailwind.config.js` is reported and not run ## Syncing With a Stylesheet Custom properties in a CSS file become variables, and variables go back into it. Click the **Sync with CSS** button in the variables toolbar: * **Import CSS variables…** reads a `.css` file. `:root`, `html` and Tailwind's `@theme` hold each collection's default values; `[data-theme="dark"]`, a class such as `.dark`, and `:root` blocks inside `@media`, `@supports` or `@container` become modes with that condition. Colors, lengths in `px` or `rem`, durations, numbers, quoted text and font lists become variables, `var(--name)` becomes an alias, and `calc()` or `clamp()` keeps its CSS as a CSS expression. The same import dialog shows where each collection and mode goes before anything changes * **Pull from** reads the linked file again and shows what changed. A stylesheet exported from the document maps back onto the same variables and modes * **Push to** writes the variables into the linked file in place: changed values are rewritten in their own notation, missing ones are added to their block, and comments, other rules and properties without a variable stay as they are. Nothing is removed. Where the browser cannot write the file, a copy is saved instead * **Pull when the file changes** imports every save of the linked file, on desktop and in browsers that grant file access, as one undo step each ## Pasting Between Documents Layers copied in one open document and pasted into another can bring the variables and styles they use. Before anything is pasted, a dialog asks how: * **Yes, import** — adds the variables and styles, so the pasted layers stay linked to them * **Paste as is** — pastes the layers with the values they showed, linked to no variable or style * **Use existing** or **Add renamed** — when this document already has a collection or style with the same name, choose per row: use the one here, where variables match by name and missing ones are added to it, or add the copy under a new name such as "Spacing 2" The paste is one step: **Undo** removes the layers and everything it added. **Paste properties** uses same-named collections and styles the same way. ## Binding Variables to Fills In the Fill section of the properties panel, use the variable picker to bind a color variable to a node's fill. * **Bind** — select a color variable from the picker. The fill shows a purple badge with the variable name. * **Detach** — click the detach button on the badge to remove the binding. The fill reverts to the resolved color value. When the variable's value changes (or when switching modes), all bound fills update automatically. ## Tips * Use collections to group related tokens (e.g., "Primitives" for raw colors, "Semantic" for role-based aliases, "Spacing" for layout values). * Modes are useful for theme switching — define Light and Dark mode values in the same collection. * Variables support aliases — a "Semantic" collection can reference values from a "Primitives" collection. * See [Drawing Shapes](./drawing-shapes) for how fills and the color picker work. --- --- url: 'https://pairdraw.dev/user-guide/design-system.md' description: >- A step-by-step tutorial that builds a themed Button and Card library with variables, variants, component properties, and slots. --- # Building a Design System This tutorial builds a small design system from scratch: color and size tokens with a light and a dark theme, a **Button** with two variants, and a **Card** whose content and actions are slots. Every step uses features described in more detail in [Variables](./variables), [Auto Layout](./auto-layout), and [Components](./components). [Download the finished file](/examples/design-system.fig){download} to compare with your own, or to start from it. It has two pages: **Components** holds the main components, and **Examples** shows the same cards in the Light and Dark modes. ## 1. Define the tokens Tokens are variables that every component reads, so a theme change happens in one place. 1. Open **View → Variables…**. 2. Click **+** next to **Collections** and name the collection `Theme`. Rename its first mode to `Light`, then click **+** next to **Modes** and name the new mode `Dark`. 3. Click **Create variable**, choose **Color**, and add these variables with a value for each mode. A slash in a name groups variables, so `color/primary` appears as *primary* under *color*. | Variable | Light | Dark | | --- | --- | --- | | `color/background` | `#F4F5F7` | `#0F1115` | | `color/surface` | `#FFFFFF` | `#1A1D23` | | `color/border` | `#E1E4EA` | `#2D323B` | | `color/text` | `#191C21` | `#F1F3F6` | | `color/text-muted` | `#5A616E` | `#A2A9B5` | | `color/primary` | `#3451D1` | `#8098F7` | | `color/on-primary` | `#FFFFFF` | `#0D1222` | | `color/secondary` | `#E9ECF2` | `#272B33` | 4. Create a second collection named `Size` with **Number** variables: `radius/control` = 8, `radius/card` = 12, `space/sm` = 8, `space/md` = 16, and `space/lg` = 24. Sizes do not change with the theme, so this collection keeps a single mode. The stylesheet under the list already shows the result: the Light values in `:root` and the Dark values under `[data-theme="dark"]`. ## 2. Build the Button 1. Rename the page `Components`. Draw a frame, press ⇧A to give it auto layout, and set both axes to **Hug**. 2. Add a text layer that reads `Button`, in Inter Medium at 14 px, and name it `Label`. 3. Bind the tokens. In **Fill**, use **Apply variable** to bind the frame's fill to `color/primary` and the text's fill to `color/on-primary`. Number fields take variables the same way: bind the corner radius to `radius/control` and the left and right padding to `space/md`, and set the top and bottom padding to 10. 4. Press ⌥⌘K (Ctrl + Alt + K) to make it a component. 5. Double-click into the component and select the Label layer. Next to its text in **Typography**, use **Apply variable/property → Create property…** to create a text property named `Label`. Instances now set their label without detaching. 6. Select the component and click **Add variant** in the panel header. The component becomes a set with two variants. In **Properties**, rename the variant property to `Variant` and its values to `Primary` and `Secondary`, then name the set `Button`. 7. In the Secondary variant, bind the fill to `color/secondary` and the label's fill to `color/text`. 8. Select the set and, in **Behaviour**, click **+** and choose **Button**. Preview (⌥⌘↩ / Ctrl + Alt + Enter) now runs it as a real button. ## 3. Build the Card 1. Draw a frame 320 px wide, give it vertical auto layout, and set its height to **Hug**. Bind its padding to `space/lg`, its gap to `space/md`, its corner radius to `radius/card`, its fill to `color/surface`, and a 1 px stroke to `color/border`. 2. Add a text layer that reads `Card title`, in Inter Semi Bold at 18 px, and name it `Title`. Bind its fill to `color/text` and set its width to **Fill**. 3. Below it, add a frame named `Content` with vertical auto layout, no fill, **Fill** width, and **Hug** height. Put a text layer in it, such as `Slots hold content that each card chooses for itself.`, in Inter Regular at 14 px, bound to `color/text-muted`, and name it `Body`. 4. Add a frame named `Actions` with horizontal auto layout and a gap bound to `space/sm`. From **Assets**, drag a Button into it. 5. Select the outer frame and make it a component named `Card`. Link the title to a text property named `Title`, as you did for the button's label. 6. Select the `Content` frame and choose **Create slot** from the context menu or the **Slots** section. Do the same for `Actions`. Each instance can now replace what these frames hold, and the main component's content becomes the default. Slot settings can describe a slot, limit how many layers it holds, and name preferred components; for example, `Actions` could prefer `Button` and hold at most 2 layers. ## 4. Use the components 1. Add a page named `Examples` and draw a frame named `Light` with vertical auto layout, padding and gap bound to `space/lg`, and a fill bound to `color/background`. 2. Place two Card instances in it: right-click the Card and choose **Create instance**, or drag it from **Assets**. Set their **Title** properties to `Welcome back` and `Pro plan`. 3. In the second card, select the button in the `Actions` slot and delete it, then paste or drag in two Button instances: a Secondary one with the label `Not now` and a Primary one with `Upgrade`. Edit the text in its `Content` slot. Slot content belongs to the instance, so it stays when the Card changes; **Reset slot** in the slot's menu brings back the component's content. 4. Duplicate the `Light` frame and name the copy `Dark`. In **Appearance**, use **Apply variable mode** to set the `Theme` collection to `Dark`. Every bound color in the frame switches, while the cards stay linked to their components. Now edit a token or a main component, for example `radius/card` or the Button's padding, and watch both frames update. ## 5. Take it further * **Publish it as a library.** Open **Assets → Manage libraries → Publish library** so other files can use the Button and Card, and accept updates when you change them ([Component Libraries](./components#component-libraries)). * **Hand the tokens to code.** `pairdraw tokens design-system.fig` prints the variables as CSS custom properties, `--format tailwind` as a Tailwind v4 theme, and `--format dtcg --out tokens/` as W3C design token files. HTML export writes the bound values as `var()` references to the same properties ([Exporting](./exporting)). * **Check it.** [Checking Designs](/user-guide/checking-designs) and `pairdraw lint design-system.fig --fix -o fixed.fig` find colors that match a token but are not bound to it, and bind them. * **Track changes.** Keep the file in Git and review changes with [`pairdraw diff files`](/programmable/cli/git). ## Build the example with a script The example file is generated by this script, which uses the same [Figma-compatible plugin API](/programmable/cli/scripting) as `pairdraw eval`. Run it to build the file yourself, or change it to try your own tokens: ```sh echo '{"children":[]}' > empty.pen pairdraw eval empty.pen --stdin -o design-system.fig < design-system.js ``` ```js // Builds design-system.fig, the example file of the design system tutorial. // Start from an empty document and write the result to a new file: // echo '{"children":[]}' > empty.pen // pairdraw eval empty.pen --stdin -o design-system.fig < design-system.js await figma.loadFontAsync({ family: 'Inter', style: 'Regular' }) await figma.loadFontAsync({ family: 'Inter', style: 'Medium' }) await figma.loadFontAsync({ family: 'Inter', style: 'Semi Bold' }) // 1. Tokens: a Theme collection with Light and Dark modes, and a Size collection. // A new .pen document comes with an empty Theme collection; start from none. for (const collection of figma.variables.getLocalVariableCollections()) { if (collection.variableIds.length === 0) collection.remove() } const theme = figma.variables.createVariableCollection('Theme') const light = theme.modes[0].modeId theme.renameMode(light, 'Light') const dark = theme.addMode('Dark') function hex(value) { const n = Number.parseInt(value.slice(1), 16) return { r: ((n >> 16) & 255) / 255, g: ((n >> 8) & 255) / 255, b: (n & 255) / 255, a: 1 } } const colors = {} for (const [name, lightValue, darkValue] of [ ['color/background', '#F4F5F7', '#0F1115'], ['color/surface', '#FFFFFF', '#1A1D23'], ['color/border', '#E1E4EA', '#2D323B'], ['color/text', '#191C21', '#F1F3F6'], ['color/text-muted', '#5A616E', '#A2A9B5'], ['color/primary', '#3451D1', '#8098F7'], ['color/on-primary', '#FFFFFF', '#0D1222'], ['color/secondary', '#E9ECF2', '#272B33'] ]) { const variable = figma.variables.createVariable(name, theme, 'COLOR') variable.setValueForMode(light, hex(lightValue)) variable.setValueForMode(dark, hex(darkValue)) colors[name] = variable } const size = figma.variables.createVariableCollection('Size') const sizes = {} for (const [name, value] of [ ['radius/control', 8], ['radius/card', 12], ['space/sm', 8], ['space/md', 16], ['space/lg', 24] ]) { const variable = figma.variables.createVariable(name, size, 'FLOAT') variable.setValueForMode(size.modes[0].modeId, value) sizes[name] = variable } function paint(variable) { return figma.variables.setBoundVariableForPaint( { type: 'SOLID', color: { r: 0, g: 0, b: 0 } }, 'color', variable ) } function bindAll(node, fields, variable) { for (const field of fields) node.setBoundVariable(field, variable) } const RADII = ['topLeftRadius', 'topRightRadius', 'bottomLeftRadius', 'bottomRightRadius'] function text(name, characters, style, fontSize, color) { const node = figma.createText() node.name = name node.fontName = { family: 'Inter', style } node.fontSize = fontSize node.characters = characters node.fills = [paint(color)] return node } const componentsPage = figma.currentPage componentsPage.name = 'Components' // 2. Button: two variants that share a Label text property. function buttonVariant(variant, fill, ink) { const button = figma.createComponent() button.name = `Variant=${variant}` button.layoutMode = 'HORIZONTAL' button.primaryAxisSizingMode = 'AUTO' button.counterAxisSizingMode = 'AUTO' button.primaryAxisAlignItems = 'CENTER' button.counterAxisAlignItems = 'CENTER' button.paddingTop = 10 button.paddingBottom = 10 bindAll(button, ['paddingLeft', 'paddingRight'], sizes['space/md']) bindAll(button, RADII, sizes['radius/control']) button.fills = [paint(fill)] button.appendChild(text('Label', 'Button', 'Medium', 14, ink)) return button } const primary = buttonVariant('Primary', colors['color/primary'], colors['color/on-primary']) const secondary = buttonVariant('Secondary', colors['color/secondary'], colors['color/text']) const buttonSet = figma.combineAsVariants([primary, secondary], componentsPage) buttonSet.name = 'Button' buttonSet.x = 0 buttonSet.y = 0 buttonSet.layoutMode = 'HORIZONTAL' buttonSet.primaryAxisSizingMode = 'AUTO' buttonSet.counterAxisSizingMode = 'AUTO' buttonSet.itemSpacing = 16 buttonSet.paddingLeft = buttonSet.paddingRight = buttonSet.paddingTop = buttonSet.paddingBottom = 20 const labelKey = buttonSet.addComponentProperty('Label', 'TEXT', 'Button') for (const variant of [primary, secondary]) { variant.findOne((node) => node.name === 'Label').componentPropertyReferences = { characters: labelKey } } pairdraw.setBehaviour(buttonSet, 'button') // 3. Card: a title property and two slots, Content and Actions. const card = figma.createComponent() card.name = 'Card' card.x = 0 card.y = 160 card.resize(320, 200) card.layoutMode = 'VERTICAL' card.primaryAxisSizingMode = 'AUTO' card.counterAxisSizingMode = 'FIXED' bindAll(card, ['paddingLeft', 'paddingRight', 'paddingTop', 'paddingBottom'], sizes['space/lg']) card.setBoundVariable('itemSpacing', sizes['space/md']) bindAll(card, RADII, sizes['radius/card']) card.fills = [paint(colors['color/surface'])] card.strokes = [paint(colors['color/border'])] card.strokeWeight = 1 const title = text('Title', 'Card title', 'Semi Bold', 18, colors['color/text']) card.appendChild(title) title.layoutSizingHorizontal = 'FILL' const titleKey = card.addComponentProperty('Title', 'TEXT', 'Card title') title.componentPropertyReferences = { characters: titleKey } function slotFrame(name, layoutMode) { const frame = figma.createFrame() frame.name = name frame.fills = [] frame.layoutMode = layoutMode frame.primaryAxisSizingMode = 'AUTO' frame.counterAxisSizingMode = 'AUTO' frame.setBoundVariable('itemSpacing', sizes['space/sm']) card.appendChild(frame) frame.layoutSizingHorizontal = 'FILL' return frame } const content = slotFrame('Content', 'VERTICAL') const body = text( 'Body', 'Slots hold content that each card chooses for itself.', 'Regular', 14, colors['color/text-muted'] ) content.appendChild(body) body.layoutSizingHorizontal = 'FILL' pairdraw.createSlot(content) const actions = slotFrame('Actions', 'HORIZONTAL') const action = primary.createInstance() actions.appendChild(action) pairdraw.createSlot(actions) // 4. Examples: the same cards in each mode, with their own slot content. const examplesPage = figma.createPage() examplesPage.name = 'Examples' function board(name, mode, x) { const frame = figma.createFrame() frame.name = name frame.x = x frame.y = 0 frame.layoutMode = 'VERTICAL' frame.primaryAxisSizingMode = 'AUTO' frame.counterAxisSizingMode = 'AUTO' bindAll(frame, ['paddingLeft', 'paddingRight', 'paddingTop', 'paddingBottom'], sizes['space/lg']) frame.setBoundVariable('itemSpacing', sizes['space/lg']) frame.fills = [paint(colors['color/background'])] frame.setExplicitVariableModeForCollection(theme, mode) examplesPage.appendChild(frame) const welcome = card.createInstance() welcome.setProperties({ [titleKey]: 'Welcome back' }) frame.appendChild(welcome) const plan = card.createInstance() plan.setProperties({ [titleKey]: 'Pro plan' }) plan.findOne((node) => node.name === 'Body').characters = 'Unlimited files, version history, and shared libraries.' const planActions = plan.findOne((node) => node.name === 'Actions') for (const child of [...planActions.children]) child.remove() const upgrade = primary.createInstance() upgrade.setProperties({ [labelKey]: 'Upgrade' }) const later = secondary.createInstance() later.setProperties({ [labelKey]: 'Not now' }) planActions.appendChild(later) planActions.appendChild(upgrade) frame.appendChild(plan) return frame } board('Light', light, 0) board('Dark', dark, 420) return { pages: figma.root.children.map((page) => page.name), variables: Object.keys(colors).length + Object.keys(sizes).length } ``` --- --- url: 'https://pairdraw.dev/user-guide/checking-designs.md' description: 'Find accessibility, consistency, and structure issues with the Lint panel.' --- # Checking Designs While the Lint tab is open, Pairdraw checks the current page as you work and points out layers that break common design rules: text that is hard to read, controls that are too small to tap, colors that should use a variable, and spacing off the scale. Nothing is checked while the Lint and Code tabs are closed, so a long agent run is not slowed down by checks after every edit. ## Lint Panel Open the **Lint** tab in the properties panel, in the left sidebar. Its badge shows how many errors and warnings the page has. * **Page** lists every issue on the current page; **Selection** narrows the list to the selected layers and everything inside them; **Document** lists every page's issues, tagging the ones on other pages. Clicking one of those switches to its page. Pages of a large `.fig` file that have not been opened yet are checked once you open them. * Issues are grouped by rule, most severe first. Errors and warnings start expanded; suggestions start collapsed. * The severity buttons under the scope switch filter errors, warnings, and suggestions on and off. * Hover a group title to read what the rule checks and why. Hover an issue to highlight its layer on the canvas. Click it to select the layer; if it is off screen, the canvas pans to it, and zooms out only when the layer does not fit. ## Fixing Issues Rows that can be fixed in one step show a button on hover: * A hardcoded color that matches one of the document's color variables binds to it (link button). The row names the variable. * Subpixel positions and sizes round to whole pixels. Values that auto layout or text resizing sets, and vector artwork and the parts of groups, are left alone. * Off-scale corner radius and spacing change to the nearest scale value, and text below the minimum size grows to it (wand button). These change the design, so they apply one row at a time. * A group converts to a frame in place, keeping its layers, position, and look (frame button), and a hidden layer can be deleted (trash button). Neither is offered for locked layers or layers inside a component or instance, whose structure belongs to the component. Binding colors and rounding pixels keep the design as it looks, so their groups also offer **Bind all** or **Fix all**. Every fix is a single undo step. Other issues show the value that needs attention, such as a contrast ratio or a touch target size, so you can fix them in the Design panel. Issues appear only in the Lint panel and as underlines in the Code tab. The canvas shows nothing for them beyond the highlight of the issue you hover, and the Layers panel and page list show none. ## In the Code Panel While it is open, the Code tab checks the page too and underlines errors and warnings on the Design JSX, HTML, Vue, or React of their layers, on the property that causes the issue when there is one, such as `size={10}` for small text, or the class that styles the layer. Hover the underline to read the issue. The underlines follow your edits while you change the code live. ## Rules The settings menu in the Lint panel switches between rule presets: * **Recommended** — balanced defaults for everyday work. * **Strict** — every rule as a warning or error. * **Accessibility** — contrast, touch target size, and text size only. Turn off a single rule from its group's menu. **Turn on turned-off rules** in the settings menu brings them back. Presets and turned-off rules are saved between sessions. The same rules run from the command line with `pairdraw lint`; see [Inspecting Files](/programmable/cli/inspecting). ## Design Memory A design memory keeps a document's design rules for the agents that work in it: the colors, fonts, font sizes, spacing, and corner radii they may use, decisions written down about them, and frames pinned as examples to follow. With nothing selected, the **Design memory** section of the Design panel shows what it holds; **Create from this document** starts one that allows the document's variables and styles and proposes the values its pages use most. In the dialog, each group can include the document's variables and styles, add values of its own, and choose what happens when an agent uses another value: * **Undo the edit** — the agent's edit is put back and it is told the nearest allowed values, so it tries again. Colors and fonts start here. * **Warn** — the edit goes through and the agent is told which values are off. Font sizes, spacing, and radii start here, since they have real exceptions such as hairlines. * **Off** — the group is not checked. Your own edits are never undone. Values outside the memory show in the Lint panel, whoever made them, with a fix to the nearest allowed value and **Allow**, which adds the value to the memory. An edit an agent had undone shows the same **Allow** in the chat. Agents are judged on the values they write: a color or font outside the memory is undone even when your layers already use it. Duplicating, grouping, flattening, or converting layers that already exist keeps their values, and the colors Pairdraw gives a new layer by default only warn. A variable or style an agent creates, changes, or rescopes is judged on every value it would then let in, and an agent cannot change, switch off, or remove the memory itself. With a frame selected, the **Design memory** section learns values from it and pins it as an example. Agents read the memory in the chat, through MCP with `get_design_memory`, and from the command line with `pairdraw design-memory`; they can write decisions down and pin examples. This covers agents working through Pairdraw's chat, MCP server, and `pairdraw agent`. A program that writes through CLI commands such as `pairdraw tool call` or `pairdraw eval` counts as you and is only warned. The memory is kept in the document's `.fig` or `.pen` file, along with its status workflow. --- --- url: 'https://pairdraw.dev/user-guide/comments.md' description: >- Leave comments pinned to the canvas, reply, resolve, and hand a marked area to an agent. --- # Comments Comments are threads pinned to the canvas and saved in the document, so they travel with the file and are readable by scripts, the AI chat, and MCP clients. ## Leave a comment Choose the **Comment** tool (C) and click the canvas to pin a thread, or drag a ring around an area. Write the comment and send it. The left sidebar becomes the comments list while the tool is active, with the document's threads; **Only current page** narrows the list. ## Read and reply Each thread shows its replies and who wrote them. **Reply** adds to the thread; **Resolve** hides it from the open list until **Show resolved comments** is on; **Reopen** puts it back. A comment can be deleted with its replies, after a confirmation. **Go to comment** brings its layer and spot into view. **Filter and sort** narrows the list: only the current page, only your threads, resolved comments, and newest or oldest first. **Search comments** finds threads by their text. ## Fix with agent A thread on a marked area offers **Fix with agent**: the area, the layers inside it, and a crop of the area go to the active agent, which changes what is circled, replies to the thread, and resolves it. **Apply open comments with AI** sends the open threads together. Comments can be left on the canvas, beside layers, and in a board's research notes; the [AI chat guide](/programmable/ai-chat) covers the agent side. --- --- url: 'https://pairdraw.dev/user-guide/statuses.md' description: 'Give layers a status, and shape the workflow a document''s statuses follow.' --- # Statuses A status is a named state a layer can carry, shown as a coloured mark in the Design panel's **Status** section. Select a layer (or several) and choose a status; a mixed selection shows **Mixed**, and a status hidden by an enclosing layer says so. ## Edit the workflow Open **Edit statuses…** from the Status section. The dialog lists the document's statuses with their names and colours; add, rename, recolour, and remove them there. A preset starts a useful set: * **Figma handoff**, **Simple**, and **Design review**. A status has a Figma counterpart where one exists (for example **Ready for dev** shows in Figma as its handoff status); the dialog names that mapping when it edits a status. Removing a status that is in use asks where its layers move first; **No status** is one of the choices. Statuses are saved in the document — in `.fig` and in `.pen` — so a handoff keeps its workflow. **Apply** commits the draft as one undo step; closing the dialog with unsaved changes offers **Discard** first. --- --- url: 'https://pairdraw.dev/user-guide/agent-notes.md' description: Leave context and a ready-to-run prompt on a layer for AI agents. --- # Agent notes A layer can carry notes written for agents. Select the layer and add **Notes for AI** at the bottom of the Design panel; the section holds two fields: * **Context** — what the layer means or does, such as "opens the sign-up dialog". Agents read it when a message concerns this layer: the layers the message mentions and the selection, or the whole page when there are none. * **Prompt** — a request about this layer. **Run prompt** sends it to the chat, so a request you repeat often does not need retyping. The plus button adds the notes, the minus removes them. Notes are saved in the file with the layer, and a `.pen` file's context notes and prompt cards are read the same way. The full rules — which messages carry which notes, and how agents treat context versus prompts — are in the [AI chat guide](/programmable/ai-chat#notes-for-ai). --- --- url: 'https://pairdraw.dev/user-guide/research.md' description: >- Quote the page open in the built-in browser onto a board as a cited sticky note. --- # Research on a Board On a board, the chat can read the page you have open in the built-in browser and turn it into a cited sticky note: a note that quotes the page, records where it came from, and is connected to the note you asked from. ## What It Needs * **A board document.** Pairdraw opens boards you already have, such as a FigJam-style `.fig` file, but Home offers no new board. In a design document the research tools are not offered at all. * **The desktop app's built-in browser.** The page is read from that window, so a browser tab answers that the browser window is desktop only. * **A sticky note to cite from.** Select one sticky; the new note connects from it. Research has no web search. The chat cannot look anything up on its own: it reads only the page the built-in browser shows, and cites that. ## Citing a Page 1. Open a board you have, add a sticky note, and select it. 2. Open the page in the built-in browser: the globe icon in the top bar, an address, **Open**. 3. Ask the chat to cite it, for example "Cite this page." The chat passes the open page to its cite tool. You can also give the chat an address to cite. It opens that address in the built-in browser first, opening the window if it was closed, and cites the page the window shows. The chat places a new sticky note 48 pixels to the right of the one you selected, and draws a connector from that note to the new one with an arrow at the new note. Citing again from the same note places the next one further right, in a row. The new note reads: ``` Source: Read: ``` The note is named after the page's title, or after the address when the page has none. The citation — address, title, quote, and read time — is stored on the note, so a saved document keeps where each quote came from. The note and its connector are one undo step. ## Reading Without Placing The chat also has a read tool. It returns the open page's address, title, and visible text — up to 8,000 characters of text and 300 of title — so a reply can answer from the page. It places nothing and changes nothing. ## The Chat Reference When the cite call returns, the reply names the new note as a citation chip with a quote icon. Choosing the chip focuses the note on the canvas. A note that carries a citation can also be sent to the chat: right-click it and choose **Run sticky as prompt**. The message holds the note's text and a citation chip, so the agent can tell a quoted note from one that was written by hand. ## Limits * The page's text is read with `innerText` from its body, so text drawn on a canvas, inside an image, or by a script is not in the quote. * A quote keeps 2,000 characters and a read keeps 8,000; a longer page is cut, not refused. * A citation addresses an `http` or `https` page only. Any other address is refused before a note is placed. * A refused address, a closed window, or a read that fails places nothing and leaves the board as it was. * The new note is placed at once. Citing does not open the approval dialog that canvas edits use when Settings asks before changes. --- --- url: 'https://pairdraw.dev/user-guide/playing-a-prototype.md' description: >- Link frames, switch component variants, and scroll frames with interactions, then play them on the canvas. --- # Playing a Prototype A prototype is the interactions you attach to layers: a click that goes to another frame, a hover that switches a button to its hover variant, a list that scrolls. Play shows one frame at a time on the canvas and runs those interactions without changing the design. ## Adding Interactions Select a layer. The design panel's **Prototype** section lists its interactions; choose the plus (**Add interaction**) to add one. Each interaction has: * **Trigger** — **On click**, **While hovering**, **While pressing**, **Mouse enter**, **Mouse leave**, or **After delay**. After delay, Mouse enter, and Mouse leave have a **Delay** in seconds; a new After delay starts at 1 second, a new Mouse enter or Mouse leave at none. * **Action** — **Navigate to**, **Open overlay**, **Change to**, **Scroll to**, **Back**, or **Close overlay**. Change to is offered on a variant, an instance of a variant, or a layer inside one; Scroll to on a screen that has something to scroll. * **Destination** — a top-level frame on the same page for Navigate to and Open overlay; another variant of the set for Change to, named by the value that tells it apart; a layer inside a scrolling frame for Scroll to. * **Animation** — **Instant**, **Dissolve**, or **Smart animate**. Dissolve and Smart animate add a **Duration**, 0.3 seconds for a new interaction, and an **Easing**: **Ease out**, which a new one starts with, **Ease in**, **Ease in and out**, or **Linear**. The minus removes an interaction. Every change is an undo step of its own. A page with no frame says **Add a frame to this page to link to.**, and its Play button stays hidden. ## Interactive Components Add the interactions to the variants of a component set, once: on the Default variant, **While hovering** → **Change to** Hover, and **On click** → **Change to** Selected. Every instance of the set then reacts in play by the variant it shows, so tabs, toggles, accordions, and hover states need no frame per state. An instance runs its main component's interactions. An interaction you add to the instance itself replaces the main component's interaction of the same trigger. The Prototype section of an instance shows how many interactions it takes from its main component; choose the line to select the main component and edit them. An **After delay** on a variant runs on each instance once it shows that variant, so a Loading variant can turn into Done by itself. ## Scrolling Frames Select a frame, component, or instance, and set **Overflow scrolling** in the Prototype section to **Vertical**, **Horizontal**, or **Both directions**. * A frame inside a screen scrolls when its content reaches past its edge and it clips its content. With **Clip content** off, the section says so. * A layer inside a scrolling frame has **Position when scrolling** in the Prototype section: **Scroll with parent** (the default), **Fixed** to stay in the frame, or **Sticky** to scroll until it reaches the frame's top or left edge and stay there. A layer in an instance can carry its own behavior as an override. * A screen that scrolls vertically and is taller than the window plays fitted to its width, and the canvas pans through the rest; one that scrolls sideways and is wider plays fitted to its height. In play the wheel, or a drag, scrolls the innermost frame under the pointer that can move that way, then the next one out; what none of them can take pans the canvas. A drag that scrolled runs no click. Ctrl or ⌘ with the wheel still zooms. **Scroll to** scrolls every frame around its layer, innermost first, until the layer meets each one's top left, as far as each can scroll; with Dissolve it eases there. On a screen that pans, the canvas pans the layer to the top of the window. ## Starting Play Choose **Play** in the Prototype section's header, or toggle **Preview** from the View menu (`⌘⌥↩` on macOS, `Ctrl+Alt+Enter` elsewhere). Play starts from: * the selected top-level frame, * else the frame that holds the selected layer, * else the page's first frame. The canvas then shows that frame alone: fitted to the window on its tighter axis, with the area around it in the page's color. The panels hide, and the canvas pans but does not select or edit. A pill at the top of the canvas shows **Previewing**, **Reset**, and **Leave preview**. **Reset** begins again from the frame play started on, puts every switched variant and scrolled frame back as designed, and puts every live control back as it was designed. **Leave preview**, or Escape, returns to editing with the view you had before preview started. ## Clicking and Hovering Through A click goes to the topmost layer under the pointer, inside the frame being shown, that has an **On click** interaction or shows a fill, stroke, image, or text there, and runs the nearest On click interaction from that layer up to the frame. A layer with an interaction counts over its whole box, so a button's background takes its click as its label does. A filled sheet laid over a button keeps the click from it, while an unfilled frame laid over the screen lets the click through, and a mask hides what lies outside it. Then: * **Navigate to** shows the destination frame and fits it to the window; the frame you left is remembered for Back. * **Open overlay** shows the destination over the frame being shown, and a scrim dims the canvas. Clicks then look only inside the overlay. **Close overlay** takes the overlay away and uncovers what was under it. * **Change to** shows the chosen variant on the instance the layer belongs to, keeping its overrides, and lays out the auto layout around it. * **Back** returns to the frame you navigated from and drops any overlays; with no frame behind it, Back does nothing. * An **After delay** interaction on the frame being shown runs when its delay passes, counted from when the transition into that frame ends, as in Figma. Changing the frame starts its delays again, and leaving play cancels them. * **Dissolve** crossfades from the frame you leave for the interaction's own **Duration**, along its **Easing**, whether a click or a delay started it. With reduced motion on, it cuts instead. * **Smart animate** moves the layers the two frames share, as [Smart Animate](#smart-animate) describes. **While hovering** runs as the pointer enters a layer and is undone as it leaves: a variant switches back, and an overlay closes when the pointer leaves the trigger in the frame behind it. **While pressing** runs on press and is undone on release, or when the pointer leaves the canvas first, closing an overlay it opened. A Dissolve crossfades for a hover, a press, and a delay as it does for a click, and a Smart animate Change to animates back the way it came when the pointer leaves or lifts. **Mouse enter** and **Mouse leave** run as the pointer enters or leaves, after their delay unless the pointer moves back first, and are not undone. A hovered variant goes back when another frame shows. A click that hits no interaction, or lands outside the frame, does nothing. A layer that holds controls takes its own click: play is the canvas's preview view, so a live control runs there as it does in Preview. ## Smart Animate Smart animate moves layers from one frame to the next instead of crossfading the whole frame. It runs on **Navigate to** between screens and on **Change to**, where it moves from the variant an instance showed to the one it shows. Play compares the two and: * matches a layer with the layer of the same name at the same place in the hierarchy: directly in both frames, or inside layers that match each other. When siblings share a name, the first matches the first, the second the second. Duplicate a frame, or name its layers alike, to have them match; grouping a layer in one frame and not in the other stops it matching. A frame matches a group, component, or instance of the same name. * moves each matching layer from its position, size, rotation, opacity, corner radius, and solid fill colors in the first frame to those in the second, over the **Duration** along the **Easing**. The destination frame's own fill blends too; its place and size do not change. * fades out the first frame's layers that have no match, where they were, and fades in the second frame's, where they are. A layer hidden in either frame, a layer of another kind, and text whose characters differ crossfade the same way instead of moving. Opening an overlay, or navigating while one is open, crossfades instead, as Figma has no Smart animate for overlays. With animations turned off in Settings, reduced motion on, or Ultralight mode, Smart animate cuts. ## What Play Does Not Do * An interaction runs its first action only, and the panel edits that one action. A file that carries more actions keeps them, but play runs only the first. * There is no drag or key trigger, and no Swap overlay, Open link, or variable action. * An overlay always opens fitted to the window, like a frame. The panel offers no corner position, and play ignores the position a file stores. * A While hovering or While pressing that opens an overlay or navigates is not undone: the overlay stays open until it is closed, and the frame stays until Back, as the new frame covers the layer the pointer would leave. * Instant, Dissolve, and Smart animate are the animations; Figma's slide, push, and move play as a cut, and Figma's animated scroll on a Scroll to plays eased. Each is kept when the file is saved. A Scroll to set to Dissolve in Pairdraw eases in play but is saved to `.fig` as instant, since which animation Figma reads for one is not confirmed. * Smart animate moves no gradient, image, stroke, effect, or text size, and does not morph one vector shape into another: those take the second frame's look at once. A spring or custom easing from a Figma file plays as ease out, and the file keeps it until the easing is changed. * Scroll to ignores the offset a Figma file stores. * A frame that holds live controls is drawn by Preview, so a Change to or scrolling inside it does not show. * Navigating to the frame already shown, or opening it as an overlay over itself, does nothing. ## Exporting a Video **File › Export Prototype as Video…**, or the clapperboard in the Prototype section's header, records what Play shows as a file, without recording the screen. Choose: * **Start frame** — the frame play starts from, chosen as Play chooses it. * **Format** — **MP4** (H.264), **GIF**, or **WebM** (VP9). MP4 and WebM are encoded by the browser, so a browser that cannot encode one, such as Firefox before 130, offers GIF; the dialog names the formats it can record. * **Size** — the start frame at its own size or double, or fitted so its long edge is 1920 or 1280 pixels. A later frame of another shape sits centred on the page color, as Play fits it. * **Frame rate** — 24, 30, or 60 frames a second, or 10, 15, or 25 for a GIF. * **Max length** — where the video stops if the flow goes on, up to 120 seconds. The recording follows the start frame's After delay interactions on a clock of its own, so the video is the same every time and never drops a frame. It ends when play comes back to the start frame, and then loops seamlessly as a GIF; when nothing else happens, after holding the last frame for a second; or at the max length. The dialog says how long the video lasts and at what size before you export, and a frame with no After delay to follow says so instead. An overlay shows over its frame, dimmed by a scrim, where its interaction places it. The video holds what each frame shows as designed: a live control, a shader, or an animated image fill appears as it is drawn on the canvas, standing still. It follows frames, overlays, and their After delays, with each Dissolve and Smart animate between frames as Play shows it: a Change to, a hover, a press, and scrolling are not recorded, so an instance shows the variant it has in the design. Agents record the same video through the `export_video` tool, and the CLI through `pairdraw export -f mp4` ([CLI reference](/reference/cli#export)). ## Saved with the Document Interactions and overflow scrolling are saved on their layers with the document and written into a `.fig` file as Figma prototype reactions and scroll settings, with each transition's Smart animate and easing, so Figma reads the same prototype and a round trip keeps it. A **Mouse enter** or **Mouse leave** delay read from a Figma file goes back into it; one set in Pairdraw plays but is not written to `.fig` yet, until where Figma stores it is confirmed. Playing changes nothing in the document: the session lives in the canvas view and leaves with it. --- --- url: 'https://pairdraw.dev/user-guide/plugins.md' description: >- Install plugin manifests, run a plugin from the command palette, and see what it may do. --- # Plugins A plugin is a manifest with a small JavaScript program. Install one and its command appears in the command palette; choosing it runs the program on the open document, in a sandbox, after asking what it may do. ## Installing Open **Settings → App → Plugins**. Install a manifest in one of two ways: * Paste the manifest's JSON into **Plugin manifest** and choose **Install**. * Choose **Choose file** and pick a `.json` file. Its size is checked before it is read. A successful install adds the plugin to this app's list, turned on. A refused one leaves the list as it was and shows why under the buttons. ## The Manifest A manifest is a JSON object with exactly these fields; an extra field makes it invalid. ```json { "id": "guide.marks", "name": "Marks", "version": "1.0.0", "command": "Mark", "source": "/* the plugin's program */", "capabilities": ["document:read"] } ``` * **`id`** — up to 64 characters: lowercase letters and digits, with single `.` or `-` separators, such as `guide.marks`. One id installs once. * **`name`** — 1 to 80 characters; the name the list shows. * **`version`** — 1 to 32 characters. * **`command`** — 1 to 80 characters; the command the palette shows for the plugin. * **`source`** — the plugin's program as text, at least 1 character and at most 64 KB. The app stores it with the plugin and runs it only when the plugin runs. * **`capabilities`** — an array of the capabilities below. Repeats are removed. Limits: the manifest text is at most 64 KB, and the app keeps at most 32 plugins. ## Capabilities A manifest may ask for these, and the panel names each one in the plugin's row: | Capability | What the panel says it allows | | --- | --- | | `document:read` | Read the open document. | | `document:write` | Change the open document. | | `filesystem:read` | Read files on this computer. | | `filesystem:write` | Write files on this computer. | | `code:execute` | Run code. | | `settings:read` | Read settings. | | `settings:write` | Change settings. | `document:read` and `document:write` are the capabilities this version can perform. The rest are listed in Settings and in the first-run prompt as **Not yet**: they cannot be granted, and a plugin's call that needs one is refused. `network:access` is not a plugin capability at all; a manifest that asks for it is refused with **Plugins cannot ask for network access.** Before a plugin's first run, the prompt names the permissions it can be given and what the plugin asked for; refusing it runs nothing. The switches in **Settings → App → Plugins** change the same permissions later. ## Running a Plugin Press ⌘K (CtrlK on Windows and Linux) and choose the plugin's command. It runs on the open document. * **One run at a time.** While a plugin runs, choosing another plugin's command answers **A plugin is already running.** * **A run has 2 seconds.** A program that does not finish in time is stopped and the run ends; a later run still works. * **The plugin calls the app's own tools.** `plugin.call(name, args)` runs a tool against the document, and each call is checked against the plugin's permissions. A call it was not granted fails inside the plugin without changing anything. * **The document changes are one undo step.** A successful run's edits undo together; a failed run puts them back. * **`plugin.pointer()` takes a canvas drag.** The canvas shows a crosshair, the plugin receives the points in document order, and the wait does not count against the run's time. Escape cancels the sequence: the plugin receives `null`, asking again is refused, and the run ends. Switching to another document or closing the tab cancels it the same way, so the other document's canvas is free and its drags reach the editor. * **Permissions are read live.** Turning the plugin off, or removing it, during a run stops its next call. ## Turning a Plugin Off, and Removing It * The switch beside a plugin turns it off and on. Turning it off also drops any capabilities it had been granted, and turning it back on does not bring them back; the next run asks again. * **Remove** asks to confirm, then deletes the plugin from the list and from this app's storage. ## Where the List Is Kept The list belongs to the app, not to a document: it is saved in this machine's local storage for the app, so a `.fig` or `.pen` file never carries a plugin, and the desktop app and a browser tab each keep their own list. On load, an entry this version cannot read is dropped on its own, and a list longer than 32 is cut to the limit. ## Limits * A program runs in an opaque-origin sandbox with no DOM. `fetch`, `XMLHttpRequest`, `WebSocket`, `EventSource`, `importScripts`, `Worker`, and `SharedWorker` are blocked or absent, and the app's storage is out of reach, so a plugin reaches neither the network nor your files. * A run's result crosses as JSON text of at most 64 KB; a larger one fails the run. A tool that runs asynchronously cannot be called. * Only `document:read` and `document:write` can be granted. There is no marketplace, no update check, no signature, and no per-document plugins. --- --- url: 'https://pairdraw.dev/programmable/sdk.md' description: Build Pairdraw-powered editors with headless Vue composables and primitives. --- # Vue SDK `@pairdraw/vue` exists so Pairdraw can be more than a standalone design app. The goal is to make Pairdraw a toolkit you can embed into other products, internal tools, and workflow-specific editors — not just a single default UI. The Pairdraw app is one composition of that toolkit. The SDK is how you build a different one. It gives you: * injected editor context * CanvasKit-backed canvas rendering * selection, commands, menu, property-panel, and variables composables * headless structural primitives like `PageListRoot`, `PropertyListRoot`, and `ToolbarRoot` * built-in i18n primitives for menus, panels, dialogs, and custom locale pickers ## Start here ## Why the SDK exists Different products and teams need different editing surfaces. Sometimes you want a full design editor. Sometimes you want a focused canvas inside another app. Sometimes you want an internal workflow tool, a template editor, or an AI-assisted editing surface built around a narrow use case. The SDK is the layer that makes those possible. ## Design principles * **Headless first**: logic and structure, not app styling * **Composable over wrapper**: use composables when there is no meaningful structural coordination * **Intentional public API**: stable exports from `packages/vue/src/index.ts` * **Framework-aware**: Vue integration over `@pairdraw/core` ## How to think about the package The SDK has two main layers: 1. **Composables** for editor state and actions 2. **Primitives** for meaningful UI structure If you only need editor state and actions, start with composables. If you are building reusable editor UI building blocks, start with primitives. ## API sections * [Components](/programmable/sdk/api/components/) * [Composables](/programmable/sdk/api/composables/) * [Advanced](/programmable/sdk/api/advanced/) --- --- url: 'https://pairdraw.dev/programmable/sdk/getting-started.md' description: 'Set up @pairdraw/vue with createEditor, provideEditor, and a canvas.' --- # SDK Getting Started ## Installation ```bash bun add @pairdraw/core @pairdraw/scene-graph @pairdraw/vue canvaskit-wasm ``` The SDK lives in the monorepo and is published as `@pairdraw/vue`. The current development version requires Vue `^3.5.41` and, when using its optional CanvasKit peer, `canvaskit-wasm >=0.41.1`. Check the installed package's peer requirements when using an older release. ```ts import { createEditor } from '@pairdraw/core' import { provideEditor } from '@pairdraw/vue' import { useCanvas } from '@pairdraw/vue/canvas/surface' ``` ## Mental model There are three layers: 1. `@pairdraw/core` — framework-agnostic editor engine 2. `@pairdraw/vue` — Vue composables and headless primitives 3. your app — styling, routing, file flows, product-specific UI ## Minimal setup ### 1. Create an editor ```ts twoslash // @module: esnext // @moduleResolution: bundler // ---cut--- import { reactive } from 'vue' import { createDefaultEditorState, createEditor } from '@pairdraw/core' import { SceneGraph } from '@pairdraw/scene-graph' const graph = new SceneGraph() const page = graph.getPages()[0] if (!page) throw new Error('Expected an initial page') const editor = createEditor({ graph, state: reactive(createDefaultEditorState(page.id)), getViewportSize: () => ({ width: 1200, height: 800 }), }) ``` Core state is framework-neutral; passing reactive state lets Vue controls observe editor changes. For a resizable editor, have `getViewportSize` return the current canvas container dimensions. `width` and `height` are not `EditorOptions` properties. Icons come from Iconify by default. To serve them from elsewhere, such as a bundled or self-hosted set, pass an `IconProvider` from `@pairdraw/core/icons` as `icons`; the editor's commands, its icon picker, and its AI tools all use it. ### 2. Provide it to Vue ```vue ``` You can think of this as the provider layer for the editor tree. The docs prefer `provideEditor()` directly because that is the current real API surface. ### 3. Attach a canvas ```vue ``` ## Using composables Once the editor is provided, child components can read selection and issue commands: ```ts import { useEditorCommands } from '@pairdraw/vue/editor/commands' import { useSelectionState } from '@pairdraw/vue/editor/selection-state' const selection = useSelectionState() const commands = useEditorCommands() ``` ## Basic example ```vue
Selected: {{ selectedCount }}
``` ## Migrating from v0.14.0 These changes describe the current development version; use them when upgrading beyond v0.14.0. * **Scene Graph overrides:** replace `SceneNode.overrides` records with `instanceOverrides`, whose `self` and `descendants` maps distinguish instance-level and descendant overrides. Use the public override helpers from `@pairdraw/scene-graph` rather than treating this as a simple field rename. * **Derived geometry:** rename `figmaDerivedLayout` to `derivedLayout`, `figmaDerivedTextGlyphs` to `derivedTextGlyphs`, and the exported `FigmaDerivedTextGlyph` type to `DerivedTextGlyph`. * **Binding providers:** implement `getBindingId()` and handle `unresolved`. For `edit-variable`, replace `setValue()` with `prepareEdit()`, which captures the edit key, value, setter, and restoration callback. See [BindableValue](./api/components/bindable-value). * **Translations:** replace `useDialogMessages()` and `dialogMessages` with the relevant product-domain composables and catalogs, such as `useSettingsMessages()` or `useRenameMessages()`. Catalog keys have also moved; do not just rename the import. See [useI18n](./api/composables/use-i18n). * **CanvasKit:** use `PathBuilder` for mutable construction and retain the returned paths from immutable `Path` operations instead of expecting in-place mutation. * **Custom tools:** use native Valibot `input` schemas and execution metadata instead of `params`, `ParamDef`, or `paramToZod()`. Programmatic MCP integrations use MCP SDK v2 server/client types; see [MCP](../mcp-server). ## Next steps * [Architecture](./architecture) * [API Reference](./api/) * [useEditor](./api/composables/use-editor) * [useCanvas](./api/composables/use-canvas) * [useI18n](./api/composables/use-i18n) --- --- url: 'https://pairdraw.dev/programmable/sdk/architecture.md' description: >- Folder structure, public API boundaries, and composition patterns in @pairdraw/vue. --- # SDK Architecture `@pairdraw/vue` is the Vue-facing layer over `@pairdraw/core`. It does not own the editor model itself. It adapts the core editor into: * Vue injection * reactive composables * headless structural primitives * canvas and input wiring ## Folder structure This package is organized by domain. ### Component families * `Canvas/` * `ColorPicker/` * `FillPicker/` * `FontPicker/` * `GradientEditor/` * `LayerTree/` * `PageList/` * `PropertyList/` * `PropertySection/` * `SegmentedControl/` * `NumberField/` * `Toolbar/` These contain structural/headless primitives and local helpers. ### Controls `controls/` contains property-panel and editor control composables: * `usePosition` * `useLayout` * `useAppearance` * `useColorModel` * `useTypography` * `useExport` * `useFillControls` * `useStrokeControls` * `useEffectsControls` * `useNodeProps` * `usePropScrub` * `useEditorPropertyList` ### Variables `VariablesEditor/` contains variables-domain composables and state wiring. ### Selection `selection/` contains selection-derived editor state and capabilities. ### Context `context/` contains editor injection helpers: * `EDITOR_KEY` * `provideEditor` * `useEditor` ### Internal `internal/` contains cross-cutting utilities not intended as primary headless primitives. ## Public API philosophy ### Prefer composables If the problem is mostly control logic, state derivation, or editor actions, expose a composable. ### Keep headless primitives for meaningful structure Use component roots when they coordinate structure, children, slots, or context. Examples: * `PageListRoot` * `PropertyListRoot` * `PropertySectionRoot` * `SegmentedControlRoot` * `ToolbarRoot` ### Avoid broad context-dump slots Prefer focused slot props or direct composable usage over giant `v-slot="ctx"` payloads. Controlled primitives such as `PropertyListRoot` emit semantic events; editor selection and undo wiring belongs in an adapter or control composable, not the primitive. ## App vs SDK responsibility ### SDK owns * editor integration * reusable headless logic * reusable UI structure without styling assumptions * canvas rendering integration ### App owns * styling * layout shells * routing * product file flows * toasts, menus, and app-specific UX ## Practical rule of thumb If a piece of logic could be reused in a different Pairdraw-based app without bringing app styling with it, it probably belongs in `@pairdraw/vue`. ## Related pages * [SDK Getting Started](./getting-started) * [API Reference](./api/) --- --- url: 'https://pairdraw.dev/programmable/sdk/guides/custom-editor-shell.md' description: >- Build your own editor shell with provideEditor, CanvasRoot, menus, panels, and toolbars. --- # Custom Editor Shell A typical Pairdraw Vue app has three layers: 1. `@pairdraw/core` creates the editor 2. `@pairdraw/vue` adapts it into Vue composables and headless primitives 3. your app renders the shell, styling, and product UX ## Why this matters The built-in Pairdraw app is only one possible shell. You can build a very different one for a focused workflow: an embedded editor inside another product, an internal asset tool, a template editor, an annotation UI, or an AI-assisted editing surface with custom controls. That is the main reason the SDK exists. ## Recommended composition A practical shell often looks like this: * provider at the top with `provideEditor()` * canvas in the center * page/layer navigation on one side * properties on the other side * menus and toolbars driven by composables ## Example ```vue ``` The fixed viewport dimensions above keep the example short. In a resizable shell, return the actual canvas container size from `getViewportSize`; do not include the surrounding sidebars or toolbar. See [SDK Getting Started](../getting-started) for installation requirements and migration notes. ## Why this split works * the SDK owns editor integration and reusable headless logic * your app owns layout, styling, and product-specific actions * composables can power menus and panels without extra wrapper components ## Related APIs * [provideEditor](../api/composables/provide-editor) * [useCanvas](../api/composables/use-canvas) * [ToolbarRoot](../api/components/toolbar-root) * [PageListRoot](../api/components/page-list-root) * [LayerTreeRoot](../api/components/layer-tree-root) --- --- url: 'https://pairdraw.dev/programmable/sdk/guides/property-panels.md' description: Build property panels with control composables and headless list primitives. --- # Property Panels Property panels in `@pairdraw/vue` are intentionally composable-first. If a panel mostly needs selection-derived values and update actions, prefer composables. If a panel needs reusable array/list structure, use a headless primitive like `PropertyListRoot`. ## Common control composables For standard property sections, start with: * `usePosition()` * `useLayout()` * `useAppearance()` * `useTypography()` * `useExport()` For list-style panels, use: * `useFillControls()` * `useStrokeControls()` * `useEffectsControls()` ## Binding-aware fields Compose `BindableValueRoot` around fields that can reference variables or external design tokens. The primitive is presentation-agnostic, but binding-aware interfaces should keep focus non-destructive: * Show variable identity while the field is idle; expose the resolved value in supporting UI such as a tooltip. * Focusing or opening the picker must not detach a binding. * Apply `detach-on-edit`, `readonly-when-bound`, or `edit-variable` only when the user actually changes the value. * Put explicit detach actions in the picker rather than on a destructive one-click field icon. * Keep binding replacement, detach-on-edit, and multi-target changes in one provider batch. Pairdraw's app skin uses a violet variable-name pill at rest and reveals the resolved numeric value when NumberField enters editing mode. Custom editor shells can present the same headless state differently. ## Example: position panel ```vue ``` ## Example: fills panel ```vue ``` ## Rule of thumb * use composables for direct control logic * use structural primitives when repeated list/tree/slot coordination is the hard part ## Related APIs * [usePosition](../api/composables/use-position) * [useLayout](../api/composables/use-layout) * [useAppearance](../api/composables/use-appearance) * [useTypography](../api/composables/use-typography) * [useFillControls](../api/composables/use-fill-controls) * [useStrokeControls](../api/composables/use-stroke-controls) * [useEffectsControls](../api/composables/use-effects-controls) * [PropertyListRoot](../api/components/property-list-root) --- --- url: 'https://pairdraw.dev/programmable/sdk/guides/navigation-panels.md' description: >- Build page and layer sidebars with PageListRoot, LayerTreeRoot, and selection state. --- # Navigation Panels Pairdraw sidebars usually combine two concerns: * page navigation * layer navigation The Vue SDK provides headless primitives for both. ## Page navigation Use `PageListRoot` or `usePageList()`. ```vue
``` ## Layer navigation Use `LayerTreeRoot` when you want SDK-managed tree structure but app-owned presentation. ```vue ``` ## Practical pattern A common layout is: * pages at the top of the sidebar * layers below * details or inline rename controls embedded in your row components ## Related APIs * [usePageList](../api/composables/use-page-list) * [PageListRoot](../api/components/page-list-root) * [LayerTreeRoot](../api/components/layer-tree-root) * [useSelectionState](../api/composables/use-selection-state) --- --- url: 'https://pairdraw.dev/programmable/sdk/api.md' description: >- Reference documentation for @pairdraw/vue components, composables, and advanced APIs. --- # API Reference The Vue SDK reference is organized into three sections. ## Suggested path * Start with **Components** if you are building reusable editor UI primitives. * Start with **Composables** if you are wiring editor state and actions. * Use **Advanced** only when you need lower-level helpers or primitive contexts. --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components.md' description: Component reference for headless Vue primitives in @pairdraw/vue. --- # Components `@pairdraw/vue` exposes headless structural primitives for canvas wiring, navigation UI, property panels, and focused input controls. ## Core editor primitives ## Property panel primitives ## Pickers and inputs --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/canvas-root.md' description: Headless canvas primitive for Pairdraw rendering surfaces. --- # CanvasRoot `CanvasRoot` is the structural canvas primitive in `@pairdraw/vue`. Use it when you want SDK-provided canvas structure and context with app-owned layout and styling. ## Related APIs * [useCanvas](../composables/use-canvas) * [useCanvasInput](../composables/use-canvas-input) * [useTextEdit](../composables/use-text-edit) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/canvas-surface.md' description: Canvas element primitive that binds to the nearest CanvasRoot context. --- # CanvasSurface `CanvasSurface` renders the actual `` element used by the SDK canvas stack. Use it inside `CanvasRoot` when you want SDK-managed canvas refs and rendering integration, but app-owned layout and styling. ## Related APIs * [CanvasRoot](./canvas-root) * [useCanvasContext](../advanced/use-canvas-context) * [useCanvas](../composables/use-canvas) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/layer-tree-root.md' description: Headless structural primitive for layer tree interfaces. --- # LayerTreeRoot `LayerTreeRoot` is the SDK primitive for rendering a layer tree with app-owned markup and styling. Use it when you want reusable tree structure and interaction wiring without built-in presentation. ## Related APIs * [useSelectionState](../composables/use-selection-state) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/layer-tree-item.md' description: Headless row primitive for a single layer tree node. --- # LayerTreeItem `LayerTreeItem` renders one layer-tree row and exposes selection, expand, visibility, lock, and rename handlers through its default slot. Use it when you want app-owned row markup with SDK-provided layer-tree behavior. ## Related APIs * [LayerTreeRoot](./layer-tree-root) * [useLayerTree](../advanced/use-layer-tree) * [useLayerDrag](../advanced/use-layer-drag) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/toolbar-root.md' description: Headless structural primitive for editor toolbar UIs. --- # ToolbarRoot `ToolbarRoot` is the headless toolbar primitive from `@pairdraw/vue`. Use it when you want reusable toolbar structure and context with your own buttons, styling, and layout. ## Related APIs * [useEditorCommands](../composables/use-editor-commands) * [useSelectionCapabilities](../composables/use-selection-capabilities) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/toolbar-item.md' description: Headless toolbar item primitive for a single editor tool. --- # ToolbarItem `ToolbarItem` exposes active-state and selection behavior for one toolbar tool. Use it inside `ToolbarRoot` when you want custom button markup but shared tool-selection wiring. ## Related APIs * [ToolbarRoot](./toolbar-root) * [useToolbar](../advanced/use-toolbar) * [useToolbarState](../advanced/use-toolbar-state) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/page-list-root.md' description: Headless structural primitive for page list UIs. --- # PageListRoot `PageListRoot` is a headless structural primitive for page list interfaces. It provides slot props for: * pages * current page id * divider detection * page actions like add, switch, rename, and delete ## Usage Use it when you want SDK-provided page-list structure with app-specific rendering and styling. ## Basic example ```vue
``` ## Related APIs * [usePageList](../composables/use-page-list) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/property-section.md' description: Headless collapsible anatomy for property-panel sections. --- # PropertySection PropertySection supplies collapsible section anatomy and canonical open, empty, and disabled state attributes without imposing presentation. ## Anatomy * `PropertySectionRoot` — controlled or uncontrolled Collapsible state * `PropertySectionHeader` — structural header container * `PropertySectionTitle` — accessible Collapsible trigger * `PropertySectionActions` — sibling action area, avoiding nested buttons * `PropertySectionContent` — collapsible content region * `PropertySectionEmptyAction` — empty-only action that opens before emitting `activate` ```vue twoslash ``` ## Generated API reference --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/property-grid.md' description: Headless field-grid and action-rail anatomy for property panels. --- # PropertyGrid `PropertyGridRoot` separates responsive property fields from optional intrinsic-width actions. It exposes structural data attributes without imposing column widths, gaps, or presentation. ```vue twoslash ``` Themes can target `data-slot="fields"`, `data-slot="actions"`, `data-columns`, and `data-distribution`. The `wide-first` distribution is semantic; consumers choose its exact ratio. ## Generated API reference --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/segmented-control.md' description: Accessible selection and action-only segmented controls. --- # SegmentedControl SegmentedControl delegates selection, roving focus, and keyboard behavior to Reka UI. Single and multiple modes retain selection; action mode emits commands without toggle state. ## Selection mode ```vue twoslash ``` ## Action mode Use `mode="action"` for grouped commands such as flip and rotate. Arrow keys move focus, while Space or Enter emits `action(value)` without leaving a selected segment. The complete state matrix is shown in the [PropertySection demo](./property-section). ## Generated API reference --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/property-list-root.md' description: 'Precisely typed headless list anatomy for fills, strokes, and effects.' --- # PropertyList PropertyList is a controlled, headless list primitive for fills, strokes, and effects. The `propKey` discriminator gives slots and actions exact `Fill`, `Stroke`, or `Effect` types. Editor mutation and undo behavior stay in `useEditorPropertyList()` or an application adapter. ## Anatomy * `PropertyListRoot` — controlled items, identity, mixed state, and semantic events * `PropertyListItem` — exact item type plus `data-hidden` and `data-dragging` * `PropertyListAdd` — adds a typed item * `PropertyListRemove` — removes an indexed item * `PropertyListVisibility` — toggles indexed visibility and exposes `aria-pressed` ```vue twoslash ``` See the [PropertySection demo](./property-section) for the shared interactive state matrix. ## Editor adapter Pairdraw panels use `useEditorPropertyList(propKey)` to connect controlled events to selection, multi-node updates, undo batching, and reordering. Third-party SDK consumers can provide their own state adapter without a Pairdraw editor context. ## Generated API reference --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/property-list-item.md' description: 'Headless item primitive for a single fills, strokes, or effects row.' --- # PropertyListItem `PropertyListItem` exposes update, patch, remove, and visibility handlers for one array item inside `PropertyListRoot`. Use it when building custom list-row UIs for fills, strokes, or effects. ## Related APIs * [PropertyListRoot](./property-list-root) * [usePropertyList](../advanced/use-property-list) * [useNodeProps](../advanced/use-node-props) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/color-picker-root.md' description: Headless popover-based color picker with interaction lifecycle events. --- # ColorPickerRoot `ColorPickerRoot` composes a color swatch trigger with a popover surface while leaving the editor UI to its slots. The trigger slot receives the current swatch style; the default slot receives the current scene-graph color. `openChange` reports the complete picker interaction boundary. `cancel` fires before an Escape close, allowing BindableValue consumers to roll back a variable detach and paint update together. Opening or focusing the picker does not emit a color update. ```vue twoslash ``` ## Generated API reference ## Related APIs * [ColorInputRoot](./color-input-root) * [useColorModel](../composables/use-color-model) * [BindableValue](./bindable-value) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/color-input-root.md' description: Headless color input helper with hex parsing and update helpers. --- # ColorInputRoot `ColorInputRoot` is a headless helper for color input UIs. It derives a hex value from a color and exposes update helpers for hex and full-color changes. ## Props ## Events ## Slots ## Example ```vue ``` ## Related APIs * [ColorPickerRoot](./color-picker-root) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/channel-slider.md' description: Accessible scalar channel slider for OkHCL controls. --- # ChannelSlider `ChannelSlider` provides the same Root/Track/Thumb composition and keyboard behavior as Reka's Slider while accepting an arbitrary scalar channel. Pairdraw uses it only for OkHCL channels; standard RGB, HSL, and HSB controls should use Reka `ColorSlider` directly. ## Anatomy * `ChannelSliderRoot` — controlled value, range, step, orientation, and accessible channel label * `ChannelSliderTrack` — polymorphic track element * `ChannelSliderThumb` — slider thumb with range ARIA and formatted value text Arrow keys step the value. Page Up and Page Down use larger steps, while Home and End move to the range boundaries. The primitive is temporary until [Reka issue #2798](https://github.com/unovue/reka-ui/issues/2798) provides first-class OkHCL support. ```vue twoslash ``` ## Generated API reference ## Related APIs * [useColorModel](../composables/use-color-model) * [FillRoot](./fill-root) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/fill-root.md' description: Headless fill category state and conversion actions. --- # FillRoot `FillRoot` owns solid, gradient, and image category state without owning a popover or visual swatch. Compose it around the picker surface appropriate for your application. Its default slot exposes the current fill, category, transparency, swatch background, and grouped conversion actions. Category changes emit immutable `Fill` values and are no-ops when the requested category is already active. ```vue twoslash ``` ## Generated API reference ## Related APIs * [FillSwatch](./fill-swatch) * [ChannelSlider](./channel-slider) * [useColorModel](../composables/use-color-model) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/fill-swatch.md' description: 'Binding-aware semantic preview for solid, gradient, and image fills.' --- # FillSwatch `FillSwatch` exposes a semantic preview for a fill without imposing application styling. Its slot provides the effective fill, preview background, category, and transparency state. The root also publishes `data-fill-type`, `data-fill-category`, and `data-transparent` for styling and tests. When nested in `BindableValueRoot`, a bound solid fill previews the provider's resolved color and forwards the binding state attributes. Reading or focusing a swatch never detaches the binding. Consumers can place a checkerboard below the slot's `background` value for transparent paints. ```vue twoslash ``` ## Generated API reference ## Related APIs * [FillRoot](./fill-root) * [BindableValue](./bindable-value) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/font-picker-root.md' description: Headless searchable font picker built on Reka Combobox. --- # FontPickerRoot `FontPickerRoot` is a headless searchable font picker built on Reka UI Combobox primitives. ## Props ## Model ## Events ## Slots ## Example ```vue ``` ## Related APIs * [useTypography](../composables/use-typography) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/gradient-editor-root.md' description: Headless root primitive for gradient stop editing. --- # GradientEditorRoot `GradientEditorRoot` is a headless root primitive for gradient editing. It owns: * active stop state * subtype switching * stop add/remove/update logic * active color editing * derived bar background ## Props ## Events ## Slots ### Default slot props ```ts { stops: GradientStop[] subtype: GradientSubtype subtypes: Array<{ value: GradientSubtype; label: string }> activeStopIndex: number activeColor: Color barBackground: string setSubtype: (type: GradientSubtype) => void selectStop: (index: number) => void addStop: () => void removeStop: (index: number) => void updateStopPosition: (index: number, position: number) => void updateStopColor: (index: number, hex: string) => void updateStopOpacity: (index: number, opacity: number) => void updateActiveColor: (color: Color) => void dragStop: (index: number, position: number) => void } ``` ## Example ```vue ``` ## Related APIs * [GradientEditorBar](./gradient-editor-bar) * [GradientEditorStop](./gradient-editor-stop) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/gradient-editor-bar.md' description: Headless draggable bar primitive for gradient stops. --- # GradientEditorBar `GradientEditorBar` is the draggable bar primitive used inside gradient editors. ## Props ## Events ## Slots ### Default slot props ```ts { stops: GradientStop[] activeStopIndex: number barBackground: string barRef: (el: unknown) => void onStopPointerDown: (index: number, event: PointerEvent) => void onPointerMove: (event: PointerEvent) => void onPointerUp: () => void draggingIndex: number | null } ``` ## Example ```vue ``` ## Related APIs * [GradientEditorRoot](./gradient-editor-root) * [GradientEditorStop](./gradient-editor-stop) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/gradient-editor-stop.md' description: Accessible primitive for a selected or draggable gradient stop. --- # GradientEditorStop `GradientEditorStop` renders a polymorphic gradient stop with documented selection and dragging state. Interactive stops use the slider role and expose their percentage position through ARIA. Use interactive stops on the gradient bar. Arrow keys nudge by `positionStep`; holding Shift uses a 10× step. Home and End move to either boundary, while Delete and Backspace emit `remove` when the stop is removable. Handled keys stop propagation so editor-level deletion and movement shortcuts do not run. Native Tab order cycles between stops. Set `interactive="false"` when reusing the primitive around a composite stop row. The row still exposes slot actions and `data-selected`/`data-dragging`, but does not enter the slider tab order. ```vue twoslash ``` ## Generated API reference ## Related APIs * [GradientEditorRoot](./gradient-editor-root) * [GradientEditorBar](./gradient-editor-bar) * [useColorModel](../composables/use-color-model) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/number-field.md' description: >- Headless numeric field primitives with scrubbing, expressions, and keyboard stepping. --- # NumberField The NumberField family provides a headless numeric control with pointer scrubbing, mixed values, keyboard stepping, safe arithmetic expressions, units, trailing actions, and binding-aware state. ## Anatomy * `NumberFieldRoot` — renderless state and interaction owner * `NumberFieldLeading` — leading label or icon * `NumberFieldValue` — non-editing value * `NumberFieldInput` — editing input with spinbutton semantics * `NumberFieldUnit` — unit text * `NumberFieldTrailing` — trailing action area * `NumberFieldMenu` — field menu area ## Root slot The default slot receives `modelValue`, `displayValue`, `draftValue`, `placeholder`, all state booleans, `state`, `actions`, and `attrs`. Bind `attrs` to the focusable outer element. It contains the canonical spinbutton ARIA contract, keyboard/focus handlers, and `data-editing`, `data-scrubbing`, `data-mixed`, `data-disabled`, and `data-bound` attributes. ## Expressions and keyboard Committed input accepts absolute arithmetic such as `12*8+4`, relative operations such as `+10`, `-4`, `*2`, and `/3`, and percentages such as `50%` when `max` is finite. The parser only accepts numbers, parentheses, and `+ - * /`; it never evaluates JavaScript. Arrow keys step by `step`. Shift multiplies the step by 10 and Alt multiplies it by 0.1. Enter commits and Escape restores the interaction-start value. ## Example ```vue twoslash ``` ## Generated API reference The following tables are extracted from the Vue source and its JSDoc during the documentation build. --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/bindable-value.md' description: Provider-driven value binding primitives for custom editor controls. --- # BindableValue BindableValue composes variable or token binding with fields without coupling the field to a specific editor store. Applications supply a `BindingProvider`; NumberField consumes the context automatically when nested beneath `BindableValueRoot`. ## Anatomy * `BindableValueRoot` — binding state, policy, resolved value, picker state, and actions * `BindableValueTrigger` — polymorphic bind-picker trigger * `BindableValuePicker` — renderless Reka Combobox composition ## Policies * `detach-on-edit` unbinds targets on the first value mutation and keeps the complete interaction in one provider undo batch. * `readonly-when-bound` blocks field editing, scrubbing, and keyboard stepping. * `edit-variable` uses `provider.prepareEdit()` to capture a stable edit key, current value, setter, and restoration callback instead of changing the target value. Focusing a bound NumberField or opening its picker is non-destructive. The policy starts only when the user types a changed draft, steps the value, or crosses the pointer-scrub threshold. Committing an unchanged field creates no undo entry. Cancellation rolls back an open provider batch. Providers without undo support still receive binding changes, with binding snapshots restored where possible. ## Provider example ```ts twoslash import type { Variable } from '@pairdraw/scene-graph' import type { BindingProvider, BindingTarget } from '@pairdraw/vue/controls/binding-provider' const variable: Variable = { id: 'spacing/md', name: 'Spacing / Medium', type: 'FLOAT', collectionId: 'spacing', valuesByMode: { default: 16 }, description: '', hiddenFromPublishing: false } const values = new Map([[variable.id, 16]]) const bindings = new Map() const getBindingId = (target: BindingTarget) => bindings.get(`${target.nodeId}:${target.path}`) const resolve: BindingProvider['resolve'] = id => values.get(id) const provider: BindingProvider = { listVariables: () => [variable], filterVariables: term => variable.name.toLowerCase().includes(term.toLowerCase()) ? [variable] : [], getBindingId, getBound: target => getBindingId(target) === variable.id ? variable : undefined, getState: targets => { const ids = new Set(targets.map(getBindingId)) if (ids.size === 0 || (ids.size === 1 && ids.has(undefined))) return 'unbound' if (ids.size > 1) return 'mixed' if (!ids.has(variable.id)) return 'unresolved' const resolved = targets.map(target => resolve(variable.id, target)) if (resolved.some(value => value === undefined)) return 'unresolved' return new Set(resolved).size > 1 ? 'mixed' : 'bound' }, resolve, bind: (target: BindingTarget, variableId) => { bindings.set(`${target.nodeId}:${target.path}`, variableId) }, unbind: (target: BindingTarget) => { bindings.delete(`${target.nodeId}:${target.path}`) } } ``` ## Generated API reference The following tables are extracted from the Vue source and JSDoc during the documentation build. --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/layout-controls-root.md' description: Headless root primitive for auto-layout and sizing controls. --- # LayoutControlsRoot `LayoutControlsRoot` exposes the slot contract returned by `useLayout()` as a structural primitive. Use it when you want a reusable layout-controls shell with app-owned markup. Width and height fields can remain editable while their axis uses Hug or Fill. On the first actual numeric mutation, `updateAxisSize()` records the sizing transition and changes that axis to Fixed. Compose the field with `BindableValue` and an interaction-batch-capable provider when sizing mode, variable detachment, and the numeric value must commit or roll back as one undo step. Focus and picker opening do not change sizing mode. Use `setAxisSizing('width', mode)` or `setAxisSizing('height', mode)` for sizing menus. The older axis-specific setters are not part of the current contract. ## Generated API reference The following tables are extracted from the Vue source and JSDoc during the documentation build. ## Related APIs * [useLayout](../composables/use-layout) * [BindableValue](./bindable-value) * [Property Panels guide](../../guides/property-panels) --- --- url: >- https://pairdraw.dev/programmable/sdk/api/components/constraints-control-root.md description: Headless constraint state and actions for frame children. --- # ConstraintsControlRoot `ConstraintsControlRoot` exposes horizontal and vertical resize constraints for the current eligible selection. It is active for children of frames, components, component sets, and instances. Normal auto-layout children and top-level page layers are excluded; absolutely positioned auto-layout children remain eligible. The default slot provides concrete or mixed axis values and undo-aware actions for setting modes or building an interactive pin control. Multi-selection changes are grouped into one undo entry. Constraint values match the Figma Plugin API: `MIN`, `CENTER`, `MAX`, `STRETCH`, and `SCALE`. ## Generated API reference The following tables are extracted from the Vue source and JSDoc during the documentation build. ## Related APIs * [PositionControlsRoot](./position-controls-root) * [LayoutControlsRoot](./layout-controls-root) * [Property Panels guide](../../guides/property-panels) --- --- url: >- https://pairdraw.dev/programmable/sdk/api/components/appearance-controls-root.md description: >- Headless root primitive for opacity, visibility, blend mode, corner radius, and smoothing controls. --- # AppearanceControlsRoot `AppearanceControlsRoot` exposes the slot contract returned by `useAppearance()` as a structural primitive. Use it when you want reusable appearance controls with custom presentation. The root owns selection-derived presentation decisions, including `showIndependentCorners`. That state becomes active when the selected node explicitly uses independent corners or when an imported node contains unequal corner values with a stale uniform flag. Consumers should render from this state rather than maintaining a parallel local expansion ref. `cornerSmoothingPercent` exposes the normalized scene value as `0…100` or `MIXED`. Update it through the corner actions using normalized `0…1` values. Multi-node independent-corner toggles, smoothing edits, and per-corner commits are grouped into one undo entry while preserving each node's original value. ## Generated API reference The following tables are extracted from the Vue source and JSDoc during the documentation build. ## Related APIs * [useAppearance](../composables/use-appearance) * [Property Panels guide](../../guides/property-panels) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/components/position-controls-root.md' description: 'Headless root primitive for position, size, alignment, and transform controls.' --- # PositionControlsRoot `PositionControlsRoot` exposes position, size, rotation, align, flip, and rotate handlers for the current selection. Use it when you want custom position controls without reimplementing editor wiring. ## Related APIs * [usePosition](../composables/use-position) * [Property Panels guide](../../guides/property-panels) --- --- url: >- https://pairdraw.dev/programmable/sdk/api/components/typography-controls-root.md description: 'Headless root primitive for font, alignment, and formatting controls.' --- # TypographyControlsRoot `TypographyControlsRoot` exposes typography state and handlers from `useTypography()` as a structural primitive. Use it when you want custom typography controls with SDK-managed font and formatting behavior. ## Related APIs * [useTypography](../composables/use-typography) * [FontPickerRoot](./font-picker-root) * [Property Panels guide](../../guides/property-panels) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables.md' description: Core composable APIs in @pairdraw/vue. --- # Composables These are the main composables most `@pairdraw/vue` consumers will use. ## Context and canvas * [provideEditor](./provide-editor) * [useEditor](./use-editor) * [useCanvas](./use-canvas) * [useCanvasInput](./use-canvas-input) * [useTextEdit](./use-text-edit) ## Selection and commands * [useSelectionState](./use-selection-state) * [useSelectionCapabilities](./use-selection-capabilities) * [useEditorCommands](./use-editor-commands) * [useMenuModel](./use-menu-model) ## Property panels * [usePosition](./use-position) * [useLayout](./use-layout) * [useConstraints](./use-constraints) * [useComponentProperties](./use-component-properties) * [useAppearance](./use-appearance) * [useSharedStyleBinding](./use-shared-style-binding) * [useColorModel](./use-color-model) * [useMask](./use-mask) * [useVariableModes](./use-variable-modes) * [useTypography](./use-typography) * [useExport](./use-export) * [useFillControls](./use-fill-controls) * [useStrokeControls](./use-stroke-controls) * [useEffectsControls](./use-effects-controls) * [useSelectionLayout](./use-selection-layout) * [useSelectionColors](./use-selection-colors) ## Document workspaces * [useDocumentWorkspace](./use-document-workspace) ## Variables, navigation, and localization * [usePageList](./use-page-list) * [useI18n](./use-i18n) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/provide-editor.md' description: Provide a Pairdraw editor instance to a Vue subtree using injection. --- # provideEditor `provideEditor(editor)` makes a Pairdraw editor available to descendant composables and headless primitives through Vue injection. This is the foundation for `useEditor()`. ## Usage ```ts import { provideEditor } from '@pairdraw/vue' provideEditor(editor) ``` ## Basic example ```vue ``` ## Notes The current SDK uses `provideEditor()` and `useEditor()` directly. Some older examples and error messages still refer to a `PairdrawProvider` component, but the injection model is the real API surface to prefer in docs and app code. ## Related APIs * [useEditor](./use-editor) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-editor.md' description: Access the current injected Pairdraw editor instance. --- # useEditor `useEditor()` returns the current injected Pairdraw editor. It is the main entry point for SDK composables and headless primitives that need editor access. ## Usage `useEditor()` must be called inside a subtree where `provideEditor(editor)` has already been called. ```ts import { useEditor } from '@pairdraw/vue' const editor = useEditor() ``` ## Basic example ```vue ``` ## Practical examples ### Read selected nodes ```ts const editor = useEditor() const selected = editor.getSelectedNodes() ``` ### Trigger commands ```ts const editor = useEditor() editor.zoomToFit() editor.undoAction() ``` ## Error behavior If called outside an editor provider tree, `useEditor()` throws with a helpful message. That is intentional — this API should fail loudly when the editor context is missing. ## Related APIs * [provideEditor](./provide-editor) * [useCanvas](./use-canvas) * [useSelectionState](./use-selection-state) * [useEditorCommands](./use-editor-commands) ## Type ```ts function useEditor(): Editor ``` --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-canvas.md' description: Attach CanvasKit-backed rendering to a canvas element for a Pairdraw editor. --- # useCanvas `useCanvas()` connects an editor to a real `` element. It handles: * CanvasKit initialization * surface creation * render scheduling * resize handling * optional ruler visibility * renderer readiness callback ## Usage ```ts import { ref } from 'vue' import { useCanvas } from '@pairdraw/vue/canvas/surface' import { useEditor } from '@pairdraw/vue' const canvasRef = ref(null) const editor = useEditor() useCanvas(canvasRef, editor) ``` ## Basic example ```vue ``` ## Practical examples ### Disable rulers for an embedded preview ```ts useCanvas(canvasRef, editor, { showRulers: false, }) ``` ### Keep drawing buffer for screenshots ```ts useCanvas(canvasRef, editor, { preserveDrawingBuffer: true, }) ``` ## Notes * `useCanvas()` is renderer-facing and browser-only in practice * it is responsible for the live canvas pipeline, not app-level file flows * it should usually be paired with `useCanvasInput()` for interaction handling ## Related APIs * [useEditor](./use-editor) * [useCanvasInput](./use-canvas-input) * [useTextEdit](./use-text-edit) ## Type ```ts interface UseCanvasOptions { showRulers?: boolean preserveDrawingBuffer?: boolean onReady?: () => void } function useCanvas( canvasRef: Ref, editor: Editor, options?: UseCanvasOptions, ): void ``` --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-canvas-input.md' description: >- Wire canvas pointer input, dragging, selection, resize, rotation, and tool behavior. --- # useCanvasInput `useCanvasInput()` connects pointer and mouse interaction to the editor canvas. It handles interaction concerns like: * selection * dragging * resize * rotation * panning * pen/draw flows * text editing interaction * scope-aware hit testing ## Usage This composable is typically paired with `useCanvas()` and hit-test helpers from the renderer. ```ts useCanvasInput( canvasRef, editor, hitTestSectionTitle, hitTestComponentLabel, hitTestFrameTitle, ) ``` ## Basic example ```ts const canvas = useCanvas(canvasRef, editor) useCanvasInput( canvasRef, editor, canvas.hitTestSectionTitle, canvas.hitTestComponentLabel, canvas.hitTestFrameTitle, ) ``` ## Practical examples ### Track cursor movement in canvas space ```ts useCanvasInput( canvasRef, editor, hitTestSectionTitle, hitTestComponentLabel, hitTestFrameTitle, (cx, cy) => { console.log(cx, cy) }, ) ``` ## Notes This composable is lower-level than most panel logic. It is best suited for editor shells and canvas containers. ## Related APIs * [useCanvas](./use-canvas) * [useEditor](./use-editor) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-text-edit.md' description: >- Manage DOM text editing, composition, formatting, and syncing for canvas text nodes. --- # useTextEdit `useTextEdit()` bridges DOM text input and the editor’s canvas text editing model. It coordinates: * textarea-backed text input * IME composition * caret blinking * delete/backspace behavior * formatting commands like bold/italic/underline * syncing text changes back into the graph ## Usage ```ts useTextEdit(canvasRef, editor) ``` ## Basic example Use this in the canvas owner component together with `useCanvas()` and `useCanvasInput()`. ## Practical examples ### Support formatting shortcuts `useTextEdit()` already handles keyboard formatting actions like bold, italic, and underline while text editing is active. ### Keep canvas and text editor in sync It updates graph text and style runs as the user types or edits formatted ranges. ## Notes This is a canvas/editor integration composable, not a generic text-field composable. ## Related APIs * [useCanvas](./use-canvas) * [useCanvasInput](./use-canvas-input) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-selection-state.md' description: >- Reactive selection-derived editor state for current node, count, and selection type. --- # useSelectionState `useSelectionState()` exposes reactive selection-derived state from the current editor. Use it when you need to render UI based on: * whether anything is selected * how many nodes are selected * the primary selected node * whether the current selection is an instance, component, or group ## Usage ```ts import { useSelectionState } from '@pairdraw/vue/editor/selection-state' const selection = useSelectionState() ``` ## Basic example ```vue ``` ## What it returns Useful values include: * `selectedIds` * `hasSelection` * `selectedNode` * `selectedCount` * `selectedNodeType` * `isInstance` * `isComponent` * `isGroup` * `canCreateComponentSet` ## Practical examples ### Show instance-only actions ```ts const { isInstance } = useSelectionState() ``` ### Enable component-set creation UI ```ts const { canCreateComponentSet } = useSelectionState() ``` ## Related APIs * [useSelectionCapabilities](./use-selection-capabilities) * [useEditorCommands](./use-editor-commands) * [useEditor](./use-editor) --- --- url: >- https://pairdraw.dev/programmable/sdk/api/composables/use-selection-capabilities.md description: Derive command-friendly booleans for selection-driven UI and actions. --- # useSelectionCapabilities `useSelectionCapabilities()` exposes reactive booleans for whether common editor actions are currently allowed. Use it when building: * menus * toolbars * keyboard shortcuts * action buttons * contextual panels ## Usage ```ts import { useSelectionCapabilities } from '@pairdraw/vue/editor/selection-capabilities' const caps = useSelectionCapabilities() ``` ## Basic example ```vue ``` ## Practical examples ### Gate menu entries ```ts const { canMoveToPage, canGoToMainComponent } = useSelectionCapabilities() ``` ### Enable zoom commands only when useful ```ts const { canZoomToSelection } = useSelectionCapabilities() ``` ## Related APIs * [useSelectionState](./use-selection-state) * [useEditorCommands](./use-editor-commands) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-editor-commands.md' description: 'Build menus, actions, and command-driven UI on top of the editor.' --- # useEditorCommands `useEditorCommands()` exposes a command-oriented layer over editor actions. It is useful when building: * app menus * context menus * toolbars * keyboard-command adapters * page-move submenus ## Usage ```ts import { useEditorCommands } from '@pairdraw/vue/editor/commands' const { commands, menuItem, runCommand, moveSelectionToPage, otherPages } = useEditorCommands() ``` ## Basic example ```ts const { menuItem } = useEditorCommands() const editMenu = [ menuItem('edit.undo', '⌘Z'), menuItem('edit.redo', '⇧⌘Z'), { separator: true }, menuItem('selection.delete'), ] ``` ## Practical examples ### Run a command directly ```ts const { runCommand } = useEditorCommands() runCommand('selection.duplicate') ``` ### Build a “move to page” submenu ```ts const { otherPages, moveSelectionToPage } = useEditorCommands() const items = otherPages.value.map(page => ({ label: page.name, action: () => moveSelectionToPage(page.id), })) ``` ## Related APIs * [useMenuModel](./use-menu-model) * [useSelectionState](./use-selection-state) * [useEditor](./use-editor) ## Main types ```ts type EditorCommandId = | 'edit.undo' | 'edit.redo' | 'selection.selectAll' | 'selection.duplicate' | 'selection.delete' | 'selection.group' | 'selection.ungroup' | 'selection.createComponent' | 'selection.createComponentSet' | 'selection.createInstance' | 'selection.detachInstance' | 'selection.goToMainComponent' | 'selection.wrapInAutoLayout' | 'selection.bringToFront' | 'selection.sendToBack' | 'selection.toggleVisibility' | 'selection.toggleLock' | 'selection.moveToPage' | 'view.zoom100' | 'view.zoomFit' | 'view.zoomSelection' ``` --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-menu-model.md' description: Build app and canvas menu models from the current editor state. --- # useMenuModel `useMenuModel()` builds higher-level menu structures on top of editor commands and selection state. It is useful when you want ready-to-render menu groups instead of composing commands manually. ## Usage ```ts import { useMenuModel } from '@pairdraw/vue/editor/menu-model' const { appMenu, canvasMenu, selectionLabelMenu } = useMenuModel() ``` ## Basic example ```ts const { canvasMenu } = useMenuModel() ``` Render `canvasMenu.value` into your context menu component. ## Practical examples ### App-style top menu `appMenu` groups entries into: * Edit * View * Object * Arrange ### Context menu with page moves `canvasMenu` includes dynamic items like “Move to page” based on current selection and available pages. ### Selection labels `selectionLabelMenu` exposes context-sensitive labels like: * `Hide` / `Show` * `Lock` / `Unlock` ## Related APIs * [useEditorCommands](./use-editor-commands) * [useSelectionState](./use-selection-state) * [useSelectionCapabilities](./use-selection-capabilities) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-position.md' description: >- Read and update selected node position, size, rotation, alignment, and flipping. --- # usePosition `usePosition()` is a control composable for position-related UI. It exposes selected-node values like: * `x` * `y` * `width` * `height` * `rotation` `x`, `y`, and `rotation` read as Figma's properties panel shows them: the top-left of the turned layer's box on the canvas, measured from its frame or page, and its counterclockwise angle. `updateProp('x' | 'y' | 'rotation', value)` moves or turns each selected node so it shows that value, turning about its center. `panelProp(key)` gives the shared value across a multi-selection, or `MIXED`. and actions like: * align * flip * rotate * scrub/update numeric properties ## Usage ```ts import { usePosition } from '@pairdraw/vue/controls/position' const position = usePosition() ``` ## Basic example ```ts const { x, y, width, height, rotation, updateProp, commitProp } = usePosition() ``` ## Practical examples ### Align selected nodes ```ts position.align('horizontal', 'center') position.align('vertical', 'min') ``` ### Flip selection ```ts position.flip('horizontal') position.flip('vertical') ``` ### Rotate selection ```ts position.rotate(90) ``` ## Related APIs * [useLayout](./use-layout) * [useAppearance](./use-appearance) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-layout.md' description: 'Work with auto-layout, sizing, padding, alignment, and grid tracks.' --- # useLayout `useLayout()` is the main control composable for layout-related panels. It exposes state and actions for: * flex vs grid mode * width/height sizing and editable derived dimensions * minimum and maximum size limits * padding * alignment * grid template track editing ## Usage ```ts import { useLayout } from '@pairdraw/vue/controls/layout' const layout = useLayout() ``` ## Axis sizing ```ts const { widthSizing, heightSizing, setAxisSizing, updateAxisSize, commitAxisSize, } = useLayout() setAxisSizing('width', 'HUG') setAxisSizing('height', 'FILL') ``` Connect `updateAxisSize()` and `commitAxisSize()` to a numeric field. Editing a Hug or Fill value switches only that axis to Fixed on the first actual mutation: ```vue ``` For one-step commit and Escape rollback across a sizing-mode change, variable detachment, and the numeric value, compose the NumberField with `BindableValue` using a provider that implements interaction batches. Merely focusing the field does not switch its sizing mode. ## Aspect ratio lock ```ts const { aspectRatioLocked, aspectRatioLockable, toggleAspectRatioLock } = useLayout() ``` `toggleAspectRatioLock()` locks the selected layer to its current proportions or unlocks it. While it is locked, `updateAxisSize()` changes both sides. `aspectRatioLockable` is false for a layer inside an instance, which keeps its component's lock. ## Size limits ```ts layout.addSizeLimit('minWidth') layout.setSizeLimitToCurrent('minWidth') layout.removeSizeLimit('minWidth') ``` ## Practical examples ### Toggle between uniform and individual padding UI ```ts layout.toggleIndividualPadding() ``` ### Update grid tracks ```ts layout.updateGridTrack('gridTemplateColumns', 0, { sizing: 'FIXED', value: 240 }) layout.addTrack('gridTemplateRows') ``` ### Change alignment ```ts layout.setAlignment('CENTER', 'MAX') ``` ## Related APIs * [LayoutControlsRoot](../components/layout-controls-root) * [BindableValue](../components/bindable-value) * [usePosition](./use-position) * [useEditor](./use-editor) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-constraints.md' description: Read and update resize constraints for eligible frame children. --- # useConstraints `useConstraints()` provides selection-derived horizontal and vertical constraint state plus undo-aware actions. ```ts import { useConstraints } from '@pairdraw/vue/controls/constraints' const constraints = useConstraints() constraints.setAxis('horizontal', 'STRETCH') constraints.togglePin('vertical', 'trailing', false) ``` * `active` requires every selected node to be an eligible child of a frame-like container. * `horizontal` and `vertical` return `MIN`, `CENTER`, `MAX`, `STRETCH`, `SCALE`, or `MIXED`. * Multi-selection updates are grouped into one undo entry. * Normal auto-layout children are excluded; absolutely positioned children remain eligible. Use `constraintPins()` and `toggleConstraintPin()` to build a custom accessible pin diagram without duplicating mode mapping. ## Related APIs * [ConstraintsControlRoot](../components/constraints-control-root) * [PositionControlsRoot](../components/position-controls-root) * [Property Panels guide](../../guides/property-panels) --- --- url: >- https://pairdraw.dev/programmable/sdk/api/composables/use-component-properties.md description: >- Read and edit variant, text, boolean, and instance-swap properties on instances. --- # useComponentProperties `useComponentProperties()` exposes compatible component properties for the selected instances and an undo-aware value action. ```ts import { useComponentProperties } from '@pairdraw/vue/controls/component-props' const { active, controls, setValue } = useComponentProperties() // Property IDs are stable Figma definition IDs when imported from .fig. setValue('12:34', 'Enabled') ``` Each item in `controls` contains: * `id` and `name` from the component property definition; * `type`: `VARIANT`, `TEXT`, `BOOLEAN`, or `INSTANCE_SWAP`; * `value`: a string or `MIXED`; * `options` for variant and instance-swap controls. `active` is true only when every selected node is an instance and each instance exposes the same ordered property IDs and types. Compatible multi-selection changes are grouped into one undo entry. For live text inputs, call `setTextValue(propertyId, value)` on each model update and `flush()` on blur or Enter. Text appears immediately, while rapid changes share an undo entry. Batches also finish after an idle pause, a selection/page change, or scope disposal. `setValue()` remains a discrete edit. Text and boolean properties update the referenced instance descendant. Instance-swap properties replace the referenced nested instance. Variant changes swap the main component and then reapply non-variant assignments, so custom labels, visibility, and nested swaps survive the change and its undo/redo cycle. Imported `.fig` definitions retain typed defaults, property references, assignments, and preferred instance-swap values. Missing swap targets remain explicit rather than silently selecting another component. ## Related APIs * [useSelectionState](./use-selection-state) * [useSharedStyleBinding](./use-shared-style-binding) * [Property Panels guide](../../guides/property-panels) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-appearance.md' description: >- Control visibility, opacity, corner radius, and smoothing for the current selection. --- # useAppearance `useAppearance()` is the appearance-focused control composable for property panels. It exposes selection-derived UI state for: * visibility * opacity * corner radius * corner smoothing as a normalized percentage * independent corner radii, including imported unequal-corner state * blend mode ## Usage ```ts import { useAppearance } from '@pairdraw/vue/controls/appearance' const appearance = useAppearance() ``` ## Basic example ```ts const { visibilityState, opacityPercent, cornerRadiusValue, cornerSmoothingPercent, showIndependentCorners, toggleVisibility, toggleIndependentCorners, } = useAppearance() ``` ## Practical examples ### Toggle selection visibility ```ts appearance.toggleVisibility() ``` ### Edit per-corner radii ```ts appearance.updateCornerProp('topLeftRadius', 12) appearance.commitCornerProp('topLeftRadius', 12, 8) ``` ### Edit corner smoothing ```ts appearance.updateCornerProp('cornerSmoothing', 0.75) appearance.commitCornerProp('cornerSmoothing', 0.75, 0) ``` Render the per-corner editor from `showIndependentCorners`. It accounts for both the explicit scene-node flag and imported nodes whose corner values differ. Multi-selection toggles and commits are grouped into one undo entry. ## Related APIs * [SDK API Overview](../) * [useLayout](./use-layout) * [useTypography](./use-typography) --- --- url: >- https://pairdraw.dev/programmable/sdk/api/composables/use-shared-style-binding.md description: 'Apply and detach local fill, stroke, text, effect, and grid styles.' --- # useSharedStyleBinding `useSharedStyleBinding(kind)` exposes the selected nodes' shared-style reference, compatible local style definitions, and undo-aware bind/detach actions. ```ts import { useSharedStyleBinding } from '@pairdraw/vue/controls/shared-style' const fillStyle = useSharedStyleBinding('fill') fillStyle.bind('1:120') fillStyle.unbind() ``` Supported kinds are `fill`, `stroke`, `text`, `effect`, and `grid`. * `active` requires every selected node to support the requested style domain. * `styleId` is the shared ID, `null`, or `MIXED`. * `styles` lists compatible local definitions imported with the document. * `bind(id)` applies supported style properties and the reference in one undo step. * `unbind()` keeps the resolved properties and removes only the reference. * Multi-selection changes are grouped into one undo entry. Manual edits to fills, strokes, supported text properties, effects, or layout grids automatically detach the matching style reference. Other style domains remain bound. Pairdraw currently consumes styles already present in a document. Creating, renaming, publishing, and synchronizing style libraries is outside this composable's scope. ## Related APIs * [useFillControls](./use-fill-controls) * [useStrokeControls](./use-stroke-controls) * [useTypography](./use-typography) * [useEffectsControls](./use-effects-controls) * [Property Panels guide](../../guides/property-panels) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-color-model.md' description: 'Build precise reactive color controls across RGB, HSL, HSB, and OkHCL.' --- # useColorModel `useColorModel()` is the shared color-state and conversion layer for custom color pickers. It accepts a scene-graph color, exposes Reka-compatible RGB/HSL/HSB values, and keeps optional OkHCL intent separate from the gamut-mapped preview color. The composable does not require an editor context and does not mutate the scene graph directly. Pass callbacks to connect it to your own state or persistence layer. ## Basic usage ```ts import { ref } from 'vue' import { useColorModel } from '@pairdraw/vue/controls/color-model' import type { Color } from '@pairdraw/scene-graph/primitives' const color = ref({ r: 0.25, g: 0.5, b: 0.9, a: 1 }) const model = useColorModel({ color, onUpdate: (nextColor) => { color.value = nextColor }, }) model.updateHSLChannel('s', 72) model.updateAlpha(0.8) ``` The returned `hex`, `rekaColor`, `rgb`, `hsl`, and `hsb` values are computed refs. Use `updateHex()` for hex input; it preserves the current alpha. RGB conversion keeps fractional channel precision rather than rounding through 8-bit values. ## Format state The built-in format identifiers are `hex`, `rgb`, `hsl`, `hsb`, and `okhcl`. The type remains extensible so applications can add another presentation format without changing the model. ```ts const model = useColorModel({ color, defaultFormat: 'hsl', onFormatChange: (format) => savePreferredFormat(format), }) model.setFormat('okhcl') ``` Pass `format` for controlled state. Without it, `setFormat()` updates local reactive state. ## OkHCL intent A scene-graph color contains a renderable RGBA value, but it cannot retain an out-of-gamut OkHCL source by itself. Pass the source intent separately and persist patches through `onUpdateOkHCL`: ```ts const model = useColorModel({ color, okhcl: () => storedOkhcl.value, onUpdateOkHCL: (patch) => { storedOkhcl.value = { ...storedOkhcl.value, ...patch } }, }) model.updateOkHCLChannel('c', 0.24) ``` When no OkHCL callback is supplied, OkHCL edits emit a gamut-mapped scene color through `onUpdate`. Conversion and gamut handling reuse Pairdraw's culori-backed core color APIs. ## Slider presentation `sliderPreview`, `sliderGradient`, `okhclSliderPreview`, and `okhclSliderGradient` provide the colors and CSS gradients needed by slider skins. They contain presentation data only; keyboard, pointer, and ARIA behavior belongs to the slider primitive. ## Update behavior * RGB values use the `0–255` presentation range. * HSL and HSB saturation/lightness/brightness use `0–100`. * OkHCL lightness and alpha use `0–1`; chroma is non-negative; hue wraps into `0–360`. * Alpha is preserved across color-space conversions. * No-op updates do not call mutation callbacks. * Editing hue on an achromatic color creates a visible color rather than remaining neutral. ## Related APIs * [ColorPickerRoot](../components/color-picker-root) * [ColorInputRoot](../components/color-input-root) * [useFillControls](./use-fill-controls) * [useStrokeControls](./use-stroke-controls) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-typography.md' description: >- Read and update font, alignment, case, truncation, and OpenType features for text nodes. --- # useTypography `useTypography()` is the text-property control composable for text editing panels. It works on the text layers in the selection: `nodes` holds them, `node` is the first, and every action changes all of them in one undo step, so a selection of text and other layers edits only the text. It exposes: * font family * font style: `faces`, the faces of the selected layers' family by the names their fonts give them (Avenir's Book and Roman apart), read from installed fonts and web font providers, every standard weight while a family's faces are unknown; `faceName`, the face the layers share or `MIXED`; and `setFace(style)`, which sets a face by its name * font size * formatting state * missing-font status * horizontal and vertical alignment, including justification * text case and direction * ending truncation and maximum lines * OpenType feature toggles * variable font axes (`axes`, `opticalSizeAuto`) * list style (`listType`, `null` when the paragraphs differ) and hanging lists * helpers for changing family, face, weight, alignment, and decorations * `merged(key)` and `fontFeature(tag)`, which return the shared value or `MIXED` ## Usage ```ts import { useTypography } from '@pairdraw/vue/controls/typography' const typography = useTypography() ``` ## Basic example ```ts const { fontFamily, fontWeight, fontSize, activeFormatting, setFamily, setFace, setWeight, setAlign, setVerticalAlign, setTextCase, setTruncation, setFontFeature, } = useTypography() ``` ## Practical examples ### Load and switch a font family ```ts const typography = useTypography({ fontLoader: { load: async (family, style) => { await myFontLoader(family, style) }, }, }) ``` ### Toggle formatting As in Figma, a family switch keeps each layer's weight and slant where the new family has them, otherwise the nearest weight with the same slant, and `toggleBold` or `toggleItalic` leave a layer alone when its family has no such face. ```ts typography.toggleBold() typography.toggleItalic() typography.toggleDecoration('UNDERLINE') typography.setTextCase('UPPER') typography.setVerticalAlign('CENTER') typography.setTruncation('ENDING') typography.setFontFeature('LIGA', false) ``` ### Make a list While the text is being edited, `setListType` and `setParagraphSpacing` change the paragraphs under the caret or selection; otherwise they change the whole text. `paragraphSpacing(field)` reads `listSpacing`, `paragraphSpacing`, or `paragraphIndent` for those paragraphs, `MIXED` when they differ, and `previewParagraphSpacing` shows a value while a field is dragged without an undo step. ```ts typography.setListType('UNORDERED') typography.setHangingList(true) typography.setParagraphSpacing('listSpacing', 8) ``` ### Set variable font axes `axes` lists the axes of the selected text's variable font, each with its `tag`, `name`, range, and the `value` it is drawn at (`MIXED` when the layers differ), and is empty for a static font or layers in different families. `previewAxis` shows a value while a field is dragged, `setAxis` sets it in one undo step, and `setOpticalSizeAuto` lets the optical size follow the font size or holds it. Changing weight, slant, or family puts the axes back at the style's own. ```ts typography.setAxis('wght', 560) typography.setOpticalSizeAuto(false) ``` ## Related APIs * [useTextEdit](./use-text-edit) * [useSelectionState](./use-selection-state) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-export.md' description: Manage export settings like scale and format for the current selection. --- # useExport `useExport()` is the export-panel composable for selected nodes. It manages: * export settings rows * selected node ids * export name labeling * supported scales and formats (`formats` ids and labeled `formatOptions`) ## Usage ```ts import { useExport } from '@pairdraw/vue/document/export' const exportState = useExport() ``` ## Basic example ```ts const { settings, nodeName, scales, formats, formatOptions, addSetting, updateScale, updateFormat, } = useExport() ``` ## Practical examples ### Add another export preset ```ts exportState.addSetting() ``` ### Change the first export to 2x WEBP ```ts exportState.updateScale(0, 2) exportState.updateFormat(0, 'webp') ``` ## Related APIs * [useSelectionState](./use-selection-state) * [useEditor](./use-editor) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-fill-controls.md' description: Fill-panel composable with default fill behavior. --- # useFillControls `useFillControls()` is the fill-property composable used by fill editing UIs. It adds a reusable default fill value. ## Usage ```ts import { useFillControls } from '@pairdraw/vue/controls/fill' const fills = useFillControls() ``` ## What it gives you It exposes: * `defaultFill` ## Practical examples ### Add a new fill row ```ts propertyList.add(fills.defaultFill) ``` ## Related APIs * [PropertyListRoot](../components/property-list-root) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-stroke-controls.md' description: >- Stroke-panel state and actions for alignment, sides, caps, joins, and miter limits. --- # useStrokeControls `useStrokeControls()` is the stroke-property composable used by stroke editing panels. It provides: * stroke align options * side presets like all, top, bottom, left, right, custom * default stroke data * helpers for per-side border weights * mixed-selection cap, join, and miter-limit state * undo-batched cap and join updates * preview and commit actions for miter-limit fields ## Usage ```ts import { useStrokeControls } from '@pairdraw/vue/controls/stroke' const strokes = useStrokeControls() ``` ## Basic example ```ts const { alignOptions, sideOptions, currentAlign, currentSides, selectSide } = useStrokeControls() ``` ## Practical examples ### Set stroke alignment ```ts strokes.updateAlign('INSIDE') ``` ### Limit a stroke to one side ```ts strokes.selectSide('TOP') ``` ### Edit stroke geometry ```ts strokes.setCap('ROUND') strokes.setJoin('BEVEL') strokes.updateMiterLimit(8) strokes.commitMiterLimit(8) ``` `advancedActive` is true only when every selected node has at least one stroke. `cap`, `join`, and `miterLimit` return the shared value or `MIXED` for a mixed selection. Alignment, sides, and border weights act on every selected node in one undo step. `currentAlign()` and `borderWeight(side)` return the shared value or `MIXED`; a node without strokes counts with the alignment it keeps for new strokes. ## Related APIs * [PropertyListRoot](../components/property-list-root) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-effects-controls.md' description: >- Effects-panel helpers for shadows, blurs, expansion state, and scrub/commit flows. --- # useEffectsControls `useEffectsControls()` is the effects-property composable used by effects panels. It provides helpers for: * default effects * shadow vs blur logic * expanded item state * scrub-preview editing * commit-on-finish updates * effect type and color changes ## Usage ```ts import { useEffectsControls } from '@pairdraw/vue/controls/effects' const effects = useEffectsControls() ``` ## Basic example ```ts const { effectOptions, createDefaultEffect, toggleExpand, scrubEffect, commitEffect } = useEffectsControls() ``` ## Practical examples ### Add a default effect ```ts const effect = effects.createDefaultEffect() ``` ### Preview scrub changes, then commit ```ts effects.scrubEffect(node, index, { radius: 12 }) effects.commitEffect(node, index, { radius: 12 }) ``` ## Related APIs * [PropertyListRoot](../components/property-list-root) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-selection-layout.md' description: >- Layout of a multi-selection as Figma shows it, with text resizing, flow, clip content, and spacing. --- # useSelectionLayout `useSelectionLayout()` reads and edits the layout of the selected layers the way Figma's panel does for several layers. Each value is the one the relevant layers share, `MIXED` when they differ, or `undefined` when no selected layer has it: * `textResize` — resizing of the selected text layers * `layoutMode` — flow, when every selected layer can hold an auto layout * `clipsContent` — clip content of the layers that can clip * `spacing` and `spacingAxis` — the gap between neighbours when the layers form one row or column Each action changes only the layers it applies to, in one undo step. ## Usage ```ts import { useSelectionLayout } from '@pairdraw/vue/controls/selection-layout' const layout = useSelectionLayout() layout.setTextResize('AUTO_HEIGHT') layout.setLayoutMode('VERTICAL') layout.toggleClipsContent() layout.setSpacing(16) ``` `setSpacing` keeps the first layer of the row in place and spaces the rest after it. ## Related APIs * [useLayout](./use-layout) * [useSelectionColors](./use-selection-colors) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-selection-colors.md' description: >- Figma's Selection colors list for the current selection, with an edit that recolours every paint using a colour. --- # useSelectionColors `useSelectionColors()` lists each solid fill and stroke colour of the selected layers and their descendants, most used first. Effect colours and colours bound to a variable are left out. `shown` is true when Figma shows the list: the Fill and Stroke sections can't already show every colour, because they differ across the selection or a selected layer has children. ## Usage ```ts import { useSelectionColors } from '@pairdraw/vue/controls/selection-colors' const selection = useSelectionColors() // Recolour every paint that uses the first colour. selection.replace(0, { color: { r: 0, g: 0.5, b: 1, a: 1 }, opacity: 1 }) ``` Edits made in quick succession, such as dragging in a colour picker, become one undo step. Call `begin()` when a row's picker opens and `finish()` when it closes to keep the list's order steady while the colour changes. ## Related APIs * [useSelectionLayout](./use-selection-layout) * [useFillControls](./use-fill-controls) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-mask.md' description: Read and update mask state for the selected node. --- # useMask `useMask()` provides headless state and actions for mask controls in a property panel. ## Usage ```ts import { useMask } from '@pairdraw/vue/controls/mask' const { active, maskType, setMaskType } = useMask() ``` * `active` is `true` when exactly one selected node is being used as a mask. * `maskType` is the selected node's `ALPHA`, `VECTOR`, or `LUMINANCE` mask type. * `setMaskType(type)` updates the active mask with undo support. Use the `selection.toggleMask` editor command to turn masking on or off so toolbar, context-menu, and keyboard behavior stays consistent. ## Related APIs * [useAppearance](./use-appearance) * [useEditorCommands](./use-editor-commands) * [SDK API Overview](../) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-variable-modes.md' description: Read and set the variable modes the selection or the current page shows. --- # useVariableModes `useVariableModes()` provides headless state and actions for Figma's Apply variable mode control: the collections a mode can be set for on the selection, or on the current page when nothing is selected, and the mode each one shows. ## Usage ```ts import { useVariableModes } from '@pairdraw/vue/controls/variable-modes' const { choices, applied, setMode } = useVariableModes() ``` * `choices` lists the collections with more than one mode that the selected layers use, through their own bindings or variables those alias; for a page, every such collection. Each has its `modes`, its `value` (the mode set on every target, `MIXED` when they differ, or `null` for Auto), and the `inherited` mode the targets show without one of their own. * `applied` is the part of `choices` with a mode set on at least one target, which a panel shows as rows. * `setMode(collectionId, modeId)` sets the mode on every target in one undo step; `null` clears it, so the targets inherit their parent's mode again. `variableModeChoices(editor, nodes)` and `setVariableMode(editor, nodes, collectionId, modeId)` do the same for any layers, outside a component. ## Related APIs * [useAppearance](./use-appearance) * [SDK API Overview](../) --- --- url: >- https://pairdraw.dev/programmable/sdk/api/composables/use-document-workspace.md description: 'Manage document lists, refreshes, lazy previews, and workspace events.' --- # useDocumentWorkspace `useDocumentWorkspace()` provides headless state for document browsers backed by local or remote storage. It manages: * initial, manual, focused-window, reconnect, and interval refreshes * deduplicated refresh requests and source invalidation events * lazy preview loading with bounded concurrency * preview object URL creation and cleanup * per-preview errors ## Usage ```ts import { useDocumentWorkspace } from '@pairdraw/vue/document/workspace' const workspace = useDocumentWorkspace({ source: { refresh: () => documentService.list(), loadPreview: (id) => documentService.loadPreview(id), subscribe: (listener) => documentService.subscribe(listener), }, refreshInterval: 60_000, }) ``` The source must return items with `id`, `name`, and `updatedAt`. A changed `updatedAt` value invalidates an existing or in-flight preview. ## Lazy previews Apply `previewDirective` to the element that should trigger loading, then resolve the current object URL with `previewURL()`: ```vue ``` When `IntersectionObserver` is unavailable, the directive loads the preview immediately. ## Errors `error` contains the latest document-list refresh failure. Preview failures are available by document ID through `previewErrors`; use `onPreviewError` when errors should also be reported to an application service. ```ts const workspace = useDocumentWorkspace({ source, onPreviewError(id, error) { reportPreviewError({ id, error }) }, }) ``` Calling `loadPreview(id)` retries a failed preview. Successful loads clear the corresponding preview error. ## Cleanup The composable revokes generated object URLs and unsubscribes from the source when its component unmounts. Call `clearPreviews()` when switching an external workspace or provider without unmounting the component. --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-page-list.md' description: 'Read pages and drive page switching, creation, deletion, and renaming.' --- # usePageList `usePageList()` is the page-management composable behind page list UIs. It exposes: * `pages` * `currentPageId` * `switchPage` * `addPage` * `deletePage` * `renamePage` ## Usage ```ts import { usePageList } from '@pairdraw/vue/primitives/PageList' const pageList = usePageList() ``` ## Basic example ```ts const { pages, currentPageId, switchPage, addPage } = usePageList() ``` ## Practical examples ### Switch pages ```ts switchPage(pageId) ``` ### Create a new page ```ts addPage() ``` ## Related APIs * [PageListRoot](../components/page-list-root) * [useMenuModel](./use-menu-model) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/composables/use-i18n.md' description: Read localized Pairdraw UI messages and switch the active SDK locale. --- # useI18n `useI18n()` is a compatibility aggregate returning reactive translation groups and locale controls. New components should import only the product-domain composables they need, rather than subscribe to every catalog. ```ts twoslash import { useSettingsMessages, useRenameMessages } from '@pairdraw/vue/i18n' const settings = useSettingsMessages() const rename = useRenameMessages() ``` Each domain composable returns a reactive ref. Read `.value` in script; Vue unwraps it in templates. See [Locale APIs](../advanced/locale-apis) for locale switching without the aggregate. ## Usage ```ts import { useI18n } from '@pairdraw/vue/i18n' const { menu, commands, panels, locale, availableLocales, localeLabels, setLocale } = useI18n() ``` ## Returns Translation refs: `ai`, `automation`, `code`, `collaboration`, `commands`, `common`, `credentials`, `diagnostics`, `editor`, `files`, `fonts`, `media`, `menu`, `pages`, `panels`, `recovery`, `rendering`, `rename`, `settings`, `storage`, `tools`, `updates`, `variables`, and `variableTypes`. Locale controls: `locale`, `availableLocales`, `localeLabels`, and `setLocale`. The former `dialogs` group, `useDialogMessages()`, and `dialogMessages` are removed in the development version after v0.14.0. Use the owning domain, such as `settings`, `rename`, or `recovery`, and update the corresponding message keys. ## Basic example ```vue ``` ## Notes * locale changes are reactive across all SDK message groups * the SDK also exports lower-level locale primitives when you need direct store access ## Related APIs * [useMenuModel](./use-menu-model) * [SDK Locale APIs](../advanced/locale-apis) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced.md' description: Lower-level and specialized APIs in @pairdraw/vue. --- # Advanced These APIs are public, but they are more specialized than the main component and composable surface. ## Selection and scene helpers * [useNodeProps](./use-node-props) * [useSceneComputed](./use-scene-computed) * [usePropScrub](./use-prop-scrub) ## Picker, variables, locale, and editor internals * [useColorVariableBinding](./use-color-variable-binding) * [useColorBindingProvider](./use-color-binding-provider) * [useGradientStops](./use-gradient-stops) * [useFontPicker](./use-font-picker) * [useOkHCL](./use-okhcl) * [useVariables](./use-variables) * [Locale APIs](./locale-apis) * [useToolbarState](./use-toolbar-state) * [useNodeFontStatus](./use-node-font-status) ## Editor-shell utilities * [useLayerDrag](./use-layer-drag) * [useInlineRename](./use-inline-rename) * [useCanvasDrop](./use-canvas-drop) * [extractImageFilesFromClipboard](./extract-image-files-from-clipboard) * [useViewportKind](./use-viewport-kind) * [toolCursor](./tool-cursor) ## Primitive context helpers * [useCanvasContext](./use-canvas-context) * [useLayerTree](./use-layer-tree) * [useToolbar](./use-toolbar) * [usePropertyList](./use-property-list) * [useNumberField](./use-number-field) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/use-node-props.md' description: Low-level selection and mixed-value helper for property panels. --- # useNodeProps `useNodeProps()` is the low-level property-panel helper behind higher-level composables like `useAppearance`, `useLayout`, and `useTypography`. Use it when you need mixed-value detection, multi-selection updates, array-item editing, or undo-aware property commits. ## Related APIs * [useAppearance](../composables/use-appearance) * [useLayout](../composables/use-layout) * [useTypography](../composables/use-typography) * [PropertyListRoot](../components/property-list-root) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/use-scene-computed.md' description: Convenience wrapper for scene-derived computed state. --- # useSceneComputed `useSceneComputed(fn)` is a thin computed wrapper used to make scene-backed derived state explicit in higher-level composables. Use it when you want intent-revealing computed state that clearly depends on editor scene data. ## Related APIs * [useSelectionState](../composables/use-selection-state) * [useSelectionCapabilities](../composables/use-selection-capabilities) * [useNodeProps](./use-node-props) --- --- url: >- https://pairdraw.dev/programmable/sdk/api/advanced/use-color-variable-binding.md description: Variable-binding helper for fill and stroke color editors. --- # useColorVariableBinding `useColorVariableBinding(kind)` exposes search, binding, and unbinding helpers for color variables used by fill and stroke editors. Use it when building color UIs that need to connect fills or strokes to design variables. ## Usage ```ts import { useColorVariableBinding } from '@pairdraw/vue/controls/color-variable-binding' const fillBinding = useColorVariableBinding('fills') const strokeBinding = useColorVariableBinding('strokes') ``` ## Related APIs * [useFillControls](../composables/use-fill-controls) * [useStrokeControls](../composables/use-stroke-controls) * [FillRoot](../components/fill-root) --- --- url: >- https://pairdraw.dev/programmable/sdk/api/advanced/use-color-binding-provider.md description: Pairdraw COLOR variable provider for BindableValue fields. --- # useColorBindingProvider `useColorBindingProvider()` adapts Pairdraw COLOR variables to the generic `BindingProvider` contract. It resolves current-mode colors, binds indexed paint paths, creates variables in a Colors collection, updates all collection modes when requested, and exposes editor undo transactions. Use it with `BindableValueRoot` and explicit targets such as `fills/0/color` or `strokes/0/color`. Picker focus and opening remain non-destructive; the consumer chooses when an actual color mutation begins and commits. ```ts twoslash import type { Color } from '@pairdraw/scene-graph/primitives' import { type BindingTarget, useColorBindingProvider } from '@pairdraw/vue/controls/binding-provider' const provider = useColorBindingProvider() const targets: BindingTarget[] = [ { nodeId: 'rectangle-id', path: 'fills/0/color' } ] const value: Color = { r: 0.2, g: 0.5, b: 0.9, a: 1 } provider.getState(targets) provider.resolve('variable-id') ``` The composable requires an editor provided by `provideEditor()`. ## Related APIs * [BindableValue](../components/bindable-value) * [FillSwatch](../components/fill-swatch) * [useColorModel](../composables/use-color-model) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/use-gradient-stops.md' description: Gradient-stop state and mutation helper for fill editors. --- # useGradientStops `useGradientStops(fill, onUpdate)` manages active-stop state, subtype switching, stop dragging, and color or opacity updates for gradient fills. Use it when building custom gradient editors beyond the packaged primitives. ## Related APIs * [GradientEditorRoot](../components/gradient-editor-root) * [GradientEditorBar](../components/gradient-editor-bar) * [GradientEditorStop](../components/gradient-editor-stop) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/use-font-picker.md' description: Searchable font-picker state and selection helper. --- # useFontPicker `useFontPicker(options)` manages available font families, search state, open state, and family selection for font-picker UIs. Use it when building custom font-picking UIs beyond `FontPickerRoot`. ## Related APIs * [FontPickerRoot](../components/font-picker-root) * [useTypography](../composables/use-typography) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/use-prop-scrub.md' description: Low-level helper for drag-to-scrub property updates with commit support. --- # usePropScrub `usePropScrub(editor)` coordinates live property updates during scrubbing and commits undo-aware changes when the interaction finishes. Use it when building numeric controls that scrub selected node properties directly. ## Related APIs * [NumberField](../components/number-field) * [useNodeProps](./use-node-props) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/use-layer-drag.md' description: Drag-and-drop wiring helper for layer tree reordering. --- # useLayerDrag `useLayerDrag(editor, indentPerLevel?)` wires pragmatic-drag-and-drop behavior for layer tree rows and maps drop instructions to editor reorder operations. Use it when extending or replacing the default layer-tree drag UI. ## Related APIs * [LayerTreeRoot](../components/layer-tree-root) * [LayerTreeItem](../components/layer-tree-item) * [useLayerTree](./use-layer-tree) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/use-inline-rename.md' description: Inline rename state and focus-management helper. --- # useInlineRename `useInlineRename(onCommit)` manages editing state, focus, outside-click handling, and keyboard behavior for inline rename flows. Use it in custom page lists, layer trees, or similar rename-in-place UIs. ## Related APIs * [PageListRoot](../components/page-list-root) * [LayerTreeItem](../components/layer-tree-item) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/use-toolbar-state.md' description: Presentation-oriented toolbar state helper for mobile category paging. --- # useToolbarState `useToolbarState()` returns mobile-category paging state and helpers like `goPrev()` and `goNext()` for responsive toolbar shells. Use it when building toolbar layouts on top of `ToolbarRoot`. ## Related APIs * [ToolbarRoot](../components/toolbar-root) * [ToolbarItem](../components/toolbar-item) * [useToolbar](./use-toolbar) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/use-node-font-status.md' description: Missing-font status helper for text nodes. --- # useNodeFontStatus `useNodeFontStatus(node)` returns missing-font information for a text-node getter. Use it in typography panels and warnings that need to surface unavailable font families. ## Related APIs * [useTypography](../composables/use-typography) * [TypographyControlsRoot](../components/typography-controls-root) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/use-canvas-drop.md' description: Image file drag-and-drop helper for canvas surfaces. --- # useCanvasDrop `useCanvasDrop(canvasRef, editor)` wires dragenter, dragover, dragleave, and drop handling so image files dropped on the canvas are placed into the scene. Use it when building custom canvas surfaces that accept image drops. ## Related APIs * [CanvasRoot](../components/canvas-root) * [CanvasSurface](../components/canvas-surface) * [extractImageFilesFromClipboard](./extract-image-files-from-clipboard) --- --- url: >- https://pairdraw.dev/programmable/sdk/api/advanced/extract-image-files-from-clipboard.md description: Clipboard utility for extracting accepted image files. --- # extractImageFilesFromClipboard `extractImageFilesFromClipboard(event)` filters clipboard files down to accepted image types used by the canvas drop flow. Use it when implementing paste-from-clipboard image workflows. ## Related APIs * [useCanvasDrop](./use-canvas-drop) * [useCanvas](../composables/use-canvas) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/tool-cursor.md' description: Helper that resolves the cursor string for an editor tool. --- # toolCursor `toolCursor(tool, override?)` maps an editor tool to the cursor the SDK should use, while still allowing an explicit override. Use it when building custom canvas shells or tool UIs that need consistent cursor behavior. ## Related APIs * [useCanvas](../composables/use-canvas) * [useEditorCommands](../composables/use-editor-commands) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/use-canvas-context.md' description: Primitive context helper for CanvasRoot descendants. --- # useCanvasContext `useCanvasContext()` reads the local canvas context provided by `CanvasRoot`. Use it inside descendants like `CanvasSurface` or your own custom canvas children. ## Related APIs * [CanvasRoot](../components/canvas-root) * [CanvasSurface](../components/canvas-surface) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/use-layer-tree.md' description: Primitive context helper for LayerTreeRoot descendants. --- # useLayerTree `useLayerTree()` reads the local layer-tree context provided by `LayerTreeRoot`. Use it inside custom layer-tree descendants that need access to tree items, selection state, expansion state, or row actions. ## Related APIs * [LayerTreeRoot](../components/layer-tree-root) * [LayerTreeItem](../components/layer-tree-item) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/use-toolbar.md' description: Primitive context helper for ToolbarRoot descendants. --- # useToolbar `useToolbar()` reads the local toolbar context provided by `ToolbarRoot`. Use it inside toolbar descendants that need access to tools, active state, or tool selection helpers. ## Related APIs * [ToolbarRoot](../components/toolbar-root) * [ToolbarItem](../components/toolbar-item) * [useToolbarState](./use-toolbar-state) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/use-property-list.md' description: Primitive context helper for PropertyListRoot descendants. --- # usePropertyList `usePropertyList()` reads the local property-list context provided by `PropertyListRoot`. Use it inside descendants that need controlled items, mixed-state information, or row-level handlers for fills, strokes, or effects. It does not access an editor. Pairdraw editor panels can use `useEditorPropertyList(propKey)` in an adapter component to connect the controlled primitive to selection, undo batching, and multi-node mutations. ## Related APIs * [PropertyListRoot](../components/property-list-root) * [PropertyListItem](../components/property-list-item) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/use-number-field.md' description: Context helper for custom NumberField descendants. --- # useNumberField `useNumberField()` reads the context provided by `NumberFieldRoot`. Use it inside custom field parts that need the canonical value, draft, state attributes, ARIA attributes, or actions. It throws when called outside a `NumberFieldRoot` subtree. ```ts import { useNumberField } from '@pairdraw/vue/primitives/NumberField' const field = useNumberField() field.actions.startEdit() ``` See [NumberField](../components/number-field) for the complete context and anatomy. --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/use-okhcl.md' description: Persist OkHCL intent for selected node fills and strokes. --- # useOkHCL `useOkHCL()` is the editor-aware adapter for OkHCL fill and stroke metadata. It reads stored color intent, updates nodes with undo, reports preview gamut information, and remembers the selected field format for each fill or stroke. Use [`useColorModel()`](../composables/use-color-model) for framework-agnostic conversion, channel editing, and slider presentation. Use `useOkHCL()` only where those edits need to be persisted to an Pairdraw editor. ## Usage ```ts import { useOkHCL } from '@pairdraw/vue/controls/okhcl' const okhcl = useOkHCL() const color = okhcl.getFillOkHCLColor(node, 0) okhcl.updateFillOkHCL(node, 0, { c: 0.2 }) ``` ## Format state ```ts const format = okhcl.getFieldFormat(node, 0, 'fill') okhcl.setFillFieldFormat(node, 0, 'okhcl') ``` Selecting `okhcl` initializes intent from the fill or stroke's current RGBA color. The returned `fieldOptions` can be used to build a format selector. ## Preview information ```ts const preview = okhcl.getFillPreviewInfo(node, 0) // { previewColorSpace, clipped } ``` Preview information reflects the document render color space and whether the stored OkHCL intent needed gamut mapping. ## Returns * `getFillOkHCLColor()` / `getStrokeOkHCLColor()` * `getFillPreviewInfo()` / `getStrokePreviewInfo()` * `getFieldFormat()` * `setFillFieldFormat()` / `setStrokeFieldFormat()` * `updateFillOkHCL()` / `updateStrokeOkHCL()` * `fieldOptions` ## Related APIs * [useColorModel](../composables/use-color-model) * [useFillControls](../composables/use-fill-controls) * [useStrokeControls](../composables/use-stroke-controls) * [ColorPickerRoot](../components/color-picker-root) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/use-variables.md' description: 'Read and mutate variable collections, variables, and variable values.' --- # useVariables `useVariables()` is the lower-level variables composable behind the higher-level variables editor helpers. Use it when you want direct control over collections, active modes, filtering, and CRUD operations without taking the full table/dialog abstraction. ## Usage ```ts import { useVariables } from '@pairdraw/vue/variables' const variables = useVariables() ``` ## Returns * `collections` * `activeCollectionId` * `activeCollection` * `activeModes` * `variables` * `searchTerm` * `setSearchTerm()` * `setActiveCollection()` * `addCollection()` * `renameCollection()` * `addVariable()` * `removeVariable()` * `renameVariable()` * `updateVariableValue()` --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/locale-apis.md' description: Lower-level locale stores and metadata exported by @pairdraw/vue. --- # Locale APIs In addition to `useI18n()`, the Vue SDK exports lower-level locale primitives for advanced integrations: * `locale` * `localeSetting` * `setLocale()` * `AVAILABLE_LOCALES` * `LOCALE_LABELS` Use these when you want direct store access, need to integrate locale state with a larger app shell, or want locale metadata without subscribing to the full `useI18n()` return object. ## Usage ```ts import { locale, localeSetting, setLocale, AVAILABLE_LOCALES, LOCALE_LABELS } from '@pairdraw/vue/i18n' ``` ## Notes * `locale` is the resolved active locale store * `localeSetting` is the persisted user preference store * `setLocale()` updates the preference and active locale together * `AVAILABLE_LOCALES` and `LOCALE_LABELS` are useful for custom pickers ## Related APIs * [useI18n](../composables/use-i18n) --- --- url: 'https://pairdraw.dev/programmable/sdk/api/advanced/use-viewport-kind.md' description: Read coarse mobile and desktop viewport flags for responsive editor shells. --- # useViewportKind `useViewportKind()` returns simple responsive flags used by Pairdraw editor UI. Use it when your shell needs a light abstraction over breakpoints instead of wiring `useBreakpoints()` directly. ## Usage ```ts import { useViewportKind } from '@pairdraw/vue/editor/viewport-kind' const { isMobile, isDesktop } = useViewportKind() ``` ## Returns * `isMobile` * `isDesktop` ## Related APIs * [useCanvas](../composables/use-canvas) --- --- url: 'https://pairdraw.dev/programmable.md' description: >- AI chat, CLI, JSX renderer, MCP server, and other automation surfaces built on the Pairdraw editor engine. --- # Automation Pairdraw treats design files as data. Every operation available in the editor — creating shapes, setting fills, managing auto-layout, exporting assets — is also available from the terminal, from AI agents, and from code. No plugins to install, no API keys, no waiting list. The editor UI and the automation interfaces use the same engine. If you can do it by clicking, you can do it by scripting. ## The bigger idea Pairdraw is not just meant to be a design app. It is also meant to be a toolkit: something you can embed into other products, wrap with your own UI, and use to build editing workflows that fit your own domain. That is why the automation surface matters. The app, the CLI, the AI tools, the JSX renderer, the MCP server, and the SDK all build on the same underlying editor engine. ## AI Chat The built-in assistant has access to 157 tools that cover the full surface of the editor. Describe what you want in natural language — "add a 16px drop shadow to all buttons", "create a card component with dark mode variant", "export every frame on this page at 2×". [AI Chat →](./ai-chat) ## Collaboration AI agents show their cursors on the canvas while they work, and the view follows them. Cloud documents on a self-hosted Pairdraw Cloud server are edited live by everyone who opens them, with cursors, follow mode, and CRDT sync. Peer-to-peer rooms are off in Pairdraw builds. [Collaboration →](./collaboration) ## Vue SDK Build Pairdraw-powered editors with the same Vue SDK the app uses internally. The SDK exposes editor context, canvas wiring, selection state, command models, property-panel composables, and headless primitives. [Vue SDK →](./sdk/) ## JSX Renderer Describe UI as JSX — the same syntax LLMs already know from React. A single call can create an entire component tree with frames, text, auto-layout, fills, and strokes. Compact, declarative, and diffable. Going the other direction, export any selection back to JSX with Tailwind classes — useful for handing off to development or feeding designs back into an LLM. [JSX Renderer →](./jsx-renderer) ## CLI Inspect, lint, export, and analyze design documents without opening the editor. List pages, search nodes, extract design tokens, catch layout or accessibility issues, and render to PNG — all from the terminal with machine-readable JSON output. The CLI also connects to the running desktop app via RPC, so you can script the editor while you're using it: open, save, and switch documents, undo, change settings, and call any MCP tool. [Inspecting Files](./cli/inspecting) · [Exporting](./cli/exporting) · [Analyzing Designs](./cli/analyzing) · [Scripting](./cli/scripting) · [Controlling the App](./cli/app-control) ## MCP Server Connect Claude Code, Cursor, Windsurf, or any MCP-compatible client to Pairdraw. The server exposes 157 shared tools plus 20 MCP-only (177 in total) for reading, creating, and modifying designs; the 157 shared tools are the same ones the built-in AI chat uses. Runs over stdio or HTTP with session support. [MCP Server →](./mcp-server) ## URL scheme The desktop app registers `pairdraw://`, so a published page — a Storybook story, a design review, a README — can link straight to a layer: ``` pairdraw://open?file=web/design/hikyo.pen&node=Button/Large/Default ``` `file` is a repository-relative path ending in `.pen` or `.fig`; absolute paths and `.` or `..` segments are refused. `node` is optional. Both values are URL-encoded — path separators may stay literal, but a literal `+` must be sent as `%2B` — and a repeated key takes its last value. The app matches `file` against the paths of the open tabs as a whole trailing segment sequence, and focuses that tab without re-reading the document, so a file that moved or turned unreadable since it opened still gets its layer selected. The first open tab whose path ends with the requested path wins, which matters when two checkouts have the same file open. Segments are compared the way the platform's filesystem does: ASCII-case-insensitively on macOS and Windows, exactly on Linux, so `Web/Design/hikyo.pen` and `web/design/hikyo.pen` are the same file on a Mac and two different ones on Linux. If no open tab matches, a file picker asks for the file once; the picked file must end with the same relative path, otherwise the link is cancelled. No path is joined onto a root and no filesystem access is granted beyond what the picker returns. A file the link actually opens — the picked one — joins the recent-files list like any other file you open; focusing a tab that was already open does not touch the list, because nothing was opened. With a node name, the app selects every layer carrying that exact name on the current page and zooms the view to the whole selection. When the current page has none, it switches to the first page that does, loading pages as needed. An unknown name shows a notice and leaves the document open. Opening a file and selecting layers is all the scheme can do. The web app takes the same link from its own address bar: ``` http://localhost:1420/?file=https://raw.githubusercontent.com/BadryansahBangsawan/pairdraw/master/tests/fixtures/pencil_button.pen&node=Button/Large/Default ``` Here `file` is an absolute `https:` URL ending in `.pen` or `.fig` — the web app has no filesystem, so a relative path, an `http:` URL or any other extension is refused with a console warning and nothing else. The extension is read off the URL's path, so a query string on the linked file changes nothing. A fragment is dropped before the fetch: it never reaches the server, so `…/hikyo.pen#a` and `…/hikyo.pen#b` open one tab, not two. `node` behaves exactly as above: the same exact-name selection and zoom, the same notice when no layer carries the name. Both values are URL-encoded, a literal `+` must be sent as `%2B`, and a repeated key takes its last value, as on the desktop. The link is handled on any route, so `/demo?file=…` works like `/?file=…`. The browser fetches the file cross-origin, so the host must allow it: `raw.githubusercontent.com` sends `Access-Control-Allow-Origin: *` and works. The request carries no credentials and refuses to follow redirects, which keeps an `https:` link from being bounced to a plaintext one — a `https://github.com///raw/...` URL redirects to `raw.githubusercontent.com` and is therefore refused, so link to the raw host directly. `file` and `node` are stripped from the address bar through the router as soon as they are read — before the fetch, and also when the link was refused — so a reload does not re-open the document, and neither a copied URL nor a later in-app navigation carries the link payload. A linked document is capped at 64 MiB: the body is counted as it streams in, not trusted from `Content-Length`, and the request is aborted the moment it goes over, with the link reporting that the file exceeds 64 MiB. A deployment that serves the app under a Content-Security-Policy must allow the linked host in `connect-src`, otherwise the fetch is blocked and the link reports that it could not open the file. On macOS the scheme belongs to the installed app bundle, so links reach an installed build and not a `tauri dev` process. On Windows and Linux the link arrives through the deep-link plugin, including when the app is not running yet: the link is queued at startup and handled once the editor is ready; on Linux the bundled desktop entry passes the link through `%U`. ## Why Open? Figma is a closed platform. Its MCP server still only offers a beta that writes to the canvas through `use_figma`; CDP browser access was killed in version 126. Design files live in a proprietary format on someone else's servers. Plugin development requires a custom runtime with limited APIs. Pairdraw is the alternative: open source, MIT licensed, local, with no seat or usage-based billing, works with any agent, reads and writes `.fig` files you own, and every operation is scriptable. Your design files are yours — inspect them, transform them, pipe them into CI, feed them to an LLM. No permission needed. --- --- url: 'https://pairdraw.dev/reference/cli.md' description: 'Complete reference for all pairdraw commands, options, and flags.' --- # CLI Reference Document commands accept a `.fig` file as a positional argument. When omitted, the CLI connects to the running desktop app via RPC. `documents`, `undo`, `redo`, and `settings` always act on the running app. A user error — a bad flag, a missing file, a refused combination — prints its message and exits 1 without a stack trace. Set `PAIRDRAW_DEBUG=1` to print the stack as well, which a crash needs to be read. ## info Show document info — pages, node counts, fonts, file size. ```sh pairdraw info [file] [--json] ``` | Option | Description | |--------|-------------| | `--json` | Output as JSON | ## tree Print the node hierarchy. ```sh pairdraw tree [file] [options] ``` | Option | Description | |--------|-------------| | `--page` | Page name (default: first page) | | `--depth` | Max depth (default: unlimited); a non-negative integer, other values are refused | | `--json` | Output as JSON | ## find Search nodes by name or type. ```sh pairdraw find [file] [options] ``` | Option | Description | |--------|-------------| | `--name` | Node name (partial match, case-insensitive) | | `--type` | Node type: `FRAME`, `TEXT`, `RECTANGLE`, `INSTANCE`, etc. | | `--page` | Page name (default: all pages) | | `--limit` | Max results (default: 100); a positive integer, other values are refused | | `--json` | Output as JSON | ## node Show detailed properties of a node. ```sh pairdraw node [file] --id [--json] ``` | Option | Description | |--------|-------------| | `--id` | **Required.** Node ID (e.g. `1:23`) | | `--json` | Output as JSON | `--json` reports the shape details a layer carries: per-corner radii (`topLeftRadius`, `topRightRadius`, `bottomRightRadius`, `bottomLeftRadius`) when the corners are independent and disagree, otherwise one `cornerRadius` when it is above zero; `isMask` and `maskType` while the layer masks; and a boolean layer's `booleanOperation`. A plain layer carries none of them. ## pages List all pages in the document. ```sh pairdraw pages [file] [--json] ``` | Option | Description | |--------|-------------| | `--json` | Output as JSON | ## variables List design variables and collections. ```sh pairdraw variables [file] [options] ``` | Option | Description | |--------|-------------| | `--collection` | Filter by collection name | | `--type` | Filter by type: `COLOR`, `FLOAT`, `STRING`, `BOOLEAN` | | `--json` | Output as JSON | ## tokens Print design variables as a stylesheet of CSS custom properties. Default mode values go in `:root`; every other mode overrides them under its condition, `[data-=""]` unless the mode names a selector or `@media` query. Aliases stay `var()` references. Tokens or modes that cannot be written are listed on stderr. ```sh pairdraw tokens [file] [options] ``` | Option | Description | |--------|-------------| | `--format` | `css` (default), `tailwind` for a Tailwind v4 `@theme` with a `@custom-variant` per mode, or `dtcg` for W3C design token files | | `--out`, `-o` | Folder the `dtcg` files are written to; required for that format | | `--collection` | Filter by collection name | | `--type` | Filter by type: `COLOR`, `FLOAT`, `STRING`, `BOOLEAN` | | `--json` | Output `{ css, tokenCount, issues }` as JSON | With `--import`, the command reads a local stylesheet's custom properties into the document's variables instead of printing them: `:root` holds each collection's default values, `.dark` and other selectors become modes, and Tailwind's `@theme` works too. ```sh pairdraw tokens app.fig --import theme.css --write ``` With `--project`, the command reads a local project folder instead of one stylesheet. Tailwind v4 `@theme` blocks and plain custom properties are imported. A shadcn/ui `:root` and `.dark` pair becomes one collection with Light and Dark modes. `tailwind.config.js` and other project JavaScript are reported and not run. A path that leaves the folder is refused, and a file over 1 MiB is skipped. Reading also stops, and reports it, after 200 files or 8 MiB in total. Component source is not imported. ```sh pairdraw tokens app.fig --project ./app --write ``` | Option | Description | |--------|-------------| | `--import` | Local CSS file to import as variables | | `--project` | Local project folder whose CSS variables are imported | | `--check` | Compare the document's variables with a stylesheet or project folder and list what differs; exits 1 on a difference | | `--sync` | Bring a stylesheet's or project folder's changes into the variables and remember the link; tokens also changed on the canvas are left unless `--conflicts` says otherwise | | `--conflicts` | With `--sync`, what a token changed on both sides takes: `skip` (default), `code`, or `canvas` | | `--write` | Write the import back to the input file | | `--output` | Write to a different file instead | `--out` is refused with `--import` or `--project`: it writes dtcg token files, while an import writes the document itself with `--write` or `--output`. ## check Check design documents in CI: render each frame at several widths, compare variables with the stylesheet they come from, and list the design memory's findings. Nothing is written back to a document. ```sh pairdraw check [files...] [options] ``` | Option | Description | |--------|-------------| | `--config` | Settings file (default: `.pairdraw/check.json`) | | `--base` | Folder holding the base revision's copies at the same paths, so only findings this change introduced fail | | `--out` | Report folder (default: `pairdraw-report`): `report.json`, `report.md`, `renders/` | | `--image-base` | URL prefix for the render images in `report.md` | | `--fail-on` | `error`, `warning`, or `never`; overrides the settings file | | `--json` | Output the report as JSON | Exit codes: `0` pass, `1` findings at the configured level, `2` the check could not run. See [CI Checks on a Pull Request](/programmable/cli/check) for the settings file and the GitHub Action. ## export Export to PNG, JPG, WEBP, SVG, PDF, PowerPoint, draw.io, JSX, HTML, `.fig`, or Storybook stories, or record the page's prototype as an MP4, GIF, or WebM video. The app does not offer PowerPoint or draw.io export; the CLI does. ```sh pairdraw export [file] [options] ``` | Option | Alias | Description | |--------|-------|-------------| | `--format` | `-f` | `png` (default), `jpg`, `webp`, `svg`, `pdf`, `pptx`, `drawio`, `jsx`, `tailwind-jsx`, `html`, `fig`, `storybook`; `mp4`, `gif`, and `webm` record the prototype | | `--output` | `-o` | Output file path (default: `.`); a directory for `storybook` (default: `-stories`) | | `--scale` | `-s` | Export scale (default: 1) | | `--quality` | `-q` | Quality 0–100, JPG/WEBP only (default: 90) | | `--page` | | Page name (default: first page; `fig`, `pptx`, and `storybook` default to every page) | | `--node` | | Node ID to export (default: all top-level nodes) | | `--style` | | JSX style: `pairdraw` (default), `tailwind` (same as `-f tailwind-jsx`) | | `--html` | | HTML mode: `fragment` (default), `standalone` | | `--css` | | HTML CSS output: `inline` (default), `tailwind` | | `--assets` | | Standalone HTML assets: `inline` (default), `external` | | `--fonts` | | Standalone HTML font output: `assets`, `none` (default) | | `--framework` | | Storybook framework: `react` (default), `vue`, `html` | | `--design-images` | | Storybook: render a PNG per variant for the Design panel (default: on; `--no-design-images` to skip) | | `--watch` | | Storybook: re-export whenever the document is saved | | `--beside` | | Storybook: write each document's stories into the document's own folder; the file argument can then be several files or a quoted glob | | `--thumbnail` | | Export a page thumbnail fitted to `--width` and `--height`; PNG, JPG, or WEBP. Cannot combine with `--node` (a thumbnail is a whole page) | | `--width` | | Thumbnail width (default: 1920) | | `--height` | | Thumbnail height (default: 1080) | | `--start` | | Video: top-level frame name or ID to play from (default: the selected or the page's first frame) | | `--fps` | | Video: frames per second (default: 30, or 15 for GIF; GIF plays at most 50) | | `--max-edge` | | Video: longest width or height in pixels (default: 1920, or 960 for GIF); `--scale` sets the start frame's size below it | | `--max-duration` | | Video: seconds the clip may last at most (default: 30, at most 120) | | `--tail` | | Video: seconds the last frame stays when the flow ends (default: 1) | | `--click` | | Video: a click to run, `:`; repeat it for more clicks | A video plays the prototype from its start frame as Play does, following each After delay and its Dissolve or Smart animate on a virtual clock rather than in real time, so the clip is the same on every run. It ends when play returns to the start frame (the GIF then loops), when nothing else happens, or at `--max-duration`. The command prints each step it recorded. MP4 (H.264) and WebM (VP9) are encoded with WebCodecs in the running app; from a file the CLI encodes them with `ffmpeg` when it is on the path (with `libx264` and `libvpx-vp9`), and otherwise records only GIF: ```sh pairdraw export hero.fig -f gif --start "Hero 1" -o hero.gif pairdraw export -f mp4 --start "Hero 1" -o hero.mp4 # app mode pairdraw export app.fig -f gif --click 1.5:"Buy button" --click 3:Close ``` ## libraries Manage filesystem catalogs of component libraries. ```sh pairdraw libraries list --root ./catalog pairdraw libraries publish components.fig --root ./catalog --id my-lib --name "My Library" pairdraw libraries seed --root ./catalog ``` | Subcommand | Description | |------------|-------------| | `list` | List the catalog's libraries; `--root` is required, `--json` prints machine-readable output | | `publish` | Publish a `.fig` document as a revision; `--id` and `--name` name the library, `--write` saves new asset keys back to the source, `--previous` expects a revision | | `seed` | Publish the built-in original **Pairdraw Basics** set (button, input, badge, card, avatar) into the catalog; does nothing when it is already there | ## import Import HTML/CSS/Tailwind into an editable Pairdraw document. ```sh pairdraw import page.html [options] ``` | Option | Alias | Description | |--------|-------|-------------| | `--format` | `-f` | Output format: `fig` (default), `json` | | `--output` | `-o` | Output file path (default: `.`) | | `--css` | | CSS file to apply before conversion | | `--css-text` | | Inline CSS text to apply before conversion | | `--tailwind` | | Tailwind utility candidates to compile and apply | | `--tailwind-file` | | File containing Tailwind utility candidates | | `--page-name` | | Scene graph page name (default: `DOM/CSS`) | | `--json` | | Print a machine-readable summary | Examples: ```sh pairdraw import card.html --css card.css -o card.fig pairdraw import card.html --tailwind "flex flex-col gap-3 w-80 p-6 rounded-xl bg-white" -o card.fig ``` ## eval Execute JavaScript with the Figma Plugin API. ```sh pairdraw eval [file] [options] ``` | Option | Alias | Description | |--------|-------|-------------| | `--code` | `-c` | JavaScript code to execute | | `--stdin` | | Read code from stdin | | `--write` | `-w` | Write changes back to the input file | | `--output` | `-o` | Write to a different file | | `--preview-output` | | Write a PNG of the current page after the script runs | | `--preview-scale` | | Preview scale from 0.1 to 4 (default: 1); the longest edge stays within 1280 pixels | | `--json` | | Output as JSON | | `--quiet` | `-q` | Suppress output | ## design-memory Show the document's design memory: the colors, fonts, font sizes, spacing, and corner radii agents may use and how each is enforced, its decisions, and its examples. See [Analyzing Designs](/programmable/cli/analyzing#design-memory). ```sh pairdraw design-memory [file] [--json] ``` ## analyze colors Analyze color palette usage across the document. ```sh pairdraw analyze colors [file] [options] ``` | Option | Description | |--------|-------------| | `--limit` | Max colors to show (default: 30) | | `--threshold` | Distance threshold for clustering similar colors, 0–50 (default: 15) | | `--similar` | Show similar color clusters | | `--json` | Output as JSON | ## analyze typography Analyze font family, size, and weight distribution. ```sh pairdraw analyze typography [file] [options] ``` | Option | Description | |--------|-------------| | `--group-by` | Group by: `family`, `size`, `weight` (default: show all styles) | | `--limit` | Max styles to show (default: 30) | | `--json` | Output as JSON | ## analyze spacing Analyze gap and padding values across auto-layout frames. ```sh pairdraw analyze spacing [file] [options] ``` | Option | Description | |--------|-------------| | `--grid` | Base grid size to check against (default: 8) | | `--json` | Output as JSON | ## analyze clusters Find repeated node patterns — potential components. ```sh pairdraw analyze clusters [file] [options] ``` | Option | Description | |--------|-------------| | `--limit` | Max clusters to show (default: 20) | | `--min-size` | Min node size in px (default: 30) | | `--min-count` | Min instances to form a cluster (default: 2) | | `--json` | Output as JSON | ## diff create Patch that turns one node tree into another, as JSX attribute changes plus moved, added, and removed children. Children match by name; see [Comparing designs](/programmable/cli/comparing) for the format. ```sh pairdraw diff create [file] --from --to [options] ``` | Option | Description | |--------|-------------| | `--from` | Source node ID | | `--to` | Target node ID | | `--depth` | Max tree depth (default: 10) | | `--json` | Output as JSON | ## diff jsx Structural diff between two nodes as design JSX. ```sh pairdraw diff jsx [file] --from --to [--json] ``` ## diff show Preview the patch that setting JSX attributes on a node would produce, without changing it. ```sh pairdraw diff show [file] --attributes '' [--json] ``` `--attributes` takes attributes as the JSX export writes them, such as `'w={200} bg="#FF0000"'`. ## diff apply Apply a patch from `diff create`, `diff show`, or `diff files`. Every node must still match the patch's old values unless `--force` is set, and nothing changes unless every hunk applies. ```sh pairdraw diff apply [file] [options] ``` | Option | Alias | Description | |--------|-------|-------------| | `--dry-run` | | Validate and list changes without applying | | `--force` | | Apply even when current values differ from the patch | | `--write` | `-w` | Write changes back to the input file | | `--output` | `-o` | Write to a different file | | `--json` | | Output as JSON | Pass `-` as the patch path to read it from stdin. ## diff visual Pixel diff between two rendered nodes, written as a PNG with changed pixels in red. ```sh pairdraw diff visual [file] --from --to --output [options] ``` | Option | Alias | Description | |--------|-------|-------------| | `--output` | `-o` | Diff PNG path | | `--scale` | | Render scale before the max-edge limit (default: 1) | | `--max-edge` | | Maximum image width or height (default: 1280) | | `--threshold` | | Color tolerance 0–1; smaller is stricter (default: 0.1) | | `--json` | | Output as JSON | ## diff files Structural diff of two documents, page by page. Pages match by name and nodes by name path, so two versions of a file compare even though their node IDs differ. Exits with status 1 when the documents differ and 2 when the options are invalid, such as a `--page` neither document has. ```sh pairdraw diff files [options] ``` | Option | Description | |--------|-------------| | `--page` | Compare only the page with this name | | `--depth` | Max tree depth below each page (default: unlimited) | | `--json` | Output as JSON | ## documents Manage documents (tabs) in the running app. See [Controlling the App](/programmable/cli/app-control). Commands share one `cli` session unless `PAIRDRAW_SESSION` names another. ```sh pairdraw documents list [--json] pairdraw documents open [--json] pairdraw documents new [--path ] [--json] pairdraw documents save [--path ] [--document-id ] [--json] pairdraw documents close [--save | --discard] [--path ] [--document-id ] [--json] pairdraw documents activate [--page-id ] [--json] ``` | Option | Description | |--------|-------------| | `--path` | `.fig` path to create or save to; relative to the current directory | | `--save` | `close`: save unsaved changes first | | `--discard` | `close`: close without saving; unsaved changes are lost | | `--document-id` | Document to use. Save defaults to the document this CLI session is targeting, or the one in front. Close defaults only to a document this session opened | | `--page-id` | Page to switch the activated document to | | `--json` | Output the result and target document as JSON | ## undo / redo Undo or redo the newest change made through the CLI or MCP in the running app. Fails when the newest change was made in the editor; see [Controlling the App](/programmable/cli/app-control#undo-and-redo). ```sh pairdraw undo [--document-id ] [--json] pairdraw redo [--document-id ] [--json] ``` ## settings Read and change editor settings in the running app by dotted key. Values parse as JSON, falling back to plain strings. ```sh pairdraw settings get [key] [--json] pairdraw settings set [--json] ``` See [Controlling the App](/programmable/cli/app-control#settings) for the available keys. ## tool List, describe, and call the editor tools that the MCP server exposes. ```sh pairdraw tool list [--json] pairdraw tool describe [--json] pairdraw tool call [file] [options] ``` | Option | Alias | Description | |--------|-------|-------------| | `--args` | | Tool arguments as a JSON object | | `--args-file` | | Read arguments from a JSON file, or `-` for stdin | | `--enforce-design-memory` | | Fail the call and write nothing when it uses a color or font the document's design memory refuses; without it, such values are warnings in the result | | `--write` | `-w` | Headless: write changes back to the input file | | `--output` | `-o` | Headless: write changes to a different file | | `--preview-output` | | Write a PNG of the current page after the tool changes the document | | `--preview-scale` | | Preview scale from 0.1 to 4 (default: 1); the longest edge stays within 1280 pixels | | `--document-id` | | App: target document | | `--page-id` | | App: target page | | `--json` | | Output as JSON | ## shell Open a document once and run tools on it line by line, with `save()` and `exit()`. Reads lines from stdin when it is not a terminal and exits with status 1 if any line failed. See [Controlling the App](/programmable/cli/app-control#interactive-shell). ```sh pairdraw shell [file] [options] ``` | Option | Alias | Description | |--------|-------|-------------| | `--output` | `-o` | Where `save()` writes without a path (default: the input file) | | `--preview-output` | | Write a PNG of the current page after each change | | `--preview-scale` | | Preview scale from 0.1 to 4 (default: 1); the longest edge stays within 1280 pixels | | `--document-id` | | App: target document | | `--page-id` | | App: target page | ## models List the AI providers and models the chat can use, and the ACP agents. ```sh pairdraw models [--provider ] [--json] ``` | Option | Alias | Description | |--------|-------|-------------| | `--provider` | `-p` | Only this provider or ACP agent, by ID (for example `openrouter` or `acp:codex`) | | `--json` | | Output as JSON | ## fonts Report fonts used by a document. ```sh pairdraw fonts [file] [options] ``` | Option | Description | |--------|-------------| | `--document-id` | Target Pairdraw document/tab ID when connected to the running app | | `--page-id` | Target page ID when connected to the running app | | `--json` | Output as JSON | ## selection Get current selection from the running app. ```sh pairdraw selection [options] ``` | Option | Description | |--------|-------------| | `--document-id` | Target Pairdraw document/tab ID when connected to the running app | | `--page-id` | Target page ID when connected to the running app | | `--json` | Output as JSON | ## formats List supported document and export formats. ```sh pairdraw formats [options] ``` | Option | Description | |--------|-------------| | `--json` | Output as JSON | ## convert Convert a document to another writable format. ```sh pairdraw convert [options] ``` | Option | Alias | Description | |--------|-------|-------------| | `--output` | `-o` | Output file path (default: `.`) | | `--format` | `-f` | Output format: `fig` (default), `pen`, or `drawio` | | `--font-policy` | | When a font of the document is missing: `warn`, `strict` (fail without writing), or `allow` (default: `warn`) | ## lint ```sh pairdraw lint [options] ``` Check a `.fig` or `.pen` document for consistency, structure, and accessibility issues, without opening the app. * `--preset ` — `recommended` (default), `strict`, or `accessibility` * `--rule ` — run one rule only; repeat for several * `--fix` — apply safe fixes: bind colours that match a variable and round to whole pixels; write the result with `-o` * `-o, --output ` — where `--fix` writes the fixed `.fig` * `--list-rules` — list the rules and exit * `--json` — print the report as JSON ``` pairdraw lint design.fig pairdraw lint design.fig --preset strict --json pairdraw lint design.fig --fix -o design.fixed.fig ``` ## agent Drive a document from a model: run, and see which tools it may call. ```sh pairdraw agent run [file] [--model ] [--json] pairdraw agent tools [--json] pairdraw agent list [--json] ``` | Subcommand | Description | |------------|-------------| | `run` | Run a design agent on a document through an OpenAI-compatible model | | `tools` | List the tools an agent run can call by default | | `list` | List the named agents a run can put in a team | ## query Query nodes using XPath selectors. A selector's tag is a node type, spelled as `find --type` spells it: `CANVAS`, `FRAME`, `RECTANGLE`, `ROUNDED_RECTANGLE`, `ELLIPSE`, `TEXT`, `LINE`, `STAR`, `POLYGON`, `VECTOR`, `BOOLEAN_OPERATION`, `GROUP`, `SECTION`, `COMPONENT`, `COMPONENT_SET`, `INSTANCE`, `CONNECTOR`, `SHAPE_WITH_TEXT`, `STICKY`, or `SCRIPT`. `//RECTANGLE` matches rectangles; `//RECT` matches nothing. ```sh pairdraw query [file] [selector] [options] ``` | Option | Description | |--------|-------------| | `selector` | XPath selector (e.g. `//FRAME[@width < 300]`, `//TEXT[contains(@name, "Label")]`) | | `--page` | Page name (default: all pages) | | `--limit` | Max results (default: 1000); a positive integer, other values are refused | | `--document-id` | Target Pairdraw document/tab ID when connected to the running app | | `--page-id` | Target page ID when connected to the running app | | `--json` | Output as JSON | --- --- url: 'https://pairdraw.dev/programmable/cli/inspecting.md' description: >- Browse node trees, search by name or type, and dig into properties from the terminal. --- # Inspecting Files The CLI lets you explore design documents without opening the editor. Every command also works on the live app — just omit the file argument. ::: tip Install ```sh npm install -g @pairdraw/cli # or bun add -g @pairdraw/cli ``` ::: ## Document Info Get a quick overview — page count, total nodes, fonts used, file size: ```sh pairdraw info design.fig ``` `--json` adds `diagnostics`, an array of `{ kind, count }` for what the Figma reader could not use, and `diagnosticComponents`, an array of `{ id, name, count, reasons }` grouping the same records under their component. A component that only fails through layers from a library that is not loaded carries `library-not-loaded`. A property path whose layers all exist in the file, but not under the instance that saved it, is saved state from other content: `diagnostics` keeps it with reason `stale-target` while `diagnosticComponents` leaves it out of the notice. The text view shows the counts and the top component names as a `Reader notes` line. Warnings never fail the command; they tell you a component, slot, or variable may look different. ## Font Diagnostics Report requested font faces, available sources, substitutions, and affected layers: ```sh pairdraw fonts design.fig pairdraw fonts design.fig --json pairdraw fonts --document-id tab-123 --page-id 0:1 ``` File mode checks all document pages using the CLI host's available fonts without downloading online fonts. Live mode reports the targeted app document/page, whose loaded fonts may differ from the CLI host. Faces are reported as `available`, `substituted`, or `unresolved`; JSON output includes `faithful`, `faces`, and `issues`. Use [export font policies](./exporting#font-substitution-policy) to warn about or reject substitutions during file-backed raster and PDF exports. ## Node Tree Print the full node hierarchy: ```sh pairdraw tree design.fig ``` ``` [0] [page] "Getting started" (0:46566) [0] [section] "" (0:46567) [0] [frame] "Body" (0:46568) [0] [frame] "Introduction" (0:46569) [0] [frame] "Introduction Card" (0:46570) [0] [frame] "Guidance" (0:46571) ``` ## Find Nodes Search by type: ```sh pairdraw find design.fig --type TEXT ``` Search by name: ```sh pairdraw find design.fig --name "Button" ``` Both flags can be combined to narrow results further. ## Query with XPath Use XPath selectors to find nodes by type, attributes, and tree structure: ```sh pairdraw query design.fig "//FRAME" ``` ### Useful patterns **By type:** ```sh pairdraw query design.fig "//TEXT" # All text nodes pairdraw query design.fig "//COMPONENT" # All components pairdraw query design.fig "//INSTANCE" # All instances ``` **By attributes:** ```sh pairdraw query design.fig "//FRAME[@width < 300]" # Frames under 300px wide pairdraw query design.fig "//*[@cornerRadius > 0]" # Rounded corners pairdraw query design.fig "//*[@visible = false]" # Hidden nodes pairdraw query design.fig "//TEXT[@fontSize >= 24]" # Large text pairdraw query design.fig "//*[@opacity < 1]" # Semi-transparent nodes ``` **By name and text content:** ```sh pairdraw query design.fig "//TEXT[contains(@name, 'Button')]" # Name contains 'Button' pairdraw query design.fig "//TEXT[contains(@text, 'Hello')]" # Text content contains 'Hello' ``` **By hierarchy:** ```sh pairdraw query design.fig "//SECTION//TEXT" # Text inside sections pairdraw query design.fig "//FRAME/TEXT" # Direct text children of frames pairdraw query design.fig "//COMPONENT_SET//INSTANCE" # Instances inside component sets ``` ### Queryable attributes `name`, `width`, `height`, `x`, `y`, `visible`, `opacity`, `cornerRadius`, `fontSize`, `fontFamily`, `fontWeight`, `layoutMode`, `itemSpacing`, `paddingTop`, `paddingRight`, `paddingBottom`, `paddingLeft`, `strokeWeight`, `rotation`, `locked`, `blendMode`, `text`, `lineHeight`, `letterSpacing` ### Example output ``` Found 5 nodes [0] [frame] "Logo 92×32" (0:9) [1] [frame] "logo-short-6 31×32" (0:10) [2] [frame] "wrapper 128×73" (0:20) [3] [frame] "pen-drawing 148×52" (0:21) [4] [frame] "surprised-emoji 32×32" (0:26) ``` ## Node Details Inspect all properties of a specific node by its ID: ```sh pairdraw node design.fig --id 1:23 ``` ## Pages List all pages in the document: ```sh pairdraw pages design.fig ``` Commands that work on one page — `tree`, `find`, `query`, `analyze overlaps`, `export`, `eval`, `tool call`, and the `diff` commands that compare layers — take it as `--page` with its name or `--page-id` with its ID from `pairdraw pages`, but not both. Both mean the same with a file and with the running app: ```sh pairdraw tree design.fig --page "Components" pairdraw find design.fig --page-id 0:46566 --type TEXT ``` ## Variables List design variables and their collections: ```sh pairdraw variables design.fig ``` ## Live App Mode When the desktop app is running, omit the file argument — the CLI connects via RPC and operates on the live canvas: ```sh pairdraw documents list # list open document/page IDs pairdraw tree # inspect the active live document pairdraw tree --document-id tab-123 --page-id 0:1 pairdraw eval --document-id tab-123 --page-id 0:1 -c "..." ``` Use `pairdraw documents list --json` in agent workflows, then pass `--document-id` and `--page-id` explicitly instead of relying on the visible active tab/page. To open, save, switch, and close documents, undo, change settings, or call any editor tool, see [Controlling the App](/programmable/cli/app-control). ## Lint Designs Check documents for naming, layout, structure, and accessibility issues: ```sh pairdraw lint design.fig pairdraw lint design.pen --preset strict pairdraw lint design.fig --rule color-contrast pairdraw lint design.fig --list-rules pairdraw lint design.fig --fix -o fixed.fig ``` Use `--json` for machine-readable output; each message carries its `fix` and `suggestions` as data. `--fix` applies the safe fixes — binding colors to the color variable they match and rounding geometry to whole pixels — and writes the result to the `.fig` file given with `-o`. ## Import Warnings When a command opens a `.pen` file that names something it cannot resolve, it prints a warning on stderr and keeps stdout for the result: variables the file does not define (read as their fallbacks), image files it cannot read (their fills are left out), and node types this reader does not know (read as placeholder frames). The command still succeeds, so check stderr when a file renders differently than expected. ```sh pairdraw info design.pen 2>warnings.txt ``` ## JSON Output All commands support `--json` for machine-readable output — pipe into `jq`, feed to CI scripts, or process with other tools: ```sh pairdraw tree design.fig --json | jq '.[] | .name' ``` --- --- url: 'https://pairdraw.dev/programmable/cli/exporting.md' description: >- Export document content to images, PDF, PowerPoint, draw.io, `.fig`, JSX, HTML, or Storybook stories, record a prototype as a video, with font-substitution policies for raster and PDF output. --- # Exporting Export designs from the terminal — raster images, vectors, PDF, editable PowerPoint, draw.io diagrams, `.fig` subsets, JSX code, HTML, Storybook stories, or a video of a prototype. The app in Pairdraw builds no longer offers PowerPoint or draw.io export; the CLI still writes both. ## Image Export ```sh pairdraw export design.fig # PNG (default) pairdraw export design.fig -f jpg -s 2 -q 90 # JPG at 2×, quality 90 pairdraw export design.fig -f webp -s 3 # WEBP at 3× pairdraw export design.fig -f svg # SVG vector pairdraw export design.fig -f pdf # PDF pairdraw export design.fig -f pptx # editable PowerPoint pairdraw export design.fig -f drawio # draw.io diagram pairdraw export design.fig -f fig --page "Page 1" # export one page as .fig pairdraw export design.fig -f fig --node 1:23 # export one node as .fig pairdraw export design.fig -f html --css tailwind # export an HTML fragment with Tailwind classes ``` Options: * `-f` — format: `png`, `jpg`, `webp`, `svg`, `pdf`, `pptx`, `drawio`, `jsx`, `tailwind-jsx`, `html`, `fig`, `storybook`; `mp4`, `gif`, or `webm` record a prototype ([Video Export](#video-export)) * `-s` — export scale (default: `1`) * `-q` — quality: `0`–`100` (JPG/WEBP only) * `-o` — output path * `--page` — page name, or `--page-id` — page ID * `--node` — specific node ID ## Video Export Record the page's prototype as a video: it plays from a top-level frame, follows each After delay interaction and its Dissolve or Smart animate on a clock of its own rather than in real time, and writes every frame, so the clip is the same on every run. ```sh pairdraw export flow.fig -f gif --start "Hero 1" # flow.gif beside the file pairdraw export flow.fig -f mp4 --start "Hero 1" -o hero.mp4 # needs ffmpeg from a file pairdraw export -f mp4 --start "Hero 1" -o hero.mp4 # the running app encodes it pairdraw export app.fig -f gif --click 1.5:"Buy button" --click 3:Close ``` * `--start` — top-level frame name or ID to play from (default: the selected frame, or the page's first frame) * `--fps` — frames per second (default: `30`, or `15` for GIF, which plays at most `50`) * `-s` — the start frame's size in the video (default: `1`); `--max-edge` — the longest side in pixels (default: `1920`; a GIF is at most `960`) * `--max-duration` — seconds the clip may last at most (default: `30`, at most `120`) * `--tail` — seconds the last frame stays when the flow ends (default: `1`) * `--click` — `:`, a click on a layer of the frame shown at that moment; repeat it for more clicks The clip ends when play returns to the start frame (a GIF then loops), when nothing else happens, or at `--max-duration`, and the command prints each step it recorded. A later frame of another shape is centred on the page color; an overlay shows over its frame behind a scrim. GIF works everywhere. MP4 (H.264) and WebM (VP9) are encoded with WebCodecs by the running app; from a file the CLI encodes them with `ffmpeg` when it is on the path with `libx264` and `libvpx-vp9`, and otherwise says which formats work. Set `PAIRDRAW_FFMPEG` to name a different ffmpeg binary; an empty or whitespace-only value falls back to `ffmpeg` from the path. Agents record the same video through the MCP `export_video` tool. ## Font Substitution Policy For file-backed PNG, JPG, WEBP, and PDF exports, and for `pairdraw convert`, choose how missing or substituted fonts are handled: ```sh pairdraw export design.fig -f pdf --font-policy strict pairdraw export design.fig -f png --font-policy warn pairdraw export design.fig -f webp --font-policy allow pairdraw convert design.pen --font-policy strict ``` * `warn` (default) — report substitutions and continue exporting. * `strict` — stop with a nonzero exit status if font preparation cannot faithfully resolve the requested faces. * `allow` — export without the additional font-fidelity check. Run [`pairdraw fonts`](./inspecting#font-diagnostics) first to inspect affected faces. Export preparation may use configured font providers, so its result can differ from the offline file diagnostic. `convert` loads fonts for `.pen`, draw.io, and Mermaid files, which store layout intent rather than sizes: it lays them out again with their text measured in their own fonts before writing, so `strict` stops it before anything is written. A Mermaid flowchart (`.mmd` or `.mermaid`) is laid out as it is read, its text measured in the fonts it is drawn in. This policy does not apply to exports from the running app, or to SVG, PowerPoint, JSX, HTML, and `.fig` exports. It checks font resolution, not complete visual equivalence with Figma. ## JSX Export Export as JSX with Tailwind utility classes: ```sh pairdraw export design.fig -f tailwind-jsx # or: -f jsx --style tailwind ``` Output: ```html

Card Title

Description text

``` Also supports `--style pairdraw` for the native JSX format (see [JSX Renderer](../jsx-renderer)). ## HTML Export Export as an HTML fragment with inline styles by default, or Tailwind utility classes: ```sh pairdraw export design.fig -f html pairdraw export design.fig -f html --css tailwind ``` Use `--html standalone` for a browser-openable HTML document with reset styles and a page wrapper. Standalone HTML is intended as a useful visual/code handoff, not a pixel-perfect renderer replacement: ```sh pairdraw export design.fig -f html --html standalone --css inline pairdraw export design.fig -f html --html standalone --css tailwind pairdraw export design.fig -f html --html standalone --css tailwind --assets external ``` Standalone Tailwind output is compiled during export; it does not depend on the Tailwind browser runtime. Use `--assets external` to write CSS and extracted image assets next to the HTML file. Use `--fonts assets` with external assets to resolve detected SceneGraph text fonts through Pairdraw's configured web-font providers and emit local `@font-face` files. HTML export writes each layer's name as a `data-name` attribute. `--no-layer-names` leaves the names out, and `--layer-ids` adds each layer's ID as `data-pairdraw-node-id` for tools that link markup back to the document. A font size Tailwind does not name as a step (such as 40px or 28px) exports as an arbitrary value, `text-[40px]`, rather than a utility like `text-10` that no stylesheet generates. Named steps and token-bound sizes keep their class. HTML export is available in file mode. ### Tokens in exported code HTML and Tailwind JSX write variable-bound properties as the design tokens they come from: a fill bound to `Primary` is `background-color: var(--color-primary)`, and in Tailwind `bg-primary`, or `bg-(--name)` for a token outside Tailwind's namespaces. A layer set to another mode gets that mode's attribute, such as `data-theme="dark"`, so the tokens resolve as the canvas draws them. A value stays literal where CSS would not reproduce it: the layer no longer draws the variable's value, the token is unitless where a length is needed, or the layer sits in a mode that only its own condition, such as a `@media` query, can select. Standalone HTML includes the stylesheet for the tokens it uses; for fragments and JSX, generate it with `pairdraw tokens` (below). ## Design Tokens Write the document's variables as CSS custom properties: ```sh pairdraw tokens design.fig > tokens.css pairdraw tokens design.fig --format tailwind > theme.css pairdraw tokens design.fig --collection Theme --type COLOR ``` Each collection's default mode goes in `:root`. Every other mode overrides the values that differ under its condition: `[data-theme="dark"]` for a Theme collection's Dark mode, or the selector or `@media` query the mode names. Aliases stay `var()` references and are declared again in each mode that changes what they point to, so switching `data-theme` on any element restyles everything built on it. ```css :root { --color-blue-500: #3b82f5; --color-primary: var(--color-blue-500); } /* Theme: Dark */ [data-theme='dark'] { --color-primary: var(--color-blue-300); } ``` `--format tailwind` puts tokens with a Tailwind v4 namespace (`--color-*`, `--spacing-*`, `--radius-*`, `--text-*`, …) in `@theme`, so `bg-primary` and `rounded-card` work, and adds a `@custom-variant` per mode, so `dark:bg-surface` follows the same condition. Import the file after `@import "tailwindcss";`. Names come from the variable's code syntax when it names a custom property (`--x` or `var(--x)`), otherwise from its name and type: `Blue/500` as a color is `--color-blue-500`. Tokens that cannot be written, such as boolean variables or a condition that is not a selector or query, are listed on stderr and left out. The command works in file mode and against the running app. ### W3C design tokens `--format dtcg` writes the variables and styles as [W3C design tokens](https://www.designtokens.org/tr/2025.10/format/) into a folder: ```sh pairdraw tokens design.fig --format dtcg --out tokens ``` Each collection mode is one file, `Theme/Light.tokens.json` and `Theme/Dark.tokens.json`, in the shape Figma imports as a mode: lengths in `px`, times in `s`, booleans as numbers marked `com.figma.type`, and aliases to another collection naming it in `com.figma.aliasData`. Text and effect styles become typography and shadow tokens in `styles.tokens.json`, kept apart because Figma's import refuses composite tokens; a text style field bound to a variable is written as a reference to that variable's token and read back as a binding. Pairdraw also records which collection each bound field's variable is in, so a path two collections share reads back to the right one; the export warns about such references, because other tools can't tell them apart. `tokens.resolver.json` is a DTCG resolver that switches each collection's modes and layers the rest, for tools such as Style Dictionary. Pairdraw's own fields, such as a token's `rem` unit, CSS name, scopes, or `clamp()` expression, and each mode's condition, ride in `$extensions["dev.pairdraw"]`, so the export reads back exactly. Import token files into a document with the `import_design_tokens` tool, passing each file's path and text as the tool's arguments: ```sh jq -Rs --arg p tokens/Tokens/Default.tokens.json '{files:[{path:$p,text:.}]}' \ tokens/Tokens/Default.tokens.json > args.json pairdraw tool call import_design_tokens design.fig --args-file args.json --write ``` It reads a file per mode grouped by folder, a resolver with the files it refers to, or a Tokens Studio file with `$themes`. Collections and modes with existing names, and variables and styles by name, are updated; the rest is added, and nothing is deleted. The result lists what was added, updated, and skipped, with the reason for each skip. ### Checking tokens against code `--check` compares the variables with a stylesheet or a project folder and lists every token that differs, without changing the document. It exits with status 1 when anything differs, so a CI job can fail when the design and the code drift apart: ```sh pairdraw tokens design.fig --check src/app.css pairdraw tokens design.fig --check . --json ``` A folder is read as `--project` reads it: Tailwind v4 `@theme`, shadcn/ui `:root` and `.dark`, and the stylesheet `components.json` names. Each line names the collection, variable, and mode, the value in code and on the canvas, and whether the token changed in code, on the canvas, on both, is new in code, or is gone from code. The `token_drift` tool reports the same for files passed as its arguments. `--sync` brings the code's changes into the document and remembers the link, with its path from the document's folder, so later checks and syncs know which side changed: ```sh pairdraw tokens design.fig --sync src/app.css --write pairdraw tokens design.fig --sync src/app.css --conflicts code --write ``` A value changed only in code, and a token new in code, always comes in. A value also changed on the canvas since the last sync is left as it is and listed, unless `--conflicts code` takes the code's value or `--conflicts canvas` keeps the canvas value. A token gone from code keeps its variable. The `sync_tokens` tool does the same for files passed as its arguments, and the variables dialog's Pull does it for a linked stylesheet, opening a review for the values only a person can decide. ## Storybook Export Generate one CSF3 `.stories.ts` file per component set or component: ```sh pairdraw export design.fig -f storybook # React stories in ./design-stories/ pairdraw export design.fig -f storybook --framework vue -o src/stories pairdraw export design.fig -f storybook --css tailwind # components styled with Tailwind pairdraw export design.fig -f storybook --framework html --page "Components" pairdraw export design.pen -f storybook -o src/stories --watch # re-export on every save pairdraw export 'src/**/*.pen' -f storybook --beside --watch # stories next to each design pairdraw export design.fig -f storybook --rules stories.json # stories and titles by rule ``` ### Fewer stories in the sidebar Each story file opens with a `Default` story, the variant the design shows at rest, with every control. Every other variant or state story is tagged `variant`, and each file is tagged `pairdraw` and `page:`, such as `page:icons`. Storybook's sidebar filter selects by these tags, and `.storybook/main.ts` can set what it shows by default, such as one story per component and no icons page: ```ts const config: StorybookConfig = { // … tags: { variant: { defaultFilterSelection: 'exclude' }, 'page:icons': { excludeFromSidebar: true } } } ``` ### Stories and titles by rule What the tags can't do, such as leaving components out or laying an icon set out as a gallery, a rules file decides. The export reads `pairdraw.stories.json` from the working directory when it is there, or the file `--rules` names, again on every export when watching: ```json { "rules": [ { "match": "**", "title": "Design system/{page}/{name}" }, { "match": "Icons/**", "stories": "gallery" }, { "match": "**/_*", "stories": "none" } ] } ``` A rule applies to every story file whose `/` path matches its glob, by the names in the document: the page's, and the component set's or component's, or the prefix of slash-named components, such as `Icons/icon`. Every matching rule applies in order, so a later rule overrides an earlier one, each field on its own. `generate: false` keeps static stories for a Vue or React export where it would generate a component, such as for an icon set. `stories` is `variants`, a story per variant or state, as without rules; `single`, the `Default` story alone; `gallery`, `Default` and a `Gallery` story laying every variant out with its name, for static stories; or `none`, which leaves the file out. `title` is the file's title, with `{document}`, `{page}`, `{name}`, and `{path}`, the title it would have, filled in; titles that end up the same are kept apart as titles always are. Rules match the document's names, never a renamed title, so renaming a file never changes which rules apply to it. ### Designs next to their stories Keep each component's design file in the component's folder and export with `--beside`: each document's stories, design images, and `.pairdraw-stories.json` manifest go into that document's own folder, next to the component's code. A Storybook `stories` glob such as `../src/**/*.stories.ts` in `.storybook/main.ts` then picks them up without further configuration. Pass several documents, or a quoted glob such as `'src/**/*.pen'` that Pairdraw expands itself (Node.js 22 or later). Several documents need `--beside` or `--output`; `--page` works with one document only. Documents are exported one after another, and when one fails the rest are still exported before the command exits with an error. `--watch` watches every matched document; a document created after the watch started needs another run. Stories are titled by the document's file name, and then the page when more than one page has components: `pricing.fig` gives `pricing/Plan picker`, so documents exported together keep their stories apart. Each variant of a component set becomes a story, and its variant properties become `select` controls, so switching a control shows the matching variant. A set with a behaviour gets the control's own props instead: a Switch or Checkbox has a `checked` boolean, a Toggle `pressed`, a Collapsible `open`, and `disabled` when the set draws a disabled state; hover, pressed, and focus stay stories of their own. Standalone components named with slashes, such as `Button/Primary` and `Button/Secondary`, are grouped into one `Button` file with a `Variant` control. A combination the design has no variant for throws a named error in Storybook rather than showing a different variant. Stories render the component as HTML with inline styles, like `-f html`, so they need no Pairdraw runtime; `--framework` (`react`, `vue`, or `html`) only changes the wrapper and the `Meta`/`StoryObj` import from `@storybook/react-vite`, `@storybook/vue3-vite`, or `@storybook/html-vite`. Text uses the document's font families: the export fetches their files from the web font providers the editor uses into `pairdraw//` with a `fonts.css` every story file imports, so stories draw in those fonts, never in a fallback first. The document's design variables go there too, as custom properties in a `tokens.css` every story file imports, so styles bound to variables resolve as the design draws them. A family no provider has, such as Menlo, falls back to the browser's fonts, which the export warns about; `--fonts none` ships no font files. Static stories don't export text, boolean, or instance-swap properties yet. With `--framework vue` or `--framework react`, every component set and standalone component becomes a real component instead, `.vue` or `.tsx` with a `.module.css` (with `--css tailwind`, Tailwind utilities in its markup, its states as variants such as `data-[state=checked]:`, for a project that builds Tailwind v4), except slash-named components grouped into one file, and any a rule sets `"generate": false` for, which keep static stories. A component without a behaviour is the design's own elements: its root is the element the design draws, a `div` for a frame, and it takes the root element's own props, such as `onClick` and `class`. Its variant properties are props it sets as `data-*` attributes, so a `State=hover` variant is a prop like any other; its boolean properties are boolean props that show or hide the layers bound to them; and its slot properties are content it shows in place of the design's, a named `` in Vue and a `ReactNode` prop in React, falling back to the design's content. A component whose behaviour is a Button, Switch, Checkbox, Toggle, Collapsible, Tabs, Radio group, Toggle group, Accordion, Slider, Progress, Number field, Text field, or Textarea is built on Reka UI or on Radix UI's `radix-ui` package, and its interaction states, such as hover and disabled, become real `:hover` and `data-disabled` styles. Its variants are compiled into a stylesheet keyed on the states Reka and Radix set (`data-state`, `data-disabled`, hover, and focus), and every other variant property is a prop the component sets as a `data-*` attribute. In Vue its value is a `v-model` such as `checked` or `open`; in React the component takes the Radix root's props, such as `checked`, `defaultChecked`, and `onCheckedChange`. Its text properties are string props, defaulting to the design's words, which the layers bound to them draw, with a text control in its stories. Tabs take the open tab as `value` (`v-model:value`, or `defaultValue` and `onValueChange` in React), named by each trigger's words as a slug, such as `account` or `password`, and starting on the first; each trigger and its panel are Reka's or Radix's `Tabs` parts around the design's layers, every trigger drawn like the design's other triggers and taking the first trigger's look while its tab is active, and the stories get a `select` control and a story per tab. A Radio group, Toggle group, or Accordion writes two components: the group, which chooses one item the same way, starting on the item the design draws on, and `Item` from its items' component set, built as the group's item primitive (`RadioGroupItem`, `ToggleGroupItem`, or `AccordionItem` with its trigger in a header) and taking the `value` it stands for. The group uses it once per item in its items slot, with each item's value, named by its label property or else its words, and its text values. A Slider, Progress, or Number field binds its number as `value` (`v-model:value`, or `defaultValue` in React, a list for Radix's slider), within the range its behaviour sets, starting where the design does; the slider's range and thumb and the progress indicator drop the place the design draws them at, since the value sets it, and stories get a range control and a story at each end. A Text field or Textarea draws its text layer as a native `input` or `textarea` binding `value`, which in React takes the component's props; when the design draws the field filled and empty, the empty field's words are the placeholder and its look the placeholder's, and the filled look shows while the field has text. Reka UI's number field draws the input and steppers in Vue; Radix has none, so React's is a native number input whose steppers change it by a step and which settles within its range when left. Focus on a slider's thumb or a field's input draws the control's focus state. A Radio is only generated as a group's item; a Toggle or Collapsible used on its own still becomes its own component. Inside a generated component, an instance of another component generated in the same export uses that component rather than drawing its layers: `` imported from `./Switch.vue` or `./Switch`, set to the variant, text, and `disabled` values the instance shows. A control the design draws on, such as a checked switch, starts on and stays operable: a local `ref` bound with `v-model` in Vue, `defaultChecked` in React. The parent only places it, so the control keeps its own look and state styles. Only an instance that draws exactly as its variant, apart from its property values and where its parent places it, uses the component; one with edited text no property sets, a fill of its own, or other changes draws its own layers, so the story keeps what the design shows. Instances of components not exported, or exported only as static stories, are drawn as before. A variant property whose default the document leaves empty starts at the default variant, the one in the set's top-left corner, which opens its stories. An icon placed from a set, unless its paths were edited, is Iconify's component, `` from `@iconify/vue` or `@iconify/react`, which loads the icon when shown. A layer filled with a shader plays it behind its content with the `shaders` library's `` from `shaders/vue` or `shaders/react`, each effect a child with the preset's props and telemetry off (`disableTelemetry`); browsers without WebGPU show nothing in its place. Its stories render the component, and a play function clicks the control and checks its state, so the Storybook project needs `reka-ui` or `radix-ui` installed, and `@iconify/vue` or `@iconify/react` when components hold icons, and `shaders` when layers fill with shaders. Stories carry `parameters.design` entries for [`@storybook/addon-designs`](https://github.com/storybookjs/addon-designs): * **Pairdraw** — when the document path is inside the current directory, an [`pairdraw://` link](../index#url-scheme) that opens the document in the desktop app and selects the variant, or its component set when another layer shares the variant's name. The scheme addresses layers by name, so a story whose variant and component names are both shared by other layers gets no link. * **Design** — a 2× PNG of the variant, written to `.design/` next to the story and referenced with `new URL(…, import.meta.url)`, so Vite bundles it. Copy the parameter onto the story of your own component to compare the implementation with the design. `--no-design-images` skips rendering; font substitution follows `--font-policy` as in raster export. `-o` names the output directory. A `.pairdraw-stories.json` manifest there records which document, as a path relative to the output directory, and which page generated each story and design image; commit it with the stories. An export replaces the files that a previous export of the same document generated there, including those of components since deleted or renamed; with `--page`, only that page's. It refuses, before changing anything, to overwrite any other file — a hand-written story, another document's, or a stray image. A one-page export whose file names shifted onto another page's stories asks for a full export instead. Without the manifest, existing stories count as someone else's, so remove them before exporting again. `--watch` keeps the command running and re-exports whenever the document is saved, so Storybook's hot reload follows the design; a save that cannot be read is reported and the watch continues. A missing `--page` or a `--font-policy strict` substitution still ends the command. ## Live App Mode Omit the file to export from the running app: ```sh pairdraw export -f png # export the selection in the active document pairdraw export --page "Components" -f png # export every layer of a page pairdraw export --node 1:23 -f png # export one layer, on any page ``` `--page` takes a page name and `--page-id` a page ID from `pairdraw pages`; either exports that page without switching the app to it. Add `--document-id` to export from a document other than the active one. Live app mode supports PNG, JPG, WEBP, SVG, and PDF. PowerPoint, JSX, HTML, Storybook, and `.fig` exports require a file argument. File-mode thumbnail export is not currently supported. --- --- url: 'https://pairdraw.dev/programmable/cli/analyzing.md' description: 'Audit colors, typography, spacing, and repeated patterns in .fig files.' --- # Analyzing Designs The `analyze` commands audit an entire design system from the terminal — find inconsistencies, extract the real palette, spot components waiting to be extracted. ## Colors ```sh pairdraw analyze colors design.fig ``` Finds every color in the file, counts usage, and shows a visual histogram: ``` #1d1b20 ██████████████████████████████ 17155× #49454f ██████████████████████████████ 9814× #ffffff ██████████████████████████████ 8620× #6750a4 ██████████████████████████████ 3967× ``` ## Typography ```sh pairdraw analyze typography design.fig ``` Lists every font family, size, and weight combination with usage counts. Useful for spotting one-off text styles that should be consolidated. ## Spacing ```sh pairdraw analyze spacing design.fig ``` Audits gap and padding values across auto-layout frames. Helps identify spacing scale inconsistencies — e.g. a stray `13px` gap among otherwise `8/16/24` values. ## Clusters ```sh pairdraw analyze clusters design.fig ``` Finds repeated node patterns that could be extracted into components: ``` 3771× frame "container" (100% match) size: 40×40, structure: Frame > [Frame] 2982× instance "Checkboxes" (100% match) size: 48×48, structure: Instance > [Frame] ``` ## Design Memory A document's design memory lists the colors, fonts, font sizes, spacing, and corner radii agents may use there, whether an edit with another value is undone or warned about, the decisions written down, and the frames pinned as examples. People set it in the Design panel with nothing selected: ```sh pairdraw design-memory design.fig pairdraw design-memory design.fig --json ``` `pairdraw lint` reports layers whose values break it. A person runs the CLI, so `pairdraw tool call` and `pairdraw eval` never undo an edit for the memory: values outside it come back as `design_memory` warnings (for `eval`, on stderr), and the command exits 0. Pass `--enforce-design-memory` to fail the call and write nothing when it uses a color or font the memory refuses, as in a CI check. `pairdraw agent` runs refuse such edits, as agents in the app are refused. ## JSON Output All analyze commands support `--json` for machine-readable output: ```sh pairdraw analyze colors design.fig --json ``` Pipe into `jq`, feed into CI checks, or use in scripts that enforce design token budgets. --- --- url: 'https://pairdraw.dev/programmable/cli/check.md' description: >- Run Pairdraw's design checks on the .fig and .pen files a pull request changes, and keep the result in one comment. --- # CI Checks on a Pull Request `pairdraw check` runs the three checks a design change needs on a list of documents and writes one report: a frame laid out at several widths, the variables compared with the stylesheet they come from, and the design memory's findings. It reads the files and never writes a design document, so a pull request can run it on every push. The repository ships a GitHub Action around it: `.github/actions/pairdraw-check`. ## The command ```sh pairdraw check designs/home.pen designs/settings.fig \ --out pairdraw-report \ --base .pairdraw-base ``` | Option | Meaning | | -------------------- | ------------------------------------------------------------------------------------------ | | `--config ` | Settings file, default `.pairdraw/check.json` | | `--base ` | The base revision's copies at the same paths, so only findings this change introduced fail | | `--out ` | Report folder, default `pairdraw-report` | | `--image-base ` | Prefix for the render images in `report.md`, where they are hosted | | `--fail-on ` | `error`, `warning`, or `never`; overrides the settings file | | `--json` | Print `report.json` to stdout | Exit codes: `0` when nothing fails at the configured level (including a run with no design files), `1` when findings do, `2` when the check could not run — a bad settings file, an unreadable document, or a frame that could not be rendered. A run that could not finish is never reported as a pass. ## What it checks * **Responsive renders.** Each frame on each page — and frames directly inside sections — is laid out at 375, 768 and 1280 px and rendered to a PNG, with text overflow, layers outside their frame, and overlapping siblings listed per width. Instances, invisible layers, and the layers inside a frame are skipped; the report counts what the frame limit left out. * **Token drift.** The document's variables are compared with `tokens.source` (a stylesheet, a project folder, or W3C token files) through the same link `pairdraw tokens --check` uses. * **Design memory.** The document's allowed colors, fonts, sizes, spacing, and radii are checked against every layer, exactly as the app's lint does. With `--base`, a finding the base revision already had is counted but does not fail, so a repository can adopt the check before cleaning old layers. ## Settings `.pairdraw/check.json`, every field optional, unknown keys refused: ```json { "checks": { "responsive": true, "designMemory": true, "tokens": true }, "responsive": { "widths": [375, 768, 1280], "maxFrames": 8, "maxWarnings": 20, "scale": 1, "maxEdge": 1280 }, "tokens": { "source": "src/styles/globals.css" }, "failOn": "error" } ``` ## The report `--out` holds `report.json` (every finding, every render's path), `report.md` (the same as a pull-request comment), and `renders/` with one PNG per frame and width. The report's first Markdown line is the marker ``, which the action uses to update its own comment instead of adding another. ## In GitHub Actions ```yaml name: Design checks on: pull_request permissions: contents: read pull-requests: write jobs: pairdraw: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 with: fetch-depth: 0 - uses: BadryansahBangsawan/pairdraw/.github/actions/pairdraw-check@v0.21.0 ``` The action installs the CLI, finds the pull request's changed `.fig` and `.pen` files, reads the merge base's copies from git, runs the command, uploads the report and renders as an artifact, and posts or updates one comment. A pull request that changes no design file updates the existing comment instead of opening a new one; the comment is cut to fit GitHub's 65,536-byte limit with the artifact line included, and `report.json` keeps every finding. Pin the action to a release tag so it installs the CLI of the same release. The action's README covers inputs, permissions, fork pull requests, and what the comment contains. --- --- url: 'https://pairdraw.dev/programmable/cli/comparing.md' description: 'Diff nodes and documents structurally and visually, and apply patches.' --- # Comparing Designs The `diff` commands compare two nodes, preview or apply changes as patches, render pixel diffs, and compare whole documents. Each node command works on a file or, without one, on the document open in the running app. ## Patches ```sh pairdraw diff create design.fig --from 1:23 --to 1:87 ``` Prints a patch that turns the first tree into the second. Its properties are the JSX attributes the [JSX export](../jsx-renderer#exporting-to-jsx) writes, so it covers everything the export does. Children match by name, and a reordered child reads as one move: ```diff @@ /Card #1:23 -rounded={8} +rounded={12} @@ /Card/Header #1:24 -bg="#FFFFFF" +bg="#F4F4F5" @@ /Card/Badge #1:26 moved to 0 @@ /Card/Note #1:27 removed @@ /Card/Price added to #1:23 at 3 +$9 ``` Each hunk names a node by path, for reading, and by ID, which locates it. `-` lines hold the old attribute values and `+` lines the new ones; an added node is its JSX. `diff show` previews setting attributes on a node without changing it, and prints the patch: ```sh pairdraw diff show 1:24 design.fig --attributes 'bg="#F4F4F5" rounded={8}' > header.diff ``` `diff apply` applies a patch to the document whose IDs it names. Every node must still have the patch's old values unless `--force` skips that check, and nothing changes unless every hunk applies, so a patch never half-applies: ```sh pairdraw diff apply header.diff design.fig --dry-run # validate first pairdraw diff apply header.diff design.fig --write # save in place pairdraw diff apply header.diff design.fig -o out.fig # save elsewhere ``` Updates change only the fields their attributes set, so node IDs, instance links, and state JSX does not describe stay intact. Removed nodes are deleted and added nodes are rendered from their JSX. ## JSX diff ```sh pairdraw diff jsx design.fig --from 1:23 --to 1:87 ``` Compares two subtrees as a line diff of their design JSX, for reading rather than applying. ## Visual diff ```sh pairdraw diff visual design.fig --from 1:23 --to 1:87 --output diff.png ``` Renders both nodes at the same scale and writes a PNG with changed pixels in red over a faded copy of the source. The report includes the changed pixel ratio and the changed region in source-node coordinates. `--scale` and `--max-edge` bound the render the same way `export_image` does; `--threshold` sets the color tolerance. ## Comparing documents ```sh pairdraw diff files before.fig after.fig pairdraw diff files before.fig after.fig --page "Mobile" --json ``` Compares two documents page by page. Pages match by name and nodes by name path, so two versions of a file compare even though node IDs differ; the patch applies to the first document. Patches do not add or remove pages: a page only one document has is listed by name and status instead. Like `diff(1)`, the command exits with status 1 when the documents differ. To see these diffs in `git diff` and `git log`, set it up as Git's diff driver for `.fig` files ([Versioning Designs with Git](./git)). ## Agents The same operations are available as the `diff_create`, `diff_jsx`, `diff_show`, `diff_apply`, and `diff_visual` tools for the built-in AI chat and MCP clients. `diff_visual` returns its image to the model, so an agent can confirm that an edit touched only the intended region. --- --- url: 'https://pairdraw.dev/programmable/cli/git.md' description: >- Configure Git to show readable diffs of .fig files with pairdraw diff files, a textconv outline, and git difftool. --- # Versioning Designs with Git A `.fig` file is binary, so `git diff` and `git log -p` only report that it changed. With the `pairdraw` CLI installed, Git can show what changed instead: [`pairdraw diff files`](./comparing#comparing-documents) compares two versions page by page and prints the changes as a patch. There are three ways to wire it in. The commands below configure the current repository; add `--global` to `git config` to configure every repository. | Setup | Used by | Shows | | --- | --- | --- | | [Diff driver](#diff-driver) | `git diff`; `git log -p` and `git show` with `--ext-diff` | the patch `diff files` prints | | [Textconv](#textconv) | `git log -p` and `git show`; `git diff` when no diff driver is set | a line diff of an outline of the layers | | [Difftool](#difftool) | `git difftool` | the patch, one file at a time | All three start from a `.gitattributes` entry at the root of the repository that gives `.fig` files a diff driver named `fig`: ```text *.fig diff=fig ``` ## Diff driver Git runs a diff driver's command with seven arguments, `path old-file old-hex old-mode new-file new-hex new-mode`, and treats any status other than 0 as a failure. `diff files` takes two documents and exits with 1 when they differ, as `diff(1)` does, so a short script sits between them. Save it as `git-diff-fig` somewhere on your `PATH` and make it executable: ```sh #!/bin/sh # Git runs an external diff driver as: path old-file old-hex old-mode new-file new-hex new-mode path=$1 old=$2 new=$5 echo "diff --pairdraw a/$path b/$path" if [ "$old" = /dev/null ]; then echo "new file" exit 0 fi if [ "$new" = /dev/null ]; then echo "deleted file" exit 0 fi pairdraw diff files "$old" "$new" status=$? # 1 means the documents differ; only 2, trouble, is passed on to Git. if [ "$status" -eq 1 ]; then exit 0 fi exit "$status" ``` ```sh chmod +x git-diff-fig git config diff.fig.command git-diff-fig ``` `git diff` now prints the patch for each changed `.fig` file. After a larger title and new body text in the Card of the [design system tutorial](/user-guide/design-system), it begins: ```diff diff --pairdraw a/design-system.fig b/design-system.fig @@ /Components/Card/Title #387261504:30 -size={18} +size={20} @@ /Components/Card/Content/Body #387261504:32 -text="Slots hold content that each card chooses for itself." +text="Pick a plan that fits your team." @@ /Examples/Light/Card/Title #0:4 -size={18} +size={20} ``` `git log` and `git show` use a diff driver only when asked, as `git log -p --ext-diff -- design.fig`. The patch is the one [Comparing Designs](./comparing#patches) describes: each hunk names a layer by its path and by its ID in the older version, so `pairdraw diff apply` can apply the patch to that version. A page only one version has is reported on stderr instead. ## Textconv A textconv command turns one version of a file into text, and Git diffs that text line by line. It is what `git log -p` and `git show` use by default, and Git can cache it per version. This script prints an outline of every page, one layer per line, with its type, name, size, and text. It uses [`pairdraw eval`](./scripting) and [`jq`](https://jqlang.org); save it as `fig-textconv` on your `PATH`: ```sh #!/bin/sh # Print a document as an outline of its layers, one per line, for Git's textconv. pairdraw eval "$1" --json --code ' const lines = [] const walk = (node, depth) => { const size = depth > 0 && "width" in node ? ` ${Math.round(node.width)}×${Math.round(node.height)}` : "" const text = node.type === "TEXT" ? ` ${JSON.stringify(node.characters)}` : "" lines.push(`${" ".repeat(depth)}${node.type} ${JSON.stringify(node.name)}${size}${text}`) if ("children" in node) for (const child of node.children) walk(child, depth + 1) } for (const page of figma.root.children) walk(page, 0) return lines ' | jq -r '.[]' ``` ```sh chmod +x fig-textconv git config diff.fig.textconv fig-textconv git config diff.fig.cachetextconv true ``` The same change in the outline: ```diff @@ -4,10 +4,10 @@ CANVAS "Components" TEXT "Label" 44×17 "Button" COMPONENT "Variant=Secondary" 76×37 TEXT "Label" 44×17 "Button" - COMPONENT "Card" 320×173 - TEXT "Title" 272×22 "Card title" - SLOT "Content" 272×34 - TEXT "Body" 272×34 "Slots hold content that each card chooses for itself." + COMPONENT "Card" 320×158 + TEXT "Title" 272×24 "Card title" + SLOT "Content" 272×17 + TEXT "Body" 272×17 "Pick a plan that fits your team." ``` When the diff driver's `command` is also set, `git diff` uses the command, and the outline appears in `git log -p` and wherever `--no-ext-diff` is given. Change the script to print what your team reviews, such as fills or component properties; a stable outline makes a readable diff. `cachetextconv` keeps each version's outline in Git's notes, so a large file is read once. ## Difftool `git difftool` runs a tool once per changed file and leaves `git diff` as it is. Define a tool that runs `diff files` on the two versions: ```sh git config difftool.pairdraw.cmd 'pairdraw diff files "$LOCAL" "$REMOTE"' ``` ```sh git difftool --no-prompt --tool=pairdraw HEAD~1 -- '*.fig' git difftool -y -t pairdraw main...my-branch -- design.fig ``` The pathspec keeps other files out of it. A diff driver set with `diff.fig.command` takes precedence over a difftool for `.fig` files, so use one or the other. Leave out `--trust-exit-code`: `diff files` exits with 1 whenever the versions differ. ## Notes * The CLI reads every version it compares, so diffing a large file takes as long as opening it twice headlessly. `cachetextconv` saves that for versions already seen. * Layers match across versions by their name path, so a renamed layer shows as removed and added. * `.pen` files are JSON, so Git already diffs them as text. --- --- url: 'https://pairdraw.dev/programmable/cli/app-control.md' description: >- Open, save, switch, and close documents, undo and redo, change settings, call any editor tool in the running app or in an interactive shell, and list AI models from the CLI. --- # Controlling the App While the desktop app is running, the CLI drives it over the same automation bridge as the [MCP server](/programmable/mcp-server). Every command on this page except headless `tool call` needs the running app. ## Documents Each open tab is a document with a stable ID. List them, then pass `--document-id` (and `--page-id`) to aim a command at a background tab without switching to it: ```sh pairdraw documents list --json pairdraw tree --document-id tab-123 --page-id 0:1 ``` Open, create, save, and close documents: ```sh pairdraw documents open designs/landing.fig # opens in a new tab pairdraw documents new --path designs/draft.fig # empty document, saved to the path pairdraw documents save # the document this session targets, or the one in front pairdraw documents save --document-id tab-123 pairdraw documents save --document-id tab-123 --path designs/copy.fig pairdraw documents close --document-id tab-123 pairdraw documents close --document-id tab-123 --save # or --discard ``` Relative paths resolve against the shell's working directory. These commands never open a dialog in the app, because nobody may be there to answer it. `save` without `--document-id` saves the document this CLI session is targeting, or the document in front. `close` without `--document-id` closes only a document this session opened. Closing a document with unsaved changes fails unless you pass `--save` or `--discard`, and saving a document that has never been saved needs `--path`. Each command prints the document and page it acted on; with `--json` it prints `{ "result", "target" }`, so a script can read the new document's ID from `target.documentId`. Set `PAIRDRAW_SESSION` to keep two CLI agents apart; without it, every command shares the `cli` session. To bring a tab to the front, optionally on a specific page: ```sh pairdraw documents activate tab-123 --page-id 0:4 ``` ## Undo and redo Step back through changes made through the CLI and MCP, like **Edit → Undo** and **Edit → Redo**: ```sh pairdraw undo --document-id tab-123 pairdraw redo --document-id tab-123 --json ``` ```json { "result": { "applied": true, "label": "Set opacity", "scope": "document" }, "target": { "documentId": "tab-123", "documentName": "Landing", "pageId": "0:1", "pageName": "Page 1" } } ``` When there is nothing to undo or redo, the command says so and `result.applied` is `false`. The editor has one history, shared by you and every automation client, so **Edit → Undo** in the app steps back through any change, newest first. Automation is narrower: `undo` and `redo` only act on a step that the CLI or MCP made, and only while it is the newest one. If the newest change was made in the editor, the command fails and leaves it alone, so an agent can't revert your work. They also fail while the document is in vector edit mode, whose history belongs to the editing session. Each CLI or MCP command that edits the document is one undo step. An `eval` script is recorded against its target page: if it switches `figma.currentPage` and edits another page, those edits are not part of the undo step. ## Settings Read and change editor settings by dotted key: ```sh pairdraw settings get pairdraw settings get appearance.theme pairdraw settings set appearance.theme light pairdraw settings set editing.snapping.pixelGrid false pairdraw settings set chat.maxAgentSteps 100 ``` Values are read as JSON when they parse (`false`, `100`, `"auto"`) and as plain strings otherwise. Invalid keys and values are rejected without changing anything. | Key | Values | |-----|--------| | `appearance.theme` | `dark`, `light`, `auto` | | `appearance.language` | `en`, `de`, `es`, `fr`, `id`, `it`, `ja`, `pl`, `ru`, `zh-CN` | | `appearance.animations` | `system`, `off` | | `appearance.accent` | JSON object: `{"kind":"preset","preset":"green"}` with `pairdraw` (the default), `blue`, `purple`, `pink`, `red`, `orange`, `yellow`, `green`, `graphite`, or `{"kind":"custom","color":"#FF6600"}` | | `editing.snapping.geometry` | `true`, `false` | | `editing.snapping.objects` | `true`, `false` | | `editing.snapping.pixelGrid` | `true`, `false` | | `rendering.canvasMode` | `retained`, `tiled` (applies after a reload) | | `recovery.enabled` | `true`, `false` | | `chat.reasoningDisplay` | `collapsed`, `while-thinking`, `expanded` | | `chat.maxAgentSteps` | integer 1–1000 | | `chat.changePreviewSize` | `off`, `small`, `medium`, `large` | | `designCheck.preset` | `recommended`, `strict`, `accessibility` | | `designCheck.disabledRules` | JSON array of rule IDs, e.g. `["no-default-names"]`; see `pairdraw lint --list-rules` | Credentials, AI models, MCP connections, storage, and tool access are deliberately not available here: an automation client can't read secrets or grant itself access. ## Calling tools Every editor tool the MCP server exposes is also available from the CLI. List them, inspect a tool's arguments as JSON Schema, and call it with a JSON object: ```sh pairdraw tool list pairdraw tool describe set_fill pairdraw tool call set_fill --args '{"id":"0:5","color":"#2563eb"}' pairdraw tool call set_fill --document-id tab-123 --args-file fill.json echo '{"name":"Icons"}' | pairdraw tool call create_page --args-file - ``` Pass a file to run a tool headlessly instead. Changes to a file are kept only with `--write` (back to the input) or `--output`: ```sh pairdraw tool call create_page design.fig --args '{"name":"Icons"}' --write pairdraw tool call get_page_tree design.fig --json ``` For multi-step edits, [`eval`](./scripting) runs a whole script against the same Figma-compatible API, and `shell` runs tools one line at a time. Pass `--preview-output` to write a PNG of the current page after a tool changes the document. The preview is drawn by `export_image`, headless or in the app. `--preview-scale` sets its scale, from 0.1 to 4, and the longest edge stays within 1280 pixels: ```sh pairdraw tool call create_shape design.fig --args '{"type":"RECTANGLE","x":0,"y":0,"width":120,"height":80}' \ --write --preview-output preview.png ``` A tool that only reads, or one that returns an error, writes no preview. If the page has nothing visible, or the renderer cannot draw it, the command warns and keeps the change. ## Interactive shell `shell` opens a document once and keeps it loaded while you run tools on it, one per line. Each tool sees the changes the previous ones made, and nothing is written until you call `save()`: ```sh pairdraw shell design.fig --preview-output preview.png ``` ```text design.fig> create_page {"name": "Icons"} design.fig> switch_page({"page": "Icons"}) design.fig> create_shape {"type": "ELLIPSE", "x": 0, "y": 0, "width": 48, "height": 48} design.fig> save() design.fig> exit() ``` | Line | Effect | |------|--------| | ``, ` {...}`, `({...})` | Run a tool from `tool list` with a JSON object of arguments | | `tools()` | List the tools | | `help()`, `help("")` | Show the shell commands, or a tool's description | | `save()`, `save("copy.fig")` | Save as `.fig` to the input file, the `--output` path, or the given path | | `preview()`, `preview("page.png")` | Write a PNG of the current page now | | `exit()` | Leave the shell | Tab completes tool names. A failing line prints its error and the shell carries on. Ctrl+C clears a half-typed line; on an empty line, Ctrl+C and Ctrl+D leave as `exit()` does. With unsaved changes, leaving asks you to save first, and a second `exit()`, Ctrl+C or Ctrl+D discards them. `save()` writes `.fig` only, so a `.pen` or `.html` input needs a `.fig` path, either `--output` or `save("name.fig")`. When standard input is not a terminal, the shell reads one line at a time from it and exits at the end of the input or at `exit()`. The command exits with status 1 if any line failed: ```sh printf '%s\n' 'create_page {"name": "Icons"}' 'save()' | pairdraw shell design.fig -o out.fig ``` Without a file, `shell` sends each line to the document this CLI session is targeting, or to the one `--document-id` names. There, `save()` saves that document like `documents save`. ## AI models `models` lists the AI providers the chat can use and the models each one offers, with its default model. ACP agents such as Claude Code and Codex are listed too; they run their own models. ```sh pairdraw models pairdraw models --provider openrouter pairdraw models --json ``` --- --- url: 'https://pairdraw.dev/programmable/cli/scripting.md' description: >- Execute JavaScript with a Figma-compatible Plugin API to query, batch-modify, and generate designs. --- # Scripting `pairdraw eval` runs JavaScript against a Pairdraw document with a Figma-compatible `figma` global. Use it for headless batch edits, inspection, fixture setup, and automation without opening the editor UI. ## Basic usage ```sh pairdraw eval design.fig -c "return figma.currentPage.children.length" ``` The `-c` flag accepts JavaScript. Its last expression is the result, so `return` is optional; `await` works at the top level. A script whose last statement is not an expression, such as a declaration, has no result and prints nothing. ```sh pairdraw eval design.fig -c " const frame = figma.createFrame() frame.name = 'Card' frame.resize(300, 200) frame.layoutMode = 'VERTICAL' frame.itemSpacing = 12 return { id: frame.id, name: frame.name } " ``` ## Variable formulas Use `pairdraw.setVariableFormula(collectionName, variableName, source, modeName?)` to replace a variable's definition with a formula. It validates before changing the document and returns the resolved value. Omitting the mode name edits the collection's default mode. ```js pairdraw.setVariableFormula('Spacing', 'large', '{base} * 2') pairdraw.setVariableFormula('State', 'visible', '{viewport} > 1024 and not {loading}') pairdraw.setVariableFormula('Copy', 'greeting', 'if({compact}, "Hi", "Hello, " + {name})') ``` References use variable names or `{Collection::variable}` and are stored as stable IDs. Formulas use stored units, so lengths are in pixels. See [Variables](/user-guide/variables) for operators and export limitations. ## Variable bindings Figma's `node.setBoundVariable(field, variable)` binds with Figma's field names and type rules. Use `pairdraw.bindVariable(node, field, variable)` to bind a layer field to a variable from `figma.variables` the way the layer panel does, and `pairdraw.unbindVariable(node, field)` to let it go; the field keeps the value the variable last gave it. Fields use Pairdraw's names, such as `text`, `visible`, `opacity`, `paddingLeft` or `fills/0/color`. Bindings follow the layer panel, which takes more than Figma's `setBoundVariable`: text content takes a text or number variable, a number shown as text, and visibility a boolean or a text variable that shows the layer unless it is empty or reads `false`, `no` or `off`. ```js const [price] = figma.variables.getLocalVariables('FLOAT') const label = figma.currentPage.findOne((node) => node.name === 'Price') pairdraw.bindVariable(label, 'text', price) ``` ## Query nodes ```sh pairdraw eval design.fig -c " return figma.currentPage .findAll((node) => node.type === 'FRAME' && node.name.includes('Button')) .map((button) => ({ id: button.id, name: button.name, width: button.width, height: button.height })) " ``` ## Modify and save Use `--write` / `-w` to write changes back to the input file: ```sh pairdraw eval design.fig -c " figma.currentPage.children.forEach((node) => { node.opacity = 0.5 }) " --write ``` Use `--output` / `-o` to write to a new file: ```sh pairdraw eval design.fig -c "figma.currentPage.name = 'Updated'" -o updated.fig ``` Use `--preview-output` to write a PNG of the page the script leaves current, after it runs: ```sh pairdraw eval design.fig --stdin --write --preview-output preview.png < transform.js ``` ## Read scripts from stdin ```sh cat transform.js | pairdraw eval design.fig --stdin --write ``` ## One page of a large file A `.fig` script loads every page before it runs, which takes a while for a file with tens of pages. `--page` with a page name, or `--page-id` with an ID from `pairdraw pages design.fig`, loads only that page, besides the first page every file opens on, and runs the script on it as `figma.currentPage`. Other pages have no layers until the script loads them, as in Figma's dynamic-page mode: `page.loadAsync()`, `figma.setCurrentPageAsync(page)`, `figma.getNodeByIdAsync(id)` and `figma.loadAllPagesAsync()` load them. `figma.getNodeById(id)`, and tools that take layer IDs, find layers on loaded pages only, and `getNodeByIdAsync` cannot find a layer inside an instance on a page not loaded yet. `--write` and `--output` save every page, loaded or not. Removing a variable unbinds only layers on loaded pages, so a script that removes one should load every page first. ```sh pairdraw eval design.fig --page "Components" -c "return figma.currentPage.children.length" ``` ## Live app mode Omit the file path to run against the currently open document in the desktop app: ```sh pairdraw eval -c "return figma.currentPage.name" ``` The desktop app must be running with a document open. ## Output By default, non-TTY output is JSON. Use `--json` to force JSON output: ```sh pairdraw eval design.fig -c "return figma.currentPage.children.map((n) => n.name)" --json ``` Use `--quiet` / `-q` to suppress output when only writing a file. ## The `pairdraw` API Next to `figma`, scripts get `pairdraw`: what Pairdraw adds to the Figma Plugin API, in the same style. The same global is available to the `eval` tool and the running app's automation. A main component or component set can [behave as a Reka UI control](/user-guide/components#behaviours-and-preview). Bind it by its own property and slot names: ```sh pairdraw eval design.fig -w -c ' const set = figma.currentPage.findOne((n) => n.type === "COMPONENT_SET" && n.name === "Switch") const behaviour = pairdraw.setBehaviour(set, "switch") .bindValue("value", "State") // On and Off guessed from the variants .bindPart("thumb", set.findOne((n) => n.name === "Thumb")) // the frame becomes a slot behaviour.states = "Interaction" behaviour.missing ' ``` * `pairdraw.setBehaviour(node, kindOrSpec)` replaces a component's behaviour: a kind alone, or a spec such as `{ kind: "slider", parts: { track: "Track", thumb: "Thumb" }, numbers: { value: { min: 0, max: 10 } } }`. It returns the behaviour. * `pairdraw.getBehaviour(node)` reads one, or `null`; a variant reads its set's. * A behaviour has `kind`, `spec` (by name), `missing` (required values and parts still unbound), and `states`, and `bindValue(valueId, property, { on, off })`, `bindPart(partId, slotNameOrFrame)`, `setNumber(valueId, { min, max, step, default })`, and `remove()`. * `pairdraw.behaviourKinds` lists every kind with the values and parts it binds. * `pairdraw.createSlot(frame)` makes a frame of a main component a slot and returns its name. Names the component does not have fail with an error that lists the ones it has. Comments people leave with the Comment tool are part of the document, so scripts and agents can read the feedback on a file, act on it, and answer: ```sh pairdraw eval design.fig -w -c ' for (const comment of pairdraw.getComments({ resolved: false })) { console.log(comment.author, comment.node?.name, comment.text) comment.reply("Bumped the title to 24px", { author: "Claude" }).resolve() } ' ``` * `pairdraw.getComments(filter)` lists threads oldest first: all of them, or `{ resolved: false }` for open ones, `{ page }` for one page's, `{ author }` for those a person started or replied to. * `pairdraw.addComment(text, { node, page, x, y, author })` pins a comment on a layer, which it follows, or at a point of a page; the current page by default. `author` is `"Agent"` when left out. * A comment has `id`, `text` (Markdown), `author`, `createdAt`, `resolved`, `page`, `node` (the top-level layer it is pinned to), `position`, and `replies`, and `reply(text, { author })`, `resolve()`, `reopen()`, and `remove()`. `pairdraw.getComment(id)` finds one. Statuses mark where a section, frame, component, or instance stands, from the document's own list such as Draft, In review, or Ready for dev: ```sh pairdraw eval design.fig -w -c ' const checkout = figma.currentPage.findOne(n => n.name === "Checkout") pairdraw.setStatus(checkout, "Ready for dev") pairdraw.statuses.map(status => status.name) ' ``` * `pairdraw.statuses` lists the document's statuses in order, each with `name`, `color` (`#RRGGBB`), and `figma`, the status Figma shows for it (`READY_FOR_DEV`, `COMPLETED`, or `null`). * `pairdraw.getStatus(node)` reads the name of the status a layer shows, or `null`, also while a section around it shows its own. * `pairdraw.setStatus(node, name)` sets one by name, and `null` clears it. Only sections, frames, components, component sets, and instances directly on a page or in a section take one; anything else fails with an error that says why, and an unknown name lists the statuses there are. * `pairdraw.designMemory` is the document's design memory, or `null`: for `colors`, `fonts`, `fontSizes`, `spacing`, and `radius`, the allowed values (its variables and styles plus values the person allowed, each with the variable's or style's `name`) and `enforce` (`refuse`, `warn`, or `off`), then `decisions` and the pinned `examples`. * `pairdraw.checkDesignValues({ colors, fonts, fontSizes, spacing, radius })` judges values before they are used; each comes back `ok`, `warn`, `refuse`, or `invalid`, with the `nearest` allowed value. * `pairdraw.recordDesignDecision(text, node?)` writes a decision down and pins `node` as an example. It never changes what the memory allows, and fails in a document without a memory. Layer features Figma's API has no member for: * `pairdraw.getLayoutDirection(node)` / `setLayoutDirection(node, direction)` and `getTextDirection(node)` / `setTextDirection(node, direction)` read and set which way an auto layout or a text runs: `AUTO`, `LTR`, or `RTL`. * `pairdraw.getFillOkHCL(node, index?)` / `setFillOkHCL(node, color, index?)` and the `Stroke` pair read and set a paint's color in OkHCL, `{ h, c, l, a? }`; its RGB follows in the document's color space. * `pairdraw.exposeInstanceSwap(instances, candidates, name?)` exposes swapping those instances as one instance swap property offering the candidate components, and returns the layer that holds it. * `pairdraw.createVariations(node, { count, labels? })` copies a layer 1 to 8 times into a section of variations beside it, each copy named `V2 ·