openpencil/packages/fig/src/document/read.ts
Danila Poyarkov c47b5f8d1d
fix(fig): read, render, and write Figma slots (#850)
* fix(fig): read, render, and write Figma slots

Instances of a component with a slot showed the component's default
content instead of their own, and saving to .fig dropped slot properties,
their settings, and every instance's content.

Figma stores an instance's slot content as a frame on the internal canvas
and assigns the slot property that frame's GUID. The reader follows the
assignment while expanding the slot frame and pulls content frames into
the dependency closure without making them layers. The scene graph gains
a SLOT property type with its settings, a SLOT_CONTENT binding, and the
rule that an assigned slot's content belongs to the instance, which
component sync now leaves alone. The writer emits content frames on the
internal canvas and binds slot frames through the parameter map, as
Figma does.

The occurrence and diagnostic types move from the interpreter to
instance-overrides/occurrence.ts to keep it under the size limit.

* fix(fig): keep slot content through swaps and missing content frames

A slot assignment whose content frame the archive lacks no longer refuses
the document: the reader reports it through onMissingSlotContent, like a
missing component, and the slot keeps its component's content.

Swapping an instance's component, which variant switches do, now carries
the instance's own slot content to the new component's slot of the same
name instead of dropping it, as Figma does.

Component sync reads which slot a frame is from the component, whose
bindings instance copies do not receive. Clipboard export numbers slot
content after the other records on its dependency canvas, and the reader
and writer share Figma's default slot value.

* docs: note slot content kept across variant switches

* fix(fig): pair clipboard text by record and drop dangling slot assignments

The Figma clipboard paired text records with source text nodes by
traversal order, but instance-owned slot content is written after the
selected layers, so slotted text and the text after it swapped shaping
data. Records are now paired with their nodes through their GUIDs.

An instance assignment whose slot content frame is missing is dropped
along with the reported diagnostic, so the slot keeps following its
component instead of looking instance-owned.

* ci: pull the slots fixture for unit tests

* test: use GUID and Array.from in the slot tests

* refactor(fig): group occurrence types and paths in one folder

occurrence.ts and occurrence-path.ts became sibling prefixes when the
occurrence types moved out of the interpreter; they now live in
instance-overrides/occurrence/ as types.ts and path.ts.
2026-10-04 00:45:10 +04:00

172 lines
6.2 KiB
TypeScript

import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { guidToString } from '@open-pencil/kiwi/fig/guid'
import { parseFigBuffer } from '../archive'
import { createOccurrenceInterpreter } from '../instance-overrides/interpret'
import type { InterpretInstanceOptions } from '../instance-overrides/occurrence/types'
import {
bySavedPosition,
createSourceIndex,
type SourceIndex
} from '../instance-overrides/source-index'
import { symbolOverridesOf } from '../instance-overrides/types'
import { applyStyleRefsToFields } from '../node-change/style/refs'
import {
resolveDocumentBindingReferences,
type BindingReferenceDiagnostic
} from './bindings/references'
import { planComponentConstruction } from './components'
import { collectSceneDependencies } from './dependency-closure'
import { inheritComponentPropertyDefinitions } from './property-inheritance'
/** Indexed source document. Resources remain separate from scene occurrences. */
export function createDocumentReader(source: readonly NodeChange[], pageIds?: ReadonlySet<string>) {
return createReader(source, 'copy', pageIds)
}
/** Parse into exclusively owned records; callers never receive the mutable source index. */
export function createArchiveDocumentReader(bytes: ArrayBuffer, pageIds?: ReadonlySet<string>) {
const parsed = parseFigBuffer(bytes)
return {
figKiwiVersion: parsed.figKiwiVersion,
figSchemaDeflated: parsed.figSchemaDeflated,
reader: createReader(parsed.nodeChanges, 'transfer', pageIds),
blobs: parsed.blobs,
images: parsed.images
}
}
function createReader(
source: readonly NodeChange[],
ownership: 'copy' | 'transfer',
pageIds?: ReadonlySet<string>
) {
const bindingDiagnostics: BindingReferenceDiagnostic[] = []
const liveSource = source.filter((node) => node.phase !== 'REMOVED')
const changes = resolveDocumentBindingReferences(
liveSource,
(diagnostic) => bindingDiagnostics.push(diagnostic),
ownership
)
// One index over these records serves inheritance, style lookup, the dependency closure
// and component planning.
const index = createSourceIndex(changes)
inheritComponentPropertyDefinitions(changes, index.sources)
const styles = index.sources
const assets = new Map<string, string>()
for (const node of changes)
if (node.guid && typeof node.key === 'string') {
const id = guidToString(node.guid)
assets.set(node.key, id)
if (typeof node.version === 'string') assets.set(`${node.key}@${node.version}`, id)
}
const resolveStyles = (node: NodeChange): void => {
applyStyleRefsToFields(styles, node, assets)
for (const override of symbolOverridesOf(node)) resolveStyles(override as NodeChange)
}
for (const node of changes) resolveStyles(node)
return createScopedReader(
changes,
bindingDiagnostics,
pageIds,
createSharedReaderState(changes, index)
)
}
/**
* Everything a scoped reader needs that does not depend on which pages are selected. Only
* the page's own subset varies, so the whole-document work happens once per document.
*/
interface SharedReaderState {
index: SourceIndex
sourceInterpreter: ReturnType<typeof createOccurrenceInterpreter>
}
function createSharedReaderState(changes: readonly NodeChange[], index: SourceIndex) {
let sourceInterpreter: SharedReaderState['sourceInterpreter'] | undefined
return {
index,
get sourceInterpreter() {
sourceInterpreter ??= createOccurrenceInterpreter(
changes.filter((change) => change.type !== 'VARIABLE' && change.type !== 'VARIABLE_SET')
)
return sourceInterpreter
}
}
}
function createScopedReader(
changes: NodeChange[],
bindingDiagnostics: BindingReferenceDiagnostic[],
pageIds: ReadonlySet<string> | undefined,
shared: SharedReaderState
) {
const resources = changes.filter(
(change) => change.type === 'VARIABLE' || change.type === 'VARIABLE_SET'
)
const closure = collectSceneDependencies(changes, pageIds, shared.index)
// Deleted components are interpreted per instance; broken hierarchy is not recoverable.
if (closure.missingIds.size)
throw new Error(`Missing reachable sources: ${[...closure.missingIds].join(', ')}`)
const sceneChanges = changes.filter(
(change) =>
change.type !== 'VARIABLE' &&
change.type !== 'VARIABLE_SET' &&
(change.type === 'CANVAS' ||
(change.guid &&
(closure.contentIds.has(guidToString(change.guid)) ||
closure.ancestorIds.has(guidToString(change.guid)))))
)
const sourceInterpreter = shared.sourceInterpreter
const interpreter = createOccurrenceInterpreter(sceneChanges)
const pages = changes
.filter((change) => change.type === 'CANVAS')
.toSorted(bySavedPosition)
.map((page) => {
if (!page.guid) throw new Error('Page has no GUID')
return {
id: guidToString(page.guid),
name: page.name ?? '',
position: page.parentIndex?.position ?? null,
internalOnly: page.internalOnly === true
}
})
const knownPageIds = new Set(pages.map((page) => page.id))
return {
selectPages(ids: ReadonlySet<string>) {
return createScopedReader(changes, bindingDiagnostics, ids, shared)
},
get sourceRecords() {
return structuredClone(changes)
},
get documentRecord() {
return structuredClone(changes.find((change) => change.type === 'DOCUMENT'))
},
dependencyClosure: closure,
pages,
get resources() {
return structuredClone(resources)
},
bindingDiagnostics,
readPage(id: string, options: InterpretInstanceOptions = {}) {
if (!knownPageIds.has(id)) throw new Error(`Unknown page ${id}`)
const page = interpreter.page(id, options)
// A slot content frame is read through the instance assigning it, never as a layer.
page.children = page.children.filter((child) => child.properties.isSlotContent !== true)
return page
},
planComponents(
roots: readonly ReturnType<typeof interpreter.page>[],
options: InterpretInstanceOptions = {}
) {
return planComponentConstruction(
changes,
roots,
(id) => sourceInterpreter.component(id, options),
shared.index.sources
)
},
readComponent: sourceInterpreter.component
}
}