AI-native design editor. Open-source Figma alternative.
fix(code): preview a code edit's roots in one render (#1659)
Danila Poyarkov932e499b033e
diff --git a/packages/core/src/library/copied-references.ts b/packages/core/src/library/copied-references.tsdeleted file mode 100644index 3cde1356a..000000000--- a/packages/core/src/library/copied-references.ts+++ /dev/null@@ -1,61 +0,0 @@-import { mapValues } from 'es-toolkit'--import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'-import { remapInstanceOverrideState } from '@open-pencil/scene-graph/instances/overrides'--function remappedReferences(- node: SceneNode,- mapped: (id: string) => string,- swapProperties: ReadonlySet<string>-): Partial<SceneNode> {- const changes: Partial<SceneNode> = {}- if (node.componentId && mapped(node.componentId) !== node.componentId)- changes.componentId = mapped(node.componentId)- const overrides = node.instanceOverrides- if (overrides.self.size > 0 || overrides.descendants.size > 0) {- changes.instanceOverrides = remapInstanceOverrideState(overrides, {- node: mapped,- variable: (id) => id- })- }- if (node.componentPropertyDefinitions.some((definition) => definition.type === 'INSTANCE_SWAP')) {- changes.componentPropertyDefinitions = node.componentPropertyDefinitions.map((definition) =>- definition.type === 'INSTANCE_SWAP' && definition.defaultValue- ? { ...definition, defaultValue: mapped(definition.defaultValue) }- : definition- )- }- if (Object.keys(node.componentPropertyAssignments).some((id) => swapProperties.has(id))) {- changes.componentPropertyAssignments = mapValues(- node.componentPropertyAssignments,- (value, id) => (swapProperties.has(id) ? mapped(value) : value)- )- }- return changes-}--/**- * Points the layers a library copy made at one another, as `prepareNodeTransfer` does for a- * paste: an instance's main component, the layers its overrides change and the components they- * swap in, and the components an instance-swap property defaults to or is set to. `mappedIds`- * maps each copied layer to its copy; a reference outside the copy stays as it is, and so do- * variable IDs, since the copies keep their source's variables.- */-export function remapCopiedReferences(- graph: SceneGraph,- mappedIds: ReadonlyMap<string, string>-): void {- const mapped = (id: string) => mappedIds.get(id) ?? id- const copies = [...mappedIds.values()].flatMap((id) => graph.getNode(id) ?? [])- const swapProperties = new Set(- copies.flatMap((node) =>- node.componentPropertyDefinitions- .filter((definition) => definition.type === 'INSTANCE_SWAP')- .map((definition) => definition.id)- )- )- for (const node of copies) {- const changes = remappedReferences(node, mapped, swapProperties)- if (Object.keys(changes).length > 0) graph.updateNode(node.id, changes)- }-}diff --git a/packages/core/src/library/materialize.ts b/packages/core/src/library/materialize.tsindex 1a9983196..ecae3a01d 100644--- a/packages/core/src/library/materialize.ts+++ b/packages/core/src/library/materialize.ts@@ -1,8 +1,8 @@import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { cloneNodeProps } from '@open-pencil/scene-graph/copy'+import { remapCopiedReferences } from '@open-pencil/scene-graph/transfer'import { regionFills } from '@open-pencil/scene-graph/vector-network'-import { remapCopiedReferences } from './copied-references'import { findLibraryDefinition } from './definitions'import { assertLibraryAssetKey, assertLibraryId, libraryAssetIdentityKey } from './identity'import type { ComponentLibraryRevision, LibraryAssetDescriptor } from './types'diff --git a/packages/core/src/library/snapshot.ts b/packages/core/src/library/snapshot.tsindex 7ac418366..528a3dd8e 100644--- a/packages/core/src/library/snapshot.ts+++ b/packages/core/src/library/snapshot.ts@@ -2,9 +2,9 @@ import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'import { cloneNodeProps } from '@open-pencil/scene-graph/copy'import { standardStyleName } from '@open-pencil/scene-graph/font-style'import { contentPluginData } from '@open-pencil/scene-graph/plugin-data'+import { remapCopiedReferences } from '@open-pencil/scene-graph/transfer'import { existingAssetKey } from './asset-keys'-import { remapCopiedReferences } from './copied-references'import { contentHash } from './hash'import { assertLibraryAssetKey } from './identity'import type { LibraryAssetDescriptor, PortableLibrarySnapshot } from './types'diff --git a/packages/core/tests/design-jsx/renderer.test.ts b/packages/core/tests/design-jsx/renderer.test.tsindex 87cb5ffce..cc1d2b7f4 100644--- a/packages/core/tests/design-jsx/renderer.test.ts+++ b/packages/core/tests/design-jsx/renderer.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from 'bun:test'-import { renderTree } from '@open-pencil/core/design-jsx'+import { renderRoots, renderTree } from '@open-pencil/core/design-jsx'import type { TreeNode } from '@open-pencil/design-jsx'import { SceneGraph } from '@open-pencil/scene-graph'@@ -51,3 +51,26 @@ describe('renderTree sizing', () => {expect(text?.width).toBeGreaterThan(text?.height ?? 0)})})++describe('renderRoots positions', () => {+ test('place each root at its own entry, and leave a coordinate the entry omits', async () => {+ const graph = new SceneGraph()+ const frame = (name: string, x?: number): TreeNode => ({+ type: 'frame',+ props: { name, w: 100, h: 50, ...(x !== undefined && { x }) },+ children: []+ })+ const tree: TreeNode = { type: '', props: {}, children: [frame('A'), frame('B', 300)] }++ const [a, b] = await renderRoots(graph, tree, {+ x: 500,+ positions: [+ { x: 10, y: 20 },+ { y: 40 }+ ]+ })++ expect(graph.getNode(a.id)).toMatchObject({ x: 10, y: 20 })+ expect(graph.getNode(b.id)).toMatchObject({ x: 300, y: 40 })+ })+})diff --git a/packages/design-jsx/AGENTS.md b/packages/design-jsx/AGENTS.mdindex 4fe182e0f..7a97800a0 100644--- a/packages/design-jsx/AGENTS.md+++ b/packages/design-jsx/AGENTS.md@@ -4,7 +4,7 @@ OpenPencil's design JSX: the elements (`Frame`, `Text`, …) and the trees theyRules:-- Depend only on `@open-pencil/scene-graph` and `@open-pencil/emit`. Engine work the renderer needs — icon lookup, SVG path conversion, vector node creation, and layout — comes in through `DesignJSXServices` (`src/services.ts`). Core binds them in `packages/core/src/design-jsx/renderer.ts` and exports the bound `renderJSX` and `renderTree` from `@open-pencil/core/design-jsx`.+- Depend only on `@open-pencil/scene-graph` and `@open-pencil/emit`. Engine work the renderer needs — icon lookup, SVG path conversion, vector node creation, and layout — comes in through `DesignJSXServices` (`src/services.ts`). Core binds them in `packages/core/src/design-jsx/renderer.ts` and exports the bound `renderJSX`, `renderTree`, and `renderRoots` from `@open-pencil/core/design-jsx`.- The `layout` service receives the rendered roots. A caller that moves them into place afterwards passes `deferLayout` and lays them out once (`packages/core/src/design-jsx/placement.ts`).- `src/streaming/` parses JSX as it streams in and projects the static subset into trees without evaluating expressions; Core's `packages/core/src/design-jsx/preview/` stages and records those trees on the canvas.- Each element is one entry in `DESIGN_JSX_ELEMENTS` (`src/elements/index.ts`): its name, the layer type it builds and the types it writes, and its props. The runtime bindings, renderer, export tag, unsupported-prop warnings, schema, and reference read it; do not add a parallel tag or type map (`tests/elements/index.test.ts`).diff --git a/packages/design-jsx/src/render/reconcile.ts b/packages/design-jsx/src/render/reconcile.tsindex c32ee25b4..6ebbb3901 100644--- a/packages/design-jsx/src/render/reconcile.ts+++ b/packages/design-jsx/src/render/reconcile.ts@@ -1,4 +1,5 @@import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { remapCopiedReferences } from '@open-pencil/scene-graph/transfer'/*** Fields a layer keeps when its code is rendered again: its place in the tree and the identity@@ -111,8 +112,9 @@ class Reconciler {/*** Folds freshly rendered layers into the layers they replace, so code edits update layers in* place: matched layers keep their ids, and only the properties that differ change. Roots pair- * by position; extra rendered roots stay, extra existing roots are deleted. Returns the id each- * rendered layer ends up with.+ * by position; extra rendered roots stay, extra existing roots are deleted. A rendered layer that+ * pointed at another, such as an instance at its component or a connector at the layers it joins,+ * points at that layer's kept id. Returns the id each rendered layer ends up with.*/export function reconcileRenderedLayers(graph: SceneGraph,@@ -130,5 +132,6 @@ export function reconcileRenderedLayers(return [rendered.id]})for (const id of existingRootIds.slice(renderedRootIds.length)) graph.deleteNode(id)+ remapCopiedReferences(graph, reconciler.ids)return { rootIds, ids: reconciler.ids }}diff --git a/packages/design-jsx/src/render/roots.ts b/packages/design-jsx/src/render/roots.tsindex 3ea396fdd..d11582e57 100644--- a/packages/design-jsx/src/render/roots.ts+++ b/packages/design-jsx/src/render/roots.ts@@ -132,8 +132,9 @@ async function renderInto<Artwork>(undefined,context)- if (options.x !== undefined) graph.updateNode(node.id, { x: options.x })- if (options.y !== undefined) graph.updateNode(node.id, { y: options.y })+ const { x, y } = options.positions?.[index] ?? options+ if (x !== undefined) graph.updateNode(node.id, { x })+ if (y !== undefined) graph.updateNode(node.id, { y })nodes[index] = node}diff --git a/packages/design-jsx/src/render/types.ts b/packages/design-jsx/src/render/types.tsindex 22d09b1dc..4586156cc 100644--- a/packages/design-jsx/src/render/types.ts+++ b/packages/design-jsx/src/render/types.ts@@ -1,10 +1,13 @@import type { SceneNode } from '@open-pencil/scene-graph'+import type { Vector } from '@open-pencil/scene-graph/primitives'import type { TreeNode } from '../tree'export interface RenderOptions {x?: numbery?: number+ /** Each root's position, in the order the roots are written; an entry replaces `x` and `y`. */+ positions?: ReadonlyArray<Partial<Vector>>parentId?: string/** Called for every layer created from an element, so callers can map source to layers. */onNode?: (tree: TreeNode, node: SceneNode) => voiddiff --git a/packages/design-jsx/tests/render/reconcile.test.ts b/packages/design-jsx/tests/render/reconcile.test.tsindex e2af431b7..fced74123 100644--- a/packages/design-jsx/tests/render/reconcile.test.ts+++ b/packages/design-jsx/tests/render/reconcile.test.ts@@ -114,4 +114,33 @@ describe('reconcileRenderedLayers', () => {expect(graph.getNode(one)?.name).toBe('One again')expect(graph.getNode(two)).toBeUndefined()})++ test('points rendered instances and connectors at the layers kept in place', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0].id+ const render = () => {+ const card = graph.createNode('COMPONENT', page, { name: 'Card' })+ const copy = graph.createNode('INSTANCE', page, { name: 'Card copy', componentId: card.id })+ const end = (nodeId: string) => ({+ nodeId,+ magnet: 'AUTO' as const,+ position: { x: 0, y: 0 }+ })+ const link = graph.createNode('CONNECTOR', page, {+ name: 'Link',+ connectorStart: end(card.id),+ connectorEnd: end(copy.id)+ })+ return [card.id, copy.id, link.id]+ }+ const before = render()+ const after = render()++ const { rootIds } = reconcileRenderedLayers(graph, before, after)++ const [card, copy, link] = rootIds.map((id) => graph.getNode(id))+ expect(card?.id).toBe(before[0])+ expect(copy?.componentId).toBe(card?.id)+ expect([link?.connectorStart?.nodeId, link?.connectorEnd?.nodeId]).toEqual([card?.id, copy?.id])+ })})diff --git a/packages/scene-graph/src/transfer/copied.ts b/packages/scene-graph/src/transfer/copied.tsnew file mode 100644index 000000000..b6105668a--- /dev/null+++ b/packages/scene-graph/src/transfer/copied.ts@@ -0,0 +1,72 @@+import { isEqual, mapValues } from 'es-toolkit'++import { componentPropertyDefinitions } from '../components/properties'+import type { SceneGraph } from '../graph'+import { remapInstanceOverrideState } from '../instances/overrides'+import type { ComponentPropertyDefinition, SceneNode } from '../types'++function swapPropertyIds(definitions: readonly ComponentPropertyDefinition[]): string[] {+ return definitions+ .filter((definition) => definition.type === 'INSTANCE_SWAP')+ .map((definition) => definition.id)+}++function remappedReferences(+ node: SceneNode,+ mapped: (id: string) => string,+ swapProperties: ReadonlySet<string>+): Partial<SceneNode> {+ const changes: Partial<SceneNode> = {}+ if (node.componentId && mapped(node.componentId) !== node.componentId)+ changes.componentId = mapped(node.componentId)+ // Only what a mapping changes: every write is an update collaboration sends.+ const overrides = remapInstanceOverrideState(node.instanceOverrides, {+ node: mapped,+ variable: (id) => id+ })+ if (!isEqual(overrides, node.instanceOverrides)) changes.instanceOverrides = overrides+ const definitions = node.componentPropertyDefinitions.map((definition) =>+ definition.type === 'INSTANCE_SWAP' && definition.defaultValue+ ? { ...definition, defaultValue: mapped(definition.defaultValue) }+ : definition+ )+ if (!isEqual(definitions, node.componentPropertyDefinitions))+ changes.componentPropertyDefinitions = definitions+ const assignments = mapValues(node.componentPropertyAssignments, (value, id) =>+ swapProperties.has(id) ? mapped(value) : value+ )+ if (!isEqual(assignments, node.componentPropertyAssignments))+ changes.componentPropertyAssignments = assignments+ for (const field of ['connectorStart', 'connectorEnd'] as const) {+ const endpoint = node[field]+ if (endpoint?.nodeId && mapped(endpoint.nodeId) !== endpoint.nodeId)+ changes[field] = { ...endpoint, nodeId: mapped(endpoint.nodeId) }+ }+ return changes+}++/**+ * Points copied layers at one another, as `prepareNodeTransfer` does for a paste: an instance's+ * main component, the layers its overrides change and the components they swap in, the+ * components an instance-swap property defaults to or is set to, and the layers a connector's+ * ends follow. `mappedIds` maps each copied layer to its copy, such as a library copy or a design+ * JSX render folded into the layers it replaces; a reference outside the copy stays as it is, and+ * so do variable IDs, since the copies keep their source's variables.+ */+export function remapCopiedReferences(+ graph: SceneGraph,+ mappedIds: ReadonlyMap<string, string>+): void {+ const mapped = (id: string) => mappedIds.get(id) ?? id+ const copies = [...mappedIds.values()].flatMap((id) => graph.getNode(id) ?? [])+ const copiedSwaps = copies.flatMap((node) => swapPropertyIds(node.componentPropertyDefinitions))+ for (const node of copies) {+ // An instance's swap property may be defined on a component the copy leaves behind.+ const swapProperties = new Set([+ ...copiedSwaps,+ ...swapPropertyIds(componentPropertyDefinitions(graph, node))+ ])+ const changes = remappedReferences(node, mapped, swapProperties)+ if (Object.keys(changes).length > 0) graph.updateNode(node.id, changes)+ }+}diff --git a/packages/scene-graph/src/transfer/index.ts b/packages/scene-graph/src/transfer/index.tsindex cea09c8d8..0af932415 100644--- a/packages/scene-graph/src/transfer/index.ts+++ b/packages/scene-graph/src/transfer/index.ts@@ -4,3 +4,4 @@ export { applyGraphTransfer, type GraphTransferPlan } from './apply'export { prepareGraphTransfer, type GraphTransferInput } from './plan'export { prepareNodeTransfer, type NodeTransferReferences } from './nodes'export { prepareVariableTransfer, type VariableTransferReferences } from './variables'+export { remapCopiedReferences } from './copied'diff --git a/packages/scene-graph/tests/transfer/copied.test.ts b/packages/scene-graph/tests/transfer/copied.test.tsnew file mode 100644index 000000000..6bea15db0--- /dev/null+++ b/packages/scene-graph/tests/transfer/copied.test.ts@@ -0,0 +1,104 @@+import { describe, expect, test } from 'bun:test'++import { SceneGraph } from '@open-pencil/scene-graph'+import { remapCopiedReferences } from '@open-pencil/scene-graph/transfer'++const end = (nodeId: string) => ({ nodeId, magnet: 'AUTO' as const, position: { x: 0, y: 0 } })++describe('remapCopiedReferences', () => {+ test('points instances and connector ends at the copies', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0].id+ const card = graph.createNode('COMPONENT', page, { name: 'Card' })+ const cardCopy = graph.createNode('COMPONENT', page, { name: 'Card' })+ const instance = graph.createNode('INSTANCE', page, { componentId: card.id })+ const link = graph.createNode('CONNECTOR', page, {+ connectorStart: end(card.id),+ connectorEnd: end(instance.id)+ })++ remapCopiedReferences(+ graph,+ new Map([+ [card.id, cardCopy.id],+ [instance.id, instance.id],+ [link.id, link.id]+ ])+ )++ expect(graph.getNode(instance.id)?.componentId).toBe(cardCopy.id)+ expect(graph.getNode(link.id)?.connectorStart?.nodeId).toBe(cardCopy.id)+ expect(graph.getNode(link.id)?.connectorEnd?.nodeId).toBe(instance.id)+ })++ test('leaves a copy alone when no reference it holds was copied', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0].id+ const card = graph.createNode('COMPONENT', page, { name: 'Card' })+ const instance = graph.createNode('INSTANCE', page, {+ componentId: card.id,+ instanceOverrides: { self: new Map([['name', 'Renamed']]), descendants: new Map() }+ })+ const updated: string[] = []+ graph.onNodeEvents({ updated: (nodeId) => updated.push(nodeId) })++ remapCopiedReferences(graph, new Map([[instance.id, instance.id]]))++ expect(updated).toEqual([])+ })++ test('writes to distinct copies and leaves their sources as they were', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0].id+ const card = graph.createNode('COMPONENT', page, { name: 'Card' })+ const cardCopy = graph.createNode('COMPONENT', page, { name: 'Card' })+ const instance = graph.createNode('INSTANCE', page, { componentId: card.id })+ const instanceCopy = graph.createNode('INSTANCE', page, { componentId: card.id })+ const ends = { connectorStart: end(card.id), connectorEnd: end(instance.id) }+ const link = graph.createNode('CONNECTOR', page, ends)+ const linkCopy = graph.createNode('CONNECTOR', page, structuredClone(ends))++ remapCopiedReferences(+ graph,+ new Map([+ [card.id, cardCopy.id],+ [instance.id, instanceCopy.id],+ [link.id, linkCopy.id]+ ])+ )++ expect(graph.getNode(instanceCopy.id)?.componentId).toBe(cardCopy.id)+ expect(graph.getNode(linkCopy.id)?.connectorStart?.nodeId).toBe(cardCopy.id)+ expect(graph.getNode(linkCopy.id)?.connectorEnd?.nodeId).toBe(instanceCopy.id)+ expect(graph.getNode(instance.id)?.componentId).toBe(card.id)+ expect(graph.getNode(link.id)?.connectorStart?.nodeId).toBe(card.id)+ expect(graph.getNode(link.id)?.connectorEnd?.nodeId).toBe(instance.id)+ })++ test('remaps a swap set on an instance of a component left behind', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0].id+ const button = graph.createNode('COMPONENT', page, {+ name: 'Button',+ componentPropertyDefinitions: [+ { id: 'icon', name: 'Icon', type: 'INSTANCE_SWAP', defaultValue: '' }+ ]+ })+ const star = graph.createNode('COMPONENT', page, { name: 'Star' })+ const starCopy = graph.createNode('COMPONENT', page, { name: 'Star' })+ const instance = graph.createNode('INSTANCE', page, {+ componentId: button.id,+ componentPropertyAssignments: { icon: star.id }+ })++ remapCopiedReferences(+ graph,+ new Map([+ [star.id, starCopy.id],+ [instance.id, instance.id]+ ])+ )++ expect(graph.getNode(instance.id)?.componentPropertyAssignments).toEqual({ icon: starCopy.id })+ })+})diff --git a/src/app/code/live-preview.ts b/src/app/code/live-preview.tsindex da762db2f..5178fe9ad 100644--- a/src/app/code/live-preview.ts+++ b/src/app/code/live-preview.ts@@ -1,6 +1,7 @@-import { renderTree } from '@open-pencil/core/design-jsx'+import { renderRoots } from '@open-pencil/core/design-jsx'import { computeAllLayouts } from '@open-pencil/core/layout'import { reconcileRenderedLayers, type TreeNode } from '@open-pencil/design-jsx'+import { Fragment } from '@open-pencil/design-jsx/jsx-runtime'import type { SceneNode } from '@open-pencil/scene-graph'import type { Vector } from '@open-pencil/scene-graph/primitives'@@ -99,25 +100,28 @@ export async function previewDesignJSX(const before = store.snapshotPage()const selectionBefore = [...store.state.selectedIds]try {- const renderedIds: string[] = []const layers: DesignJSXLayerLine[] = []const onNode = (tree: TreeNode, node: { id: string }) => {if (tree.source) layers.push({ line: tree.source.line, type: tree.type, nodeId: node.id })}- for (const [index, root] of roots.entries()) {+ const positions = roots.map((root, index) => {const origin = session.origins.at(index) ?? {x: session.fallbackOrigin.x + index * 24,y: session.fallbackOrigin.y + index * 24}// Code that places a root keeps it there; code that does not lands where the layer was.- const result = await renderTree(store.graph, root, {- parentId: session.targetParentId,+ return {x: 'x' in root.props ? undefined : origin.x,- y: 'y' in root.props ? undefined : origin.y,- onNode- })- renderedIds.push(result.id)- }+ y: 'y' in root.props ? undefined : origin.y+ }+ })+ // One render, so roots reach each other: a connector joins a layer another root draws.+ const results = await renderRoots(store.graph, Fragment({ children: roots }), {+ parentId: session.targetParentId,+ positions,+ onNode+ })+ const renderedIds = results.map(({ id }) => id)const { rootIds, ids } = reconcileRenderedLayers(store.graph, session.rootIds, renderedIds)if (session.targetIndex >= 0) {for (const [index, id] of rootIds.entries()) {diff --git a/tests/e2e/code/panel.spec.ts b/tests/e2e/code/panel.spec.tsindex 64b281192..586d3f0d0 100644--- a/tests/e2e/code/panel.spec.ts+++ b/tests/e2e/code/panel.spec.ts@@ -1,6 +1,7 @@import { expect, test, useEditorSetup } from '#tests/e2e/fixtures'import {getCodeNodeSummaries,+ getCodePreviewLinks,getFirstSelectedNodeId,getUndoLabel,hasNode,@@ -104,6 +105,49 @@ test('live previews Design JSX and keeps one undo transaction', async () => {expect(await hasNodeNamed(editor.page, 'Live JSX final')).toBe(false)})+test('previews several roots in one render, each where its layer was', async () => {+ await editor.page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const page = store.state.currentPageId+ const size = { width: 80, height: 40 }+ const left = store.graph.createNode('RECTANGLE', page, { x: 100, y: 80, ...size })+ const right = store.graph.createNode('RECTANGLE', page, { x: 400, y: 80, ...size })+ store.select([left.id, right.id])+ })+ await openCodePanel()+ const code = (width: number) =>+ [+ '<>',+ ` <Frame name="Start" w={${width}} h={100} />`,+ ` <Frame name="Done" w={${width}} h={100} />`,+ ' <Connector from="Start" to="Done" />',+ ' <Instance name="Card copy" of={card} />',+ ' <Component ref={card} name="Card" w={100} h={50} />',+ '</>'+ ].join('\n')+ const preview = async (width: number) => {+ await codeEditor().fill(`const card = ref()\nreturn ${code(width)}`)+ await expect+ .poll(async () => (await getCodePreviewLinks(editor.page, ['Start'])).layers.Start?.width)+ .toBe(width)+ return getCodePreviewLinks(editor.page, ['Start', 'Done', 'Card', 'Card copy'])+ }++ const first = await preview(200)+ expect(first.layers.Start).toMatchObject({ x: 100, y: 80 })+ expect(first.layers.Done).toMatchObject({ x: 400, y: 80 })+ expect(first.connectorEnds).toEqual([[first.layers.Start.id, first.layers.Done.id]])+ expect(first.layers['Card copy'].componentId).toBe(first.layers.Card.id)++ // The second edit updates those layers in place, so links must follow them.+ const second = await preview(240)+ expect(second.layers.Start).toMatchObject({ id: first.layers.Start.id, x: 100, y: 80 })+ expect(second.layers.Done).toMatchObject({ id: first.layers.Done.id, x: 400, y: 80 })+ expect(second.connectorEnds).toEqual([[first.layers.Start.id, first.layers.Done.id]])+ expect(second.layers['Card copy'].componentId).toBe(second.layers.Card.id)+})+test('Ctrl+Z edits the CodeMirror draft before touching the canvas transaction', async () => {await openCodePanel()const initial = await codeEditor().textContent()diff --git a/tests/helpers/code-panel.ts b/tests/helpers/code-panel.tsindex 8ea9533f2..5d24c34aa 100644--- a/tests/helpers/code-panel.ts+++ b/tests/helpers/code-panel.ts@@ -60,6 +60,40 @@ export function getCodeNodeSummaries(page: Page): Promise<CodeNodeSummary[]> {})}+export type CodePreviewLinks = {+ layers: Record<+ string,+ { id: string; x: number; y: number; width: number; componentId: string | null }+ >+ /** The layer ids each connector's ends follow. */+ connectorEnds: Array<[string | null, string | null]>+}++/** The named layers' places and main components, and the layers connectors join. */+export function getCodePreviewLinks(page: Page, names: string[]): Promise<CodePreviewLinks> {+ return page.evaluate((layerNames) => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const nodes = [...store.graph.getAllNodes()]+ const layers: CodePreviewLinks['layers'] = {}+ for (const name of layerNames) {+ const node = nodes.find((candidate) => candidate.name === name)+ if (!node) continue+ const { id, x, y, width, componentId } = node+ layers[name] = { id, x, y, width, componentId }+ }+ return {+ layers,+ connectorEnds: nodes+ .filter((node) => node.type === 'CONNECTOR')+ .map((node): [string | null, string | null] => [+ node.connectorStart?.nodeId ?? null,+ node.connectorEnd?.nodeId ?? null+ ])+ }+ }, names)+}+export function getUndoLabel(page: Page): Promise<string | null> {return page.evaluate(() => {const store = window.openPencil?.getStore?.()