Skip to content

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

fix(fig): write only the fields an edit changed into an opened .fig (#1103)

Danila Poyarkov4d5894b940cd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f8d875bf8..bd4db1f73 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,10 @@
- `computeImageHash` from `@open-pencil/core` and `@open-pencil/scene-graph` returns the hex SHA-1 of the bytes, the name Figma gives an image, instead of an OpenPencil-only hash of the same length. New images are stored under that name, so `.fig` files and the Figma clipboard carry it as it is; images in documents saved before keep their names.
+### Added
+
+- Drop design token files, `.tokens`, `.tokens.json`, or `.resolver.json`, on the editor to import them into the document's variables, as the Variables dialog's Import button does.
+
### Changed
- Trackpads and mouse wheels pan and zoom the canvas as in Figma. A two-finger pan moves the canvas twice as far, up to 120 px per scroll event. A pinch zooms as far in the desktop app and Safari as in other browsers, where it zooms a little less than before. In the desktop app and Safari, a pinch over Preview's live controls or comment pins now zooms the canvas, where it did nothing. On Windows each mouse wheel notch pans 16 px instead of 100 px, and notches less than 50 ms apart pan up to 120 px each.
@@ -14,6 +18,9 @@
- Figma shows shader fills and images from older documents in `.fig` files OpenPencil writes: every image is stored under the SHA-1 of its bytes, the only name Figma reads, and a shader keeps its preset through `.fig` files and the Figma clipboard.
- HTML, Vue, and React exports name a JPEG, GIF, or WebP image fill by its own type in the data URL instead of calling every image PNG.
+- Saving an opened `.fig` file writes only what an edit changed in a layer or variable, and keeps the rest as Figma saved it. That includes data OpenPencil does not model, an instance's library link and saved overrides, and an edited text's letter spacing in percent and font names. Before, saving rewrote each edited layer whole. Importing design tokens or adding a mode also rewrote every layer and variable in the file that uses variable modes.
+- Variables that alias library variables still point at the library after a save, and a collection's modes keep their order in Figma.
+- Importing design tokens adds them to the file's own collections, never to a collection copied from a library, where Figma did not show them. A token collection named like a library's, such as Tokens in Preline UI files, becomes a new collection of the file.
### Performance
diff --git a/packages/core/src/io/formats/design-tokens/plan.ts b/packages/core/src/io/formats/design-tokens/plan.ts
index 4c133a3bd..bfc8e74ed 100644
--- a/packages/core/src/io/formats/design-tokens/plan.ts
+++ b/packages/core/src/io/formats/design-tokens/plan.ts
@@ -1,14 +1,15 @@
import { compact } from 'es-toolkit/array'
-import type {
- CodeSyntaxPlatform,
- SceneGraph,
- TokenUnit,
- Variable,
- VariableCollection,
- VariableScope,
- VariableType,
- VariableValue
+import {
+ isLibraryCollection,
+ type CodeSyntaxPlatform,
+ type SceneGraph,
+ type TokenUnit,
+ type Variable,
+ type VariableCollection,
+ type VariableScope,
+ type VariableType,
+ type VariableValue
} from '@open-pencil/scene-graph'
import {
@@ -118,7 +119,10 @@ export function defaultTokenImportOptions(
graph: SceneGraph,
bundle: DesignTokenBundle
): TokenImportOptions {
- const existing = [...graph.variableCollections.values()]
+ // A library's collections belong to it, so tokens of the same name make one of the file's.
+ const existing = [...graph.variableCollections.values()].filter(
+ (collection) => !isLibraryCollection(collection)
+ )
const claimed = new Set<string>()
return {
collections: bundle.collections.map((collection): CollectionImportChoice => {
diff --git a/packages/core/src/io/formats/fig/export.ts b/packages/core/src/io/formats/fig/export.ts
index 05dc9265a..bba2e0cfe 100644
--- a/packages/core/src/io/formats/fig/export.ts
+++ b/packages/core/src/io/formats/fig/export.ts
@@ -23,7 +23,7 @@ import {
type FigExportSetup,
type KiwiNodeChange
} from '#core/io/formats/fig/export-setup'
-import { archiveImagesNamedForFigma, writePatchedFigFile } from '#core/io/formats/fig/patch-export'
+import { archiveImagesNamedForFigma, writePatchedFigFile } from '#core/io/formats/fig/patch/export'
import { sceneNodeToKiwi } from '#core/kiwi/fig/node-change/serialize'
import { cloneSceneGraphForFigExport } from '#core/kiwi/fig/parse/transfer'
import {
diff --git a/packages/core/src/io/formats/fig/patch-export.ts b/packages/core/src/io/formats/fig/patch/export.ts
similarity index 91%
rename from packages/core/src/io/formats/fig/patch-export.ts
rename to packages/core/src/io/formats/fig/patch/export.ts
index 1003350d8..c1e16a0db 100644
--- a/packages/core/src/io/formats/fig/patch-export.ts
+++ b/packages/core/src/io/formats/fig/patch/export.ts
@@ -24,6 +24,7 @@ import {
type FigExportSetup,
type KiwiNodeChange
} from '#core/io/formats/fig/export-setup'
+import { appendVariableNodeChanges } from '#core/io/formats/fig/variable-export'
import { sceneNodeToKiwi } from '#core/kiwi/fig/node-change/serialize'
import { figArchive, type FigArchiveAccess } from '#core/kiwi/fig/session/archive'
import { archiveChanges, type ArchiveChangeSummary } from '#core/kiwi/fig/session/archive-changes'
@@ -33,7 +34,7 @@ import {
readerCheckpoint
} from '#core/kiwi/fig/session/document-state'
-import { appendVariableNodeChanges } from './variable-export'
+import { narrowToChangedFields, type RecordWriter } from './fields'
export interface PatchedFigFileOptions {
ck?: CanvasKit
@@ -306,6 +307,31 @@ function variableRecords(setup: FigExportSetup, archiveInternalCanvas: boolean):
return records
}
+/** The document record, under the archive's GUID for it. */
+function documentRecord(setup: FigExportSetup, info: FigArchiveRecordInfo): KiwiNodeChange {
+ const guid = info.documentId ? stringToGuid(info.documentId) : setup.docGuid
+ return { ...setup.documentNc, guid }
+}
+
+/**
+ * Writes an untouched copy's records as the patch writes the document's: each layer at the
+ * position the archive saved, the document record, and every variable.
+ */
+function baselineWriter(info: FigArchiveRecordInfo): RecordWriter {
+ return (graph, setup, records) => {
+ const orderKeys = new Map<string, string>()
+ for (const id of records) {
+ const orderKey = graph.getNode(id)?.source.orderKey
+ if (orderKey) orderKeys.set(id, orderKey)
+ }
+ const plan = { records: new Set(records), orderKeys, removed: [], replaceVariables: false }
+ const written = writeRecords(setup, plan)
+ if (!written) return null
+ const internalPage = graph.getPages(true).find((page) => page.internalOnly)
+ return [documentRecord(setup, info), ...written, ...variableRecords(setup, !!internalPage)]
+ }
+}
+
async function buildPatch(
source: SceneGraph,
runtime: FigNodeChangeExportRuntime,
@@ -326,10 +352,8 @@ async function buildPatch(
const records = writeRecords(setup, plan)
if (!records) return null
// The document's own fields, its plugin data among them, are written on the document record.
- if (changes.documentChanged || changes.touched.has(graph.rootId)) {
- const guid = info.documentId ? stringToGuid(info.documentId) : setup.docGuid
- records.unshift({ ...setup.documentNc, guid })
- }
+ if (changes.documentChanged || changes.touched.has(graph.rootId))
+ records.unshift(documentRecord(setup, info))
if (plan.replaceVariables) {
const internalPage = graph.getPages(true).find((page) => page.internalOnly)
const internal = setup.canvasEntries.find((entry) => entry.page.internalOnly)
@@ -337,10 +361,19 @@ async function buildPatch(
for (const record of variableRecords(setup, !!internalPage || canvasWritten))
records.push(record)
}
+ const narrowed = await narrowToChangedFields(
+ graph,
+ runtime,
+ info,
+ archived.byGuid,
+ records,
+ baselineWriter(info)
+ )
return {
graph,
patch: {
- records,
+ records: narrowed.records,
+ fields: narrowed.fields,
blobs: setup.blobs.slice(info.blobCount),
removed: plan.removed,
replaceVariables: plan.replaceVariables
diff --git a/packages/core/src/io/formats/fig/patch/fields.ts b/packages/core/src/io/formats/fig/patch/fields.ts
new file mode 100644
index 000000000..1daa2eb55
--- /dev/null
+++ b/packages/core/src/io/formats/fig/patch/fields.ts
@@ -0,0 +1,214 @@
+import { uniq } from 'es-toolkit/array'
+import { isEqual } from 'es-toolkit/predicate'
+
+import {
+ entryPathKey,
+ type FigArchiveRecordInfo,
+ type FigEntryListPatch,
+ type FigRecordFieldPatch
+} from '@open-pencil/fig'
+import { derivedSymbolDataOf, symbolDataOf } from '@open-pencil/fig/instance-overrides'
+import type { FigNodeChangeExportRuntime } from '@open-pencil/fig/node-change'
+import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+import { prepareFigExport, type FigExportSetup } from '#core/io/formats/fig/export-setup'
+import { cloneSceneGraphForFigExport } from '#core/kiwi/fig/parse/transfer'
+import { archiveBaseline, type ArchiveBaseline } from '#core/kiwi/fig/session/archive-changes'
+
+/** Writes the records of these layers, as the patch writes the document's. */
+export type RecordWriter = (
+ graph: SceneGraph,
+ setup: FigExportSetup,
+ records: ReadonlySet<string>
+) => NodeChange[] | null
+
+const VARIABLE_TYPES = new Set(['VARIABLE', 'VARIABLE_SET'])
+
+/**
+ * The document as the archive holds it, for the pages that have loaded: a copy with the layers
+ * edits changed as they were, without the layers added since, and with the variables it opened
+ * with. It shares the rest with the document, which it does not write to.
+ */
+function archivedGraph(source: SceneGraph, baseline: ArchiveBaseline): SceneGraph {
+ const graph = cloneSceneGraphForFigExport(source)
+ for (const id of baseline.created) graph.nodes.delete(id)
+ for (const [id, node] of baseline.before) graph.nodes.set(id, structuredClone(node))
+ graph.instanceIndex = new Map()
+ for (const node of graph.nodes.values()) {
+ if (node.type !== 'INSTANCE' || !node.componentId) continue
+ const instances = graph.instanceIndex.get(node.componentId) ?? new Set<string>()
+ instances.add(node.id)
+ graph.instanceIndex.set(node.componentId, instances)
+ }
+ graph.variables = new Map(
+ [...baseline.variables].map(([id, variable]) => [id, structuredClone(variable)])
+ )
+ graph.variableCollections = new Map(structuredClone(baseline.collections.collections))
+ graph.activeMode = new Map(baseline.collections.activeMode)
+ return graph
+}
+
+/** The records the archived document writes, by GUID, for the records of these layers. */
+async function baselineRecords(
+ source: SceneGraph,
+ runtime: FigNodeChangeExportRuntime,
+ info: FigArchiveRecordInfo,
+ recordOwners: ReadonlyMap<string, string>,
+ guids: ReadonlySet<string>,
+ write: RecordWriter
+): Promise<Map<string, NodeChange> | null> {
+ const baseline = archiveBaseline(source)
+ if (!baseline) return null
+ const graph = archivedGraph(source, baseline)
+ const setup = await prepareFigExport(graph, runtime, {
+ nextLocalId: info.nextLocalId,
+ blobs: Array.from({ length: info.blobCount }, () => new Uint8Array(0)),
+ recordOwners,
+ archiveRecordIds: info.recordIds
+ })
+ // A layer loaded after an edit has no state before it to compare with, so it is written whole.
+ const ids = new Set(
+ [...guids].flatMap((guid) => {
+ const id = recordOwners.get(guid)
+ return id && graph.nodes.has(id) && !baseline.loadedAfterEdits.has(id) ? [id] : []
+ })
+ )
+ const records = write(graph, setup, ids)
+ if (!records) return null
+ return new Map(
+ records.flatMap((record) => (record.guid ? [[guidToString(record.guid), record]] : []))
+ )
+}
+
+interface PathEntry {
+ guidPath?: { guids?: GUID[] }
+}
+
+/**
+ * What changed between two lists of entries addressed by layer path, or undefined when nothing
+ * did. A list naming one path twice cannot be matched entry by entry, which `null` reports.
+ */
+function entryListPatch(
+ before: readonly PathEntry[],
+ after: readonly PathEntry[]
+): FigEntryListPatch | null | undefined {
+ const saved = new Map(before.map((entry) => [entryPathKey(entry.guidPath?.guids), entry]))
+ const current = new Map(after.map((entry) => [entryPathKey(entry.guidPath?.guids), entry]))
+ if (saved.size !== before.length || current.size !== after.length) return null
+ const entries: FigEntryListPatch['entries'] = []
+ for (const [key, entry] of current) {
+ const { guidPath, ...fields } = entry as PathEntry & Record<string, unknown>
+ const previous = saved.get(key) as (PathEntry & Record<string, unknown>) | undefined
+ const set = Object.fromEntries(
+ Object.entries(fields).filter(([field, value]) => !isEqual(previous?.[field], value))
+ )
+ const unset = previous
+ ? Object.keys(previous).filter((field) => field !== 'guidPath' && !(field in fields))
+ : []
+ if (Object.keys(set).length > 0 || unset.length > 0)
+ entries.push({ path: guidPath?.guids ?? [], set, unset })
+ }
+ const removed = [...saved].flatMap(([key, entry]) =>
+ current.has(key) ? [] : [entry.guidPath?.guids ?? []]
+ )
+ return entries.length > 0 || removed.length > 0 ? { entries, removed } : undefined
+}
+
+/**
+ * Whether `field` is one of an instance's lists addressed by layer path, compared entry by
+ * entry into `patch`. A list that cannot be, or overrides whose component changed, are not.
+ */
+function patchEntryList(
+ field: string,
+ saved: NodeChange,
+ record: NodeChange,
+ patch: FigRecordFieldPatch
+): boolean {
+ if (field === 'symbolData') {
+ const before = symbolDataOf(saved)
+ const after = symbolDataOf(record)
+ if (!before || !after) return false
+ const { symbolOverrides: savedOverrides = [], ...savedRest } = before
+ const { symbolOverrides: overrides = [], ...rest } = after
+ if (!isEqual(savedRest, rest)) return false
+ const changed = entryListPatch(savedOverrides, overrides)
+ if (changed === null) return false
+ if (changed) patch.symbolOverrides = changed
+ return true
+ }
+ if (field === 'derivedSymbolData' && saved.derivedSymbolData && record.derivedSymbolData) {
+ const changed = entryListPatch(derivedSymbolDataOf(saved), derivedSymbolDataOf(record))
+ if (changed === null) return false
+ if (changed) patch.derivedSymbolData = changed
+ return true
+ }
+ return false
+}
+
+/**
+ * The fields of `record` that differ from the `saved` one, or null when none does. An
+ * instance's overrides and derived values are compared entry by entry, so an edit to one layer
+ * leaves the entries of the others as the archive saved them.
+ */
+function changedFields(saved: NodeChange, record: NodeChange): FigRecordFieldPatch | null {
+ if (!record.guid) return null
+ const set: Partial<NodeChange> = {}
+ const unset: string[] = []
+ const patch: FigRecordFieldPatch = { guid: record.guid, set, unset }
+ for (const field of uniq([...Object.keys(saved), ...Object.keys(record)])) {
+ if (!(field in record)) unset.push(field)
+ else if (isEqual(saved[field], record[field])) continue
+ else if (!patchEntryList(field, saved, record, patch))
+ Object.assign(set, { [field]: record[field] })
+ }
+ const changed =
+ Object.keys(set).length > 0 ||
+ unset.length > 0 ||
+ patch.symbolOverrides ||
+ patch.derivedSymbolData
+ return changed ? patch : null
+}
+
+/**
+ * Narrow written records the archive holds to the fields the edits changed in them. Each is
+ * compared with the record the document as the archive holds it writes, so a field differs only
+ * where the document does, and the rest of the record, fields OpenPencil does not model among
+ * them, stays as the archive saved it. A record whose untouched copy is unavailable is written
+ * whole, as before.
+ */
+export async function narrowToChangedFields(
+ source: SceneGraph,
+ runtime: FigNodeChangeExportRuntime,
+ info: FigArchiveRecordInfo,
+ recordOwners: ReadonlyMap<string, string>,
+ written: readonly NodeChange[],
+ write: RecordWriter
+): Promise<{ records: NodeChange[]; fields: FigRecordFieldPatch[] }> {
+ const archived = new Set(info.recordIds)
+ const guids = new Set(
+ written.flatMap((record) => {
+ const id = record.guid ? guidToString(record.guid) : null
+ return id && archived.has(id) ? [id] : []
+ })
+ )
+ const baseline =
+ guids.size > 0 ? await baselineRecords(source, runtime, info, recordOwners, guids, write) : null
+ const records: NodeChange[] = []
+ const fields: FigRecordFieldPatch[] = []
+ for (const record of written) {
+ const id = record.guid ? guidToString(record.guid) : null
+ const saved = id ? baseline?.get(id) : undefined
+ if (!saved || !record.guid) {
+ records.push(record)
+ continue
+ }
+ const changed = changedFields(saved, record)
+ if (changed) fields.push(changed)
+ // A variable the patch leaves out is dropped when variables are replaced, so it stays listed.
+ else if (record.type && VARIABLE_TYPES.has(record.type))
+ fields.push({ guid: record.guid, set: {}, unset: [] })
+ }
+ return { records, fields }
+}
diff --git a/packages/core/src/io/formats/fig/variable-export.ts b/packages/core/src/io/formats/fig/variable-export.ts
index 9ea652a16..edd3d74a8 100644
--- a/packages/core/src/io/formats/fig/variable-export.ts
+++ b/packages/core/src/io/formats/fig/variable-export.ts
@@ -1,6 +1,7 @@
import {
collectionPluginDataNodeChange,
parseGuidOrNull,
+ variableAlias,
variableMetadataNodeChange
} from '@open-pencil/fig/node-change'
import type { GUID, NodeChange, VariableDataEntry } from '@open-pencil/kiwi/fig/codec'
@@ -9,9 +10,10 @@ import {
modesDefaultFirst,
type SceneGraph,
type SceneNode,
+ type VariableCollectionMode,
type VariableValue
} from '@open-pencil/scene-graph'
-import { fractionalPosition } from '@open-pencil/scene-graph/order-keys'
+import { fractionalPosition, orderKeyBetween } from '@open-pencil/scene-graph/order-keys'
import { safeColor } from '#core/kiwi/fig/node-change/serialize'
@@ -83,6 +85,25 @@ export function assignVariableGuids(
}
}
+/**
+ * Where Figma lists each mode: where the file saved it, and a new mode after the rest. A
+ * collection made in OpenPencil lists its modes in their order.
+ */
+function modeSortPositions(modes: readonly VariableCollectionMode[]) {
+ if (modes.every((mode) => !mode.sortPosition))
+ return modes.map((mode, index) => ({ mode, sortPosition: fractionalPosition(index) }))
+ let last = modes.reduce<string | null>(
+ (highest, mode) =>
+ mode.sortPosition && (!highest || mode.sortPosition > highest) ? mode.sortPosition : highest,
+ null
+ )
+ return modes.map((mode) => {
+ if (mode.sortPosition) return { mode, sortPosition: mode.sortPosition }
+ last = orderKeyBetween(last, null)
+ return { mode, sortPosition: last }
+ })
+}
+
/**
* Shared styles live on the internal canvas and need a GUID before any node cites them. A style
* read from Figma keeps the GUID it came with, which its ID spells; the others take new ones.
@@ -113,13 +134,14 @@ export function assignSharedStyleGuids(
}
function variableValueToKiwi(
+ graph: SceneGraph,
value: VariableValue,
type: string,
ids: Map<string, GUID>
): VariableDataEntry {
if (typeof value === 'object' && 'aliasId' in value)
return {
- value: { alias: { guid: ids.get(value.aliasId) ?? stringToGuid(value.aliasId) } },
+ value: { alias: variableAlias(graph, value.aliasId, ids) },
dataType: 'ALIAS',
resolvedDataType: type
}
@@ -165,12 +187,15 @@ export function appendVariableNodeChanges(
phase: 'CREATED',
strokeAlign: 'CENTER',
strokeJoin: 'BEVEL',
- variableSetModes: modesDefaultFirst(collection).map((mode, i) => ({
- id: modes.get(mode.modeId) ?? stringToGuid(mode.modeId),
- name: mode.name,
- sortPosition: fractionalPosition(i)
- })),
- pluginData: collectionPluginDataNodeChange(collection, modeKey)
+ variableSetModes: modeSortPositions(modesDefaultFirst(collection)).map(
+ ({ mode, sortPosition }) => ({
+ id: modes.get(mode.modeId) ?? stringToGuid(mode.modeId),
+ name: mode.name,
+ sortPosition
+ })
+ ),
+ pluginData: collectionPluginDataNodeChange(collection, modeKey),
+ key: collection.key
})
for (const id of collection.variableIds) {
const variable = graph.variables.get(id)
@@ -188,7 +213,7 @@ export function appendVariableNodeChanges(
variableDataValues: {
entries: Object.entries(variable.valuesByMode).map(([mode, value]) => ({
modeID: modes.get(mode) ?? stringToGuid(mode),
- variableData: variableValueToKiwi(value, variable.type, ids)
+ variableData: variableValueToKiwi(graph, value, variable.type, ids)
}))
},
...variableMetadataNodeChange(variable, modeKey),
diff --git a/packages/core/src/kiwi/fig/session/archive-changes.ts b/packages/core/src/kiwi/fig/session/archive-changes.ts
index ae1dc7a8b..42a28b6e6 100644
--- a/packages/core/src/kiwi/fig/session/archive-changes.ts
+++ b/packages/core/src/kiwi/fig/session/archive-changes.ts
@@ -1,6 +1,6 @@
import { isEqual } from 'es-toolkit/predicate'
-import type { SceneGraph } from '@open-pencil/scene-graph'
+import type { SceneGraph, SceneNode, Variable, VariableCollection } from '@open-pencil/scene-graph'
/**
* How a document opened from a `.fig` archive has diverged from it, for writing only what
@@ -10,13 +10,28 @@ import type { SceneGraph } from '@open-pencil/scene-graph'
*/
interface ArchiveChanges {
touched: Set<string>
+ /** Layers an edit changed, as they were before it: the archive's state of them. */
+ before: Map<string, SceneNode>
+ /** Layers added since the archive opened, which it does not hold. */
+ created: Set<string>
+ /**
+ * Layers loaded from the archive after an edit, so the edit may already show in them, as in
+ * instances of an edited component: their state before it is unknown.
+ */
+ loadedAfterEdits: Set<string>
/** The variables, collections and modes the archive holds. */
resourceIds: Set<string>
- variables: Map<string, unknown>
- collections: unknown
+ variables: Map<string, Variable>
+ collections: CollectionsSnapshot
settings: unknown
}
+/** The variable collections and the modes the document shows them in. */
+interface CollectionsSnapshot {
+ collections: Array<[string, VariableCollection]>
+ activeMode: Array<[string, string]>
+}
+
const changes = new WeakMap<SceneGraph, ArchiveChanges>()
function settingsSnapshot(graph: SceneGraph): unknown {
@@ -26,7 +41,7 @@ function settingsSnapshot(graph: SceneGraph): unknown {
})
}
-function collectionsSnapshot(graph: SceneGraph): unknown {
+function collectionsSnapshot(graph: SceneGraph): CollectionsSnapshot {
return structuredClone({
collections: [...graph.variableCollections],
activeMode: [...graph.activeMode]
@@ -45,6 +60,9 @@ function resourceIdsOf(graph: SceneGraph): Set<string> {
export function trackArchiveChanges(graph: SceneGraph): void {
const entry: ArchiveChanges = {
touched: new Set(),
+ before: new Map(),
+ created: new Set(),
+ loadedAfterEdits: new Set(),
resourceIds: resourceIdsOf(graph),
variables: new Map(
[...graph.variables].map(([id, variable]) => [id, structuredClone(variable)])
@@ -55,6 +73,17 @@ export function trackArchiveChanges(graph: SceneGraph): void {
const touch = (id: string) => {
if (!graph.isApplyingImportedState && !graph.isApplyingDerivedLayout) entry.touched.add(id)
}
+ const edits = () => !graph.isApplyingImportedState && !graph.isApplyingDerivedLayout
+ graph.observeNodeChanges({
+ before: (node) => {
+ if (!edits() || entry.created.has(node.id) || entry.before.has(node.id)) return
+ entry.before.set(node.id, structuredClone(node))
+ },
+ created: (node) => {
+ if (edits()) entry.created.add(node.id)
+ else if (entry.touched.size > 0) entry.loadedAfterEdits.add(node.id)
+ }
+ })
graph.onNodeEvents({
created: (node) => touch(node.id),
updated: touch,
@@ -97,3 +126,27 @@ export function archiveChanges(graph: SceneGraph): ArchiveChangeSummary | undefi
documentChanged: !isEqual(entry.settings, settingsSnapshot(graph))
}
}
+
+/** The document as the archive holds it, for the layers that have loaded. */
+export interface ArchiveBaseline {
+ /** Layers edits changed, as they were before. */
+ before: ReadonlyMap<string, SceneNode>
+ /** Layers added since, which the archive does not hold. */
+ created: ReadonlySet<string>
+ /** Layers loaded after an edit, whose state before it is unknown. */
+ loadedAfterEdits: ReadonlySet<string>
+ variables: ReadonlyMap<string, Variable>
+ collections: CollectionsSnapshot
+}
+
+export function archiveBaseline(graph: SceneGraph): ArchiveBaseline | undefined {
+ const entry = changes.get(graph)
+ if (!entry) return undefined
+ return {
+ before: entry.before,
+ created: entry.created,
+ loadedAfterEdits: entry.loadedAfterEdits,
+ variables: entry.variables,
+ collections: entry.collections
+ }
+}
diff --git a/packages/core/tests/io/formats/design-tokens/import.test.ts b/packages/core/tests/io/formats/design-tokens/import.test.ts
index cd4acf480..4c70e8cf7 100644
--- a/packages/core/tests/io/formats/design-tokens/import.test.ts
+++ b/packages/core/tests/io/formats/design-tokens/import.test.ts
@@ -115,6 +115,25 @@ describe('reading token files', () => {
})
describe('planning an import', () => {
+ test("tokens named like a library's collection make one of the file's own", () => {
+ const graph = new SceneGraph()
+ const library = graph.createCollection('Tokens')
+ library.key = 'bf3948d3'
+ const own = graph.createCollection('Spacing')
+ const bundle = readDesignTokens(
+ files({
+ 'Tokens/Default.tokens.json': { color: { $type: 'color', brand: { $value: '#2563eb' } } },
+ 'Spacing/Default.tokens.json': {
+ gap: { $type: 'dimension', $value: { value: 4, unit: 'px' } }
+ }
+ })
+ )
+
+ const [tokens, spacing] = defaultTokenImportOptions(graph, bundle).collections
+ expect(tokens.target).toEqual({ kind: 'new', name: 'Tokens' })
+ expect(spacing.target).toEqual({ kind: 'existing', collectionId: own.id })
+ })
+
test('values from other tools convert into canvas units and sRGB', () => {
const { plan: result } = plan(
files({
diff --git a/packages/core/tests/io/formats/fig/export/archive-patch.test.ts b/packages/core/tests/io/formats/fig/patch/export.test.ts
similarity index 100%
rename from packages/core/tests/io/formats/fig/export/archive-patch.test.ts
rename to packages/core/tests/io/formats/fig/patch/export.test.ts
diff --git a/packages/core/tests/io/formats/fig/patch/fields.test.ts b/packages/core/tests/io/formats/fig/patch/fields.test.ts
new file mode 100644
index 000000000..53a3c8a57
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/patch/fields.test.ts
@@ -0,0 +1,112 @@
+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 { isEqual } from 'es-toolkit/predicate'
+
+import { createEditor } from '@open-pencil/core/editor'
+import { exportFigFile, parseFigFile } from '@open-pencil/core/io'
+import { initCodec } from '@open-pencil/core/kiwi'
+import { parseFigBuffer } from '@open-pencil/fig'
+import { symbolOverridesOf } from '@open-pencil/fig/instance-overrides'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+setDefaultTimeout(120_000)
+
+beforeAll(async () => {
+ await initCodec()
+})
+
+function recordsOf(bytes: ArrayBuffer | Uint8Array) {
+ const buffer = bytes instanceof Uint8Array ? bytes.slice().buffer : bytes
+ const { nodeChanges } = parseFigBuffer(buffer as ArrayBuffer)
+ return new Map(
+ nodeChanges.flatMap((record) => (record.guid ? [[guidToString(record.guid), record]] : []))
+ )
+}
+
+/** The records of `after` that differ from `before`, with the fields that do. */
+function changes(before: Map<string, NodeChange>, after: Map<string, NodeChange>) {
+ const result = new Map<string, string[]>()
+ for (const [guid, record] of after) {
+ const saved = before.get(guid)
+ if (!saved) continue
+ const keys = uniq([...Object.keys(saved), ...Object.keys(record)])
+ const fields = keys.filter((field) => !isEqual(saved[field], record[field]))
+ if (fields.length > 0) result.set(guid, fields)
+ }
+ return result
+}
+
+async function openGoldPreview(): Promise<{ bytes: ArrayBuffer; graph: SceneGraph }> {
+ const bytes = readFixtureArrayBuffer('gold-preview.fig')
+ return { bytes, graph: await parseFigFile(bytes.slice(0), { populate: 'first-page' }) }
+}
+
+test('an edit rewrites only the fields it changed, keeping those OpenPencil does not model', async () => {
+ const { bytes, graph } = await openGoldPreview()
+ const list = expectDefined([...graph.nodes.values()].find((node) => node.name === 'Checked List'))
+ const [instance] = graph.getChildren(list.id)
+ graph.updateNode(instance.id, { name: 'Lists renamed' })
+
+ const changed = changes(recordsOf(bytes), recordsOf(await exportFigFile(graph)))
+ // Figma's own fields, its library links, and the overrides it saved all stay.
+ expect([...changed.values()]).toEqual([['name']])
+})
+
+test('renaming an instance adds its name to the overrides Figma saved, and changes no other', async () => {
+ const { bytes, graph } = await openGoldPreview()
+ const list = expectDefined([...graph.nodes.values()].find((node) => node.name === 'Checked List'))
+ const [instance] = graph.getChildren(list.id)
+ const saved = recordsOf(bytes)
+ const listGuid = [...saved].find(([, record]) => record.name === 'Checked List')?.[0]
+ const [guid] = expectDefined(
+ [...saved]
+ .filter(([, record]) => record.type === 'INSTANCE' && record.parentIndex?.guid)
+ .filter(([, record]) => guidToString(expectDefined(record.parentIndex?.guid)) === listGuid)
+ .toSorted(([, a], [, b]) =>
+ (a.parentIndex?.position ?? '').localeCompare(b.parentIndex?.position ?? '')
+ )
+ .at(0)
+ )
+ createEditor({ graph }).updateNodeWithUndo(instance.id, { name: 'Lists renamed' }, 'Rename')
+
+ const before = expectDefined(saved.get(guid))
+ const after = expectDefined(recordsOf(await exportFigFile(graph)).get(guid))
+ type Override = [path: string, fields: object]
+ const overrides = (record: NodeChange): Override[] =>
+ symbolOverridesOf(record).map(({ guidPath, ...fields }) => [JSON.stringify(guidPath), fields])
+ // Figma shows an instance's own name from the override on its own path, beside its size.
+ const renamed = overrides(before).map(([path, fields]): Override =>
+ 'stackCounterSizing' in fields ? [path, { ...fields, name: 'Lists renamed' }] : [path, fields]
+ )
+ expect(overrides(after)).toEqual(renamed)
+})
+
+test('a mode added to a collection of library aliases keeps the file as Figma saved it', async () => {
+ const { bytes, graph } = await openGoldPreview()
+ const collection = expectDefined(
+ [...graph.variableCollections.values()].find((candidate) => candidate.name === 'Tokens')
+ )
+ graph.createMode(collection.id, 'Added')
+
+ const before = recordsOf(bytes)
+ const after = recordsOf(await exportFigFile(graph))
+ const changed = changes(before, after)
+ // Only the collection's modes and its variables' values change: no layer, and no variable's
+ // library identity.
+ expect(new Set([...changed.values()].flat())).toEqual(
+ new Set(['variableSetModes', 'variableDataValues'])
+ )
+ 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)
+ // 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 ?? []
+ for (const entry of entries) expect(entry.variableData?.value?.alias?.guid).toBeUndefined()
+ }
+})
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 c8ab4e5f7..2dc18f5c7 100644
--- a/packages/core/tests/io/formats/fig/roundtrip/variables.test.ts
+++ b/packages/core/tests/io/formats/fig/roundtrip/variables.test.ts
@@ -344,7 +344,8 @@ describe('variable roundtrip', () => {
codeSyntax: { WEB: 'var(--page-gutter)' },
expressions: { '4:7': { css: 'clamp(1rem, 4vw, 2rem)', resolved: 16 } }
})
- expect(reimported.variableCollections.get('4:70')?.modes).toEqual([
+ // Modes also come back with the places the file saved for them.
+ expect(reimported.variableCollections.get('4:70')?.modes).toMatchObject([
{ modeId: '4:7', name: 'Light', condition: undefined },
{ modeId: '4:8', name: 'Dark', condition: '[data-theme="dark"]' }
])
diff --git a/packages/fig/AGENTS.md b/packages/fig/AGENTS.md
index e484b0b33..4bc79bdb1 100644
--- a/packages/fig/AGENTS.md
+++ b/packages/fig/AGENTS.md
@@ -6,7 +6,7 @@
- Figma clipboard envelope encoding, decoding, and bounds belong to `@open-pencil/fig/clipboard`; converting those records to a SceneGraph is `materializeFigFragment` in `packages/fig/src/document/fragment.ts`, which Core drives from `packages/core/src/clipboard/fig-import.ts`. Core prepares runtime fonts and text and owns editor placement and history; browser and Tauri adapters own system clipboard I/O. Do not add platform clipboard APIs here.
- One reader serves every `.fig` path — parse, worker, page population, session recovery, export, and paste — through the document sessions in `packages/fig/src/document/`. Read what it could not resolve with `readerDiagnostics(graph)` from `packages/core/src/kiwi/fig/session/document-state.ts`; do not add a second import path.
- Browser `.fig` export uses fflate and `@open-pencil/fig`; Tauri uses `build_fig_file` in `desktop/`.
-- Saving a document opened from a `.fig` rewrites only the records its edits changed and copies the rest from the archive as bytes (`packages/core/src/io/formats/fig/patch-export.ts`, `patchFigMessage` in `packages/fig/src/record-patch.ts`); the full export remains for documents with no archive. A change is what the archive tracker sees outside page loads and outside `applyDerivedLayoutDuring`, which wraps layout derived from the file or its fonts; layout an edit causes counts (`packages/core/tests/io/formats/fig/export/archive-patch.test.ts`).
+- Saving a document opened from a `.fig` writes only the fields its edits changed, merged into the archive's records, and copies the rest as bytes (`packages/core/src/io/formats/fig/patch/`, `patchFigMessage` in `packages/fig/src/record-patch/`); the full export remains for documents with no archive. A change is what the archive tracker sees outside page loads and outside `applyDerivedLayoutDuring`, which wraps layout derived from the file or its fonts; layout an edit causes counts, and the tracker keeps each edited layer as it was so the fields are found by comparing records (`packages/core/tests/io/formats/fig/patch/`).
- Vector networks use the reverse-engineered `vectorNetworkBlob`; codecs live under `packages/core/src/vector/` and types in Scene Graph.
- Changes to `.fig` behavior require round-trip validation in Figma. `packages/docs/development/roadmap.md` tracks raw metadata coverage and the code map for import/export mapping and schema files.
- Measure a reader change over a whole archive, not one frame: capture before and after with `visual-oracles compare digest --file F --out baseline.json` then `--baseline baseline.json`, and account for every node it reports. `compare interpreted-document` checks one frame against live Figma and will report no change while a rule breaks pages it does not cover.
diff --git a/packages/fig/src/document/variables.ts b/packages/fig/src/document/variables.ts
index d5aa4fc52..ee4e4d958 100644
--- a/packages/fig/src/document/variables.ts
+++ b/packages/fig/src/document/variables.ts
@@ -71,12 +71,18 @@ export function materializeVariableResources(
name: resource.name ?? 'Variables',
modes: modes.map((mode) => {
const modeId = guidToString(mode.id)
- return { modeId, name: mode.name, condition: conditions[modeId] }
+ return {
+ modeId,
+ name: mode.name,
+ condition: conditions[modeId],
+ ...(mode.sortPosition ? { sortPosition: mode.sortPosition } : {})
+ }
}),
defaultModeId: guidToString(modes[0].id),
variableIds: [],
modeAttribute: readModeAttribute(resource),
- pluginData: pluginData.length > 0 ? pluginData : undefined
+ pluginData: pluginData.length > 0 ? pluginData : undefined,
+ key: typeof resource.key === 'string' ? resource.key : undefined
})
}
addVariables(graph, resources, report)
diff --git a/packages/fig/src/index.ts b/packages/fig/src/index.ts
index c29d5dd30..22142f453 100644
--- a/packages/fig/src/index.ts
+++ b/packages/fig/src/index.ts
@@ -24,6 +24,10 @@ export {
patchFigRecords,
type FigArchiveRecordInfo,
type FigPatchedArchiveInput,
+ entryPathKey,
+ type FigEntryListPatch,
+ type FigEntryPatch,
+ type FigRecordFieldPatch,
type FigRecordPatch
} from './record-patch'
export {
diff --git a/packages/fig/src/instance-overrides/index.ts b/packages/fig/src/instance-overrides/index.ts
index 509257a12..d6f46fd32 100644
--- a/packages/fig/src/instance-overrides/index.ts
+++ b/packages/fig/src/instance-overrides/index.ts
@@ -11,7 +11,7 @@ export { linkInstanceSourceChildren, mapInstanceSourceChildren } from './source-
export type { MaterializedInstance } from './materialize-instance'
/** The Kiwi codec types only `symbolID`, so the remaining symbol fields are read through these. */
-export { symbolDataOf, symbolOverridesOf } from './types'
+export { derivedSymbolDataOf, symbolDataOf, symbolOverridesOf } from './types'
export type {
ComponentPropAssignment,
diff --git a/packages/fig/src/instance-overrides/types.ts b/packages/fig/src/instance-overrides/types.ts
index 620bc6e41..c9003e849 100644
--- a/packages/fig/src/instance-overrides/types.ts
+++ b/packages/fig/src/instance-overrides/types.ts
@@ -28,6 +28,11 @@ export function symbolOverridesOf(record: NodeChange): readonly SymbolOverride[]
return symbolDataOf(record)?.symbolOverrides ?? []
}
+/** The values an instance's record derives for its layers, by layer path. */
+export function derivedSymbolDataOf(record: NodeChange): readonly DerivedSymbolOverride[] {
+ return (record.derivedSymbolData as DerivedSymbolOverride[] | undefined) ?? []
+}
+
export function uniformScaleOf(record: NodeChange): number {
return symbolDataOf(record)?.uniformScaleFactor ?? 1
}
diff --git a/packages/fig/src/node-change/export/context.ts b/packages/fig/src/node-change/export/context.ts
index cd057f94b..5c169feb9 100644
--- a/packages/fig/src/node-change/export/context.ts
+++ b/packages/fig/src/node-change/export/context.ts
@@ -10,6 +10,8 @@ import type {
} from '@open-pencil/scene-graph'
import type { Color, GUID, Matrix } from '@open-pencil/scene-graph/primitives'
+import { variableAlias } from '../variable/bindings'
+
export type KiwiNodeChange = NodeChange & Record<string, unknown>
export interface KiwiSymbolOverridePayload {
@@ -252,7 +254,7 @@ export function applyColorVariableBinding(
colorVar: {
dataType: 'ALIAS',
resolvedDataType: 'COLOR',
- value: { alias: { guid: context.varIdToGuid?.get(variableId) ?? stringToGuid(variableId) } }
+ value: { alias: variableAlias(context.graph, variableId, context.varIdToGuid) }
}
}
}
diff --git a/packages/fig/src/node-change/variable/bindings.ts b/packages/fig/src/node-change/variable/bindings.ts
index 33c1a59ed..936977580 100644
--- a/packages/fig/src/node-change/variable/bindings.ts
+++ b/packages/fig/src/node-change/variable/bindings.ts
@@ -159,6 +159,24 @@ export function textRunVariableBindings(override: VariableConsumptionSource): Te
return bound
}
+/**
+ * How a record names a variable it uses, as Figma writes it: a library variable by its key,
+ * even where the file holds a copy of it, and a local one by its record.
+ */
+export function variableAlias(
+ graph: SceneGraph,
+ variableId: string,
+ ids?: ReadonlyMap<string, GUID>
+): { guid: GUID } | { assetRef: { key: string; version?: string } } {
+ const variable = graph.variables.get(variableId)
+ if (variable?.key) {
+ return {
+ assetRef: { key: variable.key, ...(variable.version ? { version: variable.version } : {}) }
+ }
+ }
+ return { guid: ids?.get(variableId) ?? stringToGuid(variableId) }
+}
+
function consumptionEntry(
variableField: string,
variableId: string | undefined,
@@ -174,7 +192,7 @@ function consumptionEntry(
const alias = {
dataType: 'ALIAS',
resolvedDataType: variable.type,
- value: { alias: { guid: ids?.get(variableId) ?? stringToGuid(variableId) } }
+ value: { alias: variableAlias(graph, variableId, ids) }
}
if (variable.type !== 'FLOAT' || (!expression && multiplier === 1))
return { variableField, variableData: alias }
diff --git a/packages/fig/src/node-change/variable/metadata.ts b/packages/fig/src/node-change/variable/metadata.ts
index 99f899a15..2d5b29ff2 100644
--- a/packages/fig/src/node-change/variable/metadata.ts
+++ b/packages/fig/src/node-change/variable/metadata.ts
@@ -19,7 +19,13 @@ import {
type VariableMetadata = Pick<
Variable,
- 'description' | 'hiddenFromPublishing' | 'scopes' | 'codeSyntax' | 'pluginData'
+ | 'description'
+ | 'hiddenFromPublishing'
+ | 'scopes'
+ | 'codeSyntax'
+ | 'pluginData'
+ | 'key'
+ | 'version'
>
type ModeKey = (modeId: string) => string
@@ -41,13 +47,17 @@ function readCodeSyntax(nc: NodeChange): Variable['codeSyntax'] {
export function readVariableMetadata(nc: NodeChange): VariableMetadata {
const scopes = nc.variableScopes?.filter(isScope)
const pluginData = withoutTokenPluginData(extractPluginData(nc))
- return {
+ const metadata: VariableMetadata = {
description: nc.description ?? nc.symbolDescription ?? '',
hiddenFromPublishing: nc.isPublishable === false,
scopes: scopes?.length ? scopes : undefined,
codeSyntax: readCodeSyntax(nc),
pluginData: pluginData.length > 0 ? pluginData : undefined
}
+ // A library variable's identity, which records naming it use in place of its GUID.
+ if (typeof nc.key === 'string') metadata.key = nc.key
+ if (typeof nc.version === 'string') metadata.version = nc.version
+ return metadata
}
export function variableMetadataNodeChange(
diff --git a/packages/fig/src/record-patch/fields.ts b/packages/fig/src/record-patch/fields.ts
new file mode 100644
index 000000000..890b57f6d
--- /dev/null
+++ b/packages/fig/src/record-patch/fields.ts
@@ -0,0 +1,88 @@
+import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+
+import { derivedSymbolDataOf, symbolDataOf, type SymbolData } from '../instance-overrides/types'
+
+/** One entry of a list addressed by layer path: the fields an edit set on it and dropped. */
+export interface FigEntryPatch {
+ path: GUID[]
+ set: Record<string, unknown>
+ unset: string[]
+}
+
+/** What an edit changed in a list of entries addressed by layer path. */
+export interface FigEntryListPatch {
+ /** Entries changed or added, by path. */
+ entries: FigEntryPatch[]
+ /** Paths whose entries are gone. */
+ removed: GUID[][]
+}
+
+/**
+ * Fields an edit changed in a record the archive holds. The rest of the record stays as the
+ * archive saved it, fields OpenPencil does not model included.
+ */
+export interface FigRecordFieldPatch {
+ guid: GUID
+ /** Fields written over the archive's. */
+ set: Partial<NodeChange>
+ /** Fields the record no longer has. */
+ unset: string[]
+ /**
+ * An instance's overrides and the values derived for its layers, changed entry by entry, so
+ * the entries an edit did not reach stay as Figma saved them.
+ */
+ symbolOverrides?: FigEntryListPatch
+ derivedSymbolData?: FigEntryListPatch
+}
+
+/** A layer path as a key, matching entries across lists. */
+export function entryPathKey(path: readonly GUID[] | undefined): string {
+ return (path ?? []).map(guidToString).join('/')
+}
+
+interface PathEntry {
+ guidPath?: { guids?: GUID[] }
+}
+
+/** `list` with the patch's entries merged in by path. */
+function patchedEntries<Entry extends PathEntry>(
+ list: readonly Entry[],
+ patch: FigEntryListPatch
+): Entry[] {
+ const removed = new Set(patch.removed.map(entryPathKey))
+ const result = list.filter((entry) => !removed.has(entryPathKey(entry.guidPath?.guids)))
+ const at = new Map(result.map((entry, index) => [entryPathKey(entry.guidPath?.guids), index]))
+ for (const change of patch.entries) {
+ const key = entryPathKey(change.path)
+ const index = at.get(key)
+ const merged: Record<string, unknown> = {
+ ...(index === undefined ? { guidPath: { guids: change.path } } : result[index]),
+ ...structuredClone(change.set)
+ }
+ for (const field of change.unset) Reflect.deleteProperty(merged, field)
+ if (index === undefined) {
+ at.set(key, result.length)
+ result.push(merged as Entry)
+ } else result[index] = merged as Entry
+ }
+ return result
+}
+
+/** An archive record with an edit's fields merged in. */
+export function patchedRecord(record: NodeChange, patch: FigRecordFieldPatch): NodeChange {
+ const merged: NodeChange = { ...record, ...structuredClone(patch.set) }
+ for (const field of patch.unset) Reflect.deleteProperty(merged, field)
+ const symbolData = symbolDataOf(merged)
+ if (patch.symbolOverrides && symbolData) {
+ const patched: SymbolData = {
+ ...symbolData,
+ symbolOverrides: patchedEntries(symbolData.symbolOverrides ?? [], patch.symbolOverrides)
+ }
+ // The Kiwi codec types only `symbolID`; the record keeps the rest of its symbol fields.
+ merged.symbolData = patched as NodeChange['symbolData']
+ }
+ if (patch.derivedSymbolData)
+ merged.derivedSymbolData = patchedEntries(derivedSymbolDataOf(merged), patch.derivedSymbolData)
+ return merged
+}
diff --git a/packages/fig/src/record-patch.ts b/packages/fig/src/record-patch/index.ts
similarity index 89%
rename from packages/fig/src/record-patch.ts
rename to packages/fig/src/record-patch/index.ts
index 6ee4a4907..dbad3d6b9 100644
--- a/packages/fig/src/record-patch.ts
+++ b/packages/fig/src/record-patch/index.ts
@@ -11,8 +11,16 @@ import {
} from '@open-pencil/kiwi/schema-runtime'
import { orderKeyBetween } from '@open-pencil/scene-graph/order-keys'
-import { readFigArchiveParts, writeFigArchive, type FigImageEntry } from './archive'
-import { symbolDataOf, symbolOverridesOf } from './instance-overrides/types'
+import { readFigArchiveParts, writeFigArchive, type FigImageEntry } from '../archive'
+import { symbolDataOf, symbolOverridesOf } from '../instance-overrides/types'
+import { patchedRecord, type FigRecordFieldPatch } from './fields'
+
+export {
+ entryPathKey,
+ type FigEntryListPatch,
+ type FigEntryPatch,
+ type FigRecordFieldPatch
+} from './fields'
/**
* What an edited document changes in the archive it was opened from: the records to write, by
@@ -21,6 +29,8 @@ import { symbolDataOf, symbolOverridesOf } from './instance-overrides/types'
export interface FigRecordPatch {
/** Written in place of the archive's record with the same GUID, or added after the rest. */
records: NodeChange[]
+ /** Changed fields of records the archive holds, merged into them. */
+ fields?: FigRecordFieldPatch[]
/** Blobs the records add; their indices continue after the archive's. */
blobs: Uint8Array[]
/** Dropped together with every record below them. */
@@ -213,20 +223,43 @@ function placeVariableRecords(
}
}
+/**
+ * Add the archive records whose fields the patch changes to `written`, merged, and return the
+ * records removed. A record an edit moved has left a removed parent; one it left in place goes
+ * with it.
+ */
+function writeFieldPatches<Value>(
+ archive: ReadonlyArray<RecordEntry<Value>>,
+ patch: Pick<FigRecordPatch, 'fields' | 'removed'>,
+ written: Map<string, RecordEntry<NodeChange>>,
+ decode: (value: Value) => NodeChange
+): Set<string> {
+ const fields = new Map((patch.fields ?? []).map((entry) => [guidToString(entry.guid), entry]))
+ const moved = [...fields].flatMap(([id, entry]) => ('parentIndex' in entry.set ? [id] : []))
+ const removed = removedRecords(archive, patch.removed, new Set([...written.keys(), ...moved]))
+ for (const entry of archive) {
+ if (!entry.id || written.has(entry.id) || removed.has(entry.id)) continue
+ const changed = fields.get(entry.id)
+ if (changed) written.set(entry.id, entryOf(patchedRecord(decode(entry.value), changed)))
+ }
+ return removed
+}
+
/**
* Merge a patch into the archive's records. Untouched records keep their place; a written
* record takes its archive record's, and one whose parent is new follows that parent.
*/
function mergeRecords<Value>(
archive: ReadonlyArray<RecordEntry<Value>>,
- patch: Pick<FigRecordPatch, 'records' | 'removed' | 'replaceVariables'>
+ patch: Pick<FigRecordPatch, 'records' | 'fields' | 'removed' | 'replaceVariables'>,
+ decode: (value: Value) => NodeChange
): Array<RecordEntry<Value | NodeChange>> {
const written = new Map<string, RecordEntry<NodeChange>>()
for (const record of patch.records) {
const entry = entryOf(record)
if (entry.id) written.set(entry.id, entry)
}
- const removed = removedRecords(archive, patch.removed, new Set(written.keys()))
+ const removed = writeFieldPatches(archive, patch, written, decode)
const archiveIds = new Set(archive.flatMap((entry) => entry.id ?? []))
const archivePositions = new Map<string, NodeChange['parentIndex']>()
const writer = createRecordWriter<Value | NodeChange>(written, archiveIds)
@@ -252,9 +285,9 @@ function mergeRecords<Value>(
/** Merge a patch into decoded archive records. */
export function patchFigRecords(
archive: readonly NodeChange[],
- patch: Pick<FigRecordPatch, 'records' | 'removed' | 'replaceVariables'>
+ patch: Pick<FigRecordPatch, 'records' | 'fields' | 'removed' | 'replaceVariables'>
): NodeChange[] {
- return mergeRecords(archive.map(entryOf), patch).map((entry) => entry.value)
+ return mergeRecords(archive.map(entryOf), patch, (record) => record).map((entry) => entry.value)
}
type KiwiCodec = ReturnType<typeof compileSchema>
@@ -404,7 +437,13 @@ export function patchFigMessage(
): Uint8Array {
const { codec, skipper } = archiveCodec(schemaDeflated)
const scanned = scanMessage(codec, skipper, dataRaw)
- const merged = mergeRecords(scanned.records, patch)
+ const recordsPart = scanned.parts.find((part) => part.kind === 'records')
+ // Only the records an edit changed some fields of are decoded; the rest stay bytes.
+ const decode = (bytes: Uint8Array): NodeChange => {
+ if (recordsPart?.kind !== 'records') throw new Error('The archive has no records')
+ return decoderOf(codec, recordsPart.type)(new ByteBuffer(bytes)) as NodeChange
+ }
+ const merged = mergeRecords(scanned.records, patch, decode)
const blobs = (type: string) => [
...scanned.blobs,
...patch.blobs.map((bytes) => encoded(codec, type, { bytes }))
diff --git a/packages/fig/tests/record-patch/fields.test.ts b/packages/fig/tests/record-patch/fields.test.ts
new file mode 100644
index 000000000..f6f97c708
--- /dev/null
+++ b/packages/fig/tests/record-patch/fields.test.ts
@@ -0,0 +1,56 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import { patchedRecord } from '#fig/record-patch/fields'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+const path = (...ids: number[]) => ({ guids: ids.map((id) => guid(id)) })
+
+test("merges an instance's changed overrides by path, keeping the entries it did not change", () => {
+ const instance = {
+ guid: guid(1),
+ type: 'INSTANCE',
+ name: 'Lists',
+ symbolData: {
+ symbolID: guid(9),
+ symbolOverrides: [
+ { guidPath: path(2), size: { x: 10, y: 10 }, stackCounterSizing: 'FIXED' },
+ { guidPath: path(3, 4), stackSpacing: 15 },
+ { guidPath: path(5), visible: false }
+ ]
+ },
+ derivedSymbolData: [{ guidPath: path(3), size: { x: 1, y: 1 } }]
+ } as NodeChange
+
+ const patched = patchedRecord(instance, {
+ guid: guid(1),
+ set: { name: 'Lists renamed' },
+ unset: [],
+ symbolOverrides: {
+ entries: [
+ { path: [guid(2)], set: { name: 'Lists renamed' }, unset: ['stackCounterSizing'] },
+ { path: [guid(6)], set: { visible: false }, unset: [] }
+ ],
+ removed: [[guid(5)]]
+ },
+ derivedSymbolData: {
+ entries: [{ path: [guid(3)], set: { size: { x: 2, y: 2 } }, unset: [] }],
+ removed: []
+ }
+ })
+
+ expect(patched).toEqual({
+ ...instance,
+ name: 'Lists renamed',
+ symbolData: {
+ symbolID: guid(9),
+ symbolOverrides: [
+ { guidPath: path(2), size: { x: 10, y: 10 }, name: 'Lists renamed' },
+ { guidPath: path(3, 4), stackSpacing: 15 },
+ { guidPath: path(6), visible: false }
+ ]
+ },
+ derivedSymbolData: [{ guidPath: path(3), size: { x: 2, y: 2 } }]
+ } as NodeChange)
+})
diff --git a/packages/fig/tests/record-patch.test.ts b/packages/fig/tests/record-patch/index.test.ts
similarity index 79%
rename from packages/fig/tests/record-patch.test.ts
rename to packages/fig/tests/record-patch/index.test.ts
index 4bc36f82f..78583fa18 100644
--- a/packages/fig/tests/record-patch.test.ts
+++ b/packages/fig/tests/record-patch/index.test.ts
@@ -1,7 +1,7 @@
import { beforeAll, describe, expect, test } from 'bun:test'
import { guid } from '#fig-tests/helpers/guid'
-import { figComponentUsePages, patchFigMessage, patchFigRecords } from '#fig/record-patch'
+import { figComponentUsePages, patchFigMessage, patchFigRecords } from '#fig/record-patch/index'
import { deflateSync } from 'fflate'
import {
@@ -43,6 +43,31 @@ describe('patching archive records', () => {
expect(result[4]).toBe(archive[4])
})
+ test('merges the fields an edit changed into a record, keeping the rest of it', () => {
+ const saved = record(3, 2, { name: 'Saved', opacity: 0.5, editInfo: { userId: 'a' } })
+ const result = patchFigRecords([...archive.slice(0, 3), saved, ...archive.slice(4)], {
+ records: [],
+ fields: [{ guid: guid(3), set: { name: 'Renamed' }, unset: ['opacity'] }],
+ removed: [],
+ replaceVariables: false
+ })
+ expect(ids(result)).toEqual([0, 1, 2, 3, 4, 5])
+ expect(result[3]).toEqual(record(3, 2, { name: 'Renamed', editInfo: { userId: 'a' } }))
+ })
+
+ test('keeps a record whose patched fields move it out of a removed parent', () => {
+ const result = patchFigRecords(archive, {
+ records: [],
+ fields: [
+ { guid: guid(4), set: { parentIndex: { guid: guid(1), position: '9' } }, unset: [] },
+ { guid: guid(3), set: { name: 'Stays below' }, unset: [] }
+ ],
+ removed: [guid(2)],
+ replaceVariables: false
+ })
+ expect(ids(result)).toEqual([0, 1, 4, 5])
+ })
+
test('removes a record with those below it, but not one the patch moved out', () => {
const moved = record(4, 1)
const result = patchFigRecords(archive, {
@@ -123,6 +148,7 @@ describe('splicing an encoded message', () => {
const data = codec.encodeMessage(message)
const patch = {
records: [record(4, 2, { name: 'Renamed again' }), record(9, 2, { name: 'Added' })],
+ fields: [{ guid: guid(2), set: { name: 'Frame renamed' }, unset: ['opacity'] }],
blobs: [new Uint8Array([3])],
removed: [guid(3)],
replaceVariables: false
@@ -138,10 +164,11 @@ describe('splicing an encoded message', () => {
})
)
expect(spliced).toEqual(merged as typeof message)
+ expect(spliced.nodeChanges[2].opacity).toBeUndefined()
expect(spliced.nodeChanges.map((change) => change.name)).toEqual([
'Document',
'Page',
- 'Frame',
+ 'Frame renamed',
'Renamed again',
'Added'
])
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index 9b1df8f08..1ee0c9396 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -854,6 +854,8 @@ export interface VariableCollectionMode {
* at-rule prelude (`@media (max-width: 640px)`). Absent means the default for its axis.
*/
condition?: string
+ /** Where Figma lists the mode, as the file saved it; Figma orders a collection's modes by it. */
+ sortPosition?: string
}
export interface VariableCollection {
@@ -869,6 +871,16 @@ export interface VariableCollection {
*/
modeAttribute?: string
pluginData?: PluginDataEntry[]
+ /**
+ * Published library key, for a collection the file copies from a library. Such a collection
+ * belongs to the library: Figma lists it with the library's, not the file's own.
+ */
+ key?: string
+}
+
+/** Whether a collection is a library's copy, which takes no variables or modes of the file's. */
+export function isLibraryCollection(collection: Pick<VariableCollection, 'key'>): boolean {
+ return !!collection.key
}
/** An HTML attribute name a stylesheet can select on unescaped: `data-theme`, `theme`. */
diff --git a/src/app/editor/tokens/design-tokens.ts b/src/app/editor/tokens/design-tokens.ts
index e4851faa0..882b681a1 100644
--- a/src/app/editor/tokens/design-tokens.ts
+++ b/src/app/editor/tokens/design-tokens.ts
@@ -15,6 +15,14 @@ import { toast } from '@/app/shell/ui'
/** Files a token import reads: JSON token files, or archives of them. */
export const DESIGN_TOKEN_FILE_ACCEPT = '.json,.tokens,.zip'
+/**
+ * Whether a file is a design token file by its name: the `.tokens` and `.tokens.json` token
+ * files and the `.resolver.json` resolvers of the W3C format. Other JSON may be anything.
+ */
+export function isDesignTokenFileName(name: string): boolean {
+ return /\.(tokens|tokens\.json|resolver\.json)$/i.test(name)
+}
+
function isTokenFile(path: string): boolean {
return /\.(json|tokens)$/i.test(path) && !path.split('/').some((part) => part.startsWith('.'))
}
diff --git a/src/app/editor/tokens/dialog.ts b/src/app/editor/tokens/dialog.ts
index 9b022b59b..f397365a4 100644
--- a/src/app/editor/tokens/dialog.ts
+++ b/src/app/editor/tokens/dialog.ts
@@ -1,5 +1,25 @@
+import { shallowRef, type ShallowRef } from 'vue'
+
import type { EditorStore } from '@/app/editor/active-store'
export function openVariablesDialog(store: EditorStore): void {
store.state.variablesOpen = true
}
+
+const pendingImports = new WeakMap<EditorStore, ShallowRef<File[] | null>>()
+
+/** Token files a document's variables dialog has yet to read into an import. */
+export function pendingTokenImport(store: EditorStore): ShallowRef<File[] | null> {
+ let pending = pendingImports.get(store)
+ if (!pending) {
+ pending = shallowRef<File[] | null>(null)
+ pendingImports.set(store, pending)
+ }
+ return pending
+}
+
+/** Opens the variables dialog on an import of these token files, as its Import button does. */
+export function importTokenFiles(store: EditorStore, files: File[]): void {
+ pendingTokenImport(store).value = files
+ openVariablesDialog(store)
+}
diff --git a/src/app/shell/document-drop.ts b/src/app/shell/document-drop.ts
index e8a694582..a6d5be3cc 100644
--- a/src/app/shell/document-drop.ts
+++ b/src/app/shell/document-drop.ts
@@ -2,6 +2,9 @@ import { useEventListener } from '@vueuse/core'
import { filterCanvasFiles } from '@open-pencil/vue'
+import { getActiveEditorStoreOrNull } from '@/app/editor/active-store'
+import { isDesignTokenFileName } from '@/app/editor/tokens/design-tokens'
+import { importTokenFiles } from '@/app/editor/tokens/dialog'
import { openDesignFile, openDesignFileBatch } from '@/app/shell/menu/files'
interface DroppedFile {
@@ -40,8 +43,9 @@ function droppedFiles(transfer: DataTransfer): DroppedFile[] {
/**
* Opens documents dropped anywhere on the window in new tabs, as File → Open does. Images and
- * SVG files stay with the canvas, which places them; any other file reports that it cannot be
- * opened instead of being ignored.
+ * SVG files stay with the canvas, which places them; design token files open the variables
+ * import of the document in view; any other file reports that it cannot be opened instead of
+ * being ignored.
*/
export function useDocumentDrop() {
useEventListener(window, 'dragover', (event: DragEvent) => {
@@ -55,9 +59,18 @@ export function useDocumentDrop() {
// Without this the browser would navigate away to show the file.
event.preventDefault()
// Classify each file itself: `getAsFile()` may return a new `File`, not one from `files`.
- const documents = droppedFiles(event.dataTransfer).filter(
+ const dropped = droppedFiles(event.dataTransfer).filter(
({ file }) => filterCanvasFiles([file]).length === 0
)
+ // Token files are imported into the open document's variables, as its Import button does.
+ const tokens = dropped.filter(({ file }) => isDesignTokenFileName(file.name))
+ const store = getActiveEditorStoreOrNull()
+ if (tokens.length > 0 && store)
+ importTokenFiles(
+ store,
+ tokens.map(({ file }) => file)
+ )
+ const documents = dropped.filter((entry) => !store || !tokens.includes(entry))
if (documents.length === 0) return
void openDesignFileBatch(
documents,
diff --git a/src/components/variables/TokenImportDialog.vue b/src/components/variables/TokenImportDialog.vue
index a8add084d..095638455 100644
--- a/src/components/variables/TokenImportDialog.vue
+++ b/src/components/variables/TokenImportDialog.vue
@@ -12,6 +12,7 @@ import {
type ModeTarget,
type TokenImportOptions
} from '@open-pencil/core/io/formats/design-tokens'
+import { isLibraryCollection } from '@open-pencil/scene-graph'
import { useI18n } from '@open-pencil/vue'
import { useEditorStore } from '@/app/editor/active-store'
@@ -74,7 +75,9 @@ const plan = computed(() => {
})
const existingCollections = computed(() => {
void store.state.sceneVersion
- return [...store.graph.variableCollections.values()]
+ return [...store.graph.variableCollections.values()].filter(
+ (collection) => !isLibraryCollection(collection)
+ )
})
const styleCount = computed(
() =>
diff --git a/src/components/variables/VariablesDialog.vue b/src/components/variables/VariablesDialog.vue
index 9ef62ece2..7722855ba 100644
--- a/src/components/variables/VariablesDialog.vue
+++ b/src/components/variables/VariablesDialog.vue
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { useFileDialog } from '@vueuse/core'
import { DialogTitle } from 'reka-ui'
-import { computed, defineAsyncComponent, ref, shallowRef } from 'vue'
+import { computed, defineAsyncComponent, ref, shallowRef, watch } from 'vue'
import type { DesignTokenBundle } from '@open-pencil/core/io/formats/design-tokens'
import { useI18n } from '@open-pencil/vue'
@@ -13,6 +13,7 @@ import {
exportDesignTokenArchive,
readDesignTokenFiles
} from '@/app/editor/tokens/design-tokens'
+import { pendingTokenImport } from '@/app/editor/tokens/dialog'
import { notificationMessages } from '@/app/i18n/notifications'
import { useDocumentShortcuts } from '@/app/shell/keyboard/document'
import { toast } from '@/app/shell/ui'
@@ -50,19 +51,40 @@ function reportFailure(error: unknown) {
)
}
+/** The latest import asked for; an earlier one still reading does not replace its preview. */
+let importRequest = 0
+
/** Token files, a folder's worth, or a zip of them; the import dialog shows what they would do. */
-const tokenFiles = useFileDialog({ accept: DESIGN_TOKEN_FILE_ACCEPT, multiple: true, reset: true })
-tokenFiles.onChange((files) => {
- if (!files?.length) return
- const picked = [...files]
+function importFiles(files: readonly File[]) {
+ const request = ++importRequest
void (async () => {
- const sources = await readDesignTokenFiles(picked)
+ const sources = await readDesignTokenFiles(files)
const { readDesignTokens } = await import('@open-pencil/core/io/formats/design-tokens')
+ if (request !== importRequest) return
importBundle.value = readDesignTokens(sources)
importOpen.value = true
- })().catch(reportFailure)
+ })().catch((error: unknown) => {
+ if (request === importRequest) reportFailure(error)
+ })
+}
+
+const tokenFiles = useFileDialog({ accept: DESIGN_TOKEN_FILE_ACCEPT, multiple: true, reset: true })
+tokenFiles.onChange((files) => {
+ if (files?.length) importFiles([...files])
})
+// Token files dropped on the window come here through the document's pending import.
+const pendingImport = pendingTokenImport(store)
+watch(
+ pendingImport,
+ (files) => {
+ if (!files) return
+ pendingImport.value = null
+ importFiles(files)
+ },
+ { immediate: true }
+)
+
function exportTokens() {
exportDesignTokenArchive(store).catch(reportFailure)
}
diff --git a/tests/e2e/app/document-drop.spec.ts b/tests/e2e/app/document-drop.spec.ts
index 1a88c816c..4b8a13769 100644
--- a/tests/e2e/app/document-drop.spec.ts
+++ b/tests/e2e/app/document-drop.spec.ts
@@ -48,6 +48,21 @@ test('a dropped file that is neither a document nor an image reports that it can
await expect(tabs.getByRole('tab')).toHaveCount(1)
})
+test('a design token file dropped on the canvas opens the variables import', async ({ page }) => {
+ await page.goto('/?test')
+ await new CanvasHelper(page).waitForInit()
+ const tokens = { color: { $type: 'color', brand: { $value: '#2563eb' } } }
+
+ await dropOnCanvas(page, [
+ { name: 'brand.tokens.json', bytes: [...new TextEncoder().encode(JSON.stringify(tokens))] }
+ ])
+
+ await expect(page.getByRole('dialog', { name: 'Import design tokens' })).toBeVisible()
+ await expect(page.getByText('Could not open', { exact: false })).toHaveCount(0)
+ // The modal dialog hides the tab bar from the accessibility tree, so tabs are counted by id.
+ await expect(page.getByTestId('tabbar-tab')).toHaveCount(1)
+})
+
test('an SVG dropped on the canvas is placed, not opened as a document', async ({ page }) => {
await page.goto('/?test')
await new CanvasHelper(page).waitForInit()