AI-native design editor. Open-source Figma alternative.
Scene Graph
Framework-neutral document model. Owns node types, primitives, geometry, matrices, copy/snap/undo helpers, variables, instances, hit testing, and checkpoint recovery.
The root entry holds the model:
SceneGraph(src/graph.ts), ID generation (src/ids.ts), and the node types (src/types.ts). Every other domain is a subpath named after its source path, such as./instances/overridesforsrc/instances/overrides.ts;src/index.tsonly re-exports. Add a subpath topackage.jsonandtsdown.config.tstogether (check:packages).Nodes live in a flat
Map<string, SceneNode>; runtime hierarchy usesparentIdandchildIds. Frames do not clip by default.Walk up the tree with
SceneGraph.closest()orisDescendant(), which stop on a parent cycle in bad data, rather than a hand-writtenparentIdloop (packages/scene-graph/tests/basic/graph.test.ts).Change a live graph's hierarchy through
reparentNode,insertChildAt, orupdateNode, which emit the events collaboration syncs; assignchildIdsdirectly only on a graph copy or nodes created in the same edit (sortInstanceChildreninpackages/scene-graph/src/instances/sync.ts).Geometry is built on the matrices in
packages/scene-graph/src/matrix.tsandpackages/scene-graph/src/coordinate.ts(getWorldMatrix,getAxisAlignedWorldBounds,getNodeLocalMatrix). Add new transform, bounds, or inverse helpers here beside them; do not interpret ancestor rotations or reflections independently elsewhere. LINE pivots remain at the origin; other nodes rotate around their centers.Bounds accumulation goes through the helpers in
packages/scene-graph/src/geometry.ts(computeBounds,computeAbsoluteBounds,computeVisualBounds); do not add another min/max loop.Reparenting preserves child world positions; groups preserve them too. Sort children geometrically before creating auto-layout. Consumers such as layer trees must react to reparenting rather than retaining stale child references.
Use the copy helpers in
packages/scene-graph/src/copy.tsfor nested values (fills, strokes, effects); never hand-copy node properties.A generated frame (Figma's immutable frames such as
STICKY,SHAPE_WITH_TEXTandCONNECTOR) owns real child layers built from its template inpackages/scene-graph/src/generated/(a connector's inpackages/scene-graph/src/connectors/); nothing adds, moves, or removes them (slotScopereportslocked), and the layers panel lists the frame alone. Each type registers aGeneratedFrameKindinGENERATED_FRAME_KINDS, and the editor asks it (layerRotates,layerResizes,generatedFrameText) instead of testing node types. A kind'ssizedhook says what a width or height set outside layout also sets, such as a shape's given size, andupdateNodeandupdateNodePreviewapply it to every such write (packages/scene-graph/tests/generated/kind.test.ts). A connector's ends name the layers they follow by ID; a transfer that leaves those layers behind keeps the IDs, and a reader that cannot find one leaves that end free where it was drawn (packages/scene-graph/tests/connectors/endpoints.test.ts).A connector's route derives from the layers its ends follow:
routeConnectorroutes as FigJam does andlayoutConnectorlays the line, label plate, and label out to match. Core's editor routes again when those layers change, during previews too, and deletes connectors with the layers they attach to; loading a document keeps the routes it saved, and one saved without a route is routed by layout or when its page is shown, once its label is measured (packages/scene-graph/tests/connectors/route.test.tsagainst recorded Figma routes,packages/core/tests/editor/connectors/routing.test.ts).Instance children map to component children through
componentId; runtime overrides use the structuredInstanceOverrideState(selfanddescendantsmaps) inpackages/scene-graph/src/instances/overrides.ts.A bound numeric field records its unit conversion in
variableBindingScales; preserve it through clone, copy, and transfer so a binding keeps meaning in its new scope. Core reconciles bindings and layout together inpackages/core/src/layout/variables.ts, which the editor and the Figma API both call rather than reimplementing.componentScalerecords an occurrence's coordinates relative to its component definition. Shared rescaling lives inpackages/scene-graph/src/scaling/; Core's Figma API delegates there instead of scaling nodes itself.Shared primitives that format packages and collaboration need live here: color conversion and management under
@open-pencil/scene-graph/color, text/layout direction under@open-pencil/scene-graph/text/direction, and fractional sibling order keys under@open-pencil/scene-graph/order-keys(packages/scene-graph/tests/order-keys.test.ts).A text's list items, and spacing a paragraph sets for itself over the text's (
paragraphSpacingAt), are oneTextParagraphStyleper paragraph intextParagraphs;@open-pencil/scene-graph/textnumbers them (textListItems) and keeps the styles aligned through edits (paragraphStylesAfterEdit,paragraphStylesInRange), so the renderer,.fig, the Figma API, and exporters never count markers or split paragraphs themselves (packages/scene-graph/tests/text/lists.test.ts).A text's
lineHeightandletterSpacing, on the layer and its runs, are aTextLengthin pixels or a percent of the font size, kept in that unit as Figma keeps it (nullline height is automatic). Resolve them withlineHeightPixelsandtextLengthPixelsfrom@open-pencil/scene-graph/textat the size of the characters they space; never read.valueas pixels (packages/core/tests/figma-api/text/units.test.ts).A node's per-axis sizing (Figma's
layoutSizingHorizontal/Vertical) is read and written throughpackages/scene-graph/src/layout/sizing.ts. Fill is stored on the child as Figma stores it,layoutGrowalong the parent's primary axis (a grid's is horizontal) andlayoutAlignSelf: 'STRETCH'across it;primaryAxisSizing/counterAxisSizingonly fix or hug. Layout, the Figma API, the properties panel, and exporters call it instead of mapping axes themselves (packages/core/tests/figma-api/accessors/layout/sizing.test.ts).Formats read auto layout keywords (stack direction,
justify-content,align-items,align-self, padding shorthand) throughpackages/scene-graph/src/layout/keywords.ts, and an importer builds fill and hug for a node not yet in the graph withfillSizingFieldsandautoLayoutSizingFields. Design JSX and.penpass their own spellings straight to it, and DOM/CSS parses CSS values first withparseCSSJustifyContentand its siblings in@open-pencil/scene-graph/css(packages/scene-graph/tests/layout/keywords.test.ts,packages/scene-graph/tests/css/layout.test.ts).CSS values that become scene-graph types, such as grid track lists, are parsed in
@open-pencil/scene-graph/cssonpostcss-value-parser; design-jsx and dom-css call it instead of splitting or matching CSS by hand (packages/scene-graph/tests/css).Groups of
SceneNodefields (transform, size, size limits, paints, strokes, corners, auto layout, text style) are named once inpackages/scene-graph/src/fields/, and style links come fromSTYLE_LINK_FIELDS. Build a field list, such as instance sync, layout invalidation or Paste properties, from those groups instead of spelling the fields again (packages/scene-graph/src/instances/fields.ts).Every plugin-data key OpenPencil writes is a field of
OPEN_PENCIL_PLUGIN_DATAinpackages/scene-graph/src/plugin-data/fields.ts, with the Valibot schema that reads it and its role:contenttravels with library assets and counts towards their hash (contentPluginData),formatrepeats a node field for files,bookkeepingstays behind. Read and replace entries withreadPluginDataandwithPluginDatainstead of matchingpluginIdandkeyby hand. The fields test checks that keys stay unique.A layer's
statusstays stored wherever the layer moves, as Figma keeps it; whether it shows, and whether one may be set, come fromeffectiveStatusandstatusPlacementinpackages/scene-graph/src/statuses/node.ts, which the Figma API,.figand the UI share. Copies start without one (packages/core/tests/figma-api/dev-status.test.ts).Vector network types live here;
vectorNetworkBlobcodecs live inpackages/core/src/vector/.packages/scene-graph/src/checkpoint.tsowns transaction checkpoint recovery, including hierarchy and indexes. Core's atomic tool execution usescaptureTouchedCheckpoint, which copies only the nodesobserveNodeChangesreports and their ancestors below the page, and fails an edit that sends a node event for a node it did not report first (packages/scene-graph/tests/checkpoint.test.ts).Node types (
SceneNode,Effect,Fill,Stroke) come from the root entry and primitives (Color,Vector,Rect) from@open-pencil/scene-graph/primitives; downstream packages reuse them instead of respelling shapes.A paint's
gradientTransformfollows Figma's convention, mapping the layer's unit square onto gradient space; read, build, and invert it only through@open-pencil/scene-graph/gradient, which renderers, handles, exporters, importers, and tools all share (packages/scene-graph/tests/gradient.test.ts,tests/engine/render/canvas/gradient.test.ts).StrokeextendsFill, so a stroke is a paint plus its geometry; add a paint field toFilland both get it, and copy it incopyFill, whichcopyStrokereuses (packages/scene-graph/src/copy.ts).Variable expression schemas, evaluation, mode resolution, and reference traversal belong in
src/variables/; draft validation uses the same resolver with an override, while Core owns edit history and layout (tests/variables/formula.test.ts).