Skip to content

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

fix(fig)!: open layers under the GUIDs the file saved them with (#1343)

Danila Poyarkov80637cf53a7b
diff --git a/changes/1343/breaking.md b/changes/1343/breaking.md
new file mode 100644
index 000000000..ad371098a
--- /dev/null
+++ b/changes/1343/breaking.md
@@ -0,0 +1 @@
+- Layers opened from a `.fig` file keep the GUIDs the file saved them under as their IDs, instead of `0:1`, `0:2`, and so on in reading order, so an ID stays the same after a save and reopen. IDs printed by `openpencil tree` or MCP before this release no longer find their layers.
diff --git a/packages/cli/tests/commands/diff.test.ts b/packages/cli/tests/commands/diff.test.ts
index 3462a1346..82dcde9d6 100644
--- a/packages/cli/tests/commands/diff.test.ts
+++ b/packages/cli/tests/commands/diff.test.ts
@@ -10,8 +10,8 @@ import { CLI_ENTRY, FIXTURES } from '#cli-tests/helpers/paths'
setDefaultTimeout(60_000)
const FIXTURE = join(FIXTURES, 'gold-preview.fig')
-const LOGO = '0:10'
-const TITLE = '0:9'
+const LOGO = '1:3494'
+const TITLE = '1:3474'
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47]
async function cli(args: string[]) {
diff --git a/packages/core/src/io/formats/fig/library-metadata.ts b/packages/core/src/io/formats/fig/document-metadata.ts
similarity index 75%
rename from packages/core/src/io/formats/fig/library-metadata.ts
rename to packages/core/src/io/formats/fig/document-metadata.ts
index b4b55be93..058c4aee1 100644
--- a/packages/core/src/io/formats/fig/library-metadata.ts
+++ b/packages/core/src/io/formats/fig/document-metadata.ts
@@ -8,9 +8,10 @@ import {
type SceneGraph
} from '@open-pencil/scene-graph'
-const { enabledLibraries } = OPEN_PENCIL_PLUGIN_DATA
+const { documentId, enabledLibraries } = OPEN_PENCIL_PLUGIN_DATA
-export function applyEnabledLibrariesPluginData(
+/** The DOCUMENT record's plugin data: the root's own, the libraries it enables, and its id. */
+export function applyDocumentPluginData(
documentNodeChange: KiwiNodeChange,
graph: SceneGraph
): void {
@@ -18,9 +19,11 @@ export function applyEnabledLibrariesPluginData(
const bindings = [...graph.enabledLibraries.values()]
// With no libraries enabled, the entry the document was opened with is kept as it was.
const opened = rootPluginData.find((entry) => isPluginDataEntry(entry, enabledLibraries))
- documentNodeChange.pluginData = mergePluginData(
+ const withLibraries =
bindings.length > 0
? withPluginData(rootPluginData, enabledLibraries, bindings)
: [...withoutPluginData(rootPluginData, [enabledLibraries]), ...(opened ? [opened] : [])]
+ documentNodeChange.pluginData = mergePluginData(
+ withPluginData(withLibraries, documentId, graph.rootId)
)
}
diff --git a/packages/core/src/io/formats/fig/export/setup.ts b/packages/core/src/io/formats/fig/export/setup.ts
index bb2fce137..619c7a229 100644
--- a/packages/core/src/io/formats/fig/export/setup.ts
+++ b/packages/core/src/io/formats/fig/export/setup.ts
@@ -30,7 +30,7 @@ import type { GUID, Rect, Size } from '@open-pencil/scene-graph/primitives'
import type { SkiaRenderer } from '#core/canvas'
import { CANVAS_BG_COLOR, IS_BROWSER, IS_TAURI } from '#core/constants'
import { getPageColor } from '#core/figma-api/page-backgrounds'
-import { applyEnabledLibrariesPluginData } from '#core/io/formats/fig/library-metadata'
+import { applyDocumentPluginData } from '#core/io/formats/fig/document-metadata'
import { findFigThumbnailPageId } from '#core/io/formats/fig/thumbnail-page'
import { renderThumbnail, thumbnailFrame } from '#core/io/formats/raster'
import {
@@ -110,19 +110,22 @@ async function renderFigThumbnail(
}
/**
- * The GUID a layer that was never opened from a file is saved under: its graph ID, which has
- * Figma's `sessionID:localID` shape and never changes, so later saves keep it. Saved GUIDs of
- * opened layers and GUIDs already written win over it.
+ * The GUID a layer without a `source.id` is saved under: its graph ID, which has Figma's
+ * `sessionID:localID` shape and never changes, so later saves keep it. A layer opened from a
+ * file has its record's GUID as its ID, so it keeps that record even when something, such as a
+ * room's copy of it, cleared its `source.id`. Another layer that keeps the GUID as its
+ * `source.id`, and GUIDs already written, win over it.
*/
function ownGuid(
id: string,
- sourceGuidValues: ReadonlySet<string>,
+ sourceOwners: ReadonlyMap<string, string>,
assignedGuidValues: ReadonlySet<string>
): GUID | null {
if (!/^\d+:\d+$/.test(id)) return null
const guid = stringToGuid(id)
const key = `${guid.sessionID}:${guid.localID}`
- return sourceGuidValues.has(key) || assignedGuidValues.has(key) ? null : guid
+ const owner = sourceOwners.get(key)
+ return (owner !== undefined && owner !== id) || assignedGuidValues.has(key) ? null : guid
}
/**
@@ -136,13 +139,13 @@ function savedFromFile(node: SceneNode): boolean {
function assignOwnLayerGuids(
graph: SceneGraph,
- sourceGuidValues: ReadonlySet<string>,
+ sourceOwners: ReadonlyMap<string, string>,
nodeIdToGuid: Map<string, GUID>,
assignedGuidValues: Set<string>
): void {
for (const node of graph.nodes.values()) {
if (savedFromFile(node) || node.id === graph.rootId || nodeIdToGuid.has(node.id)) continue
- const guid = ownGuid(node.id, sourceGuidValues, assignedGuidValues)
+ const guid = ownGuid(node.id, sourceOwners, assignedGuidValues)
if (!guid) continue
nodeIdToGuid.set(node.id, guid)
assignedGuidValues.add(`${guid.sessionID}:${guid.localID}`)
@@ -170,6 +173,13 @@ export function firstUnclaimedLocalId(graph: SceneGraph, propertyIds: readonly s
return last + 1
}
+/** The layer that keeps each GUID as its `source.id`, by GUID. */
+function layerSourceOwners(graph: SceneGraph): Map<string, string> {
+ const owners = new Map<string, string>()
+ for (const node of graph.nodes.values()) if (node.source.id) owners.set(node.source.id, node.id)
+ return owners
+}
+
/** The GUIDs layers keep from the file they were read from, which variables must not take. */
export function layerSourceGuids(graph: SceneGraph): Set<string> {
const guids = new Set<string>()
@@ -261,7 +271,7 @@ function buildCanvasEntries(
localIdCounter: { value: number },
nodeIdToGuid: Map<string, GUID>,
assignedGuidValues: Set<string>,
- sourceGuidValues: ReadonlySet<string>,
+ sourceOwners: ReadonlyMap<string, string>,
ownGuids = true
): { canvasEntries: CanvasExportEntry[]; internalCanvasGuid: GUID | null } {
const canvasEntries: CanvasExportEntry[] = []
@@ -271,7 +281,7 @@ function buildCanvasEntries(
const canvasGuid = (() => {
if (!page.source.id) {
return (
- (ownGuids ? ownGuid(page.id, sourceGuidValues, assignedGuidValues) : null) ?? {
+ (ownGuids ? ownGuid(page.id, sourceOwners, assignedGuidValues) : null) ?? {
sessionID: 0,
localID: localIdCounter.value++
}
@@ -379,7 +389,7 @@ export interface FigExportSetup {
}
export interface FigExportSetupOptions {
- /** Saved identities on pages that may not be loaded; new layer IDs must not claim them. */
+ /** Saved identities on pages that may not be loaded; new variable IDs must not claim them. */
archiveRecordIds?: readonly string[]
/** The first local ID a new GUID may take, above every GUID the target archive holds. */
nextLocalId?: number
@@ -411,7 +421,7 @@ export async function prepareFigExport(
const documentNc = makeDocumentNodeChange(docGuid, graph.documentColorSpace)
const rootNode = graph.getNode(graph.rootId)
if (rootNode) Object.assign(documentNc, rootNode.source.fig.rawNodeFields)
- applyEnabledLibrariesPluginData(documentNc, graph)
+ applyDocumentPluginData(documentNc, graph)
const pages = graph.getPages(true)
const nodeIdToGuid = new Map<string, GUID>()
@@ -424,7 +434,8 @@ export async function prepareFigExport(
const propertyIdToGuid = new Map<string, GUID>()
const nodeSourceGuidValues = layerSourceGuids(graph)
- const reservedLayerGuids = new Set([...nodeSourceGuidValues, ...(options.archiveRecordIds ?? [])])
+ const sourceOwners = layerSourceOwners(graph)
+ const archiveRecordIds = new Set(options.archiveRecordIds)
const propertyIds = collectComponentPropertyIds(graph)
// Before any canvas, variable or layer takes a counter GUID, so none collides.
localIdCounter.value = Math.max(
@@ -440,7 +451,7 @@ export async function prepareFigExport(
localIdCounter,
nodeIdToGuid,
assignedGuidValues,
- reservedLayerGuids,
+ sourceOwners,
true
)
// Archive records keep their GUIDs: claim them before any copy that kept one can.
@@ -461,7 +472,9 @@ export async function prepareFigExport(
assignedGuidValues,
nodeSourceGuidValues,
archived
- ? (id) => archived.has(id) || ownGuid(id, reservedLayerGuids, assignedGuidValues) !== null
+ ? (id) =>
+ archived.has(id) ||
+ (!archiveRecordIds.has(id) && ownGuid(id, sourceOwners, assignedGuidValues) !== null)
: undefined
)
@@ -473,7 +486,7 @@ export async function prepareFigExport(
nodeSourceGuidValues
)
const pluginDataOverrides = renamedBehaviourPluginData(graph, propertyIdToGuid)
- assignOwnLayerGuids(graph, reservedLayerGuids, nodeIdToGuid, assignedGuidValues)
+ assignOwnLayerGuids(graph, sourceOwners, nodeIdToGuid, assignedGuidValues)
return {
graph,
diff --git a/packages/core/tests/io/formats/fig/export/patch/index.test.ts b/packages/core/tests/io/formats/fig/export/patch/index.test.ts
index dd96f82a9..fed7c7285 100644
--- a/packages/core/tests/io/formats/fig/export/patch/index.test.ts
+++ b/packages/core/tests/io/formats/fig/export/patch/index.test.ts
@@ -364,16 +364,13 @@ describe('writing an edited document into its archive', () => {
})
})
- test('keeps every archive record its own when new pages and variables take IDs it uses', async () => {
+ test('keeps every archive record its own when a new variable takes an ID it uses', async () => {
const bytes = await fixtureBytes()
const graph = await open(bytes)
- // New IDs that happen to equal records on a page not loaded yet, as a file saved before can
- // hold: the records must stay theirs.
- const unloaded = [...recordsOf(bytes)].filter(([, record]) =>
- ['Bound', 'Branded'].includes(record.name ?? '')
- )
- const [pageGuid, variableGuid] = unloaded.map(([guid]) => guid)
- graph.createNodeWithId(pageGuid, 'CANVAS', graph.rootId, { name: 'Added page' })
+ // A new ID that happens to equal a layer's record on a page not loaded yet: the record must
+ // stay the layer's.
+ const variableGuid = [...recordsOf(bytes)].find(([, record]) => record.name === 'Branded')?.[0]
+ if (!variableGuid) throw new Error('Expected the Branded layer record')
const [collection] = graph.variableCollections.values()
const [existing] = graph.variables.values()
graph.addVariable({ ...structuredClone(existing), id: variableGuid, name: 'added' })
@@ -386,7 +383,21 @@ describe('writing an edited document into its archive', () => {
expect(after.get(guid)?.name).toBe(record.name)
}
const added = [...after.values()].filter((record) => !before.has(guidKey(record)))
- expect(added.map((record) => record.name).toSorted()).toEqual(['Added page', 'added'])
+ expect(added.map((record) => record.name)).toEqual(['added'])
+ })
+
+ test('writes a layer into its own record when something cleared its source id', async () => {
+ const bytes = await fixtureBytes()
+ const graph = await open(bytes)
+ // A room's copy of a layer carries no source metadata; the layer's ID still names its record.
+ const page = graph.getPages()[0]
+ for (const node of [page, ...graph.getChildren(page.id)])
+ graph.updateNode(node.id, { source: { ...structuredClone(node.source), id: '' } })
+ const patched = await exportFigFile(graph)
+ const before = recordsOf(bytes)
+ const after = recordsOf(patched)
+ expect([...after.keys()].toSorted()).toEqual([...before.keys()].toSorted())
+ for (const [guid, record] of before) expect(after.get(guid)?.parentIndex).toEqual(record.parentIndex)
})
test('keeps layers on unopened pages bound to a variable whose value changes', async () => {
diff --git a/packages/core/tests/io/formats/fig/roundtrip/layer-ids.test.ts b/packages/core/tests/io/formats/fig/roundtrip/layer-ids.test.ts
new file mode 100644
index 000000000..5b3eb069d
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/roundtrip/layer-ids.test.ts
@@ -0,0 +1,49 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import { exportFigFile, initCodec, parseFigFile, SceneGraph } from '@open-pencil/core'
+
+async function reopen(graph: SceneGraph): Promise<SceneGraph> {
+ return parseFigFile((await exportFigFile(graph)).slice().buffer)
+}
+
+function layerIds(graph: SceneGraph): string[] {
+ return [...graph.getAllNodes()].map((node) => node.id).toSorted()
+}
+
+describe('.fig layer ids', () => {
+ beforeAll(async () => {
+ await initCodec()
+ })
+
+ test('a layer keeps its id through a save and a reopen, as do layers added after opening', async () => {
+ const source = new SceneGraph()
+ const page = source.getPages()[0].id
+ const frame = source.createNode('FRAME', page, { name: 'Card', width: 200, height: 100 })
+ source.createNode('RECTANGLE', frame.id, { name: 'Background', width: 200, height: 100 })
+ source.addPage('Second')
+
+ const opened = await reopen(source)
+ const added = opened.createNode('ELLIPSE', opened.getPages()[0].id, { name: 'Added' })
+ const before = layerIds(opened)
+ const reopened = await reopen(opened)
+
+ expect(layerIds(reopened)).toEqual(before)
+ expect(reopened.getNode(added.id)?.name).toBe('Added')
+ expect(opened.rootId).toBe(source.rootId)
+ expect(reopened.rootId).toBe(source.rootId)
+ })
+
+ test('every open of the same file gives every layer the same id, inside instances too', async () => {
+ const source = new SceneGraph()
+ const page = source.getPages()[0].id
+ const component = source.createNode('COMPONENT', page, { name: 'Button', width: 80, height: 32 })
+ source.createNode('TEXT', component.id, { name: 'Label', text: 'Go' })
+ source.createInstance(component.id, page)
+ const bytes = await exportFigFile(source)
+
+ const first = await parseFigFile(bytes.slice().buffer)
+ const second = await parseFigFile(bytes.slice().buffer)
+
+ expect(layerIds(second)).toEqual(layerIds(first))
+ })
+})
diff --git a/packages/core/tests/io/formats/fig/session/document-session.test.ts b/packages/core/tests/io/formats/fig/session/document-session.test.ts
index d5d520a15..b0f973afc 100644
--- a/packages/core/tests/io/formats/fig/session/document-session.test.ts
+++ b/packages/core/tests/io/formats/fig/session/document-session.test.ts
@@ -18,16 +18,17 @@ test('a mid-load creation failure leaves existing nodes and loaded pages unchang
}))
const created: string[] = []
session.graph.onNodeEvents({ created: (node) => created.push(node.id) })
- const create = session.graph.createNode.bind(session.graph)
+ // Layers read from the file are created under their saved GUIDs.
+ const create = session.graph.createNodeWithId.bind(session.graph)
let calls = 0
- session.graph.createNode = (...args) => {
+ session.graph.createNodeWithId = (...args) => {
if (++calls === 2) throw new Error('Injected creation failure')
return create(...args)
}
try {
expect(() => session.loadPage(session.pages[0].id)).toThrow('Injected creation failure')
} finally {
- session.graph.createNode = create
+ session.graph.createNodeWithId = create
}
expect(
[...session.graph.getAllNodes()].map((node) => ({ id: node.id, children: [...node.childIds] }))
diff --git a/packages/docs/development/document-identity.md b/packages/docs/development/document-identity.md
index 86047b388..6f359dd7d 100644
--- a/packages/docs/development/document-identity.md
+++ b/packages/docs/development/document-identity.md
@@ -13,11 +13,13 @@ Every process picks a random session at startup, outside sessions 0 and 1, which
## Imported layers
-Reading a `.fig` file gives its layers handles from a counter of their own, `0:1`, `0:2`, and so on, in the order the reader builds them. The same file gets the same handles on every run, which is what lets `openpencil tree` print an ID that a later `openpencil node` or `diff apply` finds. Pages loaded later continue the counter, and a resumed session carries it in its checkpoint. A handle is not the layer's identity: the GUID the file saved it under is its `source.id`.
+Reading a `.fig` file creates each layer under the GUID its record was saved with, and the document root under the ID OpenPencil saved it with, so a layer has the same ID in every process that opens the file and after every save and reopen. `openpencil tree` prints an ID that a later `openpencil node` or `diff apply` finds, and a Cloud room matches the layers of a tab that reopened the stored file. The saved GUID is also the layer's `source.id`.
+
+Layers inside instances have no records of their own and get IDs from a counter, `0:1`, `0:2`, and so on, in the order the reader builds them. The counter skips every GUID in the archive, including records on pages not loaded yet, so a page loaded later still finds its GUIDs free. The same file gets the same counter IDs on every run; pages loaded later continue the counter, and a resumed session carries it in its checkpoint. A record whose GUID another layer already has, such as a repeated record, takes a counter ID too.
## Saving
-A layer read from the file keeps its saved GUID. A new layer is saved under its own ID when that ID has the GUID shape and no record in the archive, including records on pages never opened, already uses it. Otherwise it takes a counter GUID past every GUID in the file. Reopening the file makes the saved GUID the layer's `source.id`, so later saves keep it.
+Figma saves the root as the document record, always `0:0`, so OpenPencil keeps the root's ID in the document record's plugin data; a file saved elsewhere opens with `0:0` as its root. A layer read from the file keeps its saved GUID, which is its ID, even when something such as a Cloud room's copy of it has no `source.id`. A new layer is saved under its own ID when that ID has the GUID shape and no other layer keeps it as its `source.id`; a new variable also stays clear of every record in the archive, including records on pages never opened. Otherwise it takes a counter GUID past every GUID in the file. Reopening the file creates the layer under that GUID, so later saves keep it.
## Limits
diff --git a/packages/fig/src/document/materialize.ts b/packages/fig/src/document/materialize.ts
index da2cb2e51..0ce950fdb 100644
--- a/packages/fig/src/document/materialize.ts
+++ b/packages/fig/src/document/materialize.ts
@@ -1,6 +1,8 @@
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
import {
generateId,
+ OPEN_PENCIL_PLUGIN_DATA,
remapStyleRunReferences,
SceneGraph,
type SceneNode
@@ -23,6 +25,7 @@ import {
} from '../instance-overrides/source-children'
import { nodeChangeToProps } from '../node-change'
import { generatedFrameCodec } from '../node-change/generated/codecs'
+import { readNodeChangePluginData } from '../node-change/plugin-data'
import { figArchiveRecordInfo, type FigArchiveRecordInfo } from '../record-patch'
import { applyDocumentLayoutBindings } from './bindings/layout'
import { applyDocumentPaintBindings } from './bindings/paint'
@@ -75,6 +78,8 @@ export function materializeFigArchive(
export interface AssemblyState {
graph: SceneGraph
nextImportedId: number
+ /** Every GUID the archive's records keep, on pages loaded or not; minted ids skip them. */
+ recordIds: ReadonlySet<string>
sources: Map<string, string>
components: Map<string, MaterializedComponentOccurrence>
componentIds: Map<string, string>
@@ -84,7 +89,7 @@ export interface AssemblyState {
}
export interface FigSessionCheckpoint {
- /** Continuation of imported runtime handles, including handles consumed then deleted. */
+ /** Continuation of the import's counter ids, including ids consumed then deleted. */
nextImportedId?: number
sources: Array<[string, string]>
componentIds: Array<[string, string]>
@@ -135,6 +140,7 @@ function restoreAssemblyState(
return {
graph,
nextImportedId: checkpoint.nextImportedId ?? inferNextImportedId(graph),
+ recordIds: reader.recordIds,
components,
sources: new Map(checkpoint.sources),
componentIds: new Map(checkpoint.componentIds),
@@ -237,28 +243,71 @@ function seedDefinitionTypes(graph: SceneGraph): Map<string, string> {
}
/**
- * A graph whose own root and first page take imported ids, and every later entity the production
- * allocator's. The graph keeps its generator for life, and a closure keeps every variable its
- * scope shares with other closures, so the generator lives here, away from the archive reader.
+ * The next id the import mints for a layer with no record of its own, such as a copy inside an
+ * instance. It skips every GUID the archive's records keep, so a page loaded later still finds
+ * its layers' GUIDs free.
*/
-function createImportedGraph(): { graph: SceneGraph; nextImportedId: number } {
+function mintImportedId(state: Pick<AssemblyState, 'nextImportedId' | 'recordIds'>): string {
+ let id: string
+ do id = `0:${state.nextImportedId++}`
+ while (state.recordIds.has(id))
+ return id
+}
+
+/**
+ * A graph whose root takes the document record's GUID and whose first page an imported id, and
+ * every later entity the production allocator's. The graph keeps its generator for life, and a
+ * closure keeps every variable its scope shares with other closures, so the generator lives
+ * here, away from the archive reader.
+ */
+function createImportedGraph(
+ rootId: string | undefined,
+ recordIds: ReadonlySet<string>
+): { graph: SceneGraph; nextImportedId: number } {
let initializing = true
- let nextImportedId = 1
- const graph = new SceneGraph(() => (initializing ? `0:${nextImportedId++}` : generateId()))
+ let root = rootId
+ const counter = { nextImportedId: 1, recordIds }
+ const graph = new SceneGraph(() => {
+ if (!initializing) return generateId()
+ const id = root ?? mintImportedId(counter)
+ root = undefined
+ return id
+ })
initializing = false
- return { graph, nextImportedId }
+ return { graph, nextImportedId: counter.nextImportedId }
+}
+
+/**
+ * The root's id: the one OpenPencil saved it under, or else the document record's GUID, which
+ * Figma always saves as `0:0`.
+ */
+function documentRootId(document: NodeChange, recordIds: ReadonlySet<string>): string | undefined {
+ const saved = readNodeChangePluginData(document, OPEN_PENCIL_PLUGIN_DATA.documentId)
+ if (saved && !recordIds.has(saved)) return saved
+ return document.guid && guidToString(document.guid)
}
function createAssemblyState(
reader: ReturnType<typeof createDocumentReader>,
options: DocumentAssemblyOptions
): AssemblyState {
- // Imported runtime handles remain reproducible for CLI inspection and patches. Authored
- // entities use the production allocator even when created in a previously imported graph.
- const imported = createImportedGraph()
+ // Layers take their records' GUIDs and the rest counter ids, the same on every run, for CLI
+ // inspection, patches, and rooms. Authored entities use the production allocator even when
+ // created in a previously imported graph.
+ const document = reader.documentRecord
+ const { recordIds } = reader
+ const imported = createImportedGraph(document && documentRootId(document, recordIds), recordIds)
const { graph } = imported
- let { nextImportedId } = imported
- applyDocumentMetadata(graph, reader.documentRecord)
+ const state: AssemblyState = {
+ graph,
+ nextImportedId: imported.nextImportedId,
+ recordIds,
+ sources: new Map(),
+ components: new Map(),
+ componentIds: new Map(),
+ savedSizeNodes: new Set()
+ }
+ applyDocumentMetadata(graph, document)
for (const [hash, bytes] of options.images ?? []) graph.images.set(hash, bytes.slice())
graph.applyImportedStateDuring(
() =>
@@ -268,17 +317,10 @@ function createAssemblyState(
options.onUnsupportedResource,
options.onUnsupportedVariableExpression
),
- () => `0:${nextImportedId++}`
+ () => mintImportedId(state)
)
for (const page of graph.getPages()) graph.deleteNode(page.id)
- return {
- graph,
- nextImportedId,
- sources: new Map(),
- components: new Map(),
- componentIds: new Map(),
- savedSizeNodes: new Set()
- }
+ return state
}
/** Compatibility with checkpoints saved before they carried the import counter. */
@@ -350,7 +392,7 @@ function materializeReader(
const plan = reader.planComponents(pages, readOptions, (id) => state.components.has(id))
return state.graph.applyImportedStateDuring(
() => materializeReaderInto(pages, plan, blobs, state, load),
- () => `0:${state.nextImportedId++}`
+ () => mintImportedId(state)
)
}
@@ -375,6 +417,9 @@ function materializeReaderInto(
if (occurrence.layoutScale !== undefined) layoutScales.set(node.id, occurrence.layoutScale)
}
}
+ /** A record's layer keeps the record's GUID, unless a layer has it already: a repeated record. */
+ const recordId = ({ sourceId }: InstanceOccurrence): string | undefined =>
+ graph.isEntityIdTaken(sourceId) ? undefined : sourceId
/** Generated frames whose records name other layers, linked once the pass has made them. */
const linked: Array<{ node: SceneNode; record: NodeChange }> = []
const createShells = (occurrence: InstanceOccurrence, parentId: string): void => {
@@ -387,7 +432,10 @@ function materializeReaderInto(
const { nodeType, ...props } = nodeChangeToProps(occurrence.properties, blobs)
if (nodeType === 'DOCUMENT' || nodeType === 'VARIABLE')
throw new Error(`Unsupported scene type ${nodeType}`)
- const node = graph.createNode(nodeType, parentId, props)
+ const id = recordId(occurrence)
+ const node = id
+ ? graph.createNodeWithId(id, nodeType, parentId, props)
+ : graph.createNode(nodeType, parentId, props)
sources.set(occurrence.sourceId, node.id)
if (node.type === 'COMPONENT') componentIds.set(occurrence.sourceId, node.id)
const codec = generatedFrameCodec(node.type)
@@ -412,7 +460,8 @@ function materializeReaderInto(
const materialized = materializeInstance(graph, parentId, item.occurrence, componentIds, {
blobs,
sourceChildren: mapInstanceSourceChildren(item.occurrence, components),
- existingNodes
+ existingNodes,
+ recordId
})
rememberDerivedSizes(materialized.nodes)
linkInstanceSourceChildren(item.occurrence, materialized, components)
@@ -437,7 +486,8 @@ function materializeReaderInto(
onProgress?.()
const materialized = materializeInstance(graph, parentId, child, componentIds, {
blobs,
- sourceChildren: mapInstanceSourceChildren(child, components)
+ sourceChildren: mapInstanceSourceChildren(child, components),
+ recordId
})
rememberDerivedSizes(materialized.nodes)
linkInstanceSourceChildren(child, materialized, components)
diff --git a/packages/fig/src/document/read.ts b/packages/fig/src/document/read.ts
index 062c56e68..3dc3dd857 100644
--- a/packages/fig/src/document/read.ts
+++ b/packages/fig/src/document/read.ts
@@ -282,6 +282,7 @@ function createScopedReader(
}
})
const knownPageIds = new Set(pages.map((page) => page.id))
+ let recordIds: ReadonlySet<string> | undefined
return {
selectPages(ids: ReadonlySet<string>) {
return createScopedReader(shared, ids)
@@ -289,6 +290,13 @@ function createScopedReader(
get sourceRecords() {
return structuredClone(changes.map(whole))
},
+ /** Every live record's GUID, on every page, read or not. */
+ get recordIds(): ReadonlySet<string> {
+ recordIds ??= new Set(
+ changes.flatMap((change) => (change.guid ? [guidToString(change.guid)] : []))
+ )
+ return recordIds
+ },
get documentRecord() {
const document = changes.find((change) => change.type === 'DOCUMENT')
return structuredClone(document && whole(document))
diff --git a/packages/fig/src/instance-overrides/materialize-instance.ts b/packages/fig/src/instance-overrides/materialize-instance.ts
index 4d3fb6c24..55a6846a9 100644
--- a/packages/fig/src/instance-overrides/materialize-instance.ts
+++ b/packages/fig/src/instance-overrides/materialize-instance.ts
@@ -82,6 +82,11 @@ export interface MaterializeInstanceOptions {
sourceChildren?: ReadonlyMap<InstanceOccurrence, string>
/** Nodes to update in place rather than create, keyed by occurrence. */
existingNodes?: ReadonlyMap<InstanceOccurrence, SceneNode>
+ /**
+ * The id to create a layer under that is a record of its own, not a copy inside an instance:
+ * its saved GUID, so it keeps one id across loads. Undefined creates it under a fresh id.
+ */
+ recordId?: (occurrence: InstanceOccurrence) => string | undefined
}
/** A document or a variable is a resource record, never a node in an expansion. */
@@ -100,7 +105,7 @@ export function materializeInstance(
components: ReadonlyMap<string, string>,
options: MaterializeInstanceOptions = {}
): MaterializedInstance {
- const { blobs = [], sourceChildren = new Map(), existingNodes = new Map() } = options
+ const { blobs = [], sourceChildren = new Map(), existingNodes = new Map(), recordId } = options
if (!graph.getNode(parentId)) throw new Error('Missing materialization parent')
const prepared = new Map<InstanceOccurrence, ReturnType<typeof nodeChangeToProps>>()
const validate = (current: InstanceOccurrence): void => {
@@ -144,6 +149,19 @@ export function materializeInstance(
}
}
}
+ /** A record of its own takes its saved GUID, and a copy inside an instance a fresh id. */
+ const createLayer = (
+ current: InstanceOccurrence,
+ nodeType: SceneNode['type'],
+ parent: string,
+ props: Partial<SceneNode>,
+ owner: SceneNode | undefined
+ ): SceneNode => {
+ const id = owner ? undefined : recordId?.(current)
+ return id
+ ? graph.createNodeWithId(id, nodeType, parent, props)
+ : graph.createNode(nodeType, parent, props)
+ }
const create = (current: InstanceOccurrence, parent: string, owner?: SceneNode): SceneNode => {
const converted = prepared.get(current)
if (!converted) throw new Error('Missing prepared occurrence')
@@ -169,7 +187,7 @@ export function materializeInstance(
if (existing && existing.parentId !== parent) {
throw new Error(`Preallocated occurrence has wrong parent ${current.sourceId}`)
}
- const node = existing ?? graph.createNode(nodeType, parent, propsWithIdentity)
+ const node = existing ?? createLayer(current, nodeType, parent, propsWithIdentity, owner)
if (existing) graph.updateNode(existing.id, propsWithIdentity)
const sharedSource = graph.getNode(sourceChildren.get(current) ?? '')
if (sharedSource) shareUnchanged(node, sharedSource)
diff --git a/packages/fig/tests/document/layer-ids.test.ts b/packages/fig/tests/document/layer-ids.test.ts
new file mode 100644
index 000000000..bbc28fc3c
--- /dev/null
+++ b/packages/fig/tests/document/layer-ids.test.ts
@@ -0,0 +1,78 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+
+import { materializeDocument } from '@open-pencil/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+const DOCUMENT = { sessionID: 0, localID: 0 }
+
+test('layers are created under their records’ GUIDs, and copies in instances under ids of their own', () => {
+ const changes: NodeChange[] = [
+ { guid: DOCUMENT, type: 'DOCUMENT' },
+ {
+ guid: guid(1),
+ type: 'CANVAS',
+ name: 'Design',
+ parentIndex: { guid: DOCUMENT, position: '!' }
+ },
+ { guid: guid(2), type: 'SYMBOL', parentIndex: { guid: guid(1), position: '!' } },
+ {
+ guid: guid(3),
+ type: 'TEXT',
+ parentIndex: { guid: guid(2), position: '!' },
+ textData: { characters: 'Label' }
+ },
+ {
+ guid: guid(4),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '"' },
+ symbolData: { symbolID: guid(2) }
+ }
+ ]
+ const { graph } = materializeDocument(changes)
+ expect(graph.rootId).toBe('0:0')
+ expect(graph.getPages().map((page) => page.id)).toEqual(['1:1'])
+ expect(graph.getNode('1:2')?.type).toBe('COMPONENT')
+ expect(graph.getNode('1:3')?.parentId).toBe('1:2')
+ expect(graph.getNode('1:4')?.componentId).toBe('1:2')
+ const [copy] = graph.getChildren('1:4')
+ expect(copy.text).toBe('Label')
+ expect(copy.id).not.toBe('1:3')
+})
+
+test('ids the import mints skip the GUIDs of pages it has not read', () => {
+ // The unread page's records sit where the import counts from, in session 0.
+ const unread = [
+ { sessionID: 0, localID: 1 },
+ { sessionID: 0, localID: 2 },
+ { sessionID: 0, localID: 3 },
+ { sessionID: 0, localID: 4 }
+ ]
+ const changes: NodeChange[] = [
+ { guid: guid(1), type: 'CANVAS', name: 'Design' },
+ { guid: guid(2), type: 'SYMBOL', parentIndex: { guid: guid(1), position: '!' } },
+ {
+ guid: guid(3),
+ type: 'TEXT',
+ parentIndex: { guid: guid(2), position: '!' },
+ textData: { characters: 'Label' }
+ },
+ {
+ guid: guid(4),
+ type: 'INSTANCE',
+ parentIndex: { guid: guid(1), position: '"' },
+ symbolData: { symbolID: guid(2) }
+ },
+ { guid: unread[0], type: 'CANVAS', name: 'Later' },
+ ...unread.slice(1).map((id, index): NodeChange => ({
+ guid: id,
+ type: 'RECTANGLE',
+ parentIndex: { guid: unread[0], position: String.fromCharCode(33 + index) }
+ }))
+ ]
+ const { graph } = materializeDocument(changes, [], { pageIds: new Set(['1:1']) })
+ expect(graph.getNode('0:1')?.name).toBe('Later')
+ expect(graph.getChildren('1:4')).toHaveLength(1)
+ for (const { localID } of unread.slice(1)) expect(graph.getNode(`0:${localID}`)).toBeUndefined()
+})
diff --git a/packages/fig/tests/document/load-transaction.test.ts b/packages/fig/tests/document/load-transaction.test.ts
index 7852a164c..aa1cb3f8e 100644
--- a/packages/fig/tests/document/load-transaction.test.ts
+++ b/packages/fig/tests/document/load-transaction.test.ts
@@ -15,6 +15,7 @@ test('failed page mutation restores changed existing instance indexes and object
const state: AssemblyState = {
graph,
nextImportedId: 10,
+ recordIds: new Set(),
sources: new Map([['instance', instance.id]]),
components: new Map(),
componentIds: new Map(),
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index 4fefd31c7..110090696 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -526,7 +526,8 @@ export class SceneGraph {
for (const collection of this.variableCollections.values()) count += collection.modes.length
return count
}
- private isEntityIdTaken(id: string): boolean {
+ /** Whether a node, variable, collection, or mode has this id. */
+ isEntityIdTaken(id: string): boolean {
if (this.nodes.has(id) || this.variables.has(id) || this.variableCollections.has(id))
return true
// Callers replace collection maps and edit `modes` in place (history snapshots, transfer,
diff --git a/packages/scene-graph/src/plugin-data/fields.ts b/packages/scene-graph/src/plugin-data/fields.ts
index 47759a65f..4cdd08bce 100644
--- a/packages/scene-graph/src/plugin-data/fields.ts
+++ b/packages/scene-graph/src/plugin-data/fields.ts
@@ -203,6 +203,15 @@ export const OPEN_PENCIL_PLUGIN_DATA = {
textPathBox: jsonPluginDataField('textPathBox', 'format', textPathBox),
/** The library asset a node was inserted from. */
librarySource: jsonPluginDataField('librarySource', 'bookkeeping', librarySource),
+ /**
+ * The document root's id, on the DOCUMENT node, whose own GUID is always Figma's `0:0`; the
+ * root keeps it across a save as every layer keeps its GUID.
+ */
+ documentId: jsonPluginDataField(
+ 'documentId',
+ 'bookkeeping',
+ v.pipe(v.string(), v.nonEmpty(), v.maxLength(64))
+ ),
/** Libraries enabled for the document, on the DOCUMENT node. */
enabledLibraries: jsonPluginDataField('enabledLibraries', 'bookkeeping', enabledLibraries),
/** The library this document publishes as, on the DOCUMENT node. */
diff --git a/tests/engine/io/fig/import/component-props.test.ts b/tests/engine/io/fig/import/component-props.test.ts
index ea4dd3c05..e2e774e10 100644
--- a/tests/engine/io/fig/import/component-props.test.ts
+++ b/tests/engine/io/fig/import/component-props.test.ts
@@ -99,7 +99,6 @@ describe('Figma component property import', () => {
expect(instance?.componentPropertyAssignments).toEqual({ '3:1': 'Profile Item' })
if (!component || !instance) throw new Error('Expected imported component and instance')
expect(graph.getInstances(component.id).map((node) => node.id)).toContain(instance.id)
- expect(graph.instanceIndex.get('1:1')?.has(instance.id)).toBeFalsy()
// Page-shell loading is covered through the replacement session API in session/main-thread.test.ts.
})
diff --git a/tests/integration/collab/cloud-relay.test.ts b/tests/integration/collab/cloud-relay.test.ts
index f03002448..769cbceea 100644
--- a/tests/integration/collab/cloud-relay.test.ts
+++ b/tests/integration/collab/cloud-relay.test.ts
@@ -213,7 +213,8 @@ describe('Cloud document rooms, reopening', () => {
const relay = await startRelay()
const documentId = crypto.randomUUID()
const roomId = `cloud:${documentId}:0`
- const [grace, earlier] = await openedTwice()
+ const [grace, earlier, reopened] = await openedCopies(3)
+ if (!grace || !earlier || !reopened) throw new Error('Expected three tabs')
const first = openCloudDocumentRoom(grace, {
roomId,
transport: relay.join(documentId, 'Grace', 'edit', 'user'),
@@ -234,7 +235,6 @@ describe('Cloud document rooms, reopening', () => {
visit.stop()
visit.session.dispose()
- const [reopened] = await openedTwice()
await until(() => reopened.state.preparation === null)
// A page the room never had, as the file's own copy of a page can be.
const stray = reopened.graph.addPage('Stray')
@@ -356,19 +356,29 @@ describe('Cloud document rooms, opening', () => {
})
/** Tabs that each opened the same stored file, which gives each its own root. */
-async function openedTwice() {
+/** Tabs that each opened the same stored file. */
+async function openedCopies(count: number) {
await initCodec()
const graph = new SceneGraph()
const page = graph.getPages()[0]
if (!page) throw new Error('Expected a page')
graph.createNode('RECTANGLE', page.id, { name: 'Card' })
const bytes = await exportFigFile(graph)
- const open = async () => createEditorStore(await parseFigFile(Uint8Array.from(bytes).buffer))
- const stores = [await open(), await open()] as const
- for (const store of stores) cleanups.push(() => store.preparationController.dispose())
+ const stores = []
+ for (let index = 0; index < count; index++) {
+ const store = createEditorStore(await parseFigFile(Uint8Array.from(bytes).buffer))
+ cleanups.push(() => store.preparationController.dispose())
+ stores.push(store)
+ }
return stores
}
+async function openedTwice() {
+ const [first, second] = await openedCopies(2)
+ if (!first || !second) throw new Error('Expected two tabs')
+ return [first, second] as const
+}
+
describe('Cloud document rooms', () => {
test('tabs that opened the stored file edit one document, and one of them saves', async () => {
const relay = await startRelay()