fix(fig): keep variable metadata, plugin data and default mode on save (#848)

* fix(fig): keep variable metadata, plugin data and default mode on save

Saving a .fig rebuilt every variable record from the model, which held none
of Figma's variable metadata, so each save wrote variables as published to
all scopes with no description or code names, dropped other plugins' data,
and made the first mode the default.

Variables now carry scopes, codeSyntax and pluginData, collections carry
pluginData, and the reader and writer translate description,
symbolDescription, isPublishable, variableScopes and codeSyntax. Figma has
no default-mode field, so setting a default moves that mode first (undo
restores the order) and the writer orders the default first.

This is the base for design tokens: the CSS name will live in
codeSyntax.WEB and unit and mode conditions in OpenPencil plugin data.

* refactor(scene-graph): share the default-first mode order

setDefaultMode and the .fig writer both moved the default mode first by
hand; modesDefaultFirst does it once, with es-toolkit's partition.

* fix(core): undo a default mode change on the collection currently in the graph

Undoing a collection's removal restores a copy of it, so the inverse of
setDefaultMode wrote the previous order and default to an object the
graph no longer held when both were undone. Look the collection up by id
when undoing, as the forward step already does.
This commit is contained in:
Danila Poyarkov 2026-10-04 12:53:04 +04:00 committed by GitHub
parent b422ea53a4
commit 5146e7f7e5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 295 additions and 15 deletions

View file

@ -60,6 +60,7 @@
- Keep fixed-size text from collapsing and clipping beside smaller siblings in a Hug auto-layout container.
- Keep the text and icon an instance was given when a page loads on its own, instead of resynchronising it back to the component's defaults.
- Keep the ordering keys a `.fig` gave its layers when saving one again, instead of renumbering every sibling, and give every layer on a canvas its own key. Shared styles, variables and the canvas's own layers were numbered in separate passes that each restarted, so Figma saw siblings claiming the same position and ordered them arbitrarily.
- Keep a `.fig` variable's description, scopes, code syntax, publishing visibility, and plugin data when saving the file, and a collection's plugin data and default mode. Saving previously wrote every variable as published to all scopes with no description or code names, and made the first mode the default.
- Clear a `.fig` fill or stroke's colour-variable binding when you unbind it, instead of exporting the variable the layer was imported with and rebinding it on reopen. An emptied binding record is no longer written into the file either.
- Keep an AI reply running in the chat panel, with its Stop button, when you switch pages, instead of detaching the panel from the reply in progress.
- Undo an AI edit while another page is on screen; undo previously did nothing until you returned to the page the AI changed.

View file

@ -252,6 +252,7 @@ export function createVariableActions(ctx: EditorContext) {
const collection = ctx.graph.variableCollections.get(collectionId)
if (!collection) return
const prevDefault = collection.defaultModeId
const prevModes = structuredClone(collection.modes)
ctx.graph.setDefaultMode(collectionId, modeId)
ctx.undo.push({
label: 'Set default mode',
@ -260,7 +261,13 @@ export function createVariableActions(ctx: EditorContext) {
refreshVariables()
},
inverse: () => {
ctx.graph.setDefaultMode(collectionId, prevDefault)
// Setting a default moves it first; undo restores the column order too. Look the
// collection up again: undoing its removal in between restores a copy.
const current = ctx.graph.variableCollections.get(collectionId)
if (current) {
current.modes = structuredClone(prevModes)
current.defaultModeId = prevDefault
}
refreshVariables()
}
})

View file

@ -1,6 +1,12 @@
import { pluginDataNodeChange, variableMetadataNodeChange } from '@open-pencil/fig/node-change'
import type { GUID, NodeChange, VariableDataEntry } from '@open-pencil/kiwi/fig/codec'
import { stringToGuid } from '@open-pencil/kiwi/fig/guid'
import type { SceneGraph, SceneNode, VariableValue } from '@open-pencil/scene-graph'
import {
modesDefaultFirst,
type SceneGraph,
type SceneNode,
type VariableValue
} from '@open-pencil/scene-graph'
import { fractionalPosition, safeColor } from '#core/kiwi/fig/node-change/serialize'
@ -132,11 +138,12 @@ export function appendVariableNodeChanges(
phase: 'CREATED',
strokeAlign: 'CENTER',
strokeJoin: 'BEVEL',
variableSetModes: collection.modes.map((mode, i) => ({
variableSetModes: modesDefaultFirst(collection).map((mode, i) => ({
id: modes.get(mode.modeId) ?? stringToGuid(mode.modeId),
name: mode.name,
sortPosition: fractionalPosition(i)
}))
})),
pluginData: pluginDataNodeChange(collection.pluginData)
})
for (const id of collection.variableIds) {
const variable = graph.variables.get(id)
@ -157,7 +164,7 @@ export function appendVariableNodeChanges(
variableData: variableValueToKiwi(value, variable.type, ids)
}))
},
variableScopes: ['ALL_SCOPES'],
...variableMetadataNodeChange(variable),
key: variable.key,
version: variable.version
})

View file

@ -0,0 +1,56 @@
import { describe, expect, test } from 'bun:test'
import { createEditor } from '@open-pencil/core/editor'
describe('variable mode undo', () => {
test('setting a default mode moves it first, and undo restores the order', () => {
const editor = createEditor()
editor.graph.addCollection({
id: 'theme',
name: 'Theme',
modes: [
{ modeId: 'light', name: 'Light' },
{ modeId: 'dim', name: 'Dim' },
{ modeId: 'dark', name: 'Dark' }
],
defaultModeId: 'light',
variableIds: []
})
const order = () => editor.graph.variableCollections.get('theme')?.modes.map((m) => m.modeId)
editor.setDefaultMode('theme', 'dark')
expect(order()).toEqual(['dark', 'light', 'dim'])
expect(editor.graph.variableCollections.get('theme')?.defaultModeId).toBe('dark')
editor.undo.undo()
expect(order()).toEqual(['light', 'dim', 'dark'])
expect(editor.graph.variableCollections.get('theme')?.defaultModeId).toBe('light')
editor.undo.redo()
expect(order()).toEqual(['dark', 'light', 'dim'])
})
test('undo restores the default mode of a collection restored by an earlier undo', () => {
const editor = createEditor()
editor.graph.addCollection({
id: 'theme',
name: 'Theme',
modes: [
{ modeId: 'light', name: 'Light' },
{ modeId: 'dark', name: 'Dark' }
],
defaultModeId: 'light',
variableIds: []
})
editor.setDefaultMode('theme', 'dark')
editor.removeCollection('theme')
// Undoing the removal restores a copy of the collection, not the object it had before.
editor.undo.undo()
editor.undo.undo()
const restored = editor.graph.variableCollections.get('theme')
expect(restored?.defaultModeId).toBe('light')
expect(restored?.modes.map((m) => m.modeId)).toEqual(['light', 'dark'])
})
})

View file

@ -252,6 +252,76 @@ describe('variable roundtrip', () => {
)
})
test('variable metadata and plugin data survive export → re-import', async () => {
await initCodec()
const graph = new SceneGraph()
graph.addCollection({
id: '4:60',
name: 'Radius',
modes: [{ modeId: '4:3', name: 'Base' }],
defaultModeId: '4:3',
variableIds: [],
pluginData: [
{ pluginId: 'open-pencil', key: 'modes', value: '{"4:3":":root"}' },
{ pluginId: 'tokens-studio', key: 'theme', value: 'base' }
]
})
graph.addVariable({
id: '5:2',
name: 'Radius/card',
type: 'FLOAT',
collectionId: '4:60',
valuesByMode: { '4:3': 12 },
description: 'Cards and sheets',
hiddenFromPublishing: true,
scopes: ['CORNER_RADIUS'],
codeSyntax: { WEB: '--radius-card', iOS: 'Radius.card' },
pluginData: [
{ pluginId: 'open-pencil', key: 'token', value: '{"unit":"rem"}' },
{ pluginId: 'tokens-studio', key: 'path', value: 'radius.card' }
]
})
const reimported = await parseFigFile((await exportFigFile(graph)).buffer as ArrayBuffer)
const variable = expectDefined(reimported.variables.get('5:2'), 'radius variable')
expect(variable).toMatchObject({
description: 'Cards and sheets',
hiddenFromPublishing: true,
scopes: ['CORNER_RADIUS'],
codeSyntax: { WEB: '--radius-card', iOS: 'Radius.card' }
})
expect(variable.pluginData).toEqual(graph.variables.get('5:2')?.pluginData)
expect(reimported.variableCollections.get('4:60')?.pluginData).toEqual(
graph.variableCollections.get('4:60')?.pluginData
)
})
test('a default mode that is not first survives export → re-import', async () => {
await initCodec()
const graph = new SceneGraph()
const collection = graph.createCollection('Theme')
graph.addMode(collection.id, 'dark', 'Dark')
const background = graph.createVariable('Background', 'COLOR', collection.id, {
r: 1,
g: 1,
b: 1,
a: 1
})
background.valuesByMode.dark = { r: 0, g: 0, b: 0, a: 1 }
graph.setDefaultMode(collection.id, 'dark')
const reimported = await parseFigFile((await exportFigFile(graph)).buffer as ArrayBuffer)
const imported = expectDefined(
[...reimported.variableCollections.values()].find((c) => c.name === 'Theme'),
'theme collection'
)
const defaultMode = imported.modes.find((mode) => mode.modeId === imported.defaultModeId)
expect(defaultMode?.name).toBe('Dark')
expect(imported.modes.map((mode) => mode.name)).toEqual(['Dark', 'Mode 1'])
})
test.if(runsHeavyTests)(
'material3.fig variables survive round-trip',
async () => {
@ -264,6 +334,19 @@ describe('variable roundtrip', () => {
expect(reimported.variableCollections.size).toBeGreaterThanOrEqual(
[...original.variableCollections.values()].filter((c) => c.variableIds.length > 0).length
)
const metadata = (graph: typeof original) =>
[...graph.variables.values()].map(
({ id, description, hiddenFromPublishing, scopes, codeSyntax }) => ({
id,
description,
hiddenFromPublishing,
scopes,
codeSyntax
})
)
expect(metadata(original).some((v) => v.codeSyntax)).toBe(true)
expect(metadata(original).some((v) => v.description)).toBe(true)
expect(metadata(reimported)).toEqual(metadata(original))
},
120_000
)

View file

@ -2,6 +2,8 @@ import type { NodeChange, VariableDataValuesEntry } from '@open-pencil/kiwi/fig/
import { guidToString } from '@open-pencil/kiwi/fig/guid'
import type { SceneGraph, VariableValue } from '@open-pencil/scene-graph'
import { extractPluginData } from '../node-change/plugin-data'
import { readVariableMetadata } from '../node-change/variable/metadata'
import { createResourceResolver } from './resource-reference'
function valueOf(
@ -56,12 +58,14 @@ export function materializeVariableResources(
report(resource, 'missing collection identity or modes')
continue
}
const pluginData = extractPluginData(resource)
graph.addCollection({
id: guidToString(resource.guid),
name: resource.name ?? 'Variables',
modes: modes.map((mode) => ({ modeId: guidToString(mode.id), name: mode.name })),
defaultModeId: guidToString(modes[0].id),
variableIds: []
variableIds: [],
pluginData: pluginData.length > 0 ? pluginData : undefined
})
}
addVariables(graph, resources, report)
@ -109,8 +113,7 @@ function addVariables(
type,
collectionId,
valuesByMode,
description: '',
hiddenFromPublishing: false
...readVariableMetadata(resource)
})
}
}

View file

@ -19,5 +19,6 @@ export * from './style/runs'
export * from './text/data-export'
export * from './text/values'
export * from './variable/bindings'
export * from './variable/metadata'
export * from './vector/geometry'
export * from './vector/network'

View file

@ -0,0 +1,65 @@
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import {
CODE_SYNTAX_PLATFORMS,
VARIABLE_SCOPES,
type CodeSyntaxPlatform,
type PluginDataEntry,
type Variable,
type VariableScope
} from '@open-pencil/scene-graph'
import { extractPluginData, mergePluginData } from '../plugin-data'
type VariableMetadata = Pick<
Variable,
'description' | 'hiddenFromPublishing' | 'scopes' | 'codeSyntax' | 'pluginData'
>
const isScope = (value: string): value is VariableScope =>
(VARIABLE_SCOPES as readonly string[]).includes(value)
const isPlatform = (value: string): value is CodeSyntaxPlatform =>
(CODE_SYNTAX_PLATFORMS as readonly string[]).includes(value)
function readCodeSyntax(nc: NodeChange): Variable['codeSyntax'] {
const entries = (nc.codeSyntax?.entries ?? []).flatMap(({ platform, value }) =>
isPlatform(platform) && value ? [[platform, value] as const] : []
)
return entries.length > 0 ? Object.fromEntries(entries) : undefined
}
/** Figma keeps the description twice, as `description` and `symbolDescription`. */
export function readVariableMetadata(nc: NodeChange): VariableMetadata {
const scopes = nc.variableScopes?.filter(isScope)
const pluginData = extractPluginData(nc)
return {
description: nc.description ?? nc.symbolDescription ?? '',
hiddenFromPublishing: nc.isPublishable === false,
scopes: scopes?.length ? scopes : undefined,
codeSyntax: readCodeSyntax(nc),
pluginData: pluginData.length > 0 ? pluginData : undefined
}
}
export function variableMetadataNodeChange(variable: Variable): Partial<NodeChange> {
const codeSyntax = Object.entries(variable.codeSyntax ?? {}).flatMap(([platform, value]) =>
value ? [{ platform, value }] : []
)
const nc: Partial<NodeChange> = {
isPublishable: !variable.hiddenFromPublishing,
variableScopes: variable.scopes?.length ? variable.scopes : ['ALL_SCOPES'],
pluginData: pluginDataNodeChange(variable.pluginData)
}
if (variable.description) {
nc.description = variable.description
nc.symbolDescription = variable.description
}
if (codeSyntax.length > 0) nc.codeSyntax = { entries: codeSyntax }
return nc
}
export function pluginDataNodeChange(
pluginData: PluginDataEntry[] | undefined
): NodeChange['pluginData'] {
return pluginData?.length ? mergePluginData(pluginData) : undefined
}

View file

@ -387,6 +387,10 @@ export interface NodeChange {
variableResolvedType?: string
variableDataValues?: { entries?: VariableDataValuesEntry[] }
variableScopes?: string[]
codeSyntax?: { entries?: Array<{ platform: string; value: string }> }
description?: string
symbolDescription?: string
isPublishable?: boolean
documentColorProfile?: 'SRGB' | 'DISPLAY_P3'
pluginData?: PluginData[]
pluginRelaunchData?: PluginRelaunchData[]

View file

@ -1,6 +1,7 @@
/* eslint-disable max-lines -- SceneGraph exposes a stable facade over domain modules */
export * from './mutation-impact'
export * from './variables/bindings'
export { modesDefaultFirst } from './variables'
export { rescaleNodeTree, scaleNodeChanges } from './scaling'
import { TRANSFORM_FIELDS, SIZE_FIELDS } from './fields/geometry'
export { TRANSFORM_FIELDS, SIZE_FIELDS } from './fields/geometry'

View file

@ -58,7 +58,7 @@ export function prepareVariableTransfer(
}
return {
collections: collections.map((collection) => ({
...collection,
...structuredClone(collection),
id: mapped(references.collections, collection.id, 'collection'),
defaultModeId: mapped(references.modes, collection.defaultModeId, 'mode'),
modes: collection.modes.map((mode) => ({
@ -68,7 +68,7 @@ export function prepareVariableTransfer(
variableIds: collection.variableIds.map((id) => mapped(references.variables, id, 'variable'))
})),
variables: variables.map((variable) => ({
...variable,
...structuredClone(variable),
id: mapped(references.variables, variable.id, 'variable'),
collectionId: mapped(references.collections, variable.collectionId, 'collection'),
valuesByMode: Object.fromEntries(

View file

@ -626,6 +626,37 @@ export type VariableType = 'COLOR' | 'FLOAT' | 'STRING' | 'BOOLEAN'
export type VariableValue = Color | number | string | boolean | { aliasId: string }
export type VariableModeMap = Record<string, string>
/** Property pickers a variable is offered in, as Figma names them. */
export const VARIABLE_SCOPES = [
'ALL_SCOPES',
'TEXT_CONTENT',
'CORNER_RADIUS',
'WIDTH_HEIGHT',
'GAP',
'ALL_FILLS',
'FRAME_FILL',
'SHAPE_FILL',
'TEXT_FILL',
'STROKE',
'STROKE_FLOAT',
'EFFECT_FLOAT',
'EFFECT_COLOR',
'OPACITY',
'FONT_STYLE',
'FONT_FAMILY',
'FONT_SIZE',
'LINE_HEIGHT',
'LETTER_SPACING',
'PARAGRAPH_SPACING',
'PARAGRAPH_INDENT',
'FONT_VARIATIONS',
'TRANSFORM'
] as const
export type VariableScope = (typeof VARIABLE_SCOPES)[number]
export const CODE_SYNTAX_PLATFORMS = ['WEB', 'ANDROID', 'iOS'] as const
export type CodeSyntaxPlatform = (typeof CODE_SYNTAX_PLATFORMS)[number]
export interface Variable {
id: string
name: string
@ -634,6 +665,11 @@ export interface Variable {
valuesByMode: Record<string, VariableValue>
description: string
hiddenFromPublishing: boolean
/** Absent means every scope. */
scopes?: VariableScope[]
/** Per-platform code name; `WEB` is the CSS custom property. */
codeSyntax?: Partial<Record<CodeSyntaxPlatform, string>>
pluginData?: PluginDataEntry[]
/** Published library key (from NodeChange.key). Used for assetRef resolution in colorVar. */
key?: string
/** Published library version (from NodeChange.version). Used for assetRef resolution in colorVar. */
@ -653,7 +689,9 @@ export interface VariableCollectionMode {
export interface VariableCollection {
id: string
name: string
/** The default mode comes first, as in Figma. */
modes: VariableCollectionMode[]
defaultModeId: string
variableIds: string[]
pluginData?: PluginDataEntry[]
}

View file

@ -1,3 +1,4 @@
import { partition } from 'es-toolkit/array'
import { omit, omitBy } from 'es-toolkit/object'
import { BLACK } from './constants'
@ -5,7 +6,13 @@ import type { SceneGraph } from './index'
import { setInstanceOverride } from './instance-overrides'
import { findInstanceAncestor } from './instances'
import type { Color } from './primitives'
import type { Variable, VariableCollection, VariableType, VariableValue } from './types'
import type {
Variable,
VariableCollection,
VariableCollectionMode,
VariableType,
VariableValue
} from './types'
import {
isNumericVariableBindingField,
variableBindingOwner,
@ -199,6 +206,13 @@ export function setDefaultMode(graph: SceneGraph, collectionId: string, modeId:
if (!collection) return
if (!collection.modes.some((m) => m.modeId === modeId)) return
collection.defaultModeId = modeId
collection.modes = modesDefaultFirst(collection)
}
/** Figma has no default-mode field: the first mode is the default. */
export function modesDefaultFirst(collection: VariableCollection): VariableCollectionMode[] {
const [defaults, rest] = partition(collection.modes, (m) => m.modeId === collection.defaultModeId)
return [...defaults, ...rest]
}
export function resolveVariable(

View file

@ -373,12 +373,12 @@ describe('Figma Kiwi schema coverage', () => {
expect(
Object.fromEntries([...buckets].map(([bucket, items]) => [bucket, items.length]))
).toEqual({
modeled: 117,
modeled: 121,
schemaTag: 60,
internalBookkeeping: 17,
rawPreserved: 48,
styleLibraryMetadata: 39,
componentInstanceMetadata: 33,
rawPreserved: 46,
styleLibraryMetadata: 38,
componentInstanceMetadata: 32,
textMetadata: 23,
slideFigjamMetadata: 39,
visualGeometryMetadata: 38,