Skip to content

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

fix(pen): build instances from merged fields and ID-path overrides (#1414)

Danila Poyarkovfcf6198bdaf7
diff --git a/changes/1414/fixed.md b/changes/1414/fixed.md
new file mode 100644
index 000000000..8569e8f44
--- /dev/null
+++ b/changes/1414/fixed.md
@@ -0,0 +1 @@
+- `.pen` instances keep their component's layout and paints when they override only some of them, and their overrides reach layers inside nested instances or replace layers.
diff --git a/packages/pen/src/instances.ts b/packages/pen/src/instances.ts
new file mode 100644
index 000000000..102b9a71b
--- /dev/null
+++ b/packages/pen/src/instances.ts
@@ -0,0 +1,141 @@
+import { generateId, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+import { populateInstanceChildren } from '@open-pencil/scene-graph/instances'
+
+import { applyPenProperties, createSceneNode, type Build } from './nodes'
+import type { PenNode, PenOverride } from './schema'
+
+/** The layers a copy was made from, nearest first, through copies of copies. */
+function sources(graph: SceneGraph, node: SceneNode): Set<string> {
+ const found = new Set<string>()
+ for (
+ let id = node.componentId;
+ id && !found.has(id);
+ id = graph.getNode(id)?.componentId ?? null
+ ) {
+ found.add(id)
+ }
+ return found
+}
+
+/** The copy in `root`'s layers made from the pen.dev layer `sourceId`, at any depth. */
+function findCopy(graph: SceneGraph, root: SceneNode, sourceId: string): SceneNode | undefined {
+ const queue = graph.getChildren(root.id)
+ for (const node of queue) {
+ if (sources(graph, node).has(sourceId)) return node
+ queue.push(...graph.getChildren(node.id))
+ }
+ return undefined
+}
+
+/**
+ * The layer an override's key names: pen.dev IDs separated by `/`, each one inside the copy of the
+ * instance the one before it names.
+ */
+function resolvePath(graph: SceneGraph, instance: SceneNode, path: string): SceneNode | undefined {
+ let current: SceneNode | undefined = instance
+ for (const id of path.split('/')) {
+ current = current ? findCopy(graph, current, id) : undefined
+ }
+ return current
+}
+
+/** Runs `apply` in the merged theme of a layer's ancestors, as the layer was read in. */
+function inAncestorThemes<T>(build: Build, node: SceneNode, apply: () => T): T {
+ const chain: Record<string, string>[] = []
+ for (let id = node.parentId; id; id = build.graph.getNode(id)?.parentId ?? null) {
+ const theme = build.effective.get(id)?.theme
+ if (theme) chain.unshift(theme)
+ }
+ const leave = chain.map((theme) => build.ctx.enterTheme(theme))
+ try {
+ return apply()
+ } finally {
+ for (const exit of leave.toReversed()) exit()
+ }
+}
+
+function replaceLayer(build: Build, target: SceneNode, replacement: PenOverride): void {
+ const { graph } = build
+ const parentId = target.parentId
+ if (!parentId) return
+ const index = graph.getNode(parentId)?.childIds.indexOf(target.id) ?? -1
+ const pen: PenNode = {
+ ...replacement,
+ type: replacement.type ?? 'frame',
+ id: replacement.id ?? generateId()
+ }
+ inAncestorThemes(build, target, () => {
+ graph.deleteNode(target.id)
+ const id = createSceneNode(pen, parentId, build)
+ if (id && index >= 0) graph.insertChildAt(id, parentId, index)
+ })
+}
+
+function overrideLayer(build: Build, target: SceneNode, override: PenOverride): void {
+ const { graph, ctx, effective } = build
+ const base = effective.get(target.id) ?? { type: 'frame', id: target.id }
+ const { descendants: _descendants, children, ...fields } = override
+ const merged: PenNode = { ...base, ...fields, type: base.type, id: base.id }
+ inAncestorThemes(build, target, () => {
+ const leave = merged.theme ? ctx.enterTheme(merged.theme) : undefined
+ try {
+ applyPenProperties(target, merged, build)
+ if (children) {
+ const replaced = target.childIds
+ for (const childId of replaced) graph.deleteNode(childId)
+ for (const child of children) createSceneNode(child, target.id, build)
+ }
+ } finally {
+ leave?.()
+ }
+ })
+}
+
+/** Gives an instance's copies their overrides; a key with a `type` replaces the layer. */
+function applyDescendants(build: Build, instance: SceneNode, ref: PenNode): void {
+ for (const [path, override] of Object.entries(ref.descendants ?? {})) {
+ const target = resolvePath(build.graph, instance, path)
+ if (!target) continue
+ if (override.type) replaceLayer(build, target, override)
+ else overrideLayer(build, target, override)
+ }
+}
+
+/**
+ * Fills each instance with copies of its component's layers, then applies its overrides. An
+ * instance inside a component is filled first, so the copies made of it carry its layers and
+ * overrides; a copy keeps its source's pen.dev fields and placement.
+ */
+export function populateInstances(build: Build): void {
+ const { graph, effective, placements, instances } = build
+ const done = new Set<string>()
+
+ function populate(id: string): void {
+ if (done.has(id)) return
+ done.add(id)
+ const instance = graph.getNode(id)
+ const ref = instances.get(id)
+ if (!instance?.componentId || !ref) return
+ const component = graph.getNode(instance.componentId)
+ if (!component) return
+ for (const nested of instances.keys()) {
+ if (graph.isDescendant(nested, component.id)) populate(nested)
+ }
+ populateInstanceChildren(graph, instance.id, component.id)
+ const copies = graph.getChildren(instance.id)
+ for (const copy of copies) {
+ const source = copy.componentId
+ const fields = source ? effective.get(source) : undefined
+ if (fields) effective.set(copy.id, fields)
+ const placement = source ? placements.get(source) : undefined
+ if (placement) placements.set(copy.id, placement)
+ if (source && build.groupIds.has(source)) build.groupIds.add(copy.id)
+ if (source && build.aroundIds.has(source)) build.aroundIds.add(copy.id)
+ copies.push(...graph.getChildren(copy.id))
+ }
+ applyDescendants(build, instance, ref)
+ }
+
+ // A replacement may hold instances of its own, which join the map as they are read.
+ for (const id of instances.keys()) populate(id)
+}
diff --git a/packages/pen/src/nodes.ts b/packages/pen/src/nodes.ts
new file mode 100644
index 000000000..62439a332
--- /dev/null
+++ b/packages/pen/src/nodes.ts
@@ -0,0 +1,231 @@
+import type {
+ AxisSizingMode,
+ LayoutMode,
+ LayoutSizing,
+ NodeType,
+ SceneGraph,
+ SceneNode
+} from '@open-pencil/scene-graph'
+import { fillSizingFields } from '@open-pencil/scene-graph/layout'
+
+import { convertEffects } from './effects'
+import { ellipseArc, pathNetwork } from './geometry'
+import {
+ applyCornerRadius,
+ applyPadding,
+ mapAlignItems,
+ mapJustifyContent,
+ mapLayoutMode,
+ parseSize
+} from './layout'
+import { applyStroke, convertPaints, strokeFields } from './paints'
+import { isPlain, type PenPlacement } from './placement'
+import type { PenNode, PenOverride } from './schema'
+import { applyTextProps } from './text'
+import { bindIfVar, resolveBoolean, resolveNumber, type VarContext } from './variables'
+
+/** What reading one document builds up. */
+export interface Build {
+ graph: SceneGraph
+ ctx: VarContext
+ /** Reusable nodes by their pen.dev ID. */
+ components: Map<string, PenNode>
+ /** The pen.dev fields each layer was built from, its instance's and overrides' merged in. */
+ effective: Map<string, PenNode>
+ /** Instances in reading order, with the `ref` node that made each. */
+ instances: Map<string, PenNode>
+ /** pen.dev's placement of each turned or mirrored layer, and of every group. */
+ placements: Map<string, PenPlacement>
+ /** Groups in reading order. */
+ groupIds: Set<string>
+ /** Frames spreading their children with `space_around`. */
+ aroundIds: Set<string>
+}
+
+function penPlacement(pen: PenOverride, ctx: VarContext): PenPlacement {
+ return {
+ x: pen.x ?? 0,
+ y: pen.y ?? 0,
+ rotation: resolveNumber(pen.rotation, ctx),
+ flipX: resolveBoolean(pen.flipX, ctx, false),
+ flipY: resolveBoolean(pen.flipY, ctx, false)
+ }
+}
+
+function sceneType(pen: PenNode): NodeType {
+ if (pen.type === 'frame') return pen.reusable ? 'COMPONENT' : 'FRAME'
+ if (pen.type === 'rectangle') return 'RECTANGLE'
+ if (pen.type === 'ellipse') return 'ELLIPSE'
+ if (pen.type === 'polygon') return 'POLYGON'
+ if (pen.type === 'group') return 'GROUP'
+ if (pen.type === 'text' || pen.type === 'icon_font') return 'TEXT'
+ if (pen.type === 'path') return 'VECTOR'
+ return 'FRAME'
+}
+
+function resolveSizing(pen: PenNode, ctx: VarContext) {
+ const isTextLike = pen.type === 'text' || pen.type === 'icon_font'
+ const defaultSize = isTextLike ? 20 : 100
+ const defaultW = isTextLike && pen.width === undefined ? 0 : defaultSize
+ const w = parseSize(pen.width, defaultW, ctx)
+ const h = parseSize(pen.height, defaultSize, ctx)
+ const layout = mapLayoutMode(pen)
+
+ if (pen.width === undefined && layout !== 'NONE') w.sizing = 'HUG'
+ if (pen.height === undefined && layout !== 'NONE') h.sizing = 'HUG'
+
+ return { w, h, layout, isTextLike }
+}
+
+function applyAutoLayout(
+ node: SceneNode,
+ layoutMode: LayoutMode,
+ pen: PenNode,
+ widthSizing: LayoutSizing,
+ heightSizing: LayoutSizing,
+ ctx: VarContext
+): void {
+ node.layoutMode = layoutMode
+ node.primaryAxisAlign = mapJustifyContent(pen.justifyContent)
+ node.counterAxisAlign = mapAlignItems(pen.alignItems)
+ node.itemSpacing = resolveNumber(pen.gap, ctx)
+ bindIfVar(node, 'itemSpacing', pen.gap, ctx)
+ node.strokesIncludedInLayout = pen.layoutIncludeStroke ?? false
+
+ // Fill is the child's grow or stretch, set with its parent; the frame itself stays fixed.
+ const own = (sizing: LayoutSizing): AxisSizingMode => (sizing === 'HUG' ? 'HUG' : 'FIXED')
+ if (layoutMode === 'VERTICAL') {
+ node.primaryAxisSizing = own(heightSizing)
+ node.counterAxisSizing = own(widthSizing)
+ } else {
+ node.primaryAxisSizing = own(widthSizing)
+ node.counterAxisSizing = own(heightSizing)
+ }
+}
+
+/**
+ * Sets every field a layer takes from its pen.dev fields, so a layer copied from a component can be
+ * given its overrides by applying its merged fields again. Turned and mirrored layers are built
+ * upright and placed once laid out.
+ */
+// eslint-disable-next-line complexity -- .pen node mapping touches many format-specific fields
+export function applyPenProperties(node: SceneNode, pen: PenNode, build: Build): void {
+ const { graph, ctx } = build
+ const { w, h, layout, isTextLike } = resolveSizing(pen, ctx)
+ const hasChildren = (pen.children?.length ?? 0) > 0 || node.childIds.length > 0
+ const parentLayout = (node.parentId && graph.getNode(node.parentId)?.layoutMode) || 'NONE'
+ // An absolute layer leaves its parent's flow; fill sizing then falls back to its value.
+ const absolute = pen.layoutPosition === 'absolute' && parentLayout !== 'NONE'
+ const flowLayout = absolute ? 'NONE' : parentLayout
+
+ Object.assign(node, {
+ name: pen.name ?? (pen.type === 'icon_font' ? (pen.iconFontName ?? 'Icon') : pen.type),
+ x: pen.x ?? 0,
+ y: pen.y ?? 0,
+ rotation: 0,
+ flipX: false,
+ flipY: false,
+ width: w.value,
+ height: h.value,
+ minWidth: !hasChildren && w.fitContentFallback !== undefined ? w.fitContentFallback : null,
+ minHeight: !hasChildren && h.fitContentFallback !== undefined ? h.fitContentFallback : null,
+ visible: resolveBoolean(pen.enabled, ctx),
+ opacity: resolveNumber(pen.opacity, ctx, 1),
+ clipsContent: resolveBoolean(pen.clip, ctx, false),
+ layoutPositioning: absolute ? 'ABSOLUTE' : 'AUTO',
+ layoutGrow: 0,
+ layoutAlignSelf: 'AUTO',
+ boundVariables: {},
+ variableModes: pen.theme ? { [ctx.collectionId]: ctx.modeId() } : {}
+ } satisfies Partial<SceneNode>)
+ bindIfVar(node, 'visible', pen.enabled, ctx)
+ bindIfVar(node, 'opacity', pen.opacity, ctx)
+ bindIfVar(node, 'width', pen.width, ctx)
+ bindIfVar(node, 'height', pen.height, ctx)
+
+ node.layoutMode = 'NONE'
+ if (layout !== 'NONE') {
+ const widthSizing = flowLayout === 'NONE' && w.sizing === 'FILL' ? 'FIXED' : w.sizing
+ const heightSizing = flowLayout === 'NONE' && h.sizing === 'FILL' ? 'FIXED' : h.sizing
+ applyAutoLayout(node, layout, pen, widthSizing, heightSizing, ctx)
+ }
+ if (layout !== 'NONE' && pen.justifyContent === 'space_around') build.aroundIds.add(node.id)
+ else build.aroundIds.delete(node.id)
+
+ const placement = penPlacement(pen, ctx)
+ if (pen.type === 'group') build.groupIds.add(node.id)
+ if (pen.type === 'group' || !isPlain(placement)) build.placements.set(node.id, placement)
+ else build.placements.delete(node.id)
+
+ node.fills = convertPaints(pen.fill, 'fills', ctx, node)
+ applyStroke(node, strokeFields(pen), ctx)
+ node.effects = convertEffects(pen.effect, ctx)
+ applyCornerRadius(node, pen.cornerRadius, ctx)
+ applyPadding(node, pen.padding, ctx)
+
+ // Text without a width resizes to its content, which laying out the document measures.
+ if (isTextLike) applyTextProps(node, pen, ctx)
+
+ if (pen.type === 'ellipse') node.arcData = ellipseArc(pen, ctx)
+ if (pen.type === 'polygon') node.pointCount = Math.max(3, resolveNumber(pen.polygonCount, ctx, 3))
+ if (pen.type === 'path') {
+ const network = pathNetwork(pen, node.width, node.height)
+ if (network) node.vectorNetwork = network
+ }
+
+ if (flowLayout !== 'NONE') {
+ if (w.sizing === 'FILL') Object.assign(node, fillSizingFields(flowLayout, 'HORIZONTAL'))
+ if (h.sizing === 'FILL') Object.assign(node, fillSizingFields(flowLayout, 'VERTICAL'))
+ }
+ build.effective.set(node.id, pen)
+}
+
+/**
+ * The fields an instance draws with: its component's, with the `ref` node's own replacing them one
+ * by one, as pen.dev reads them. A theme on both merges axis by axis.
+ */
+function instanceFields(ref: PenNode, component: PenNode | undefined): PenNode {
+ const { ref: _ref, type: _type, descendants: _descendants, children: _children, ...own } = ref
+ if (!component) return { ...own, type: 'frame' }
+ const {
+ id: _id,
+ reusable: _reusable,
+ children: _componentChildren,
+ descendants: _componentDescendants,
+ ...inherited
+ } = component
+ const theme = component.theme || ref.theme ? { ...component.theme, ...ref.theme } : undefined
+ return { ...inherited, ...own, theme, name: ref.name ?? component.name }
+}
+
+/** Builds a layer and its children in the layer's theme, merged over its parent's. */
+export function createSceneNode(pen: PenNode, parentId: string, build: Build): string | null {
+ if (pen.type === 'prompt') return null
+ const component = pen.type === 'ref' && pen.ref ? build.components.get(pen.ref) : undefined
+ // A component that is not a frame has no instances; its uses are plain copies.
+ const instanceOf = pen.type === 'ref' && component?.type === 'frame' ? component : undefined
+ const fields = pen.type === 'ref' ? instanceFields(pen, component) : pen
+ const leaveTheme = fields.theme ? build.ctx.enterTheme(fields.theme) : undefined
+ try {
+ const node = build.graph.createNode(instanceOf ? 'INSTANCE' : sceneType(fields), parentId, {
+ id: pen.id
+ })
+ applyPenProperties(node, fields, build)
+ if (instanceOf) {
+ node.componentId = instanceOf.id
+ build.instances.set(node.id, pen)
+ } else {
+ const children = pen.type === 'ref' ? (component?.children ?? []) : (pen.children ?? [])
+ for (const child of children) {
+ createSceneNode(
+ pen.type === 'ref' ? { ...child, id: `${pen.id}/${child.id}` } : child,
+ node.id,
+ build
+ )
+ }
+ }
+ return node.id
+ } finally {
+ leaveTheme?.()
+ }
+}
diff --git a/packages/pen/src/read.ts b/packages/pen/src/read.ts
index 7c0d2e283..89f9536f4 100644
--- a/packages/pen/src/read.ts
+++ b/packages/pen/src/read.ts
@@ -1,39 +1,13 @@
import * as v from 'valibot'
-import {
- SceneGraph,
- type AxisSizingMode,
- type LayoutMode,
- type LayoutSizing,
- type NodeType,
- type SceneNode
-} from '@open-pencil/scene-graph'
-import { copyEffects, copyFills, copyStrokes } from '@open-pencil/scene-graph/copy'
-import { populateInstanceChildren } from '@open-pencil/scene-graph/instances'
-import { fillSizingFields } from '@open-pencil/scene-graph/layout'
+import { SceneGraph } from '@open-pencil/scene-graph'
-import { convertEffects } from './effects'
-import { ellipseArc, pathNetwork } from './geometry'
-import {
- applyCornerRadius,
- applyPadding,
- mapAlignItems,
- mapJustifyContent,
- mapLayoutMode,
- parseSize,
- spreadAround
-} from './layout'
-import { applyStroke, convertPaints, strokeFields } from './paints'
-import { isPlain, placeLayers, type PenPlacement } from './placement'
-import { penFileSchema, type PenNode, type PenOverride } from './schema'
-import { applyTextProps } from './text'
-import {
- bindIfVar,
- buildVarContext,
- resolveBoolean,
- resolveNumber,
- type VarContext
-} from './variables'
+import { populateInstances } from './instances'
+import { spreadAround } from './layout'
+import { createSceneNode, type Build } from './nodes'
+import { placeLayers } from './placement'
+import { penFileSchema, type PenNode } from './schema'
+import { buildVarContext } from './variables'
/** Options for reading a document. */
export interface PenReadOptions {
@@ -44,383 +18,21 @@ export interface PenReadOptions {
layout?(graph: SceneGraph): void
}
-/** What reading one document builds up. */
-interface Build {
- graph: SceneGraph
- ctx: VarContext
- componentIds: Map<string, string>
- penSources: Map<string, PenNode>
- /** pen.dev's placement of each turned or mirrored layer, and of every group. */
- placements: Map<string, PenPlacement>
- /** Groups in reading order. */
- groupIds: string[]
- /** Frames spreading their children with `space_around`. */
- aroundIds: string[]
-}
-
-function penPlacement(pen: PenOverride, ctx: VarContext, base?: PenPlacement): PenPlacement {
- return {
- x: pen.x ?? base?.x ?? 0,
- y: pen.y ?? base?.y ?? 0,
- rotation: pen.rotation === undefined ? (base?.rotation ?? 0) : resolveNumber(pen.rotation, ctx),
- flipX: pen.flipX === undefined ? (base?.flipX ?? false) : resolveBoolean(pen.flipX, ctx),
- flipY: pen.flipY === undefined ? (base?.flipY ?? false) : resolveBoolean(pen.flipY, ctx)
- }
-}
-
-/** A layer's own fields; it is built upright and placed once laid out. */
-function buildBaseOverrides(pen: PenNode, ctx: VarContext): Partial<SceneNode> {
- return {
- id: pen.id,
- name: pen.name ?? (pen.type === 'icon_font' ? (pen.iconFontName ?? 'Icon') : pen.type),
- x: pen.x ?? 0,
- y: pen.y ?? 0,
- visible: resolveBoolean(pen.enabled, ctx),
- opacity: resolveNumber(pen.opacity, ctx, 1),
- clipsContent: resolveBoolean(pen.clip, ctx, false),
- boundVariables: {}
- }
-}
-
-function applyAutoLayout(
- overrides: Partial<SceneNode>,
- layoutMode: LayoutMode,
- pen: PenNode,
- widthSizing: LayoutSizing,
- heightSizing: LayoutSizing,
- ctx: VarContext
-): void {
- overrides.layoutMode = layoutMode
- overrides.primaryAxisAlign = mapJustifyContent(pen.justifyContent)
- overrides.counterAxisAlign = mapAlignItems(pen.alignItems)
- overrides.itemSpacing = resolveNumber(pen.gap, ctx)
- overrides.strokesIncludedInLayout = pen.layoutIncludeStroke ?? false
-
- // Fill is the child's grow or stretch, set with its parent; the frame itself stays fixed.
- const own = (sizing: LayoutSizing): AxisSizingMode => (sizing === 'HUG' ? 'HUG' : 'FIXED')
- if (layoutMode === 'VERTICAL') {
- overrides.primaryAxisSizing = own(heightSizing)
- overrides.counterAxisSizing = own(widthSizing)
- } else {
- overrides.primaryAxisSizing = own(widthSizing)
- overrides.counterAxisSizing = own(heightSizing)
- }
-}
-
-function resolveSizing(pen: PenNode, ctx: VarContext) {
- const isTextLike = pen.type === 'text' || pen.type === 'icon_font'
- const defaultSize = isTextLike ? 20 : 100
- const defaultW = isTextLike && pen.width === undefined ? 0 : defaultSize
- const w = parseSize(pen.width, defaultW, ctx)
- const h = parseSize(pen.height, defaultSize, ctx)
- const layout = mapLayoutMode(pen)
-
- if (pen.width === undefined && layout !== 'NONE') w.sizing = 'HUG'
- if (pen.height === undefined && layout !== 'NONE') h.sizing = 'HUG'
-
- return { w, h, layout, isTextLike }
-}
-
-function inheritLayoutFromComp(node: SceneNode, pen: PenNode, comp: SceneNode): void {
- const wasRow = node.layoutMode === 'HORIZONTAL'
- node.layoutMode = comp.layoutMode
- node.primaryAxisAlign = comp.primaryAxisAlign
- node.counterAxisAlign = comp.counterAxisAlign
- const isRow = node.layoutMode === 'HORIZONTAL'
- if (wasRow !== isRow) {
- const oldP = node.primaryAxisSizing
- node.primaryAxisSizing = node.counterAxisSizing
- node.counterAxisSizing = oldP
- }
- const widthAxis = isRow ? 'primaryAxisSizing' : 'counterAxisSizing'
- const heightAxis = isRow ? 'counterAxisSizing' : 'primaryAxisSizing'
- if (pen.width === undefined) node[widthAxis] = comp[widthAxis]
- if (pen.height === undefined) node[heightAxis] = comp[heightAxis]
- if (pen.gap === undefined) node.itemSpacing = comp.itemSpacing
- if (pen.padding === undefined) {
- node.paddingTop = comp.paddingTop
- node.paddingRight = comp.paddingRight
- node.paddingBottom = comp.paddingBottom
- node.paddingLeft = comp.paddingLeft
- }
- if (pen.clip === undefined) node.clipsContent = comp.clipsContent
-}
-
-function applyRefVisuals(
- node: SceneNode,
- pen: PenNode,
- compPen: PenNode | undefined,
- ctx: VarContext
-): void {
- if (!compPen) return
- if (pen.fill === undefined) node.fills = convertPaints(compPen.fill, 'fills', ctx, node)
- applyStroke(node, strokeFields(pen, strokeFields(compPen)), ctx)
- if (pen.effect === undefined) node.effects = convertEffects(compPen.effect, ctx)
- if (pen.cornerRadius === undefined) applyCornerRadius(node, compPen.cornerRadius, ctx)
-}
-
-function applyRefProps(node: SceneNode, pen: PenNode, build: Build): void {
- const { graph, componentIds, penSources, ctx } = build
- if (!pen.ref) return
- const componentId = componentIds.get(pen.ref) ?? pen.ref
- node.componentId = componentId
- const comp = graph.getNode(componentId)
- if (!comp) return
- if (pen.width === undefined) node.width = comp.width
- if (pen.height === undefined) node.height = comp.height
- if (pen.layout === undefined) inheritLayoutFromComp(node, pen, comp)
- applyRefVisuals(node, pen, penSources.get(pen.ref), ctx)
-}
-
-function applyAllRefProps(penNodes: PenNode[], build: Build): void {
- for (const pen of penNodes) {
- if (pen.type === 'ref') {
- const node = build.graph.getNode(pen.id)
- if (node) applyRefProps(node, pen, build)
- }
- if (pen.children) applyAllRefProps(pen.children, build)
- }
-}
-
-/** Builds a layer and its children in the layer's theme, merged over its parent's. */
-function createSceneNode(pen: PenNode, parentId: string, build: Build): string | null {
- const { ctx } = build
- if (pen.type === 'prompt') return null
- const leaveTheme = pen.theme ? ctx.enterTheme(pen.theme) : undefined
- try {
- return buildSceneNode(pen, parentId, build)
- } finally {
- leaveTheme?.()
- }
-}
-
-// eslint-disable-next-line complexity -- .pen node mapping touches many format-specific fields
-function buildSceneNode(pen: PenNode, parentId: string, build: Build): string {
- const { graph, ctx } = build
-
- const { w, h, layout, isTextLike } = resolveSizing(pen, ctx)
- const overrides = buildBaseOverrides(pen, ctx)
- overrides.width = w.value
- overrides.height = h.value
- const hasChildren = (pen.children?.length ?? 0) > 0
- if (!hasChildren && w.fitContentFallback !== undefined) overrides.minWidth = w.fitContentFallback
- if (!hasChildren && h.fitContentFallback !== undefined) overrides.minHeight = h.fitContentFallback
-
- const parentLayout = graph.getNode(parentId)?.layoutMode ?? 'NONE'
- // An absolute layer leaves its parent's flow; fill sizing then falls back to its value.
- const absolute = pen.layoutPosition === 'absolute' && parentLayout !== 'NONE'
- if (absolute) overrides.layoutPositioning = 'ABSOLUTE'
- const flowLayout = absolute ? 'NONE' : parentLayout
- if (layout !== 'NONE') {
- const widthSizing =
- flowLayout === 'NONE' && w.sizing === 'FILL' ? ('FIXED' as LayoutSizing) : w.sizing
- const heightSizing =
- flowLayout === 'NONE' && h.sizing === 'FILL' ? ('FIXED' as LayoutSizing) : h.sizing
- applyAutoLayout(overrides, layout, pen, widthSizing, heightSizing, ctx)
- }
-
- const node = graph.createNode(mapNodeType(pen), parentId, overrides)
- if (pen.theme) node.variableModes = { [ctx.collectionId]: ctx.modeId() }
- bindIfVar(node, 'visible', pen.enabled, ctx)
- bindIfVar(node, 'opacity', pen.opacity, ctx)
- bindIfVar(node, 'width', pen.width, ctx)
- bindIfVar(node, 'height', pen.height, ctx)
- const placement = penPlacement(pen, ctx)
- if (pen.type === 'group') build.groupIds.push(node.id)
- if (layout !== 'NONE' && pen.justifyContent === 'space_around') build.aroundIds.push(node.id)
- bindIfVar(node, 'itemSpacing', pen.gap, ctx)
- if (pen.type === 'group' || !isPlain(placement)) build.placements.set(node.id, placement)
-
- node.fills = convertPaints(pen.fill, 'fills', ctx, node)
- applyStroke(node, strokeFields(pen), ctx)
- node.effects = convertEffects(pen.effect, ctx)
- applyCornerRadius(node, pen.cornerRadius, ctx)
- applyPadding(node, pen.padding, ctx)
-
- // Text without a width resizes to its content, which laying out the document measures.
- if (isTextLike) applyTextProps(node, pen, ctx)
-
- if (pen.type === 'ellipse') node.arcData = ellipseArc(pen, ctx)
- if (pen.type === 'polygon') node.pointCount = Math.max(3, resolveNumber(pen.polygonCount, ctx, 3))
- if (pen.type === 'path') {
- const network = pathNetwork(pen, node.width, node.height)
- if (network) node.vectorNetwork = network
- }
-
- if (flowLayout !== 'NONE') {
- if (w.sizing === 'FILL') Object.assign(node, fillSizingFields(flowLayout, 'HORIZONTAL'))
- if (h.sizing === 'FILL') Object.assign(node, fillSizingFields(flowLayout, 'VERTICAL'))
- }
-
- if (pen.reusable) {
- build.componentIds.set(pen.id, node.id)
- build.penSources.set(pen.id, pen)
- }
-
- if (pen.children) {
- for (const child of pen.children) createSceneNode(child, node.id, build)
- }
-
- return node.id
-}
-
-function collectByNameType(
- graph: SceneGraph,
- parentId: string,
- name: string,
- type: string,
- out: SceneNode[],
- depth: number
-): void {
- if (depth > 2) return
- const parent = graph.getNode(parentId)
- if (!parent) return
- for (const childId of parent.childIds) {
- const child = graph.getNode(childId)
- if (!child) continue
- if (child.name === name && child.type === type) out.push(child)
- collectByNameType(graph, childId, name, type, out, depth + 1)
- }
-}
-
-function findCloneByComponentId(
- graph: SceneGraph,
- parentId: string,
- origId: string
-): SceneNode | undefined {
- const parent = graph.getNode(parentId)
- if (!parent) return undefined
- for (const childId of parent.childIds) {
- const child = graph.getNode(childId)
- if (!child) continue
- if (child.componentId === origId) return child
- const deep = findCloneByComponentId(graph, childId, origId)
- if (deep) return deep
- }
- return undefined
-}
-
-function findCloneByNameFallback(
- graph: SceneGraph,
- parentId: string,
- origId: string
-): SceneNode | undefined {
- const orig = graph.getNode(origId)
- if (!orig) return undefined
- const matches: SceneNode[] = []
- collectByNameType(graph, parentId, orig.name, orig.type, matches, 0)
- return matches.length === 1 ? matches[0] : undefined
-}
-
-function applyOverrideProps(target: SceneNode, overrideData: PenOverride, build: Build): void {
- const { ctx } = build
- if (overrideData.fill !== undefined)
- target.fills = convertPaints(overrideData.fill, 'fills', ctx, target)
- if (overrideData.content !== undefined) target.text = overrideData.content
- if (overrideData.x !== undefined) target.x = overrideData.x
- if (overrideData.y !== undefined) target.y = overrideData.y
- const base = build.placements.get(target.id)
- const placement = penPlacement(overrideData, ctx, base ?? { ...target, rotation: 0 })
- if (base || !isPlain(placement)) build.placements.set(target.id, placement)
- if (overrideData.enabled !== undefined) target.visible = resolveBoolean(overrideData.enabled, ctx)
- if (overrideData.width !== undefined)
- target.width = parseSize(overrideData.width, target.width, ctx).value
- if (overrideData.height !== undefined)
- target.height = parseSize(overrideData.height, target.height, ctx).value
- if (overrideData.name !== undefined) target.name = overrideData.name
-}
-
-/** Fills empty instances from their components; a copied layer keeps its source's placement. */
-function populateInstances(build: Build): void {
- const { graph, placements } = build
- for (const node of graph.getAllNodes()) {
- if (node.type !== 'INSTANCE' || !node.componentId || node.childIds.length > 0) continue
- if (!graph.getNode(node.componentId)) continue
- populateInstanceChildren(graph, node.id, node.componentId)
- const copies = [...graph.getChildren(node.id)]
- for (const copy of copies) {
- const source = copy.componentId ? placements.get(copy.componentId) : undefined
- if (source && !placements.has(copy.id)) placements.set(copy.id, source)
- copies.push(...graph.getChildren(copy.id))
- }
- }
-}
-
-function applyDescendantOverrides(pen: PenNode, build: Build): void {
- const { graph } = build
- if (pen.type !== 'ref' || !pen.descendants) return
- const instanceNode = graph.getNode(pen.id)
- if (!instanceNode) return
-
- for (const [origId, overrideData] of Object.entries(pen.descendants)) {
- const clone =
- findCloneByComponentId(graph, instanceNode.id, origId) ??
- findCloneByNameFallback(graph, instanceNode.id, origId)
-
- if (clone) {
- if (overrideData.children) {
- const toDelete = clone.childIds.slice()
- for (const childId of toDelete) graph.deleteNode(childId)
- for (const child of overrideData.children) createSceneNode(child, clone.id, build)
- }
- applyOverrideProps(clone, overrideData, build)
- continue
- }
-
- if (overrideData.type && overrideData.id) {
- createSceneNode(overrideData as PenNode, instanceNode.id, build)
- }
- }
-}
-
-function walkAndApplyOverrides(nodes: PenNode[], build: Build): void {
- for (const pen of nodes) {
- applyDescendantOverrides(pen, build)
- if (pen.children) walkAndApplyOverrides(pen.children, build)
- }
-}
-
-function collectComponentIds(nodes: PenNode[], map: Map<string, string>): void {
+function collectComponents(nodes: PenNode[], components: Map<string, PenNode>): void {
for (const node of nodes) {
- if (node.reusable) map.set(node.id, node.id)
- if (node.children) collectComponentIds(node.children, map)
+ if (node.reusable) components.set(node.id, node)
+ if (node.children) collectComponents(node.children, components)
}
}
-function fixInstanceWidths(graph: SceneGraph): void {
- for (const node of graph.getAllNodes()) {
- if (node.type !== 'INSTANCE' || !node.componentId) continue
- const comp = graph.getNode(node.componentId)
- if (!comp) continue
- if (node.width <= 100 && comp.width > 100) node.width = comp.width
- if (node.height <= 100 && comp.height > 100) node.height = comp.height
- if (comp.layoutGrow > 0) node.layoutGrow = comp.layoutGrow
- if (comp.layoutAlignSelf !== 'AUTO') node.layoutAlignSelf = comp.layoutAlignSelf
- node.fills = copyFills(node.fills)
- node.strokes = copyStrokes(node.strokes)
- node.effects = copyEffects(node.effects)
- }
-}
-
-function mapNodeType(pen: PenNode): NodeType {
- if (pen.type === 'frame') return pen.reusable ? 'COMPONENT' : 'FRAME'
- if (pen.type === 'rectangle') return 'RECTANGLE'
- if (pen.type === 'ellipse') return 'ELLIPSE'
- if (pen.type === 'polygon') return 'POLYGON'
- if (pen.type === 'group') return 'GROUP'
- if (pen.type === 'text' || pen.type === 'icon_font') return 'TEXT'
- if (pen.type === 'path') return 'VECTOR'
- if (pen.type === 'ref') return 'INSTANCE'
- return 'FRAME'
-}
-
/** Whether a group sits in an auto layout's flow, where fitting it changes the layout. */
-function groupsInFlow(graph: SceneGraph, groupIds: readonly string[]): boolean {
- return groupIds.some((id) => {
+function groupsInFlow(graph: SceneGraph, groupIds: Iterable<string>): boolean {
+ for (const id of groupIds) {
const group = graph.getNode(id)
const parent = group?.parentId ? graph.getNode(group.parentId) : undefined
- return parent !== undefined && parent.layoutMode !== 'NONE'
- })
+ if (parent && parent.layoutMode !== 'NONE') return true
+ }
+ return false
}
export function parsePenFile(json: string, options: PenReadOptions = {}): SceneGraph {
@@ -435,31 +47,25 @@ export function parsePenFile(json: string, options: PenReadOptions = {}): SceneG
graph.deleteNode(page.id)
}
- const ctx = buildVarContext(graph, doc)
const build: Build = {
graph,
- ctx,
- componentIds: new Map(),
- penSources: new Map(),
+ ctx: buildVarContext(graph, doc),
+ components: new Map(),
+ effective: new Map(),
+ instances: new Map(),
placements: new Map(),
- groupIds: [],
- aroundIds: []
+ groupIds: new Set(),
+ aroundIds: new Set()
}
-
- collectComponentIds(doc.children, build.componentIds)
+ collectComponents(doc.children, build.components)
const page = graph.addPage(doc.children[0]?.name ?? 'Page 1')
for (const child of doc.children) createSceneNode(child, page.id, build)
-
- applyAllRefProps(doc.children, build)
- populateInstances(build)
- walkAndApplyOverrides(doc.children, build)
populateInstances(build)
- fixInstanceWidths(graph)
options.layout?.(graph)
- const spread = options.layout ? spreadAround(graph, build.aroundIds) : false
- placeLayers(graph, build.placements, build.groupIds)
+ const spread = options.layout ? spreadAround(graph, [...build.aroundIds]) : false
+ placeLayers(graph, build.placements, [...build.groupIds])
if (spread || groupsInFlow(graph, build.groupIds)) options.layout?.(graph)
if (graph.getPages(true).length === 0) {
diff --git a/packages/pen/tests/instances.test.ts b/packages/pen/tests/instances.test.ts
new file mode 100644
index 000000000..5ef603c00
--- /dev/null
+++ b/packages/pen/tests/instances.test.ts
@@ -0,0 +1,138 @@
+import { describe, expect, test } from 'bun:test'
+
+import type { PenNode } from '@open-pencil/pen'
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+import { expectDefined, getNodeOrThrow } from './helpers/assert'
+import { parseDocument } from './helpers/document'
+
+const button: PenNode = {
+ id: 'button',
+ type: 'frame',
+ reusable: true,
+ layout: 'horizontal',
+ alignItems: 'center',
+ padding: [8, 14],
+ gap: 6,
+ fill: '#2255CC',
+ children: [
+ { id: 'dot', type: 'ellipse', width: 10, height: 10, fill: '#FFFFFF' },
+ { id: 'label', type: 'text', content: 'Button', fontSize: 14, fill: '#FFFFFF' }
+ ]
+}
+
+const card: PenNode = {
+ id: 'card',
+ type: 'frame',
+ reusable: true,
+ layout: 'vertical',
+ children: [
+ { id: 'title', type: 'text', content: 'Card title', fill: '#111111' },
+ { id: 'cardButton', type: 'ref', ref: 'button' }
+ ]
+}
+
+function layers(graph: SceneGraph, id: string): SceneNode[] {
+ const found: SceneNode[] = []
+ const queue = [...graph.getChildren(id)]
+ for (const node of queue) {
+ found.push(node)
+ queue.push(...graph.getChildren(node.id))
+ }
+ return found
+}
+
+/** The copy in an instance made, through copies of copies, from the pen.dev layer `sourceId`. */
+function copyOf(graph: SceneGraph, instanceId: string, sourceId: string): SceneNode {
+ const madeFrom = (node: SceneNode): boolean => {
+ for (let id = node.componentId; id; id = graph.getNode(id)?.componentId ?? null) {
+ if (id === sourceId) return true
+ }
+ return false
+ }
+ return expectDefined(layers(graph, instanceId).find(madeFrom), `${sourceId} in ${instanceId}`)
+}
+
+describe('parsePenFile — instances', () => {
+ test('fills an instance with copies linked to the component', () => {
+ const graph = parseDocument([button, { id: 'plain', type: 'ref', ref: 'button' }])
+ const instance = getNodeOrThrow(graph, 'plain')
+ expect(instance.type).toBe('INSTANCE')
+ expect(instance.componentId).toBe('button')
+ expect(graph.getChildren('plain').map((node) => node.componentId)).toEqual(['dot', 'label'])
+ })
+
+ test('replaces the component fields the ref sets, keeping the rest', () => {
+ const graph = parseDocument([
+ button,
+ { id: 'tall', type: 'ref', ref: 'button', layout: 'vertical', padding: 12 }
+ ])
+ expect(getNodeOrThrow(graph, 'tall')).toMatchObject({
+ layoutMode: 'VERTICAL',
+ counterAxisAlign: 'CENTER',
+ itemSpacing: 6,
+ paddingTop: 12,
+ paddingLeft: 12
+ })
+ })
+
+ test('overrides a descendant by its ID', () => {
+ const graph = parseDocument([
+ button,
+ { id: 'changed', type: 'ref', ref: 'button', descendants: { label: { content: 'Changed' } } }
+ ])
+ expect(copyOf(graph, 'changed', 'label').text).toBe('Changed')
+ expect(getNodeOrThrow(graph, 'label').text).toBe('Button')
+ })
+
+ test('follows an ID path through a nested instance', () => {
+ const graph = parseDocument([
+ button,
+ card,
+ {
+ id: 'nested',
+ type: 'ref',
+ ref: 'card',
+ descendants: { 'cardButton/label': { content: 'Deep' }, cardButton: { fill: '#119944' } }
+ }
+ ])
+ const nestedButton = expectDefined(
+ graph.getChildren('nested').find((node) => node.componentId === 'cardButton'),
+ 'nested button copy'
+ )
+ expect(nestedButton.fills[0]?.color).toMatchObject({ r: 0x11 / 255, g: 0x99 / 255 })
+ expect(copyOf(graph, nestedButton.id, 'label').text).toBe('Deep')
+ })
+
+ test('replaces a descendant whose override has a type', () => {
+ const graph = parseDocument([
+ button,
+ {
+ id: 'swapped',
+ type: 'ref',
+ ref: 'button',
+ descendants: {
+ dot: { type: 'rectangle', id: 'square', width: 10, height: 10, fill: '#FFFF00' }
+ }
+ }
+ ])
+ expect(graph.getChildren('swapped').map((node) => node.type)).toEqual(['RECTANGLE', 'TEXT'])
+ expect(getNodeOrThrow(graph, 'square').fills[0]?.color).toMatchObject({ r: 1, g: 1, b: 0 })
+ })
+
+ test('hides a descendant through its enabled field', () => {
+ const graph = parseDocument([
+ button,
+ { id: 'hidden', type: 'ref', ref: 'button', descendants: { dot: { enabled: false } } }
+ ])
+ expect(copyOf(graph, 'hidden', 'dot').visible).toBe(false)
+ })
+
+ test('copies a reusable layer that is not a frame', () => {
+ const graph = parseDocument([
+ { id: 'swatch', type: 'rectangle', reusable: true, width: 20, height: 20, fill: '#FF0000' },
+ { id: 'use', type: 'ref', ref: 'swatch', x: 40 }
+ ])
+ expect(getNodeOrThrow(graph, 'use')).toMatchObject({ type: 'RECTANGLE', x: 40, width: 20 })
+ })
+})