Skip to content

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

9.7 KB
Raw Blame

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/overrides for src/instances/overrides.ts; src/index.ts only re-exports. Add a subpath to package.json and tsdown.config.ts together (check:packages).

  • Nodes live in a flat Map<string, SceneNode>; runtime hierarchy uses parentId and childIds. Frames do not clip by default.

  • Walk up the tree with SceneGraph.closest() or isDescendant(), which stop on a parent cycle in bad data, rather than a hand-written parentId loop (packages/scene-graph/tests/basic/graph.test.ts).

  • Change a live graph's hierarchy through reparentNode, insertChildAt, or updateNode, which emit the events collaboration syncs; assign childIds directly only on a graph copy or nodes created in the same edit (sortInstanceChildren in packages/scene-graph/src/instances/sync.ts).

  • Geometry is built on the matrices in packages/scene-graph/src/matrix.ts and packages/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.ts for nested values (fills, strokes, effects); never hand-copy node properties.

  • A generated frame (Figma's immutable frames such as STICKY, SHAPE_WITH_TEXT and CONNECTOR) owns real child layers built from its template in packages/scene-graph/src/generated/ (a connector's in packages/scene-graph/src/connectors/); nothing adds, moves, or removes them (slotScope reports locked), and the layers panel lists the frame alone. Each type registers a GeneratedFrameKind in GENERATED_FRAME_KINDS, and the editor asks it (layerRotates, layerResizes, generatedFrameText) instead of testing node types. A kind's sized hook says what a width or height set outside layout also sets, such as a shape's given size, and updateNode and updateNodePreview apply 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: routeConnector routes as FigJam does and layoutConnector lays 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.ts against recorded Figma routes, packages/core/tests/editor/connectors/routing.test.ts).

  • Instance children map to component children through componentId; runtime overrides use the structured InstanceOverrideState (self and descendants maps) in packages/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 in packages/core/src/layout/variables.ts, which the editor and the Figma API both call rather than reimplementing.

  • componentScale records an occurrence's coordinates relative to its component definition. Shared rescaling lives in packages/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 one TextParagraphStyle per paragraph in textParagraphs; @open-pencil/scene-graph/text numbers 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 lineHeight and letterSpacing, on the layer and its runs, are a TextLength in pixels or a percent of the font size, kept in that unit as Figma keeps it (null line height is automatic). Resolve them with lineHeightPixels and textLengthPixels from @open-pencil/scene-graph/text at the size of the characters they space; never read .value as pixels (packages/core/tests/figma-api/text/units.test.ts).

  • A node's per-axis sizing (Figma's layoutSizingHorizontal/Vertical) is read and written through packages/scene-graph/src/layout/sizing.ts. Fill is stored on the child as Figma stores it, layoutGrow along the parent's primary axis (a grid's is horizontal) and layoutAlignSelf: 'STRETCH' across it; primaryAxisSizing/counterAxisSizing only 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) through packages/scene-graph/src/layout/keywords.ts, and an importer builds fill and hug for a node not yet in the graph with fillSizingFields and autoLayoutSizingFields. Design JSX and .pen pass their own spellings straight to it, and DOM/CSS parses CSS values first with parseCSSJustifyContent and 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/css on postcss-value-parser; design-jsx and dom-css call it instead of splitting or matching CSS by hand (packages/scene-graph/tests/css).

  • Groups of SceneNode fields (transform, size, size limits, paints, strokes, corners, auto layout, text style) are named once in packages/scene-graph/src/fields/, and style links come from STYLE_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_DATA in packages/scene-graph/src/plugin-data/fields.ts, with the Valibot schema that reads it and its role: content travels with library assets and counts towards their hash (contentPluginData), format repeats a node field for files, bookkeeping stays behind. Read and replace entries with readPluginData and withPluginData instead of matching pluginId and key by hand. The fields test checks that keys stay unique.

  • A layer's status stays stored wherever the layer moves, as Figma keeps it; whether it shows, and whether one may be set, come from effectiveStatus and statusPlacement in packages/scene-graph/src/statuses/node.ts, which the Figma API, .fig and the UI share. Copies start without one (packages/core/tests/figma-api/dev-status.test.ts).

  • Vector network types live here; vectorNetworkBlob codecs live in packages/core/src/vector/.

  • packages/scene-graph/src/checkpoint.ts owns transaction checkpoint recovery, including hierarchy and indexes. Core's atomic tool execution uses captureTouchedCheckpoint, which copies only the nodes observeNodeChanges reports 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 gradientTransform follows 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).

  • Stroke extends Fill, so a stroke is a paint plus its geometry; add a paint field to Fill and both get it, and copy it in copyFill, which copyStroke reuses (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).