Skip to content

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

feat: show controls in a prebuilt demo and fix what saving it to .fig lost (#938)

Danila Poyarkov759f9eb6110f
diff --git a/.gitignore b/.gitignore
index 5d70c2768..f303add59 100644
--- a/.gitignore
+++ b/.gitignore
@@ -58,6 +58,10 @@ storybook-static/
/packages/docs/public/brand/
/packages/docs/public/favicon.ico
/packages/docs/public/apple-touch-icon.png
+# Generated by tools/generate/demo from its sources
+/.cache/demo/
+/.cache/demo.lock/
+/public/demo.fig
/desktop/icons/
# Copied from node_modules at build time
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2c239b747..deda1d4b1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -40,8 +40,9 @@
- Share only the selected layers with MCP clients: **Share only the selection** under **Settings → MCP → Local server**, or `OPENPENCIL_MCP_SCOPE=selection` for a server you start yourself, limits clients to `get_selection`, `get_node`, `get_page_tree`, `describe`, and `export_image` on the selected layers and what they hold, enforced by the server for MCP sessions, stdio clients, and `/rpc` alike.
- Set up AI in a few steps with guided setup. On first launch OpenPencil asks what AI should help with and what you already use: a coding agent on this computer (Claude Code, Codex, Gemini CLI, or Pi, in the desktop app), an API account (Anthropic, OpenAI, Google AI, OpenRouter, DeepSeek, Z.ai, or MiniMax), or a local or company server such as Ollama or LM Studio. Sign in to OpenRouter from the browser or the desktop app instead of pasting a key. In the desktop app, setup checks whether the agent, its OpenPencil adapter, OpenPencil's MCP server, and Pi's Harness companion are installed and match the app, installs or updates them with one click through npm, and links a [setup guide](https://openpencil.dev/programmable/coding-agents) or copies a prompt that asks the agent to set itself up. Setup tests each connection, proposes a model for each role that you can change, and keeps anything configured by hand. Skip it to start designing, or run it again from **Settings → AI & agents**.
- Print the installed version of OpenPencil's MCP server and Harness companion with `openpencil-mcp-http --version`, `openpencil-mcp --version`, and `openpencil-harness --version`. The desktop app asks it to check that they match the app on every platform, including npm `.cmd` shims on Windows and version managers such as Volta and mise.
+- Add a Controls page to the `/demo` document: a switch, checkbox, slider, tabs, text field, and a button with hover, pressed, focus, and disabled states, written as Reka-named design JSX, and a settings card made of their instances to try in preview.
- Make main components behave like real controls and try them in preview. The Behaviour section turns a component or component set into a Button, Text field, Textarea, Number field, Toggle, Switch, Checkbox, Radio, Radio group, Toggle group, Slider, Progress, Tabs, Collapsible, or Accordion, after Reka UI's primitives: its values bind to the component's variant, boolean, and text properties, a slider or number field keeps its own number range, its parts are its slots (a group's items slot holds its radios, toggles, or collapsibles), and a variant property can draw its default, hover, pressed, focus, and disabled states. Rows are named for the control, and an empty row creates what it needs: a text layer and text property, Off and On variants, a slot in every variant, or a variant for each interaction state, turning a lone component into a component set when it needs variants. View > Preview (⌥⌘↩) runs each top-level layer holding controls as live Reka UI components over the canvas, drawn by the component's variants: real inputs with the browser's caret, selection, and paste, keyboard focus and navigation, and layout that grows as collapsibles open, all without changing the document, its history, or what collaborators see; Esc or the pill returns to editing.
-- Build controls from scripts, tools, and design JSX. Scripts run by `eval`, `openpencil eval`, and app automation get an `openpencil` global next to `figma`, in the Figma API's style: `openpencil.setBehaviour(set, { kind: 'switch', values: { value: 'State' }, parts: { thumb: 'Thumb' }, states: 'Interaction' })` or `.bindValue()` and `.bindPart()` by property and slot names, `getBehaviour`, `behaviourKinds`, and `createSlot`. MCP and AI chat get `set_behaviour`, `get_behaviour`, and `create_slot`. Design JSX writes controls with Reka UI's element names, such as `<Switch.Root modelValue="State">` with `<Switch.Thumb>`, `<TextField.Input>`, and `<Tabs.List>`, and exports components with behaviours the same way.
+- Build controls from scripts, tools, and design JSX. Scripts run by `eval`, `openpencil eval`, and app automation get an `openpencil` global next to `figma`, in the Figma API's style: `openpencil.setBehaviour(set, { kind: 'switch', values: { value: 'State' }, parts: { thumb: 'Thumb' }, states: 'Interaction' })` or `.bindValue()` and `.bindPart()` by property and slot names, `getBehaviour`, `behaviourKinds`, and `createSlot`. MCP and AI chat get `set_behaviour`, `get_behaviour`, and `create_slot`. Design JSX writes controls with Reka UI's element names, such as `<Switch.Root modelValue="State">` with `<Switch.Thumb>`, `<TextField.Input>`, and `<Tabs.List>`, in JSX strings or in TSX through the typed `Switch`, `Slider`, `Tabs`, and other namespaces `@open-pencil/design-jsx` exports, and exports components with behaviours the same way.
- Open a `.fig`, `.pen`, or other supported document by dragging it onto the window, where it opens in a new tab as File → Open does. Images and SVG files dropped on the canvas are still placed, and other files report that they can't be opened instead of being ignored.
- Pass an ID generator to `new SceneGraph()` from `@open-pencil/scene-graph` to choose the IDs of the nodes, variables, collections, and modes the graph creates, including modes added later with `createMode`; generated IDs skip any node, variable, collection, or mode ID already in the graph, and an exhausted generator throws instead of hanging. `createComponentPropertyId` gives new component properties the `prop:` IDs the editor, plugin API, and design JSX share.
- Diagnose failures from Settings → Diagnostics. Uncaught errors, unhandled rejections, component errors, failed AI chats, and AI tool calls that broke inside OpenPencil are recorded with their message and stack, and other failed tool calls as warnings. Messages and stacks are scrubbed of URL queries and credentials, API keys and tokens, email addresses, and home folder names, and provider errors keep no message. Each event has a specific label, such as *Tool: render · 162 ms* or *Error: TypeError*, expands to its details, and can be filtered by level and category and paged; copied diagnostics include the app version and browser.
@@ -88,6 +89,7 @@
- Run Pi with the providers you signed in to in the Pi CLI and Pi's default model, so an AI Gateway key and a model ID are optional. The Pi model editor shows whether the Harness companion and MCP server are installed and match the app, and a chat whose Harness companion is missing, or whose companion or MCP server does not match the app, says what to fix and offers guided setup instead of failing with a generic error, and the message and its attachments stay in the composer.
- Point Codex install instructions at `@agentclientprotocol/codex-acp`, which replaces `@zed-industries/codex-acp` and provides the same `codex-acp` command.
- The desktop app shows an available update in a Software Update window with formatted, scrollable release notes, a link to the full notes, and download progress you can cancel, instead of a system dialog that showed raw Markdown and could grow taller than the screen (#743). On macOS and Linux the update installs first and you choose when to restart; restarting, and on Windows installing, first asks about unsaved documents as Quit does.
+- Show Go to main component and Detach instance as buttons in an instance's panel header instead of a row of links below it.
- `openpencil eval` prints the value of a script's last expression, as the `eval` tool and app automation already do, so `-c 'figma.currentPage.children.length'` prints the count without a `return`.
- In scripts, children of groups and booleans report `x`, `y`, and `relativeTransform` in their container's space, as in Figma, and a group refits whenever a script moves, resizes, rotates, adds, or removes one of its children; a group left without children is removed. The canvas and the plugin API share the refit.
- The properties panel shows and edits X, Y, and rotation as Figma's does: X and Y are the top-left of a turned layer's box on the canvas, measured from its frame or page through any groups, rotation is counterclockwise, and a typed rotation turns the layer about its center. Previously a layer Figma shows at 30° read −30°, and a turned layer's X and Y were those of its unturned box.
@@ -131,6 +133,10 @@
- Read geometry in scripts after an edit without waiting for the script to finish: `x`, `y`, `width`, `height`, `relativeTransform`, `absoluteTransform`, `absoluteBoundingBox`, and `absoluteRenderBounds` lay out what the script changed first, as in Figma, so a hugging parent reports its new size right after a child is added.
- Draw segmented controls in the properties panel at the height of the fields beside them.
- Keep saving AI chat history in Safari Private Browsing after a message with an image or a reply that changed the document. Safari cannot store image data that way in a private window, so the conversation stopped saving from that point and showed "Chat history could not be saved".
+- Keep a component set's dashed border one pixel wide at every zoom; zooming in after opening a page scaled it into thick dashes until the page was redrawn.
+- Keep a layer's blend mode, such as Multiply or Screen, when saving to `.fig`; it was dropped and the layer reopened as pass-through.
+- Stop the underline of saved or Figma text where the text ends instead of running to the edge of its text box.
+- Keep the content of an imported auto layout frame centred, or otherwise aligned, within the width its parent stretches it to, instead of laying it out as if the frame hugged its content.
- `figma.combineAsVariants` derives variant properties from components named as Figma names variants, such as `State=On, Size=Large`, as Combine as variants in the editor now does too; before, only slash-separated names gave the set any properties.
- HTML and Tailwind export place layers of frames without auto layout at their coordinates instead of stacking them, leave the size of hugging auto layout frames and auto-sizing text to their content, and round ellipses.
- Show the blinking caret in a new, empty text layer before the first character is typed.
@@ -215,6 +221,7 @@
### Performance
- Edit variables in large documents without stalls: renaming, reordering, or adding a variable, or changing its CSS name, unit, scopes, or conditions, no longer redraws the canvas, and changing a value or mode updates only the layers bound to those variables or to variables aliasing them instead of re-resolving and laying out every bound layer in the document.
+- Open the `/demo` document like any `.fig` file, built ahead of time, instead of generating it in the browser, which froze the page for several seconds.
- Open large `.fig` files with less memory in the macOS desktop app and Safari: imported layers now share one object layout in JavaScriptCore instead of each being stored as a slower, larger dictionary.
- Open multi-page `.fig` documents faster: the archive is indexed once rather than once for every page, each page resolves only the layers it adds instead of rescanning the whole document, placing an instance no longer re-synchronises every other instance of its component, and archive records are copied directly rather than through `structuredClone`. A 33-page file loads about a fifth quicker, and a page of repeated components opens three to four times faster once a document is already open.
diff --git a/bun.lock b/bun.lock
index 0650aec8f..e286b98b8 100644
--- a/bun.lock
+++ b/bun.lock
@@ -107,6 +107,7 @@
"@lobehub/icons-static-svg": "^1.95.1",
"@modelcontextprotocol/client": "^2.0.0",
"@open-pencil/brand-tools": "workspace:*",
+ "@open-pencil/demo-tools": "workspace:*",
"@open-pencil/mcp": "workspace:*",
"@oxlint/plugins": "1.57.0",
"@playwright/test": "^1.63.0",
@@ -571,6 +572,22 @@
"typescript": "~5.8.3",
},
},
+ "tools/generate/demo": {
+ "name": "@open-pencil/demo-tools",
+ "dependencies": {
+ "@open-pencil/core": "workspace:*",
+ "@open-pencil/design-jsx": "workspace:*",
+ "@open-pencil/package-artifacts-tools": "workspace:*",
+ "@open-pencil/scene-graph": "workspace:*",
+ "proper-lockfile": "4.1.2",
+ },
+ "devDependencies": {
+ "@types/bun": "^1.3.14",
+ "@types/node": "^25.9.9",
+ "@types/proper-lockfile": "4.1.4",
+ "typescript": "~5.8.3",
+ },
+ },
"tools/generate/tauri-menu": {
"name": "@open-pencil/tauri-menu-tools",
"dependencies": {
@@ -1490,6 +1507,8 @@
"@open-pencil/core": ["@open-pencil/core@workspace:packages/core"],
+ "@open-pencil/demo-tools": ["@open-pencil/demo-tools@workspace:tools/generate/demo"],
+
"@open-pencil/design-jsx": ["@open-pencil/design-jsx@workspace:packages/design-jsx"],
"@open-pencil/dev-server-tools": ["@open-pencil/dev-server-tools@workspace:tools/dev/dev-server"],
@@ -4806,30 +4825,6 @@
"@multiformats/dns/uint8arrays": ["[email protected]", "", { "dependencies": { "multiformats": "^14.0.0" } }, "sha512-iz7JN0XCSZYA111lhFG2Ui9EhFvTNekqSRHw3lvMHq+dzwWy1OQftxFQREEh4rffU0oSoXdQHsk2TiHKVm4fsA=="],
- "@open-pencil/brand-tools/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
-
- "@open-pencil/cli/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
-
- "@open-pencil/core/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
-
- "@open-pencil/design-jsx/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
-
- "@open-pencil/dom-css/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
-
- "@open-pencil/emit/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
-
- "@open-pencil/fig/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
-
- "@open-pencil/harness/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
-
- "@open-pencil/kiwi/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
-
- "@open-pencil/pen/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
-
- "@open-pencil/scene-graph/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
-
- "@open-pencil/tools/@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="],
-
"@oxc-parser/binding-wasm32-wasi/@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw=="],
"@oxc-resolver/binding-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" } }, "sha512-l9Oo58x0HOP5znGzVhYW9U3e5wVuA4LAZU2AGezTmkhO1CgQRFDhDg4nneHsu/t3WniXg9QrG2nIXL/ZS8ln8Q=="],
@@ -5400,30 +5395,6 @@
"@multiformats/dns/uint8arrays/multiformats": ["[email protected]", "", {}, "sha512-vbIm83F2yZ1pWJGS0yl0ysracIvv56LtbrIyiIQHoLdYDJOMoLfVFsXhh9DUH4SFdkdkFhucyWniihsNzVEjkQ=="],
- "@open-pencil/brand-tools/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
-
- "@open-pencil/cli/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
-
- "@open-pencil/core/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
-
- "@open-pencil/design-jsx/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
-
- "@open-pencil/dom-css/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
-
- "@open-pencil/emit/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
-
- "@open-pencil/fig/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
-
- "@open-pencil/harness/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
-
- "@open-pencil/kiwi/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
-
- "@open-pencil/pen/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
-
- "@open-pencil/scene-graph/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
-
- "@open-pencil/tools/@types/bun/bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
-
"@puppeteer/browsers/yargs/cliui": ["[email protected]", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="],
"@puppeteer/browsers/yargs/yargs-parser": ["[email protected]", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
diff --git a/package.json b/package.json
index 2a219dd25..29ba5bc44 100644
--- a/package.json
+++ b/package.json
@@ -34,6 +34,7 @@
"tools/dev/unit-tests",
"tools/generate/authoring-reference",
"tools/generate/brand",
+ "tools/generate/demo",
"tools/generate/tauri-menu",
"tools/generate/visual-oracles",
"tools/release/package-artifacts",
@@ -94,6 +95,7 @@
"docs:build": "bun --filter @open-pencil/docs build",
"docs:build:production": "bun --filter @open-pencil/docs build:production",
"docs:preview": "bun --filter @open-pencil/docs preview",
+ "generate:demo": "bun tools/generate/demo/src/cli.ts --force",
"generate:icons": "bun tools/generate/brand/src/cli.ts generate",
"check:icons": "bun tools/generate/brand/src/cli.ts check",
"generate:tauri-menu": "bun tools/generate/tauri-menu/src/generate.ts",
@@ -202,6 +204,7 @@
"@lobehub/icons-static-svg": "^1.95.1",
"@modelcontextprotocol/client": "^2.0.0",
"@open-pencil/brand-tools": "workspace:*",
+ "@open-pencil/demo-tools": "workspace:*",
"@open-pencil/mcp": "workspace:*",
"@oxlint/plugins": "1.57.0",
"@playwright/test": "^1.63.0",
diff --git a/packages/core/src/canvas/labels/cache.ts b/packages/core/src/canvas/labels/cache.ts
index d40502c30..c2fcfec65 100644
--- a/packages/core/src/canvas/labels/cache.ts
+++ b/packages/core/src/canvas/labels/cache.ts
@@ -66,6 +66,7 @@ export class LabelCache {
private sections: CachedSection[] = []
private components: CachedComponent[] = []
private frames: CachedFrame[] = []
+ private componentSets: CachedFrame[] = []
private cachedSceneVersion = -1
private cachedPositionPreviewVersion = -1
private cachedPageId: string | null = null
@@ -96,6 +97,7 @@ export class LabelCache {
this.sections = []
this.components = []
this.frames = []
+ this.componentSets = []
}
getSections(
@@ -138,6 +140,15 @@ export class LabelCache {
return collectVisibleLabels(graph, viewport, this.frames, () => ({}), preview)
}
+ /** Every visible component set on the page in the viewport, wherever it is nested. */
+ getComponentSets(
+ graph: SceneGraph,
+ viewport: Viewport,
+ preview?: RenderOverlays['rotationPreview']
+ ): Array<{ node: SceneNode; absX: number; absY: number }> {
+ return collectVisibleLabels(graph, viewport, this.componentSets, () => ({}), preview)
+ }
+
getAllFrames(): readonly CachedFrame[] {
return this.frames
}
@@ -154,6 +165,7 @@ export class LabelCache {
this.sections = []
this.components = []
this.frames = []
+ this.componentSets = []
const pageNode = graph.getNode(pageId ?? graph.rootId)
if (!pageNode) return
@@ -180,6 +192,10 @@ export class LabelCache {
})
this.walkChildren(graph, childId, true)
} else if (LABEL_TYPES.has(child.type)) {
+ if (child.type === 'COMPONENT_SET') {
+ const origin = graph.getAbsolutePosition(childId)
+ this.componentSets.push({ nodeId: childId, absX: origin.x, absY: origin.y })
+ }
if (COMPONENT_LABEL_PARENT_TYPES.has(parentType)) {
const origin = graph.getAbsolutePosition(childId)
this.components.push({ nodeId: childId, absX: origin.x, absY: origin.y, parentType })
diff --git a/packages/core/src/canvas/overlays/component-sets.ts b/packages/core/src/canvas/overlays/component-sets.ts
new file mode 100644
index 000000000..938480b17
--- /dev/null
+++ b/packages/core/src/canvas/overlays/component-sets.ts
@@ -0,0 +1,50 @@
+import type { Canvas } from 'canvaskit-wasm'
+
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+import { labelViewport } from '#core/canvas/labels/layout'
+import type { SkiaRenderer } from '#core/canvas/renderer'
+import { COMPONENT_SET_OUTLINE_RADIUS } from '#core/constants'
+import { createSceneGeometry, type RotationPreview } from '#core/geometry'
+
+/**
+ * The dashed editing border of each component set without a stroke of its own. It is drawn
+ * every frame at the live zoom, so it stays one pixel wide on screen; drawn into the scene, it
+ * would scale with the cached pictures it was recorded in. A set with a stroke draws that
+ * stroke in the scene instead.
+ */
+export function drawComponentSetBorders(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ graph: SceneGraph,
+ preview?: RotationPreview | null
+): void {
+ const sets = r.labelCache
+ .getComponentSets(graph, labelViewport(r.worldViewport, r.zoom), preview)
+ .filter(({ node }) => !node.strokes.some((stroke) => stroke.visible))
+ if (sets.length === 0) return
+
+ const geometry = createSceneGeometry(graph, preview)
+ const dash = r.ck.PathEffect.MakeDash(
+ [r.COMPONENT_SET_DASH / r.zoom, r.COMPONENT_SET_DASH_GAP / r.zoom],
+ 0
+ )
+ r.auxStroke.setStrokeWidth(r.COMPONENT_SET_BORDER_WIDTH / r.zoom)
+ r.auxStroke.setColor(r.compColor())
+ r.auxStroke.setPathEffect(dash)
+ try {
+ for (const { node } of sets) {
+ canvas.save()
+ canvas.concat(geometry.screenMatrix(node, r))
+ const rect = r.ck.LTRBRect(0, 0, node.width, node.height)
+ canvas.drawRRect(
+ r.ck.RRectXY(rect, COMPONENT_SET_OUTLINE_RADIUS, COMPONENT_SET_OUTLINE_RADIUS),
+ r.auxStroke
+ )
+ canvas.restore()
+ }
+ } finally {
+ r.auxStroke.setPathEffect(null)
+ dash.delete()
+ }
+}
diff --git a/packages/core/src/canvas/renderer/overlay-pass.ts b/packages/core/src/canvas/renderer/overlay-pass.ts
index 0bbee8258..b96b8d476 100644
--- a/packages/core/src/canvas/renderer/overlay-pass.ts
+++ b/packages/core/src/canvas/renderer/overlay-pass.ts
@@ -5,6 +5,7 @@ import type { SceneGraph } from '@open-pencil/scene-graph'
import { drawGuides } from '#core/canvas/guides/draw'
import { drawIssueHighlight, drawIssueMarkers } from '#core/canvas/issues/draw'
import { layoutIssueMarkers } from '#core/canvas/issues/layout'
+import { drawComponentSetBorders } from '#core/canvas/overlays/component-sets'
import { drawLayoutOutlines } from '#core/canvas/overlays/layout-outlines'
import { drawMeasurementSegment } from '#core/canvas/overlays/measurement'
import { drawCodeFocus } from '#core/canvas/overlays/selection'
@@ -96,6 +97,7 @@ export function drawOverlayPass(
measuring || overlays.hoveredNodeId === overlays.nodeEditState?.nodeId
? null
: overlays.hoveredNodeId
+ drawComponentSetBorders(r, canvas, graph, overlays.rotationPreview)
drawCodeFocus(r, canvas, graph, overlays.codeFocusNodeId, overlays.rotationPreview)
if (!measuring)
drawSlotOutlines(r, canvas, graph, selectedIds, hoveredNodeId, overlays.rotationPreview)
diff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.ts
index 9cb6256e0..be6912e36 100644
--- a/packages/core/src/canvas/scene.ts
+++ b/packages/core/src/canvas/scene.ts
@@ -12,11 +12,7 @@ import { computeDescendantVisualBounds } from '@open-pencil/scene-graph/geometry
import Matrix from '@open-pencil/scene-graph/matrix'
import type { Color } from '@open-pencil/scene-graph/primitives'
-import {
- COMPONENT_SET_OUTLINE_RADIUS,
- DROP_HIGHLIGHT_ALPHA,
- DROP_HIGHLIGHT_STROKE
-} from '#core/constants'
+import { DROP_HIGHLIGHT_ALPHA, DROP_HIGHLIGHT_STROKE } from '#core/constants'
import { createSceneGeometry, nodeOrientationMatrix, projectedNode } from '#core/geometry'
import { transformTextCase } from '#core/text/case'
import { fontManager } from '#core/text/fonts'
@@ -434,16 +430,25 @@ function forVisibleStrokes(
}
}
-export function renderSection(
+/** Fill a section's or set's rounded bounds and return them, for its strokes to follow. */
+function fillRoundedBounds(
r: SkiaRenderer,
canvas: Canvas,
node: SceneNode,
graph: SceneGraph
-): void {
+): Float32Array {
const rrect = makeNodeRRect(r, node, node.cornerRadius)
-
drawVisibleFills(r, node, graph, () => canvas.drawRRect(rrect, r.fillPaint))
+ return rrect
+}
+export function renderSection(
+ r: SkiaRenderer,
+ canvas: Canvas,
+ node: SceneNode,
+ graph: SceneGraph
+): void {
+ const rrect = fillRoundedBounds(r, canvas, node, graph)
forVisibleStrokes(r, node, graph, (stroke, color) => {
configureStrokePaint(r, node, stroke, color)
@@ -458,39 +463,25 @@ export function renderComponentSet(
node: SceneNode,
graph: SceneGraph
): void {
- const rrect = makeNodeRRect(r, node, node.cornerRadius)
-
- drawVisibleFills(r, node, graph, () => canvas.drawRRect(rrect, r.fillPaint))
-
- const visibleStrokes = node.strokes.filter((stroke) => stroke.visible)
- if (visibleStrokes.length > 0) {
- forVisibleStrokes(r, node, graph, (stroke, color) => {
- const dashPhase = stroke.dashPattern?.[1] ?? 0
- if (stroke.dashPattern && stroke.dashPattern.length > 0) {
- drawDashedRRectWithSolidCorners(
- r,
- canvas,
- node,
- stroke,
- color,
- // Skia fits a rounded rect's radii to its bounds; the dashed outline must match the fill.
- Math.min(node.cornerRadius, node.width / 2, node.height / 2),
- dashPhase
- )
- } else {
- drawStyledRRectStroke(r, canvas, rrect, node, stroke, color, dashPhase)
- }
- })
- return
- }
-
- r.auxStroke.setStrokeWidth(r.COMPONENT_SET_BORDER_WIDTH / r.zoom)
- r.auxStroke.setColor(r.compColor())
- r.auxStroke.setPathEffect(
- r.ck.PathEffect.MakeDash([r.COMPONENT_SET_DASH / r.zoom, r.COMPONENT_SET_DASH_GAP / r.zoom], 0)
- )
- canvas.drawRRect(makeNodeRRect(r, node, COMPONENT_SET_OUTLINE_RADIUS), r.auxStroke)
- r.auxStroke.setPathEffect(null)
+ const rrect = fillRoundedBounds(r, canvas, node, graph)
+ // A set without a stroke gets its dashed editing border from the overlay pass.
+ forVisibleStrokes(r, node, graph, (stroke, color) => {
+ const dashPhase = stroke.dashPattern?.[1] ?? 0
+ if (stroke.dashPattern && stroke.dashPattern.length > 0) {
+ drawDashedRRectWithSolidCorners(
+ r,
+ canvas,
+ node,
+ stroke,
+ color,
+ // Skia fits a rounded rect's radii to its bounds; the dashed outline must match the fill.
+ Math.min(node.cornerRadius, node.width / 2, node.height / 2),
+ dashPhase
+ )
+ } else {
+ drawStyledRRectStroke(r, canvas, rrect, node, stroke, color, dashPhase)
+ }
+ })
}
function canRasterCacheEffects(node: SceneNode): boolean {
diff --git a/packages/core/src/canvas/text/derived.ts b/packages/core/src/canvas/text/derived.ts
index 18970fbe6..5788cb61b 100644
--- a/packages/core/src/canvas/text/derived.ts
+++ b/packages/core/src/canvas/text/derived.ts
@@ -52,10 +52,28 @@ export function derivedUnderlineRect(node: Pick<SceneNode, 'width'>, baselineY:
}
}
+/**
+ * Where the drawn text starts and ends, from its glyphs, when every glyph knows its advance;
+ * text narrower than its layer, or aligned to the centre or the end, does not reach its edges.
+ */
+function derivedTextExtent(node: SceneNode): { x1: number; x2: number } | null {
+ const glyphs = node.derivedTextGlyphs ?? []
+ if (glyphs.length === 0) return null
+ // A loop rather than spreading into Math.min/max, which long texts would overflow.
+ let x1 = Infinity
+ let x2 = -Infinity
+ for (const glyph of glyphs) {
+ if (glyph.advance === undefined) return null
+ x1 = Math.min(x1, glyph.x)
+ x2 = Math.max(x2, glyph.x + glyph.advance * (glyph.scaleX ?? 1))
+ }
+ return { x1, x2 }
+}
+
function styleRunX(node: SceneNode, index: number): number {
const glyph = node.derivedTextGlyphs?.[index]
if (glyph) return glyph.x
- if (index >= node.text.length) return node.width
+ if (index >= node.text.length) return derivedTextExtent(node)?.x2 ?? node.width
if (node.text.length === 0) return 0
return (node.width * index) / node.text.length
}
@@ -104,9 +122,10 @@ function isDecorationSpan(span: DecorationSpan | null): span is DecorationSpan {
function baseDecorationSpan(node: SceneNode): DecorationSpan | null {
if (node.textDecoration !== 'UNDERLINE') return null
const rect = derivedUnderlineRect(node, 0)
+ const extent = derivedTextExtent(node)
return {
- x1: rect.x1,
- x2: rect.x2,
+ x1: extent?.x1 ?? rect.x1,
+ x2: extent?.x2 ?? rect.x2,
style: node.textDecorationStyle,
thickness: node.textDecorationThickness ?? rect.y2 - rect.y1,
offset: node.textUnderlineOffset ?? 0,
diff --git a/packages/core/src/editor/components/behaviours/complete.ts b/packages/core/src/editor/components/behaviours/complete.ts
index 13cfa86dd..91a48e912 100644
--- a/packages/core/src/editor/components/behaviours/complete.ts
+++ b/packages/core/src/editor/components/behaviours/complete.ts
@@ -104,17 +104,36 @@ export function createBehaviourCompletionActions(
}
/**
- * Show a text value through a new text property named `name`. Each variant's first text
- * layer that no property shows becomes its target; a variant without one gets a new text
- * layer inset in it.
+ * Add a property under a new id inside a behaviour's owner and bind it, as one undo step:
+ * `create` edits the owner's layers, and `bind` returns the behaviour holding the new id.
*/
- function addBehaviourText(ownerId: string, valueId: string, name: string): string | null {
+ function createAndBind(
+ ownerId: string,
+ label: string,
+ create: (owner: SceneNode, id: string) => void,
+ bind: (behaviour: Behaviour, id: string) => Behaviour
+ ): string | null {
const found = owned(ownerId)
if (!found) return null
const { owner, behaviour } = found
const id = createComponentPropertyId()
- ctx.undo.runBatch(`Add ${name} text`, () => {
- recordSubtreeEdit(ctx, `Add ${name} text`, owner.id, () => {
+ ctx.undo.runBatch(label, () => {
+ recordSubtreeEdit(ctx, label, owner.id, () => create(owner, id))
+ setBehaviour(owner.id, bind(behaviour, id))
+ })
+ return id
+ }
+
+ /**
+ * Show a text value through a new text property named `name`. Each variant's first text
+ * layer that no property shows becomes its target; a variant without one gets a new text
+ * layer inset in it.
+ */
+ function addBehaviourText(ownerId: string, valueId: string, name: string): string | null {
+ return createAndBind(
+ ownerId,
+ `Add ${name} text`,
+ (owner, id) => {
let defaultValue = name
for (const variant of variantsOf(ctx, owner)) {
const layer =
@@ -144,13 +163,12 @@ export function createBehaviourCompletionActions(
{ id, name, type: 'TEXT', defaultValue }
]
})
- })
- setBehaviour(owner.id, {
+ },
+ (behaviour, id) => ({
...behaviour,
texts: { ...behaviour.texts, [valueId]: { propertyId: id } }
})
- })
- return id
+ )
}
/**
@@ -186,12 +204,10 @@ export function createBehaviourCompletionActions(
* variant of a set, all under one slot id so the part is the same slot in every state.
*/
function addBehaviourPart(ownerId: string, partId: string, name: string): string | null {
- const found = owned(ownerId)
- if (!found) return null
- const { owner, behaviour } = found
- const id = createComponentPropertyId()
- ctx.undo.runBatch(`Add ${name} slot`, () => {
- recordSubtreeEdit(ctx, `Add ${name} slot`, owner.id, () => {
+ return createAndBind(
+ ownerId,
+ `Add ${name} slot`,
+ (owner, id) => {
for (const variant of variantsOf(ctx, owner)) {
const frame = ctx.graph.createNode('FRAME', variant.id, {
name,
@@ -203,10 +219,9 @@ export function createBehaviourCompletionActions(
})
createSlotProperty(ctx.graph, frame.id, id)
}
- })
- setBehaviour(owner.id, { ...behaviour, parts: { ...behaviour.parts, [partId]: id } })
- })
- return id
+ },
+ (behaviour, id) => ({ ...behaviour, parts: { ...behaviour.parts, [partId]: id } })
+ )
}
/**
diff --git a/packages/core/src/layout.ts b/packages/core/src/layout.ts
index e194b2ce0..34097bf46 100644
--- a/packages/core/src/layout.ts
+++ b/packages/core/src/layout.ts
@@ -47,7 +47,8 @@ import {
mapAlign,
mapAlignSelf,
mapGridTrack,
- mapJustify
+ mapJustify,
+ parentStretchedAxis
} from './layout/yoga-helpers'
export function computeLayout(graph: SceneGraph, frameId: string): void {
@@ -122,6 +123,11 @@ function buildYogaTree(
if (frame.layoutMode === 'HORIZONTAL') root.setHeight(frame.height)
else root.setWidth(frame.width)
}
+ // Laid out on its own, a frame its parent stretches keeps the size the parent gave it on
+ // that axis, so its content aligns within that size rather than within a hug.
+ const stretchedAxis = parentStretchedAxis(graph, frame)
+ if (stretchedAxis === 'width') root.setWidth(frame.width)
+ if (stretchedAxis === 'height') root.setHeight(frame.height)
configureFlexContainer(root, frame, direction)
diff --git a/packages/core/src/layout/yoga-helpers.ts b/packages/core/src/layout/yoga-helpers.ts
index 980877bcb..019b18ceb 100644
--- a/packages/core/src/layout/yoga-helpers.ts
+++ b/packages/core/src/layout/yoga-helpers.ts
@@ -7,7 +7,7 @@ import Yoga, {
type Node as YogaNode
} from 'yoga-layout'
-import type { GridTrack, SceneNode } from '@open-pencil/scene-graph'
+import type { GridTrack, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
const yogaConfig = Yoga.Config.create()
yogaConfig.setPointScaleFactor(0)
@@ -119,3 +119,18 @@ export function mapAlignSelf(alignSelf: string): Align | null {
return null
}
}
+
+/** The axis a frame's auto layout parent stretches it along, if any. */
+export function parentStretchedAxis(
+ graph: SceneGraph,
+ frame: SceneNode
+): 'width' | 'height' | null {
+ const parent = frame.parentId ? graph.getNode(frame.parentId) : undefined
+ if (!parent || frame.layoutPositioning === 'ABSOLUTE') return null
+ if (parent.layoutMode !== 'HORIZONTAL' && parent.layoutMode !== 'VERTICAL') return null
+ const stretched =
+ frame.layoutAlignSelf === 'STRETCH' ||
+ (frame.layoutAlignSelf === 'AUTO' && parent.counterAxisAlign === 'STRETCH')
+ if (!stretched) return null
+ return parent.layoutMode === 'VERTICAL' ? 'width' : 'height'
+}
diff --git a/packages/core/tests/canvas/component-set.test.ts b/packages/core/tests/canvas/component-set.test.ts
new file mode 100644
index 000000000..4f4f83d9c
--- /dev/null
+++ b/packages/core/tests/canvas/component-set.test.ts
@@ -0,0 +1,47 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+import { SkiaRenderer } from '#core/canvas/renderer'
+import { getCanvasKit } from '#core/canvaskit'
+import { renderNodesToImage } from '#core/io/formats/raster/render'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+let ck: Awaited<ReturnType<typeof getCanvasKit>>
+
+beforeAll(async () => {
+ ck = await getCanvasKit()
+})
+
+describe('component set rendering', () => {
+ test('a set without a stroke draws no editing border in the scene', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const set = graph.createNode('COMPONENT_SET', page.id, { width: 40, height: 40, fills: [] })
+ const surface = expectDefined(ck.MakeSurface(1, 1), 'surface')
+ const renderer = new SkiaRenderer(ck, surface)
+
+ try {
+ const png = expectDefined(
+ renderNodesToImage(ck, renderer, graph, page.id, [set.id], { scale: 1, format: 'PNG' }),
+ 'png'
+ )
+ const image = expectDefined(ck.MakeImageFromEncoded(png), 'image')
+ const pixels = expectDefined(
+ image.readPixels(0, 0, {
+ alphaType: ck.AlphaType.Unpremul,
+ colorType: ck.ColorType.RGBA_8888,
+ colorSpace: ck.ColorSpace.SRGB,
+ width: image.width(),
+ height: image.height()
+ }),
+ 'pixels'
+ )
+ // The border is editor chrome, drawn by the overlay pass at the live zoom.
+ expect(Math.max(...pixels.filter((_, index) => index % 4 === 3))).toBe(0)
+ image.delete()
+ } finally {
+ surface.delete()
+ }
+ })
+})
diff --git a/packages/core/tests/canvas/text/derived.test.ts b/packages/core/tests/canvas/text/derived.test.ts
new file mode 100644
index 000000000..f951ae482
--- /dev/null
+++ b/packages/core/tests/canvas/text/derived.test.ts
@@ -0,0 +1,82 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+import { SkiaRenderer } from '#core/canvas/renderer'
+import { getCanvasKit } from '#core/canvaskit'
+import { renderNodesToImage } from '#core/io/formats/raster/render'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+let ck: Awaited<ReturnType<typeof getCanvasKit>>
+
+beforeAll(async () => {
+ ck = await getCanvasKit()
+})
+
+/** A unit square outline in the glyph commands blob format. */
+function squareCommandsBlob(): Uint8Array {
+ const corners = [
+ [1, 0, 0],
+ [2, 1, 0],
+ [2, 1, 1],
+ [2, 0, 1]
+ ] as const
+ const blob = new Uint8Array(1 + corners.length * 9)
+ const view = new DataView(blob.buffer)
+ corners.forEach(([command, x, y], index) => {
+ blob[index * 9] = command
+ view.setFloat32(index * 9 + 1, x, true)
+ view.setFloat32(index * 9 + 5, y, true)
+ })
+ return blob
+}
+
+/** The highest coverage on the underline rows at column `x` of a rendered text layer. */
+function underlineAlpha(pixels: ArrayLike<number>, width: number, x: number): number {
+ return Math.max(...[15, 16].map((y) => pixels[(y * width + x) * 4 + 3]))
+}
+
+describe('derived text decorations', () => {
+ test('an underline ends where the glyphs end, not at the layer edge', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const text = graph.createNode('TEXT', page.id, {
+ width: 40,
+ height: 24,
+ text: 'x',
+ fontFamily: '__MissingFont__',
+ textDecoration: 'UNDERLINE',
+ fills: [{ type: 'SOLID', color: { r: 0, g: 0, b: 0, a: 1 }, opacity: 1, visible: true }],
+ derivedTextGlyphs: [
+ { commandsBlob: squareCommandsBlob(), x: 2, y: 12, fontSize: 10, advance: 10 }
+ ]
+ })
+ const surface = expectDefined(ck.MakeSurface(1, 1), 'surface')
+ const renderer = new SkiaRenderer(ck, surface)
+ // The font is missing, so the saved glyphs are what draws the text.
+ renderer.nodeFontReadiness = () => 'exhausted'
+
+ try {
+ const png = expectDefined(
+ renderNodesToImage(ck, renderer, graph, page.id, [text.id], { scale: 1, format: 'PNG' }),
+ 'png'
+ )
+ const image = expectDefined(ck.MakeImageFromEncoded(png), 'image')
+ const pixels = expectDefined(
+ image.readPixels(0, 0, {
+ alphaType: ck.AlphaType.Unpremul,
+ colorType: ck.ColorType.RGBA_8888,
+ colorSpace: ck.ColorSpace.SRGB,
+ width: image.width(),
+ height: image.height()
+ }),
+ 'pixels'
+ )
+ expect(underlineAlpha(pixels, image.width(), 8)).toBeGreaterThan(0)
+ expect(underlineAlpha(pixels, image.width(), 30)).toBe(0)
+ image.delete()
+ } finally {
+ surface.delete()
+ }
+ })
+})
diff --git a/packages/core/tests/io/formats/fig/roundtrip/blend-mode.test.ts b/packages/core/tests/io/formats/fig/roundtrip/blend-mode.test.ts
new file mode 100644
index 000000000..0ee30f3bb
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/roundtrip/blend-mode.test.ts
@@ -0,0 +1,27 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
+import { populateFigPage } from '@open-pencil/core/io/formats/fig'
+
+describe('roundtrip: layer blend modes', () => {
+ beforeAll(async () => {
+ await initCodec()
+ })
+
+ test('a layer keeps its blend mode, and an unset one stays pass-through', async () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ for (const blendMode of ['MULTIPLY', 'SCREEN', 'PASS_THROUGH'] as const)
+ graph.createNode('ELLIPSE', page.id, { name: blendMode, width: 80, height: 80, blendMode })
+
+ const reImported = await parseFigFile((await exportFigFile(graph)).buffer as ArrayBuffer)
+ const [reImportedPage] = reImported.getPages()
+ populateFigPage(reImported, reImportedPage.id)
+
+ expect(reImported.getChildren(reImportedPage.id).map((node) => node.blendMode)).toEqual([
+ 'MULTIPLY',
+ 'SCREEN',
+ 'PASS_THROUGH'
+ ])
+ })
+})
diff --git a/packages/design-jsx/README.md b/packages/design-jsx/README.md
index 14d82c214..c182db0e7 100644
--- a/packages/design-jsx/README.md
+++ b/packages/design-jsx/README.md
@@ -27,7 +27,7 @@ import { renderJSX } from '@open-pencil/core/design-jsx'
await renderJSX(graph, '<Frame w={320} p={16} bg="#FFFFFF"><Text>Hello</Text></Frame>')
```
-Components that behave as controls are written with Reka UI's element names, and export writes them back the same way:
+Components that behave as controls are written with Reka UI's element names, in TSX (import `Switch`, `Slider`, `Tabs`, and the other namespaces, typed with their behaviour props) or in strings, and export writes them back the same way:
```tsx
<Switch.Root name="Switch" modelValue="State">
diff --git a/packages/design-jsx/src/behaviours/elements.ts b/packages/design-jsx/src/behaviours/elements.ts
new file mode 100644
index 000000000..8df46fb13
--- /dev/null
+++ b/packages/design-jsx/src/behaviours/elements.ts
@@ -0,0 +1,47 @@
+import { node, type BaseProps, type TreeNode } from '../tree'
+import { REKA_ELEMENTS, type BindingProp, type RekaNamespaces } from './index'
+
+/** Props of a Reka element: a frame's, plus the behaviour a root binds and a group item's component. */
+export interface RekaProps extends BaseProps {
+ modelValue?: BindingProp
+ open?: BindingProp
+ disabled?: BindingProp
+ filled?: BindingProp
+ /** The variant property whose values draw rest, hover, pressed, focus, and disabled. */
+ states?: string
+ min?: number
+ max?: number
+ step?: number
+ defaultValue?: number
+ /** For a group's item: the component or set it is an instance of. */
+ of?: string
+}
+
+type Child = TreeNode | string
+export type RekaElement = (props?: RekaProps, ...children: Child[]) => TreeNode
+
+/** One Reka namespace as element functions, such as `Switch.Root` and `Switch.Thumb`. */
+function namespace<N extends keyof RekaNamespaces>(name: N) {
+ const element =
+ (part: string): RekaElement =>
+ (props = {}, ...children) =>
+ node(`${name}.${part}`, children.length > 0 ? { ...props, children } : props)
+ return Object.fromEntries(
+ Object.keys(REKA_ELEMENTS[name]).map((part) => [part, element(part)])
+ ) as { [P in keyof RekaNamespaces[N]]: RekaElement }
+}
+
+export const Button = namespace('Button')
+export const Toggle = namespace('Toggle')
+export const Switch = namespace('Switch')
+export const Checkbox = namespace('Checkbox')
+export const RadioGroup = namespace('RadioGroup')
+export const ToggleGroup = namespace('ToggleGroup')
+export const Slider = namespace('Slider')
+export const Progress = namespace('Progress')
+export const Tabs = namespace('Tabs')
+export const Collapsible = namespace('Collapsible')
+export const Accordion = namespace('Accordion')
+export const NumberField = namespace('NumberField')
+export const TextField = namespace('TextField')
+export const Textarea = namespace('Textarea')
diff --git a/packages/design-jsx/src/behaviours/index.ts b/packages/design-jsx/src/behaviours/index.ts
index 5e9e64a37..3dedb61ec 100644
--- a/packages/design-jsx/src/behaviours/index.ts
+++ b/packages/design-jsx/src/behaviours/index.ts
@@ -34,7 +34,7 @@ const input = (valueId: string): RekaRole => ({ role: 'input', valueId })
* `Item` is the component of its items when written on its own, and an item when it names one
* with `of`, as an `Instance` does.
*/
-export const REKA_ELEMENTS: Readonly<Record<string, Readonly<Record<string, RekaRole>>>> = {
+const REKA_PARTS = {
Button: { Root: root('button') },
Toggle: { Root: root('toggle') },
Switch: { Root: root('switch'), Thumb: part('thumb') },
@@ -70,7 +70,14 @@ export const REKA_ELEMENTS: Readonly<Record<string, Readonly<Record<string, Reka
},
TextField: { Root: root('textField'), Input: input('value') },
Textarea: { Root: root('textarea'), Input: input('value') }
-}
+} as const satisfies Readonly<Record<string, Readonly<Record<string, RekaRole>>>>
+
+/** Each Reka namespace and its parts, as typed elements are built from them. */
+export type RekaNamespaces = typeof REKA_PARTS
+
+/** The same elements, looked up by any element name, as parsing and export do. */
+export const REKA_ELEMENTS: Readonly<Record<string, Readonly<Record<string, RekaRole>>>> =
+ REKA_PARTS
/** The container a repeated part goes in when written directly under its root. */
const CONTAINER_NAMES: Record<string, string> = { list: 'List', panels: 'Panels', items: 'Items' }
@@ -196,7 +203,8 @@ export const BEHAVIOUR_PROPS = [
'defaultValue'
] as const
-type BindingProp = string | { property: string; on?: string; off?: string }
+/** A value bound to a component property by name; a variant property may name its on and off. */
+export type BindingProp = string | { property: string; on?: string; off?: string }
function isBinding(value: unknown): value is BindingProp {
return (
diff --git a/packages/design-jsx/src/index.ts b/packages/design-jsx/src/index.ts
index 6f1d80957..2f901b824 100644
--- a/packages/design-jsx/src/index.ts
+++ b/packages/design-jsx/src/index.ts
@@ -17,6 +17,24 @@ export {
Page,
INTRINSIC_ELEMENTS
} from './components'
+export {
+ Accordion,
+ Button,
+ Checkbox,
+ Collapsible,
+ NumberField,
+ Progress,
+ RadioGroup,
+ Slider,
+ Switch,
+ Tabs,
+ Textarea,
+ TextField,
+ Toggle,
+ ToggleGroup,
+ type RekaElement,
+ type RekaProps
+} from './behaviours/elements'
export {
type TreeNode,
diff --git a/packages/design-jsx/tests/behaviours/elements.test.tsx b/packages/design-jsx/tests/behaviours/elements.test.tsx
new file mode 100644
index 000000000..87c8aa911
--- /dev/null
+++ b/packages/design-jsx/tests/behaviours/elements.test.tsx
@@ -0,0 +1,34 @@
+/** @jsxImportSource @open-pencil/design-jsx */
+import { describe, expect, test } from 'bun:test'
+
+import { REKA_ELEMENTS } from '#design-jsx/behaviours'
+import * as designJSX from '#design-jsx/index'
+import { Component, Switch, Text } from '#design-jsx/index'
+import { node } from '#design-jsx/tree'
+
+describe('Reka elements in TSX', () => {
+ test('build the same nodes the JSX string renderer reads', () => {
+ const tree = (
+ <Switch.Root name="Switch" modelValue="State">
+ <Component name="State=Off">
+ <Switch.Thumb w={20} />
+ </Component>
+ </Switch.Root>
+ )
+ expect(tree).toEqual(
+ node('Switch.Root', {
+ name: 'Switch',
+ modelValue: 'State',
+ children: [Component({ name: 'State=Off', children: [node('Switch.Thumb', { w: 20 })] })]
+ })
+ )
+ expect(<Switch.Thumb />).toEqual(node('Switch.Thumb', {}))
+ expect(Switch.Root({ name: 'Switch' }, Text({ children: 'On' })).children).toHaveLength(1)
+ })
+
+ test('every Reka namespace and part is exported', () => {
+ const api: Record<string, unknown> = designJSX
+ for (const [namespace, parts] of Object.entries(REKA_ELEMENTS))
+ expect(Object.keys(api[namespace] ?? {})).toEqual(Object.keys(parts))
+ })
+})
diff --git a/packages/dom-css/src/export/projection.ts b/packages/dom-css/src/export/projection.ts
index 6519772e3..f9a66ae59 100644
--- a/packages/dom-css/src/export/projection.ts
+++ b/packages/dom-css/src/export/projection.ts
@@ -37,15 +37,14 @@ function justifyContentToCSS(value: SceneNode['primaryAxisAlign']): string | und
return undefined
}
-function alignItemsToCSS(value: SceneNode['counterAxisAlign']): string | undefined {
- if (value === 'CENTER') return 'center'
- if (value === 'MAX') return 'flex-end'
- if (value === 'STRETCH') return 'stretch'
- if (value === 'BASELINE') return 'baseline'
- return undefined
-}
-
-function alignSelfToCSS(value: SceneNode['layoutAlignSelf']): string | undefined {
+/**
+ * Cross-axis alignment of a container's children, or of one child. Auto layout starts children
+ * at the start while flexbox stretches them, so start is written out: a child that hugs its
+ * content keeps its own size.
+ */
+function alignToCSS(
+ value: SceneNode['counterAxisAlign'] | SceneNode['layoutAlignSelf']
+): string | undefined {
if (value === 'MIN') return 'flex-start'
if (value === 'CENTER') return 'center'
if (value === 'MAX') return 'flex-end'
@@ -255,7 +254,7 @@ function styleFromSceneNode(
if (node.opacity < 1) style.opacity = css('opacity', String(node.opacity))
addCornerRadii(style, node, css)
if (node.clipsContent) style.overflow = 'hidden'
- const alignSelf = alignSelfToCSS(node.layoutAlignSelf)
+ const alignSelf = alignToCSS(node.layoutAlignSelf)
if (alignSelf) style['align-self'] = alignSelf
addLayoutChild(style, node, parent)
@@ -269,7 +268,7 @@ function styleFromSceneNode(
// Row is the flexbox default.
if (node.layoutMode === 'VERTICAL') style['flex-direction'] = 'column'
const justifyContent = justifyContentToCSS(node.primaryAxisAlign)
- const alignItems = alignItemsToCSS(node.counterAxisAlign)
+ const alignItems = alignToCSS(node.counterAxisAlign)
if (justifyContent) style['justify-content'] = justifyContent
if (alignItems) style['align-items'] = alignItems
if (node.layoutWrap === 'WRAP') style['flex-wrap'] = 'wrap'
diff --git a/packages/dom-css/tests/export/projection.test.ts b/packages/dom-css/tests/export/projection.test.ts
index f026e92f5..7c5b45b7a 100644
--- a/packages/dom-css/tests/export/projection.test.ts
+++ b/packages/dom-css/tests/export/projection.test.ts
@@ -38,6 +38,15 @@ describe('DOM projection', () => {
expect(root.inlineStyle?.position).toBeUndefined()
expect(element(root.children[0]).inlineStyle?.position).toBeUndefined()
})
+
+ test('children start at the cross-axis start, as auto layout places them, not stretched', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const column = graph.createNode('FRAME', page.id, { name: 'Column', layoutMode: 'VERTICAL' })
+
+ const root = element(sceneNodeToDesignDocument(graph, column.id).children[0])
+ expect(root.inlineStyle?.['align-items']).toBe('flex-start')
+ })
})
describe('DOM projection sizes', () => {
diff --git a/packages/fig/src/node-change/derived-text/build.ts b/packages/fig/src/node-change/derived-text/build.ts
index 3a385dc9d..6261742ac 100644
--- a/packages/fig/src/node-change/derived-text/build.ts
+++ b/packages/fig/src/node-change/derived-text/build.ts
@@ -149,6 +149,16 @@ function savedGlyphLayout(
return { baselines, logicalIndexToCharacterOffsetMap: offsets }
}
+/**
+ * A kept glyph's advance in ems: its own when it has one, else the distance to the next glyph
+ * on its line, else nothing.
+ */
+function savedAdvance(glyph: DerivedTextGlyph, next: DerivedTextGlyph | undefined): number {
+ if (glyph.fontSize <= 0) return 0
+ if (glyph.advance !== undefined) return (glyph.advance * (glyph.scaleX ?? 1)) / glyph.fontSize
+ return next ? Math.max(next.x - glyph.x, 0) / glyph.fontSize : 0
+}
+
function savedGlyphRecords(
glyphs: DerivedTextGlyph[],
context: DerivedTextBuildContext
@@ -172,7 +182,7 @@ function savedGlyphRecords(
position: { x: glyph.x, y: glyph.y },
fontSize: glyph.fontSize,
firstCharacter: glyph.firstCharacter ?? index,
- advance: sameLine && glyph.fontSize > 0 ? Math.max(next.x - glyph.x, 0) / glyph.fontSize : 0,
+ advance: savedAdvance(glyph, sameLine ? next : undefined),
// Preserve path-text radians; hardcoding 0 used to flatten circular text on re-export.
rotation: glyph.rotation ?? 0
}
diff --git a/packages/fig/src/node-change/derived-text/glyphs.ts b/packages/fig/src/node-change/derived-text/glyphs.ts
index 626dad749..1a7562029 100644
--- a/packages/fig/src/node-change/derived-text/glyphs.ts
+++ b/packages/fig/src/node-change/derived-text/glyphs.ts
@@ -37,13 +37,16 @@ export function convertFigmaDerivedTextGlyphs(
const commandsBlob = glyph.commandsBlob === undefined ? undefined : blobs[glyph.commandsBlob]
// Layout written without outlines, or with some missing, would draw text with gaps.
if (!commandsBlob) return []
+ // Kiwi stores the advance in ems; files that omit it leave decorations to the layer width.
+ const advance = glyph.advance * glyph.fontSize
glyphs.push({
commandsBlob,
x: glyph.position.x,
y: glyph.position.y,
fontSize: glyph.fontSize,
firstCharacter: glyph.firstCharacter,
- rotation: glyph.rotation
+ rotation: glyph.rotation,
+ advance: Number.isFinite(advance) ? advance : undefined
})
}
return glyphs
diff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.ts
index b4cb80403..98e43ccd5 100644
--- a/packages/fig/src/node-change/export/node.ts
+++ b/packages/fig/src/node-change/export/node.ts
@@ -918,6 +918,8 @@ export function sceneNodeToKiwiWithContext(
transform: exportNodeTransform(context, node)
}
if (node.sharedStyleType) nc.styleType = node.sharedStyleType
+ // Readers take a missing blend mode as pass-through, the layer default.
+ if (node.blendMode !== 'PASS_THROUGH') nc.blendMode = node.blendMode
if (node.type === 'GROUP') {
nc.resizeToFit = true
}
diff --git a/packages/fig/tests/node-change/derived-text.test.ts b/packages/fig/tests/node-change/derived-text.test.ts
index cb675aaa0..215cca191 100644
--- a/packages/fig/tests/node-change/derived-text.test.ts
+++ b/packages/fig/tests/node-change/derived-text.test.ts
@@ -182,6 +182,25 @@ function earlierOpenPencilData(characters: string, lineHeight: number): DerivedT
describe('derived text reader', () => {
const blobs = [new Uint8Array([0])]
+ test("keeps a glyph's own advance through reading and saving", () => {
+ const characters = 'Table item'
+ const data = earlierOpenPencilData(characters, 16)
+ // One offset per character, as Figma writes, so the reader keeps the glyphs.
+ data.logicalIndexToCharacterOffsetMap = data.logicalIndexToCharacterOffsetMap?.slice(0, -1)
+ for (const glyph of data.glyphs ?? []) glyph.advance = 0.5
+
+ const glyphs = convertFigmaDerivedTextGlyphs(data, blobs, characters)
+ expect(glyphs.at(-1)?.advance).toBe(6.5)
+ const saved = expectDefined(
+ buildNodeDerivedTextData(
+ textNode({ text: characters, derivedTextGlyphs: glyphs }),
+ context(null)
+ ),
+ 'derived text'
+ )
+ expect(saved.glyphs?.at(-1)?.advance).toBe(0.5)
+ })
+
test('drops one-line glyphs an earlier OpenPencil wrote without shaping (#914)', () => {
const characters = 'A sentence long enough that it has to wrap onto a second line.'
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index e30aa5199..2ff8eb39f 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -340,6 +340,11 @@ export interface DerivedTextGlyph {
fontSize: number
/** Figma Glyph.rotation — radians, not degrees. Zero for axis-aligned text. */
rotation?: number
+ /**
+ * Horizontal advance in pixels at `fontSize`, before `scaleX`, when the shaping source gave
+ * one; where the glyph ends, so decorations stop at the text rather than the layer's edge.
+ */
+ advance?: number
/**
* Accumulated non-uniform resize scale (default 1). Paint order is
* translate → scale(scaleX,Y) → rotate → scale(fontSize,-fontSize) so
diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.json
index aeff17cad..84ef1dab2 100644
--- a/packages/vue/src/i18n/locales/de/panels.json
+++ b/packages/vue/src/i18n/locales/de/panels.json
@@ -93,7 +93,6 @@
"missingStyle": "Fehlender Stil ({id})",
"layersCount": "{count} Ebenen",
"goToMainComponent": "Zur Hauptkomponente",
- "detachInstance": "Instanz lösen",
"solid": "Vollton",
"linearGradient": "Linear",
"radialGradient": "Radial",
diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.json
index a3dd34248..4ef6d5d81 100644
--- a/packages/vue/src/i18n/locales/es/panels.json
+++ b/packages/vue/src/i18n/locales/es/panels.json
@@ -106,7 +106,6 @@
"missingStyle": "Estilo no disponible ({id})",
"layersCount": "{count} capas",
"goToMainComponent": "Ir al componente principal",
- "detachInstance": "Separar instancia",
"solid": "Sólido",
"linearGradient": "Lineal",
"radialGradient": "Radial",
diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.json
index cfd3c75dc..7c095639e 100644
--- a/packages/vue/src/i18n/locales/fr/panels.json
+++ b/packages/vue/src/i18n/locales/fr/panels.json
@@ -93,7 +93,6 @@
"missingStyle": "Style manquant ({id})",
"layersCount": "{count} calques",
"goToMainComponent": "Aller au composant principal",
- "detachInstance": "Détacher l'instance",
"solid": "Uni",
"linearGradient": "Linéaire",
"radialGradient": "Radial",
diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.json
index c05820459..1a3d2deed 100644
--- a/packages/vue/src/i18n/locales/it/panels.json
+++ b/packages/vue/src/i18n/locales/it/panels.json
@@ -93,7 +93,6 @@
"missingStyle": "Stile mancante ({id})",
"layersCount": "{count} livelli",
"goToMainComponent": "Vai al componente principale",
- "detachInstance": "Scollega istanza",
"solid": "Pieno",
"linearGradient": "Lineare",
"radialGradient": "Radiale",
diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.json
index c13937f86..6b407655f 100644
--- a/packages/vue/src/i18n/locales/ja/panels.json
+++ b/packages/vue/src/i18n/locales/ja/panels.json
@@ -106,7 +106,6 @@
"missingStyle": "不明なスタイル ({id})",
"layersCount": "{count} 個のレイヤー",
"goToMainComponent": "メインコンポーネントに移動",
- "detachInstance": "インスタンスの切り離し",
"solid": "ソリッド (単色)",
"linearGradient": "線形グラデーション",
"radialGradient": "放射状グラデーション",
diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.json
index 0c97e0d20..72a8c356c 100644
--- a/packages/vue/src/i18n/locales/pl/panels.json
+++ b/packages/vue/src/i18n/locales/pl/panels.json
@@ -93,7 +93,6 @@
"missingStyle": "Brakujący styl ({id})",
"layersCount": "{count} warstw",
"goToMainComponent": "Przejdź do głównego komponentu",
- "detachInstance": "Odłącz instancję",
"solid": "Jednolity",
"linearGradient": "Liniowy",
"radialGradient": "Promieniowy",
diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.json
index 9efb31161..10535a0d4 100644
--- a/packages/vue/src/i18n/locales/ru/panels.json
+++ b/packages/vue/src/i18n/locales/ru/panels.json
@@ -106,7 +106,6 @@
"missingStyle": "Недоступный стиль ({id})",
"layersCount": "{count} слоёв",
"goToMainComponent": "Перейти к главному компоненту",
- "detachInstance": "Отвязать экземпляр",
"solid": "Сплошной",
"linearGradient": "Линейный",
"radialGradient": "Радиальный",
diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.json
index 1be87fd49..fd71dbc88 100644
--- a/packages/vue/src/i18n/locales/zh-cn/panels.json
+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json
@@ -106,7 +106,6 @@
"missingStyle": "缺失样式 ({id})",
"layersCount": "{count} 个图层",
"goToMainComponent": "转到主组件",
- "detachInstance": "分离实例",
"solid": "纯色",
"linearGradient": "线性",
"radialGradient": "径向",
diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.ts
index 7ea983e4f..cd1e9565f 100644
--- a/packages/vue/src/i18n/messages/panels.ts
+++ b/packages/vue/src/i18n/messages/panels.ts
@@ -396,7 +396,6 @@ export const panelMessageDefaults = {
missingStyle: params('Missing style ({id})'),
layersCount: params('{count} layers'),
goToMainComponent: 'Go to main component',
- detachInstance: 'Detach instance',
gap: 'Gap',
diff --git a/src/app/demo/document.ts b/src/app/demo/document.ts
index 386b3257c..cde6785f1 100644
--- a/src/app/demo/document.ts
+++ b/src/app/demo/document.ts
@@ -1,189 +1,32 @@
-import { computeAllLayouts } from '@open-pencil/core/layout'
-import type { SceneGraph } from '@open-pencil/scene-graph'
-
-import { yieldToUI } from '@/app/document/io/browser'
import type { EditorStore } from '@/app/editor/session'
-import { createAnnouncementSection } from './announcement/section'
-import { loadDemoFonts } from './fonts'
-import { createPaintSection } from './paint/section'
-import { createComponentsSection } from './sections/components'
-import { createDemoVariables } from './sections/variables'
-import { createTypographySection } from './typography/section'
import { fitDemoPagesOnFirstVisit } from './viewport'
-const PAGE_ORIGIN = 60
-const PAGE_GAP = 64
-
-type DemoPreparation = ReturnType<EditorStore['preparationController']['begin']>
-
-interface DemoBuildState {
- initialPageId: string
- initialPageName: string | null
- preexistingCollections: ReadonlySet<string>
- createdRootIds: string[]
- createdPageIds: string[]
-}
-
-interface DemoBuild {
- graph: SceneGraph
- state: DemoBuildState
- /** Resolves false when the build was abandoned before it finished. */
- run: () => Promise<boolean>
-}
+/** Built from `tools/generate/demo` before the app is served or bundled. */
+const DEMO_URL = '/demo.fig'
+const DEMO_FILE_NAME = 'Demo.fig'
/**
- * A superseded or failed build must not leave a half-built document behind, so the pages,
- * sections, and variables it added are removed again. Guarded by graph identity because node
- * and page IDs are only unique within one graph.
+ * Opens the bundled demo document like any `.fig` file: decoded off the main thread, behind
+ * the canvas loader, with pages materialized as they are visited. Each page is fitted to the
+ * viewport on its first visit.
*/
-function rollbackBuild(store: EditorStore, graph: SceneGraph, state: DemoBuildState): void {
- if (store.graph !== graph) return
- for (const rootId of state.createdRootIds) {
- if (graph.getNode(rootId)) graph.deleteNode(rootId)
- }
- for (const pageId of state.createdPageIds) {
- if (graph.getNode(pageId)) store.deletePage(pageId)
- }
- for (const collectionId of Array.from(graph.variableCollections.keys())) {
- if (!state.preexistingCollections.has(collectionId)) graph.removeCollection(collectionId)
- }
- if (state.initialPageName !== null) {
- graph.updateNode(state.initialPageId, { name: state.initialPageName })
- }
- store.clearSelection()
-}
-
-function reportDemoFailure(preparation: DemoPreparation, error: unknown): void {
- if (preparation.signal.aborted) return
- preparation.fail({
- code: 'layout-failed',
- message: error instanceof Error ? error.message : String(error),
- retryable: true
- })
- console.warn('[Demo] Failed to prepare the demo document:', error)
-}
-
-/**
- * Builds the demo document while reporting the same preparation phases as a document open, so
- * the canvas overlay and tab indicator cover generation instead of an empty canvas.
- */
-function createDemoBuild(store: EditorStore, preparation: DemoPreparation): DemoBuild {
- const graph = store.graph
- const state: DemoBuildState = {
- initialPageId: store.state.currentPageId,
- initialPageName: graph.getNode(store.state.currentPageId)?.name ?? null,
- preexistingCollections: new Set(graph.variableCollections.keys()),
- createdRootIds: [],
- createdPageIds: []
- }
- const abandoned = () => store.graph !== graph || preparation.signal.aborted
- const step = (completed: number) =>
- preparation.update({ phase: 'materializing', completed, total: 4, unit: 'pages' })
-
- async function run(): Promise<boolean> {
- await store.canvasReady
- // A file opened while the canvas was loading must not receive demo content.
- if (
- abandoned() ||
- store.state.currentPageId !== state.initialPageId ||
- graph.getPages().length !== 1 ||
- graph.getChildren(state.initialPageId).length > 0
- )
- return false
-
- step(0)
- await yieldToUI()
- await loadDemoFonts()
-
- graph.updateNode(state.initialPageId, { name: '01 · Components & variables' })
- const typography = graph.addPage('02 · Typography')
- const paint = graph.addPage('03 · Paint & effects')
- state.createdPageIds.push(typography.id, paint.id)
-
- // Build page 01 while it is still the current page, so shape creation inside
- // the section helpers lands here rather than on a leftover empty page.
- const announcement = await createAnnouncementSection(graph, state.initialPageId)
- state.createdRootIds.push(announcement.rootId)
- graph.updateNode(announcement.rootId, { x: PAGE_ORIGIN, y: PAGE_ORIGIN })
- step(1)
- if (abandoned()) return false
-
- computeAllLayouts(graph, state.initialPageId)
- const components = await createComponentsSection(graph, state.initialPageId, {
- x: PAGE_ORIGIN,
- y: PAGE_ORIGIN + (graph.getNode(announcement.rootId)?.height ?? 0) + PAGE_GAP
- })
- state.createdRootIds.push(components.rootId)
- createDemoVariables(store)
- step(2)
- if (abandoned()) return false
-
- await createTypographySection(graph, typography.id)
- step(3)
- if (abandoned()) return false
-
- await createPaintSection(graph, paint.id)
- step(4)
- if (abandoned()) return false
-
- const pages = graph.getPages()
- preparation.update({
- phase: 'resolving-fonts',
- completed: 0,
- total: pages.length,
- unit: 'pages'
- })
- for (const [index, page] of pages.entries()) {
- await store.loadFontsForNodes(page.childIds)
- if (abandoned()) return false
- preparation.update({
- phase: 'resolving-fonts',
- completed: index + 1,
- total: pages.length,
- unit: 'pages'
- })
- }
-
- preparation.update({ phase: 'layout' })
- await yieldToUI()
- for (const page of pages) computeAllLayouts(graph, page.id)
- if (abandoned()) return false
-
- store.undo.clear()
- fitDemoPagesOnFirstVisit(
- store,
- graph.getPages().map((page) => page.id)
- )
- await store.switchPage(state.initialPageId, { preparation })
- if (abandoned()) return false
-
- store.clearSelection()
- store.zoomToFit()
- preparation.update({ phase: 'preparing-render' })
- store.requestRender()
- await store.preparationController.waitForPresentation(preparation.id, store.state.sceneVersion)
- return true
- }
-
- return { graph, state, run }
-}
-
-export async function createDemoShapes(store: EditorStore) {
- const preparation = store.preparationController.begin({
- kind: 'demo-load',
- phase: 'materializing'
- })
- const build = createDemoBuild(store, preparation)
- try {
- if (await build.run()) {
- preparation.complete()
- return
- }
- } catch (error) {
- reportDemoFailure(preparation, error)
- }
- rollbackBuild(store, build.graph, build.state)
- // A failed or superseded handle has already cleared itself, so this is a no-op then.
- preparation.cancel('superseded')
+export async function openDemoDocument(store: EditorStore): Promise<void> {
+ const blank = store.graph
+ const response = await fetch(DEMO_URL)
+ if (!response.ok) throw new Error(`The demo document is unavailable (${response.status})`)
+ const file = new File([await response.arrayBuffer()], DEMO_FILE_NAME)
+ // A file opened, or a layer drawn, while the demo was loading keeps the tab; the demo never
+ // replaces them.
+ const untouched =
+ store.graph === blank &&
+ store.state.preparation === null &&
+ store.graph.getChildren(store.state.currentPageId).length === 0
+ if (!untouched) return
+ await store.openFigFile(file)
+ const [, ...later] = store.graph.getPages()
+ fitDemoPagesOnFirstVisit(
+ store,
+ later.map((page) => page.id)
+ )
}
diff --git a/src/app/demo/fonts.ts b/src/app/demo/fonts.ts
deleted file mode 100644
index 13e030c3d..000000000
--- a/src/app/demo/fonts.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { loadFont } from '@/app/editor/fonts'
-
-export async function loadDemoFonts() {
- await Promise.all([
- loadFont('Inter', 'Regular'),
- loadFont('Inter', 'Medium'),
- loadFont('Inter', 'SemiBold'),
- loadFont('Inter', 'Bold')
- ])
-}
diff --git a/src/app/demo/helpers.ts b/src/app/demo/helpers.ts
deleted file mode 100644
index a9cf14d96..000000000
--- a/src/app/demo/helpers.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import type { EditorStore } from '@/app/editor/session'
-
-export function makeComponent(store: EditorStore, ids: string[]): string {
- store.select(ids)
- store.createComponentFromSelection()
- return [...store.state.selectedIds][0]
-}
diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vue
index 3f95f42a8..0b6ba3583 100644
--- a/src/components/DesignPanel.vue
+++ b/src/components/DesignPanel.vue
@@ -7,6 +7,7 @@ import { useEditorStore } from '@/app/editor/active-store'
import { COMPONENT_TYPES, nodeIcon } from '@/app/editor/icons'
import { openVariablesDialog } from '@/app/editor/tokens/dialog'
import { openLibraryReview, useLibraryService } from '@/app/libraries'
+import IconButton from '@/components/ui/button/IconButton.vue'
import Tip from '@/components/ui/overlay/Tip.vue'
import PanelHeader from '@/components/ui/panel/PanelHeader.vue'
@@ -127,30 +128,25 @@ const { panels } = useI18n()
@review="openSelectedInstanceReview"
/>
<SelectionActionsControl />
+ <template v-if="node.type === 'INSTANCE'">
+ <IconButton
+ :label="goToMainComponent.label"
+ data-test-id="instance-go-to-main"
+ @click="goToMainComponent.run()"
+ >
+ <icon-lucide-crosshair class="size-3.5" />
+ </IconButton>
+ <IconButton
+ :label="detachInstance.label"
+ data-test-id="instance-detach"
+ @click="detachInstance.run()"
+ >
+ <icon-lucide-unlink class="size-3.5" />
+ </IconButton>
+ </template>
</template>
</PanelHeader>
- <!-- Component actions -->
- <div
- v-if="node.type === 'INSTANCE'"
- class="flex flex-col gap-1 border-b border-border px-3 py-2"
- >
- <button
- type="button"
- class="rounded bg-component/10 px-2 py-1 text-left text-[11px] text-component hover:bg-component/20"
- @click="goToMainComponent.run()"
- >
- {{ panels.goToMainComponent }}
- </button>
- <button
- type="button"
- class="rounded px-2 py-1 text-left text-[11px] text-muted hover:bg-hover"
- @click="detachInstance.run()"
- >
- {{ panels.detachInstance }}
- </button>
- </div>
-
<ComponentPropertiesSection v-if="node.type === 'INSTANCE'" />
<VariantAuthoringSection
v-if="
diff --git a/src/components/properties/component-properties/behaviour/Behaviour.stories.ts b/src/components/properties/component-properties/behaviour/Behaviour.stories.ts
index fa87f6ff6..b19c88051 100644
--- a/src/components/properties/component-properties/behaviour/Behaviour.stories.ts
+++ b/src/components/properties/component-properties/behaviour/Behaviour.stories.ts
@@ -47,7 +47,7 @@ export const MapState: Story = {
export const CreateMissing: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement)
- await userEvent.click(canvas.getByRole('button', { name: 'Still needed: Text.' }))
+ await expect(canvas.getByRole('status')).toHaveTextContent('Still needed: Text.')
await userEvent.click(canvas.getByRole('button', { name: 'Add text layer' }))
await waitFor(() => expect(canvas.getByText('create text Text for value')).toBeVisible())
}
diff --git a/src/components/properties/component-properties/behaviour/BehaviourBindingField.vue b/src/components/properties/component-properties/behaviour/BehaviourBindingField.vue
index 2ebcede47..a642a8557 100644
--- a/src/components/properties/component-properties/behaviour/BehaviourBindingField.vue
+++ b/src/components/properties/component-properties/behaviour/BehaviourBindingField.vue
@@ -69,7 +69,7 @@ const items = computed(() => options.map((option) => ({ value: option.id, label:
<button
v-else
type="button"
- class="flex h-6 w-full items-center gap-1.5 rounded border border-dashed border-border px-2 text-xs text-muted outline-none hover:border-accent hover:text-surface focus-visible:border-panel-focus"
+ class="flex h-6 w-full items-center gap-1.5 rounded border border-dashed border-border px-2 text-xs text-muted outline-none hover:border-accent hover:text-surface focus-visible:border-panel-focus data-[missing]:border-issue-warning/60"
:data-missing="missing || undefined"
v-bind="$attrs"
@click="emit('create')"
diff --git a/src/components/properties/component-properties/behaviour/BehaviourRow.vue b/src/components/properties/component-properties/behaviour/BehaviourRow.vue
index e70f0ab20..8bb277959 100644
--- a/src/components/properties/component-properties/behaviour/BehaviourRow.vue
+++ b/src/components/properties/component-properties/behaviour/BehaviourRow.vue
@@ -33,6 +33,11 @@ const labels = useBehaviourLabels()
const part = computed(() => ('part' in row ? row.part : null))
const value = computed(() => ('value' in row ? row.value : null))
+/** A row the control requires that is still unbound; its label shows it. */
+const missing = computed(() => {
+ const control = part.value ?? value.value
+ return !!control && 'required' in control && control.required && !control.propertyId
+})
const number = computed(() => (value.value?.type === 'number' ? value.value : null))
const id = computed(() => part.value?.id ?? value.value?.id ?? '')
const label = computed(() =>
@@ -86,7 +91,12 @@ function numberLabel(field: NumberSetting) {
</script>
<template>
- <PanelFieldGroup :label="label" :data-row="id">
+ <PanelFieldGroup
+ :label="label"
+ :data-row="id"
+ :data-missing="missing || undefined"
+ :ui="{ root: 'group', label: 'group-data-[missing]:text-issue-warning' }"
+ >
<BehaviourBindingField
v-if="part"
:label="label"
diff --git a/src/components/properties/component-properties/behaviour/BehaviourSection.vue b/src/components/properties/component-properties/behaviour/BehaviourSection.vue
index 600d11b40..e72e9886d 100644
--- a/src/components/properties/component-properties/behaviour/BehaviourSection.vue
+++ b/src/components/properties/component-properties/behaviour/BehaviourSection.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { computed, ref, useTemplateRef } from 'vue'
+import { computed, ref } from 'vue'
import type { BehaviourKind, InteractionState } from '@open-pencil/scene-graph'
import { useI18n } from '@open-pencil/vue'
@@ -107,15 +107,6 @@ const nextStep = computed(() => {
const list = new Intl.ListFormat(locale.value, { type: 'conjunction' }).format(names)
return panels.value.behaviourNextStep({ names: list })
})
-
-const root = useTemplateRef<HTMLElement>('root')
-/** Bring the first missing row into view and focus its control. */
-function showMissing() {
- const [missing] = behaviour?.missing ?? []
- const row = missing ? root.value?.querySelector<HTMLElement>(`[data-row="${missing}"]`) : null
- row?.scrollIntoView({ block: 'nearest' })
- row?.querySelector<HTMLElement>('button, input')?.focus()
-}
</script>
<template>
@@ -127,7 +118,7 @@ function showMissing() {
</IconButton>
</template>
- <div v-if="behaviour && kind" ref="root" class="flex flex-col gap-2" data-property="behaviour">
+ <div v-if="behaviour && kind" class="flex flex-col gap-2" data-property="behaviour">
<div class="flex items-center gap-1.5 text-xs text-surface">
<icon-lucide-mouse-pointer-click class="size-3.5 shrink-0 text-component" />
<span class="min-w-0 flex-1 truncate font-medium">{{ kind.label }}</span>
@@ -140,16 +131,15 @@ function showMissing() {
</span>
</div>
- <button
+ <p
v-if="behaviour.missing.length"
- type="button"
- class="flex items-start gap-1.5 rounded bg-issue-warning/10 px-1.5 py-1 text-left text-[11px] leading-4 text-issue-warning outline-none hover:bg-issue-warning/20 focus-visible:bg-issue-warning/20"
+ role="status"
+ class="flex items-start gap-1.5 rounded bg-issue-warning/10 px-1.5 py-1 text-[11px] leading-4 text-issue-warning"
data-property="behaviour-missing"
- @click="showMissing"
>
<SeverityIcon severity="warning" class="mt-0.5 shrink-0" />
{{ nextStep }}
- </button>
+ </p>
<BehaviourRow
v-for="row in mainRows"
diff --git a/src/views/WorkspaceView.vue b/src/views/WorkspaceView.vue
index 3c13173d8..a18ad272b 100644
--- a/src/views/WorkspaceView.vue
+++ b/src/views/WorkspaceView.vue
@@ -15,7 +15,7 @@ import { useJoinRoom } from '@/app/collab/join'
import { bindDesktopRoomLinks } from '@/app/collab/room/links'
import { syncRoomRoute } from '@/app/collab/route'
import { COLLAB_KEY, useCollab } from '@/app/collab/use'
-import { createDemoShapes } from '@/app/demo/document'
+import { openDemoDocument } from '@/app/demo/document'
import type { PendingOpenFile } from '@/app/document/io/pending-open'
import { openPendingFiles } from '@/app/document/io/pending-open'
import { openWebLinkFromLocation, withoutWebLinkParams } from '@/app/document/io/web-link'
@@ -72,7 +72,15 @@ function openFirstTab(): Tab {
{
const firstTab = activeTab.value ?? openFirstTab()
if (createdInitialTab && route.meta.demo && !appRuntimeConfig.test) {
- void createDemoShapes(firstTab.store)
+ openDemoDocument(firstTab.store).catch((error: unknown) => {
+ console.error('[Demo] Could not open the demo document:', error)
+ toast.error(
+ notificationMessages.get().openFileFailed({
+ name: 'Demo',
+ error: error instanceof Error ? error.message : String(error)
+ })
+ )
+ })
}
}
diff --git a/tests/app/demo/document.test.ts b/tests/app/demo/document.test.ts
new file mode 100644
index 000000000..af45e5904
--- /dev/null
+++ b/tests/app/demo/document.test.ts
@@ -0,0 +1,48 @@
+import { afterEach, describe, expect, spyOn, test } from 'bun:test'
+
+import { openDemoDocument } from '@/app/demo/document'
+import { createEditorStore } from '@/app/editor/session'
+
+const originalFetch = globalThis.fetch
+
+/** A fetch of the demo that runs `meanwhile` before the bytes arrive, as a user could. */
+function stubDemoFetch(meanwhile: () => void = () => undefined, ok = true) {
+ globalThis.fetch = Object.assign(
+ async () => {
+ meanwhile()
+ return new Response(new Uint8Array([1, 2, 3]), { status: ok ? 200 : 404 })
+ },
+ { preconnect: originalFetch.preconnect }
+ )
+}
+
+afterEach(() => {
+ globalThis.fetch = originalFetch
+})
+
+describe('opening the demo', () => {
+ test('opens the bundled file in a tab that is still blank', async () => {
+ const store = createEditorStore()
+ const open = spyOn(store, 'openFigFile').mockResolvedValue(undefined)
+ stubDemoFetch()
+ await openDemoDocument(store)
+ expect(open).toHaveBeenCalledTimes(1)
+ expect(open.mock.calls[0]?.[0].name).toBe('Demo.fig')
+ })
+
+ test('leaves a tab alone once something was drawn while the demo loaded', async () => {
+ const store = createEditorStore()
+ const open = spyOn(store, 'openFigFile').mockResolvedValue(undefined)
+ stubDemoFetch(() => {
+ store.graph.createNode('RECTANGLE', store.state.currentPageId, { width: 10, height: 10 })
+ })
+ await openDemoDocument(store)
+ expect(open).not.toHaveBeenCalled()
+ })
+
+ test('fails when the bundled file is missing', async () => {
+ const store = createEditorStore()
+ stubDemoFetch(undefined, false)
+ await expect(openDemoDocument(store)).rejects.toThrow('The demo document is unavailable (404)')
+ })
+})
diff --git a/tests/e2e/canvas/color-space.webkit.spec.ts b/tests/e2e/canvas/color-space.webkit.spec.ts
index be3195ad6..ab91e8795 100644
--- a/tests/e2e/canvas/color-space.webkit.spec.ts
+++ b/tests/e2e/canvas/color-space.webkit.spec.ts
@@ -19,8 +19,10 @@ test('P3 paint blends and masks survive pan, zoom, and surface resize', async ({
await canvas.waitForInit()
await focusPaintEffects(page)
// The notice appears once the document is Display P3, and dismissing it keeps the canvas
- // at a fixed offset for the snapshot.
+ // at a fixed offset for the snapshot. The canvas grows when it goes, so focus again to fit
+ // the paint page to the final size.
await dismissWideGamutBanner(page)
+ await focusPaintEffects(page)
await waitForSettledScene(page)
async function expectEffects() {
diff --git a/tests/e2e/canvas/color-space.webkit.spec.ts-snapshots/paint-effects-openpencil-darwin.png b/tests/e2e/canvas/color-space.webkit.spec.ts-snapshots/paint-effects-openpencil-darwin.png
index da24bae65..eb0f90f3d 100644
Binary files a/tests/e2e/canvas/color-space.webkit.spec.ts-snapshots/paint-effects-openpencil-darwin.png and b/tests/e2e/canvas/color-space.webkit.spec.ts-snapshots/paint-effects-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/component-set-border.spec.ts b/tests/e2e/canvas/component-set-border.spec.ts
new file mode 100644
index 000000000..60c6b23cd
--- /dev/null
+++ b/tests/e2e/canvas/component-set-border.spec.ts
@@ -0,0 +1,80 @@
+import { expect, test } from '#tests/e2e/fixtures'
+import { CanvasHelper } from '#tests/helpers/canvas'
+
+/**
+ * The thickest run of border-coloured pixels, in CSS pixels, across the top edge of the set
+ * `setId` near its right end, clear of the left-aligned labels, at `zoom`, drawn with every pass
+ * as a settled frame is, through the pictures cached at earlier zooms.
+ */
+function borderThickness({ setId, zoom }: { setId: string; zoom: number }) {
+ const store = window.openPencil?.getStore?.()
+ const renderer = store?.canvasRenderers.find((candidate) => candidate.tracksSceneSettlement)
+ const source = document.querySelector<HTMLCanvasElement>('[data-test-id="scene-canvas-element"]')
+ const set = store?.graph.getNode(setId)
+ if (!store || !renderer || !source || !set) throw new Error('Scene canvas unavailable')
+ const origin = store.graph.getAbsolutePosition(setId)
+ const sampleX = origin.x + set.width - 40
+ store.centerOn(sampleX, origin.y, zoom)
+ renderer.renderFromEditorState(
+ store.state,
+ store.graph,
+ store.textEditor,
+ renderer.viewportWidth,
+ renderer.viewportHeight,
+ false,
+ 'full',
+ false
+ )
+ const copy = document.createElement('canvas')
+ copy.width = source.width
+ copy.height = source.height
+ const context = copy.getContext('2d', { colorSpace: 'srgb' })
+ if (!context) throw new Error('sRGB canvas unavailable')
+ context.drawImage(source, 0, 0)
+ const dpr = devicePixelRatio
+ const top = Math.round((origin.y * store.state.zoom + store.state.panY) * dpr)
+ const band = 4 * dpr
+ const width = Math.round(40 * dpr)
+ const left = Math.round(copy.width / 2 - width / 2)
+ const { data } = context.getImageData(left, top - band, width, band * 2)
+ let thickest = 0
+ for (let x = 0; x < width; x++) {
+ let rows = 0
+ for (let y = 0; y < band * 2; y++) {
+ const i = (y * width + x) * 4
+ // The component colour, #9747ff: strongly blue, much less green.
+ if (data[i + 2] > 180 && data[i + 1] < 140) rows++
+ }
+ thickest = Math.max(thickest, rows)
+ }
+ store.requestRepaint()
+ return thickest / dpr
+}
+
+test('a component set border stays one pixel wide on screen at every zoom', async ({ page }) => {
+ await page.goto('/?test&no-rulers')
+ const canvas = new CanvasHelper(page)
+ await canvas.waitForInit()
+ const setId = await page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('Editor unavailable')
+ const set = store.graph.createNode('COMPONENT_SET', store.state.currentPageId, {
+ name: 'Button',
+ x: 200,
+ y: 200,
+ width: 240,
+ height: 120,
+ fills: []
+ })
+ store.graph.createNode('COMPONENT', set.id, { x: 20, y: 20, width: 80, height: 40 })
+ store.requestRender()
+ return set.id
+ })
+ await canvas.waitForRender()
+
+ for (const zoom of [1, 4]) {
+ const thickness = await page.evaluate(borderThickness, { setId, zoom })
+ expect(thickness, `border at ${zoom}x`).toBeGreaterThan(0)
+ expect(thickness, `border at ${zoom}x`).toBeLessThanOrEqual(2)
+ }
+})
diff --git a/tests/e2e/canvas/demo-workspace.spec.ts b/tests/e2e/canvas/demo-workspace.spec.ts
index d6ac593cd..d3483946c 100644
--- a/tests/e2e/canvas/demo-workspace.spec.ts
+++ b/tests/e2e/canvas/demo-workspace.spec.ts
@@ -1,7 +1,6 @@
import { expect, test, type Page } from '@playwright/test'
import { CanvasHelper } from '#tests/helpers/canvas'
-import type * as DemoStartup from '#tests/helpers/canvas/demo-startup'
import { waitForDemo } from '#tests/helpers/demo'
async function openDemo(page: Page) {
@@ -16,7 +15,8 @@ test.use({ viewport: { width: 1200, height: 1300 } })
for (const [name, snapshot] of [
['01 · Components & variables', 'demo-components-and-variables'],
['02 · Typography', 'demo-typography'],
- ['03 · Paint & effects', 'demo-paint']
+ ['03 · Paint & effects', 'demo-paint'],
+ ['04 · Controls', 'demo-controls']
] as const) {
test(`demo startup and page navigation: ${name}`, async ({ page }) => {
const canvas = await openDemo(page)
@@ -48,78 +48,27 @@ for (const [name, snapshot] of [
})
}
-test('demo generation reports canvas preparation until the document is ready', async ({ page }) => {
- const canvas = new CanvasHelper(page)
- await page.goto('/demo?no-chrome&no-rulers')
- const loader = page.getByTestId('canvas-loading')
- await expect(loader).toBeVisible()
- await expect(loader).toContainText(
- /Preparing layers|Resolving fonts|Computing layout|Preparing canvas/
- )
- await canvas.waitForInit()
- await waitForDemo(page)
- await expect(loader).toBeHidden()
-})
-
-test('an abandoned demo build leaves the document as it was', async ({ page }) => {
- const canvas = new CanvasHelper(page)
- await page.goto('/demo?no-chrome&no-rulers')
-
- const documentState = () =>
- page.evaluate(() => {
- const store = window.openPencil?.getStore?.()
- if (!store) throw new Error('OpenPencil store not initialized')
- const pages = store.graph.getPages()
- return {
- pages: pages.length,
- name: pages[0]?.name ?? null,
- children: pages[0] ? store.graph.getChildren(pages[0].id).length : -1,
- collections: store.graph.variableCollections.size,
- preparing: store.state.preparation !== null
- }
- })
-
- await page.waitForFunction(
- () => window.openPencil?.getStore?.()?.state.preparation?.kind === 'demo-load'
- )
- const pristine = await documentState()
- // Wait until generation has touched the document (it has added its extra pages), so the
- // interruption exercises the rollback rather than a build that never started mutating.
- await page.waitForFunction(() => {
- const store = window.openPencil?.getStore?.()
- return store?.state.preparation?.kind === 'demo-load' && store.graph.getPages().length > 1
- })
- await page.evaluate(async () => {
- const store = window.openPencil?.getStore?.()
- if (!store) throw new Error('OpenPencil store not initialized')
- await store.switchPage(store.graph.getPages()[0].id)
- })
-
- // The abandoned build must roll its pages, sections, and variables back.
- await expect
- .poll(async () => {
- const state = await documentState()
- return state.preparing ? null : state
- })
- .toEqual({ ...pristine, preparing: false })
- canvas.assertNoErrors()
-})
-
-test('demo completion preserves a document replaced during its final page switch', async ({
- page
-}) => {
- await page.goto('/?test&no-chrome&no-rulers')
- const canvas = new CanvasHelper(page)
- await canvas.waitForInit()
- const result = await page.evaluate(async () => {
+test('the demo opens as a document with every page', async ({ page }) => {
+ await openDemo(page)
+ const opened = await page.evaluate(() => {
const store = window.openPencil?.getStore?.()
if (!store) throw new Error('Editor unavailable')
- const fixtureURL = '/tests/helpers/canvas/demo-startup.ts'
- const { replaceGraphDuringDemoSwitch }: typeof DemoStartup = await import(fixtureURL)
- return replaceGraphDuringDemoSwitch(store)
+ return {
+ name: store.state.documentName,
+ pages: store.graph.getPages().map((item) => item.name),
+ preparing: store.state.preparation !== null
+ }
+ })
+ expect(opened).toEqual({
+ name: 'Demo',
+ pages: [
+ '01 · Components & variables',
+ '02 · Typography',
+ '03 · Paint & effects',
+ '04 · Controls'
+ ],
+ preparing: false
})
- expect(result.actual).toEqual(result.expected)
- canvas.assertNoErrors()
})
test('demo tokens and main-component edits survive undo', async ({ page }) => {
@@ -128,13 +77,20 @@ test('demo tokens and main-component edits survive undo', async ({ page }) => {
const store = window.openPencil?.getStore?.()
if (!store) throw new Error('Editor unavailable')
const graph = store.graph
- const token = graph.variables.get('announcement-accent')
- if (!token) throw new Error('Accent token unavailable')
- const original = structuredClone(token.valuesByMode.default)
- store.updateVariableValue(token.id, 'default', { r: 0.05, g: 0.55, b: 0.5, a: 1 })
- const changed = structuredClone(token.valuesByMode.default)
+ // The demo is opened from `.fig`, which gives variables and modes ids of its own.
+ const collection = [...graph.variableCollections.values()].find(
+ (item) => item.name === 'Announcement / Color'
+ )
+ const token = [...graph.variables.values()].find(
+ (item) => item.name === 'Accent' && item.collectionId === collection?.id
+ )
+ if (!collection || !token) throw new Error('Accent token unavailable')
+ const mode = collection.defaultModeId
+ const original = structuredClone(token.valuesByMode[mode])
+ store.updateVariableValue(token.id, mode, { r: 0.05, g: 0.55, b: 0.5, a: 1 })
+ const changed = structuredClone(token.valuesByMode[mode])
store.undoAction()
- const restored = structuredClone(token.valuesByMode.default)
+ const restored = structuredClone(token.valuesByMode[mode])
const component = Array.from(graph.getAllNodes()).find(
(node) => node.type === 'COMPONENT' && node.name === 'Announcement'
)
diff --git a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-components-and-variables-openpencil-darwin.png b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-components-and-variables-openpencil-darwin.png
index 02c980b08..600354e3d 100644
Binary files a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-components-and-variables-openpencil-darwin.png and b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-components-and-variables-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-controls-openpencil-darwin.png b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-controls-openpencil-darwin.png
new file mode 100644
index 000000000..b93c82417
Binary files /dev/null and b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-controls-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-paint-openpencil-darwin.png b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-paint-openpencil-darwin.png
index 290f2c619..a71b5e37d 100644
Binary files a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-paint-openpencil-darwin.png and b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-paint-openpencil-darwin.png differ
diff --git a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-typography-openpencil-darwin.png b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-typography-openpencil-darwin.png
index 2fbfe5c4e..068b963a9 100644
Binary files a/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-typography-openpencil-darwin.png and b/tests/e2e/canvas/demo-workspace.spec.ts-snapshots/demo-typography-openpencil-darwin.png differ
diff --git a/tests/e2e/components/behaviours.spec.ts b/tests/e2e/components/behaviours.spec.ts
index 7610f41df..9ec8f58bf 100644
--- a/tests/e2e/components/behaviours.spec.ts
+++ b/tests/e2e/components/behaviours.spec.ts
@@ -274,7 +274,7 @@ test('a rectangle made a Textarea gets its text layer from the panel and takes t
const section = propertySection(editor.page, 'Behaviour')
await section.getByRole('button', { name: 'Add behaviour' }).click()
await editor.page.getByRole('option', { name: /Textarea/ }).click()
- await expect(section.getByRole('button', { name: 'Still needed: Text.' })).toBeVisible()
+ await expect(section.getByRole('status')).toHaveText('Still needed: Text.')
await section.getByRole('button', { name: 'Add text layer' }).click()
await expect(section.getByText('Ready', { exact: true })).toBeVisible()
diff --git a/tests/engine/cli/export/index.test.ts b/tests/engine/cli/export/index.test.ts
index f74fdc4f9..eb1b48f28 100644
--- a/tests/engine/cli/export/index.test.ts
+++ b/tests/engine/cli/export/index.test.ts
@@ -197,7 +197,7 @@ test('export CLI writes Tailwind JSX for a page', async () => {
const jsx = await Bun.file(output).text()
expect(jsx).toStartWith('<div data-name="First slide" className="')
expect(jsx).toContain(
- '<div data-name="Export Card" className="flex absolute top-0 left-0 p-4 gap-2'
+ '<div data-name="Export Card" className="flex absolute top-0 left-0 p-4 items-start gap-2'
)
expect(jsx).not.toContain('Second Card')
})
diff --git a/tests/engine/io/fig/import/derived-symbol-data.test.ts b/tests/engine/io/fig/import/derived-symbol-data.test.ts
index ea5212d09..8d6648d8e 100644
--- a/tests/engine/io/fig/import/derived-symbol-data.test.ts
+++ b/tests/engine/io/fig/import/derived-symbol-data.test.ts
@@ -133,7 +133,7 @@ describe('occurrence derived symbol data', () => {
[blob]
)
expect(child.derivedTextGlyphs).toEqual([
- { commandsBlob: blob, firstCharacter: 0, x: 4, y: 15, fontSize: 14, rotation: 0 }
+ { commandsBlob: blob, firstCharacter: 0, x: 4, y: 15, fontSize: 14, rotation: 0, advance: 14 }
])
})
})
diff --git a/tests/engine/io/fig/import/legacy/text.test.ts b/tests/engine/io/fig/import/legacy/text.test.ts
index 7215a92cf..a5da5d28c 100644
--- a/tests/engine/io/fig/import/legacy/text.test.ts
+++ b/tests/engine/io/fig/import/legacy/text.test.ts
@@ -58,7 +58,9 @@ describe('fig-import: text properties', () => {
fontSize: 14,
// Path text needs per-glyph rotation preserved through import (#396);
// plain text imports it as 0 rather than dropping the field.
- rotation: 0
+ rotation: 0,
+ // One em at 14px, so decorations can stop where the glyph ends.
+ advance: 14
}
])
diff --git a/tests/engine/layout/auto-layout/layout/imported-derived.test.ts b/tests/engine/layout/auto-layout/layout/imported-derived.test.ts
index b93483e86..65dbf4a16 100644
--- a/tests/engine/layout/auto-layout/layout/imported-derived.test.ts
+++ b/tests/engine/layout/auto-layout/layout/imported-derived.test.ts
@@ -29,6 +29,35 @@ describe('imported auto-layout bounds', () => {
expect(graph.getNode(line.id)).toMatchObject({ x: 0, y: 1, width: 320, height: 0 })
})
+ test('centres content within the width a stretching parent gives a hug frame with a saved size', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const column = graph.createNode('FRAME', page.id, {
+ width: 320,
+ height: 200,
+ layoutMode: 'VERTICAL',
+ primaryAxisSizing: 'FIXED',
+ counterAxisSizing: 'FIXED'
+ })
+ const tile = graph.createNode('FRAME', column.id, {
+ width: 320,
+ height: 100,
+ layoutMode: 'HORIZONTAL',
+ primaryAxisSizing: 'HUG',
+ counterAxisSizing: 'HUG',
+ primaryAxisAlign: 'CENTER',
+ paddingLeft: 16,
+ paddingRight: 16,
+ layoutAlignSelf: 'STRETCH',
+ derivedLayout: { x: 0, y: 0, width: 320, height: 100 }
+ })
+ const swatch = graph.createNode('RECTANGLE', tile.id, { width: 200, height: 100 })
+
+ computeAllLayouts(graph)
+
+ expect(graph.getNode(swatch.id)?.x).toBe(60)
+ })
+
test('preserves visible hug container bounds when hidden children would collapse layout', () => {
const graph = new SceneGraph()
const page = graph.getPages()[0]
diff --git a/tests/helpers/canvas/color-space.ts b/tests/helpers/canvas/color-space.ts
index 36e1c55ab..ab29225a6 100644
--- a/tests/helpers/canvas/color-space.ts
+++ b/tests/helpers/canvas/color-space.ts
@@ -26,6 +26,19 @@ export async function dismissWideGamutBanner(page: Page) {
/** Focus the demo's paint and effects page, where blends and masks live. */
export async function focusPaintEffects(page: Page) {
+ // Zooming to a layer uses the viewport size the canvas last measured, so a window resize must
+ // reach it first or the zoom fits the old size. The canvas sizes its pixels in the same step.
+ await page.waitForFunction(() => {
+ const canvas = document.querySelector<HTMLCanvasElement>(
+ '[data-test-id="scene-canvas-element"]'
+ )
+ const dpr = window.devicePixelRatio || 1
+ return (
+ !!canvas &&
+ canvas.width === Math.round(canvas.clientWidth * dpr) &&
+ canvas.height === Math.round(canvas.clientHeight * dpr)
+ )
+ })
await page.evaluate(async () => {
const store = window.openPencil?.getStore?.()
if (!store) throw new Error('Editor unavailable')
diff --git a/tests/helpers/canvas/demo-startup.ts b/tests/helpers/canvas/demo-startup.ts
deleted file mode 100644
index 28d4e80ee..000000000
--- a/tests/helpers/canvas/demo-startup.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { SceneGraph } from '@open-pencil/scene-graph'
-
-import { createDemoShapes } from '@/app/demo/document'
-import type { EditorStore } from '@/app/editor/session'
-
-export async function replaceGraphDuringDemoSwitch(store: EditorStore) {
- const switchPage = store.switchPage
- const snapshot = () => ({
- selectedIds: [...store.state.selectedIds],
- zoom: store.state.zoom,
- panX: store.state.panX,
- panY: store.state.panY
- })
- let expected: ReturnType<typeof snapshot> | undefined
- store.switchPage = async (...args) => {
- const result = await switchPage(...args)
- const replacement = new SceneGraph()
- const page = replacement.addPage('Replacement document')
- const node = replacement.createNode('RECTANGLE', page.id, { width: 100, height: 100 })
- store.replaceGraph(replacement)
- await switchPage(page.id)
- store.select([node.id])
- store.zoomToLevel(0.75)
- expected = snapshot()
- return result
- }
- try {
- await createDemoShapes(store)
- if (!expected) throw new Error('Demo did not reach its final page switch')
- return { expected, actual: snapshot() }
- } finally {
- store.switchPage = switchPage
- }
-}
diff --git a/tools/AGENTS.md b/tools/AGENTS.md
index ba449bfe7..4b126b401 100644
--- a/tools/AGENTS.md
+++ b/tools/AGENTS.md
@@ -5,7 +5,7 @@ Private tooling lives under `tools/<role>/<domain>/{src,tests}`; Steiger enforce
| Role | Contract | Domains |
| ----------- | ---------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `checks/` | Read the tree and exit non-zero; never write inside the repository except an own baseline behind an explicit `--write` | `architecture`, `lint`, `i18n`, `secret-scan`, `type-shapes`, `docs`, `test-homes`, `package-quality` |
-| `generate/` | Write generated files or artifacts, idempotently | `brand`, `tauri-menu`, `authoring-reference`, `visual-oracles` |
+| `generate/` | Write generated files or artifacts, idempotently | `brand`, `demo`, `tauri-menu`, `authoring-reference`, `visual-oracles` |
| `release/` | Build, verify, and publish packages and native artifacts | `package-artifacts`, `release-packages` |
| `ci/` | Consumed by workflows: path classification and gate policy, container images, the review-guidance bot | `policy`, `images`, `pr-review-guidance` |
| `dev/` | Test running and benchmarks for humans | `unit-tests`, `navigation-benchmark`, `dev-server` |
@@ -33,6 +33,10 @@ Private tooling lives under `tools/<role>/<domain>/{src,tests}`; Steiger enforce
- Ensure Tauri and Apple signing/notarization secrets are configured. Verify the draft title, body, and artifacts, then publish. Release titles are exactly the tag (`vX.Y.Z`) without a product-name prefix.
- Homebrew's `openpencil` cask is managed upstream: BrewTestBot proposes bumps and Homebrew merges them. Check the upstream cask PR after publication; do not push to the archived custom tap or add bump automation. Users install the app with `brew install --cask openpencil` and the CLI through npm or Bun.
+## Demo document
+
+The `/demo` document is built from `tools/generate/demo/src/document/` into the ignored `public/demo.fig`, and the app opens it like any `.fig` file; it is never generated in the browser. `ensureDemoDocument` runs from `vite.config.ts`, rebuilds only when its inputs' fingerprint changes, and runs the build in Bun; `bun run generate:demo` forces it. A section that needs something new from the engine adds that package's `src` to the fingerprint in `tools/generate/demo/src/ensure.ts`.
+
## Brand assets
Canonical artwork lives in `assets/brand/` (main mark and optical micro master; see its README). `tools/generate/brand/` derives web, docs, and native icons with RealFaviconGenerator and Tauri; generated assets are ignored, not committed. Vite and VitePress configs prepare their own targets, and Tauri dev/build hooks prepare native icons.
diff --git a/tools/checks/test-homes/engine-baseline.txt b/tools/checks/test-homes/engine-baseline.txt
index 2e3de8ab2..c04693b53 100644
--- a/tools/checks/test-homes/engine-baseline.txt
+++ b/tools/checks/test-homes/engine-baseline.txt
@@ -37,7 +37,6 @@ tests/engine/app/clipboard/references.test.ts
tests/engine/app/clipboard/styles.test.ts
tests/engine/app/clipboard/variables.test.ts
tests/engine/app/code/sandbox.test.ts
-tests/engine/app/demo.test.ts
tests/engine/app/demo/viewport.test.ts
tests/engine/app/diagnostics/events.test.ts
tests/engine/app/diagnostics/recorder.test.ts
diff --git a/tools/generate/demo/package.json b/tools/generate/demo/package.json
new file mode 100644
index 000000000..f9605590a
--- /dev/null
+++ b/tools/generate/demo/package.json
@@ -0,0 +1,27 @@
+{
+ "name": "@open-pencil/demo-tools",
+ "private": true,
+ "type": "module",
+ "imports": {
+ "#demo/*": "./src/*.ts"
+ },
+ "exports": {
+ ".": "./src/ensure.ts"
+ },
+ "scripts": {
+ "test": "bun test tests"
+ },
+ "dependencies": {
+ "@open-pencil/core": "workspace:*",
+ "@open-pencil/design-jsx": "workspace:*",
+ "@open-pencil/package-artifacts-tools": "workspace:*",
+ "@open-pencil/scene-graph": "workspace:*",
+ "proper-lockfile": "4.1.2"
+ },
+ "devDependencies": {
+ "@types/bun": "^1.3.14",
+ "@types/node": "^25.9.9",
+ "@types/proper-lockfile": "4.1.4",
+ "typescript": "~5.8.3"
+ }
+}
diff --git a/tools/generate/demo/src/build.ts b/tools/generate/demo/src/build.ts
new file mode 100644
index 000000000..0173f7473
--- /dev/null
+++ b/tools/generate/demo/src/build.ts
@@ -0,0 +1,80 @@
+import { SkiaRenderer } from '@open-pencil/core/canvas'
+import { exportFigFile, initCanvasKit } from '@open-pencil/core/io'
+import { computeAllLayouts, installTextMeasurer } from '@open-pencil/core/layout'
+import { fontManager, prepareGraphFonts } from '@open-pencil/core/text'
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { createAnnouncementSection } from './document/announcement/section'
+import { createControlsSection } from './document/controls/section'
+import { createPaintSection } from './document/paint/section'
+import { createComponentsSection } from './document/sections/components'
+import { createDemoVariables } from './document/sections/variables'
+import { createTypographySection } from './document/typography/section'
+
+const PAGE_ORIGIN = 60
+const PAGE_GAP = 64
+const INTER_STYLES = ['Regular', 'Medium', 'SemiBold', 'Bold']
+
+/** A renderer on a 1×1 surface, for measuring text while laying the document out. */
+export async function measuringRenderer() {
+ const ck = await initCanvasKit()
+ const surface = ck.MakeSurface(1, 1)
+ if (!surface) throw new Error('CanvasKit could not create a surface')
+ const renderer = new SkiaRenderer(ck, surface)
+ await renderer.loadFonts()
+ return { ck, renderer }
+}
+
+/** Runs `build` with Inter loaded and text measured by `renderer`, as demo layout needs. */
+export async function withMeasuredText<T>(
+ renderer: SkiaRenderer,
+ build: () => Promise<T>
+): Promise<T> {
+ const uninstall = installTextMeasurer((node, maxWidth) =>
+ renderer.measureTextNode(node, maxWidth)
+ )
+ try {
+ await Promise.all(INTER_STYLES.map((style) => fontManager.loadFont('Inter', style)))
+ return await build()
+ } finally {
+ uninstall()
+ }
+}
+
+/** Builds every page of the demo into a fresh graph, laid out with `renderer`'s text metrics. */
+function buildDemoGraph(renderer: SkiaRenderer): Promise<SceneGraph> {
+ return withMeasuredText(renderer, async () => {
+ const graph = new SceneGraph()
+ const [first] = graph.getPages()
+ graph.updateNode(first.id, { name: '01 · Components & variables' })
+ const typography = graph.addPage('02 · Typography')
+ const paint = graph.addPage('03 · Paint & effects')
+ const controls = graph.addPage('04 · Controls')
+
+ const announcement = await createAnnouncementSection(graph, first.id)
+ graph.updateNode(announcement.rootId, { x: PAGE_ORIGIN, y: PAGE_ORIGIN })
+ computeAllLayouts(graph, first.id)
+ await createComponentsSection(graph, first.id, {
+ x: PAGE_ORIGIN,
+ y: PAGE_ORIGIN + (graph.getNode(announcement.rootId)?.height ?? 0) + PAGE_GAP
+ })
+ createDemoVariables(graph)
+ await createTypographySection(graph, typography.id)
+ await createPaintSection(graph, paint.id)
+ await createControlsSection(graph, controls.id)
+
+ const pages = graph.getPages()
+ await prepareGraphFonts(
+ graph,
+ pages.map((page) => page.id)
+ )
+ for (const page of pages) computeAllLayouts(graph, page.id)
+ return graph
+ })
+}
+
+/** The demo document as `.fig` bytes, as `/demo` opens it. */
+export async function buildDemoDocument(): Promise<Uint8Array> {
+ const { ck, renderer } = await measuringRenderer()
+ return exportFigFile(await buildDemoGraph(renderer), ck, renderer)
+}
diff --git a/tools/generate/demo/src/cli.ts b/tools/generate/demo/src/cli.ts
new file mode 100644
index 000000000..f36a66ed1
--- /dev/null
+++ b/tools/generate/demo/src/cli.ts
@@ -0,0 +1,3 @@
+import { ensureDemoDocument } from './ensure'
+
+await ensureDemoDocument({ force: process.argv.includes('--force') })
diff --git a/src/app/demo/announcement/component.ts b/tools/generate/demo/src/document/announcement/component.ts
similarity index 99%
rename from src/app/demo/announcement/component.ts
rename to tools/generate/demo/src/document/announcement/component.ts
index 8b43750a2..fad72ed1c 100644
--- a/src/app/demo/announcement/component.ts
+++ b/tools/generate/demo/src/document/announcement/component.ts
@@ -102,7 +102,7 @@ export async function createAnnouncementComponent(
...text,
name: 'Details',
w: 'fill',
- size: 10,
+ size: 12,
lineHeight: 16,
color: tokens.muted,
children: ANNOUNCEMENT.details,
diff --git a/src/app/demo/announcement/content.ts b/tools/generate/demo/src/document/announcement/content.ts
similarity index 100%
rename from src/app/demo/announcement/content.ts
rename to tools/generate/demo/src/document/announcement/content.ts
diff --git a/src/app/demo/announcement/section.ts b/tools/generate/demo/src/document/announcement/section.ts
similarity index 100%
rename from src/app/demo/announcement/section.ts
rename to tools/generate/demo/src/document/announcement/section.ts
diff --git a/src/app/demo/announcement/tokens.ts b/tools/generate/demo/src/document/announcement/tokens.ts
similarity index 100%
rename from src/app/demo/announcement/tokens.ts
rename to tools/generate/demo/src/document/announcement/tokens.ts
diff --git a/src/app/demo/colors.ts b/tools/generate/demo/src/document/colors.ts
similarity index 100%
rename from src/app/demo/colors.ts
rename to tools/generate/demo/src/document/colors.ts
diff --git a/tools/generate/demo/src/document/controls/components.tsx b/tools/generate/demo/src/document/controls/components.tsx
new file mode 100644
index 000000000..15f9f26a3
--- /dev/null
+++ b/tools/generate/demo/src/document/controls/components.tsx
@@ -0,0 +1,143 @@
+/** @jsxImportSource @open-pencil/design-jsx */
+/**
+ * The demo's controls, written with Reka UI's element names: each is a main component (or set)
+ * with a behaviour, ready to place and to run in preview.
+ */
+import {
+ Button,
+ Checkbox,
+ Component,
+ Slider,
+ Switch,
+ Tabs,
+ Text,
+ TextField,
+ type BaseProps,
+ type TreeNode
+} from '@open-pencil/design-jsx'
+
+export const CONTROL_COLORS = {
+ ink: '#172554',
+ muted: '#536487',
+ accent: '#4F46E5',
+ accentHover: '#4338CA',
+ accentPressed: '#3730A3',
+ line: '#CBD5E1',
+ tile: '#EEF2FF',
+ surface: '#FFFFFF',
+ disabled: '#E2E8F0'
+}
+
+const { ink, muted, accent, accentHover, accentPressed, line, tile, surface, disabled } =
+ CONTROL_COLORS
+
+function buttonVariant(state: string, look: BaseProps, color = surface): TreeNode {
+ return (
+ <Component name={`Interaction=${state}`} flex="row" px={16} py={8} rounded={8} {...look}>
+ <Text font="Inter" size={13} weight={600} color={color}>
+ Save
+ </Text>
+ </Component>
+ )
+}
+
+/** A button whose variants draw its interaction states. */
+export const BUTTON = (
+ <Button.Root name="Button" states="Interaction" flex="row" gap={12} p={16}>
+ {buttonVariant('Default', { bg: accent })}
+ {buttonVariant('Hover', { bg: accentHover })}
+ {buttonVariant('Pressed', { bg: accentPressed })}
+ {buttonVariant('Focus', { bg: accent, stroke: ink, strokeWidth: 2 })}
+ {buttonVariant('Disabled', { bg: disabled }, muted)}
+ </Button.Root>
+)
+
+export const SWITCH = (
+ <Switch.Root name="Switch" modelValue="State" flex="row" gap={16} p={16}>
+ <Component name="State=Off" w={40} h={22} rounded={11} bg={line}>
+ <Switch.Thumb x={2} y={2} w={18} h={18} rounded={9} bg={surface} />
+ </Component>
+ <Component name="State=On" w={40} h={22} rounded={11} bg={accent}>
+ <Switch.Thumb x={20} y={2} w={18} h={18} rounded={9} bg={surface} />
+ </Component>
+ </Switch.Root>
+)
+
+export const CHECKBOX = (
+ <Checkbox.Root name="Checkbox" modelValue="Checked" flex="row" gap={16} p={16}>
+ <Component
+ name="Checked=Off"
+ w={18}
+ h={18}
+ rounded={4}
+ bg={surface}
+ stroke={line}
+ strokeWidth={1.5}
+ />
+ <Component name="Checked=On" w={18} h={18} rounded={4} bg={accent}>
+ <Checkbox.Indicator x={5} y={5} w={8} h={8} rounded={2} bg={surface} />
+ </Component>
+ </Checkbox.Root>
+)
+
+export const SLIDER = (
+ <Slider.Root name="Slider" w={220} h={20} min={0} max={100} step={1} defaultValue={60}>
+ <Slider.Track x={0} y={8} w={220} h={4} rounded={2} bg={tile} />
+ <Slider.Range x={0} y={8} w={132} h={4} rounded={2} bg={accent} />
+ <Slider.Thumb
+ x={122}
+ y={0}
+ w={20}
+ h={20}
+ rounded={10}
+ bg={surface}
+ stroke={accent}
+ strokeWidth={2}
+ />
+ </Slider.Root>
+)
+
+export const TEXT_FIELD = (
+ <TextField.Root
+ name="Text field"
+ w={260}
+ h={36}
+ rounded={8}
+ bg={surface}
+ stroke={line}
+ flex="row"
+ items="center"
+ px={12}
+ >
+ <TextField.Input font="Inter" size={13} color={ink}>
+ </TextField.Input>
+ </TextField.Root>
+)
+
+const TABS_CONTENT = [
+ ['Profile', 'Your name and photo, as teammates see them.'],
+ ['Notifications', 'Choose what reaches your inbox.'],
+ ['Billing', 'Plan, invoices, and payment method.']
+] as const
+
+export const TABS = (
+ <Tabs.Root name="Tabs" w={300} flex="col" gap={12}>
+ <Tabs.List flex="row" gap={4} p={4} rounded={8} bg={tile}>
+ {TABS_CONTENT.map(([title]) => (
+ <Tabs.Trigger px={12} py={6} rounded={6}>
+ <Text font="Inter" size={12} weight={600} color={ink}>
+ {title}
+ </Text>
+ </Tabs.Trigger>
+ ))}
+ </Tabs.List>
+ {TABS_CONTENT.map(([, panel]) => (
+ <Tabs.Content w={300} flex="col">
+ <Text font="Inter" size={13} color={muted} w="fill">
+ {panel}
+ </Text>
+ </Tabs.Content>
+ ))}
+ </Tabs.Root>
+)
diff --git a/tools/generate/demo/src/document/controls/section.ts b/tools/generate/demo/src/document/controls/section.ts
new file mode 100644
index 000000000..fc96d2aee
--- /dev/null
+++ b/tools/generate/demo/src/document/controls/section.ts
@@ -0,0 +1,138 @@
+import { renderTree } from '@open-pencil/core/design-jsx'
+import { Frame, Instance, Text } from '@open-pencil/design-jsx'
+import type { TreeNode } from '@open-pencil/design-jsx'
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+import { BUTTON, CHECKBOX, CONTROL_COLORS, SLIDER, SWITCH, TABS, TEXT_FIELD } from './components'
+
+const { ink, muted, line, surface, tile } = CONTROL_COLORS
+const ORIGIN = 60
+const GAP = 48
+
+const text = (size: number, color: string, children: string, extra: object = {}) =>
+ Text({ font: 'Inter', size, color, children, ...extra })
+
+/** A labelled row of the settings card: what the control sets, then the control. */
+function settingRow(title: string, caption: string, control: TreeNode): TreeNode {
+ return Frame({
+ name: title,
+ flex: 'row',
+ w: 'fill',
+ h: 'hug',
+ gap: 24,
+ items: 'center',
+ children: [
+ Frame({
+ name: 'Label',
+ flex: 'col',
+ w: 'fill',
+ h: 'hug',
+ gap: 2,
+ children: [text(13, ink, title, { weight: 600 }), text(12, muted, caption, { w: 'fill' })]
+ }),
+ control
+ ]
+ })
+}
+
+/** Renders one control onto the board and returns its main component or set. */
+async function renderControl(graph: SceneGraph, boardId: string, control: TreeNode) {
+ const result = await renderTree(graph, control, { parentId: boardId })
+ const node = graph.getNode(result.id)
+ if (!node) throw new Error('The control did not render')
+ return node
+}
+
+/** The variant of a set named `name`, or the component itself when it is not a set. */
+function variant(graph: SceneGraph, id: string, name: string): string {
+ return graph.getChildren(id).find((child) => child.name === name)?.id ?? id
+}
+
+/**
+ * The Controls page: main components that behave as Reka UI controls, and a settings card
+ * built from their instances, which preview runs as live components.
+ */
+export async function createControlsSection(graph: SceneGraph, pageId: string) {
+ const header = await renderTree(
+ graph,
+ Frame({
+ name: 'About this page',
+ flex: 'col',
+ w: 1056,
+ h: 'hug',
+ gap: 8,
+ children: [
+ text(20, ink, 'Components that work.', { weight: 600 }),
+ text(
+ 13,
+ muted,
+ 'Each main component has a behaviour from the Behaviour section: a switch, a slider, tabs, a text field. Press ⌥⌘↩ (View › Preview) and the card on the right runs as real Reka UI components; nothing you do there changes the document.',
+ { w: 'fill', lineHeight: 20 }
+ )
+ ]
+ }),
+ { parentId: pageId }
+ )
+ graph.updateNode(header.id, { x: ORIGIN, y: ORIGIN })
+
+ const board = await renderTree(
+ graph,
+ Frame({
+ name: 'Components',
+ flex: 'col',
+ w: 480,
+ h: 'hug',
+ gap: 24,
+ p: 32,
+ rounded: 16,
+ bg: tile,
+ children: [text(12, muted, 'MAIN COMPONENTS', { weight: 600 })]
+ }),
+ { parentId: pageId }
+ )
+ const top = ORIGIN + (graph.getNode(header.id)?.height ?? 0) + GAP
+ graph.updateNode(board.id, { x: ORIGIN, y: top })
+
+ const button = await renderControl(graph, board.id, BUTTON)
+ const toggle = await renderControl(graph, board.id, SWITCH)
+ const checkbox = await renderControl(graph, board.id, CHECKBOX)
+ const slider = await renderControl(graph, board.id, SLIDER)
+ const field = await renderControl(graph, board.id, TEXT_FIELD)
+ const tabs = await renderControl(graph, board.id, TABS)
+
+ const card = await renderTree(
+ graph,
+ Frame({
+ name: 'Account settings',
+ flex: 'col',
+ w: 520,
+ h: 'hug',
+ gap: 24,
+ p: 32,
+ rounded: 16,
+ bg: surface,
+ stroke: line,
+ children: [
+ text(18, ink, 'Account settings', { weight: 600 }),
+ Instance({ of: tabs.id }),
+ settingRow(
+ 'Email alerts',
+ 'Hear about mentions and replies.',
+ Instance({ of: variant(graph, toggle.id, 'State=On') })
+ ),
+ settingRow(
+ 'Weekly digest',
+ 'A Monday summary of your projects.',
+ Instance({ of: variant(graph, checkbox.id, 'Checked=Off') })
+ ),
+ settingRow('Volume', 'Notification sounds.', Instance({ of: slider.id })),
+ settingRow('Email', 'Where alerts go.', Instance({ of: field.id })),
+ Instance({ of: variant(graph, button.id, 'Interaction=Default') })
+ ]
+ }),
+ { parentId: pageId }
+ )
+ graph.updateNode(card.id, { x: ORIGIN + 480 + GAP, y: top })
+
+ return { rootIds: [header.id, board.id, card.id] }
+}
diff --git a/src/app/demo/effects.ts b/tools/generate/demo/src/document/effects.ts
similarity index 100%
rename from src/app/demo/effects.ts
rename to tools/generate/demo/src/document/effects.ts
diff --git a/src/app/demo/paint/samples.ts b/tools/generate/demo/src/document/paint/samples.ts
similarity index 100%
rename from src/app/demo/paint/samples.ts
rename to tools/generate/demo/src/document/paint/samples.ts
diff --git a/src/app/demo/paint/section.ts b/tools/generate/demo/src/document/paint/section.ts
similarity index 100%
rename from src/app/demo/paint/section.ts
rename to tools/generate/demo/src/document/paint/section.ts
diff --git a/src/app/demo/sections/components.ts b/tools/generate/demo/src/document/sections/components.ts
similarity index 99%
rename from src/app/demo/sections/components.ts
rename to tools/generate/demo/src/document/sections/components.ts
index 3ecbf2796..4710eb61a 100644
--- a/src/app/demo/sections/components.ts
+++ b/tools/generate/demo/src/document/sections/components.ts
@@ -23,7 +23,7 @@ const BORDER = '#DCE3F5'
const text = { font: 'Inter', color: INK }
const label = { ...text, size: 12, color: MUTED }
-const caption = { ...label, size: 10 }
+const caption = { ...label, size: 12 }
export const COMPONENT_PROPERTIES = {
buttonLabel: {
@@ -292,9 +292,9 @@ export async function createComponentsSection(
Text({
...text,
name: 'Label',
- size: 11,
+ size: 12,
weight: 600,
- color: '#16A34A',
+ color: '#15803D',
children: COMPONENT_PROPERTIES.badgeLabel.defaultValue,
propertyRefs: [{ propertyId: COMPONENT_PROPERTIES.badgeLabel.id, field: 'TEXT' }]
})
diff --git a/src/app/demo/sections/example.ts b/tools/generate/demo/src/document/sections/example.ts
similarity index 100%
rename from src/app/demo/sections/example.ts
rename to tools/generate/demo/src/document/sections/example.ts
diff --git a/src/app/demo/sections/variables.ts b/tools/generate/demo/src/document/sections/variables.ts
similarity index 94%
rename from src/app/demo/sections/variables.ts
rename to tools/generate/demo/src/document/sections/variables.ts
index 47806dcd8..f79c531ad 100644
--- a/src/app/demo/sections/variables.ts
+++ b/tools/generate/demo/src/document/sections/variables.ts
@@ -1,11 +1,8 @@
-import type { Color } from '@open-pencil/scene-graph'
+import type { Color, SceneGraph } from '@open-pencil/scene-graph'
-import { DEMO_COLORS } from '@/app/demo/colors'
-import type { EditorStore } from '@/app/editor/session'
-
-export function createDemoVariables(store: EditorStore) {
- const { graph } = store
+import { DEMO_COLORS } from '../colors'
+export function createDemoVariables(graph: SceneGraph) {
graph.addCollection({
id: 'col-primitives',
name: 'Primitives',
diff --git a/src/app/demo/typography/content.ts b/tools/generate/demo/src/document/typography/content.ts
similarity index 100%
rename from src/app/demo/typography/content.ts
rename to tools/generate/demo/src/document/typography/content.ts
diff --git a/src/app/demo/typography/samples.ts b/tools/generate/demo/src/document/typography/samples.ts
similarity index 100%
rename from src/app/demo/typography/samples.ts
rename to tools/generate/demo/src/document/typography/samples.ts
diff --git a/src/app/demo/typography/section.ts b/tools/generate/demo/src/document/typography/section.ts
similarity index 96%
rename from src/app/demo/typography/section.ts
rename to tools/generate/demo/src/document/typography/section.ts
index a04ebe084..1be20867c 100644
--- a/src/app/demo/typography/section.ts
+++ b/tools/generate/demo/src/document/typography/section.ts
@@ -38,7 +38,7 @@ export async function createTypographySection(graph: SceneGraph, parentId: strin
rounded: 16,
bg: '#EEF2FF',
children: [
- Text({ ...label, size: 10, children: ARTICLE.eyebrow }),
+ Text({ ...label, size: 12, children: ARTICLE.eyebrow }),
Text({
...text,
name: 'Article headline',
@@ -64,7 +64,7 @@ export async function createTypographySection(graph: SceneGraph, parentId: strin
lineHeight: 22,
children: ARTICLE.body
}),
- Text({ ...label, size: 10, children: ARTICLE.detail })
+ Text({ ...label, size: 12, children: ARTICLE.detail })
]
}),
Frame({
@@ -89,7 +89,7 @@ export async function createTypographySection(graph: SceneGraph, parentId: strin
description: 'Readable lines, generous leading, and a content-sized frame.'
},
{
- title: 'Details · 10',
+ title: 'Details · 12',
description: 'Supporting information with enough contrast to stay useful.'
}
].map((item) =>
@@ -143,7 +143,7 @@ export async function createTypographySection(graph: SceneGraph, parentId: strin
{ parentId: comparisonRow.id }
)
for (const [index, settings] of [comparison.enabled, comparison.disabled].entries()) {
- await renderTree(graph, Text({ ...label, size: 10, children: comparison.labels[index] }), {
+ await renderTree(graph, Text({ ...label, size: 12, children: comparison.labels[index] }), {
parentId: column.id
})
await createTypographySample(graph, column.id, {
diff --git a/tools/generate/demo/src/ensure.ts b/tools/generate/demo/src/ensure.ts
new file mode 100644
index 000000000..0e502f767
--- /dev/null
+++ b/tools/generate/demo/src/ensure.ts
@@ -0,0 +1,98 @@
+import { execFile } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { promisify } from 'node:util'
+
+import { lock } from 'proper-lockfile'
+
+import { resolveWorkspaceRoot } from '@open-pencil/package-artifacts-tools/workspace'
+
+/** Where the app serves the demo from, relative to the repository root. */
+const DEMO_OUTPUT = 'public/demo.fig'
+const CACHE = '.cache/demo'
+
+/** Everything the demo's bytes depend on: its own sources and the engine that writes them. */
+const INPUT_DIRECTORIES = [
+ 'tools/generate/demo/src',
+ 'packages/scene-graph/src',
+ 'packages/core/src',
+ 'packages/design-jsx/src',
+ 'packages/dom-css/src',
+ 'packages/emit/src',
+ 'packages/fig/src',
+ 'packages/kiwi/src'
+]
+const INPUT_FILES = ['tools/generate/demo/package.json', 'package.json', 'bun.lock']
+
+async function filesIn(root: string, directory: string): Promise<string[]> {
+ const result: string[] = []
+ for (const item of await readdir(join(root, directory), { withFileTypes: true })) {
+ const path = join(directory, item.name)
+ if (item.isDirectory()) result.push(...(await filesIn(root, path)))
+ else if (item.isFile()) result.push(path)
+ }
+ return result
+}
+
+async function fingerprint(root: string): Promise<string> {
+ const listed = await Promise.all(INPUT_DIRECTORIES.map((directory) => filesIn(root, directory)))
+ const paths = [...listed.flat(), ...INPUT_FILES].sort()
+ const hash = createHash('sha256')
+ for (const path of paths)
+ hash
+ .update(path)
+ .update('\0')
+ .update(await readFile(join(root, path)))
+ .update('\0')
+ return hash.digest('hex')
+}
+
+const digest = (bytes: Uint8Array) => createHash('sha256').update(bytes).digest('hex')
+
+/** Whether the output is the one built from these inputs and nobody replaced it since. */
+async function isCurrent(root: string, key: string): Promise<boolean> {
+ try {
+ const [recorded, output] = await Promise.all([
+ readFile(join(root, CACHE, 'fingerprint'), 'utf8'),
+ readFile(join(root, DEMO_OUTPUT))
+ ])
+ return recorded === `${key}\n${digest(output)}`
+ } catch {
+ return false
+ }
+}
+
+/**
+ * Build `public/demo.fig` unless the one there was built from the current sources. Build-time
+ * only: Vite's config calls it before serving or bundling, and `generate:demo` forces it.
+ */
+export async function ensureDemoDocument(options: { root?: string; force?: boolean } = {}) {
+ const root = options.root ?? (await resolveWorkspaceRoot(fileURLToPath(import.meta.url)))
+ const cache = join(root, CACHE)
+ await mkdir(cache, { recursive: true })
+ // Dev, Storybook, and Playwright servers may start together; one of them builds.
+ const release = await lock(cache, {
+ realpath: false,
+ retries: { retries: 120, minTimeout: 100, maxTimeout: 1000, randomize: false }
+ })
+ try {
+ const key = await fingerprint(root)
+ if (!options.force && (await isCurrent(root, key))) return
+ // Vite loads this module in Node; the build runs in Bun, like the repository's other
+ // tools, and only when the sources changed, so a cached start never loads the engine.
+ const output = join(root, DEMO_OUTPUT)
+ await promisify(execFile)(
+ 'bun',
+ [fileURLToPath(new URL('write.ts', import.meta.url)), output],
+ {
+ cwd: root
+ }
+ )
+ await writeFile(join(cache, 'fingerprint'), `${key}\n${digest(await readFile(output))}`)
+ console.info('Generated the demo document')
+ } finally {
+ await release()
+ }
+}
diff --git a/tools/generate/demo/src/write.ts b/tools/generate/demo/src/write.ts
new file mode 100644
index 000000000..3d61f340c
--- /dev/null
+++ b/tools/generate/demo/src/write.ts
@@ -0,0 +1,12 @@
+import { mkdir, rename, writeFile } from 'node:fs/promises'
+import { dirname } from 'node:path'
+
+import { buildDemoDocument } from './build'
+
+/** Bun entry that `ensureDemoDocument` runs: build the demo and write it to the given path. */
+const [output] = process.argv.slice(2)
+if (!output) throw new Error('Usage: bun write.ts <output.fig>')
+const bytes = await buildDemoDocument()
+await mkdir(dirname(output), { recursive: true })
+await writeFile(`${output}.tmp`, bytes)
+await rename(`${output}.tmp`, output)
diff --git a/tools/generate/demo/tests/build.test.ts b/tools/generate/demo/tests/build.test.ts
new file mode 100644
index 000000000..419d4bb5c
--- /dev/null
+++ b/tools/generate/demo/tests/build.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, test } from 'bun:test'
+
+import { measuringRenderer, withMeasuredText } from '#demo/build'
+import { createControlsSection } from '#demo/document/controls/section'
+
+import { exportFigFile, readFigFile } from '@open-pencil/core/io'
+import { populateAllFigPages } from '@open-pencil/core/io/formats/fig'
+import { computeAllLayouts } from '@open-pencil/core/layout'
+import { missingBindings, readBehaviour, SceneGraph } from '@open-pencil/scene-graph'
+
+describe('demo controls', () => {
+ test('keep complete behaviours through the .fig the demo opens', async () => {
+ const { ck, renderer } = await measuringRenderer()
+ const built = await withMeasuredText(renderer, async () => {
+ const graph = new SceneGraph()
+ const [page] = graph.getPages()
+ await createControlsSection(graph, page.id)
+ computeAllLayouts(graph, page.id)
+ return graph
+ })
+ const bytes = await exportFigFile(built, ck, renderer)
+ const graph = await readFigFile(new File([bytes.slice()], 'Demo.fig'))
+ populateAllFigPages(graph)
+
+ const controls = [...graph.getAllNodes()].flatMap((node) => {
+ const behaviour = node.type === 'INSTANCE' ? null : readBehaviour(node)
+ return behaviour
+ ? [{ kind: behaviour.kind, missing: missingBindings(graph, node, behaviour) }]
+ : []
+ })
+ expect(controls.map((control) => control.kind).sort()).toEqual([
+ 'button',
+ 'checkbox',
+ 'slider',
+ 'switch',
+ 'tabs',
+ 'textField'
+ ])
+ for (const control of controls) expect(control.missing).toEqual([])
+ })
+})
diff --git a/tests/engine/app/demo.test.ts b/tools/generate/demo/tests/typography.test.ts
similarity index 79%
rename from tests/engine/app/demo.test.ts
rename to tools/generate/demo/tests/typography.test.ts
index a8f0a51b8..168a42365 100644
--- a/tests/engine/app/demo.test.ts
+++ b/tools/generate/demo/tests/typography.test.ts
@@ -1,16 +1,17 @@
import { describe, expect, test } from 'bun:test'
-import { createTypographySection } from '@/app/demo/typography/section'
-import { createEditorStore } from '@/app/editor/session'
+import { createTypographySection } from '#demo/document/typography/section'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
describe('demo document', () => {
test('showcases OpenType features and native text decorations', async () => {
- const store = createEditorStore()
- const page = store.graph.addPage('Typography')
+ const graph = new SceneGraph()
+ const page = graph.addPage('Typography')
- await createTypographySection(store.graph, page.id)
+ await createTypographySection(graph, page.id)
- const nodes = [...store.graph.getAllNodes()]
+ const nodes = [...graph.getAllNodes()]
const sample = (name: string) =>
nodes.find((node) => node.name === name && node.type === 'TEXT')
diff --git a/tools/tsconfig.json b/tools/tsconfig.json
index 57ed1fa35..9c22c4a54 100644
--- a/tools/tsconfig.json
+++ b/tools/tsconfig.json
@@ -7,6 +7,7 @@
},
"include": [
"*/*/src/**/*.ts",
+ "*/*/src/**/*.tsx",
"*/*/tests/**/*.ts",
"../src/global.d.ts",
"../src/markdown.d.ts",
diff --git a/vite.config.ts b/vite.config.ts
index 705811309..33cee0d10 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -9,6 +9,7 @@ import Components from 'unplugin-vue-components/vite'
import { defineConfig } from 'vite'
import { ensureBrandAssets } from '@open-pencil/brand-tools'
+import { ensureDemoDocument } from '@open-pencil/demo-tools'
import packageJson from './package.json'
import { viteBuildTarget } from './src/app/shell/support/baseline'
@@ -28,7 +29,7 @@ const host = process.env.TAURI_DEV_HOST
const automationRoute = localAutomationRoute(host)
export default defineConfig(async ({ command }) => {
- await ensureBrandAssets(['web'])
+ await Promise.all([ensureBrandAssets(['web']), ensureDemoDocument()])
return {
resolve: {
alias: createOpenPencilAliases(__dirname)