Skip to content

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

fix: lay out authored content the same way on every path (#1019)

Danila Poyarkovd14f082c90a5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ed48c3243..d5135fa3e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -47,6 +47,8 @@
- Paste SVG markup copied as text, such as from a code editor or Figma's Copy as SVG, as layers.
- Show the pixel grid when zoomed in, as in Figma: from 800% on a standard display and 400% on a Retina one, toggled with **View → Pixel Grid** or <kbd>⇧</kbd><kbd>'</kbd>. <kbd>⇧</kbd><kbd>⌘</kbd><kbd>'</kbd> toggles **Snap to Pixel Grid**. The zoom menu in the properties panel lists both, with Figma's shortcuts, and labels its shortcuts for zoom to fit (<kbd>⇧</kbd><kbd>1</kbd>) and 100% (<kbd>⌘</kbd><kbd>0</kbd>); <kbd>⇧</kbd><kbd>R</kbd> toggles rulers and <kbd>⌥</kbd><kbd>⌘</kbd><kbd>\\</kbd> multiplayer cursors.
- Set a component's text, boolean, and swap properties on a design JSX `<Instance>` by name, as variants are set, such as `<Instance of="Card" Title="Hello" Badge={false} />`; `properties` accepts names too. An instance written this way still works after the document is saved to `.fig` and reopened, which gives each property a new ID ([#750](https://github.com/open-pencil/open-pencil/issues/750)).
+- Import `designDocumentToSceneGraph` from `@open-pencil/dom-css/scene-graph` in browser builds, which the package's main entry, with its headless CSS runtime, cannot be bundled for.
+- Open HTML files in CLI commands that read documents, such as `openpencil tree` and `openpencil convert`, laid out as `openpencil import` lays them out.
- Save the open document to cloud storage with **File → Save to storage…**. The tab stays bound to the stored copy, so Save and auto-save write to the bucket; before storage is configured, the command opens its settings. A new Cloud Storage guide covers connecting a bucket, CORS, syncing, and provider notes.
- Add a variant to a standalone component from the header's **Add variant** button, as in Figma (#847): it becomes a component set named after it, whose existing instances and properties carry over, with a `Property 1=Variant2` copy below. A set's variant properties are rows of its **Properties** list, each opening to rename it and add, rename, reorder, or remove its values; removing a value variants still use moves them to another value. Variants that share a combination of values are named in a notice that selects them.
- Create and edit a component's text, boolean, and instance swap properties from the properties panel, as in Figma (#847). A layer in a main component links its text content, visibility, or swapped component to a new or existing property from the Typography and Appearance sections and the instance header, and shows the linked property in place of the value. The component lists its properties, each opening to rename it, change its default, see and unlink the layers it drives, or delete it, and reorders them by dragging. Expose nested instances so their properties show, grouped under the instance's name, on instances of the component. Typing into text a property drives sets the property: its default in the main component, the instance's value in an instance.
@@ -155,6 +157,9 @@
- Keep `fill-opacity` and `stroke-opacity` when importing SVG instead of drawing those paints opaque.
- Use an API key saved in Settings for the open AI chat right away, including when asking again after a failed request, instead of only after reloading; the failure's notice closes once the request is sent again.
- 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).
+- 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.
+- Size text in `.pen` files from its font instead of estimating its width from the number of characters; wrapping text without a width wraps at the width of its content.
- Reject an argument an AI, MCP, CLI, or WebMCP tool does not take, such as `properties: { y: 500 }` for `update_node` or `font: { family }` for `set_font`, and name it, instead of reporting success without changing anything (#977).
- Choose an instance's variant by its variant property in design JSX, such as `<Instance component="Button" State="Pressed" />`, without a warning that the property is unsupported.
- Lay out design JSX `justifyContent="space-between"`, `"flex-start"`, and `"flex-end"`, and `alignItems="flex-end"` and `"flex-start"`, as written instead of at the start; `space-around` and `space-evenly`, which auto layout has no equivalent for, still start at the start, and align a row's children by their baseline with `items="baseline"`, which JSX export now writes instead of dropping. A `.pen` padding with one or three values fills the sides it leaves out as CSS does, instead of with 0.
diff --git a/packages/cli/src/commands/formats.ts b/packages/cli/src/commands/formats.ts
index e0635989f..81b310781 100644
--- a/packages/cli/src/commands/formats.ts
+++ b/packages/cli/src/commands/formats.ts
@@ -1,10 +1,11 @@
import { defineCommand } from 'citty'
-import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'
+import { IORegistry } from '@open-pencil/core/io'
import { bold, fmtList, kv } from '#cli/format'
+import { CLI_IO_FORMATS } from '#cli/headless'
-const io = new IORegistry(BUILTIN_IO_FORMATS)
+const io = new IORegistry(CLI_IO_FORMATS)
function supportLabels(format: ReturnType<IORegistry['listFormats']>[number]): string[] {
const labels: string[] = []
diff --git a/packages/cli/src/commands/import.ts b/packages/cli/src/commands/import.ts
index 2cacee6e7..4912e277b 100644
--- a/packages/cli/src/commands/import.ts
+++ b/packages/cli/src/commands/import.ts
@@ -4,14 +4,7 @@ import { basename, dirname, extname, resolve } from 'node:path'
import { defineCommand } from 'citty'
import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'
-import {
- createHeadlessCSSRuntime,
- htmlToDesignDocument,
- htmlToSceneGraph,
- tailwindHTMLToDesignDocument,
- tailwindHTMLToSceneGraph,
- type DesignDocument
-} from '@open-pencil/dom-css'
+import { readHTMLDocument, type ReadHTMLResult } from '@open-pencil/core/io/formats/html/import'
import { requireFile } from '#cli/app/client'
import { fmtList, ok, printError } from '#cli/format'
@@ -57,44 +50,22 @@ async function tailwindCandidatesForArgs(args: ImportArgs): Promise<string[] | u
return classes.length > 0 ? classes : undefined
}
-function childCount(document: DesignDocument): number {
- return document.children.length
+async function importHTML(args: ImportArgs): Promise<ReadHTMLResult> {
+ return readHTMLDocument(await readTextFile(requireFile(args.file)), {
+ cssText: await cssTextForArgs(args),
+ tailwind: await tailwindCandidatesForArgs(args),
+ pageName: args.pageName
+ })
}
-async function importHTML(args: ImportArgs) {
- const file = requireFile(args.file)
- const html = await readTextFile(file)
- const runtime = createHeadlessCSSRuntime()
- const tailwind = await tailwindCandidatesForArgs(args)
- const cssText = await cssTextForArgs(args)
-
- if (tailwind) {
- const options = { ...args, css: cssText, runtime }
- return {
- document: await tailwindHTMLToDesignDocument(html, tailwind, options),
- graph: await tailwindHTMLToSceneGraph(html, tailwind, options)
- }
- }
-
- const options = { cssText, runtime, pageName: args.pageName }
- return {
- document: await htmlToDesignDocument(html, options),
- graph: await htmlToSceneGraph(html, options)
- }
-}
-
-async function writeOutput(
- args: ImportArgs,
- document: DesignDocument,
- graph: Awaited<ReturnType<typeof htmlToSceneGraph>>
-) {
+async function writeOutput(args: ImportArgs, { styled, graph }: ReadHTMLResult) {
const format = args.format.toLowerCase()
const output = args.output ? resolve(args.output) : defaultOutput(requireFile(args.file), format)
await mkdir(dirname(output), { recursive: true })
if (format === 'json') {
- await writeFile(output, `${JSON.stringify(document, null, 2)}\n`)
+ await writeFile(output, `${JSON.stringify(styled, null, 2)}\n`)
return output
}
@@ -160,15 +131,15 @@ export default defineCommand({
process.exit(1)
}
- const { document, graph } = await importHTML(args)
- const output = await writeOutput(args, document, graph)
- const pages = graph.getPages()
+ const imported = await importHTML(args)
+ const output = await writeOutput(args, imported)
+ const pages = imported.graph.getPages()
const summary = {
input: requireFile(args.file),
output,
format,
pages: pages.length,
- rootElements: childCount(document)
+ rootElements: imported.styled.children.length
}
if (args.json) {
diff --git a/packages/cli/src/headless.ts b/packages/cli/src/headless.ts
index a25f90dda..545737d00 100644
--- a/packages/cli/src/headless.ts
+++ b/packages/cli/src/headless.ts
@@ -2,6 +2,7 @@ import { readFile, writeFile } from 'node:fs/promises'
import { BUILTIN_IO_FORMATS, IORegistry, initCanvasKit } from '@open-pencil/core/io'
import { populateAllFigPages, populateFigPage } from '@open-pencil/core/io/formats/fig'
+import { headlessHTMLReader } from '@open-pencil/core/io/formats/html/import'
import { computeAllLayouts } from '@open-pencil/core/layout'
import type { SceneGraph } from '@open-pencil/scene-graph'
@@ -9,7 +10,10 @@ import { printError } from '#cli/format'
export { initCanvasKit }
-const io = new IORegistry(BUILTIN_IO_FORMATS)
+/** The document formats the CLI reads and writes, with HTML read by the headless CSS runtime. */
+export const CLI_IO_FORMATS = [...BUILTIN_IO_FORMATS, headlessHTMLReader]
+
+const io = new IORegistry(CLI_IO_FORMATS)
export async function loadDocument(filePath: string): Promise<SceneGraph> {
const bytes = new Uint8Array(await readFile(filePath))
diff --git a/packages/cli/tests/commands/import.test.ts b/packages/cli/tests/commands/import.test.ts
new file mode 100644
index 000000000..a743c7aca
--- /dev/null
+++ b/packages/cli/tests/commands/import.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, setDefaultTimeout, test } from 'bun:test'
+import { mkdtemp, readFile, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+import { CLI_ENTRY } from '#cli-tests/helpers/paths'
+
+import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'
+
+setDefaultTimeout(60_000)
+
+const io = new IORegistry(BUILTIN_IO_FORMATS)
+
+async function cli(args: string[]) {
+ const proc = Bun.spawn([process.execPath, CLI_ENTRY, ...args], { stdout: 'pipe', stderr: 'pipe' })
+ const stderr = await new Response(proc.stderr).text()
+ return { stderr: stderr.trim(), exitCode: await proc.exited }
+}
+
+describe('import CLI', () => {
+ test('saves an imported flex column with its layout applied', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-import-'))
+ const htmlPath = join(dir, 'column.html')
+ const figPath = join(dir, 'column.fig')
+ await writeFile(
+ htmlPath,
+ `<div style="width:390px;height:844px;display:flex;flex-direction:column;padding:24px;gap:16px">
+ <div style="width:100px;height:40px;background:#ff0000"></div>
+ <div style="width:200px;height:60px;background:#00ff00"></div>
+ </div>`
+ )
+
+ const imported = await cli(['import', htmlPath, '-o', figPath])
+ expect(imported.stderr).toBe('')
+ expect(imported.exitCode).toBe(0)
+
+ // A .fig keeps the geometry it stores, so this reads what the import wrote.
+ const { graph } = await io.readDocument({
+ name: figPath,
+ data: new Uint8Array(await readFile(figPath))
+ })
+ const page = graph.getPages()[0]
+ const column = graph.getNode(page.childIds[0])
+ const [first, second] = (column?.childIds ?? []).map((id) => graph.getNode(id))
+ expect(first).toMatchObject({ x: 24, y: 24, width: 100, height: 40 })
+ expect(second).toMatchObject({ x: 24, y: 80, width: 200, height: 60 })
+ })
+})
diff --git a/packages/core/package.json b/packages/core/package.json
index 407144098..b98e3875a 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -113,6 +113,16 @@
"import": "./dist/io/formats/fig/index.js",
"default": "./dist/io/formats/fig/index.js"
},
+ "./io/formats/html/import": {
+ "types": "./dist/io/formats/html/import.d.ts",
+ "import": "./dist/io/formats/html/import.js",
+ "default": "./dist/io/formats/html/import.js"
+ },
+ "./io/formats/html/layers": {
+ "types": "./dist/io/formats/html/layers.d.ts",
+ "import": "./dist/io/formats/html/layers.js",
+ "default": "./dist/io/formats/html/layers.js"
+ },
"./io/formats/raster": {
"types": "./dist/io/formats/raster/index.d.ts",
"import": "./dist/io/formats/raster/index.js",
diff --git a/packages/core/src/design-jsx/placement.ts b/packages/core/src/design-jsx/placement.ts
index 25e869ee3..bf41c9e13 100644
--- a/packages/core/src/design-jsx/placement.ts
+++ b/packages/core/src/design-jsx/placement.ts
@@ -2,7 +2,7 @@ import type { RenderResult } from '@open-pencil/design-jsx'
import type { SceneGraph } from '@open-pencil/scene-graph'
import { findPageId } from '#core/io/subgraph'
-import { computeAllLayouts } from '#core/layout'
+import { layoutAuthoredNodes } from '#core/layout'
/** Placement fields shared by the render tool and its speculative preview. */
export interface RenderPlacementInput {
@@ -15,6 +15,8 @@ export interface RenderPlacementInput {
export interface RenderPlacement {
parentId: string
+ /** Leave layout to `finishRenderPlacement`, which runs it once the roots are in order. */
+ deferLayout?: boolean
pageId: string
replaceId?: string
insertIndex?: number
@@ -45,6 +47,7 @@ export function resolveRenderPlacement(
validateInsertIndex(insertIndex)
return {
parentId,
+ deferLayout: true,
pageId,
replaceId: replacement?.id,
insertIndex,
@@ -65,5 +68,8 @@ export function finishRenderPlacement(
}
}
if (placement.replaceId) graph.deleteNode(placement.replaceId)
- computeAllLayouts(graph, placement.pageId)
+ layoutAuthoredNodes(
+ graph,
+ results.map((result) => result.id)
+ )
}
diff --git a/packages/core/src/design-jsx/renderer.ts b/packages/core/src/design-jsx/renderer.ts
index 38b8b32b7..e7e9e9292 100644
--- a/packages/core/src/design-jsx/renderer.ts
+++ b/packages/core/src/design-jsx/renderer.ts
@@ -3,7 +3,7 @@ import { createDesignJSXRenderer, type SVGSource } from '@open-pencil/design-jsx
import { iconify, placeIcon, type IconProvider } from '#core/icons'
import { extractPaths, extractPathsFromElements, scalePathInfos } from '#core/icons/svg'
import type { IconData } from '#core/icons/types'
-import { computeAllLayouts } from '#core/layout'
+import { layoutAuthoredNodes } from '#core/layout'
function parseViewBox(viewBox: string | undefined): { w: number; h: number } {
if (!viewBox) return { w: 0, h: 0 }
@@ -52,7 +52,7 @@ function createRenderer(icons: IconProvider) {
// Inline SVG is artwork, not an icon from a set.
identity: icon.prefix !== INLINE_SVG
}),
- layout: computeAllLayouts
+ layout: layoutAuthoredNodes
})
}
diff --git a/packages/core/src/editor/components/authoring/values.ts b/packages/core/src/editor/components/authoring/values.ts
index 2dd9a9deb..a0e752b15 100644
--- a/packages/core/src/editor/components/authoring/values.ts
+++ b/packages/core/src/editor/components/authoring/values.ts
@@ -1,9 +1,9 @@
import { canCreateInstance, resolveComponentPropertyValue } from '@open-pencil/scene-graph'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-import { textAutoResizeChanges } from '#core/editor/text/auto-resize'
import { pathTextEditChanges } from '#core/editor/text/path-edit'
import type { EditorContext } from '#core/editor/types'
+import { textAutoResizeChanges } from '#core/layout/text-auto-resize'
import type { ExposableComponentField } from './context'
diff --git a/packages/core/src/editor/nodes.ts b/packages/core/src/editor/nodes.ts
index b3afa404c..ec20c7385 100644
--- a/packages/core/src/editor/nodes.ts
+++ b/packages/core/src/editor/nodes.ts
@@ -8,12 +8,12 @@ import {
type SceneNode
} from '@open-pencil/scene-graph'
+import { textAutoResizeChanges } from '#core/layout/text-auto-resize'
import { reconcileVariableLayouts } from '#core/layout/variables'
import { createLayoutModeActions } from './layout-mode'
import { createNodePreviewActions } from './node-preview'
import { createNudgeActions } from './nudge'
-import { textAutoResizeChanges } from './text/auto-resize'
import { pathTextEditChanges } from './text/path-edit'
import type { EditorContext } from './types'
import { createVariableBindingActions } from './variable-bindings'
diff --git a/packages/core/src/editor/undo.ts b/packages/core/src/editor/undo.ts
index fa28c0f8a..ad9c3ae6e 100644
--- a/packages/core/src/editor/undo.ts
+++ b/packages/core/src/editor/undo.ts
@@ -6,6 +6,8 @@ import type { Rect, Vector } from '@open-pencil/scene-graph/primitives'
import { createResizeSnapshot, type ResizeSnapshot } from '@open-pencil/scene-graph/resize'
import type { UndoEntry } from '@open-pencil/scene-graph/undo'
+import { textAutoResizeChanges } from '#core/layout/text-auto-resize'
+
import { assertNodeEditable } from './capabilities'
import { restoreSubtree, snapshotSubtree } from './clipboard/subtree-history'
import {
@@ -19,7 +21,6 @@ import {
snapshotPage as createPageSnapshot,
type PageSnapshot
} from './history/snapshot'
-import { textAutoResizeChanges } from './text/auto-resize'
import type { EditorContext } from './types'
type ResizeOriginal = Rect &
diff --git a/packages/core/src/figma-api/accessor-utils.ts b/packages/core/src/figma-api/accessor-utils.ts
index f20944d3a..ce98063f1 100644
--- a/packages/core/src/figma-api/accessor-utils.ts
+++ b/packages/core/src/figma-api/accessor-utils.ts
@@ -6,8 +6,8 @@ import {
import type { GroupFitOptions, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { assertNodeEditable } from '#core/editor/capabilities'
-import { textAutoResizeChanges } from '#core/editor/text/auto-resize'
import type { NodeProxyHost } from '#core/figma-api/proxy'
+import { textAutoResizeChanges } from '#core/layout/text-auto-resize'
export interface NodeProxyInternals {
id: symbol
diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.ts
index 9c26e515b..c8e43b998 100644
--- a/packages/core/src/figma-api/index.ts
+++ b/packages/core/src/figma-api/index.ts
@@ -23,11 +23,11 @@ import { newLayerDefaults } from '#core/editor/shapes/defaults'
import { booleanOperationPaints, createBooleanOperation } from '#core/editor/structure/boolean'
import { wrapNodes } from '#core/editor/structure/container-wrap'
import { ungroupNode } from '#core/editor/structure/group'
-import { textAutoResizeChanges } from '#core/editor/text/auto-resize'
import { setDefaultPageBackground } from '#core/figma-api/page-backgrounds'
import { iconify, type IconProvider } from '#core/icons'
import type { RasterCodec } from '#core/io/formats/raster'
import { createSVGNodes } from '#core/io/formats/svg'
+import { textAutoResizeChanges } from '#core/layout/text-auto-resize'
import { reconcileVariableLayouts } from '#core/layout/variables'
import { documentFontStatus, type DocumentFontStatus } from '#core/text/font/status'
diff --git a/packages/core/src/io/formats.ts b/packages/core/src/io/formats.ts
index 16edbb192..2b86f090b 100644
--- a/packages/core/src/io/formats.ts
+++ b/packages/core/src/io/formats.ts
@@ -1,6 +1,8 @@
import { sceneNodeToJSX, selectionToJSX } from '@open-pencil/design-jsx'
import { parsePenFile } from '@open-pencil/pen'
+import { layoutAuthoredNodes } from '#core/layout'
+
import { exportFigFile, parseFigFile } from './formats/fig'
import type { PPTXExportOptions } from './formats/pptx'
import { headlessRenderNodes, renderNodesToImage, type RasterExportFormat } from './formats/raster'
@@ -223,6 +225,11 @@ export const penFormat: IOFormatAdapter<'pen'> = {
async readDocument(input) {
const text = new TextDecoder().decode(input.data)
const graph = parsePenFile(text)
+ // A .pen file stores its layout intent, not the sizes and positions it implies.
+ layoutAuthoredNodes(
+ graph,
+ graph.getPages().map((page) => page.id)
+ )
return { graph, sourceFormat: 'pen' }
}
}
diff --git a/packages/core/src/io/formats/html/import.ts b/packages/core/src/io/formats/html/import.ts
new file mode 100644
index 000000000..3d5796618
--- /dev/null
+++ b/packages/core/src/io/formats/html/import.ts
@@ -0,0 +1,55 @@
+import {
+ createHeadlessCSSRuntime,
+ htmlToDesignDocument,
+ tailwindHTMLToDesignDocument,
+ type DesignDocument
+} from '@open-pencil/dom-css'
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+import type { IOFormatAdapter } from '#core/io/types'
+
+import { sceneGraphFromStyledHTML } from './layers'
+
+export interface ReadHTMLOptions {
+ /** A stylesheet applied after the document's own `<style>` blocks. */
+ cssText?: string
+ /** Tailwind utility candidates compiled into the stylesheet, as the page's classes use. */
+ tailwind?: readonly string[]
+ pageName?: string
+}
+
+export interface ReadHTMLResult {
+ /** The styled DOM the layers were built from. */
+ styled: DesignDocument
+ graph: SceneGraph
+}
+
+/**
+ * HTML and CSS as a laid-out document, styled by the headless CSS runtime. The runtime needs
+ * Node, so browser builds style with the browser runtime and call `sceneGraphFromStyledHTML`.
+ */
+export async function readHTMLDocument(
+ html: string,
+ options: ReadHTMLOptions = {}
+): Promise<ReadHTMLResult> {
+ const runtime = createHeadlessCSSRuntime()
+ const styled = options.tailwind
+ ? await tailwindHTMLToDesignDocument(html, options.tailwind, { css: options.cssText, runtime })
+ : await htmlToDesignDocument(html, { cssText: options.cssText, runtime })
+ return { styled, graph: sceneGraphFromStyledHTML(styled, { pageName: options.pageName }) }
+}
+
+/** Reads HTML files where the headless CSS runtime is available, as in the CLI. */
+export const headlessHTMLReader: IOFormatAdapter<'html'> = {
+ id: 'html',
+ label: 'HTML',
+ role: 'interchange-document',
+ category: 'document',
+ extensions: ['html', 'htm'],
+ mimeTypes: ['text/html'],
+ support: { readDocument: true },
+ async readDocument(input) {
+ const { graph } = await readHTMLDocument(new TextDecoder().decode(input.data))
+ return { graph, sourceFormat: 'html' }
+ }
+}
diff --git a/packages/core/src/io/formats/html/layers.ts b/packages/core/src/io/formats/html/layers.ts
new file mode 100644
index 000000000..616faa6ee
--- /dev/null
+++ b/packages/core/src/io/formats/html/layers.ts
@@ -0,0 +1,22 @@
+import type { DesignDocument } from '@open-pencil/dom-css'
+import { designDocumentToSceneGraph } from '@open-pencil/dom-css/scene-graph'
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+import { layoutAuthoredNodes } from '#core/layout'
+
+/**
+ * The layers a styled DOM describes, with the sizes and positions its layout implies. Styling
+ * belongs to whoever has a CSS runtime, such as a browser or the headless runtime; building and
+ * laying out the layers happens here for every caller. Safe to bundle for the browser.
+ */
+export function sceneGraphFromStyledHTML(
+ styled: DesignDocument,
+ options: { pageName?: string } = {}
+): SceneGraph {
+ const graph = designDocumentToSceneGraph(styled, { pageName: options.pageName })
+ layoutAuthoredNodes(
+ graph,
+ graph.getPages().map((page) => page.id)
+ )
+ return graph
+}
diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.ts
index 34097bf46..8c6d94297 100644
--- a/packages/core/src/layout.ts
+++ b/packages/core/src/layout.ts
@@ -23,6 +23,7 @@ import {
import { usesDetachedDerivedLayout } from './layout/derived'
import { applyEffectiveGeneratedTextLayout } from './layout/effective-generated-text'
import { buildGridTree, createGridChildNode } from './layout/grid'
+import { sizeAutoResizingText } from './layout/text-auto-resize'
export {
estimateTextSize,
getTextMeasurer,
@@ -89,6 +90,30 @@ export function computeAllLayouts(graph: SceneGraph, scopeId?: string): void {
})
}
+/**
+ * Gives content an author wrote, such as design JSX, HTML, or a `.pen` file, the sizes and
+ * positions its layout implies, which the source does not store, measuring its text first.
+ * Documents that store their geometry, such as `.fig` files, keep theirs and do not come here.
+ */
+export function layoutAuthoredNodes(graph: SceneGraph, rootIds: Iterable<string>): void {
+ const roots = [...rootIds]
+ const pageIds = new Set<string>()
+ let outsidePages = false
+ for (const id of roots) {
+ sizeAutoResizingText(graph, id)
+ const page = graph.closest(id, (node) => node.type === 'CANVAS')
+ if (page) pageIds.add(page.id)
+ else outsidePages = true
+ }
+ const layout = () => {
+ if (outsidePages) computeAllLayouts(graph)
+ else for (const pageId of pageIds) computeAllLayouts(graph, pageId)
+ }
+ layout()
+ // Layout gives wrapping text its width, which its height follows.
+ if (roots.map((id) => sizeAutoResizingText(graph, id, true)).some(Boolean)) layout()
+}
+
function computeLayoutsBottomUp(graph: SceneGraph, nodeId: string, visited: Set<string>): void {
const node = graph.getNode(nodeId)
if (!node || visited.has(nodeId)) return
diff --git a/packages/core/src/editor/text/auto-resize.ts b/packages/core/src/layout/text-auto-resize.ts
similarity index 58%
rename from packages/core/src/editor/text/auto-resize.ts
rename to packages/core/src/layout/text-auto-resize.ts
index 01ae7cb86..acc72cbd3 100644
--- a/packages/core/src/editor/text/auto-resize.ts
+++ b/packages/core/src/layout/text-auto-resize.ts
@@ -1,6 +1,6 @@
-import { TEXT_METRIC_FIELDS, type SceneNode } from '@open-pencil/scene-graph'
+import { TEXT_METRIC_FIELDS, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
-import { estimateTextSize, getTextMeasurer } from '#core/layout/text-measurement'
+import { estimateTextSize, getTextMeasurer } from './text-measurement'
export const TEXT_AUTO_RESIZE_KEYS = new Set<keyof SceneNode>([
...TEXT_METRIC_FIELDS,
@@ -49,3 +49,35 @@ export function textAutoResizeChanges(
return resized
}
+
+/**
+ * Measures the text under `rootId` that resizes to its content; `wrappingOnly` measures only text
+ * that wraps, at the width it has now. Auto layout measures the text it holds when it lays out;
+ * text anywhere else keeps the size it was created with otherwise. Reports whether a size changed.
+ */
+export function sizeAutoResizingText(
+ graph: SceneGraph,
+ rootId: string,
+ wrappingOnly = false
+): boolean {
+ let changed = false
+ const stack = [rootId]
+ for (let id = stack.pop(); id !== undefined; id = stack.pop()) {
+ const node = graph.getNode(id)
+ if (!node) continue
+ stack.push(...node.childIds)
+ if (node.type !== 'TEXT' || (wrappingOnly && node.textAutoResize !== 'HEIGHT')) continue
+ // Wrapping text the source gave no width wraps at the width its content takes.
+ const unsized = node.textAutoResize === 'HEIGHT' && node.width <= 0
+ const changes = textAutoResizeChanges(node, {
+ textAutoResize: unsized ? 'WIDTH_AND_HEIGHT' : node.textAutoResize
+ })
+ const resized =
+ (changes.width !== undefined && changes.width !== node.width) ||
+ (changes.height !== undefined && changes.height !== node.height)
+ if (!resized) continue
+ graph.updateNode(id, changes)
+ changed = true
+ }
+ return changed
+}
diff --git a/packages/core/tests/design-jsx/renderer.test.ts b/packages/core/tests/design-jsx/renderer.test.ts
index 440cfafc8..87cb5ffce 100644
--- a/packages/core/tests/design-jsx/renderer.test.ts
+++ b/packages/core/tests/design-jsx/renderer.test.ts
@@ -32,3 +32,22 @@ describe('renderTree onNode', () => {
expect(graph.getNode(result.id)?.name).toBe('Card')
})
})
+
+describe('renderTree sizing', () => {
+ test('text in a frame without auto layout takes its content size', async () => {
+ const graph = new SceneGraph()
+ const root: TreeNode = {
+ type: 'frame',
+ props: { w: 300, h: 200 },
+ children: [{ type: 'text', props: { size: 28 }, children: ['Hello world'] }]
+ }
+
+ const result = await renderTree(graph, root)
+ const text = graph.getNode(graph.getNode(result.id)?.childIds[0] ?? '')
+
+ expect(text?.textAutoResize).toBe('WIDTH_AND_HEIGHT')
+ expect(text?.width).not.toBe(100)
+ expect(text?.height).toBeLessThan(100)
+ expect(text?.width).toBeGreaterThan(text?.height ?? 0)
+ })
+})
diff --git a/packages/core/tests/layout/authored.test.ts b/packages/core/tests/layout/authored.test.ts
new file mode 100644
index 000000000..ac286bfd2
--- /dev/null
+++ b/packages/core/tests/layout/authored.test.ts
@@ -0,0 +1,83 @@
+import { afterEach, describe, expect, test } from 'bun:test'
+
+import { layoutAuthoredNodes, setTextMeasurer } from '@open-pencil/core/layout'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+afterEach(() => setTextMeasurer(null))
+
+function measureByLength() {
+ setTextMeasurer((node, maxWidth) => {
+ const width = (node.text?.length ?? 0) * 10
+ if (maxWidth && width > maxWidth) return { width: maxWidth, height: 40 }
+ return { width, height: 20 }
+ })
+}
+
+describe('laying out authored content', () => {
+ test('text that resizes to its content is measured outside auto layout too', () => {
+ measureByLength()
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const frame = graph.createNode('FRAME', page, { width: 300, height: 200 })
+ const hugging = graph.createNode('TEXT', frame.id, {
+ text: 'Hello',
+ textAutoResize: 'WIDTH_AND_HEIGHT'
+ })
+ const wrapping = graph.createNode('TEXT', frame.id, {
+ text: 'A longer line',
+ width: 60,
+ textAutoResize: 'HEIGHT'
+ })
+ const fixed = graph.createNode('TEXT', frame.id, { text: 'Fixed', textAutoResize: 'NONE' })
+
+ layoutAuthoredNodes(graph, [frame.id])
+
+ expect(graph.getNode(hugging.id)).toMatchObject({ width: 50, height: 20 })
+ expect(graph.getNode(wrapping.id)).toMatchObject({ width: 60, height: 40 })
+ expect(graph.getNode(fixed.id)).toMatchObject({ width: 100, height: 100 })
+ })
+
+ test('wrapping text that layout stretches takes the height of its lines', () => {
+ // No measurer, as headless tools run: layout alone would keep the height of one line.
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const column = graph.createNode('FRAME', page, {
+ layoutMode: 'VERTICAL',
+ width: 200,
+ primaryAxisSizing: 'HUG'
+ })
+ const text = graph.createNode('TEXT', column.id, {
+ text: 'A paragraph long enough to wrap across several lines of the column',
+ fontSize: 14,
+ width: 0,
+ textAutoResize: 'HEIGHT',
+ layoutAlignSelf: 'STRETCH'
+ })
+ layoutAuthoredNodes(graph, [column.id])
+
+ const laidOut = graph.getNode(text.id)
+ expect(laidOut?.width).toBe(200)
+ expect(laidOut?.height).toBeGreaterThan(2 * 14 * 1.4)
+ expect(graph.getNode(column.id)?.height).toBe(laidOut?.height)
+ })
+
+ test('auto layout places the roots it is given', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const stack = graph.createNode('FRAME', page, {
+ layoutMode: 'VERTICAL',
+ paddingTop: 24,
+ paddingLeft: 24,
+ itemSpacing: 16,
+ width: 200,
+ height: 400
+ })
+ const first = graph.createNode('FRAME', stack.id, { width: 50, height: 50 })
+ const second = graph.createNode('FRAME', stack.id, { width: 50, height: 50 })
+
+ layoutAuthoredNodes(graph, [stack.id])
+
+ expect(graph.getNode(first.id)).toMatchObject({ x: 24, y: 24 })
+ expect(graph.getNode(second.id)).toMatchObject({ x: 24, y: 90 })
+ })
+})
diff --git a/packages/design-jsx/src/renderer.ts b/packages/design-jsx/src/renderer.ts
index a5803c42c..5bdd13bf6 100644
--- a/packages/design-jsx/src/renderer.ts
+++ b/packages/design-jsx/src/renderer.ts
@@ -94,7 +94,8 @@ export async function renderRoots<Artwork>(
nodes.push(node)
}
- services.layout(graph)
+ const rootIds = nodes.map((node) => node.id)
+ if (!options.deferLayout) services.layout(graph, rootIds)
return nodes.map((node) => ({
id: node.id,
diff --git a/packages/design-jsx/src/services.ts b/packages/design-jsx/src/services.ts
index fe1c23352..035d1400b 100644
--- a/packages/design-jsx/src/services.ts
+++ b/packages/design-jsx/src/services.ts
@@ -28,6 +28,6 @@ export interface DesignJSXServices<Artwork> {
svg(source: SVGSource, size: number): Artwork | null
/** Vector nodes for the artwork, created under the placement's parent. */
createArtwork(graph: SceneGraph, artwork: Artwork, placement: ArtworkPlacement): SceneNode
- /** Lay out the graph once rendered nodes are in place. */
- layout(graph: SceneGraph): void
+ /** Size and lay out the rendered roots once they are in place. */
+ layout(graph: SceneGraph, rootIds: readonly string[]): void
}
diff --git a/packages/design-jsx/src/types.ts b/packages/design-jsx/src/types.ts
index e1247007d..a283b4877 100644
--- a/packages/design-jsx/src/types.ts
+++ b/packages/design-jsx/src/types.ts
@@ -8,4 +8,6 @@ export interface RenderOptions {
parentId?: string
/** Called for every layer created from an element, so callers can map source to layers. */
onNode?: (tree: TreeNode, node: SceneNode) => void
+ /** Leave layout to the caller, which lays out once after moving the roots into place. */
+ deferLayout?: boolean
}
diff --git a/packages/dom-css/package.json b/packages/dom-css/package.json
index 45a22e7ac..ba51f43ae 100644
--- a/packages/dom-css/package.json
+++ b/packages/dom-css/package.json
@@ -30,6 +30,12 @@
"import": "./dist/export.js",
"default": "./dist/export.js"
},
+ "./scene-graph": {
+ "types": "./dist/scene-graph.d.ts",
+ "bun": "./src/import/scene-graph.ts",
+ "import": "./dist/scene-graph.js",
+ "default": "./dist/scene-graph.js"
+ },
"./jsx-runtime": {
"types": "./dist/jsx-runtime.d.ts",
"bun": "./src/import/jsx/runtime.ts",
diff --git a/packages/dom-css/tsdown.config.ts b/packages/dom-css/tsdown.config.ts
index 498ed8a16..6f0165ee3 100644
--- a/packages/dom-css/tsdown.config.ts
+++ b/packages/dom-css/tsdown.config.ts
@@ -5,6 +5,7 @@ export default defineConfig({
index: './src/index.ts',
browser: './src/browser.ts',
export: './src/export/index.ts',
+ 'scene-graph': './src/import/scene-graph.ts',
'jsx-runtime': './src/import/jsx/runtime.ts',
'jsx-dev-runtime': './src/import/jsx/dev-runtime.ts'
},
diff --git a/packages/pen/src/read.ts b/packages/pen/src/read.ts
index e936caf6d..c5c4af611 100644
--- a/packages/pen/src/read.ts
+++ b/packages/pen/src/read.ts
@@ -262,17 +262,8 @@ function createSceneNode(
applyCornerRadius(node, pen.cornerRadius, ctx)
applyPadding(node, pen.padding, ctx)
- if (isTextLike) {
- applyTextProps(node, pen, ctx)
- if (parentLayout === 'NONE' && pen.width === undefined && !pen.textGrowth) {
- node.textAutoResize = 'NONE'
- node.width = estimateTextWidth(node)
- node.height = node.fontSize * (node.lineHeight ? node.lineHeight / node.fontSize : 1.2)
- } else if (pen.width === undefined) {
- // Headless layout keeps stored sizes, so an omitted width starts from the content.
- node.width = estimateTextWidth(node)
- }
- }
+ // Text without a width resizes to its content, which laying out the document measures.
+ if (isTextLike) applyTextProps(node, pen, ctx)
if (pen.type === 'path' && pen.geometry) {
const vectorNetwork = parseSVGPath(pen.geometry)
@@ -479,10 +470,6 @@ function fixInstanceWidths(graph: SceneGraph): void {
}
}
-function estimateTextWidth(node: SceneNode): number {
- return node.text.length * node.fontSize * 0.65
-}
-
export function parsePenFile(json: string): SceneGraph {
const doc: PenDocument = JSON.parse(json)
const graph = new SceneGraph()
diff --git a/src/app/document/io/dom.ts b/src/app/document/io/dom.ts
index 07aa67602..678494aa0 100644
--- a/src/app/document/io/dom.ts
+++ b/src/app/document/io/dom.ts
@@ -1,4 +1,5 @@
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 { describeDiagnosticError, recordDocumentFailure } from '@/app/diagnostics'
@@ -67,6 +68,10 @@ export function createDOMOpenActions({
signal: load.signal
})
load.signal.throwIfAborted()
+ layoutAuthoredNodes(
+ graph,
+ graph.getPages().map((page) => page.id)
+ )
await yieldToUI()
await applyImportedDocument(editor, graph, load)
state.documentName = pageName
diff --git a/src/app/tabs/index.ts b/src/app/tabs/index.ts
index 449f98801..5ddf3a20b 100644
--- a/src/app/tabs/index.ts
+++ b/src/app/tabs/index.ts
@@ -481,8 +481,6 @@ export async function openFileInNewTab(
sourceFormat = result.sourceFormat
}
- const firstPageId = imported.getPages()[0]?.id
- if (!isFig && firstPageId) computeAllLayouts(imported, firstPageId)
await showImportedGraph(
store,
imported,
diff --git a/tests/engine/pen/layout.test.ts b/tests/engine/pen/layout.test.ts
index 182bca87f..9e332e175 100644
--- a/tests/engine/pen/layout.test.ts
+++ b/tests/engine/pen/layout.test.ts
@@ -1,12 +1,16 @@
import { describe, expect, test } from 'bun:test'
-import { computeAllLayouts } from '@open-pencil/core/layout'
+import { layoutAuthoredNodes } from '@open-pencil/core/layout'
import { parsePenFile, parseSize, type PenDocument, type PenNode } from '@open-pencil/pen'
function parseLayoutDocument(children: PenNode[]) {
const document: PenDocument = { version: '2.17', children }
const graph = parsePenFile(JSON.stringify(document))
- computeAllLayouts(graph)
+ // As the .pen reader lays out what it reads.
+ layoutAuthoredNodes(
+ graph,
+ graph.getPages().map((page) => page.id)
+ )
return graph
}