Skip to content

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

feat: add and edit variants the way Figma does (#992)

Danila Poyarkov3ab194e90039
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a1fcb4b79..f8a8e9ad2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -37,6 +37,7 @@
### Added
+- Add a variant to a standalone component from the header's **Add variant** button, as in Figma (#847): it becomes a component set named after it, whose existing instances and properties carry over, with a `Property 1=Variant2` copy below. A set's variant properties are rows of its **Properties** list, each opening to rename it and add, rename, reorder, or remove its values; removing a value variants still use moves them to another value. Variants that share a combination of values are named in a notice that selects them.
- Create and edit a component's text, boolean, and instance swap properties from the properties panel, as in Figma (#847). A layer in a main component links its text content, visibility, or swapped component to a new or existing property from the Typography and Appearance sections and the instance header, and shows the linked property in place of the value. The component lists its properties, each opening to rename it, change its default, see and unlink the layers it drives, or delete it, and reorders them by dragging. Expose nested instances so their properties show, grouped under the instance's name, on instances of the component. Typing into text a property drives sets the property: its default in the main component, the instance's value in an instance.
- 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.
@@ -86,6 +87,7 @@
### Changed
+- **Add variant** on a component set copies its last variant below it, 20 px apart, with the next free value such as `Variant3`, and grows the set to hold it, as Figma does. It used to place a copy with the same values to the right, which made a duplicate combination.
- The `get_selection` tool returns the selected layers with their direct children by default instead of their whole subtrees, and takes a `depth` for more or fewer levels, so agents can start from what the user selected without reading the full tree.
- The width and height menus in the properties panel offer Hug only for auto-layout frames and text, as in Figma; on a frame without auto layout it had no effect.
- Confirm deleting an AI conversation in the standard confirmation dialog, which names the conversation, instead of a prompt inside the chat panel.
diff --git a/packages/core/src/editor/bridges/components.ts b/packages/core/src/editor/bridges/components.ts
index d91bbd4ce..5639794d2 100644
--- a/packages/core/src/editor/bridges/components.ts
+++ b/packages/core/src/editor/bridges/components.ts
@@ -57,6 +57,9 @@ export function createComponentBridge(
switchInstanceVariant: components.switchInstanceVariant,
addVariant: components.addVariant,
duplicateVariant: components.duplicateVariant,
+ getVariantOptions: components.getVariantOptions,
+ addVariantValue: components.addVariantValue,
+ removeVariantValue: components.removeVariantValue,
removeVariant: components.removeVariant,
getInstanceComponentPropertyDefinitions: components.getInstanceComponentPropertyDefinitions,
getInstanceComponentPropertyValue: components.getInstanceComponentPropertyValue,
diff --git a/packages/core/src/editor/components/authoring/index.ts b/packages/core/src/editor/components/authoring/index.ts
index 47057449e..ea9e4a792 100644
--- a/packages/core/src/editor/components/authoring/index.ts
+++ b/packages/core/src/editor/components/authoring/index.ts
@@ -243,17 +243,21 @@ export function createComponentAuthoringActions(ctx: EditorContext) {
return true
}
- /** Move a text, boolean or swap property among its siblings; `.fig` keeps the order. */
+ /**
+ * Move a property among its siblings; slots keep their place. `.fig` keeps the order, and a
+ * set's variant names follow its variant properties' order.
+ */
function moveComponentProperty(ownerId: string, propertyId: string, index: number): boolean {
- const editable = editableProperty(ownerId, propertyId)
- if (!editable) return false
- const { owner } = editable
+ const owner = ctx.graph.getNode(ownerId)
+ if (owner?.type !== 'COMPONENT' && owner?.type !== 'COMPONENT_SET') return false
+ assertNodeEditable(ctx.graph, ownerId)
const ids = owner.componentPropertyDefinitions.map((definition) => definition.id)
const movable = new Set(
owner.componentPropertyDefinitions
- .filter((definition) => AUTHORED_TYPES.has(definition.type))
+ .filter((definition) => definition.type !== 'SLOT')
.map((definition) => definition.id)
)
+ if (!movable.has(propertyId)) return false
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)
diff --git a/packages/core/src/editor/components/variants/add.ts b/packages/core/src/editor/components/variants/add.ts
new file mode 100644
index 000000000..68bd03c24
--- /dev/null
+++ b/packages/core/src/editor/components/variants/add.ts
@@ -0,0 +1,205 @@
+import { createComponentPropertyId, type SceneNode } from '@open-pencil/scene-graph'
+import { buildVariantName } from '@open-pencil/scene-graph/variant-name'
+
+import { assertNodeEditable } from '#core/editor/capabilities'
+import { restoreSubtree, snapshotSubtree } from '#core/editor/clipboard/subtree-history'
+import { VARIANT_SET_PADDING, variantSetProps } from '#core/editor/components/variant-set'
+import { wrapSelectionInContainer } from '#core/editor/structure/container-wrap'
+import type { EditorContext } from '#core/editor/types'
+
+import {
+ getComponentSet,
+ getComponentSetVariants,
+ getVariantDefinitions,
+ getVariantOptions
+} from './model'
+
+type SetFields = Pick<
+ SceneNode,
+ 'componentPropertyDefinitions' | 'width' | 'height' | 'derivedLayout'
+>
+type VariantFields = Pick<
+ SceneNode,
+ 'name' | 'componentPropertyValues' | 'componentPropertyDefinitions'
+>
+
+/** Figma names a set's first variant property `Property 1` and its first value `Default`. */
+const FIRST_PROPERTY = 'Property 1'
+const FIRST_VALUE = 'Default'
+
+function setFields(node: SceneNode): SetFields {
+ return {
+ componentPropertyDefinitions: structuredClone(node.componentPropertyDefinitions),
+ width: node.width,
+ height: node.height,
+ derivedLayout: structuredClone(node.derivedLayout)
+ }
+}
+
+function variantFields(node: SceneNode): VariantFields {
+ return {
+ name: node.name,
+ componentPropertyValues: structuredClone(node.componentPropertyValues),
+ componentPropertyDefinitions: structuredClone(node.componentPropertyDefinitions)
+ }
+}
+
+/**
+ * Make a standalone component the first variant of a new set, as Figma's Add variant does: the
+ * set is named after it and padded like Combine as variants, the component keeps its node so its
+ * instances follow it, and its own properties move to the set.
+ */
+function wrapInVariantSet(ctx: EditorContext, component: SceneNode): string | undefined {
+ const parentId = component.parentId ?? ctx.state.currentPageId
+ const setId = wrapSelectionInContainer(
+ ctx,
+ 'COMPONENT_SET',
+ [component],
+ variantSetProps(ctx.graph, [component], parentId, 'canvas')
+ )
+ const set = setId ? ctx.graph.getNode(setId) : undefined
+ if (!setId || !set) return undefined
+ const setBefore = setFields(set)
+ const componentBefore = variantFields(component)
+ const setAfter: SetFields = {
+ ...setBefore,
+ componentPropertyDefinitions: [
+ {
+ id: createComponentPropertyId(),
+ name: FIRST_PROPERTY,
+ type: 'VARIANT',
+ defaultValue: FIRST_VALUE,
+ variantOptions: [FIRST_VALUE]
+ },
+ ...structuredClone(component.componentPropertyDefinitions)
+ ]
+ }
+ const componentAfter: VariantFields = {
+ name: buildVariantName({ [FIRST_PROPERTY]: FIRST_VALUE }),
+ componentPropertyValues: { [FIRST_PROPERTY]: FIRST_VALUE },
+ componentPropertyDefinitions: []
+ }
+ const apply = (setValues: SetFields, componentValues: VariantFields) => {
+ ctx.graph.updateNode(setId, structuredClone(setValues))
+ ctx.graph.updateNode(component.id, structuredClone(componentValues))
+ ctx.requestRender()
+ }
+ ctx.undo.execute({
+ label: 'Add variant',
+ forward: () => apply(setAfter, componentAfter),
+ inverse: () => apply(setBefore, componentBefore)
+ })
+ return setId
+}
+
+/** The first `Variant2`, `Variant3`, … no variant of the property uses yet, as Figma names them. */
+function nextVariantValue(options: readonly string[]): string {
+ const taken = new Set(options)
+ let index = 2
+ while (taken.has(`Variant${index}`)) index++
+ return `Variant${index}`
+}
+
+/**
+ * Copy `source` after the set's last variant. A set with auto layout places the copy itself; one
+ * without, as Figma makes them, gets it 20 below the last variant and grows to hold it. With
+ * `nextValue`, the copy takes the next free value of the set's first variant property, as Figma's
+ * Add variant does; without, it keeps the source's values for the caller to change.
+ */
+export function appendVariant(
+ ctx: EditorContext,
+ setId: string,
+ source: SceneNode,
+ nextValue: boolean
+): string | undefined {
+ const set = getComponentSet(ctx.graph, setId)
+ const definition = getVariantDefinitions(ctx.graph, setId).at(0)
+ if (!set || (nextValue && !definition)) return undefined
+ assertNodeEditable(ctx.graph, source.id)
+ const variants = getComponentSetVariants(ctx.graph, setId)
+ const bottom = Math.max(...variants.map((variant) => variant.y + variant.height))
+ const value =
+ definition && nextValue
+ ? nextVariantValue(getVariantOptions(ctx.graph, setId, definition.id))
+ : null
+ const values =
+ definition && value
+ ? { ...source.componentPropertyValues, [definition.name]: value }
+ : source.componentPropertyValues
+ const ordered = Object.fromEntries(
+ getVariantDefinitions(ctx.graph, setId).map((item) => [item.name, values[item.name] ?? ''])
+ )
+ const laidOut = set.layoutMode !== 'NONE'
+ const fields: Partial<SceneNode> = {
+ name: buildVariantName(ordered),
+ componentPropertyValues: values,
+ // A new layer has no geometry a file saved for it; the source's would pin it in place.
+ derivedLayout: null
+ }
+ if (!laidOut) {
+ fields.x = source.x
+ fields.y = bottom + VARIANT_SET_PADDING
+ }
+ const clone = ctx.graph.cloneTree(source.id, setId, fields)
+ if (!clone) return undefined
+ const setBefore = setFields(set)
+ const setAfter: SetFields = {
+ componentPropertyDefinitions: set.componentPropertyDefinitions.map((item) =>
+ value && item.id === definition?.id
+ ? { ...item, variantOptions: [...(item.variantOptions ?? []), value] }
+ : item
+ ),
+ width: laidOut ? set.width : Math.max(set.width, clone.x + clone.width + VARIANT_SET_PADDING),
+ height: laidOut
+ ? set.height
+ : Math.max(set.height, clone.y + clone.height + VARIANT_SET_PADDING),
+ derivedLayout: laidOut ? null : set.derivedLayout
+ }
+ // Auto layout sizes the set and places the copy; the stored size is only a starting point.
+ const apply = (fields: SetFields) => {
+ ctx.graph.updateNode(setId, structuredClone(fields))
+ if (laidOut) ctx.runLayoutForNode(setId)
+ }
+ apply(setAfter)
+ const snapshots = snapshotSubtree(ctx.graph, clone.id)
+ ctx.setSelectedIds(new Set([clone.id]))
+ ctx.undo.push({
+ label: 'Add variant',
+ forward: () => {
+ const root = snapshots.get(clone.id)
+ if (root) restoreSubtree(ctx.graph, root, setId, snapshots)
+ apply(setAfter)
+ ctx.setSelectedIds(new Set([clone.id]))
+ ctx.requestRender()
+ },
+ inverse: () => {
+ ctx.graph.deleteNode(clone.id)
+ apply(setBefore)
+ ctx.setSelectedIds(new Set([source.id]))
+ ctx.requestRender()
+ }
+ })
+ ctx.requestRender()
+ return clone.id
+}
+
+/**
+ * Figma's Add variant. A standalone component becomes a set first; a variant is copied as is,
+ * and a set copies its last variant. The copy is selected.
+ */
+export function addVariant(ctx: EditorContext, nodeId: string): string | undefined {
+ const node = ctx.graph.getNode(nodeId)
+ if (node?.type !== 'COMPONENT' && node?.type !== 'COMPONENT_SET') return undefined
+ assertNodeEditable(ctx.graph, nodeId)
+ let result: string | undefined
+ ctx.undo.runBatch('Add variant', () => {
+ let setId = node.type === 'COMPONENT_SET' ? node.id : node.parentId
+ if (node.type === 'COMPONENT' && (!setId || !getComponentSet(ctx.graph, setId)))
+ setId = wrapInVariantSet(ctx, node) ?? null
+ if (!setId) return
+ const source =
+ node.type === 'COMPONENT' ? node : getComponentSetVariants(ctx.graph, setId).at(-1)
+ if (source) result = appendVariant(ctx, setId, source, true)
+ })
+ return result
+}
diff --git a/packages/core/src/editor/components/variants/definitions.ts b/packages/core/src/editor/components/variants/definitions.ts
index f3ade16cb..2895f9f28 100644
--- a/packages/core/src/editor/components/variants/definitions.ts
+++ b/packages/core/src/editor/components/variants/definitions.ts
@@ -19,7 +19,7 @@ import {
getComponentSet,
getComponentSetVariants,
getVariantDefinitions,
- hasDuplicateCombination,
+ getVariantOptions,
variantValues,
type VariantMutationResult
} from './model'
@@ -70,7 +70,7 @@ export function reorderVariantValues(
const definition = getVariantDefinitions(ctx.graph, componentSetId).find(
(item) => item.id === propertyId
)
- const currentValues = definition?.variantOptions ?? []
+ const currentValues = getVariantOptions(ctx.graph, componentSetId, propertyId)
const before = captureVariantSnapshot(ctx, componentSetId)
if (!componentSet || !definition || !before) return false
if (
@@ -234,17 +234,8 @@ export function renameVariantValue(
previousValue === normalizedValue
)
return false
- if (
- hasDuplicateCombination(ctx.graph, componentSetId, (variant) => ({
- ...variantValues(ctx.graph, componentSetId, variant),
- [definition.name]:
- variant.componentPropertyValues[definition.name] === previousValue
- ? normalizedValue
- : (variant.componentPropertyValues[definition.name] ?? '')
- }))
- ) {
- return false
- }
+ const options = getVariantOptions(ctx.graph, componentSetId, propertyId)
+ if (!options.includes(previousValue) || options.includes(normalizedValue)) return false
ctx.graph.updateNode(componentSetId, {
componentPropertyDefinitions: componentSet.componentPropertyDefinitions.map((item) =>
@@ -252,7 +243,7 @@ export function renameVariantValue(
? {
...item,
defaultValue: item.defaultValue === previousValue ? normalizedValue : item.defaultValue,
- variantOptions: item.variantOptions?.map((option) =>
+ variantOptions: options.map((option) =>
option === previousValue ? normalizedValue : option
)
}
diff --git a/packages/core/src/editor/components/variants/history.ts b/packages/core/src/editor/components/variants/history.ts
index a18c28abf..db1e8dbb2 100644
--- a/packages/core/src/editor/components/variants/history.ts
+++ b/packages/core/src/editor/components/variants/history.ts
@@ -90,7 +90,8 @@ export function updateVariantName(
variant.componentPropertyValues[definition.name] ?? ''
])
)
- ctx.graph.updateNode(variant.id, { name: buildVariantName(values) })
+ if (Object.keys(values).length)
+ ctx.graph.updateNode(variant.id, { name: buildVariantName(values) })
}
export function refreshVariantOptions(ctx: EditorContext, componentSetId: string): void {
@@ -101,7 +102,7 @@ export function refreshVariantOptions(ctx: EditorContext, componentSetId: string
if (definition.type !== 'VARIANT') return definition
const present = collected.get(definition.name) ?? new Set<string>()
const options = [
- ...(definition.variantOptions ?? []).filter((value) => present.has(value)),
+ ...(definition.variantOptions ?? []),
...[...present].filter((value) => !definition.variantOptions?.includes(value))
]
return {
diff --git a/packages/core/src/editor/components/variants/index.ts b/packages/core/src/editor/components/variants/index.ts
index 60c139469..7614a7dfe 100644
--- a/packages/core/src/editor/components/variants/index.ts
+++ b/packages/core/src/editor/components/variants/index.ts
@@ -6,6 +6,7 @@ import { restoreSubtree, snapshotSubtree } from '#core/editor/clipboard/subtree-
import { reapplyInstanceComponentProperties } from '#core/editor/components/properties'
import type { EditorContext } from '#core/editor/types'
+import { addVariant, appendVariant } from './add'
import {
addPropertyDefinition,
removePropertyDefinition,
@@ -23,11 +24,13 @@ import {
getComponentSetVariantConflicts,
getComponentSetVariants,
getDefaultVariantForComponentSet,
+ getVariantOptions,
validateComponentSet,
variantValues,
type VariantOptionAvailability,
type VariantTransitionResult
} from './model'
+import { addVariantValue, removeVariantValue } from './options'
export type {
VariantConflict,
@@ -110,45 +113,13 @@ export function createVariantActions(ctx: EditorContext) {
return { kind: 'changed', componentId: target.id }
}
+ /** A copy of a variant with its values, below the set's last variant, for the caller to set. */
function duplicateVariant(variantId: string): string | undefined {
- assertNodeEditable(ctx.graph, variantId)
const variant = ctx.graph.getNode(variantId)
- const componentSetId = variant?.parentId
- if (
- variant?.type !== 'COMPONENT' ||
- !componentSetId ||
- !getComponentSet(ctx.graph, componentSetId)
- ) {
+ const setId = variant?.parentId
+ if (variant?.type !== 'COMPONENT' || !setId || !getComponentSet(ctx.graph, setId))
return undefined
- }
- const clone = ctx.graph.cloneTree(variantId, componentSetId, {
- x: variant.x + variant.width + 40,
- name: variant.name
- })
- if (!clone) return undefined
- const snapshots = snapshotSubtree(ctx.graph, clone.id)
- ctx.setSelectedIds(new Set([clone.id]))
- ctx.undo.push({
- label: 'Add variant',
- forward: () => {
- const root = snapshots.get(clone.id)
- if (root) restoreSubtree(ctx.graph, root, componentSetId, snapshots)
- ctx.setSelectedIds(new Set([clone.id]))
- ctx.requestRender()
- },
- inverse: () => {
- ctx.graph.deleteNode(clone.id)
- ctx.setSelectedIds(new Set([variantId]))
- ctx.requestRender()
- }
- })
- ctx.requestRender()
- return clone.id
- }
-
- function addVariant(componentSetId: string): string | undefined {
- const source = getDefaultVariantForComponentSet(ctx.graph, componentSetId)
- return source ? duplicateVariant(source.id) : undefined
+ return appendVariant(ctx, setId, variant, false)
}
function removeVariant(variantId: string): boolean {
@@ -216,7 +187,17 @@ export function createVariantActions(ctx: EditorContext) {
validateComponentSet(ctx.graph, componentSetId),
getVariantOptionAvailability,
switchInstanceVariant,
- addVariant,
+ addVariant: (nodeId: string) => addVariant(ctx, nodeId),
+ getVariantOptions: (componentSetId: string, propertyId: string) =>
+ getVariantOptions(ctx.graph, componentSetId, propertyId),
+ addVariantValue: (componentSetId: string, propertyId: string, value: string) =>
+ addVariantValue(ctx, componentSetId, propertyId, value),
+ removeVariantValue: (
+ componentSetId: string,
+ propertyId: string,
+ value: string,
+ replacement?: string
+ ) => removeVariantValue(ctx, componentSetId, propertyId, value, replacement),
duplicateVariant,
removeVariant
}
diff --git a/packages/core/src/editor/components/variants/model.ts b/packages/core/src/editor/components/variants/model.ts
index 9a5ed70e7..cd59e1538 100644
--- a/packages/core/src/editor/components/variants/model.ts
+++ b/packages/core/src/editor/components/variants/model.ts
@@ -1,3 +1,5 @@
+import { uniq } from 'es-toolkit/array'
+
import type { ComponentPropertyDefinition, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
export type VariantConflict = {
@@ -87,6 +89,16 @@ export function collectVariantOptions(
return options
}
+/** Declared values stay available even before a component uses them. */
+export function getVariantOptions(graph: SceneGraph, setId: string, propertyId: string): string[] {
+ const definition = getVariantDefinitions(graph, setId).find((item) => item.id === propertyId)
+ if (!definition) return []
+ return uniq([
+ ...(definition.variantOptions ?? []),
+ ...(collectVariantOptions(graph, setId).get(definition.name) ?? [])
+ ])
+}
+
export function findVariantByValues(
graph: SceneGraph,
componentSetId: string,
diff --git a/packages/core/src/editor/components/variants/options.ts b/packages/core/src/editor/components/variants/options.ts
new file mode 100644
index 000000000..18bd3b8c3
--- /dev/null
+++ b/packages/core/src/editor/components/variants/options.ts
@@ -0,0 +1,103 @@
+import type { EditorContext } from '#core/editor/types'
+
+import {
+ assertComponentSetEditable,
+ captureVariantSnapshot,
+ recordSnapshotChange,
+ setVariantValues
+} from './history'
+import {
+ getComponentSet,
+ getComponentSetVariants,
+ getVariantOptions,
+ variantValues,
+ type VariantMutationResult
+} from './model'
+
+export function addVariantValue(
+ ctx: EditorContext,
+ setId: string,
+ propertyId: string,
+ value: string
+): boolean {
+ assertComponentSetEditable(ctx, setId)
+ const set = getComponentSet(ctx.graph, setId)
+ const definition = set?.componentPropertyDefinitions.find(
+ (item) => item.id === propertyId && item.type === 'VARIANT'
+ )
+ const normalized = value.trim()
+ const options = getVariantOptions(ctx.graph, setId, propertyId)
+ const before = captureVariantSnapshot(ctx, setId)
+ if (!set || !definition || !before || !normalized || options.includes(normalized)) return false
+ ctx.graph.updateNode(setId, {
+ componentPropertyDefinitions: set.componentPropertyDefinitions.map((item) =>
+ item.id === propertyId ? { ...item, variantOptions: [...options, normalized] } : item
+ )
+ })
+ const after = captureVariantSnapshot(ctx, setId)
+ if (after) recordSnapshotChange(ctx, setId, 'Add variant value', before, after)
+ return true
+}
+
+export function removeVariantValue(
+ ctx: EditorContext,
+ setId: string,
+ propertyId: string,
+ value: string,
+ replacement?: string
+): VariantMutationResult {
+ assertComponentSetEditable(ctx, setId)
+ const set = getComponentSet(ctx.graph, setId)
+ const definition = set?.componentPropertyDefinitions.find(
+ (item) => item.id === propertyId && item.type === 'VARIANT'
+ )
+ const before = captureVariantSnapshot(ctx, setId)
+ const options = getVariantOptions(ctx.graph, setId, propertyId)
+ if (!set || !definition || !before || !options.includes(value)) return { kind: 'invalid' }
+ const remaining = options.filter((option) => option !== value)
+ const variants = getComponentSetVariants(ctx.graph, setId)
+ const affected = variants.filter(
+ (node) => node.componentPropertyValues[definition.name] === value
+ )
+ if (affected.length && (!replacement || !remaining.includes(replacement)))
+ return { kind: 'invalid' }
+ if (affected.length) {
+ const affectedIds = new Set(affected.map((node) => node.id))
+ const combinations = new Map<string, string[]>()
+ for (const node of variants) {
+ const values = variantValues(ctx.graph, setId, node)
+ if (affectedIds.has(node.id) && replacement) values[definition.name] = replacement
+ const key = JSON.stringify(values)
+ const ids = combinations.get(key) ?? []
+ ids.push(node.id)
+ combinations.set(key, ids)
+ }
+ const conflicts = [...combinations.values()]
+ .filter((ids) => ids.length > 1 && ids.some((id) => affectedIds.has(id)))
+ .flat()
+ if (conflicts.length) return { kind: 'conflict', componentIds: conflicts }
+ }
+ ctx.graph.updateNode(setId, {
+ componentPropertyDefinitions: set.componentPropertyDefinitions.map((item) =>
+ item.id === propertyId
+ ? {
+ ...item,
+ variantOptions: remaining,
+ defaultValue:
+ item.defaultValue === value
+ ? (replacement ?? remaining.at(0) ?? '')
+ : item.defaultValue
+ }
+ : item
+ )
+ })
+ if (replacement)
+ for (const node of affected)
+ setVariantValues(ctx, setId, node.id, {
+ ...node.componentPropertyValues,
+ [definition.name]: replacement
+ })
+ const after = captureVariantSnapshot(ctx, setId)
+ if (after) recordSnapshotChange(ctx, setId, 'Remove variant value', before, after)
+ return { kind: 'changed' }
+}
diff --git a/packages/core/src/editor/index.ts b/packages/core/src/editor/index.ts
index bdb907a7f..c705af8f9 100644
--- a/packages/core/src/editor/index.ts
+++ b/packages/core/src/editor/index.ts
@@ -32,7 +32,11 @@ export type { NodePreview } from './node-preview'
export { EDITOR_TOOLS, TOOL_SHORTCUTS } from './tool-registry'
export type { RenameSelectionOptions, RenameSelectionPreview } from './structure/rename'
export type { EditorToolDef } from './tool-registry'
-export type { VariantConflict, VariantValidationIssue } from './components/variants'
+export type {
+ VariantConflict,
+ VariantMutationResult,
+ VariantValidationIssue
+} from './components/variants'
export type {
ClipboardImageResolution,
EditorContext,
diff --git a/packages/core/tests/editor/components/variants/add.test.ts b/packages/core/tests/editor/components/variants/add.test.ts
new file mode 100644
index 000000000..58efd2524
--- /dev/null
+++ b/packages/core/tests/editor/components/variants/add.test.ts
@@ -0,0 +1,193 @@
+import { describe, expect, test } from 'bun:test'
+
+import { createEditor } from '@open-pencil/core/editor'
+
+function defined<T>(value: T | null | undefined): T {
+ if (value == null) throw new Error('Expected value')
+ return value
+}
+
+/** A standalone Chip component with a text property and an instance, as on Figma's canvas. */
+function setup() {
+ const editor = createEditor()
+ const page = editor.state.currentPageId
+ const chip = editor.graph.createNode('COMPONENT', page, {
+ name: 'Chip',
+ x: 40,
+ y: 40,
+ width: 80,
+ height: 32
+ })
+ const label = editor.graph.createNode('TEXT', chip.id, { name: 'Label', text: 'Chip' })
+ const property = defined(editor.exposeComponentProperty(label.id, 'TEXT', 'Label'))
+ const instance = defined(editor.graph.createInstance(chip.id, page, { x: 40, y: 200 }))
+ return { editor, chip, property, instance }
+}
+
+// Live Figma 126: Add variant on a standalone component and then on its set.
+describe('Add variant', () => {
+ test('turns a standalone component into a set the way Figma does', () => {
+ const { editor, chip, property, instance } = setup()
+ editor.undo.clear()
+ const added = defined(editor.addVariant(chip.id))
+
+ const set = defined(editor.graph.getNode(defined(chip.parentId)))
+ expect(set).toMatchObject({ type: 'COMPONENT_SET', name: 'Chip', layoutMode: 'NONE' })
+ expect(set).toMatchObject({ x: 20, y: 20, width: 120, height: 124 })
+ const [variant, value] = set.componentPropertyDefinitions
+ expect(variant).toMatchObject({
+ name: 'Property 1',
+ type: 'VARIANT',
+ defaultValue: 'Default',
+ variantOptions: ['Default', 'Variant2']
+ })
+ expect(value).toMatchObject({ id: property, name: 'Label', type: 'TEXT' })
+
+ const copy = defined(editor.graph.getNode(added))
+ expect(chip).toMatchObject({ name: 'Property 1=Default', x: 20, y: 20 })
+ expect(chip.componentPropertyDefinitions).toEqual([])
+ expect(copy).toMatchObject({ name: 'Property 1=Variant2', x: 20, y: 72 })
+ expect(instance.componentId).toBe(chip.id)
+ expect([...editor.state.selectedIds]).toEqual([added])
+
+ // One step: the component is back as it was, with its property and outside a set.
+ editor.undo.undo()
+ expect(editor.graph.getNode(added)).toBeUndefined()
+ expect(chip).toMatchObject({ name: 'Chip', x: 40, y: 40 })
+ expect(chip.componentPropertyDefinitions.map((item) => item.id)).toEqual([property])
+ expect(editor.graph.getNode(defined(chip.parentId))?.type).toBe('CANVAS')
+ expect(editor.undo.undo()).toBeNull()
+ })
+
+ test('from a set, appends the next value below the last variant and grows the set', () => {
+ const { editor, chip } = setup()
+ editor.addVariant(chip.id)
+ const setId = defined(chip.parentId)
+ const third = defined(editor.addVariant(setId))
+
+ const set = defined(editor.graph.getNode(setId))
+ expect(defined(editor.graph.getNode(third))).toMatchObject({
+ name: 'Property 1=Variant3',
+ x: 20,
+ y: 124
+ })
+ expect(set).toMatchObject({ width: 120, height: 176 })
+ expect(set.componentPropertyDefinitions[0]?.variantOptions).toEqual([
+ 'Default',
+ 'Variant2',
+ 'Variant3'
+ ])
+ editor.undo.undo()
+ expect(editor.graph.getNode(third)).toBeUndefined()
+ expect(set.height).toBe(124)
+ expect(set.componentPropertyDefinitions[0]?.variantOptions).toEqual(['Default', 'Variant2'])
+ })
+
+ test('skips values variants use even when the set does not list them', () => {
+ const { editor, chip } = setup()
+ editor.addVariant(chip.id)
+ const set = defined(editor.graph.getNode(defined(chip.parentId)))
+ // As some files save it: Variant2 is in use but missing from the declared options.
+ const [variant, ...rest] = set.componentPropertyDefinitions
+ editor.graph.updateNode(set.id, {
+ componentPropertyDefinitions: [{ ...defined(variant), variantOptions: ['Default'] }, ...rest]
+ })
+ const added = defined(editor.addVariant(set.id))
+ expect(defined(editor.graph.getNode(added)).name).toBe('Property 1=Variant3')
+ expect(editor.getComponentSetVariantConflicts(set.id)).toEqual([])
+ })
+
+ test('in a set with auto layout, the copy follows the last variant where layout puts it', async () => {
+ const editor = createEditor()
+ const page = editor.state.currentPageId
+ const set = editor.graph.createNode('COMPONENT_SET', page, {
+ name: 'Badge',
+ layoutMode: 'HORIZONTAL',
+ primaryAxisSizing: 'HUG',
+ counterAxisSizing: 'HUG',
+ itemSpacing: 16,
+ paddingTop: 16,
+ paddingRight: 16,
+ paddingBottom: 16,
+ paddingLeft: 16,
+ componentPropertyDefinitions: [
+ {
+ id: 'variant:state',
+ name: 'State',
+ type: 'VARIANT',
+ defaultValue: 'Info',
+ variantOptions: ['Info', 'Warning']
+ }
+ ]
+ })
+ for (const state of ['Info', 'Warning'])
+ editor.graph.createNode('COMPONENT', set.id, {
+ name: `State=${state}`,
+ width: 71,
+ height: 25,
+ componentPropertyValues: { State: state }
+ })
+ await Promise.resolve()
+ editor.runLayoutForNode(set.id)
+ const width = set.width
+ // As loaded from a .fig: layout prefers the geometry the file saved.
+ for (const variant of editor.graph.getChildren(set.id))
+ editor.graph.updateNode(variant.id, {
+ derivedLayout: { x: variant.x, y: variant.y, width: variant.width, height: variant.height }
+ })
+ editor.graph.updateNode(set.id, { derivedLayout: { width, height: set.height } })
+
+ const added = defined(editor.addVariant(set.id))
+ const copy = defined(editor.graph.getNode(added))
+ expect(copy).toMatchObject({ name: 'State=Variant2', x: 16 + 2 * (71 + 16), y: 16 })
+ expect(set.width).toBe(width + 71 + 16)
+ editor.undo.undo()
+ expect(editor.graph.getNode(added)).toBeUndefined()
+ expect(set.width).toBe(width)
+ expect(set.derivedLayout).toEqual({ width, height: set.height })
+ })
+
+ test('a duplicated variant keeps its values for the caller to change', () => {
+ const { editor, chip } = setup()
+ const second = defined(editor.addVariant(chip.id))
+ const copy = defined(editor.duplicateVariant(second))
+ expect(defined(editor.graph.getNode(copy))).toMatchObject({
+ name: 'Property 1=Variant2',
+ y: 124
+ })
+ expect(editor.getComponentSetVariantConflicts(defined(chip.parentId))).toHaveLength(1)
+ })
+})
+
+describe('variant values', () => {
+ test('adds a value no variant uses yet and removes it again', () => {
+ const { editor, chip } = setup()
+ editor.addVariant(chip.id)
+ const setId = defined(chip.parentId)
+ const propertyId = defined(editor.getComponentSetPropertyDefs(setId)[0]).id
+ expect(editor.addVariantValue(setId, propertyId, 'Pressed')).toBe(true)
+ expect(editor.getVariantOptions(setId, propertyId)).toEqual(['Default', 'Variant2', 'Pressed'])
+ expect(editor.addVariantValue(setId, propertyId, 'Pressed')).toBe(false)
+ expect(editor.removeVariantValue(setId, propertyId, 'Pressed')).toEqual({ kind: 'changed' })
+ expect(editor.getVariantOptions(setId, propertyId)).toEqual(['Default', 'Variant2'])
+ })
+
+ test('removing a value variants use needs a replacement that keeps combinations unique', () => {
+ const { editor, chip } = setup()
+ const second = defined(editor.addVariant(chip.id))
+ const setId = defined(chip.parentId)
+ const propertyId = defined(editor.getComponentSetPropertyDefs(setId)[0]).id
+ expect(editor.removeVariantValue(setId, propertyId, 'Variant2')).toEqual({ kind: 'invalid' })
+ // Variant2 → Default would give two variants the same combination.
+ expect(editor.removeVariantValue(setId, propertyId, 'Variant2', 'Default')).toMatchObject({
+ kind: 'conflict'
+ })
+ editor.addVariantValue(setId, propertyId, 'Hover')
+ expect(editor.removeVariantValue(setId, propertyId, 'Variant2', 'Hover')).toEqual({
+ kind: 'changed'
+ })
+ expect(defined(editor.graph.getNode(second)).name).toBe('Property 1=Hover')
+ editor.undo.undo()
+ expect(defined(editor.graph.getNode(second)).name).toBe('Property 1=Variant2')
+ })
+})
diff --git a/packages/docs/user-guide/components.md b/packages/docs/user-guide/components.md
index 55600f538..e32d1de35 100644
--- a/packages/docs/user-guide/components.md
+++ b/packages/docs/user-guide/components.md
@@ -27,13 +27,13 @@ Select two or more components and press <kbd>⇧</kbd><kbd>⌘</kbd><kbd>K</kbd>
Each component in a set can define values across multiple variant dimensions, such as `Size=Small`, `State=Hover`, and `Theme=Dark`. OpenPencil supports sparse combinations, so a set does not need every possible combination. The top-left variant is the default and is used as the fallback when an update no longer contains an exact combination.
-Use the component properties panel to add, rename, reorder, and remove variant dimensions and values. Duplicate combinations are rejected.
+Select a component and press **Add variant** in the panel header to turn it into a component set, as Figma does: the component becomes `Property 1=Default` and a copy named `Property 1=Variant2` appears below it. On a set, **Add variant** copies its last variant with the next value. The set's variant properties are rows of its **Properties** list; click one to rename it or to add, rename, drag to reorder, or remove its values. Removing a value variants still use moves them to another value first, and variants that share every value are named in a notice that selects them.
## Component Properties
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.
+To link a layer of a main component to a property, use the link 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.
diff --git a/packages/vue/src/controls/component-props/authoring.ts b/packages/vue/src/controls/component-props/authoring.ts
index c982c65db..c0c3746fc 100644
--- a/packages/vue/src/controls/component-props/authoring.ts
+++ b/packages/vue/src/controls/component-props/authoring.ts
@@ -49,6 +49,72 @@ export function useComponentPropertyAuthoring() {
})
)
)
+ /** The set the selection belongs to, whose variant properties the list shows too. */
+ const componentSet = computed(() =>
+ context.value?.owner.type === 'COMPONENT_SET' ? context.value.owner : null
+ )
+ const variantProperties = useSceneComputed(() => {
+ const set = componentSet.value
+ if (!set) return []
+ const used = editor.collectVariantOptions(set.id)
+ return set.componentPropertyDefinitions
+ .filter((definition) => definition.type === 'VARIANT')
+ .map((definition) => ({
+ id: definition.id,
+ name: definition.name,
+ values: editor.getVariantOptions(set.id, definition.id),
+ used: [...(used.get(definition.name) ?? [])]
+ }))
+ })
+ type VariantProperty = (typeof variantProperties.value)[number]
+ type AuthoredProperty = (typeof definitions.value)[number]
+ type PropertyRow =
+ | { kind: 'variant'; id: string; variant: VariantProperty }
+ | { kind: 'property'; id: string; property: AuthoredProperty }
+ /** Every row of the list in the owner's order: variant properties and authored ones. */
+ const rows = computed((): PropertyRow[] => {
+ const owner = context.value?.owner
+ if (!owner) return []
+ const variantById = new Map(variantProperties.value.map((item) => [item.id, item]))
+ const authoredById = new Map(definitions.value.map((item) => [item.id, item]))
+ const ownRows = owner.componentPropertyDefinitions.flatMap((definition): PropertyRow[] => {
+ const variant = variantById.get(definition.id)
+ if (variant) return [{ kind: 'variant' as const, id: variant.id, variant }]
+ const property = authoredById.get(definition.id)
+ return property ? [{ kind: 'property' as const, id: property.id, property }] : []
+ })
+ // Properties a variant owns on its own come after the set's shared ones.
+ const localRows = definitions.value
+ .filter((item) => item.ownerId !== owner.id)
+ .map((property) => ({ kind: 'property' as const, id: property.id, property }))
+ return [...ownRows, ...localRows]
+ })
+ const conflicts = useSceneComputed(() => {
+ const set = componentSet.value
+ if (!set) return []
+ return editor.getComponentSetVariantConflicts(set.id).map((conflict) => ({
+ label: Object.entries(conflict.values)
+ .map(([name, value]) => `${name}=${value}`)
+ .join(', '),
+ componentIds: conflict.componentIds
+ }))
+ })
+
+ /** Figma names a new variant property Property 1, Property 2, … with the value Default. */
+ function addVariantProperty() {
+ const set = componentSet.value
+ if (!set) return undefined
+ const taken = new Set(set.componentPropertyDefinitions.map((definition) => definition.name))
+ let index = 1
+ while (taken.has(`Property ${index}`)) index++
+ return editor.addPropertyDefinition(set.id, `Property ${index}`, 'VARIANT', 'Default')
+ }
+
+ function withSet<T>(run: (setId: string) => T): T | undefined {
+ const set = componentSet.value
+ return set ? run(set.id) : undefined
+ }
+
const components = useSceneComputed(() =>
[...editor.graph.getAllNodes()].filter((node) => node.type === 'COMPONENT')
)
@@ -94,6 +160,23 @@ export function useComponentPropertyAuthoring() {
return {
context,
definitions,
+ rows,
+ componentSet,
+ conflicts,
+ addVariantProperty,
+ renameVariantProperty: (propertyId: string, name: string) =>
+ withSet((setId) => editor.renamePropertyDefinition(setId, propertyId, name)),
+ removeVariantProperty: (propertyId: string) =>
+ withSet((setId) => editor.removePropertyDefinition(setId, propertyId)),
+ renameVariantValue: (propertyId: string, previous: string, value: string) =>
+ withSet((setId) => editor.renameVariantValue(setId, propertyId, previous, value)),
+ reorderVariantValues: (propertyId: string, values: string[]) =>
+ withSet((setId) => editor.reorderVariantValues(setId, propertyId, values)),
+ addVariantValue: (propertyId: string, value: string) =>
+ withSet((setId) => editor.addVariantValue(setId, propertyId, value)),
+ removeVariantValue: (propertyId: string, value: string, replacement?: string) =>
+ withSet((setId) => editor.removeVariantValue(setId, propertyId, value, replacement)),
+ selectNodes: (nodeIds: string[]) => editor.select(nodeIds),
nestedInstances,
variantCount: computed(() => variants.value.length),
editable: computed(() => !!context.value?.editable),
diff --git a/packages/vue/src/i18n/locales/de/panels.json b/packages/vue/src/i18n/locales/de/panels.json
index 9c15825c0..a8575e53c 100644
--- a/packages/vue/src/i18n/locales/de/panels.json
+++ b/packages/vue/src/i18n/locales/de/panels.json
@@ -318,16 +318,10 @@
"preferLibrary": "Diese Bibliothek bevorzugen",
"assetVariantSummary": "{count} Varianten · {names}",
"duplicateVariantValues": "Doppelte Variantenwerte",
- "variantPropertyName": "Eigenschaftsname",
"addVariantProperty": "Varianteneigenschaft hinzufügen",
"addVariant": "Variante hinzufügen",
"duplicateVariant": "Variante duplizieren",
"removeVariantProperty": "Varianteneigenschaft entfernen",
- "moveVariantPropertyUp": "Varianteneigenschaft nach oben verschieben",
- "moveVariantPropertyDown": "Varianteneigenschaft nach unten verschieben",
- "moveVariantValueUp": "Variantenwert nach oben verschieben",
- "moveVariantValueDown": "Variantenwert nach unten verschieben",
- "noVariantProperties": "Keine Varianteneigenschaften",
"variantConflictHelp": "Jede Variante benötigt eine eindeutige Kombination von Eigenschaftswerten",
"openDocumentation": "Dokumentation öffnen",
"noLocalComponents": "Keine lokalen Komponenten",
@@ -338,6 +332,13 @@
"documentation": "Dokumentation",
"openDocs": "Dokumentation öffnen",
"properties": "Eigenschaften",
+ "componentPropertyVariant": "Variante",
+ "variantsShareValues": "{count} Varianten teilen {values}",
+ "selectVariants": "Auswählen",
+ "removeVariantValue": "{value} entfernen",
+ "moveVariantsTo": "Varianten mit {value} verschieben nach",
+ "addVariantValue": "Wert hinzufügen",
+ "variantValues": "Werte",
"componentPropertyText": "Text",
"componentPropertyBoolean": "Boolean",
"componentPropertySwap": "Instanz austauschen",
diff --git a/packages/vue/src/i18n/locales/es/panels.json b/packages/vue/src/i18n/locales/es/panels.json
index c6e8a067c..76439ba22 100644
--- a/packages/vue/src/i18n/locales/es/panels.json
+++ b/packages/vue/src/i18n/locales/es/panels.json
@@ -334,16 +334,10 @@
"preferLibrary": "Preferir esta biblioteca",
"assetVariantSummary": "{count} variantes · {names}",
"duplicateVariantValues": "Valores de variante duplicados",
- "variantPropertyName": "Nombre de la propiedad",
"addVariantProperty": "Agregar propiedad de variante",
"addVariant": "Agregar variante",
"duplicateVariant": "Duplicar variante",
"removeVariantProperty": "Eliminar propiedad de variante",
- "moveVariantPropertyUp": "Mover propiedad variante hacia arriba",
- "moveVariantPropertyDown": "Mover propiedad variante hacia abajo",
- "moveVariantValueUp": "Mover el valor de la variante hacia arriba",
- "moveVariantValueDown": "Mover el valor de la variante hacia abajo",
- "noVariantProperties": "Sin propiedades variantes",
"variantConflictHelp": "Cada variante necesita una combinación única de valores de propiedad.",
"openDocumentation": "Abrir documentación",
"noLocalComponents": "No hay componentes locales",
@@ -354,6 +348,13 @@
"documentation": "Documentación",
"openDocs": "Abrir docs",
"properties": "Propiedades",
+ "componentPropertyVariant": "Variante",
+ "variantsShareValues": "{count} variantes comparten {values}",
+ "selectVariants": "Seleccionar",
+ "removeVariantValue": "Quitar {value}",
+ "moveVariantsTo": "Mover las variantes con {value} a",
+ "addVariantValue": "Añadir valor",
+ "variantValues": "Valores",
"componentPropertyText": "Texto",
"componentPropertyBoolean": "Booleano",
"componentPropertySwap": "Intercambio de instancia",
diff --git a/packages/vue/src/i18n/locales/fr/panels.json b/packages/vue/src/i18n/locales/fr/panels.json
index 7f34302b7..b6133ee99 100644
--- a/packages/vue/src/i18n/locales/fr/panels.json
+++ b/packages/vue/src/i18n/locales/fr/panels.json
@@ -318,16 +318,10 @@
"preferLibrary": "Privilégier cette bibliothèque",
"assetVariantSummary": "{count} variantes · {names}",
"duplicateVariantValues": "Valeurs de variante en double",
- "variantPropertyName": "Nom de la propriété",
"addVariantProperty": "Ajouter une propriété de variante",
"addVariant": "Ajouter une variante",
"duplicateVariant": "Variante en double",
"removeVariantProperty": "Supprimer la propriété de variante",
- "moveVariantPropertyUp": "Déplacer la propriété de variante vers le haut",
- "moveVariantPropertyDown": "Déplacer la propriété de variante vers le bas",
- "moveVariantValueUp": "Déplacer la valeur de la variante vers le haut",
- "moveVariantValueDown": "Déplacer la valeur de la variante vers le bas",
- "noVariantProperties": "Aucune propriété de variante",
"variantConflictHelp": "Chaque variante nécessite une combinaison unique de valeurs de propriété",
"openDocumentation": "Ouvrir la documentation",
"noLocalComponents": "Aucun composant local",
@@ -338,6 +332,13 @@
"documentation": "Documentation",
"openDocs": "Ouvrir la doc",
"properties": "Propriétés",
+ "componentPropertyVariant": "Variante",
+ "variantsShareValues": "{count} variantes partagent {values}",
+ "selectVariants": "Sélectionner",
+ "removeVariantValue": "Retirer {value}",
+ "moveVariantsTo": "Déplacer les variantes avec {value} vers",
+ "addVariantValue": "Ajouter une valeur",
+ "variantValues": "Valeurs",
"componentPropertyText": "Texte",
"componentPropertyBoolean": "Booléen",
"componentPropertySwap": "Permutation d’instance",
diff --git a/packages/vue/src/i18n/locales/it/panels.json b/packages/vue/src/i18n/locales/it/panels.json
index daf1e06ab..cd8d94d8a 100644
--- a/packages/vue/src/i18n/locales/it/panels.json
+++ b/packages/vue/src/i18n/locales/it/panels.json
@@ -318,16 +318,10 @@
"preferLibrary": "Preferisci questa libreria",
"assetVariantSummary": "{count} varianti · {names}",
"duplicateVariantValues": "Valori variante duplicati",
- "variantPropertyName": "Nome della proprietà",
"addVariantProperty": "Aggiungi proprietà variante",
"addVariant": "Aggiungi variante",
"duplicateVariant": "Duplica variante",
"removeVariantProperty": "Rimuovi la proprietà della variante",
- "moveVariantPropertyUp": "Sposta la proprietà della variante verso l'alto",
- "moveVariantPropertyDown": "Sposta la proprietà della variante verso il basso",
- "moveVariantValueUp": "Sposta il valore della variante verso l'alto",
- "moveVariantValueDown": "Sposta il valore della variante verso il basso",
- "noVariantProperties": "Nessuna proprietà variante",
"variantConflictHelp": "Ogni variante necessita di una combinazione univoca di valori di proprietà",
"openDocumentation": "Apri documentazione",
"noLocalComponents": "Nessun componente locale",
@@ -338,6 +332,13 @@
"documentation": "Documentazione",
"openDocs": "Apri documentazione",
"properties": "Proprietà",
+ "componentPropertyVariant": "Variante",
+ "variantsShareValues": "{count} varianti condividono {values}",
+ "selectVariants": "Seleziona",
+ "removeVariantValue": "Rimuovi {value}",
+ "moveVariantsTo": "Sposta le varianti con {value} in",
+ "addVariantValue": "Aggiungi valore",
+ "variantValues": "Valori",
"componentPropertyText": "Testo",
"componentPropertyBoolean": "Booleano",
"componentPropertySwap": "Scambio di istanza",
diff --git a/packages/vue/src/i18n/locales/ja/panels.json b/packages/vue/src/i18n/locales/ja/panels.json
index c0fee558a..024ac9d7f 100644
--- a/packages/vue/src/i18n/locales/ja/panels.json
+++ b/packages/vue/src/i18n/locales/ja/panels.json
@@ -328,16 +328,10 @@
"preferLibrary": "このライブラリを優先",
"assetVariantSummary": "{count} 個のバリアント · {names}",
"duplicateVariantValues": "重複したバリアント値",
- "variantPropertyName": "プロパティ名",
"addVariantProperty": "バリアントプロパティを追加",
"addVariant": "バリアントを追加",
"duplicateVariant": "バリアントを複製",
"removeVariantProperty": "バリアントプロパティを削除",
- "moveVariantPropertyUp": "バリアントプロパティを上へ移動",
- "moveVariantPropertyDown": "バリアントプロパティを下へ移動",
- "moveVariantValueUp": "バリアント値を上へ移動",
- "moveVariantValueDown": "バリアント値を下へ移動",
- "noVariantProperties": "バリアントプロパティなし",
"variantConflictHelp": "各バリアントにはプロパティ値の一意の組み合わせが必要です",
"openDocumentation": "ドキュメントを開く",
"noLocalComponents": "ローカルコンポーネントはありません",
@@ -348,6 +342,13 @@
"documentation": "ドキュメント",
"openDocs": "ドキュメントを開く",
"properties": "プロパティ",
+ "componentPropertyVariant": "バリアント",
+ "variantsShareValues": "{count}個のバリアントが {values} を共有しています",
+ "selectVariants": "選択",
+ "removeVariantValue": "{value} を削除",
+ "moveVariantsTo": "{value} のバリアントの移動先",
+ "addVariantValue": "値を追加",
+ "variantValues": "値",
"componentPropertyText": "テキスト",
"componentPropertyBoolean": "ブール値",
"componentPropertySwap": "インスタンスの入れ替え",
diff --git a/packages/vue/src/i18n/locales/pl/panels.json b/packages/vue/src/i18n/locales/pl/panels.json
index 4514f2241..4073efd79 100644
--- a/packages/vue/src/i18n/locales/pl/panels.json
+++ b/packages/vue/src/i18n/locales/pl/panels.json
@@ -324,16 +324,10 @@
"preferLibrary": "Preferuj tę bibliotekę",
"assetVariantSummary": "{count} wariantów · {names}",
"duplicateVariantValues": "Zduplikowane wartości wariantu",
- "variantPropertyName": "Nazwa właściwości",
"addVariantProperty": "Dodaj właściwość wariantu",
"addVariant": "Dodaj wariant",
"duplicateVariant": "Duplikuj wariant",
"removeVariantProperty": "Usuń właściwość wariantu",
- "moveVariantPropertyUp": "Przesuń właściwość wariantu w górę",
- "moveVariantPropertyDown": "Przesuń właściwość wariantu w dół",
- "moveVariantValueUp": "Przesuń wartość wariantu w górę",
- "moveVariantValueDown": "Przesuń wartość wariantu w dół",
- "noVariantProperties": "Brak właściwości wariantu",
"variantConflictHelp": "Każdy wariant wymaga unikalnej kombinacji wartości właściwości",
"openDocumentation": "Otwórz dokumentację",
"noLocalComponents": "Brak lokalnych komponentów",
@@ -344,6 +338,13 @@
"documentation": "Dokumentacja",
"openDocs": "Otwórz dokumentację",
"properties": "Właściwości",
+ "componentPropertyVariant": "Wariant",
+ "variantsShareValues": "{count} wariantów ma {values}",
+ "selectVariants": "Zaznacz",
+ "removeVariantValue": "Usuń {value}",
+ "moveVariantsTo": "Przenieś warianty z {value} do",
+ "addVariantValue": "Dodaj wartość",
+ "variantValues": "Wartości",
"componentPropertyText": "Tekst",
"componentPropertyBoolean": "Wartość logiczna",
"componentPropertySwap": "Zamiana instancji",
diff --git a/packages/vue/src/i18n/locales/ru/panels.json b/packages/vue/src/i18n/locales/ru/panels.json
index 9055582e7..c6c4ce792 100644
--- a/packages/vue/src/i18n/locales/ru/panels.json
+++ b/packages/vue/src/i18n/locales/ru/panels.json
@@ -324,16 +324,10 @@
"preferLibrary": "Предпочитать эту библиотеку",
"assetVariantSummary": "{count} вариантов · {names}",
"duplicateVariantValues": "Повторяющиеся значения вариантов",
- "variantPropertyName": "Имя свойства",
"addVariantProperty": "Добавить свойство варианта",
"addVariant": "Добавить вариант",
"duplicateVariant": "Дублировать вариант",
"removeVariantProperty": "Удалить свойство варианта",
- "moveVariantPropertyUp": "Переместить свойство варианта вверх",
- "moveVariantPropertyDown": "Переместить свойство варианта вниз",
- "moveVariantValueUp": "Переместить значение варианта вверх",
- "moveVariantValueDown": "Переместить значение варианта вниз",
- "noVariantProperties": "Нет свойств варианта",
"variantConflictHelp": "Для каждого варианта требуется уникальная комбинация значений свойств.",
"openDocumentation": "Открыть документацию",
"noLocalComponents": "Нет локальных компонентов",
@@ -344,6 +338,13 @@
"documentation": "Документация",
"openDocs": "Открыть документацию",
"properties": "Свойства",
+ "componentPropertyVariant": "Вариант",
+ "variantsShareValues": "{count} варианта совпадают: {values}",
+ "selectVariants": "Выбрать",
+ "removeVariantValue": "Удалить {value}",
+ "moveVariantsTo": "Перенести варианты со значением {value} в",
+ "addVariantValue": "Добавить значение",
+ "variantValues": "Значения",
"componentPropertyText": "Текст",
"componentPropertyBoolean": "Логическое",
"componentPropertySwap": "Замена экземпляра",
diff --git a/packages/vue/src/i18n/locales/zh-cn/panels.json b/packages/vue/src/i18n/locales/zh-cn/panels.json
index 6ddcf7523..8108e90ce 100644
--- a/packages/vue/src/i18n/locales/zh-cn/panels.json
+++ b/packages/vue/src/i18n/locales/zh-cn/panels.json
@@ -312,16 +312,10 @@
"preferLibrary": "优先使用此库",
"assetVariantSummary": "{count} 个变体 · {names}",
"duplicateVariantValues": "重复的变体值",
- "variantPropertyName": "属性名称",
"addVariantProperty": "添加变体属性",
"addVariant": "添加变体",
"duplicateVariant": "复制变体",
"removeVariantProperty": "删除变体属性",
- "moveVariantPropertyUp": "向上移动变体属性",
- "moveVariantPropertyDown": "向下移动变体属性",
- "moveVariantValueUp": "上移变体值",
- "moveVariantValueDown": "下移变体值",
- "noVariantProperties": "无变体属性",
"variantConflictHelp": "每个变体都需要独特的属性值组合",
"openDocumentation": "打开文档",
"noLocalComponents": "没有本地组件",
@@ -332,6 +326,13 @@
"documentation": "文档",
"openDocs": "打开文档",
"properties": "属性",
+ "componentPropertyVariant": "变体",
+ "variantsShareValues": "{count} 个变体共用 {values}",
+ "selectVariants": "选择",
+ "removeVariantValue": "移除 {value}",
+ "moveVariantsTo": "将含 {value} 的变体移到",
+ "addVariantValue": "添加值",
+ "variantValues": "值",
"componentPropertyText": "文本",
"componentPropertyBoolean": "布尔值",
"componentPropertySwap": "实例切换",
diff --git a/packages/vue/src/i18n/messages/panels.ts b/packages/vue/src/i18n/messages/panels.ts
index 4b49c1141..55a4dcbfa 100644
--- a/packages/vue/src/i18n/messages/panels.ts
+++ b/packages/vue/src/i18n/messages/panels.ts
@@ -75,16 +75,10 @@ export const panelMessageDefaults = {
preferLibrary: 'Prefer this library',
assetVariantSummary: params('{count} variants · {names}'),
duplicateVariantValues: 'Duplicate variant values',
- variantPropertyName: 'Property name',
addVariantProperty: 'Add variant property',
addVariant: 'Add variant',
duplicateVariant: 'Duplicate variant',
removeVariantProperty: 'Remove variant property',
- moveVariantPropertyUp: 'Move variant property up',
- moveVariantPropertyDown: 'Move variant property down',
- moveVariantValueUp: 'Move variant value up',
- moveVariantValueDown: 'Move variant value down',
- noVariantProperties: 'No variant properties',
variantConflictHelp: 'Each variant needs a unique combination of property values',
openDocumentation: 'Open documentation',
noLocalComponents: 'No local components',
@@ -95,6 +89,13 @@ export const panelMessageDefaults = {
documentation: 'Documentation',
openDocs: 'Open docs',
properties: 'Properties',
+ componentPropertyVariant: 'Variant',
+ variantsShareValues: params('{count} variants share {values}'),
+ selectVariants: 'Select',
+ removeVariantValue: params('Remove {value}'),
+ moveVariantsTo: params('Move variants with {value} to'),
+ addVariantValue: 'Add value',
+ variantValues: 'Values',
componentPropertyText: 'Text',
componentPropertyBoolean: 'Boolean',
componentPropertySwap: 'Instance swap',
diff --git a/src/components/DesignPanel.vue b/src/components/DesignPanel.vue
index 4b40d6a40..7ca33e8a6 100644
--- a/src/components/DesignPanel.vue
+++ b/src/components/DesignPanel.vue
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { computed } from 'vue'
+import { getNodeEditCapability } from '@open-pencil/core/editor'
import { useI18n, useSelectionState, useEditorCommands } from '@open-pencil/vue'
import { useEditorStore } from '@/app/editor/active-store'
@@ -52,6 +53,10 @@ const isComponentType = computed(() => {
const type = node.value?.type
return type ? COMPONENT_TYPES.has(type) : false
})
+// A library's components are edited in the library, so Add variant has nothing to change here.
+const canAddVariant = computed(
+ () => !!node.value && getNodeEditCapability(store.graph, node.value.id).editable
+)
const selectedIcon = computed(() => (node.value ? nodeIcon(node.value) : undefined))
function openSelectedInstanceReview() {
const instance = node.value
@@ -130,6 +135,15 @@ const { panels } = useI18n()
<template v-else>{{ node.name }}</template>
</span>
<template #actions>
+ <IconButton
+ v-if="node.type === 'COMPONENT' || node.type === 'COMPONENT_SET'"
+ :label="panels.addVariant"
+ data-test-id="add-variant"
+ :disabled="!canAddVariant"
+ @click="store.addVariant(node.id)"
+ >
+ <icon-lucide-diamond-plus class="size-3.5" />
+ </IconButton>
<PropertyBindButton v-if="node.type === 'INSTANCE'" field="INSTANCE_SWAP" />
<InstanceUpdateAction
v-if="node.type === 'INSTANCE'"
diff --git a/src/components/properties/component-properties/ComponentPropertyListSection.vue b/src/components/properties/component-properties/ComponentPropertyListSection.vue
index 2e0daaf15..33b088ae3 100644
--- a/src/components/properties/component-properties/ComponentPropertyListSection.vue
+++ b/src/components/properties/component-properties/ComponentPropertyListSection.vue
@@ -21,15 +21,17 @@ 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 PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.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'
+import VariantValueList from './variant/VariantValueList.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 { context, definitions, rows, conflicts, componentSet, nestedInstances, editable } = authoring
const { panels, common } = useI18n()
const menu = useMenuUI({ content: 'min-w-44' })
const item = menuItem({ justify: 'start' })
@@ -52,8 +54,11 @@ const nestedStyles = usePopoverUI({
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)
+/** Rows the owner holds itself; a variant's own properties keep their place. */
+const ownRows = computed(() =>
+ rows.value.filter(
+ (row) => row.kind === 'variant' || row.property.ownerId === context.value?.owner.id
+ )
)
const exposed = computed(() => nestedInstances.value.filter((node) => node.exposed))
const NEW_PROPERTIES: { type: ComponentPropertyType; label: () => string }[] = [
@@ -63,14 +68,14 @@ const NEW_PROPERTIES: { type: ComponentPropertyType; label: () => string }[] = [
]
const reorder = useFlatReorderDrag({
- items: () => ownDefinitions.value,
+ items: () => ownRows.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
+ if (!ownRows.value.some((row) => row.id === propertyId)) return
reorder.setupItem(element instanceof HTMLElement ? element : null, () => ({ id: propertyId }))
}
@@ -137,6 +142,15 @@ function valueLabel(type: ComponentPropertyType, value: string) {
<PropertyTypeIcon :kind="option.type" />
{{ option.label() }}
</DropdownMenuItem>
+ <DropdownMenuItem
+ v-if="componentSet"
+ :class="item"
+ data-property-type="VARIANT"
+ @select="authoring.addVariantProperty()"
+ >
+ <PropertyTypeIcon kind="VARIANT" />
+ {{ panels.componentPropertyVariant }}
+ </DropdownMenuItem>
<template v-if="nestedInstances.length">
<DropdownMenuSeparator :class="menu.separator" />
<DropdownMenuItem
@@ -153,33 +167,85 @@ function valueLabel(type: ComponentPropertyType, value: string) {
</DropdownMenuRoot>
</template>
- <div v-if="definitions.length" class="-mx-1.5 flex flex-col">
+ <div
+ v-for="conflict in conflicts"
+ :key="conflict.label"
+ role="alert"
+ class="flex items-start gap-1.5 rounded bg-issue-warning/10 px-2 py-1.5 text-[11px] leading-4 text-issue-warning"
+ >
+ <icon-lucide-triangle-alert class="mt-0.5 size-3 shrink-0" aria-hidden="true" />
+ <span class="min-w-0 flex-1">
+ {{
+ panels.variantsShareValues({
+ count: conflict.componentIds.length,
+ values: conflict.label
+ })
+ }}
+ </span>
+ <button
+ type="button"
+ class="shrink-0 underline-offset-2 hover:underline"
+ @click="authoring.selectNodes(conflict.componentIds)"
+ >
+ {{ panels.selectVariants }}
+ </button>
+ </div>
+
+ <div v-if="rows.length" class="-mx-1.5 flex flex-col">
<div
- v-for="definition in definitions"
- :key="definition.id"
- :ref="(element) => setupRow(element, definition.id)"
+ v-for="row in rows"
+ :key="row.id"
+ :ref="(element) => setupRow(element, row.id)"
class="relative data-[dragging]:opacity-50"
- :data-dragging="reorder.draggingId.value === definition.id || undefined"
+ :data-dragging="reorder.draggingId.value === row.id || undefined"
>
<div
- v-if="dropPosition(definition.id)"
+ v-if="dropPosition(row.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'"
+ :class="dropPosition(row.id) === 'before' ? 'top-0' : 'bottom-0'"
/>
<PropertyRow
- :name="definition.name"
- :kind="definition.type"
- :value="definition.defaultValue"
- :value-label="valueLabel(definition.type, definition.defaultValue)"
+ v-if="row.kind === 'variant'"
+ :name="row.variant.name"
+ kind="VARIANT"
+ :value="row.variant.values[0] ?? ''"
+ :value-label="row.variant.values.join(', ')"
+ :disabled="!editable"
+ @rename="authoring.renameVariantProperty(row.id, $event)"
+ @remove="authoring.removeVariantProperty(row.id)"
+ >
+ <PanelFieldGroup :label="panels.variantValues">
+ <VariantValueList
+ :name="row.variant.name"
+ :values="row.variant.values"
+ :used="row.variant.used"
+ :disabled="!editable"
+ :rename="
+ (previous, value) => authoring.renameVariantValue(row.id, previous, value)
+ "
+ :reorder="(values) => authoring.reorderVariantValues(row.id, values)"
+ :add="(value) => authoring.addVariantValue(row.id, value)"
+ :remove="
+ (value, replacement) => authoring.removeVariantValue(row.id, value, replacement)
+ "
+ />
+ </PanelFieldGroup>
+ </PropertyRow>
+ <PropertyRow
+ v-else
+ :name="row.property.name"
+ :kind="row.property.type"
+ :value="row.property.defaultValue"
+ :value-label="valueLabel(row.property.type, row.property.defaultValue)"
:options="
- definition.type === 'INSTANCE_SWAP' ? authoring.swapOptions(definition.id) : []
+ row.property.type === 'INSTANCE_SWAP' ? authoring.swapOptions(row.property.id) : []
"
- :groups="definition.bindingGroups"
+ :groups="row.property.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)"
+ @rename="authoring.rename(row.property.ownerId, row.property.id, $event)"
+ @update="authoring.setDefault(row.property.ownerId, row.property.id, $event)"
+ @remove="authoring.remove(row.property.ownerId, row.property.id)"
@select="authoring.select"
@unbind="
(binding) =>
diff --git a/src/components/properties/component-properties/PropertyBindButton.vue b/src/components/properties/component-properties/PropertyBindButton.vue
index 35b20990d..6cce01727 100644
--- a/src/components/properties/component-properties/PropertyBindButton.vue
+++ b/src/components/properties/component-properties/PropertyBindButton.vue
@@ -33,7 +33,7 @@ const item = menuItem({ justify: 'start' })
:disabled="!binding.editable.value"
:data-property-bind="field"
>
- <icon-lucide-diamond-plus class="size-3.5" />
+ <icon-lucide-link class="size-3.5" />
</IconButton>
</DropdownMenuTrigger>
<DropdownMenuPortal>
diff --git a/src/components/properties/component-properties/PropertyRow.vue b/src/components/properties/component-properties/PropertyRow.vue
index 901495c2e..95ea69676 100644
--- a/src/components/properties/component-properties/PropertyRow.vue
+++ b/src/components/properties/component-properties/PropertyRow.vue
@@ -36,6 +36,7 @@ const {
totalVariants?: number
disabled?: boolean
}>()
+defineSlots<{ default?(): unknown }>()
const emit = defineEmits<{
rename: [name: string]
update: [value: string]
@@ -112,18 +113,21 @@ const shownValue = computed(() => {
@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>
+ <!-- A variant property edits its values here instead of a default. -->
+ <slot>
+ <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>
+ </slot>
<PanelFieldGroup v-if="groups.length" :label="panels.layers">
<div class="flex flex-col gap-0.5">
<PropertyBindings
diff --git a/src/components/properties/component-properties/PropertyTypeIcon.vue b/src/components/properties/component-properties/PropertyTypeIcon.vue
index 5499394dc..70ab1e154 100644
--- a/src/components/properties/component-properties/PropertyTypeIcon.vue
+++ b/src/components/properties/component-properties/PropertyTypeIcon.vue
@@ -8,6 +8,11 @@ const { kind } = defineProps<{ kind: ComponentPropertyType }>()
class="size-3.5 shrink-0 text-muted"
aria-hidden="true"
/>
+ <icon-lucide-diamond
+ v-else-if="kind === 'VARIANT'"
+ 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"
diff --git a/src/components/properties/component-properties/variant/VariantAuthoringSection.vue b/src/components/properties/component-properties/variant/VariantAuthoringSection.vue
index a51605e0d..ab9184f47 100644
--- a/src/components/properties/component-properties/variant/VariantAuthoringSection.vue
+++ b/src/components/properties/component-properties/variant/VariantAuthoringSection.vue
@@ -1,65 +1,35 @@
<script setup lang="ts">
-import { computed, nextTick, reactive, ref, watch } from 'vue'
+import { computed, reactive, ref, watch } from 'vue'
import { useI18n, useVariantAuthoring } from '@open-pencil/vue'
-import AppButton from '@/components/ui/button/AppButton.vue'
-import IconButton from '@/components/ui/button/IconButton.vue'
import AppInput from '@/components/ui/input/AppInput.vue'
import PanelFieldGroup from '@/components/ui/panel/PanelFieldGroup.vue'
import PanelSection from '@/components/ui/panel/PanelSection.vue'
-const {
- active,
- variant,
- definitions,
- diagnostics,
- addProperty,
- renameProperty,
- removeProperty,
- reorderProperties,
- renameValue,
- reorderValues,
- setVariantValue,
- addVariant,
- duplicateVariant
-} = useVariantAuthoring()
+/**
+ * The selected variant's own values. The set's variant properties and their values are edited
+ * in the Properties list, and Add variant sits in the panel header.
+ */
+const { variant, definitions, diagnostics, setVariantValue } = useVariantAuthoring()
const { panels } = useI18n()
-const propertyNames = reactive<Record<string, string>>({})
-const propertyValues = reactive<Record<string, string>>({})
const selectedValues = reactive<Record<string, string>>({})
const mutationConflictIds = ref<string[]>([])
-const conflictIds = computed(
- () =>
- new Set([
- ...diagnostics.value.flatMap((diagnostic) => diagnostic.componentIds),
- ...mutationConflictIds.value
- ])
-)
const selectedHasConflict = computed(() => {
const variantId = variant.value?.id
- return variantId ? conflictIds.value.has(variantId) : false
+ if (!variantId) return false
+ return (
+ mutationConflictIds.value.includes(variantId) ||
+ diagnostics.value.some((diagnostic) => diagnostic.componentIds.includes(variantId))
+ )
})
watch(
- definitions,
- (items) => {
+ [definitions, variant],
+ ([items, selected]) => {
for (const definition of items) {
- propertyNames[definition.id] = definition.name
- for (const value of definition.values) propertyValues[`${definition.id}:${value}`] = value
- selectedValues[definition.id] =
- variant.value?.componentPropertyValues[definition.name] ?? definition.values[0] ?? ''
- }
- },
- { immediate: true }
-)
-watch(
- variant,
- (selected) => {
- if (!selected) return
- for (const definition of definitions.value) {
selectedValues[definition.id] =
- selected.componentPropertyValues[definition.name] ?? definition.values[0] ?? ''
+ selected?.componentPropertyValues[definition.name] ?? definition.values[0] ?? ''
}
},
{ immediate: true }
@@ -70,46 +40,6 @@ function blurInput(event: KeyboardEvent) {
if (target instanceof HTMLInputElement) target.blur()
}
-function commitPropertyName(propertyId: string) {
- const name = propertyNames[propertyId]?.trim()
- const definition = definitions.value.find((item) => item.id === propertyId)
- if (!name || !definition || !renameProperty(propertyId, name)) {
- if (definition) propertyNames[propertyId] = definition.name
- }
-}
-
-function moveProperty(propertyId: string, offset: -1 | 1) {
- const ids = definitions.value.map((definition) => definition.id)
- const index = ids.indexOf(propertyId)
- const destination = index + offset
- if (index === -1 || destination < 0 || destination >= ids.length) return
- const [moved] = ids.splice(index, 1)
- if (!moved) return
- ids.splice(destination, 0, moved)
- reorderProperties(ids)
-}
-
-function moveValue(propertyId: string, value: string, offset: -1 | 1) {
- const definition = definitions.value.find((item) => item.id === propertyId)
- if (!definition) return
- const values = [...definition.values]
- const index = values.indexOf(value)
- const destination = index + offset
- if (index === -1 || destination < 0 || destination >= values.length) return
- const [moved] = values.splice(index, 1)
- if (!moved) return
- values.splice(destination, 0, moved)
- reorderValues(propertyId, values)
-}
-
-function commitPropertyValue(propertyId: string, previousValue: string) {
- const key = `${propertyId}:${previousValue}`
- const value = propertyValues[key]?.trim()
- if (!value || !renameValue(propertyId, previousValue, value)) {
- propertyValues[key] = previousValue
- }
-}
-
function commitSelectedValue(propertyId: string) {
const value = selectedValues[propertyId]?.trim()
const definition = definitions.value.find((item) => item.id === propertyId)
@@ -120,36 +50,11 @@ function commitSelectedValue(propertyId: string) {
selectedValues[propertyId] = variant.value?.componentPropertyValues[definition.name] ?? ''
}
}
-
-/** Add Property N and put the cursor in its name, so typing renames it right away. */
-async function createProperty() {
- const id = addProperty()
- if (!id) return
- await nextTick()
- nameInputs.get(id)?.select()
-}
-
-/** Name fields of the listed properties, so a new one can be selected for typing. */
-type SelectableInput = { select(): void }
-const nameInputs = new Map<string, SelectableInput>()
-function nameInputRef(id: string, input: SelectableInput | null) {
- if (input) nameInputs.set(id, input)
- else nameInputs.delete(id)
-}
</script>
<template>
- <PanelSection v-if="active" :label="panels.variants" :empty="definitions.length === 0">
- <template #actions>
- <IconButton
- :label="variant ? panels.duplicateVariant : panels.addVariantProperty"
- @click="variant ? duplicateVariant() : createProperty()"
- >
- <icon-lucide-plus class="size-3.5" />
- </IconButton>
- </template>
-
- <div v-if="variant" class="flex flex-col gap-1.5">
+ <PanelSection v-if="variant && definitions.length" :label="panels.variants">
+ <div class="flex flex-col gap-1.5">
<PanelFieldGroup
v-for="definition in definitions"
:key="definition.id"
@@ -174,91 +79,5 @@ function nameInputRef(id: string, input: SelectableInput | null) {
{{ panels.duplicateVariantValues }}. {{ panels.variantConflictHelp }}.
</p>
</div>
-
- <div v-else-if="definitions.length" class="flex flex-col gap-2">
- <div
- v-for="definition in definitions"
- :key="definition.id"
- class="flex flex-col gap-1.5 rounded border border-border p-1.5"
- :data-property="definition.id"
- >
- <div class="flex items-center gap-1">
- <AppInput
- :ref="(input) => nameInputRef(definition.id, input as SelectableInput | null)"
- v-model="propertyNames[definition.id]"
- size="sm"
- tone="panel"
- :aria-label="panels.variantPropertyName"
- @change="commitPropertyName(definition.id)"
- @enter="blurInput"
- />
- <IconButton
- :label="panels.moveVariantPropertyUp"
- :disabled="definitions[0]?.id === definition.id"
- @click="moveProperty(definition.id, -1)"
- >
- <icon-lucide-chevron-up class="size-3.5" />
- </IconButton>
- <IconButton
- :label="panels.moveVariantPropertyDown"
- :disabled="definitions.at(-1)?.id === definition.id"
- @click="moveProperty(definition.id, 1)"
- >
- <icon-lucide-chevron-down class="size-3.5" />
- </IconButton>
- <IconButton :label="panels.removeVariantProperty" @click="removeProperty(definition.id)">
- <icon-lucide-minus class="size-3.5" />
- </IconButton>
- </div>
- <div
- v-for="(value, valueIndex) in definition.values"
- :key="value"
- class="flex items-center gap-1"
- >
- <AppInput
- v-model="propertyValues[`${definition.id}:${value}`]"
- size="sm"
- tone="panel"
- :aria-label="`${definition.name}: ${value}`"
- @change="commitPropertyValue(definition.id, value)"
- @enter="blurInput"
- />
- <IconButton
- :label="panels.moveVariantValueUp"
- :disabled="valueIndex === 0"
- @click="moveValue(definition.id, value, -1)"
- >
- <icon-lucide-chevron-up class="size-3.5" />
- </IconButton>
- <IconButton
- :label="panels.moveVariantValueDown"
- :disabled="valueIndex === definition.values.length - 1"
- @click="moveValue(definition.id, value, 1)"
- >
- <icon-lucide-chevron-down class="size-3.5" />
- </IconButton>
- </div>
- </div>
- <p
- v-if="diagnostics.length"
- role="alert"
- class="rounded bg-danger/10 px-2 py-1.5 text-[10px] leading-4 text-danger"
- >
- {{ panels.duplicateVariantValues }}. {{ panels.variantConflictHelp }}.
- </p>
- </div>
-
- <p v-else class="py-1 text-[10px] text-muted">{{ panels.noVariantProperties }}</p>
-
- <AppButton
- v-if="!variant"
- size="xs"
- variant="soft"
- class="mt-2 self-start"
- @click="addVariant()"
- >
- <icon-lucide-plus class="size-3.5" />
- {{ panels.addVariant }}
- </AppButton>
</PanelSection>
</template>
diff --git a/src/components/properties/component-properties/variant/VariantValueList.vue b/src/components/properties/component-properties/variant/VariantValueList.vue
new file mode 100644
index 000000000..157d51326
--- /dev/null
+++ b/src/components/properties/component-properties/variant/VariantValueList.vue
@@ -0,0 +1,156 @@
+<script setup lang="ts">
+import { omit } from 'es-toolkit'
+import { ref, type ComponentPublicInstance } from 'vue'
+
+import type { VariantMutationResult } from '@open-pencil/core/editor'
+import { useFlatReorderDrag, useI18n } from '@open-pencil/vue'
+
+import IconButton from '@/components/ui/button/IconButton.vue'
+import AppInput from '@/components/ui/input/AppInput.vue'
+import AppSelect from '@/components/ui/select/AppSelect.vue'
+
+/**
+ * A variant property's values: rename in place, drag to reorder, add one, or remove one. A value
+ * variants still use is removed by moving them to another value first.
+ */
+const {
+ name,
+ values,
+ used,
+ disabled = false,
+ rename,
+ reorder,
+ add,
+ remove
+} = defineProps<{
+ name: string
+ values: string[]
+ used: string[]
+ disabled?: boolean
+ rename: (previous: string, value: string) => boolean | undefined
+ reorder: (values: string[]) => boolean | undefined
+ add: (value: string) => boolean | undefined
+ remove: (value: string, replacement?: string) => VariantMutationResult | undefined
+}>()
+const { panels } = useI18n()
+const drafts = ref<Record<string, string>>({})
+const newValue = ref('')
+const replacing = ref<string | null>(null)
+const conflict = ref(false)
+
+const drag = useFlatReorderDrag({
+ items: () => values.map((value) => ({ id: value })),
+ onMove: (value, index) => {
+ const next = values.filter((item) => item !== value)
+ next.splice(index, 0, value)
+ reorder(next)
+ }
+})
+
+function setupRow(element: Element | ComponentPublicInstance | null, value: string) {
+ drag.setupItem(element instanceof HTMLElement ? element : null, () => ({ id: value }))
+}
+
+function commitRename(value: string) {
+ const next = drafts.value[value]?.trim()
+ if (next && next !== value) rename(value, next)
+ // The row shows the stored value again, renamed or not.
+ drafts.value = omit(drafts.value, [value])
+}
+
+function commitAdd() {
+ if (newValue.value.trim() && add(newValue.value.trim())) newValue.value = ''
+}
+
+function startRemove(value: string) {
+ conflict.value = false
+ if (!used.includes(value)) {
+ remove(value)
+ return
+ }
+ replacing.value = value
+}
+
+function replace(value: string, replacement: string) {
+ const result = remove(value, replacement)
+ conflict.value = result?.kind === 'conflict'
+ if (result?.kind === 'changed') replacing.value = null
+}
+</script>
+
+<template>
+ <div class="flex flex-col gap-1" :data-variant-values="name">
+ <div
+ v-for="value in values"
+ :key="value"
+ :ref="(element) => setupRow(element, value)"
+ class="group/value relative flex flex-col gap-1"
+ :data-dragging="drag.draggingId.value === value || undefined"
+ >
+ <div
+ v-if="drag.instructionTargetId.value === value"
+ class="pointer-events-none absolute inset-x-1 z-10 h-0.5 rounded-full bg-accent"
+ :class="drag.instruction.value?.operation === 'reorder-before' ? '-top-0.5' : '-bottom-0.5'"
+ />
+ <div class="flex items-center gap-1">
+ <icon-lucide-grip-vertical
+ class="size-3.5 shrink-0 cursor-grab text-muted opacity-0 group-hover/value:opacity-100"
+ aria-hidden="true"
+ />
+ <AppInput
+ :model-value="drafts[value] ?? value"
+ size="sm"
+ tone="panel"
+ :aria-label="`${name}: ${value}`"
+ :disabled="disabled"
+ @update:model-value="drafts[value] = String($event)"
+ @change="commitRename(value)"
+ @enter="commitRename(value)"
+ />
+ <IconButton
+ :label="panels.removeVariantValue({ value })"
+ :disabled="disabled || values.length < 2"
+ @click="startRemove(value)"
+ >
+ <icon-lucide-minus class="size-3.5" />
+ </IconButton>
+ </div>
+ <div v-if="replacing === value" class="flex flex-col gap-1 pl-5">
+ <span class="text-[11px] text-muted">{{ panels.moveVariantsTo({ value }) }}</span>
+ <AppSelect
+ :label="panels.moveVariantsTo({ value })"
+ :model-value="''"
+ :options="
+ values.filter((item) => item !== value).map((item) => ({ value: item, label: item }))
+ "
+ @update:model-value="replace(value, $event)"
+ />
+ <span v-if="conflict" role="alert" class="text-[11px] text-issue-warning">
+ {{ panels.duplicateVariantValues }}
+ </span>
+ </div>
+ </div>
+ <div class="flex items-center gap-1">
+ <span class="size-3.5 shrink-0" aria-hidden="true" />
+ <AppInput
+ v-model="newValue"
+ size="sm"
+ tone="panel"
+ :placeholder="panels.addVariantValue"
+ :aria-label="panels.addVariantValue"
+ :disabled="disabled"
+ @enter="commitAdd"
+ @change="commitAdd"
+ />
+ <!-- Keeps the field as wide as the values above, whose rows end in a remove button. -->
+ <IconButton
+ :label="panels.addVariantValue"
+ class="invisible"
+ aria-hidden="true"
+ tabindex="-1"
+ >
+ <icon-lucide-minus class="size-3.5" />
+ </IconButton>
+ </div>
+ </div>
+</template>
diff --git a/tests/e2e/components/variant-authoring.spec.ts b/tests/e2e/components/variant-authoring.spec.ts
index 5716f7ba8..d26d5dcd4 100644
--- a/tests/e2e/components/variant-authoring.spec.ts
+++ b/tests/e2e/components/variant-authoring.spec.ts
@@ -1,6 +1,7 @@
-import { expect, test } from '@playwright/test'
+import { expect, test, type Page } from '@playwright/test'
import { CanvasHelper } from '#tests/helpers/canvas'
+import { selectNode } from '#tests/helpers/components/properties'
import { propertySection } from '#tests/helpers/properties'
test('authors multiple variant dimensions and reports duplicate combinations', async ({ page }) => {
@@ -55,25 +56,24 @@ test('authors multiple variant dimensions and reports duplicate combinations', a
})
await canvas.waitForRender()
- const section = propertySection(page, 'Variants')
- await expect(section).toBeVisible()
- const propertyRows = section.locator('[data-property]')
- await expect(propertyRows).toHaveCount(2)
- await propertyRows.nth(0).getByRole('textbox', { name: 'Property name' }).fill('Type')
- await propertyRows.nth(0).getByRole('textbox', { name: 'Property name' }).blur()
- await canvas.waitForRender()
- await propertyRows.nth(1).getByRole('textbox', { name: 'Property name' }).fill('Size')
- await propertyRows.nth(1).getByRole('textbox', { name: 'Property name' }).blur()
- await canvas.waitForRender()
+ // The set's variant properties are rows of the Properties list; each opens to rename it.
+ const properties = propertySection(page, 'Properties')
+ async function renameProperty(from: string, to: string) {
+ await properties.getByRole('button', { name: new RegExp(`^${from}`) }).click()
+ const name = page.getByRole('dialog', { name: from }).getByRole('textbox', { name: 'Name' })
+ await name.fill(to)
+ await name.press('Enter')
+ await page.keyboard.press('Escape')
+ await canvas.waitForRender()
+ }
+ await renameProperty('Variant', 'Type')
+ await renameProperty('Property 2', 'Size')
- // The header + adds Property 1 with the value Default and selects its name for typing.
- await section.getByRole('button', { name: 'Add variant property' }).click()
- const added = propertyRows.nth(2).getByRole('textbox', { name: 'Property name' })
- await expect(added).toHaveValue('Property 1')
- await expect(added).toBeFocused()
- await page.keyboard.type('State')
- await added.blur()
+ // The section's + adds a variant property named Property 1 with the value Default.
+ await properties.getByRole('button', { name: 'Create property…' }).click()
+ await page.getByRole('menuitem', { name: 'Variant', exact: true }).click()
await canvas.waitForRender()
+ await renameProperty('Property 1', 'State')
const definitions = await page.evaluate((componentSetId) => {
const store = window.openPencil?.getStore?.()
@@ -123,3 +123,62 @@ test('authors multiple variant dimensions and reports duplicate combinations', a
await expect(variantSection.getByRole('alert')).toHaveCount(0)
await expect(variantSection.getByRole('textbox', { name: 'Size' })).toHaveValue('Large')
})
+
+test('adds a variant to a standalone component the way Figma does', async ({ page }) => {
+ const canvas = new CanvasHelper(page)
+ await page.goto('/?test')
+ await canvas.waitForInit()
+ const chipId = await page.evaluate(() => {
+ const store = window.openPencil?.getStore?.()
+ if (!store) throw new Error('OpenPencil store not initialized')
+ const chip = store.graph.createNode('COMPONENT', store.state.currentPageId, {
+ name: 'Chip',
+ x: 40,
+ y: 40,
+ width: 80,
+ height: 32
+ })
+ return chip.id
+ })
+ await selectNode(page, chipId)
+ await canvas.waitForRender()
+
+ await page.getByRole('button', { name: 'Add variant' }).click()
+ await canvas.waitForRender()
+
+ const properties = propertySection(page, 'Properties')
+ await selectNode(page, await setOf(page, chipId))
+ await expect(properties.getByRole('button', { name: /^Property 1/ })).toContainText(
+ 'Default, Variant2'
+ )
+ expect(await variantNames(page, chipId)).toEqual(['Property 1=Default', 'Property 1=Variant2'])
+
+ // A value variants use moves them to another value first.
+ await properties.getByRole('button', { name: /^Property 1/ }).click()
+ const values = page.getByRole('dialog', { name: 'Property 1' })
+ await values.getByRole('textbox', { name: 'Add value' }).fill('Hover')
+ await values.getByRole('textbox', { name: 'Add value' }).press('Enter')
+ await values.getByRole('button', { name: 'Remove Variant2' }).click()
+ await values.getByRole('combobox', { name: /Move variants with Variant2/ }).click()
+ await page.getByRole('option', { name: 'Hover', exact: true }).click()
+ await expect
+ .poll(() => variantNames(page, chipId))
+ .toEqual(['Property 1=Default', 'Property 1=Hover'])
+})
+
+async function setOf(page: Page, componentId: string): Promise<string> {
+ const id = await page.evaluate(
+ (nodeId) => window.openPencil?.getStore?.()?.graph.getNode(nodeId)?.parentId,
+ componentId
+ )
+ if (!id) throw new Error('Expected a component set')
+ return id
+}
+
+function variantNames(page: Page, componentId: string) {
+ return page.evaluate((nodeId) => {
+ const graph = window.openPencil?.getStore?.()?.graph
+ const setId = graph?.getNode(nodeId)?.parentId
+ return setId ? (graph?.getChildren(setId).map((node) => node.name) ?? []) : []
+ }, componentId)
+}