AI-native design editor. Open-source Figma alternative.
feat(design-jsx): set instance properties by name like variants (#1017)
Danila Poyarkov22a9302f7fed
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex aa300605a..7a0ca1369 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -39,6 +39,7 @@### Added+- Set a component's text, boolean, and swap properties on a design JSX `<Instance>` by name, as variants are set, such as `<Instance of="Card" Title="Hello" Badge={false} />`; `properties` accepts names too. An instance written this way still works after the document is saved to `.fig` and reopened, which gives each property a new ID ([#750](https://github.com/open-pencil/open-pencil/issues/750)).- Save the open document to cloud storage with **File → Save to storage…**. The tab stays bound to the stored copy, so Save and auto-save write to the bucket; before storage is configured, the command opens its settings. A new Cloud Storage guide covers connecting a bucket, CORS, syncing, and provider notes.- Add a variant to a standalone component from the header's **Add variant** button, as in Figma (#847): it becomes a component set named after it, whose existing instances and properties carry over, with a `Property 1=Variant2` copy below. A set's variant properties are rows of its **Properties** list, each opening to rename it and add, rename, reorder, or remove its values; removing a value variants still use moves them to another value. Variants that share a combination of values are named in a notice that selects them.- Create and edit a component's text, boolean, and instance swap properties from the properties panel, as in Figma (#847). A layer in a main component links its text content, visibility, or swapped component to a new or existing property from the Typography and Appearance sections and the instance header, and shows the linked property in place of the value. The component lists its properties, each opening to rename it, change its default, see and unlink the layers it drives, or delete it, and reorders them by dragging. Expose nested instances so their properties show, grouped under the instance's name, on instances of the component. Typing into text a property drives sets the property: its default in the main component, the instance's value in an instance.diff --git a/packages/core/tests/design-jsx/instance-properties.test.ts b/packages/core/tests/design-jsx/instance-properties.test.tsnew file mode 100644index 000000000..73bebb66d--- /dev/null+++ b/packages/core/tests/design-jsx/instance-properties.test.ts@@ -0,0 +1,111 @@+import { expect, test } from 'bun:test'++import { renderJSX, renderTree } from '@open-pencil/core/design-jsx'+import { exportFigFile, parseFigFile } from '@open-pencil/core/io'+import { initCodec } from '@open-pencil/core/kiwi'+import { Component, Instance, Text } from '@open-pencil/design-jsx'+import { SceneGraph } from '@open-pencil/scene-graph'++const CARD = `+<ComponentSet name="Card" properties={[+ { id: "title", name: "Title", type: "TEXT", defaultValue: "Default title" },+ { id: "badge", name: "Badge", type: "BOOLEAN", defaultValue: "true" }+]}>+ <Component name="state=default">+ <Text propertyRefs={[{ propertyId: "title", field: "TEXT" }]}>Default title</Text>+ <Text propertyRefs={[{ propertyId: "badge", field: "VISIBLE" }]}>New</Text>+ </Component>+ <Component name="state=selected">+ <Text propertyRefs={[{ propertyId: "title", field: "TEXT" }]}>Default title</Text>+ <Text propertyRefs={[{ propertyId: "badge", field: "VISIBLE" }]}>New</Text>+ </Component>+</ComponentSet>`++async function reopenedCard(): Promise<SceneGraph> {+ await initCodec()+ const graph = new SceneGraph()+ await renderJSX(graph, CARD)+ return parseFigFile((await exportFigFile(graph)).slice().buffer, { populate: 'first-page' })+}++function layers(graph: SceneGraph, instance: { id: string }) {+ return graph.getChildren(instance.id).map((child) => [child.text, child.visible])+}++test('sets component properties by name, like variants, after a .fig reload', async () => {+ const graph = await reopenedCard()+ const [instance] = await renderJSX(+ graph,+ `<Instance of="Card" state="selected" Title="Hello" Badge={false} />`+ )+ expect(instance.warnings).toBeUndefined()+ expect(graph.getNode(instance.id)?.name).toBe('state=selected')+ expect(layers(graph, instance)).toEqual([+ ['Hello', true],+ ['New', false]+ ])+})++test('assigns properties by ID or by name', async () => {+ const graph = await reopenedCard()+ const set = [...graph.getAllNodes()].find((node) => node.type === 'COMPONENT_SET')+ const title = set?.componentPropertyDefinitions.find((item) => item.name === 'Title')+ if (!title) throw new Error('Missing Title property')+ expect(title.id).not.toBe('title')++ for (const key of [title.id, 'Title']) {+ const [instance] = await renderJSX(+ graph,+ `<Instance of="Card" properties={{ ${JSON.stringify(key)}: "By ${key}" }} />`+ )+ expect(layers(graph, instance)[0]).toEqual([`By ${key}`, true])+ }+ await expect(+ renderJSX(graph, `<Instance of="Card" properties={{ title: "Hello" }} />`)+ ).rejects.toThrow('Unknown component property: title')+})++test('properties prefers an ID; a prop always names the property', async () => {+ const graph = new SceneGraph()+ const component = await renderTree(+ graph,+ Component({+ name: 'Note',+ properties: [+ { id: 'label', name: 'Title', type: 'TEXT', defaultValue: 'Label' },+ { id: 'Title', name: 'Heading', type: 'TEXT', defaultValue: 'Heading' }+ ],+ children: Text({+ children: 'Label',+ propertyRefs: [{ propertyId: 'label', field: 'TEXT' }]+ })+ })+ )+ const instance = await renderTree(+ graph,+ Instance({ of: component.id, properties: { Title: 'Changed' } })+ )+ expect(graph.getChildren(instance.id)[0]?.text).toBe('Label')+ expect(graph.getNode(instance.id)?.componentPropertyAssignments).toEqual({ Title: 'Changed' })++ const named = await renderTree(graph, Instance({ of: component.id, Title: 'By name' }))+ expect(graph.getChildren(named.id)[0]?.text).toBe('By name')+ expect(graph.getNode(named.id)?.componentPropertyAssignments).toEqual({ label: 'By name' })+})++test('rejects a property name that more than one property has', async () => {+ const graph = new SceneGraph()+ const component = await renderTree(+ graph,+ Component({+ name: 'Note',+ properties: [+ { id: 'a', name: 'Title', type: 'TEXT', defaultValue: 'A' },+ { id: 'b', name: 'Title', type: 'TEXT', defaultValue: 'B' }+ ]+ })+ )+ await expect(renderTree(graph, Instance({ of: component.id, Title: 'Changed' }))).rejects.toThrow(+ 'Component property name Title is ambiguous; use one of the IDs: a, b'+ )+})diff --git a/packages/design-jsx/src/component-properties.ts b/packages/design-jsx/src/component-properties.tsindex f78cd7524..813e5995e 100644--- a/packages/design-jsx/src/component-properties.ts+++ b/packages/design-jsx/src/component-properties.ts@@ -8,6 +8,7 @@ import type {SceneNode} from '@open-pencil/scene-graph'+import { DESIGN_JSX_SUPPORTED_PROPERTIES } from './schema'import { parseScriptInput } from './validation'const definitionSchema = v.object({@@ -92,6 +93,60 @@ export function componentPropertyScope(return undefined}+/** The one property with this name; a name several properties share is an error. */+function namedDefinition(+ definitions: readonly ComponentPropertyDefinition[],+ name: string+): ComponentPropertyDefinition | undefined {+ const matches = definitions.filter((item) => item.name === name)+ if (matches.length > 1)+ throw new Error(+ `Component property name ${name} is ambiguous; use one of the IDs: ${matches.map((item) => item.id).join(', ')}`+ )+ return matches[0]+}++function assignValue(+ graph: SceneGraph,+ instance: SceneNode,+ definition: ComponentPropertyDefinition,+ key: string,+ value: string+): void {+ if (definition.type === 'VARIANT')+ throw new Error('Select a component-set variant when creating the instance')+ if (definition.type === 'BOOLEAN' && value !== 'true' && value !== 'false')+ throw new Error(`Expected true or false for component property: ${key}`)+ if (!applyComponentPropertyValue(graph, instance.id, definition, value))+ throw new Error(`Cannot assign component property: ${key}`)+}++/**+ * Set text, boolean, and swap properties an instance names as props, as in+ * `Title="Hello"`, the way it picks a variant; design JSX props keep their meaning.+ */+export function assignNamedProperties(+ graph: SceneGraph,+ instance: SceneNode,+ props: Record<string, unknown>+): void {+ const definitions = componentPropertyDefinitions(graph, instance).filter(+ (definition) => definition.type !== 'VARIANT'+ )+ for (const [key, value] of Object.entries(props)) {+ if (DESIGN_JSX_SUPPORTED_PROPERTIES.has(key)) continue+ const definition = namedDefinition(definitions, key)+ if (!definition) continue+ if (typeof value !== 'string' && typeof value !== 'boolean' && typeof value !== 'number')+ throw new Error(`Expected a string or boolean for component property: ${key}`)+ assignValue(graph, instance, definition, key, String(value))+ }+}++/**+ * Keys are property IDs or, because saving to `.fig` replaces authored IDs+ * with GUIDs, names, which survive a reload.+ */export function assignComponentProperties(graph: SceneGraph,instance: SceneNode,@@ -104,14 +159,10 @@ export function assignComponentProperties(input)const definitions = componentPropertyDefinitions(graph, instance)- for (const [id, value] of Object.entries(assignments)) {- const definition = definitions.find((item) => item.id === id)- if (!definition) throw new Error(`Unknown component property: ${id}`)- if (definition.type === 'VARIANT')- throw new Error('Select a component-set variant when creating the instance')- if (definition.type === 'BOOLEAN' && value !== 'true' && value !== 'false')- throw new Error(`Expected true or false for component property: ${id}`)- if (!applyComponentPropertyValue(graph, instance.id, definition, value))- throw new Error(`Cannot assign component property: ${id}`)+ for (const [key, value] of Object.entries(assignments)) {+ const definition =+ definitions.find((item) => item.id === key) ?? namedDefinition(definitions, key)+ if (!definition) throw new Error(`Unknown component property: ${key}`)+ assignValue(graph, instance, definition, key, value)}}diff --git a/packages/design-jsx/src/reference/authoring.md b/packages/design-jsx/src/reference/authoring.mdindex a26d8ea17..fc2eb89bf 100644--- a/packages/design-jsx/src/reference/authoring.md+++ b/packages/design-jsx/src/reference/authoring.md@@ -33,9 +33,9 @@ This reference describes scene creation, not React DOM output. Use the `render`- `bind` maps supported scene-field paths to variable IDs or references when no shorthand exists. Use semantic tokens consistently rather than declaring unused collections.- A reusable JavaScript function shares source code, not component identity. Use `Component`, `ComponentSet`, and `Instance` for editable main components and linked instances.- `Instance` resolves an existing component through `of`, `component`, or `componentId`. Component-set children named `variant=Primary`, for example, define variants that can be selected when instantiating the set.-- `Component` and `ComponentSet` accept `properties`, an array of native property definitions (`id`, `name`, `type`, `defaultValue`). `Instance` accepts `properties`, an ID-to-value assignment object. Ordinary nodes do not accept `properties`.+- `Component` and `ComponentSet` accept `properties`, an array of native property definitions (`id`, `name`, `type`, `defaultValue`). An `Instance` sets text, boolean, and swap properties by name, the way it picks a variant: `<Instance of="Note" State="Done" Message="Updated review" Pinned={false} />`. `properties` takes the same values keyed by property ID or name, for names that are not JSX identifiers or that design JSX already uses, such as `name`. Names survive a `.fig` save, which replaces authored IDs such as `message` with Figma IDs. Ordinary nodes do not accept `properties`.- Child `propertyRefs` connect fields to stable property IDs, for example `[{ propertyId: 'message', field: 'TEXT' }]`. Supported fields are `TEXT`, `VISIBLE`, and `INSTANCE_SWAP`; text and swap references require text and instance nodes respectively. References do not depend on layer names.-- Instance assignments use the native string values (including `'true'` / `'false'` for BOOLEAN properties and component IDs for swaps). For example `Instance({ of: noteId, properties: { message: 'Updated review' } })`. Assignments persist through component synchronization; unknown IDs and invalid values fail rather than silently creating inert overrides. Select variants through component-set variant props, not through instance property assignments.+- Instance assignments use the native string values (`'true'` / `'false'` for BOOLEAN properties and component IDs for swaps), and a property set as a prop also takes `true` / `false`, as in `Pinned={false}`. Assignments persist through component synchronization; unknown IDs and invalid values fail rather than silently creating inert overrides. Select variants through component-set variant props, not through instance property assignments.- 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.diff --git a/packages/design-jsx/src/render.ts b/packages/design-jsx/src/render.tsindex 2c00415a4..e97fea5b0 100644--- a/packages/design-jsx/src/render.ts+++ b/packages/design-jsx/src/render.ts@@ -6,7 +6,7 @@ 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, variantPropNames, type RenderResult } from './renderer'+import { renderRoots, renderTree, componentPropNames, type RenderResult } from './renderer'import { DESIGN_JSX_SUPPORTED_PROPERTIES } from './schema'import type { DesignJSXServices } from './services'import { isTreeNode, resolveToTree, type TreeNode } from './tree'@@ -46,10 +46,10 @@ function collectUnsupportedPropWarnings(warnings: string[]): void {const supportedProps = tree.type === 'svg' ? SVG_ROOT_PROPS : SUPPORTED_PROPS- // An instance chooses its variant by the set's variant properties, such as `State="On"`.- const variants = variantPropNames(graph, tree.props)+ // An instance sets its component's properties by name, such as `State="On"` or `Title="Hi"`.+ const properties = componentPropNames(graph, tree.props)for (const key of Object.keys(tree.props)) {- if (!supportedProps.has(key) && !variants.includes(key)) {+ if (!supportedProps.has(key) && !properties.includes(key)) {warnings.push(`Unsupported prop "${key}" on <${tree.type}> is ignored.`)}}diff --git a/packages/design-jsx/src/renderer.ts b/packages/design-jsx/src/renderer.tsindex b167c5801..a5803c42c 100644--- a/packages/design-jsx/src/renderer.ts+++ b/packages/design-jsx/src/renderer.ts@@ -16,6 +16,7 @@ import { renderRekaNode } from './behaviours/render'import {assignComponentProperties,componentMetadata,+ assignNamedProperties,componentPropertyScope} from './component-properties'import { applySizeOverrides, propsToOverrides } from './props-overrides'@@ -403,13 +404,11 @@ function resolveComponent(return named?.type === 'COMPONENT_SET' ? findVariantInSet(graph, named, props) : named}-/** The variant properties an element chooses its component's variant by, such as `State`. */-export function variantPropNames(graph: SceneGraph, props: Record<string, unknown>): string[] {- const named = namedComponent(graph, props)- if (named?.type !== 'COMPONENT_SET') return []- return named.componentPropertyDefinitions- .filter((definition) => definition.type === 'VARIANT')- .map((definition) => definition.name)+/** The component properties an element sets by name, such as `State` or `Title`. */+export function componentPropNames(graph: SceneGraph, props: Record<string, unknown>): string[] {+ const component = resolveComponent(graph, props)+ if (!component) return []+ return (componentPropertyScope(graph, component.id) ?? []).map((definition) => definition.name)}async function renderInstanceNode(@@ -456,6 +455,7 @@ async function renderInstanceNode(graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })applyBindings(graph, instance.id, bindings)applyInstanceOverrides(graph, instance, tree.props.overrides)+ assignNamedProperties(graph, instance, props)assignComponentProperties(graph, instance, props.properties)return instance} catch (error) {diff --git a/packages/docs/reference/design-authoring.md b/packages/docs/reference/design-authoring.mdindex 7d2737972..ad12e1daf 100644--- a/packages/docs/reference/design-authoring.md+++ b/packages/docs/reference/design-authoring.md@@ -35,9 +35,9 @@ This reference describes scene creation, not React DOM output. Use the `render`- `bind` maps supported scene-field paths to variable IDs or references when no shorthand exists. Use semantic tokens consistently rather than declaring unused collections.- A reusable JavaScript function shares source code, not component identity. Use `Component`, `ComponentSet`, and `Instance` for editable main components and linked instances.- `Instance` resolves an existing component through `of`, `component`, or `componentId`. Component-set children named `variant=Primary`, for example, define variants that can be selected when instantiating the set.-- `Component` and `ComponentSet` accept `properties`, an array of native property definitions (`id`, `name`, `type`, `defaultValue`). `Instance` accepts `properties`, an ID-to-value assignment object. Ordinary nodes do not accept `properties`.+- `Component` and `ComponentSet` accept `properties`, an array of native property definitions (`id`, `name`, `type`, `defaultValue`). An `Instance` sets text, boolean, and swap properties by name, the way it picks a variant: `<Instance of="Note" State="Done" Message="Updated review" Pinned={false} />`. `properties` takes the same values keyed by property ID or name, for names that are not JSX identifiers or that design JSX already uses, such as `name`. Names survive a `.fig` save, which replaces authored IDs such as `message` with Figma IDs. Ordinary nodes do not accept `properties`.- Child `propertyRefs` connect fields to stable property IDs, for example `[{ propertyId: 'message', field: 'TEXT' }]`. Supported fields are `TEXT`, `VISIBLE`, and `INSTANCE_SWAP`; text and swap references require text and instance nodes respectively. References do not depend on layer names.-- Instance assignments use the native string values (including `'true'` / `'false'` for BOOLEAN properties and component IDs for swaps). For example `Instance({ of: noteId, properties: { message: 'Updated review' } })`. Assignments persist through component synchronization; unknown IDs and invalid values fail rather than silently creating inert overrides. Select variants through component-set variant props, not through instance property assignments.+- Instance assignments use the native string values (`'true'` / `'false'` for BOOLEAN properties and component IDs for swaps), and a property set as a prop also takes `true` / `false`, as in `Pinned={false}`. Assignments persist through component synchronization; unknown IDs and invalid values fail rather than silently creating inert overrides. Select variants through component-set variant props, not through instance property assignments.- 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.diff --git a/skills/open-pencil/references/design-authoring.md b/skills/open-pencil/references/design-authoring.mdindex 7d2737972..ad12e1daf 100644--- a/skills/open-pencil/references/design-authoring.md+++ b/skills/open-pencil/references/design-authoring.md@@ -35,9 +35,9 @@ This reference describes scene creation, not React DOM output. Use the `render`- `bind` maps supported scene-field paths to variable IDs or references when no shorthand exists. Use semantic tokens consistently rather than declaring unused collections.- A reusable JavaScript function shares source code, not component identity. Use `Component`, `ComponentSet`, and `Instance` for editable main components and linked instances.- `Instance` resolves an existing component through `of`, `component`, or `componentId`. Component-set children named `variant=Primary`, for example, define variants that can be selected when instantiating the set.-- `Component` and `ComponentSet` accept `properties`, an array of native property definitions (`id`, `name`, `type`, `defaultValue`). `Instance` accepts `properties`, an ID-to-value assignment object. Ordinary nodes do not accept `properties`.+- `Component` and `ComponentSet` accept `properties`, an array of native property definitions (`id`, `name`, `type`, `defaultValue`). An `Instance` sets text, boolean, and swap properties by name, the way it picks a variant: `<Instance of="Note" State="Done" Message="Updated review" Pinned={false} />`. `properties` takes the same values keyed by property ID or name, for names that are not JSX identifiers or that design JSX already uses, such as `name`. Names survive a `.fig` save, which replaces authored IDs such as `message` with Figma IDs. Ordinary nodes do not accept `properties`.- Child `propertyRefs` connect fields to stable property IDs, for example `[{ propertyId: 'message', field: 'TEXT' }]`. Supported fields are `TEXT`, `VISIBLE`, and `INSTANCE_SWAP`; text and swap references require text and instance nodes respectively. References do not depend on layer names.-- Instance assignments use the native string values (including `'true'` / `'false'` for BOOLEAN properties and component IDs for swaps). For example `Instance({ of: noteId, properties: { message: 'Updated review' } })`. Assignments persist through component synchronization; unknown IDs and invalid values fail rather than silently creating inert overrides. Select variants through component-set variant props, not through instance property assignments.+- Instance assignments use the native string values (`'true'` / `'false'` for BOOLEAN properties and component IDs for swaps), and a property set as a prop also takes `true` / `false`, as in `Pinned={false}`. Assignments persist through component synchronization; unknown IDs and invalid values fail rather than silently creating inert overrides. Select variants through component-set variant props, not through instance property assignments.- 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.