AI-native design editor. Open-source Figma alternative.
feat: behaviours and preview mode (#893)
Danila Poyarkove0716a3a38ff
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3ba906660..b437a85ed 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -31,6 +31,8 @@### Added+- 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.- 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.@@ -69,6 +71,7 @@### Changed+- `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.- Group, Frame selection, Create component, and boolean operations match Figma from the canvas and from scripts, through one shared implementation. From the canvas, the new layer takes the topmost selected layer's place in the layer list, Frame selection adds no fill and does not clip, a component wrapped around layers is white and takes a single layer's name, and a boolean is filled like its topmost operand, or its base for Subtract, without strokes. In scripts, `figma.ungroup()` leaves the children in the group's place instead of moving them to the top, booleans are named Union, Subtract, Intersect, or Exclude with the default grey fill, and `figma.createComponentFromNode()` turns a frame or group into a component that keeps its children instead of copying them, and wraps any other layer. Undoing a group or boolean returns each layer to its own place in the layer list.- Combine as variants matches Figma: the set pads its variants by 20 px and has a dashed purple stroke instead of a grey fill and 40 px of padding, and `figma.combineAsVariants()` in scripts wraps the components exactly with no fill or stroke, as Figma's plugin API does. Both share one implementation.@@ -95,6 +98,8 @@### Fixed+- `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.- Text saved to `.fig` or copied to Figma keeps its layout in Figma: it wraps at the layer's width with its alignment and line height, and keeps ligatures and contextual forms such as Inter's arrows, where Figma previously drew every saved OpenPencil text layer on one unwrapped line (#914).- Release a document's memory when its tab closes. Every closed tab kept its scene, canvas, and editor panels alive until reload, so memory grew with each document opened and closed. Menus and shortcuts now also follow the active document, so Undo and Redo are offered according to its history rather than the first document opened.diff --git a/README.md b/README.mdindex c13233c02..e211be5e2 100644--- a/README.md+++ b/README.md@@ -29,9 +29,10 @@ Requires macOS 13 or later with current Safari updates, Windows 10 or later, or- **Opens `.fig` and `.pen` files** — read and write native Figma files, open supported Pencil documents from the app or OS file browser, copy & paste nodes between apps- **AI builds designs** — describe what you want in chat, 100+ tools create and modify nodes. Connect OpenRouter, Anthropic, OpenAI, Google AI, DeepSeek, Z.ai, MiniMax, or compatible endpoints-- **Fully programmable** — headless CLI, XPath queries, Figma Plugin API via `eval`, MCP server for AI agents, and desktop agent integrations for Claude Code, Codex, and Gemini CLI+- **Fully programmable** — headless CLI, XPath queries, Figma Plugin API plus an `openpencil` API via `eval`, MCP server for AI agents, and desktop agent integrations for Claude Code, Codex, and Gemini CLI- **Lint, convert, and extract tokens** — inspect documents, lint naming/layout/accessibility, convert between supported formats, analyze colors/typography/spacing/clusters, and extract design tokens- **Components and variants** — create reusable components, group variants into component sets, insert local assets as instances, and switch variants from the inspector+- **Working controls** — give a component a Reka UI behaviour (switch, slider, tabs, text field, …) and preview it live over the canvas, with real inputs, focus, and keyboard- **Image vectorization** — convert image layers into editable vector layers with Recraft or fal.ai- **Design-to-code export** — export selections as JSX/Tailwind, generate token outputs, and map designs into component-oriented code workflows- **Vue SDK for custom editors** — headless components and composables for embedding OpenPencil into other apps or building workflow-specific editing surfaces. [Read the SDK docs →](https://openpencil.dev/programmable/sdk/)diff --git a/bun.lock b/bun.lockindex eac5a3a63..ec177432c 100644--- a/bun.lock+++ b/bun.lock@@ -207,7 +207,6 @@"acorn": "^8.18.0","canvaskit-wasm": "^0.41.1","culori": "^4.0.2",- "dedent": "^1.7.2","destr": "^2.0.5","diff": "^8.0.4","es-toolkit": "^1.52.0",@@ -435,6 +434,7 @@"@atlaskit/pragmatic-drag-and-drop-hitbox": "^1.2.0","@nanostores/i18n": "^1.3.3","@nanostores/vue": "^1.1.0",+ "@open-pencil/dom-css": "workspace:*","@open-pencil/scene-graph": "workspace:*","@vueuse/core": "^14.4.0","es-toolkit": "^1.52.0",diff --git a/desktop/generated/menu.json b/desktop/generated/menu.jsonindex 0c6a0227d..8269aac86 100644--- a/desktop/generated/menu.json+++ b/desktop/generated/menu.json@@ -265,6 +265,11 @@"label": "Toggle UI","accelerator": "CmdOrCtrl+\\"},+ {+ "id": "toggle-preview",+ "label": "Preview",+ "accelerator": "CmdOrCtrl+Alt+Enter"+ },{"type": "separator"},diff --git a/packages/cli/README.md b/packages/cli/README.mdindex 35b99ea4f..11dd06c5d 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -1,6 +1,6 @@# @open-pencil/cli-Headless command line for [OpenPencil](https://openpencil.dev) and `.fig` files: inspect documents and layers, query with XPath, export to PNG, JPG, WEBP, SVG, PDF, PPTX, JSX, HTML, or `.fig`, import HTML/CSS/Tailwind, lint design files, analyze and extract design tokens, and script documents with a Figma Plugin API-compatible `figma` global through `eval`.+Headless command line for [OpenPencil](https://openpencil.dev) and `.fig` files: inspect documents and layers, query with XPath, export to PNG, JPG, WEBP, SVG, PDF, PPTX, JSX, HTML, or `.fig`, import HTML/CSS/Tailwind, lint design files, analyze and extract design tokens, and script documents through `eval` with a Figma Plugin API-compatible `figma` global and an `openpencil` global for what OpenPencil adds, such as component behaviours and slots.```shnpm install -g @open-pencil/cli # or: bun add -g @open-pencil/clidiff --git a/packages/cli/src/commands/eval.ts b/packages/cli/src/commands/eval.tsindex 0139cf33d..fc6ca3dc8 100644--- a/packages/cli/src/commands/eval.ts+++ b/packages/cli/src/commands/eval.ts@@ -1,6 +1,7 @@import { defineCommand } from 'citty'import { FigmaAPI } from '@open-pencil/core/figma-api'+import { compileScript } from '@open-pencil/core/tools'import { isAppMode, requireFile, rpc } from '#cli/app/client'import { appTargetOptions, appTargetRPCArgs } from '#cli/app/target'@@ -71,19 +72,9 @@ export default defineCommand({populateWholeDocument(graph)const figma = new FigmaAPI(graph)- type AsyncFunctionConstructor = new (- ...args: string[]- ) => (...args: unknown[]) => Promise<unknown>- const AsyncFunction = Object.getPrototypeOf(async () => undefined)- .constructor as AsyncFunctionConstructor- const wrappedCode = code.trim().startsWith('return')- ? code- : `return (async () => { ${code} })()`-let result: unknowntry {- const fn = new AsyncFunction('figma', wrappedCode)- result = await fn(figma)+ result = await compileScript(code)(figma)} catch (err) {printError(err instanceof Error ? err.message : String(err))process.exit(1)diff --git a/packages/core/AGENTS.md b/packages/core/AGENTS.mdindex e288bf3e1..0648cce1b 100644--- a/packages/core/AGENTS.md+++ b/packages/core/AGENTS.md@@ -44,6 +44,15 @@ Renderer, layout, editor, Figma API, tools, clipboard, vector conversion, and do- Renderer interaction policy uses explicit `beginInteractiveEdit()` leases and `isInteractiveEditing()`, not undo batching. Release leases on every terminal path. Keep live queries callable across app facades that spread editor actions.- `packages/core/src/editor/history/atomic-tool.ts` owns synchronous property/variable transactions for AI, MCP, and WebMCP tools; see Tools above.+## OpenPencil API++`OpenPencilAPI` (`packages/core/src/openpencil-api/`) is what OpenPencil adds to the Plugin API, exposed to scripts as the `openpencil` global next to `figma`.++- Keep `figma` Figma-shaped and put OpenPencil-only features on `openpencil`, in the same style: methods and node-like handles with getters and setters, not parallel helper functions. Never add non-Figma members to `FigmaAPI` (`compatibility.ts`).+- Script runners get both globals only through `compileScript` (`packages/core/src/tools/analyze/eval/wrap.ts`); the `eval` tool, `openpencil eval`, and app automation must not build their own `AsyncFunction`.+- Members take names, not internal ids, and write through the same scene-graph functions the editor's actions use, such as `behaviourFromSpec`; errors name what exists. Tools for the same feature wrap the `openpencil` API rather than reimplementing it (`packages/core/src/tools/create/behaviours.ts`).+- A new member updates `packages/docs/programmable/cli/scripting.md` and the agent skill in the same change; tests drive it as scripts do, through `compileScript` (`packages/core/tests/openpencil-api/`).+## RendererCanvas is CanvasKit (Skia WASM) on a WebGL surface, not DOM.diff --git a/packages/core/README.md b/packages/core/README.mdindex c7992c008..333847826 100644--- a/packages/core/README.md+++ b/packages/core/README.md@@ -6,6 +6,18 @@ It depends on `@open-pencil/scene-graph`, `@open-pencil/pen`, `@open-pencil/kiwiImport the root barrel or the targeted subpaths listed in `package.json` `exports`, for example `@open-pencil/core/io`, `@open-pencil/core/geometry`, and `@open-pencil/core/canvaskit`.+Scripts get two globals through `compileScript` from `@open-pencil/core/tools`: `figma`, the Figma Plugin API over a document, and `openpencil` (`OpenPencilAPI` from `@open-pencil/core/openpencil-api`), what OpenPencil adds to it in the same style, such as making a component behave as a Reka UI control:++```ts+import { FigmaAPI } from '@open-pencil/core/figma-api'+import { compileScript } from '@open-pencil/core/tools'++await compileScript(`+ const set = figma.currentPage.findOne((n) => n.name === 'Switch')+ openpencil.setBehaviour(set, { kind: 'switch', values: { value: 'State' } })+`)(new FigmaAPI(graph))+```+- Programmable overview and SDK docs: https://openpencil.dev/programmable/- Source and issues: https://github.com/open-pencil/open-pencildiff --git a/packages/core/package.json b/packages/core/package.jsonindex f016adc18..cbd670838 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -47,6 +47,11 @@"import": "./dist/vector/index.js","default": "./dist/vector/index.js"},+ "./openpencil-api": {+ "types": "./dist/openpencil-api/index.d.ts",+ "import": "./dist/openpencil-api/index.js",+ "default": "./dist/openpencil-api/index.js"+ },"./figma-api": {"types": "./dist/figma-api/index.d.ts","import": "./dist/figma-api/index.js",@@ -174,7 +179,6 @@"acorn": "^8.18.0","canvaskit-wasm": "^0.41.1","culori": "^4.0.2",- "dedent": "^1.7.2","destr": "^2.0.5","diff": "^8.0.4","es-toolkit": "^1.52.0",diff --git a/packages/core/src/canvas/renderer/pipeline.ts b/packages/core/src/canvas/renderer/pipeline.tsindex 8e6b20ce7..942dd4804 100644--- a/packages/core/src/canvas/renderer/pipeline.ts+++ b/packages/core/src/canvas/renderer/pipeline.ts@@ -4,6 +4,7 @@ import type { SceneGraph } from '@open-pencil/scene-graph'import { computeDescendantVisualBounds } from '@open-pencil/scene-graph/geometry'import type { RenderOverlays, SkiaRenderer } from '#core/canvas/renderer'+import { playIslandRoots } from '#core/editor/play/islands'import type { EditorState } from '#core/editor/types'import { emitNavigationTrace } from '#core/profiler'@@ -54,12 +55,16 @@ export function renderFromEditorState(r.pageId = state.currentPageIdr.navigationPhase = state.navigation.phaser.navigationGeneration = state.navigation.generation+ // A previewing canvas shows the design as it runs: no selection, hover, or edit chrome.+ const previewing = state.play !== nullrender(r,graph,- state.selectedIds,+ previewing ? new Set<string>() : state.selectedIds,{- hoveredNodeId: state.hoveredNodeId,+ playing: previewing,+ playIslands: previewing ? new Set(playIslandRoots(graph, state.currentPageId)) : undefined,+ hoveredNodeId: previewing ? null : state.hoveredNodeId,measurementMode: state.measurementMode,enteredContainerId: state.enteredContainerId,editingTextId: state.editingTextId,@@ -94,7 +99,8 @@ function sceneContentDependsOnOverlay(overlays: RenderOverlays): boolean {overlays.dropTargetId != null ||overlays.rotationPreview != null ||overlays.editingTextId != null ||- overlays.nodeEditState != null+ overlays.nodeEditState != null ||+ overlays.playing === true)}@@ -165,6 +171,28 @@ function measure<T>(fn: () => T): { value: T; duration: number } {return { value, duration: now() - start }}+/** Labels, editing overlays, and rulers; a previewing canvas keeps only the rulers' chrome pass. */+function drawAboveScene(+ r: SkiaRenderer,+ canvas: Canvas,+ graph: SceneGraph,+ selectedIds: Set<string>,+ overlays: RenderOverlays,+ sceneVersion: number+): void {+ canvas.save()+ canvas.scale(r.dpr, r.dpr)+ r.labelCache.update(graph, r.pageId, sceneVersion, graph.positionPreviewVersion)+ if (!overlays.playing) drawLabelPass(r, canvas, graph, selectedIds, overlays)+ canvas.restore()++ canvas.save()+ canvas.scale(r.dpr, r.dpr)+ if (!overlays.playing) drawOverlayPass(r, canvas, graph, selectedIds, overlays)+ drawChromePass(r, canvas, graph, selectedIds, overlays)+ canvas.restore()+}+export function render(r: SkiaRenderer,graph: SceneGraph,@@ -273,21 +301,7 @@ export function render(canvas.restore()}- if (layer !== 'scene') {- canvas.save()- canvas.scale(r.dpr, r.dpr)- r.labelCache.update(graph, r.pageId, sceneVersion, graph.positionPreviewVersion)- drawLabelPass(r, canvas, graph, selectedIds, overlays)- canvas.restore()-- canvas.save()- canvas.scale(r.dpr, r.dpr)-- drawOverlayPass(r, canvas, graph, selectedIds, overlays)- drawChromePass(r, canvas, graph, selectedIds, overlays)-- canvas.restore()- }+ if (layer !== 'scene') drawAboveScene(r, canvas, graph, selectedIds, overlays, sceneVersion)p.beginPhase('render:flush')const { duration: flushDuration } = measure(() => r.surface.flush())diff --git a/packages/core/src/canvas/renderer/types.ts b/packages/core/src/canvas/renderer/types.tsindex 80dcb6de2..7a8f4674b 100644--- a/packages/core/src/canvas/renderer/types.ts+++ b/packages/core/src/canvas/renderer/types.ts@@ -28,6 +28,11 @@ export interface PresenceCursor {}export interface RenderOverlays {+ /** Whether the canvas previews: it draws the design without labels or editing outlines. */+ playing?: boolean+ /** Nodes a previewing canvas draws from its preview session instead of the document. */+ /** Layers a previewing canvas leaves to its live islands. */+ playIslands?: ReadonlySet<string>hoveredNodeId?: string | nullmeasurementMode?: MeasurementModeenteredContainerId?: string | nulldiff --git a/packages/core/src/canvas/scene.ts b/packages/core/src/canvas/scene.tsindex c15169a8a..1471a8b11 100644--- a/packages/core/src/canvas/scene.ts+++ b/packages/core/src/canvas/scene.ts@@ -125,7 +125,8 @@ function renderNodeContent(): void {if (node.type === 'SECTION') {r.renderSection(canvas, node, graph)- } else if (node.type === 'COMPONENT_SET') {+ } else if (node.type === 'COMPONENT_SET' && !overlays.playing) {+ // A previewing canvas draws a set as a plain frame, without its dashed editing border.r.renderComponentSet(canvas, node, graph)} else if (node.type === 'BOOLEAN_OPERATION') {renderBooleanOperation(r, canvas, node, graph)@@ -297,6 +298,16 @@ function nodeIsolationLayerBounds(: r.ck.LTRBRect(0, 0, node.width, node.height)}+/**+ * Whether the canvas draws a node itself: not hidden, a mask, blocked on fonts, drawn live by+ * node-edit mode, or left to a live island while the canvas previews.+ */+function drawsNode(node: SceneNode, overlays: RenderOverlays): boolean {+ if (node.internalOnly || !node.visible || node.isMask || fontManager.isNodeBlocked(node.id))+ return false+ return overlays.nodeEditState?.nodeId !== node.id && !overlays.playIslands?.has(node.id)+}+export function renderNode(r: SkiaRenderer,canvas: Canvas,@@ -308,18 +319,7 @@ export function renderNode(hasTransformedAncestor = false): void {const node = graph.getNode(nodeId)- if (- !node ||- node.internalOnly ||- !node.visible ||- node.isMask ||- fontManager.isNodeBlocked(nodeId)- ) {- return- }-- // Hide the node being edited in node-edit mode (overlay draws it live)- if (overlays.nodeEditState?.nodeId === nodeId) return+ if (!node || !drawsNode(node, overlays)) returnr._nodeCount++diff --git a/packages/core/src/editor/bridges/components.ts b/packages/core/src/editor/bridges/components.tsindex e4fd6756a..92b60fadd 100644--- a/packages/core/src/editor/bridges/components.ts+++ b/packages/core/src/editor/bridges/components.ts@@ -36,6 +36,11 @@ export function createComponentBridge(convertToSlot: components.convertToSlot,updateSlot: components.updateSlot,removeSlot: components.removeSlot,+ setBehaviour: components.setBehaviour,+ addBehaviourText: components.addBehaviourText,+ addBehaviourVariant: components.addBehaviourVariant,+ addBehaviourPart: components.addBehaviourPart,+ addBehaviourStates: components.addBehaviourStates,addPropertyDefinition: components.addPropertyDefinition,removePropertyDefinition: components.removePropertyDefinition,renamePropertyDefinition: components.renamePropertyDefinition,diff --git a/packages/core/src/editor/components.ts b/packages/core/src/editor/components.tsindex 6a626b4f9..6eadcefb0 100644--- a/packages/core/src/editor/components.ts+++ b/packages/core/src/editor/components.ts@@ -1,5 +1,6 @@import type { SceneNode } from '@open-pencil/scene-graph'+import { createBehaviourActions } from './components/behaviours'import { becomesComponent, componentWrapProps } from './components/create'import { createComponentFocusActions } from './components/focus'import { createComponentInstanceActions } from './components/instances'@@ -86,6 +87,7 @@ export function createComponentActions(ctx: EditorContext) {...variantActions,...componentPropertyActions,...createSlotActions(ctx),- ...createSlotAuthoringActions(ctx)+ ...createSlotAuthoringActions(ctx),+ ...createBehaviourActions(ctx, variantActions)}}diff --git a/packages/core/src/editor/components/behaviours/complete.ts b/packages/core/src/editor/components/behaviours/complete.tsnew file mode 100644index 000000000..13cfa86dd--- /dev/null+++ b/packages/core/src/editor/components/behaviours/complete.ts@@ -0,0 +1,266 @@+import {+ createComponentPropertyId,+ createSlotProperty,+ INTERACTION_STATES,+ readBehaviour,+ type Behaviour,+ type InteractionState,+ type SceneNode+} from '@open-pencil/scene-graph'++import { recordSubtreeEdit } from '#core/editor/components/slots/history'+import { VARIANT_SET_PADDING, variantSetProps } from '#core/editor/components/variant-set'+import type { createVariantActions } from '#core/editor/components/variants'+import { wrapSelectionInContainer } from '#core/editor/structure/container-wrap'+import type { EditorContext } from '#core/editor/types'++type VariantActions = Pick<+ ReturnType<typeof createVariantActions>,+ 'addPropertyDefinition' | 'duplicateVariant' | 'setVariantPropertyValue'+>++/** The components a behaviour's properties live in: a set's variants, or the component. */+function variantsOf(ctx: EditorContext, owner: SceneNode): SceneNode[] {+ return owner.type === 'COMPONENT_SET'+ ? ctx.graph.getChildren(owner.id).filter((child) => child.type === 'COMPONENT')+ : [owner]+}++/** The variant value a new states property draws each interaction state with. */+const STATE_VALUES: Record<InteractionState, string> = {+ rest: 'Default',+ hover: 'Hover',+ pressed: 'Pressed',+ focus: 'Focus',+ disabled: 'Disabled'+}+/** Names tried, in order, for a new states property, skipping ones the set already has. */+const STATE_PROPERTY_NAMES = ['State', 'Interaction', 'Interaction state']+/** Space between variants in a set laid out as a grid. */+const SET_GAP = 20++/**+ * Lay a set's variants out as rows, one per variant it had, each followed by its new state+ * copies, and fit the set around them, as one undo step.+ */+function layOutRows(ctx: EditorContext, setId: string, rows: string[][]): void {+ const nodes = rows.map((row) => row.flatMap((id) => ctx.graph.getNode(id) ?? []))+ const width = Math.max(...nodes.flat().map((node) => node.width))+ const ids = [setId, ...nodes.flat().map((node) => node.id)]+ const capture = () =>+ ids.flatMap((id) => {+ const node = ctx.graph.getNode(id)+ return node ? [{ id, x: node.x, y: node.y, width: node.width, height: node.height }] : []+ })+ const before = capture()+ let y = VARIANT_SET_PADDING+ for (const row of nodes) {+ for (const [column, node] of row.entries())+ ctx.graph.updateNode(node.id, { x: VARIANT_SET_PADDING + column * (width + SET_GAP), y })+ y += Math.max(...row.map((node) => node.height)) + SET_GAP+ }+ const columns = Math.max(...nodes.map((row) => row.length))+ ctx.graph.updateNode(setId, {+ width: VARIANT_SET_PADDING * 2 + columns * width + (columns - 1) * SET_GAP,+ height: y - SET_GAP + VARIANT_SET_PADDING+ })+ const after = capture()+ const apply = (frames: typeof before) => {+ for (const { id, ...frame } of frames) ctx.graph.updateNode(id, frame)+ ctx.requestRender()+ }+ ctx.undo.push({+ label: 'Arrange variants',+ forward: () => apply(after),+ inverse: () => apply(before)+ })+}++/** The first text layer of a component that no text property shows yet. */+function freeTextLayer(ctx: EditorContext, root: SceneNode): SceneNode | undefined {+ for (const child of ctx.graph.getChildren(root.id)) {+ if (child.type === 'INSTANCE') continue+ const bound = child.componentPropertyReferences.some((item) => item.field === 'TEXT')+ if (child.type === 'TEXT' && !bound) return child+ const nested = freeTextLayer(ctx, child)+ if (nested) return nested+ }+ return undefined+}++/**+ * Actions that create what a behaviour is missing and bind it in the same undo step, so a+ * bare component becomes a working control from the Behaviour section alone.+ */+export function createBehaviourCompletionActions(+ ctx: EditorContext,+ setBehaviour: (ownerId: string, behaviour: Behaviour | null) => void,+ variants: VariantActions+) {+ function owned(ownerId: string) {+ const owner = ctx.graph.getNode(ownerId)+ const behaviour = owner && readBehaviour(owner)+ return owner && behaviour ? { owner, behaviour } : null+ }++ /**+ * 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 {+ 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, () => {+ let defaultValue = name+ for (const variant of variantsOf(ctx, owner)) {+ const layer =+ freeTextLayer(ctx, variant) ??+ ctx.graph.createNode('TEXT', variant.id, {+ name,+ text: name,+ x: 12,+ y: 12,+ width: Math.max(1, variant.width - 24),+ height: 16,+ fontSize: 14,+ textAutoResize: 'HEIGHT'+ })+ defaultValue = layer.text || defaultValue+ ctx.graph.updateNode(layer.id, {+ componentPropertyReferences: [+ ...layer.componentPropertyReferences,+ { propertyId: id, field: 'TEXT' }+ ]+ })+ }+ const current = ctx.graph.getNode(owner.id) ?? owner+ ctx.graph.updateNode(owner.id, {+ componentPropertyDefinitions: [+ ...current.componentPropertyDefinitions,+ { id, name, type: 'TEXT', defaultValue }+ ]+ })+ })+ setBehaviour(owner.id, {+ ...behaviour,+ texts: { ...behaviour.texts, [valueId]: { propertyId: id } }+ })+ })+ return id+ }++ /**+ * Hold a boolean value in a new variant property `name` with values Off and On: every+ * variant is drawn Off, and a copy of each is added drawn On, ready to restyle. A lone main+ * component first becomes the only variant of a new set.+ */+ function addBehaviourVariant(ownerId: string, valueId: string, name: string): string | null {+ const found = owned(ownerId)+ if (!found) return null+ return ctx.undo.runBatch(`Add ${name} variants`, () => {+ const set = ownSet(found.owner, found.behaviour)+ const id = set && variants.addPropertyDefinition(set.id, name, 'VARIANT', 'Off')+ if (!set || !id) return null+ const rows = variantsOf(ctx, set).map((variant) => {+ const copy = variants.duplicateVariant(variant.id)+ if (copy) variants.setVariantPropertyValue(copy, id, 'On')+ return copy ? [variant.id, copy] : [variant.id]+ })+ layOutRows(ctx, set.id, rows)+ const behaviour = readBehaviour(ctx.graph.getNode(set.id) ?? set) ?? found.behaviour+ setBehaviour(set.id, {+ ...behaviour,+ booleans: { ...behaviour.booleans, [valueId]: { propertyId: id, on: 'On', off: 'Off' } }+ })+ ctx.setSelectedIds(new Set([set.id]))+ return id+ })+ }++ /**+ * Make a new frame the slot for a part named `name`: in the main component, or in each+ * 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, () => {+ for (const variant of variantsOf(ctx, owner)) {+ const frame = ctx.graph.createNode('FRAME', variant.id, {+ name,+ x: 12,+ y: 12,+ width: Math.max(1, Math.min(variant.width - 24, 48)),+ height: Math.max(1, Math.min(variant.height - 24, 24)),+ fills: []+ })+ createSlotProperty(ctx.graph, frame.id, id)+ }+ })+ setBehaviour(owner.id, { ...behaviour, parts: { ...behaviour.parts, [partId]: id } })+ })+ return id+ }++ /**+ * The set a behaviour's owner draws its variants in: the owner itself, or, for a lone main+ * component, a new set it becomes the only variant of, which takes over the behaviour.+ */+ function ownSet(owner: SceneNode, behaviour: Behaviour): SceneNode | undefined {+ if (owner.type === 'COMPONENT_SET') return owner+ const component = owner+ const parentId = component.parentId ?? ctx.state.currentPageId+ const setId = wrapSelectionInContainer(+ ctx,+ 'COMPONENT_SET',+ [component],+ variantSetProps(ctx.graph, [component], parentId, 'canvas')+ )+ if (!setId) return undefined+ setBehaviour(component.id, null)+ setBehaviour(setId, behaviour)+ return ctx.graph.getNode(setId)+ }++ /**+ * Give a control its interaction states: a new variant property with Default, Hover,+ * Pressed, Focus, and Disabled, a copy of each variant for every state but Default, ready to+ * restyle, and the behaviour's states bound to it. A lone main component first becomes the+ * only variant of a new set. Returns the new property's id.+ */+ function addBehaviourStates(ownerId: string): string | null {+ const found = owned(ownerId)+ if (!found) return null+ return ctx.undo.runBatch('Add states', () => {+ const set = ownSet(found.owner, found.behaviour)+ if (!set) return null+ const taken = new Set(set.componentPropertyDefinitions.map((item) => item.name))+ const name = STATE_PROPERTY_NAMES.find((item) => !taken.has(item))+ const id = name && variants.addPropertyDefinition(set.id, name, 'VARIANT', STATE_VALUES.rest)+ if (!id) return null+ const others = INTERACTION_STATES.filter((state) => state !== 'rest')+ const rows = variantsOf(ctx, set).map((variant) => [+ variant.id,+ ...others.flatMap((state) => {+ const copy = variants.duplicateVariant(variant.id)+ if (copy) variants.setVariantPropertyValue(copy, id, STATE_VALUES[state])+ return copy ?? []+ })+ ])+ layOutRows(ctx, set.id, rows)+ const behaviour = readBehaviour(ctx.graph.getNode(set.id) ?? set) ?? found.behaviour+ setBehaviour(set.id, { ...behaviour, states: { propertyId: id, ...STATE_VALUES } })+ ctx.setSelectedIds(new Set([set.id]))+ return id+ })+ }++ return { addBehaviourText, addBehaviourVariant, addBehaviourPart, addBehaviourStates }+}diff --git a/packages/core/src/editor/components/behaviours/index.ts b/packages/core/src/editor/components/behaviours/index.tsnew file mode 100644index 000000000..9b683588c--- /dev/null+++ b/packages/core/src/editor/components/behaviours/index.ts@@ -0,0 +1,34 @@+import { readBehaviour, withBehaviour, type Behaviour } from '@open-pencil/scene-graph'++import type { EditorContext } from '#core/editor/types'++import { createBehaviourCompletionActions } from './complete'++type VariantActions = Parameters<typeof createBehaviourCompletionActions>[2]++function behaviourEditLabel(before: Behaviour | null, after: Behaviour | null): string {+ if (!after) return 'Remove behaviour'+ return before ? 'Edit behaviour' : 'Add behaviour'+}++export function createBehaviourActions(ctx: EditorContext, variants: VariantActions) {+ /**+ * Set the behaviour a component or component set keeps, or remove it with null, as one undo+ * step. The panel composes the new behaviour; this only stores it.+ */+ function setBehaviour(ownerId: string, behaviour: Behaviour | null): void {+ const owner = ctx.graph.getNode(ownerId)+ if (!owner || (owner.type !== 'COMPONENT' && owner.type !== 'COMPONENT_SET')) return+ const before = structuredClone(owner.pluginData)+ const after = withBehaviour(owner, behaviour)+ const label = behaviourEditLabel(readBehaviour(owner), behaviour)+ const apply = (pluginData: typeof before) => {+ ctx.graph.updateNode(ownerId, { pluginData: structuredClone(pluginData) })+ ctx.requestRender()+ }+ apply(after)+ ctx.undo.push({ label, forward: () => apply(after), inverse: () => apply(before) })+ }++ return { setBehaviour, ...createBehaviourCompletionActions(ctx, setBehaviour, variants) }+}diff --git a/packages/core/src/editor/components/variant-set.ts b/packages/core/src/editor/components/variant-set.tsindex 8be8da7b0..64eef3442 100644--- a/packages/core/src/editor/components/variant-set.ts+++ b/packages/core/src/editor/components/variant-set.ts@@ -6,7 +6,7 @@ import {} from '@open-pencil/scene-graph'import { getAxisAlignedBoundsInParent } from '@open-pencil/scene-graph/coordinate'import { copyStrokes } from '@open-pencil/scene-graph/copy'-import { deriveSlashVariantProperties } from '@open-pencil/scene-graph/variant-properties'+import { deriveVariantProperties } from '@open-pencil/scene-graph/variant-properties'/*** How a new component set looks. Figma's Combine as variants command (`canvas`) pads the variants@@ -15,7 +15,8 @@ import { deriveSlashVariantProperties } from '@open-pencil/scene-graph/variant-p*/export type VariantSetStyle = 'canvas' | 'script'-const CANVAS_PADDING = 20+/** Space around the variants of a set made on the canvas. */+export const VARIANT_SET_PADDING = 20const CANVAS_STROKE: Stroke = {type: 'SOLID',color: { r: 138 / 255, g: 56 / 255, b: 245 / 255, a: 1 },@@ -34,7 +35,7 @@ export function variantSetProps(style: VariantSetStyle): Partial<SceneNode> {const bounds = getAxisAlignedBoundsInParent(components, parentId, graph)- const padding = style === 'canvas' ? CANVAS_PADDING : 0+ const padding = style === 'canvas' ? VARIANT_SET_PADDING : 0return {name: components[0]?.name.split('/')[0]?.trim() || 'Component Set',x: bounds.x - padding,@@ -47,13 +48,16 @@ export function variantSetProps(}}-/** Turns slash-separated names such as `Button/Primary` into the set's variant property. */+/**+ * Turns variant names into the set's variant properties, as Figma does: slash paths such as+ * `Button/Primary`, else `Property=Value` pairs such as `State=On, Size=Large`.+ */export function applyVariantProperties(graph: SceneGraph,components: readonly SceneNode[],setId: string): void {- const derived = deriveSlashVariantProperties([...components], createComponentPropertyId)+ const derived = deriveVariantProperties([...components], createComponentPropertyId)if (!derived) returnfor (const [nodeId, changes] of derived.variants) graph.updateNode(nodeId, changes)graph.updateNode(setId, { componentPropertyDefinitions: derived.definitions })diff --git a/packages/core/src/editor/components/variants/definitions.ts b/packages/core/src/editor/components/variants/definitions.tsnew file mode 100644index 000000000..f3ade16cb--- /dev/null+++ b/packages/core/src/editor/components/variants/definitions.ts@@ -0,0 +1,312 @@+import { omit } from 'es-toolkit/object'++import type { ComponentPropertyDefinition, ComponentPropertyType } from '@open-pencil/scene-graph'+import { createComponentPropertyId } from '@open-pencil/scene-graph'++import { assertNodeEditable } from '#core/editor/capabilities'+import type { EditorContext } from '#core/editor/types'++import {+ assertComponentSetEditable,+ captureVariantSnapshot,+ recordSnapshotChange,+ refreshVariantOptions,+ setVariantValues,+ updateVariantName+} from './history'+import {+ findExactVariant,+ getComponentSet,+ getComponentSetVariants,+ getVariantDefinitions,+ hasDuplicateCombination,+ variantValues,+ type VariantMutationResult+} from './model'++export function reorderPropertyDefinitions(+ ctx: EditorContext,+ componentSetId: string,+ propertyIds: string[]+): boolean {+ assertComponentSetEditable(ctx, componentSetId)+ const componentSet = getComponentSet(ctx.graph, componentSetId)+ const before = captureVariantSnapshot(ctx, componentSetId)+ if (!componentSet || !before) return false+ const definitionsById = new Map(+ componentSet.componentPropertyDefinitions.map((definition) => [definition.id, definition])+ )+ if (+ propertyIds.length !== definitionsById.size ||+ new Set(propertyIds).size !== definitionsById.size ||+ propertyIds.some((id) => !definitionsById.has(id))+ ) {+ return false+ }+ if (propertyIds.every((id, index) => componentSet.componentPropertyDefinitions[index]?.id === id))+ return true++ ctx.graph.updateNode(componentSetId, {+ componentPropertyDefinitions: propertyIds.flatMap((id) => {+ const definition = definitionsById.get(id)+ return definition ? [definition] : []+ })+ })+ for (const variant of getComponentSetVariants(ctx.graph, componentSetId))+ updateVariantName(ctx, componentSetId, variant)+ const after = captureVariantSnapshot(ctx, componentSetId)+ if (after) recordSnapshotChange(ctx, componentSetId, 'Reorder properties', before, after)+ return true+}++export function reorderVariantValues(+ ctx: EditorContext,+ componentSetId: string,+ propertyId: string,+ values: string[]+): boolean {+ assertComponentSetEditable(ctx, componentSetId)+ const componentSet = getComponentSet(ctx.graph, componentSetId)+ const definition = getVariantDefinitions(ctx.graph, componentSetId).find(+ (item) => item.id === propertyId+ )+ const currentValues = definition?.variantOptions ?? []+ const before = captureVariantSnapshot(ctx, componentSetId)+ if (!componentSet || !definition || !before) return false+ if (+ values.length !== currentValues.length ||+ new Set(values).size !== currentValues.length ||+ values.some((value) => !currentValues.includes(value))+ ) {+ return false+ }+ if (values.every((value, index) => currentValues[index] === value)) return true++ ctx.graph.updateNode(componentSetId, {+ componentPropertyDefinitions: componentSet.componentPropertyDefinitions.map((item) =>+ item.id === propertyId+ ? {+ ...item,+ variantOptions: [...values],+ defaultValue: values[0] ?? ''+ }+ : item+ )+ })+ const after = captureVariantSnapshot(ctx, componentSetId)+ if (after) recordSnapshotChange(ctx, componentSetId, 'Reorder variant values', before, after)+ return true+}++export function addPropertyDefinition(+ ctx: EditorContext,+ componentSetId: string,+ name: string,+ type: ComponentPropertyType = 'VARIANT',+ defaultValue = ''+): string | undefined {+ assertComponentSetEditable(ctx, componentSetId)+ const node = getComponentSet(ctx.graph, componentSetId)+ const normalizedName = name.trim()+ if (!node || !normalizedName) return undefined+ if (node.componentPropertyDefinitions.some((definition) => definition.name === normalizedName)) {+ return undefined+ }++ const before = captureVariantSnapshot(ctx, componentSetId)+ if (!before) return undefined+ const id = createComponentPropertyId()+ const definition: ComponentPropertyDefinition = {+ id,+ name: normalizedName,+ type,+ defaultValue,+ variantOptions: type === 'VARIANT' ? [defaultValue] : undefined+ }+ ctx.graph.updateNode(componentSetId, {+ componentPropertyDefinitions: [...node.componentPropertyDefinitions, definition]+ })+ if (type === 'VARIANT') {+ for (const variant of getComponentSetVariants(ctx.graph, componentSetId)) {+ setVariantValues(ctx, componentSetId, variant.id, {+ ...variant.componentPropertyValues,+ [normalizedName]: defaultValue+ })+ }+ refreshVariantOptions(ctx, componentSetId)+ }+ const after = captureVariantSnapshot(ctx, componentSetId)+ if (after) recordSnapshotChange(ctx, componentSetId, 'Add property', before, after)+ return id+}++export function removePropertyDefinition(+ ctx: EditorContext,+ componentSetId: string,+ propertyId: string+): boolean {+ assertComponentSetEditable(ctx, componentSetId)+ const node = getComponentSet(ctx.graph, componentSetId)+ const definition = node?.componentPropertyDefinitions.find((item) => item.id === propertyId)+ const before = captureVariantSnapshot(ctx, componentSetId)+ if (!node || !definition || !before) return false++ ctx.graph.updateNode(componentSetId, {+ componentPropertyDefinitions: node.componentPropertyDefinitions.filter(+ (item) => item.id !== propertyId+ )+ })+ if (definition.type === 'VARIANT') {+ for (const variant of getComponentSetVariants(ctx.graph, componentSetId)) {+ setVariantValues(+ ctx,+ componentSetId,+ variant.id,+ omit(variant.componentPropertyValues, [definition.name])+ )+ }+ refreshVariantOptions(ctx, componentSetId)+ }+ const after = captureVariantSnapshot(ctx, componentSetId)+ if (after) recordSnapshotChange(ctx, componentSetId, 'Remove property', before, after)+ return true+}++export function renamePropertyDefinition(+ ctx: EditorContext,+ componentSetId: string,+ propertyId: string,+ newName: string+): boolean {+ assertComponentSetEditable(ctx, componentSetId)+ const node = getComponentSet(ctx.graph, componentSetId)+ const normalizedName = newName.trim()+ const definition = node?.componentPropertyDefinitions.find((item) => item.id === propertyId)+ const before = captureVariantSnapshot(ctx, componentSetId)+ if (!node || !definition || !before || !normalizedName) return false+ if (+ node.componentPropertyDefinitions.some(+ (item) => item.id !== propertyId && item.name === normalizedName+ )+ ) {+ return false+ }+ if (definition.name === normalizedName) return true++ ctx.graph.updateNode(componentSetId, {+ componentPropertyDefinitions: node.componentPropertyDefinitions.map((item) =>+ item.id === propertyId ? { ...item, name: normalizedName } : item+ )+ })+ if (definition.type === 'VARIANT') {+ for (const variant of getComponentSetVariants(ctx.graph, componentSetId)) {+ const value = variant.componentPropertyValues[definition.name] ?? ''+ setVariantValues(ctx, componentSetId, variant.id, {+ ...omit(variant.componentPropertyValues, [definition.name]),+ [normalizedName]: value+ })+ }+ }+ const after = captureVariantSnapshot(ctx, componentSetId)+ if (after) recordSnapshotChange(ctx, componentSetId, 'Rename property', before, after)+ return true+}++export function renameVariantValue(+ ctx: EditorContext,+ componentSetId: string,+ propertyId: string,+ previousValue: string,+ newValue: string+): boolean {+ assertComponentSetEditable(ctx, componentSetId)+ const definition = getVariantDefinitions(ctx.graph, componentSetId).find(+ (item) => item.id === propertyId+ )+ const normalizedValue = newValue.trim()+ const before = captureVariantSnapshot(ctx, componentSetId)+ const componentSet = getComponentSet(ctx.graph, componentSetId)+ if (+ !definition ||+ !componentSet ||+ !before ||+ !normalizedValue ||+ previousValue === normalizedValue+ )+ return false+ if (+ hasDuplicateCombination(ctx.graph, componentSetId, (variant) => ({+ ...variantValues(ctx.graph, componentSetId, variant),+ [definition.name]:+ variant.componentPropertyValues[definition.name] === previousValue+ ? normalizedValue+ : (variant.componentPropertyValues[definition.name] ?? '')+ }))+ ) {+ return false+ }++ ctx.graph.updateNode(componentSetId, {+ componentPropertyDefinitions: componentSet.componentPropertyDefinitions.map((item) =>+ item.id === propertyId+ ? {+ ...item,+ defaultValue: item.defaultValue === previousValue ? normalizedValue : item.defaultValue,+ variantOptions: item.variantOptions?.map((option) =>+ option === previousValue ? normalizedValue : option+ )+ }+ : item+ )+ })+ for (const variant of getComponentSetVariants(ctx.graph, componentSetId)) {+ if (variant.componentPropertyValues[definition.name] !== previousValue) continue+ setVariantValues(ctx, componentSetId, variant.id, {+ ...variant.componentPropertyValues,+ [definition.name]: normalizedValue+ })+ }+ refreshVariantOptions(ctx, componentSetId)+ const after = captureVariantSnapshot(ctx, componentSetId)+ if (after) recordSnapshotChange(ctx, componentSetId, 'Rename variant value', before, after)+ return true+}++export function setVariantPropertyValue(+ ctx: EditorContext,+ variantId: string,+ propertyId: string,+ value: string+): VariantMutationResult {+ assertNodeEditable(ctx.graph, variantId)+ const variant = ctx.graph.getNode(variantId)+ const componentSetId = variant?.parentId+ if (variant?.type !== 'COMPONENT' || !componentSetId) return { kind: 'invalid' }+ const definition = getVariantDefinitions(ctx.graph, componentSetId).find(+ (item) => item.id === propertyId+ )+ const normalizedValue = value.trim()+ const before = captureVariantSnapshot(ctx, componentSetId)+ if (!definition || !before || !normalizedValue) return { kind: 'invalid' }+ if (variant.componentPropertyValues[definition.name] === normalizedValue) {+ return { kind: 'unchanged' }+ }++ const requested = {+ ...variantValues(ctx.graph, componentSetId, variant),+ [definition.name]: normalizedValue+ }+ const conflicting = findExactVariant(ctx.graph, componentSetId, requested)+ if (conflicting && conflicting.id !== variantId) {+ return { kind: 'conflict', componentIds: [variantId, conflicting.id] }+ }++ setVariantValues(ctx, componentSetId, variantId, {+ ...variant.componentPropertyValues,+ [definition.name]: normalizedValue+ })+ refreshVariantOptions(ctx, componentSetId)+ const after = captureVariantSnapshot(ctx, componentSetId)+ if (after) recordSnapshotChange(ctx, componentSetId, `Change ${definition.name}`, before, after)+ return { kind: 'changed' }+}diff --git a/packages/core/src/editor/components/variants/history.ts b/packages/core/src/editor/components/variants/history.tsnew file mode 100644index 000000000..a18c28abf--- /dev/null+++ b/packages/core/src/editor/components/variants/history.ts@@ -0,0 +1,130 @@+import type { ComponentPropertyDefinition, SceneNode } from '@open-pencil/scene-graph'+import { buildVariantName } from '@open-pencil/scene-graph/variant-name'++import { assertNodeEditable } from '#core/editor/capabilities'+import type { EditorContext } from '#core/editor/types'++import {+ collectVariantOptions,+ getComponentSet,+ getComponentSetVariants,+ getVariantDefinitions+} from './model'++/** A component set's property definitions and its variants' values and names, for undo. */+export type VariantSnapshot = {+ definitions: ComponentPropertyDefinition[]+ variants: Map<string, Pick<SceneNode, 'componentPropertyValues' | 'name'>>+}++export function assertComponentSetEditable(ctx: EditorContext, componentSetId: string): void {+ assertNodeEditable(ctx.graph, componentSetId)+ for (const variant of getComponentSetVariants(ctx.graph, componentSetId)) {+ assertNodeEditable(ctx.graph, variant.id)+ }+}++export function captureVariantSnapshot(+ ctx: EditorContext,+ componentSetId: string+): VariantSnapshot | null {+ const componentSet = getComponentSet(ctx.graph, componentSetId)+ if (!componentSet) return null+ return {+ definitions: structuredClone(componentSet.componentPropertyDefinitions),+ variants: new Map(+ getComponentSetVariants(ctx.graph, componentSetId).map((variant) => [+ variant.id,+ {+ componentPropertyValues: structuredClone(variant.componentPropertyValues),+ name: variant.name+ }+ ])+ )+ }+}++export function restoreVariantSnapshot(+ ctx: EditorContext,+ componentSetId: string,+ snapshot: VariantSnapshot+): void {+ const componentSet = getComponentSet(ctx.graph, componentSetId)+ if (!componentSet) return+ ctx.graph.updateNode(componentSetId, {+ componentPropertyDefinitions: structuredClone(snapshot.definitions)+ })+ for (const [variantId, variantSnapshot] of snapshot.variants) {+ if (!ctx.graph.getNode(variantId)) continue+ ctx.graph.updateNode(variantId, {+ componentPropertyValues: structuredClone(variantSnapshot.componentPropertyValues),+ name: variantSnapshot.name+ })+ }+ ctx.requestRender()+}++export function recordSnapshotChange(+ ctx: EditorContext,+ componentSetId: string,+ label: string,+ before: VariantSnapshot,+ after: VariantSnapshot+): void {+ ctx.undo.push({+ label,+ forward: () => restoreVariantSnapshot(ctx, componentSetId, after),+ inverse: () => restoreVariantSnapshot(ctx, componentSetId, before)+ })+ ctx.requestRender()+}++export function updateVariantName(+ ctx: EditorContext,+ componentSetId: string,+ variant: SceneNode+): void {+ const values = Object.fromEntries(+ getVariantDefinitions(ctx.graph, componentSetId).map((definition) => [+ definition.name,+ variant.componentPropertyValues[definition.name] ?? ''+ ])+ )+ ctx.graph.updateNode(variant.id, { name: buildVariantName(values) })+}++export function refreshVariantOptions(ctx: EditorContext, componentSetId: string): void {+ const componentSet = getComponentSet(ctx.graph, componentSetId)+ if (!componentSet) return+ const collected = collectVariantOptions(ctx.graph, componentSetId)+ const definitions = componentSet.componentPropertyDefinitions.map((definition) => {+ if (definition.type !== 'VARIANT') return definition+ const present = collected.get(definition.name) ?? new Set<string>()+ const options = [+ ...(definition.variantOptions ?? []).filter((value) => present.has(value)),+ ...[...present].filter((value) => !definition.variantOptions?.includes(value))+ ]+ return {+ ...definition,+ defaultValue: options.includes(definition.defaultValue)+ ? definition.defaultValue+ : (options[0] ?? ''),+ variantOptions: options+ }+ })+ ctx.graph.updateNode(componentSetId, {+ componentPropertyDefinitions: definitions+ })+}++/** Set a variant's property values and rename it to match. */+export function setVariantValues(+ ctx: EditorContext,+ componentSetId: string,+ variantId: string,+ componentPropertyValues: Record<string, string>+): void {+ ctx.graph.updateNode(variantId, { componentPropertyValues })+ const updated = ctx.graph.getNode(variantId)+ if (updated) updateVariantName(ctx, componentSetId, updated)+}diff --git a/packages/core/src/editor/components/variants/index.ts b/packages/core/src/editor/components/variants/index.tsindex 5368f97e1..60c139469 100644--- a/packages/core/src/editor/components/variants/index.ts+++ b/packages/core/src/editor/components/variants/index.ts@@ -1,13 +1,4 @@-/* eslint-disable max-lines -- component variant operations share one atomic editor domain */--import { omit } from 'es-toolkit/object'--import type {- ComponentPropertyDefinition,- ComponentPropertyType,- SceneNode-} from '@open-pencil/scene-graph'-import { createComponentPropertyId } from '@open-pencil/scene-graph'+import type { ComponentPropertyDefinition, ComponentPropertyType } from '@open-pencil/scene-graph'import { buildVariantName, parseVariantName } from '@open-pencil/scene-graph/variant-name'import { assertNodeEditable } from '#core/editor/capabilities'@@ -15,547 +6,44 @@ import { restoreSubtree, snapshotSubtree } from '#core/editor/clipboard/subtree-import { reapplyInstanceComponentProperties } from '#core/editor/components/properties'import type { EditorContext } from '#core/editor/types'-export type VariantConflict = {- values: Record<string, string>- componentIds: string[]-}--export type VariantValidationIssue =- | ({ kind: 'duplicate-combination' } & VariantConflict)- | {- kind: 'missing-value'- propertyId: string- propertyName: string- componentIds: string[]- }--export type VariantTransitionResult =- | { kind: 'changed'; componentId: string }- | { kind: 'unchanged'; componentId: string }- | { kind: 'unavailable'; requested: Record<string, string> }- | { kind: 'invalid' }--export type VariantMutationResult =- | { kind: 'changed' }- | { kind: 'unchanged' }- | { kind: 'conflict'; componentIds: string[] }- | { kind: 'invalid' }--export type VariantOptionAvailability = {- value: string- available: boolean-}--type VariantSnapshot = {- definitions: ComponentPropertyDefinition[]- variants: Map<string, Pick<SceneNode, 'componentPropertyValues' | 'name'>>-}--function sortByCanvasPosition(a: SceneNode, b: SceneNode) {- return a.y - b.y || a.x - b.x || a.name.localeCompare(b.name)-}-+import {+ addPropertyDefinition,+ removePropertyDefinition,+ renamePropertyDefinition,+ renameVariantValue,+ reorderPropertyDefinitions,+ reorderVariantValues,+ setVariantPropertyValue+} from './definitions'+import {+ collectVariantOptions,+ findExactVariant,+ findVariantByValues,+ getComponentSet,+ getComponentSetVariantConflicts,+ getComponentSetVariants,+ getDefaultVariantForComponentSet,+ validateComponentSet,+ variantValues,+ type VariantOptionAvailability,+ type VariantTransitionResult+} from './model'++export type {+ VariantConflict,+ VariantMutationResult,+ VariantOptionAvailability,+ VariantTransitionResult,+ VariantValidationIssue+} from './model'++/**+ * Variant authoring on component sets: property definitions and values (in `definitions`), the+ * set's variants, and switching an instance between them. Each edit is one undo step.+ */export function createVariantActions(ctx: EditorContext) {- function getComponentSet(componentSetId: string): SceneNode | undefined {- const node = ctx.graph.getNode(componentSetId)- return node?.type === 'COMPONENT_SET' ? node : undefined- }-- function getVariantDefinitions(componentSetId: string): ComponentPropertyDefinition[] {- return (getComponentSet(componentSetId)?.componentPropertyDefinitions ?? []).filter(- (definition) => definition.type === 'VARIANT'- )- }-function getComponentSetPropertyDefs(componentSetId: string): ComponentPropertyDefinition[] {- return getComponentSet(componentSetId)?.componentPropertyDefinitions ?? []- }-- function getComponentSetVariants(componentSetId: string): SceneNode[] {- const node = getComponentSet(componentSetId)- if (!node) return []- return node.childIds- .map((id) => ctx.graph.getNode(id))- .filter((child): child is SceneNode => child?.type === 'COMPONENT')- }-- function assertComponentSetEditable(componentSetId: string): void {- assertNodeEditable(ctx.graph, componentSetId)- for (const variant of getComponentSetVariants(componentSetId)) {- assertNodeEditable(ctx.graph, variant.id)- }- }-- function captureVariantSnapshot(componentSetId: string): VariantSnapshot | null {- const componentSet = getComponentSet(componentSetId)- if (!componentSet) return null- return {- definitions: structuredClone(componentSet.componentPropertyDefinitions),- variants: new Map(- getComponentSetVariants(componentSetId).map((variant) => [- variant.id,- {- componentPropertyValues: structuredClone(variant.componentPropertyValues),- name: variant.name- }- ])- )- }- }-- function restoreVariantSnapshot(componentSetId: string, snapshot: VariantSnapshot): void {- const componentSet = getComponentSet(componentSetId)- if (!componentSet) return- ctx.graph.updateNode(componentSetId, {- componentPropertyDefinitions: structuredClone(snapshot.definitions)- })- for (const [variantId, variantSnapshot] of snapshot.variants) {- if (!ctx.graph.getNode(variantId)) continue- ctx.graph.updateNode(variantId, {- componentPropertyValues: structuredClone(variantSnapshot.componentPropertyValues),- name: variantSnapshot.name- })- }- ctx.requestRender()- }-- function recordSnapshotChange(- componentSetId: string,- label: string,- before: VariantSnapshot,- after: VariantSnapshot- ): void {- ctx.undo.push({- label,- forward: () => restoreVariantSnapshot(componentSetId, after),- inverse: () => restoreVariantSnapshot(componentSetId, before)- })- ctx.requestRender()- }-- function updateVariantName(componentSetId: string, variant: SceneNode): void {- const values = Object.fromEntries(- getVariantDefinitions(componentSetId).map((definition) => [- definition.name,- variant.componentPropertyValues[definition.name] ?? ''- ])- )- ctx.graph.updateNode(variant.id, { name: buildVariantName(values) })- }-- function refreshVariantOptions(componentSetId: string): void {- const componentSet = getComponentSet(componentSetId)- if (!componentSet) return- const collected = collectVariantOptions(componentSetId)- const definitions = componentSet.componentPropertyDefinitions.map((definition) => {- if (definition.type !== 'VARIANT') return definition- const present = collected.get(definition.name) ?? new Set<string>()- const options = [- ...(definition.variantOptions ?? []).filter((value) => present.has(value)),- ...[...present].filter((value) => !definition.variantOptions?.includes(value))- ]- return {- ...definition,- defaultValue: options.includes(definition.defaultValue)- ? definition.defaultValue- : (options[0] ?? ''),- variantOptions: options- }- })- ctx.graph.updateNode(componentSetId, { componentPropertyDefinitions: definitions })- }-- function hasDuplicateCombination(- componentSetId: string,- valuesForVariant: (variant: SceneNode) => Record<string, string>- ): boolean {- const seen = new Set<string>()- const definitions = getVariantDefinitions(componentSetId)- for (const variant of getComponentSetVariants(componentSetId)) {- const values = valuesForVariant(variant)- const key = definitions.map((definition) => values[definition.name] ?? '').join('\u0000')- if (seen.has(key)) return true- seen.add(key)- }- return false- }-- function reorderPropertyDefinitions(componentSetId: string, propertyIds: string[]): boolean {- assertComponentSetEditable(componentSetId)- const componentSet = getComponentSet(componentSetId)- const before = captureVariantSnapshot(componentSetId)- if (!componentSet || !before) return false- const definitionsById = new Map(- componentSet.componentPropertyDefinitions.map((definition) => [definition.id, definition])- )- if (- propertyIds.length !== definitionsById.size ||- new Set(propertyIds).size !== definitionsById.size ||- propertyIds.some((id) => !definitionsById.has(id))- ) {- return false- }- if (- propertyIds.every((id, index) => componentSet.componentPropertyDefinitions[index]?.id === id)- )- return true-- ctx.graph.updateNode(componentSetId, {- componentPropertyDefinitions: propertyIds.flatMap((id) => {- const definition = definitionsById.get(id)- return definition ? [definition] : []- })- })- for (const variant of getComponentSetVariants(componentSetId))- updateVariantName(componentSetId, variant)- const after = captureVariantSnapshot(componentSetId)- if (after) recordSnapshotChange(componentSetId, 'Reorder properties', before, after)- return true- }-- function reorderVariantValues(- componentSetId: string,- propertyId: string,- values: string[]- ): boolean {- assertComponentSetEditable(componentSetId)- const componentSet = getComponentSet(componentSetId)- const definition = getVariantDefinitions(componentSetId).find((item) => item.id === propertyId)- const currentValues = definition?.variantOptions ?? []- const before = captureVariantSnapshot(componentSetId)- if (!componentSet || !definition || !before) return false- if (- values.length !== currentValues.length ||- new Set(values).size !== currentValues.length ||- values.some((value) => !currentValues.includes(value))- ) {- return false- }- if (values.every((value, index) => currentValues[index] === value)) return true-- ctx.graph.updateNode(componentSetId, {- componentPropertyDefinitions: componentSet.componentPropertyDefinitions.map((item) =>- item.id === propertyId- ? { ...item, variantOptions: [...values], defaultValue: values[0] ?? '' }- : item- )- })- const after = captureVariantSnapshot(componentSetId)- if (after) recordSnapshotChange(componentSetId, 'Reorder variant values', before, after)- return true- }-- function addPropertyDefinition(- componentSetId: string,- name: string,- type: ComponentPropertyType = 'VARIANT',- defaultValue = ''- ): string | undefined {- assertComponentSetEditable(componentSetId)- const node = getComponentSet(componentSetId)- const normalizedName = name.trim()- if (!node || !normalizedName) return undefined- if (- node.componentPropertyDefinitions.some((definition) => definition.name === normalizedName)- ) {- return undefined- }-- const before = captureVariantSnapshot(componentSetId)- if (!before) return undefined- const id = createComponentPropertyId()- const definition: ComponentPropertyDefinition = {- id,- name: normalizedName,- type,- defaultValue,- variantOptions: type === 'VARIANT' ? [defaultValue] : undefined- }- ctx.graph.updateNode(componentSetId, {- componentPropertyDefinitions: [...node.componentPropertyDefinitions, definition]- })- if (type === 'VARIANT') {- for (const variant of getComponentSetVariants(componentSetId)) {- ctx.graph.updateNode(variant.id, {- componentPropertyValues: {- ...variant.componentPropertyValues,- [normalizedName]: defaultValue- }- })- const updated = ctx.graph.getNode(variant.id)- if (updated) updateVariantName(componentSetId, updated)- }- refreshVariantOptions(componentSetId)- }- const after = captureVariantSnapshot(componentSetId)- if (after) recordSnapshotChange(componentSetId, 'Add property', before, after)- return id- }-- function removePropertyDefinition(componentSetId: string, propertyId: string): boolean {- assertComponentSetEditable(componentSetId)- const node = getComponentSet(componentSetId)- const definition = node?.componentPropertyDefinitions.find((item) => item.id === propertyId)- const before = captureVariantSnapshot(componentSetId)- if (!node || !definition || !before) return false-- ctx.graph.updateNode(componentSetId, {- componentPropertyDefinitions: node.componentPropertyDefinitions.filter(- (item) => item.id !== propertyId- )- })- if (definition.type === 'VARIANT') {- for (const variant of getComponentSetVariants(componentSetId)) {- ctx.graph.updateNode(variant.id, {- componentPropertyValues: omit(variant.componentPropertyValues, [definition.name])- })- const updated = ctx.graph.getNode(variant.id)- if (updated) updateVariantName(componentSetId, updated)- }- refreshVariantOptions(componentSetId)- }- const after = captureVariantSnapshot(componentSetId)- if (after) recordSnapshotChange(componentSetId, 'Remove property', before, after)- return true- }-- function renamePropertyDefinition(- componentSetId: string,- propertyId: string,- newName: string- ): boolean {- assertComponentSetEditable(componentSetId)- const node = getComponentSet(componentSetId)- const normalizedName = newName.trim()- const definition = node?.componentPropertyDefinitions.find((item) => item.id === propertyId)- const before = captureVariantSnapshot(componentSetId)- if (!node || !definition || !before || !normalizedName) return false- if (- node.componentPropertyDefinitions.some(- (item) => item.id !== propertyId && item.name === normalizedName- )- ) {- return false- }- if (definition.name === normalizedName) return true-- ctx.graph.updateNode(componentSetId, {- componentPropertyDefinitions: node.componentPropertyDefinitions.map((item) =>- item.id === propertyId ? { ...item, name: normalizedName } : item- )- })- if (definition.type === 'VARIANT') {- for (const variant of getComponentSetVariants(componentSetId)) {- const value = variant.componentPropertyValues[definition.name] ?? ''- ctx.graph.updateNode(variant.id, {- componentPropertyValues: {- ...omit(variant.componentPropertyValues, [definition.name]),- [normalizedName]: value- }- })- const updated = ctx.graph.getNode(variant.id)- if (updated) updateVariantName(componentSetId, updated)- }- }- const after = captureVariantSnapshot(componentSetId)- if (after) recordSnapshotChange(componentSetId, 'Rename property', before, after)- return true- }-- function renameVariantValue(- componentSetId: string,- propertyId: string,- previousValue: string,- newValue: string- ): boolean {- assertComponentSetEditable(componentSetId)- const definition = getVariantDefinitions(componentSetId).find((item) => item.id === propertyId)- const normalizedValue = newValue.trim()- const before = captureVariantSnapshot(componentSetId)- const componentSet = getComponentSet(componentSetId)- if (- !definition ||- !componentSet ||- !before ||- !normalizedValue ||- previousValue === normalizedValue- )- return false- if (- hasDuplicateCombination(componentSetId, (variant) => ({- ...variantValues(componentSetId, variant),- [definition.name]:- variant.componentPropertyValues[definition.name] === previousValue- ? normalizedValue- : (variant.componentPropertyValues[definition.name] ?? '')- }))- ) {- return false- }-- ctx.graph.updateNode(componentSetId, {- componentPropertyDefinitions: componentSet.componentPropertyDefinitions.map((item) =>- item.id === propertyId- ? {- ...item,- defaultValue:- item.defaultValue === previousValue ? normalizedValue : item.defaultValue,- variantOptions: item.variantOptions?.map((option) =>- option === previousValue ? normalizedValue : option- )- }- : item- )- })- for (const variant of getComponentSetVariants(componentSetId)) {- if (variant.componentPropertyValues[definition.name] !== previousValue) continue- ctx.graph.updateNode(variant.id, {- componentPropertyValues: {- ...variant.componentPropertyValues,- [definition.name]: normalizedValue- }- })- const updated = ctx.graph.getNode(variant.id)- if (updated) updateVariantName(componentSetId, updated)- }- refreshVariantOptions(componentSetId)- const after = captureVariantSnapshot(componentSetId)- if (after) recordSnapshotChange(componentSetId, 'Rename variant value', before, after)- return true- }-- function setVariantPropertyValue(- variantId: string,- propertyId: string,- value: string- ): VariantMutationResult {- assertNodeEditable(ctx.graph, variantId)- const variant = ctx.graph.getNode(variantId)- const componentSetId = variant?.parentId- if (variant?.type !== 'COMPONENT' || !componentSetId) return { kind: 'invalid' }- const definition = getVariantDefinitions(componentSetId).find((item) => item.id === propertyId)- const normalizedValue = value.trim()- const before = captureVariantSnapshot(componentSetId)- if (!definition || !before || !normalizedValue) return { kind: 'invalid' }- if (variant.componentPropertyValues[definition.name] === normalizedValue) {- return { kind: 'unchanged' }- }-- const requested = {- ...variantValues(componentSetId, variant),- [definition.name]: normalizedValue- }- const conflicting = findExactVariant(componentSetId, requested)- if (conflicting && conflicting.id !== variantId) {- return { kind: 'conflict', componentIds: [variantId, conflicting.id] }- }-- ctx.graph.updateNode(variantId, {- componentPropertyValues: {- ...variant.componentPropertyValues,- [definition.name]: normalizedValue- }- })- const updated = ctx.graph.getNode(variantId)- if (updated) updateVariantName(componentSetId, updated)- refreshVariantOptions(componentSetId)- const after = captureVariantSnapshot(componentSetId)- if (after) recordSnapshotChange(componentSetId, `Change ${definition.name}`, before, after)- return { kind: 'changed' }- }-- function collectVariantOptions(componentSetId: string): Map<string, Set<string>> {- const options = new Map<string, Set<string>>()- for (const definition of getVariantDefinitions(componentSetId)) {- options.set(definition.name, new Set())- }- for (const variant of getComponentSetVariants(componentSetId)) {- for (const definition of getVariantDefinitions(componentSetId)) {- const value = variant.componentPropertyValues[definition.name]- if (value) options.get(definition.name)?.add(value)- }- }- return options- }-- function variantValues(componentSetId: string, variant: SceneNode): Record<string, string> {- return Object.fromEntries(- getVariantDefinitions(componentSetId).map((definition) => [- definition.name,- variant.componentPropertyValues[definition.name] ?? ''- ])- )- }-- function findVariantByValues(- componentSetId: string,- values: Record<string, string>- ): SceneNode | undefined {- return getComponentSetVariants(componentSetId)- .sort(sortByCanvasPosition)- .find((variant) =>- Object.entries(values).every(- ([propertyName, value]) => variant.componentPropertyValues[propertyName] === value- )- )- }-- function findExactVariant(- componentSetId: string,- values: Record<string, string>- ): SceneNode | undefined {- const definitions = getVariantDefinitions(componentSetId)- if (definitions.some((definition) => !Object.hasOwn(values, definition.name))) return undefined- return findVariantByValues(- componentSetId,- Object.fromEntries(- definitions.map((definition) => [definition.name, values[definition.name]])- )- )- }-- function getDefaultVariantForComponentSet(componentSetId: string): SceneNode | undefined {- return getComponentSetVariants(componentSetId).sort(sortByCanvasPosition)[0]- }-- function getComponentSetVariantConflicts(componentSetId: string): VariantConflict[] {- const definitions = getVariantDefinitions(componentSetId)- const byKey = new Map<string, VariantConflict>()- for (const variant of getComponentSetVariants(componentSetId)) {- const values = variantValues(componentSetId, variant)- const key = definitions- .map((definition) => `${definition.name}=${values[definition.name]}`)- .join('\u0000')- const entry = byKey.get(key) ?? { values, componentIds: [] }- entry.componentIds.push(variant.id)- byKey.set(key, entry)- }- return [...byKey.values()].filter((entry) => entry.componentIds.length > 1)- }-- function validateComponentSet(componentSetId: string): VariantValidationIssue[] {- const missing = getVariantDefinitions(componentSetId).flatMap((definition) => {- const componentIds = getComponentSetVariants(componentSetId)- .filter((variant) => !variant.componentPropertyValues[definition.name]?.trim())- .map((variant) => variant.id)- return componentIds.length > 0- ? [- {- kind: 'missing-value' as const,- propertyId: definition.id,- propertyName: definition.name,- componentIds- }- ]- : []- })- return [- ...missing,- ...getComponentSetVariantConflicts(componentSetId).map((conflict) => ({- kind: 'duplicate-combination' as const,- ...conflict- }))- ]+ return getComponentSet(ctx.graph, componentSetId)?.componentPropertyDefinitions ?? []}function getVariantOptionAvailability(@@ -568,12 +56,13 @@ export function createVariantActions(ctx: EditorContext) {if (instance?.type !== 'INSTANCE' || component?.type !== 'COMPONENT' || !componentSetId) {return []}- const options = collectVariantOptions(componentSetId).get(propertyName) ?? new Set<string>()+ const options =+ collectVariantOptions(ctx.graph, componentSetId).get(propertyName) ?? new Set<string>()return [...options].map((value) => ({value,available: Boolean(- findExactVariant(componentSetId, {- ...variantValues(componentSetId, component),+ findExactVariant(ctx.graph, componentSetId, {+ ...variantValues(ctx.graph, componentSetId, component),[propertyName]: value}))@@ -590,15 +79,19 @@ export function createVariantActions(ctx: EditorContext) {if (instance?.type !== 'INSTANCE' || !instance.componentId) return { kind: 'invalid' }const component = ctx.graph.getNode(instance.componentId)const componentSetId = component?.parentId- if (component?.type !== 'COMPONENT' || !componentSetId || !getComponentSet(componentSetId)) {+ if (+ component?.type !== 'COMPONENT' ||+ !componentSetId ||+ !getComponentSet(ctx.graph, componentSetId)+ ) {return { kind: 'invalid' }}const requested = {- ...variantValues(componentSetId, component),+ ...variantValues(ctx.graph, componentSetId, component),[propertyName]: newValue}- const target = findExactVariant(componentSetId, requested)+ const target = findExactVariant(ctx.graph, componentSetId, requested)if (!target) return { kind: 'unavailable', requested }if (target.id === instance.componentId) return { kind: 'unchanged', componentId: target.id }@@ -621,7 +114,11 @@ export function createVariantActions(ctx: EditorContext) {assertNodeEditable(ctx.graph, variantId)const variant = ctx.graph.getNode(variantId)const componentSetId = variant?.parentId- if (variant?.type !== 'COMPONENT' || !componentSetId || !getComponentSet(componentSetId)) {+ if (+ variant?.type !== 'COMPONENT' ||+ !componentSetId ||+ !getComponentSet(ctx.graph, componentSetId)+ ) {return undefined}const clone = ctx.graph.cloneTree(variantId, componentSetId, {@@ -650,7 +147,7 @@ export function createVariantActions(ctx: EditorContext) {}function addVariant(componentSetId: string): string | undefined {- const source = getDefaultVariantForComponentSet(componentSetId)+ const source = getDefaultVariantForComponentSet(ctx.graph, componentSetId)return source ? duplicateVariant(source.id) : undefined}@@ -659,7 +156,7 @@ export function createVariantActions(ctx: EditorContext) {const variant = ctx.graph.getNode(variantId)const componentSetId = variant?.parentIdif (variant?.type !== 'COMPONENT' || !componentSetId) return false- if (getComponentSetVariants(componentSetId).length <= 1) return false+ if (getComponentSetVariants(ctx.graph, componentSetId).length <= 1) return falseconst snapshots = snapshotSubtree(ctx.graph, variantId)ctx.graph.deleteNode(variantId)ctx.setSelectedIds(new Set([componentSetId]))@@ -683,20 +180,40 @@ export function createVariantActions(ctx: EditorContext) {return {getComponentSetPropertyDefs,- addPropertyDefinition,- removePropertyDefinition,- renamePropertyDefinition,- reorderPropertyDefinitions,- renameVariantValue,- reorderVariantValues,- setVariantPropertyValue,+ addPropertyDefinition: (+ componentSetId: string,+ name: string,+ type?: ComponentPropertyType,+ defaultValue?: string+ ) => addPropertyDefinition(ctx, componentSetId, name, type, defaultValue),+ removePropertyDefinition: (componentSetId: string, propertyId: string) =>+ removePropertyDefinition(ctx, componentSetId, propertyId),+ renamePropertyDefinition: (componentSetId: string, propertyId: string, newName: string) =>+ renamePropertyDefinition(ctx, componentSetId, propertyId, newName),+ reorderPropertyDefinitions: (componentSetId: string, propertyIds: string[]) =>+ reorderPropertyDefinitions(ctx, componentSetId, propertyIds),+ renameVariantValue: (+ componentSetId: string,+ propertyId: string,+ previousValue: string,+ newValue: string+ ) => renameVariantValue(ctx, componentSetId, propertyId, previousValue, newValue),+ reorderVariantValues: (componentSetId: string, propertyId: string, values: string[]) =>+ reorderVariantValues(ctx, componentSetId, propertyId, values),+ setVariantPropertyValue: (variantId: string, propertyId: string, value: string) =>+ setVariantPropertyValue(ctx, variantId, propertyId, value),parseVariantName,buildVariantName,- collectVariantOptions,- findVariantByValues,- getDefaultVariantForComponentSet,- getComponentSetVariantConflicts,- validateComponentSet,+ collectVariantOptions: (componentSetId: string) =>+ collectVariantOptions(ctx.graph, componentSetId),+ findVariantByValues: (componentSetId: string, values: Record<string, string>) =>+ findVariantByValues(ctx.graph, componentSetId, values),+ getDefaultVariantForComponentSet: (componentSetId: string) =>+ getDefaultVariantForComponentSet(ctx.graph, componentSetId),+ getComponentSetVariantConflicts: (componentSetId: string) =>+ getComponentSetVariantConflicts(ctx.graph, componentSetId),+ validateComponentSet: (componentSetId: string) =>+ validateComponentSet(ctx.graph, componentSetId),getVariantOptionAvailability,switchInstanceVariant,addVariant,diff --git a/packages/core/src/editor/components/variants/model.ts b/packages/core/src/editor/components/variants/model.tsnew file mode 100644index 000000000..9a5ed70e7--- /dev/null+++ b/packages/core/src/editor/components/variants/model.ts@@ -0,0 +1,185 @@+import type { ComponentPropertyDefinition, SceneGraph, SceneNode } from '@open-pencil/scene-graph'++export type VariantConflict = {+ values: Record<string, string>+ componentIds: string[]+}++export type VariantValidationIssue =+ | ({ kind: 'duplicate-combination' } & VariantConflict)+ | {+ kind: 'missing-value'+ propertyId: string+ propertyName: string+ componentIds: string[]+ }++export type VariantTransitionResult =+ | { kind: 'changed'; componentId: string }+ | { kind: 'unchanged'; componentId: string }+ | { kind: 'unavailable'; requested: Record<string, string> }+ | { kind: 'invalid' }++export type VariantMutationResult =+ | { kind: 'changed' }+ | { kind: 'unchanged' }+ | { kind: 'conflict'; componentIds: string[] }+ | { kind: 'invalid' }++export type VariantOptionAvailability = {+ value: string+ available: boolean+}++function sortByCanvasPosition(a: SceneNode, b: SceneNode) {+ return a.y - b.y || a.x - b.x || a.name.localeCompare(b.name)+}++export function getComponentSet(graph: SceneGraph, componentSetId: string): SceneNode | undefined {+ const node = graph.getNode(componentSetId)+ return node?.type === 'COMPONENT_SET' ? node : undefined+}++export function getVariantDefinitions(+ graph: SceneGraph,+ componentSetId: string+): ComponentPropertyDefinition[] {+ return (getComponentSet(graph, componentSetId)?.componentPropertyDefinitions ?? []).filter(+ (definition) => definition.type === 'VARIANT'+ )+}++export function getComponentSetVariants(graph: SceneGraph, componentSetId: string): SceneNode[] {+ const node = getComponentSet(graph, componentSetId)+ if (!node) return []+ return node.childIds+ .map((id) => graph.getNode(id))+ .filter((child): child is SceneNode => child?.type === 'COMPONENT')+}++export function variantValues(+ graph: SceneGraph,+ componentSetId: string,+ variant: SceneNode+): Record<string, string> {+ return Object.fromEntries(+ getVariantDefinitions(graph, componentSetId).map((definition) => [+ definition.name,+ variant.componentPropertyValues[definition.name] ?? ''+ ])+ )+}++export function collectVariantOptions(+ graph: SceneGraph,+ componentSetId: string+): Map<string, Set<string>> {+ const options = new Map<string, Set<string>>()+ for (const definition of getVariantDefinitions(graph, componentSetId)) {+ options.set(definition.name, new Set())+ }+ for (const variant of getComponentSetVariants(graph, componentSetId)) {+ for (const definition of getVariantDefinitions(graph, componentSetId)) {+ const value = variant.componentPropertyValues[definition.name]+ if (value) options.get(definition.name)?.add(value)+ }+ }+ return options+}++export function findVariantByValues(+ graph: SceneGraph,+ componentSetId: string,+ values: Record<string, string>+): SceneNode | undefined {+ return getComponentSetVariants(graph, componentSetId)+ .sort(sortByCanvasPosition)+ .find((variant) =>+ Object.entries(values).every(+ ([propertyName, value]) => variant.componentPropertyValues[propertyName] === value+ )+ )+}++export function findExactVariant(+ graph: SceneGraph,+ componentSetId: string,+ values: Record<string, string>+): SceneNode | undefined {+ const definitions = getVariantDefinitions(graph, componentSetId)+ if (definitions.some((definition) => !Object.hasOwn(values, definition.name))) return undefined+ return findVariantByValues(+ graph,+ componentSetId,+ Object.fromEntries(definitions.map((definition) => [definition.name, values[definition.name]]))+ )+}++export function getDefaultVariantForComponentSet(+ graph: SceneGraph,+ componentSetId: string+): SceneNode | undefined {+ return getComponentSetVariants(graph, componentSetId).sort(sortByCanvasPosition)[0]+}++export function getComponentSetVariantConflicts(+ graph: SceneGraph,+ componentSetId: string+): VariantConflict[] {+ const definitions = getVariantDefinitions(graph, componentSetId)+ const byKey = new Map<string, VariantConflict>()+ for (const variant of getComponentSetVariants(graph, componentSetId)) {+ const values = variantValues(graph, componentSetId, variant)+ const key = definitions+ .map((definition) => `${definition.name}=${values[definition.name]}`)+ .join('\u0000')+ const entry = byKey.get(key) ?? { values, componentIds: [] }+ entry.componentIds.push(variant.id)+ byKey.set(key, entry)+ }+ return [...byKey.values()].filter((entry) => entry.componentIds.length > 1)+}++export function validateComponentSet(+ graph: SceneGraph,+ componentSetId: string+): VariantValidationIssue[] {+ const missing = getVariantDefinitions(graph, componentSetId).flatMap((definition) => {+ const componentIds = getComponentSetVariants(graph, componentSetId)+ .filter((variant) => !variant.componentPropertyValues[definition.name]?.trim())+ .map((variant) => variant.id)+ return componentIds.length > 0+ ? [+ {+ kind: 'missing-value' as const,+ propertyId: definition.id,+ propertyName: definition.name,+ componentIds+ }+ ]+ : []+ })+ return [+ ...missing,+ ...getComponentSetVariantConflicts(graph, componentSetId).map((conflict) => ({+ kind: 'duplicate-combination' as const,+ ...conflict+ }))+ ]+}++export function hasDuplicateCombination(+ graph: SceneGraph,+ componentSetId: string,+ valuesForVariant: (variant: SceneNode) => Record<string, string>+): boolean {+ const seen = new Set<string>()+ const definitions = getVariantDefinitions(graph, componentSetId)+ for (const variant of getComponentSetVariants(graph, componentSetId)) {+ const values = valuesForVariant(variant)+ const key = definitions.map((definition) => values[definition.name] ?? '').join('\u0000')+ if (seen.has(key)) return true+ seen.add(key)+ }+ return false+}diff --git a/packages/core/src/editor/create.ts b/packages/core/src/editor/create.tsindex 40aca9073..501c3df7e 100644--- a/packages/core/src/editor/create.ts+++ b/packages/core/src/editor/create.ts@@ -33,6 +33,7 @@ import { createGuideActions } from './guides'import { createDesignIssueActions } from './issues'import { createNodeActions } from './nodes'import { createPageActions } from './pages'+import { createPlayActions } from './play/actions'import { createSelectionActions } from './selection'import { createShapeActions } from './shapes'import { createDefaultEditorState } from './state'@@ -233,6 +234,7 @@ export function createEditor(options?: EditorOptions) {const variables = createVariableActions(ctx)const vectorize = createVectorizeActions(ctx)const alignment = createAlignmentActions(ctx)+ const preview = createPlayActions(ctx)const clipboardBridge = createClipboardBridge(clipboard, selection)const componentBridge = createComponentBridge(components, selection, structure, pages)const structureBridge = createStructureBridge(structure, selection)@@ -357,6 +359,9 @@ export function createEditor(options?: EditorOptions) {// Alignment (align, flip, rotate)...alignment,+ // Preview: instances with a behaviour respond to the pointer on this canvas+ ...preview,+// Bitmap-to-vector replacement...vectorize,diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.tsindex d4d1cf139..e95e24b69 100644--- a/packages/core/src/editor/index.ts+++ b/packages/core/src/editor/index.ts@@ -18,6 +18,9 @@ export type { PageSnapshot } from './history/snapshot'export { graphFromPageSnapshot } from './history/snapshot-graph'export type { ClipboardPayload, ClipboardSnapshot } from './clipboard/copy'export { resolvePasteTarget } from './clipboard/paste-target'+export { hasBehaviour, playIslandRoots } from './play/islands'+export { layerPath, resolvePlayState, type InstanceState } from './play/states'+export type { PlayState } from './play/actions'export type { Editor } from './create'export type { VariableTokenFields } from './variables'export { reapplyInstanceComponentProperties } from './components/properties'diff --git a/packages/core/src/editor/play/actions.ts b/packages/core/src/editor/play/actions.tsnew file mode 100644index 000000000..594099b60--- /dev/null+++ b/packages/core/src/editor/play/actions.ts@@ -0,0 +1,38 @@+import type { EditorContext } from '#core/editor/types'++/** A previewing canvas: its islands remount whenever the revision changes. */+export interface PlayState {+ revision: number+}++export function createPlayActions(ctx: EditorContext) {+ /** Preview this canvas: layers holding controls run as live components. */+ function startPlay(): void {+ if (ctx.state.play) return+ ctx.state.play = { revision: 0 }+ ctx.state.hoveredNodeId = null+ ctx.requestRepaint()+ }++ /** Go back to editing; the canvas draws every layer again. */+ function stopPlay(): void {+ if (!ctx.state.play) return+ ctx.state.play = null+ ctx.requestRepaint()+ }++ function togglePlay(): void {+ if (ctx.state.play) stopPlay()+ else startPlay()+ }++ /** Put every control back as designed by running the islands afresh. */+ function resetPlay(): void {+ if (ctx.state.play) ctx.state.play = { revision: ctx.state.play.revision + 1 }+ }++ // Another document's layers start from their designed state, not from the old islands'.+ ctx.onEditorEvent('graph:replaced', resetPlay)++ return { startPlay, stopPlay, togglePlay, resetPlay }+}diff --git a/packages/core/src/editor/play/islands.ts b/packages/core/src/editor/play/islands.tsnew file mode 100644index 000000000..43cabaa31--- /dev/null+++ b/packages/core/src/editor/play/islands.ts@@ -0,0 +1,32 @@+import {+ behaviourOwner,+ readBehaviour,+ type SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'++/** Whether an instance's main component, or its set, has a behaviour. */+export function hasBehaviour(graph: SceneGraph, node: SceneNode): boolean {+ if (node.type !== 'INSTANCE' || !node.componentId) return false+ const component = graph.getNode(node.componentId)+ const owner = component && behaviourOwner(graph, component)+ return !!owner && !!readBehaviour(owner)+}++function containsControl(graph: SceneGraph, node: SceneNode): boolean {+ if (hasBehaviour(graph, node)) return true+ return graph.getChildren(node.id).some((child) => containsControl(graph, child))+}++/**+ * The layers a previewing canvas runs as live islands: each top-level layer of the page that+ * holds an instance with a behaviour, so the controls inside it and the layout around them run+ * as real components. The canvas leaves them to the islands.+ */+export function playIslandRoots(graph: SceneGraph, pageId: string): string[] {+ return graph+ .getChildren(pageId)+ .filter((node) => node.visible && node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET')+ .filter((node) => containsControl(graph, node))+ .map((node) => node.id)+}diff --git a/packages/core/src/editor/play/states.ts b/packages/core/src/editor/play/states.tsnew file mode 100644index 000000000..2e7193278--- /dev/null+++ b/packages/core/src/editor/play/states.ts@@ -0,0 +1,187 @@+import {+ applyComponentPropertyValue,+ componentPropertyDefinitions,+ SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'++import { computeAllLayouts } from '#core/layout'++/** How one instance of an island is shown: the variant, properties, and layers it displays. */+export interface InstanceState {+ /** Variant values by property name the instance must show. */+ variants?: Record<string, string>+ /**+ * Variant values shown when the set draws them together with `variants`, such as a hover+ * state; otherwise those properties keep the instance's own values where a variant allows.+ */+ prefer?: Record<string, string>+ /** Component property values by property id, such as a boolean that shows a layer. */+ properties?: Record<string, string>+ /** Layers, by path below the island root, shown even where the design hides them. */+ reveal?: string[]+}++/**+ * A layer's path below a root: the names of the layers down to it, with the position among+ * same-named siblings when names repeat. It stays the same when a variant switch rebuilds an+ * instance's layers, so it identifies controls and keeps their DOM in place.+ */+export function layerPath(graph: SceneGraph, rootId: string, nodeId: string): string {+ const segments: string[] = []+ let current = graph.getNode(nodeId)+ while (current && current.id !== rootId) {+ const parent = current.parentId ? graph.getNode(current.parentId) : undefined+ const { id, name } = current+ const twins = parent ? graph.getChildren(parent.id).filter((child) => child.name === name) : []+ const index = twins.findIndex((child) => child.id === id)+ segments.unshift(twins.length > 1 ? `${name}#${index}` : name)+ current = parent+ }+ return segments.join('/')+}++function findByPath(graph: SceneGraph, rootId: string, path: string): SceneNode | undefined {+ let current = graph.getNode(rootId)+ for (const segment of path ? path.split('/') : []) {+ if (!current) return undefined+ const hash = segment.lastIndexOf('#')+ const name = hash === -1 ? segment : segment.slice(0, hash)+ const twins = graph.getChildren(current.id).filter((child) => child.name === name)+ current = twins.at(hash === -1 ? 0 : Number(segment.slice(hash + 1)))+ }+ return current+}++/** The root's layers and every component they show, so instances can switch variant. */+function closure(source: SceneGraph, rootId: string): Set<string> {+ const ids = new Set<string>()+ const visit = (id: string) => {+ if (ids.has(id)) return+ const node = source.getNode(id)+ if (!node) return+ ids.add(id)+ for (const child of node.childIds) visit(child)+ if (node.componentId) {+ const component = source.getNode(node.componentId)+ const set = component?.parentId ? source.getNode(component.parentId) : undefined+ visit(set?.type === 'COMPONENT_SET' ? set.id : node.componentId)+ }+ }+ visit(rootId)+ return ids+}++function copyGraph(source: SceneGraph, ids: Set<string>): SceneGraph {+ const graph = new SceneGraph()+ // Fills, images, and bindings resolve against the document's own tables.+ graph.variables = source.variables+ graph.variableCollections = source.variableCollections+ graph.activeMode = source.activeMode+ graph.images = source.images+ graph.documentColorSpace = source.documentColorSpace+ for (const id of ids) {+ const node = source.getNode(id)+ if (!node) continue+ const copy = structuredClone(node)+ graph.nodes.set(id, copy)+ if (copy.type === 'INSTANCE' && copy.componentId) {+ const instances = graph.instanceIndex.get(copy.componentId) ?? new Set<string>()+ instances.add(id)+ graph.instanceIndex.set(copy.componentId, instances)+ }+ }+ return graph+}++/**+ * The variant of the instance's set that shows `required`, and `prefer` too when one does, and+ * otherwise keeps as many of the instance's values as it can.+ */+function variantFor(+ graph: SceneGraph,+ instance: SceneNode,+ required: Record<string, string>,+ prefer: Record<string, string>+): SceneNode | undefined {+ let current = instance.componentId ? graph.getNode(instance.componentId) : undefined+ while (current?.type === 'INSTANCE' && current.componentId)+ current = graph.getNode(current.componentId)+ const set = current?.parentId ? graph.getNode(current.parentId) : undefined+ if (current?.type !== 'COMPONENT' || set?.type !== 'COMPONENT_SET') return undefined+ const values = current.componentPropertyValues+ const variants = graph.getChildren(set.id).filter((variant) => variant.type === 'COMPONENT')+ const showing = (wanted: Record<string, string>) => (variant: SceneNode) =>+ Object.entries(wanted).every(([key, value]) => variant.componentPropertyValues[key] === value)+ const kept = (variant: SceneNode) =>+ Object.entries(values).filter(([key, value]) => variant.componentPropertyValues[key] === value)+ .length+ const best = (candidates: SceneNode[]) =>+ candidates.reduce<SceneNode | undefined>(+ (found, variant) => (!found || kept(variant) > kept(found) ? variant : found),+ undefined+ )+ return (+ best(variants.filter(showing({ ...required, ...prefer }))) ??+ best(variants.filter(showing(required)))+ )+}++/** Let auto layout size a changed layer's ancestors again, not as a `.fig` file recorded them. */+function reflow(graph: SceneGraph, nodeId: string): void {+ let current = graph.getNode(nodeId)+ while (current) {+ if (current.derivedLayout) graph.updateNode(current.id, { derivedLayout: null })+ current = current.parentId ? graph.getNode(current.parentId) : undefined+ }+}++function applyState(+ graph: SceneGraph,+ rootId: string,+ instance: SceneNode,+ state: InstanceState+): void {+ if (state.variants || state.prefer) {+ const variant = variantFor(graph, instance, state.variants ?? {}, state.prefer ?? {})+ if (variant && variant.id !== instance.componentId) {+ graph.swapInstanceComponent(instance.id, variant.id)+ reflow(graph, instance.id)+ }+ }+ for (const [propertyId, value] of Object.entries(state.properties ?? {})) {+ const definition = componentPropertyDefinitions(graph, instance).find(+ (item) => item.id === propertyId+ )+ if (!definition) continue+ applyComponentPropertyValue(graph, instance.id, definition, value)+ reflow(graph, instance.id)+ }+ for (const path of state.reveal ?? []) {+ const layer = findByPath(graph, rootId, path)+ if (layer && !layer.visible) {+ graph.updateNode(layer.id, { visible: true })+ reflow(graph, layer.id)+ }+ }+}++/**+ * A private graph of the layer `rootId` with its instances shown in the given states, by layer+ * path below the root, and laid out again. Outer instances are applied before the layers inside+ * them, since a variant switch rebuilds what an instance contains. The document is untouched.+ */+export function resolvePlayState(+ source: SceneGraph,+ rootId: string,+ states: ReadonlyMap<string, InstanceState>+): SceneGraph {+ const graph = copyGraph(source, closure(source, rootId))+ const ordered = [...states].sort(([a], [b]) => a.split('/').length - b.split('/').length)+ for (const [path, state] of ordered) {+ const instance = findByPath(graph, rootId, path)+ if (instance?.type === 'INSTANCE') applyState(graph, rootId, instance, state)+ }+ computeAllLayouts(graph, rootId)+ return graph+}diff --git a/packages/core/src/editor/state/view.ts b/packages/core/src/editor/state/view.tsindex 4d96f6fb0..1565517d2 100644--- a/packages/core/src/editor/state/view.ts+++ b/packages/core/src/editor/state/view.ts@@ -28,7 +28,8 @@ export function createDefaultEditorViewState(pageId: string): EditorViewState {enteredContainerId: null,nodeEditState: null,cursorCanvasX: null,- cursorCanvasY: null+ cursorCanvasY: null,+ play: null}}diff --git a/packages/core/src/editor/types.ts b/packages/core/src/editor/types.tsindex 3bcaf67fb..2419c8e6e 100644--- a/packages/core/src/editor/types.ts+++ b/packages/core/src/editor/types.ts@@ -17,6 +17,7 @@ import type { GuideOverlayState } from '#core/canvas/guides/types'import type { DesignIssueOverlay } from '#core/canvas/issues/types'import type { RulerTheme, SkiaRenderer } from '#core/canvas/renderer'import type { MeasurementMode, PresenceCursor, RenderOverlays } from '#core/canvas/renderer/types'+import type { PlayState } from '#core/editor/play/actions'import type { SnappingPreferences } from '#core/editor/preferences'import type { RotationPreview } from '#core/geometry'import type { TextEditor } from '#core/text/editor'@@ -96,6 +97,8 @@ export interface EditorViewState {nodeEditState?: RenderOverlays['nodeEditState'] | nullcursorCanvasX?: number | nullcursorCanvasY?: number | null+ /** This canvas's preview, or null while it edits. */+ play: PlayState | null}export type NavigationPhase = 'idle' | 'pan' | 'zoom' | 'momentum' | 'settling'diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 6e8e1ae9e..bf9d95829 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -69,6 +69,7 @@ export {} from '@open-pencil/scene-graph'export { FigmaAPI, FigmaNodeProxy, computeImageHash, type FigmaFontName } from './figma-api'+export { BehaviourHandle, OpenPencilAPI, type NodeRef } from './openpencil-api'export {ALL_TOOLS,CORE_TOOLS,diff --git a/packages/core/src/io/formats/fig/export.ts b/packages/core/src/io/formats/fig/export.tsindex 3c1cb15c4..10a66c41f 100644--- a/packages/core/src/io/formats/fig/export.ts+++ b/packages/core/src/io/formats/fig/export.ts@@ -15,7 +15,13 @@ import {import { initCodec, getCompiledSchema, getSchemaBytes } from '@open-pencil/kiwi/fig/codec'import type { NodeChange } from '@open-pencil/kiwi/fig/codec'import { decodeBinarySchema, compileSchema, ByteBuffer } from '@open-pencil/kiwi/schema-runtime'-import { ownsSlotContent, type SceneGraph } from '@open-pencil/scene-graph'+import {+ ownsSlotContent,+ readBehaviour,+ renameBehaviourProperties,+ withBehaviour,+ type SceneGraph+} from '@open-pencil/scene-graph'import { fractionalPosition } from '@open-pencil/scene-graph/order-keys'import type { GUID } from '@open-pencil/scene-graph/primitives'@@ -134,6 +140,21 @@ function assignComponentPropertyGuids(}}+/** Behaviours bind component properties by id, so they follow the ids' new GUIDs. */+function renameBehaviourPropertyIds(graph: SceneGraph, propertyIdToGuid: Map<string, GUID>): void {+ const rename = (propertyId: string) => {+ const guid = propertyIdToGuid.get(propertyId)+ return guid ? `${guid.sessionID}:${guid.localID}` : propertyId+ }+ for (const node of graph.getAllNodes()) {+ const behaviour = readBehaviour(node)+ if (behaviour)+ graph.updateNode(node.id, {+ pluginData: withBehaviour(node, renameBehaviourProperties(behaviour, rename))+ })+ }+}+function applyImportedCanvasFields(page: FigExportPage, canvasNc: KiwiNodeChange): void {if ('backgroundColor' in page.source.fig.rawNodeFields) {canvasNc.backgroundColor = structuredClone(page.source.fig.rawNodeFields.backgroundColor)@@ -428,6 +449,7 @@ async function writeFigFile(assignedGuidValues,nodeSourceGuidValues)+ renameBehaviourPropertyIds(graph, propertyIdToGuid)for (const entry of canvasEntries) nodeChanges.push(entry.canvasNc)diff --git a/packages/core/src/library/snapshot.ts b/packages/core/src/library/snapshot.tsindex a1872c556..0a95f3de7 100644--- a/packages/core/src/library/snapshot.ts+++ b/packages/core/src/library/snapshot.ts@@ -1,4 +1,4 @@-import { cloneNodeProps, SceneGraph } from '@open-pencil/scene-graph'+import { cloneNodeProps, contentPluginData, SceneGraph } from '@open-pencil/scene-graph'import type { SceneNode } from '@open-pencil/scene-graph'import { contentHash } from './hash'@@ -15,8 +15,7 @@ const VOLATILE_NODE_FIELDS = new Set(['textPicture','derivedTextGlyphs','derivedLayout',- 'librarySource',- 'pluginData'+ 'librarySource'])function assetKey(node: SceneNode): string {@@ -50,11 +49,11 @@ function addSnapshotNode(): void {const node = source.getNode(sourceId)if (!node) return- const created = target.createNode(- node.type,- targetParentId,- cloneNodeProps(node, node.componentId)- )+ const created = target.createNode(node.type, targetParentId, {+ ...cloneNodeProps(node, node.componentId),+ // A behaviour or other plugin content belongs to the asset; where it came from does not.+ pluginData: contentPluginData(node.pluginData)+ })mappedIds.set(sourceId, created.id)for (const childId of node.childIds)addSnapshotNode(source, target, childId, created.id, mappedIds)@@ -172,7 +171,13 @@ export function canonicalLibraryNode(key !== 'name' &&key !== 'symbolDescription')- .map(([key, value]) => [key, normalizedLibraryField(key, value)])+ .map(([key, value]) => [+ key,+ // Plugin content such as a behaviour is part of the asset; its bookkeeping is not.+ key === 'pluginData'+ ? contentPluginData(node.pluginData)+ : normalizedLibraryField(key, value)+ ]))const component = node.componentId ? graph.getNode(node.componentId) : undefinedconst dependencyKey =diff --git a/packages/core/src/openpencil-api/behaviours.ts b/packages/core/src/openpencil-api/behaviours.tsnew file mode 100644index 000000000..ec49eab24--- /dev/null+++ b/packages/core/src/openpencil-api/behaviours.ts@@ -0,0 +1,172 @@+import {+ behaviourFromSpec,+ behaviourOwner,+ behaviourToSpec,+ createComponentPropertyId,+ createSlotProperty,+ emptyBehaviour,+ missingBindings,+ readBehaviour,+ slotOwner,+ slotPropertyId,+ withBehaviour,+ type Behaviour,+ type BehaviourKind,+ type BehaviourNumberSettings,+ type BehaviourSpec,+ type SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'++/** A node as scripts pass it: a Figma API node, or its id. */+export type NodeRef = { readonly id: string } | string++export function nodeOf(graph: SceneGraph, ref: NodeRef): SceneNode {+ const id = typeof ref === 'string' ? ref : ref.id+ const node = graph.getNode(id)+ if (!node) throw new Error(`No node ${id}`)+ return node+}++/** The component or component set that keeps a node's behaviour: a variant's set, or itself. */+function ownerOf(graph: SceneGraph, ref: NodeRef): SceneNode {+ const node = nodeOf(graph, ref)+ const owner = behaviourOwner(graph, node)+ if (!owner) throw new Error(`${node.name} is not a main component or component set`)+ return owner+}++/**+ * Make a frame of a main component a slot, as Create slot does, and return the slot property's+ * name; a frame that already is one keeps its slot.+ */+export function makeSlot(graph: SceneGraph, ref: NodeRef): string {+ const frame = nodeOf(graph, ref)+ if (!slotPropertyId(frame) && !createSlotProperty(graph, frame.id, createComponentPropertyId()))+ throw new Error(+ `${frame.name} cannot become a slot: it must be a frame inside a main component`+ )+ const id = slotPropertyId(nodeOf(graph, frame.id))+ const owner = slotOwner(graph, frame)+ return owner?.componentPropertyDefinitions.find((item) => item.id === id)?.name ?? frame.name+}++/**+ * A component's behaviour as scripts edit it, in the style of the Figma API: properties read the+ * current behaviour by name, and every change is written to the document at once.+ */+export class BehaviourHandle {+ constructor(+ private readonly graph: SceneGraph,+ private readonly ownerId: string+ ) {}++ private get owner(): SceneNode {+ return nodeOf(this.graph, this.ownerId)+ }++ private get stored(): Behaviour {+ const behaviour = readBehaviour(this.owner)+ if (!behaviour) throw new Error(`${this.owner.name} no longer has a behaviour`)+ return behaviour+ }++ private write(behaviour: Behaviour | null): void {+ this.graph.updateNode(this.ownerId, { pluginData: withBehaviour(this.owner, behaviour) })+ }++ private change(edit: (spec: BehaviourSpec) => BehaviourSpec): this {+ this.write(behaviourFromSpec(this.graph, this.owner, edit(this.spec)))+ return this+ }++ /** The id of the component or component set that keeps the behaviour. */+ get id(): string {+ return this.ownerId+ }++ get kind(): BehaviourKind {+ return this.stored.kind+ }++ /** The behaviour with properties and slots by name, as `openpencil.setBehaviour` takes it. */+ get spec(): BehaviourSpec {+ return behaviourToSpec(this.graph, this.owner, this.stored)+ }++ /** Required values and parts still unbound, by id, as the Behaviour section's chip counts them. */+ get missing(): string[] {+ return missingBindings(this.graph, this.owner, this.stored)+ }++ /** The variant property that draws interaction states, by name, or null for none. */+ get states(): string | null {+ const states = this.spec.states+ if (!states) return null+ return typeof states === 'string' ? states : states.property+ }++ set states(property: string | null) {+ this.change(({ states: _states, ...spec }) => (property ? { ...spec, states: property } : spec))+ }++ /**+ * Hold a boolean or text value in the property named `property`; for a variant property,+ * `on` and `off` name its values, guessed from names like On and Off when left out.+ */+ bindValue(valueId: string, property: string, values: { on?: string; off?: string } = {}): this {+ return this.change((spec) => ({+ ...spec,+ values: { ...spec.values, [valueId]: { property, ...values } }+ }))+ }++ /** Set a number value's range: its minimum, maximum, step, and default. */+ setNumber(valueId: string, settings: Partial<BehaviourNumberSettings>): this {+ return this.change((spec) => ({+ ...spec,+ numbers: { ...spec.numbers, [valueId]: { ...spec.numbers?.[valueId], ...settings } }+ }))+ }++ /**+ * Make a slot the part `partId`: a slot property by name, or a frame of the component, which+ * becomes a slot first if it is not one.+ */+ bindPart(partId: string, slot: NodeRef): this {+ const name =+ typeof slot === 'string' && !this.graph.getNode(slot) ? slot : makeSlot(this.graph, slot)+ return this.change((spec) => ({ ...spec, parts: { ...spec.parts, [partId]: name } }))+ }++ /** Remove the behaviour; the component keeps its properties and slots. */+ remove(): void {+ this.write(null)+ }++ toJSON() {+ return { id: this.id, ...this.spec, missing: this.missing }+ }+}++/** The behaviour a node's component keeps, or null when it has none. */+export function getBehaviour(graph: SceneGraph, ref: NodeRef): BehaviourHandle | null {+ const owner = ownerOf(graph, ref)+ return readBehaviour(owner) ? new BehaviourHandle(graph, owner.id) : null+}++/**+ * Give a main component or component set a behaviour, replacing any it has: a kind with+ * nothing bound yet, or a whole spec by name.+ */+export function setBehaviour(+ graph: SceneGraph,+ ref: NodeRef,+ spec: BehaviourKind | BehaviourSpec+): BehaviourHandle {+ const owner = ownerOf(graph, ref)+ const behaviour =+ typeof spec === 'string' ? emptyBehaviour(spec) : behaviourFromSpec(graph, owner, spec)+ graph.updateNode(owner.id, { pluginData: withBehaviour(owner, behaviour) })+ return new BehaviourHandle(graph, owner.id)+}diff --git a/packages/core/src/openpencil-api/index.ts b/packages/core/src/openpencil-api/index.tsnew file mode 100644index 000000000..e2adf2a26--- /dev/null+++ b/packages/core/src/openpencil-api/index.ts@@ -0,0 +1,51 @@+import {+ BEHAVIOUR_CONTRACTS,+ BEHAVIOUR_KINDS,+ type BehaviourKind,+ type BehaviourSpec+} from '@open-pencil/scene-graph'++import type { FigmaAPI } from '#core/figma-api'++import {+ getBehaviour,+ makeSlot,+ setBehaviour,+ type BehaviourHandle,+ type NodeRef+} from './behaviours'++export { BehaviourHandle, type NodeRef } from './behaviours'++/**+ * What OpenPencil adds to the Figma Plugin API for scripts, as the `openpencil` global next to+ * `figma`: features Figma has no API for, in the same style. It edits the same document as the+ * `figma` it is made for.+ */+export class OpenPencilAPI {+ constructor(private readonly figma: FigmaAPI) {}++ /** The behaviour kinds, after Reka UI's primitives, with the values and parts each binds. */+ get behaviourKinds() {+ return BEHAVIOUR_KINDS.map((kind) => ({ kind, ...structuredClone(BEHAVIOUR_CONTRACTS[kind]) }))+ }++ /** The behaviour a node's main component keeps, or null; a variant reads its set's. */+ getBehaviour(node: NodeRef): BehaviourHandle | null {+ return getBehaviour(this.figma.graph, node)+ }++ /**+ * Give a main component or component set a behaviour, replacing any it has: a kind alone, or+ * a spec naming its properties and slots, such as+ * `{ kind: 'switch', values: { value: 'State' }, parts: { thumb: 'Thumb' }, states: 'Interaction' }`.+ */+ setBehaviour(node: NodeRef, spec: BehaviourKind | BehaviourSpec): BehaviourHandle {+ return setBehaviour(this.figma.graph, node, spec)+ }++ /** Make a frame of a main component a slot, as Create slot does; returns the slot's name. */+ createSlot(frame: NodeRef): string {+ return makeSlot(this.figma.graph, frame)+ }+}diff --git a/packages/core/src/tools/analyze.ts b/packages/core/src/tools/analyze.tsindex df136b341..b34337968 100644--- a/packages/core/src/tools/analyze.ts+++ b/packages/core/src/tools/analyze.ts@@ -12,7 +12,7 @@ export {export type { DocumentDiff, DocumentDiffOptions, LayerJSXChange } from './analyze/diff'export { evalCode } from './analyze/eval'export { lint, lintFix } from './analyze/lint'-export { wrapEvalCode } from './analyze/eval/wrap'+export { compileScript, wrapEvalCode } from './analyze/eval/wrap'export { analyzeOverlaps, computeOverlaps } from './analyze/overlaps'export type {AnalyzeOverlapsArgs,diff --git a/packages/core/src/tools/analyze/eval/index.ts b/packages/core/src/tools/analyze/eval/index.tsindex 04ac32ce5..f25ca749e 100644--- a/packages/core/src/tools/analyze/eval/index.ts+++ b/packages/core/src/tools/analyze/eval/index.ts@@ -2,12 +2,12 @@ import * as v from 'valibot'import { defineTool } from '#core/tools/schema'-import { wrapEvalCode } from './wrap'+import { compileScript } from './wrap'export const evalCode = defineTool({name: 'eval',description:- 'Execute JavaScript with full Figma Plugin API access. Use for operations not covered by other tools. The `figma` global is available.',+ 'Execute JavaScript with full Figma Plugin API access. Use for operations not covered by other tools. The `figma` global is the Figma Plugin API; the `openpencil` global adds what Figma has no API for, such as component behaviours (`openpencil.setBehaviour`, `openpencil.getBehaviour`, `openpencil.behaviourKinds`) and slots (`openpencil.createSlot`).',execution: { kind: 'async', mutation: 'document' },capabilities: ['document:read', 'document:write', 'code:execute'],availability: 'eval',@@ -16,13 +16,7 @@ export const evalCode = defineTool({}),execute: async (figma, { code }) => {- type AsyncFunctionConstructor = new (- ...args: string[]- ) => (...args: unknown[]) => Promise<unknown>- const AsyncFunction = Object.getPrototypeOf(async () => undefined)- .constructor as AsyncFunctionConstructor- const fn = new AsyncFunction('figma', wrapEvalCode(code))- const result = await fn(figma)+ const result = await compileScript(code)(figma)if (result && typeof result === 'object') {const toJSON = Reflect.get(result, 'toJSON')if (typeof toJSON === 'function') return toJSON.call(result)diff --git a/packages/core/src/tools/analyze/eval/wrap.ts b/packages/core/src/tools/analyze/eval/wrap.tsindex 0ce4d731b..6e72159eb 100644--- a/packages/core/src/tools/analyze/eval/wrap.ts+++ b/packages/core/src/tools/analyze/eval/wrap.ts@@ -1,5 +1,8 @@import { type Node, parse } from 'acorn'+import type { FigmaAPI } from '#core/figma-api'+import { OpenPencilAPI } from '#core/openpencil-api'+/*** Wrap eval code so the last bare expression is returned (REPL-style).*@@ -35,3 +38,16 @@ export function wrapEvalCode(code: string): string {return `return (async () => { ${trimmed} })()`}++type AsyncFunctionConstructor = new (...args: string[]) => (...args: unknown[]) => Promise<unknown>++/**+ * Compile a script for a document: it sees the `figma` global, the Figma Plugin API, and the+ * `openpencil` global, what OpenPencil adds to it, both over the same document.+ */+export function compileScript(code: string): (figma: FigmaAPI) => Promise<unknown> {+ const AsyncFunction = Object.getPrototypeOf(async () => undefined)+ .constructor as AsyncFunctionConstructor+ const run = new AsyncFunction('figma', 'openpencil', wrapEvalCode(code))+ return (figma) => run(figma, new OpenPencilAPI(figma))+}diff --git a/packages/core/src/tools/create.ts b/packages/core/src/tools/create.tsindex fad3783fd..803016fe7 100644--- a/packages/core/src/tools/create.ts+++ b/packages/core/src/tools/create.ts@@ -1,4 +1,5 @@export { createPage, createShape, createSlice } from './create/basic'+export { createSlot, getBehaviour, setBehaviour } from './create/behaviours'export {combineAsVariants,createComponent,diff --git a/packages/core/src/tools/create/behaviours.ts b/packages/core/src/tools/create/behaviours.tsnew file mode 100644index 000000000..bd63e9108--- /dev/null+++ b/packages/core/src/tools/create/behaviours.ts@@ -0,0 +1,81 @@+import * as v from 'valibot'++import { behaviourSpecSchema } from '@open-pencil/scene-graph'++import { OpenPencilAPI } from '#core/openpencil-api'+import { defineTool } from '#core/tools/schema'++const failure = (error: unknown) => ({+ error: error instanceof Error ? error.message : String(error)+})++export const setBehaviour = defineTool({+ name: 'set_behaviour',+ description:+ 'Make a main component or component set behave as a Reka UI control in preview and code, ' ++ 'naming its own properties and slots: e.g. { kind: "switch", values: { value: "State" }, ' ++ 'parts: { thumb: "Thumb" }, states: "Interaction" }. Variant on/off values are guessed from ' ++ 'names like On and Off unless given as { property, on, off }. Pass null to remove it. ' ++ 'Returns the behaviour and the required values and parts still missing; get_behaviour lists ' ++ 'every kind with its values and parts.',+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ id: v.pipe(+ v.string(),+ v.description('Main component or component set ID; a variant uses its set')+ ),+ behaviour: v.pipe(+ v.nullable(behaviourSpecSchema),+ v.description('The behaviour by property and slot names, or null to remove it')+ )+ }),+ execute: (figma, { id, behaviour }) => {+ try {+ const openpencil = new OpenPencilAPI(figma)+ if (behaviour) return openpencil.setBehaviour(id, behaviour).toJSON()+ openpencil.getBehaviour(id)?.remove()+ return { ok: true }+ } catch (error) {+ return failure(error)+ }+ }+})++export const createSlot = defineTool({+ name: 'create_slot',+ description:+ 'Make a frame inside a main component a slot, as Create slot does: instances can then hold ' ++ 'their own content in it, and a behaviour can bind it as a part. Returns the slot name.',+ execution: { kind: 'sync', mutation: 'document' },+ input: v.object({+ id: v.pipe(v.string(), v.description('Frame ID inside a main component'))+ }),+ execute: (figma, { id }) => {+ try {+ return { slot: new OpenPencilAPI(figma).createSlot(id) }+ } catch (error) {+ return failure(error)+ }+ }+})++export const getBehaviour = defineTool({+ name: 'get_behaviour',+ description:+ 'Read the behaviour of a main component, component set, or variant by property and slot ' ++ 'names, with the required values and parts still missing. Without an ID, list every ' ++ 'behaviour kind with the values and parts it binds.',+ execution: { kind: 'sync', mutation: 'none' },+ input: v.object({+ id: v.optional(v.pipe(v.string(), v.description('Component, set, or variant ID')))+ }),+ execute: (figma, { id }) => {+ const openpencil = new OpenPencilAPI(figma)+ if (!id) return { kinds: openpencil.behaviourKinds }+ try {+ return openpencil.getBehaviour(id)?.toJSON() ?? { behaviour: null }+ } catch (error) {+ return failure(error)+ }+ }+})diff --git a/packages/core/src/tools/create/components.ts b/packages/core/src/tools/create/components.tsindex 32a0f3400..dfd6dcaea 100644--- a/packages/core/src/tools/create/components.ts+++ b/packages/core/src/tools/create/components.ts@@ -45,7 +45,8 @@ export const combineAsVariants = defineTool({description:'Combine components sharing a parent into a component set (variant set). Components named ' +- '"Category/Value" (e.g. "Button/Primary") derive variant properties from the name segments.',+ 'as Figma names variants, "State=On, Size=Large", get those variant properties; names like ' ++ '"Button/Primary" derive a Variant property from the segments after the first slash.',execution: { kind: 'sync', mutation: 'document' },input: v.object({ids: v.pipe(v.array(v.string()), v.minLength(1), v.description('Component node IDs to combine'))diff --git a/packages/core/src/tools/index.ts b/packages/core/src/tools/index.tsindex 53bb8a3d2..258cabec2 100644--- a/packages/core/src/tools/index.ts+++ b/packages/core/src/tools/index.ts@@ -27,7 +27,13 @@ export {export { toolNumber } from './input'export { toolsToAI, buildDebugLog } from './ai-adapter'export type { ToolLogEntry, ToolDebugLog, AIAdapterOptions, StepBudget } from './ai-adapter'-export { calcClusterConfidence, diffDocuments, diffPageLayersJSX, wrapEvalCode } from './analyze'+export {+ calcClusterConfidence,+ compileScript,+ diffDocuments,+ diffPageLayersJSX,+ wrapEvalCode+} from './analyze'export type { DocumentDiff, DocumentDiffOptions, LayerJSXChange } from './analyze'export {VALID_OVERLAP_CATEGORIES,diff --git a/packages/core/src/tools/prompts/codegen.md b/packages/core/src/tools/prompts/codegen.mdindex 997d80fdb..d666878be 100644--- a/packages/core/src/tools/prompts/codegen.md+++ b/packages/core/src/tools/prompts/codegen.md@@ -49,6 +49,7 @@ For each component determine:- **Props** — what content varies between instances (text, color, icon, visibility)- **Variants** — if the component has multiple states (default/hover/active, small/medium/large)- **Slots** — where child content is injected+- **Behaviour** — `get_behaviour id=<component_id>` tells whether the designer made it a control, after Reka UI's primitives. Build such a component on that Reka primitive (`SwitchRoot` with `SwitchThumb`, `SliderRoot` with `SliderTrack`, `SliderRange`, and `SliderThumb`, `TabsRoot` with `TabsList`, `TabsTrigger`, and `TabsContent`, …): each part is the slot the behaviour names, its values are the properties it binds (`v-model` for the value, `disabled`), and its interaction states map to the variants for `data-state`, `:hover`, `:active`, `:focus-visible`, and `[data-disabled]`. Do not reimplement the control's keyboard and accessibility handling.### Step 3 — Extract tokensdiff --git a/packages/core/src/tools/prompts/index.ts b/packages/core/src/tools/prompts/index.tsindex 5dfbea8fa..41a7d8b02 100644--- a/packages/core/src/tools/prompts/index.ts+++ b/packages/core/src/tools/prompts/index.ts@@ -1,12 +1,9 @@-import dedent from 'dedent'-import { JSX_REFERENCE } from '@open-pencil/design-jsx'import codegen from './codegen.md?raw'-/** Keep frontend-code generation instructions distinct from scene-authoring syntax. */-export const CODEGEN_PROMPT = dedent`-${codegen.trim()}--${JSX_REFERENCE}-`+/**+ * Keep frontend-code generation instructions distinct from scene-authoring syntax. The+ * reference is joined verbatim: dedenting it would flatten its indented code examples.+ */+export const CODEGEN_PROMPT = [codegen.trim(), JSX_REFERENCE].join('\n\n')diff --git a/packages/core/src/tools/registry-extended.ts b/packages/core/src/tools/registry-extended.tsindex bd8b689a8..f5f1f4b20 100644--- a/packages/core/src/tools/registry-extended.ts+++ b/packages/core/src/tools/registry-extended.ts@@ -19,10 +19,13 @@ import {createVector,exposeInstanceSwap,combineAsVariants,+ createSlot,fetchIconsTool,+ getBehaviour,importSVG,insertIcon,- searchIconsTool+ searchIconsTool,+ setBehaviour} from './create'import {setBlend,@@ -130,6 +133,9 @@ export const EXTENDED_TOOLS: ToolDef[] = [createComponent,createInstance,exposeInstanceSwap,+ createSlot,+ getBehaviour,+ setBehaviour,createPage,createVector,createSlice,diff --git a/packages/core/tests/design-jsx/behaviours.test.ts b/packages/core/tests/design-jsx/behaviours.test.tsnew file mode 100644index 000000000..b0accf094--- /dev/null+++ b/packages/core/tests/design-jsx/behaviours.test.ts@@ -0,0 +1,161 @@+import { describe, expect, test } from 'bun:test'++import { getNodeOrThrow } from '#core-tests/helpers/assert'++import { renderJSX } from '@open-pencil/core/design-jsx'+import { sceneNodeToJSX } from '@open-pencil/design-jsx'+import {+ missingBindings,+ readBehaviour,+ SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'++async function render(jsx: string) {+ const graph = new SceneGraph()+ const [result] = await renderJSX(graph, jsx)+ const root = getNodeOrThrow(graph, result.id)+ const behaviour = readBehaviour(root)+ if (!behaviour) throw new Error(`${root.name} has no behaviour`)+ const names = (definitions: SceneNode['componentPropertyDefinitions']) =>+ definitions.map((item) => `${item.name}:${item.type}`)+ return { graph, root, behaviour, names, missing: missingBindings(graph, root, behaviour) }+}++describe('Reka UI elements in design JSX', () => {+ test('a Switch.Root with variants is a set whose thumb is one slot across its variants', async () => {+ const { graph, root, behaviour, missing } = await render(`+ <Switch.Root name="Switch" modelValue="State" states="Interaction">+ <Component name="State=Off, Interaction=Default" w={44} h={24}>+ <Switch.Thumb x={2} y={2} w={20} h={20} />+ </Component>+ <Component name="State=On, Interaction=Default" w={44} h={24}>+ <Switch.Thumb x={22} y={2} w={20} h={20} />+ </Component>+ <Component name="State=Off, Interaction=Hover" w={44} h={24}>+ <Switch.Thumb x={2} y={2} w={20} h={20} />+ </Component>+ </Switch.Root>+ `)+ expect(root.type).toBe('COMPONENT_SET')+ expect(behaviour.kind).toBe('switch')+ expect(behaviour.booleans.value).toMatchObject({ on: 'On', off: 'Off' })+ expect(behaviour.states).toMatchObject({ rest: 'Default', hover: 'Hover' })+ const thumbs = [...graph.getAllNodes()].filter((node) => node.name === 'Thumb')+ expect(thumbs).toHaveLength(3)+ expect(+ new Set(thumbs.map((thumb) => thumb.componentPropertyReferences[0]?.propertyId))+ ).toEqual(new Set([behaviour.parts.thumb]))+ expect(missing).toEqual([])+ })++ test('a TextField.Input becomes the field’s text property', async () => {+ const { root, behaviour, names, missing } = await render(`+ <TextField.Root name="Field" w={200} h={36}>+ <TextField.Input x={10} y={10}>Email</TextField.Input>+ </TextField.Root>+ `)+ expect(names(root.componentPropertyDefinitions)).toEqual(['Text:TEXT'])+ expect(behaviour.texts.value?.propertyId).toBe(root.componentPropertyDefinitions[0]?.id)+ expect(missing).toEqual([])+ })++ test('tab triggers and panels go in their List and Panels slots, the first panel showing', async () => {+ const { graph, root, behaviour, missing } = await render(`+ <Tabs.Root name="Tabs" w={240} flex="col">+ <Tabs.List flex="row" gap={8}>+ <Tabs.Trigger><Text>Account</Text></Tabs.Trigger>+ <Tabs.Trigger><Text>Password</Text></Tabs.Trigger>+ </Tabs.List>+ <Tabs.Content><Text>Your name</Text></Tabs.Content>+ <Tabs.Content><Text>Your password</Text></Tabs.Content>+ </Tabs.Root>+ `)+ expect(graph.getChildren(root.id).map((child) => child.name)).toEqual(['List', 'Panels'])+ const panels = graph.getChildren(graph.getChildren(root.id)[1]?.id ?? '')+ expect(panels.map((panel) => panel.visible)).toEqual([true, false])+ expect(Object.keys(behaviour.parts).sort()).toEqual(['list', 'panels'])+ expect(missing).toEqual([])+ })++ test('a radio group’s items are instances of its RadioGroup.Item component in an Items slot', async () => {+ const graph = new SceneGraph()+ const [radio] = await renderJSX(+ graph,+ `<RadioGroup.Item name="Radio" modelValue="Checked">+ <Component name="Checked=Off" w={20} h={20} />+ <Component name="Checked=On" w={20} h={20} />+ </RadioGroup.Item>`+ )+ const [group] = await renderJSX(+ graph,+ `<RadioGroup.Root name="Plan">+ <RadioGroup.Item of="${radio.id}" />+ <RadioGroup.Item of="${radio.id}" />+ </RadioGroup.Root>`+ )+ const root = getNodeOrThrow(graph, group.id)+ const [items] = graph.getChildren(root.id)+ expect(items?.name).toBe('Items')+ expect(graph.getChildren(items?.id ?? '').map((item) => item.type)).toEqual([+ 'INSTANCE',+ 'INSTANCE'+ ])+ expect(readBehaviour(getNodeOrThrow(graph, radio.id))?.kind).toBe('radio')+ const behaviour = readBehaviour(root)+ expect(behaviour && missingBindings(graph, root, behaviour)).toEqual([])+ })+})++describe('Reka UI elements in JSX export', () => {+ test('a switch set exports as Switch.Root with its thumb and renders back the same', async () => {+ const graph = new SceneGraph()+ const [first] = await renderJSX(+ graph,+ `<Switch.Root name="Switch" modelValue="State">+ <Component name="State=Off" w={44} h={24}><Switch.Thumb x={2} y={2} w={20} h={20} /></Component>+ <Component name="State=On" w={44} h={24}><Switch.Thumb x={22} y={2} w={20} h={20} /></Component>+ </Switch.Root>`+ )+ const code = sceneNodeToJSX(first.id, graph)+ expect(code).toContain('<Switch.Root')+ expect(code).toContain('modelValue={{ property: "State", on: "On", off: "Off" }}')+ expect(code.match(/<Switch\.Thumb/g)).toHaveLength(2)++ const [second] = await renderJSX(graph, code)+ const again = readBehaviour(getNodeOrThrow(graph, second.id))+ const before = readBehaviour(getNodeOrThrow(graph, first.id))+ expect(again?.kind).toBe('switch')+ expect(again?.booleans.value).toMatchObject({ on: 'On', off: 'Off' })+ expect(Object.keys(again?.parts ?? {})).toEqual(Object.keys(before?.parts ?? {}))+ })++ test('tabs and a radio group export their repeated parts and items as Reka writes them', async () => {+ const graph = new SceneGraph()+ const [radio] = await renderJSX(+ graph,+ `<RadioGroup.Item name="Radio" modelValue="Checked">+ <Component name="Checked=Off" w={20} h={20} />+ <Component name="Checked=On" w={20} h={20} />+ </RadioGroup.Item>`+ )+ const [group] = await renderJSX(+ graph,+ `<RadioGroup.Root name="Plan"><RadioGroup.Item of="${radio.id}" /></RadioGroup.Root>`+ )+ expect(sceneNodeToJSX(group.id, graph)).toContain(`<RadioGroup.Item of="${radio.id}" />`)++ const [tabs] = await renderJSX(+ graph,+ `<Tabs.Root name="Tabs">+ <Tabs.List><Tabs.Trigger><Text>One</Text></Tabs.Trigger></Tabs.List>+ <Tabs.Content><Text>First</Text></Tabs.Content>+ </Tabs.Root>`+ )+ const code = sceneNodeToJSX(tabs.id, graph)+ expect(code).toContain('<Tabs.List')+ expect(code).toContain('<Tabs.Trigger')+ expect(code).toContain('<Tabs.Content')+ expect(code).not.toContain('name="Panels"')+ })+})diff --git a/packages/core/tests/editor/components/behaviours.test.ts b/packages/core/tests/editor/components/behaviours.test.tsnew file mode 100644index 000000000..77e24dc69--- /dev/null+++ b/packages/core/tests/editor/components/behaviours.test.ts@@ -0,0 +1,191 @@+import { describe, expect, test } from 'bun:test'++import { createEditor } from '@open-pencil/core/editor'+import {+ emptyBehaviour,+ missingBindings,+ readBehaviour,+ type Behaviour+} from '@open-pencil/scene-graph'++describe('setBehaviour', () => {+ test('adds, edits, and removes as single undo steps', () => {+ const editor = createEditor()+ const set = editor.graph.createNode('COMPONENT_SET', editor.state.currentPageId, { name: 'Switch' })+ editor.setBehaviour(set.id, emptyBehaviour('switch'))+ expect(editor.undo.undoLabel).toBe('Add behaviour')+ editor.setBehaviour(set.id, { ...emptyBehaviour('switch'), parts: { thumb: 'x' } })+ expect(editor.undo.undoLabel).toBe('Edit behaviour')+ editor.setBehaviour(set.id, null)+ expect(readBehaviour(editor.graph.getNode(set.id) ?? set)).toBeNull()++ editor.undo.undo()+ expect(readBehaviour(editor.graph.getNode(set.id) ?? set)?.parts).toEqual({ thumb: 'x' })+ editor.undo.undo()+ editor.undo.undo()+ expect(readBehaviour(editor.graph.getNode(set.id) ?? set)).toBeNull()+ })+})++describe('completing a behaviour', () => {+ /** A main component drawn as a plain rectangle, as a designer starts one. */+ function bareComponent(kind: Behaviour['kind']) {+ const editor = createEditor()+ const component = editor.graph.createNode('COMPONENT', editor.state.currentPageId, {+ name: 'Field',+ width: 220,+ height: 120+ })+ editor.graph.createNode('RECTANGLE', component.id, { name: 'Box', width: 220, height: 120 })+ editor.setBehaviour(component.id, emptyBehaviour(kind))+ const behaviour = () => readBehaviour(editor.graph.getNode(component.id) ?? component)+ return { editor, component, behaviour }+ }++ test('a textarea drawn as a rectangle gets a text layer and property in one step', () => {+ const { editor, component, behaviour } = bareComponent('textarea')+ const undoDepth = editor.undo.undoLabel+ const id = editor.addBehaviourText(component.id, 'value', 'Text')+ if (!id) throw new Error('No text property')++ const text = editor.graph.getChildren(component.id).find((child) => child.type === 'TEXT')+ expect(text?.componentPropertyReferences).toEqual([{ propertyId: id, field: 'TEXT' }])+ expect(editor.graph.getNode(component.id)?.componentPropertyDefinitions).toEqual([+ { id, name: 'Text', type: 'TEXT', defaultValue: 'Text' }+ ])+ const current = behaviour()+ expect(current && missingBindings(editor.graph, component, current)).toEqual([])++ editor.undo.undo()+ expect(editor.undo.undoLabel).toBe(undoDepth)+ expect(editor.graph.getChildren(component.id).map((child) => child.type)).toEqual([+ 'RECTANGLE'+ ])+ expect(behaviour()?.texts).toEqual({})+ expect(editor.graph.getNode(component.id)?.componentPropertyDefinitions).toEqual([])+ })++ test('an existing text layer becomes the text instead of a new one', () => {+ const { editor, component } = bareComponent('textField')+ const label = editor.graph.createNode('TEXT', component.id, { name: 'Label', text: 'Email' })+ const id = editor.addBehaviourText(component.id, 'value', 'Text')+ expect(editor.graph.getChildren(component.id).filter((child) => child.type === 'TEXT')).toHaveLength(+ 1+ )+ expect(editor.graph.getNode(label.id)?.componentPropertyReferences).toEqual([+ { propertyId: id, field: 'TEXT' }+ ])+ expect(+ editor.graph.getNode(component.id)?.componentPropertyDefinitions[0]?.defaultValue+ ).toBe('Email')+ })++ test('a switch set gets Off and On variants of each variant in one step', () => {+ const editor = createEditor()+ const set = editor.graph.createNode('COMPONENT_SET', editor.state.currentPageId, {+ name: 'Switch'+ })+ editor.graph.createNode('COMPONENT', set.id, { name: 'Default', width: 40, height: 20 })+ editor.setBehaviour(set.id, emptyBehaviour('switch'))+ const undoDepth = editor.undo.undoLabel++ const id = editor.addBehaviourVariant(set.id, 'value', 'On')+ const variants = editor.graph.getChildren(set.id)+ expect(variants.map((variant) => variant.componentPropertyValues.On)).toEqual(['Off', 'On'])+ expect(readBehaviour(editor.graph.getNode(set.id) ?? set)?.booleans.value).toEqual({+ propertyId: id,+ on: 'On',+ off: 'Off'+ })++ editor.undo.undo()+ expect(editor.undo.undoLabel).toBe(undoDepth)+ expect(editor.graph.getChildren(set.id)).toHaveLength(1)+ })++ test('a slider gets a new slot frame for a missing part', () => {+ const { editor, component, behaviour } = bareComponent('slider')+ const id = editor.addBehaviourPart(component.id, 'track', 'Track')+ const frame = editor.graph.getChildren(component.id).find((child) => child.name === 'Track')+ expect(frame?.componentPropertyReferences).toEqual([{ propertyId: id, field: 'SLOT_CONTENT' }])+ expect(behaviour()?.parts.track).toBe(id)+ editor.undo.undo()+ expect(editor.graph.getChildren(component.id).map((child) => child.name)).toEqual(['Box'])+ })++ test('a lone slider gets state variants as a new set that keeps its behaviour, in one step', () => {+ const { editor, component } = bareComponent('slider')+ const track = editor.addBehaviourPart(component.id, 'track', 'Track')+ const page = editor.state.currentPageId+ const undoDepth = editor.undo.undoLabel++ const id = editor.addBehaviourStates(component.id)+ const set = editor.graph.getNode(component.parentId ?? '')+ if (set?.type !== 'COMPONENT_SET' || !id) throw new Error('No set')+ const variants = editor.graph.getChildren(set.id)+ expect(variants.map((variant) => variant.componentPropertyValues.State)).toEqual([+ 'Default',+ 'Hover',+ 'Pressed',+ 'Focus',+ 'Disabled'+ ])+ // Laid out side by side, inside the set.+ expect(new Set(variants.map((variant) => variant.x)).size).toBe(5)+ expect(set.width).toBeGreaterThan(5 * component.width)+ expect(readBehaviour(editor.graph.getNode(component.id) ?? component)).toBeNull()+ const behaviour = readBehaviour(set)+ expect(behaviour?.parts.track).toBe(track)+ expect(behaviour?.states).toEqual({+ propertyId: id,+ rest: 'Default',+ hover: 'Hover',+ pressed: 'Pressed',+ focus: 'Focus',+ disabled: 'Disabled'+ })++ editor.undo.undo()+ expect(editor.undo.undoLabel).toBe(undoDepth)+ expect(editor.graph.getNode(set.id)).toBeUndefined()+ expect(editor.graph.getNode(component.id)?.parentId).toBe(page)+ expect(readBehaviour(editor.graph.getNode(component.id) ?? component)?.parts.track).toBe(track)+ })++ test('a states property takes a free name when the set already has State', () => {+ const editor = createEditor()+ const set = editor.graph.createNode('COMPONENT_SET', editor.state.currentPageId, {+ name: 'Switch'+ })+ editor.graph.createNode('COMPONENT', set.id, { name: 'Default', width: 40, height: 20 })+ editor.setBehaviour(set.id, emptyBehaviour('switch'))+ editor.addBehaviourVariant(set.id, 'value', 'State')+ editor.addBehaviourStates(set.id)+ const names = editor.graph.getNode(set.id)?.componentPropertyDefinitions.map((item) => item.name)+ expect(names).toEqual(['State', 'Interaction'])+ expect(editor.graph.getChildren(set.id)).toHaveLength(10)+ })++ test('a lone switch gets Off and On variants as a new set', () => {+ const { editor, component } = bareComponent('switch')+ const id = editor.addBehaviourVariant(component.id, 'value', 'On')+ const set = editor.graph.getNode(component.parentId ?? '')+ expect(set?.type).toBe('COMPONENT_SET')+ expect(set && readBehaviour(set)?.booleans.value).toEqual({ propertyId: id, on: 'On', off: 'Off' })+ })++ test('a part added to a set is one slot in every variant', () => {+ const { editor, component } = bareComponent('slider')+ editor.addBehaviourStates(component.id)+ const set = editor.graph.getNode(component.parentId ?? '')+ if (!set) throw new Error('No set')+ const id = editor.addBehaviourPart(set.id, 'thumb', 'Thumb')+ const slots = editor.graph+ .getChildren(set.id)+ .map((variant) => editor.graph.getChildren(variant.id).find((child) => child.name === 'Thumb'))+ expect(slots).toHaveLength(5)+ for (const slot of slots)+ expect(slot?.componentPropertyReferences).toEqual([{ propertyId: id, field: 'SLOT_CONTENT' }])+ expect(readBehaviour(editor.graph.getNode(set.id) ?? set)?.parts.thumb).toBe(id)+ })+})diff --git a/packages/core/tests/editor/play/states.test.ts b/packages/core/tests/editor/play/states.test.tsnew file mode 100644index 000000000..6afd3aa77--- /dev/null+++ b/packages/core/tests/editor/play/states.test.ts@@ -0,0 +1,98 @@+import { describe, expect, test } from 'bun:test'++import {+ createEditor,+ layerPath,+ playIslandRoots,+ resolvePlayState+} from '@open-pencil/core/editor'+import { emptyBehaviour, instanceMainComponent, SceneGraph } from '@open-pencil/scene-graph'++/** A Switch set (State × Interaction) and a card frame holding an Off instance with a label. */+function switchCard() {+ const editor = createEditor()+ const graph = editor.graph+ const pageId = editor.state.currentPageId+ const set = graph.createNode('COMPONENT_SET', pageId, {+ name: 'Switch',+ componentPropertyDefinitions: [+ { id: 'state', name: 'State', type: 'VARIANT', defaultValue: 'Off', variantOptions: ['Off', 'On'] },+ {+ id: 'interaction',+ name: 'Interaction',+ type: 'VARIANT',+ defaultValue: 'Default',+ variantOptions: ['Default', 'Hover']+ }+ ]+ })+ const variant = (state: string, interaction: string) =>+ graph.createNode('COMPONENT', set.id, {+ name: `State=${state}, Interaction=${interaction}`,+ componentPropertyValues: { State: state, Interaction: interaction }+ })+ const off = variant('Off', 'Default')+ const on = variant('On', 'Default')+ const offHover = variant('Off', 'Hover')+ editor.setBehaviour(set.id, {+ ...emptyBehaviour('switch'),+ booleans: { value: { propertyId: 'state', on: 'On', off: 'Off' } }+ })+ const card = graph.createNode('FRAME', pageId, { name: 'Card', x: 400 })+ const instance = graph.createInstance(off.id, card.id)+ if (!instance) throw new Error('No instance')+ graph.updateNode(instance.id, { name: 'Wifi' })+ graph.createNode('FRAME', pageId, { name: 'Empty', x: 800 })+ return { graph, pageId, card, instance, off, on, offHover }+}++describe('preview islands', () => {+ test('a top-level layer holding a control is an island; main components and empty layers are not', () => {+ const { graph, pageId, card } = switchCard()+ expect(playIslandRoots(graph, pageId)).toEqual([card.id])+ })++ test('a state shows the matching variant on a private copy and leaves the document alone', () => {+ const { graph, card, instance, off, on } = switchCard()+ const path = layerPath(graph, card.id, instance.id)+ expect(path).toBe('Wifi')++ const shown = resolvePlayState(graph, card.id, new Map([[path, { variants: { State: 'On' } }]]))+ const copy = shown.getChildren(card.id)[0]+ expect(copy && instanceMainComponent(shown, copy)?.id).toBe(on.id)+ expect(instanceMainComponent(graph, instance)?.id).toBe(off.id)+ })++ test('a preferred state shows only where the set draws it with the required values', () => {+ const { graph, card, instance, on, offHover } = switchCard()+ const path = layerPath(graph, card.id, instance.id)+ const shownWith = (state: string) => {+ const shown = resolvePlayState(+ graph,+ card.id,+ new Map([[path, { variants: { State: state }, prefer: { Interaction: 'Hover' } }]])+ )+ const copy = shown.getChildren(card.id)[0]+ return copy && instanceMainComponent(shown, copy)?.id+ }+ expect(shownWith('Off')).toBe(offHover.id)+ // No hovered On variant: the switch shows On as designed.+ expect(shownWith('On')).toBe(on.id)+ })++ test('a control reveals a layer the design hides, such as a closed panel', () => {+ const { graph, card } = switchCard()+ const hidden = graph.createNode('FRAME', card.id, { name: 'Panel', visible: false })+ const shown = resolvePlayState(graph, card.id, new Map([['Wifi', { reveal: ['Panel'] }]]))+ expect(shown.getNode(hidden.id)?.visible).toBe(true)+ expect(graph.getNode(hidden.id)?.visible).toBe(false)+ })++ test('a replaced document previews from its designed state', () => {+ const editor = createEditor()+ editor.startPlay()+ editor.resetPlay()+ editor.replaceGraph(new SceneGraph())+ expect(editor.state.play).toEqual({ revision: 2 })+ })+})diff --git a/packages/core/tests/io/formats/fig/roundtrip/behaviours.test.ts b/packages/core/tests/io/formats/fig/roundtrip/behaviours.test.tsnew file mode 100644index 000000000..9a039a069--- /dev/null+++ b/packages/core/tests/io/formats/fig/roundtrip/behaviours.test.ts@@ -0,0 +1,68 @@+import { describe, expect, test } from 'bun:test'++import { exportFigFile, initCodec, parseFigFile } from '@open-pencil/core'+import { createEditor } from '@open-pencil/core/editor'+import {+ emptyBehaviour,+ guessInteractionStates,+ missingBindings,+ readBehaviour+} from '@open-pencil/scene-graph'++describe('.fig round trip of behaviours', () => {+ test('bindings follow the GUIDs their component properties get', async () => {+ await initCodec()+ const editor = createEditor()+ const pageId = editor.state.currentPageId+ const set = editor.graph.createNode('COMPONENT_SET', pageId, {+ name: 'Field',+ componentPropertyDefinitions: [+ {+ id: 'filled',+ name: 'Filled',+ type: 'VARIANT',+ defaultValue: 'No',+ variantOptions: ['No', 'Yes']+ },+ {+ id: 'interaction',+ name: 'Interaction',+ type: 'VARIANT',+ defaultValue: 'Default',+ variantOptions: ['Default', 'Focus']+ },+ { id: 'value', name: 'Value', type: 'TEXT', defaultValue: 'Email' }+ ]+ })+ for (const filled of ['No', 'Yes'])+ for (const interaction of ['Default', 'Focus']) {+ const variant = editor.graph.createNode('COMPONENT', set.id, {+ name: `Filled=${filled}, Interaction=${interaction}`,+ componentPropertyValues: { Filled: filled, Interaction: interaction }+ })+ editor.graph.createNode('TEXT', variant.id, {+ text: 'Email',+ componentPropertyReferences: [{ propertyId: 'value', field: 'TEXT' }]+ })+ }+ editor.setBehaviour(set.id, {+ ...emptyBehaviour('textField'),+ texts: { value: { propertyId: 'value' } },+ booleans: { filled: { propertyId: 'filled', on: 'Yes', off: 'No' } },+ states: guessInteractionStates('interaction', ['Default', 'Focus'])+ })+ expect(missingBindings(editor.graph, set, readBehaviour(set) ?? emptyBehaviour('button'))).toEqual([])++ const reopened = await parseFigFile((await exportFigFile(editor.graph)).buffer)+ const owner = [...reopened.nodes.values()].find((node) => node.name === 'Field')+ const behaviour = owner && readBehaviour(owner)+ if (!owner || !behaviour) throw new Error('Behaviour lost')+ expect(missingBindings(reopened, owner, behaviour)).toEqual([])+ const ids = new Map(owner.componentPropertyDefinitions.map((item) => [item.name, item.id]))+ expect(behaviour.texts.value.propertyId).toBe(ids.get('Value') ?? '')+ expect(behaviour.booleans.filled.propertyId).toBe(ids.get('Filled') ?? '')+ expect(behaviour.states?.propertyId).toBe(ids.get('Interaction'))+ // The document keeps its own ids.+ expect(readBehaviour(editor.graph.getNode(set.id) ?? set)?.texts.value.propertyId).toBe('value')+ })+})diff --git a/packages/core/tests/library/plugin-content.test.ts b/packages/core/tests/library/plugin-content.test.tsnew file mode 100644index 000000000..4cab12631--- /dev/null+++ b/packages/core/tests/library/plugin-content.test.ts@@ -0,0 +1,87 @@+import { describe, expect, test } from 'bun:test'++import { createLibraryRevision, materializeLibraryAsset } from '@open-pencil/core/library'+import {+ emptyBehaviour,+ OPEN_PENCIL_PLUGIN_DATA,+ pluginDataEntry,+ readBehaviour,+ SceneGraph,+ withBehaviour,+ type Behaviour+} from '@open-pencil/scene-graph'++const OTHER_PLUGIN = { pluginId: 'tokens-studio', key: 'theme', value: 'dark' }++/** A Switch set with a behaviour, plugin data of another plugin, and a stale library source. */+function switchLibrary(behaviour: Behaviour) {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const set = graph.createNode('COMPONENT_SET', page.id, {+ name: 'Switch',+ componentKey: 'switch',+ componentPropertyDefinitions: [+ {+ id: 'state',+ name: 'State',+ type: 'VARIANT',+ defaultValue: 'Off',+ variantOptions: ['Off', 'On']+ }+ ]+ })+ for (const value of ['Off', 'On'])+ graph.createNode('COMPONENT', set.id, {+ name: `State=${value}`,+ componentKey: `switch-${value}`,+ componentPropertyValues: { State: value }+ })+ const stale = pluginDataEntry(OPEN_PENCIL_PLUGIN_DATA.librarySource, {+ identity: { libraryId: 'elsewhere', assetKey: 'switch', revisionId: 'old' },+ sourceNodeId: null,+ readOnly: true+ })+ graph.updateNode(set.id, {+ pluginData: [...withBehaviour(set, behaviour), OTHER_PLUGIN, stale]+ })+ return graph+}++const SWITCH: Behaviour = {+ ...emptyBehaviour('switch'),+ booleans: { value: { propertyId: 'state', on: 'On', off: 'Off' } }+}++describe('plugin content in libraries', () => {+ test('a published control keeps its behaviour and other plugins’ data, not bookkeeping', async () => {+ const revision = await createLibraryRevision({+ libraryId: 'controls',+ name: 'Controls',+ graph: switchLibrary(SWITCH)+ })+ const consumer = new SceneGraph()+ const { componentSetId } = materializeLibraryAsset(consumer, revision, 'switch')+ const set = consumer.getNode(componentSetId ?? '')+ if (!set) throw new Error('Switch not inserted')++ expect(readBehaviour(set)).toEqual(SWITCH)+ expect(set.pluginData).toContainEqual(OTHER_PLUGIN)+ expect(set.pluginData.map((entry) => entry.key)).not.toContain(+ OPEN_PENCIL_PLUGIN_DATA.librarySource.key+ )+ })++ test('changing only a behaviour changes the asset, so instances are offered the update', async () => {+ const hash = async (behaviour: Behaviour) =>+ (+ await createLibraryRevision({+ libraryId: 'controls',+ name: 'Controls',+ graph: switchLibrary(behaviour)+ })+ ).manifest.assets.find((asset) => asset.key === 'switch')?.contentHash++ expect(await hash(SWITCH)).toBe(await hash(structuredClone(SWITCH)))+ expect(await hash({ ...SWITCH, kind: 'toggle' })).not.toBe(await hash(SWITCH))+ })+})diff --git a/packages/core/tests/openpencil-api/behaviours.test.ts b/packages/core/tests/openpencil-api/behaviours.test.tsnew file mode 100644index 000000000..7ea455b26--- /dev/null+++ b/packages/core/tests/openpencil-api/behaviours.test.ts@@ -0,0 +1,71 @@+import { describe, expect, test } from 'bun:test'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import { compileScript } from '@open-pencil/core/tools'+import { readBehaviour, SceneGraph } from '@open-pencil/scene-graph'++/** Run a script against a fresh document with a two-variant Switch set and a thumb frame. */+async function run(code: string) {+ const graph = new SceneGraph()+ const figma = new FigmaAPI(graph)+ await compileScript(`+ const off = figma.createComponent()+ off.name = 'State=Off'+ const on = figma.createComponent()+ on.name = 'State=On'+ const set = figma.combineAsVariants([off, on], figma.currentPage)+ set.name = 'Switch'+ const thumb = figma.createFrame()+ thumb.name = 'Thumb'+ off.appendChild(thumb)+ `)(figma)+ const set = graph.getAllNodes().find((node) => node.name === 'Switch')+ if (!set) throw new Error('No switch set')+ const result = await compileScript(code)(figma)+ return { graph, set, result }+}++describe('openpencil scripting API', () => {+ test('a script gives a component set a behaviour by property and slot names', async () => {+ const { graph, set, result } = await run(`+ const set = figma.currentPage.findOne((node) => node.name === 'Switch')+ const thumb = set.findOne((node) => node.name === 'Thumb')+ const behaviour = openpencil.setBehaviour(set, 'switch')+ behaviour.bindValue('value', 'State').bindPart('thumb', thumb)+ return { spec: behaviour.spec, missing: behaviour.missing }+ `)+ expect(result).toEqual({+ spec: {+ kind: 'switch',+ values: { value: { property: 'State', on: 'On', off: 'Off' } },+ parts: { thumb: 'Thumb' }+ },+ missing: []+ })+ expect(readBehaviour(graph.getNode(set.id) ?? set)?.kind).toBe('switch')+ })++ test('a variant reads its set’s behaviour, and removing it leaves the component alone', async () => {+ const { graph, set, result } = await run(`+ const set = figma.currentPage.findOne((node) => node.name === 'Switch')+ openpencil.setBehaviour(set, { kind: 'switch', values: { value: 'State' } })+ const variant = set.children[0]+ const kind = openpencil.getBehaviour(variant).kind+ openpencil.getBehaviour(set).remove()+ return [kind, openpencil.getBehaviour(set), openpencil.behaviourKinds.length]+ `)+ expect(result).toEqual(['switch', null, 15])+ expect(graph.getNode(set.id)?.componentPropertyDefinitions.map((item) => item.name)).toContain(+ 'State'+ )+ })++ test('names the component lacks fail with what it has', async () => {+ await expect(+ run(`+ const set = figma.currentPage.findOne((node) => node.name === 'Switch')+ openpencil.setBehaviour(set, { kind: 'switch', values: { value: 'Checked' } })+ `)+ ).rejects.toThrow('named "Checked"; the component has "State"')+ })+})diff --git a/packages/core/tests/tools/create/behaviours.test.ts b/packages/core/tests/tools/create/behaviours.test.tsnew file mode 100644index 000000000..9e977712b--- /dev/null+++ b/packages/core/tests/tools/create/behaviours.test.ts@@ -0,0 +1,58 @@+import { describe, expect, test } from 'bun:test'++import { FigmaAPI } from '@open-pencil/core/figma-api'+import { ALL_TOOLS } from '@open-pencil/core/tools'+import { SceneGraph } from '@open-pencil/scene-graph'++function tool(name: string) {+ const found = ALL_TOOLS.find((item) => item.name === name)+ if (!found) throw new Error(`No tool ${name}`)+ return (figma: FigmaAPI, args: Record<string, unknown>) => found.execute(figma, args)+}+const createSlot = { execute: tool('create_slot') }+const setBehaviour = { execute: tool('set_behaviour') }+const getBehaviour = { execute: tool('get_behaviour') }++/** A component with a Checked BOOLEAN property and a Box frame, as an agent finds it. */+function checkbox() {+ const graph = new SceneGraph()+ const figma = new FigmaAPI(graph)+ const component = figma.createComponent()+ component.name = 'Checkbox'+ component.addComponentProperty('Checked', 'BOOLEAN', false)+ const box = figma.createFrame()+ box.name = 'Box'+ component.appendChild(box)+ return { figma, component, box }+}++describe('behaviour tools', () => {+ test('an agent makes a slot, binds a behaviour by name, and reads it back', () => {+ const { figma, component, box } = checkbox()+ expect(createSlot.execute(figma, { id: box.id })).toEqual({ slot: 'Box' })+ expect(+ setBehaviour.execute(figma, {+ id: component.id,+ behaviour: { kind: 'checkbox', values: { value: 'Checked' }, parts: { indicator: 'Box' } }+ })+ ).toMatchObject({ kind: 'checkbox', parts: { indicator: 'Box' }, missing: [] })+ expect(getBehaviour.execute(figma, { id: component.id })).toMatchObject({+ values: { value: 'Checked' }+ })+ expect(setBehaviour.execute(figma, { id: component.id, behaviour: null })).toEqual({ ok: true })+ expect(getBehaviour.execute(figma, { id: component.id })).toEqual({ behaviour: null })+ })++ test('mistakes come back as errors naming what exists, and kinds are listed without an ID', () => {+ const { figma, component } = checkbox()+ expect(+ setBehaviour.execute(figma, {+ id: component.id,+ behaviour: { kind: 'checkbox', values: { value: 'State' } }+ })+ ).toEqual({+ error: 'value needs a VARIANT or BOOLEAN property named "State"; the component has "Checked"'+ })+ expect(JSON.stringify(getBehaviour.execute(figma, {}))).toContain('"kind":"accordion"')+ })+})diff --git a/packages/design-jsx/README.md b/packages/design-jsx/README.mdindex 73a782f49..14d82c214 100644--- a/packages/design-jsx/README.md+++ b/packages/design-jsx/README.md@@ -27,4 +27,13 @@ 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:++```tsx+<Switch.Root name="Switch" modelValue="State">+ <Component name="State=Off" w={44} h={24}><Switch.Thumb x={2} y={2} w={20} h={20} /></Component>+ <Component name="State=On" w={44} h={24}><Switch.Thumb x={22} y={2} w={20} h={20} /></Component>+</Switch.Root>+```+This package depends only on `@open-pencil/scene-graph` and `@open-pencil/emit`. Rendering needs icons, SVG conversion, and layout, which `@open-pencil/core/design-jsx` provides; other engines can supply their own through `createDesignJSXRenderer(services)`.diff --git a/packages/design-jsx/src/behaviours/index.ts b/packages/design-jsx/src/behaviours/index.tsnew file mode 100644index 000000000..5e9e64a37--- /dev/null+++ b/packages/design-jsx/src/behaviours/index.ts@@ -0,0 +1,246 @@+import {+ behaviourFromSpec,+ createComponentPropertyId,+ createSlotProperty,+ withBehaviour,+ type BehaviourKind,+ type BehaviourSpec,+ type SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'++import { node, type TreeNode } from '../tree'++/** What a Reka UI element is to the component it builds. */+export type RekaRole =+ | { role: 'root'; kind: BehaviourKind }+ /** A Reka subcomponent drawn by a slot of the component, such as a switch's thumb. */+ | { role: 'part'; part: string }+ /** One of a slot's repeated parts, such as a tab trigger in the tab list. */+ | { role: 'repeat'; container: string }+ /** The text layer a text value shows, which becomes the field's text property. */+ | { role: 'input'; valueId: string }+ /** A Reka wrapper with no state of its own, drawn as a plain frame. */+ | { role: 'frame' }++const root = (kind: BehaviourKind): RekaRole => ({ role: 'root', kind })+const part = (id: string): RekaRole => ({ role: 'part', part: id })+const repeat = (container: string): RekaRole => ({ role: 'repeat', container })+const input = (valueId: string): RekaRole => ({ role: 'input', valueId })++/**+ * Design JSX's Reka UI elements, by namespace and part, after Reka's own anatomy: `Switch.Root`+ * is a main component that behaves as a switch and `Switch.Thumb` its thumb slot. A group's+ * `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>>>> = {+ Button: { Root: root('button') },+ Toggle: { Root: root('toggle') },+ Switch: { Root: root('switch'), Thumb: part('thumb') },+ Checkbox: { Root: root('checkbox'), Indicator: part('indicator') },+ RadioGroup: { Root: root('radioGroup'), Item: root('radio'), Indicator: part('indicator') },+ ToggleGroup: { Root: root('toggleGroup'), Item: root('toggle') },+ Slider: {+ Root: root('slider'),+ Track: part('track'),+ Range: part('range'),+ Thumb: part('thumb')+ },+ Progress: { Root: root('progress'), Indicator: part('indicator') },+ Tabs: {+ Root: root('tabs'),+ List: part('list'),+ Trigger: repeat('list'),+ Content: repeat('panels')+ },+ Collapsible: { Root: root('collapsible'), Trigger: part('trigger'), Content: part('content') },+ Accordion: {+ Root: root('accordion'),+ Item: root('collapsible'),+ Header: { role: 'frame' },+ Trigger: part('trigger'),+ Content: part('content')+ },+ NumberField: {+ Root: root('numberField'),+ Input: input('text'),+ Increment: part('increment'),+ Decrement: part('decrement')+ },+ TextField: { Root: root('textField'), Input: input('value') },+ Textarea: { Root: root('textarea'), Input: input('value') }+}++/** 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' }++/** The role of a Reka element type such as `Switch.Thumb`, or undefined for other elements. */+export function rekaRole(type: string): RekaRole | undefined {+ const dot = type.indexOf('.')+ if (dot === -1) return undefined+ const namespace = REKA_ELEMENTS[type.slice(0, dot)] as Record<string, RekaRole> | undefined+ return namespace?.[type.slice(dot + 1)]+}++/** The element type for a part container that JSX leaves implicit. */+const containerType = (container: string) => `reka-container:${container}`++export function containerPart(type: string): string | undefined {+ return type.startsWith('reka-container:') ? type.slice('reka-container:'.length) : undefined+}++/** Whether an element names an existing component, as an item of a group does. */+export function namesComponent(props: Record<string, unknown>): boolean {+ return props.of !== undefined || props.component !== undefined || props.componentId !== undefined+}++const GROUPS = new Set<BehaviourKind>(['radioGroup', 'toggleGroup', 'accordion'])++/** The container slot a child written directly under a root belongs in, if any. */+function containerOf(child: TreeNode, kind: BehaviourKind): string | undefined {+ const role = rekaRole(child.type)+ if (role?.role === 'repeat') return role.container+ if (GROUPS.has(kind) && role?.role === 'root' && namesComponent(child.props)) return 'items'+ return undefined+}++/**+ * A root's children with repeated parts and group items that are written directly under it+ * wrapped in their container slot, as the behaviour binds them: tab panels in Panels, a group's+ * items in Items. Containers the JSX writes itself are kept.+ */+export function wrapRepeatedParts(tree: TreeNode, kind: BehaviourKind): TreeNode['children'] {+ const result: TreeNode['children'] = []+ let open: TreeNode | null = null+ for (const child of tree.children) {+ const container = typeof child === 'string' ? undefined : containerOf(child, kind)+ if (!container || typeof child === 'string') {+ open = null+ result.push(child)+ continue+ }+ if (open?.type !== containerType(container)) {+ open = node(containerType(container), {+ name: CONTAINER_NAMES[container] ?? container,+ flex: kind === 'toggleGroup' ? 'row' : 'col',+ gap: kind === 'toggleGroup' ? 4 : 8+ })+ result.push(open)+ }+ open.children.push(child)+ }+ return result+}++/** What a root collects from its parts while they render. */+export interface RekaScope {+ kind: BehaviourKind+ ownerId: string+ /** Slot property ids by part, shared by every variant of a set. */+ slots: Map<string, string>+ /** Text property ids by value, defined once on the root. */+ texts: Map<string, string>+}++export function createScope(kind: BehaviourKind, ownerId: string): RekaScope {+ return { kind, ownerId, slots: new Map(), texts: new Map() }+}++/** Make a rendered part frame its part's slot, with the id the part has in this component. */+export function bindPart(graph: SceneGraph, scope: RekaScope, frame: SceneNode, partId: string) {+ const id = scope.slots.get(partId) ?? createComponentPropertyId()+ if (!createSlotProperty(graph, frame.id, id))+ throw new Error(`<${partId}> must be inside a main component`)+ scope.slots.set(partId, id)+}++/** Make a rendered text layer show the value's text property, defined on the root. */+export function bindInput(+ graph: SceneGraph,+ scope: RekaScope,+ text: SceneNode,+ valueId: string,+ propertyName: string+) {+ let id = scope.texts.get(valueId)+ if (!id) {+ id = createComponentPropertyId()+ scope.texts.set(valueId, id)+ const owner = graph.getNode(scope.ownerId)+ graph.updateNode(scope.ownerId, {+ componentPropertyDefinitions: [+ ...(owner?.componentPropertyDefinitions ?? []),+ { id, name: propertyName, type: 'TEXT', defaultValue: text.text }+ ]+ })+ }+ graph.updateNode(text.id, {+ componentPropertyReferences: [+ ...text.componentPropertyReferences,+ { propertyId: id, field: 'TEXT' }+ ]+ })+}++/** Root props that describe the behaviour rather than the drawing. */+export const BEHAVIOUR_PROPS = [+ 'modelValue',+ 'open',+ 'disabled',+ 'filled',+ 'states',+ 'min',+ 'max',+ 'step',+ 'defaultValue'+] as const++type BindingProp = string | { property: string; on?: string; off?: string }++function isBinding(value: unknown): value is BindingProp {+ return (+ typeof value === 'string' ||+ (typeof value === 'object' &&+ value !== null &&+ 'property' in value &&+ typeof value.property === 'string')+ )+}++/** The spec a root's props give: values by property name, a range, and states. */+function rootSpec(kind: BehaviourKind, props: Record<string, unknown>): BehaviourSpec {+ const values: NonNullable<BehaviourSpec['values']> = {}+ const main = kind === 'collapsible' ? props.open : props.modelValue+ if (isBinding(main)) values[kind === 'collapsible' ? 'open' : 'value'] = main+ if (isBinding(props.disabled)) values.disabled = props.disabled+ if (isBinding(props.filled)) values.filled = props.filled+ const range = Object.fromEntries(+ (['min', 'max', 'step'] as const).flatMap((key) =>+ typeof props[key] === 'number' ? [[key, props[key]]] : []+ )+ )+ if (typeof props.defaultValue === 'number') range.default = props.defaultValue+ const spec: BehaviourSpec = { kind }+ if (Object.keys(values).length) spec.values = values+ if (Object.keys(range).length) spec.numbers = { value: range }+ if (typeof props.states === 'string') spec.states = props.states+ return spec+}++/** Store the behaviour a rendered root describes, with the slots and texts its parts made. */+export function finishRoot(+ graph: SceneGraph,+ scope: RekaScope,+ props: Record<string, unknown>+): void {+ const owner = graph.getNode(scope.ownerId)+ if (!owner) return+ const behaviour = behaviourFromSpec(graph, owner, rootSpec(scope.kind, props))+ behaviour.parts = { ...behaviour.parts, ...Object.fromEntries(scope.slots) }+ behaviour.texts = {+ ...behaviour.texts,+ ...Object.fromEntries([...scope.texts].map(([valueId, id]) => [valueId, { propertyId: id }]))+ }+ graph.updateNode(owner.id, { pluginData: withBehaviour(owner, behaviour) })+}diff --git a/packages/design-jsx/src/behaviours/render.ts b/packages/design-jsx/src/behaviours/render.tsnew file mode 100644index 000000000..de914611a--- /dev/null+++ b/packages/design-jsx/src/behaviours/render.ts@@ -0,0 +1,129 @@+import type { NodeType, SceneGraph, SceneNode } from '@open-pencil/scene-graph'++import type { TreeNode } from '../tree'+import {+ BEHAVIOUR_PROPS,+ bindInput,+ bindPart,+ containerPart,+ createScope,+ finishRoot,+ namesComponent,+ rekaRole,+ wrapRepeatedParts,+ type RekaScope+} from './index'++export type RenderChild = (+ tree: TreeNode,+ parentId: string,+ scope?: RekaScope+) => Promise<SceneNode>+export type CreateElement = (nodeType: NodeType, tree: TreeNode, parentId: string) => SceneNode+export type RenderInstance = (tree: TreeNode, parentId: string) => Promise<SceneNode>++function withoutBehaviourProps(tree: TreeNode): TreeNode {+ const props = Object.fromEntries(+ Object.entries(tree.props).filter(+ ([key]) => !(BEHAVIOUR_PROPS as readonly string[]).includes(key)+ )+ )+ return { ...tree, props }+}++async function renderChildren(+ render: RenderChild,+ children: TreeNode['children'],+ parentId: string,+ scope: RekaScope | undefined+): Promise<void> {+ for (const child of children) if (typeof child !== 'string') await render(child, parentId, scope)+}++/** A name for a part that JSX leaves unnamed: the Reka part it is, such as Thumb. */+function named(tree: TreeNode, fallback: string): TreeNode {+ return tree.props.name === undefined+ ? { ...tree, props: { ...tree.props, name: fallback } }+ : tree+}++/**+ * Render a Reka UI element: a root as a main component (or a component set, when it has+ * variants) that behaves as its control, a part as the slot that draws it, and an input as the+ * text layer of the field's text property. Returns undefined for other elements.+ */+export async function renderRekaNode(+ graph: SceneGraph,+ tree: TreeNode,+ parentId: string,+ scope: RekaScope | undefined,+ hooks: {+ render: RenderChild+ create: CreateElement+ instance: RenderInstance+ /** Derive a component set's variant properties from its variants' names. */+ finishSet: (setId: string) => void+ }+): Promise<SceneNode | undefined> {+ const container = containerPart(tree.type)+ const role = container ? { role: 'part' as const, part: container } : rekaRole(tree.type)+ if (!role) return undefined+ const partName = tree.type.slice(tree.type.indexOf('.') + 1)+ switch (role.role) {+ case 'root': {+ // A group's item that names a component is an item, drawn as an instance of it.+ if (namesComponent(tree.props)) return hooks.instance(tree, parentId)+ const variants = tree.children.some(+ (child) => typeof child !== 'string' && child.type === 'component'+ )+ const root = hooks.create(+ variants ? 'COMPONENT_SET' : 'COMPONENT',+ withoutBehaviourProps(tree),+ parentId+ )+ const own = createScope(role.kind, root.id)+ await renderChildren(hooks.render, wrapRepeatedParts(tree, role.kind), root.id, own)+ if (variants) hooks.finishSet(root.id)+ finishRoot(graph, own, tree.props)+ return root+ }+ case 'part': {+ if (!scope) throw new Error(`<${tree.type}> must be inside its Root`)+ const frame = hooks.create('FRAME', named(tree, partName), parentId)+ await renderChildren(hooks.render, tree.children, frame.id, scope)+ bindPart(graph, scope, frame, role.part)+ return frame+ }+ case 'repeat': {+ const frame = hooks.create('FRAME', named(tree, partName), parentId)+ await renderChildren(hooks.render, tree.children, frame.id, scope)+ // Only the first tab's panel shows as designed; preview shows the others as chosen.+ const siblings = graph.getChildren(parentId)+ if (+ role.container === 'panels' &&+ siblings[0]?.id !== frame.id &&+ tree.props.visible === undefined+ )+ graph.updateNode(frame.id, { visible: false })+ return frame+ }+ case 'input': {+ if (!scope) throw new Error(`<${tree.type}> must be inside its Root`)+ const text = hooks.create('TEXT', named(tree, 'Text'), parentId)+ bindInput(+ graph,+ scope,+ text,+ role.valueId,+ typeof tree.props.name === 'string' ? tree.props.name : 'Text'+ )+ return text+ }+ case 'frame': {+ const frame = hooks.create('FRAME', named(tree, partName), parentId)+ await renderChildren(hooks.render, tree.children, frame.id, scope)+ return frame+ }+ }+ return undefined+}diff --git a/packages/design-jsx/src/export/behaviours.ts b/packages/design-jsx/src/export/behaviours.tsnew file mode 100644index 000000000..736aef85e--- /dev/null+++ b/packages/design-jsx/src/export/behaviours.ts@@ -0,0 +1,144 @@+import {+ behaviourToSpec,+ instanceMainComponent,+ readBehaviour,+ slotPropertyId,+ textBinding,+ type BehaviourKind,+ type SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'++import { REKA_ELEMENTS, rekaRole } from '../behaviours'+import type { JSXProp, JSXValue } from './value'++/** The Reka namespace and element a kind's component is written as. */+const ROOTS: Record<BehaviourKind, [namespace: string, element: string]> = {+ button: ['Button', 'Root'],+ toggle: ['Toggle', 'Root'],+ switch: ['Switch', 'Root'],+ checkbox: ['Checkbox', 'Root'],+ radio: ['RadioGroup', 'Item'],+ radioGroup: ['RadioGroup', 'Root'],+ toggleGroup: ['ToggleGroup', 'Root'],+ slider: ['Slider', 'Root'],+ progress: ['Progress', 'Root'],+ tabs: ['Tabs', 'Root'],+ collapsible: ['Collapsible', 'Root'],+ accordion: ['Accordion', 'Root'],+ numberField: ['NumberField', 'Root'],+ textField: ['TextField', 'Root'],+ textarea: ['Textarea', 'Root']+}++/** How the layers of a component with a behaviour are written as Reka elements. */+export interface RekaExport {+ /** Element names by layer id: the root, its parts, its input, and repeated parts. */+ tags: Map<string, string>+ /** Props a layer adds: the root's behaviour, an item's component. */+ props: Map<string, JSXProp[]>+ /** Containers JSX leaves implicit, written as their children alone. */+ flatten: Set<string>+}++/** The element a part is written as in a namespace, such as `Thumb` for a switch's thumb. */+function elementFor(namespace: string, match: (role: ReturnType<typeof rekaRole>) => boolean) {+ const parts = REKA_ELEMENTS[namespace] ?? {}+ const found = Object.keys(parts).find((element) => match(rekaRole(`${namespace}.${element}`)))+ return found ? `${namespace}.${found}` : undefined+}++function rootProps(graph: SceneGraph, owner: SceneNode): JSXProp[] {+ const behaviour = readBehaviour(owner)+ if (!behaviour) return []+ const spec = behaviourToSpec(graph, owner, behaviour)+ const props: JSXProp[] = []+ const valueProp = (value: NonNullable<typeof spec.values>[string]): JSXValue =>+ typeof value === 'string' ? value : { property: value.property, on: value.on, off: value.off }+ for (const [valueId, value] of Object.entries(spec.values ?? {})) {+ if (Object.hasOwn(behaviour.texts, valueId)) continue+ const name = valueId === 'value' ? 'modelValue' : valueId+ props.push([name, valueProp(value)])+ }+ const range = spec.numbers?.value+ if (range) {+ for (const key of ['min', 'max', 'step'] as const) {+ const value = range[key]+ if (value !== undefined) props.push([key, value])+ }+ if (range.default !== undefined) props.push(['defaultValue', range.default])+ }+ if (spec.states)+ props.push(['states', typeof spec.states === 'string' ? spec.states : spec.states.property])+ return props+}++/** A part's slot frame as its element, and its children as the repeated parts or items. */+function exportPart(+ graph: SceneGraph,+ namespace: string,+ layer: SceneNode,+ partId: string,+ result: RekaExport+): void {+ const tag = elementFor(namespace, (role) => role?.role === 'part' && role.part === partId)+ const repeated = elementFor(+ namespace,+ (role) => role?.role === 'repeat' && role.container === partId+ )+ if (tag) result.tags.set(layer.id, tag)+ else result.flatten.add(layer.id)+ for (const child of graph.getChildren(layer.id)) {+ if (repeated) result.tags.set(child.id, repeated)+ const item = child.type === 'INSTANCE' ? instanceMainComponent(graph, child) : undefined+ if (partId !== 'items' || !item) continue+ // A group's items are written as the group's Item, naming their component.+ const set = item.parentId ? graph.getNode(item.parentId) : undefined+ result.tags.set(child.id, `${namespace}.Item`)+ result.props.set(child.id, [['of', (set?.type === 'COMPONENT_SET' ? set : item).id]])+ }+}++/** Every layer below a node, depth first. */+function descendants(graph: SceneGraph, node: SceneNode): SceneNode[] {+ return graph.getChildren(node.id).flatMap((child) => [child, ...descendants(graph, child)])+}++/**+ * How a main component or component set with a behaviour is written: `Switch.Root` and its+ * `Switch.Thumb`, `TextField.Input`, tab triggers and panels, and a group's items as+ * `RadioGroup.Item of="…"`. Null for other layers.+ */+export function rekaExport(graph: SceneGraph, owner: SceneNode): RekaExport | null {+ const behaviour = readBehaviour(owner)+ if (!behaviour || (owner.type !== 'COMPONENT' && owner.type !== 'COMPONENT_SET')) return null+ const [namespace, element] = ROOTS[behaviour.kind]+ const result: RekaExport = {+ tags: new Map([[owner.id, `${namespace}.${element}`]]),+ props: new Map([[owner.id, rootProps(graph, owner)]]),+ flatten: new Set()+ }+ const textIds = new Map(+ Object.keys(behaviour.texts).map((valueId) => [textBinding(behaviour, valueId), valueId])+ )+ for (const layer of descendants(graph, owner)) {+ if (layer.type === 'INSTANCE') continue+ const partId = Object.entries(behaviour.parts).find(+ ([, id]) => id === slotPropertyId(layer)+ )?.[0]+ if (partId) {+ exportPart(graph, namespace, layer, partId, result)+ continue+ }+ const reference = layer.componentPropertyReferences.find((item) => item.field === 'TEXT')+ const valueId = reference && textIds.get(reference.propertyId)+ if (layer.type === 'TEXT' && valueId) {+ const tag = elementFor(+ namespace,+ (role) => role?.role === 'input' && role.valueId === valueId+ )+ if (tag) result.tags.set(layer.id, tag)+ }+ }+ return result+}diff --git a/packages/design-jsx/src/export/index.ts b/packages/design-jsx/src/export/index.tsindex 159dfb672..e385a4702 100644--- a/packages/design-jsx/src/export/index.ts+++ b/packages/design-jsx/src/export/index.ts@@ -3,6 +3,7 @@ import { compact } from 'es-toolkit/array'import { jsx, type SyntaxNode } from '@open-pencil/emit'import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { rekaExport, type RekaExport } from './behaviours'import { collectProps, NODE_TYPE_TO_TAG, type JSXProp } from './props'import { valueSyntax } from './value'@@ -27,24 +28,47 @@ export interface DesignJSXWithLayers {layerIds: string[]}+const NO_REKA: RekaExport = { tags: new Map(), props: new Map(), flatten: new Set() }++function mergeReka(outer: RekaExport, inner: RekaExport | null): RekaExport {+ if (!inner) return outer+ return {+ tags: new Map([...outer.tags, ...inner.tags]),+ props: new Map([...outer.props, ...inner.props]),+ flatten: new Set([...outer.flatten, ...inner.flatten])+ }+}++/**+ * A layer and the layers below it as JSX elements. A component with a behaviour is written as+ * Reka UI elements; a container JSX leaves implicit is written as its children alone.+ */function nodeToJSX(node: SceneNode,graph: SceneGraph,depth: number,- layerIds?: string[]-): SyntaxNode | null {- const tag = NODE_TYPE_TO_TAG[node.type]- if (!tag) return null+ layerIds?: string[],+ outer: RekaExport = NO_REKA+): SyntaxNode[] {+ const reka = mergeReka(outer, rekaExport(graph, node))+ // Hidden children export with `visible={false}` rather than disappearing.+ const children = (childDepth: number) =>+ graph+ .getChildren(node.id)+ .flatMap((child) => nodeToJSX(child, graph, childDepth, layerIds, reka))+ if (reka.flatten.has(node.id)) return children(depth)+ const tag = reka.tags.get(node.id) ?? NODE_TYPE_TO_TAG[node.type]+ if (!tag) return []layerIds?.push(node.id)- const attributes = collectProps(node, graph).map(propAttribute)+ const ownProps = reka.props.get(node.id)+ // An item names its component; the instance's own layers are the component's to write.+ if (ownProps?.some(([name]) => name === 'of'))+ return [jsx.element(tag, ownProps.map(propAttribute), [], depth)]+ const attributes = [...collectProps(node, graph), ...(ownProps ?? [])].map(propAttribute)if (node.type === 'TEXT') {- return jsx.element(tag, attributes, node.text ? [jsx.text(node.text)] : [], depth, true)+ return [jsx.element(tag, attributes, node.text ? [jsx.text(node.text)] : [], depth, true)]}- // Hidden children export with `visible={false}` rather than disappearing.- const children = graph- .getChildren(node.id)- .flatMap((child) => nodeToJSX(child, graph, depth + 1, layerIds) ?? [])- return jsx.element(tag, attributes, children, depth)+ return [jsx.element(tag, attributes, children(depth + 1), depth)]}/** A JSX attribute as the export prints it: its name and its source, such as `w={320}`. */@@ -115,7 +139,7 @@ export function designJSXElement(nodeId: string, graph: SceneGraph): DesignJSXElexport function sceneNodeToJSX(nodeId: string, graph: SceneGraph): string {const node = graph.getNode(nodeId)- const syntax = node ? nodeToJSX(node, graph, 0) : null+ const syntax = node ? nodeToJSX(node, graph, 0).at(0) : undefinedreturn syntax ? jsx.printJSX(syntax) : ''}@@ -131,7 +155,7 @@ export function selectionToJSXWithLayers(const code = compact(nodeIds.map((id) => {const node = graph.getNode(id)- const syntax = node ? nodeToJSX(node, graph, 0, layerIds) : null+ const syntax = node ? nodeToJSX(node, graph, 0, layerIds).at(0) : undefinedreturn syntax ? jsx.printJSX(syntax) : ''})).join('\n\n')diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.mdindex 29315c532..1472b9da1 100644--- a/packages/design-jsx/src/reference/authoring.md+++ b/packages/design-jsx/src/reference/authoring.md@@ -39,6 +39,24 @@ This reference describes scene creation, not React DOM output. Use the `render`- Reuse existing local or library components before recreating them. Keep meaningful text, visibility, and swap properties exposed rather than hand-editing cloned child nodes.- Explicit instance `w` / `h` replace the inherited sizing mode on that axis; omitted dimensions retain the main component's sizing. Authored overrides survive component synchronization. Distinguish those placement constraints from the main component's default size, and verify actual bounds in narrower parents. Do not compensate for a sizing mismatch with guessed heights, clipping, or manually positioned siblings.+## Controls++- A main component can behave as a Reka UI control in preview and code. Write it with Reka's names: `Switch.Root` is the component (a component set when its children are `Component` variants), and each Reka part is the slot that draws it, such as `Switch.Thumb`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Tabs.List`, `Collapsible.Trigger`, or `NumberField.Increment`. Parts in different variants share one slot.+- The root names the properties that hold its values: `modelValue` (`open` on `Collapsible.Root`), `disabled`, and, for text fields, `filled`, as a variant or boolean property name, or `{ property, on, off }` when the variant values are not named like On and Off. `states` names the variant property that draws default, hover, pressed, focus, and disabled; a slider, progress bar, or number field takes `min`, `max`, `step`, and `defaultValue`.+- `TextField.Input`, `Textarea.Input`, and `NumberField.Input` are the text layers whose text becomes the field's text property. `Tabs.Trigger` goes in `Tabs.List`; `Tabs.Content` panels may sit directly under `Tabs.Root`, the first showing.+- A group's item component is written on its own (`RadioGroup.Item`, `ToggleGroup.Item`, `Accordion.Item` with its `Accordion.Trigger` and `Accordion.Content`); the group's root then lists items as `<RadioGroup.Item of={radioId} />`.++```tsx+<Switch.Root name="Switch" modelValue="State" states="Interaction">+ <Component name="State=Off, Interaction=Default" w={44} h={24} rounded={12} bg="#D0D4DA">+ <Switch.Thumb x={2} y={2} w={20} h={20} rounded={10} bg="#FFFFFF" />+ </Component>+ <Component name="State=On, Interaction=Default" w={44} h={24} rounded={12} bg="#3B6CF6">+ <Switch.Thumb x={22} y={2} w={20} h={20} rounded={10} bg="#FFFFFF" />+ </Component>+</Switch.Root>+```+## VerificationInspect structure and actual rendered output. Node counts and `describe` diagnostics do not establish visual fidelity. Check wrapping with longer content, narrower containers, component edits, and relevant modes. Resolve overflow and contrast problems at their source. Reuse IDs returned by creation tools rather than repeatedly searching for the same nodes.diff --git a/packages/design-jsx/src/render.ts b/packages/design-jsx/src/render.tsindex 3be7cdaf8..a81014ca0 100644--- a/packages/design-jsx/src/render.ts+++ b/packages/design-jsx/src/render.ts@@ -3,6 +3,7 @@ import { transform } from 'sucrase'import type { SceneGraph } from '@open-pencil/scene-graph'+import { REKA_ELEMENTS } from './behaviours'import { designJSXHelpers } from './helpers'import * as React from './mini-react'import { renderRoots, renderTree, type RenderResult } from './renderer'@@ -17,6 +18,16 @@ import type { RenderOptions as RenderJSXOptions } from './types'*/const SUPPORTED_PROPS = DESIGN_JSX_SUPPORTED_PROPERTIES+/** `const Switch = { Root: 'Switch.Root', … }`: each Reka namespace as element types. */+const REKA_ALIASES = Object.entries(REKA_ELEMENTS)+ .map(+ ([namespace, parts]) =>+ `const ${namespace} = ${JSON.stringify(+ Object.fromEntries(Object.keys(parts).map((part) => [part, `${namespace}.${part}`]))+ )}`+ )+ .join('\n')+function stripHTMLComments(jsxString: string): string {return jsxString.replace(/<!--[\s\S]*?-->/g, '')}@@ -57,6 +68,7 @@ export function buildComponent(jsxString: string, warnings: string[] = []): Reacconst Component = 'component', ComponentSet = 'component-set', Instance = 'instance'const Icon = 'icon'const svg = 'svg'+ ${REKA_ALIASES}const dropShadow = __helpers.dropShadowconst innerShadow = __helpers.innerShadowconst layerBlur = __helpers.layerBlurdiff --git a/packages/design-jsx/src/renderer.ts b/packages/design-jsx/src/renderer.tsindex 8c2706983..e462bdf1b 100644--- a/packages/design-jsx/src/renderer.ts+++ b/packages/design-jsx/src/renderer.ts@@ -11,6 +11,8 @@ import {} from '@open-pencil/scene-graph'import { parseColor } from '@open-pencil/scene-graph/color'+import type { RekaScope } from './behaviours'+import { renderRekaNode } from './behaviours/render'import {assignComponentProperties,componentMetadata,@@ -542,9 +544,10 @@ async function renderNode<Artwork>(graph: SceneGraph,tree: TreeNode,parentId: string,- onNode?: RenderOptions['onNode']+ onNode?: RenderOptions['onNode'],+ scope?: RekaScope): Promise<SceneNode> {- const node = await renderNodeContent(services, graph, tree, parentId, onNode)+ const node = await renderNodeContent(services, graph, tree, parentId, onNode, scope)onNode?.(tree, node)return node}@@ -554,11 +557,25 @@ async function renderNodeContent<Artwork>(graph: SceneGraph,tree: TreeNode,parentId: string,- onNode?: RenderOptions['onNode']+ onNode?: RenderOptions['onNode'],+ scope?: RekaScope): Promise<SceneNode> {if (tree.type === 'icon' || tree.type === 'svg')return renderArtworkNode(services, graph, tree, parentId)if (tree.type === 'instance') return renderInstanceNode(graph, tree, parentId)+ const reka = await renderRekaNode(graph, tree, parentId, scope, {+ render: (child, childParentId, childScope) =>+ renderNode(services, graph, child, childParentId, onNode, childScope),+ create: (nodeType, element, elementParentId) => {+ const { overrides, bindings } = elementOverrides(graph, nodeType, element, elementParentId)+ const created = graph.createNode(nodeType, elementParentId, overrides)+ applyBindings(graph, created.id, bindings)+ return created+ },+ instance: (element, elementParentId) => renderInstanceNode(graph, element, elementParentId),+ finishSet: (setId) => inferComponentSetProperties(graph, setId)+ })+ if (reka) return rekaconst nodeType = TYPE_MAP[tree.type]if (!nodeType) throw new Error(`Unknown element: <${tree.type}>`)@@ -570,7 +587,7 @@ async function renderNodeContent<Artwork>(for (const child of tree.children) {if (typeof child === 'string') continueif (isTreeNode(child)) {- await renderNode(services, graph, child, node.id, onNode)+ await renderNode(services, graph, child, node.id, onNode, scope)}}diff --git a/packages/design-jsx/src/schema.ts b/packages/design-jsx/src/schema.tsindex 8f8e6e569..7334f8d90 100644--- a/packages/design-jsx/src/schema.ts+++ b/packages/design-jsx/src/schema.ts@@ -1,3 +1,23 @@+import { REKA_ELEMENTS, rekaRole } from './behaviours'++function rekaDescription(namespace: string, part: string): string {+ const role = rekaRole(`${namespace}.${part}`)+ if (role?.role === 'root')+ return `A main component that behaves as Reka UI's ${namespace} ${part}.`+ if (role?.role === 'input') return `The text layer of a ${namespace}'s text property.`+ return `The ${namespace} ${part}, drawn by a slot of its component.`+}++/** A Reka UI element as the element list describes it. */+function rekaElementDefinitions(): DesignJSXElementDefinition[] {+ return Object.entries(REKA_ELEMENTS).flatMap(([namespace, parts]) =>+ Object.keys(parts).map((part) => {+ const type = `${namespace}.${part}`+ return { name: type, runtimeType: type, description: rekaDescription(namespace, part) }+ })+ )+}+export type DesignJSXElementDefinition = {name: stringruntimeType: string@@ -28,7 +48,8 @@ export const DESIGN_JSX_ELEMENTS: DesignJSXElementDefinition[] = [{ name: 'Instance', runtimeType: 'instance', description: 'An instance of a component.' },{ name: 'View', runtimeType: 'frame', description: 'An alias for Frame.' },{ name: 'Rect', runtimeType: 'rectangle', description: 'An alias for Rectangle.' },- { name: 'Icon', runtimeType: 'icon', description: 'An Iconify icon.' }+ { name: 'Icon', runtimeType: 'icon', description: 'An Iconify icon.' },+ ...rekaElementDefinitions()]export const DESIGN_JSX_SUPPORTED_PROPERTY_NAMES = [@@ -149,7 +170,17 @@ export const DESIGN_JSX_SUPPORTED_PROPERTY_NAMES = ['componentId','properties','propertyRefs',- 'of'+ 'of',+ // A Reka UI root's behaviour, by its own property names+ 'modelValue',+ 'open',+ 'disabled',+ 'filled',+ 'states',+ 'min',+ 'max',+ 'step',+ 'defaultValue'] as constexport const DESIGN_JSX_SUPPORTED_PROPERTIES = new Set<string>(DESIGN_JSX_SUPPORTED_PROPERTY_NAMES)diff --git a/packages/docs/.vitepress/sidebars.ts b/packages/docs/.vitepress/sidebars.tsindex 67b92e1fb..e6fcd38ea 100644--- a/packages/docs/.vitepress/sidebars.ts+++ b/packages/docs/.vitepress/sidebars.ts@@ -120,6 +120,7 @@ export const developmentSidebar = (...(!prefix? [{ text: 'Roadmap', link: '/development/roadmap' },+ { text: 'Behaviours and Preview', link: '/development/behaviours-and-preview' },{ text: 'Navigation Performance', link: '/development/navigation-performance' },{ text: 'Renderer Lifecycle', link: '/development/renderer-lifecycle' },{ text: 'Renderer Profiler', link: '/development/renderer-profiler' },diff --git a/packages/docs/development/architecture.md b/packages/docs/development/architecture.mdindex 2c2bce1cd..2b3e9a982 100644--- a/packages/docs/development/architecture.md+++ b/packages/docs/development/architecture.md@@ -77,10 +77,14 @@ Tools are defined once in `packages/core/src/tools/`, split by domain: read, cre- **AI chat** — valibot schemas, multi-provider (Anthropic, OpenAI, Google AI, OpenRouter, compatible endpoints)- **MCP server** — zod schemas, stdio + HTTP transports-- **CLI** — available via the `eval` command+- **CLI** — available via the `eval` command, whose scripts get the `figma` Plugin API and the `openpencil` API90+ core tools + 3 MCP file management tools. Includes XPath query (`query_nodes`), JSX inspection (`get_jsx`, `diff_jsx`), semantic description (`describe`), and vision-based verification (`export_image` returns images to the model).+### Behaviours and Preview++A behaviour stored on a main component makes it work as a Reka UI control. Preview runs top-level layers holding controls as live islands: shadow-DOM projections laid over the canvas, with each control mounted as its Reka UI primitive and drawn by the component's variants. See [Behaviours and Preview](./behaviours-and-preview).+### Undo/RedoInverse-command pattern. Before applying any change, affected fields are snapshotted. The snapshot becomes the inverse operation. Batching groups rapid changes (like drag) into single undo entries.@@ -109,7 +113,7 @@ The headless CLI already supports `analyze colors/typography/spacing/clusters`.### Prototyping-Frame-to-frame transitions, interaction triggers (click, hover, drag), overlay management, and fullscreen preview mode.+Preview already runs components with behaviours as live controls. Next: reactions and variables that let controls drive the rest of a design, frame-to-frame transitions, interaction triggers, and overlays.### Windows Code Signingdiff --git a/packages/docs/development/behaviours-and-preview.md b/packages/docs/development/behaviours-and-preview.mdnew file mode 100644index 000000000..82e35ce3d--- /dev/null+++ b/packages/docs/development/behaviours-and-preview.md@@ -0,0 +1,49 @@+---+title: Behaviours and Preview+description: How components become working controls, how agents and scripts author them, and how preview runs them as live Reka UI islands.+---++# Behaviours and Preview++A behaviour makes a main component or component set work as a real control: a Switch, Slider, Tabs, Text field, and so on, after [Reka UI](https://reka-ui.com)'s primitives. It adds no node types. It describes which of the component's existing properties hold the control's values, which of its slots draw the control's parts, and which variants draw its interaction states. Preview then runs the control as the real Reka UI component, and code export can generate the same.++## The model++The model lives in `@open-pencil/scene-graph` (`packages/scene-graph/src/behaviours/`).++- **Kinds and contracts** (`kinds.ts`). `BEHAVIOUR_CONTRACTS` gives each kind its values and parts, keyed by kind, so a kind without a contract does not type-check. Contracts follow Reka UI's anatomy: every Reka subcomponent is a slot of the component, the component itself is the root, and a slot that holds repeated parts names the Reka part of its children, such as the tab list's triggers or a group's items.+- **Storage** (`schema.ts`, `model.ts`). A behaviour is stored as the `behaviour` field of OpenPencil's plugin data on the component or set, with properties and slots bound by id. Its role is `content`, so it travels with library assets and counts towards their update hash. `.fig` export renames the bound ids to the GUIDs it gives the properties.+- **Values**: a boolean is a variant property (with the values that mean on and off) or a boolean property; text is a text property; a number is the behaviour's own range, since Figma has no number property; a choice is which child of a slot is active.+- **States**: a variant property whose values draw rest, hover, pressed, focus, and disabled.+- **Specs** (`spec.ts`). `behaviourFromSpec` and `behaviourToSpec` convert between the stored behaviour and a spec that names properties and slots, which is how every authoring surface except the panel writes it. Errors name what the component has.++## Authoring surfaces++All of them write the same model.++| Surface | Where | Notes |+|---|---|---|+| Behaviour section | `src/components/properties/component-properties/behaviour/`, `useBehaviour` in `packages/vue` | Binds by id; Core's editor actions (`setBehaviour`, `addBehaviourText`, `addBehaviourVariant`, `addBehaviourPart`) create what is missing in one undo step. |+| `openpencil` scripting API | `packages/core/src/openpencil-api/` | The `openpencil` global next to `figma` in every script runner, through `compileScript`. |+| Tools | `packages/core/src/tools/create/behaviours.ts` | `set_behaviour`, `get_behaviour`, `create_slot`, built on the `openpencil` API. |+| Design JSX | `packages/design-jsx/src/behaviours/`, `export/behaviours.ts` | Reka-named elements (`Switch.Root`, `Switch.Thumb`) render and export components with behaviours. |++## Preview islands++Preview is a per-pane mode (`EditorViewState.play`). It runs controls as real components; it never simulates them on the canvas.++1. **Islands.** `playIslandRoots` (Core) picks the top-level layers of the page that hold an instance with a behaviour. The renderer skips them while the pane previews, and `PlayIslands` (`packages/vue/src/canvas/islands/`) mounts one island per root, laid over the canvas at the pane's pan and zoom.+2. **Shadow DOM.** Each island renders into its own shadow root: app CSS does not reach in, island CSS does not leak out, fonts already loaded by the app apply, and the island moves with the canvas in the same frame. Wheel gestures over an island are passed to the canvas.+3. **State to design.** An island keeps each control's state (values, choice, number, typed text, hover, pressed, focus). Core's `resolvePlayState` copies the island's layers into a private graph and shows each instance in its state: the matching variant, boolean properties, and layers a control reveals, such as tab panels. The document is never changed.+4. **Design to DOM.** The private graph is projected to DOM through `@open-pencil/dom-css`, the same projection HTML export uses, so island fidelity and export fidelity improve together.+5. **DOM to Reka.** Each projected layer has a role: a control's root, a part, a group's item, a tab trigger or panel, or a text input. Roles wrap the layer in its Reka UI primitive with `asChild`, so Reka renders through the designed element. Typing, focus, keyboard navigation, and accessibility are the browser's and Reka's.++Controls and DOM keys use layer paths (names below the island root), not node ids: a variant switch rebuilds an instance's layers with new ids, and a stable path keeps the DOM in place, including a focused input.++## Adding a kind or a part++1. Add the kind to `BEHAVIOUR_KINDS` and its contract to `BEHAVIOUR_CONTRACTS` in scene-graph; part ids follow Reka's part names.+2. Map it in preview: its root and parts in `packages/vue/src/canvas/islands/controls/`, with the Reka primitives it uses.+3. Name its elements in design JSX: `REKA_ELEMENTS` in `packages/design-jsx/src/behaviours/index.ts` and the export's root table in `export/behaviours.ts`.+4. Label it in the Behaviour section (`labels.ts`) and translate the strings.+5. Cover the model and spec in scene-graph tests, preview in `tests/e2e/components/behaviours.spec.ts`, and JSX in `packages/core/tests/design-jsx/behaviours.test.ts`.diff --git a/packages/docs/development/roadmap.md b/packages/docs/development/roadmap.mdindex a37658399..99f172c5a 100644--- a/packages/docs/development/roadmap.md+++ b/packages/docs/development/roadmap.md@@ -232,7 +232,7 @@ Figma's design documentation groups features into these areas:| Prototype hotspots / triggers / actions | — | — | — | — | — | Not modeled. || Prototype overlays / scroll-to | — | — | — | — | — | Not modeled. || Smart animate / easing / spring / duration | — | — | — | — | — | Not modeled. |-| Interactive components | — | — | — | — | — | Component-level prototype connections are not supported. |+| Interactive components | — | — | — | — | — | Figma's component-level prototype connections are not supported; OpenPencil's own behaviours make components run as Reka UI controls in preview. || Dev Mode inspect / measurements / annotations | — | ◐ | ◐ | — | ◐ | OpenPencil has CLI/MCP inspection and Option/Alt distance overlays, but not Figma Dev Mode annotations or its full UI. || Code Connect / dev resources / ready-for-dev | — | — | — | — | — | Not modeled. || Comments | — | — | — | — | — | Not modeled. |diff --git a/packages/docs/overview/features.md b/packages/docs/overview/features.mdindex 49bd365b4..e5cb15e66 100644--- a/packages/docs/overview/features.md+++ b/packages/docs/overview/features.md@@ -13,7 +13,8 @@ Open and save native Figma files directly. The import/export pipeline uses the s- **Text** — canvas-native editing with IME support, double-click to enter edit mode- **Rich text** — per-character bold (<kbd>⌘</kbd><kbd>B</kbd>), italic (<kbd>⌘</kbd><kbd>I</kbd>), underline (<kbd>⌘</kbd><kbd>U</kbd>), strikethrough- **Auto-layout** — flexbox and CSS Grid via Yoga WASM: direction, gap, padding, justify, align, child sizing, grid tracks. <kbd>⇧</kbd><kbd>A</kbd> to toggle-- **Components** — create (<kbd>⌥</kbd><kbd>⌘</kbd><kbd>K</kbd>), component sets (<kbd>⇧</kbd><kbd>⌘</kbd><kbd>K</kbd>), instances with override support, live sync+- **Components** — create (<kbd>⌥</kbd><kbd>⌘</kbd><kbd>K</kbd>), component sets (<kbd>⇧</kbd><kbd>⌘</kbd><kbd>K</kbd>), instances with override support, slots, live sync+- **Behaviours and preview** — make components work as Reka UI controls (switch, slider, tabs, text field, accordion, …) and try them live over the canvas with <kbd>⌥</kbd><kbd>⌘</kbd><kbd>↩</kbd> ([Components](/user-guide/components#behaviours-and-preview))- **Variables** — design tokens with collections, modes (Light/Dark), color/float/string/boolean types, variable binding- **Sections** — organizational containers with auto-adopting children and title pillsdiff --git a/packages/docs/programmable/ai-chat.md b/packages/docs/programmable/ai-chat.mdindex 8f428bc64..1016e4c9a 100644--- a/packages/docs/programmable/ai-chat.md+++ b/packages/docs/programmable/ai-chat.md@@ -70,7 +70,7 @@ The configurable tool catalog covers these categories; the tools offered to a mo- **Create** — frames, shapes, text, components, pages. Renders JSX for complex layouts.- **Style** — fills, strokes, effects, opacity, corner radius, blend modes.- **Layout** — auto-layout, grid, alignment, spacing, sizing.-- **Components** — create components, instances, component sets. Manage overrides.+- **Components** — create components, instances, component sets, and slots. Manage overrides. Give components Reka UI behaviours so they work in preview.- **Variables** — create/edit variables, collections, modes. Bind to fills.- **Query** — find nodes, XPath selectors, read properties, list pages, fonts, selection.- **Inspect** — `get_jsx` for JSX roundtrip view, `diff_create` and `diff_jsx` for structural diffs, `diff_visual` for pixel diffs, `describe` for semantic role and design issue detection.@@ -92,6 +92,7 @@ The assistant can verify its work visually. When `export_image` is enabled, it c- "Find all text nodes with font size less than 12"- "Describe the selected component — what role does it look like?"- "Show me the JSX for this frame"+- "Make this component a switch that I can try in preview"## Tipsdiff --git a/packages/docs/programmable/cli/scripting.md b/packages/docs/programmable/cli/scripting.mdindex 61c7e237d..4a9061f99 100644--- a/packages/docs/programmable/cli/scripting.md+++ b/packages/docs/programmable/cli/scripting.md@@ -13,7 +13,7 @@ description: Execute JavaScript with a Figma-compatible Plugin API to query, batopenpencil eval design.fig -c "return figma.currentPage.children.length"```-The `-c` flag accepts JavaScript. If the code does not start with `return`, OpenPencil wraps it in an async function and returns the value from that function when present.+The `-c` flag accepts JavaScript. Its last expression is the result, so `return` is optional; `await` works at the top level. A script whose last statement is not an expression, such as a declaration, has no result and prints nothing.```shopenpencil eval design.fig -c "@@ -85,6 +85,31 @@ openpencil eval design.fig -c "return figma.currentPage.children.map((n) => n.naUse `--quiet` / `-q` to suppress output when only writing a file.+## The `openpencil` API++Next to `figma`, scripts get `openpencil`: what OpenPencil adds to the Figma Plugin API, in the same style. The same global is available to the `eval` tool and the running app's automation.++A main component or component set can [behave as a Reka UI control](/user-guide/components#behaviours-and-preview). Bind it by its own property and slot names:++```sh+openpencil eval design.fig -w -c '+ const set = figma.currentPage.findOne((n) => n.type === "COMPONENT_SET" && n.name === "Switch")+ const behaviour = openpencil.setBehaviour(set, "switch")+ .bindValue("value", "State") // On and Off guessed from the variants+ .bindPart("thumb", set.findOne((n) => n.name === "Thumb")) // the frame becomes a slot+ behaviour.states = "Interaction"+ behaviour.missing+'+```++- `openpencil.setBehaviour(node, kindOrSpec)` replaces a component's behaviour: a kind alone, or a spec such as `{ kind: "slider", parts: { track: "Track", thumb: "Thumb" }, numbers: { value: { min: 0, max: 10 } } }`. It returns the behaviour.+- `openpencil.getBehaviour(node)` reads one, or `null`; a variant reads its set's.+- A behaviour has `kind`, `spec` (by name), `missing` (required values and parts still unbound), and `states`, and `bindValue(valueId, property, { on, off })`, `bindPart(partId, slotNameOrFrame)`, `setNumber(valueId, { min, max, step, default })`, and `remove()`.+- `openpencil.behaviourKinds` lists every kind with the values and parts it binds.+- `openpencil.createSlot(frame)` makes a frame of a main component a slot and returns its name.++Names the component does not have fail with an error that lists the ones it has.+## Supported API surfaceThe API is intentionally close to Figma's Plugin API, but it maps to OpenPencil's scene graph and file format.@@ -128,6 +153,7 @@ The API is intentionally close to Figma's Plugin API, but it maps to OpenPencil'### Components- `figma.createComponentFromNode(node)`+- `figma.combineAsVariants(components, parent)` — properties come from names such as `State=On, Size=Large`- `component.createInstance()`- `instance.mainComponent`diff --git a/packages/docs/programmable/mcp-server.md b/packages/docs/programmable/mcp-server.mdindex 5bbcbabd3..c30529f2c 100644--- a/packages/docs/programmable/mcp-server.md+++ b/packages/docs/programmable/mcp-server.md@@ -232,6 +232,9 @@ Settings tools never expose credentials, AI models, MCP connections, storage, or| `render` | Render JSX to design nodes — create entire component trees in one call || `create_component` | Convert a frame/group into a component || `create_instance` | Create an instance of a component |+| `create_slot` | Make a frame inside a main component a slot |+| `set_behaviour` | Make a component behave as a Reka UI control, by its property and slot names; `null` removes it |+| `get_behaviour` | Read a component's behaviour and what it still misses; without an ID, list every kind || `node_to_component` | Convert an existing node into a component in-place |### Modifydiff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.mdindex 6457a2b08..06f681a05 100644--- a/packages/docs/reference/design-authoring.md+++ b/packages/docs/reference/design-authoring.md@@ -41,6 +41,24 @@ This reference describes scene creation, not React DOM output. Use the `render`- Reuse existing local or library components before recreating them. Keep meaningful text, visibility, and swap properties exposed rather than hand-editing cloned child nodes.- Explicit instance `w` / `h` replace the inherited sizing mode on that axis; omitted dimensions retain the main component's sizing. Authored overrides survive component synchronization. Distinguish those placement constraints from the main component's default size, and verify actual bounds in narrower parents. Do not compensate for a sizing mismatch with guessed heights, clipping, or manually positioned siblings.+## Controls++- A main component can behave as a Reka UI control in preview and code. Write it with Reka's names: `Switch.Root` is the component (a component set when its children are `Component` variants), and each Reka part is the slot that draws it, such as `Switch.Thumb`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Tabs.List`, `Collapsible.Trigger`, or `NumberField.Increment`. Parts in different variants share one slot.+- The root names the properties that hold its values: `modelValue` (`open` on `Collapsible.Root`), `disabled`, and, for text fields, `filled`, as a variant or boolean property name, or `{ property, on, off }` when the variant values are not named like On and Off. `states` names the variant property that draws default, hover, pressed, focus, and disabled; a slider, progress bar, or number field takes `min`, `max`, `step`, and `defaultValue`.+- `TextField.Input`, `Textarea.Input`, and `NumberField.Input` are the text layers whose text becomes the field's text property. `Tabs.Trigger` goes in `Tabs.List`; `Tabs.Content` panels may sit directly under `Tabs.Root`, the first showing.+- A group's item component is written on its own (`RadioGroup.Item`, `ToggleGroup.Item`, `Accordion.Item` with its `Accordion.Trigger` and `Accordion.Content`); the group's root then lists items as `<RadioGroup.Item of={radioId} />`.++```tsx+<Switch.Root name="Switch" modelValue="State" states="Interaction">+ <Component name="State=Off, Interaction=Default" w={44} h={24} rounded={12} bg="#D0D4DA">+ <Switch.Thumb x={2} y={2} w={20} h={20} rounded={10} bg="#FFFFFF" />+ </Component>+ <Component name="State=On, Interaction=Default" w={44} h={24} rounded={12} bg="#3B6CF6">+ <Switch.Thumb x={22} y={2} w={20} h={20} rounded={10} bg="#FFFFFF" />+ </Component>+</Switch.Root>+```+## VerificationInspect structure and actual rendered output. Node counts and `describe` diagnostics do not establish visual fidelity. Check wrapping with longer content, narrower containers, component edits, and relevant modes. Resolve overflow and contrast problems at their source. Reuse IDs returned by creation tools rather than repeatedly searching for the same nodes.@@ -68,8 +86,8 @@ The examples below are executed by the authoring-reference tests. Create the namGenerated from the renderer metadata. This inventory lists accepted names, not arbitrary browser CSS support.-**Elements:** `Frame`, `Text`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`.+**Elements:** `Frame`, `Text`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `designVar`, `defineVars`.-**Properties:** `name`, `key`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textCase`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `propertyRefs`, `of`.\ No newline at end of file+**Properties:** `name`, `key`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textCase`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `propertyRefs`, `of`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.\ No newline at end of filediff --git a/packages/docs/reference/keyboard-shortcuts.md b/packages/docs/reference/keyboard-shortcuts.mdindex 87f0cc1e9..16ad09752 100644--- a/packages/docs/reference/keyboard-shortcuts.md+++ b/packages/docs/reference/keyboard-shortcuts.md@@ -70,6 +70,7 @@ Full Figma-compatible shortcut map. ✅ = implemented.| <kbd>⌃</kbd><kbd>G</kbd> | Layout Guides | 🔲 || <kbd>⇧</kbd><kbd>R</kbd> | Rulers | 🔲 || <kbd>⌘</kbd><kbd>\\</kbd> | Show/Hide UI | ✅ |+| <kbd>⌥</kbd><kbd>⌘</kbd><kbd>↩</kbd> | Preview controls | ✅ || <kbd>⌘</kbd><kbd>=</kbd> | Zoom In | ✅ || <kbd>⌘</kbd><kbd>-</kbd> | Zoom Out | ✅ || <kbd>⌘</kbd><kbd>0</kbd> | Zoom to 100% | ✅ |diff --git a/packages/docs/user-guide/components.md b/packages/docs/user-guide/components.mdindex 1925c7e3a..cdca6705a 100644--- a/packages/docs/user-guide/components.md+++ b/packages/docs/user-guide/components.md@@ -31,7 +31,27 @@ Use the component properties panel to add, rename, reorder, and remove variant d## Component Properties-Components and component sets support reusable text, boolean visibility, and instance-swap properties. Link a property to a descendant field, then select an instance to edit its assigned value without detaching it. Properties and assignments are preserved when saving and reopening `.fig` files.+Components and component sets support reusable text, boolean visibility, instance-swap, and slot properties. Link a property to a descendant field, then select an instance to edit its assigned value without detaching it. Properties and assignments are preserved when saving and reopening `.fig` files.++## Slots++A slot is a frame of a main component whose content each instance can change. Select a frame inside a main component and choose **Create slot** from the context menu or the Slots section, or select other layers to wrap them in a new slot frame. Slot settings set a description, the components it prefers, and how many items it holds; an instance outside those limits shows a warning. In an instance, add, reorder, and remove a slot's items, or reset it to the component's content.++## Behaviours and Preview++A behaviour makes a main component or component set work like a real control, after [Reka UI](https://reka-ui.com)'s primitives: Button, Text field, Textarea, Number field, Toggle, Switch, Checkbox, Radio, Radio group, Toggle group, Slider, Progress, Tabs, Collapsible, or Accordion. Select the component and use **+** in the **Behaviour** section to choose one.++The section lists what the control needs:++- **Values** — the property that holds each value: a variant or boolean property for On, Checked, Pressed, Open, Filled, or Disabled (with the variant values that mean on and off), a text property for a field's text, or a slider's own minimum, maximum, step, and default.+- **Parts** — the slot that draws each part, such as a switch's thumb, a slider's track, range, and thumb, or a tab list. A group's items slot holds instances of its radios, toggles, or collapsibles.+- **States** — a variant property whose values draw default, hover, pressed, focus, and disabled. Values named like those states are matched automatically.++Rows the control requires come first; the rest are under **More options**. When a component has nothing to bind yet, a row offers to create it: a text layer and text property, Off and On variants, or a slot, and **States** offers **Add state variants**, which adds a Default, Hover, Pressed, Focus, and Disabled variant of the component. A lone main component that gets variants this way becomes a component set, and a slot added to a set appears in every variant. Until the control works, a line under its name says what is still needed; clicking it goes there.++Press <kbd>⌥</kbd><kbd>⌘</kbd><kbd>↩</kbd> (<kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Enter</kbd>), choose **View → Preview**, or use ▶ next to Share to preview the canvas. Each top-level layer holding controls runs as live Reka UI components over the canvas, drawn by the component's variants: switches flip, sliders drag, tabs and accordions open, and text fields are real inputs with the browser's caret, selection, and paste. Preview never changes the document or its history. **Reset** puts every control back as designed, and <kbd>Esc</kbd> or the pill's close button returns to editing. In split view, each canvas previews on its own.++Behaviours are saved in `.fig` files and published with library components.## Component Libraries@@ -133,6 +153,7 @@ Components and instances are opaque containers — clicking on a child selects t| Create component | <kbd>⌥</kbd><kbd>⌘</kbd><kbd>K</kbd> | <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>K</kbd> || Create component set | <kbd>⇧</kbd><kbd>⌘</kbd><kbd>K</kbd> | <kbd>Shift</kbd> + <kbd>Ctrl</kbd> + <kbd>K</kbd> || Detach instance | <kbd>⌥</kbd><kbd>⌘</kbd><kbd>B</kbd> | <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>B</kbd> |+| Preview | <kbd>⌥</kbd><kbd>⌘</kbd><kbd>↩</kbd> | <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Enter</kbd> |## Tipsdiff --git a/packages/dom-css/src/export/projection.ts b/packages/dom-css/src/export/projection.tsindex fb9b40fd8..ef17d9002 100644--- a/packages/dom-css/src/export/projection.ts+++ b/packages/dom-css/src/export/projection.ts@@ -61,16 +61,47 @@ function textCaseToCSS(value: SceneNode['textCase']): string | undefined {return undefined}+/** Whether a layer sizes itself to its content along an axis, so CSS should too. */+function hugs(node: SceneNode, axis: 'width' | 'height'): boolean {+ if (node.type === 'TEXT')+ return (+ node.textAutoResize === 'WIDTH_AND_HEIGHT' ||+ (axis === 'height' && node.textAutoResize === 'HEIGHT')+ )+ if (node.layoutMode !== 'HORIZONTAL' && node.layoutMode !== 'VERTICAL') return false+ const primary = (node.layoutMode === 'HORIZONTAL') === (axis === 'width')+ return (primary ? node.primaryAxisSizing : node.counterAxisSizing) === 'HUG'+}++/**+ * A layer's size: fixed on the axes the design fixes, and left to the content where the layer+ * hugs it (an auto layout frame set to Hug, or auto-sizing text), so the page grows with it.+ */function addSize(style: DesignStyleDeclaration, node: SceneNode, css: FieldCSS): void {- if (node.width > 0) style.width = css('width', px(node.width))- if (node.height > 0) style.height = css('height', px(node.height))+ if (node.width > 0 && !hugs(node, 'width')) style.width = css('width', px(node.width))+ if (node.height > 0 && !hugs(node, 'height')) style.height = css('height', px(node.height))}-function addPositioning(style: DesignStyleDeclaration, node: SceneNode): void {- if (node.layoutPositioning !== 'ABSOLUTE') return- style.position = 'absolute'- style.left = `${node.x}px`- style.top = `${node.y}px`+/**+ * Place a layer at its coordinates when its parent does not lay it out: it is absolutely+ * positioned, or its parent frame has no auto layout. A frame without auto layout becomes the+ * containing block of the children it places.+ */+function addPositioning(+ style: DesignStyleDeclaration,+ node: SceneNode,+ parent: SceneNode | undefined+): void {+ const placed =+ node.layoutPositioning === 'ABSOLUTE' ||+ (parent !== undefined && parent.type !== 'CANVAS' && parent.layoutMode === 'NONE')+ if (placed) {+ style.position = 'absolute'+ style.left = `${node.x}px`+ style.top = `${node.y}px`+ } else if (node.layoutMode === 'NONE' && node.type !== 'TEXT' && node.childIds.length > 0) {+ style.position = 'relative'+ }}function addSizeConstraints(style: DesignStyleDeclaration, node: SceneNode, css: FieldCSS): void {@@ -81,6 +112,10 @@ function addSizeConstraints(style: DesignStyleDeclaration, node: SceneNode, css:}function addCornerRadii(style: DesignStyleDeclaration, node: SceneNode, css: FieldCSS): void {+ if (node.type === 'ELLIPSE') {+ style['border-radius'] = '50%'+ return+ }if (node.independentCorners) {const corners = [['border-top-left-radius', 'topLeftRadius', node.topLeftRadius],@@ -186,7 +221,7 @@ function styleFromSceneNode(): DesignStyleDeclaration {const style: DesignStyleDeclaration = {}addSize(style, node, css)- addPositioning(style, node)+ addPositioning(style, node, parent)addSizeConstraints(style, node, css)const fill = fillToCSS(node.fills.at(0))if (fill) style['background-color'] = css('fills/0/color', fill)@@ -228,7 +263,7 @@ function styleFromTextNode(): DesignStyleDeclaration {const style: DesignStyleDeclaration = {}addSize(style, node, css)- addPositioning(style, node)+ addPositioning(style, node, parent)addLayoutChild(style, node, parent)if (resolveNodeTextDirection(node) === 'RTL') style.direction = 'rtl'const color = fillToCSS(node.fills.at(0))diff --git a/packages/dom-css/tests/export/projection.test.ts b/packages/dom-css/tests/export/projection.test.tsnew file mode 100644index 000000000..f026e92f5--- /dev/null+++ b/packages/dom-css/tests/export/projection.test.ts@@ -0,0 +1,72 @@+import { describe, expect, test } from 'bun:test'++import {+ sceneNodeToDesignDocument,+ type DesignElement,+ type DesignNode+} from '@open-pencil/dom-css/export'+import { SceneGraph } from '@open-pencil/scene-graph'++function element(node: DesignNode | undefined): DesignElement {+ if (node?.type !== 'element') throw new Error('Expected an element')+ return node+}++describe('DOM projection', () => {+ test('a frame without auto layout places its layers at their coordinates', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const toggle = graph.createNode('FRAME', page.id, { name: 'Switch', width: 44, height: 24 })+ graph.createNode('ELLIPSE', toggle.id, { name: 'Knob', x: 22, y: 2, width: 20, height: 20 })++ const root = element(sceneNodeToDesignDocument(graph, toggle.id).children[0])+ expect(root.inlineStyle).toMatchObject({ position: 'relative', width: '44px' })+ expect(element(root.children[0]).inlineStyle).toMatchObject({+ position: 'absolute',+ left: '22px',+ top: '2px'+ })+ })++ test('an auto layout frame leaves its layers to flexbox', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const row = graph.createNode('FRAME', page.id, { name: 'Row', layoutMode: 'HORIZONTAL' })+ graph.createNode('FRAME', row.id, { name: 'Item', x: 30, width: 10, height: 10 })++ const root = element(sceneNodeToDesignDocument(graph, row.id).children[0])+ expect(root.inlineStyle?.position).toBeUndefined()+ expect(element(root.children[0]).inlineStyle?.position).toBeUndefined()+ })+})++describe('DOM projection sizes', () => {+ test('a hugging auto layout frame and auto-sizing text leave their size to the content', () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const card = graph.createNode('FRAME', page.id, {+ name: 'Card',+ width: 240,+ height: 72,+ layoutMode: 'VERTICAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'FIXED'+ })+ graph.createNode('TEXT', card.id, {+ name: 'Title',+ text: 'Details',+ width: 60,+ height: 16,+ textAutoResize: 'WIDTH_AND_HEIGHT'+ })+ graph.createNode('ELLIPSE', card.id, { name: 'Knob', width: 20, height: 20 })++ const root = element(sceneNodeToDesignDocument(graph, card.id).children[0])+ expect(root.inlineStyle).toMatchObject({ width: '240px' })+ expect(root.inlineStyle?.height).toBeUndefined()+ const [title, dot] = root.children.map(element)+ expect(title.inlineStyle?.width).toBeUndefined()+ expect(title.inlineStyle?.height).toBeUndefined()+ expect(dot.inlineStyle).toMatchObject({ width: '20px', 'border-radius': '50%' })+ })+})diff --git a/packages/scene-graph/AGENTS.md b/packages/scene-graph/AGENTS.mdindex 7e4be1219..f54ced3f4 100644--- a/packages/scene-graph/AGENTS.md+++ b/packages/scene-graph/AGENTS.md@@ -14,7 +14,7 @@ Framework-neutral document model. Owns node types, primitives, geometry, matrice- `componentScale` records an occurrence's coordinates relative to its component definition. Shared rescaling lives in `packages/scene-graph/src/scaling/`; Core's Figma API delegates there instead of scaling nodes itself.- Shared primitives that format packages and collaboration need live here: color conversion and management under `@open-pencil/scene-graph/color`, text/layout direction under `@open-pencil/scene-graph/text-direction`, and fractional sibling order keys under `@open-pencil/scene-graph/order-keys` (`packages/scene-graph/tests/order-keys.test.ts`).- CSS values that become scene-graph types, such as grid track lists, are parsed in `@open-pencil/scene-graph/css` on `postcss-value-parser`; design-jsx and dom-css call it instead of splitting or matching CSS by hand (`packages/scene-graph/tests/css`).-- Every plugin-data key OpenPencil writes is a field of `OPEN_PENCIL_PLUGIN_DATA` in `packages/scene-graph/src/plugin-data/fields.ts`, with the Valibot schema that reads it; read and replace entries with `readPluginData` and `withPluginData` instead of matching `pluginId` and `key` by hand. The fields test checks that keys stay unique.+- Every plugin-data key OpenPencil writes is a field of `OPEN_PENCIL_PLUGIN_DATA` in `packages/scene-graph/src/plugin-data/fields.ts`, with the Valibot schema that reads it and its role: `content` travels with library assets and counts towards their hash (`contentPluginData`), `format` repeats a node field for files, `bookkeeping` stays behind. Read and replace entries with `readPluginData` and `withPluginData` instead of matching `pluginId` and `key` by hand. The fields test checks that keys stay unique.- Vector network types live here; the reverse-engineered `vectorNetworkBlob` codecs live in `packages/core/src/vector/`.- `packages/scene-graph/src/checkpoint.ts` owns transaction checkpoint recovery, including hierarchy and indexes; Core's atomic tool execution relies on it.- Export named types and primitives (`Color`, `Vector`, `Rect`, `SceneNode`, `Effect`, `Fill`, `Stroke`) from the public entry; downstream packages reuse them instead of respelling shapes.diff --git a/packages/scene-graph/README.md b/packages/scene-graph/README.mdindex 96880684e..3d28d3005 100644--- a/packages/scene-graph/README.md+++ b/packages/scene-graph/README.md@@ -2,4 +2,4 @@Shared OpenPencil design document model.-This package owns `SceneGraph`, `SceneNode`, paint/effect/layout/variable types, graph mutation helpers, source metadata, and model-level utilities. It does not own editor state, UI, file format policy, rendering, or app document I/O.+This package owns `SceneGraph`, `SceneNode`, paint/effect/layout/variable types, graph mutation helpers, source metadata, and model-level utilities, including component slots and behaviours: the contracts after Reka UI's primitives, the behaviour stored in plugin data, and specs that name properties and slots. It does not own editor state, UI, file format policy, rendering, or app document I/O.diff --git a/packages/scene-graph/src/behaviours/kinds.ts b/packages/scene-graph/src/behaviours/kinds.tsnew file mode 100644index 000000000..3f5870189--- /dev/null+++ b/packages/scene-graph/src/behaviours/kinds.ts@@ -0,0 +1,185 @@+/** The controls a main component can behave as, in the order the picker lists them. */+export const BEHAVIOUR_KINDS = [+ 'button',+ 'textField',+ 'textarea',+ 'numberField',+ 'toggle',+ 'switch',+ 'checkbox',+ 'radio',+ 'radioGroup',+ 'toggleGroup',+ 'slider',+ 'progress',+ 'tabs',+ 'collapsible',+ 'accordion'+] as const++export type BehaviourKind = (typeof BEHAVIOUR_KINDS)[number]++/**+ * The interaction states a control can show, each drawn as a value of one variant property:+ * at rest, under the pointer, while pressed, focused from the keyboard, and disabled.+ */+export const INTERACTION_STATES = ['rest', 'hover', 'pressed', 'focus', 'disabled'] as const++export type InteractionState = (typeof INTERACTION_STATES)[number]++/**+ * How a behaviour value is held. A boolean is a variant or boolean property of the component,+ * and text is a text property. Figma has no number property, so a number is the behaviour's+ * own (min, max, step, default); a choice is which item of a slot is active, the first by+ * default.+ */+export type BehaviourValueType = 'boolean' | 'text' | 'number' | 'choice'++/** A value of the control: its state, which preview reads and changes. */+export interface BehaviourValueContract {+ id: string+ type: BehaviourValueType+ /** Whether a boolean or text value must be bound before the behaviour is complete. */+ required: boolean+}++/**+ * A Reka UI subcomponent of the control, which is a slot of the component: the behaviour binds+ * it to one of the component's slot properties, never to a layer found by name.+ */+export interface BehaviourPartContract {+ id: string+ required: boolean+ /**+ * Whether the slot holds the control's items, each an instance with its own behaviour (a+ * radio, a toggle, a collapsible), which the control turns on and off.+ */+ items?: boolean+ /**+ * The Reka UI part each child of the slot is, when the slot holds repeated parts: a tab list's+ * triggers, the tabs' content panels, or a group's items.+ */+ children?: string+}++export interface BehaviourContract {+ values: BehaviourValueContract[]+ parts: BehaviourPartContract[]+}++/**+ * A text field or textarea: its text is a text property, and `filled`, when bound, draws the+ * empty field with its placeholder.+ */+const TEXT_INPUT: BehaviourContract = {+ values: [+ { id: 'value', type: 'text', required: true },+ { id: 'filled', type: 'boolean', required: false },+ { id: 'disabled', type: 'boolean', required: false }+ ],+ parts: []+}++/**+ * The behaviours OpenPencil knows, after Reka UI's primitives. Their states are drawn as the+ * component's variants and properties; their subcomponents (thumb, range, trigger, …) are the+ * component's slots, and the component itself is the control's root.+ */+export const BEHAVIOUR_CONTRACTS: Readonly<Record<BehaviourKind, BehaviourContract>> = {+ button: {+ values: [{ id: 'disabled', type: 'boolean', required: false }],+ parts: []+ },+ textField: TEXT_INPUT,+ textarea: TEXT_INPUT,+ numberField: {+ values: [+ { id: 'value', type: 'number', required: false },+ { id: 'text', type: 'text', required: true },+ { id: 'disabled', type: 'boolean', required: false }+ ],+ parts: [+ { id: 'increment', required: false },+ { id: 'decrement', required: false }+ ]+ },+ toggle: {+ values: [+ { id: 'value', type: 'boolean', required: true },+ { id: 'disabled', type: 'boolean', required: false }+ ],+ parts: []+ },+ switch: {+ values: [+ { id: 'value', type: 'boolean', required: true },+ { id: 'disabled', type: 'boolean', required: false }+ ],+ parts: [{ id: 'thumb', required: false }]+ },+ checkbox: {+ values: [+ { id: 'value', type: 'boolean', required: true },+ { id: 'disabled', type: 'boolean', required: false }+ ],+ parts: [{ id: 'indicator', required: false }]+ },+ radio: {+ values: [+ { id: 'value', type: 'boolean', required: true },+ { id: 'disabled', type: 'boolean', required: false }+ ],+ parts: [{ id: 'indicator', required: false }]+ },+ radioGroup: {+ values: [{ id: 'disabled', type: 'boolean', required: false }],+ parts: [{ id: 'items', required: true, items: true, children: 'item' }]+ },+ toggleGroup: {+ values: [{ id: 'disabled', type: 'boolean', required: false }],+ parts: [{ id: 'items', required: true, items: true, children: 'item' }]+ },+ slider: {+ values: [+ { id: 'value', type: 'number', required: false },+ { id: 'disabled', type: 'boolean', required: false }+ ],+ parts: [+ { id: 'track', required: true },+ { id: 'range', required: false },+ { id: 'thumb', required: true }+ ]+ },+ tabs: {+ values: [{ id: 'value', type: 'choice', required: false }],+ parts: [+ { id: 'list', required: true, children: 'trigger' },+ { id: 'panels', required: false, children: 'content' }+ ]+ },+ progress: {+ values: [{ id: 'value', type: 'number', required: false }],+ parts: [+ { id: 'track', required: true },+ { id: 'indicator', required: true }+ ]+ },+ collapsible: {+ values: [+ { id: 'open', type: 'boolean', required: false },+ { id: 'disabled', type: 'boolean', required: false }+ ],+ parts: [+ { id: 'trigger', required: true },+ { id: 'content', required: true }+ ]+ },+ accordion: {+ values: [{ id: 'disabled', type: 'boolean', required: false }],+ parts: [{ id: 'items', required: true, items: true, children: 'item' }]+ }+}++export function behaviourContract(kind: BehaviourKind): BehaviourContract {+ return BEHAVIOUR_CONTRACTS[kind]+}diff --git a/packages/scene-graph/src/behaviours/model.ts b/packages/scene-graph/src/behaviours/model.tsnew file mode 100644index 000000000..560cde38f--- /dev/null+++ b/packages/scene-graph/src/behaviours/model.ts@@ -0,0 +1,192 @@+import type { SceneGraph } from '../index'+import { readPluginData, withPluginData } from '../plugin-data/field'+import { OPEN_PENCIL_PLUGIN_DATA } from '../plugin-data/fields'+import type { ComponentPropertyDefinition, SceneNode } from '../types'+import {+ behaviourContract,+ INTERACTION_STATES,+ type BehaviourKind,+ type InteractionState+} from './kinds'+import type {+ Behaviour,+ BehaviourBooleanBinding,+ BehaviourInteractionStates,+ BehaviourNumberSettings+} from './schema'++export type {+ Behaviour,+ BehaviourBooleanBinding,+ BehaviourInteractionStates,+ BehaviourNumberSettings+} from './schema'+export { isNumberRange } from './schema'++export const DEFAULT_NUMBER_SETTINGS: BehaviourNumberSettings = {+ min: 0,+ max: 100,+ step: 1,+ default: 50+}++/** A boolean value's binding, if the behaviour has one. */+export function booleanBinding(+ behaviour: Behaviour,+ valueId: string+): BehaviourBooleanBinding | undefined {+ return Object.hasOwn(behaviour.booleans, valueId) ? behaviour.booleans[valueId] : undefined+}++/** The slot property a part is bound to, if any. */+export function partBinding(behaviour: Behaviour, partId: string): string | undefined {+ return Object.hasOwn(behaviour.parts, partId) ? behaviour.parts[partId] : undefined+}++/** The text property a text value is bound to, if any. */+export function textBinding(behaviour: Behaviour, valueId: string): string | undefined {+ return Object.hasOwn(behaviour.texts, valueId) ? behaviour.texts[valueId].propertyId : undefined+}++/** A number value's range, if the behaviour has one. */+export function numberSettings(+ behaviour: Behaviour,+ valueId: string+): BehaviourNumberSettings | undefined {+ return Object.hasOwn(behaviour.numbers, valueId) ? behaviour.numbers[valueId] : undefined+}++/** A new behaviour of a kind, its number values at their defaults and nothing bound. */+export function emptyBehaviour(kind: BehaviourKind): Behaviour {+ const contract = behaviourContract(kind)+ const numbers = Object.fromEntries(+ contract.values+ .filter((value) => value.type === 'number')+ .map((value) => [value.id, { ...DEFAULT_NUMBER_SETTINGS }])+ )+ return { kind, booleans: {}, texts: {}, numbers, parts: {} }+}++/**+ * The node that keeps the behaviour: a component set for its variants, otherwise the main+ * component itself.+ */+export function behaviourOwner(graph: SceneGraph, node: SceneNode): SceneNode | undefined {+ if (node.type === 'COMPONENT_SET') return node+ if (node.type !== 'COMPONENT') return undefined+ const parent = node.parentId ? graph.getNode(node.parentId) : undefined+ return parent?.type === 'COMPONENT_SET' ? parent : node+}++/** The behaviour a component or component set keeps, or null when it has none or it is unreadable. */+export function readBehaviour(owner: SceneNode): Behaviour | null {+ return readPluginData(owner.pluginData, OPEN_PENCIL_PLUGIN_DATA.behaviour) ?? null+}++/** The owner's plugin data with the behaviour set, or removed when null. */+export function withBehaviour(+ owner: SceneNode,+ behaviour: Behaviour | null+): SceneNode['pluginData'] {+ return withPluginData(owner.pluginData, OPEN_PENCIL_PLUGIN_DATA.behaviour, behaviour ?? undefined)+}++/** Component properties the behaviour can bind to: the owner's, and a set's variants' own. */+export function behaviourProperties(+ graph: SceneGraph,+ owner: SceneNode+): ComponentPropertyDefinition[] {+ const variants =+ owner.type === 'COMPONENT_SET'+ ? owner.childIds.flatMap((id) => graph.getNode(id)?.componentPropertyDefinitions ?? [])+ : []+ const seen = new Set<string>()+ return [...owner.componentPropertyDefinitions, ...variants].filter((definition) => {+ if (seen.has(definition.id)) return false+ seen.add(definition.id)+ return true+ })+}++/**+ * Required values and parts that are unbound, or bound to a property the component no longer+ * has, by value or part id; `states` when the interaction states lost their variant property.+ */+export function missingBindings(+ graph: SceneGraph,+ owner: SceneNode,+ behaviour: Behaviour+): string[] {+ const contract = behaviourContract(behaviour.kind)+ const properties = new Map(+ behaviourProperties(graph, owner).map((definition) => [definition.id, definition])+ )+ const bound = (propertyId: string | undefined, type: ComponentPropertyDefinition['type'][]) => {+ const definition = propertyId ? properties.get(propertyId) : undefined+ return !!definition && type.includes(definition.type)+ }+ const values = contract.values+ .filter((value) => value.required)+ .filter((value) =>+ value.type === 'text'+ ? !bound(textBinding(behaviour, value.id), ['TEXT'])+ : value.type === 'boolean' &&+ !bound(booleanBinding(behaviour, value.id)?.propertyId, ['VARIANT', 'BOOLEAN'])+ )+ .map((value) => value.id)+ const parts = contract.parts+ .filter((part) => part.required && !bound(partBinding(behaviour, part.id), ['SLOT']))+ .map((part) => part.id)+ const states =+ behaviour.states && !bound(behaviour.states.propertyId, ['VARIANT']) ? ['states'] : []+ return [...values, ...parts, ...states]+}++/** Variant value names that usually mean each interaction state, compared case-insensitively. */+const STATE_NAMES: Record<InteractionState, readonly string[]> = {+ rest: ['default', 'rest', 'idle', 'normal', 'enabled'],+ hover: ['hover', 'hovered', 'hovering'],+ pressed: ['pressed', 'active', 'down', 'pressing'],+ focus: ['focus', 'focused', 'focus visible', 'focus-visible'],+ disabled: ['disabled', 'inactive']+}++/**+ * Interaction states for a variant property, each mapped to the value whose name means it, such+ * as `Hover` or `Pressed`; states without such a value are left unset.+ */+export function guessInteractionStates(+ propertyId: string,+ values: readonly string[]+): BehaviourInteractionStates {+ const states: BehaviourInteractionStates = { propertyId }+ for (const state of INTERACTION_STATES) {+ const match = values.find((value) => STATE_NAMES[state].includes(value.trim().toLowerCase()))+ if (match) states[state] = match+ }+ return states+}++/**+ * The behaviour with every component property id it binds renamed by `rename`, for formats that+ * give properties new ids on write, such as `.fig` with its GUIDs.+ */+export function renameBehaviourProperties(+ behaviour: Behaviour,+ rename: (propertyId: string) => string+): Behaviour {+ const mapValues = <T>(record: Record<string, T>, change: (value: T) => T) =>+ Object.fromEntries(Object.entries(record).map(([key, value]) => [key, change(value)]))+ return {+ ...behaviour,+ booleans: mapValues(behaviour.booleans, (binding) => ({+ ...binding,+ propertyId: rename(binding.propertyId)+ })),+ texts: mapValues(behaviour.texts, (binding) => ({ propertyId: rename(binding.propertyId) })),+ parts: mapValues(behaviour.parts, rename),+ ...(behaviour.states+ ? { states: { ...behaviour.states, propertyId: rename(behaviour.states.propertyId) } }+ : {})+ }+}diff --git a/packages/scene-graph/src/behaviours/schema.ts b/packages/scene-graph/src/behaviours/schema.tsnew file mode 100644index 000000000..60230707d--- /dev/null+++ b/packages/scene-graph/src/behaviours/schema.ts@@ -0,0 +1,58 @@+import * as v from 'valibot'++import { BEHAVIOUR_KINDS, type InteractionState } from './kinds'++const BooleanBinding = v.object({+ propertyId: v.string(),+ /** For a variant property: the values that mean on and off. */+ on: v.optional(v.string()),+ off: v.optional(v.string())+})++/** Whether a number value's range can be stepped through: `max` above `min`, a positive step. */+export function isNumberRange(settings: { min: number; max: number; step: number }): boolean {+ return settings.max > settings.min && settings.step > 0+}++const NumberSettings = v.pipe(+ v.object({+ min: v.pipe(v.number(), v.finite()),+ max: v.pipe(v.number(), v.finite()),+ step: v.pipe(v.number(), v.finite()),+ default: v.pipe(v.number(), v.finite())+ }),+ v.check(+ (settings) => isNumberRange(settings),+ 'A number value needs max above min and a positive step'+ )+)++/** Each interaction state's variant value, by state; a state left out shows the rest value. */+export const interactionStateValues = {+ rest: v.optional(v.string()),+ hover: v.optional(v.string()),+ pressed: v.optional(v.string()),+ focus: v.optional(v.string()),+ disabled: v.optional(v.string())+} satisfies Record<InteractionState, unknown>++const InteractionStates = v.object({ propertyId: v.string(), ...interactionStateValues })++export const behaviourSchema = v.object({+ kind: v.picklist(BEHAVIOUR_KINDS),+ /** Boolean values, by value id, bound to component properties. */+ booleans: v.record(v.string(), BooleanBinding),+ /** Text values, by value id, bound to text properties. */+ texts: v.optional(v.record(v.string(), v.object({ propertyId: v.string() })), {}),+ /** Number values, by value id: the range the behaviour keeps itself. */+ numbers: v.record(v.string(), NumberSettings),+ /** Parts, by part id, bound to slot properties. */+ parts: v.record(v.string(), v.string()),+ states: v.optional(InteractionStates)+})++/** How a main component behaves as a control, as kept in its plugin data. */+export type Behaviour = v.InferOutput<typeof behaviourSchema>+export type BehaviourBooleanBinding = v.InferOutput<typeof BooleanBinding>+export type BehaviourNumberSettings = v.InferOutput<typeof NumberSettings>+export type BehaviourInteractionStates = v.InferOutput<typeof InteractionStates>diff --git a/packages/scene-graph/src/behaviours/spec.ts b/packages/scene-graph/src/behaviours/spec.tsnew file mode 100644index 000000000..cf8b876e9--- /dev/null+++ b/packages/scene-graph/src/behaviours/spec.ts@@ -0,0 +1,223 @@+import { omitBy } from 'es-toolkit/object'+import * as v from 'valibot'++import type { SceneGraph } from '../index'+import type { ComponentPropertyDefinition, SceneNode } from '../types'+import { BEHAVIOUR_KINDS, behaviourContract, type BehaviourKind } from './kinds'+import {+ behaviourProperties,+ emptyBehaviour,+ guessInteractionStates,+ textBinding,+ type Behaviour,+ type BehaviourNumberSettings+} from './model'+import { interactionStateValues, isNumberRange } from './schema'++/**+ * A behaviour as scripts, tools, and JSX write it: component properties and slots by name, not+ * by id. Values are boolean or text values by their contract id; numbers are a slider's or+ * number field's own range.+ */+export const behaviourSpecSchema = v.object({+ kind: v.picklist(BEHAVIOUR_KINDS),+ values: v.optional(+ v.record(+ v.string(),+ v.union([+ v.string(),+ v.object({ property: v.string(), on: v.optional(v.string()), off: v.optional(v.string()) })+ ])+ )+ ),+ numbers: v.optional(+ v.record(+ v.string(),+ v.object({+ min: v.optional(v.number()),+ max: v.optional(v.number()),+ step: v.optional(v.number()),+ default: v.optional(v.number())+ })+ )+ ),+ parts: v.optional(v.record(v.string(), v.string())),+ states: v.optional(+ v.union([v.string(), v.object({ property: v.string(), ...interactionStateValues })])+ )+})++export type BehaviourSpec = v.InferOutput<typeof behaviourSpecSchema>++/** Variant values that usually mean on, compared case-insensitively. */+const ON_NAMES = ['on', 'true', 'yes', 'checked', 'pressed', 'open', 'selected', 'active']+const OFF_NAMES = ['off', 'false', 'no', 'unchecked', 'closed', 'default', 'inactive']++function named(names: readonly string[], options: readonly string[]): string | undefined {+ return options.find((option) => names.includes(option.trim().toLowerCase()))+}++/**+ * The variant values that likely mean on and off: names such as On, True, or Checked first,+ * then the values in order.+ */+export function guessOnOff(+ options: readonly string[],+ explicit: { on?: string; off?: string } = {}+): { on?: string; off?: string } {+ const on = explicit.on ?? named(ON_NAMES, options) ?? options[0]+ const off = explicit.off ?? named(OFF_NAMES, options) ?? options.find((option) => option !== on)+ return { on, off }+}++function findProperty(+ properties: readonly ComponentPropertyDefinition[],+ name: string,+ types: readonly ComponentPropertyDefinition['type'][],+ what: string+): ComponentPropertyDefinition {+ const found = properties.find((item) => item.name === name && types.includes(item.type))+ if (found) return found+ const available = properties.filter((item) => types.includes(item.type)).map((item) => item.name)+ throw new Error(+ `${what} needs a ${types.join(' or ')} property named "${name}"; the component has ${+ available.length ? available.map((item) => `"${item}"`).join(', ') : 'none'+ }`+ )+}++type ValueBinding = NonNullable<BehaviourSpec['values']>[string]+type StatesSpec = NonNullable<BehaviourSpec['states']>++function listed(items: readonly { id: string }[]): string {+ return items.map((item) => `"${item.id}"`).join(', ')+}++/** Bind a boolean or text value to the property named in its binding. */+function resolveValue(+ behaviour: Behaviour,+ properties: readonly ComponentPropertyDefinition[],+ valueId: string,+ binding: ValueBinding+): void {+ const contract = behaviourContract(behaviour.kind)+ const bindable = contract.values.filter((item) => item.type === 'boolean' || item.type === 'text')+ const value = bindable.find((item) => item.id === valueId)+ if (!value)+ throw new Error(+ `A ${behaviour.kind} has no boolean or text value "${valueId}"; it has ${listed(bindable)}`+ )+ const name = typeof binding === 'string' ? binding : binding.property+ if (value.type === 'text') {+ behaviour.texts[valueId] = { propertyId: findProperty(properties, name, ['TEXT'], valueId).id }+ return+ }+ const definition = findProperty(properties, name, ['VARIANT', 'BOOLEAN'], valueId)+ if (definition.type === 'BOOLEAN') {+ behaviour.booleans[valueId] = { propertyId: definition.id }+ return+ }+ const options = definition.variantOptions ?? []+ const explicit: { on?: string; off?: string } = typeof binding === 'string' ? {} : binding+ const { on, off } = guessOnOff(options, explicit)+ for (const choice of [on, off])+ if (choice !== undefined && !options.includes(choice))+ throw new Error(`"${definition.name}" has no value "${choice}"; it has ${options.join(', ')}`)+ behaviour.booleans[valueId] = { propertyId: definition.id, on, off }+}++function resolveStates(+ behaviour: Behaviour,+ properties: readonly ComponentPropertyDefinition[],+ states: StatesSpec+): void {+ const name = typeof states === 'string' ? states : states.property+ const definition = findProperty(properties, name, ['VARIANT'], 'states')+ const guessed = guessInteractionStates(definition.id, definition.variantOptions ?? [])+ if (typeof states === 'string') {+ behaviour.states = guessed+ return+ }+ const { property: _property, ...values } = states+ behaviour.states = { ...guessed, ...stripUndefined(values) }+}++/**+ * The stored behaviour for a spec, with names resolved to the owner's property and slot ids. A+ * name the component lacks, a value the kind does not have, or a variant value the property+ * does not offer fails with a message naming what exists.+ */+export function behaviourFromSpec(+ graph: SceneGraph,+ owner: SceneNode,+ spec: BehaviourSpec+): Behaviour {+ const contract = behaviourContract(spec.kind)+ const properties = behaviourProperties(graph, owner)+ const behaviour = emptyBehaviour(spec.kind)+ for (const [valueId, binding] of Object.entries(spec.values ?? {}))+ resolveValue(behaviour, properties, valueId, binding)+ const numbers = contract.values.filter((item) => item.type === 'number')+ for (const [valueId, settings] of Object.entries(spec.numbers ?? {})) {+ if (!numbers.some((item) => item.id === valueId))+ throw new Error(`A ${spec.kind} has no number value "${valueId}"; it has ${listed(numbers)}`)+ const range = { ...behaviour.numbers[valueId], ...stripUndefined(settings) }+ if (!isNumberRange(range))+ throw new Error(`"${valueId}" needs max above min and a positive step`)+ behaviour.numbers[valueId] = range+ }+ for (const [partId, slotName] of Object.entries(spec.parts ?? {})) {+ if (!contract.parts.some((item) => item.id === partId))+ throw new Error(`A ${spec.kind} has no part "${partId}"; it has ${listed(contract.parts)}`)+ const id = findProperty(properties, slotName, ['SLOT'], partId).id+ const taken = Object.entries(behaviour.parts).find(([, slot]) => slot === id)?.[0]+ if (taken) throw new Error(`"${slotName}" is already the ${taken}; a slot draws one part`)+ behaviour.parts[partId] = id+ }+ if (spec.states !== undefined) resolveStates(behaviour, properties, spec.states)+ return behaviour+}++function stripUndefined<T extends Record<string, unknown>>(record: T): Partial<T> {+ return omitBy(record, (value) => value === undefined)+}++/** The spec a stored behaviour reads as, with ids back to names; unresolved bindings are left out. */+export function behaviourToSpec(+ graph: SceneGraph,+ owner: SceneNode,+ behaviour: Behaviour+): BehaviourSpec {+ const properties = behaviourProperties(graph, owner)+ const nameOf = (id: string | undefined) => properties.find((item) => item.id === id)?.name+ const values: NonNullable<BehaviourSpec['values']> = {}+ for (const [valueId, binding] of Object.entries(behaviour.booleans)) {+ const name = nameOf(binding.propertyId)+ if (name)+ values[valueId] =+ binding.on || binding.off ? { property: name, on: binding.on, off: binding.off } : name+ }+ for (const valueId of Object.keys(behaviour.texts)) {+ const name = nameOf(textBinding(behaviour, valueId))+ if (name) values[valueId] = name+ }+ const parts = Object.fromEntries(+ Object.entries(behaviour.parts).flatMap(([partId, id]) => {+ const name = nameOf(id)+ return name ? [[partId, name]] : []+ })+ )+ const statesName = nameOf(behaviour.states?.propertyId)+ const spec: BehaviourSpec = { kind: behaviour.kind }+ if (Object.keys(values).length) spec.values = values+ if (Object.keys(behaviour.numbers).length) spec.numbers = structuredClone(behaviour.numbers)+ if (Object.keys(parts).length) spec.parts = parts+ if (behaviour.states && statesName)+ spec.states = {+ ...stripUndefined({ ...behaviour.states, propertyId: undefined }),+ property: statesName+ }+ return spec+}++export type { BehaviourKind, BehaviourNumberSettings }diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.tsindex 0a7b59f41..ff9f09f91 100644--- a/packages/scene-graph/src/index.ts+++ b/packages/scene-graph/src/index.ts@@ -19,6 +19,9 @@ export { instanceMainComponent } from './instances/main-component'export * from './slots/content'export * from './slots/authoring'export * from './slots/limits'+export * from './behaviours/kinds'+export * from './behaviours/model'+export * from './behaviours/spec'export * from './copy'export { createDefaultNode, FITTED_CONTAINER_TYPES } from './node-defaults'export {diff --git a/packages/scene-graph/src/plugin-data/field.ts b/packages/scene-graph/src/plugin-data/field.tsindex b1592ece7..37cedf6e2 100644--- a/packages/scene-graph/src/plugin-data/field.ts+++ b/packages/scene-graph/src/plugin-data/field.ts@@ -5,9 +5,20 @@ import type { PluginDataEntry } from '../types'/** The plugin id OpenPencil keeps its own state under, on nodes and in `.fig` files. */export const OPEN_PENCIL_PLUGIN_ID = 'open-pencil'+/**+ * What a field holds:+ * - `content` belongs to the node like its fills do and exists only as plugin data, so it+ * travels with a component copied into a library or another document;+ * - `format` repeats a node or variable field for files that have no slot for it, where the+ * node field is what counts;+ * - `bookkeeping` records where a node or document came from and stays behind.+ */+export type PluginDataRole = 'content' | 'format' | 'bookkeeping'+/** One OpenPencil plugin-data key. */export interface PluginDataKey {readonly key: string+ readonly role: PluginDataRole}/** A plugin-data key and how its string value is read and written. */@@ -23,11 +34,13 @@ export interface PluginDataField<T> extends PluginDataKey {*/export function jsonPluginDataField<T>(key: string,+ role: PluginDataRole,schema: v.GenericSchema<unknown, T>): PluginDataField<T> {const stored = v.pipe(v.string(), v.parseJson(), schema)return {key,+ role,decode(value) {const parsed = v.safeParse(stored, value)return parsed.success ? parsed.output : undefined@@ -39,11 +52,13 @@ export function jsonPluginDataField<T>(/** A value stored as one of a fixed set of plain strings. */export function textPluginDataField<const T extends string>(key: string,+ role: PluginDataRole,values: readonly T[]): PluginDataField<T> {const schema = v.picklist(values)return {key,+ role,decode(value) {const parsed = v.safeParse(schema, value)return parsed.success ? parsed.output : undefineddiff --git a/packages/scene-graph/src/plugin-data/fields.ts b/packages/scene-graph/src/plugin-data/fields.tsindex 7c87495a6..2448fff25 100644--- a/packages/scene-graph/src/plugin-data/fields.ts+++ b/packages/scene-graph/src/plugin-data/fields.ts@@ -1,5 +1,6 @@import * as v from 'valibot'+import { behaviourSchema } from '../behaviours/schema'import type { OkHCLPayload } from '../color/okhcl'import { isExportFormatId, type ExportFormatId } from '../export-format'import { clampExportScale } from '../export-scale'@@ -11,11 +12,17 @@ import {type ExportSetting,type LayoutDirection,type LibraryAssetSource,+ type PluginDataEntry,type SourceLibraryPublication,type TextDirection,type TokenUnit} from '../types'-import { jsonPluginDataField, textPluginDataField, type PluginDataKey } from './field'+import {+ jsonPluginDataField,+ textPluginDataField,+ withoutPluginData,+ type PluginDataKey+} from './field'const DIRECTIONS = ['AUTO', 'LTR', 'RTL'] as const satisfies readonly (| TextDirection@@ -129,34 +136,53 @@ const sourceLibraryPublication: v.GenericSchema<unknown, SourceLibraryPublicatio*/export const OPEN_PENCIL_PLUGIN_DATA = {/** A text node's direction, on TEXT nodes. */- textDirection: textPluginDataField('textDirection', DIRECTIONS),+ textDirection: textPluginDataField('textDirection', 'format', DIRECTIONS),/** An auto-layout frame's direction. */- layoutDirection: textPluginDataField('layoutDirection', DIRECTIONS),+ layoutDirection: textPluginDataField('layoutDirection', 'format', DIRECTIONS),/** Marks a component set Figma would read as a plain frame. */- nodeType: textPluginDataField('nodeType', ['COMPONENT_SET']),+ nodeType: textPluginDataField('nodeType', 'format', ['COMPONENT_SET']),/** Variable bindings by field path, including those Figma cannot store natively. */- boundVariables: jsonPluginDataField('boundVariables', boundVariables),- exportSettings: jsonPluginDataField('exportSettings', exportSettings),+ boundVariables: jsonPluginDataField('boundVariables', 'format', boundVariables),+ exportSettings: jsonPluginDataField('exportSettings', 'format', exportSettings),/** The node-local rect a TEXT_PATH layout maps onto, which Kiwi has no field for. */- textPathBox: jsonPluginDataField('textPathBox', textPathBox),+ textPathBox: jsonPluginDataField('textPathBox', 'format', textPathBox),/** The library asset a node was inserted from. */- librarySource: jsonPluginDataField('librarySource', librarySource),+ librarySource: jsonPluginDataField('librarySource', 'bookkeeping', librarySource),/** Libraries enabled for the document, on the DOCUMENT node. */- enabledLibraries: jsonPluginDataField('enabledLibraries', enabledLibraries),+ enabledLibraries: jsonPluginDataField('enabledLibraries', 'bookkeeping', enabledLibraries),/** The library this document publishes as, on the DOCUMENT node. */sourceLibraryPublication: jsonPluginDataField('sourceLibraryPublication',+ 'bookkeeping',sourceLibraryPublication),/** Unit and CSS expressions, on each VARIABLE. */- token: jsonPluginDataField('token', token),+ token: jsonPluginDataField('token', 'format', token),/** Mode conditions by mode id, on each VARIABLE_SET. */- modeConditions: jsonPluginDataField('modeConditions', v.record(v.string(), cssText)),+ modeConditions: jsonPluginDataField('modeConditions', 'format', v.record(v.string(), cssText)),/** The attribute that switches manual modes, on each VARIABLE_SET. */modeAttribute: jsonPluginDataField('modeAttribute',+ 'format',v.pipe(v.string(), v.trim(), v.maxLength(100), v.regex(MODE_ATTRIBUTE_PATTERN))),/** One entry per paint picked in OkHCL, so the picker reopens on the same coordinates. */- okhcl: jsonPluginDataField('okhcl', okhcl)+ okhcl: jsonPluginDataField('okhcl', 'content', okhcl),+ /** How a main component or component set behaves as a control in preview. */+ behaviour: jsonPluginDataField('behaviour', 'content', behaviourSchema)} satisfies Record<string, PluginDataKey>++const NOT_CONTENT = Object.values(OPEN_PENCIL_PLUGIN_DATA).filter(+ (field) => field.role !== 'content'+)++/**+ * A node's plugin data that is part of its content, in a stable order: OpenPencil's content+ * fields and every other plugin's entries, which the node carries wherever it goes. Format+ * copies of node fields and bookkeeping are left out.+ */+export function contentPluginData(entries: readonly PluginDataEntry[]): PluginDataEntry[] {+ return withoutPluginData(entries, NOT_CONTENT).sort(+ (a, b) => a.pluginId.localeCompare(b.pluginId) || a.key.localeCompare(b.key)+ )+}diff --git a/packages/scene-graph/src/variant-properties.ts b/packages/scene-graph/src/variant-properties.tsindex e14abe467..abe4e779e 100644--- a/packages/scene-graph/src/variant-properties.ts+++ b/packages/scene-graph/src/variant-properties.ts@@ -1,4 +1,7 @@+import { uniq } from 'es-toolkit/array'+import type { ComponentPropertyDefinition, SceneNode } from './types'+import { buildVariantName, parseVariantName } from './variant-name'export interface DerivedVariantProperties {definitions: ComponentPropertyDefinition[]@@ -46,3 +49,50 @@ export function deriveSlashVariantProperties(return { definitions, variants }}++/**+ * Variant properties from names written as `Property=Value` pairs, as Figma names variants:+ * `State=On, Size=Large` gives State and Size. Every component must name at least one pair;+ * a property a component leaves out takes an empty value.+ */+export function deriveNamedVariantProperties(+ components: ReadonlyArray<Pick<SceneNode, 'id' | 'name'>>,+ createPropertyId: () => string+): DerivedVariantProperties | null {+ const parsed = components.map((component) => parseVariantName(component.name))+ if (parsed.some((values) => Object.keys(values).length === 0)) return null+ const names = uniq(parsed.flatMap((values) => Object.keys(values)))+ const definitions: ComponentPropertyDefinition[] = names.map((name) => {+ const options = uniq(parsed.map((values) => values[name] ?? ''))+ return {+ id: createPropertyId(),+ name,+ type: 'VARIANT',+ defaultValue: options[0] ?? '',+ variantOptions: options+ }+ })+ const variants = new Map(+ components.map((component, index) => {+ const componentPropertyValues = Object.fromEntries(+ names.map((name) => [name, parsed[index][name] ?? ''])+ )+ return [+ component.id,+ { componentPropertyValues, name: buildVariantName(componentPropertyValues) }+ ]+ })+ )+ return { definitions, variants }+}++/** Variant properties from component names: slash paths first, else `Property=Value` pairs. */+export function deriveVariantProperties(+ components: ReadonlyArray<Pick<SceneNode, 'id' | 'name'>>,+ createPropertyId: () => string+): DerivedVariantProperties | null {+ return (+ deriveSlashVariantProperties(components, createPropertyId) ??+ deriveNamedVariantProperties(components, createPropertyId)+ )+}diff --git a/packages/scene-graph/tests/behaviours/model.test.ts b/packages/scene-graph/tests/behaviours/model.test.tsnew file mode 100644index 000000000..4df31b51e--- /dev/null+++ b/packages/scene-graph/tests/behaviours/model.test.ts@@ -0,0 +1,105 @@+import { describe, expect, test } from 'bun:test'++import {+ behaviourOwner,+ emptyBehaviour,+ guessInteractionStates,+ missingBindings,+ readBehaviour,+ SceneGraph,+ withBehaviour+} from '@open-pencil/scene-graph'++/** A Switch set with a State variant property and a Thumb slot. */+function switchSet() {+ const graph = new SceneGraph()+ const pageId = graph.getPages()[0].id+ const set = graph.createNode('COMPONENT_SET', pageId, {+ name: 'Switch',+ componentPropertyDefinitions: [+ {+ id: 'state',+ name: 'State',+ type: 'VARIANT',+ defaultValue: 'Off',+ variantOptions: ['On', 'Off']+ }+ ]+ })+ const on = graph.createNode('COMPONENT', set.id, {+ name: 'State=On',+ componentPropertyValues: { State: 'On' },+ componentPropertyDefinitions: [{ id: 'thumb', name: 'Thumb', type: 'SLOT', defaultValue: '' }]+ })+ return { graph, set, on }+}++describe('behaviour model', () => {+ test('a variant keeps its behaviour on its set', () => {+ const { graph, set, on } = switchSet()+ expect(behaviourOwner(graph, on)?.id).toBe(set.id)+ expect(behaviourOwner(graph, set)?.id).toBe(set.id)+ })++ test('round-trips through plugin data and reports what is still unbound', () => {+ const { graph, set } = switchSet()+ const behaviour = emptyBehaviour('switch')+ graph.updateNode(set.id, { pluginData: withBehaviour(set, behaviour) })+ expect(readBehaviour(set)).toEqual(behaviour)+ expect(missingBindings(graph, set, behaviour)).toEqual(['value'])++ const bound = {+ ...behaviour,+ booleans: { value: { propertyId: 'state', on: 'On', off: 'Off' } }+ }+ expect(missingBindings(graph, set, bound)).toEqual([])+ expect(missingBindings(graph, set, { ...bound, parts: { thumb: 'state' } })).toEqual([])++ graph.updateNode(set.id, { pluginData: withBehaviour(set, null) })+ expect(readBehaviour(set)).toBeNull()+ })++ test('a slider keeps its own number range and requires track and thumb slots', () => {+ const { graph, set } = switchSet()+ const slider = emptyBehaviour('slider')+ expect(slider.numbers.value).toEqual({ min: 0, max: 100, step: 1, default: 50 })+ expect(missingBindings(graph, set, slider)).toEqual(['track', 'thumb'])+ expect(+ missingBindings(graph, set, { ...slider, parts: { track: 'state', thumb: 'thumb' } })+ ).toEqual(['track'])+ })++ test('a number range that cannot be stepped through reads as no behaviour', () => {+ const { graph, set } = switchSet()+ const slider = emptyBehaviour('slider')+ for (const range of [+ { min: 100, max: 0, step: 1, default: 50 },+ { min: 0, max: 100, step: 0, default: 50 }+ ]) {+ graph.updateNode(set.id, {+ pluginData: withBehaviour(set, { ...slider, numbers: { value: range } })+ })+ expect(readBehaviour(set)).toBeNull()+ }+ })++ test('unreadable plugin data reads as no behaviour', () => {+ const { graph, set } = switchSet()+ graph.updateNode(set.id, {+ pluginData: [{ pluginId: 'open-pencil', key: 'behaviour', value: '{"kind":"dial"}' }]+ })+ expect(readBehaviour(set)).toBeNull()+ })++ test('interaction states are guessed from variant value names', () => {+ expect(+ guessInteractionStates('interaction', ['Idle', 'Hovered', 'Active', 'Focus visible', 'Big'])+ ).toEqual({+ propertyId: 'interaction',+ rest: 'Idle',+ hover: 'Hovered',+ pressed: 'Active',+ focus: 'Focus visible'+ })+ })+})diff --git a/packages/scene-graph/tests/behaviours/spec.test.ts b/packages/scene-graph/tests/behaviours/spec.test.tsnew file mode 100644index 000000000..c95d8e68b--- /dev/null+++ b/packages/scene-graph/tests/behaviours/spec.test.ts@@ -0,0 +1,87 @@+import { describe, expect, test } from 'bun:test'++import {+ behaviourFromSpec,+ behaviourToSpec,+ guessOnOff,+ SceneGraph+} from '@open-pencil/scene-graph'++/** A switch set with State and Interaction variant properties and a Thumb slot. */+function switchSet() {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const set = graph.createNode('COMPONENT_SET', page.id, {+ name: 'Switch',+ componentPropertyDefinitions: [+ {+ id: 'p1',+ name: 'State',+ type: 'VARIANT',+ defaultValue: 'Off',+ variantOptions: ['Off', 'On']+ },+ {+ id: 'p2',+ name: 'Interaction',+ type: 'VARIANT',+ defaultValue: 'Default',+ variantOptions: ['Default', 'Hover']+ },+ { id: 'p3', name: 'Thumb', type: 'SLOT', defaultValue: '' }+ ]+ })+ return { graph, set }+}++describe('behaviour specs', () => {+ test('names resolve to the component’s property and slot ids, with on and off guessed', () => {+ const { graph, set } = switchSet()+ const behaviour = behaviourFromSpec(graph, set, {+ kind: 'switch',+ values: { value: 'State' },+ parts: { thumb: 'Thumb' },+ states: 'Interaction'+ })+ expect(behaviour.booleans.value).toEqual({ propertyId: 'p1', on: 'On', off: 'Off' })+ expect(behaviour.parts).toEqual({ thumb: 'p3' })+ expect(behaviour.states).toEqual({ propertyId: 'p2', rest: 'Default', hover: 'Hover' })++ expect(behaviourToSpec(graph, set, behaviour)).toEqual({+ kind: 'switch',+ values: { value: { property: 'State', on: 'On', off: 'Off' } },+ parts: { thumb: 'Thumb' },+ states: { property: 'Interaction', rest: 'Default', hover: 'Hover' }+ })+ })++ test('on and off are guessed by name before order', () => {+ expect(guessOnOff(['Off', 'On'])).toEqual({ on: 'On', off: 'Off' })+ expect(guessOnOff(['False', 'True'])).toEqual({ on: 'True', off: 'False' })+ expect(guessOnOff(['Small', 'Large'])).toEqual({ on: 'Small', off: 'Large' })+ })++ test('a name or value the component lacks fails with what it has', () => {+ const { graph, set } = switchSet()+ expect(() =>+ behaviourFromSpec(graph, set, { kind: 'switch', values: { value: 'Checked' } })+ ).toThrow(+ 'needs a VARIANT or BOOLEAN property named "Checked"; the component has "State", "Interaction"'+ )+ expect(() =>+ behaviourFromSpec(graph, set, { kind: 'switch', parts: { knob: 'Thumb' } })+ ).toThrow('A switch has no part "knob"; it has "thumb"')+ expect(() =>+ behaviourFromSpec(graph, set, {+ kind: 'switch',+ values: { value: { property: 'State', on: 'Enabled' } }+ })+ ).toThrow('"State" has no value "Enabled"; it has Off, On')+ expect(() =>+ behaviourFromSpec(graph, set, { kind: 'slider', numbers: { value: { min: 10, max: 5 } } })+ ).toThrow('"value" needs max above min and a positive step')+ expect(() =>+ behaviourFromSpec(graph, set, { kind: 'slider', parts: { track: 'Thumb', thumb: 'Thumb' } })+ ).toThrow('"Thumb" is already the track; a slot draws one part')+ })+})diff --git a/packages/scene-graph/tests/plugin-data/fields.test.ts b/packages/scene-graph/tests/plugin-data/fields.test.tsindex 74a6f2b9e..fff1c6592 100644--- a/packages/scene-graph/tests/plugin-data/fields.test.ts+++ b/packages/scene-graph/tests/plugin-data/fields.test.ts@@ -1,6 +1,7 @@import { describe, expect, test } from 'bun:test'import {+ contentPluginData,OPEN_PENCIL_PLUGIN_DATA,OPEN_PENCIL_PLUGIN_ID,readAllPluginData,@@ -24,6 +25,16 @@ function entry(key: string, value: string): PluginDataEntry {}describe('OpenPencil plugin data', () => {+ test('keeps content and other plugins’ entries as a node’s content', () => {+ const entries = [+ OTHER_PLUGIN,+ entry('textDirection', 'RTL'),+ entry('librarySource', '{}'),+ entry('okhcl', '[]')+ ]+ expect(contentPluginData(entries)).toEqual([entry('okhcl', '[]'), OTHER_PLUGIN])+ })+test('gives every field its own key', () => {const keys = Object.values(OPEN_PENCIL_PLUGIN_DATA).map((field) => field.key)expect(new Set(keys).size).toBe(keys.length)diff --git a/packages/vue/AGENTS.md b/packages/vue/AGENTS.mdindex e3dd8b78d..a9c1053aa 100644--- a/packages/vue/AGENTS.md+++ b/packages/vue/AGENTS.md@@ -15,6 +15,12 @@ Headless Vue 3 primitives and composables; the root app is one consumer. PrimitiThe app's `DesignPanel` retains at most one selection-property subtree through `RetainedPanel`. The app installs `createRetainedScopePlugin()`; opted-in descendants receive `provideRetainedActivity()`. Vue component scopes are detached, so pausing only a parent or bare `KeepAlive` does not suspend descendant work. Cancel drafts synchronously before DOM detachment can fire blur, close transient state and gate portals with `useRetainedPopup()`, and invalidate pending async results on deactivation or disposal. The plugin lets cleanup flush before pausing each component scope and resumes it on activation; it requires Vue's Options API. Unmounting the owning editor releases the retained subtree.+## Preview islands++- Preview runs controls as real components, never as canvas simulations: `packages/vue/src/canvas/islands/` renders each top-level layer that holds an instance with a behaviour as DOM in a shadow root over the canvas, projected through `@open-pencil/dom-css`, and mounts each behaviour's Reka UI primitives on its layers. Typing, focus, and keyboard handling belong to the browser and Reka.+- The concept, the pipeline from state to DOM, and how to add a kind are in `packages/docs/development/behaviours-and-preview.md`.+- Variants draw control states: Core's `resolvePlayState` shows instances in a state on a private graph, and controls are keyed by layer path so a variant switch keeps their DOM, including a focused input. The document is never changed (`packages/core/tests/editor/play/states.test.ts`, `tests/e2e/components/behaviours.spec.ts`).+## Commands, menus, i18n- Commands use `packages/vue/src/editor/commands/registry.ts` for shortcuts, bindings, and menu IDs. Store portable tokens (`MOD+D`) and format them at render time; labels and translations never contain shortcuts.diff --git a/packages/vue/README.md b/packages/vue/README.mdindex c391bfc12..ddf56cf96 100644--- a/packages/vue/README.md+++ b/packages/vue/README.md@@ -82,9 +82,12 @@ At the composable level, the main canvas APIs are:- `useCanvas()`- `useCanvasInput()`- `useTextEdit()`+- `PlayIslands`If you want SDK-provided structure, use headless primitives like `CanvasRoot` and `CanvasSurface`.+`PlayIslands` previews a canvas pane: place it over the canvas with the pane's view state, and while the pane's `play` state is set, each top-level layer holding components with behaviours runs as live Reka UI components in its own shadow root.+### Headless primitivesMain structural primitives include:diff --git a/packages/vue/package.json b/packages/vue/package.jsonindex 56deb0213..2303e489e 100644--- a/packages/vue/package.json+++ b/packages/vue/package.json@@ -45,6 +45,7 @@"@atlaskit/pragmatic-drag-and-drop-hitbox": "^1.2.0","@nanostores/i18n": "^1.3.3","@nanostores/vue": "^1.1.0",+ "@open-pencil/dom-css": "workspace:*","@open-pencil/scene-graph": "workspace:*","@vueuse/core": "^14.4.0","es-toolkit": "^1.52.0",diff --git a/packages/vue/src/canvas/index.ts b/packages/vue/src/canvas/index.tsindex c87e7e471..55e396f14 100644--- a/packages/vue/src/canvas/index.ts+++ b/packages/vue/src/canvas/index.ts@@ -2,3 +2,4 @@ export { default as CanvasRoot } from '#vue/canvas/CanvasRoot.vue'export { default as CanvasSurface } from '#vue/canvas/CanvasSurface.vue'export { useCanvasContext } from '#vue/canvas/context'export type { CanvasContext } from '#vue/canvas/context'+export { default as PlayIslands } from '#vue/canvas/islands/IslandLayer.vue'diff --git a/packages/vue/src/canvas/islands/Island.vue b/packages/vue/src/canvas/islands/Island.vuenew file mode 100644index 000000000..5b8a6f6b5--- /dev/null+++ b/packages/vue/src/canvas/islands/Island.vue@@ -0,0 +1,68 @@+<script setup lang="ts">+import { computed, shallowRef, useTemplateRef, watch } from 'vue'++import { resolvePlayState } from '@open-pencil/core/editor'+import { sceneNodeToDesignDocument } from '@open-pencil/dom-css/export'++import { useEditor } from '#vue/editor/context'++import { islandControls } from './model'+import { renderNode } from './render'+import { islandRoles } from './roles'+import { useShadowContainer } from './shadow'+import { createIslandState, instanceStates } from './state'++/**+ * One live island: a top-level layer that holds controls, rendered as DOM in its own shadow+ * root, with each control running as its Reka UI component. The design's variants draw the+ * controls' states; the document never changes.+ */+const { rootId, revision } = defineProps<{+ rootId: string+ /** Changing it starts every control again as designed. */+ revision: number+}>()+const editor = useEditor()++/** Styles of the island's own document; the app's styles do not reach into it. */+const ISLAND_CSS = ':host{all:initial;display:block}*,*::before,*::after{box-sizing:border-box}'+const container = useShadowContainer(useTemplateRef<HTMLElement>('host'), ISLAND_CSS)++const controls = computed(() => {+ void editor.state.sceneVersion+ return islandControls(editor.graph, rootId)+})+const roles = computed(() => islandRoles(controls.value))+const state = shallowRef(createIslandState(controls.value))+watch(+ () => [rootId, revision, [...controls.value.keys()].join('\n')],+ () => (state.value = createIslandState(controls.value))+)++const projection = computed(() => {+ void editor.state.sceneVersion+ const graph = resolvePlayState(editor.graph, rootId, instanceStates(controls.value, state.value))+ const [root] = sceneNodeToDesignDocument(graph, rootId).children+ return { graph, root }+})++/** The island's layers, rendered from the projection of their current states. */+function Layers() {+ const { graph, root } = projection.value+ return root+ ? renderNode(+ { graph, rootId, controls: controls.value, roles: roles.value, state: state.value },+ root,+ ''+ )+ : null+}+</script>++<template>+ <div ref="host" :data-island="rootId">+ <Teleport v-if="container" :to="container">+ <Layers />+ </Teleport>+ </div>+</template>diff --git a/packages/vue/src/canvas/islands/IslandLayer.vue b/packages/vue/src/canvas/islands/IslandLayer.vuenew file mode 100644index 000000000..3bbac62cf--- /dev/null+++ b/packages/vue/src/canvas/islands/IslandLayer.vue@@ -0,0 +1,58 @@+<script setup lang="ts">+import { computed } from 'vue'++import { playIslandRoots, type PlayState } from '@open-pencil/core/editor'++import { useEditor } from '#vue/editor/context'++import Island from './Island.vue'++/**+ * The live islands of a previewing canvas pane, laid over the canvas at its pan and zoom. The+ * canvas leaves these layers to the islands; wheel gestures over them still pan and zoom it.+ */+const { view, canvas } = defineProps<{+ view: { panX: number; panY: number; zoom: number; currentPageId: string; play: PlayState | null }+ /** The canvas that wheel gestures over the islands are passed on to. */+ canvas: HTMLElement | null+}>()+const editor = useEditor()++const islands = computed(() => {+ void editor.state.sceneVersion+ if (!view.play) return []+ return playIslandRoots(editor.graph, view.currentPageId).map((id) => ({+ id,+ position: editor.graph.getAbsolutePosition(id)+ }))+})++function forwardWheel(event: WheelEvent) {+ if (!canvas) return+ event.preventDefault()+ canvas.dispatchEvent(new WheelEvent(event.type, event))+}+</script>++<template>+ <div+ v-if="view.play"+ class="pointer-events-none absolute inset-0 overflow-hidden"+ data-test-id="play-islands"+ @wheel="forwardWheel"+ >+ <div+ class="absolute top-0 left-0 origin-top-left"+ :style="{ transform: `translate(${view.panX}px, ${view.panY}px) scale(${view.zoom})` }"+ >+ <Island+ v-for="island in islands"+ :key="island.id"+ :root-id="island.id"+ :revision="view.play.revision"+ class="pointer-events-auto absolute"+ :style="{ left: `${island.position.x}px`, top: `${island.position.y}px` }"+ />+ </div>+ </div>+</template>diff --git a/packages/vue/src/canvas/islands/controls/fields.ts b/packages/vue/src/canvas/islands/controls/fields.tsnew file mode 100644index 000000000..2e87bde12--- /dev/null+++ b/packages/vue/src/canvas/islands/controls/fields.ts@@ -0,0 +1,96 @@+import {+ NumberFieldDecrement,+ NumberFieldIncrement,+ NumberFieldInput,+ NumberFieldRoot+} from 'reka-ui'+import { h, type VNode } from 'vue'++import { numberSettings } from '@open-pencil/scene-graph'++import { booleanOf, type ControlModel } from '#vue/canvas/islands/model'+import type { ElementOverride, IslandRenderContext } from '#vue/canvas/islands/render'+import type { IslandRole } from '#vue/canvas/islands/roles'++import { disabled, interaction, stateOf } from './shared'++type Base = (override?: ElementOverride) => VNode++/** A text layer's look carried over to the input that replaces it. */+const INPUT_RESET: Record<string, string> = {+ border: 'none',+ outline: 'none',+ padding: '0',+ margin: '0',+ background: 'transparent',+ resize: 'none',+ 'box-sizing': 'border-box'+}++/** A text field, textarea, or number field: its root shows focus and drives its look. */+export function fieldRoot(island: IslandRenderContext, control: ControlModel, base: Base): VNode {+ const state = stateOf(island, control)+ const props = interaction(state, true)+ if (control.kind !== 'numberField') return base({ props })+ const settings = numberSettings(control.behaviour, 'value')+ return h(+ NumberFieldRoot,+ {+ asChild: true,+ modelValue: state.number,+ 'onUpdate:modelValue': (value: number) => {+ if (Number.isFinite(value)) state.number = value+ },+ min: settings?.min,+ max: settings?.max,+ step: settings?.step,+ disabled: disabled(island, control)+ },+ { default: () => base({ props }) }+ )+}++/** The text layer of a field, as the input it is, or a number field's stepper part. */+export function fieldRole(+ island: IslandRenderContext,+ role: IslandRole,+ base: Base+): VNode | undefined {+ if (role.type === 'part' && role.control.kind === 'numberField') {+ const stepper = role.part === 'increment' ? NumberFieldIncrement : NumberFieldDecrement+ return h(+ stepper,+ { asChild: true },+ { default: () => base({ tag: 'button', props: { type: 'button' } }) }+ )+ }+ if (role.type !== 'text') return undefined+ const { control, valueId } = role+ const state = stateOf(island, control)+ const off = disabled(island, control)+ if (control.kind === 'numberField')+ return h(+ NumberFieldInput,+ { asChild: true },+ {+ default: () =>+ base({ tag: 'input', style: INPUT_RESET, props: { disabled: off }, children: () => [] })+ }+ )+ const text = Object.hasOwn(control.texts, valueId) ? control.texts[valueId] : undefined+ const placeholder = booleanOf(control, 'filled') ? text?.designed : undefined+ return base({+ tag: control.kind === 'textarea' ? 'textarea' : 'input',+ style: INPUT_RESET,+ props: {+ value: state.texts[valueId] ?? '',+ placeholder,+ disabled: off,+ onInput: (event: Event) => {+ if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement)+ state.texts[valueId] = event.target.value+ }+ },+ children: () => []+ })+}diff --git a/packages/vue/src/canvas/islands/controls/index.ts b/packages/vue/src/canvas/islands/controls/index.tsnew file mode 100644index 000000000..aa992f71b--- /dev/null+++ b/packages/vue/src/canvas/islands/controls/index.ts@@ -0,0 +1,251 @@+import {+ AccordionContent,+ AccordionHeader,+ AccordionItem,+ AccordionRoot,+ AccordionTrigger,+ CheckboxRoot,+ CollapsibleContent,+ CollapsibleRoot,+ CollapsibleTrigger,+ ProgressIndicator,+ ProgressRoot,+ RadioGroupItem,+ RadioGroupRoot,+ SliderRange,+ SliderRoot,+ SliderThumb,+ SliderTrack,+ SwitchRoot,+ SwitchThumb,+ TabsContent,+ TabsList,+ TabsRoot,+ TabsTrigger,+ Toggle,+ ToggleGroupItem,+ ToggleGroupRoot+} from 'reka-ui'+import { h, type Component, type VNode } from 'vue'++import type { DesignElement } from '@open-pencil/dom-css/export'+import { numberSettings } from '@open-pencil/scene-graph'++import type { ElementOverride, IslandRenderContext } from '#vue/canvas/islands/render'+import type { IslandRole } from '#vue/canvas/islands/roles'+import { groupOf } from '#vue/canvas/islands/roles'++import { fieldRole, fieldRoot } from './fields'+import { chooseItem, disabled, interaction, stateOf, type RoleContext } from './shared'++/** Wrap an element in a Reka part that renders through it. */+function asChild(component: Component, props: Record<string, unknown>, child: () => VNode): VNode {+ return h(component, { asChild: true, ...props }, { default: () => child() })+}++const ON_OFF: Record<string, Component> = { switch: SwitchRoot, toggle: Toggle }++function root({ island, role, base }: RoleContext<Extract<IslandRole, { type: 'root' }>>): VNode {+ const { control } = role+ const state = stateOf(island, control)+ const off = disabled(island, control)+ const pointer = interaction(state)+ const bound = (valueId: string) => ({+ modelValue: state.booleans[valueId] ?? false,+ 'onUpdate:modelValue': (value: boolean) => (state.booleans[valueId] = value),+ disabled: off+ })+ const button = (props: Record<string, unknown> = {}) =>+ base({ tag: 'button', props: { type: 'button', ...pointer, ...props } })+ switch (control.kind) {+ case 'button':+ return button({ disabled: off })+ case 'switch':+ case 'toggle':+ return asChild(ON_OFF[control.kind], bound('value'), button)+ case 'checkbox':+ return asChild(CheckboxRoot, bound('value'), button)+ case 'radio':+ return button({+ role: 'radio',+ 'aria-checked': state.booleans.value ?? false,+ disabled: off,+ onClick: () => (state.booleans.value = true)+ })+ case 'radioGroup':+ case 'toggleGroup':+ case 'accordion':+ return groupRoot(island, role.control, base)+ case 'slider':+ case 'progress':+ case 'tabs':+ case 'collapsible':+ return valueRoot(island, control, base)+ case 'textField':+ case 'textarea':+ case 'numberField':+ return fieldRoot(island, control, base)+ }+ return base()+}++/** A control that holds a number, a choice, or an open state rather than on and off. */+function valueRoot(+ island: IslandRenderContext,+ control: RoleContext['role']['control'],+ base: RoleContext['base']+): VNode {+ const state = stateOf(island, control)+ const off = disabled(island, control)+ const settings = numberSettings(control.behaviour, 'value')+ if (control.kind === 'slider')+ return asChild(+ SliderRoot,+ {+ modelValue: [state.number],+ 'onUpdate:modelValue': (value: number[] | undefined) =>+ (state.number = value?.[0] ?? state.number),+ min: settings?.min,+ max: settings?.max,+ step: settings?.step,+ disabled: off+ },+ () => base({ props: interaction(state) })+ )+ if (control.kind === 'progress')+ return asChild(ProgressRoot, { modelValue: state.number, max: settings?.max }, () => base())+ if (control.kind === 'tabs')+ return asChild(+ TabsRoot,+ {+ modelValue: state.choice,+ 'onUpdate:modelValue': (value: string | number) => (state.choice = String(value))+ },+ () => base()+ )+ return asChild(+ CollapsibleRoot,+ {+ open: state.booleans.open ?? false,+ 'onUpdate:open': (value: boolean) => (state.booleans.open = value),+ disabled: off+ },+ () => base({ props: interaction(state) })+ )+}++function groupRoot(+ island: IslandRenderContext,+ group: RoleContext['role']['control'],+ base: RoleContext['base']+): VNode {+ const state = stateOf(island, group)+ const choose = (value: unknown) =>+ chooseItem(+ island,+ group,+ typeof value === 'string' || typeof value === 'number' ? String(value) : ''+ )+ if (group.kind === 'radioGroup')+ return asChild(+ RadioGroupRoot,+ {+ modelValue: state.choice,+ 'onUpdate:modelValue': choose,+ disabled: disabled(island, group)+ },+ () => base()+ )+ if (group.kind === 'toggleGroup')+ return asChild(+ ToggleGroupRoot,+ { type: 'single', modelValue: state.choice, 'onUpdate:modelValue': choose },+ () => base()+ )+ return asChild(+ AccordionRoot,+ { type: 'single', collapsible: true, modelValue: state.choice, 'onUpdate:modelValue': choose },+ () => base()+ )+}++/** An item of a group: a radio, a toggle, or a collapsible inside an accordion. */+function item({ island, role, base }: RoleContext<Extract<IslandRole, { type: 'item' }>>): VNode {+ const state = stateOf(island, role.control)+ const value = String(role.index)+ const pointer = interaction(state)+ const button = () => base({ tag: 'button', props: { type: 'button', ...pointer } })+ if (role.group.kind === 'radioGroup') return asChild(RadioGroupItem, { value }, button)+ if (role.group.kind === 'toggleGroup') return asChild(ToggleGroupItem, { value }, button)+ return asChild(AccordionItem, { value }, () => base({ props: pointer }))+}++/** Parts the slider and progress components position themselves. */+const SLIDER_PARTS: Record<string, { component: Component; omit: readonly string[] }> = {+ track: { component: SliderTrack, omit: [] },+ range: { component: SliderRange, omit: ['left', 'width'] },+ thumb: { component: SliderThumb, omit: ['left', 'transform'] }+}++function part({ island, role, base }: RoleContext<Extract<IslandRole, { type: 'part' }>>): VNode {+ const { control } = role+ const sliderPart = control.kind === 'slider' ? SLIDER_PARTS[role.part] : undefined+ if (sliderPart) return asChild(sliderPart.component, {}, () => base({ omit: sliderPart.omit }))+ if (control.kind === 'switch' && role.part === 'thumb')+ return asChild(SwitchThumb, {}, () => base())+ if (control.kind === 'progress' && role.part === 'indicator') {+ const settings = numberSettings(control.behaviour, 'value')+ const span = settings ? settings.max - settings.min : 0+ const ratio = settings && span > 0 ? (stateOf(island, control).number - settings.min) / span : 0+ return asChild(ProgressIndicator, {}, () =>+ base({ style: { width: `${Math.min(1, Math.max(0, ratio)) * 100}%` } })+ )+ }+ if (control.kind === 'tabs' && role.part === 'list') return asChild(TabsList, {}, () => base())+ if (control.kind === 'collapsible') return disclosurePart(island, role, base)+ return fieldRole(island, role, base) ?? base()+}++/** A collapsible's trigger and content, or an accordion item's when it is one. */+function disclosurePart(+ island: IslandRenderContext,+ role: Extract<IslandRole, { type: 'part' }>,+ base: RoleContext['base']+): VNode {+ const inAccordion = groupOf(island.roles, role.control)?.kind === 'accordion'+ if (role.part === 'trigger') {+ const trigger = () => base({ tag: 'button', props: { type: 'button' } })+ return inAccordion+ ? asChild(AccordionHeader, {}, () => asChild(AccordionTrigger, {}, trigger))+ : asChild(CollapsibleTrigger, {}, trigger)+ }+ if (role.part === 'content')+ return asChild(inAccordion ? AccordionContent : CollapsibleContent, {}, () => base())+ return base()+}++/** Render a layer with the role it has for the controls of its island. */+export function wrapRole(+ island: IslandRenderContext,+ role: IslandRole,+ element: DesignElement,+ base: (override?: ElementOverride) => VNode+): VNode {+ switch (role.type) {+ case 'root':+ return root({ island, role, element, base })+ case 'item':+ return item({ island, role, element, base })+ case 'part':+ return part({ island, role, element, base })+ case 'trigger':+ return asChild(TabsTrigger, { value: String(role.index) }, () =>+ base({ tag: 'button', props: { type: 'button' } })+ )+ case 'panel':+ return asChild(TabsContent, { value: String(role.index) }, () => base())+ case 'text':+ return fieldRole(island, role, base) ?? base()+ }+ return base()+}diff --git a/packages/vue/src/canvas/islands/controls/shared.ts b/packages/vue/src/canvas/islands/controls/shared.tsnew file mode 100644index 000000000..8e3464fdc--- /dev/null+++ b/packages/vue/src/canvas/islands/controls/shared.ts@@ -0,0 +1,56 @@+import type { VNode } from 'vue'++import type { DesignElement } from '@open-pencil/dom-css/export'++import type { ControlModel } from '#vue/canvas/islands/model'+import type { ElementOverride, IslandRenderContext } from '#vue/canvas/islands/render'+import type { IslandRole } from '#vue/canvas/islands/roles'+import { isDisabled, type ControlState } from '#vue/canvas/islands/state'++/** What a role's wrapper gets: the island, the layer, and how to render it as designed. */+export interface RoleContext<R extends IslandRole = IslandRole> {+ island: IslandRenderContext+ role: R+ element: DesignElement+ base: (override?: ElementOverride) => VNode+}++export function stateOf(island: IslandRenderContext, control: ControlModel): ControlState {+ const state = island.state.get(control.path)+ if (!state) throw new Error(`No state for control ${control.path}`)+ return state+}++export function disabled(island: IslandRenderContext, control: ControlModel): boolean {+ return isDisabled(control, island.state.get(control.path))+}++/**+ * Pointer and focus handlers that drive a control's interaction states. Focus shows from the+ * keyboard, as `:focus-visible` does, or always when `focusOnPress`, as on a text field.+ */+export function interaction(state: ControlState, focusOnPress = false): Record<string, unknown> {+ return {+ onPointerenter: () => (state.hovered = true),+ onPointerleave: () => {+ state.hovered = false+ state.pressed = false+ },+ onPointerdown: () => (state.pressed = true),+ onPointerup: () => (state.pressed = false),+ onFocusin: (event: FocusEvent) => {+ const target = event.target instanceof Element ? event.target : null+ state.focused = focusOnPress || !!target?.matches(':focus-visible')+ },+ onFocusout: () => (state.focused = false)+ }+}++/** Turn a group's items on and off so that only the chosen one is on. */+export function chooseItem(island: IslandRenderContext, group: ControlModel, choice: string): void {+ stateOf(island, group).choice = choice+ for (const [index, item] of group.items.entries()) {+ const valueId = item.kind === 'collapsible' ? 'open' : 'value'+ stateOf(island, item).booleans[valueId] = String(index) === choice+ }+}diff --git a/packages/vue/src/canvas/islands/model.ts b/packages/vue/src/canvas/islands/model.tsnew file mode 100644index 000000000..6514f30f1--- /dev/null+++ b/packages/vue/src/canvas/islands/model.ts@@ -0,0 +1,196 @@+import { hasBehaviour, layerPath } from '@open-pencil/core/editor'+import {+ behaviourContract,+ behaviourOwner,+ behaviourProperties,+ booleanBinding,+ findComponentPropertyTargets,+ instanceMainComponent,+ instanceSlotFrames,+ partBinding,+ readBehaviour,+ slotPropertyId,+ textBinding,+ type Behaviour,+ type ComponentPropertyDefinition,+ type SceneGraph,+ type SceneNode+} from '@open-pencil/scene-graph'++/** A boolean value of a control and the property that draws it. */+export interface BooleanModel {+ definition: ComponentPropertyDefinition+ on?: string+ off?: string+ /** The value as the document's instance draws it. */+ designed: boolean+}++/** The variant property that draws a control's interaction states. */+export interface StatesModel {+ name: string+ values: NonNullable<Behaviour['states']>+ /** The value the instance shows at rest. */+ rest: string | undefined+ /** Whether the document's instance is drawn disabled. */+ designedDisabled: boolean+}++/** An instance with a behaviour inside an island, as the island runs it. */+export interface ControlModel {+ /** The instance's layer path below the island root. */+ path: string+ kind: Behaviour['kind']+ behaviour: Behaviour+ booleans: Record<string, BooleanModel>+ states: StatesModel | null+ /** Each bound part's slot frame, by part id, as a layer path below the island root. */+ parts: Record<string, string>+ /** Each bound text value's text layer, by value id, as a layer path below the island root. */+ texts: Record<string, { path: string; designed: string }>+ /** The children of the items slot that are controls themselves, in order. */+ items: ControlModel[]+ /**+ * Layers the control decides to show, which the design may hide: tab panels, or a+ * collapsible's content, as layer paths below the island root.+ */+ reveal: string[]+ /** For tabs, each panel's layer path, in order. */+ panels: string[]+ /** For tabs, each trigger's layer path, in order. */+ triggers: string[]+}++function designedBoolean(+ graph: SceneGraph,+ instance: SceneNode,+ definition: ComponentPropertyDefinition,+ on: string | undefined+): boolean {+ if (definition.type === 'BOOLEAN') {+ const assignments = instance.componentPropertyAssignments+ const value = Object.hasOwn(assignments, definition.id)+ ? assignments[definition.id]+ : definition.defaultValue+ return value === 'true'+ }+ return instanceMainComponent(graph, instance)?.componentPropertyValues[definition.name] === on+}++function statesModel(+ graph: SceneGraph,+ instance: SceneNode,+ owner: SceneNode,+ behaviour: Behaviour+): StatesModel | null {+ const states = behaviour.states+ const definition = states+ ? behaviourProperties(graph, owner).find(+ (item) => item.id === states.propertyId && item.type === 'VARIANT'+ )+ : undefined+ if (!states || !definition) return null+ const authored = instanceMainComponent(graph, instance)?.componentPropertyValues[definition.name]+ return {+ name: definition.name,+ values: states,+ rest: states.rest ?? authored,+ designedDisabled: !!states.disabled && authored === states.disabled+ }+}++function controlModel(graph: SceneGraph, rootId: string, instance: SceneNode): ControlModel | null {+ const component = instanceMainComponent(graph, instance)+ const owner = component && behaviourOwner(graph, component)+ const behaviour = owner && readBehaviour(owner)+ if (!owner || !behaviour) return null+ const path = layerPath(graph, rootId, instance.id)+ const properties = behaviourProperties(graph, owner)+ const booleans: Record<string, BooleanModel> = {}+ for (const valueId of Object.keys(behaviour.booleans)) {+ const binding = booleanBinding(behaviour, valueId)+ const definition = properties.find((item) => item.id === binding?.propertyId)+ if (!binding || !definition) continue+ booleans[valueId] = {+ definition,+ on: binding.on,+ off: binding.off,+ designed: designedBoolean(graph, instance, definition, binding.on)+ }+ }+ const frames = instanceSlotFrames(graph, instance)+ const parts = Object.fromEntries(+ Object.entries(behaviour.parts).flatMap(([partId, propertyId]) => {+ const frame = frames.find((item) => slotPropertyId(item) === propertyId)+ return frame ? [[partId, layerPath(graph, rootId, frame.id)]] : []+ })+ )+ const texts = Object.fromEntries(+ Object.keys(behaviour.texts).flatMap((valueId) => {+ const propertyId = textBinding(behaviour, valueId)+ const target = propertyId+ ? findComponentPropertyTargets(graph, instance, propertyId).find(+ (item) => item.node.type === 'TEXT'+ )+ : undefined+ return target+ ? [+ [+ valueId,+ { path: layerPath(graph, rootId, target.node.id), designed: target.node.text }+ ]+ ]+ : []+ })+ )+ const frameOf = (partId: string) => {+ const propertyId = partBinding(behaviour, partId)+ return propertyId ? frames.find((item) => slotPropertyId(item) === propertyId) : undefined+ }+ const itemsPart = behaviourContract(behaviour.kind).parts.find((part) => part.items)+ const itemsFrame = itemsPart ? frameOf(itemsPart.id) : undefined+ const items = (itemsFrame ? graph.getChildren(itemsFrame.id) : []).flatMap((child) => {+ const item = controlModel(graph, rootId, child)+ return item ? [item] : []+ })+ const childPaths = (frame: SceneNode | undefined) =>+ (frame ? graph.getChildren(frame.id) : []).map((child) => layerPath(graph, rootId, child.id))+ const panels = behaviour.kind === 'tabs' ? childPaths(frameOf('panels')) : []+ const content = behaviour.kind === 'collapsible' ? frameOf('content') : undefined+ return {+ path,+ kind: behaviour.kind,+ behaviour,+ booleans,+ states: statesModel(graph, instance, owner, behaviour),+ parts,+ texts,+ items,+ reveal: content ? [layerPath(graph, rootId, content.id)] : panels,+ panels,+ triggers: behaviour.kind === 'tabs' ? childPaths(frameOf('list')) : []+ }+}++/**+ * The controls of an island, by layer path, outermost first. Items of a group are listed both+ * in the group's `items` and on their own, since each keeps its own state.+ */+export function islandControls(graph: SceneGraph, rootId: string): Map<string, ControlModel> {+ const controls = new Map<string, ControlModel>()+ const visit = (node: SceneNode) => {+ if (hasBehaviour(graph, node)) {+ const control = controlModel(graph, rootId, node)+ if (control) controls.set(control.path, control)+ }+ for (const child of graph.getChildren(node.id)) visit(child)+ }+ const root = graph.getNode(rootId)+ if (root) visit(root)+ return controls+}++/** A control's boolean value, if the behaviour binds it. */+export function booleanOf(control: ControlModel, valueId: string): BooleanModel | undefined {+ return Object.hasOwn(control.booleans, valueId) ? control.booleans[valueId] : undefined+}diff --git a/packages/vue/src/canvas/islands/render.ts b/packages/vue/src/canvas/islands/render.tsnew file mode 100644index 000000000..8b8a3bf02--- /dev/null+++ b/packages/vue/src/canvas/islands/render.ts@@ -0,0 +1,83 @@+import { h, type VNode } from 'vue'++import { layerPath } from '@open-pencil/core/editor'+import type { DesignElement, DesignNode } from '@open-pencil/dom-css/export'+import type { SceneGraph } from '@open-pencil/scene-graph'++import { wrapRole } from './controls'+import type { ControlModel } from './model'+import type { IslandRole } from './roles'+import type { IslandState } from './state'++export interface IslandRenderContext {+ /** The island's layers in their current states. */+ graph: SceneGraph+ rootId: string+ controls: ReadonlyMap<string, ControlModel>+ roles: ReadonlyMap<string, IslandRole>+ state: IslandState+}++/** How a role's wrapper changes the element it wraps. */+export interface ElementOverride {+ tag?: string+ style?: Record<string, string | undefined>+ props?: Record<string, unknown>+ /** Style properties the wrapping component sets itself, removed from the design's. */+ omit?: readonly string[]+ children?: () => (VNode | string)[]+}++/** Element styles a native `<button>` adds, cleared so the design's own styles show. */+const BUTTON_RESET: Record<string, string> = {+ border: 'none',+ padding: '0',+ margin: '0',+ background: 'none',+ font: 'inherit',+ color: 'inherit',+ 'text-align': 'inherit',+ cursor: 'pointer'+}++/** Render an element as the design draws it, with a role's changes applied. */+export function renderElement(+ context: IslandRenderContext,+ element: DesignElement,+ path: string,+ override: ElementOverride = {}+): VNode {+ // Omitted properties are removed, not cleared: a Reka part that renders through this element+ // sets them, and an `undefined` here would override it.+ const omitted = new Set(override.omit)+ const style = Object.fromEntries(+ Object.entries({+ ...(override.tag === 'button' ? BUTTON_RESET : {}),+ ...element.inlineStyle,+ ...override.style+ }).filter(([key]) => !omitted.has(key))+ )+ const children =+ override.children ?? (() => element.children.map((child) => renderNode(context, child, path)))+ const { 'data-open-pencil-node-id': _id, ...attrs } = element.attrs+ return h(+ override.tag ?? element.tagName,+ { ...attrs, key: path, 'data-layer': path, style, ...override.props },+ children()+ )+}++/** Render a projected layer: as designed, or as the control it is part of. */+export function renderNode(+ context: IslandRenderContext,+ node: DesignNode,+ parentPath: string+): VNode | string {+ if (node.type === 'text') return node.text+ const path = node.sourceSceneNodeId+ ? layerPath(context.graph, context.rootId, node.sourceSceneNodeId)+ : parentPath+ const role = context.roles.get(path)+ const base = (override?: ElementOverride) => renderElement(context, node, path, override)+ return role ? wrapRole(context, role, node, base) : base()+}diff --git a/packages/vue/src/canvas/islands/roles.ts b/packages/vue/src/canvas/islands/roles.tsnew file mode 100644index 000000000..41b5e406d--- /dev/null+++ b/packages/vue/src/canvas/islands/roles.ts@@ -0,0 +1,42 @@+import type { ControlModel } from './model'++/** What a layer of an island is to the controls in it. */+export type IslandRole =+ | { type: 'root'; control: ControlModel }+ | { type: 'part'; control: ControlModel; part: string }+ | { type: 'item'; group: ControlModel; control: ControlModel; index: number }+ | { type: 'trigger'; control: ControlModel; index: number }+ | { type: 'panel'; control: ControlModel; index: number }+ | { type: 'text'; control: ControlModel; valueId: string }++/**+ * Each layer's role by layer path: control roots, their parts, items of groups, tab triggers+ * and panels, and the text layers that become inputs. Items of a group take the item role in+ * place of their root role, since the group drives them.+ */+export function islandRoles(controls: ReadonlyMap<string, ControlModel>): Map<string, IslandRole> {+ const roles = new Map<string, IslandRole>()+ for (const control of controls.values()) {+ if (!roles.has(control.path)) roles.set(control.path, { type: 'root', control })+ for (const [part, path] of Object.entries(control.parts))+ if (!roles.has(path)) roles.set(path, { type: 'part', control, part })+ for (const [valueId, text] of Object.entries(control.texts))+ roles.set(text.path, { type: 'text', control, valueId })+ for (const [index, path] of control.triggers.entries())+ roles.set(path, { type: 'trigger', control, index })+ for (const [index, path] of control.panels.entries())+ roles.set(path, { type: 'panel', control, index })+ for (const [index, item] of control.items.entries())+ roles.set(item.path, { type: 'item', group: control, control: item, index })+ }+ return roles+}++/** The group a control is an item of, if any. */+export function groupOf(+ roles: ReadonlyMap<string, IslandRole>,+ control: ControlModel+): ControlModel | undefined {+ const role = roles.get(control.path)+ return role?.type === 'item' ? role.group : undefined+}diff --git a/packages/vue/src/canvas/islands/shadow.ts b/packages/vue/src/canvas/islands/shadow.tsnew file mode 100644index 000000000..3c0670577--- /dev/null+++ b/packages/vue/src/canvas/islands/shadow.ts@@ -0,0 +1,20 @@+import { onMounted, shallowRef, type Ref } from 'vue'++/**+ * A container inside a shadow root of `host`, created once `host` mounts, with `css` as the+ * shadow root's only styles: the app's styles do not reach into it, nor its styles out.+ */+export function useShadowContainer(host: Readonly<Ref<HTMLElement | null>>, css: string) {+ const container = shallowRef<HTMLElement | null>(null)+ onMounted(() => {+ if (!host.value) return+ const shadow = host.value.attachShadow({ mode: 'open' })+ const sheet = new CSSStyleSheet()+ sheet.replaceSync(css)+ shadow.adoptedStyleSheets = [sheet]+ const mount = document.createElement('div')+ shadow.append(mount)+ container.value = mount+ })+ return container+}diff --git a/packages/vue/src/canvas/islands/state.ts b/packages/vue/src/canvas/islands/state.tsnew file mode 100644index 000000000..89d69a17c--- /dev/null+++ b/packages/vue/src/canvas/islands/state.ts@@ -0,0 +1,119 @@+import { reactive } from 'vue'++import type { InstanceState } from '@open-pencil/core/editor'+import { numberSettings, type InteractionState } from '@open-pencil/scene-graph'++import { booleanOf, type ControlModel } from './model'++/** What one control of an island holds while it runs. */+export interface ControlState {+ booleans: Partial<Record<string, boolean>>+ /** The chosen tab, radio, toggle, or accordion item, as its index; '' when none is. */+ choice: string+ number: number+ texts: Partial<Record<string, string>>+ hovered: boolean+ pressed: boolean+ /** Whether the control shows focus: from the keyboard, or always for a text field. */+ focused: boolean+}++const TEXT_INPUTS = new Set(['textField', 'textarea', 'numberField'])++function initialChoice(control: ControlModel): string {+ if (control.kind === 'tabs') return '0'+ const index = control.items.findIndex((item) => {+ const value = booleanOf(item, 'value') ?? booleanOf(item, 'open')+ return value?.designed ?? false+ })+ if (index !== -1) return String(index)+ // A radio group always has one radio on; other groups may have none.+ return control.kind === 'radioGroup' ? '0' : ''+}++function initialTexts(control: ControlModel): Record<string, string> {+ const filled = booleanOf(control, 'filled')+ const placeholder = !!filled && !filled.designed+ return Object.fromEntries(+ Object.entries(control.texts).map(([valueId, text]) => [+ valueId,+ placeholder ? '' : text.designed+ ])+ )+}++/** The island's controls as they start: each as its instance is drawn. */+export function createIslandState(controls: ReadonlyMap<string, ControlModel>) {+ return reactive(+ new Map(+ [...controls.values()].map((control): [string, ControlState] => [+ control.path,+ {+ booleans: Object.fromEntries(+ Object.entries(control.booleans).map(([valueId, model]) => [valueId, model.designed])+ ),+ choice: initialChoice(control),+ number: numberSettings(control.behaviour, 'value')?.default ?? 0,+ texts: initialTexts(control),+ hovered: false,+ pressed: false,+ focused: false+ }+ ])+ )+ )+}++export type IslandState = ReturnType<typeof createIslandState>++/** Whether a control is disabled: its disabled value is on, or it is drawn disabled. */+export function isDisabled(control: ControlModel, state: ControlState | undefined): boolean {+ return !!state?.booleans.disabled || !!control.states?.designedDisabled+}++function interactionState(control: ControlModel, state: ControlState): InteractionState {+ if (isDisabled(control, state)) return 'disabled'+ if (state.pressed) return 'pressed'+ if (state.hovered) return 'hover'+ if (state.focused) return 'focus'+ return 'rest'+}++/** The text field's Filled value follows whether it holds text. */+function filled(control: ControlModel, state: ControlState): ControlState['booleans'] {+ if (!TEXT_INPUTS.has(control.kind) || !booleanOf(control, 'filled')) return state.booleans+ return { ...state.booleans, filled: (state.texts.value ?? '') !== '' }+}++function instanceState(control: ControlModel, state: ControlState): InstanceState {+ const variants: Record<string, string> = {}+ const properties: Record<string, string> = {}+ for (const [valueId, on] of Object.entries(filled(control, state))) {+ const model = booleanOf(control, valueId)+ if (!model || on === undefined) continue+ if (model.definition.type === 'BOOLEAN') properties[model.definition.id] = String(on)+ else {+ const value = on ? model.on : model.off+ if (value) variants[model.definition.name] = value+ }+ }+ const prefer: Record<string, string> = {}+ if (control.states) {+ const value = control.states.values[interactionState(control, state)] ?? control.states.rest+ if (value) prefer[control.states.name] = value+ }+ return { variants, prefer, properties, reveal: control.reveal }+}++/** How each instance of the island is shown, by layer path, for `resolvePlayState`. */+export function instanceStates(+ controls: ReadonlyMap<string, ControlModel>,+ state: IslandState+): Map<string, InstanceState> {+ const states = new Map<string, InstanceState>()+ for (const control of controls.values()) {+ const current = state.get(control.path)+ if (current) states.set(control.path, instanceState(control, current))+ }+ return states+}diff --git a/packages/vue/src/canvas/useCanvasInput.ts b/packages/vue/src/canvas/useCanvasInput.tsindex 64dc85972..d8b7f6053 100644--- a/packages/vue/src/canvas/useCanvasInput.ts+++ b/packages/vue/src/canvas/useCanvasInput.ts@@ -47,6 +47,7 @@ export function useCanvasInput(const drag = ref<DragState | null>(null)const canvasLabelEdit = createCanvasLabelEdit(editor)const cursorOverride = ref<string | null>(null)+ /** Whether the primary button is held on a preview control, such as a slider thumb. */const autoLayoutPaddingEdit = ref<{nodeId: stringside: 'top' | 'right' | 'bottom' | 'left'@@ -212,6 +213,7 @@ export function useCanvasInput(}function onDblClick(e: MouseEvent) {+ if (editor.state.play) returnif (startAutoLayoutPaddingEdit(e)) returnonTextDblClick(e)}@@ -219,6 +221,11 @@ export function useCanvasInput(function onMouseDown(e: MouseEvent) {onActivate?.()if (!isEnabled()) return+ // Preview: controls live in islands above the canvas; the canvas itself only pans.+ if (editor.state.play && e.button === 0 && editor.state.activeTool !== 'HAND') {+ e.preventDefault()+ return+ }editor.setMeasurementMode('off')const paddingEdit = autoLayoutPaddingEdit.valueif (paddingEdit) {@@ -266,6 +273,8 @@ export function useCanvasInput(onCursorMove(coords.cx, coords.cy)}+ if (editor.state.play && !drag.value) return+if (!drag.value) {const { cx, cy } = coordsupdatePenHover(cx, cy, editor)@@ -511,17 +520,16 @@ export function useCanvasInput(editor.setMeasurementMode('off')cancelPointerInteraction()})- const stopPreviewListeners = (- ['selection:changed', 'page:changed', 'graph:replaced'] as const- ).map((event) =>- editor.onEditorEvent(event, () => {- if (drag.value?.type === 'draw' || drag.value?.type === 'rotate') cancelPointerInteraction()- })+ const stopPlayListeners = (['selection:changed', 'page:changed', 'graph:replaced'] as const).map(+ (event) =>+ editor.onEditorEvent(event, () => {+ if (drag.value?.type === 'draw' || drag.value?.type === 'rotate') cancelPointerInteraction()+ }))onScopeDispose(() => {stopRotationListener()stopToolListener()- for (const stop of stopPreviewListeners) stop()+ for (const stop of stopPlayListeners) stop()cancelPointerInteraction()})diff --git a/packages/vue/src/controls/behaviour/index.ts b/packages/vue/src/controls/behaviour/index.tsnew file mode 100644index 000000000..96a3db7b8--- /dev/null+++ b/packages/vue/src/controls/behaviour/index.ts@@ -0,0 +1,2 @@+export type * from './types'+export { useBehaviour } from './use'diff --git a/packages/vue/src/controls/behaviour/types.ts b/packages/vue/src/controls/behaviour/types.tsnew file mode 100644index 000000000..02140764f--- /dev/null+++ b/packages/vue/src/controls/behaviour/types.ts@@ -0,0 +1,69 @@+import type { BehaviourKind, InteractionState } from '@open-pencil/scene-graph'++import type { VariantDefinitionControl } from '#vue/controls/variants'++/** A boolean value of the behaviour: the variant or boolean property that holds it. */+export interface BehaviourBooleanControl {+ id: string+ type: 'boolean'+ required: boolean+ /** The bound property, if any. */+ propertyId: string | null+ /** For a variant property: the values meaning on and off. */+ on?: string+ off?: string+ options: VariantDefinitionControl[]+}++/** A number value of the behaviour, which keeps its own range since Figma has no number property. */+export interface BehaviourNumberControl {+ id: string+ type: 'number'+ min: number+ max: number+ step: number+ default: number+}++/** A text value of the behaviour: the text property that shows it. */+export interface BehaviourTextControl {+ id: string+ type: 'text'+ required: boolean+ /** The bound text property, if any. */+ propertyId: string | null+ options: VariantDefinitionControl[]+}++export type BehaviourValueControl =+ | BehaviourBooleanControl+ | BehaviourTextControl+ | BehaviourNumberControl++/** One part of the selected component's behaviour: the slot property that is that part. */+export interface BehaviourPartControl {+ id: string+ required: boolean+ /** The bound slot property, if any. */+ propertyId: string | null+ /** The component's slot properties. */+ options: VariantDefinitionControl[]+}++/** The variant property that draws interaction states, and the value of each state. */+export interface BehaviourStatesControl {+ /** The bound variant property, if any. */+ propertyId: string | null+ values: Partial<Record<InteractionState, string>>+ /** The component's variant properties. */+ options: VariantDefinitionControl[]+}++export interface BehaviourControl {+ kind: BehaviourKind+ values: BehaviourValueControl[]+ parts: BehaviourPartControl[]+ states: BehaviourStatesControl+ /** Ids of required values and parts that are still unbound, in contract order. */+ missing: string[]+}diff --git a/packages/vue/src/controls/behaviour/use.ts b/packages/vue/src/controls/behaviour/use.tsnew file mode 100644index 000000000..1bfe90efa--- /dev/null+++ b/packages/vue/src/controls/behaviour/use.ts@@ -0,0 +1,210 @@+import {+ behaviourContract,+ behaviourOwner,+ behaviourProperties,+ booleanBinding,+ DEFAULT_NUMBER_SETTINGS,+ emptyBehaviour,+ guessInteractionStates,+ guessOnOff,+ INTERACTION_STATES,+ isNumberRange,+ missingBindings,+ partBinding,+ readBehaviour,+ textBinding,+ type Behaviour,+ type BehaviourKind,+ type BehaviourNumberSettings,+ type InteractionState+} from '@open-pencil/scene-graph'++import type { VariantDefinitionControl } from '#vue/controls/variants'+import { useEditor } from '#vue/editor/context'+import { useSceneComputed } from '#vue/internal/scene-computed/use'++import type { BehaviourControl, BehaviourValueControl } from './types'++/**+ * The behaviour of the selected main component or component set, as the properties panel+ * shows it, and the edits it makes. Each edit is one undo step.+ */+export function useBehaviour() {+ const editor = useEditor()+ const owner = useSceneComputed(() => {+ const nodes = editor.getSelectedNodes()+ return nodes.length === 1 ? behaviourOwner(editor.graph, nodes[0]) : undefined+ })+ const behaviour = useSceneComputed(() => (owner.value ? readBehaviour(owner.value) : null))++ const control = useSceneComputed<BehaviourControl | null>(() => {+ const current = behaviour.value+ const target = owner.value+ if (!current || !target) return null+ const contract = behaviourContract(current.kind)+ const properties = behaviourProperties(editor.graph, target)+ const options = (types: string[]): VariantDefinitionControl[] =>+ properties+ .filter((definition) => types.includes(definition.type))+ .map((definition) => ({+ id: definition.id,+ name: definition.name,+ values: definition.variantOptions ?? []+ }))+ const values = contract.values.flatMap((value): BehaviourValueControl[] => {+ if (value.type === 'boolean') {+ const binding = booleanBinding(current, value.id)+ return [+ {+ id: value.id,+ type: 'boolean',+ required: value.required,+ propertyId: binding?.propertyId ?? null,+ on: binding?.on,+ off: binding?.off,+ options: options(['VARIANT', 'BOOLEAN'])+ }+ ]+ }+ if (value.type === 'text')+ return [+ {+ id: value.id,+ type: 'text',+ required: value.required,+ propertyId: textBinding(current, value.id) ?? null,+ options: options(['TEXT'])+ }+ ]+ if (value.type === 'number')+ return [+ {+ id: value.id,+ type: 'number',+ ...(current.numbers[value.id] ?? DEFAULT_NUMBER_SETTINGS)+ }+ ]+ return []+ })+ return {+ kind: current.kind,+ values,+ // A slot draws one part, so another part's slot is not offered.+ parts: contract.parts.map((part) => {+ const others = new Set(+ Object.entries(current.parts).flatMap(([id, slot]) => (id === part.id ? [] : [slot]))+ )+ return {+ id: part.id,+ required: part.required,+ propertyId: partBinding(current, part.id) ?? null,+ options: options(['SLOT']).filter((slot) => !others.has(slot.id))+ }+ }),+ states: {+ propertyId: current.states?.propertyId ?? null,+ values: Object.fromEntries(+ INTERACTION_STATES.flatMap((state) => {+ const value = current.states?.[state]+ return value ? [[state, value]] : []+ })+ ),+ options: options(['VARIANT'])+ },+ missing: missingBindings(editor.graph, target, current)+ }+ })++ function update(change: (current: Behaviour) => Behaviour) {+ const target = owner.value+ const current = behaviour.value+ if (target && current) editor.setBehaviour(target.id, change(structuredClone(current)))+ }++ return {+ /** Whether a main component or component set is selected. */+ active: useSceneComputed(() => !!owner.value),+ behaviour: control,+ add: (kind: BehaviourKind) => {+ if (owner.value) editor.setBehaviour(owner.value.id, emptyBehaviour(kind))+ },+ remove: () => {+ if (owner.value) editor.setBehaviour(owner.value.id, null)+ },+ /** Bind a boolean value; a variant property starts with the values that likely mean on and off. */+ bindValue: (valueId: string, propertyId: string) =>+ update((current) => {+ const target = owner.value+ const definition = target+ ? behaviourProperties(editor.graph, target).find((item) => item.id === propertyId)+ : undefined+ current.booleans[valueId] =+ definition?.type === 'VARIANT'+ ? { propertyId, ...guessOnOff(definition.variantOptions ?? []) }+ : { propertyId }+ return current+ }),+ /** Show a text value through a text property. */+ bindText: (valueId: string, propertyId: string) =>+ update((current) => {+ current.texts[valueId] = { propertyId }+ return current+ }),+ mapValue: (valueId: string, mapping: { on: string; off: string }) =>+ update((current) => {+ const binding = booleanBinding(current, valueId)+ if (binding) current.booleans[valueId] = { ...binding, ...mapping }+ return current+ }),+ /** Set a number value's range; a range that cannot be stepped through is ignored. */+ setNumber: (valueId: string, settings: BehaviourNumberSettings) => {+ if (!isNumberRange(settings)) return+ update((current) => {+ current.numbers[valueId] = settings+ return current+ })+ },+ bindPart: (partId: string, propertyId: string) =>+ update((current) => {+ current.parts[partId] = propertyId+ return current+ }),+ /** Add a text layer and text property for a text value, named `name`, and bind it. */+ createText: (valueId: string, name: string) => {+ if (owner.value) editor.addBehaviourText(owner.value.id, valueId, name)+ },+ /** Add an Off/On variant property named `name` for a boolean value, and bind it. */+ createVariant: (valueId: string, name: string) => {+ if (owner.value) editor.addBehaviourVariant(owner.value.id, valueId, name)+ },+ /** Add a slot frame named `name` for a part, and bind it. */+ createPart: (partId: string, name: string) => {+ if (owner.value) editor.addBehaviourPart(owner.value.id, partId, name)+ },+ /** Add a variant for each interaction state, making a lone component a set, and bind them. */+ createStates: () => {+ if (owner.value) editor.addBehaviourStates(owner.value.id)+ },+ /**+ * Draw interaction states with a variant property, its values named like states (Hover,+ * Pressed, …) mapped to them; an empty id stops drawing states.+ */+ bindStates: (propertyId: string) =>+ update((current) => {+ const target = owner.value+ const definition = target+ ? behaviourProperties(editor.graph, target).find((item) => item.id === propertyId)+ : undefined+ if (!definition) delete current.states+ else current.states = guessInteractionStates(propertyId, definition.variantOptions ?? [])+ return current+ }),+ /** Choose the variant value of one interaction state; an empty value unsets it. */+ mapState: (state: InteractionState, value: string) =>+ update((current) => {+ if (!current.states) return current+ current.states = { ...current.states, [state]: value || undefined }+ return current+ })+ }+}diff --git a/packages/vue/src/controls/component-props/index.ts b/packages/vue/src/controls/component-props/index.tsindex deb12d631..2551633ff 100644--- a/packages/vue/src/controls/component-props/index.ts+++ b/packages/vue/src/controls/component-props/index.ts@@ -1,4 +1,2 @@-export * from './authoring'export * from './model'-export * from './slots'export * from './use'diff --git a/packages/vue/src/controls/slots/authoring.ts b/packages/vue/src/controls/slots/authoring.tsnew file mode 100644index 000000000..2c412cf3c--- /dev/null+++ b/packages/vue/src/controls/slots/authoring.ts@@ -0,0 +1,116 @@+import { canCreateSlot, slotOwner, slotPropertyId } from '@open-pencil/scene-graph'+import type {+ ComponentPropertyDefinition,+ SceneNode,+ SlotPropertyPatch+} from '@open-pencil/scene-graph'++import { useEditor } from '#vue/editor/context'+import { useSceneComputed } from '#vue/internal/scene-computed/use'++import { slotInstanceOptions, type SlotInstanceOption } from './instance'++/** A slot property as its main component defines it. */+export interface SlotDefinitionControl {+ id: string+ name: string+ description: string+ minChildren?: number+ maxChildren?: number+ preferredOnly: boolean+ /** Components the slot prefers, resolved from the definition's preferred values. */+ preferred: SlotInstanceOption[]+}++/** The value a preferred-components list stores for a component: its key, else its id. */+function preferredValue(component: SceneNode): string {+ return component.componentKey ?? component.id+}++/**+ * Slot properties of the selected main component or slot frame, with the actions that+ * create, configure, and remove them.+ */+export function useSlotAuthoring() {+ const editor = useEditor()+ const target = useSceneComputed(() => {+ const nodes = editor.getSelectedNodes()+ if (nodes.length !== 1) return undefined+ const [node] = nodes+ if (node.type === 'COMPONENT') return { owner: node, frame: undefined, propertyId: undefined }+ const owner = slotOwner(editor.graph, node)+ if (!owner) return undefined+ const propertyId = slotPropertyId(node)+ if (!propertyId && !canCreateSlot(editor.graph, node)) return undefined+ return { owner, frame: node, propertyId }+ })+ const slots = useSceneComputed<SlotDefinitionControl[]>(() => {+ const current = target.value+ if (!current) return []+ return current.owner.componentPropertyDefinitions+ .filter((definition) => definition.type === 'SLOT')+ .filter((definition) => !current.frame || definition.id === current.propertyId)+ .map((definition) => {+ const values = new Set(definition.preferredValues)+ return {+ id: definition.id,+ name: definition.name,+ description: definition.description ?? '',+ minChildren: definition.slotSettings?.minChildren,+ maxChildren: definition.slotSettings?.maxChildren,+ preferredOnly: definition.slotSettings?.allowPreferredValuesOnly ?? false,+ preferred: slotInstanceOptions(editor.graph, definition).filter(+ (option) => option.preferred && values.size > 0+ )+ }+ })+ })+ /** Whether the selection is a frame that can become a slot. */+ const canCreate = useSceneComputed(() => !!target.value?.frame && !target.value.propertyId)+ const active = useSceneComputed(() => slots.value.length > 0 || canCreate.value)++ function update(propertyId: string, patch: SlotPropertyPatch) {+ const owner = target.value?.owner+ if (owner) editor.updateSlot(owner.id, propertyId, patch)+ }++ function definition(propertyId: string): ComponentPropertyDefinition | undefined {+ return target.value?.owner.componentPropertyDefinitions.find((item) => item.id === propertyId)+ }++ /** Components that can be marked preferred, the slot's current choices first. */+ function options(propertyId: string): SlotInstanceOption[] {+ const found = definition(propertyId)+ return found ? slotInstanceOptions(editor.graph, found) : []+ }++ function setPreferred(propertyId: string, componentId: string, preferred: boolean) {+ const found = definition(propertyId)+ const component = editor.graph.getNode(componentId)+ if (!found || !component) return+ const keys = new Set([component.id, component.componentKey, component.sourceLibraryKey])+ const rest = (found.preferredValues ?? []).filter((value) => !keys.has(value))+ update(propertyId, {+ preferredValues: preferred ? [...rest, preferredValue(component)] : rest+ })+ }++ return {+ active,+ canCreate,+ slots,+ options,+ create: () => editor.createSlot(),+ rename: (propertyId: string, name: string) => update(propertyId, { name }),+ describe: (propertyId: string, description: string) => update(propertyId, { description }),+ setLimits: (propertyId: string, limits: { minChildren?: number; maxChildren?: number }) =>+ update(propertyId, { slotSettings: limits }),+ setPreferredOnly: (propertyId: string, value: boolean) =>+ update(propertyId, { slotSettings: { allowPreferredValuesOnly: value } }),+ setPreferred,+ remove: (propertyId: string) => {+ const owner = target.value?.owner+ if (owner) editor.removeSlot(owner.id, propertyId)+ }+ }+}diff --git a/packages/vue/src/controls/slots/index.ts b/packages/vue/src/controls/slots/index.tsnew file mode 100644index 000000000..4a9def144--- /dev/null+++ b/packages/vue/src/controls/slots/index.ts@@ -0,0 +1,2 @@+export * from './authoring'+export * from './instance'diff --git a/packages/vue/src/controls/component-props/slots.ts b/packages/vue/src/controls/slots/instance.tssimilarity index 53%rename from packages/vue/src/controls/component-props/slots.tsrename to packages/vue/src/controls/slots/instance.tsindex 4dd90525e..ae9a8bca1 100644--- a/packages/vue/src/controls/component-props/slots.ts+++ b/packages/vue/src/controls/slots/instance.ts@@ -1,18 +1,11 @@import {- canCreateSlot,instanceSlotFrames,isPreferredComponent,nonPreferredLayers,ownsSlotContent,- slotOwner,slotPropertyId} from '@open-pencil/scene-graph'-import type {- ComponentPropertyDefinition,- SceneGraph,- SceneNode,- SlotPropertyPatch-} from '@open-pencil/scene-graph'+import type { ComponentPropertyDefinition, SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { useEditor } from '#vue/editor/context'import { useSceneComputed } from '#vue/internal/scene-computed/use'@@ -157,108 +150,3 @@ export function useSlotProperties() {selectLayers: (ids: string[]) => editor.select(ids)}}--/** A slot property as its main component defines it. */-export interface SlotDefinitionControl {- id: string- name: string- description: string- minChildren?: number- maxChildren?: number- preferredOnly: boolean- /** Components the slot prefers, resolved from the definition's preferred values. */- preferred: SlotInstanceOption[]-}--/** The value a preferred-components list stores for a component: its key, else its id. */-function preferredValue(component: SceneNode): string {- return component.componentKey ?? component.id-}--/**- * Slot properties of the selected main component or slot frame, with the actions that- * create, configure, and remove them.- */-export function useSlotAuthoring() {- const editor = useEditor()- const target = useSceneComputed(() => {- const nodes = editor.getSelectedNodes()- if (nodes.length !== 1) return undefined- const [node] = nodes- if (node.type === 'COMPONENT') return { owner: node, frame: undefined, propertyId: undefined }- const owner = slotOwner(editor.graph, node)- if (!owner) return undefined- const propertyId = slotPropertyId(node)- if (!propertyId && !canCreateSlot(editor.graph, node)) return undefined- return { owner, frame: node, propertyId }- })- const slots = useSceneComputed<SlotDefinitionControl[]>(() => {- const current = target.value- if (!current) return []- return current.owner.componentPropertyDefinitions- .filter((definition) => definition.type === 'SLOT')- .filter((definition) => !current.frame || definition.id === current.propertyId)- .map((definition) => {- const values = new Set(definition.preferredValues)- return {- id: definition.id,- name: definition.name,- description: definition.description ?? '',- minChildren: definition.slotSettings?.minChildren,- maxChildren: definition.slotSettings?.maxChildren,- preferredOnly: definition.slotSettings?.allowPreferredValuesOnly ?? false,- preferred: slotInstanceOptions(editor.graph, definition).filter(- (option) => option.preferred && values.size > 0- )- }- })- })- /** Whether the selection is a frame that can become a slot. */- const canCreate = useSceneComputed(() => !!target.value?.frame && !target.value.propertyId)- const active = useSceneComputed(() => slots.value.length > 0 || canCreate.value)-- function update(propertyId: string, patch: SlotPropertyPatch) {- const owner = target.value?.owner- if (owner) editor.updateSlot(owner.id, propertyId, patch)- }-- function definition(propertyId: string): ComponentPropertyDefinition | undefined {- return target.value?.owner.componentPropertyDefinitions.find((item) => item.id === propertyId)- }-- /** Components that can be marked preferred, the slot's current choices first. */- function options(propertyId: string): SlotInstanceOption[] {- const found = definition(propertyId)- return found ? slotInstanceOptions(editor.graph, found) : []- }-- function setPreferred(propertyId: string, componentId: string, preferred: boolean) {- const found = definition(propertyId)- const component = editor.graph.getNode(componentId)- if (!found || !component) return- const keys = new Set([component.id, component.componentKey, component.sourceLibraryKey])- const rest = (found.preferredValues ?? []).filter((value) => !keys.has(value))- update(propertyId, {- preferredValues: preferred ? [...rest, preferredValue(component)] : rest- })- }-- return {- active,- canCreate,- slots,- options,- create: () => editor.createSlot(),- rename: (propertyId: string, name: string) => update(propertyId, { name }),- describe: (propertyId: string, description: string) => update(propertyId, { description }),- setLimits: (propertyId: string, limits: { minChildren?: number; maxChildren?: number }) =>- update(propertyId, { slotSettings: limits }),- setPreferredOnly: (propertyId: string, value: boolean) =>- update(propertyId, { slotSettings: { allowPreferredValuesOnly: value } }),- setPreferred,- remove: (propertyId: string) => {- const owner = target.value?.owner- if (owner) editor.removeSlot(owner.id, propertyId)- }- }-}diff --git a/packages/vue/src/controls/component-props/authoring.ts b/packages/vue/src/controls/variants/authoring.tssimilarity index 100%rename from packages/vue/src/controls/component-props/authoring.tsrename to packages/vue/src/controls/variants/authoring.tsdiff --git a/packages/vue/src/controls/variants/index.ts b/packages/vue/src/controls/variants/index.tsnew file mode 100644index 000000000..5bca920a9--- /dev/null+++ b/packages/vue/src/controls/variants/index.ts@@ -0,0 +1 @@+export * from './authoring'diff --git a/packages/vue/src/i18n/locales/de/editor.json b/packages/vue/src/i18n/locales/de/editor.jsonindex 2ac305411..851ca073b 100644--- a/packages/vue/src/i18n/locales/de/editor.json+++ b/packages/vue/src/i18n/locales/de/editor.json@@ -1,5 +1,9 @@{"toolOptions": "Optionen für {tool}","removeGradientStop": "Farbverlaufspunkt entfernen",- "showUI": "UI anzeigen ({shortcut})"+ "showUI": "UI anzeigen ({shortcut})",+ "previewing": "Vorschau",+ "resetPreview": "Zurücksetzen",+ "leavePreview": "Vorschau verlassen ({shortcut})",+ "startPreview": "Vorschau ({shortcut})"}diff --git a/packages/vue/src/i18n/locales/de/menu.json b/packages/vue/src/i18n/locales/de/menu.jsonindex 2f759b7ce..4012c4530 100644--- a/packages/vue/src/i18n/locales/de/menu.json+++ b/packages/vue/src/i18n/locales/de/menu.json@@ -72,5 +72,6 @@"exportSelectionAsPNG": "Auswahl als PNG exportieren","exportSelectionAsSVG": "Auswahl als SVG exportieren","exportSelectionAsPPTX": "Auswahl als PPTX exportieren",- "exportSelectionAsFig": "Auswahl als .fig exportieren"+ "exportSelectionAsFig": "Auswahl als .fig exportieren",+ "togglePreview": "Vorschau"}diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.jsonindex e6c43cbed..aeff17cad 100644--- a/packages/vue/src/i18n/locales/de/panels.json+++ b/packages/vue/src/i18n/locales/de/panels.json@@ -405,5 +405,85 @@"strokeDashLength": "Strich","strokeDashGap": "Lücke","lineHeightMode": "Zeilenhöhenmodus",- "unresolvedVariable": "Variablenwert nicht verfügbar"+ "unresolvedVariable": "Variablenwert nicht verfügbar",+ "behaviour": "Verhalten",+ "addBehaviour": "Verhalten hinzufügen",+ "removeBehaviour": "Verhalten entfernen",+ "searchBehaviours": "Verhalten suchen",+ "noBehavioursFound": "Kein Verhalten gefunden",+ "behaviourSwitch": "Schalter",+ "behaviourCheckbox": "Kontrollkästchen",+ "behaviourSlider": "Schieberegler",+ "behaviourTabs": "Tabs",+ "behaviourSwitchDescription": "Schaltet zwischen an und aus",+ "behaviourCheckboxDescription": "Hakt an und ab",+ "behaviourSliderDescription": "Zieht einen Regler an einer Spur entlang",+ "behaviourTabsDescription": "Zeigt jeweils ein Panel",+ "behaviourTextField": "Textfeld",+ "behaviourTextFieldDescription": "Nimmt eine Zeile Eingabe auf",+ "behaviourTextarea": "Textbereich",+ "behaviourTextareaDescription": "Nimmt mehrere Zeilen Eingabe auf",+ "behaviourNumberField": "Zahlenfeld",+ "behaviourNumberFieldDescription": "Erhöht, verringert und nimmt Zahlen auf",+ "behaviourFilled": "Ausgefüllt",+ "behaviourText": "Text",+ "behaviourIncrement": "Erhöhen",+ "behaviourDecrement": "Verringern",+ "behaviourToggle": "Umschalter",+ "behaviourToggleDescription": "Wird gedrückt und wieder gelöst",+ "behaviourRadio": "Option",+ "behaviourRadioDescription": "Wird in ihrer Optionsgruppe aktiviert",+ "behaviourRadioGroup": "Optionsgruppe",+ "behaviourRadioGroupDescription": "Aktiviert eine ihrer Optionen",+ "behaviourToggleGroup": "Umschaltergruppe",+ "behaviourToggleGroupDescription": "Aktiviert höchstens einen ihrer Umschalter",+ "behaviourProgress": "Fortschritt",+ "behaviourProgressDescription": "Füllt eine Spur bis zu einem Wert",+ "behaviourCollapsible": "Ausklappbereich",+ "behaviourCollapsibleDescription": "Zeigt und verbirgt seinen Inhalt",+ "behaviourAccordion": "Akkordeon",+ "behaviourAccordionDescription": "Öffnet jeweils einen seiner Ausklappbereiche",+ "behaviourOpen": "Geöffnet",+ "behaviourItems": "Elemente",+ "behaviourChecked": "Ausgewählt",+ "behaviourPressed": "Gedrückt",+ "behaviourAddTextLayer": "Textebene hinzufügen",+ "behaviourAddVariants": "Varianten Aus und Ein hinzufügen",+ "behaviourAddSlot": "Slot {name} hinzufügen",+ "behaviourMoreOptions": "Weitere Optionen",+ "behaviourValue": "Wert",+ "behaviourDisabled": "Deaktiviert",+ "behaviourOnValue": "An",+ "behaviourOffValue": "Aus",+ "behaviourTrack": "Spur",+ "behaviourThumb": "Regler",+ "behaviourRange": "Bereich",+ "behaviourIndicator": "Indikator",+ "behaviourList": "Liste",+ "behaviourTrigger": "Auslöser",+ "behaviourContent": "Inhalt",+ "behaviourPanels": "Bereiche",+ "behaviourChooseProperty": "Eigenschaft wählen",+ "behaviourChooseSlot": "Slot wählen",+ "behaviourNoSlots": "Noch keine Slots; erstelle einen mit „Slot erstellen“",+ "behaviourComplete": "Bereit",+ "behaviourMin": "Min",+ "behaviourMax": "Max",+ "behaviourStep": "Schritt",+ "behaviourStart": "Anfangswert",+ "behaviourNextStep": "Noch nötig: {names}.",+ "behaviourStatesHint": "Hover-, Gedrückt-, Fokus- und Deaktiviert-Ansichten werden als Varianten gezeichnet.",+ "behaviourAddStates": "Zustandsvarianten hinzufügen",+ "behaviourButton": "Schaltfläche",+ "behaviourButtonDescription": "Zeigt Hover-, Gedrückt-, Fokus- und Deaktiviert-Zustände",+ "behaviourStates": "Zustände",+ "behaviourStateRest": "Standard",+ "behaviourStateHover": "Hover",+ "behaviourStatePressed": "Gedrückt",+ "behaviourStateFocus": "Fokus",+ "behaviourStateDisabled": "Deaktiviert",+ "behaviourStateUnset": "Keine",+ "behaviourStateField": "Zustand {state}",+ "searchComponentProperties": "Eigenschaften suchen",+ "noComponentProperties": "Keine Eigenschaften gefunden"}diff --git a/packages/vue/src/i18n/locales/es/editor.json b/packages/vue/src/i18n/locales/es/editor.jsonindex 0ff6e825a..7e3d6751d 100644--- a/packages/vue/src/i18n/locales/es/editor.json+++ b/packages/vue/src/i18n/locales/es/editor.json@@ -1,5 +1,9 @@{"toolOptions": "Opciones de {tool}","removeGradientStop": "Eliminar parada de degradado",- "showUI": "Mostrar interfaz ({shortcut})"+ "showUI": "Mostrar interfaz ({shortcut})",+ "previewing": "Vista previa",+ "resetPreview": "Restablecer",+ "leavePreview": "Salir de la vista previa ({shortcut})",+ "startPreview": "Vista previa ({shortcut})"}diff --git a/packages/vue/src/i18n/locales/es/menu.json b/packages/vue/src/i18n/locales/es/menu.jsonindex 8bdbf0d73..dbe08d42b 100644--- a/packages/vue/src/i18n/locales/es/menu.json+++ b/packages/vue/src/i18n/locales/es/menu.json@@ -72,5 +72,6 @@"exportSelectionAsPNG": "Exportar selección como PNG","exportSelectionAsSVG": "Exportar selección como SVG","exportSelectionAsPPTX": "Exportar selección como PPTX",- "exportSelectionAsFig": "Exportar selección como .fig"+ "exportSelectionAsFig": "Exportar selección como .fig",+ "togglePreview": "Vista previa"}diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.jsonindex bb8244d9e..a3dd34248 100644--- a/packages/vue/src/i18n/locales/es/panels.json+++ b/packages/vue/src/i18n/locales/es/panels.json@@ -405,5 +405,85 @@"strokeDashLength": "Guion","strokeDashGap": "Espacio","lineHeightMode": "Modo de altura de línea",- "unresolvedVariable": "Valor de variable no disponible"+ "unresolvedVariable": "Valor de variable no disponible",+ "behaviour": "Comportamiento",+ "addBehaviour": "Añadir comportamiento",+ "removeBehaviour": "Quitar comportamiento",+ "searchBehaviours": "Buscar comportamientos",+ "noBehavioursFound": "No se encontraron comportamientos",+ "behaviourSwitch": "Interruptor",+ "behaviourCheckbox": "Casilla",+ "behaviourSlider": "Control deslizante",+ "behaviourTabs": "Pestañas",+ "behaviourSwitchDescription": "Alterna entre encendido y apagado",+ "behaviourCheckboxDescription": "Marca y desmarca",+ "behaviourSliderDescription": "Desliza un control a lo largo de una pista",+ "behaviourTabsDescription": "Muestra un panel a la vez",+ "behaviourTextField": "Campo de texto",+ "behaviourTextFieldDescription": "Admite una línea de texto",+ "behaviourTextarea": "Área de texto",+ "behaviourTextareaDescription": "Admite varias líneas de texto",+ "behaviourNumberField": "Campo numérico",+ "behaviourNumberFieldDescription": "Aumenta, reduce y admite números",+ "behaviourFilled": "Relleno",+ "behaviourText": "Texto",+ "behaviourIncrement": "Aumentar",+ "behaviourDecrement": "Reducir",+ "behaviourToggle": "Interruptor de alternancia",+ "behaviourToggleDescription": "Se pulsa y se suelta",+ "behaviourRadio": "Opción",+ "behaviourRadioDescription": "Se activa dentro de su grupo de opciones",+ "behaviourRadioGroup": "Grupo de opciones",+ "behaviourRadioGroupDescription": "Activa una de sus opciones",+ "behaviourToggleGroup": "Grupo de alternancia",+ "behaviourToggleGroupDescription": "Activa como máximo uno de sus botones",+ "behaviourProgress": "Progreso",+ "behaviourProgressDescription": "Llena una pista hasta un valor",+ "behaviourCollapsible": "Plegable",+ "behaviourCollapsibleDescription": "Muestra y oculta su contenido",+ "behaviourAccordion": "Acordeón",+ "behaviourAccordionDescription": "Abre uno de sus plegables a la vez",+ "behaviourOpen": "Abierto",+ "behaviourItems": "Elementos",+ "behaviourChecked": "Marcado",+ "behaviourPressed": "Pulsado",+ "behaviourAddTextLayer": "Añadir capa de texto",+ "behaviourAddVariants": "Añadir variantes Off y On",+ "behaviourAddSlot": "Añadir slot {name}",+ "behaviourMoreOptions": "Más opciones",+ "behaviourValue": "Valor",+ "behaviourDisabled": "Desactivado",+ "behaviourOnValue": "Encendido",+ "behaviourOffValue": "Apagado",+ "behaviourTrack": "Pista",+ "behaviourThumb": "Control",+ "behaviourRange": "Rango",+ "behaviourIndicator": "Indicador",+ "behaviourList": "Lista",+ "behaviourTrigger": "Disparador",+ "behaviourContent": "Contenido",+ "behaviourPanels": "Paneles",+ "behaviourChooseProperty": "Elegir propiedad",+ "behaviourChooseSlot": "Elegir slot",+ "behaviourNoSlots": "Aún no hay slots; crea uno con Crear slot",+ "behaviourComplete": "Listo",+ "behaviourMin": "Mín",+ "behaviourMax": "Máx",+ "behaviourStep": "Paso",+ "behaviourStart": "Inicio",+ "behaviourNextStep": "Falta: {names}.",+ "behaviourStatesHint": "Los aspectos de hover, pulsado, foco y deshabilitado se dibujan como variantes.",+ "behaviourAddStates": "Añadir variantes de estado",+ "behaviourButton": "Botón",+ "behaviourButtonDescription": "Muestra los estados de hover, pulsado, foco y desactivado",+ "behaviourStates": "Estados",+ "behaviourStateRest": "Predeterminado",+ "behaviourStateHover": "Al pasar",+ "behaviourStatePressed": "Pulsado",+ "behaviourStateFocus": "Foco",+ "behaviourStateDisabled": "Desactivado",+ "behaviourStateUnset": "Ninguno",+ "behaviourStateField": "Estado {state}",+ "searchComponentProperties": "Buscar propiedades",+ "noComponentProperties": "No se encontraron propiedades"}diff --git a/packages/vue/src/i18n/locales/fr/editor.json b/packages/vue/src/i18n/locales/fr/editor.jsonindex 86fbfa76b..8275446dd 100644--- a/packages/vue/src/i18n/locales/fr/editor.json+++ b/packages/vue/src/i18n/locales/fr/editor.json@@ -1,5 +1,9 @@{"toolOptions": "Options de {tool}","removeGradientStop": "Supprimer le point de dégradé",- "showUI": "Afficher l’interface ({shortcut})"+ "showUI": "Afficher l’interface ({shortcut})",+ "previewing": "Aperçu",+ "resetPreview": "Réinitialiser",+ "leavePreview": "Quitter l’aperçu ({shortcut})",+ "startPreview": "Aperçu ({shortcut})"}diff --git a/packages/vue/src/i18n/locales/fr/menu.json b/packages/vue/src/i18n/locales/fr/menu.jsonindex c9b96fe3b..686a11d0d 100644--- a/packages/vue/src/i18n/locales/fr/menu.json+++ b/packages/vue/src/i18n/locales/fr/menu.json@@ -72,5 +72,6 @@"exportSelectionAsPNG": "Exporter la sélection en PNG","exportSelectionAsSVG": "Exporter la sélection en SVG","exportSelectionAsPPTX": "Exporter la sélection en PPTX",- "exportSelectionAsFig": "Exporter la sélection en .fig"+ "exportSelectionAsFig": "Exporter la sélection en .fig",+ "togglePreview": "Aperçu"}diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.jsonindex 4b1bf9cee..cfd3c75dc 100644--- a/packages/vue/src/i18n/locales/fr/panels.json+++ b/packages/vue/src/i18n/locales/fr/panels.json@@ -405,5 +405,85 @@"strokeDashLength": "Tiret","strokeDashGap": "Espacement","lineHeightMode": "Mode de hauteur de ligne",- "unresolvedVariable": "Valeur de variable indisponible"+ "unresolvedVariable": "Valeur de variable indisponible",+ "behaviour": "Comportement",+ "addBehaviour": "Ajouter un comportement",+ "removeBehaviour": "Supprimer le comportement",+ "searchBehaviours": "Rechercher des comportements",+ "noBehavioursFound": "Aucun comportement trouvé",+ "behaviourSwitch": "Interrupteur",+ "behaviourCheckbox": "Case à cocher",+ "behaviourSlider": "Curseur",+ "behaviourTabs": "Onglets",+ "behaviourSwitchDescription": "Bascule entre activé et désactivé",+ "behaviourCheckboxDescription": "Coche et décoche",+ "behaviourSliderDescription": "Fait glisser un bouton le long d’une piste",+ "behaviourTabsDescription": "Affiche un panneau à la fois",+ "behaviourTextField": "Champ de texte",+ "behaviourTextFieldDescription": "Accepte une ligne de saisie",+ "behaviourTextarea": "Zone de texte",+ "behaviourTextareaDescription": "Accepte plusieurs lignes de saisie",+ "behaviourNumberField": "Champ numérique",+ "behaviourNumberFieldDescription": "Incrémente et saisit un nombre",+ "behaviourFilled": "Rempli",+ "behaviourText": "Texte",+ "behaviourIncrement": "Incrémenter",+ "behaviourDecrement": "Décrémenter",+ "behaviourToggle": "Bascule",+ "behaviourToggleDescription": "S’enfonce et se relâche",+ "behaviourRadio": "Bouton radio",+ "behaviourRadioDescription": "S’active dans son groupe radio",+ "behaviourRadioGroup": "Groupe radio",+ "behaviourRadioGroupDescription": "Active l’une de ses options",+ "behaviourToggleGroup": "Groupe de bascules",+ "behaviourToggleGroupDescription": "Active au plus une de ses bascules",+ "behaviourProgress": "Progression",+ "behaviourProgressDescription": "Remplit une piste jusqu’à une valeur",+ "behaviourCollapsible": "Repliable",+ "behaviourCollapsibleDescription": "Affiche et masque son contenu",+ "behaviourAccordion": "Accordéon",+ "behaviourAccordionDescription": "Ouvre un seul de ses repliables à la fois",+ "behaviourOpen": "Ouvert",+ "behaviourItems": "Éléments",+ "behaviourChecked": "Coché",+ "behaviourPressed": "Appuyé",+ "behaviourAddTextLayer": "Ajouter un calque de texte",+ "behaviourAddVariants": "Ajouter les variantes Off et On",+ "behaviourAddSlot": "Ajouter le slot {name}",+ "behaviourMoreOptions": "Plus d’options",+ "behaviourValue": "Valeur",+ "behaviourDisabled": "Désactivé",+ "behaviourOnValue": "Activé",+ "behaviourOffValue": "Désactivé",+ "behaviourTrack": "Piste",+ "behaviourThumb": "Bouton",+ "behaviourRange": "Plage",+ "behaviourIndicator": "Indicateur",+ "behaviourList": "Liste",+ "behaviourTrigger": "Déclencheur",+ "behaviourContent": "Contenu",+ "behaviourPanels": "Panneaux",+ "behaviourChooseProperty": "Choisir une propriété",+ "behaviourChooseSlot": "Choisir un slot",+ "behaviourNoSlots": "Aucun slot pour l’instant ; créez-en un avec Créer un slot",+ "behaviourComplete": "Prêt",+ "behaviourMin": "Min",+ "behaviourMax": "Max",+ "behaviourStep": "Pas",+ "behaviourStart": "Départ",+ "behaviourNextStep": "Encore requis : {names}.",+ "behaviourStatesHint": "Les apparences survol, pressé, focus et désactivé sont dessinées comme des variantes.",+ "behaviourAddStates": "Ajouter des variantes d’état",+ "behaviourButton": "Bouton",+ "behaviourButtonDescription": "Affiche les états survol, appuyé, focus et désactivé",+ "behaviourStates": "États",+ "behaviourStateRest": "Par défaut",+ "behaviourStateHover": "Survol",+ "behaviourStatePressed": "Appuyé",+ "behaviourStateFocus": "Focus",+ "behaviourStateDisabled": "Désactivé",+ "behaviourStateUnset": "Aucun",+ "behaviourStateField": "État {state}",+ "searchComponentProperties": "Rechercher des propriétés",+ "noComponentProperties": "Aucune propriété trouvée"}diff --git a/packages/vue/src/i18n/locales/it/editor.json b/packages/vue/src/i18n/locales/it/editor.jsonindex 08081b81c..f78efcad3 100644--- a/packages/vue/src/i18n/locales/it/editor.json+++ b/packages/vue/src/i18n/locales/it/editor.json@@ -1,5 +1,9 @@{"toolOptions": "Opzioni di {tool}","removeGradientStop": "Rimuovi punto sfumatura",- "showUI": "Mostra interfaccia ({shortcut})"+ "showUI": "Mostra interfaccia ({shortcut})",+ "previewing": "Anteprima",+ "resetPreview": "Ripristina",+ "leavePreview": "Esci dall’anteprima ({shortcut})",+ "startPreview": "Anteprima ({shortcut})"}diff --git a/packages/vue/src/i18n/locales/it/menu.json b/packages/vue/src/i18n/locales/it/menu.jsonindex 0969cdd81..588ed384c 100644--- a/packages/vue/src/i18n/locales/it/menu.json+++ b/packages/vue/src/i18n/locales/it/menu.json@@ -72,5 +72,6 @@"exportSelectionAsPNG": "Esporta selezione come PNG","exportSelectionAsSVG": "Esporta selezione come SVG","exportSelectionAsPPTX": "Esporta selezione come PPTX",- "exportSelectionAsFig": "Esporta selezione come .fig"+ "exportSelectionAsFig": "Esporta selezione come .fig",+ "togglePreview": "Anteprima"}diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.jsonindex 38bccb2b3..c05820459 100644--- a/packages/vue/src/i18n/locales/it/panels.json+++ b/packages/vue/src/i18n/locales/it/panels.json@@ -405,5 +405,85 @@"strokeDashLength": "Trattino","strokeDashGap": "Spazio","lineHeightMode": "Modalità altezza riga",- "unresolvedVariable": "Valore della variabile non disponibile"+ "unresolvedVariable": "Valore della variabile non disponibile",+ "behaviour": "Comportamento",+ "addBehaviour": "Aggiungi comportamento",+ "removeBehaviour": "Rimuovi comportamento",+ "searchBehaviours": "Cerca comportamenti",+ "noBehavioursFound": "Nessun comportamento trovato",+ "behaviourSwitch": "Interruttore",+ "behaviourCheckbox": "Casella di controllo",+ "behaviourSlider": "Cursore",+ "behaviourTabs": "Schede",+ "behaviourSwitchDescription": "Passa da acceso a spento",+ "behaviourCheckboxDescription": "Seleziona e deseleziona",+ "behaviourSliderDescription": "Trascina un cursore lungo una traccia",+ "behaviourTabsDescription": "Mostra un pannello alla volta",+ "behaviourTextField": "Campo di testo",+ "behaviourTextFieldDescription": "Accetta una riga di testo",+ "behaviourTextarea": "Area di testo",+ "behaviourTextareaDescription": "Accetta più righe di testo",+ "behaviourNumberField": "Campo numerico",+ "behaviourNumberFieldDescription": "Incrementa e accetta un numero",+ "behaviourFilled": "Compilato",+ "behaviourText": "Testo",+ "behaviourIncrement": "Incrementa",+ "behaviourDecrement": "Decrementa",+ "behaviourToggle": "Interruttore a pulsante",+ "behaviourToggleDescription": "Si preme e si rilascia",+ "behaviourRadio": "Pulsante di opzione",+ "behaviourRadioDescription": "Si attiva nel suo gruppo radio",+ "behaviourRadioGroup": "Gruppo radio",+ "behaviourRadioGroupDescription": "Attiva una delle sue opzioni",+ "behaviourToggleGroup": "Gruppo di interruttori",+ "behaviourToggleGroupDescription": "Attiva al massimo uno dei suoi interruttori",+ "behaviourProgress": "Avanzamento",+ "behaviourProgressDescription": "Riempie una traccia fino a un valore",+ "behaviourCollapsible": "Comprimibile",+ "behaviourCollapsibleDescription": "Mostra e nasconde il suo contenuto",+ "behaviourAccordion": "Fisarmonica",+ "behaviourAccordionDescription": "Apre uno dei suoi comprimibili alla volta",+ "behaviourOpen": "Aperto",+ "behaviourItems": "Elementi",+ "behaviourChecked": "Selezionato",+ "behaviourPressed": "Premuto",+ "behaviourAddTextLayer": "Aggiungi livello di testo",+ "behaviourAddVariants": "Aggiungi varianti Off e On",+ "behaviourAddSlot": "Aggiungi slot {name}",+ "behaviourMoreOptions": "Altre opzioni",+ "behaviourValue": "Valore",+ "behaviourDisabled": "Disattivato",+ "behaviourOnValue": "Acceso",+ "behaviourOffValue": "Spento",+ "behaviourTrack": "Traccia",+ "behaviourThumb": "Cursore",+ "behaviourRange": "Intervallo",+ "behaviourIndicator": "Indicatore",+ "behaviourList": "Elenco",+ "behaviourTrigger": "Attivatore",+ "behaviourContent": "Contenuto",+ "behaviourPanels": "Pannelli",+ "behaviourChooseProperty": "Scegli proprietà",+ "behaviourChooseSlot": "Scegli slot",+ "behaviourNoSlots": "Ancora nessuno slot; creane uno con Crea slot",+ "behaviourComplete": "Pronto",+ "behaviourMin": "Min",+ "behaviourMax": "Max",+ "behaviourStep": "Passo",+ "behaviourStart": "Inizio",+ "behaviourNextStep": "Ancora da impostare: {names}.",+ "behaviourStatesHint": "Gli aspetti hover, premuto, focus e disattivato si disegnano come varianti.",+ "behaviourAddStates": "Aggiungi varianti di stato",+ "behaviourButton": "Pulsante",+ "behaviourButtonDescription": "Mostra gli stati hover, premuto, focus e disattivato",+ "behaviourStates": "Stati",+ "behaviourStateRest": "Predefinito",+ "behaviourStateHover": "Hover",+ "behaviourStatePressed": "Premuto",+ "behaviourStateFocus": "Focus",+ "behaviourStateDisabled": "Disattivato",+ "behaviourStateUnset": "Nessuno",+ "behaviourStateField": "Stato {state}",+ "searchComponentProperties": "Cerca proprietà",+ "noComponentProperties": "Nessuna proprietà trovata"}diff --git a/packages/vue/src/i18n/locales/ja/editor.json b/packages/vue/src/i18n/locales/ja/editor.jsonindex 412a3ba52..9ee7015c1 100644--- a/packages/vue/src/i18n/locales/ja/editor.json+++ b/packages/vue/src/i18n/locales/ja/editor.json@@ -1,5 +1,9 @@{"toolOptions": "{tool}のオプション","removeGradientStop": "グラデーション停止点を削除",- "showUI": "UIを表示 ({shortcut})"+ "showUI": "UIを表示 ({shortcut})",+ "previewing": "プレビュー中",+ "resetPreview": "リセット",+ "leavePreview": "プレビューを終了 ({shortcut})",+ "startPreview": "プレビュー ({shortcut})"}diff --git a/packages/vue/src/i18n/locales/ja/menu.json b/packages/vue/src/i18n/locales/ja/menu.jsonindex 6ea4d1914..51473f2d5 100644--- a/packages/vue/src/i18n/locales/ja/menu.json+++ b/packages/vue/src/i18n/locales/ja/menu.json@@ -72,5 +72,6 @@"exportSelectionAsPNG": "選択範囲を PNG としてエクスポート","exportSelectionAsSVG": "選択範囲を SVG としてエクスポート","exportSelectionAsPPTX": "選択範囲を PPTX としてエクスポート",- "exportSelectionAsFig": "選択範囲を .fig としてエクスポート"+ "exportSelectionAsFig": "選択範囲を .fig としてエクスポート",+ "togglePreview": "プレビュー"}diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.jsonindex 18d175f1f..c13937f86 100644--- a/packages/vue/src/i18n/locales/ja/panels.json+++ b/packages/vue/src/i18n/locales/ja/panels.json@@ -399,5 +399,85 @@"strokeDashLength": "破線の長さ","strokeDashGap": "間隔","lineHeightMode": "行の高さモード",- "unresolvedVariable": "変数の値を取得できません"+ "unresolvedVariable": "変数の値を取得できません",+ "behaviour": "動作",+ "addBehaviour": "動作を追加",+ "removeBehaviour": "動作を削除",+ "searchBehaviours": "動作を検索",+ "noBehavioursFound": "動作が見つかりません",+ "behaviourSwitch": "スイッチ",+ "behaviourCheckbox": "チェックボックス",+ "behaviourSlider": "スライダー",+ "behaviourTabs": "タブ",+ "behaviourSwitchDescription": "オンとオフを切り替えます",+ "behaviourCheckboxDescription": "チェックを付け外しします",+ "behaviourSliderDescription": "トラックに沿ってつまみをドラッグします",+ "behaviourTabsDescription": "一度に 1 つのパネルを表示します",+ "behaviourTextField": "テキストフィールド",+ "behaviourTextFieldDescription": "1 行の入力を受け付けます",+ "behaviourTextarea": "テキストエリア",+ "behaviourTextareaDescription": "複数行の入力を受け付けます",+ "behaviourNumberField": "数値フィールド",+ "behaviourNumberFieldDescription": "数値の増減と入力を受け付けます",+ "behaviourFilled": "入力済み",+ "behaviourText": "テキスト",+ "behaviourIncrement": "増やす",+ "behaviourDecrement": "減らす",+ "behaviourToggle": "トグル",+ "behaviourToggleDescription": "押し込みと解除を切り替えます",+ "behaviourRadio": "ラジオ",+ "behaviourRadioDescription": "ラジオグループ内でオンになります",+ "behaviourRadioGroup": "ラジオグループ",+ "behaviourRadioGroupDescription": "ラジオのいずれか 1 つをオンにします",+ "behaviourToggleGroup": "トグルグループ",+ "behaviourToggleGroupDescription": "トグルを最大 1 つオンにします",+ "behaviourProgress": "プログレス",+ "behaviourProgressDescription": "値までトラックを塗りつぶします",+ "behaviourCollapsible": "折りたたみ",+ "behaviourCollapsibleDescription": "コンテンツを表示または非表示にします",+ "behaviourAccordion": "アコーディオン",+ "behaviourAccordionDescription": "折りたたみを一度に 1 つだけ開きます",+ "behaviourOpen": "開く",+ "behaviourItems": "項目",+ "behaviourChecked": "チェック",+ "behaviourPressed": "押下",+ "behaviourAddTextLayer": "テキストレイヤーを追加",+ "behaviourAddVariants": "Off と On のバリアントを追加",+ "behaviourAddSlot": "{name} スロットを追加",+ "behaviourMoreOptions": "その他のオプション",+ "behaviourValue": "値",+ "behaviourDisabled": "無効",+ "behaviourOnValue": "オン",+ "behaviourOffValue": "オフ",+ "behaviourTrack": "トラック",+ "behaviourThumb": "つまみ",+ "behaviourRange": "範囲",+ "behaviourIndicator": "インジケーター",+ "behaviourList": "リスト",+ "behaviourTrigger": "トリガー",+ "behaviourContent": "コンテンツ",+ "behaviourPanels": "パネル",+ "behaviourChooseProperty": "プロパティを選択",+ "behaviourChooseSlot": "スロットを選択",+ "behaviourNoSlots": "スロットはまだありません。「スロットを作成」で作成できます",+ "behaviourComplete": "準備完了",+ "behaviourMin": "最小",+ "behaviourMax": "最大",+ "behaviourStep": "ステップ",+ "behaviourStart": "開始値",+ "behaviourNextStep": "まだ必要: {names}。",+ "behaviourStatesHint": "ホバー、押下、フォーカス、無効の見た目はバリアントとして描きます。",+ "behaviourAddStates": "状態バリアントを追加",+ "behaviourButton": "ボタン",+ "behaviourButtonDescription": "ホバー、押下、フォーカス、無効の状態を表示します",+ "behaviourStates": "状態",+ "behaviourStateRest": "既定",+ "behaviourStateHover": "ホバー",+ "behaviourStatePressed": "押下",+ "behaviourStateFocus": "フォーカス",+ "behaviourStateDisabled": "無効",+ "behaviourStateUnset": "なし",+ "behaviourStateField": "{state} 状態",+ "searchComponentProperties": "プロパティを検索",+ "noComponentProperties": "プロパティが見つかりません"}diff --git a/packages/vue/src/i18n/locales/pl/editor.json b/packages/vue/src/i18n/locales/pl/editor.jsonindex 5ef480038..2d2b71a63 100644--- a/packages/vue/src/i18n/locales/pl/editor.json+++ b/packages/vue/src/i18n/locales/pl/editor.json@@ -1,5 +1,9 @@{"toolOptions": "Opcje narzędzia {tool}","removeGradientStop": "Usuń punkt gradientu",- "showUI": "Pokaż interfejs ({shortcut})"+ "showUI": "Pokaż interfejs ({shortcut})",+ "previewing": "Podgląd",+ "resetPreview": "Resetuj",+ "leavePreview": "Zakończ podgląd ({shortcut})",+ "startPreview": "Podgląd ({shortcut})"}diff --git a/packages/vue/src/i18n/locales/pl/menu.json b/packages/vue/src/i18n/locales/pl/menu.jsonindex f2824bb9c..e24542235 100644--- a/packages/vue/src/i18n/locales/pl/menu.json+++ b/packages/vue/src/i18n/locales/pl/menu.json@@ -72,5 +72,6 @@"exportSelectionAsPNG": "Eksportuj zaznaczenie jako PNG","exportSelectionAsSVG": "Eksportuj zaznaczenie jako SVG","exportSelectionAsPPTX": "Eksportuj zaznaczenie jako PPTX",- "exportSelectionAsFig": "Eksportuj zaznaczenie jako .fig"+ "exportSelectionAsFig": "Eksportuj zaznaczenie jako .fig",+ "togglePreview": "Podgląd"}diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.jsonindex f0c986eae..0c97e0d20 100644--- a/packages/vue/src/i18n/locales/pl/panels.json+++ b/packages/vue/src/i18n/locales/pl/panels.json@@ -411,5 +411,85 @@"strokeDashLength": "Kreska","strokeDashGap": "Odstęp","lineHeightMode": "Tryb wysokości wiersza",- "unresolvedVariable": "Wartość zmiennej jest niedostępna"+ "unresolvedVariable": "Wartość zmiennej jest niedostępna",+ "behaviour": "Zachowanie",+ "addBehaviour": "Dodaj zachowanie",+ "removeBehaviour": "Usuń zachowanie",+ "searchBehaviours": "Szukaj zachowań",+ "noBehavioursFound": "Nie znaleziono zachowań",+ "behaviourSwitch": "Przełącznik",+ "behaviourCheckbox": "Pole wyboru",+ "behaviourSlider": "Suwak",+ "behaviourTabs": "Karty",+ "behaviourSwitchDescription": "Przełącza między włączonym a wyłączonym",+ "behaviourCheckboxDescription": "Zaznacza i odznacza",+ "behaviourSliderDescription": "Przesuwa uchwyt wzdłuż ścieżki",+ "behaviourTabsDescription": "Pokazuje jeden panel naraz",+ "behaviourTextField": "Pole tekstowe",+ "behaviourTextFieldDescription": "Przyjmuje jeden wiersz tekstu",+ "behaviourTextarea": "Obszar tekstowy",+ "behaviourTextareaDescription": "Przyjmuje kilka wierszy tekstu",+ "behaviourNumberField": "Pole liczbowe",+ "behaviourNumberFieldDescription": "Zwiększa, zmniejsza i przyjmuje liczbę",+ "behaviourFilled": "Wypełnione",+ "behaviourText": "Tekst",+ "behaviourIncrement": "Zwiększ",+ "behaviourDecrement": "Zmniejsz",+ "behaviourToggle": "Przełącznik",+ "behaviourToggleDescription": "Wciska się i zwalnia",+ "behaviourRadio": "Opcja",+ "behaviourRadioDescription": "Włącza się w swojej grupie opcji",+ "behaviourRadioGroup": "Grupa opcji",+ "behaviourRadioGroupDescription": "Włącza jedną ze swoich opcji",+ "behaviourToggleGroup": "Grupa przełączników",+ "behaviourToggleGroupDescription": "Włącza najwyżej jeden ze swoich przełączników",+ "behaviourProgress": "Postęp",+ "behaviourProgressDescription": "Wypełnia ścieżkę do wartości",+ "behaviourCollapsible": "Zwijany panel",+ "behaviourCollapsibleDescription": "Pokazuje i ukrywa swoją zawartość",+ "behaviourAccordion": "Akordeon",+ "behaviourAccordionDescription": "Otwiera jednocześnie jeden ze swoich paneli",+ "behaviourOpen": "Otwarty",+ "behaviourItems": "Elementy",+ "behaviourChecked": "Zaznaczony",+ "behaviourPressed": "Wciśnięty",+ "behaviourAddTextLayer": "Dodaj warstwę tekstu",+ "behaviourAddVariants": "Dodaj warianty Off i On",+ "behaviourAddSlot": "Dodaj slot {name}",+ "behaviourMoreOptions": "Więcej opcji",+ "behaviourValue": "Wartość",+ "behaviourDisabled": "Wyłączony",+ "behaviourOnValue": "Wł.",+ "behaviourOffValue": "Wył.",+ "behaviourTrack": "Ścieżka",+ "behaviourThumb": "Uchwyt",+ "behaviourRange": "Zakres",+ "behaviourIndicator": "Wskaźnik",+ "behaviourList": "Lista",+ "behaviourTrigger": "Wyzwalacz",+ "behaviourContent": "Zawartość",+ "behaviourPanels": "Panele",+ "behaviourChooseProperty": "Wybierz właściwość",+ "behaviourChooseSlot": "Wybierz slot",+ "behaviourNoSlots": "Brak slotów; utwórz je poleceniem Utwórz slot",+ "behaviourComplete": "Gotowe",+ "behaviourMin": "Min",+ "behaviourMax": "Maks",+ "behaviourStep": "Krok",+ "behaviourStart": "Początek",+ "behaviourNextStep": "Jeszcze potrzebne: {names}.",+ "behaviourStatesHint": "Wygląd po najechaniu, wciśnięciu, fokusie i wyłączeniu rysuje się jako warianty.",+ "behaviourAddStates": "Dodaj warianty stanów",+ "behaviourButton": "Przycisk",+ "behaviourButtonDescription": "Pokazuje stany najechania, wciśnięcia, fokusu i wyłączenia",+ "behaviourStates": "Stany",+ "behaviourStateRest": "Domyślny",+ "behaviourStateHover": "Najechanie",+ "behaviourStatePressed": "Wciśnięty",+ "behaviourStateFocus": "Fokus",+ "behaviourStateDisabled": "Wyłączony",+ "behaviourStateUnset": "Brak",+ "behaviourStateField": "Stan {state}",+ "searchComponentProperties": "Szukaj właściwości",+ "noComponentProperties": "Nie znaleziono właściwości"}diff --git a/packages/vue/src/i18n/locales/ru/editor.json b/packages/vue/src/i18n/locales/ru/editor.jsonindex e6bcff77c..dac18e61c 100644--- a/packages/vue/src/i18n/locales/ru/editor.json+++ b/packages/vue/src/i18n/locales/ru/editor.json@@ -1,5 +1,9 @@{"toolOptions": "Параметры инструмента «{tool}»","removeGradientStop": "Удалить точку градиента",- "showUI": "Показать интерфейс ({shortcut})"+ "showUI": "Показать интерфейс ({shortcut})",+ "previewing": "Просмотр",+ "resetPreview": "Сбросить",+ "leavePreview": "Выйти из просмотра ({shortcut})",+ "startPreview": "Просмотр ({shortcut})"}diff --git a/packages/vue/src/i18n/locales/ru/menu.json b/packages/vue/src/i18n/locales/ru/menu.jsonindex 73c0c911d..c87ec307a 100644--- a/packages/vue/src/i18n/locales/ru/menu.json+++ b/packages/vue/src/i18n/locales/ru/menu.json@@ -72,5 +72,6 @@"exportSelectionAsPNG": "Экспортировать выделение как PNG","exportSelectionAsSVG": "Экспортировать выделение как SVG","exportSelectionAsPPTX": "Экспортировать выделение как PPTX",- "exportSelectionAsFig": "Экспортировать выделение как .fig"+ "exportSelectionAsFig": "Экспортировать выделение как .fig",+ "togglePreview": "Просмотр"}diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.jsonindex 8fce76ce1..9efb31161 100644--- a/packages/vue/src/i18n/locales/ru/panels.json+++ b/packages/vue/src/i18n/locales/ru/panels.json@@ -411,5 +411,85 @@"strokeDashLength": "Штрих","strokeDashGap": "Промежуток","lineHeightMode": "Режим межстрочного интервала",- "unresolvedVariable": "Значение переменной недоступно"+ "unresolvedVariable": "Значение переменной недоступно",+ "behaviour": "Поведение",+ "addBehaviour": "Добавить поведение",+ "removeBehaviour": "Удалить поведение",+ "searchBehaviours": "Поиск поведения",+ "noBehavioursFound": "Поведение не найдено",+ "behaviourSwitch": "Переключатель",+ "behaviourCheckbox": "Флажок",+ "behaviourSlider": "Ползунок",+ "behaviourTabs": "Вкладки",+ "behaviourSwitchDescription": "Переключается между вкл. и выкл.",+ "behaviourCheckboxDescription": "Ставит и снимает отметку",+ "behaviourSliderDescription": "Перемещает бегунок по дорожке",+ "behaviourTabsDescription": "Показывает одну панель за раз",+ "behaviourTextField": "Текстовое поле",+ "behaviourTextFieldDescription": "Принимает одну строку текста",+ "behaviourTextarea": "Многострочное поле",+ "behaviourTextareaDescription": "Принимает несколько строк текста",+ "behaviourNumberField": "Числовое поле",+ "behaviourNumberFieldDescription": "Увеличивает, уменьшает и принимает число",+ "behaviourFilled": "Заполнено",+ "behaviourText": "Текст",+ "behaviourIncrement": "Увеличить",+ "behaviourDecrement": "Уменьшить",+ "behaviourToggle": "Переключатель-кнопка",+ "behaviourToggleDescription": "Нажимается и отжимается",+ "behaviourRadio": "Радиокнопка",+ "behaviourRadioDescription": "Включается в своей группе радиокнопок",+ "behaviourRadioGroup": "Группа радиокнопок",+ "behaviourRadioGroupDescription": "Включает одну из своих радиокнопок",+ "behaviourToggleGroup": "Группа переключателей",+ "behaviourToggleGroupDescription": "Включает не более одного из своих переключателей",+ "behaviourProgress": "Прогресс",+ "behaviourProgressDescription": "Заполняет дорожку до значения",+ "behaviourCollapsible": "Раскрывающийся блок",+ "behaviourCollapsibleDescription": "Показывает и скрывает своё содержимое",+ "behaviourAccordion": "Аккордеон",+ "behaviourAccordionDescription": "Открывает только один из своих блоков",+ "behaviourOpen": "Открыт",+ "behaviourItems": "Элементы",+ "behaviourChecked": "Отмечен",+ "behaviourPressed": "Нажата",+ "behaviourAddTextLayer": "Добавить текстовый слой",+ "behaviourAddVariants": "Добавить варианты Off и On",+ "behaviourAddSlot": "Добавить слот «{name}»",+ "behaviourMoreOptions": "Ещё параметры",+ "behaviourValue": "Значение",+ "behaviourDisabled": "Отключено",+ "behaviourOnValue": "Вкл.",+ "behaviourOffValue": "Выкл.",+ "behaviourTrack": "Дорожка",+ "behaviourThumb": "Бегунок",+ "behaviourRange": "Диапазон",+ "behaviourIndicator": "Индикатор",+ "behaviourList": "Список",+ "behaviourTrigger": "Триггер",+ "behaviourContent": "Содержимое",+ "behaviourPanels": "Панели",+ "behaviourChooseProperty": "Выберите свойство",+ "behaviourChooseSlot": "Выберите слот",+ "behaviourNoSlots": "Слотов пока нет; создайте их командой «Создать слот»",+ "behaviourComplete": "Готово",+ "behaviourMin": "Мин",+ "behaviourMax": "Макс",+ "behaviourStep": "Шаг",+ "behaviourStart": "Старт",+ "behaviourNextStep": "Ещё нужно: {names}.",+ "behaviourStatesHint": "Виды при наведении, нажатии, фокусе и отключении рисуются как варианты.",+ "behaviourAddStates": "Добавить варианты состояний",+ "behaviourButton": "Кнопка",+ "behaviourButtonDescription": "Показывает состояния наведения, нажатия, фокуса и отключения",+ "behaviourStates": "Состояния",+ "behaviourStateRest": "По умолчанию",+ "behaviourStateHover": "Наведение",+ "behaviourStatePressed": "Нажата",+ "behaviourStateFocus": "Фокус",+ "behaviourStateDisabled": "Отключена",+ "behaviourStateUnset": "Нет",+ "behaviourStateField": "Состояние «{state}»",+ "searchComponentProperties": "Поиск свойств",+ "noComponentProperties": "Свойства не найдены"}diff --git a/packages/vue/src/i18n/locales/zh-cn/editor.json b/packages/vue/src/i18n/locales/zh-cn/editor.jsonindex a201fce1a..d7723436b 100644--- a/packages/vue/src/i18n/locales/zh-cn/editor.json+++ b/packages/vue/src/i18n/locales/zh-cn/editor.json@@ -1,5 +1,9 @@{"toolOptions": "{tool}选项","removeGradientStop": "删除渐变色标",- "showUI": "显示界面({shortcut})"+ "showUI": "显示界面({shortcut})",+ "previewing": "预览中",+ "resetPreview": "重置",+ "leavePreview": "退出预览 ({shortcut})",+ "startPreview": "预览 ({shortcut})"}diff --git a/packages/vue/src/i18n/locales/zh-cn/menu.json b/packages/vue/src/i18n/locales/zh-cn/menu.jsonindex 0363951b3..fc4e773ca 100644--- a/packages/vue/src/i18n/locales/zh-cn/menu.json+++ b/packages/vue/src/i18n/locales/zh-cn/menu.json@@ -72,5 +72,6 @@"exportSelectionAsPNG": "将所选内容导出为 PNG","exportSelectionAsSVG": "将所选内容导出为 SVG","exportSelectionAsPPTX": "将所选内容导出为 PPTX",- "exportSelectionAsFig": "将所选内容导出为 .fig"+ "exportSelectionAsFig": "将所选内容导出为 .fig",+ "togglePreview": "预览"}diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.jsonindex 9db49b84b..1be87fd49 100644--- a/packages/vue/src/i18n/locales/zh-cn/panels.json+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json@@ -399,5 +399,85 @@"strokeDashLength": "虚线","strokeDashGap": "间距","lineHeightMode": "行高模式",- "unresolvedVariable": "变量值不可用"+ "unresolvedVariable": "变量值不可用",+ "behaviour": "行为",+ "addBehaviour": "添加行为",+ "removeBehaviour": "移除行为",+ "searchBehaviours": "搜索行为",+ "noBehavioursFound": "未找到行为",+ "behaviourSwitch": "开关",+ "behaviourCheckbox": "复选框",+ "behaviourSlider": "滑块",+ "behaviourTabs": "标签页",+ "behaviourSwitchDescription": "在开和关之间切换",+ "behaviourCheckboxDescription": "勾选和取消勾选",+ "behaviourSliderDescription": "沿轨道拖动滑块",+ "behaviourTabsDescription": "一次显示一个面板",+ "behaviourTextField": "文本框",+ "behaviourTextFieldDescription": "接受单行输入",+ "behaviourTextarea": "多行文本框",+ "behaviourTextareaDescription": "接受多行输入",+ "behaviourNumberField": "数字框",+ "behaviourNumberFieldDescription": "递增、递减并输入数字",+ "behaviourFilled": "已填写",+ "behaviourText": "文本",+ "behaviourIncrement": "增加",+ "behaviourDecrement": "减少",+ "behaviourToggle": "切换按钮",+ "behaviourToggleDescription": "按下与弹起",+ "behaviourRadio": "单选项",+ "behaviourRadioDescription": "在其单选组中打开",+ "behaviourRadioGroup": "单选组",+ "behaviourRadioGroupDescription": "打开其中一个单选项",+ "behaviourToggleGroup": "切换组",+ "behaviourToggleGroupDescription": "最多打开其中一个切换按钮",+ "behaviourProgress": "进度",+ "behaviourProgressDescription": "将轨道填充到某个值",+ "behaviourCollapsible": "折叠面板",+ "behaviourCollapsibleDescription": "显示或隐藏其内容",+ "behaviourAccordion": "手风琴",+ "behaviourAccordionDescription": "一次只打开一个折叠面板",+ "behaviourOpen": "展开",+ "behaviourItems": "项目",+ "behaviourChecked": "已选中",+ "behaviourPressed": "已按下",+ "behaviourAddTextLayer": "添加文本图层",+ "behaviourAddVariants": "添加 Off 和 On 变体",+ "behaviourAddSlot": "添加 {name} 插槽",+ "behaviourMoreOptions": "更多选项",+ "behaviourValue": "值",+ "behaviourDisabled": "已禁用",+ "behaviourOnValue": "开",+ "behaviourOffValue": "关",+ "behaviourTrack": "轨道",+ "behaviourThumb": "滑块按钮",+ "behaviourRange": "范围",+ "behaviourIndicator": "指示器",+ "behaviourList": "列表",+ "behaviourTrigger": "触发器",+ "behaviourContent": "内容",+ "behaviourPanels": "面板",+ "behaviourChooseProperty": "选择属性",+ "behaviourChooseSlot": "选择插槽",+ "behaviourNoSlots": "暂无插槽;使用“创建插槽”创建一个",+ "behaviourComplete": "就绪",+ "behaviourMin": "最小",+ "behaviourMax": "最大",+ "behaviourStep": "步长",+ "behaviourStart": "起始值",+ "behaviourNextStep": "仍需设置:{names}。",+ "behaviourStatesHint": "悬停、按下、焦点和禁用的外观以变体绘制。",+ "behaviourAddStates": "添加状态变体",+ "behaviourButton": "按钮",+ "behaviourButtonDescription": "显示悬停、按下、聚焦和禁用状态",+ "behaviourStates": "状态",+ "behaviourStateRest": "默认",+ "behaviourStateHover": "悬停",+ "behaviourStatePressed": "按下",+ "behaviourStateFocus": "聚焦",+ "behaviourStateDisabled": "禁用",+ "behaviourStateUnset": "无",+ "behaviourStateField": "{state}状态",+ "searchComponentProperties": "搜索属性",+ "noComponentProperties": "未找到属性"}diff --git a/packages/vue/src/i18n/messages/editor.ts b/packages/vue/src/i18n/messages/editor.tsindex 41f46665c..43c8052dd 100644--- a/packages/vue/src/i18n/messages/editor.ts+++ b/packages/vue/src/i18n/messages/editor.ts@@ -5,7 +5,11 @@ import { i18n } from '#vue/i18n/create'export const editorMessageDefaults = {toolOptions: params('{tool} options'),removeGradientStop: 'Remove gradient stop',- showUI: params('Show UI ({shortcut})')+ showUI: params('Show UI ({shortcut})'),+ previewing: 'Previewing',+ startPreview: params('Preview ({shortcut})'),+ resetPreview: 'Reset',+ leavePreview: params('Leave preview ({shortcut})')} as constexport const editorMessages = i18n('editor', editorMessageDefaults)diff --git a/packages/vue/src/i18n/messages/menu.ts b/packages/vue/src/i18n/messages/menu.tsindex 793a75762..6acc391b4 100644--- a/packages/vue/src/i18n/messages/menu.ts+++ b/packages/vue/src/i18n/messages/menu.ts@@ -51,6 +51,7 @@ export const menuMessageDefaults = {front: 'Front',back: 'Back',toggleUI: 'Toggle UI',+ togglePreview: 'Preview',bold: 'Bold',italic: 'Italic',diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.tsindex 5b7281b31..7ea983e4f 100644--- a/packages/vue/src/i18n/messages/panels.ts+++ b/packages/vue/src/i18n/messages/panels.ts@@ -181,6 +181,86 @@ export const panelMessageDefaults = {resetSlot: 'Reset slot',deleteSlotContents: 'Delete contents',slotActions: params('{name} actions'),+ behaviour: 'Behaviour',+ addBehaviour: 'Add behaviour',+ removeBehaviour: 'Remove behaviour',+ searchBehaviours: 'Search behaviours',+ noBehavioursFound: 'No behaviours found',+ behaviourSwitch: 'Switch',+ behaviourCheckbox: 'Checkbox',+ behaviourSlider: 'Slider',+ behaviourTabs: 'Tabs',+ behaviourSwitchDescription: 'Toggles between on and off',+ behaviourCheckboxDescription: 'Checks and unchecks',+ behaviourSliderDescription: 'Drags a thumb along a track',+ behaviourTabsDescription: 'Shows one panel at a time',+ behaviourTextField: 'Text field',+ behaviourTextFieldDescription: 'Takes one line of typing',+ behaviourTextarea: 'Textarea',+ behaviourTextareaDescription: 'Takes several lines of typing',+ behaviourNumberField: 'Number field',+ behaviourNumberFieldDescription: 'Steps and types a number',+ behaviourFilled: 'Filled',+ behaviourText: 'Text',+ behaviourIncrement: 'Increment',+ behaviourDecrement: 'Decrement',+ behaviourToggle: 'Toggle',+ behaviourToggleDescription: 'Presses in and out',+ behaviourRadio: 'Radio',+ behaviourRadioDescription: 'Turns on within its radio group',+ behaviourRadioGroup: 'Radio group',+ behaviourRadioGroupDescription: 'Turns on one of its radios',+ behaviourToggleGroup: 'Toggle group',+ behaviourToggleGroupDescription: 'Turns on at most one of its toggles',+ behaviourProgress: 'Progress',+ behaviourProgressDescription: 'Fills a track up to a value',+ behaviourCollapsible: 'Collapsible',+ behaviourCollapsibleDescription: 'Shows and hides its content',+ behaviourAccordion: 'Accordion',+ behaviourAccordionDescription: 'Opens one of its collapsibles at a time',+ behaviourOpen: 'Open',+ behaviourItems: 'Items',+ behaviourChecked: 'Checked',+ behaviourPressed: 'Pressed',+ behaviourAddTextLayer: 'Add text layer',+ behaviourAddVariants: 'Add Off and On variants',+ behaviourAddSlot: params('Add {name} slot'),+ behaviourMoreOptions: 'More options',+ behaviourValue: 'Value',+ behaviourDisabled: 'Disabled',+ behaviourOnValue: 'On',+ behaviourOffValue: 'Off',+ behaviourTrack: 'Track',+ behaviourThumb: 'Thumb',+ behaviourRange: 'Range',+ behaviourIndicator: 'Indicator',+ behaviourList: 'List',+ behaviourTrigger: 'Trigger',+ behaviourContent: 'Content',+ behaviourPanels: 'Panels',+ behaviourChooseProperty: 'Choose property',+ behaviourChooseSlot: 'Choose slot',+ behaviourNoSlots: 'No slots yet; make one with Create slot',+ behaviourComplete: 'Ready',+ behaviourMin: 'Min',+ behaviourMax: 'Max',+ behaviourStep: 'Step',+ behaviourStart: 'Start',+ behaviourNextStep: params('Still needed: {names}.'),+ behaviourStatesHint: 'Hover, pressed, focus, and disabled looks are drawn as variants.',+ behaviourAddStates: 'Add state variants',+ behaviourButton: 'Button',+ behaviourButtonDescription: 'Shows hover, pressed, focus, and disabled states',+ behaviourStates: 'States',+ behaviourStateRest: 'Default',+ behaviourStateHover: 'Hover',+ behaviourStatePressed: 'Pressed',+ behaviourStateFocus: 'Focus',+ behaviourStateDisabled: 'Disabled',+ behaviourStateUnset: 'None',+ behaviourStateField: params('{state} state'),+ searchComponentProperties: 'Search properties',+ noComponentProperties: 'No properties found',slots: 'Slots',createSlot: 'Create slot',removeSlot: 'Remove slot',diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.tsindex 6f350eca2..66743efb9 100644--- a/packages/vue/src/index.ts+++ b/packages/vue/src/index.ts@@ -160,7 +160,7 @@ export { useGradientStops } from '#vue/primitives/GradientEditor/useGradientStopexport { useFontPicker } from '#vue/primitives/FontPicker/useFontPicker'/** Headless structural primitives and their local contexts. */-export { CanvasRoot, CanvasSurface, useCanvasContext } from '#vue/canvas'+export { CanvasRoot, CanvasSurface, PlayIslands, useCanvasContext } from '#vue/canvas'export type { CanvasContext } from '#vue/canvas'export { ColorInputRoot, ColorPickerRoot } from '#vue/primitives/ColorPicker'export {@@ -243,22 +243,36 @@ export {compatibleComponentPropertyDefinitions,instanceSwapOptions,mergedComponentPropertyValue,+ useComponentProperties+} from '#vue/controls/component-props'+export {slotInstanceOptions,slotLimits,- useComponentProperties,useSlotAuthoring,- useSlotProperties,- useVariantAuthoring-} from '#vue/controls/component-props'+ useSlotProperties+} from '#vue/controls/slots'+export { useVariantAuthoring } from '#vue/controls/variants'+export { useBehaviour } from '#vue/controls/behaviour'+export type {+ BehaviourBooleanControl,+ BehaviourControl,+ BehaviourNumberControl,+ BehaviourPartControl,+ BehaviourStatesControl,+ BehaviourTextControl,+ BehaviourValueControl+} from '#vue/controls/behaviour'export type {ComponentPropertyControl,- ComponentPropertyOption,+ ComponentPropertyOption+} from '#vue/controls/component-props'+export type {SlotDefinitionControl,SlotInstanceOption,SlotLimit,- SlotPropertyControl,- VariantDefinitionControl-} from '#vue/controls/component-props'+ SlotPropertyControl+} from '#vue/controls/slots'+export type { VariantDefinitionControl } from '#vue/controls/variants'export type { CornerGeometryKey, CornerRadiusKey } from '#vue/controls/appearance/types'export { isPageDivider, PageListRoot, PAGE_DIVIDER_PATTERN } from '#vue/primitives/PageList'export { PositionControlsRoot } from '#vue/primitives/PositionControls'diff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.mdindex 5df7bbe4d..d90ebf174 100644--- a/skills/open-pencil/SKILL.md+++ b/skills/open-pencil/SKILL.md@@ -162,6 +162,22 @@ openpencil eval design.fig -o modified.fig -c '...'echo 'figma.currentPage.children.map(n => n.name)' | openpencil eval design.fig --stdin```+Next to `figma`, scripts get `openpencil`: what OpenPencil adds to the Figma API, in its style. A main component can behave as a Reka UI control, by its own property and slot names:++```bash+openpencil eval design.fig -w -c '+ const set = figma.currentPage.findOne(n => n.type === "COMPONENT_SET" && n.name === "Switch");+ const thumb = set.findOne(n => n.name === "Thumb");+ const behaviour = openpencil.setBehaviour(set, "switch")+ .bindValue("value", "State") // On/Off guessed from the variant values+ .bindPart("thumb", thumb); // the frame becomes a slot+ behaviour.states = "Interaction";+ behaviour.missing // [] when the control is complete+'+```++`openpencil.behaviourKinds` lists every kind with its values and parts; `openpencil.getBehaviour(node)` reads one (a variant reads its set's); `openpencil.createSlot(frame)` makes a frame a slot. The `set_behaviour`, `get_behaviour`, and `create_slot` tools do the same over MCP, and design JSX writes controls with Reka's element names (`Switch.Root`, `Switch.Thumb`).+### DiffCompare nodes and documents, and apply patches:diff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.mdindex 6457a2b08..06f681a05 100644--- a/skills/open-pencil/references/design-authoring.md+++ b/skills/open-pencil/references/design-authoring.md@@ -41,6 +41,24 @@ This reference describes scene creation, not React DOM output. Use the `render`- Reuse existing local or library components before recreating them. Keep meaningful text, visibility, and swap properties exposed rather than hand-editing cloned child nodes.- Explicit instance `w` / `h` replace the inherited sizing mode on that axis; omitted dimensions retain the main component's sizing. Authored overrides survive component synchronization. Distinguish those placement constraints from the main component's default size, and verify actual bounds in narrower parents. Do not compensate for a sizing mismatch with guessed heights, clipping, or manually positioned siblings.+## Controls++- A main component can behave as a Reka UI control in preview and code. Write it with Reka's names: `Switch.Root` is the component (a component set when its children are `Component` variants), and each Reka part is the slot that draws it, such as `Switch.Thumb`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Tabs.List`, `Collapsible.Trigger`, or `NumberField.Increment`. Parts in different variants share one slot.+- The root names the properties that hold its values: `modelValue` (`open` on `Collapsible.Root`), `disabled`, and, for text fields, `filled`, as a variant or boolean property name, or `{ property, on, off }` when the variant values are not named like On and Off. `states` names the variant property that draws default, hover, pressed, focus, and disabled; a slider, progress bar, or number field takes `min`, `max`, `step`, and `defaultValue`.+- `TextField.Input`, `Textarea.Input`, and `NumberField.Input` are the text layers whose text becomes the field's text property. `Tabs.Trigger` goes in `Tabs.List`; `Tabs.Content` panels may sit directly under `Tabs.Root`, the first showing.+- A group's item component is written on its own (`RadioGroup.Item`, `ToggleGroup.Item`, `Accordion.Item` with its `Accordion.Trigger` and `Accordion.Content`); the group's root then lists items as `<RadioGroup.Item of={radioId} />`.++```tsx+<Switch.Root name="Switch" modelValue="State" states="Interaction">+ <Component name="State=Off, Interaction=Default" w={44} h={24} rounded={12} bg="#D0D4DA">+ <Switch.Thumb x={2} y={2} w={20} h={20} rounded={10} bg="#FFFFFF" />+ </Component>+ <Component name="State=On, Interaction=Default" w={44} h={24} rounded={12} bg="#3B6CF6">+ <Switch.Thumb x={22} y={2} w={20} h={20} rounded={10} bg="#FFFFFF" />+ </Component>+</Switch.Root>+```+## VerificationInspect structure and actual rendered output. Node counts and `describe` diagnostics do not establish visual fidelity. Check wrapping with longer content, narrower containers, component edits, and relevant modes. Resolve overflow and contrast problems at their source. Reuse IDs returned by creation tools rather than repeatedly searching for the same nodes.@@ -68,8 +86,8 @@ The examples below are executed by the authoring-reference tests. Create the namGenerated from the renderer metadata. This inventory lists accepted names, not arbitrary browser CSS support.-**Elements:** `Frame`, `Text`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`.+**Elements:** `Frame`, `Text`, `Rectangle`, `Ellipse`, `Line`, `Star`, `Polygon`, `Vector`, `Group`, `Section`, `Component`, `ComponentSet`, `Instance`, `View`, `Rect`, `Icon`, `Button.Root`, `Toggle.Root`, `Switch.Root`, `Switch.Thumb`, `Checkbox.Root`, `Checkbox.Indicator`, `RadioGroup.Root`, `RadioGroup.Item`, `RadioGroup.Indicator`, `ToggleGroup.Root`, `ToggleGroup.Item`, `Slider.Root`, `Slider.Track`, `Slider.Range`, `Slider.Thumb`, `Progress.Root`, `Progress.Indicator`, `Tabs.Root`, `Tabs.List`, `Tabs.Trigger`, `Tabs.Content`, `Collapsible.Root`, `Collapsible.Trigger`, `Collapsible.Content`, `Accordion.Root`, `Accordion.Item`, `Accordion.Header`, `Accordion.Trigger`, `Accordion.Content`, `NumberField.Root`, `NumberField.Input`, `NumberField.Increment`, `NumberField.Decrement`, `TextField.Root`, `TextField.Input`, `Textarea.Root`, `Textarea.Input`.**Helpers:** `solid`, `gradient`, `linearGradient`, `radialGradient`, `angularGradient`, `diamondGradient`, `dropShadow`, `innerShadow`, `layerBlur`, `backgroundBlur`, `foregroundBlur`, `designVar`, `defineVars`.-**Properties:** `name`, `key`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textCase`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `propertyRefs`, `of`.\ No newline at end of file+**Properties:** `name`, `key`, `flex`, `flow`, `dir`, `gap`, `wrap`, `rowGap`, `columnGap`, `justify`, `justifyContent`, `items`, `align`, `alignItems`, `grow`, `w`, `h`, `width`, `height`, `minW`, `maxW`, `minH`, `maxH`, `x`, `y`, `top`, `left`, `position`, `constraints`, `p`, `padding`, `px`, `py`, `pt`, `pr`, `pb`, `pl`, `bg`, `fill`, `fills`, `background`, `backgroundColor`, `stroke`, `border`, `borderColor`, `strokeWidth`, `borderWidth`, `strokeAlign`, `strokeDash`, `strokeCap`, `strokeJoin`, `dashPattern`, `strokes`, `strokeWeights`, `rounded`, `borderRadius`, `roundedTL`, `roundedTR`, `roundedBL`, `roundedBR`, `cornerRadius`, `cornerSmoothing`, `opacity`, `blendMode`, `rotate`, `rotation`, `overflow`, `mask`, `visible`, `locked`, `shadow`, `blur`, `effects`, `size`, `fontSize`, `font`, `fontFamily`, `weight`, `fontWeight`, `italic`, `color`, `text`, `characters`, `content`, `value`, `title`, `textAlign`, `textAlignHorizontal`, `textHorizontalAlignment`, `textAlignVertical`, `textVerticalAlignment`, `textAutoResize`, `lineHeight`, `letterSpacing`, `textDecoration`, `textCase`, `maxLines`, `truncate`, `grid`, `columns`, `rows`, `colStart`, `rowStart`, `col`, `row`, `colSpan`, `rowSpan`, `points`, `pointCount`, `innerRadius`, `label`, `style`, `bind`, `component`, `componentId`, `properties`, `propertyRefs`, `of`, `modelValue`, `open`, `disabled`, `filled`, `states`, `min`, `max`, `step`, `defaultValue`.\ No newline at end of filediff --git a/src/app/ai/chat/system-prompt.md b/src/app/ai/chat/system-prompt.mdindex eae529198..e2b3eb042 100644--- a/src/app/ai/chat/system-prompt.md+++ b/src/app/ai/chat/system-prompt.md@@ -8,6 +8,7 @@ You are a design assistant inside OpenPencil. Create and modify designs using th- Use the tool schemas actually available in this session. The shared authoring reference below describes the renderer; it does not promise that every library export is a scripting global.- Use `render` for design JSX. For replacement workflows, use `replace_id` rather than deleting the original before new content is ready. Keep references to the newly returned IDs.- Use `describe` on a relevant subtree to diagnose layout; batch related fixes where appropriate. Reinspect after meaningful changes, not repeatedly without changes. Diagnose a failed edit before replacing content; do not blindly delete nodes after a fixed retry count.+- For an interactive control (switch, checkbox, slider, tabs, text field, accordion, …), build a main component whose variants draw its states and give it a behaviour: Reka UI elements in `render` (`<Switch.Root modelValue="State">` with `<Switch.Thumb>`), or `set_behaviour` on an existing component. `get_behaviour` without an ID lists every kind with its values and parts; its `missing` list must be empty before the control works in preview.- Ordinary JavaScript through `eval` is appropriate for supported scripting operations. Respect that environment's exposed API. Prefer auto-layout to arithmetic for content sizing; use `calc` only when it is useful.- Check actual rendered output when completing or reviewing visual work. Export the affected nodes rather than a huge page, inspect the image, and summarize what you observed. Structural diagnostics alone are not visual acceptance.- Edit existing designs in place with targeted property and structure tools; re-render a whole tree only when its structure must change.diff --git a/src/app/ai/chat/system-prompt.ts b/src/app/ai/chat/system-prompt.tsindex 1a2b9ac42..4bcfcd4a5 100644--- a/src/app/ai/chat/system-prompt.ts+++ b/src/app/ai/chat/system-prompt.ts@@ -1,14 +1,11 @@-import dedent from 'dedent'-import { JSX_REFERENCE } from '@open-pencil/design-jsx'import behavior from './system-prompt.md?raw'-/** Chat and ACP share scene-authoring knowledge without copying the renderer reference. */-const SYSTEM_PROMPT = dedent`-${behavior.trim()}--${JSX_REFERENCE}-`+/**+ * Chat and ACP share scene-authoring knowledge without copying the renderer reference. The+ * reference is joined verbatim: dedenting it would flatten its indented code examples.+ */+const SYSTEM_PROMPT = [behavior.trim(), JSX_REFERENCE].join('\n\n')export default SYSTEM_PROMPTdiff --git a/src/app/automation/bridge/eval-handler.ts b/src/app/automation/bridge/eval-handler.tsindex 69e173289..3d5325812 100644--- a/src/app/automation/bridge/eval-handler.ts+++ b/src/app/automation/bridge/eval-handler.ts@@ -1,5 +1,5 @@import type { FigmaAPI } from '@open-pencil/core/figma-api'-import { wrapEvalCode } from '@open-pencil/core/tools'+import { compileScript } from '@open-pencil/core/tools'import type { AutomationTarget } from '@/app/automation/bridge/target'import { automationUndoLabel, executeWithPageUndo } from '@/app/automation/execution/editor'@@ -12,17 +12,14 @@ export function createAutomationEvalHandler(makeFigma: FigmaFactory) {const code = (args as { code?: string }).codeif (!code) throw new Error('Missing "code" in args')const figma = makeFigma(target.store, target.pageId)- const AsyncFunction = Object.getPrototypeOf(async function () {- /* noop */- }).constructor- const fn = new AsyncFunction('figma', wrapEvalCode(code))+ const run = compileScript(code)const result = await executeWithPageUndo(target.store,target.pageId,automationUndoLabel('eval'),() =>target.store.runMutationWithLayout(- () => fn(figma),+ () => run(figma),target.pageId,async () => {const page = target.store.graph.getNode(target.pageId)diff --git a/src/app/editor/panes/state.ts b/src/app/editor/panes/state.tsindex ff5c38d11..3ddcfe9b5 100644--- a/src/app/editor/panes/state.ts+++ b/src/app/editor/panes/state.ts@@ -44,6 +44,8 @@ export function cloneCanvasPaneState(id: string, source: CanvasPaneState): CanvanodeEditState: null,cursorCanvasX: null,cursorCanvasY: null,+ // A new canvas edits; preview belongs to the canvas that started it.+ play: null,viewportWidth: source.viewportWidth,viewportHeight: source.viewportHeight})diff --git a/src/app/shell/keyboard/actions.ts b/src/app/shell/keyboard/actions.tsindex b9fabd854..b91433128 100644--- a/src/app/shell/keyboard/actions.ts+++ b/src/app/shell/keyboard/actions.ts@@ -58,6 +58,10 @@ export function createKeyboardActions({}function escapeOrDeselect() {+ if (store.state.play) {+ store.stopPlay()+ return+ }if (store.state.rotationPreview) {store.setRotationPreview(null)return@@ -91,6 +95,10 @@ export function createKeyboardActions({store.state.showUI = !store.state.showUI}+ function togglePlay() {+ store.togglePlay()+ }+function toggleAI() {if (isMobile.value) {store.state.activeRibbonTab = store.state.activeRibbonTab === 'ai' ? 'panels' : 'ai'@@ -140,6 +148,7 @@ export function createKeyboardActions({escapeOrDeselect,toggleAutoLayout,toggleUI,+ togglePlay,toggleAI,exportSelectionPNG,opacityDigitdiff --git a/src/app/shell/keyboard/registry.ts b/src/app/shell/keyboard/registry.tsindex 8feecb6b9..12b2f600e 100644--- a/src/app/shell/keyboard/registry.ts+++ b/src/app/shell/keyboard/registry.ts@@ -24,6 +24,8 @@ type ShortcutDefinition = {run: ShortcutActionshouldPreventDefault?: (event: KeyboardEvent) => booleanglobal?: boolean+ /** Whether the shortcut also works while a canvas previews. */+ preview?: boolean}function commandShortcut(@@ -135,6 +137,12 @@ export function registerKeyboardShortcuts(options: KeyboardShortcutOptions) {run: ({ store }) => void store.saveFigFileAs()},...commandShortcuts('selection.ungroup', 'edit.redo'),+ {+ id: 'toggle-preview',+ keys: appMenuTinykeysShortcut('toggle-preview') ?? '$mod+Alt+Enter',+ run: ({ actions }) => actions.togglePlay(),+ preview: true+ },{id: 'toggle-ui',keys: appMenuTinykeysShortcut('toggle-ui') ?? '$mod+Backslash',@@ -215,12 +223,21 @@ export function registerKeyboardShortcuts(options: KeyboardShortcutOptions) {{ id: 'delete', keys: 'Delete', run: ({ actions }) => actions.smartDelete(false) },{ id: 'delete-alt', keys: 'Alt+Delete', run: ({ actions }) => actions.smartDelete(true) },{ id: 'enter', keys: 'Enter', run: ({ actions }) => actions.confirmOrEnterText() },- { id: 'escape', keys: 'Escape', run: ({ actions }) => actions.escapeOrDeselect() },+ {+ id: 'escape',+ keys: 'Escape',+ run: ({ actions }) => actions.escapeOrDeselect(),+ preview: true+ },...opacityBindings()]const bindings: KeyBindingMap = {}const globalBindings: KeyBindingMap = {}+ /** Keys that keep working while a canvas previews; everything else would edit the design. */+ const previewKeys = new Set(+ shortcuts.filter((shortcut) => shortcut.preview).flatMap((shortcut) => [shortcut.keys].flat())+ )bindToolShortcuts(bindings, runOptions(new KeyboardEvent('keydown')))for (const shortcut of shortcuts) {@@ -237,6 +254,7 @@ export function registerKeyboardShortcuts(options: KeyboardShortcutOptions) {keys,(event: KeyboardEvent) => {if (shouldIgnoreShortcut(event, options)) return+ if (options.store.state.play && !previewKeys.has(keys)) returnhandler(event)}])diff --git a/src/app/shell/keyboard/types.ts b/src/app/shell/keyboard/types.tsindex 04e9fda2f..2b6f810fb 100644--- a/src/app/shell/keyboard/types.ts+++ b/src/app/shell/keyboard/types.ts@@ -10,6 +10,7 @@ export type KeyboardShortcutActions = {escapeOrDeselect: () => voidtoggleAutoLayout: () => voidtoggleUI: () => void+ togglePlay: () => voidtoggleAI: () => voidexportSelectionPNG: () => voidopacityDigit: (digit: string) => voiddiff --git a/src/app/shell/menu/app-menu.ts b/src/app/shell/menu/app-menu.tsindex 341049c8a..678edd2cd 100644--- a/src/app/shell/menu/app-menu.ts+++ b/src/app/shell/menu/app-menu.ts@@ -121,6 +121,7 @@ export function useAppMenu() {'snap-pixel-grid': 'snapToPixelGrid',profiler: 'profiler','toggle-ui': 'toggleUI',+ 'toggle-preview': 'togglePreview',theme: 'theme','theme-light': 'themeLight','theme-dark': 'themeDark',diff --git a/src/app/shell/menu/editor-actions.ts b/src/app/shell/menu/editor-actions.tsindex 076194288..a8ac4b978 100644--- a/src/app/shell/menu/editor-actions.ts+++ b/src/app/shell/menu/editor-actions.ts@@ -75,6 +75,7 @@ export function createSharedEditorMenuActions('toggle-ui': () => {store.state.showUI = !store.state.showUI},+ 'toggle-preview': () => store.togglePlay(),'theme-light': () => setTheme('light'),'theme-dark': () => setTheme('dark'),'theme-auto': () => setTheme('auto'),diff --git a/src/app/shell/menu/schema.ts b/src/app/shell/menu/schema.tsindex 91c0b5e41..cf55ae690 100644--- a/src/app/shell/menu/schema.ts+++ b/src/app/shell/menu/schema.ts@@ -233,6 +233,7 @@ export const APP_MENU_SCHEMA = [},{ type: 'separator' },{ id: 'toggle-ui', label: 'Toggle UI', shortcut: 'MOD+\\' },+ { id: 'toggle-preview', label: 'Preview', shortcut: 'MOD+ALT+↩' },{ type: 'separator' },{ id: 'profiler', label: 'Profiler', checkbox: true, target: 'browser' },{diff --git a/src/app/shell/menu/shortcut.ts b/src/app/shell/menu/shortcut.tsindex c0097085c..a1c37c4d0 100644--- a/src/app/shell/menu/shortcut.ts+++ b/src/app/shell/menu/shortcut.ts@@ -30,7 +30,7 @@ export function appMenuShortcut(id: string): string | undefined {}function normalizeShortcutToken(shortcut: string): string {- return shortcut === '⌫' ? 'Backspace' : shortcut+ return shortcut === '⌫' ? 'Backspace' : shortcut.replaceAll('↩', 'Enter')}export function shortcutTokenToTinykeys(shortcut: string | undefined): string | undefined {diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vueindex 7ff7c8579..3f95f42a8 100644--- a/src/components/DesignPanel.vue+++ b/src/components/DesignPanel.vue@@ -11,10 +11,11 @@ import Tip from '@/components/ui/overlay/Tip.vue'import PanelHeader from '@/components/ui/panel/PanelHeader.vue'import AppearanceSection from './properties/AppearanceSection.vue'+import BehaviourPanel from './properties/component-properties/behaviour/BehaviourPanel.vue'import ComponentPropertiesSection from './properties/component-properties/ComponentPropertiesSection.vue'import InstanceUpdateAction from './properties/component-properties/instance-update/InstanceUpdateAction.vue'import SlotAuthoringSection from './properties/component-properties/slot/SlotAuthoringSection.vue'-import VariantAuthoringSection from './properties/component-properties/VariantAuthoringSection.vue'+import VariantAuthoringSection from './properties/component-properties/variant/VariantAuthoringSection.vue'import ConstraintsSection from './properties/constraints/ConstraintsSection.vue'import EffectsSection from './properties/EffectsSection.vue'import ExportSection from './properties/ExportSection.vue'@@ -161,6 +162,7 @@ const { panels } = useI18n()/><SlotAuthoringSection />+ <BehaviourPanel v-if="node.type === 'COMPONENT' || node.type === 'COMPONENT_SET'" /><FramePresetSelect v-if="node.type === 'FRAME'" />diff --git a/src/components/EditorCanvas.vue b/src/components/EditorCanvas.vueindex 365bf44e1..6db8f8383 100644--- a/src/components/EditorCanvas.vue+++ b/src/components/EditorCanvas.vue@@ -18,6 +18,7 @@ import {AUTO_LAYOUT_PADDING_EDITOR_OFFSET_Y} from '@open-pencil/core/constants'import {+ PlayIslands,toolCursor,useCanvas,useCanvasDrop,@@ -65,6 +66,8 @@ function updatePaneCursor(cx: number, cy: number) {}const getRenderState = paneId ? () => store.getPaneRenderState(paneId) : undefined+/** This pane's view: its pan, zoom, page, and whether it previews. */+const paneView = computed(() => (paneId ? store.getPaneRenderState(paneId) : store.state))const onViewportResize = (width: number, height: number) => {if (paneId) store.resizePane(paneId, width, height)if (isActivePane.value) store.setViewportSize(width, height)@@ -96,7 +99,7 @@ const { hitTestSectionTitle, hitTestComponentLabel, hitTestFrameTitle, hitTestIsuseCanvas(canvasRef, store, {layer: 'overlays',get showRulers() {- return appRuntimeConfig.showRulers && store.state.showRulers+ return appRuntimeConfig.showRulers && store.state.showRulers && paneView.value.play === null},getOverlayObstacles: () => canvasOverlayObstacles(canvasRef.value),shouldSuspendRender,@@ -226,6 +229,7 @@ const cursor = computed(() =>:style="{ cursor }"class="absolute inset-0 block size-full touch-none outline-none"/>+ <PlayIslands :view="paneView" :canvas="canvasRef" /><Transitionenter-active-class="transition-opacity duration-150"enter-from-class="opacity-0"diff --git a/src/components/editor/EditorWorkspace.vue b/src/components/editor/EditorWorkspace.vueindex 97646edbd..899134f7a 100644--- a/src/components/editor/EditorWorkspace.vue+++ b/src/components/editor/EditorWorkspace.vue@@ -1,6 +1,7 @@<script setup lang="ts">import { SplitterGroup, SplitterPanel, SplitterResizeHandle } from 'reka-ui'import { tv } from 'tailwind-variants'+import { computed } from 'vue'import { formatShortcut, provideEditor, useI18n, useViewportKind } from '@open-pencil/vue'@@ -8,9 +9,7 @@ import { useEditorStore } from '@/app/editor/active-store'import { appRuntimeConfig } from '@/app/runtime/config'import { loadEditorLayout, saveEditorLayout } from '@/app/shell/layout-storage'import { appMenuShortcut } from '@/app/shell/menu/shortcut'-import { resolvedAppTheme } from '@/app/shell/theme'import { activeTab } from '@/app/tabs'-import BrandMark from '@/components/brand/BrandMark.vue'import CanvasSplitRoot from '@/components/canvas/CanvasSplitRoot.vue'import CollabPanel from '@/components/collab-panel/CollabPanel.vue'import ActiveRoomOverlay from '@/components/collab-room/ActiveRoomOverlay.vue'@@ -25,6 +24,8 @@ import IconButton from '@/components/ui/button/IconButton.vue'import VariablesDialog from '@/components/variables/VariablesDialog.vue'import splitterTheme from '@/theme/splitter'+import WorkspacePill from './WorkspacePill.vue'+const showChrome = appRuntimeConfig.showChromeconst store = useEditorStore()// WorkspaceView keys this view by tab, so the tab's own store is fixed for its lifetime. Its@@ -32,10 +33,12 @@ const store = useEditorStore()// active tab and would move these subscriptions to the next document when this tab closes.const tab = activeTab.valueif (tab) provideEditor(tab.store)-const { editor } = useI18n()const { isMobile } = useViewportKind()const initialEditorLayout = loadEditorLayout()const horizontalSplitterStyles = tv(splitterTheme)({ direction: 'horizontal' })+/** One canvas previewing takes the whole window, in the canvas-only layout; split view keeps panels. */+const playingAlone = computed(() => store.state.play !== null && store.visiblePaneCount.value <= 1)+const { editor } = useI18n()// Until a room's document arrives there is nothing to edit, so its screen replaces the editor.const { pending: roomPending } = useRoomActions()</script>@@ -50,7 +53,7 @@ const { pending: roomPending } = useRoomActions()</div><SplitterGroup- v-else-if="!isMobile && showChrome && store.state.showUI"+ v-else-if="!isMobile && showChrome && store.state.showUI && !playingAlone":key="activeTab?.id"direction="horizontal"class="flex-1 overflow-hidden"@@ -88,8 +91,19 @@ const { pending: roomPending } = useRoomActions():max-size="30"class="flex flex-col">- <div class="flex shrink-0 items-center justify-between border-b border-border px-1.5 py-1.5">- <CollabPanel />+ <div class="flex shrink-0 items-center gap-1 border-b border-border px-1.5 py-1.5">+ <CollabPanel class="min-w-0 flex-1" />+ <IconButton+ :label="+ editor.startPreview({+ shortcut: formatShortcut(appMenuShortcut('toggle-preview')) ?? ''+ })+ "+ data-test-id="editor-start-preview"+ @click="store.startPlay()"+ >+ <icon-lucide-play class="size-3.5" />+ </IconButton></div><PropertiesPanel /></SplitterPanel>@@ -117,23 +131,21 @@ const { pending: roomPending } = useRoomActions()<div class="relative flex min-w-0 flex-1"><EditorCanvas /><ActiveRoomOverlay />- <div- v-if="!isMobile"- class="absolute top-7 left-7 z-10 flex items-center gap-2 rounded-lg border border-border bg-panel px-2 py-1 shadow-sm"- >- <BrandMark variant="app-icon" :appearance="resolvedAppTheme" class="size-6" />- <span data-test-id="editor-document-name" class="text-xs text-surface">{{- store.state.documentName- }}</span>- <IconButton- :label="editor.showUI({ shortcut: formatShortcut(appMenuShortcut('toggle-ui')) ?? '' })"- data-test-id="editor-show-ui"- class="ml-1"- @click="store.state.showUI = true"- >- <icon-lucide-sidebar class="size-3.5" />- </IconButton>- </div>+ <WorkspacePill+ v-if="!isMobile && playingAlone"+ mode="preview"+ :document-name="store.state.documentName"+ :shortcut="formatShortcut(appMenuShortcut('toggle-preview')) ?? ''"+ @reset="store.resetPlay()"+ @leave="store.stopPlay()"+ />+ <WorkspacePill+ v-else-if="!isMobile"+ mode="collapsed"+ :document-name="store.state.documentName"+ :shortcut="formatShortcut(appMenuShortcut('toggle-ui')) ?? ''"+ @show-ui="store.state.showUI = true"+ /></div></div>diff --git a/src/components/editor/WorkspacePill.stories.ts b/src/components/editor/WorkspacePill.stories.tsnew file mode 100644index 000000000..c50295902--- /dev/null+++ b/src/components/editor/WorkspacePill.stories.ts@@ -0,0 +1,31 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, userEvent, waitFor, within } from 'storybook/test'++import Pill from './examples/Pill.vue'++const meta = {+ title: 'Editor/Workspace Pill',+ component: Pill,+ parameters: {+ docs: {+ description: {+ component:+ 'The pill of the canvas-only layout. Hiding the UI shows the way back to the panels; preview says so, resets the controls, and leaves preview.'+ }+ }+ }+} satisfies Meta<typeof Pill>++export default meta+type Story = StoryObj<typeof meta>++export const States: Story = {}++export const ResetAndLeave: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await userEvent.click(canvas.getByRole('button', { name: 'Reset' }))+ await userEvent.click(canvas.getByRole('button', { name: /Leave preview/ }))+ await waitFor(() => expect(canvas.getByText('leave')).toBeVisible())+ }+}diff --git a/src/components/editor/WorkspacePill.vue b/src/components/editor/WorkspacePill.vuenew file mode 100644index 000000000..75b207fb7--- /dev/null+++ b/src/components/editor/WorkspacePill.vue@@ -0,0 +1,59 @@+<script setup lang="ts">+import { useI18n } from '@open-pencil/vue'++import { resolvedAppTheme } from '@/app/shell/theme'+import BrandMark from '@/components/brand/BrandMark.vue'+import AppButton from '@/components/ui/button/AppButton.vue'+import IconButton from '@/components/ui/button/IconButton.vue'++/**+ * The pill of the canvas-only layout: the document name and the way back. In preview it says+ * so, resets the controls, and leaves preview.+ */+const { documentName, mode, shortcut } = defineProps<{+ documentName: string+ mode: 'collapsed' | 'preview'+ /** The shortcut of the way back: Toggle UI, or leaving preview. */+ shortcut: string+}>()+const emit = defineEmits<{ showUi: []; reset: []; leave: [] }>()+const { editor } = useI18n()+</script>++<template>+ <div+ class="absolute top-7 left-7 z-10 flex items-center gap-2 rounded-lg border border-border bg-panel px-2 py-1 shadow-sm"+ :data-mode="mode"+ >+ <BrandMark variant="app-icon" :appearance="resolvedAppTheme" class="size-6" />+ <span data-test-id="editor-document-name" class="text-xs text-surface">{{ documentName }}</span>+ <IconButton+ v-if="mode === 'collapsed'"+ :label="editor.showUI({ shortcut })"+ data-test-id="editor-show-ui"+ class="ml-1"+ @click="emit('showUi')"+ >+ <icon-lucide-sidebar class="size-3.5" />+ </IconButton>+ <template v-else>+ <span+ class="ml-1 flex h-5 items-center gap-1 rounded bg-accent/15 px-1.5 text-[10px] font-medium text-accent"+ >+ <icon-lucide-play class="size-3" />+ {{ editor.previewing }}+ </span>+ <AppButton size="xs" variant="soft" data-property="preview-reset" @click="emit('reset')">+ <icon-lucide-rotate-ccw class="size-3" />+ {{ editor.resetPreview }}+ </AppButton>+ <IconButton+ :label="editor.leavePreview({ shortcut })"+ data-property="preview-leave"+ @click="emit('leave')"+ >+ <icon-lucide-x class="size-3.5" />+ </IconButton>+ </template>+ </div>+</template>diff --git a/src/components/editor/examples/Pill.vue b/src/components/editor/examples/Pill.vuenew file mode 100644index 000000000..517fa82dd--- /dev/null+++ b/src/components/editor/examples/Pill.vue@@ -0,0 +1,35 @@+<script setup lang="ts">+import { ref } from 'vue'++import WorkspacePill from '../WorkspacePill.vue'++const log = ref<string[]>([])+const record = (entry: string) => {+ log.value = [entry, ...log.value].slice(0, 4)+}+</script>++<template>+ <div class="flex flex-col gap-4">+ <div class="relative h-20 w-[520px] rounded-lg bg-canvas">+ <WorkspacePill+ mode="preview"+ document-name="Settings screen"+ shortcut="⌥⌘↩"+ @reset="record('reset')"+ @leave="record('leave')"+ />+ </div>+ <div class="relative h-20 w-[520px] rounded-lg bg-canvas">+ <WorkspacePill+ mode="collapsed"+ document-name="Settings screen"+ shortcut="⌘\"+ @show-ui="record('show UI')"+ />+ </div>+ <ul class="text-xs text-muted" aria-label="Events">+ <li v-for="entry in log" :key="entry">{{ entry }}</li>+ </ul>+ </div>+</template>diff --git a/src/components/properties/component-properties/behaviour/AddBehaviourPicker.vue b/src/components/properties/component-properties/behaviour/AddBehaviourPicker.vuenew file mode 100644index 000000000..e36fdf57d--- /dev/null+++ b/src/components/properties/component-properties/behaviour/AddBehaviourPicker.vue@@ -0,0 +1,49 @@+<script setup lang="ts">+import { computed } from 'vue'++import { BEHAVIOUR_KINDS, type BehaviourKind } from '@open-pencil/scene-graph'+import { useI18n } from '@open-pencil/vue'++import IconButton from '@/components/ui/button/IconButton.vue'+import AppPicker, { type AppPickerItem } from '@/components/ui/select/AppPicker.vue'++import { useBehaviourLabels } from './labels'++/** The section's + : the controls a component can behave as. */+const emit = defineEmits<{ add: [kind: BehaviourKind] }>()+const { panels, common } = useI18n()+const labels = useBehaviourLabels()++const items = computed<AppPickerItem[]>(() =>+ BEHAVIOUR_KINDS.map((kind) => ({+ value: kind,+ label: labels.value.kind(kind).label,+ description: labels.value.kind(kind).description+ }))+)++function add(value: string) {+ const kind = BEHAVIOUR_KINDS.find((item) => item === value)+ if (kind) emit('add', kind)+}+</script>++<template>+ <AppPicker+ :heading="panels.addBehaviour"+ :items="items"+ :search-placeholder="panels.searchBehaviours"+ :empty-label="panels.noBehavioursFound"+ :close-label="common.close"+ @select="add"+ >+ <template #trigger>+ <IconButton :label="panels.addBehaviour" data-property="add-behaviour">+ <icon-lucide-plus class="size-3.5" />+ </IconButton>+ </template>+ <template #leading>+ <icon-lucide-mouse-pointer-click class="size-3.5 text-component" />+ </template>+ </AppPicker>+</template>diff --git a/src/components/properties/component-properties/behaviour/Behaviour.stories.ts b/src/components/properties/component-properties/behaviour/Behaviour.stories.tsnew file mode 100644index 000000000..40cdeb75d--- /dev/null+++ b/src/components/properties/component-properties/behaviour/Behaviour.stories.ts@@ -0,0 +1,52 @@+import type { Meta, StoryObj } from '@storybook/vue3-vite'+import { expect, userEvent, waitFor, within } from 'storybook/test'++import BehaviourStates from './examples/States.vue'++const meta = {+ title: 'Editor/Properties/Behaviour',+ component: BehaviourStates,+ tags: ['autodocs'],+ parameters: {+ docs: {+ description: {+ component:+ 'The behaviour of a main component: the control it acts as in preview, the properties that hold its values, and the layers that are its parts.'+ }+ }+ }+} satisfies Meta<typeof BehaviourStates>++export default meta+type Story = StoryObj<typeof meta>++export const States: Story = {}++export const AddBehaviour: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ const page = within(canvasElement.ownerDocument.body)+ await userEvent.click(canvas.getByRole('button', { name: 'Add behaviour' }))+ await userEvent.click(await page.findByRole('option', { name: /Slider/ }))+ await waitFor(() => expect(canvas.getByText('add slider')).toBeVisible())+ }+}++export const MapState: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ const page = within(canvasElement.ownerDocument.body)+ await userEvent.click(canvas.getByRole('combobox', { name: 'Pressed state' }))+ await userEvent.click(await page.findByRole('option', { name: 'None' }))+ await waitFor(() => expect(canvas.getByText('pressed → default')).toBeVisible())+ }+}++export const CreateMissing: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ await userEvent.click(canvas.getByRole('button', { name: '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.vuenew file mode 100644index 000000000..602c2bbcd--- /dev/null+++ b/src/components/properties/component-properties/behaviour/BehaviourBindingField.vue@@ -0,0 +1,80 @@+<script setup lang="ts">+import { computed } from 'vue'++import { useI18n } from '@open-pencil/vue'++import AppButton from '@/components/ui/button/AppButton.vue'+import AppPickerField from '@/components/ui/select/AppPickerField.vue'++/**+ * One binding of a behaviour row: a picker of the component's matching properties or slots,+ * whose footer creates a new one, or, when it has none, that create action alone.+ */+const {+ label,+ propertyId,+ options,+ placeholder,+ emptyLabel,+ createLabel,+ missing = false+} = defineProps<{+ label: string+ propertyId: string | null+ options: { id: string; name: string }[]+ placeholder: string+ emptyLabel: string+ /** The action that creates a property or slot when the component has none. */+ createLabel: string+ missing?: boolean+}>()+const emit = defineEmits<{ bind: [propertyId: string]; create: [] }>()+defineOptions({ inheritAttrs: false })+const { panels, common } = useI18n()++const items = computed(() => options.map((option) => ({ value: option.id, label: option.name })))+</script>++<template>+ <AppPickerField+ v-if="options.length"+ :model-value="propertyId ?? ''"+ :items="items"+ :label="label"+ :placeholder="placeholder"+ :search-placeholder="panels.searchComponentProperties"+ :empty-label="emptyLabel"+ :close-label="common.close"+ :data-missing="(missing && !propertyId) || undefined"+ v-bind="$attrs"+ @update:model-value="emit('bind', $event)"+ >+ <template #footer="{ close }">+ <AppButton+ size="xs"+ class="w-full justify-start"+ data-slot="action"+ @click="+ () => {+ close()+ emit('create')+ }+ "+ >+ <template #leading><icon-lucide-plus class="size-3" /></template>+ {{ createLabel }}+ </AppButton>+ </template>+ </AppPickerField>+ <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-accent"+ :data-missing="missing || undefined"+ v-bind="$attrs"+ @click="emit('create')"+ >+ <icon-lucide-plus class="size-3 shrink-0" />+ <span class="min-w-0 truncate">{{ createLabel }}</span>+ </button>+</template>diff --git a/src/components/properties/component-properties/behaviour/BehaviourPanel.vue b/src/components/properties/component-properties/behaviour/BehaviourPanel.vuenew file mode 100644index 000000000..cf7cb7961--- /dev/null+++ b/src/components/properties/component-properties/behaviour/BehaviourPanel.vue@@ -0,0 +1,28 @@+<script setup lang="ts">+import { useBehaviour } from '@open-pencil/vue'++import BehaviourSection from './BehaviourSection.vue'++/** The Behaviour section connected to the selected main component or component set. */+const behaviour = useBehaviour()+</script>++<template>+ <BehaviourSection+ v-if="behaviour.active.value"+ :behaviour="behaviour.behaviour.value"+ @add="behaviour.add"+ @remove="behaviour.remove"+ @bind-value="behaviour.bindValue"+ @bind-text="behaviour.bindText"+ @map-value="behaviour.mapValue"+ @set-number="behaviour.setNumber"+ @bind-part="behaviour.bindPart"+ @bind-states="behaviour.bindStates"+ @map-state="behaviour.mapState"+ @create-text="behaviour.createText"+ @create-variant="behaviour.createVariant"+ @create-part="behaviour.createPart"+ @create-states="behaviour.createStates"+ />+</template>diff --git a/src/components/properties/component-properties/behaviour/BehaviourRow.vue b/src/components/properties/component-properties/behaviour/BehaviourRow.vuenew file mode 100644index 000000000..e70f0ab20--- /dev/null+++ b/src/components/properties/component-properties/behaviour/BehaviourRow.vue@@ -0,0 +1,161 @@+<script setup lang="ts">+import { computed, reactive, watch } from 'vue'++import { isNumberRange, type BehaviourKind } from '@open-pencil/scene-graph'+import { useI18n } from '@open-pencil/vue'+import type {+ BehaviourBooleanControl,+ BehaviourNumberControl,+ BehaviourPartControl,+ BehaviourValueControl+} from '@open-pencil/vue'++import NumberField from '@/components/inputs/NumberField.vue'+import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'+import AppSelect from '@/components/ui/select/AppSelect.vue'++import BehaviourBindingField from './BehaviourBindingField.vue'+import { useBehaviourLabels } from './labels'++/** One row of the Behaviour section: a value of the control, or one of its parts. */+const { kind, row } = defineProps<{+ kind: BehaviourKind+ row: { part: BehaviourPartControl } | { value: BehaviourValueControl }+}>()+const emit = defineEmits<{+ bind: [propertyId: string]+ create: [name: string]+ mapValue: [mapping: { on: string; off: string }]+ setNumber: [settings: Omit<BehaviourNumberControl, 'id' | 'type'>]+}>()+const { panels } = useI18n()+const labels = useBehaviourLabels()++const part = computed(() => ('part' in row ? row.part : null))+const value = computed(() => ('value' in row ? row.value : null))+const number = computed(() => (value.value?.type === 'number' ? value.value : null))+const id = computed(() => part.value?.id ?? value.value?.id ?? '')+const label = computed(() =>+ part.value ? labels.value.part(id.value) : labels.value.valueOf(kind, id.value)+)++/** Variant values of the bound property, for choosing which mean on and off. */+function variantValues(boolean: BehaviourBooleanControl) {+ const option = boolean.options.find((item) => item.id === boolean.propertyId)+ return (option?.values ?? []).map((name) => ({ value: name, label: name }))+}++function setMapping(boolean: BehaviourBooleanControl, side: 'on' | 'off', choice: string) {+ emit('mapValue', {+ on: side === 'on' ? choice : (boolean.on ?? ''),+ off: side === 'off' ? choice : (boolean.off ?? '')+ })+}++const NUMBER_FIELDS = ['min', 'max', 'step', 'default'] as const+type NumberSetting = (typeof NUMBER_FIELDS)[number]++/** Number fields as they are scrubbed, reset whenever the value changes. */+const drafts = reactive<Partial<Record<NumberSetting, number>>>({})+watch(+ value,+ (current) => {+ if (current?.type === 'number')+ for (const field of NUMBER_FIELDS) drafts[field] = current[field]+ },+ { immediate: true, deep: true }+)++/** Keep a range a slider can step through; any other puts the field back. */+function commitNumber(number: BehaviourNumberControl, field: NumberSetting, input: number) {+ const { id: _id, type: _type, ...settings } = number+ const next = { ...settings, [field]: input }+ if (isNumberRange(next)) emit('setNumber', next)+ else drafts[field] = number[field]+}++function numberLabel(field: NumberSetting) {+ const p = panels.value+ return {+ min: p.behaviourMin,+ max: p.behaviourMax,+ step: p.behaviourStep,+ default: p.behaviourStart+ }[field]+}+</script>++<template>+ <PanelFieldGroup :label="label" :data-row="id">+ <BehaviourBindingField+ v-if="part"+ :label="label"+ :property-id="part.propertyId"+ :options="part.options"+ :placeholder="panels.behaviourChooseSlot"+ :empty-label="panels.behaviourNoSlots"+ :create-label="panels.behaviourAddSlot({ name: label })"+ :missing="part.required"+ :data-property="`behaviour-part-${id}`"+ @bind="emit('bind', $event)"+ @create="emit('create', label)"+ />+ <template v-else-if="value?.type === 'boolean'">+ <BehaviourBindingField+ :label="label"+ :property-id="value.propertyId"+ :options="value.options"+ :placeholder="panels.behaviourChooseProperty"+ :empty-label="panels.noComponentProperties"+ :create-label="panels.behaviourAddVariants"+ :missing="value.required"+ :data-property="`behaviour-value-${id}`"+ @bind="emit('bind', $event)"+ @create="emit('create', label)"+ />+ <div+ v-if="value.propertyId && variantValues(value).length"+ class="mt-1 grid grid-cols-2 gap-1"+ >+ <AppSelect+ :label="panels.behaviourOnValue"+ :model-value="value.on ?? ''"+ :options="variantValues(value)"+ @update:model-value="setMapping(value, 'on', $event)"+ />+ <AppSelect+ :label="panels.behaviourOffValue"+ :model-value="value.off ?? ''"+ :options="variantValues(value)"+ @update:model-value="setMapping(value, 'off', $event)"+ />+ </div>+ </template>+ <BehaviourBindingField+ v-else-if="value?.type === 'text'"+ :label="label"+ :property-id="value.propertyId"+ :options="value.options"+ :placeholder="panels.behaviourChooseProperty"+ :empty-label="panels.noComponentProperties"+ :create-label="panels.behaviourAddTextLayer"+ :missing="value.required"+ :data-property="`behaviour-value-${id}`"+ @bind="emit('bind', $event)"+ @create="emit('create', label)"+ />+ <div v-else-if="number" class="grid grid-cols-2 gap-1" :data-property="`behaviour-value-${id}`">+ <NumberField+ v-for="field in NUMBER_FIELDS"+ :key="field"+ :label="numberLabel(field)"+ :aria-label="numberLabel(field)"+ :model-value="drafts[field] ?? number[field]"+ :data-property="`behaviour-number-${field}`"+ @update:model-value="drafts[field] = $event"+ @commit="(input: number) => number && commitNumber(number, field, input)"+ @cancel="drafts[field] = number[field]"+ />+ </div>+ </PanelFieldGroup>+</template>diff --git a/src/components/properties/component-properties/behaviour/BehaviourSection.vue b/src/components/properties/component-properties/behaviour/BehaviourSection.vuenew file mode 100644index 000000000..600d11b40--- /dev/null+++ b/src/components/properties/component-properties/behaviour/BehaviourSection.vue@@ -0,0 +1,200 @@+<script setup lang="ts">+import { computed, ref, useTemplateRef } from 'vue'++import type { BehaviourKind, InteractionState } from '@open-pencil/scene-graph'+import { useI18n } from '@open-pencil/vue'+import type {+ BehaviourControl,+ BehaviourNumberControl,+ BehaviourPartControl,+ BehaviourValueControl+} from '@open-pencil/vue'++import IconButton from '@/components/ui/button/IconButton.vue'+import AppCollapsible from '@/components/ui/collapsible/AppCollapsible.vue'+import SeverityIcon from '@/components/ui/feedback/SeverityIcon.vue'+import PanelSection from '@/components/ui/panel/PanelSection.vue'++import AddBehaviourPicker from './AddBehaviourPicker.vue'+import BehaviourRow from './BehaviourRow.vue'+import BehaviourStates from './BehaviourStates.vue'+import { useBehaviourLabels } from './labels'++/**+ * The behaviour of the selected main component: which control it acts as, the properties that+ * hold its values, and the slots that are its parts. Rows it needs, or already uses, come+ * first; the optional rest folds under More options. An empty row offers to create what it+ * needs.+ */+const { behaviour } = defineProps<{ behaviour: BehaviourControl | null }>()+const emit = defineEmits<{+ add: [kind: BehaviourKind]+ remove: []+ bindValue: [valueId: string, propertyId: string]+ bindText: [valueId: string, propertyId: string]+ mapValue: [valueId: string, mapping: { on: string; off: string }]+ setNumber: [valueId: string, settings: Omit<BehaviourNumberControl, 'id' | 'type'>]+ bindPart: [partId: string, propertyId: string]+ bindStates: [propertyId: string]+ mapState: [state: InteractionState, value: string]+ createText: [valueId: string, name: string]+ createVariant: [valueId: string, name: string]+ createPart: [partId: string, name: string]+ createStates: []+}>()+const { panels, locale } = useI18n()+const labels = useBehaviourLabels()++type Row = { part: BehaviourPartControl } | { value: BehaviourValueControl }+const rowOf = (row: Row) => ('part' in row ? row.part : row.value)++/** A row comes first when the control needs it, uses it, or keeps its own settings. */+function first(row: BehaviourValueControl | BehaviourPartControl): boolean {+ return !('required' in row) || row.required || !!row.propertyId+}+/**+ * Whether a row belongs in the section. An unbound Disabled leaves its look to the states,+ * which add a Disabled variant, unless the component has a property to bind it to.+ */+function usable(row: BehaviourValueControl | BehaviourPartControl): boolean {+ if (row.id !== 'disabled' || !('options' in row) || row.propertyId) return true+ return row.options.length > 0 && !behaviour?.states.values.disabled+}+const rows = computed<Row[]>(() =>+ [+ ...(behaviour?.values.map((value) => ({ value })) ?? []),+ ...(behaviour?.parts.map((part) => ({ part })) ?? [])+ ].filter((row) => usable(rowOf(row)))+)+const mainRows = computed(() => rows.value.filter((row) => first(rowOf(row))))+const moreRows = computed(() => rows.value.filter((row) => !first(rowOf(row))))+/** States come first once drawn, or when there is nothing else to set up, as on a button. */+const statesFirst = computed(+ () =>+ !!behaviour?.states.propertyId ||+ !rows.value.some((row) => {+ const control = rowOf(row)+ return 'required' in control && control.required+ })+)+const moreOpen = ref(false)++function bind(row: Row, propertyId: string) {+ if ('part' in row) emit('bindPart', row.part.id, propertyId)+ else if (row.value.type === 'text') emit('bindText', row.value.id, propertyId)+ else emit('bindValue', row.value.id, propertyId)+}++function create(row: Row, name: string) {+ if ('part' in row) emit('createPart', row.part.id, name)+ else if (row.value.type === 'text') emit('createText', row.value.id, name)+ else emit('createVariant', row.value.id, name)+}++const kind = computed(() => (behaviour ? labels.value.kind(behaviour.kind) : null))++/** The name of a missing row: a part, the states, or a value. */+function missingName(control: BehaviourControl, id: string): string {+ if (control.parts.some((row) => row.id === id)) return labels.value.part(id)+ if (id === 'states') return panels.value.behaviourStates+ return labels.value.valueOf(control.kind, id)+}++/** What is left to bind, by row name, such as "Still needed: Track and Thumb." */+const nextStep = computed(() => {+ if (!behaviour) return ''+ const names = behaviour.missing.map((id) => missingName(behaviour, id))+ 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>+ <PanelSection :label="panels.behaviour" :empty="!behaviour">+ <template #actions>+ <AddBehaviourPicker v-if="!behaviour" @add="emit('add', $event)" />+ <IconButton v-else :label="panels.removeBehaviour" @click="emit('remove')">+ <icon-lucide-minus class="size-3.5" />+ </IconButton>+ </template>++ <div v-if="behaviour && kind" ref="root" 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>+ <span+ v-if="!behaviour.missing.length"+ class="flex h-5 shrink-0 items-center gap-1 rounded bg-panel-field px-1.5 text-[10px] text-muted"+ >+ <icon-lucide-check class="size-3 text-success" />+ {{ panels.behaviourComplete }}+ </span>+ </div>++ <button+ 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"+ data-property="behaviour-missing"+ @click="showMissing"+ >+ <SeverityIcon severity="warning" class="mt-0.5 shrink-0" />+ {{ nextStep }}+ </button>++ <BehaviourRow+ v-for="row in mainRows"+ :key="rowOf(row).id"+ :kind="behaviour.kind"+ :row="row"+ @bind="bind(row, $event)"+ @create="create(row, $event)"+ @map-value="emit('mapValue', rowOf(row).id, $event)"+ @set-number="emit('setNumber', rowOf(row).id, $event)"+ />+ <BehaviourStates+ v-if="statesFirst"+ :states="behaviour.states"+ @bind="emit('bindStates', $event)"+ @map="(state, value) => emit('mapState', state, value)"+ @create="emit('createStates')"+ />++ <AppCollapsible+ v-if="moreRows.length || !statesFirst"+ v-model:open="moreOpen"+ :label="panels.behaviourMoreOptions"+ :ui="{ trigger: 'text-[11px] text-muted hover:text-surface', icon: 'size-3' }"+ data-property="behaviour-more"+ >+ <div class="flex flex-col gap-2 pt-2">+ <BehaviourRow+ v-for="row in moreRows"+ :key="rowOf(row).id"+ :kind="behaviour.kind"+ :row="row"+ @bind="bind(row, $event)"+ @create="create(row, $event)"+ @map-value="emit('mapValue', rowOf(row).id, $event)"+ />+ <BehaviourStates+ v-if="!statesFirst"+ :states="behaviour.states"+ @bind="emit('bindStates', $event)"+ @map="(state, value) => emit('mapState', state, value)"+ @create="emit('createStates')"+ />+ </div>+ </AppCollapsible>+ </div>+ </PanelSection>+</template>diff --git a/src/components/properties/component-properties/behaviour/BehaviourStates.vue b/src/components/properties/component-properties/behaviour/BehaviourStates.vuenew file mode 100644index 000000000..46f7c0cfb--- /dev/null+++ b/src/components/properties/component-properties/behaviour/BehaviourStates.vue@@ -0,0 +1,93 @@+<script setup lang="ts">+import { computed } from 'vue'++import { INTERACTION_STATES, type InteractionState } from '@open-pencil/scene-graph'+import { useI18n } from '@open-pencil/vue'+import type { BehaviourStatesControl } from '@open-pencil/vue'++import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'+import AppPickerField from '@/components/ui/select/AppPickerField.vue'+import AppSelect from '@/components/ui/select/AppSelect.vue'++import BehaviourBindingField from './BehaviourBindingField.vue'+import { useBehaviourLabels } from './labels'++/**+ * Which variant property draws the control's interaction states, and which of its values is+ * each state. A state set to None shows the default value. A component without variant+ * properties offers to add a variant for each state instead.+ */+const { states } = defineProps<{ states: BehaviourStatesControl }>()+const emit = defineEmits<{+ bind: [propertyId: string]+ map: [state: InteractionState, value: string]+ create: []+}>()+const { panels, common } = useI18n()+const labels = useBehaviourLabels()++/** Stands for "no value" in a select, which cannot hold an empty string and never a number. */+const UNSET = -1++const properties = computed(() =>+ states.options.map((option) => ({ value: option.id, label: option.name }))+)+const values = computed<{ value: string | number; label: string }[]>(() => {+ const property = states.options.find((option) => option.id === states.propertyId)+ return [+ { value: UNSET, label: panels.value.behaviourStateUnset },+ ...(property?.values ?? []).map((value) => ({ value, label: value }))+ ]+})++function map(state: InteractionState, value: string | number) {+ emit('map', state, typeof value === 'string' ? value : '')+}+</script>++<template>+ <div class="flex flex-col gap-1.5" data-property="behaviour-states">+ <div class="text-[11px] text-muted">{{ panels.behaviourStates }}</div>+ <template v-if="!states.options.length">+ <p class="text-[11px] leading-4 text-muted">{{ panels.behaviourStatesHint }}</p>+ <BehaviourBindingField+ :label="panels.behaviourStates"+ :property-id="null"+ :options="[]"+ :placeholder="panels.behaviourChooseProperty"+ :empty-label="panels.noComponentProperties"+ :create-label="panels.behaviourAddStates"+ data-property="behaviour-states-create"+ @bind="emit('bind', $event)"+ @create="emit('create')"+ />+ </template>+ <AppPickerField+ v-else+ :model-value="states.propertyId ?? ''"+ :items="properties"+ :label="panels.behaviourStates"+ :placeholder="panels.behaviourChooseProperty"+ :search-placeholder="panels.searchComponentProperties"+ :empty-label="panels.noComponentProperties"+ :close-label="common.close"+ data-property="behaviour-states-property"+ @update:model-value="emit('bind', $event)"+ />+ <div v-if="states.propertyId" class="grid grid-cols-2 gap-x-1 gap-y-1.5">+ <PanelFieldGroup+ v-for="state in INTERACTION_STATES"+ :key="state"+ :label="labels.state(state)"+ >+ <AppSelect+ :label="panels.behaviourStateField({ state: labels.state(state) })"+ :model-value="states.values[state] ?? UNSET"+ :options="values"+ :data-property="`behaviour-state-${state}`"+ @update:model-value="map(state, $event)"+ />+ </PanelFieldGroup>+ </div>+ </div>+</template>diff --git a/src/components/properties/component-properties/behaviour/examples/States.vue b/src/components/properties/component-properties/behaviour/examples/States.vuenew file mode 100644index 000000000..cb6f623ca--- /dev/null+++ b/src/components/properties/component-properties/behaviour/examples/States.vue@@ -0,0 +1,125 @@+<script setup lang="ts">+import { ref } from 'vue'++import type { BehaviourControl } from '@open-pencil/vue'++import BehaviourSection from '../BehaviourSection.vue'++const stateProperty = { id: 'state', name: 'State', values: ['On', 'Off'] }+const sizeProperty = { id: 'size', name: 'Size', values: ['Small', 'Large'] }+const interactionProperty = {+ id: 'interaction',+ name: 'Interaction',+ values: ['Default', 'Hover', 'Pressed', 'Disabled']+}+const thumbSlot = { id: 'thumb', name: 'Thumb', values: [] }+const trackSlot = { id: 'track', name: 'Track', values: [] }++const switchComplete = ref<BehaviourControl>({+ kind: 'switch',+ missing: [],+ values: [+ {+ id: 'value',+ type: 'boolean',+ required: true,+ propertyId: 'state',+ on: 'On',+ off: 'Off',+ options: [stateProperty, sizeProperty]+ },+ {+ id: 'disabled',+ type: 'boolean',+ required: false,+ propertyId: null,+ options: [stateProperty, sizeProperty]+ }+ ],+ parts: [{ id: 'thumb', required: false, propertyId: 'thumb', options: [thumbSlot] }],+ states: {+ propertyId: 'interaction',+ values: { rest: 'Default', hover: 'Hover', pressed: 'Pressed', disabled: 'Disabled' },+ options: [stateProperty, sizeProperty, interactionProperty]+ }+})+const sliderIncomplete = ref<BehaviourControl>({+ kind: 'slider',+ missing: ['thumb'],+ values: [+ { id: 'value', type: 'number', min: 0, max: 100, step: 1, default: 50 },+ {+ id: 'disabled',+ type: 'boolean',+ required: false,+ propertyId: null,+ options: [stateProperty]+ }+ ],+ parts: [+ { id: 'track', required: true, propertyId: 'track', options: [trackSlot] },+ { id: 'range', required: false, propertyId: null, options: [trackSlot] },+ { id: 'thumb', required: true, propertyId: null, options: [] }+ ],+ states: { propertyId: null, values: {}, options: [interactionProperty] }+})+/** A plain rectangle made a component and given a Textarea behaviour: nothing to bind yet. */+const textareaBare = ref<BehaviourControl>({+ kind: 'textarea',+ missing: ['value'],+ values: [+ { id: 'value', type: 'text', required: true, propertyId: null, options: [] },+ {+ id: 'filled',+ type: 'boolean',+ required: false,+ propertyId: null,+ options: []+ },+ {+ id: 'disabled',+ type: 'boolean',+ required: false,+ propertyId: null,+ options: []+ }+ ],+ parts: [],+ states: { propertyId: null, values: {}, options: [] }+})+const log = ref<string[]>([])+const record = (entry: string) => {+ log.value = [entry, ...log.value].slice(0, 4)+}+</script>++<template>+ <div class="flex items-start gap-6">+ <div+ v-for="(state, index) in [null, textareaBare, switchComplete, sliderIncomplete]"+ :key="index"+ class="w-[240px] overflow-hidden rounded-lg border border-border bg-panel"+ >+ <BehaviourSection+ :behaviour="state"+ @add="record(`add ${$event}`)"+ @remove="record('remove')"+ @bind-value="(value, property) => record(`bind ${value} → ${property}`)"+ @map-value="(value, mapping) => record(`map ${value}: ${mapping.on}/${mapping.off}`)"+ @set-number="+ (value, settings) =>+ record(`${value}: ${settings.min}..${settings.max} by ${settings.step}`)+ "+ @bind-part="(part, property) => record(`bind ${part} → ${property}`)"+ @bind-states="(property) => record(`states → ${property}`)"+ @map-state="(state, value) => record(`${state} → ${value || 'default'}`)"+ @create-text="(value, name) => record(`create text ${name} for ${value}`)"+ @create-variant="(value, name) => record(`create ${name} variants for ${value}`)"+ @create-part="(part, name) => record(`create ${name} slot for ${part}`)"+ />+ </div>+ <ul class="text-xs text-muted" aria-label="Events">+ <li v-for="entry in log" :key="entry">{{ entry }}</li>+ </ul>+ </div>+</template>diff --git a/src/components/properties/component-properties/behaviour/labels.ts b/src/components/properties/component-properties/behaviour/labels.tsnew file mode 100644index 000000000..9d796c0f8--- /dev/null+++ b/src/components/properties/component-properties/behaviour/labels.ts@@ -0,0 +1,83 @@+import { computed } from 'vue'++import type { BehaviourKind, InteractionState } from '@open-pencil/scene-graph'+import { useI18n } from '@open-pencil/vue'++/** Translated names of behaviour kinds, values, parts, and interaction states. */+export function useBehaviourLabels() {+ const { panels } = useI18n()+ return computed(() => {+ const p = panels.value+ const kinds: Record<BehaviourKind, { label: string; description: string }> = {+ button: { label: p.behaviourButton, description: p.behaviourButtonDescription },+ textField: { label: p.behaviourTextField, description: p.behaviourTextFieldDescription },+ textarea: { label: p.behaviourTextarea, description: p.behaviourTextareaDescription },+ numberField: {+ label: p.behaviourNumberField,+ description: p.behaviourNumberFieldDescription+ },+ toggle: { label: p.behaviourToggle, description: p.behaviourToggleDescription },+ switch: { label: p.behaviourSwitch, description: p.behaviourSwitchDescription },+ checkbox: { label: p.behaviourCheckbox, description: p.behaviourCheckboxDescription },+ radio: { label: p.behaviourRadio, description: p.behaviourRadioDescription },+ radioGroup: { label: p.behaviourRadioGroup, description: p.behaviourRadioGroupDescription },+ toggleGroup: {+ label: p.behaviourToggleGroup,+ description: p.behaviourToggleGroupDescription+ },+ slider: { label: p.behaviourSlider, description: p.behaviourSliderDescription },+ progress: { label: p.behaviourProgress, description: p.behaviourProgressDescription },+ tabs: { label: p.behaviourTabs, description: p.behaviourTabsDescription },+ collapsible: {+ label: p.behaviourCollapsible,+ description: p.behaviourCollapsibleDescription+ },+ accordion: { label: p.behaviourAccordion, description: p.behaviourAccordionDescription }+ }+ const values: Record<string, string> = {+ value: p.behaviourValue,+ open: p.behaviourOpen,+ filled: p.behaviourFilled,+ text: p.behaviourText,+ disabled: p.behaviourDisabled+ }+ const parts: Record<string, string> = {+ track: p.behaviourTrack,+ thumb: p.behaviourThumb,+ range: p.behaviourRange,+ indicator: p.behaviourIndicator,+ list: p.behaviourList,+ trigger: p.behaviourTrigger,+ content: p.behaviourContent,+ panels: p.behaviourPanels,+ items: p.behaviourItems,+ increment: p.behaviourIncrement,+ decrement: p.behaviourDecrement+ }+ const states: Record<InteractionState, string> = {+ rest: p.behaviourStateRest,+ hover: p.behaviourStateHover,+ pressed: p.behaviourStatePressed,+ focus: p.behaviourStateFocus,+ disabled: p.behaviourStateDisabled+ }+ /** What a control's main value is called, which code calls its `value`. */+ const mainValue: Partial<Record<BehaviourKind, string>> = {+ switch: p.behaviourChecked,+ checkbox: p.behaviourChecked,+ radio: p.behaviourChecked,+ toggle: p.behaviourPressed,+ textField: p.behaviourText,+ textarea: p.behaviourText+ }+ return {+ state: (state: InteractionState) => states[state],+ /** A value's name for this kind of control. */+ valueOf: (kind: BehaviourKind, id: string) =>+ (id === 'value' ? mainValue[kind] : undefined) ??+ (Object.hasOwn(values, id) ? values[id] : id),+ kind: (kind: BehaviourKind) => kinds[kind],+ part: (id: string) => parts[id] ?? id+ }+ })+}diff --git a/src/components/properties/component-properties/VariantAuthoringSection.vue b/src/components/properties/component-properties/variant/VariantAuthoringSection.vuesimilarity index 100%rename from src/components/properties/component-properties/VariantAuthoringSection.vuerename to src/components/properties/component-properties/variant/VariantAuthoringSection.vuediff --git a/src/components/ui/select/AppPickerField.vue b/src/components/ui/select/AppPickerField.vueindex e294f2d5a..59582a849 100644--- a/src/components/ui/select/AppPickerField.vue+++ b/src/components/ui/select/AppPickerField.vue@@ -16,7 +16,11 @@ const { label, items, searchPlaceholder, emptyLabel, closeLabel, placeholder } =placeholder?: string}>()const value = defineModel<string>({ required: true })-defineSlots<{ leading?(props: { item: AppPickerItem }): unknown }>()+defineSlots<{+ leading?(props: { item: AppPickerItem }): unknown+ /** An action under the list, such as creating a new item. */+ footer?(props: { close: () => void }): unknown+}>()defineOptions({ inheritAttrs: false })const styles = tv(theme)()const current = computed(() => items.find((item) => item.value === value.value))@@ -49,5 +53,8 @@ const current = computed(() => items.find((item) => item.value === value.value))<template v-if="$slots.leading" #leading="{ item }"><slot name="leading" :item="item" /></template>+ <template v-if="$slots.footer" #footer="{ close }">+ <slot name="footer" :close="close" />+ </template></AppPicker></template>diff --git a/tests/e2e/components/behaviours.spec.ts b/tests/e2e/components/behaviours.spec.tsnew file mode 100644index 000000000..7610f41df--- /dev/null+++ b/tests/e2e/components/behaviours.spec.ts@@ -0,0 +1,294 @@+import { colorToCSS } from '@open-pencil/scene-graph/color'++import { expect, test, useEditorSetupWithClear } from '#tests/e2e/fixtures'+import { propertySection } from '#tests/helpers/properties'++const editor = useEditorSetupWithClear('/?test&no-rulers')++/** The live island a previewing canvas runs for a top-level layer. */+function island(layerId: string) {+ return editor.page.locator(`[data-island="${layerId}"]`)+}++async function startPreview() {+ await editor.page.keyboard.press('ControlOrMeta+Alt+Enter')+ await expect(editor.page.getByRole('button', { name: /Leave preview/ })).toBeVisible()+}++/** A Switch set whose State=On and State=Off variants differ, and an Off instance below it. */+async function createSwitch() {+ return editor.page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const graph = store.graph+ const pageId = store.state.currentPageId+ const solid = (r: number, g: number, b: number) => [+ { type: 'SOLID' as const, color: { r, g, b, a: 1 }, opacity: 1, visible: true }+ ]+ const set = graph.createNode('COMPONENT_SET', pageId, {+ name: 'Switch',+ x: 120,+ y: 120,+ width: 200,+ height: 80,+ componentPropertyDefinitions: [+ {+ id: 'state',+ name: 'State',+ type: 'VARIANT',+ defaultValue: 'Off',+ variantOptions: ['On', 'Off']+ }+ ]+ })+ const variant = (value: string, index: number, on: boolean) => {+ const component = graph.createNode('COMPONENT', set.id, {+ name: `State=${value}`,+ x: 20 + index * 90,+ y: 20,+ width: 56,+ height: 32,+ cornerRadius: 16,+ fills: on ? solid(0.2, 0.6, 1) : solid(0.8, 0.8, 0.85),+ componentPropertyValues: { State: value }+ })+ graph.createNode('ELLIPSE', component.id, {+ name: 'Knob',+ x: on ? 28 : 4,+ y: 4,+ width: 24,+ height: 24,+ fills: solid(1, 1, 1)+ })+ return component+ }+ variant('On', 0, true)+ const off = variant('Off', 1, false)+ const instance = graph.createInstance(off.id, pageId, { x: 120, y: 260 })+ if (!instance) throw new Error('Instance not created')+ store.select([set.id])+ return { setId: set.id, offId: off.id, instanceId: instance.id }+ })+}++test('a Switch behaviour flips in preview and leaves the document alone', async () => {+ const ids = await createSwitch()+ await editor.canvas.waitForRender()++ const section = propertySection(editor.page, 'Behaviour')+ await section.getByRole('button', { name: 'Add behaviour' }).click()+ await editor.page.getByRole('option', { name: /Switch/ }).click()+ await section.getByRole('combobox', { name: 'Checked' }).click()+ await editor.page.getByRole('option', { name: 'State' }).click()+ await expect(section.getByText('Ready', { exact: true })).toBeVisible()++ await startPreview()+ // The instance runs as Reka UI's Switch, drawn by the set's variants.+ const control = island(ids.instanceId).getByRole('switch')+ await expect(control).toHaveAttribute('aria-checked', 'false')+ await control.click()+ await expect(control).toHaveAttribute('aria-checked', 'true')+ await editor.page.mouse.move(4, 400)+ await expect(island(ids.instanceId)).toHaveScreenshot('switch-island-on.png')+ await control.press('Space')+ await expect(control).toHaveAttribute('aria-checked', 'false')+ await control.click()++ const document = await editor.page.evaluate((instanceId) => {+ const store = window.openPencil?.getStore?.()+ return store?.graph.getNode(instanceId)?.componentId+ }, ids.instanceId)+ expect(document).toBe(ids.offId)++ await editor.page.keyboard.press('Escape')+ await expect(editor.page.getByRole('button', { name: /Leave preview/ })).toHaveCount(0)+ // Editing again: the panels and their Preview button are back.+ await expect(editor.page.getByRole('button', { name: /^Preview/ })).toBeVisible()+})++test('a Button behaviour maps its states and shows them in preview', async () => {+ const ids = await editor.page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const graph = store.graph+ const pageId = store.state.currentPageId+ const values = ['Default', 'Hover', 'Pressed', 'Focus', 'Disabled']+ const set = graph.createNode('COMPONENT_SET', pageId, {+ name: 'Button',+ x: 120,+ y: 120,+ width: 520,+ height: 80,+ componentPropertyDefinitions: [+ {+ id: 'interaction',+ name: 'Interaction',+ type: 'VARIANT',+ defaultValue: 'Default',+ variantOptions: values+ }+ ]+ })+ const components = values.map((value, index) =>+ graph.createNode('COMPONENT', set.id, {+ name: `Interaction=${value}`,+ x: 20 + index * 100,+ y: 24,+ width: 80,+ height: 32,+ cornerRadius: 8,+ fills: [+ {+ type: 'SOLID' as const,+ color: { r: 0.2 + index * 0.15, g: 0.4, b: 0.9 - index * 0.15, a: 1 },+ opacity: 1,+ visible: true+ }+ ],+ componentPropertyValues: { Interaction: value }+ })+ )+ const instance = graph.createInstance(components[0].id, pageId, { x: 120, y: 260 })+ if (!instance) throw new Error('Instance not created')+ store.select([set.id])+ return {+ instanceId: instance.id,+ byValue: Object.fromEntries(values.map((value, index) => [value, components[index].id]))+ }+ })+ await editor.canvas.waitForRender()++ const section = propertySection(editor.page, 'Behaviour')+ await section.getByRole('button', { name: 'Add behaviour' }).click()+ await editor.page.getByRole('option', { name: /Button/ }).click()+ await section.getByRole('combobox', { name: 'States' }).click()+ await editor.page.getByRole('option', { name: 'Interaction' }).click()+ // Values named like states are mapped to them.+ await expect(section.getByRole('combobox', { name: 'Hover state' })).toHaveText(/Hover/)+ await expect(section.getByRole('combobox', { name: 'Pressed state' })).toHaveText(/Pressed/)+ await expect(section.getByRole('combobox', { name: 'Disabled state' })).toHaveText(/Disabled/)++ await startPreview()+ // Each state shows its variant's fill: the components are filled by index, as created above.+ const fill = (index: number) =>+ colorToCSS({ r: 0.2 + index * 0.15, g: 0.4, b: 0.9 - index * 0.15, a: 1 })+ const button = island(ids.instanceId).getByRole('button')+ await expect(button).toHaveCSS('background-color', fill(0))+ await button.hover()+ await expect(button).toHaveCSS('background-color', fill(1))+ await editor.page.mouse.down()+ await expect(button).toHaveCSS('background-color', fill(2))+ await editor.page.mouse.up()+ await expect(button).toHaveCSS('background-color', fill(1))+ await editor.page.mouse.move(4, 400)+ await expect(button).toHaveCSS('background-color', fill(0))+ await editor.page.keyboard.press('Escape')+ await expect(editor.page.getByRole('button', { name: /Leave preview/ })).toHaveCount(0)+})++test('a Text field takes typing in preview without triggering shortcuts', async () => {+ const instanceId = await editor.page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const graph = store.graph+ const pageId = store.state.currentPageId+ const component = graph.createNode('COMPONENT', pageId, {+ name: 'Field',+ x: 120,+ y: 120,+ width: 200,+ height: 36,+ cornerRadius: 6,+ fills: [+ { type: 'SOLID' as const, color: { r: 1, g: 1, b: 1, a: 1 }, opacity: 1, visible: true }+ ],+ componentPropertyDefinitions: [+ { id: 'value', name: 'Value', type: 'TEXT', defaultValue: 'Name' }+ ]+ })+ graph.createNode('TEXT', component.id, {+ name: 'Value',+ x: 10,+ y: 10,+ width: 180,+ height: 16,+ text: 'Name',+ componentPropertyReferences: [{ propertyId: 'value', field: 'TEXT' }]+ })+ store.setBehaviour(component.id, {+ kind: 'textField',+ booleans: {},+ texts: { value: { propertyId: 'value' } },+ numbers: {},+ parts: {}+ })+ const instance = graph.createInstance(component.id, pageId, { x: 120, y: 220 })+ if (!instance) throw new Error('Instance not created')+ return instance.id+ })+ await editor.canvas.waitForRender()++ await startPreview()+ // A real input: typing, the caret, and selection are the browser's.+ const input = island(instanceId).locator('input')+ await expect(input).toHaveValue('Name')+ await input.click()+ await editor.page.keyboard.press('End')+ // R, T, and V are tool shortcuts while editing.+ await editor.page.keyboard.type(' Vera T')+ await editor.page.keyboard.press('Home')+ await editor.page.keyboard.press('Shift+ArrowRight')+ await editor.page.keyboard.type('S')+ await expect(input).toHaveValue('Same Vera T')+ expect(await editor.page.evaluate(() => window.openPencil?.getStore?.()?.state.activeTool)).toBe(+ 'SELECT'+ )+ await editor.page.getByRole('button', { name: /Leave preview/ }).click()+ await expect(island(instanceId)).toHaveCount(0)+})++test('a rectangle made a Textarea gets its text layer from the panel and takes typing', async () => {+ const componentId = await editor.page.evaluate(() => {+ const store = window.openPencil?.getStore?.()+ if (!store) throw new Error('OpenPencil store not initialized')+ const component = store.graph.createNode('COMPONENT', store.state.currentPageId, {+ name: 'Component',+ x: 120,+ y: 120,+ width: 220,+ height: 120,+ fills: [+ {+ type: 'SOLID' as const,+ color: { r: 0.85, g: 0.85, b: 0.85, a: 1 },+ opacity: 1,+ visible: true+ }+ ]+ })+ store.select([component.id])+ return component.id+ })+ await editor.canvas.waitForRender()++ 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 section.getByRole('button', { name: 'Add text layer' }).click()+ await expect(section.getByText('Ready', { exact: true })).toBeVisible()++ const instanceId = await editor.page.evaluate((id) => {+ const store = window.openPencil?.getStore?.()+ const instance = store?.graph.createInstance(id, store.state.currentPageId, { x: 120, y: 300 })+ return instance?.id ?? ''+ }, componentId)+ await startPreview()+ const field = island(instanceId).locator('textarea')+ await field.click()+ await editor.page.keyboard.press('End')+ await editor.page.keyboard.type(' typed')+ await editor.page.keyboard.press('Enter')+ await editor.page.keyboard.type('second line')+ await expect(field).toHaveValue('Text typed\nsecond line')+})diff --git a/tests/e2e/components/behaviours.spec.ts-snapshots/switch-island-on-openpencil-darwin.png b/tests/e2e/components/behaviours.spec.ts-snapshots/switch-island-on-openpencil-darwin.pngnew file mode 100644index 000000000..435a03c9aBinary files /dev/null and b/tests/e2e/components/behaviours.spec.ts-snapshots/switch-island-on-openpencil-darwin.png differdiff --git a/tests/engine/cli/eval.test.ts b/tests/engine/cli/eval.test.tsindex 113597708..4573c2a2d 100644--- a/tests/engine/cli/eval.test.ts+++ b/tests/engine/cli/eval.test.ts@@ -212,7 +212,12 @@ heavy('eval CLI', () => {})test('undefined result produces no output', async () => {- const { stdout, exitCode } = await run(['eval', FIXTURE, '--code', 'figma.createFrame()'])+ const { stdout, exitCode } = await run([+ 'eval',+ FIXTURE,+ '--code',+ 'const frame = figma.createFrame()'+ ])expect(exitCode).toBe(0)expect(stdout).toBe('')})diff --git a/tests/engine/cli/export/index.test.ts b/tests/engine/cli/export/index.test.tsindex 6f2e9af3f..f74fdc4f9 100644--- a/tests/engine/cli/export/index.test.ts+++ b/tests/engine/cli/export/index.test.ts@@ -196,7 +196,9 @@ test('export CLI writes Tailwind JSX for a page', async () => {expect(exitCode).toBe(0)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 p-4 gap-2')+ expect(jsx).toContain(+ '<div data-name="Export Card" className="flex absolute top-0 left-0 p-4 gap-2'+ )expect(jsx).not.toContain('Second Card')})diff --git a/tests/engine/figma/api/create/combine-as-variants.test.ts b/tests/engine/figma/api/create/combine-as-variants.test.tsindex cfb6d89b9..d3c6695a9 100644--- a/tests/engine/figma/api/create/combine-as-variants.test.ts+++ b/tests/engine/figma/api/create/combine-as-variants.test.ts@@ -88,3 +88,29 @@ describe('combineAsVariants', () => {expect(() => api.combineAsVariants([component, frame], api.currentPage)).toThrow()})})++describe('combineAsVariants with Property=Value names', () => {+ test('derives each named property and its values, as Figma names variants', () => {+ const api = createAPI()+ const names = ['State=Off, Size=Small', 'State=On, Size=Small', 'State=On, Size=Large']+ const components = names.map((name) => {+ const component = api.createComponent()+ component.name = name+ return component+ })++ const set = api.combineAsVariants(components, api.currentPage)+ const raw = api.graph.getNode(set.id)++ expect(+ raw?.componentPropertyDefinitions.map((item) => [item.name, item.variantOptions])+ ).toEqual([+ ['State', ['Off', 'On']],+ ['Size', ['Small', 'Large']]+ ])+ expect(api.graph.getNode(components[2].id)?.componentPropertyValues).toEqual({+ State: 'On',+ Size: 'Large'+ })+ })+})diff --git a/tools/checks/i18n/mixed-script-baseline.txt b/tools/checks/i18n/mixed-script-baseline.txtindex b39c8946f..591b4fa43 100644--- a/tools/checks/i18n/mixed-script-baseline.txt+++ b/tools/checks/i18n/mixed-script-baseline.txt@@ -115,6 +115,7 @@ ja:menu.exportSelectionAsPNGja:menu.exportSelectionAsPPTXja:menu.exportSelectionAsSVGja:menu.toggleUI+ja:panels.behaviourAddVariantsja:panels.colorHintHsbja:panels.colorHintHslja:panels.colorHintOkhcl@@ -260,6 +261,7 @@ zh-cn:menu.exportSelectionAsFigzh-cn:menu.exportSelectionAsPNGzh-cn:menu.exportSelectionAsPPTXzh-cn:menu.exportSelectionAsSVG+zh-cn:panels.behaviourAddVariantszh-cn:panels.colorHintHsbzh-cn:panels.colorHintHslzh-cn:panels.colorHintOkhcldiff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txtindex 621db7206..b4fcf3811 100644--- a/tools/checks/i18n/translation-baseline.txt+++ b/tools/checks/i18n/translation-baseline.txt@@ -44,6 +44,11 @@ de:panels.radialGradientde:panels.radiusde:panels.textCaseOriginalde:panels.slots+de:panels.behaviourTabs+de:panels.behaviourMin+de:panels.behaviourMax+de:panels.behaviourStateHover+de:panels.behaviourTextde:settings.mcpde:storage.bucketde:storage.providerAmazonS3@@ -146,6 +151,9 @@ fr:panels.saturationfr:panels.variablesfr:panels.slotsfr:panels.slotDescription+fr:panels.behaviourMin+fr:panels.behaviourMax+fr:panels.behaviourStateFocusfr:settings.animationsfr:settings.diagnosticsfr:settings.mcp@@ -183,6 +191,10 @@ it:panels.framePresetCategoryFigmaCommunityit:panels.framePresetCategorySocialMediait:panels.framePresetCategoryTabletit:panels.layout+it:panels.behaviourMin+it:panels.behaviourMax+it:panels.behaviourStateHover+it:panels.behaviourStateFocusit:rendering.settingsTitleit:settings.mcpit:settings.media@@ -233,6 +245,7 @@ pl:panels.designpl:panels.framePresetCategoryFigmaCommunitypl:panels.framePresetCategoryTabletpl:panels.kerning+pl:panels.behaviourMinpl:settings.mcppl:settings.mediapl:storage.providerAmazonS3