AI-native design editor. Open-source Figma alternative.
Core
Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and document I/O. Depends on scene-graph, pen, kiwi, and fig. Framework-neutral: no Vue, no app imports, no browser DOM; guard browser globals explicitly.
- The root entry is the editor (
createEditorand its types); every other domain is a subpath listed inpackages/core/package.jsonexports. Add a subpath there rather than deep-importing, and never re-export another package's names. - CanvasKit runtime loading is centralized in
@open-pencil/core/canvaskit, which loads the full build so every host encodes JPEG and WebP itself, as headless raster export's owncanvaskit-wasm/fulldoes; elsewhereimport typeand pass CanvasKit in (packages/core/tests/io/formats/raster/pixels.test.ts). - Start a worker module with
new Worker(new URL('./worker.js', import.meta.url), { type: 'module' }): the.jsspelling reaches the.tssource under Vite and Bun and the built file indist, where a.tsURL has nothing to load (packages/core/src/layout/arrange/elk.ts). - Node-only helpers live under
@open-pencil/core/node/*, which nothing browser code imports. Files the CLI, MCP server, and harness replace are written withwriteFileAtomicfrom@open-pencil/core/node/fsrather than a hand-rolled temporary file and rename; only a document saved in place follows a symlink (packages/core/tests/node/fs.test.ts). - Drawing and input share preview-aware geometry through
@open-pencil/core/geometry, built on Scene Graph matrices. Use it for world/screen transforms, inverses, bounds, and handle placement. - Content an author wrote (design JSX, HTML,
.pen) gets its sizes and positions fromlayoutAuthoredNodesinpackages/core/src/layout.ts, which measures text that resizes to its content wherever it sits and then lays out the pages involved; renderers and readers of authored formats call it, while.figkeeps the geometry it stores (packages/core/tests/layout/authored.test.ts). .pendocuments draw as pen.dev draws them.bun tools/generate/visual-oracles/src/cli.ts compare penexports every frame of the document open in pen.dev intotests/fixtures/pen-oracles/with the icons and fonts it uses; a new reading rule adds a probe frame there and a threshold to itsmanifest.json(packages/core/tests/io/formats/pen/oracle.test.ts).- HTML is styled by whoever has a CSS runtime and built into layers by
sceneGraphFromStyledHTML(packages/core/src/io/formats/html/layers.ts), which browser builds may bundle.readHTMLDocumentandheadlessHTMLReaderuse the headless CSS runtime, which cannot be bundled for browsers, so they stay out ofBUILTIN_IO_FORMATSand the CLI registers the reader (packages/core/tests/io/formats/html/import.test.ts). - Copies of part of a document, such as previews, history snapshots, and exports, come from
extractPageContextorextractExportGraphinpackages/core/src/io/subgraph.ts, not another copier. PasscomponentSetswhen instances must switch variant andshareTablesfor a read-only view rebuilt often (packages/core/tests/io/subgraph.test.ts). - An edit that records the document changes it makes, as AI and MCP calls do apart from atomic tools (Tools), runs through
recordEdit, orrecordEditAsyncwhen it awaits, which keeps the edit open until its step is recorded so undoing it returns the document to saved; capturing a change by hand failsopen-pencil/no-document-change-capture(packages/core/tests/editor/history/edit.test.ts). - The recording copies only what an edit touches: the edit's page is copied up front, and another page or the document node the first time
SceneGraph.observeNodeChangesreports it about to change, so code that writes into a node directly callswillChangeNodefirst. Copies share values rather than deep-copying, so values must be replaced rather than written into, apart from the child lists, source metadata, and override maps it copies; comments on the document node stay out of undo (packages/core/tests/editor/history/document-change.test.ts).
Layout
@open-pencil/yoga-layoutsupplies both flexbox and CSS Grid.- Recompute layout after demo creation and for each materialized or imported page; scope computation to the affected page or subtree where possible.
- The first Hug/Fill dimension mutation switches only that axis to Fixed; focus is non-destructive, and mode/value changes share one undo transaction.
- Arranging layers runs through
packages/core/src/layout/arrange/:arrangeBoxesruns an ELK layout (spread, compact, pack, flow, tree, radial, network), loaded on first use,applyArrangementmoves the layers that draw it and joins their connectors, routing them when they flow, andarrangeLayersdoes both for layers already on a page, finding the connectors between them; importers and tools that arrange layers go through them, and connectors that pass through stored bend points usebendConnectorThrough(packages/core/tests/layout/arrange/layers.test.ts). - A shape with text fits itself to its label before its auto layout runs: it grows from its given size only while the label needs room, and layout never changes that given size (
packages/core/tests/layout/generated/shape-with-text.test.ts).
Components and instances
- Component types use
#9747ff. - Component edits propagate through editor component sync in
packages/core/src/editor/components/; never hand-copy properties in app UI. Use Scene Graph copy helpers for nested values.
Vector conversion
- Bitmap-to-vector conversion lives in
packages/core/src/vector/vectorize/; app provider clients, preferences, and credential resolution live undersrc/app/editor/vectorize/in the app. Bound request and response sizes and validate provider-owned download URLs before importing returned SVG.
Tools (AI, MCP, CLI, WebMCP)
- Operations are
ToolDefs underpackages/core/src/tools/**;schema.tsdefines the contract and registries expose them. Each definition owns its native Valibotinput, execution/mutation metadata, and optional per-interface exposure exclusions (mcp,ai,webmcp). Exposure defaults to inclusion; adapters useisToolExposed(), then apply execution support and user permissions independently. - Infer arguments from the schema; derive effects and default capabilities from execution metadata. Do not maintain parameter DSLs or tool-name lists. Add work to the nearest existing domain and the appropriate registry.
packages/core/src/tools/ai-adapter.tsconverts ToolDefs for Vercel AI; the app binds them to the active editor'sFigmaAPIinsrc/app/ai/tools/index.ts. MCP v2 registration uses Standard Schema with Valibot JSON Schema conversion; AI and WebMCP adapters share the same input contract.packages/core/src/editor/history/atomic-tool.tsowns synchronous property/variable transactions for AI, MCP, and WebMCP and records their undo step itself, not throughrecordEdit; Scene Graph owns checkpoint recovery. Async and structural tools cannot declare atomic property execution (packages/core/src/tools/schema.ts).- An atomic tool writes layers through graph methods, or reports a layer with
willChangeNodebefore writing into it, since a transaction copies only the layers the graph reports and their ancestors below the page (captureTouchedCheckpoint) (packages/core/tests/editor/history/atomic/tools.test.ts). - An atomic transaction, its undo, and its redo lay out each changed layer once, as the outermost auto-layout frame holding it where there is one, so changed siblings share one layout of their parent; every page is laid out only when a variable changed (
packages/core/tests/editor/history/atomic/layout.test.ts). - One atomic call changes at most 10 000 layers, and a larger one is rolled back with an error asking for fewer layers per call (
packages/core/tests/editor/history/atomic/tools.test.ts). - Shared scene-authoring guidance and tested examples live under
packages/design-jsx/src/reference/;reference/index.tscombines them with renderer metadata. Prompts underpackages/core/src/tools/prompts/and the app chat/ACP prompt compose that reference rather than copying it. Runbun run generate:authoring-referenceafter changes;check:authoring-reference(part ofcheck:docs) verifies the committed skill/docs copies. Do not edit generated reference files. - The installable agent skill is maintained in
skills/open-pencil/. Changes to agent-facing APIs, CLI/MCP behavior, or design authoring must update affected skill examples, prompts, and public documentation in the same change. Keep examples valid in their actual execution environment; do not advertise library exports as scripting globals unless exposed there. Prefer runtime discovery and canonical references over duplicated API/tool inventories. - MCP-only tools and transports:
packages/mcp/AGENTS.md. WebMCP registration and app completion:src/AGENTS.md.
Editor
createEditor() in packages/core/src/editor/create.ts assembles an EditorContext plus domain action modules for viewport, selection, pages, shapes, structure, components, clipboard, undo/history, text, variables, layout, color space, graph reads, and the tool registry. Editor is ReturnType<typeof createEditor>. Check the folder before adding behavior; keep new actions in the nearest domain module or folder instead of growing unrelated files. Modules share state through EditorContext, never through app code or Vue.
- All selection mutations go through
ctx.setSelectedIds()and all tool changes throughctx.setActiveTool()so events fire consistently. App code uses editor actions such asclearSelection(),select(), orsetTool(), never directstate.selectedIds =orstate.activeTool =assignments. - The editor exposes a typed nanoevents emitter. Event names and payloads live in
EditorEventsinpackages/core/src/editor/types.ts; graph events are bridged from SceneGraph bypackages/core/src/editor/graph-events.ts. Subscribe witheditor.onEditorEvent(event, handler); in Vue useuseEditorEvent()frompackages/vue/src/editor/events/use.ts. UI that only cares about graph data should use editor events for incremental surfaces such as the layer tree instead of watching repaint-only state. - Commands under
packages/core/src/editor/structure/(group, boolean, container wrap, flatten) andpackages/core/src/editor/components/are the canonical implementations of user actions. The Figma API, tools, and app call them or share their helpers; do not reimplement sizing, placement, or propagation elsewhere. - Live property controls use selected-node projections from
packages/core/src/editor/selection-state/nodes.ts: shallow reactive copies that receivenode:previewUpdatedpatches at property granularity. Never add preview invalidation to alluseSceneComputedconsumers; catalogs and unrelated controls must not refresh for geometry previews. Projection subscriptions belong to the consuming scope or session and must be disposed. - Numeric geometry edits own a
beginNodePreview()handle withupdate,commit, andcancel. It captures all affected fields and layout children, publishes the complete delta once, and restores exact originals on cancellation. Selection, page, and graph changes and disposal cancel the old edit; trailing input must not target the new selection. Controls must close previews even when a gesture returns to its starting value. - Rotation previews change through
setRotationPreview()androtation:preview-changed; cancellation must close the owning gesture without deselecting or committing it. - A read-only document (
setReadOnly) refuses every editor action not listed inREAD_ONLY_ACTIONS, so a new action that only reads, selects, or navigates is added there; front ends ignore the refusal and change only what behaves differently, such as the toolbar (packages/core/tests/editor/read-only.test.ts). - A canvas pane behaves by its profile (
resolveEditorProfileinpackages/core/src/editor/views/): the document's kind (design or board) decides its tools, tool keys, and snap grid, its view the pointer, shortcuts, editing chrome, live islands, panels, and where leaving goes, and the host's restrictions narrow both. A new kind, view, or host limit is a new entry there; other code reads profile values, never the kind, view, or restrictions themselves, whichopen-pencil/no-editor-profile-inputsenforces (packages/core/tests/editor/views/profile.test.ts). - Renderer interaction policy uses explicit
beginInteractiveEdit()leases andisInteractiveEditing(), not undo batching. Release leases on every terminal path. Keep live queries callable across app facades that spread editor actions. packages/core/src/editor/history/atomic-tool.tsowns synchronous property/variable transactions for AI, MCP, and WebMCP tools; see Tools above.
OpenPencil API
OpenPencilAPI (packages/core/src/openpencil-api/) is what OpenPencil adds to the Plugin API, exposed to scripts as the openpencil global next to figma.
- Put OpenPencil-only features on
openpencil, in the same style asfigma: methods and node-like handles with getters and setters, not parallel helper functions.figmastays Figma's (Figma API, Shape follows Figma). - Script runners get both globals only through
compileScript(packages/core/src/tools/analyze/eval/wrap.ts); theevaltool,openpencil eval, and app automation must not build their ownAsyncFunction. - Members take names, not internal ids, and write through the same scene-graph functions the editor's actions use, such as
behaviourFromSpec; errors name what exists. Tools for the same feature wrap theopenpencilAPI rather than reimplementing it (packages/core/src/tools/create/behaviours.ts). - A new member updates
packages/docs/programmable/cli/scripting.mdand the agent skill in the same change; tests drive it as scripts do, throughcompileScript(packages/core/tests/openpencil-api/).
Renderer
Canvas is CanvasKit (Skia WASM) on a WebGL surface, not DOM.
Invalidation
renderVersionis a canvas repaint (pan, zoom, hover);sceneVersionis a scene-graph mutation.requestRender()bumps both;requestRepaint()bumps onlyrenderVersion. UI that only cares about graph data must not watch repaint-only state.renderNow()is only for surface recreation and font loading, where an immediate draw is required.- The resize observer uses a rAF throttle, not a debounce; debounce causes canvas skew.
- Viewport culling skips off-screen nodes; unclipped parents are not culled because children may extend beyond bounds.
- Overscan images accelerate navigation; a settled scene is the exact visible tiles at the live viewport's device scale. Pixel-grid alignment alone does not guarantee Skia anti-aliasing parity. Keep settlement pending until the viewport pass completes; do not add a second viewport image cache.
Paints
- A gradient or image paint builds a Skia shader through
applyGradientFillandapplyImageFill(packages/core/src/canvas/fills.ts), which take the targetPaint, so a stroke reuses them instead of a second shader path. Both say whether they set one; a caller skips the paint when they did not, since CanvasKit builds no gradient from a transform it cannot invert and an image may not be decoded yet (packages/core/tests/canvas/paints.test.ts). packages/core/src/canvas/scene.tswalks the tree and dispatches: text draws incanvas/text/render.ts, a layer's strokes incanvas/strokes/dispatch.ts, and a shape with effects through its node picture incanvas/renderer/node-pictures.ts; keepscene.tsto traversal and move a new drawing domain beside those.forVisibleStrokes(packages/core/src/canvas/strokes.ts) is where a stroke's shader and dash are set and cleared, for shapes and booleans alike; stroke draw helpers take an already-configuredstrokePaintand must not reset its shader, and a dash goes on throughwithStrokeDash, which frees the effect (packages/core/tests/canvas/strokes.test.ts).- Shadows are cast from what a layer draws, children included, through
drawSilhouette(packages/core/src/canvas/shadows/silhouette.ts); a container's shadows are drawn byrenderLayerShadowsaround its children, not byrenderShape. A faster path for a shape must give the same pixels as its silhouette (packages/core/tests/canvas/shadows.test.ts).
Caches
- Bounded rendering caches share
packages/core/src/cache/resource.tsfor recency, count/weight accounting, and removal disposal. Domain adapters own keys, font/page/dependency invalidation, and sizing units; use non-touchingpeek()for FIFO or planning reads. Rejected insertions leave ownership with the caller. - Keep weak memos, async request registries, pools, and dependency-owned picture/path maps on their distinct lifetime policies.
- CanvasKit path caches are built with
createPathCacheand weighed by points; node paths live in the renderer'sNodePathCaches, whosestorekeeps a path too large to cache until the next frame or export starts (packages/core/tests/canvas/paths/cache.test.ts). - Set fill types on the detached
Path, never on aPathBuilder: in CanvasKit 0.41PathBuilder.setFillTypereturns an undeleted copy of the builder (packages/core/src/vector/index.ts). - Paragraph construction is typed against
packages/core/src/canvas/text/paragraph/inputs.ts; the same inputs drive preparation-cache invalidation. Add a mutation case when extending that contract. Drawing borrows native paragraphs; the renderer owns their bounded cache and destruction. - Text lays out through
buildParagraphinto aTextLayout(packages/core/src/canvas/text/layout/): one native paragraph for plain text, or one per paragraph with its list indent, marker, and spacing, since Skia has no hanging indent. Drawing, measurement, the text editor, saved glyphs (shapeText), and text outlines all read that layout rather than laying text out again (packages/core/tests/canvas/text/lists.test.ts). - Text is laid out only in its own prepared fonts.
prepareTextFontsandprepareGraphFonts(packages/core/src/text/prepare.ts) are the one way text gets its faces, script fallbacks, and emoji; readers and design JSX call them beforelayoutAuthoredNodes, and the canvas loads the faces its tools create text in. Edits apply at once: text layout reaches before its fonts are prepared keeps its stored size and stays hidden while the editor prepares them, then is laid out once (packages/core/src/editor/text/pending-layout.ts,packages/core/tests/editor/text/pending-layout.test.ts). - Renderers and shapers take the font provider from
fontManager.acquireProviderand return it withreleaseProvider, neverTypefaceFontProvider.Make(): every provider holds its own copy of every registered face, and the canvases of one CanvasKit share one (packages/core/tests/text/font/manager.test.ts). - Emoji are 1 em squares with their image drawn over, once per text and apart from the fills, as Figma does:
drawSavedEmojiover a saved glyph's placeholder square (emojiCodePoints),drawLaidOutEmojiover the blank square the layout gives a character it falls back toOpenPencil Emoji Metricsfor, the last fallback family, generated bybun run generate:emoji-metrics. The image comes from the browser's emoji font through a 2D canvas, or from Noto Color Emoji thatprepareGraphFontsloads where nothing draws platform emoji (tests/e2e/canvas/saved-glyph-visual.spec.ts). - A keycap mark (U+20E3) is laid out as a zero-width space (
laidOutText), since CanvasKit shapes it with the key's font, which lacks it; its frame, Noto Sans Symbols' outline that Figma draws, is drawn in the text's paint and saved apart (packages/core/src/text/keycap.ts, whose framebun run generate:emoji-metricswrites topackages/core/src/text/font/keycap.ts;packages/core/tests/canvas/text/shape.test.ts).
Text decorations
- Underlines and strikethroughs come from
textDecorationRects(packages/core/src/text/decorations.ts), Figma's geometry over laid-out or saved glyphs, both for drawing and for the rects.figfiles save, which Figma draws decorations from; Skia's paragraph decorations stay off. Drawn decorations are kept with the prepared text, whose paragraph inputs cover them, or by saved glyphs in the renderer'stextCaches.derivedDecorations(packages/core/tests/text/decorations.test.ts).
Geometry and overlays
- Use
@open-pencil/core/geometryfor world/screen transforms, inverses, bounds, and handle placement instead of interpreting ancestor rotations or reflections independently. - Label drawing and hit testing share
packages/core/src/canvas/labels/{layout,transform,style}.ts, including paragraph measurements and unreflected label axes. - Editor chrome sized in screen pixels (outlines, borders, carets, highlights) draws in the overlay pass, never in the scene, which is cached and scaled while navigating. Draw outlines with
withScreenStrokeandinNodeSpace(packages/core/src/canvas/overlays/outline.ts).open-pencil/no-zoom-in-scene-drawingenforces it. - Selection border width is constant regardless of zoom: divide by scale. Section and frame title text never scales: render at a fixed font size and ellipsize to fit.
- Rulers are rendered on the canvas with selection range badges that do not overlap tick numbers. Remote cursors are Figma-style colored arrows with a white border and name pill, rendered in screen space.
Visual coverage
Pixel-affecting features need committed visual coverage, not only mock or geometry assertions. Add or update a Playwright canvas snapshot for changes to fills, gradients, images, blend modes, masks, boolean geometry, corners, strokes, shadows, blur, text rendering, or demo showcase scenes. Use targeted updates such as bun run test tests/e2e/canvas/fill-modes-visual.spec.ts --update-snapshots, then rerun the same test without --update-snapshots.
Figma API
FigmaAPI mimics Figma's Plugin API over the SceneGraph. openpencil eval, the AI and MCP tools, and the app bind to it. Tests live under packages/core/tests/figma-api/ and mirror packages/core/src/figma-api/.
- Shape follows Figma. Match
@figma/plugin-typingsat the version pinned in the rootpackage.json, and add every new member toSupportedPluginAPI.compatibility.tsfails the typecheck on a member Figma's types lack or type differently, andpackages/core/tests/figma-api/surface.test.tson one a script can reach; the lists inpackages/core/src/figma-api/surface.tsonly shrink. - Behavior follows Figma. Read the Plugin API documentation for the member, and for anything observable (geometry, ordering, defaults, errors) run the same script in live Figma and record the observed result in the test.
figma-useandtests/figma/are the live oracle;tests/fixtures/figma-oracles/holds recorded values. - User actions are shared code. When an editor command does the same thing (group, ungroup, boolean, flatten, instance creation, component sync), call the implementation under
packages/core/src/editor/or its shared helper. Do not reimplement geometry, placement, or propagation here; new geometry helpers belong in Scene Graph. - Geometry getters lay out what the graph's edits touched since the last read, as Figma does, through
flushPendingLayoutinpackages/core/src/figma-api/pending-layout.ts; a new geometry getter calls it first (packages/core/tests/figma-api/pending-layout.test.ts). - Node proxies live in
packages/core/src/figma-api/proxy.tsandpackages/core/src/figma-api/accessors/; per-character text styles are modelled inpackages/core/src/text/character-style.ts, which the editor's selection styling shares, and read for scripts inpackages/core/src/figma-api/text/style.ts, which node getters, range methods, and segments all use (packages/core/tests/figma-api/text/styles.test.ts);packages/core/src/figma-api/render-bounds.tsimplements Figma'sabsoluteRenderBoundssemantics and is the only geometry that is Figma-specific. packages/core/src/figma-api/index.tsstays under the 600-line limit by moving whole domains into sibling modules such ascomponents.tsandtext/, not by extracting generic helpers into this folder.