AI-native design editor. Open-source Figma alternative.
feat(figma-api): sync instance swap feature with master
Danila Poyarkov419a8330c2ed
diff --git a/packages/core/src/figma-api/components.ts b/packages/core/src/figma-api/components.tsindex 73dde2475..6582b674a 100644--- a/packages/core/src/figma-api/components.ts+++ b/packages/core/src/figma-api/components.ts@@ -1,11 +1,81 @@-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import type { ComponentPropertyDefinition, SceneGraph, SceneNode } from '@open-pencil/scene-graph'import { computeAbsoluteBounds } from '@open-pencil/scene-graph/geometry'import { deriveSlashVariantProperties } from '@open-pencil/scene-graph/variant-properties'import { randomHex } from '#core/random'+import type { FigmaNodeProxy } from './proxy'+const COMPONENT_SET_PADDING = 40+export function exposeInstanceSwap(+ graph: SceneGraph,+ slots: ReadonlyArray<FigmaNodeProxy>,+ candidates: ReadonlyArray<FigmaNodeProxy>,+ propertyName = 'Instance'+): SceneNode {+ if (slots.length === 0) throw new Error('Provide at least one instance to expose')+ if (candidates.length === 0) throw new Error('Provide at least one candidate component')+ const name = propertyName.trim()+ if (!name) throw new Error('Property name must not be empty')+ const slotNodes = slots.map((slot) => graph.getNode(slot.id))+ if (new Set(slotNodes.map((node) => node?.id)).size !== slotNodes.length)+ throw new Error('exposeInstanceSwap requires distinct INSTANCE nodes')+ if (!slotNodes.every((node): node is SceneNode => node?.type === 'INSTANCE'))+ throw new Error('exposeInstanceSwap requires INSTANCE nodes')+ if (+ slotNodes.some((node) =>+ node.componentPropertyReferences.some((ref) => ref.field === 'INSTANCE_SWAP')+ )+ )+ throw new Error('Instance already has an INSTANCE_SWAP property')+ const candidateNodes = candidates.map((candidate) => graph.getNode(candidate.id))+ if (+ !candidateNodes.every(+ (node): node is SceneNode => node?.type === 'COMPONENT' || node?.type === 'COMPONENT_SET'+ )+ )+ throw new Error('Candidates must be COMPONENT or COMPONENT_SET nodes')+ const candidateIds = [...new Set(candidateNodes.map((node) => node.id))]+ if (candidateIds.length !== candidateNodes.length) throw new Error('Candidates must be distinct')+ const host = findPropertyHost(graph, slotNodes[0].parentId)+ if (!host) throw new Error('Instance must be nested inside a COMPONENT or COMPONENT_SET')+ if (host.componentPropertyDefinitions.some((definition) => definition.name === name))+ throw new Error(`A component property named "${name}" already exists`)+ if (!slotNodes.every((node) => findPropertyHost(graph, node.parentId)?.id === host.id))+ throw new Error('All instances must belong to the same component or component set')+ const definition: ComponentPropertyDefinition = {+ id: `prop:${randomHex(8)}`,+ name,+ type: 'INSTANCE_SWAP',+ defaultValue: slotNodes[0].componentId ?? candidateIds[0],+ preferredValues: candidateIds+ }+ graph.updateNode(host.id, {+ componentPropertyDefinitions: [...host.componentPropertyDefinitions, definition]+ })+ for (const node of slotNodes) {+ graph.updateNode(node.id, {+ componentPropertyReferences: [+ ...node.componentPropertyReferences,+ { propertyId: definition.id, field: 'INSTANCE_SWAP' }+ ]+ })+ }+ return host+}++function findPropertyHost(graph: SceneGraph, nodeId: string | null): SceneNode | null {+ let current = nodeId ? graph.getNode(nodeId) : null+ let fallback: SceneNode | null = null+ while (current) {+ if (current.type === 'COMPONENT_SET') return current+ if (current.type === 'COMPONENT' && !fallback) fallback = current+ current = current.parentId ? graph.getNode(current.parentId) : null+ }+ return fallback+}+function requireDistinctComponents(graph: SceneGraph, nodeIds: ReadonlyArray<string>): SceneNode[] {if (nodeIds.length === 0) throw new Error('Need at least 1 component to combine as variants')if (new Set(nodeIds).size !== nodeIds.length) {diff --git a/packages/core/src/figma-api/index.ts b/packages/core/src/figma-api/index.tsindex c4e665584..9b6fb2d42 100644--- a/packages/core/src/figma-api/index.ts+++ b/packages/core/src/figma-api/index.ts@@ -1,5 +1,4 @@import type {- ComponentPropertyDefinition,SceneGraph,SceneNode as CoreSceneNode,NodeType,@@ -19,12 +18,13 @@ import { canMakeBooleanSourceNode } from '#core/canvas/boolean'import { flattenNodesToVectorProps } from '#core/canvas/flatten'import { IS_BROWSER } from '#core/constants'import type { RasterExportFormat } from '#core/io/formats/raster'-import { randomHex } from '#core/random'import { documentFontStatus, type DocumentFontStatus } from '#core/text/font/status'+import { combineComponentsAsVariants, exposeInstanceSwap } from './components'import type {FigmaBooleanOperationNode,FigmaComponentNode,+ FigmaComponentSetNode,FigmaEllipseNode,FigmaFrameNode,FigmaGroupNode,@@ -51,6 +51,7 @@ export { FigmaNodeProxy } from './proxy'export type {FigmaBooleanOperationNode,FigmaComponentNode,+ FigmaComponentSetNode,FigmaEllipseNode,FigmaFrameNode,FigmaGroupNode,@@ -267,74 +268,39 @@ export class FigmaAPI implements NodeProxyHost {return this.wrapNode(comp.id)}- private _findPropertyHost(nodeId: string | null): CoreSceneNode | null {- let current = nodeId ? this.graph.getNode(nodeId) : null- let fallbackComponent: CoreSceneNode | null = null- while (current) {- if (current.type === 'COMPONENT_SET') return current- if (current.type === 'COMPONENT' && !fallbackComponent) fallbackComponent = current- current = current.parentId ? this.graph.getNode(current.parentId) : null- }- return fallbackComponent+ combineAsVariants(+ nodes: ReadonlyArray<FigmaComponentNode>,+ parent: FigmaNodeProxy,+ index?: number+ ): FigmaComponentSetNode+ combineAsVariants(+ nodes: ReadonlyArray<ComponentNode>,+ parent: BaseNode & ChildrenMixin,+ index?: number+ ): ComponentSetNode+ combineAsVariants(+ nodes: ReadonlyArray<ComponentNode | FigmaComponentNode>,+ parent: (BaseNode & ChildrenMixin) | FigmaNodeProxy,+ index?: number+ ): FigmaComponentSetNode {+ const componentSet = combineComponentsAsVariants(+ this.graph,+ nodes.map((node) => this._nodeId(node)),+ this._nodeId(parent),+ index+ )+ return this.wrapNode(componentSet.id) as FigmaComponentSetNode}- /**- * Exposes one or more nested instances as an instance-swap slot: the- * enclosing component (or component set) gets an INSTANCE_SWAP property- * offering `candidates`, and each slot instance is tagged to respond to it- * — mirrors Figma's "Create component property > Instance swap".- */exposeInstanceSwap(slots: ReadonlyArray<FigmaNodeProxy>,candidates: ReadonlyArray<FigmaNodeProxy>,propertyName = 'Instance'): FigmaNodeProxy {- if (slots.length === 0) throw new Error('Provide at least one instance to expose')- if (candidates.length === 0) throw new Error('Provide at least one candidate component')-- const slotNodes = slots.map((s) => this.graph.getNode(s[INTERNAL_ID]))- if (!slotNodes.every((n): n is CoreSceneNode => n?.type === 'INSTANCE')) {- throw new Error('exposeInstanceSwap requires INSTANCE nodes')- }-- const candidateNodes = candidates.map((c) => this.graph.getNode(c[INTERNAL_ID]))- if (!candidateNodes.every((n): n is CoreSceneNode => n?.type === 'COMPONENT')) {- throw new Error('Candidates must be COMPONENT nodes')- }- const candidateIds = candidateNodes.map((n) => n.id)-- const host = this._findPropertyHost(slotNodes[0].parentId)- if (!host) throw new Error('Instance must be nested inside a COMPONENT or COMPONENT_SET')- const sameHost = slotNodes.every((n) => this._findPropertyHost(n.parentId)?.id === host.id)- if (!sameHost) throw new Error('All instances must belong to the same component or component set')-- const propId = `prop:${randomHex(8)}`- const propDef: ComponentPropertyDefinition = {- id: propId,- name: propertyName,- type: 'INSTANCE_SWAP',- defaultValue: slotNodes[0].componentId ?? candidateIds[0],- preferredValues: candidateIds- }-- this.graph.updateNode(host.id, {- componentPropertyDefinitions: [...host.componentPropertyDefinitions, propDef]- })-- for (const node of slotNodes) {- this.graph.updateNode(node.id, {- componentPropertyReferences: [- ...node.componentPropertyReferences.filter((r) => r.field !== 'INSTANCE_SWAP'),- { propertyId: propId, field: 'INSTANCE_SWAP' }- ]- })- }-+ const host = exposeInstanceSwap(this.graph, slots, candidates, propertyName)return this.wrapNode(host.id)}- // --- Variables ----getVariableById(id: string): Variable | null {return this.graph.variables.get(id) ?? null}diff --git a/packages/core/src/tools/create.ts b/packages/core/src/tools/create.tsindex a45c44c19..fad3783fd 100644--- a/packages/core/src/tools/create.ts+++ b/packages/core/src/tools/create.ts@@ -1,5 +1,10 @@export { createPage, createShape, createSlice } from './create/basic'-export { createComponent, createInstance, exposeInstanceSwap } from './create/components'+export {+ combineAsVariants,+ createComponent,+ createInstance,+ exposeInstanceSwap+} from './create/components'export { fetchIconsTool, insertIcon, searchIconsTool } from './create/icons'export { render } from './create/render'export { importSVG } from './create/svg'diff --git a/packages/core/src/tools/create/components.ts b/packages/core/src/tools/create/components.tsindex e72738b7f..b6585a42a 100644--- a/packages/core/src/tools/create/components.ts+++ b/packages/core/src/tools/create/components.ts@@ -1,5 +1,5 @@-import type { FigmaNodeProxy } from '#core/figma-api'-import { defineTool, nodeSummary } from '#core/tools/schema'+import type { FigmaComponentNode, FigmaNodeProxy } from '#core/figma-api'+import { defineTool, nodeSummary, requireNodes } from '#core/tools/schema'export const createComponent = defineTool({name: 'create_component',@@ -35,36 +35,61 @@ export const createInstance = defineTool({}})+export const combineAsVariants = defineTool({+ name: 'combine_as_variants',+ mutates: true,+ description:+ 'Combine components sharing a parent into a component set (variant set). Components named ' ++ '"Category/Value" (e.g. "Button/Primary") derive variant properties from the name segments.',+ params: {+ ids: { type: 'string[]', description: 'Component node IDs to combine', required: true }+ },+ execute: (figma, { ids }) => {+ const nodes = requireNodes(figma, ids)+ if (!nodes) return { error: 'One or more node IDs were not found' }+ if (nodes.length < 2) return { error: 'Need at least 2 components to combine as variants' }+ if (!nodes.every((node): node is FigmaComponentNode => node.type === 'COMPONENT')) {+ return { error: 'combineAsVariants requires COMPONENT nodes' }+ }+ const parent = nodes[0].parent ?? figma.currentPage+ if (!nodes.every((node) => node.parent?.id === parent.id)) {+ return { error: 'combineAsVariants requires components to share a parent' }+ }+ try {+ const componentSet = figma.combineAsVariants(nodes, parent)+ return nodeSummary(componentSet)+ } catch (error) {+ return { error: error instanceof Error ? error.message : String(error) }+ }+ }+})+export const exposeInstanceSwap = defineTool({name: 'expose_instance_swap',mutates: true,- description:- 'Expose one or more nested instances as an instance-swap slot, so instances of the enclosing ' +- 'component can pick which component fills it (e.g. an icon slot on a button). All slot instances ' +- 'must live inside the same component or component set.',+ description: 'Expose nested instances as an instance-swap slot on their component.',params: {- instance_ids: {- type: 'string[]',- description: 'Instance node IDs to expose as the swap slot (one per variant that has this slot)',- required: true- },+ instance_ids: { type: 'string[]', description: 'Instance node IDs', required: true },candidate_ids: {type: 'string[]',- description: 'Component node IDs the designer can swap the slot to',+ description: 'Candidate component node IDs',required: true},- property_name: { type: 'string', description: 'Name for the property (default: "Instance")' }+ property_name: { type: 'string', description: 'Property name' }},execute: (figma, { instance_ids, candidate_ids, property_name }) => {- const slots = instance_ids.map((id) => figma.getNodeById(id)).filter((n): n is FigmaNodeProxy => n !== null)- if (slots.length !== instance_ids.length) return { error: 'One or more instance IDs were not found' }+ const slots = instance_ids+ .map((id) => figma.getNodeById(id))+ .filter((node): node is FigmaNodeProxy => node !== null)+ if (slots.length !== instance_ids.length)+ return { error: 'One or more instance IDs were not found' }const candidates = candidate_ids.map((id) => figma.getNodeById(id))- .filter((n): n is FigmaNodeProxy => n !== null)- if (candidates.length !== candidate_ids.length) return { error: 'One or more candidate IDs were not found' }+ .filter((node): node is FigmaNodeProxy => node !== null)+ if (candidates.length !== candidate_ids.length)+ return { error: 'One or more candidate IDs were not found' }try {- const host = figma.exposeInstanceSwap(slots, candidates, property_name)- return nodeSummary(host)+ return nodeSummary(figma.exposeInstanceSwap(slots, candidates, property_name))} catch (error) {return { error: error instanceof Error ? error.message : String(error) }}