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
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.
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.
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 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.
const [price] = figma.variables.getLocalVariables('FLOAT')
const label = figma.currentPage.findOne((node) => node.name === 'Price')
pairdraw.bindVariable(label, 'text', price)Query nodes
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:
pairdraw eval design.fig -c "
figma.currentPage.children.forEach((node) => {
node.opacity = 0.5
})
" --writeUse --output / -o to write to a new file:
pairdraw eval design.fig -c "figma.currentPage.name = 'Updated'" -o updated.figUse --preview-output to write a PNG of the page the script leaves current, after it runs:
pairdraw eval design.fig --stdin --write --preview-output preview.png < transform.jsRead scripts from stdin
cat transform.js | pairdraw eval design.fig --stdin --writeOne 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.
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:
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:
pairdraw eval design.fig -c "return figma.currentPage.children.map((n) => n.name)" --jsonUse --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. Bind it by its own property and slot names:
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, ornull; a variant reads its set's.- A behaviour has
kind,spec(by name),missing(required values and parts still unbound), andstates, andbindValue(valueId, property, { on, off }),bindPart(partId, slotNameOrFrame),setNumber(valueId, { min, max, step, default }), andremove(). pairdraw.behaviourKindslists 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:
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.authoris"Agent"when left out.- A comment has
id,text(Markdown),author,createdAt,resolved,page,node(the top-level layer it is pinned to),position, andreplies, andreply(text, { author }),resolve(),reopen(), andremove().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:
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.statuseslists the document's statuses in order, each withname,color(#RRGGBB), andfigma, the status Figma shows for it (READY_FOR_DEV,COMPLETED, ornull).pairdraw.getStatus(node)reads the name of the status a layer shows, ornull, also while a section around it shows its own.pairdraw.setStatus(node, name)sets one by name, andnullclears 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.designMemoryis the document's design memory, ornull: forcolors,fonts,fontSizes,spacing, andradius, the allowed values (its variables and styles plus values the person allowed, each with the variable's or style'sname) andenforce(refuse,warn, oroff), thendecisionsand the pinnedexamples.pairdraw.checkDesignValues({ colors, fonts, fontSizes, spacing, radius })judges values before they are used; each comes backok,warn,refuse, orinvalid, with thenearestallowed value.pairdraw.recordDesignDecision(text, node?)writes a decision down and pinsnodeas 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)andgetTextDirection(node)/setTextDirection(node, direction)read and set which way an auto layout or a text runs:AUTO,LTR, orRTL.pairdraw.getFillOkHCL(node, index?)/setFillOkHCL(node, color, index?)and theStrokepair 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 namedV2 · <label>, and returns{ set, versions }; on a version, it copies that version into its set.pairdraw.getVariations(node)reads the set a layer belongs to, ornull, andpairdraw.variationslists the sets on the current page. A set hasid,original,versions,use(version), which makes the original look like that version while it keeps its id, name, and place, and removes the set, anddiscard().pairdraw.getFontStatus()reports whether the current page's fonts are available: the faces asked for, where each loaded from, substitutions, and the layers affected.
Supported API surface
The API is intentionally close to Figma's Plugin API, but it maps to Pairdraw's scene graph and file format.
Document and pages
figma.rootfigma.currentPagefigma.currentPage.selectionfigma.getNodeById(id)figma.createPage()
Node creation
figma.createFrame()figma.createRectangle()figma.createEllipse()figma.createText()figma.createLine()figma.createPolygon()figma.createStar()figma.createVector()figma.createSlice()figma.createNodeFromSvg(svg)figma.createComponent()figma.createSection()
Tree operations
node.childrennode.parentnode.appendChild(child)node.insertChild(index, child)node.clone()node.remove()node.findAll(callback?)node.findOne(callback)node.findChild(callback)node.findChildren(callback?)figma.group(nodes, parent)figma.ungroup(node)
Components
figma.createComponentFromNode(node)figma.combineAsVariants(components, parent)— properties come from names such asState=On, Size=Large- On a component set,
addComponentProperty(name, 'VARIANT', value)appends the value to every variant's name andeditComponentProperty(name, { name })renames the property in them, which instances follow; renaming a variant updates the set's values, andvariantPropertiesreads a variant's or an instance's values component.createInstance()instance.mainComponent
Variables
figma.variables.getLocalVariables(type?),getVariableById(id),getLocalVariableCollections(),getVariableCollectionById(id), and their…Asyncformsfigma.variables.createVariableCollection(name)andcreateVariable(name, collection, resolvedType), which starts every mode at Figma's defaultfigma.variables.createVariableAlias(variable)andsetBoundVariableForPaint(paint, 'color', variable)variable.setValueForMode(modeId, value),valuesByMode,resolveForConsumer(node),name,description,scopes,codeSyntax, andremove()collection.addMode(name),renameMode(modeId, name),removeMode(modeId),modes,defaultModeId,variableIds, andremove()node.boundVariables,node.setBoundVariable(field, variable),node.setExplicitVariableModeForCollection(collection, modeId), andnode.clearExplicitVariableModeForCollection(collection)
Properties
Common node properties are readable/writable through the proxy, including:
- Geometry:
x,y,width,height,rotation,resize(width, height) - Appearance:
fills,strokes,effects,opacity,visible,locked,blendMode,clipsContent. Paints take Figma's shape here, on pagebackgrounds, text ranges, and vector regions: a solidcoloris RGB with its alpha inopacity, and an image namesscaleMode,rotation, andscalingFactor; a paint Figma refuses throws Figma's message - Radius:
cornerRadius,topLeftRadius,topRightRadius,bottomRightRadius,bottomLeftRadius - Text:
characters,fontSize,fontName(withvariationSettings, every axis of a variable font),fontWeight(a variable font'swght),fills,letterSpacing,lineHeight, andtextDecoration, which readfigma.mixedwhile characters differ and restyle every character when set, and alignment - Text font status:
node.hasMissingFontreadstruewhile a face the text draws in is neither loaded nor one the document's font catalog offers, so a script can tell a face needs loading or is absent from the document - Text ranges:
getStyledTextSegments(fields, start?, end?), andgetRange…/setRange…forFontSize,FontName,Fills,LetterSpacing,LineHeight,TextDecorationwith itsStyle,Offset,Thickness,Color, andSkipInk,TextCase,Hyperlink(a{ type: 'URL' | 'NODE', value }link, ornull),TextStyleIdandFillStyleId(set withsetRangeTextStyleIdAsyncandsetRangeFillStyleIdAsync, which give the range the style's fields), andgetRangeBoundVariable/setRangeBoundVariablefor the text fields Figma binds, plusgetRangeFontWeight,getRangeAllFontNames, andgetRangeOpenTypeFeatures. Line height and letter spacing keep the unit they are set in, pixels or a percent of the font size that follows the size, as in Figma; other lengths read in pixels, and a percent given to their setters is of the font size - Text lists and paragraphs:
getRangeListOptions/setRangeListOptionsfor bulleted (UNORDERED) and numbered (ORDERED) items,getRangeIndentation/setRangeIndentationfor nesting (1–5 for list items),listSpacing,paragraphSpacing, andparagraphIndentfor the whole text (figma.mixedwhen paragraphs differ) or per paragraph withgetRangeListSpacing/setRangeListSpacing,getRangeParagraphSpacing/setRangeParagraphSpacing, andgetRangeParagraphIndent/setRangeParagraphIndent, andhangingList - Auto-layout:
layoutMode,primaryAxisAlignItems,counterAxisAlignItems,itemSpacing, padding, sizing, and layout positioning fields - Stroke helpers:
strokeWeight,strokeAlign,dashPattern - Status:
devStatuson sections, frames, components, component sets, and instances directly on a page or in a section, as{ type: 'READY_FOR_DEV' | 'COMPLETED' }ornull(a description is not kept); it readsnullwhile the layer sits where it cannot show one
Utilities
figma.mixedfigma.util.rgb(color),figma.util.rgba(color, alphaOverride?), andfigma.util.solidPaint(color, overrides?)read a hex or CSS color string (rgb(),hsl(),lab(),oklab(),oklch(),color(display-p3 …), or a name), clipped to sRGB, or an{ r, g, b, a? }object with channels from 0 to 1;solidPainttakes its color and opacity fromcolorand its other properties fromoverrides, such as an existing paintfigma.createImage(data)takes a PNG, JPEG, or GIF up to 4096 pixels a side and gives Figma'sImage: itshash,getBytesAsync(), andgetSizeAsync();figma.getImageByHash(hash)gives a stored image backfigma.createImageAsync(url)loads anhttp(s)://URL or a data URI. The desktop app fetches through its native proxy, as Figma fetches through its servers; in the browser, the image's host must allow cross-origin requestsfigma.loadFontAsync(fontName)loads the font so text measures and draws with it; a family named without a style loads every style it has, and a variable family its named styles too. A font that cannot load rejects with Figma'sThe font "Family Style" could not be loaded- As in Figma, an edit that lays text out again throws
Cannot write to node with unloaded fontuntil every font the text uses is loaded:characters,insertCharacters,deleteCharacters,fontSize, spacing, case, decoration, alignment,textAutoResize, truncation, and the matchingsetRange…methods. A newfontNamehas to be loaded too, but it replaces the text's own, so text in a missing font can take a loaded one. Paints, links, size, and transforms need no font figma.getFontFamilyVariationAxes(family)lists a variable family's axis tags, ornullfor a static one; unlike Figma, the family has to be loaded first- A font set with
variationSettingsand no style, throughfontNameorsetRangeFontName, takes the nearest named style, and an axis the family lacks throws Figma's error - OpenType features:
text.openTypeFeaturesandtext.getRangeOpenTypeFeatures(start, end)read the features explicitly set, as a tag-to-boolean map. Figma's plugin API has no setter for them;pairdraw.setFontFeatures(text, { TNUM: true, LIGA: false })merges toggles into the whole text's features andpairdraw.setRangeFontFeatures(text, start, end, { SMCP: true })into a range's, keeping the tags they do not name. Only features the font has take effect; the text panel lists them figma.listAvailableFontsAsync()lists every style of installed and bundled families, and of online families once a font of theirs is loaded; an online family not looked up yet is listed asRegularfigma.getNodeByIdAsync(id)finds a layer on a page the document has not loaded yet by loading that page, as in Figma's dynamic-page mode; a layer already in the document resolves asfigma.getNodeById(id)does.instance.getMainComponentAsync()resolves to the same node asinstance.mainComponentfigma.setCurrentPageAsync(page)switches pages as settingfigma.currentPagedoes, loading the page's layers first when they are not in memory;page.loadAsync()loads a page not loaded yet with the fonts its text uses, and resolves at once for one already loadedfigma.notify(message)logs a warning in headless modefigma.uiandfigma.showUI(html?, options?)exist in headless mode as Figma's no-ops:ui.postMessage,ui.resize,ui.show,ui.hide, andui.closedo nothing,ui.onmessageis assignable but never fires, andshowUIshows nothing. A script that posts to a UI runs without throwingfigma.closePlugin(message?)lets a script written as a Figma plugin run: nothing needs closing, andclosePluginpasses its message tofigma.notify. Figma refuses every call afterclosePluginwhile a script here keeps running, so follow it withreturnas Figma's docs do.figma.loadAllPagesAsync()loads every page's layers, which a.figopened on its first page has not read yetinstance.swapComponent(component)points an instance at another component- A layer inside an instance refuses
x,y,rotation,relativeTransform,constraints,isMask, andmaskTypewith Figma's error, such asin set_x: This property cannot be overridden in an instance: relative-transform; those always follow the component. Slot content keeps them, and setting one on a slot's default content makes the instance own the slot component.createSlot()adds a slot frame and itsSLOTproperty; slot frames readtype: 'SLOT',resetSlot()brings back an instance slot's component content, andlimitViolationslists the limits an instance slot breaks.addComponentPropertyandeditComponentPropertytake adescriptionand, for slots,slotSettingsfigma.viewport
Not yet Figma-compatible
These Figma APIs are not exposed as compatible helpers yet:
node.exportAsync()figma.util.normalizeMarkdown(), which fails because Pairdraw has no rich-text descriptions or annotations to normalize for- Library variables, extended collections, and variable bindings on effects and layout grids
- Figma style APIs such as
figma.createPaintStyle()/figma.createTextStyle() - Full vector boolean operation parity
Use Pairdraw CLI export commands, core tools, or direct scene-graph helpers where available.