AI-native design editor. Open-source Figma alternative.
fix(fig): keep shared styles across .fig save, reopen, and paste (#1100)
Danila Poyarkov16124568a81b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b1286351a..533e9f3b5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -32,6 +32,9 @@- Lines of text that mix font sizes or line heights are spaced as in Figma: each line is as tall as the tallest line height on it, with its largest font centred in it, instead of stacking the tallest parts of every style on it, which put lines after a large word or a taller line height up to 10 px off.- A line height in pixels shorter than the font, such as 24 px on 24 px text, opens from `.fig` files as set instead of as the font's own height.- Text with an empty line, or ending in one, saved to `.fig` or copied to Figma shows there, where Figma showed it blank.+- The properties panel shows the shared styles layers use in opened `.fig` files, where it listed them as missing styles.+- Styles made in OpenPencil, by importing design tokens or by pasting layers from another document, are saved in `.fig` files as styles, and layers reopen with them. Saving wrote their references empty, so reopening dropped the styles, and saving into an opened file made them layers of the page in Figma.+- Layers and text that use a library style keep it in Figma after OpenPencil saves them, where Figma showed them with no style.## 0.16.0-beta.1 — 2026-10-11diff --git a/packages/core/src/io/formats/fig/export-setup.ts b/packages/core/src/io/formats/fig/export-setup.tsindex fd2c4fa05..525026040 100644--- a/packages/core/src/io/formats/fig/export-setup.ts+++ b/packages/core/src/io/formats/fig/export-setup.ts@@ -6,6 +6,7 @@ import {buildComponentPropIndex,exportCanvasGuides,importCanvasGuides,+ parseGuidOrNull,stringToGuid,type FigNodeChangeExportRuntime} from '@open-pencil/fig/node-change'@@ -18,7 +19,8 @@ import {renameBehaviourProperties,withBehaviour,type PluginDataEntry,- type SceneGraph+ type SceneGraph,+ type SceneNode} from '@open-pencil/scene-graph'import { fractionalPosition } from '@open-pencil/scene-graph/order-keys'import type { GUID } from '@open-pencil/scene-graph/primitives'@@ -102,6 +104,15 @@ function ownGuid(return sourceGuidValues.has(key) || assignedGuidValues.has(key) ? null : guid}+/**+ * Whether a layer was opened from a file. A style keeps an ID of its own in `source.id`, which+ * only names a saved record when it spells a GUID; one made by token import or paste does not.+ */+function savedFromFile(node: SceneNode): boolean {+ if (!node.source.id) return false+ return node.sharedStyleType === null || parseGuidOrNull(node.source.id) !== null+}+function assignOwnLayerGuids(graph: SceneGraph,sourceGuidValues: ReadonlySet<string>,@@ -109,7 +120,7 @@ function assignOwnLayerGuids(assignedGuidValues: Set<string>): void {for (const node of graph.nodes.values()) {- if (node.source.id || node.id === graph.rootId || nodeIdToGuid.has(node.id)) continue+ if (savedFromFile(node) || node.id === graph.rootId || nodeIdToGuid.has(node.id)) continueconst guid = ownGuid(node.id, sourceGuidValues, assignedGuidValues)if (!guid) continuenodeIdToGuid.set(node.id, guid)diff --git a/packages/core/src/io/formats/fig/patch-export.ts b/packages/core/src/io/formats/fig/patch-export.tsindex 4ba53f46b..99b0897f9 100644--- a/packages/core/src/io/formats/fig/patch-export.ts+++ b/packages/core/src/io/formats/fig/patch-export.ts@@ -130,10 +130,12 @@ function siblingPositions(graph: SceneGraph, records: Set<string>): Map<string,const parents = new Set<string>()for (const id of records) {const node = graph.getNode(id)- if (node && node.type !== 'CANVAS' && node.parentId) parents.add(node.parentId)+ if (node && node.type !== 'CANVAS' && node.sharedStyleType === null && node.parentId)+ parents.add(node.parentId)}for (const parentId of parents) {- const siblings = graph.getChildren(parentId)+ // Styles are records of the internal canvas, wherever the document keeps them.+ const siblings = graph.getChildren(parentId).filter((child) => child.sharedStyleType === null)const keys = siblingOrderKeys(siblings.map((sibling) => sibling.source.orderKey))siblings.forEach((sibling, index) => {orderKeys.set(sibling.id, keys[index])@@ -143,6 +145,27 @@ function siblingPositions(graph: SceneGraph, records: Set<string>): Map<string,return orderKeys}+/**+ * Styles' positions on the internal canvas: the ones the archive saved, and new ones after the+ * internal canvas's records.+ */+function stylePositions(graph: SceneGraph, records: Set<string>, orderKeys: Map<string, string>) {+ const styles = [...records].flatMap((id) => {+ const node = graph.getNode(id)+ return node?.sharedStyleType ? [node] : []+ })+ for (const style of styles)+ if (style.source.orderKey) orderKeys.set(style.id, style.source.orderKey)+ const placed = styles.filter((style) => !style.source.orderKey)+ if (placed.length === 0) return+ const internal = graph.getPages(true).find((page) => page.internalOnly)+ const saved = (internal ? graph.getChildren(internal.id) : [])+ .filter((child) => !placed.includes(child))+ .map((child) => child.source.orderKey)+ const keys = siblingOrderKeys([...saved, ...placed.map(() => undefined)])+ placed.forEach((style, index) => orderKeys.set(style.id, keys[saved.length + index]))+}+function planRecords(graph: SceneGraph,changes: ArchiveChangeSummary,@@ -159,6 +182,7 @@ function planRecords(const replaceVariables = changes.changedVariables.size > 0 || changes.collectionsChangedif (replaceVariables) addVariableUsers(graph, changes, add)const orderKeys = siblingPositions(graph, records)+ stylePositions(graph, records, orderKeys)const removed: GUID[] = []for (const [guid, nodeId] of archived.byGuid)if (!graph.nodes.has(nodeId)) removed.push(stringToGuid(guid))@@ -219,9 +243,29 @@ function writeRecords(setup: FigExportSetup, plan: RecordPlan): KiwiNodeChange[]// Parents first, so a new parent has its GUID before its children name it.const ordered = [...plan.records].toSorted((left, right) => depth(left) - depth(right))const written: KiwiNodeChange[] = []+ const internal = setup.canvasEntries.find((entry) => entry.page.internalOnly)+ let internalWritten = falsefor (const id of ordered) {const node = graph.getNode(id)if (!node) continue+ // A style is a record of the internal canvas, which a document without one gains.+ if (node.sharedStyleType !== null) {+ if (!internal) return null+ if (!internal.page.id && !internalWritten) written.push(internal.canvasNc)+ internalWritten = true+ written.push(+ ...sceneNodeToKiwi(+ node,+ internal.canvasGuid,+ 0,+ setup.localIdCounter,+ graph,+ setup.blobs,+ options+ )+ )+ continue+ }if (node.type === 'CANVAS') {const entry = canvasGuids.get(node.id)if (entry) written.push(entry.canvasNc)@@ -283,7 +327,10 @@ async function buildPatch(}if (plan.replaceVariables) {const internalPage = graph.getPages(true).find((page) => page.internalOnly)- for (const record of variableRecords(setup, !!internalPage)) records.push(record)+ const internal = setup.canvasEntries.find((entry) => entry.page.internalOnly)+ const canvasWritten = records.some((record) => record === internal?.canvasNc)+ for (const record of variableRecords(setup, !!internalPage || canvasWritten))+ records.push(record)}return {graph,diff --git a/packages/core/src/io/formats/fig/variable-export.ts b/packages/core/src/io/formats/fig/variable-export.tsindex 3ed17bf4b..9ea652a16 100644--- a/packages/core/src/io/formats/fig/variable-export.ts+++ b/packages/core/src/io/formats/fig/variable-export.ts@@ -1,5 +1,6 @@import {collectionPluginDataNodeChange,+ parseGuidOrNull,variableMetadataNodeChange} from '@open-pencil/fig/node-change'import type { GUID, NodeChange, VariableDataEntry } from '@open-pencil/kiwi/fig/codec'@@ -82,7 +83,10 @@ export function assignVariableGuids(}}-/** Shared styles live on the internal canvas and need a GUID before any node cites them. */+/**+ * 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.+ */export function assignSharedStyleGuids(styles: readonly SceneNode[],localIdCounter: { value: number },@@ -91,6 +95,14 @@ export function assignSharedStyleGuids(): void {for (const style of styles) {if (nodeIdToGuid.has(style.id)) continue+ // A style read from Figma keeps its GUID, compared in the form the ID parses to.+ const imported = style.source.id ? parseGuidOrNull(style.source.id) : null+ const value = imported ? guidToString(imported) : null+ if (imported && value && !assignedGuidValues.has(value)) {+ nodeIdToGuid.set(style.id, imported)+ assignedGuidValues.add(value)+ continue+ }let guid: GUIDdo {guid = { sessionID: 1, localID: localIdCounter.value++ }diff --git a/packages/core/tests/io/formats/fig/export/archive-patch.test.ts b/packages/core/tests/io/formats/fig/export/archive-patch.test.tsindex 5e7bd3e21..d23badc85 100644--- a/packages/core/tests/io/formats/fig/export/archive-patch.test.ts+++ b/packages/core/tests/io/formats/fig/export/archive-patch.test.ts@@ -8,7 +8,7 @@ import { populateAllFigPages, populateFigPage } from '@open-pencil/core/io/formaimport { parseFigBuffer } from '@open-pencil/fig'import type { NodeChange } from '@open-pencil/kiwi/fig/codec'import { guidToString } from '@open-pencil/kiwi/fig/guid'-import type { SceneNode } from '@open-pencil/scene-graph'+import { getSharedStyles, type SceneNode } from '@open-pencil/scene-graph'import { cloneNodeProps } from '@open-pencil/scene-graph/copy'import { releaseFigArchive } from '#core/kiwi/fig/session/archive'@@ -47,6 +47,38 @@ test('independent headless branches preserve distinct new GUIDs across patched sexpect([...recordsOf(bytes).keys()].filter((guid) => !saved.has(guid))).toEqual([])})+test('styles added to an opened file are written on the internal canvas, not as layers', async () => {+ const bytes = await fixtureBytes()+ const graph = await open(bytes)+ const page = graph.getPages()[0]+ const style = graph.createNode('RECTANGLE', page.id, {+ name: 'Brand',+ sharedStyleType: 'FILL',+ internalOnly: true+ })+ style.source.id = 'style:a1b2c3d4e5f6'+ graph.updateNode(layerNamed(graph, 'A').id, { fillStyleId: style.source.id })++ const saved = await exportFigFile(graph)+ const records = [...recordsOf(saved).values()]+ const internal = records.find((record) => record.type === 'CANVAS' && record.internalOnly)+ const definition = records.find((record) => record.name === 'Brand')+ expect(definition?.parentIndex?.guid).toEqual(expectDefined(internal?.guid))+ // A style made in OpenPencil is saved under its own ID, as a new layer is.+ expect(guidToString(expectDefined(definition?.guid))).toBe(style.id)+ // The page's layers keep their records: the style takes no place among them.+ const before = recordsOf(bytes)+ for (const name of ['Frame', 'Dot']) {+ const record = records.find((candidate) => candidate.name === name)+ expect(record).toEqual(before.get(guidToString(expectDefined(record?.guid))))+ }+ const reopened = await open(saved)+ const styled = layerNamed(reopened, 'A')+ expect(getSharedStyles(reopened, 'fill').find((s) => s.id === styled.fillStyleId)?.name).toBe(+ 'Brand'+ )+})+/** A document over three pages: a frame of layers, a component, and a page of its instances. */async function fixtureBytes(): Promise<Uint8Array> {await initCodec()diff --git a/packages/core/tests/io/formats/fig/export/shared-style-export.test.ts b/packages/core/tests/io/formats/fig/export/shared-style-export.test.tsindex 48771b527..a936aa0ac 100644--- a/packages/core/tests/io/formats/fig/export/shared-style-export.test.ts+++ b/packages/core/tests/io/formats/fig/export/shared-style-export.test.ts@@ -1,9 +1,13 @@-import { expect, test } from 'bun:test'+import { beforeAll, expect, test } from 'bun:test'-import { exportFigFile } from '@open-pencil/core/io'+import { exportFigFile, parseFigFile } from '@open-pencil/core/io'import { initCodec } from '@open-pencil/core/kiwi'import { parseFigBuffer } from '@open-pencil/fig'-import { SceneGraph } from '@open-pencil/scene-graph'+import { getSharedStyles, SceneGraph } from '@open-pencil/scene-graph'++beforeAll(async () => {+ await initCodec()+})test('exports shared styles once even when present in a normal page subtree', async () => {await initCodec()@@ -21,3 +25,112 @@ test('exports shared styles once even when present in a normal page subtree', asconst ids = nodeChanges.map((node) => JSON.stringify(node.guid))expect(new Set(ids).size).toBe(ids.length)})++test('names local styles by the records it writes for them, whatever their ids', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ for (const [name, id, type] of [+ ['Imported', '1:10', 'FILL'],+ ['Tokens', 'style:a1b2c3d4e5f6', 'FILL'],+ ['Heading', 'style:0f9e8d7c6b5a', 'TEXT']+ ] as const) {+ const style = graph.createNode(type === 'TEXT' ? 'TEXT' : 'RECTANGLE', page.id, {+ name,+ sharedStyleType: type,+ internalOnly: true+ })+ style.source.id = id+ graph.createNode(type === 'TEXT' ? 'TEXT' : 'RECTANGLE', page.id, {+ name: `${name} target`,+ ...(type === 'TEXT' ? { textStyleId: id } : { fillStyleId: id })+ })+ }++ const parsed = parseFigBuffer((await exportFigFile(graph)).slice().buffer as ArrayBuffer)+ for (const name of ['Imported', 'Tokens', 'Heading']) {+ const definition = parsed.nodeChanges.find((change) => change.name === name && change.styleType)+ const target = parsed.nodeChanges.find((change) => change.name === `${name} target`)+ const reference = target?.styleIdForFill ?? target?.styleIdForText+ expect(definition?.guid).toBeDefined()+ expect(reference?.guid).toEqual(definition?.guid)+ }+})++test('reopen layers and ranges with the styles made in OpenPencil they use', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const fill = graph.createNode('RECTANGLE', page.id, {+ name: 'Brand',+ sharedStyleType: 'FILL',+ internalOnly: true+ })+ fill.source.id = 'style:a1b2c3d4e5f6'+ const heading = graph.createNode('TEXT', page.id, {+ name: 'Heading',+ sharedStyleType: 'TEXT',+ internalOnly: true,+ fontSize: 28+ })+ heading.source.id = 'style:0f9e8d7c6b5a'+ graph.createNode('TEXT', page.id, {+ name: 'Styled',+ text: 'Title body',+ fillStyleId: fill.source.id,+ styleRuns: [{ start: 0, length: 5, style: { textStyleId: heading.source.id, fontSize: 28 } }]+ })++ const reopened = await parseFigFile((await exportFigFile(graph)).slice().buffer as ArrayBuffer)+ const styled = [...reopened.getAllNodes()].find((node) => node.name === 'Styled')+ const named = (kind: 'fill' | 'text', id: string | null | undefined) =>+ getSharedStyles(reopened, kind).find((style) => style.id === id)?.name+ expect(named('fill', styled?.fillStyleId)).toBe('Brand')+ expect(named('text', styled?.styleRuns[0]?.style.textStyleId)).toBe('Heading')+})++test('names a library style by its key, as Figma does, on layers and ranges', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ const style = graph.createNode('TEXT', page.id, {+ name: 'LG/Medium',+ sharedStyleType: 'TEXT',+ internalOnly: true+ })+ style.source.id = '1:42'+ style.source.fig.rawNodeFields = { key: 'c98daa82', version: '4169:25' }+ graph.createNode('TEXT', page.id, {+ name: 'Styled',+ text: 'Title body',+ textStyleId: '1:42',+ styleRuns: [{ start: 0, length: 5, style: { textStyleId: '1:42' } }]+ })++ const parsed = parseFigBuffer((await exportFigFile(graph)).slice().buffer as ArrayBuffer)+ const styled = parsed.nodeChanges.find((change) => change.name === 'Styled')+ const library = { assetRef: { key: 'c98daa82', version: '4169:25' } }+ expect(styled?.styleIdForText).toEqual(library)+ expect(styled?.textData?.styleOverrideTable?.[0]?.styleIdForText).toEqual(library)+})++test('gives styles whose ids spell one GUID records of their own', async () => {+ const graph = new SceneGraph()+ const page = graph.getPages()[0]+ for (const [name, id] of [+ ['Plain', '1:10'],+ ['Padded', '01:010']+ ]) {+ const style = graph.createNode('RECTANGLE', page.id, {+ name,+ sharedStyleType: 'FILL',+ internalOnly: true+ })+ style.source.id = id+ }++ const parsed = parseFigBuffer((await exportFigFile(graph)).slice().buffer as ArrayBuffer)+ const guids = ['Plain', 'Padded'].map((name) => {+ const guid = parsed.nodeChanges.find((change) => change.name === name)?.guid+ expect(guid).toBeDefined()+ return JSON.stringify(guid)+ })+ expect(new Set(guids).size).toBe(2)+})diff --git a/packages/fig/src/document/materialize.ts b/packages/fig/src/document/materialize.tsindex 0580cbbcd..4f033c9bd 100644--- a/packages/fig/src/document/materialize.ts+++ b/packages/fig/src/document/materialize.ts@@ -393,27 +393,15 @@ function materializeReaderInto(for (const page of pages) populateInstances(page)for (const instanceId of resync) graph.syncInstance(instanceId)if (resync.size > 0) restoreDerivedSizes(graph, derivedSizes)+ // Layers and ranges name their styles by the styles' own IDs, which the records' GUIDs are,+ // so only links to other layers are renamed to the layers this page added.for (const node of graph.getAllNodes()) {- if (existingNodeIds.has(node.id)) continue- for (const field of [- 'fillStyleId',- 'strokeStyleId',- 'textStyleId',- 'effectStyleId',- 'gridStyleId'- ] as const) {- const id = node[field]- if (id && sources.has(id)) node[field] = sources.get(id) ?? id- }- // Ranges name their styles and linked layers by record too; a layer left out stays named.- if (node.styleRuns.length > 0) {- const source = (id: string) => sources.get(id) ?? id- node.styleRuns = remapStyleRunReferences(node.styleRuns, {- variable: (id) => id,- style: source,- node: source- })- }+ if (existingNodeIds.has(node.id) || node.styleRuns.length === 0) continue+ node.styleRuns = remapStyleRunReferences(node.styleRuns, {+ variable: (id) => id,+ style: (id) => id,+ node: (id) => sources.get(id) ?? id+ })}// These passes apply to the nodes this page added, not to the whole graph.const materialized = [...graph.nodes.values()].filter((node) => !existingNodeIds.has(node.id))diff --git a/packages/fig/src/document/style-dependencies.ts b/packages/fig/src/document/style-dependencies.tsindex 1b7d2e055..9bab8ab11 100644--- a/packages/fig/src/document/style-dependencies.ts+++ b/packages/fig/src/document/style-dependencies.ts@@ -11,7 +11,10 @@ export const STYLE_REFERENCE_FIELDS = ['styleIdForGrid'] as const-/** Include available style definitions, including references declared on override paths. */+/**+ * Include available style definitions, including references declared on override paths and by+ * ranges of text.+ */export function styleDependencies(node: NodeChange,resolve: (reference: StyleReference) => string | undefined,@@ -19,11 +22,14 @@ export function styleDependencies(): Set<string> {const result = new Set<string>()forEachOverrideRecord(node, (source) => {- for (const field of STYLE_REFERENCE_FIELDS) {- const reference = source[field]- if (!reference) continue- const id = reference.guid ? guidToString(reference.guid) : resolve(reference)- if (id && available.has(id)) result.add(id)+ // Ranges of a text name their styles in its style table, as the record names its own.+ for (const record of [source, ...(source.textData?.styleOverrideTable ?? [])]) {+ for (const field of STYLE_REFERENCE_FIELDS) {+ const reference = record[field]+ if (!reference) continue+ const id = reference.guid ? guidToString(reference.guid) : resolve(reference)+ if (id && available.has(id)) result.add(id)+ }}})return resultdiff --git a/packages/fig/src/node-change/export/context.ts b/packages/fig/src/node-change/export/context.tsindex 89c5523ec..cd057f94b 100644--- a/packages/fig/src/node-change/export/context.ts+++ b/packages/fig/src/node-change/export/context.ts@@ -1,6 +1,6 @@import { effectiveFigmaRawNodeFields } from '#fig/source-metadata'-import type { NodeChange, Paint } from '@open-pencil/kiwi/fig/codec'+import type { NodeChange, Paint, StyleReference } from '@open-pencil/kiwi/fig/codec'import { stringToGuid } from '@open-pencil/kiwi/fig/guid'import type {ComponentPropertyDefinition,@@ -19,17 +19,11 @@ export interface KiwiSymbolOverridePayload {[key: string]: unknown}-/** How a record names a shared style: a local GUID, or a published library asset. */-export interface StyleReference {- guid?: GUID- assetRef?: { key: string; version?: string }-}--/** Published text styles by source id, built once with the rest of the context. */+/** Library styles by source id, built once with the rest of the context. */export function buildStyleReferences(graph: SceneGraph): ReadonlyMap<string, StyleReference> {const references = new Map<string, StyleReference>()for (const node of graph.getAllNodes()) {- if (node.sharedStyleType !== 'TEXT' || !node.source.id) continue+ if (node.sharedStyleType === null || !node.source.id) continueconst raw = effectiveFigmaRawNodeFields(node)if (typeof raw.key !== 'string') continuereferences.set(node.source.id, {@@ -42,8 +36,45 @@ export function buildStyleReferences(graph: SceneGraph): ReadonlyMap<string, Styreturn references}+/**+ * The GUID a layer names a style with: the record written for the local style of that ID, or+ * the GUID the ID spells. Styles made in OpenPencil, by token import or by pasting from another+ * document, have IDs that spell no GUID, so only their records can name them.+ */+export function styleReferenceGuid(+ context: Pick<SceneNodeToKiwiContext, 'graph' | 'nodeIdToGuid' | 'styleNodeIds'>,+ id: string+): GUID {+ if (!context.styleNodeIds) {+ const styleNodeIds = new Map<string, string>()+ for (const node of context.graph.getAllNodes())+ if (node.sharedStyleType !== null && node.source.id) styleNodeIds.set(node.source.id, node.id)+ context.styleNodeIds = styleNodeIds+ }+ const styleNodeId = context.styleNodeIds.get(id)+ const written = styleNodeId ? context.nodeIdToGuid?.get(styleNodeId) : undefined+ return written ?? context.nodeIdToGuid?.get(id) ?? stringToGuid(id)+}++/**+ * How a layer names a style, as Figma writes it: a library style by its key, which Figma+ * resolves and keeps linked to the library, and a local one by its record.+ */+export function exportedStyleReference(+ context: Pick<+ SceneNodeToKiwiContext,+ 'graph' | 'nodeIdToGuid' | 'styleNodeIds' | 'styleReferences'+ >,+ id: string+): StyleReference {+ context.styleReferences ??= buildStyleReferences(context.graph)+ return context.styleReferences.get(id) ?? { guid: styleReferenceGuid(context, id) }+}+export interface SceneNodeToKiwiContext {styleReferences?: ReadonlyMap<string, StyleReference>+ /** Local styles' node IDs by the style IDs layers name them with, built on first use. */+ styleNodeIds?: ReadonlyMap<string, string>graph: SceneGraphblobs: Uint8Array[]blobIndexByHex?: Map<string, number>diff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.tsindex e687ec229..06d26ec0a 100644--- a/packages/fig/src/node-change/export/node.ts+++ b/packages/fig/src/node-change/export/node.ts@@ -35,6 +35,7 @@ import {createFillPaints,createStrokePaints,getOrCreateNodeGuid,+ exportedStyleReference,instanceGuidResolver,getOrCreatePropertyGuid,parseGuidOrNull,@@ -807,7 +808,7 @@ function applySharedStyleProps(node: SceneNode,nc: KiwiNodeChange): void {- const reference = (id: string) => ({ guid: context.nodeIdToGuid?.get(id) ?? stringToGuid(id) })+ const reference = (id: string) => exportedStyleReference(context, id)if (node.fillStyleId) nc.styleIdForFill = reference(node.fillStyleId)if (node.strokeStyleId) nc.styleIdForStrokeFill = reference(node.strokeStyleId)if (node.textStyleId) nc.styleIdForText = reference(node.textStyleId)diff --git a/packages/fig/src/node-change/export/override-claims.ts b/packages/fig/src/node-change/export/override-claims.tsindex 19606059a..9d9f3daf6 100644--- a/packages/fig/src/node-change/export/override-claims.ts+++ b/packages/fig/src/node-change/export/override-claims.ts@@ -1,7 +1,6 @@import { type OverrideField, SCENE_OVERRIDE_FIELDS } from '#fig/instance-overrides/fields'import { compact } from 'es-toolkit'-import { stringToGuid } from '@open-pencil/kiwi/fig/guid'import {forEachInstanceOverride,ownsSlotContent,@@ -14,27 +13,19 @@ import type { GUID, Vector } from '@open-pencil/scene-graph/primitives'import { instanceExportAddress } from '../instance/geometry'import { mergeVariableConsumptionMaps, overrideVariableBindingEntry } from '../variable/bindings'import {- buildStyleReferences,createFillPaints,createStrokePaints,getOrCreateNodeGuid,+ exportedStyleReference,instanceGuidResolver,isDescendantOf,type KiwiNodeChange,type KiwiSymbolOverridePayload,- type SceneNodeToKiwiContext,- type StyleReference+ type SceneNodeToKiwiContext} from './context'import { fillsOwnSizingAxis } from './fill-sizing'import { exportedNode } from './resolved-bindings'-function exportedTextStyleReference(context: SceneNodeToKiwiContext, id: string): StyleReference {- context.styleReferences ??= buildStyleReferences(context.graph)- const mapped = context.nodeIdToGuid?.get(id)- if (mapped) return { guid: mapped }- return context.styleReferences.get(id) ?? { guid: stringToGuid(id) }-}-function unscaledRootSize(instance: SceneNode, target: SceneNode): Vector {const scale = instance.componentScaleif (!Number.isFinite(scale) || scale <= 0) throw new Error('Invalid instance uniform scale')@@ -148,7 +139,7 @@ function rawClaim(}case 'text-style':return target.textStyleId- ? { styleIdForText: exportedTextStyleReference(context, target.textStyleId) }+ ? { styleIdForText: exportedStyleReference(context, target.textStyleId) }: undefinedcase 'paint':return raw === 'fillPaints'diff --git a/packages/fig/src/node-change/index.ts b/packages/fig/src/node-change/index.tsindex bd157d136..51c8fd73c 100644--- a/packages/fig/src/node-change/index.ts+++ b/packages/fig/src/node-change/index.ts@@ -4,6 +4,7 @@ export * from './convert'export * from './derived-text/build'export * from './derived-text/data'export * from './derived-text/glyphs'+export { parseGuidOrNull } from './export/context'export * from './export/node'export * from './export/runtime'export { placeSlotContent } from './export/slots'diff --git a/packages/fig/src/node-change/text/run-references.ts b/packages/fig/src/node-change/text/run-references.tsindex dcbab3a14..fb413b508 100644--- a/packages/fig/src/node-change/text/run-references.ts+++ b/packages/fig/src/node-change/text/run-references.ts@@ -2,15 +2,15 @@ import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'import { stringToGuid, UNSET_GUID } from '@open-pencil/kiwi/fig/guid'import type { CharacterStyleOverride, SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { exportedStyleReference, type SceneNodeToKiwiContext } from '../export/context'import { textRunVariableEntries } from '../variable/bindings'import { textStyleOverrides } from './data-export'/** The identities a document's records are written with. */-export interface TextRunReferenceContext {- graph: SceneGraph- nodeIdToGuid?: Map<string, GUID>- varIdToGuid?: Map<string, GUID>-}+export type TextRunReferenceContext = Pick<+ SceneNodeToKiwiContext,+ 'graph' | 'nodeIdToGuid' | 'varIdToGuid' | 'styleNodeIds' | 'styleReferences'+>function applyRunReferences(context: TextRunReferenceContext,@@ -23,14 +23,14 @@ function applyRunReferences(override.hyperlink = link.type === 'URL' ? { url: link.value } : { guid: guid(link.value) }// The unset GUID writes a range that leaves the text's style.if (style.textStyleId !== undefined) {- override.styleIdForText = {- guid: style.textStyleId ? guid(style.textStyleId) : { ...UNSET_GUID }- }+ override.styleIdForText = style.textStyleId+ ? exportedStyleReference(context, style.textStyleId)+ : { guid: { ...UNSET_GUID } }}if (style.fillStyleId !== undefined) {- override.styleIdForFill = {- guid: style.fillStyleId ? guid(style.fillStyleId) : { ...UNSET_GUID }- }+ override.styleIdForFill = style.fillStyleId+ ? exportedStyleReference(context, style.fillStyleId)+ : { guid: { ...UNSET_GUID } }}const entries = textRunVariableEntries(style.boundVariables ?? {},diff --git a/packages/scene-graph/src/transfer/plan.ts b/packages/scene-graph/src/transfer/plan.tsindex 3fba5d0b6..d0458a285 100644--- a/packages/scene-graph/src/transfer/plan.ts+++ b/packages/scene-graph/src/transfer/plan.ts@@ -12,6 +12,18 @@ export interface GraphTransferInput {parentId: string}+/** A transferred style's props under the ID the transfer gives it. */+function withStyleId(+ node: SceneNode,+ props: Partial<SceneNode>,+ styles: ReadonlyMap<string, string>+): Partial<SceneNode> {+ const id =+ node.sharedStyleType !== null && node.source.id ? styles.get(node.source.id) : undefined+ if (!id || id === node.source.id) return props+ return { ...props, source: { ...(props.source ?? node.source), id } }+}+/** Preflight a self-contained fragment; allocation does not insert anything into the target. */export function prepareGraphTransfer(input: GraphTransferInput) {const { source, target, parentId } = input@@ -59,6 +71,17 @@ export function prepareGraphTransfer(input: GraphTransferInput) {propertyTypes.set(definition.id, definition.type)if (!properties.has(definition.id)) properties.set(definition.id, allocate())}+ // Layers name a style by the style's own ID, which a transferred style keeps unless the+ // target already holds another style by it: IDs read from Figma are only unique in one file.+ const targetStyleIds = new Set<string>()+ for (const node of target.getAllNodes())+ if (node.sharedStyleType !== null && node.source.id) targetStyleIds.add(node.source.id)+ const styles = new Map<string, string>()+ for (const node of ordered) {+ const id = node.source.id+ if (node.sharedStyleType === null || !id) continue+ styles.set(id, targetStyleIds.has(id) ? allocate() : id)+ }const references = {nodes,variables,@@ -66,7 +89,7 @@ export function prepareGraphTransfer(input: GraphTransferInput) {modes,properties,propertyTypes,- styles: nodes+ styles}const resources = prepareVariableTransfer([...source.variables.values()],@@ -93,7 +116,7 @@ export function prepareGraphTransfer(input: GraphTransferInput) {id: mapped(node.id),type: node.type,parentId: destinationParent(node),- props: prepareNodeTransfer(node, references)+ props: withStyleId(node, prepareNodeTransfer(node, references), styles)})),...resources,activeModes: new Map(diff --git a/packages/scene-graph/src/transfer/validation.ts b/packages/scene-graph/src/transfer/validation.tsindex 02804008d..910c297a7 100644--- a/packages/scene-graph/src/transfer/validation.ts+++ b/packages/scene-graph/src/transfer/validation.ts@@ -25,9 +25,14 @@ export function validateTransferReferences(target: SceneGraph, plan: GraphTransfpropertyTypes.set(definition.id, definition.type)}const collections = new Map(plan.collections.map((collection) => [collection.id, collection]))+ const styles = new Map(+ [...nodes.values()].flatMap((node) =>+ node.sharedStyleType !== null && node.source.id ? [[node.source.id, node.source.id]] : []+ )+ )const references = {nodes: identities,- styles: identities,+ styles,properties,propertyTypes,...variableIdentityReferences(plan.variables, plan.collections)diff --git a/packages/scene-graph/tests/transfer/apply.test.ts b/packages/scene-graph/tests/transfer/apply.test.tsindex 8fa32cb4b..3c1b7ef17 100644--- a/packages/scene-graph/tests/transfer/apply.test.ts+++ b/packages/scene-graph/tests/transfer/apply.test.ts@@ -2,6 +2,7 @@ import { expect, test } from 'bun:test'import {applyGraphTransfer,+ getSharedStyles,prepareGraphTransfer,SceneGraph,CommittedGraphEventError@@ -91,3 +92,37 @@ test('observer failure reports committed transfer instead of rolling it back', (expect(() => applyGraphTransfer(target, plan)).toThrow(CommittedGraphEventError)expect(target.getChildren(plan.rootIds[0])).toHaveLength(1)})++test('a style named by an ID the target already uses for another style comes in under a new one', () => {+ const source = new SceneGraph(),+ target = new SceneGraph()+ const style = (graph: SceneGraph, pageId: string, name: string) => {+ const node = graph.createNode('RECTANGLE', pageId, {+ name,+ sharedStyleType: 'FILL',+ internalOnly: true+ })+ node.source.id = '1:42'+ return node+ }+ const library = source.addPage('Styles')+ source.updateNode(library.id, { internalOnly: true })+ style(source, library.id, 'Incoming')+ const root = source.createNode('RECTANGLE', source.getPages()[0].id, { fillStyleId: '1:42' })+ style(target, target.getPages()[0].id, 'Existing')+ const plan = prepareGraphTransfer({+ source,+ target,+ rootIds: [root.id],+ dependencyPageIds: [library.id],+ parentId: target.getPages()[0].id+ })+ applyGraphTransfer(target, plan)++ const pasted = target.getNode(plan.rootIds[0])+ const named = (id: string | null | undefined) =>+ getSharedStyles(target, 'fill').find((candidate) => candidate.id === id)?.name+ expect(pasted?.fillStyleId).not.toBe('1:42')+ expect(named(pasted?.fillStyleId)).toBe('Incoming')+ expect(named('1:42')).toBe('Existing')+})diff --git a/tests/engine/io/fig/import/legacy/shared-styles.test.ts b/tests/engine/io/fig/import/legacy/shared-styles.test.tsindex 1cf517400..add7852e6 100644--- a/tests/engine/io/fig/import/legacy/shared-styles.test.ts+++ b/tests/engine/io/fig/import/legacy/shared-styles.test.ts@@ -63,7 +63,7 @@ describe('fig-import: shared styles', () => {const target = [...graph.getAllNodes()].find((item) => item.name === 'Styled target')const styleId = (name: string) =>- [...graph.getAllNodes()].find((node) => node.name === name)?.id+ [...graph.getAllNodes()].find((node) => node.name === name)?.source.idexpect(target).toMatchObject({fillStyleId: styleId('Brand/Fill'),strokeStyleId: styleId('Brand/Fill'),diff --git a/tests/engine/io/fig/import/legacy/text.test.ts b/tests/engine/io/fig/import/legacy/text.test.tsindex 33c6e9090..79b0bae54 100644--- a/tests/engine/io/fig/import/legacy/text.test.ts+++ b/tests/engine/io/fig/import/legacy/text.test.ts@@ -2,9 +2,16 @@ import { describe, expect, test } from 'bun:test'import { materializeDocument } from '@open-pencil/fig'import type { NodeChange } from '@open-pencil/kiwi/fig/codec'+import type { SceneGraph } from '@open-pencil/scene-graph'import { canvas, doc, node } from './helpers'+/** The name of the style a layer's style ID names, found by the style's own ID as the panel does. */+function styleNamed(graph: SceneGraph, id: string | null | undefined) {+ return [...graph.getAllNodes()].find((style) => style.sharedStyleType && style.source.id === id)+ ?.name+}+describe('fig-import: text properties', () => {test('text auto resize', () => {const graph = materializeDocument([@@ -182,7 +189,7 @@ describe('fig-import: text properties', () => {.getChildren(graph.getPages()[0].id).find((node) => node.text === 'Styled text')expect(styled?.fontSize).toBe(16)- expect(graph.getNode(styled?.textStyleId ?? '')?.name).toBe('Body style')+ expect(styleNamed(graph, styled?.textStyleId)).toBe('Body style')expect(styled?.fontWeight).toBe(400)expect(styled?.lineHeight).toBe(24)expect(styled?.textDecoration).toBe('NONE')@@ -219,7 +226,7 @@ describe('fig-import: text properties', () => {const target = nodes.find((child) => child.name === 'Target')const style = [...graph.getAllNodes()].find((child) => child.name === 'Heading style')expect(text?.styleRuns.map((run) => run.style)).toEqual([- expect.objectContaining({ textStyleId: style?.id }),+ expect.objectContaining({ textStyleId: style?.source.id }),{ hyperlink: { type: 'NODE', value: target?.id } }])})@@ -257,7 +264,7 @@ describe('fig-import: text properties', () => {const styled = graph.getChildren(graph.getPages()[0].id).find((node) => node.name === 'ROUNDED_RECTANGLE_10')- expect(graph.getNode(styled?.fillStyleId ?? '')?.name).toBe('slate/900')+ expect(styleNamed(graph, styled?.fillStyleId)).toBe('slate/900')expect(styled?.fills[0]?.color).toEqual({r: 0.05882352963089943,g: 0.09019608050584793,