AI-native design editor. Open-source Figma alternative.
fix: order variable modes by sort position and keep the default first (#1633)
Andrew Avsenin3a5e3fe98919
diff --git a/changes/1633/fixed.md b/changes/1633/fixed.mdnew file mode 100644index 000000000..0d4e3596a--- /dev/null+++ b/changes/1633/fixed.md@@ -0,0 +1 @@+- Variable modes from a .fig file open in Figma's order with Figma's default mode, and keep that order through export.diff --git a/packages/core/src/editor/variables.ts b/packages/core/src/editor/variables.tsindex 6ef2de649..471c1803e 100644--- a/packages/core/src/editor/variables.ts+++ b/packages/core/src/editor/variables.ts@@ -318,8 +318,12 @@ export function createVariableActions(ctx: EditorContext) {function removeMode(collectionId: string, modeId: string) {const collection = ctx.graph.variableCollections.get(collectionId)if (!collection || collection.modes.length <= 1) return- const modeIndex = collection.modes.findIndex((m) => m.modeId === modeId)- const modeName = collection.modes[modeIndex]?.name ?? ''+ const removedMode = collection.modes.find((m) => m.modeId === modeId)+ if (!removedMode) {+ return+ }+ const modeIndex = collection.modes.indexOf(removedMode)+ const savedMode = structuredClone(removedMode)const wasDefault = collection.defaultModeId === modeIdconst valueSnapshots = new Map<string, VariableValue>()for (const varId of collection.variableIds) {@@ -336,11 +340,12 @@ export function createVariableActions(ctx: EditorContext) {refreshVariables(collectionScope(collectionId))},inverse: () => {- ctx.graph.addMode(collectionId, modeId, modeName)+ ctx.graph.addMode(collectionId, modeId, savedMode.name)const col = ctx.graph.variableCollections.get(collectionId)- if (col && modeIndex !== -1) {- const mode = col.modes.pop()- if (mode) col.modes.splice(modeIndex, 0, mode)+ if (col) {+ col.modes = col.modes+ .filter((m) => m.modeId !== modeId)+ .toSpliced(modeIndex, 0, structuredClone(savedMode))}for (const [varId, value] of valueSnapshots) {const v = ctx.graph.variables.get(varId)diff --git a/packages/core/tests/io/formats/fig/export/patch/fields.test.ts b/packages/core/tests/io/formats/fig/export/patch/fields.test.tsindex 9d3a62506..34d0e4fd9 100644--- a/packages/core/tests/io/formats/fig/export/patch/fields.test.ts+++ b/packages/core/tests/io/formats/fig/export/patch/fields.test.ts@@ -2,7 +2,7 @@ import { beforeAll, expect, setDefaultTimeout, test } from 'bun:test'import { expectDefined } from '#core-tests/helpers/assert'import { readFixtureArrayBuffer } from '#core-tests/helpers/fig/fixtures'-import { uniq } from 'es-toolkit/array'+import { sortBy, uniq } from 'es-toolkit/array'import { isEqual } from 'es-toolkit/predicate'import { createEditor } from '@open-pencil/core'@@ -103,7 +103,15 @@ test('a mode added to a collection of library aliases keeps the file as Figma sa)const set = expectDefined(after.get(guidToString(expectDefined(before.get(collection.id)?.guid))))const saved = expectDefined(before.get(collection.id)?.variableSetModes)- expect(set.variableSetModes?.slice(0, saved.length)).toEqual(saved)+ const listed = sortBy(saved, [+ (mode) => mode.sortPosition === undefined,+ (mode) => mode.sortPosition ?? ''+ ])+ const written = expectDefined(set.variableSetModes)+ expect(written.slice(0, -1)).toEqual(listed)+ const added = expectDefined(written.at(-1))+ expect(added.name).toBe('Added')+ expect(expectDefined(added.sortPosition) > expectDefined(listed.at(-1)?.sortPosition)).toBe(true)// Values aliasing library variables still name them by key, as Figma writes them.for (const guid of changed.keys()) {const entries = after.get(guid)?.variableDataValues?.entries ?? []diff --git a/packages/core/tests/io/formats/fig/roundtrip/variables.test.ts b/packages/core/tests/io/formats/fig/roundtrip/variables.test.tsindex 2582d9ad4..8ba41124e 100644--- a/packages/core/tests/io/formats/fig/roundtrip/variables.test.ts+++ b/packages/core/tests/io/formats/fig/roundtrip/variables.test.ts@@ -4,6 +4,7 @@ import { expectDefined } from '#core-tests/helpers/assert'import { parseFixture } from '#core-tests/helpers/fig/fixtures'import { runsHeavyTests } from '#core-tests/helpers/test-utils'+import { createEditor } from '@open-pencil/core/editor'import { FigmaAPI } from '@open-pencil/core/figma-api'import { exportFigFile, parseFigFile } from '@open-pencil/core/io/formats/fig'import { initCodec } from '@open-pencil/kiwi/fig/codec'@@ -407,6 +408,81 @@ describe('variable roundtrip', () => {expect(imported.modes.map((mode) => mode.name)).toEqual(['Dark', 'Mode 1'])})+ function themeWithSavedModes(): SceneGraph {+ const graph = new SceneGraph()+ graph.addCollection({+ id: 'theme',+ name: 'Theme',+ modes: [+ { modeId: 'light', name: 'Light', sortPosition: 'm' },+ { modeId: 'dark', name: 'Dark', sortPosition: 'q' }+ ],+ defaultModeId: 'light',+ variableIds: []+ })+ graph.addMode('theme', 'contrast', 'Contrast')+ graph.createVariable('Gap', 'FLOAT', 'theme', 4)+ return graph+ }++ async function reimportedTheme(graph: SceneGraph) {+ const reimported = await parseFigFile((await exportFigFile(graph)).buffer as ArrayBuffer)+ const theme = expectDefined(+ [...reimported.variableCollections.values()].find((c) => c.name === 'Theme'),+ 'theme collection'+ )+ const defaultMode = theme.modes.find((mode) => mode.modeId === theme.defaultModeId)+ return { defaultMode: defaultMode?.name, modes: theme.modes.map((mode) => mode.name) }+ }++ test('saved mode order and default survive export → re-import', async () => {+ await initCodec()++ expect(await reimportedTheme(themeWithSavedModes())).toEqual({+ defaultMode: 'Light',+ modes: ['Light', 'Dark', 'Contrast']+ })+ })++ test('a default chosen among saved modes survives export → re-import', async () => {+ await initCodec()+ const graph = themeWithSavedModes()++ graph.setDefaultMode('theme', 'dark')++ expect(await reimportedTheme(graph)).toEqual({+ defaultMode: 'Dark',+ modes: ['Dark', 'Light', 'Contrast']+ })+ })++ test('a saved mode restored by undo keeps its place after export → re-import', async () => {+ await initCodec()+ const graph = new SceneGraph()+ graph.addCollection({+ id: 'theme',+ name: 'Theme',+ modes: [+ { modeId: 'a', name: 'A', sortPosition: 'a' },+ { modeId: 'b', name: 'B', sortPosition: 'b' },+ { modeId: 'c', name: 'C', sortPosition: 'c' }+ ],+ defaultModeId: 'a',+ variableIds: []+ })+ graph.createVariable('Gap', 'FLOAT', 'theme', 4)+ const editor = createEditor({ graph })++ editor.removeMode('theme', 'b')+ expect(graph.variableCollections.get('theme')?.modes.map((mode) => mode.modeId)).toEqual([+ 'a',+ 'c'+ ])+ editor.undo.undo()++ expect(await reimportedTheme(graph)).toEqual({ defaultMode: 'A', modes: ['A', 'B', 'C'] })+ })+test.if(runsHeavyTests)('material3.fig variables survive round-trip',async () => {diff --git a/packages/fig/src/document/variables.ts b/packages/fig/src/document/variables.tsindex a735b4156..0f34612e1 100644--- a/packages/fig/src/document/variables.ts+++ b/packages/fig/src/document/variables.ts@@ -1,3 +1,4 @@+import { sortBy } from 'es-toolkit/array'import * as v from 'valibot'import type { NodeChange, VariableDataEntry } from '@open-pencil/kiwi/fig/codec'@@ -188,6 +189,16 @@ function modeValues(return values}+type SavedMode = NonNullable<NodeChange['variableSetModes']>[number]++/** Figma lists modes by `sortPosition`; modes without one follow, in saved order. */+function modesInListedOrder(resource: NodeChange): SavedMode[] {+ return sortBy(resource.variableSetModes ?? [], [+ (mode) => !mode.sortPosition,+ (mode) => mode.sortPosition ?? ''+ ])+}+/** No invented values or fallback collections: unsupported resources remain explicit. */export function materializeVariableResources(graph: SceneGraph,@@ -201,7 +212,7 @@ export function materializeVariableResources(}for (const resource of resources) {if (resource.type !== 'VARIABLE_SET') continue- const modes = resource.variableSetModes ?? []+ const modes = modesInListedOrder(resource)if (!resource.guid || modes.length === 0) {report(resource, 'missing collection identity or modes')continuediff --git a/packages/fig/tests/document/bindings/modes.test.ts b/packages/fig/tests/document/bindings/modes.test.tsindex 3f1eb0278..889038d0d 100644--- a/packages/fig/tests/document/bindings/modes.test.ts+++ b/packages/fig/tests/document/bindings/modes.test.ts@@ -102,3 +102,51 @@ test('repeated instances resolve nested bindings using inherited collection modeexpect(child.width).toBe(expected)}})++test('bindings without an explicit mode resolve in the first listed mode', () => {+ const changes = [+ { guid: guid(1), type: 'DOCUMENT' },+ { guid: guid(2), type: 'CANVAS', parentIndex: { guid: guid(1), position: '!' } },+ {+ guid: guid(3),+ type: 'VARIABLE_SET',+ variableSetModes: [+ { id: guid(10), name: 'Listed second', sortPosition: 'b' },+ { id: guid(11), name: 'Listed first', sortPosition: 'a' }+ ]+ },+ {+ guid: guid(4),+ type: 'VARIABLE',+ variableResolvedType: 'FLOAT',+ variableSetID: { guid: guid(3) },+ variableDataValues: {+ entries: [10, 11].map((mode) => ({+ modeID: guid(mode),+ variableData: { dataType: 'FLOAT', value: { floatValue: mode } }+ }))+ }+ },+ {+ guid: guid(5),+ type: 'FRAME',+ parentIndex: { guid: guid(2), position: 'a' },+ stackMode: 'HORIZONTAL',+ stackSpacing: 10,+ variableConsumptionMap: {+ entries: [+ {+ variableField: 'STACK_SPACING',+ variableData: { dataType: 'ALIAS', value: { alias: { guid: guid(4) } } }+ }+ ]+ }+ }+ ] as NodeChange[]+ const { graph, sources } = materializeDocument(changes)+ const id = sources.get('1:5')+ if (!id) {+ throw new Error('Missing frame')+ }+ expect(graph.nodes.get(id)?.itemSpacing).toBe(11)+})diff --git a/packages/fig/tests/document/variables.test.ts b/packages/fig/tests/document/variables.test.tsindex 437085471..a4a6d0472 100644--- a/packages/fig/tests/document/variables.test.ts+++ b/packages/fig/tests/document/variables.test.ts@@ -1,9 +1,13 @@import { expect, test } from 'bun:test'+import { readFixtureArrayBuffer } from '#fig-tests/helpers/fig-fixtures'import { guid } from '#fig-tests/helpers/guid'import { materializeDocument } from '#fig/document/materialize'+import { materializeVariableResources } from '#fig/document/variables'+import { parseFigBuffer } from '@open-pencil/fig'import type { NodeChange, VariableDataEntry } from '@open-pencil/kiwi/fig/codec'+import { SceneGraph } from '@open-pencil/scene-graph'function resources(operand: VariableDataEntry): NodeChange[] {return [@@ -60,3 +64,65 @@ test('FIG formulas preserve valid operands and report incompatible definitions wexpect(reported).toEqual([resources(operand)[1]])}})++function collectionWithModes(modes: NonNullable<NodeChange['variableSetModes']>): NodeChange[] {+ return [{ guid: guid(3), type: 'VARIABLE_SET', variableSetModes: modes }]+}++function listedModes(changes: NodeChange[]) {+ const collection = materializeDocument(changes).graph.variableCollections.get('1:3')+ if (!collection) {+ throw new Error('Missing collection')+ }+ return {+ names: collection.modes.map((mode) => mode.name),+ defaultModeId: collection.defaultModeId+ }+}++test('a collection lists its modes by sort position and defaults to the first listed', () => {+ const listed = listedModes(+ collectionWithModes([+ { id: guid(10), name: 'A', sortPosition: 'b' },+ { id: guid(11), name: 'B', sortPosition: 'a' }+ ])+ )+ expect(listed).toEqual({ names: ['B', 'A'], defaultModeId: '1:11' })+})++test('modes without a sort position follow the positioned ones in saved order', () => {+ const listed = listedModes(+ collectionWithModes([+ { id: guid(10), name: 'A' },+ { id: guid(11), name: 'B', sortPosition: 'b' },+ { id: guid(12), name: 'C', sortPosition: 'a' },+ { id: guid(13), name: 'D' }+ ])+ )+ expect(listed).toEqual({ names: ['C', 'B', 'A', 'D'], defaultModeId: '1:12' })+})++test('modes sharing a sort position keep their saved order', () => {+ const listed = listedModes(+ collectionWithModes([+ { id: guid(10), name: 'A', sortPosition: 'a' },+ { id: guid(11), name: 'B', sortPosition: 'a' }+ ])+ )+ expect(listed).toEqual({ names: ['A', 'B'], defaultModeId: '1:10' })+})++test('a saved collection lists its modes in the order Figma shows them', () => {+ const { nodeChanges } = parseFigBuffer(readFixtureArrayBuffer('gold-preview.fig'))+ const graph = new SceneGraph()+ materializeVariableResources(graph, nodeChanges, () => undefined)+ const tokens = [...graph.variableCollections.values()].find((c) => c.name === 'Tokens')+ expect(tokens?.modes.map((mode) => mode.name)).toEqual([+ 'Default',+ 'Default (Dark)',+ 'Harvest',+ 'Harvest (Dark)',+ 'Retro',+ 'Retro (Dark)'+ ])+})diff --git a/packages/scene-graph/src/variables/index.ts b/packages/scene-graph/src/variables/index.tsindex 8bf0875e1..3f3b906a6 100644--- a/packages/scene-graph/src/variables/index.ts+++ b/packages/scene-graph/src/variables/index.ts@@ -5,6 +5,7 @@ import { BLACK } from '../constants'import type { SceneGraph } from '../graph'import { findInstanceAncestor } from '../instances'import { bindingOverrideField, setInstanceOverride } from '../instances/overrides'+import { siblingOrderKeys } from '../order-keys'import type {Variable,VariableCollection,@@ -207,7 +208,15 @@ export function setDefaultMode(graph: SceneGraph, collectionId: string, modeId:if (!collection) returnif (!collection.modes.some((m) => m.modeId === modeId)) returncollection.defaultModeId = modeId- collection.modes = modesDefaultFirst(collection)+ collection.modes = withSortPositionsInOrder(modesDefaultFirst(collection))+}++function withSortPositionsInOrder(modes: VariableCollectionMode[]): VariableCollectionMode[] {+ if (modes.every((mode) => !mode.sortPosition)) {+ return modes+ }+ const positions = siblingOrderKeys(modes.map((mode) => mode.sortPosition))+ return modes.map((mode, index) => ({ ...mode, sortPosition: positions[index] }))}/** Figma has no default-mode field: the first mode is the default. */diff --git a/packages/scene-graph/tests/basic/variables.test.ts b/packages/scene-graph/tests/basic/variables.test.tsindex 8e39497d5..4482074e1 100644--- a/packages/scene-graph/tests/basic/variables.test.ts+++ b/packages/scene-graph/tests/basic/variables.test.ts@@ -361,4 +361,57 @@ describe('Variables', () => {expect(graph.resolveColorVariable('v1')).toBeUndefined()})++ function collectionWithSortPositions(graph: SceneGraph, sortPositions: string[]): void {+ graph.addCollection({+ id: 'col1',+ name: 'Theme',+ modes: sortPositions.map((sortPosition, index) => ({+ modeId: `m${index}`,+ name: `Mode ${index}`,+ sortPosition+ })),+ defaultModeId: 'm0',+ variableIds: []+ })+ }++ function listedModes(graph: SceneGraph) {+ return graph.variableCollections.get('col1')?.modes ?? []+ }++ test('a new default mode sorts first and the others keep their positions', () => {+ const graph = new SceneGraph()+ collectionWithSortPositions(graph, ['a', 'b', 'c'])++ graph.setDefaultMode('col1', 'm2')++ const modes = listedModes(graph)+ expect(modes.map((mode) => mode.modeId)).toEqual(['m2', 'm0', 'm1'])+ expect(modes.slice(1).map((mode) => mode.sortPosition)).toEqual(['a', 'b'])+ expect((modes[0].sortPosition ?? '') < 'a').toBe(true)+ })++ test('a new default mode sorts first even when no position fits below the old first', () => {+ const graph = new SceneGraph()+ collectionWithSortPositions(graph, ['!', '"'])++ graph.setDefaultMode('col1', 'm1')++ const positions = listedModes(graph).map((mode) => mode.sortPosition ?? '')+ expect(listedModes(graph)[0].modeId).toBe('m1')+ expect(positions).toEqual(positions.toSorted())+ expect(new Set(positions).size).toBe(positions.length)+ })++ test('a collection without sort positions does not gain any when its default changes', () => {+ const graph = new SceneGraph()+ const collection = graph.createCollection('Theme')+ graph.addMode(collection.id, 'dark', 'Dark')++ graph.setDefaultMode(collection.id, 'dark')++ const modes = graph.variableCollections.get(collection.id)?.modes ?? []+ expect(modes.map((mode) => mode.sortPosition)).toEqual([undefined, undefined])+ })})