Skip to content

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

fix: read and save component sets as Figma does (#1699)

Danila Poyarkovccafbb96004c
diff --git a/changes/1699/fixed.md b/changes/1699/fixed.md
new file mode 100644
index 000000000..6a6cf51ee
--- /dev/null
+++ b/changes/1699/fixed.md
@@ -0,0 +1,6 @@
+- Component sets from files that save no variant values, such as the shadcn/ui community kits, list their values in Figma's order and take their defaults from the default variant, so behaviours bind to them and scripts read them as Figma does (#1699).
+- Component sets made in OpenPencil open in Figma as component sets rather than frames of loose components, and sets whose variants were renamed or given new properties are saved without Figma reporting errors (#1699).
+- A variant property's default is the value of the set's top-left variant, as in Figma, whatever default the file records (#1699).
+- `appendChild` in scripts moves a layer that is already a child to the end, as Figma does (#1699).
+- Duplicating or cloning an instance from a `.fig` file that holds two instances of the same component, such as a button with left and right icons, no longer makes the document fail to save (#1699).
+- Duplicating a frame that holds a component and its instances gives instances of the duplicated component, as in Figma (#1699).
diff --git a/packages/core/src/editor/components/variants/model.ts b/packages/core/src/editor/components/variants/model.ts
index c6218d24f..3a2df339e 100644
--- a/packages/core/src/editor/components/variants/model.ts
+++ b/packages/core/src/editor/components/variants/model.ts
@@ -1,7 +1,9 @@
-import { uniq } from 'es-toolkit/array'
-
import type { ComponentPropertyDefinition, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-import { compareCanvasPosition, defaultVariant } from '@open-pencil/scene-graph/components'
+import {
+ compareCanvasPosition,
+ defaultVariant,
+ variantOptions
+} from '@open-pencil/scene-graph/components'
export type VariantConflict = {
values: Record<string, string>
@@ -88,12 +90,9 @@ export function collectVariantOptions(
/** Declared values stay available even before a component uses them. */
export function getVariantOptions(graph: SceneGraph, setId: string, propertyId: string): string[] {
+ const set = getComponentSet(graph, setId)
const definition = getVariantDefinitions(graph, setId).find((item) => item.id === propertyId)
- if (!definition) return []
- return uniq([
- ...(definition.variantOptions ?? []),
- ...(collectVariantOptions(graph, setId).get(definition.name) ?? [])
- ])
+ return set && definition ? variantOptions(graph, set, definition) : []
}
export function findVariantByValues(
diff --git a/packages/core/src/figma-api/accessors/component.ts b/packages/core/src/figma-api/accessors/component.ts
index dd319dd1f..17c1adbd3 100644
--- a/packages/core/src/figma-api/accessors/component.ts
+++ b/packages/core/src/figma-api/accessors/component.ts
@@ -1,9 +1,8 @@
import type { ComponentSetNode } from '@figma/plugin-typings/plugin-api-standalone'
-import { compact, uniq } from 'es-toolkit/array'
import * as v from 'valibot'
import type { SceneNode } from '@open-pencil/scene-graph'
-import { defaultVariant } from '@open-pencil/scene-graph/components'
+import { defaultVariant, variantOptions } from '@open-pencil/scene-graph/components'
import {
graph,
@@ -73,24 +72,12 @@ export function installComponentNodeAccessors(
variantGroupProperties: {
get(this: ProxyThis): ComponentSetNode['variantGroupProperties'] {
const set = raw(this, internals)
- const variants = graph(this, internals)
- .getChildren(set.id)
- .filter((child) => child.type === 'COMPONENT')
return Object.fromEntries(
set.componentPropertyDefinitions
.filter((definition) => definition.type === 'VARIANT')
.map((definition) => [
definition.name,
- // A file may leave the options out; the variants still hold their values.
- {
- values: definition.variantOptions
- ? [...definition.variantOptions]
- : uniq(
- compact(
- variants.map((variant) => variant.componentPropertyValues[definition.name])
- )
- )
- }
+ { values: variantOptions(graph(this, internals), set, definition) }
])
)
}
diff --git a/packages/core/src/figma-api/components.ts b/packages/core/src/figma-api/components.ts
index cb894b5e1..95240bc6e 100644
--- a/packages/core/src/figma-api/components.ts
+++ b/packages/core/src/figma-api/components.ts
@@ -14,7 +14,8 @@ import {
createComponentPropertyId,
exposedInstances,
instanceExposureIssue,
- resolveComponentPropertyValue
+ resolveComponentPropertyValue,
+ resolvedVariantDefinition
} from '@open-pencil/scene-graph/components'
import { cloneNodeProps } from '@open-pencil/scene-graph/copy'
@@ -167,8 +168,15 @@ function definitions(
): Record<string, FigmaComponentPropertyDefinition> {
const node = raw(target, internals)
if (node.type !== 'COMPONENT' && node.type !== 'COMPONENT_SET') return {}
+ const scene = graph(target, internals)
+ const resolved =
+ node.type === 'COMPONENT_SET'
+ ? node.componentPropertyDefinitions.map((item) =>
+ resolvedVariantDefinition(scene, node, item)
+ )
+ : node.componentPropertyDefinitions
return Object.fromEntries(
- node.componentPropertyDefinitions.map((definition) => [
+ resolved.map((definition) => [
propertyName(definition),
{
type: definition.type,
diff --git a/packages/core/src/figma-api/proxy.ts b/packages/core/src/figma-api/proxy.ts
index 0ad7ce8b8..32769b94a 100644
--- a/packages/core/src/figma-api/proxy.ts
+++ b/packages/core/src/figma-api/proxy.ts
@@ -236,6 +236,10 @@ export class FigmaNodeProxy extends FigmaNodeMembers {
)
prepareSlotMove(this[INTERNAL_GRAPH], this[INTERNAL_ID], child[INTERNAL_ID], 'appendChild')
this._reparentAndFit(child[INTERNAL_ID])
+ // A child already here moves to the end, as Figma does; reparenting leaves it in place.
+ const last = this._raw().childIds.length - 1
+ if (this._raw().childIds[last] !== child[INTERNAL_ID])
+ this[INTERNAL_GRAPH].insertChildAt(child[INTERNAL_ID], this[INTERNAL_ID], last)
}
/**
diff --git a/packages/core/src/io/formats/fig/export/setup.ts b/packages/core/src/io/formats/fig/export/setup.ts
index 8634444a0..7ed0b3f76 100644
--- a/packages/core/src/io/formats/fig/export/setup.ts
+++ b/packages/core/src/io/formats/fig/export/setup.ts
@@ -194,14 +194,26 @@ export function collectComponentPropertyIds(graph: SceneGraph): string[] {
return [...ids]
}
+/**
+ * Writing into an archive, a property keeps the GUID it was read with, however large: the
+ * records left as they were name it by that GUID. Otherwise a GUID past 31 bits, which Figma
+ * drops from a paste, is replaced.
+ */
function assignComponentPropertyGuids(
propertyIds: readonly string[],
localIdCounter: { value: number },
propertyIdToGuid: Map<string, GUID>,
assignedGuidValues: Set<string>,
- nodeSourceGuidValues: Set<string>
+ nodeSourceGuidValues: Set<string>,
+ intoArchive: boolean
): void {
for (const propertyId of propertyIds) {
+ const kept = intoArchive ? parseGuidOrNull(propertyId, { wholeParts: true }) : null
+ if (kept && !assignedGuidValues.has(propertyId) && !nodeSourceGuidValues.has(propertyId)) {
+ assignedGuidValues.add(propertyId)
+ propertyIdToGuid.set(propertyId, kept)
+ continue
+ }
const guid = assignVariableGuid(
propertyId,
localIdCounter,
@@ -477,7 +489,8 @@ export async function prepareFigExport(
localIdCounter,
propertyIdToGuid,
assignedGuidValues,
- nodeSourceGuidValues
+ nodeSourceGuidValues,
+ archived !== undefined
)
const pluginDataOverrides = renamedBehaviourPluginData(graph, propertyIdToGuid)
assignOwnLayerGuids(graph, sourceOwners, nodeIdToGuid, assignedGuidValues)
diff --git a/packages/core/tests/figma-api/components/members.test.ts b/packages/core/tests/figma-api/components/members.test.ts
index 582797984..b603cb808 100644
--- a/packages/core/tests/figma-api/components/members.test.ts
+++ b/packages/core/tests/figma-api/components/members.test.ts
@@ -38,21 +38,29 @@ describe('component and component set members', () => {
await expect(component.getInstancesAsync()).rejects.toThrow()
})
+ // The shadcn/ui community kit saves its sets' variant properties with neither values nor a
+ // default.
test('a set read from a file without its option lists gives its variants’ values', () => {
const figma = createAPI()
const small = figma.createComponent()
small.name = 'size=s'
const large = figma.createComponent()
large.name = 'size=l'
+ large.y = 200
const set = figma.combineAsVariants([small, large], figma.currentPage)
+ // Small stays the top-left, default variant while coming second in layer order.
+ set.insertChild(0, large)
const node = figma.graph.getNode(set.id)
if (!node) throw new Error('Expected the set')
figma.graph.updateNode(set.id, {
componentPropertyDefinitions: node.componentPropertyDefinitions.map(
- ({ variantOptions: _options, ...definition }) => definition
+ ({ variantOptions: _options, ...definition }) => ({ ...definition, defaultValue: '' })
)
})
- expect(set.variantGroupProperties).toEqual({ size: { values: ['s', 'l'] } })
+ expect(set.variantGroupProperties).toEqual({ size: { values: ['l', 's'] } })
+ expect(set.componentPropertyDefinitions).toEqual({
+ size: { type: 'VARIANT', defaultValue: 's', variantOptions: ['l', 's'] }
+ })
})
test('a set’s default variant, the first in reading order, and its variant values', () => {
diff --git a/packages/core/tests/figma-api/pending-layout.test.ts b/packages/core/tests/figma-api/pending-layout.test.ts
index a8b070de9..fd8518a46 100644
--- a/packages/core/tests/figma-api/pending-layout.test.ts
+++ b/packages/core/tests/figma-api/pending-layout.test.ts
@@ -37,6 +37,21 @@ describe('geometry reads after edits', () => {
expect(row.width).toBe(150)
})
+ // Measured in Figma desktop 126.
+ test('appending a child already there moves it to the end of the row', () => {
+ const api = createAPI()
+ const row = hugRow(api)
+ const first = api.createRectangle()
+ first.resize(40, 20)
+ row.appendChild(first)
+ const second = api.createRectangle()
+ second.resize(60, 30)
+ row.appendChild(second)
+ row.appendChild(first)
+ expect([second.x, first.x]).toEqual([0, 70])
+ expect([row.width, row.height]).toEqual([110, 30])
+ })
+
test('removing a child and changing spacing reflow the rest before the next read', () => {
const api = createAPI()
const row = hugRow(api)
diff --git a/packages/core/tests/figma-api/proxy/tree.test.ts b/packages/core/tests/figma-api/proxy/tree.test.ts
index 3c6977869..0012708eb 100644
--- a/packages/core/tests/figma-api/proxy/tree.test.ts
+++ b/packages/core/tests/figma-api/proxy/tree.test.ts
@@ -14,6 +14,18 @@ describe('tree operations', () => {
expect(expectDefined(child.parent, 'child parent').id).toBe(parent.id)
})
+ // Measured in Figma's plugin API (Figma desktop 126).
+ test('appendChild moves a child already there to the end', () => {
+ const api = createAPI()
+ const parent = api.createFrame()
+ const a = api.createRectangle()
+ const b = api.createRectangle()
+ parent.appendChild(a)
+ parent.appendChild(b)
+ parent.appendChild(a)
+ expect(parent.children.map((c) => c.id)).toEqual([b.id, a.id])
+ })
+
test('insertChild at index', () => {
const api = createAPI()
const parent = api.createFrame()
diff --git a/packages/core/tests/io/formats/fig/export/component-sets.test.ts b/packages/core/tests/io/formats/fig/export/component-sets.test.ts
new file mode 100644
index 000000000..71e886e0d
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/component-sets.test.ts
@@ -0,0 +1,199 @@
+import { describe, expect, setDefaultTimeout, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+import { deflateSync } from 'fflate'
+
+import {
+ FigmaAPI,
+ type FigmaComponentSetNode,
+} from '@open-pencil/core/figma-api'
+import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig'
+import { compressFigDataSync, parseFigBuffer } from '@open-pencil/fig'
+import type { GUID } from '@open-pencil/kiwi/fig'
+import {
+ getCompiledSchema,
+ getSchemaBytes,
+ initCodec,
+ type NodeChange
+} from '@open-pencil/kiwi/fig/codec'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+import { SceneGraph } from '@open-pencil/scene-graph'
+import { parseVariantName } from '@open-pencil/scene-graph/variant-name'
+
+import { releaseFigArchive } from '#core/kiwi/fig/session/archive/access'
+
+setDefaultTimeout(60_000)
+
+interface SavedDefinition {
+ id?: GUID
+ name?: string
+ type?: string
+ preferredValues?: unknown
+}
+
+interface SavedSpec {
+ propDefId?: GUID
+ value?: string
+}
+
+/** The Kiwi codec types these fields loosely; read the saved definitions and specs through here. */
+const definitionsOf = (record: NodeChange) => (record.componentPropDefs ?? []) as SavedDefinition[]
+const specsOf = (record: NodeChange) => (record.variantPropSpecs ?? []) as SavedSpec[]
+
+/** The GUID the shadcn/ui kit's Checkbox gives its Interaction property: past 31 bits. */
+const KIT_PROPERTY = { sessionID: 2583624281, localID: 1250876564 }
+
+/**
+ * A switch set saved as the shadcn/ui kit saves its sets: its variant property under a GUID
+ * Figma made past 31 bits, no preferred values, and the values' order saved apart.
+ */
+async function kitStyleArchive(): Promise<Uint8Array> {
+ await initCodec()
+ const source = new SceneGraph()
+ const figma = new FigmaAPI(source)
+ const off = figma.createComponent()
+ off.name = 'State=Off'
+ const on = figma.createComponent()
+ on.name = 'State=On'
+ on.x = 100
+ figma.combineAsVariants([off, on], figma.currentPage)
+ const parsed = parseFigBuffer((await exportFigFile(source)).slice().buffer as ArrayBuffer)
+ const set = setRecord(parsed.nodeChanges)
+ set.isStateGroup = true
+ const [definition] = definitionsOf(set)
+ const saved = guidToString(expectDefined(definition.id, 'definition id'))
+ definition.id = KIT_PROPERTY
+ delete definition.preferredValues
+ set.stateGroupPropertyValueOrders = [{ property: 'State', values: ['On', 'Off'] }]
+ for (const record of parsed.nodeChanges)
+ for (const spec of specsOf(record))
+ if (spec.propDefId && guidToString(spec.propDefId) === saved) spec.propDefId = KIT_PROPERTY
+ const kiwi = getCompiledSchema().encodeMessage({
+ type: 'NODE_CHANGES',
+ sessionID: 0,
+ ackID: 0,
+ nodeChanges: parsed.nodeChanges
+ })
+ return compressFigDataSync(
+ deflateSync(getSchemaBytes()),
+ kiwi,
+ expectDefined(parsed.thumbnailPNG, 'thumbnail'),
+ parsed.metaJSON ?? '{}',
+ []
+ )
+}
+
+/** The set's record: the one whose properties include a variant property. */
+function setRecord(records: NodeChange[]): NodeChange {
+ return expectDefined(
+ records.find((record) => definitionsOf(record).some((def) => def.type === 'VARIANT')),
+ 'set record'
+ )
+}
+
+const open = (bytes: Uint8Array) =>
+ parseFigFile(bytes.slice().buffer as ArrayBuffer, { populate: 'first-page' })
+
+/** Splits Invalid out as its own property and turns it on for one variant, as the kit adapts. */
+function addInvalid(graph: SceneGraph): void {
+ const figma = new FigmaAPI(graph)
+ const set = expectDefined(
+ figma.currentPage.findOne((node) => node.type === 'COMPONENT_SET') as FigmaComponentSetNode | null,
+ 'set'
+ )
+ set.addComponentProperty('Invalid', 'VARIANT', 'Off')
+ const on = expectDefined(
+ set.children.find((variant) => variant.name.startsWith('State=On')),
+ 'on variant'
+ )
+ on.name = 'State=On, Invalid=On'
+}
+
+/** Each variant's saved specs, by property name, and its name's values. */
+function savedVariants(bytes: Uint8Array) {
+ const records = parseFigBuffer(bytes.slice().buffer as ArrayBuffer).nodeChanges
+ const set = setRecord(records)
+ const names = new Map(
+ definitionsOf(set).map((definition) => [
+ guidToString(expectDefined(definition.id, 'definition id')),
+ definition.name
+ ])
+ )
+ const setGuid = guidToString(expectDefined(set.guid, 'set guid'))
+ const variants = records.filter(
+ (record: NodeChange) =>
+ record.parentIndex?.guid && guidToString(record.parentIndex.guid) === setGuid
+ )
+ return {
+ set,
+ variants: variants.map((record) => ({
+ name: parseVariantName(record.name ?? ''),
+ specs: Object.fromEntries(
+ specsOf(record).map((spec) => [
+ names.get(guidToString(expectDefined(spec.propDefId, 'spec property'))) ?? 'unknown',
+ spec.value
+ ])
+ )
+ }))
+ }
+}
+
+// Without the flag Figma (desktop 126) reads the set as a plain frame of loose components, and
+// an instance of one variant has no properties; it lists the values in the saved order.
+test('a set made in OpenPencil is written as a set Figma reads', async () => {
+ await initCodec()
+ const graph = new SceneGraph()
+ const figma = new FigmaAPI(graph)
+ const variants = ['State=Off', 'State=On'].map((name, index) => {
+ const component = figma.createComponent()
+ component.name = name
+ component.x = index * 100
+ return component
+ })
+ figma.combineAsVariants(variants, figma.currentPage)
+ const saved = await exportFigFile(graph)
+ const set = setRecord(parseFigBuffer(saved.slice().buffer as ArrayBuffer).nodeChanges)
+ expect(set.isStateGroup).toBe(true)
+ expect(set.stateGroupPropertyValueOrders).toEqual([{ property: 'State', values: ['Off', 'On'] }])
+})
+
+describe('saving variants edited in a set read from a .fig', () => {
+ test('writes each variant’s values under its set’s properties', async () => {
+ const bytes = await kitStyleArchive()
+ const patchedGraph = await open(bytes)
+ addInvalid(patchedGraph)
+ const patched = await exportFigFile(patchedGraph)
+ const fullGraph = await open(bytes)
+ addInvalid(fullGraph)
+ releaseFigArchive(fullGraph)
+ const full = await exportFigFile(fullGraph)
+
+ for (const saved of [patched, full]) {
+ const { set, variants } = savedVariants(saved)
+ // Every spec names one of the set's properties and agrees with the variant's name.
+ expect(variants.map((variant) => variant.specs)).toEqual(
+ variants.map((variant) => variant.name)
+ )
+ expect(variants.map((variant) => variant.name)).toEqual([
+ { State: 'Off', Invalid: 'Off' },
+ { State: 'On', Invalid: 'On' }
+ ])
+ // Figma lists a set's values in this order, and reads a frame without the flag as a plain
+ // frame (desktop 126): the order is written again for the properties the set has now.
+ expect(set.isStateGroup).toBe(true)
+ expect(set.stateGroupPropertyValueOrders).toEqual([
+ { property: 'State', values: ['On', 'Off'] },
+ { property: 'Invalid', values: ['Off', 'On'] }
+ ])
+ const reopened = await open(saved)
+ const values = [...reopened.nodes.values()]
+ .filter((node) => node.type === 'COMPONENT')
+ .map((node) => node.componentPropertyValues)
+ expect(values).toEqual(variants.map((variant) => variant.name))
+ }
+ // Written into the archive, the set keeps the property's GUID the untouched records use.
+ const { set } = savedVariants(patched)
+ const state = definitionsOf(set).find((definition) => definition.name === 'State')
+ expect(state?.id).toEqual(KIT_PROPERTY)
+ })
+})
diff --git a/packages/dom-css/src/export/components/model.ts b/packages/dom-css/src/export/components/model.ts
index 6c483407b..af026b936 100644
--- a/packages/dom-css/src/export/components/model.ts
+++ b/packages/dom-css/src/export/components/model.ts
@@ -4,7 +4,6 @@ import { allElements } from '#dom-css/behaviours/states/layers'
import { ownerVariants, restLayerOf, stateStyles } from '#dom-css/behaviours/states/model'
import { layerClassNames, propAttribute } from '#dom-css/behaviours/states/names'
import type { StateElement, StateStyles } from '#dom-css/behaviours/states/types'
-import { uniq } from 'es-toolkit/array'
import { camelCase } from 'es-toolkit/string'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
@@ -16,7 +15,6 @@ import {
textBinding,
type Behaviour
} from '@open-pencil/scene-graph/behaviours'
-import { variantDefaultValue } from '@open-pencil/scene-graph/components'
import { slotPropertyId } from '@open-pencil/scene-graph/slots'
import type { SceneGraphToDesignOptions } from '../projection'
@@ -321,14 +319,8 @@ function variantProps(
.map((definition) => ({
name: claimName(camelCase(identifierName(definition.name, 'Prop')), taken),
property: definition.name,
- // A document may record no options, which the variants' own values then are.
- options: uniq([
- ...(definition.variantOptions ?? []),
- ...ownerVariants(graph, set).map(
- (variant) => variant.componentPropertyValues[definition.name] ?? ''
- )
- ]).filter((option) => option !== ''),
- default: variantDefaultValue(graph, set, definition)
+ options: definition.variantOptions ?? [],
+ default: definition.defaultValue
}))
}
diff --git a/packages/dom-css/src/export/storybook/groups.ts b/packages/dom-css/src/export/storybook/groups.ts
index fa245541d..515b12f65 100644
--- a/packages/dom-css/src/export/storybook/groups.ts
+++ b/packages/dom-css/src/export/storybook/groups.ts
@@ -2,7 +2,7 @@ import { behaviourArgs } from '#dom-css/behaviours/args'
import { uniq } from 'es-toolkit/array'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
-import { restingVariant } from '@open-pencil/scene-graph/components'
+import { defaultVariant } from '@open-pencil/scene-graph/components'
import { deriveSlashVariantProperties } from '@open-pencil/scene-graph/variant-properties'
import type { StoryProp } from './module'
@@ -56,7 +56,7 @@ function componentSetGroup(
): StoryGroup {
const definitions = set.componentPropertyDefinitions.filter((def) => def.type === 'VARIANT')
// The variant at its default values opens the file as its Default story.
- const first = restingVariant(graph, set)
+ const first = defaultVariant(graph, set)
const components = graph
.getChildren(set.id)
.filter((child) => child.type === 'COMPONENT' && isExported(child))
diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.ts
index 33cf8acfa..47bf79156 100644
--- a/packages/fig/src/node-change/convert.ts
+++ b/packages/fig/src/node-change/convert.ts
@@ -914,12 +914,17 @@ function extractComponentPropertyDefs(nc: NodeChange): ComponentPropertyDefiniti
for (const def of defs) {
if (!def.id || !def.name) continue
const propType = COMPONENT_PROP_TYPE_MAP[def.type ?? ''] ?? 'VARIANT'
+ // A set saved without its values keeps their order apart, which Figma reads them in.
+ const valueOrder = nc.stateGroupPropertyValueOrders?.find(
+ (order) => order.property === def.name
+ )?.values
const definition: ComponentPropertyDefinition = {
id: guidToString(def.id),
name: def.name,
type: propType,
defaultValue: componentPropValueToString(def.initialValue),
- variantOptions: propType === 'VARIANT' ? def.preferredValues?.stringValues : undefined,
+ variantOptions:
+ propType === 'VARIANT' ? (def.preferredValues?.stringValues ?? valueOrder) : undefined,
preferredValues:
propType === 'INSTANCE_SWAP' || propType === 'SLOT'
? def.preferredValues?.instanceSwapValues
diff --git a/packages/fig/src/node-change/export/context.ts b/packages/fig/src/node-change/export/context.ts
index 2d5b68722..227627e8d 100644
--- a/packages/fig/src/node-change/export/context.ts
+++ b/packages/fig/src/node-change/export/context.ts
@@ -1,7 +1,7 @@
import { effectiveFigmaRawNodeFields } from '#fig/source-metadata'
import type { NodeChange, Paint, StyleReference } from '@open-pencil/kiwi/fig/codec'
-import { stringToGuid } from '@open-pencil/kiwi/fig/guid'
+import { isUnsetGuid, stringToGuid, UNSET_GUID } from '@open-pencil/kiwi/fig/guid'
import type {
ComponentPropertyDefinition,
PluginDataEntry,
@@ -149,14 +149,21 @@ export interface SceneNodeToKiwiContext {
) => KiwiNodeChange[]
}
-/** Figma reads both parts of a GUID as signed 32-bit integers and drops a paste beyond them. */
+/** Figma drops a pasted layer whose GUID part is past a signed 32-bit integer. */
const MAX_FIGMA_GUID_PART = 0x7fffffff
-/** The GUID an ID spells, or null when it spells none Figma can read. */
-export function parseGuidOrNull(value: string) {
+/**
+ * The GUID an ID spells, or null when it spells none Figma can read. A layer's GUID parts stay
+ * within signed 32 bits; `wholeParts` allows the full unsigned 32 bits Figma itself gives
+ * component properties, in files and on the clipboard alike (desktop 126). The unset GUID never
+ * names anything.
+ */
+export function parseGuidOrNull(value: string, { wholeParts = false } = {}) {
if (!/^\d+:\d+$/.test(value)) return null
const guid = stringToGuid(value)
- return guid.sessionID <= MAX_FIGMA_GUID_PART && guid.localID <= MAX_FIGMA_GUID_PART ? guid : null
+ if (isUnsetGuid(guid)) return null
+ const max = wholeParts ? UNSET_GUID.sessionID : MAX_FIGMA_GUID_PART
+ return guid.sessionID <= max && guid.localID <= max ? guid : null
}
export function resolveInstanceComponentId(
diff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.ts
index 85e926b25..492501fa7 100644
--- a/packages/fig/src/node-change/export/node.ts
+++ b/packages/fig/src/node-change/export/node.ts
@@ -9,8 +9,10 @@ import type {
ComponentPropertyReferenceField,
LayoutGrid,
SceneGraph,
- SceneNode
+ SceneNode,
+ VariantPropSpec
} from '@open-pencil/scene-graph'
+import { variantOptions } from '@open-pencil/scene-graph/components'
import {
DEFAULT_STROKE_MITER_LIMIT,
DEFAULT_STROKE_WEIGHT
@@ -605,6 +607,44 @@ function mergeParameterBindings(nc: KiwiNodeChange): void {
}
}
+/**
+ * What makes Figma read a frame as a component set (desktop 126 reads one without the flag as a
+ * plain frame of loose components), and the order it lists each variant property's values in,
+ * which it takes from here rather than from the properties' preferred values.
+ */
+function applyStateGroup(context: SceneNodeToKiwiContext, set: SceneNode, nc: KiwiNodeChange) {
+ nc.isStateGroup = true
+ const orders = set.componentPropertyDefinitions.flatMap((definition) =>
+ definition.type === 'VARIANT'
+ ? [{ property: definition.name, values: variantOptions(context.graph, set, definition) }]
+ : []
+ )
+ if (shouldSerializeRawBackedField(set, 'stateGroupPropertyValueOrders', orders.length > 0))
+ nc.stateGroupPropertyValueOrders = orders
+}
+
+/**
+ * A variant's values as Figma saves them, by its set's variant properties: the values the
+ * variant has now, which renaming it or its set's properties changes. Specs it was read with
+ * that still say the same are kept in their order, as Figma saved them.
+ */
+function variantSpecs(context: SceneNodeToKiwiContext, node: SceneNode): VariantPropSpec[] {
+ const set = node.parentId ? context.graph.getNode(node.parentId) : undefined
+ if (node.type !== 'COMPONENT' || set?.type !== 'COMPONENT_SET') return node.variantPropSpecs
+ const current = set.componentPropertyDefinitions.flatMap((definition) =>
+ definition.type === 'VARIANT' && Object.hasOwn(node.componentPropertyValues, definition.name)
+ ? [{ propDefId: definition.id, value: node.componentPropertyValues[definition.name] }]
+ : []
+ )
+ const stored = node.variantPropSpecs
+ const unchanged =
+ stored.length === current.length &&
+ current.every((spec) =>
+ stored.some((saved) => saved.propDefId === spec.propDefId && saved.value === spec.value)
+ )
+ return unchanged ? stored : current
+}
+
function applyParameterReferences(nc: KiwiNodeChange, refs: ExportedPropertyReference[]): void {
if (!refs.length) return
const existing = nc.parameterConsumptionMap as { entries?: ExportedParameterEntry[] } | undefined
@@ -709,7 +749,7 @@ function applyComponentMetadata(
nc.componentPropAssignments = componentPropAssignments
}
- const variantPropSpecs = node.variantPropSpecs.map((spec) => ({
+ const variantPropSpecs = variantSpecs(context, node).map((spec) => ({
propDefId: getOrCreatePropertyGuid(context, spec.propDefId, localIdCounter),
value: spec.value
}))
@@ -997,8 +1037,10 @@ export function sceneNodeToKiwiWithContext(
applyNodeVisualProps(context, node, nc)
applyComponentMetadata(context, node, nc, localIdCounter)
applyInstancePayload(context, node, nc, localIdCounter)
- if (node.type === 'COMPONENT_SET')
+ if (node.type === 'COMPONENT_SET') {
node.pluginData = withPluginData(node.pluginData, OPEN_PENCIL_PLUGIN_DATA.nodeType, node.type)
+ applyStateGroup(context, node, nc)
+ }
if (nc.type === 'CANVAS') nc.pageType = 'DESIGN'
if (node.type === 'BOOLEAN_OPERATION')
nc.booleanOperation = toKiwiBooleanOperation(node.booleanOperation)
diff --git a/packages/fig/src/source-metadata.ts b/packages/fig/src/source-metadata.ts
index 18c2e2390..afe170f14 100644
--- a/packages/fig/src/source-metadata.ts
+++ b/packages/fig/src/source-metadata.ts
@@ -97,9 +97,12 @@ const EDITED_RAW_FIELDS: Partial<Record<string, readonly string[]>> = {
isMask: ['mask'],
maskType: ['maskType'],
maskIsOutline: ['maskIsOutline'],
- componentPropertyDefinitions: ['componentPropDefs'],
+ // A set's saved value order lists the values its properties had; preferred values replace it.
+ componentPropertyDefinitions: ['componentPropDefs', 'stateGroupPropertyValueOrders'],
componentPropertyReferences: ['componentPropRefs'],
componentPropertyAssignments: ['componentPropAssignments'],
+ // A variant's specs are written from its values.
+ componentPropertyValues: ['variantPropSpecs'],
variantPropSpecs: ['variantPropSpecs']
}
diff --git a/packages/fig/tests/document/variant-values.test.ts b/packages/fig/tests/document/variant-values.test.ts
index 60734e0d0..dab04aca1 100644
--- a/packages/fig/tests/document/variant-values.test.ts
+++ b/packages/fig/tests/document/variant-values.test.ts
@@ -38,3 +38,31 @@ test('variant property values resolve through the component set definitions', ()
expect(variant?.componentPropertyValues).toEqual({ State: 'Disabled' })
expect(variant?.variantPropSpecs).toEqual([{ propDefId: '1:10', value: 'Disabled' }])
})
+
+// The shadcn/ui kit's Accordion item saves no values with its property, only their order, which
+// Figma (desktop 126) reports as variantOptions: Open before Closed, against the layer order.
+test('a variant property saved without values takes their saved order', () => {
+ const changes: NodeChange[] = [
+ { guid: guid(0), type: 'DOCUMENT' },
+ { guid: guid(1), type: 'CANVAS', parentIndex: { guid: guid(0), position: '!' } },
+ {
+ guid: guid(2),
+ type: 'FRAME',
+ isStateGroup: true,
+ name: 'AccordionItem',
+ parentIndex: { guid: guid(1), position: '!' },
+ componentPropDefs: [{ id: guid(10), name: 'Data State', type: 'VARIANT' }],
+ stateGroupPropertyValueOrders: [{ property: 'Data State', values: ['Open', 'Closed'] }]
+ },
+ ...['Closed', 'Open'].map((value, index): NodeChange => ({
+ guid: guid(3 + index),
+ type: 'SYMBOL',
+ name: `Data State=${value}`,
+ parentIndex: { guid: guid(2), position: String.fromCharCode(33 + index) },
+ variantPropSpecs: [{ propDefId: guid(10), value }]
+ }))
+ ]
+ const { graph, sources } = materializeDocument(changes)
+ const set = graph.getNode(sources.get('1:2') ?? '')
+ expect(set?.componentPropertyDefinitions[0]?.variantOptions).toEqual(['Open', 'Closed'])
+})
diff --git a/packages/fig/tests/node-change/export/guids.test.ts b/packages/fig/tests/node-change/export/guids.test.ts
new file mode 100644
index 000000000..f0c8a952e
--- /dev/null
+++ b/packages/fig/tests/node-change/export/guids.test.ts
@@ -0,0 +1,17 @@
+import { expect, test } from 'bun:test'
+
+import { parseGuidOrNull } from '#fig/node-change/export/context'
+
+// Figma (desktop 126) drops a pasted layer whose GUID part is past a signed 32-bit integer, and
+// gives component properties ids that use all 32 bits, such as the shadcn/ui kit's 2583624281:….
+test('a GUID part past 31 bits names a component property but not a layer', () => {
+ expect(parseGuidOrNull('12:34')).toEqual({ sessionID: 12, localID: 34 })
+ expect(parseGuidOrNull('2583624281:1250876564')).toBeNull()
+ expect(parseGuidOrNull('2583624281:1250876564', { wholeParts: true })).toEqual({
+ sessionID: 2583624281,
+ localID: 1250876564
+ })
+ // Past 32 bits, the unset GUID, and anything not spelled as one are never GUIDs.
+ for (const value of ['4294967296:1', '4294967295:4294967295', 'prop:abc', '1:2:3'])
+ expect([value, parseGuidOrNull(value, { wholeParts: true })]).toEqual([value, null])
+})
diff --git a/packages/scene-graph/src/behaviours/model.ts b/packages/scene-graph/src/behaviours/model.ts
index 4d2ef8cb0..650127d5e 100644
--- a/packages/scene-graph/src/behaviours/model.ts
+++ b/packages/scene-graph/src/behaviours/model.ts
@@ -1,5 +1,6 @@
import { mapValues } from 'es-toolkit'
+import { resolvedVariantDefinition } from '../components/variants'
import type { SceneGraph } from '../graph'
import { readPluginData, withPluginData } from '../plugin-data/field'
import { OPEN_PENCIL_PLUGIN_DATA } from '../plugin-data/fields'
@@ -85,17 +86,25 @@ export function withBehaviour(
return withPluginData(owner.pluginData, OPEN_PENCIL_PLUGIN_DATA.behaviour, behaviour ?? undefined)
}
-/** Component properties the behaviour can bind to: the owner's, and a set's variants' own. */
+/**
+ * Component properties the behaviour can bind to: the owner's, with a set's variant values and
+ * defaults read from its variants, and a set's variants' own.
+ */
export function behaviourProperties(
graph: SceneGraph,
owner: SceneNode
): ComponentPropertyDefinition[] {
- const variants =
- owner.type === 'COMPONENT_SET'
- ? owner.childIds.flatMap((id) => graph.getNode(id)?.componentPropertyDefinitions ?? [])
- : []
+ const isSet = owner.type === 'COMPONENT_SET'
+ const own = isSet
+ ? owner.componentPropertyDefinitions.map((definition) =>
+ resolvedVariantDefinition(graph, owner, definition)
+ )
+ : owner.componentPropertyDefinitions
+ const variants = isSet
+ ? owner.childIds.flatMap((id) => graph.getNode(id)?.componentPropertyDefinitions ?? [])
+ : []
const seen = new Set<string>()
- return [...owner.componentPropertyDefinitions, ...variants].filter((definition) => {
+ return [...own, ...variants].filter((definition) => {
if (seen.has(definition.id)) return false
seen.add(definition.id)
return true
diff --git a/packages/scene-graph/src/components/variants.ts b/packages/scene-graph/src/components/variants.ts
index dcbdefaa6..1174a95d9 100644
--- a/packages/scene-graph/src/components/variants.ts
+++ b/packages/scene-graph/src/components/variants.ts
@@ -1,5 +1,7 @@
+import { compact, uniq } from 'es-toolkit/array'
+
import type { SceneGraph } from '../graph'
-import type { SceneNode } from '../types'
+import type { ComponentPropertyDefinition, SceneNode } from '../types'
/** Variants in reading order on the canvas: top to bottom, then left to right, then by name. */
export function compareCanvasPosition(a: SceneNode, b: SceneNode): number {
@@ -29,36 +31,44 @@ export function defaultVariant(graph: SceneGraph, set: SceneNode): SceneNode | u
}
/**
- * The value a variant property starts at: its recorded default when that is one of its options,
- * or else the default variant's, since a document may leave the recorded default empty.
+ * The value a variant property starts at: the default variant's, as Figma reads it whatever
+ * default the document records, and follows when another variant moves to the top left. The
+ * recorded default stands only while the default variant has no value for the property.
*/
export function variantDefaultValue(
graph: SceneGraph,
set: SceneNode,
- property: { name: string; defaultValue: string; variantOptions?: string[] }
+ property: { name: string; defaultValue: string }
): string {
- if (property.variantOptions?.includes(property.defaultValue)) return property.defaultValue
- return defaultVariant(graph, set)?.componentPropertyValues[property.name] ?? property.defaultValue
+ const value = defaultVariant(graph, set)?.componentPropertyValues[property.name]
+ return value || property.defaultValue
}
/**
- * The variant with every property at its default value: the recorded defaults when they name a
- * variant, else the default variant, as a document that leaves them out draws it.
+ * A variant property's values: the ones the document records, then any its variants use that it
+ * does not, since older documents record none and a set's page may have loaded only some
+ * variants.
*/
-export function restingVariant(graph: SceneGraph, set: SceneNode): SceneNode | undefined {
- const properties = set.componentPropertyDefinitions.filter(
- (definition) => definition.type === 'VARIANT'
- )
- const values = properties.map(
- (property) => [property.name, variantDefaultValue(graph, set, property)] as const
- )
- return (
- graph
- .getChildren(set.id)
- .find(
- (child) =>
- child.type === 'COMPONENT' &&
- values.every(([name, value]) => child.componentPropertyValues[name] === value)
- ) ?? defaultVariant(graph, set)
- )
+export function variantOptions(
+ graph: SceneGraph,
+ set: SceneNode,
+ property: { name: string; variantOptions?: string[] }
+): string[] {
+ const used = graph
+ .getChildren(set.id)
+ .map((child) =>
+ child.type === 'COMPONENT' ? child.componentPropertyValues[property.name] : ''
+ )
+ return compact(uniq([...(property.variantOptions ?? []), ...used]))
+}
+
+/** A set's definition with a variant property's values and default filled in from its variants. */
+export function resolvedVariantDefinition(
+ graph: SceneGraph,
+ set: SceneNode,
+ definition: ComponentPropertyDefinition
+): ComponentPropertyDefinition {
+ if (definition.type !== 'VARIANT') return definition
+ const options = { ...definition, variantOptions: variantOptions(graph, set, definition) }
+ return { ...options, defaultValue: variantDefaultValue(graph, set, options) }
}
diff --git a/packages/scene-graph/src/graph.ts b/packages/scene-graph/src/graph.ts
index 4a6cc401b..7f0f83816 100644
--- a/packages/scene-graph/src/graph.ts
+++ b/packages/scene-graph/src/graph.ts
@@ -26,6 +26,7 @@ import { updateNodePreview, type NodePreviewObserver } from './preview'
import type { Color, Rect, Vector } from './primitives'
import { markSourceFieldsEdited } from './source-metadata'
import { invalidateTextCaches } from './text/picture'
+import { remapCopiedReferences } from './transfer/copied'
import type {
DocumentColorSpace,
DocumentKind,
@@ -742,6 +743,20 @@ export class SceneGraph {
sourceId: string,
parentId: string,
overrides: Partial<SceneNode> = {}
+ ): SceneNode | null {
+ const ids = new Map<string, string>()
+ const clone = this.cloneSubtree(sourceId, parentId, overrides, ids)
+ // Copies point at one another, as a paste's do: an instance at a component cloned with it,
+ // as Figma's clone does (desktop 126), and its override records at its copies' new ids.
+ remapCopiedReferences(this, ids)
+ return clone
+ }
+
+ private cloneSubtree(
+ sourceId: string,
+ parentId: string,
+ overrides: Partial<SceneNode>,
+ ids: Map<string, string>
): SceneNode | null {
const src = this.nodes.get(sourceId)
if (!src) return null
@@ -753,9 +768,10 @@ export class SceneGraph {
props.status = null
const clone = this.createNode(src.type, parentId, { ...props, ...overrides })
if (src.status) markSourceFieldsEdited(clone, ['status'])
+ ids.set(src.id, clone.id)
for (const childId of src.childIds) {
- this.cloneTree(childId, clone.id)
+ this.cloneSubtree(childId, clone.id, {}, ids)
}
return clone
diff --git a/packages/scene-graph/tests/behaviours/spec.test.ts b/packages/scene-graph/tests/behaviours/spec.test.ts
index cbe32497a..df881db15 100644
--- a/packages/scene-graph/tests/behaviours/spec.test.ts
+++ b/packages/scene-graph/tests/behaviours/spec.test.ts
@@ -51,6 +51,22 @@ describe('behaviour specs', () => {
})
})
+ // The shadcn/ui community kit saves its switch as `state` with neither values nor a default.
+ test('a set read from a file without its option lists binds to its variants’ values', () => {
+ const graph = new SceneGraph()
+ const set = graph.createNode('COMPONENT_SET', graph.getPages()[0].id, {
+ name: 'switch',
+ componentPropertyDefinitions: [{ id: 'p1', name: 'state', type: 'VARIANT', defaultValue: '' }]
+ })
+ for (const state of ['off', 'on'])
+ graph.createNode('COMPONENT', set.id, {
+ name: `state=${state}`,
+ componentPropertyValues: { state }
+ })
+ const behaviour = behaviourFromSpec(graph, set, { kind: 'switch', values: { value: 'state' } })
+ expect(behaviour.booleans.value).toEqual({ propertyId: 'p1', on: 'on', off: 'off' })
+ })
+
test('on and off are guessed by name before order', () => {
expect(guessOnOff(['Off', 'On'])).toEqual({ on: 'On', off: 'Off' })
expect(guessOnOff(['False', 'True'])).toEqual({ on: 'True', off: 'False' })
diff --git a/packages/scene-graph/tests/clone/tree.test.ts b/packages/scene-graph/tests/clone/tree.test.ts
index fb8e6865c..65026880d 100644
--- a/packages/scene-graph/tests/clone/tree.test.ts
+++ b/packages/scene-graph/tests/clone/tree.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, test } from 'bun:test'
import { SceneGraph } from '@open-pencil/scene-graph'
+import {
+ cloneInstanceOverrideState,
+ copiedComponentLayerId,
+ setInstanceOverride
+} from '@open-pencil/scene-graph/instances/overrides'
import { expectDefined, getNodeOrThrow } from '../helpers/assert'
@@ -104,6 +109,52 @@ describe('SceneGraph.cloneTree', () => {
const clonedChild = graph.getChildren(clone.id)[0]
expect(clonedChild.source.id).toBeNull()
})
+ // A badge with a left and a right icon, as the shadcn/ui kit draws one. A .fig file records
+ // which badge layer each icon copy copies, by the copy's id: both copies are instances of the
+ // same icon, so their own componentId cannot tell them apart.
+ test('a cloned instance keeps which component layer each copy copies', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const icon = graph.createNode('COMPONENT', page.id, { name: 'Icon', width: 16, height: 16 })
+ const badge = graph.createNode('COMPONENT', page.id, { name: 'Badge', width: 60, height: 20 })
+ for (const name of ['Left', 'Right'])
+ expectDefined(graph.createInstance(icon.id, badge.id, { name }), name)
+ const instance = expectDefined(graph.createInstance(badge.id, page.id), 'badge instance')
+ const layers = graph.getChildren(badge.id).map((layer) => layer.id)
+ // As the .fig reader builds them: each icon copy names the icon itself, and the instance
+ // records the badge layer it copies.
+ const overrides = cloneInstanceOverrideState(instance.instanceOverrides)
+ for (const [index, copy] of graph.getChildren(instance.id).entries()) {
+ graph.updateNode(copy.id, { componentId: icon.id })
+ setInstanceOverride(overrides, instance.id, copy.id, 'sourceComponentId', layers[index])
+ }
+ graph.updateNode(instance.id, { instanceOverrides: overrides })
+ const sources = (id: string) => {
+ const node = getNodeOrThrow(graph, id)
+ return graph
+ .getChildren(id)
+ .map((copy) => copiedComponentLayerId(node.instanceOverrides, id, copy))
+ }
+ expect(sources(instance.id)).toEqual(layers)
+
+ const clone = expectDefined(graph.cloneTree(instance.id, page.id), 'clone')
+ expect(sources(clone.id)).toEqual(layers)
+ })
+
+ // Figma (desktop 126): cloning a frame that holds a component and an instance of it gives an
+ // instance of the cloned component.
+ test('an instance cloned with its component names the cloned component', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const frame = graph.createNode('FRAME', page.id, { name: 'Holder', width: 300, height: 100 })
+ const component = graph.createNode('COMPONENT', frame.id, { name: 'Inner', width: 40 })
+ expectDefined(graph.createInstance(component.id, frame.id, { x: 100 }), 'instance')
+ const clone = expectDefined(graph.cloneTree(frame.id, page.id), 'clone')
+ const [clonedComponent, clonedInstance] = graph.getChildren(clone.id)
+ expect(clonedComponent.id).not.toBe(component.id)
+ expect(clonedInstance.componentId).toBe(clonedComponent.id)
+ })
+
test('clone deep-copies source.fig so mutations do not affect original', () => {
const graph = new SceneGraph()
const page = graph.getPages()[0]
diff --git a/packages/scene-graph/tests/components/variants.test.ts b/packages/scene-graph/tests/components/variants.test.ts
index 4dcb1eb2c..34e4c4ab0 100644
--- a/packages/scene-graph/tests/components/variants.test.ts
+++ b/packages/scene-graph/tests/components/variants.test.ts
@@ -3,8 +3,8 @@ import { describe, expect, test } from 'bun:test'
import { SceneGraph } from '@open-pencil/scene-graph'
import {
defaultVariant,
- restingVariant,
- variantDefaultValue
+ variantDefaultValue,
+ variantOptions
} from '@open-pencil/scene-graph/components'
/** A set of sizes laid out with Large first in its children but Small in the top-left corner. */
@@ -62,18 +62,31 @@ describe('default variants', () => {
expect(pick(at(0, 0), at(0, 0))).toBe('v=0')
})
- test('give a property its default value when the document leaves it out', () => {
+ // Figma (desktop 126) reports the default variant's value whatever default the file records,
+ // and follows the variant moved to the top left.
+ test('give a property the default variant’s value, whatever the document records', () => {
const empty = sizes('')
expect(variantDefaultValue(empty.graph, empty.set, empty.definition)).toBe('Small')
- // A recorded default that is one of the options stands.
const recorded = sizes('Large')
+ expect(variantDefaultValue(recorded.graph, recorded.set, recorded.definition)).toBe('Small')
+ const [large, small] = recorded.graph.getChildren(recorded.set.id)
+ recorded.graph.updateNode(large.id, { y: 0 })
+ recorded.graph.updateNode(small.id, { y: 60 })
expect(variantDefaultValue(recorded.graph, recorded.set, recorded.definition)).toBe('Large')
})
- test('rest at the recorded defaults when they name a variant, else at the default variant', () => {
- const recorded = sizes('Large')
- expect(restingVariant(recorded.graph, recorded.set)?.name).toBe('Size=Large')
- const empty = sizes('')
- expect(restingVariant(empty.graph, empty.set)?.name).toBe('Size=Small')
+ test('keep the recorded default while the default variant has no value for the property', () => {
+ const { graph, set, definition } = sizes('Large')
+ const small = graph.getChildren(set.id).find((variant) => variant.name === 'Size=Small')
+ graph.updateNode(small?.id ?? '', { componentPropertyValues: { Size: '' } })
+ expect(variantDefaultValue(graph, set, definition)).toBe('Large')
+ })
+})
+
+describe('variant options', () => {
+ test('keep the recorded values first and add those the variants use', () => {
+ const { graph, set } = sizes('')
+ const options = variantOptions(graph, set, { name: 'Size', variantOptions: ['Medium'] })
+ expect(options).toEqual(['Medium', 'Large', 'Small'])
})
})