Skip to content

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

feat: author component properties in the properties panel (#986)

Danila Poyarkov2cd9135161f0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8618f96db..81ce7a52b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@
### Breaking changes
+- `SceneNode` from `@open-pencil/scene-graph` has `isExposedInstance`, whether an instance inside a component shows its properties on instances of that component, so code that builds `SceneNode` objects itself must include it. In the plugin API, `isExposedInstance` and `exposedInstances` follow that flag and Figma's rules instead of treating an instance whose swap is bound to a property as exposed: only an instance in a component's own layers whose component has properties can be exposed, and its copies in instances report it but cannot change it.
- `usePosition` from `@open-pencil/vue` reports and edits `x`, `y`, and `rotation` as Figma's properties panel does: the turned layer's box on the canvas, measured from its frame or page, and its counterclockwise angle. `getDefaultCanvasBgColor` and `CANVAS_BG_COLOR_DARK` are removed from `@open-pencil/core/constants`; new pages use `PAGE_DEFAULT_BACKGROUNDS`, keyed by interface theme.
- `SkiaRenderer.hitTestFrameTitle` no longer takes the selected IDs: it finds the name of any frame on the page or in a section under a point, selected or not.
- `SceneNode` from `@open-pencil/scene-graph` has `strokeWeight` and `strokeAlign`, the stroke weight and alignment a layer keeps without strokes, so code that builds `SceneNode` objects itself must include them. `SECTION_DEFAULT_FILL` from `@open-pencil/core/constants` is replaced by `SECTION_DEFAULT_FILLS`, keyed by interface theme.
@@ -36,6 +37,7 @@
### Added
+- 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.
- Attach images to an AI chat message by dropping them anywhere on the chat panel: an outline over the composer shows where they go, or why they cannot be attached while a reply is running or four images are already attached. SVG images are drawn as PNGs when dropped, pasted, or chosen. Documents dropped on the chat still open in a new tab.
- Share only the selected layers with MCP clients: **Share only the selection** under **Settings → MCP → Local server**, or `OPENPENCIL_MCP_SCOPE=selection` for a server you start yourself, limits clients to `get_selection`, `get_node`, `get_page_tree`, `describe`, and `export_image` on the selected layers and what they hold, enforced by the server for MCP sessions, stdio clients, and `/rpc` alike.
- Set up AI in a few steps with guided setup. On first launch OpenPencil asks what AI should help with and what you already use: a coding agent on this computer (Claude Code, Codex, Gemini CLI, or Pi, in the desktop app), an API account (Anthropic, OpenAI, Google AI, OpenRouter, DeepSeek, Z.ai, or MiniMax), or a local or company server such as Ollama or LM Studio. Sign in to OpenRouter from the browser or the desktop app instead of pasting a key. In the desktop app, setup checks whether the agent, its OpenPencil adapter, OpenPencil's MCP server, and Pi's Harness companion are installed and match the app, installs or updates them with one click through npm, and links a [setup guide](https://openpencil.dev/programmable/coding-agents) or copies a prompt that asks the agent to set itself up. Setup tests each connection, proposes a model for each role that you can change, and keeps anything configured by hand. Skip it to start designing, or run it again from **Settings → AI & agents**.
@@ -126,6 +128,9 @@
### Fixed
+- Keep a Figma file's exposed nested instances when it is saved from OpenPencil; their properties stopped showing on the outer component's instances in Figma.
+- Offer only components that fit in an instance swap's list: one that would contain itself, such as the component the swapped layer sits in, is left out, and a variant is named with its set, as in `Badge / State=Info`.
+- Undo a change to a property that drives several layers of an instance on all of them, and show an instance's value on a layer linked to that property after the instance was made.
- Open S3 storage documents and show their previews on servers that answer a byte-range read with `200` instead of `206`, such as `rclone serve s3`. Previews failed to load, and the browser cached the partial reply as the whole document, so opening it failed with "Invalid fig-kiwi container". Storage requests now skip the browser cache, and a `200` whose `Content-Range` matches the request is accepted.
- Keep a layer's `.fig` ID the same across saves (#890). Layers created in OpenPencil were numbered in tree order on each save until the file was reopened, so inserting a layer shifted the IDs of the layers after it; variable collections and modes could also be renumbered.
- Store crash recovery snapshots of any size. Snapshots of documents over 127 MiB failed to save to IndexedDB and stayed in memory for the rest of the session.
diff --git a/packages/core/src/editor/bridges/components.ts b/packages/core/src/editor/bridges/components.ts
index 92b60fadd..d91bbd4ce 100644
--- a/packages/core/src/editor/bridges/components.ts
+++ b/packages/core/src/editor/bridges/components.ts
@@ -61,6 +61,17 @@ export function createComponentBridge(
getInstanceComponentPropertyDefinitions: components.getInstanceComponentPropertyDefinitions,
getInstanceComponentPropertyValue: components.getInstanceComponentPropertyValue,
setInstanceComponentProperty: components.setInstanceComponentProperty,
+ getComponentPropertyAuthoring: components.getComponentPropertyAuthoring,
+ getComponentPropertyBindings: components.getComponentPropertyBindings,
+ getExposableInstances: components.getExposableInstances,
+ createComponentProperty: components.createComponentProperty,
+ exposeComponentProperty: components.exposeComponentProperty,
+ bindComponentProperty: components.bindComponentProperty,
+ renameComponentProperty: components.renameComponentProperty,
+ setComponentPropertyDefault: components.setComponentPropertyDefault,
+ deleteComponentProperty: components.deleteComponentProperty,
+ moveComponentProperty: components.moveComponentProperty,
+ setInstanceExposed: components.setInstanceExposed,
resetSlot: components.resetSlot,
clearSlot: components.clearSlot,
addInstanceToSlot: components.addInstanceToSlot
diff --git a/packages/core/src/editor/components.ts b/packages/core/src/editor/components.ts
index 6eadcefb0..b75f7ab01 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 { createComponentAuthoringActions } from './components/authoring'
import { createBehaviourActions } from './components/behaviours'
import { becomesComponent, componentWrapProps } from './components/create'
import { createComponentFocusActions } from './components/focus'
@@ -87,6 +88,7 @@ export function createComponentActions(ctx: EditorContext) {
...variantActions,
...componentPropertyActions,
...createSlotActions(ctx),
+ ...createComponentAuthoringActions(ctx),
...createSlotAuthoringActions(ctx),
...createBehaviourActions(ctx, variantActions)
}
diff --git a/packages/core/src/editor/components/authoring/context.ts b/packages/core/src/editor/components/authoring/context.ts
new file mode 100644
index 000000000..d0d2fe428
--- /dev/null
+++ b/packages/core/src/editor/components/authoring/context.ts
@@ -0,0 +1,96 @@
+import type {
+ ComponentPropertyReferenceField,
+ SceneGraph,
+ SceneNode
+} from '@open-pencil/scene-graph'
+
+import { getNodeEditCapability } from '#core/editor/capabilities'
+
+export type ExposableComponentField = Exclude<ComponentPropertyReferenceField, 'SLOT_CONTENT'>
+
+export const COMPONENT_FIELD_TYPES = {
+ TEXT: 'TEXT',
+ VISIBLE: 'BOOLEAN',
+ INSTANCE_SWAP: 'INSTANCE_SWAP'
+} as const
+
+/** Instance descendants belong to their source component, not the enclosing definition. */
+export function componentAuthoringContext(graph: SceneGraph, nodeId: string) {
+ const node = graph.getNode(nodeId)
+ if (!node) return null
+ let component: SceneNode | undefined = node
+ if (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET') {
+ component = node.parentId
+ ? graph.closest(
+ node.parentId,
+ (item) => item.type === 'COMPONENT' || item.type === 'INSTANCE'
+ )
+ : undefined
+ }
+ if (!component || component.type === 'INSTANCE') return null
+ const parent = component.parentId ? graph.getNode(component.parentId) : undefined
+ const owner = parent?.type === 'COMPONENT_SET' ? parent : component
+ const owners = owner.id === component.id ? [owner] : [owner, component]
+ const fields: ExposableComponentField[] = []
+ if (node.id !== component.id) {
+ fields.push('VISIBLE')
+ if (node.type === 'TEXT') fields.push('TEXT')
+ if (node.type === 'INSTANCE') fields.push('INSTANCE_SWAP')
+ }
+ return {
+ node,
+ component,
+ owner,
+ owners,
+ fields,
+ editable: getNodeEditCapability(graph, node.id).editable
+ }
+}
+
+export function componentBindingNodes(graph: SceneGraph, ownerId: string): SceneNode[] {
+ const nodes: SceneNode[] = []
+ const visit = (id: string) => {
+ for (const child of graph.getChildren(id)) {
+ nodes.push(child)
+ if (child.type !== 'INSTANCE') visit(child.id)
+ }
+ }
+ visit(ownerId)
+ return nodes
+}
+
+export function componentFieldValue(node: SceneNode, field: ExposableComponentField): string {
+ if (field === 'TEXT') return node.text
+ if (field === 'VISIBLE') return String(node.visible)
+ return node.componentId ?? ''
+}
+
+export function componentPropertyNameExists(
+ graph: SceneGraph,
+ owner: SceneNode,
+ name: string,
+ exceptId?: string
+): boolean {
+ const scopes = [owner]
+ const parent = owner.parentId ? graph.getNode(owner.parentId) : undefined
+ if (parent?.type === 'COMPONENT_SET') scopes.push(parent)
+ if (owner.type === 'COMPONENT_SET') {
+ scopes.push(...graph.getChildren(owner.id).filter((node) => node.type === 'COMPONENT'))
+ }
+ return scopes.some((scope) =>
+ scope.componentPropertyDefinitions.some(
+ (definition) => definition.id !== exceptId && definition.name === name
+ )
+ )
+}
+
+/** The source layers and fields controlled by one component property. */
+export function componentPropertySources(graph: SceneGraph, ownerId: string, propertyId: string) {
+ return componentBindingNodes(graph, ownerId).flatMap((node) =>
+ node.componentPropertyReferences
+ .filter(
+ (reference) => reference.propertyId === propertyId && reference.field !== 'SLOT_CONTENT'
+ )
+ .map((reference) => ({ node, field: reference.field as ExposableComponentField }))
+ )
+}
diff --git a/packages/core/src/editor/components/authoring/index.ts b/packages/core/src/editor/components/authoring/index.ts
new file mode 100644
index 000000000..47057449e
--- /dev/null
+++ b/packages/core/src/editor/components/authoring/index.ts
@@ -0,0 +1,304 @@
+import { isEqual } from 'es-toolkit'
+
+import {
+ createComponentPropertyId,
+ exposableInstances,
+ instanceExposureIssue,
+ removeComponentProperty,
+ resolveComponentPropertyValue
+} from '@open-pencil/scene-graph'
+import type { ComponentPropertyDefinition, SceneNode } from '@open-pencil/scene-graph'
+
+import { assertNodeEditable } from '#core/editor/capabilities'
+import { reorderPropertyDefinitions } from '#core/editor/components/variants/definitions'
+import type { EditorContext } from '#core/editor/types'
+
+import {
+ COMPONENT_FIELD_TYPES,
+ componentAuthoringContext,
+ componentBindingNodes,
+ componentPropertySources,
+ componentFieldValue,
+ componentPropertyNameExists,
+ type ExposableComponentField
+} from './context'
+import { createAuthoringValueActions } from './values'
+
+/** Property types a layer field can drive; variants and slots have their own authoring. */
+const AUTHORED_TYPES = new Set<ComponentPropertyDefinition['type']>([
+ 'TEXT',
+ 'BOOLEAN',
+ 'INSTANCE_SWAP'
+])
+
+type PropertyMetadata = Pick<
+ SceneNode,
+ 'componentPropertyDefinitions' | 'componentPropertyReferences' | 'componentPropertyAssignments'
+>
+
+function metadata(node: SceneNode): PropertyMetadata {
+ return structuredClone({
+ componentPropertyDefinitions: node.componentPropertyDefinitions,
+ componentPropertyReferences: node.componentPropertyReferences,
+ componentPropertyAssignments: node.componentPropertyAssignments
+ })
+}
+
+/** Move one item within the subset `movable` selects, leaving the others where they are. */
+function moveWithin(ids: string[], movable: Set<string>, sourceId: string, index: number) {
+ const subset = ids.filter((id) => movable.has(id))
+ const from = subset.indexOf(sourceId)
+ if (from === -1 || index < 0 || index >= subset.length) return null
+ subset.splice(from, 1)
+ subset.splice(index, 0, sourceId)
+ let next = 0
+ return ids.map((id) => (movable.has(id) ? subset[next++] : id))
+}
+
+/** Create, link, edit and remove a main component's text, boolean and swap properties. */
+export function createComponentAuthoringActions(ctx: EditorContext) {
+ function patch(id: string, changes: Partial<SceneNode>, label: string) {
+ const node = ctx.graph.getNode(id)
+ if (!node) return
+ const before = Object.fromEntries(
+ Object.keys(changes).map((key) => [key, structuredClone(node[key as keyof SceneNode])])
+ )
+ const apply = (values: Partial<SceneNode>) => {
+ ctx.graph.updateNode(id, structuredClone(values))
+ if ('text' in values || 'visible' in values) ctx.runLayoutForNode(id)
+ ctx.requestRender()
+ }
+ ctx.undo.execute({
+ label,
+ forward: () => apply(changes),
+ inverse: () => apply(before)
+ })
+ }
+
+ const sourceValues = createAuthoringValueActions(ctx, patch)
+
+ function bindingContext(nodeId: string, field: ExposableComponentField) {
+ const context = componentAuthoringContext(ctx.graph, nodeId)
+ if (!context?.fields.includes(field)) return null
+ assertNodeEditable(ctx.graph, nodeId)
+ assertNodeEditable(ctx.graph, context.owner.id)
+ return context
+ }
+
+ function bindComponentProperty(
+ nodeId: string,
+ field: ExposableComponentField,
+ propertyId: string | null
+ ): boolean {
+ const context = bindingContext(nodeId, field)
+ if (!context) return false
+ const { node, owners } = context
+ const definition = owners
+ .flatMap((item) => item.componentPropertyDefinitions)
+ .find((item) => item.id === propertyId)
+ if (propertyId && definition?.type !== COMPONENT_FIELD_TYPES[field]) return false
+ if (definition && !sourceValues.accepts(node, field, definition.defaultValue)) return false
+ const references = node.componentPropertyReferences.filter((item) => item.field !== field)
+ if (propertyId) references.push({ propertyId, field })
+ if (isEqual(references, node.componentPropertyReferences)) return true
+
+ ctx.undo.runBatch(propertyId ? 'Link component property' : 'Detach component property', () => {
+ patch(nodeId, { componentPropertyReferences: references }, 'Link component property')
+ // A linked layer shows the property's default, as every instance without a value does.
+ if (definition) sourceValues.apply(node, field, definition.defaultValue)
+ })
+ return true
+ }
+
+ function createComponentProperty(
+ ownerId: string,
+ name: string,
+ type: ComponentPropertyDefinition['type'],
+ defaultValue: string
+ ): string | null {
+ const owner = ctx.graph.getNode(ownerId)
+ if (owner?.type !== 'COMPONENT' && owner?.type !== 'COMPONENT_SET') return null
+ assertNodeEditable(ctx.graph, ownerId)
+ const normalizedName = name.trim()
+ if (!normalizedName || componentPropertyNameExists(ctx.graph, owner, normalizedName))
+ return null
+ if (!AUTHORED_TYPES.has(type)) return null
+ if (type === 'BOOLEAN' && defaultValue !== 'true' && defaultValue !== 'false') return null
+ if (type === 'INSTANCE_SWAP' && !resolveComponentPropertyValue(ctx.graph, defaultValue))
+ return null
+ const id = createComponentPropertyId()
+ const definition: ComponentPropertyDefinition = { id, name: normalizedName, type, defaultValue }
+ patch(
+ ownerId,
+ { componentPropertyDefinitions: [...owner.componentPropertyDefinitions, definition] },
+ 'Create component property'
+ )
+ return id
+ }
+
+ /** Create a property from a layer field, defaulting to what the layer shows, and link it. */
+ function exposeComponentProperty(
+ nodeId: string,
+ field: ExposableComponentField,
+ name: string
+ ): string | null {
+ const context = bindingContext(nodeId, field)
+ if (!context) return null
+ let id: string | null = null
+ ctx.undo.runBatch('Create component property', () => {
+ id = createComponentProperty(
+ context.owner.id,
+ name,
+ COMPONENT_FIELD_TYPES[field],
+ componentFieldValue(context.node, field)
+ )
+ if (id) bindComponentProperty(nodeId, field, id)
+ })
+ return id
+ }
+
+ function editableProperty(ownerId: string, propertyId: string) {
+ const owner = ctx.graph.getNode(ownerId)
+ if (owner?.type !== 'COMPONENT' && owner?.type !== 'COMPONENT_SET') return null
+ assertNodeEditable(ctx.graph, ownerId)
+ const definition = owner.componentPropertyDefinitions.find((item) => item.id === propertyId)
+ return definition && AUTHORED_TYPES.has(definition.type) ? { owner, definition } : null
+ }
+
+ function renameComponentProperty(ownerId: string, propertyId: string, name: string): boolean {
+ const editable = editableProperty(ownerId, propertyId)
+ const normalizedName = name.trim()
+ if (
+ !editable ||
+ !normalizedName ||
+ componentPropertyNameExists(ctx.graph, editable.owner, normalizedName, propertyId)
+ )
+ return false
+ const { owner, definition } = editable
+ if (definition.name === normalizedName) return true
+ patch(
+ ownerId,
+ {
+ componentPropertyDefinitions: owner.componentPropertyDefinitions.map((item) =>
+ item.id === propertyId ? { ...item, name: normalizedName } : item
+ )
+ },
+ 'Rename component property'
+ )
+ return true
+ }
+
+ /** The property's one default, shown by every linked layer and every instance without a value. */
+ function setComponentPropertyDefault(
+ ownerId: string,
+ propertyId: string,
+ value: string
+ ): boolean {
+ const editable = editableProperty(ownerId, propertyId)
+ if (!editable) return false
+ const { owner, definition } = editable
+ if (definition.type === 'BOOLEAN' && value !== 'true' && value !== 'false') return false
+ if (definition.type === 'INSTANCE_SWAP' && !resolveComponentPropertyValue(ctx.graph, value))
+ return false
+ const targets = componentPropertySources(ctx.graph, ownerId, propertyId)
+ if (targets.some(({ node, field }) => !sourceValues.accepts(node, field, value))) return false
+ for (const { node } of targets) assertNodeEditable(ctx.graph, node.id)
+ if (definition.defaultValue === value) return true
+ ctx.undo.runBatch('Change component property default', () => {
+ patch(
+ ownerId,
+ {
+ componentPropertyDefinitions: owner.componentPropertyDefinitions.map((item) =>
+ item.id === propertyId ? { ...item, defaultValue: value } : item
+ )
+ },
+ 'Change component property default'
+ )
+ for (const { node, field } of targets) sourceValues.apply(node, field, value)
+ })
+ return true
+ }
+
+ function deleteComponentProperty(ownerId: string, propertyId: string): boolean {
+ if (!editableProperty(ownerId, propertyId)) return false
+ const affected = [...ctx.graph.getAllNodes()].filter(
+ (node) =>
+ node.id === ownerId ||
+ node.componentPropertyReferences.some((reference) => reference.propertyId === propertyId) ||
+ Object.hasOwn(node.componentPropertyAssignments, propertyId)
+ )
+ const before = new Map(affected.map((node) => [node.id, metadata(node)]))
+ removeComponentProperty(ctx.graph, ownerId, propertyId)
+ const after = new Map(affected.map((node) => [node.id, metadata(node)]))
+ const apply = (values: Map<string, PropertyMetadata>) => {
+ for (const [id, value] of values) ctx.graph.updateNode(id, structuredClone(value))
+ ctx.requestRender()
+ }
+ ctx.undo.push({
+ label: 'Delete component property',
+ forward: () => apply(after),
+ inverse: () => apply(before)
+ })
+ ctx.requestRender()
+ return true
+ }
+
+ /** Move a text, boolean or swap property among its siblings; `.fig` keeps the order. */
+ function moveComponentProperty(ownerId: string, propertyId: string, index: number): boolean {
+ const editable = editableProperty(ownerId, propertyId)
+ if (!editable) return false
+ const { owner } = editable
+ const ids = owner.componentPropertyDefinitions.map((definition) => definition.id)
+ const movable = new Set(
+ owner.componentPropertyDefinitions
+ .filter((definition) => AUTHORED_TYPES.has(definition.type))
+ .map((definition) => definition.id)
+ )
+ const order = moveWithin(ids, movable, propertyId, index)
+ if (!order || isEqual(order, ids)) return !!order
+ if (owner.type === 'COMPONENT_SET') return reorderPropertyDefinitions(ctx, owner.id, order)
+ const byId = new Map(owner.componentPropertyDefinitions.map((item) => [item.id, item]))
+ patch(
+ owner.id,
+ { componentPropertyDefinitions: order.flatMap((id) => byId.get(id) ?? []) },
+ 'Reorder component properties'
+ )
+ return true
+ }
+
+ /** Show a nested instance's properties on instances of its component, as Figma does. */
+ function setInstanceExposed(nodeId: string, exposed: boolean): boolean {
+ const node = ctx.graph.getNode(nodeId)
+ if (node?.type !== 'INSTANCE') return false
+ const issue = instanceExposureIssue(ctx.graph, node)
+ if (issue === 'not-in-component' || issue === 'not-primary') return false
+ if (exposed && issue) return false
+ assertNodeEditable(ctx.graph, nodeId)
+ if (node.isExposedInstance === exposed) return true
+ patch(
+ nodeId,
+ { isExposedInstance: exposed },
+ exposed ? 'Expose nested instance' : 'Hide nested instance'
+ )
+ return true
+ }
+
+ return {
+ getComponentPropertyAuthoring: (nodeId: string) => componentAuthoringContext(ctx.graph, nodeId),
+ getComponentPropertyBindings: (ownerId: string, propertyId: string) =>
+ componentBindingNodes(ctx.graph, ownerId).flatMap((node) =>
+ node.componentPropertyReferences
+ .filter((reference) => reference.propertyId === propertyId)
+ .map((reference) => ({ nodeId: node.id, name: node.name, field: reference.field }))
+ ),
+ getExposableInstances: (componentId: string) => exposableInstances(ctx.graph, componentId),
+ createComponentProperty,
+ exposeComponentProperty,
+ bindComponentProperty,
+ renameComponentProperty,
+ setComponentPropertyDefault,
+ deleteComponentProperty,
+ moveComponentProperty,
+ setInstanceExposed
+ }
+}
diff --git a/packages/core/src/editor/components/authoring/text-edit.ts b/packages/core/src/editor/components/authoring/text-edit.ts
new file mode 100644
index 000000000..170a83beb
--- /dev/null
+++ b/packages/core/src/editor/components/authoring/text-edit.ts
@@ -0,0 +1,121 @@
+import { pick } from 'es-toolkit/object'
+
+import {
+ applyComponentPropertyValue,
+ cloneInstanceOverrideState,
+ componentPropertyDefinitions,
+ findComponentPropertyTargets
+} from '@open-pencil/scene-graph'
+import type { SceneNode } from '@open-pencil/scene-graph'
+
+import type { EditorContext } from '#core/editor/types'
+
+import { componentAuthoringContext, componentPropertySources } from './context'
+import { componentPropertyTextChanges } from './values'
+
+/**
+ * Text typed into a layer a text property drives becomes the property's value, as in Figma:
+ * the default when the layer is in the main component, the instance's value when it is in an
+ * instance. The caller records the edit itself; this records the property change beside it.
+ */
+export function applyBoundTextEdit(ctx: EditorContext, nodeId: string, text: string): void {
+ const node = ctx.graph.getNode(nodeId)
+ const propertyId = node?.componentPropertyReferences.find(
+ (reference) => reference.field === 'TEXT'
+ )?.propertyId
+ if (!node || !propertyId) return
+ if (componentAuthoringContext(ctx.graph, nodeId)) setDefault(ctx, node, propertyId, text)
+ else setInstanceValue(ctx, node, propertyId, text)
+}
+
+interface LayerChanges {
+ id: string
+ changes: Partial<SceneNode>
+}
+
+/** What showing `text` changes on each layer, resizing included, and what it changes back. */
+function layerTextChanges(layers: SceneNode[], text: string) {
+ const after: LayerChanges[] = layers.map((layer) => ({
+ id: layer.id,
+ changes: componentPropertyTextChanges(layer, text)
+ }))
+ const before: LayerChanges[] = after.map(({ id, changes }, index) => ({
+ id,
+ changes: pick(layers[index], Object.keys(changes) as (keyof SceneNode)[])
+ }))
+ return { before, after }
+}
+
+function setDefault(ctx: EditorContext, node: SceneNode, propertyId: string, text: string) {
+ const context = componentAuthoringContext(ctx.graph, node.id)
+ const owner = context?.owners.find((item) =>
+ item.componentPropertyDefinitions.some((definition) => definition.id === propertyId)
+ )
+ const definition = owner?.componentPropertyDefinitions.find((item) => item.id === propertyId)
+ if (!owner || !definition || definition.defaultValue === text) return
+ const before = structuredClone(owner.componentPropertyDefinitions)
+ const after = before.map((item) =>
+ item.id === propertyId ? { ...item, defaultValue: text } : item
+ )
+ // Every other layer the property drives shows the same default, resized as an edit would be.
+ const others = componentPropertySources(ctx.graph, owner.id, propertyId).flatMap((source) =>
+ source.node.id !== node.id && source.node.type === 'TEXT' ? [source.node] : []
+ )
+ const { before: othersBefore, after: othersAfter } = layerTextChanges(others, text)
+ const apply = (definitions: typeof before, layers: LayerChanges[]) => {
+ ctx.graph.updateNode(owner.id, { componentPropertyDefinitions: structuredClone(definitions) })
+ for (const layer of layers) {
+ ctx.graph.updateNode(layer.id, structuredClone(layer.changes))
+ ctx.runLayoutForNode(layer.id)
+ }
+ ctx.requestRender()
+ }
+ ctx.undo.execute({
+ label: 'Edit text',
+ forward: () => apply(after, othersAfter),
+ inverse: () => apply(before, othersBefore)
+ })
+}
+
+function setInstanceValue(ctx: EditorContext, node: SceneNode, propertyId: string, text: string) {
+ const instance = node.parentId
+ ? ctx.graph.closest(
+ node.parentId,
+ (item) =>
+ item.type === 'INSTANCE' &&
+ componentPropertyDefinitions(ctx.graph, item).some(
+ (definition) => definition.id === propertyId
+ )
+ )
+ : undefined
+ const definition = instance
+ ? componentPropertyDefinitions(ctx.graph, instance).find((item) => item.id === propertyId)
+ : undefined
+ if (!instance || !definition) return
+ const before = {
+ componentPropertyAssignments: { ...instance.componentPropertyAssignments },
+ instanceOverrides: cloneInstanceOverrideState(instance.instanceOverrides)
+ }
+ // Other layers the property drives in this instance change and resize with it, and undo with it.
+ const others = findComponentPropertyTargets(ctx.graph, instance, propertyId).flatMap((target) =>
+ target.node.id !== node.id && target.node.type === 'TEXT' ? [target.node] : []
+ )
+ const { before: othersBefore, after: othersAfter } = layerTextChanges(others, text)
+ const apply = (values: typeof before, layers: LayerChanges[]) => {
+ ctx.graph.updateNode(instance.id, structuredClone(values))
+ for (const layer of layers) ctx.graph.updateNode(layer.id, structuredClone(layer.changes))
+ ctx.runLayoutForNode(instance.id)
+ ctx.requestRender()
+ }
+ applyComponentPropertyValue(ctx.graph, instance.id, definition, text)
+ const after = {
+ componentPropertyAssignments: { ...instance.componentPropertyAssignments },
+ instanceOverrides: cloneInstanceOverrideState(instance.instanceOverrides)
+ }
+ apply(after, othersAfter)
+ ctx.undo.push({
+ label: 'Edit text',
+ forward: () => apply(after, othersAfter),
+ inverse: () => apply(before, othersBefore)
+ })
+}
diff --git a/packages/core/src/editor/components/authoring/values.ts b/packages/core/src/editor/components/authoring/values.ts
new file mode 100644
index 000000000..2dd9a9deb
--- /dev/null
+++ b/packages/core/src/editor/components/authoring/values.ts
@@ -0,0 +1,65 @@
+import { canCreateInstance, resolveComponentPropertyValue } from '@open-pencil/scene-graph'
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+import { textAutoResizeChanges } from '#core/editor/text/auto-resize'
+import { pathTextEditChanges } from '#core/editor/text/path-edit'
+import type { EditorContext } from '#core/editor/types'
+
+import type { ExposableComponentField } from './context'
+
+type Patch = (id: string, changes: Partial<SceneNode>, label: string) => void
+
+export function acceptsComponentPropertyValue(
+ graph: SceneGraph,
+ node: SceneNode,
+ field: ExposableComponentField,
+ value: string
+) {
+ if (field === 'TEXT') return node.type === 'TEXT'
+ if (field === 'VISIBLE') return value === 'true' || value === 'false'
+ const target = resolveComponentPropertyValue(graph, value)
+ return (
+ node.type === 'INSTANCE' &&
+ !!target &&
+ !!node.parentId &&
+ canCreateInstance(graph, target.id, node.parentId)
+ )
+}
+
+export function componentPropertyTextChanges(node: SceneNode, value: string): Partial<SceneNode> {
+ const changes = { text: value }
+ return {
+ ...changes,
+ ...textAutoResizeChanges(node, changes),
+ ...pathTextEditChanges(node, changes)
+ }
+}
+
+export function createAuthoringValueActions(ctx: EditorContext, patch: Patch) {
+ function accepts(node: SceneNode, field: ExposableComponentField, value: string) {
+ return acceptsComponentPropertyValue(ctx.graph, node, field, value)
+ }
+
+ function apply(node: SceneNode, field: ExposableComponentField, value: string) {
+ if (field === 'INSTANCE_SWAP') {
+ const target = resolveComponentPropertyValue(ctx.graph, value)
+ const previous = node.componentId
+ if (!target || !previous || previous === target.id) return
+ const swap = (componentId: string) => {
+ ctx.graph.swapInstanceComponent(node.id, componentId)
+ ctx.runLayoutForNode(node.id)
+ ctx.requestRender()
+ }
+ ctx.undo.execute({
+ label: 'Change property source',
+ forward: () => swap(target.id),
+ inverse: () => swap(previous)
+ })
+ } else if (field === 'TEXT') {
+ patch(node.id, componentPropertyTextChanges(node, value), 'Change property source')
+ } else {
+ patch(node.id, { visible: value === 'true' }, 'Change property source')
+ }
+ }
+ return { accepts, apply }
+}
diff --git a/packages/core/src/editor/components/properties.ts b/packages/core/src/editor/components/properties.ts
index a31c886cf..985d88964 100644
--- a/packages/core/src/editor/components/properties.ts
+++ b/packages/core/src/editor/components/properties.ts
@@ -2,7 +2,7 @@ import {
applyComponentPropertyValue,
cloneInstanceOverrideState,
componentPropertyDefinitions,
- findComponentPropertyTarget,
+ findComponentPropertyTargets,
resolveComponentPropertyValue,
setInstanceOverride
} from '@open-pencil/scene-graph'
@@ -22,14 +22,6 @@ function definitionsForInstance(
return componentPropertyDefinitions(ctx.graph, instance)
}
-function propertyTarget(
- ctx: Pick<EditorContext, 'graph'>,
- instance: SceneNode,
- propertyId: string
-): ComponentPropertyTarget | null {
- return findComponentPropertyTarget(ctx.graph, instance, propertyId)
-}
-
function swapTargetId(ctx: Pick<EditorContext, 'graph'>, value: string): string | null {
return resolveComponentPropertyValue(ctx.graph, value)?.id ?? null
}
@@ -90,6 +82,26 @@ export function createComponentPropertyActions(
return definition.type === 'INSTANCE_SWAP' ? (swapTargetId(ctx, value) ?? value) : value
}
+ function restoreTarget(instance: SceneNode, target: ComponentPropertyTarget, value: string) {
+ if (target.field === 'TEXT' && target.node.type === 'TEXT') {
+ ctx.graph.updateNode(target.node.id, { text: value })
+ } else if (target.field === 'VISIBLE') {
+ ctx.graph.updateNode(target.node.id, { visible: value === 'true' })
+ } else if (target.field === 'INSTANCE_SWAP' && target.node.type === 'INSTANCE') {
+ const componentId = swapTargetId(ctx, value)
+ if (!componentId) return
+ ctx.graph.swapInstanceComponent(target.node.id, componentId)
+ setInstanceOverride(
+ instance.instanceOverrides,
+ instance.id,
+ target.node.id,
+ 'sourceComponentId',
+ target.source.id
+ )
+ ctx.graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides })
+ }
+ }
+
function setInstanceComponentProperty(instanceId: string, propertyId: string, value: string) {
const instance = ctx.graph.getNode(instanceId)
if (instance?.type !== 'INSTANCE') return
@@ -104,12 +116,14 @@ export function createComponentPropertyActions(
const previousAssignments = { ...instance.componentPropertyAssignments }
const previousOverrides = cloneInstanceOverrideState(instance.instanceOverrides)
- const target = propertyTarget(ctx, instance, propertyId)
+ // A property can drive several layers; undo restores each one to what it showed.
const assignedValue = instance.componentPropertyAssignments[propertyId]
- const previousValue =
- definition.type === 'INSTANCE_SWAP' && assignedValue
- ? (swapTargetId(ctx, assignedValue) ?? assignedValue)
- : targetValue(target)
+ const previousValues = findComponentPropertyTargets(ctx.graph, instance, propertyId).map(
+ (target) =>
+ definition.type === 'INSTANCE_SWAP' && assignedValue
+ ? (swapTargetId(ctx, assignedValue) ?? assignedValue)
+ : targetValue(target)
+ )
if (!applyPropertyValue(ctx, instanceId, definition, value)) return
ctx.undo.push({
@@ -121,29 +135,14 @@ export function createComponentPropertyActions(
inverse: () => {
const live = ctx.graph.getNode(instanceId)
if (live) {
- const restoredTarget = propertyTarget(ctx, live, propertyId)
+ const restoredTargets = findComponentPropertyTargets(ctx.graph, live, propertyId)
ctx.graph.updateNode(instanceId, {
componentPropertyAssignments: previousAssignments,
instanceOverrides: cloneInstanceOverrideState(previousOverrides)
})
- if (restoredTarget?.field === 'TEXT' && restoredTarget.node.type === 'TEXT') {
- ctx.graph.updateNode(restoredTarget.node.id, { text: previousValue })
- } else if (restoredTarget?.field === 'VISIBLE') {
- ctx.graph.updateNode(restoredTarget.node.id, { visible: previousValue === 'true' })
- } else if (restoredTarget?.field === 'INSTANCE_SWAP') {
- const componentId = swapTargetId(ctx, previousValue)
- if (componentId && restoredTarget.node.type === 'INSTANCE') {
- ctx.graph.swapInstanceComponent(restoredTarget.node.id, componentId)
- setInstanceOverride(
- live.instanceOverrides,
- live.id,
- restoredTarget.node.id,
- 'sourceComponentId',
- restoredTarget.source.id
- )
- ctx.graph.updateNode(live.id, { instanceOverrides: live.instanceOverrides })
- }
- }
+ restoredTargets.forEach((target, index) =>
+ restoreTarget(live, target, previousValues[index] ?? '')
+ )
}
ctx.requestRender()
}
diff --git a/packages/core/src/editor/text.ts b/packages/core/src/editor/text.ts
index 5d3c1dad9..a6debf738 100644
--- a/packages/core/src/editor/text.ts
+++ b/packages/core/src/editor/text.ts
@@ -9,6 +9,7 @@ import { copyDerivedGlyphs, copyGeometryPaths } from '@open-pencil/scene-graph/c
import { weightToStyle } from '#core/text/fonts'
import { hasGlyphOutlines } from '#core/text/opentype'
+import { applyBoundTextEdit } from './components/authoring/text-edit'
import { pathTextEditChanges } from './text/path-edit'
import {
createTextEditSession,
@@ -178,26 +179,30 @@ export function createTextActions(ctx: EditorContext) {
ctx.state.editingTextId = null
activeSession = null
- ctx.undo.push({
- label: 'Edit text',
- forward: () => {
- ctx.graph.updateNode(result.nodeId, {
- text: after.text,
- styleRuns: after.styleRuns,
- ...after.size,
- ...afterPathText
- })
- restoreInstanceOverrides(ctx, instanceOverridesAfter)
- },
- inverse: () => {
- ctx.graph.updateNode(result.nodeId, {
- text: before.text,
- styleRuns: before.styleRuns,
- ...before.size,
- ...beforePathText
- })
- restoreInstanceOverrides(ctx, instanceOverridesBefore)
- }
+ // Text a property drives becomes the property's value too, in the same undo step.
+ ctx.undo.runBatch('Edit text', () => {
+ ctx.undo.push({
+ label: 'Edit text',
+ forward: () => {
+ ctx.graph.updateNode(result.nodeId, {
+ text: after.text,
+ styleRuns: after.styleRuns,
+ ...after.size,
+ ...afterPathText
+ })
+ restoreInstanceOverrides(ctx, instanceOverridesAfter)
+ },
+ inverse: () => {
+ ctx.graph.updateNode(result.nodeId, {
+ text: before.text,
+ styleRuns: before.styleRuns,
+ ...before.size,
+ ...beforePathText
+ })
+ restoreInstanceOverrides(ctx, instanceOverridesBefore)
+ }
+ })
+ if (before.text !== after.text) applyBoundTextEdit(ctx, result.nodeId, after.text)
})
}
diff --git a/packages/core/src/figma-api/components.ts b/packages/core/src/figma-api/components.ts
index d877281d2..409ad81a4 100644
--- a/packages/core/src/figma-api/components.ts
+++ b/packages/core/src/figma-api/components.ts
@@ -11,7 +11,9 @@ import {
applyComponentPropertyValue,
componentPropertyDefinitions as sharedComponentPropertyDefinitions,
removeComponentProperty,
- createComponentPropertyId
+ createComponentPropertyId,
+ exposedInstances,
+ instanceExposureIssue
} from '@open-pencil/scene-graph'
import { cloneNodeProps } from '@open-pencil/scene-graph/copy'
@@ -381,44 +383,36 @@ export function installComponentPropertyAccessors(
isExposedInstance: {
get(this: ProxyThis) {
const node = raw(this, internals)
- return (
- node.type === 'INSTANCE' &&
- node.componentPropertyReferences.some((reference) => reference.field === 'INSTANCE_SWAP')
- )
+ if (node.type !== 'INSTANCE') return false
+ if (node.isExposedInstance) return true
+ // A copy inside an instance reports what its source in the component says.
+ const owner = node.parentId
+ ? graph(this, internals).closest(node.parentId, (item) => item.type === 'INSTANCE')
+ : undefined
+ return !!owner && exposedInstances(graph(this, internals), owner).includes(node)
},
set(this: ProxyThis, value: boolean) {
const node = raw(this, internals)
if (node.type !== 'INSTANCE')
throw new Error('isExposedInstance is only supported on instances')
- if (!value)
- updateNode(this, internals, {
- componentPropertyReferences: node.componentPropertyReferences.filter(
- (reference) => reference.field !== 'INSTANCE_SWAP'
- )
- })
+ const issue = instanceExposureIssue(graph(this, internals), node)
+ if (issue === 'not-in-component')
+ throw new Error(
+ 'Instance must be contained within a component or component set to be exposed.'
+ )
+ if (issue === 'not-primary') throw new Error('Can only expose primary instances.')
+ if (value && issue)
+ throw new Error(
+ 'Can only expose instances that have exposed nested instances or children with component property references.'
+ )
+ updateNode(this, internals, { isExposedInstance: value })
}
},
exposedInstances: {
get(this: ProxyThis) {
const node = raw(this, internals)
- if (node.type !== 'INSTANCE') return []
- const result: FigmaNodeProxy[] = []
- const visit = (id: string): void => {
- const child = graph(this, internals).getNode(id)
- if (!child) return
- if (
- child.type === 'INSTANCE' &&
- child.componentPropertyReferences.some(
- (reference) => reference.field === 'INSTANCE_SWAP'
- )
- )
- result.push(
- (this[internals.api] as { wrapNode(id: string): FigmaNodeProxy }).wrapNode(child.id)
- )
- child.childIds.forEach(visit)
- }
- node.childIds.forEach(visit)
- return result
+ const api = this[internals.api] as { wrapNode(id: string): FigmaNodeProxy }
+ return exposedInstances(graph(this, internals), node).map((item) => api.wrapNode(item.id))
}
},
setProperties: {
diff --git a/packages/core/tests/editor/components/authoring.test.ts b/packages/core/tests/editor/components/authoring.test.ts
new file mode 100644
index 000000000..c99a6c251
--- /dev/null
+++ b/packages/core/tests/editor/components/authoring.test.ts
@@ -0,0 +1,281 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+
+function setup() {
+ const editor = createEditor()
+ const pageId = editor.state.currentPageId
+ const component = editor.graph.createNode('COMPONENT', pageId, { name: 'Button' })
+ const label = editor.graph.createNode('TEXT', component.id, { name: 'Label', text: 'Button' })
+ const badge = editor.graph.createNode('FRAME', component.id, { name: 'Badge' })
+ const instance = editor.graph.createInstance(component.id, pageId)
+ if (!instance) throw new Error('Expected instance')
+ return { editor, pageId, component, label, badge, instance }
+}
+
+function defined<T>(value: T | null | undefined): T {
+ if (value == null) throw new Error('Expected value')
+ return value
+}
+
+describe('manual component property authoring', () => {
+ test('renames a property without replacing its identity or its links', () => {
+ const { editor, label, component } = setup()
+ const first = defined(editor.exposeComponentProperty(label.id, 'TEXT', 'Label'))
+ const other = editor.graph.createNode('TEXT', component.id, { name: 'Caption' })
+ const second = defined(editor.exposeComponentProperty(other.id, 'TEXT', 'Caption'))
+ expect(editor.renameComponentProperty(component.id, second, 'Secondary label')).toBe(true)
+ expect(component.componentPropertyDefinitions.map((item) => item.id)).toEqual([first, second])
+ expect(component.componentPropertyDefinitions.map((item) => item.name)).toEqual([
+ 'Label',
+ 'Secondary label'
+ ])
+ editor.undo.undo()
+ expect(component.componentPropertyDefinitions.map((item) => item.name)).toEqual([
+ 'Label',
+ 'Caption'
+ ])
+ expect(other.componentPropertyReferences).toEqual([{ propertyId: second, field: 'TEXT' }])
+ })
+
+ test('exposes a text property in one undo entry and applies it to existing instances', async () => {
+ const { editor, component, label, instance } = setup()
+ await Promise.resolve()
+ editor.undo.clear()
+ const id = defined(editor.exposeComponentProperty(label.id, 'TEXT', 'Label'))
+ expect(component.componentPropertyDefinitions).toEqual([
+ { id, name: 'Label', type: 'TEXT', defaultValue: 'Button' }
+ ])
+ expect(label.componentPropertyReferences).toEqual([{ propertyId: id, field: 'TEXT' }])
+ editor.undo.undo()
+ expect(label.componentPropertyReferences).toEqual([])
+ expect(component.componentPropertyDefinitions).toEqual([])
+ expect(editor.undo.undo()).toBeNull()
+ editor.undo.redo()
+ editor.setInstanceComponentProperty(instance.id, id, 'Buy now')
+ expect(editor.graph.getChildren(instance.id).find((node) => node.name === 'Label')?.text).toBe(
+ 'Buy now'
+ )
+ expect(label.text).toBe('Button')
+ })
+
+ test('shares set properties across variants and preserves assignments on variant changes', async () => {
+ const { editor, pageId, component, label, instance } = setup()
+ const set = editor.graph.createNode('COMPONENT_SET', pageId, { name: 'Buttons' })
+ editor.graph.reparentNode(component.id, set.id)
+ const other = editor.graph.createNode('COMPONENT', set.id, { name: 'Secondary' })
+ const otherLabel = editor.graph.createNode('TEXT', other.id, { text: 'Secondary' })
+ const id = defined(editor.exposeComponentProperty(label.id, 'TEXT', 'Label'))
+ expect(set.componentPropertyDefinitions[0]?.id).toBe(id)
+ expect(editor.bindComponentProperty(otherLabel.id, 'TEXT', id)).toBe(true)
+ editor.addPropertyDefinition(set.id, 'Style', 'VARIANT', 'Primary')
+ const variantProperty = defined(
+ set.componentPropertyDefinitions.find((item) => item.type === 'VARIANT')
+ )
+ editor.setVariantPropertyValue(other.id, variantProperty.id, 'Secondary')
+ editor.setInstanceComponentProperty(instance.id, id, 'Custom label')
+ editor.setInstanceComponentProperty(instance.id, variantProperty.id, 'Secondary')
+ await Promise.resolve()
+ expect(instance.componentId).toBe(other.id)
+ expect(editor.graph.getChildren(instance.id)[0]?.text).toBe('Custom label')
+ })
+
+ test('binds multiple layers to one default and restores that value on instance undo', async () => {
+ const { editor, component, label, instance } = setup()
+ const second = editor.graph.createNode('TEXT', component.id, { name: 'Second', text: 'Second' })
+ await Promise.resolve()
+ const id = defined(editor.exposeComponentProperty(label.id, 'TEXT', 'Label'))
+ editor.bindComponentProperty(second.id, 'TEXT', id)
+ await Promise.resolve()
+ editor.setInstanceComponentProperty(instance.id, id, 'Together')
+ expect(
+ editor.graph
+ .getChildren(instance.id)
+ .filter((node) => node.type === 'TEXT')
+ .map((node) => node.text)
+ ).toEqual(['Together', 'Together'])
+ editor.undo.undo()
+ expect(
+ editor.graph
+ .getChildren(instance.id)
+ .filter((node) => node.type === 'TEXT')
+ .map((node) => node.text)
+ ).toEqual(['Button', 'Button'])
+ editor.undo.redo()
+ expect(
+ editor.graph
+ .getChildren(instance.id)
+ .filter((node) => node.type === 'TEXT')
+ .map((node) => node.text)
+ ).toEqual(['Together', 'Together'])
+ })
+
+ test('applies an existing assignment when another layer is bound and undoes that binding', async () => {
+ const { editor, component, label, instance } = setup()
+ const second = editor.graph.createNode('TEXT', component.id, { name: 'Second', text: 'Second' })
+ await Promise.resolve()
+ const id = defined(editor.exposeComponentProperty(label.id, 'TEXT', 'Label'))
+ editor.setInstanceComponentProperty(instance.id, id, 'Custom')
+ editor.bindComponentProperty(second.id, 'TEXT', id)
+ await Promise.resolve()
+ expect(editor.graph.getChildren(instance.id).find((node) => node.name === 'Second')?.text).toBe(
+ 'Custom'
+ )
+ editor.undo.undo()
+ await Promise.resolve()
+ expect(second.componentPropertyReferences).toEqual([])
+ expect(editor.graph.getChildren(instance.id).find((node) => node.name === 'Second')?.text).toBe(
+ 'Second'
+ )
+ expect(instance.componentPropertyAssignments[id]).toBe('Custom')
+ })
+
+ test('exposes visibility, renames without losing bindings, and deletes with undo', async () => {
+ const { editor, component, badge, instance } = setup()
+ const id = defined(editor.exposeComponentProperty(badge.id, 'VISIBLE', 'Show badge'))
+ editor.setInstanceComponentProperty(instance.id, id, 'false')
+ expect(editor.renameComponentProperty(component.id, id, 'Badge visible')).toBe(true)
+ expect(editor.getInstanceComponentPropertyDefinitions(instance.id)[0]?.name).toBe(
+ 'Badge visible'
+ )
+ expect(editor.getComponentPropertyBindings(component.id, id)).toEqual([
+ { nodeId: badge.id, name: 'Badge', field: 'VISIBLE' }
+ ])
+ expect(editor.deleteComponentProperty(component.id, id)).toBe(true)
+ expect(badge.componentPropertyReferences).toEqual([])
+ expect(instance.componentPropertyAssignments).toEqual({})
+ editor.undo.undo()
+ await Promise.resolve()
+ expect(instance.componentPropertyAssignments[id]).toBe('false')
+ expect(badge.componentPropertyReferences).toEqual([{ propertyId: id, field: 'VISIBLE' }])
+ expect(
+ editor.graph.getChildren(instance.id).find((node) => node.name === 'Badge')?.visible
+ ).toBe(false)
+ })
+
+ test('exposes nested swaps while rejecting authoring inside instance descendants', async () => {
+ const { editor, pageId, component, label, instance } = setup()
+ const icon = editor.graph.createNode('COMPONENT', pageId, { name: 'Icon' })
+ editor.graph.createNode('TEXT', icon.id, { text: 'Icon' })
+ const otherIcon = editor.graph.createNode('COMPONENT', pageId, { name: 'Other icon' })
+ const nested = defined(editor.graph.createInstance(icon.id, component.id))
+ await Promise.resolve()
+ const id = defined(editor.exposeComponentProperty(nested.id, 'INSTANCE_SWAP', 'Icon'))
+ editor.setInstanceComponentProperty(instance.id, id, otherIcon.id)
+ expect(
+ editor.graph.getChildren(instance.id).find((node) => node.type === 'INSTANCE')?.componentId
+ ).toBe(otherIcon.id)
+ editor.undo.undo()
+ expect(
+ editor.graph.getChildren(instance.id).find((node) => node.type === 'INSTANCE')?.componentId
+ ).toBe(icon.id)
+ const inherited = defined(
+ editor.graph.getChildren(instance.id).find((node) => node.name === label.name)
+ )
+ expect(editor.getComponentPropertyAuthoring(inherited.id)).toBeNull()
+ expect(
+ editor.getComponentPropertyAuthoring(defined(editor.graph.getChildren(nested.id)[0]).id)
+ ).toBeNull()
+ expect(editor.exposeComponentProperty(inherited.id, 'TEXT', 'Wrong owner')).toBeNull()
+ expect(editor.exposeComponentProperty(component.id, 'VISIBLE', 'Root')).toBeNull()
+ expect(editor.bindComponentProperty(label.id, 'TEXT', id)).toBe(false)
+ })
+
+ test('rejects empty and duplicate names and does not record invalid mutations', async () => {
+ const { editor, component, label, badge } = setup()
+ await Promise.resolve()
+ const id = defined(editor.exposeComponentProperty(label.id, 'TEXT', 'Label'))
+ editor.undo.clear()
+ expect(editor.exposeComponentProperty(badge.id, 'VISIBLE', ' ')).toBeNull()
+ expect(editor.exposeComponentProperty(badge.id, 'VISIBLE', 'Label')).toBeNull()
+ expect(editor.renameComponentProperty(component.id, id, ' ')).toBe(false)
+ expect(editor.bindComponentProperty(badge.id, 'TEXT', id)).toBe(false)
+ expect(editor.undo.undo()).toBeNull()
+ })
+
+ test('keeps library property definitions read-only while allowing instance edits', () => {
+ const { editor, component, label, instance } = setup()
+ const id = defined(editor.exposeComponentProperty(label.id, 'TEXT', 'Label'))
+ editor.graph.updateNode(component.id, {
+ librarySource: {
+ identity: { libraryId: 'shared', assetKey: 'button', revisionId: 'r1' },
+ sourceNodeId: 'source-button',
+ readOnly: true
+ }
+ })
+ expect(editor.getComponentPropertyAuthoring(label.id)?.editable).toBe(false)
+ expect(() => editor.exposeComponentProperty(label.id, 'VISIBLE', 'Show label')).toThrow()
+ expect(() => editor.bindComponentProperty(label.id, 'TEXT', null)).toThrow()
+ expect(() => editor.renameComponentProperty(component.id, id, 'Changed')).toThrow()
+ expect(() => editor.deleteComponentProperty(component.id, id)).toThrow()
+ editor.setInstanceComponentProperty(instance.id, id, 'Allowed')
+ expect(instance.componentPropertyAssignments[id]).toBe('Allowed')
+ })
+
+ test('rejects shared names that collide with a property owned by another variant', () => {
+ const { editor, pageId, component, label } = setup()
+ const localId = defined(editor.exposeComponentProperty(label.id, 'TEXT', 'Local label'))
+ const set = editor.graph.createNode('COMPONENT_SET', pageId)
+ editor.graph.reparentNode(component.id, set.id)
+ const other = editor.graph.createNode('COMPONENT', set.id)
+ const text = editor.graph.createNode('TEXT', other.id)
+ expect(editor.exposeComponentProperty(text.id, 'TEXT', 'Local label')).toBeNull()
+ const sharedId = defined(editor.exposeComponentProperty(text.id, 'TEXT', 'Shared label'))
+ expect(editor.renameComponentProperty(set.id, sharedId, 'Local label')).toBe(false)
+ expect(editor.renameComponentProperty(component.id, localId, 'Shared label')).toBe(false)
+ })
+
+ test('a default shows on every linked layer and on instances without their own value', async () => {
+ const { editor, component, label, instance } = setup()
+ const second = editor.graph.createNode('TEXT', component.id, { name: 'Second', text: 'Second' })
+ const other = defined(editor.graph.createInstance(component.id, editor.state.currentPageId))
+ const id = defined(editor.exposeComponentProperty(label.id, 'TEXT', 'Label'))
+ editor.bindComponentProperty(second.id, 'TEXT', id)
+ editor.setInstanceComponentProperty(other.id, id, 'Own value')
+ await Promise.resolve()
+ expect(editor.setComponentPropertyDefault(component.id, id, 'Continue')).toBe(true)
+ await Promise.resolve()
+ const texts = (node: { id: string }) =>
+ editor.graph
+ .getChildren(node.id)
+ .filter((child) => child.type === 'TEXT')
+ .map((child) => child.text)
+ expect([label.text, second.text]).toEqual(['Continue', 'Continue'])
+ expect(texts(instance)).toEqual(['Continue', 'Continue'])
+ expect(texts(other)).toEqual(['Own value', 'Own value'])
+ editor.undo.undo()
+ await Promise.resolve()
+ expect(component.componentPropertyDefinitions[0]?.defaultValue).toBe('Button')
+ expect(texts(instance)).toEqual(['Button', 'Button'])
+ })
+
+ test('moves a property among its siblings with undo', () => {
+ const { editor, component, label, badge } = setup()
+ const text = defined(editor.exposeComponentProperty(label.id, 'TEXT', 'Label'))
+ const visible = defined(editor.exposeComponentProperty(badge.id, 'VISIBLE', 'Show badge'))
+ expect(editor.moveComponentProperty(component.id, visible, 0)).toBe(true)
+ expect(component.componentPropertyDefinitions.map((item) => item.id)).toEqual([visible, text])
+ editor.undo.undo()
+ expect(component.componentPropertyDefinitions.map((item) => item.id)).toEqual([text, visible])
+ expect(editor.moveComponentProperty(component.id, visible, 5)).toBe(false)
+ })
+
+ test('exposes a nested instance of the component, not one inside an instance', async () => {
+ const { editor, pageId, component, instance } = setup()
+ const icon = editor.graph.createNode('COMPONENT', pageId, { name: 'Icon' })
+ const nested = defined(editor.graph.createInstance(icon.id, component.id))
+ await Promise.resolve()
+ expect(editor.getExposableInstances(component.id).map((node) => node.id)).toEqual([nested.id])
+ // Figma only exposes an instance whose component has something to show.
+ expect(editor.setInstanceExposed(nested.id, true)).toBe(false)
+ const glyph = editor.graph.createNode('TEXT', icon.id, { name: 'Glyph', text: 'i' })
+ defined(editor.exposeComponentProperty(glyph.id, 'TEXT', 'Glyph'))
+ expect(editor.setInstanceExposed(nested.id, true)).toBe(true)
+ expect(nested.isExposedInstance).toBe(true)
+ editor.undo.undo()
+ expect(nested.isExposedInstance).toBe(false)
+ await Promise.resolve()
+ const copy = defined(editor.graph.getChildren(instance.id).find((node) => node.type === 'INSTANCE'))
+ expect(editor.setInstanceExposed(copy.id, true)).toBe(false)
+ })
+})
diff --git a/packages/docs/de/user-guide/components.md b/packages/docs/de/user-guide/components.md
index 2a685ff03..207ff59ee 100644
--- a/packages/docs/de/user-guide/components.md
+++ b/packages/docs/de/user-guide/components.md
@@ -23,6 +23,8 @@ Mindestens zwei Komponenten auswählen und <kbd>⇧</kbd><kbd>⌘</kbd><kbd>K</k
Unterstützt werden Text, boolesche Sichtbarkeit und Instanztausch. Eine Eigenschaft kann mit einem untergeordneten Feld verbunden und anschließend in einer Instanz verändert werden, ohne die Verbindung zu lösen.
+Verknüpft wird mit der Raute-Schaltfläche dort, wo das Feld steht: **Typografie** für den Textinhalt, **Darstellung** für die Sichtbarkeit und der Kopf einer Instanz für die ausgetauschte Komponente. Die Hauptkomponente listet ihre **Eigenschaften**; ein Klick öffnet Name, Standardwert und verknüpfte Ebenen. Über **+ → Verschachtelte Instanzen** zeigen Instanzen der Komponente auch die Eigenschaften einer verschachtelten Instanz, wie in Figma.
+
## Bibliotheken
Bibliotheken veröffentlichen Komponenten als unveränderliche Versionen. In **Assets → Manage libraries → Publish library** werden eine dauerhafte Kennung und ein Name festgelegt und die zu veröffentlichenden Änderungen ausgewählt.
diff --git a/packages/docs/development/roadmap.md b/packages/docs/development/roadmap.md
index 838d0f7b6..2c95d4114 100644
--- a/packages/docs/development/roadmap.md
+++ b/packages/docs/development/roadmap.md
@@ -44,7 +44,7 @@ See [canvas navigation](../user-guide/canvas-navigation), [components and librar
### Editor depth
- Complete variable inspector coverage for common numeric/text/layout fields.
-- Extend component and instance authoring with deeper override inspection and slots. Multidimensional variant definitions, instance property editing, and component-library publish/update workflows are already supported.
+- Extend component and instance authoring with deeper override inspection and slots. Multidimensional variant definitions, text, boolean, and instance-swap property authoring, exposed nested instances, instance property editing, and component-library publish/update workflows are already supported.
- Treat variables, styles, components, and libraries as governed design-system assets with proposal, review, publish, update, migration, and conformance workflows.
- Complete layout-grid style parity beyond existing grid geometry controls and editable page/frame guides.
- Extend inspection aids beyond the existing Option/Alt measurements between selected and hovered layers.
@@ -255,7 +255,7 @@ OpenPencil deliberately preserves many Figma/Kiwi fields even when they are not
| `source.fig.derivedSymbolDataLayoutVersion` | ✅ | — | — | Figma bookkeeping. |
| `source.fig.uniformScaleFactor` | ✅ | Indirect | — | Important for scaled instances. |
| Style IDs: fill/stroke/text/effect/grid | ↩ | — | — | Preserves style linkage for Figma, but OpenPencil has no style manager yet. |
-| Component property refs/defs/specs | ✅ | Indirect | ◐ | Full Figma component-property authoring is incomplete. |
+| Component property refs/defs/specs | ✅ | Indirect | ◐ | Text, boolean, and instance-swap properties, their links, and exposed nested instances (`propsAreBubbled`) are authored in the panel. |
| State-group metadata | ↩ | — | — | Preserved only. |
| Version/sort/publish/library metadata | ↩ | — | ◐ | Figma metadata is preserved; OpenPencil's component-library publish/update workflow uses its own stable asset identities and revision review. |
| Variable and parameter consumption maps | ✅ | ◐ | ◐ | Filtered/preserved for safe round-trip; normalized bindings cover common cases. |
diff --git a/packages/docs/pl/user-guide/components.md b/packages/docs/pl/user-guide/components.md
index 9fd55249b..39ab1ebd1 100644
--- a/packages/docs/pl/user-guide/components.md
+++ b/packages/docs/pl/user-guide/components.md
@@ -27,6 +27,8 @@ Każdy komponent w zestawie może określać kilka wymiarów wariantu, na przyk
Komponenty obsługują właściwości tekstu, widoczności logicznej i zamiany egzemplarza. Powiąż właściwość z polem obiektu potomnego, aby zmieniać jej wartość w egzemplarzu bez odłączania.
+Powiązanie tworzy przycisk z rombem przy polu: **Typografia** dla treści tekstu, **Wygląd** dla widoczności i nagłówek egzemplarza dla zamienianego komponentu. Komponent główny pokazuje swoje **Właściwości**; kliknięcie otwiera nazwę, wartość domyślną i powiązane warstwy. **+ → Zagnieżdżone instancje** pokazuje właściwości zagnieżdżonego egzemplarza w egzemplarzach komponentu, jak w Figmie.
+
## Biblioteki
Biblioteka publikuje komponenty jako niezmienne wersje. Każdy zasób ma stałe identyfikatory biblioteki, zasobu i wersji, dlatego różne egzemplarze mogą pozostać na różnych wersjach do jawnej aktualizacji.
diff --git a/packages/docs/ru/user-guide/components.md b/packages/docs/ru/user-guide/components.md
index b0a596c92..b3b3ff11c 100644
--- a/packages/docs/ru/user-guide/components.md
+++ b/packages/docs/ru/user-guide/components.md
@@ -39,6 +39,8 @@ description: Переиспользуемые компоненты, экземп
Свяжите свойство с полем дочернего объекта. После этого значение можно менять в экземпляре без отсоединения. Определения свойств и назначенные значения сохраняются в `.fig`.
+Связь создаёт кнопка с ромбом там, где находится поле: **Типографика** для текста, **Оформление** для видимости и заголовок экземпляра для заменяемого компонента. Главный компонент показывает свои **Свойства**; щелчок открывает название, значение по умолчанию и связанные слои. Через **+ → Вложенные экземпляры** свойства вложенного экземпляра появляются в экземплярах компонента, как в Figma.
+
## Библиотеки компонентов
Библиотека публикует компоненты как неизменяемые редакции. У каждого опубликованного ресурса есть постоянные идентификаторы библиотеки, ресурса и редакции. Поэтому разные экземпляры могут оставаться на разных редакциях до явного обновления.
diff --git a/packages/docs/user-guide/components.md b/packages/docs/user-guide/components.md
index cdca6705a..55600f538 100644
--- a/packages/docs/user-guide/components.md
+++ b/packages/docs/user-guide/components.md
@@ -31,7 +31,13 @@ Use the component properties panel to add, rename, reorder, and remove variant d
## Component Properties
-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.
+Components and component sets support reusable text, boolean visibility, instance-swap, and slot properties. Select an instance to edit its values without detaching it. Properties and their values are preserved when saving and reopening `.fig` files.
+
+To link a layer of a main component to a property, use the diamond button where its field lives: **Typography** for text content, **Appearance** for visibility, and the instance header for the swapped component. Create a property from the layer's current value or pick an existing one; the field then shows the property instead of its value. Typing into linked text sets the property — its default in the main component, the instance's value in an instance.
+
+Select the main component to see its **Properties**. Click a property to rename it, change its default, see and unlink the layers it drives, or delete it, and drag properties to reorder them. **+** adds a text, boolean, or instance-swap property.
+
+To show a nested instance's properties on instances of the component, choose **+ → Nested instances** and tick it, as Figma's **Expose properties from nested instances** does. Instances of the component then list its properties under its name. Only an instance whose component has properties can be exposed.
## Slots
diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.ts
index e36d5cf98..7d96d4cae 100644
--- a/packages/fig/src/node-change/convert.ts
+++ b/packages/fig/src/node-change/convert.ts
@@ -891,6 +891,7 @@ type ComponentMetadataProps = Pick<
| 'publishedVersion'
| 'isPublishable'
| 'isSymbolPublishable'
+ | 'isExposedInstance'
| 'symbolDescription'
| 'symbolLinks'
| 'variantPropSpecs'
@@ -928,6 +929,7 @@ function extractComponentMetadata(nc: NodeChange): ComponentMetadataProps {
publishedVersion: stringOrNull(nc.publishedVersion),
isPublishable: booleanOrFalse(nc.isPublishable),
isSymbolPublishable: booleanOrFalse(nc.isSymbolPublishable),
+ isExposedInstance: booleanOrFalse(nc.propsAreBubbled),
symbolDescription: stringOrEmpty(nc.symbolDescription),
symbolLinks: symbolLinks
.filter((link): link is SymbolLink => typeof link.uri === 'string')
diff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.ts
index 98e43ccd5..7b4d88c40 100644
--- a/packages/fig/src/node-change/export/node.ts
+++ b/packages/fig/src/node-change/export/node.ts
@@ -654,6 +654,7 @@ function applyComponentMetadata(
if (node.type === 'COMPONENT' || node.isSymbolPublishable) {
nc.isSymbolPublishable = node.isSymbolPublishable
}
+ if (node.isExposedInstance) nc.propsAreBubbled = true
if (node.symbolDescription) nc.symbolDescription = node.symbolDescription
if (node.symbolLinks.length > 0) nc.symbolLinks = structuredClone(node.symbolLinks)
const componentPropDefs = node.componentPropertyDefinitions.map((def) => {
diff --git a/packages/scene-graph/src/components/exposure.ts b/packages/scene-graph/src/components/exposure.ts
new file mode 100644
index 000000000..3944c90a2
--- /dev/null
+++ b/packages/scene-graph/src/components/exposure.ts
@@ -0,0 +1,61 @@
+import type { SceneGraph } from '../index'
+import { instanceMainComponent } from '../instances/main-component'
+import { walkInstanceSources } from '../instances/source-walk'
+import type { SceneNode } from '../types'
+import { componentPropertyDefinitions } from './properties'
+
+/**
+ * Instances a component can expose: those in its own layers, not inside another instance,
+ * whose content belongs to that instance's component.
+ */
+export function exposableInstances(graph: SceneGraph, componentId: string): SceneNode[] {
+ const found: SceneNode[] = []
+ const visit = (parentId: string): void => {
+ for (const child of graph.getChildren(parentId)) {
+ if (child.type === 'INSTANCE') found.push(child)
+ else visit(child.id)
+ }
+ }
+ visit(componentId)
+ return found
+}
+
+/**
+ * The layers of an instance that stand for exposed nested instances of its component, in
+ * layer order. Each is matched to its source the way instance sync matches children.
+ */
+export function exposedInstances(graph: SceneGraph, instance: SceneNode): SceneNode[] {
+ const found: SceneNode[] = []
+ walkInstanceSources(graph, instance, (source, target) => {
+ if (source.type !== 'INSTANCE') return true
+ if (source.isExposedInstance) found.push(target)
+ return false
+ })
+ return found
+}
+
+const OWNER_TYPES = new Set<SceneNode['type']>(['INSTANCE', 'COMPONENT', 'COMPONENT_SET'])
+
+/** Why Figma refuses to expose an instance, or null when it may be exposed. */
+export type InstanceExposureIssue = 'not-in-component' | 'not-primary' | 'nothing-to-expose'
+
+/**
+ * Whether an instance may be exposed, under Figma's rules: it sits in a component's own layers
+ * (an instance's copy follows its source) and its component has properties or exposes nested
+ * instances itself.
+ */
+export function instanceExposureIssue(
+ graph: SceneGraph,
+ instance: SceneNode
+): InstanceExposureIssue | null {
+ const owner = instance.parentId
+ ? graph.closest(instance.parentId, (node) => OWNER_TYPES.has(node.type))
+ : undefined
+ if (!owner) return 'not-in-component'
+ if (owner.type === 'INSTANCE') return 'not-primary'
+ const component = instanceMainComponent(graph, instance)
+ const exposes =
+ componentPropertyDefinitions(graph, instance).length > 0 ||
+ (!!component && exposableInstances(graph, component.id).some((node) => node.isExposedInstance))
+ return exposes ? null : 'nothing-to-expose'
+}
diff --git a/packages/scene-graph/src/components/properties.ts b/packages/scene-graph/src/components/properties.ts
index 6776d0ada..1e1396ff1 100644
--- a/packages/scene-graph/src/components/properties.ts
+++ b/packages/scene-graph/src/components/properties.ts
@@ -1,7 +1,8 @@
import type { SceneGraph } from '../index'
-import { getInstanceOverride, setInstanceOverride } from '../instance-overrides'
+import { setInstanceOverride } from '../instance-overrides'
import { findInstanceAncestor } from '../instances'
import { instanceMainComponent } from '../instances/main-component'
+import { walkInstanceSources } from '../instances/source-walk'
import { randomHex } from '../random'
import type {
ComponentPropertyDefinition,
@@ -67,36 +68,19 @@ export function findComponentPropertyTargets(
instance: SceneNode,
propertyId: string
): ComponentPropertyTarget[] {
- if (instance.type !== 'INSTANCE' || !instance.componentId) return []
- const component = graph.getNode(instance.componentId)
- if (!component) return []
const targets: ComponentPropertyTarget[] = []
- const visit = (sourceParent: SceneNode, instanceParent: SceneNode): void => {
- const bySource = new Map<string, SceneNode>()
- for (const child of graph.getChildren(instanceParent.id)) {
- const mapped = getInstanceOverride(
- instance.instanceOverrides,
- instance.id,
- child.id,
- 'sourceComponentId'
- )
- const sourceId = typeof mapped === 'string' ? mapped : child.componentId
- if (!sourceId) continue
- if (bySource.has(sourceId)) throw new Error(`Ambiguous component-property target ${sourceId}`)
- bySource.set(sourceId, child)
- }
- for (const childId of sourceParent.childIds) {
- const source = graph.getNode(childId)
- const target = bySource.get(childId)
- if (!source || !target) continue
+ walkInstanceSources(
+ graph,
+ instance,
+ (source, target) => {
const reference = source.componentPropertyReferences.find(
(candidate) => candidate.propertyId === propertyId
)
if (reference) targets.push({ node: target, field: reference.field, source })
- visit(source, target)
- }
- }
- visit(component, instance)
+ return true
+ },
+ true
+ )
return targets
}
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index fdf894c02..bc3dbf51c 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -16,6 +16,13 @@ export * from './images'
export * from './components/properties'
export * from './slots/frames'
export { instanceMainComponent } from './instances/main-component'
+export { canCreateInstance } from './instances/cycles'
+export {
+ exposableInstances,
+ exposedInstances,
+ instanceExposureIssue,
+ type InstanceExposureIssue
+} from './components/exposure'
export * from './slots/content'
export * from './slots/authoring'
export * from './slots/limits'
diff --git a/packages/scene-graph/src/instances/cycles.ts b/packages/scene-graph/src/instances/cycles.ts
new file mode 100644
index 000000000..a030d8ecf
--- /dev/null
+++ b/packages/scene-graph/src/instances/cycles.ts
@@ -0,0 +1,36 @@
+import type { SceneGraph } from '../'
+import { instanceMainComponent } from './main-component'
+
+/**
+ * Whether placing this definition's instance under `parentId` would make a component contain
+ * itself. Both components and instances above the parent count: an instance's layers are its
+ * component's, so a swap inside one may not bring that component back in.
+ */
+export function canCreateInstance(
+ graph: SceneGraph,
+ componentId: string,
+ parentId: string
+): boolean {
+ if (graph.getNode(componentId)?.type !== 'COMPONENT') return false
+ const ancestors = new Set<string>()
+ graph.closest(parentId, (node) => {
+ if (node.type === 'COMPONENT') ancestors.add(node.id)
+ if (node.type === 'INSTANCE') {
+ const main = instanceMainComponent(graph, node)
+ if (main) ancestors.add(main.id)
+ }
+ return false
+ })
+ const visited = new Set<string>()
+ function reachesAncestor(id: string): boolean {
+ if (ancestors.has(id)) return true
+ if (visited.has(id)) return false
+ visited.add(id)
+ const node = graph.getNode(id)
+ if (!node) return false
+ if (node.type === 'INSTANCE' && node.componentId && reachesAncestor(node.componentId))
+ return true
+ return node.childIds.some(reachesAncestor)
+ }
+ return !reachesAncestor(componentId)
+}
diff --git a/packages/scene-graph/src/instances/source-walk.ts b/packages/scene-graph/src/instances/source-walk.ts
new file mode 100644
index 000000000..62162e5bb
--- /dev/null
+++ b/packages/scene-graph/src/instances/source-walk.ts
@@ -0,0 +1,41 @@
+import type { SceneGraph } from '../'
+import { getInstanceOverride } from '../instance-overrides'
+import type { SceneNode } from '../types'
+
+/**
+ * Walk an instance's layers beside the component layers they copy, matched the way instance
+ * sync matches them. `visit` returns whether to continue into that pair's children. With
+ * `strict`, two layers claiming one source throw instead of the later one winning.
+ */
+export function walkInstanceSources(
+ graph: SceneGraph,
+ instance: SceneNode,
+ visit: (source: SceneNode, target: SceneNode) => boolean,
+ strict = false
+): void {
+ if (instance.type !== 'INSTANCE' || !instance.componentId) return
+ const component = graph.getNode(instance.componentId)
+ if (!component) return
+ const walk = (sourceParent: SceneNode, instanceParent: SceneNode): void => {
+ const bySource = new Map<string, SceneNode>()
+ for (const child of graph.getChildren(instanceParent.id)) {
+ const mapped = getInstanceOverride(
+ instance.instanceOverrides,
+ instance.id,
+ child.id,
+ 'sourceComponentId'
+ )
+ const sourceId = typeof mapped === 'string' ? mapped : child.componentId
+ if (!sourceId) continue
+ if (strict && bySource.has(sourceId))
+ throw new Error(`Ambiguous component-property target ${sourceId}`)
+ bySource.set(sourceId, child)
+ }
+ for (const sourceId of sourceParent.childIds) {
+ const source = graph.getNode(sourceId)
+ const target = bySource.get(sourceId)
+ if (source && target && visit(source, target)) walk(source, target)
+ }
+ }
+ walk(component, instance)
+}
diff --git a/packages/scene-graph/src/instances/sync.ts b/packages/scene-graph/src/instances/sync.ts
index a2efa8d1d..624579f8e 100644
--- a/packages/scene-graph/src/instances/sync.ts
+++ b/packages/scene-graph/src/instances/sync.ts
@@ -268,6 +268,26 @@ function propertyDrivenFields(
return driven
}
+/**
+ * The text and visibility enclosing assignments give an existing child whose layer a property
+ * drives. A layer linked to a property after the instance was made would otherwise keep what it
+ * showed before, since synchronising leaves driven fields alone.
+ */
+function assignedFieldValues(
+ graph: SceneGraph,
+ instChild: SceneNode,
+ compChild: SceneNode
+): Partial<SceneNode> {
+ const values: Partial<SceneNode> = {}
+ for (const reference of compChild.componentPropertyReferences) {
+ const value = enclosingAssignment(graph, instChild, reference.propertyId)
+ if (value === undefined) continue
+ if (reference.field === 'TEXT' && instChild.type === 'TEXT') values.text = value
+ else if (reference.field === 'VISIBLE') values.visible = value === 'true'
+ }
+ return values
+}
+
function childBindingProtection(
graph: SceneGraph,
child: SceneNode,
@@ -485,6 +505,7 @@ export function syncChildren(
copyProp(updates, source, key)
}
+ Object.assign(updates, assignedFieldValues(graph, instChild, compChild))
updateSyncedProps(graph, instChild, updates)
if (
diff --git a/packages/scene-graph/src/node-defaults.ts b/packages/scene-graph/src/node-defaults.ts
index 6c4544b56..18990d4ea 100644
--- a/packages/scene-graph/src/node-defaults.ts
+++ b/packages/scene-graph/src/node-defaults.ts
@@ -186,6 +186,7 @@ export function createDefaultNode(
librarySource: null,
isPublishable: false,
isSymbolPublishable: false,
+ isExposedInstance: false,
symbolDescription: '',
symbolLinks: [],
variantPropSpecs: [],
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index 2ff8eb39f..350128d65 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -579,6 +579,11 @@ export interface SceneNode {
librarySource: LibraryAssetSource | null
isPublishable: boolean
isSymbolPublishable: boolean
+ /**
+ * On an instance inside a component: its properties show on instances of that component,
+ * as Figma's `isExposedInstance`.
+ */
+ isExposedInstance: boolean
symbolDescription: string
symbolLinks: SymbolLink[]
variantPropSpecs: VariantPropSpec[]
diff --git a/packages/scene-graph/tests/components/exposure.test.ts b/packages/scene-graph/tests/components/exposure.test.ts
new file mode 100644
index 000000000..a5c264bbe
--- /dev/null
+++ b/packages/scene-graph/tests/components/exposure.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, test } from 'bun:test'
+
+import {
+ canCreateInstance,
+ exposableInstances,
+ exposedInstances,
+ SceneGraph
+} from '@open-pencil/scene-graph'
+
+function setup() {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0].id
+ const icon = graph.createNode('COMPONENT', page, { name: 'Icon' })
+ const button = graph.createNode('COMPONENT', page, { name: 'Button' })
+ const buttonIcon = graph.createInstance(icon.id, button.id, { name: 'Icon' })
+ const card = graph.createNode('COMPONENT', page, { name: 'Card' })
+ const footer = graph.createNode('FRAME', card.id, { name: 'Footer' })
+ const action = graph.createInstance(button.id, footer.id, { name: 'Action' })
+ const badge = graph.createInstance(icon.id, card.id, { name: 'Badge' })
+ if (!buttonIcon || !action || !badge) throw new Error('instances were not created')
+ return { graph, page, icon, button, card, action, badge }
+}
+
+describe('exposed nested instances', () => {
+ test('a component can expose the instances in its own layers, not inside them', () => {
+ const { graph, card, action, badge } = setup()
+ expect(exposableInstances(graph, card.id).map((node) => node.id)).toEqual([action.id, badge.id])
+ })
+
+ test('an instance finds the layers its component exposes, wherever they are nested', () => {
+ const { graph, page, card, action } = setup()
+ graph.updateNode(action.id, { isExposedInstance: true })
+ const instance = graph.createInstance(card.id, page)
+ if (!instance) throw new Error('card instance was not created')
+
+ const exposed = exposedInstances(graph, instance)
+ expect(exposed.map((node) => node.name)).toEqual(['Action'])
+ expect(exposed[0].id).not.toBe(action.id)
+ expect(exposed[0].parentId).not.toBe(card.id)
+ })
+
+ test('exposure follows the component after the instance was created', () => {
+ const { graph, page, card, action, badge } = setup()
+ const instance = graph.createInstance(card.id, page)
+ if (!instance) throw new Error('card instance was not created')
+ expect(exposedInstances(graph, instance)).toEqual([])
+
+ graph.updateNode(badge.id, { isExposedInstance: true })
+ graph.updateNode(action.id, { isExposedInstance: true })
+ expect(exposedInstances(graph, instance).map((node) => node.name)).toEqual(['Action', 'Badge'])
+ })
+})
+
+describe('instance cycles', () => {
+ test('refuses an instance that would contain its own component', () => {
+ const { graph, icon, button, card } = setup()
+ expect(canCreateInstance(graph, icon.id, card.id)).toBe(true)
+ expect(canCreateInstance(graph, card.id, card.id)).toBe(false)
+ // Button holds Icon, so Icon cannot hold Button, directly or through a nested layer.
+ const frame = graph.createNode('FRAME', icon.id, { name: 'Holder' })
+ expect(canCreateInstance(graph, button.id, frame.id)).toBe(false)
+ })
+
+ test('counts the component of an instance the new one would sit in', () => {
+ const { graph, page, button, card } = setup()
+ const outer = graph.createInstance(card.id, page)
+ const action = outer && graph.getChildren(outer.id).find((node) => node.name === 'Footer')
+ const copy = action && graph.getChildren(action.id).find((node) => node.name === 'Action')
+ if (!copy) throw new Error('Expected the Action copy')
+ // A layer inside a Button, wherever it is shown, cannot become another Button.
+ expect(canCreateInstance(graph, button.id, copy.id)).toBe(false)
+ expect(canCreateInstance(graph, card.id, copy.id)).toBe(false)
+ })
+})
diff --git a/packages/vue/src/controls/component-props/authoring.ts b/packages/vue/src/controls/component-props/authoring.ts
new file mode 100644
index 000000000..c982c65db
--- /dev/null
+++ b/packages/vue/src/controls/component-props/authoring.ts
@@ -0,0 +1,118 @@
+import { uniqBy } from 'es-toolkit/array'
+import { computed } from 'vue'
+
+import { instanceExposureIssue, type ComponentPropertyType } from '@open-pencil/scene-graph'
+
+import { useEditor } from '#vue/editor/context'
+import { useSceneComputed } from '#vue/internal/scene-computed/use'
+
+import { groupComponentBindings } from './bindings'
+import { instanceSwapOptions, swapOptionLabel } from './model'
+
+const AUTHORED_TYPES = new Set<ComponentPropertyType>(['TEXT', 'BOOLEAN', 'INSTANCE_SWAP'])
+
+/** The selected main component's text, boolean and swap properties, and its nested instances. */
+export function useComponentPropertyAuthoring() {
+ const editor = useEditor()
+ const context = useSceneComputed(() => {
+ const selected = editor.getSelectedNodes()
+ return selected.length === 1 ? editor.getComponentPropertyAuthoring(selected[0].id) : null
+ })
+ /** A set's variants may own properties of their own besides the shared ones. */
+ const variants = useSceneComputed(() => {
+ const owner = context.value?.owner
+ return owner?.type === 'COMPONENT_SET'
+ ? editor.graph.getChildren(owner.id).filter((node) => node.type === 'COMPONENT')
+ : []
+ })
+ const owners = computed(() =>
+ context.value?.node.type === 'COMPONENT_SET'
+ ? [context.value.owner, ...variants.value]
+ : (context.value?.owners ?? [])
+ )
+ const definitions = useSceneComputed(() =>
+ owners.value.flatMap((owner) =>
+ owner.componentPropertyDefinitions
+ .filter((definition) => AUTHORED_TYPES.has(definition.type))
+ .map((definition) => {
+ const bindings = editor
+ .getComponentPropertyBindings(owner.id, definition.id)
+ .flatMap((binding) => {
+ const node = editor.graph.getNode(binding.nodeId)
+ return node ? [{ ...binding, node }] : []
+ })
+ return {
+ ...definition,
+ ownerId: owner.id,
+ bindingGroups: groupComponentBindings(editor.graph, bindings)
+ }
+ })
+ )
+ )
+ const components = useSceneComputed(() =>
+ [...editor.graph.getAllNodes()].filter((node) => node.type === 'COMPONENT')
+ )
+ /** Nested instances a component, or every variant of a set, can expose. */
+ const nestedInstances = useSceneComputed(() => {
+ const selected = context.value?.node
+ if (!selected || (selected.type !== 'COMPONENT' && selected.type !== 'COMPONENT_SET')) return []
+ const sources = selected.type === 'COMPONENT_SET' ? variants.value : [selected]
+ return uniqBy(
+ sources.flatMap((source) => editor.getExposableInstances(source.id)),
+ (node) => node.id
+ ).map((node) => ({
+ id: node.id,
+ name: node.name,
+ exposed: node.isExposedInstance,
+ available: !instanceExposureIssue(editor.graph, node)
+ }))
+ })
+
+ /**
+ * Components a swap property's default can show. A linked layer must not end up holding its own
+ * component, and a property with no layers yet must still fit inside every owning component.
+ */
+ function swapOptions(propertyId: string) {
+ const definition = definitions.value.find((item) => item.id === propertyId)
+ const layerParents =
+ definition?.bindingGroups.flatMap((group) =>
+ group.bindings.flatMap((binding) => (binding.node.parentId ? [binding.node.parentId] : []))
+ ) ?? []
+ const owners = variants.value.length ? variants.value : (context.value?.owners ?? [])
+ return instanceSwapOptions(
+ editor.graph,
+ components.value,
+ definition ?? { id: '', name: '', type: 'INSTANCE_SWAP', defaultValue: '' },
+ definition?.defaultValue ?? '',
+ [
+ ...layerParents,
+ ...owners.filter((owner) => owner.type === 'COMPONENT').map((owner) => owner.id)
+ ]
+ )
+ }
+
+ return {
+ context,
+ definitions,
+ nestedInstances,
+ variantCount: computed(() => variants.value.length),
+ editable: computed(() => !!context.value?.editable),
+ swapOptions,
+ componentName: (id: string) => {
+ const node = editor.graph.getNode(id)
+ return node ? swapOptionLabel(editor.graph, node) : id
+ },
+ create: editor.createComponentProperty,
+ expose: editor.exposeComponentProperty,
+ bind: editor.bindComponentProperty,
+ rename: editor.renameComponentProperty,
+ setDefault: editor.setComponentPropertyDefault,
+ remove: editor.deleteComponentProperty,
+ move: editor.moveComponentProperty,
+ setExposed: editor.setInstanceExposed,
+ selectOwner: () => {
+ if (context.value) editor.select([context.value.owner.id])
+ },
+ select: (nodeId: string) => editor.select([nodeId])
+ }
+}
diff --git a/packages/vue/src/controls/component-props/bindings.ts b/packages/vue/src/controls/component-props/bindings.ts
new file mode 100644
index 000000000..c27ff3cc9
--- /dev/null
+++ b/packages/vue/src/controls/component-props/bindings.ts
@@ -0,0 +1,65 @@
+import type {
+ ComponentPropertyReferenceField,
+ SceneGraph,
+ SceneNode
+} from '@open-pencil/scene-graph'
+
+export interface ComponentBinding {
+ nodeId: string
+ name: string
+ field: ComponentPropertyReferenceField
+ node: SceneNode
+ variantId: string | null
+ variantName: string | null
+}
+
+export interface ComponentBindingGroup {
+ key: string
+ name: string
+ node: SceneNode
+ bindings: ComponentBinding[]
+}
+
+/** A structural path distinguishes same-named layers in different containers or sibling slots. */
+function bindingPath(graph: SceneGraph, node: SceneNode, variantId: string): string {
+ const path: Array<[string, string, number]> = []
+ graph.closest(node.id, (current) => {
+ if (current.id === variantId) return true
+ const peers = (current.parentId ? graph.getChildren(current.parentId) : []).filter(
+ (sibling) => sibling.type === current.type && sibling.name === current.name
+ )
+ path.unshift([current.type, current.name, peers.findIndex((peer) => peer.id === current.id)])
+ return false
+ })
+ return JSON.stringify(path)
+}
+
+export function groupComponentBindings(
+ graph: SceneGraph,
+ bindings: Omit<ComponentBinding, 'variantId' | 'variantName'>[]
+): ComponentBindingGroup[] {
+ const groups = new Map<string, ComponentBindingGroup>()
+ for (const binding of bindings) {
+ const variant = graph.closest(
+ binding.nodeId,
+ (node) =>
+ node.type === 'COMPONENT' &&
+ !!node.parentId &&
+ graph.getNode(node.parentId)?.type === 'COMPONENT_SET'
+ )
+ const key = variant
+ ? `${binding.field}:${bindingPath(graph, binding.node, variant.id)}`
+ : binding.nodeId
+ let group = groups.get(key)
+ if (!group) {
+ group = { key, name: binding.name, node: binding.node, bindings: [] }
+ groups.set(key, group)
+ }
+ group.bindings.push({
+ ...binding,
+ variantId: variant?.id ?? null,
+ variantName: variant?.name ?? null
+ })
+ }
+ return [...groups.values()]
+}
diff --git a/packages/vue/src/controls/component-props/index.ts b/packages/vue/src/controls/component-props/index.ts
index 2551633ff..69050f5aa 100644
--- a/packages/vue/src/controls/component-props/index.ts
+++ b/packages/vue/src/controls/component-props/index.ts
@@ -1,2 +1,4 @@
+export * from './authoring'
+export * from './bindings'
export * from './model'
export * from './use'
diff --git a/packages/vue/src/controls/component-props/model.ts b/packages/vue/src/controls/component-props/model.ts
index f027dca37..2455becee 100644
--- a/packages/vue/src/controls/component-props/model.ts
+++ b/packages/vue/src/controls/component-props/model.ts
@@ -1,7 +1,9 @@
import type { Editor } from '@open-pencil/core/editor'
+import { canCreateInstance } from '@open-pencil/scene-graph'
import type {
ComponentPropertyDefinition,
ComponentPropertyType,
+ SceneGraph,
SceneNode
} from '@open-pencil/scene-graph'
@@ -40,17 +42,33 @@ export function mergedComponentPropertyValue(values: string[]): MixedValue<strin
return values.every((value) => value === first) ? first : MIXED
}
+/** A swap choice's name; a variant names its set too, since variant names repeat across sets. */
+export function swapOptionLabel(graph: SceneGraph, component: SceneNode): string {
+ const parent = component.parentId ? graph.getNode(component.parentId) : undefined
+ return parent?.type === 'COMPONENT_SET' ? `${parent.name} / ${component.name}` : component.name
+}
+
+/**
+ * Components a swap property can show, preferred ones first. `parentIds` are the containers of
+ * the layers it swaps; a component that holds one of them would contain itself and is left out.
+ */
export function instanceSwapOptions(
+ graph: SceneGraph,
components: SceneNode[],
definition: ComponentPropertyDefinition,
- value: string
+ value: string,
+ parentIds: readonly string[] = []
): ComponentPropertyOption[] {
const preferred = new Set(definition.preferredValues)
const options: ComponentPropertyOption[] = components
- .filter((node) => node.type === 'COMPONENT')
+ .filter(
+ (node) =>
+ node.type === 'COMPONENT' &&
+ parentIds.every((parentId) => canCreateInstance(graph, node.id, parentId))
+ )
.map((node) => ({
value: node.id,
- label: node.name,
+ label: swapOptionLabel(graph, node),
preferred:
preferred.has(node.componentKey ?? '') || preferred.has(node.sourceLibraryKey ?? '')
}))
@@ -59,7 +77,12 @@ export function instanceSwapOptions(
Number(right.preferred) - Number(left.preferred) || left.label.localeCompare(right.label)
)
if (value && !options.some((option) => option.value === value)) {
- options.push({ value, label: value, missing: true })
+ const current = graph.getNode(value)
+ options.push({
+ value,
+ label: current ? swapOptionLabel(graph, current) : value,
+ missing: !current
+ })
}
return options
}
diff --git a/packages/vue/src/controls/component-props/use.ts b/packages/vue/src/controls/component-props/use.ts
index eb8d56a29..5ea493081 100644
--- a/packages/vue/src/controls/component-props/use.ts
+++ b/packages/vue/src/controls/component-props/use.ts
@@ -1,5 +1,6 @@
import { computed, watch } from 'vue'
+import { exposedInstances, findComponentPropertyTargets } from '@open-pencil/scene-graph'
import type { ComponentPropertyDefinition, SceneNode } from '@open-pencil/scene-graph'
import {
@@ -27,7 +28,11 @@ function batchKey(propertyId: string, targets: SceneNode[]): string {
return [propertyId, ...targets.map((node) => node.id)].join(':')
}
-export function useComponentProperties() {
+/**
+ * Value controls for the selected instances, or for `targets` when given, such as an exposed
+ * nested instance shown under the instance that contains it.
+ */
+export function useComponentProperties(targets?: () => SceneNode[]) {
const editor = useEditor()
const batch = useUndoBatch(editor.undo, editor.beginInteractiveEdit)
const retainedActivity = useRetainedActivity()
@@ -45,11 +50,12 @@ export function useComponentProperties() {
)
}
const instances = useSceneComputed(() =>
- editor.getSelectedNodes().filter((node) => node.type === 'INSTANCE')
+ (targets ? targets() : editor.getSelectedNodes()).filter((node) => node.type === 'INSTANCE')
)
const selectedCount = computed(() => editor.state.selectedIds.size)
const allSelectedAreInstances = computed(
- () => instances.value.length > 0 && instances.value.length === selectedCount.value
+ () =>
+ instances.value.length > 0 && (!!targets || instances.value.length === selectedCount.value)
)
const definitionSets = useSceneComputed(() =>
instances.value.map((instance) => editor.getInstanceComponentPropertyDefinitions(instance.id))
@@ -76,7 +82,19 @@ export function useComponentProperties() {
options = variantOptions(editor, firstInstance, definition.name)
} else if (definition.type === 'INSTANCE_SWAP') {
componentNodes ??= [...editor.graph.getAllNodes()]
- options = instanceSwapOptions(componentNodes, definition, value === MIXED ? '' : value)
+ // Each layer the property swaps, in every selected instance, must not hold its own choice.
+ const parentIds = instances.value.flatMap((instance) =>
+ findComponentPropertyTargets(editor.graph, instance, definition.id).flatMap((target) =>
+ target.node.parentId ? [target.node.parentId] : []
+ )
+ )
+ options = instanceSwapOptions(
+ editor.graph,
+ componentNodes,
+ definition,
+ value === MIXED ? '' : value,
+ parentIds
+ )
}
return {
id: definition.id,
@@ -136,3 +154,16 @@ export function useComponentProperties() {
return { active, controls, setValue, setTextValue, flush: batch.flush }
}
+
+/** The exposed nested instances of the one selected instance, each shown as its own group. */
+export function useExposedInstances() {
+ const editor = useEditor()
+ return useSceneComputed(() => {
+ const selected = editor.getSelectedNodes()
+ if (selected.length !== 1 || selected[0].type !== 'INSTANCE') return []
+ return exposedInstances(editor.graph, selected[0]).map((node) => ({
+ id: node.id,
+ name: node.name
+ }))
+ })
+}
diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.json
index 84ef1dab2..9c15825c0 100644
--- a/packages/vue/src/i18n/locales/de/panels.json
+++ b/packages/vue/src/i18n/locales/de/panels.json
@@ -338,6 +338,28 @@
"documentation": "Dokumentation",
"openDocs": "Dokumentation öffnen",
"properties": "Eigenschaften",
+ "componentPropertyText": "Text",
+ "componentPropertyBoolean": "Boolean",
+ "componentPropertySwap": "Instanz austauschen",
+ "createComponentProperty": "Eigenschaft erstellen…",
+ "applyComponentProperty": "Komponenteneigenschaft auf {field} anwenden",
+ "goToComponentProperty": "Zur Eigenschaft",
+ "detachComponentProperty": "Eigenschaft trennen",
+ "deleteComponentProperty": "Eigenschaft löschen",
+ "componentPropertyName": "Name",
+ "componentPropertyDefault": "Standardwert",
+ "propertyOn": "An",
+ "propertyOff": "Aus",
+ "textContent": "Textinhalt",
+ "layerVisibility": "Sichtbarkeit",
+ "nestedInstance": "Instanz",
+ "nestedInstances": "Verschachtelte Instanzen",
+ "hideNestedInstance": "{name} nicht mehr freigeben",
+ "nothingToExpose": "Ihre Komponente hat keine Eigenschaften zum Freigeben",
+ "showLayer": "{name} anzeigen",
+ "content": "Inhalt",
+ "allVariants": "Alle Varianten",
+ "usedInVariants": "{count} von {total} Varianten",
"removeFill": "Füllung entfernen",
"removeStroke": "Kontur entfernen",
"removeEffect": "Effekt entfernen",
diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.json
index 4ef6d5d81..c6e8a067c 100644
--- a/packages/vue/src/i18n/locales/es/panels.json
+++ b/packages/vue/src/i18n/locales/es/panels.json
@@ -354,6 +354,28 @@
"documentation": "Documentación",
"openDocs": "Abrir docs",
"properties": "Propiedades",
+ "componentPropertyText": "Texto",
+ "componentPropertyBoolean": "Booleano",
+ "componentPropertySwap": "Intercambio de instancia",
+ "createComponentProperty": "Crear propiedad…",
+ "applyComponentProperty": "Aplicar propiedad de componente a {field}",
+ "goToComponentProperty": "Ir a la propiedad",
+ "detachComponentProperty": "Separar propiedad",
+ "deleteComponentProperty": "Eliminar propiedad",
+ "componentPropertyName": "Nombre",
+ "componentPropertyDefault": "Valor predeterminado",
+ "propertyOn": "Activado",
+ "propertyOff": "Desactivado",
+ "textContent": "Contenido de texto",
+ "layerVisibility": "Visibilidad",
+ "nestedInstance": "Instancia",
+ "nestedInstances": "Instancias anidadas",
+ "hideNestedInstance": "Dejar de exponer {name}",
+ "nothingToExpose": "Su componente no tiene propiedades que exponer",
+ "showLayer": "Mostrar {name}",
+ "content": "Contenido",
+ "allVariants": "Todas las variantes",
+ "usedInVariants": "{count} de {total} variantes",
"removeFill": "Eliminar relleno",
"removeStroke": "Eliminar trazo",
"removeEffect": "Eliminar efecto",
diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.json
index 7c095639e..7f34302b7 100644
--- a/packages/vue/src/i18n/locales/fr/panels.json
+++ b/packages/vue/src/i18n/locales/fr/panels.json
@@ -338,6 +338,28 @@
"documentation": "Documentation",
"openDocs": "Ouvrir la doc",
"properties": "Propriétés",
+ "componentPropertyText": "Texte",
+ "componentPropertyBoolean": "Booléen",
+ "componentPropertySwap": "Permutation d’instance",
+ "createComponentProperty": "Créer une propriété…",
+ "applyComponentProperty": "Appliquer une propriété de composant à {field}",
+ "goToComponentProperty": "Aller à la propriété",
+ "detachComponentProperty": "Dissocier la propriété",
+ "deleteComponentProperty": "Supprimer la propriété",
+ "componentPropertyName": "Nom",
+ "componentPropertyDefault": "Valeur par défaut",
+ "propertyOn": "Activé",
+ "propertyOff": "Désactivé",
+ "textContent": "Contenu du texte",
+ "layerVisibility": "Visibilité",
+ "nestedInstance": "Instance",
+ "nestedInstances": "Instances imbriquées",
+ "hideNestedInstance": "Ne plus exposer {name}",
+ "nothingToExpose": "Son composant n’a aucune propriété à exposer",
+ "showLayer": "Afficher {name}",
+ "content": "Contenu",
+ "allVariants": "Toutes les variantes",
+ "usedInVariants": "{count} variantes sur {total}",
"removeFill": "Supprimer le remplissage",
"removeStroke": "Supprimer le contour",
"removeEffect": "Supprimer l’effet",
diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.json
index 1a3d2deed..daf1e06ab 100644
--- a/packages/vue/src/i18n/locales/it/panels.json
+++ b/packages/vue/src/i18n/locales/it/panels.json
@@ -338,6 +338,28 @@
"documentation": "Documentazione",
"openDocs": "Apri documentazione",
"properties": "Proprietà",
+ "componentPropertyText": "Testo",
+ "componentPropertyBoolean": "Booleano",
+ "componentPropertySwap": "Scambio di istanza",
+ "createComponentProperty": "Crea proprietà…",
+ "applyComponentProperty": "Applica proprietà del componente a {field}",
+ "goToComponentProperty": "Vai alla proprietà",
+ "detachComponentProperty": "Scollega proprietà",
+ "deleteComponentProperty": "Elimina proprietà",
+ "componentPropertyName": "Nome",
+ "componentPropertyDefault": "Valore predefinito",
+ "propertyOn": "Attivo",
+ "propertyOff": "Disattivo",
+ "textContent": "Contenuto del testo",
+ "layerVisibility": "Visibilità",
+ "nestedInstance": "Istanza",
+ "nestedInstances": "Istanze nidificate",
+ "hideNestedInstance": "Non esporre più {name}",
+ "nothingToExpose": "Il suo componente non ha proprietà da esporre",
+ "showLayer": "Mostra {name}",
+ "content": "Contenuto",
+ "allVariants": "Tutte le varianti",
+ "usedInVariants": "{count} varianti su {total}",
"removeFill": "Rimuovi riempimento",
"removeStroke": "Rimuovi traccia",
"removeEffect": "Rimuovi effetto",
diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.json
index 6b407655f..c0fee558a 100644
--- a/packages/vue/src/i18n/locales/ja/panels.json
+++ b/packages/vue/src/i18n/locales/ja/panels.json
@@ -348,6 +348,28 @@
"documentation": "ドキュメント",
"openDocs": "ドキュメントを開く",
"properties": "プロパティ",
+ "componentPropertyText": "テキスト",
+ "componentPropertyBoolean": "ブール値",
+ "componentPropertySwap": "インスタンスの入れ替え",
+ "createComponentProperty": "プロパティを作成…",
+ "applyComponentProperty": "{field}にコンポーネントプロパティを適用",
+ "goToComponentProperty": "プロパティに移動",
+ "detachComponentProperty": "プロパティを解除",
+ "deleteComponentProperty": "プロパティを削除",
+ "componentPropertyName": "名前",
+ "componentPropertyDefault": "デフォルト値",
+ "propertyOn": "オン",
+ "propertyOff": "オフ",
+ "textContent": "テキストコンテンツ",
+ "layerVisibility": "表示",
+ "nestedInstance": "インスタンス",
+ "nestedInstances": "ネストされたインスタンス",
+ "hideNestedInstance": "{name}の公開を停止",
+ "nothingToExpose": "このコンポーネントには公開できるプロパティがありません",
+ "showLayer": "{name}を表示",
+ "content": "コンテンツ",
+ "allVariants": "すべてのバリアント",
+ "usedInVariants": "{total}個中{count}個のバリアント",
"removeFill": "塗りを削除",
"removeStroke": "線を削除",
"removeEffect": "エフェクトを削除",
diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.json
index 72a8c356c..4514f2241 100644
--- a/packages/vue/src/i18n/locales/pl/panels.json
+++ b/packages/vue/src/i18n/locales/pl/panels.json
@@ -344,6 +344,28 @@
"documentation": "Dokumentacja",
"openDocs": "Otwórz dokumentację",
"properties": "Właściwości",
+ "componentPropertyText": "Tekst",
+ "componentPropertyBoolean": "Wartość logiczna",
+ "componentPropertySwap": "Zamiana instancji",
+ "createComponentProperty": "Utwórz właściwość…",
+ "applyComponentProperty": "Zastosuj właściwość komponentu do: {field}",
+ "goToComponentProperty": "Przejdź do właściwości",
+ "detachComponentProperty": "Odłącz właściwość",
+ "deleteComponentProperty": "Usuń właściwość",
+ "componentPropertyName": "Nazwa",
+ "componentPropertyDefault": "Wartość domyślna",
+ "propertyOn": "Włączone",
+ "propertyOff": "Wyłączone",
+ "textContent": "Treść tekstu",
+ "layerVisibility": "Widoczność",
+ "nestedInstance": "Instancja",
+ "nestedInstances": "Zagnieżdżone instancje",
+ "hideNestedInstance": "Przestań udostępniać {name}",
+ "nothingToExpose": "Jej komponent nie ma właściwości do udostępnienia",
+ "showLayer": "Pokaż {name}",
+ "content": "Treść",
+ "allVariants": "Wszystkie warianty",
+ "usedInVariants": "{count} z {total} wariantów",
"removeFill": "Usuń wypełnienie",
"removeStroke": "Usuń obrys",
"removeEffect": "Usuń efekt",
diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.json
index 10535a0d4..9055582e7 100644
--- a/packages/vue/src/i18n/locales/ru/panels.json
+++ b/packages/vue/src/i18n/locales/ru/panels.json
@@ -344,6 +344,28 @@
"documentation": "Документация",
"openDocs": "Открыть документацию",
"properties": "Свойства",
+ "componentPropertyText": "Текст",
+ "componentPropertyBoolean": "Логическое",
+ "componentPropertySwap": "Замена экземпляра",
+ "createComponentProperty": "Создать свойство…",
+ "applyComponentProperty": "Применить свойство компонента к полю «{field}»",
+ "goToComponentProperty": "Перейти к свойству",
+ "detachComponentProperty": "Отвязать свойство",
+ "deleteComponentProperty": "Удалить свойство",
+ "componentPropertyName": "Название",
+ "componentPropertyDefault": "Значение по умолчанию",
+ "propertyOn": "Вкл.",
+ "propertyOff": "Выкл.",
+ "textContent": "Текст",
+ "layerVisibility": "Видимость",
+ "nestedInstance": "Экземпляр",
+ "nestedInstances": "Вложенные экземпляры",
+ "hideNestedInstance": "Не показывать свойства {name}",
+ "nothingToExpose": "У его компонента нет свойств, которые можно показать",
+ "showLayer": "Показывать {name}",
+ "content": "Содержимое",
+ "allVariants": "Все варианты",
+ "usedInVariants": "{count} из {total} вариантов",
"removeFill": "Удалить заливку",
"removeStroke": "Удалить обводку",
"removeEffect": "Удалить эффект",
diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.json
index fd71dbc88..6ddcf7523 100644
--- a/packages/vue/src/i18n/locales/zh-cn/panels.json
+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json
@@ -332,6 +332,28 @@
"documentation": "文档",
"openDocs": "打开文档",
"properties": "属性",
+ "componentPropertyText": "文本",
+ "componentPropertyBoolean": "布尔值",
+ "componentPropertySwap": "实例切换",
+ "createComponentProperty": "创建属性…",
+ "applyComponentProperty": "将组件属性应用到{field}",
+ "goToComponentProperty": "转到属性",
+ "detachComponentProperty": "分离属性",
+ "deleteComponentProperty": "删除属性",
+ "componentPropertyName": "名称",
+ "componentPropertyDefault": "默认值",
+ "propertyOn": "开",
+ "propertyOff": "关",
+ "textContent": "文本内容",
+ "layerVisibility": "可见性",
+ "nestedInstance": "实例",
+ "nestedInstances": "嵌套实例",
+ "hideNestedInstance": "停止公开 {name}",
+ "nothingToExpose": "其组件没有可公开的属性",
+ "showLayer": "显示 {name}",
+ "content": "内容",
+ "allVariants": "所有变体",
+ "usedInVariants": "{total} 个变体中的 {count} 个",
"removeFill": "移除填充",
"removeStroke": "移除描边",
"removeEffect": "移除效果",
diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.ts
index cd1e9565f..4b49c1141 100644
--- a/packages/vue/src/i18n/messages/panels.ts
+++ b/packages/vue/src/i18n/messages/panels.ts
@@ -95,6 +95,28 @@ export const panelMessageDefaults = {
documentation: 'Documentation',
openDocs: 'Open docs',
properties: 'Properties',
+ componentPropertyText: 'Text',
+ componentPropertyBoolean: 'Boolean',
+ componentPropertySwap: 'Instance swap',
+ createComponentProperty: 'Create property…',
+ applyComponentProperty: params('Apply component property to {field}'),
+ goToComponentProperty: 'Go to property',
+ detachComponentProperty: 'Detach property',
+ deleteComponentProperty: 'Delete property',
+ componentPropertyName: 'Name',
+ componentPropertyDefault: 'Default value',
+ propertyOn: 'On',
+ propertyOff: 'Off',
+ textContent: 'Text content',
+ layerVisibility: 'Visibility',
+ nestedInstance: 'Instance',
+ nestedInstances: 'Nested instances',
+ hideNestedInstance: params('Stop exposing {name}'),
+ nothingToExpose: 'Its component has no properties to expose',
+ showLayer: params('Show {name}'),
+ content: 'Content',
+ allVariants: 'All variants',
+ usedInVariants: params('{count} of {total} variants'),
xAxis: 'X Axis',
yAxis: 'Y Axis',
diff --git a/packages/vue/src/index.ts b/packages/vue/src/index.ts
index 66743efb9..8fed65c3c 100644
--- a/packages/vue/src/index.ts
+++ b/packages/vue/src/index.ts
@@ -243,8 +243,11 @@ export {
compatibleComponentPropertyDefinitions,
instanceSwapOptions,
mergedComponentPropertyValue,
- useComponentProperties
+ useComponentProperties,
+ useComponentPropertyAuthoring,
+ useExposedInstances
} from '#vue/controls/component-props'
+export type { ComponentBinding, ComponentBindingGroup } from '#vue/controls/component-props'
export {
slotInstanceOptions,
slotLimits,
diff --git a/packages/vue/tests/controls/component-props/bindings.test.ts b/packages/vue/tests/controls/component-props/bindings.test.ts
new file mode 100644
index 000000000..bfa97c132
--- /dev/null
+++ b/packages/vue/tests/controls/component-props/bindings.test.ts
@@ -0,0 +1,21 @@
+import { expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { groupComponentBindings } from '#vue/controls/component-props/bindings'
+
+test('groups repeated structural bindings across 23 variants without merging same-named siblings', () => {
+ const graph = new SceneGraph()
+ const set = graph.createNode('COMPONENT_SET', graph.getPages()[0].id)
+ const bindings = Array.from({ length: 23 }, (_, index) => {
+ const variant = graph.createNode('COMPONENT', set.id, { name: `Variant ${index}` })
+ return [0, 1].map(() => {
+ const node = graph.createNode('TEXT', variant.id, { name: 'Label' })
+ return { node, name: node.name, nodeId: node.id, field: 'TEXT' as const }
+ })
+ }).flat()
+ const groups = groupComponentBindings(graph, bindings)
+ expect(groups).toHaveLength(2)
+ expect(groups.map((group) => group.bindings.length)).toEqual([23, 23])
+ expect(new Set(groups[0].bindings.map((binding) => binding.variantId)).size).toBe(23)
+})
diff --git a/packages/vue/tests/controls/component-props/swap-options.test.ts b/packages/vue/tests/controls/component-props/swap-options.test.ts
new file mode 100644
index 000000000..3d1d9333b
--- /dev/null
+++ b/packages/vue/tests/controls/component-props/swap-options.test.ts
@@ -0,0 +1,43 @@
+import { expect, test } from 'bun:test'
+
+import { SceneGraph } from '@open-pencil/scene-graph'
+
+import { instanceSwapOptions } from '#vue/controls/component-props/model'
+
+test('leaves out swaps that would contain themselves and names variants with their set', () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const star = graph.createNode('COMPONENT', pageId, { name: 'Star' })
+ const button = graph.createNode('COMPONENT', pageId, { name: 'Button' })
+ const icon = graph.createInstance(star.id, button.id, { name: 'Icon' })
+ const card = graph.createNode('COMPONENT', pageId, { name: 'Card' })
+ const action = graph.createInstance(button.id, card.id, { name: 'Action' })
+ const badge = graph.createNode('COMPONENT_SET', pageId, { name: 'Badge' })
+ const info = graph.createNode('COMPONENT', badge.id, { name: 'State=Info' })
+ if (!icon || !action) throw new Error('Expected instances')
+ const definition = {
+ id: '1:4',
+ name: 'Icon',
+ type: 'INSTANCE_SWAP' as const,
+ defaultValue: star.id
+ }
+ const components = [...graph.getAllNodes()]
+
+ // The icon inside Button, as Card's Action shows it: neither Button nor Card can replace it.
+ const options = instanceSwapOptions(graph, components, definition, star.id, [action.id])
+ expect(options.map((option) => option.label)).toEqual(['Badge / State=Info', 'Star'])
+ expect(options.map((option) => option.value)).toEqual([info.id, star.id])
+})
+
+test('a swap with no layers yet still has to fit inside its own component', () => {
+ const graph = new SceneGraph()
+ const pageId = graph.getPages()[0].id
+ const star = graph.createNode('COMPONENT', pageId, { name: 'Star' })
+ const button = graph.createNode('COMPONENT', pageId, { name: 'Button' })
+ const card = graph.createNode('COMPONENT', pageId, { name: 'Card' })
+ graph.createInstance(button.id, card.id)
+ const definition = { id: '1:5', name: 'Icon', type: 'INSTANCE_SWAP' as const, defaultValue: '' }
+
+ const options = instanceSwapOptions(graph, [star, button, card], definition, '', [button.id])
+ expect(options.map((option) => option.label)).toEqual(['Star'])
+})
diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vue
index 0b6ba3583..4b40d6a40 100644
--- a/src/components/DesignPanel.vue
+++ b/src/components/DesignPanel.vue
@@ -14,8 +14,12 @@ 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 ComponentPropertyListSection from './properties/component-properties/ComponentPropertyListSection.vue'
import InstanceUpdateAction from './properties/component-properties/instance-update/InstanceUpdateAction.vue'
+import PropertyBindButton from './properties/component-properties/PropertyBindButton.vue'
+import PropertyBoundField from './properties/component-properties/PropertyBoundField.vue'
import SlotAuthoringSection from './properties/component-properties/slot/SlotAuthoringSection.vue'
+import { usePropertyBinding } from './properties/component-properties/usePropertyBinding'
import VariantAuthoringSection from './properties/component-properties/variant/VariantAuthoringSection.vue'
import ConstraintsSection from './properties/constraints/ConstraintsSection.vue'
import EffectsSection from './properties/EffectsSection.vue'
@@ -38,6 +42,8 @@ const store = useEditorStore()
const libraryService = useLibraryService()
const activeTool = computed(() => store.state.activeTool)
const { selectedNode: node, selectedCount: multiCount } = useSelectionState()
+const swapBinding = usePropertyBinding('INSTANCE_SWAP')
+const swapLinked = computed(() => !!swapBinding.definition.value)
const showBooleanOperations = computed(() => multiCount.value >= 2)
const { getCommand } = useEditorCommands()
const goToMainComponent = getCommand('selection.goToMainComponent')
@@ -118,8 +124,13 @@ const { panels } = useI18n()
</span>
</Tip>
</template>
- <span role="heading" aria-level="2">{{ node.name }}</span>
+ <span role="heading" aria-level="2" class="min-w-0">
+ <!-- A swap linked to a property shows the property in place of the layer, as Figma does. -->
+ <PropertyBoundField v-if="swapLinked" field="INSTANCE_SWAP" compact />
+ <template v-else>{{ node.name }}</template>
+ </span>
<template #actions>
+ <PropertyBindButton v-if="node.type === 'INSTANCE'" field="INSTANCE_SWAP" />
<InstanceUpdateAction
v-if="node.type === 'INSTANCE'"
:node="node"
@@ -157,6 +168,7 @@ const { panels } = useI18n()
"
/>
+ <ComponentPropertyListSection />
<SlotAuthoringSection />
<BehaviourPanel v-if="node.type === 'COMPONENT' || node.type === 'COMPONENT_SET'" />
diff --git a/src/components/properties/AppearanceSection.vue b/src/components/properties/AppearanceSection.vue
index 7313fbc05..e26217520 100644
--- a/src/components/properties/AppearanceSection.vue
+++ b/src/components/properties/AppearanceSection.vue
@@ -11,6 +11,9 @@ import PanelGrid from '@/components/ui/panel/PanelGrid.vue'
import PanelSection from '@/components/ui/panel/PanelSection.vue'
import AppSelect from '@/components/ui/select/AppSelect.vue'
+import PropertyBindButton from './component-properties/PropertyBindButton.vue'
+import PropertyBoundField from './component-properties/PropertyBoundField.vue'
+
const { panels } = useI18n()
type BlendModeSelectValue = BlendMode | 'MIXED'
@@ -42,6 +45,7 @@ function blendModeOptions(value: BlendMode | typeof MIXED) {
>
<PanelSection v-if="active" :label="panels.appearance">
<template #actions>
+ <PropertyBindButton field="VISIBLE" />
<IconButton
:label="panels.toggleVisibility"
:active="visibilityState === 'hidden'"
@@ -52,6 +56,7 @@ function blendModeOptions(value: BlendMode | typeof MIXED) {
<icon-lucide-eye v-else class="size-3.5 opacity-50" />
</IconButton>
</template>
+ <PropertyBoundField field="VISIBLE" />
<PanelGrid :columns="2" distribution="wide-first">
<PanelFieldGroup :label="panels.blendMode">
diff --git a/src/components/properties/TypographySection.vue b/src/components/properties/TypographySection.vue
index 37158e193..cbafb1b1d 100644
--- a/src/components/properties/TypographySection.vue
+++ b/src/components/properties/TypographySection.vue
@@ -20,6 +20,9 @@ import AppSelect from '@/components/ui/select/AppSelect.vue'
import SegmentedControl from '@/components/ui/select/SegmentedControl.vue'
import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'
+import PropertyBindButton from './component-properties/PropertyBindButton.vue'
+import PropertyBoundField from './component-properties/PropertyBoundField.vue'
+
const { panels, menu } = useI18n()
const fontLoader = { load: loadFont }
const alignmentOptions = computed(() => [
@@ -57,6 +60,10 @@ function featureEnabled(features: Array<{ tag: string; enabled: boolean }>, tag:
<template>
<TypographyControlsRoot v-slot="ctx" :font-loader="fontLoader">
<PanelSection v-if="ctx.node.value" :label="panels.typography">
+ <template #actions>
+ <PropertyBindButton field="TEXT" />
+ </template>
+ <PropertyBoundField field="TEXT" :label="panels.content" />
<SharedStyleField kind="text" :label="panels.textStyle" />
<div class="mb-1.5 flex min-w-0 items-center gap-1.5">
diff --git a/src/components/properties/component-properties/ComponentPropertiesSection.vue b/src/components/properties/component-properties/ComponentPropertiesSection.vue
index 663f6ef2e..8447c0d5e 100644
--- a/src/components/properties/component-properties/ComponentPropertiesSection.vue
+++ b/src/components/properties/component-properties/ComponentPropertiesSection.vue
@@ -1,63 +1,37 @@
<script setup lang="ts">
import { computed } from 'vue'
-import { MIXED, useComponentProperties, useI18n, useSlotProperties } from '@open-pencil/vue'
+import {
+ useComponentProperties,
+ useExposedInstances,
+ useI18n,
+ useSlotProperties
+} from '@open-pencil/vue'
import AssetThumbnail from '@/components/assets-panel/AssetThumbnail.vue'
-import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'
import PanelSection from '@/components/ui/panel/PanelSection.vue'
-import type { AppPickerItem } from '@/components/ui/select/AppPicker.vue'
-import AppPickerField from '@/components/ui/select/AppPickerField.vue'
-import AppSelect from '@/components/ui/select/AppSelect.vue'
-import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'
-import ComponentPropertyTextField from './ComponentPropertyTextField.vue'
+import ComponentPropertyControl from './ComponentPropertyControl.vue'
+import ComponentPropertyRow from './ComponentPropertyRow.vue'
+import ExposedInstanceGroup from './ExposedInstanceGroup.vue'
import SlotPropertyRow from './slot/SlotPropertyRow.vue'
const { active, controls, setValue, setTextValue, flush } = useComponentProperties()
+const exposedGroups = useExposedInstances()
const slotProperties = useSlotProperties()
const slots = slotProperties.slots
-const visible = computed(() => active.value || slots.value.length > 0)
+const visible = computed(
+ () => active.value || exposedGroups.value.length > 0 || slots.value.length > 0
+)
/** Thumbnail edge in the Add instances list, matching the picker's 32px tile. */
const SLOT_THUMBNAIL_SIZE = 32
-const { panels, common } = useI18n()
+const { panels } = useI18n()
const componentSectionUI = { title: 'text-component' }
-function selectOptions(control: (typeof controls.value)[number]) {
- return control.value === MIXED
- ? [{ value: 'MIXED', label: panels.value.mixed }, ...control.options]
- : control.options
-}
-
-function selectValue(control: (typeof controls.value)[number]) {
- return control.value === MIXED ? 'MIXED' : control.value
-}
-
-function updateSelect(propertyId: string, value: string) {
- if (value !== 'MIXED') setValue(propertyId, value)
-}
-
-/** Swap choices with the definition's preferred components first, as Figma lists them. */
-function swapItems(control: (typeof controls.value)[number]): AppPickerItem[] {
- const anyPreferred = control.options.some((option) => option.preferred)
- const groupOf = (preferred: boolean | undefined) => {
- if (!anyPreferred) return undefined
- return preferred ? panels.value.preferredInstances : panels.value.allInstances
- }
- return control.options.map((option) => ({
- value: option.value,
- label: option.label,
- disabled: option.disabled,
- group: groupOf(option.preferred)
- }))
-}
-
-function booleanValue(control: (typeof controls.value)[number]) {
- return control.value !== MIXED && control.value === 'true'
-}
-
const sectionLabel = computed(() =>
- slots.value.length === 0 && controls.value.every((control) => control.type === 'VARIANT')
+ slots.value.length === 0 &&
+ exposedGroups.value.length === 0 &&
+ controls.value.every((control) => control.type === 'VARIANT')
? panels.value.variants
: panels.value.componentProperties
)
@@ -65,46 +39,21 @@ const sectionLabel = computed(() =>
<template>
<PanelSection v-if="visible" :label="sectionLabel" :ui="componentSectionUI">
- <div class="flex flex-col gap-1.5">
- <PanelFieldGroup v-for="control in controls" :key="control.id" :label="control.name">
- <ComponentPropertyTextField
- v-if="control.type === 'TEXT'"
- :value="control.value"
- :label="control.name"
- :data-property="control.id"
- @update="setTextValue(control.id, $event)"
- @commit="flush"
- />
- <div v-else-if="control.type === 'BOOLEAN'" class="flex h-field items-center">
- <AppSwitch
- :model-value="booleanValue(control)"
- :label="control.name"
- :state="control.value === MIXED ? 'mixed' : 'idle'"
- :data-property="control.id"
- @update:model-value="setValue(control.id, String($event))"
- />
- </div>
- <AppPickerField
- v-else-if="control.type === 'INSTANCE_SWAP'"
- :model-value="control.value === MIXED ? '' : control.value"
- :items="swapItems(control)"
- :label="control.name"
- :placeholder="control.value === MIXED ? panels.mixed : undefined"
- :search-placeholder="panels.searchInstances"
- :empty-label="panels.noComponentsFound"
- :close-label="common.close"
- :data-property="control.id"
- @update:model-value="setValue(control.id, $event)"
- />
- <AppSelect
- v-else
- :label="control.name"
- :model-value="selectValue(control)"
- :options="selectOptions(control)"
- :data-property="control.id"
- @update:model-value="updateSelect(control.id, $event)"
+ <div class="flex flex-col gap-1">
+ <ComponentPropertyRow v-for="control in controls" :key="control.id" :name="control.name">
+ <ComponentPropertyControl
+ :control="control"
+ @set="setValue"
+ @text="setTextValue"
+ @flush="flush"
/>
- </PanelFieldGroup>
+ </ComponentPropertyRow>
+ <ExposedInstanceGroup
+ v-for="group in exposedGroups"
+ :key="group.id"
+ :instance-id="group.id"
+ :name="group.name"
+ />
<SlotPropertyRow
v-for="slot in slots"
:key="slot.id"
diff --git a/src/components/properties/component-properties/ComponentPropertyControl.vue b/src/components/properties/component-properties/ComponentPropertyControl.vue
new file mode 100644
index 000000000..01cab0ab4
--- /dev/null
+++ b/src/components/properties/component-properties/ComponentPropertyControl.vue
@@ -0,0 +1,81 @@
+<script setup lang="ts">
+import { MIXED, useI18n } from '@open-pencil/vue'
+import type { ComponentPropertyControl } from '@open-pencil/vue'
+
+import type { AppPickerItem } from '@/components/ui/select/AppPicker.vue'
+import AppPickerField from '@/components/ui/select/AppPickerField.vue'
+import AppSelect from '@/components/ui/select/AppSelect.vue'
+import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'
+
+import ComponentPropertyTextField from './ComponentPropertyTextField.vue'
+
+/** The value control of one instance property, in the right column of its row. */
+const { control } = defineProps<{ control: ComponentPropertyControl }>()
+const emit = defineEmits<{
+ set: [propertyId: string, value: string]
+ text: [propertyId: string, value: string]
+ flush: []
+}>()
+const { panels, common } = useI18n()
+
+function preferredGroup(preferred: boolean | undefined) {
+ return preferred ? panels.value.preferredInstances : panels.value.allInstances
+}
+
+/** Swap choices with the definition's preferred components first, as Figma lists them. */
+function swapItems(): AppPickerItem[] {
+ const anyPreferred = control.options.some((option) => option.preferred)
+ return control.options.map((option) => ({
+ value: option.value,
+ label: option.label,
+ disabled: option.disabled,
+ group: anyPreferred ? preferredGroup(option.preferred) : undefined
+ }))
+}
+
+function selectOptions() {
+ return control.value === MIXED
+ ? [{ value: 'MIXED', label: panels.value.mixed }, ...control.options]
+ : control.options
+}
+</script>
+
+<template>
+ <div v-if="control.type === 'BOOLEAN'" class="flex">
+ <AppSwitch
+ :model-value="control.value !== MIXED && control.value === 'true'"
+ :label="control.name"
+ :state="control.value === MIXED ? 'mixed' : 'idle'"
+ :data-property="control.id"
+ @update:model-value="emit('set', control.id, String($event))"
+ />
+ </div>
+ <ComponentPropertyTextField
+ v-else-if="control.type === 'TEXT'"
+ :value="control.value"
+ :label="control.name"
+ :data-property="control.id"
+ @update="emit('text', control.id, $event)"
+ @commit="emit('flush')"
+ />
+ <AppPickerField
+ v-else-if="control.type === 'INSTANCE_SWAP'"
+ :model-value="control.value === MIXED ? '' : control.value"
+ :items="swapItems()"
+ :label="control.name"
+ :placeholder="control.value === MIXED ? panels.mixed : undefined"
+ :search-placeholder="panels.searchInstances"
+ :empty-label="panels.noComponentsFound"
+ :close-label="common.close"
+ :data-property="control.id"
+ @update:model-value="emit('set', control.id, $event)"
+ />
+ <AppSelect
+ v-else
+ :label="control.name"
+ :model-value="control.value === MIXED ? 'MIXED' : control.value"
+ :options="selectOptions()"
+ :data-property="control.id"
+ @update:model-value="$event !== 'MIXED' && emit('set', control.id, $event)"
+ />
+</template>
diff --git a/src/components/properties/component-properties/ComponentPropertyListSection.vue b/src/components/properties/component-properties/ComponentPropertyListSection.vue
new file mode 100644
index 000000000..2e0daaf15
--- /dev/null
+++ b/src/components/properties/component-properties/ComponentPropertyListSection.vue
@@ -0,0 +1,262 @@
+<script setup lang="ts">
+import {
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuPortal,
+ DropdownMenuRoot,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ PopoverAnchor,
+ PopoverContent,
+ PopoverPortal,
+ PopoverRoot
+} from 'reka-ui'
+import { computed, ref, type ComponentPublicInstance } from 'vue'
+
+import type { ComponentPropertyType } from '@open-pencil/scene-graph'
+import { useComponentPropertyAuthoring, useFlatReorderDrag, useI18n } from '@open-pencil/vue'
+
+import AppButton from '@/components/ui/button/AppButton.vue'
+import IconButton from '@/components/ui/button/IconButton.vue'
+import { menuItem, useMenuUI } from '@/components/ui/menu/menu'
+import { usePopoverUI } from '@/components/ui/overlay/popover'
+import Tip from '@/components/ui/overlay/Tip.vue'
+import PanelSection from '@/components/ui/panel/PanelSection.vue'
+import AppCheckbox from '@/components/ui/toggle/AppCheckbox.vue'
+
+import PropertyRow from './PropertyRow.vue'
+import PropertyTypeIcon from './PropertyTypeIcon.vue'
+
+/** A main component's text, boolean and swap properties, and the nested instances it exposes. */
+const authoring = useComponentPropertyAuthoring()
+const { context, definitions, nestedInstances, editable } = authoring
+const { panels, common } = useI18n()
+const menu = useMenuUI({ content: 'min-w-44' })
+const item = menuItem({ justify: 'start' })
+const nestedOpen = ref(false)
+/** Set by the menu item; the popover opens once the menu has closed and returned focus. */
+const nestedRequested = ref(false)
+
+function openNestedAfterMenu(event: Event) {
+ if (!nestedRequested.value) return
+ event.preventDefault()
+ nestedRequested.value = false
+ nestedOpen.value = true
+}
+const nestedStyles = usePopoverUI({
+ content: 'w-60 max-w-[calc(100vw-1rem)]',
+ header: 'flex items-center border-b border-border px-3 py-2',
+ body: 'flex max-h-72 flex-col gap-0.5 overflow-y-auto p-1.5'
+})
+
+const isComponent = computed(
+ () => context.value?.node.type === 'COMPONENT' || context.value?.node.type === 'COMPONENT_SET'
+)
+const ownDefinitions = computed(() =>
+ definitions.value.filter((definition) => definition.ownerId === context.value?.owner.id)
+)
+const exposed = computed(() => nestedInstances.value.filter((node) => node.exposed))
+const NEW_PROPERTIES: { type: ComponentPropertyType; label: () => string }[] = [
+ { type: 'TEXT', label: () => panels.value.componentPropertyText },
+ { type: 'BOOLEAN', label: () => panels.value.componentPropertyBoolean },
+ { type: 'INSTANCE_SWAP', label: () => panels.value.componentPropertySwap }
+]
+
+const reorder = useFlatReorderDrag({
+ items: () => ownDefinitions.value,
+ onMove: (propertyId, index) => {
+ if (context.value) authoring.move(context.value.owner.id, propertyId, index)
+ }
+})
+
+function setupRow(element: Element | ComponentPublicInstance | null, propertyId: string) {
+ if (!ownDefinitions.value.some((definition) => definition.id === propertyId)) return
+ reorder.setupItem(element instanceof HTMLElement ? element : null, () => ({ id: propertyId }))
+}
+
+function dropPosition(propertyId: string) {
+ if (reorder.instructionTargetId.value !== propertyId) return undefined
+ return reorder.instruction.value?.operation === 'reorder-before' ? 'before' : 'after'
+}
+
+function initialValue(type: ComponentPropertyType, name: string) {
+ if (type === 'BOOLEAN') return 'true'
+ if (type === 'TEXT') return name
+ return authoring.swapOptions('').find((option) => !option.disabled)?.value ?? ''
+}
+
+/** A new property starts with a unique name and a value its type accepts. */
+function addProperty(type: ComponentPropertyType, label: string) {
+ const owner = context.value?.owner
+ if (!owner) return
+ const taken = new Set(definitions.value.map((definition) => definition.name))
+ let name = label
+ for (let suffix = 2; taken.has(name); suffix++) name = `${label} ${suffix}`
+ authoring.create(owner.id, name, type, initialValue(type, name))
+}
+
+function valueLabel(type: ComponentPropertyType, value: string) {
+ return type === 'INSTANCE_SWAP' ? authoring.componentName(value) : value
+}
+</script>
+
+<template>
+ <PopoverRoot v-if="context && isComponent" v-model:open="nestedOpen">
+ <PopoverAnchor as-child>
+ <PanelSection
+ :key="context.node.id"
+ :label="panels.properties"
+ data-test-id="component-property-list"
+ >
+ <template #actions>
+ <DropdownMenuRoot>
+ <DropdownMenuTrigger as-child>
+ <IconButton
+ :label="panels.createComponentProperty"
+ :disabled="!editable"
+ data-property="create-property"
+ >
+ <icon-lucide-plus class="size-3.5" />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuContent
+ side="bottom"
+ align="end"
+ :side-offset="4"
+ :class="menu.content"
+ @close-auto-focus="openNestedAfterMenu"
+ >
+ <DropdownMenuItem
+ v-for="option in NEW_PROPERTIES"
+ :key="option.type"
+ :class="item"
+ :data-property-type="option.type"
+ @select="addProperty(option.type, option.label())"
+ >
+ <PropertyTypeIcon :kind="option.type" />
+ {{ option.label() }}
+ </DropdownMenuItem>
+ <template v-if="nestedInstances.length">
+ <DropdownMenuSeparator :class="menu.separator" />
+ <DropdownMenuItem
+ :class="item"
+ data-property-type="nested"
+ @select="nestedRequested = true"
+ >
+ <icon-lucide-component :class="menu.icon" />
+ {{ panels.nestedInstances }}…
+ </DropdownMenuItem>
+ </template>
+ </DropdownMenuContent>
+ </DropdownMenuPortal>
+ </DropdownMenuRoot>
+ </template>
+
+ <div v-if="definitions.length" class="-mx-1.5 flex flex-col">
+ <div
+ v-for="definition in definitions"
+ :key="definition.id"
+ :ref="(element) => setupRow(element, definition.id)"
+ class="relative data-[dragging]:opacity-50"
+ :data-dragging="reorder.draggingId.value === definition.id || undefined"
+ >
+ <div
+ v-if="dropPosition(definition.id)"
+ class="pointer-events-none absolute inset-x-1 z-10 h-0.5 rounded-full bg-accent"
+ :class="dropPosition(definition.id) === 'before' ? 'top-0' : 'bottom-0'"
+ />
+ <PropertyRow
+ :name="definition.name"
+ :kind="definition.type"
+ :value="definition.defaultValue"
+ :value-label="valueLabel(definition.type, definition.defaultValue)"
+ :options="
+ definition.type === 'INSTANCE_SWAP' ? authoring.swapOptions(definition.id) : []
+ "
+ :groups="definition.bindingGroups"
+ :total-variants="authoring.variantCount.value"
+ :disabled="!editable"
+ @rename="authoring.rename(definition.ownerId, definition.id, $event)"
+ @update="authoring.setDefault(definition.ownerId, definition.id, $event)"
+ @remove="authoring.remove(definition.ownerId, definition.id)"
+ @select="authoring.select"
+ @unbind="
+ (binding) =>
+ binding.field !== 'SLOT_CONTENT' &&
+ authoring.bind(binding.nodeId, binding.field, null)
+ "
+ />
+ </div>
+ </div>
+
+ <div v-if="exposed.length" class="flex flex-col gap-0.5">
+ <span class="text-[11px] text-muted">{{ panels.nestedInstances }}</span>
+ <div class="-mx-1.5 flex flex-col">
+ <div
+ v-for="node in exposed"
+ :key="node.id"
+ class="group/nested flex h-7 items-center gap-1.5 rounded px-1.5 text-xs hover:bg-hover"
+ :data-exposed-instance="node.name"
+ >
+ <button
+ type="button"
+ class="flex min-w-0 flex-1 items-center gap-1.5 text-left"
+ @click="authoring.select(node.id)"
+ >
+ <icon-lucide-component class="size-3.5 shrink-0 text-component" />
+ <span class="truncate text-surface">{{ node.name }}</span>
+ </button>
+ <IconButton
+ :label="panels.hideNestedInstance({ name: node.name })"
+ :disabled="!editable"
+ class="opacity-0 group-hover/nested:opacity-100 focus-visible:opacity-100"
+ @click="authoring.setExposed(node.id, false)"
+ >
+ <icon-lucide-minus class="size-3.5" />
+ </IconButton>
+ </div>
+ </div>
+ </div>
+ </PanelSection>
+ </PopoverAnchor>
+ <PopoverPortal>
+ <PopoverContent
+ side="left"
+ align="start"
+ :side-offset="8"
+ :aria-label="panels.nestedInstances"
+ :class="nestedStyles.content"
+ >
+ <div :class="nestedStyles.header">
+ <h3 class="text-xs font-semibold text-surface">{{ panels.nestedInstances }}</h3>
+ <AppButton :aria-label="common.close" class="ml-auto" @click="nestedOpen = false">
+ <icon-lucide-x class="size-3.5" />
+ </AppButton>
+ </div>
+ <div :class="nestedStyles.body">
+ <Tip
+ v-for="node in nestedInstances"
+ :key="node.id"
+ :label="panels.nothingToExpose"
+ :disabled="node.available"
+ >
+ <label
+ class="flex h-7 items-center gap-2 rounded px-1.5 text-xs text-surface hover:bg-hover data-[disabled]:text-muted data-[disabled]:hover:bg-transparent"
+ :data-disabled="!node.available || undefined"
+ >
+ <AppCheckbox
+ :model-value="node.exposed"
+ :disabled="!editable || !node.available"
+ :ariaLabel="node.name"
+ @update:model-value="authoring.setExposed(node.id, $event)"
+ />
+ <icon-lucide-component class="size-3.5 shrink-0 text-component" />
+ <span class="truncate">{{ node.name }}</span>
+ </label>
+ </Tip>
+ </div>
+ </PopoverContent>
+ </PopoverPortal>
+ </PopoverRoot>
+</template>
diff --git a/src/components/properties/component-properties/ComponentPropertyRow.vue b/src/components/properties/component-properties/ComponentPropertyRow.vue
new file mode 100644
index 000000000..d05735898
--- /dev/null
+++ b/src/components/properties/component-properties/ComponentPropertyRow.vue
@@ -0,0 +1,11 @@
+<script setup lang="ts">
+/** One instance property: its name on the left, its value control on the right. */
+const { name } = defineProps<{ name: string }>()
+</script>
+
+<template>
+ <div class="grid min-h-7 grid-cols-[minmax(0,5.5rem)_minmax(0,1fr)] items-center gap-2">
+ <span class="truncate text-xs text-muted">{{ name }}</span>
+ <slot />
+ </div>
+</template>
diff --git a/src/components/properties/component-properties/ExposedInstanceGroup.vue b/src/components/properties/component-properties/ExposedInstanceGroup.vue
new file mode 100644
index 000000000..09f475802
--- /dev/null
+++ b/src/components/properties/component-properties/ExposedInstanceGroup.vue
@@ -0,0 +1,48 @@
+<script setup lang="ts">
+import { CollapsibleContent, CollapsibleRoot, CollapsibleTrigger } from 'reka-ui'
+
+import { useComponentProperties, useSceneComputed, useEditor } from '@open-pencil/vue'
+
+import { collapsibleContentMotion } from '@/theme/collapsible/collapsible'
+
+import ComponentPropertyControl from './ComponentPropertyControl.vue'
+import ComponentPropertyRow from './ComponentPropertyRow.vue'
+
+/** An exposed nested instance's properties, under its name, as Figma groups them. */
+const { instanceId, name } = defineProps<{ instanceId: string; name: string }>()
+const editor = useEditor()
+const nested = useSceneComputed(() => {
+ const node = editor.graph.getNode(instanceId)
+ return node ? [node] : []
+})
+const { controls, setValue, setTextValue, flush } = useComponentProperties(() => nested.value)
+</script>
+
+<template>
+ <CollapsibleRoot v-if="controls.length" v-slot="{ open }" default-open>
+ <CollapsibleTrigger
+ class="flex h-7 w-full items-center gap-1 text-left text-xs text-surface"
+ :data-exposed-instance="name"
+ >
+ <icon-lucide-chevron-right
+ class="size-3 shrink-0 text-muted transition-transform data-[open]:rotate-90 motion-reduce:transition-none"
+ :data-open="open || undefined"
+ aria-hidden="true"
+ />
+ <icon-lucide-component class="size-3.5 shrink-0 text-component" aria-hidden="true" />
+ <span class="truncate">{{ name }}</span>
+ </CollapsibleTrigger>
+ <CollapsibleContent :class="collapsibleContentMotion">
+ <div class="flex flex-col gap-1 pl-4">
+ <ComponentPropertyRow v-for="control in controls" :key="control.id" :name="control.name">
+ <ComponentPropertyControl
+ :control="control"
+ @set="setValue"
+ @text="setTextValue"
+ @flush="flush"
+ />
+ </ComponentPropertyRow>
+ </div>
+ </CollapsibleContent>
+ </CollapsibleRoot>
+</template>
diff --git a/src/components/properties/component-properties/PropertyBindButton.vue b/src/components/properties/component-properties/PropertyBindButton.vue
new file mode 100644
index 000000000..35b20990d
--- /dev/null
+++ b/src/components/properties/component-properties/PropertyBindButton.vue
@@ -0,0 +1,61 @@
+<script setup lang="ts">
+import {
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuPortal,
+ DropdownMenuRoot,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger
+} from 'reka-ui'
+
+import { usePanelMessages } from '@open-pencil/vue'
+
+import IconButton from '@/components/ui/button/IconButton.vue'
+import { menuItem, useMenuUI } from '@/components/ui/menu/menu'
+
+import PropertyTypeIcon from './PropertyTypeIcon.vue'
+import { usePropertyBinding, type BindableField } from './usePropertyBinding'
+
+/** Section action that links an unbound field of a component layer to a property. */
+const { field } = defineProps<{ field: BindableField }>()
+const binding = usePropertyBinding(field)
+const panels = usePanelMessages()
+const menu = useMenuUI({ content: 'min-w-44' })
+const item = menuItem({ justify: 'start' })
+</script>
+
+<template>
+ <DropdownMenuRoot v-if="binding.available.value && !binding.definition.value">
+ <DropdownMenuTrigger as-child>
+ <IconButton
+ :label="panels.applyComponentProperty({ field: binding.fieldLabel.value })"
+ :disabled="!binding.editable.value"
+ :data-property-bind="field"
+ >
+ <icon-lucide-diamond-plus class="size-3.5" />
+ </IconButton>
+ </DropdownMenuTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuContent side="bottom" align="end" :side-offset="4" :class="menu.content">
+ <DropdownMenuItem :class="item" @select="binding.create()">
+ <icon-lucide-plus :class="menu.icon" />
+ {{ panels.createComponentProperty }}
+ </DropdownMenuItem>
+ <template v-if="binding.compatible.value.length">
+ <DropdownMenuSeparator :class="menu.separator" />
+ <DropdownMenuLabel :class="menu.label">{{ panels.properties }}</DropdownMenuLabel>
+ <DropdownMenuItem
+ v-for="definition in binding.compatible.value"
+ :key="definition.id"
+ :class="item"
+ @select="binding.bind(definition.id)"
+ >
+ <PropertyTypeIcon :kind="definition.type" />
+ {{ definition.name }}
+ </DropdownMenuItem>
+ </template>
+ </DropdownMenuContent>
+ </DropdownMenuPortal>
+ </DropdownMenuRoot>
+</template>
diff --git a/src/components/properties/component-properties/PropertyBindingRow.vue b/src/components/properties/component-properties/PropertyBindingRow.vue
new file mode 100644
index 000000000..02e40691f
--- /dev/null
+++ b/src/components/properties/component-properties/PropertyBindingRow.vue
@@ -0,0 +1,36 @@
+<script setup lang="ts">
+import type { ComponentBinding } from '@open-pencil/vue'
+import { usePanelMessages } from '@open-pencil/vue'
+
+import { nodeIcon } from '@/app/editor/icons'
+import AppButton from '@/components/ui/button/AppButton.vue'
+import IconButton from '@/components/ui/button/IconButton.vue'
+
+const { binding, disabled } = defineProps<{ binding: ComponentBinding; disabled?: boolean }>()
+defineEmits<{ select: [id: string]; unbind: [binding: ComponentBinding] }>()
+const panels = usePanelMessages()
+</script>
+
+<template>
+ <div class="flex items-center gap-1" :data-node-id="binding.nodeId">
+ <AppButton
+ size="xs"
+ variant="ghost"
+ class="min-w-0 flex-1 justify-start"
+ :aria-label="binding.variantName ? `${binding.variantName}: ${binding.name}` : binding.name"
+ @click="$emit('select', binding.nodeId)"
+ >
+ <component :is="nodeIcon(binding.node)" class="size-3.5 shrink-0" aria-hidden="true" />
+ <span class="min-w-0 truncate text-left"
+ >{{ binding.variantName ? `${binding.variantName} / ` : '' }}{{ binding.name }}</span
+ >
+ </AppButton>
+ <IconButton
+ :label="`${panels.detachComponentProperty}: ${binding.variantName ? `${binding.variantName}: ` : ''}${binding.name}`"
+ :disabled="disabled"
+ @click="$emit('unbind', binding)"
+ >
+ <icon-lucide-unlink class="size-3.5" />
+ </IconButton>
+ </div>
+</template>
diff --git a/src/components/properties/component-properties/PropertyBindings.vue b/src/components/properties/component-properties/PropertyBindings.vue
new file mode 100644
index 000000000..4c9795e6b
--- /dev/null
+++ b/src/components/properties/component-properties/PropertyBindings.vue
@@ -0,0 +1,66 @@
+<script setup lang="ts">
+import { CollapsibleRoot, CollapsibleContent, CollapsibleTrigger } from 'reka-ui'
+
+import {
+ usePanelMessages,
+ type ComponentBinding,
+ type ComponentBindingGroup
+} from '@open-pencil/vue'
+
+import { nodeIcon } from '@/app/editor/icons'
+import AppButton from '@/components/ui/button/AppButton.vue'
+import { collapsibleContentMotion } from '@/theme/collapsible/collapsible'
+
+import PropertyBindingRow from './PropertyBindingRow.vue'
+
+const { groups, totalVariants, disabled } = defineProps<{
+ groups: ComponentBindingGroup[]
+ totalVariants: number
+ disabled?: boolean
+}>()
+defineEmits<{ select: [id: string]; unbind: [binding: ComponentBinding] }>()
+const panels = usePanelMessages()
+</script>
+
+<template>
+ <template v-for="group in groups" :key="group.key">
+ <CollapsibleRoot v-if="group.bindings.length > 1" v-slot="{ open }">
+ <CollapsibleTrigger as-child>
+ <AppButton size="xs" variant="ghost" class="w-full justify-start gap-1">
+ <icon-lucide-chevron-right
+ class="size-3.5 shrink-0 transition-transform data-[open]:rotate-90 motion-reduce:transition-none"
+ :data-open="open || undefined"
+ />
+ <component :is="nodeIcon(group.node)" class="size-3.5 shrink-0" aria-hidden="true" />
+ <span class="min-w-0 truncate">{{ group.name }}</span>
+ <span class="ml-auto text-[10px] text-muted">{{
+ group.bindings.length === totalVariants
+ ? panels.allVariants
+ : panels.usedInVariants({ count: group.bindings.length, total: totalVariants })
+ }}</span>
+ </AppButton>
+ </CollapsibleTrigger>
+ <CollapsibleContent :class="collapsibleContentMotion">
+ <div class="flex flex-col gap-1 pl-3">
+ <PropertyBindingRow
+ v-for="binding in group.bindings"
+ :key="binding.nodeId"
+ :binding="binding"
+ :disabled="disabled"
+ @select="$emit('select', $event)"
+ @unbind="$emit('unbind', $event)"
+ />
+ </div>
+ </CollapsibleContent>
+ </CollapsibleRoot>
+ <PropertyBindingRow
+ v-else
+ v-for="binding in group.bindings"
+ :key="binding.nodeId"
+ :binding="binding"
+ :disabled="disabled"
+ @select="$emit('select', $event)"
+ @unbind="$emit('unbind', $event)"
+ />
+ </template>
+</template>
diff --git a/src/components/properties/component-properties/PropertyBoundField.vue b/src/components/properties/component-properties/PropertyBoundField.vue
new file mode 100644
index 000000000..3b8c5bf6a
--- /dev/null
+++ b/src/components/properties/component-properties/PropertyBoundField.vue
@@ -0,0 +1,89 @@
+<script setup lang="ts">
+import {
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuPortal,
+ DropdownMenuRoot,
+ DropdownMenuTrigger
+} from 'reka-ui'
+
+import { usePanelMessages } from '@open-pencil/vue'
+
+import IconButton from '@/components/ui/button/IconButton.vue'
+import { menuItem, useMenuUI } from '@/components/ui/menu/menu'
+import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'
+
+import PropertyTypeIcon from './PropertyTypeIcon.vue'
+import { usePropertyBinding, type BindableField } from './usePropertyBinding'
+
+/** A bound field: the property it follows, with go-to and detach, in place of the value. */
+const {
+ field,
+ label,
+ compact = false
+} = defineProps<{
+ field: BindableField
+ label?: string
+ compact?: boolean
+}>()
+const binding = usePropertyBinding(field)
+const panels = usePanelMessages()
+const menu = useMenuUI({ content: 'min-w-40' })
+const item = menuItem({ justify: 'start' })
+const chip =
+ 'flex h-7 min-w-0 items-center gap-1.5 rounded bg-component/15 px-2 text-xs text-component'
+</script>
+
+<template>
+ <DropdownMenuRoot v-if="compact && binding.available.value && binding.definition.value">
+ <DropdownMenuTrigger as-child>
+ <button
+ type="button"
+ :class="[chip, 'max-w-40']"
+ :aria-label="`${binding.fieldLabel.value}: ${binding.definition.value.name}`"
+ :data-property-bound="field"
+ >
+ <PropertyTypeIcon :kind="binding.definition.value.type" class="!text-component" />
+ <span class="truncate">{{ binding.definition.value.name }}</span>
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuContent side="bottom" align="end" :side-offset="4" :class="menu.content">
+ <DropdownMenuItem :class="item" @select="binding.goToProperty()">
+ <icon-lucide-crosshair :class="menu.icon" />
+ {{ panels.goToComponentProperty }}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ :class="item"
+ :disabled="!binding.editable.value"
+ @select="binding.bind(null)"
+ >
+ <icon-lucide-unlink :class="menu.icon" />
+ {{ panels.detachComponentProperty }}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenuPortal>
+ </DropdownMenuRoot>
+ <PanelFieldGroup
+ v-else-if="binding.available.value && binding.definition.value"
+ class="mb-1.5"
+ :label="label ?? binding.fieldLabel.value"
+ >
+ <div class="flex min-w-0 flex-1 items-center gap-1" :data-property-bound="field">
+ <span :class="[chip, 'flex-1']">
+ <PropertyTypeIcon :kind="binding.definition.value.type" class="!text-component" />
+ <span class="truncate">{{ binding.definition.value.name }}</span>
+ </span>
+ <IconButton :label="panels.goToComponentProperty" @click="binding.goToProperty()">
+ <icon-lucide-crosshair class="size-3.5" />
+ </IconButton>
+ <IconButton
+ :label="panels.detachComponentProperty"
+ :disabled="!binding.editable.value"
+ @click="binding.bind(null)"
+ >
+ <icon-lucide-unlink class="size-3.5" />
+ </IconButton>
+ </div>
+ </PanelFieldGroup>
+</template>
diff --git a/src/components/properties/component-properties/PropertyRow.vue b/src/components/properties/component-properties/PropertyRow.vue
new file mode 100644
index 000000000..901495c2e
--- /dev/null
+++ b/src/components/properties/component-properties/PropertyRow.vue
@@ -0,0 +1,154 @@
+<script setup lang="ts">
+import { PopoverClose, PopoverContent, PopoverPortal, PopoverRoot, PopoverTrigger } from 'reka-ui'
+import { computed, ref, watch } from 'vue'
+
+import type { ComponentPropertyType } from '@open-pencil/scene-graph'
+import { useI18n, useRetainedPopup } from '@open-pencil/vue'
+import type { ComponentBinding, ComponentBindingGroup } from '@open-pencil/vue'
+
+import AppButton from '@/components/ui/button/AppButton.vue'
+import AppInput from '@/components/ui/input/AppInput.vue'
+import { usePopoverUI } from '@/components/ui/overlay/popover'
+import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'
+
+import PropertyBindings from './PropertyBindings.vue'
+import PropertyTypeIcon from './PropertyTypeIcon.vue'
+import PropertyValueField from './PropertyValueField.vue'
+
+/** One property of a main component: a single row that opens its settings. */
+const {
+ name,
+ kind,
+ value,
+ valueLabel,
+ options = [],
+ groups = [],
+ totalVariants = 0,
+ disabled
+} = defineProps<{
+ name: string
+ kind: ComponentPropertyType
+ value: string
+ /** The default as people read it, e.g. a component name for a swap. */
+ valueLabel: string
+ options?: { value: string; label: string; disabled?: boolean }[]
+ groups?: ComponentBindingGroup[]
+ totalVariants?: number
+ disabled?: boolean
+}>()
+const emit = defineEmits<{
+ rename: [name: string]
+ update: [value: string]
+ remove: []
+ select: [id: string]
+ unbind: [binding: ComponentBinding]
+}>()
+const { panels, common } = useI18n()
+const { open, portalActive } = useRetainedPopup()
+const styles = usePopoverUI({
+ content: 'w-64 max-w-[calc(100vw-1rem)]',
+ header: 'flex items-center gap-1.5 border-b border-border px-3 py-2',
+ body: 'flex flex-col gap-3 p-3',
+ footer: 'flex border-t border-border px-3 py-2'
+})
+const draftName = ref(name)
+watch(
+ () => name,
+ (next) => {
+ draftName.value = next
+ }
+)
+function commitName() {
+ const next = draftName.value.trim()
+ if (next && next !== name) emit('rename', next)
+ else draftName.value = name
+}
+const shownValue = computed(() => {
+ if (kind !== 'BOOLEAN') return valueLabel
+ return value === 'true' ? panels.value.propertyOn : panels.value.propertyOff
+})
+</script>
+
+<template>
+ <PopoverRoot v-model:open="open">
+ <PopoverTrigger as-child>
+ <button
+ type="button"
+ class="group/row flex h-7 w-full min-w-0 items-center gap-1.5 rounded px-1.5 text-left text-xs hover:bg-hover data-[state=open]:bg-hover"
+ :data-property-row="name"
+ >
+ <PropertyTypeIcon :kind="kind" />
+ <span class="shrink-0 truncate text-surface">{{ name }}</span>
+ <span class="min-w-0 truncate text-muted">· {{ shownValue }}</span>
+ </button>
+ </PopoverTrigger>
+ <PopoverPortal v-if="portalActive">
+ <PopoverContent
+ side="left"
+ align="start"
+ :side-offset="8"
+ :aria-label="name"
+ :class="styles.content"
+ @focus-outside.prevent
+ >
+ <div :class="styles.header">
+ <PropertyTypeIcon :kind="kind" />
+ <h3 class="truncate text-xs font-semibold text-surface">{{ name }}</h3>
+ <PopoverClose as-child>
+ <AppButton :aria-label="common.close" class="ml-auto">
+ <icon-lucide-x class="size-3.5" />
+ </AppButton>
+ </PopoverClose>
+ </div>
+ <div :class="styles.body">
+ <PanelFieldGroup :label="panels.componentPropertyName">
+ <AppInput
+ v-model="draftName"
+ size="sm"
+ tone="panel"
+ :aria-label="panels.componentPropertyName"
+ :disabled="disabled"
+ @change="commitName"
+ @enter="commitName"
+ />
+ </PanelFieldGroup>
+ <PanelFieldGroup :label="panels.componentPropertyDefault">
+ <div class="flex">
+ <PropertyValueField
+ :kind="kind"
+ :value="value"
+ :label="panels.componentPropertyDefault"
+ :options="options"
+ :disabled="disabled"
+ @update="emit('update', $event)"
+ />
+ </div>
+ </PanelFieldGroup>
+ <PanelFieldGroup v-if="groups.length" :label="panels.layers">
+ <div class="flex flex-col gap-0.5">
+ <PropertyBindings
+ :groups="groups"
+ :total-variants="totalVariants"
+ :disabled="disabled"
+ @select="emit('select', $event)"
+ @unbind="emit('unbind', $event)"
+ />
+ </div>
+ </PanelFieldGroup>
+ </div>
+ <div :class="styles.footer">
+ <AppButton
+ size="xs"
+ variant="ghost"
+ :disabled="disabled"
+ class="text-issue-error"
+ @click="emit('remove')"
+ >
+ <icon-lucide-trash-2 class="size-3.5" />
+ {{ panels.deleteComponentProperty }}
+ </AppButton>
+ </div>
+ </PopoverContent>
+ </PopoverPortal>
+ </PopoverRoot>
+</template>
diff --git a/src/components/properties/component-properties/PropertyTypeIcon.vue b/src/components/properties/component-properties/PropertyTypeIcon.vue
new file mode 100644
index 000000000..5499394dc
--- /dev/null
+++ b/src/components/properties/component-properties/PropertyTypeIcon.vue
@@ -0,0 +1,17 @@
+<script setup lang="ts">
+import type { ComponentPropertyType } from '@open-pencil/scene-graph'
+const { kind } = defineProps<{ kind: ComponentPropertyType }>()
+</script>
+<template>
+ <icon-lucide-eye
+ v-if="kind === 'BOOLEAN'"
+ class="size-3.5 shrink-0 text-muted"
+ aria-hidden="true"
+ />
+ <icon-lucide-type
+ v-else-if="kind === 'TEXT'"
+ class="size-3.5 shrink-0 text-muted"
+ aria-hidden="true"
+ />
+ <icon-lucide-component v-else class="size-3.5 shrink-0 text-muted" aria-hidden="true" />
+</template>
diff --git a/src/components/properties/component-properties/PropertyValueField.vue b/src/components/properties/component-properties/PropertyValueField.vue
new file mode 100644
index 000000000..ff2a3f0ea
--- /dev/null
+++ b/src/components/properties/component-properties/PropertyValueField.vue
@@ -0,0 +1,64 @@
+<script setup lang="ts">
+import { ref, watch } from 'vue'
+
+import type { ComponentPropertyType } from '@open-pencil/scene-graph'
+
+import AppInput from '@/components/ui/input/AppInput.vue'
+import AppSelect from '@/components/ui/select/AppSelect.vue'
+import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'
+
+/** A property default: text commits on change or Enter, a boolean toggles, a swap picks. */
+const {
+ kind,
+ value,
+ label,
+ disabled,
+ options = []
+} = defineProps<{
+ kind: ComponentPropertyType
+ value: string
+ label: string
+ disabled?: boolean
+ options?: { value: string; label: string; disabled?: boolean }[]
+}>()
+const emit = defineEmits<{ update: [value: string] }>()
+const draft = ref(value)
+watch(
+ () => value,
+ (next) => {
+ draft.value = next
+ }
+)
+function commit() {
+ if (!disabled && draft.value !== value) emit('update', draft.value)
+}
+</script>
+
+<template>
+ <AppSwitch
+ v-if="kind === 'BOOLEAN'"
+ :label="label"
+ :model-value="value === 'true'"
+ :disabled="disabled"
+ @update:model-value="emit('update', String($event))"
+ />
+ <AppInput
+ v-else-if="kind === 'TEXT'"
+ v-model="draft"
+ :aria-label="label"
+ size="sm"
+ tone="panel"
+ :disabled="disabled"
+ @change="commit"
+ @enter="commit"
+ />
+ <AppSelect
+ v-else
+ class="w-full"
+ :label="label"
+ :model-value="value"
+ :options="options"
+ :disabled="disabled"
+ @update:model-value="emit('update', $event)"
+ />
+</template>
diff --git a/src/components/properties/component-properties/usePropertyBinding.ts b/src/components/properties/component-properties/usePropertyBinding.ts
new file mode 100644
index 000000000..1a4d2978c
--- /dev/null
+++ b/src/components/properties/component-properties/usePropertyBinding.ts
@@ -0,0 +1,57 @@
+import { computed } from 'vue'
+
+import { useComponentPropertyAuthoring, usePanelMessages } from '@open-pencil/vue'
+
+export type BindableField = 'TEXT' | 'VISIBLE' | 'INSTANCE_SWAP'
+
+const FIELD_TYPES = { TEXT: 'TEXT', VISIBLE: 'BOOLEAN', INSTANCE_SWAP: 'INSTANCE_SWAP' } as const
+
+/** How the selected component layer's field links to a property of its component. */
+export function usePropertyBinding(field: BindableField) {
+ const authoring = useComponentPropertyAuthoring()
+ const panels = usePanelMessages()
+ const context = authoring.context
+ const propertyId = computed(
+ () =>
+ context.value?.node.componentPropertyReferences.find((item) => item.field === field)
+ ?.propertyId
+ )
+ const fieldLabels = computed(() => ({
+ TEXT: panels.value.textContent,
+ VISIBLE: panels.value.layerVisibility,
+ INSTANCE_SWAP: panels.value.nestedInstance
+ }))
+
+ /** A name no property of the component uses yet, from the layer's own name. */
+ function suggestedName() {
+ const name = context.value?.node.name.trim()
+ const stem =
+ (field === 'VISIBLE' && name ? panels.value.showLayer({ name }) : name) ||
+ fieldLabels.value[field]
+ const taken = new Set(authoring.definitions.value.map((item) => item.name))
+ let candidate = stem
+ for (let suffix = 2; taken.has(candidate); suffix++) candidate = `${stem} ${suffix}`
+ return candidate
+ }
+
+ return {
+ available: computed(() => !!context.value?.fields.includes(field)),
+ editable: authoring.editable,
+ definition: computed(() =>
+ authoring.definitions.value.find((item) => item.id === propertyId.value)
+ ),
+ compatible: computed(() =>
+ authoring.definitions.value.filter((item) => item.type === FIELD_TYPES[field])
+ ),
+ fieldLabel: computed(() => fieldLabels.value[field]),
+ create: () => {
+ const node = context.value?.node
+ if (node) authoring.expose(node.id, field, suggestedName())
+ },
+ bind: (id: string | null) => {
+ const node = context.value?.node
+ if (node) authoring.bind(node.id, field, id)
+ },
+ goToProperty: authoring.selectOwner
+ }
+}
diff --git a/tests/e2e/components/property-authoring.spec.ts b/tests/e2e/components/property-authoring.spec.ts
new file mode 100644
index 000000000..e53e59225
--- /dev/null
+++ b/tests/e2e/components/property-authoring.spec.ts
@@ -0,0 +1,94 @@
+import { expect, test, type Page } from '@playwright/test'
+
+import { CanvasHelper } from '#tests/helpers/canvas'
+import {
+ componentPropertyDefinitions,
+ createPropertyAuthoringScene,
+ nestedInstanceText,
+ selectNode,
+ type PropertyAuthoringScene
+} from '#tests/helpers/components/properties'
+import { propertySection } from '#tests/helpers/properties'
+
+let page: Page
+let canvas: CanvasHelper
+let ids: PropertyAuthoringScene
+
+async function select(nodeId: string) {
+ await selectNode(page, nodeId)
+ await canvas.waitForRender()
+}
+
+test.describe.configure({ mode: 'serial' })
+
+test.beforeAll(async ({ browser }) => {
+ page = await browser.newPage()
+ canvas = new CanvasHelper(page)
+ await page.goto('/?test')
+ await canvas.waitForInit()
+ ids = await createPropertyAuthoringScene(page)
+ await canvas.waitForRender()
+})
+
+test.afterAll(async () => {
+ await page.close()
+})
+
+test('links a layer field to a new property from the section that owns the field', async () => {
+ await select(ids.labelId)
+ const typography = propertySection(page, 'Typography')
+ await typography.getByRole('button', { name: /Apply component property/ }).click()
+ await page.getByRole('menuitem', { name: /Create property/ }).click()
+
+ await expect(typography.getByRole('button', { name: 'Detach property' })).toBeVisible()
+ await expect
+ .poll(() => componentPropertyDefinitions(page, ids.buttonId))
+ .toEqual([{ name: 'Label', type: 'TEXT', defaultValue: 'Button' }])
+})
+
+test('edits a property from its row and adds another from the section menu', async () => {
+ await select(ids.buttonId)
+ const properties = propertySection(page, 'Properties')
+ await properties.getByRole('button', { name: /^Label/ }).click()
+ const name = page.getByRole('dialog', { name: 'Label' }).getByRole('textbox', { name: 'Name' })
+ await name.fill('Caption')
+ await name.press('Enter')
+ // The popover is named after the property, so it follows the rename.
+ const value = page
+ .getByRole('dialog', { name: 'Caption' })
+ .getByRole('textbox', { name: 'Default value' })
+ await value.fill('Continue')
+ await value.press('Enter')
+ await page.keyboard.press('Escape')
+
+ await properties.getByRole('button', { name: 'Create property…' }).click()
+ await page.getByRole('menuitem', { name: 'Boolean' }).click()
+
+ await expect
+ .poll(() => componentPropertyDefinitions(page, ids.buttonId))
+ .toEqual([
+ { name: 'Caption', type: 'TEXT', defaultValue: 'Continue' },
+ { name: 'Boolean', type: 'BOOLEAN', defaultValue: 'true' }
+ ])
+})
+
+test('exposes a nested instance and sets its properties from the outer instance', async () => {
+ await select(ids.cardId)
+ await propertySection(page, 'Properties')
+ .getByRole('button', { name: 'Create property…' })
+ .click()
+ await page.getByRole('menuitem', { name: /Nested instances/ }).click()
+ await page
+ .getByRole('dialog', { name: 'Nested instances' })
+ .getByRole('checkbox', { name: 'Action' })
+ .click()
+ await page.keyboard.press('Escape')
+
+ await select(ids.cardInstanceId)
+ const instance = propertySection(page, 'Component properties')
+ await expect(instance.getByRole('button', { name: 'Action' })).toBeVisible()
+ const caption = instance.getByRole('textbox', { name: 'Caption' })
+ await caption.fill('Upgrade')
+ await caption.press('Enter')
+ await expect.poll(() => nestedInstanceText(page, ids.cardInstanceId, 'Action')).toBe('Upgrade')
+})
diff --git a/tests/e2e/properties/component-properties.spec.ts-snapshots/component-properties-controls-openpencil-darwin.png b/tests/e2e/properties/component-properties.spec.ts-snapshots/component-properties-controls-openpencil-darwin.png
index 3afd57f52..37ded6791 100644
Binary files a/tests/e2e/properties/component-properties.spec.ts-snapshots/component-properties-controls-openpencil-darwin.png and b/tests/e2e/properties/component-properties.spec.ts-snapshots/component-properties-controls-openpencil-darwin.png differ
diff --git a/tests/engine/figma/api/components.test.ts b/tests/engine/figma/api/components.test.ts
index 625d14e6a..e9410a04f 100644
--- a/tests/engine/figma/api/components.test.ts
+++ b/tests/engine/figma/api/components.test.ts
@@ -42,12 +42,29 @@ describe('components', () => {
instance.setProperties({ [visibleName]: false })
expect(instance.componentProperties[visibleName]?.value).toBe(false)
- const nested = api.createComponent()
- const slot = nested.createInstance()
- slot.componentPropertyReferences = { mainComponent: textName }
- expect(slot.isExposedInstance).toBe(true)
- slot.isExposedInstance = false
- expect(slot.isExposedInstance).toBe(false)
+ // Live Figma 126: only an instance in a component's own layers, whose component has
+ // properties, can be exposed; its copies report it but cannot change it.
+ expect(() => {
+ instance.isExposedInstance = true
+ }).toThrow('Instance must be contained within a component or component set to be exposed.')
+ const card = api.createComponent()
+ const bare = api.createComponent().createInstance()
+ card.appendChild(bare)
+ expect(() => {
+ bare.isExposedInstance = true
+ }).toThrow('Can only expose instances that have exposed nested instances')
+ const action = component.createInstance()
+ card.appendChild(action)
+ action.isExposedInstance = true
+ expect(action.isExposedInstance).toBe(true)
+ const cardInstance = card.createInstance()
+ const [copy] = cardInstance.exposedInstances
+ expect(copy?.isExposedInstance).toBe(true)
+ expect(() => {
+ if (copy) copy.isExposedInstance = false
+ }).toThrow('Can only expose primary instances.')
+ action.isExposedInstance = false
+ expect(cardInstance.exposedInstances).toEqual([])
const editedName = component.editComponentProperty(visibleName, { name: 'Shown' })
expect(editedName).toContain('Shown#')
diff --git a/tests/engine/io/fig/export/component-properties.test.ts b/tests/engine/io/fig/export/component-properties.test.ts
index 8fd3ea773..035af8c17 100644
--- a/tests/engine/io/fig/export/component-properties.test.ts
+++ b/tests/engine/io/fig/export/component-properties.test.ts
@@ -198,4 +198,37 @@ describe('Figma component property roundtrip', () => {
)
expect(reloadedInstance?.componentPropertyAssignments).toEqual({ '30:1': 'Edited' })
})
+
+ test('saves an exposed nested instance as Figma does and reopens it', async () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const button = graph.createNode('COMPONENT', page.id, {
+ name: 'Button',
+ componentPropertyDefinitions: [
+ { id: '10:1', name: 'Label', type: 'TEXT', defaultValue: 'Button' }
+ ]
+ })
+ graph.createNode('TEXT', button.id, {
+ name: 'Label',
+ text: 'Button',
+ componentPropertyReferences: [{ propertyId: '10:1', field: 'TEXT' }]
+ })
+ const card = graph.createNode('COMPONENT', page.id, { name: 'Card' })
+ const action = graph.createInstance(button.id, card.id, { name: 'Action' })
+ const plain = graph.createInstance(button.id, card.id, { name: 'Plain' })
+ if (!action || !plain) throw new Error('nested instances were not created')
+ graph.updateNode(action.id, { isExposedInstance: true })
+
+ const bytes = await exportFigFile(graph)
+ const parsed = parseFigBuffer(uint8ArrayToArrayBuffer(bytes))
+ const saved = (name: string) => parsed.nodeChanges.find((change) => change.name === name)
+ expect(saved('Action')?.propsAreBubbled).toBe(true)
+ expect(saved('Plain')?.propsAreBubbled).toBeUndefined()
+
+ const imported = materializeDocument(parsed.nodeChanges, parsed.blobs).graph
+ const reopened = (name: string) =>
+ [...imported.getAllNodes()].find((node) => node.name === name && node.type === 'INSTANCE')
+ expect(reopened('Action')?.isExposedInstance).toBe(true)
+ expect(reopened('Plain')?.isExposedInstance).toBe(false)
+ })
})
diff --git a/tests/engine/text/edit-undo.test.ts b/tests/engine/text/edit-undo.test.ts
index f469f5569..3635b66e2 100644
--- a/tests/engine/text/edit-undo.test.ts
+++ b/tests/engine/text/edit-undo.test.ts
@@ -445,3 +445,73 @@ describe('text edit undo', () => {
expect(undo.canUndo).toBe(false)
})
})
+
+describe('editing text a component property drives', () => {
+ function boundComponent(graph: SceneGraph) {
+ const page = graph.getPages()[0]
+ const component = graph.createNode('COMPONENT', page.id, {
+ width: 100,
+ height: 40,
+ componentPropertyDefinitions: [
+ { id: '10:1', name: 'Label', type: 'TEXT', defaultValue: 'Buy' }
+ ]
+ })
+ const reference = [{ propertyId: '10:1', field: 'TEXT' as const }]
+ const label = graph.createNode('TEXT', component.id, {
+ text: 'Buy',
+ width: 100,
+ height: 20,
+ componentPropertyReferences: reference
+ })
+ const caption = graph.createNode('TEXT', component.id, {
+ text: 'Buy',
+ width: 100,
+ height: 20,
+ componentPropertyReferences: reference
+ })
+ return { page, component, label, caption }
+ }
+
+ test('in the main component, the text becomes the default every linked layer shows', () => {
+ const { graph, undo, textEditor, actions } = setup()
+ const { component, label, caption } = boundComponent(graph)
+
+ actions.startTextEditing(label.id)
+ textEditor.insert(' now', label)
+ actions.commitTextEdit()
+
+ const definition = () => getNodeOrThrow(graph, component.id).componentPropertyDefinitions[0]
+ expect(definition()?.defaultValue).toBe('Buy now')
+ expect(getNodeOrThrow(graph, caption.id).text).toBe('Buy now')
+
+ undo.undo()
+ expect(definition()?.defaultValue).toBe('Buy')
+ expect(getNodeOrThrow(graph, label.id).text).toBe('Buy')
+ expect(getNodeOrThrow(graph, caption.id).text).toBe('Buy')
+ expect(undo.canUndo).toBe(false)
+ })
+
+ test("in an instance, the text becomes that instance's value for the property", () => {
+ const { graph, undo, textEditor, actions } = setup()
+ const { page, component } = boundComponent(graph)
+ const instance = expectDefined(graph.createInstance(component.id, page.id), 'instance')
+ const [label, caption] = instance.childIds.map((id) => getNodeOrThrow(graph, id))
+
+ actions.startTextEditing(label.id)
+ textEditor.insert(' later', label)
+ actions.commitTextEdit()
+
+ expect(getNodeOrThrow(graph, instance.id).componentPropertyAssignments['10:1']).toBe(
+ 'Buy later'
+ )
+ expect(getNodeOrThrow(graph, caption.id).text).toBe('Buy later')
+ expect(getNodeOrThrow(graph, component.id).componentPropertyDefinitions[0]?.defaultValue).toBe(
+ 'Buy'
+ )
+
+ undo.undo()
+ expect(getNodeOrThrow(graph, instance.id).componentPropertyAssignments).toEqual({})
+ expect(getNodeOrThrow(graph, label.id).text).toBe('Buy')
+ expect(getNodeOrThrow(graph, caption.id).text).toBe('Buy')
+ })
+})
diff --git a/tests/engine/vue/controls/component-properties.test.ts b/tests/engine/vue/controls/component-properties.test.ts
index 27c75a06e..93551bafc 100644
--- a/tests/engine/vue/controls/component-properties.test.ts
+++ b/tests/engine/vue/controls/component-properties.test.ts
@@ -38,6 +38,7 @@ describe('component property control model', () => {
})
expect(
instanceSwapOptions(
+ graph,
[secondary, preferred],
{
id: '1:3',
diff --git a/tests/helpers/components/properties.ts b/tests/helpers/components/properties.ts
new file mode 100644
index 000000000..3f4f8d1e5
--- /dev/null
+++ b/tests/helpers/components/properties.ts
@@ -0,0 +1,62 @@
+import type { Page } from '@playwright/test'
+
+export interface PropertyAuthoringScene {
+ buttonId: string
+ labelId: string
+ cardId: string
+ cardInstanceId: string
+}
+
+/** A Button component with a Label text, nested in a Card component, and an instance of Card. */
+export function createPropertyAuthoringScene(page: Page): Promise<PropertyAuthoringScene> {
+ return page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const pageId = store.state.currentPageId
+ const button = store.graph.createNode('COMPONENT', pageId, { name: 'Button', width: 120 })
+ const label = store.graph.createNode('TEXT', button.id, { name: 'Label', text: 'Button' })
+ const card = store.graph.createNode('COMPONENT', pageId, { name: 'Card', y: 120, width: 200 })
+ const action = store.graph.createInstance(button.id, card.id, { name: 'Action' })
+ const cardInstance = store.graph.createInstance(card.id, pageId, { x: 300, y: 120 })
+ if (!action || !cardInstance) throw new Error('Expected instances')
+ return {
+ buttonId: button.id,
+ labelId: label.id,
+ cardId: card.id,
+ cardInstanceId: cardInstance.id
+ }
+ })
+}
+
+export async function selectNode(page: Page, nodeId: string): Promise<void> {
+ await page.evaluate((id) => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ store.select([id])
+ }, nodeId)
+}
+
+/** A component's property definitions, as name, type, and default. */
+export function componentPropertyDefinitions(page: Page, componentId: string) {
+ return page.evaluate((id) => {
+ const node = window.openPencil?.getStore?.()?.graph.getNode(id)
+ return (node?.componentPropertyDefinitions ?? []).map(({ name, type, defaultValue }) => ({
+ name,
+ type,
+ defaultValue
+ }))
+ }, componentId)
+}
+
+/** The text a nested instance shows inside an instance. */
+export function nestedInstanceText(page: Page, instanceId: string, nestedName: string) {
+ return page.evaluate(
+ ({ id, name }) => {
+ const graph = window.openPencil?.getStore?.()?.graph
+ const nested = graph?.getChildren(id).find((node) => node.name === name)
+ if (!graph || !nested) return null
+ return graph.getChildren(nested.id).find((node) => node.type === 'TEXT')?.text ?? null
+ },
+ { id: instanceId, name: nestedName }
+ )
+}
diff --git a/tools/checks/i18n/translation-baseline.txt b/tools/checks/i18n/translation-baseline.txt
index b4fcf3811..cb2d4fdfe 100644
--- a/tools/checks/i18n/translation-baseline.txt
+++ b/tools/checks/i18n/translation-baseline.txt
@@ -27,6 +27,9 @@ de:panels.colorFormatHsb
de:panels.colorFormatHsl
de:panels.colorFormatOkhcl
de:panels.colorFormatRgb
+de:panels.componentPropertyBoolean
+de:panels.componentPropertyName
+de:panels.componentPropertyText
de:panels.design
de:panels.export
de:panels.frame
@@ -142,6 +145,7 @@ fr:panels.maskTypeAlpha
fr:panels.maskTypeLuminance
fr:panels.maxHeightShort
fr:panels.minHeightShort
+fr:panels.nestedInstance
fr:panels.page
fr:panels.pages
fr:panels.position