Skip to content

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

refactor: build layers from authored content only through Core (#1025)

Danila Poyarkovcc5091049b8e
diff --git a/AGENTS.md b/AGENTS.md
index defa9477a..99e69ae07 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -45,6 +45,7 @@ Before a PR run `bun run check`, `bun run format`, `bun run test:unit`, and `bun
- Across package/app boundaries import the owning package's public exports, never workspace internals or forwarding-only shims. `@open-pencil/scene-graph` owns graph types and primitives; `@open-pencil/kiwi` owns low-level Kiwi/FIG helpers; `@open-pencil/core` provides the compatibility barrel plus the subpaths listed in `packages/core/package.json`.
- `bun run check:arch` enforces: public workspace exports, framework-neutral Core, no app services in views or shared UI, property-panel internals scoped to that panel.
+- The app, CLI, MCP server, and Vue SDK build layers from authored content (HTML, JSX, `.pen`) only through Core: IO `readDocument`, `readHTMLDocument`, `sceneGraphFromStyledHTML`, or `@open-pencil/core/design-jsx`, which lay the layers out. Format packages' own builders, such as `htmlToSceneGraph` or `parsePenFile`, skip that; `open-pencil/no-graph-builders-in-front-ends` (`check:arch`) rejects them outside Core.
- Package aliases are `#core/*`, `#fig/*`, `#vue/*`, `#cli/*`, `#mcp/*`, `#dom-css/*`, `#design-jsx/*`, `#emit/*`; a package's own tests use `#core-tests/*`, `#fig-tests/*`, and `#dom-css-tests/*`; the app uses `@/`. Prefer clear relative imports nearby. Never escape an alias root with `../` (for example `#tests/../vite`); fix module ownership instead.
- Never drill with `../../`: one `../` to a sibling folder is fine, two or more means an alias. This holds in tests as much as in source — a test reaches its package's source through `#<pkg>/*` and its own helpers through `#<pkg>-tests/*`. `open-pencil/no-deep-parent-relative-imports` enforces it for imports and `open-pencil/no-deep-parent-relative-paths` for paths built from `import.meta`; a new test directory must be added to `lint:structure` so the rules reach it.
- Reuse named types from `@open-pencil/scene-graph`; do not respell `Color`, `Vector`, `SceneNode`, `Effect`, `Fill`, or `Stroke`.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 53162ec6f..13c646164 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -159,6 +159,8 @@
- Renaming a section title on the canvas keeps the title's size, weight, and place. Section titles draw in Inter SemiBold rather than an emboldened regular weight, and labels that are not rotated sit on whole pixels, so they stay crisp.
- Save HTML imported with `openpencil import` with its layout applied: layers in a flex container sit where its padding and gap place them instead of all at the top left (#788).
- Import HTML and CSS laid out as a browser lays it out, in `openpencil import` and the app's HTML import. Block elements stack and fill their parent's width, inline elements and buttons hug their content, flex items stretch across their container by default, `flex: 1` and `width: 100%` fill, padding and borders sit outside a `width` or `height` unless `box-sizing: border-box`, `display: none` is left out, and text wraps or hugs its content instead of taking an estimated size. Before, block elements became fixed 100 × 100 frames without layout, so `openpencil import` left their children at the top left (#788).
+- Import HTML and CSS laid out as a browser lays it out, in `openpencil import` and the app's HTML import. Block elements stack and fill their parent's width, inline elements and buttons hug their content, flex items stretch across their container by default, `flex: 1` and `width: 100%` fill, padding and borders sit outside a `width` or `height` unless `box-sizing: border-box`, `display: none` is left out, and text wraps or hugs its content instead of taking an estimated size. Before, `openpencil import` saved every child at the top left, and block elements became fixed 100 × 100 frames (#788).
+- Import HTML and CSS laid out as a browser lays it out, in `openpencil import`, the app's HTML import, and the code panel's HTML preview, which showed its layers without any layout. Block elements stack and fill their parent's width, inline elements and buttons hug their content, flex items stretch across their container by default, `flex: 1` and `width: 100%` fill, padding and borders sit outside a `width` or `height` unless `box-sizing: border-box`, `display: none` is left out, and text wraps or hugs its content instead of taking an estimated size. Before, `openpencil import` saved every child at the top left, and block elements became fixed 100 × 100 frames (#788).
- Apply rules that use the universal selector, such as Tailwind's `box-sizing: border-box` base style, when HTML and Tailwind are converted headlessly, and let a `padding-inline` or `padding-block` override a less specific rule's padding.
- Keep exported HTML at the size it has in OpenPencil when a box has padding or a border: it declares `box-sizing: border-box`, so its width includes them in HTML used without OpenPencil's standalone stylesheet.
- Size design JSX text in a frame without auto layout, such as text an AI agent or MCP client renders into a plain frame, to its content instead of 100 × 100.
diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.md
index 687fbd3ac..87bea547f 100644
--- a/packages/core/AGENTS.md
+++ b/packages/core/AGENTS.md
@@ -5,6 +5,8 @@ Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and do
- Public surface is the compatibility barrel plus the subpaths listed in `packages/core/package.json` `exports`; add a subpath there rather than deep-importing.
- CanvasKit runtime loading is centralized in `@open-pencil/core/canvaskit`. Headless raster export may dynamically load `canvaskit-wasm/full`; elsewhere `import type` and pass CanvasKit in.
- 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 from `layoutAuthoredNodes` in `packages/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 `.fig` keeps the geometry it stores (`packages/core/tests/layout/authored.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. `readHTMLDocument` and `headlessHTMLReader` use the headless CSS runtime, which cannot be bundled for browsers, so they stay out of `BUILTIN_IO_FORMATS` and 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 `extractPageContext` or `extractExportGraph` in `packages/core/src/io/subgraph.ts`, not another copier. Pass `componentSets` when instances must switch variant and `shareTables` for a read-only view rebuilt often (`packages/core/tests/io/subgraph.test.ts`).
- Undo for structural AI and MCP edits records only the layers an edit touches with `capturePageChange`, whose capture shares unchanged values instead of deep-copying the page, since a page copy per tool call grows memory with every call. It relies on every change emitting a graph event and on values being replaced rather than written into, apart from the child lists, source metadata, and override maps it copies (`packages/core/tests/editor/history/page-change.test.ts`).
diff --git a/packages/design-jsx/AGENTS.md b/packages/design-jsx/AGENTS.md
index 38c35ada4..c6d833d58 100644
--- a/packages/design-jsx/AGENTS.md
+++ b/packages/design-jsx/AGENTS.md
@@ -5,6 +5,7 @@ OpenPencil's design JSX: the elements (`Frame`, `Text`, …) and the trees they
Rules:
- 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`.
+- 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.
- JSX export (`src/export/`) collects typed props in `props.ts` and prints them with `@open-pencil/emit`'s JSX builders; never build JSX from string fragments.
- `src/reference/authoring.md` is the source of the shared authoring reference. Run `bun run generate:authoring-reference` after changing it or the schema; never edit the generated copies.
diff --git a/packages/dom-css/AGENTS.md b/packages/dom-css/AGENTS.md
index ec6017d94..13e4b53b9 100644
--- a/packages/dom-css/AGENTS.md
+++ b/packages/dom-css/AGENTS.md
@@ -14,3 +14,5 @@ Rules:
- Keep the `./export` entry browser-safe: load `node:*` modules and the headless CSS object model lazily inside the functions that need them, so the app never bundles them.
- Build generated code as syntax trees with `@open-pencil/emit` (`es` for TypeScript modules, `jsx` for JSX, `vue` for single-file components), not string fragments.
- Imported documents are untrusted: check Base64 with `js-base64`'s `isValid` before decoding.
+- Import maps CSS flow onto the auto layout semantics in `@open-pencil/scene-graph` from `src/import/flow.ts`: an element's display comes from CSS or its tag's default, block flow stacks and stretches block-level children, flex items stretch across by default, and padding and borders sit outside an explicit size unless `box-sizing: border-box`. It records fill and hug and never sizes text; Core measures and lays out what it builds (`packages/dom-css/tests/import/flow.test.ts`).
+- `./scene-graph` is the browser-safe entry for building layers from a styled DOM. The main entry carries the headless CSS runtime, whose CSSOM dependency has no browser build with the exports it uses, so browser bundles must not import it.
diff --git a/src/app/code/dom-preview.ts b/src/app/code/dom-preview.ts
index 629607b85..08a906129 100644
--- a/src/app/code/dom-preview.ts
+++ b/src/app/code/dom-preview.ts
@@ -1,4 +1,5 @@
-import { browserHTMLToSceneGraph } from '@open-pencil/dom-css/browser'
+import { sceneGraphFromStyledHTML } from '@open-pencil/core/io/formats/html/layers'
+import { browserHTMLToDesignDocument } from '@open-pencil/dom-css/browser'
import type { SceneGraph } from '@open-pencil/scene-graph'
import type { EditorStore } from '@/app/editor/active-store'
@@ -25,7 +26,9 @@ export async function previewDOMCode(
source: string
): Promise<{ ok: true } | { ok: false; error: string }> {
try {
- const graph = await browserHTMLToSceneGraph(source, { pageName: 'Code preview' })
+ const graph = sceneGraphFromStyledHTML(await browserHTMLToDesignDocument(source), {
+ pageName: 'Code preview'
+ })
const pageId = graph.getPages()[0]?.id ?? graph.rootId
session.previewGraph = graph
session.previewPageId = pageId
diff --git a/src/app/document/io/dom.ts b/src/app/document/io/dom.ts
index 678494aa0..0a3cf8a2f 100644
--- a/src/app/document/io/dom.ts
+++ b/src/app/document/io/dom.ts
@@ -1,6 +1,6 @@
import type { Editor, EditorState } from '@open-pencil/core/editor'
-import { layoutAuthoredNodes } from '@open-pencil/core/layout'
-import { browserHTMLToSceneGraph } from '@open-pencil/dom-css/browser'
+import { sceneGraphFromStyledHTML } from '@open-pencil/core/io/formats/html/layers'
+import { browserHTMLToDesignDocument } from '@open-pencil/dom-css/browser'
import { describeDiagnosticError, recordDocumentFailure } from '@/app/diagnostics'
import { yieldToUI } from '@/app/document/io/browser'
@@ -62,16 +62,12 @@ export function createDOMOpenActions({
await yieldToUI()
const pageName = options.documentName ?? 'DOM Import'
load.update({ phase: 'decoding', detail: pageName })
- const graph = await browserHTMLToSceneGraph(html, {
+ const styled = await browserHTMLToDesignDocument(html, {
cssText: options.cssText,
- pageName,
signal: load.signal
})
load.signal.throwIfAborted()
- layoutAuthoredNodes(
- graph,
- graph.getPages().map((page) => page.id)
- )
+ const graph = sceneGraphFromStyledHTML(styled, { pageName })
await yieldToUI()
await applyImportedDocument(editor, graph, load)
state.documentName = pageName
diff --git a/steiger.config.ts b/steiger.config.ts
index 9266dc1bd..537c002e5 100644
--- a/steiger.config.ts
+++ b/steiger.config.ts
@@ -41,6 +41,7 @@ export default defineConfig([
'open-pencil/no-production-test-ids-in-shared-layers': 'error',
'open-pencil/no-native-title-attributes-in-vue': 'error',
'open-pencil/no-ui-imports-in-core': 'error',
+ 'open-pencil/no-graph-builders-in-front-ends': 'error',
'open-pencil/scripts-are-entrypoint-shims': 'error',
'open-pencil/strict-tools-layout': 'error'
}
diff --git a/tools/checks/architecture/src/steiger-rules/graph-builders.ts b/tools/checks/architecture/src/steiger-rules/graph-builders.ts
new file mode 100644
index 000000000..8452186b5
--- /dev/null
+++ b/tools/checks/architecture/src/steiger-rules/graph-builders.ts
@@ -0,0 +1,69 @@
+import { compact } from 'es-toolkit'
+import ts from 'typescript'
+import { parse as parseVueSfc } from 'vue/compiler-sfc'
+
+import { createTextRule, type Rule } from './support.ts'
+
+/** Packages that hold the app, CLI, MCP server, and UI rather than a document format. */
+const FRONT_END_SOURCES = /^(src|packages\/(cli|mcp|vue|harness)\/src)\//u
+
+/** Entry points that build layers from authored content without laying them out. */
+function isGraphBuilder(specifier: string, name: string): boolean {
+ if (specifier === '@open-pencil/dom-css' || specifier === '@open-pencil/dom-css/browser') {
+ return name.endsWith('ToSceneGraph')
+ }
+ if (specifier === '@open-pencil/pen') return name === 'parsePenFile' || name === 'readPenFile'
+ if (specifier === '@open-pencil/design-jsx') {
+ return ['renderTree', 'renderJSX', 'renderRoots', 'createDesignJSXRenderer'].includes(name)
+ }
+ return false
+}
+
+/** The source's script with the line it starts on: a Vue file's script blocks, or the file. */
+function scriptsOf(sourceRel: string, content: string): Array<{ text: string; line: number }> {
+ if (!sourceRel.endsWith('.vue')) return [{ text: content, line: 1 }]
+ const { script, scriptSetup } = parseVueSfc(content, { filename: sourceRel }).descriptor
+ return compact([script, scriptSetup]).map((block) => ({
+ text: block.content,
+ line: block.loc.start.line
+ }))
+}
+
+export interface GraphBuilderImport {
+ specifier: string
+ name: string
+ line: number
+}
+
+/** Named imports a front end makes of format packages' graph builders. */
+export function graphBuilderImports(sourceRel: string, content: string): GraphBuilderImport[] {
+ if (!FRONT_END_SOURCES.test(sourceRel) || !/\.([cm]?tsx?|vue)$/u.test(sourceRel)) return []
+ const found: GraphBuilderImport[] = []
+ for (const script of scriptsOf(sourceRel, content)) {
+ const source = ts.createSourceFile(sourceRel, script.text, ts.ScriptTarget.Latest, true)
+ for (const statement of source.statements) {
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
+ continue
+ const specifier = statement.moduleSpecifier.text
+ const bindings = statement.importClause?.namedBindings
+ if (!bindings || !ts.isNamedImports(bindings)) continue
+ for (const element of bindings.elements) {
+ const name = (element.propertyName ?? element.name).text
+ if (element.isTypeOnly || !isGraphBuilder(specifier, name)) continue
+ const { line } = source.getLineAndCharacterOfPosition(element.getStart(source))
+ found.push({ specifier, name, line: script.line + line })
+ }
+ }
+ }
+ return found
+}
+
+export const noGraphBuildersInFrontEnds: Rule = createTextRule(
+ 'open-pencil/no-graph-builders-in-front-ends',
+ (sourceRel, content) =>
+ graphBuilderImports(sourceRel, content).map(({ specifier, name, line }) => ({
+ message: `Build layers from authored content through Core, which lays them out: \`${name}\` from \`${specifier}\` skips that. Use IO \`readDocument\`, \`readHTMLDocument\`, \`sceneGraphFromStyledHTML\` from \`@open-pencil/core/io/formats/html/layers\`, or \`@open-pencil/core/design-jsx\`.`,
+ line,
+ column: 0
+ }))
+)
diff --git a/tools/checks/architecture/src/steiger-rules/index.ts b/tools/checks/architecture/src/steiger-rules/index.ts
index d49da1762..fa8a7b2b6 100644
--- a/tools/checks/architecture/src/steiger-rules/index.ts
+++ b/tools/checks/architecture/src/steiger-rules/index.ts
@@ -8,6 +8,7 @@ import {
noDynamicTailwindStateClasses,
noVueTemplateUIHooksOrSVG
} from './dynamic-tailwind-classes.ts'
+import { noGraphBuildersInFrontEnds } from './graph-builders.ts'
import {
collectFiles,
collectFolders,
@@ -516,6 +517,7 @@ export const openPencilArchitecturePlugin = {
ruleDefinitions: [
preferDomainFoldersOverFilenamePrefixes,
noCrossPackageReexportShims,
+ noGraphBuildersInFrontEnds,
scriptsAreEntrypointShims,
strictToolsLayout,
strictTestFilePlacement,
diff --git a/tools/checks/architecture/tests/graph-builders.test.ts b/tools/checks/architecture/tests/graph-builders.test.ts
new file mode 100644
index 000000000..2f8371f37
--- /dev/null
+++ b/tools/checks/architecture/tests/graph-builders.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, test } from 'bun:test'
+
+import { graphBuilderImports } from '../src/steiger-rules/graph-builders'
+
+describe('graph builders in front ends', () => {
+ test('finds format packages building layers that Core would lay out', () => {
+ const content = [
+ "import { browserHTMLToSceneGraph, serializeHTML } from '@open-pencil/dom-css/browser'",
+ "import { parsePenFile as parse } from '@open-pencil/pen'",
+ "import { renderTree } from '@open-pencil/design-jsx'"
+ ].join('\n')
+ expect(graphBuilderImports('src/app/document/io/dom.ts', content)).toEqual([
+ { specifier: '@open-pencil/dom-css/browser', name: 'browserHTMLToSceneGraph', line: 1 },
+ { specifier: '@open-pencil/pen', name: 'parsePenFile', line: 2 },
+ { specifier: '@open-pencil/design-jsx', name: 'renderTree', line: 3 }
+ ])
+ })
+
+ test('reports the line in a Vue file', () => {
+ const content = `<template>\n <div />\n</template>\n<script setup lang="ts">\nimport { htmlToSceneGraph } from '@open-pencil/dom-css'\n</script>\n`
+ expect(graphBuilderImports('packages/vue/src/Panel.vue', content)).toEqual([
+ { specifier: '@open-pencil/dom-css', name: 'htmlToSceneGraph', line: 5 }
+ ])
+ })
+
+ test('allows Core, styling helpers, types, and the format packages themselves', () => {
+ expect(
+ graphBuilderImports(
+ 'src/app/code/dom-preview.ts',
+ [
+ "import { sceneGraphFromStyledHTML } from '@open-pencil/core/io/formats/html/layers'",
+ "import { browserHTMLToDesignDocument } from '@open-pencil/dom-css/browser'",
+ "import { renderTree } from '@open-pencil/core/design-jsx'",
+ "import { type renderJSX } from '@open-pencil/design-jsx'"
+ ].join('\n')
+ )
+ ).toEqual([])
+ expect(
+ graphBuilderImports(
+ 'packages/core/src/io/formats/html/import.ts',
+ "import { designDocumentToSceneGraph } from '@open-pencil/dom-css'"
+ )
+ ).toEqual([])
+ })
+})
diff --git a/tsconfig.json b/tsconfig.json
index 3e2e02f72..8ff2a66f7 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -73,6 +73,15 @@
"@open-pencil/dom-css": [
"./packages/dom-css/src/index.ts"
],
+ "@open-pencil/dom-css/scene-graph": [
+ "./packages/dom-css/src/import/scene-graph.ts"
+ ],
+ "@open-pencil/dom-css/export": [
+ "./packages/dom-css/src/export/index.ts"
+ ],
+ "@open-pencil/dom-css/*": [
+ "./packages/dom-css/src/*"
+ ],
"#scene-graph/*": [
"./packages/scene-graph/src/*"
],
diff --git a/vite/aliases.ts b/vite/aliases.ts
index c4d8f80b3..66c43149e 100644
--- a/vite/aliases.ts
+++ b/vite/aliases.ts
@@ -18,6 +18,10 @@ export function createOpenPencilAliases(rootDir: string) {
find: /^@open-pencil\/dom-css\/export$/,
replacement: resolve(rootDir, 'packages/dom-css/src/export/index.ts')
},
+ {
+ find: /^@open-pencil\/dom-css\/scene-graph$/,
+ replacement: resolve(rootDir, 'packages/dom-css/src/import/scene-graph.ts')
+ },
{
find: /^@open-pencil\/dom-css\/jsx-runtime$/,
replacement: resolve(rootDir, 'packages/dom-css/src/import/jsx/runtime.ts')