diff --git a/CHANGELOG.md b/CHANGELOG.md index df730ac29..2449a4f52 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/packages/core/src/editor/variables.ts b/packages/core/src/editor/variables.ts index 1e1060eb7..d683f8c3c 100644 --- a/packages/core/src/editor/variables.ts +++ b/packages/core/src/editor/variables.ts @@ -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() } }) diff --git a/packages/core/src/io/formats/fig/variable-export.ts b/packages/core/src/io/formats/fig/variable-export.ts index 7626f3394..8361fa279 100644 --- a/packages/core/src/io/formats/fig/variable-export.ts +++ b/packages/core/src/io/formats/fig/variable-export.ts @@ -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 }) diff --git a/packages/core/tests/editor/undo/variable-modes.test.ts b/packages/core/tests/editor/undo/variable-modes.test.ts new file mode 100644 index 000000000..5fb7a0200 --- /dev/null +++ b/packages/core/tests/editor/undo/variable-modes.test.ts @@ -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']) + }) +}) diff --git a/packages/core/tests/io/formats/fig/roundtrip/variables.test.ts b/packages/core/tests/io/formats/fig/roundtrip/variables.test.ts index c1daa5be4..1770f2881 100644 --- a/packages/core/tests/io/formats/fig/roundtrip/variables.test.ts +++ b/packages/core/tests/io/formats/fig/roundtrip/variables.test.ts @@ -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 ) diff --git a/packages/fig/src/document/variables.ts b/packages/fig/src/document/variables.ts index f02e26ec9..9690790ee 100644 --- a/packages/fig/src/document/variables.ts +++ b/packages/fig/src/document/variables.ts @@ -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) }) } } diff --git a/packages/fig/src/node-change/index.ts b/packages/fig/src/node-change/index.ts index 525eb7db1..734b9754e 100644 --- a/packages/fig/src/node-change/index.ts +++ b/packages/fig/src/node-change/index.ts @@ -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' diff --git a/packages/fig/src/node-change/variable/metadata.ts b/packages/fig/src/node-change/variable/metadata.ts new file mode 100644 index 000000000..d5c705fc6 --- /dev/null +++ b/packages/fig/src/node-change/variable/metadata.ts @@ -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 { + const codeSyntax = Object.entries(variable.codeSyntax ?? {}).flatMap(([platform, value]) => + value ? [{ platform, value }] : [] + ) + const nc: Partial = { + 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 +} diff --git a/packages/kiwi/src/fig/codec.ts b/packages/kiwi/src/fig/codec.ts index 6c203b170..6dfbadb38 100644 --- a/packages/kiwi/src/fig/codec.ts +++ b/packages/kiwi/src/fig/codec.ts @@ -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[] diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts index 53b7e9351..30b86e355 100644 --- a/packages/scene-graph/src/index.ts +++ b/packages/scene-graph/src/index.ts @@ -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' diff --git a/packages/scene-graph/src/transfer/variables.ts b/packages/scene-graph/src/transfer/variables.ts index ce2e2c15c..3e97e8b1b 100644 --- a/packages/scene-graph/src/transfer/variables.ts +++ b/packages/scene-graph/src/transfer/variables.ts @@ -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( diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts index 5bcee959d..69971b6bc 100644 --- a/packages/scene-graph/src/types.ts +++ b/packages/scene-graph/src/types.ts @@ -626,6 +626,37 @@ export type VariableType = 'COLOR' | 'FLOAT' | 'STRING' | 'BOOLEAN' export type VariableValue = Color | number | string | boolean | { aliasId: string } export type VariableModeMap = Record +/** 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 description: string hiddenFromPublishing: boolean + /** Absent means every scope. */ + scopes?: VariableScope[] + /** Per-platform code name; `WEB` is the CSS custom property. */ + codeSyntax?: Partial> + 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[] } diff --git a/packages/scene-graph/src/variables.ts b/packages/scene-graph/src/variables.ts index 3ed11d461..b91ea2e21 100644 --- a/packages/scene-graph/src/variables.ts +++ b/packages/scene-graph/src/variables.ts @@ -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( diff --git a/tests/engine/io/fig/import/schema-coverage.test.ts b/tests/engine/io/fig/import/schema-coverage.test.ts index 38c2d54ba..1c7bf0a62 100644 --- a/tests/engine/io/fig/import/schema-coverage.test.ts +++ b/tests/engine/io/fig/import/schema-coverage.test.ts @@ -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,