Skip to content

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

fix(fig): read, render, and write Figma slots (#850)

Danila Poyarkovc47b5f8d1db9
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index c955f010a..2274e3987 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -241,7 +241,7 @@ jobs:
with:
lfs: 'true'
# Quick shards read only the small fixtures; heavy-tests.yml pulls the large .fig corpora.
- lfs-include: tests/fixtures/gold-preview.fig,tests/fixtures/circle-text.fig,tests/fixtures/fonts/*
+ lfs-include: tests/fixtures/gold-preview.fig,tests/fixtures/circle-text.fig,tests/fixtures/slots.fig,tests/fixtures/fonts/*
- name: Build shared Core test dependency
run: bun --filter @open-pencil/core build
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b0d51176d..8a12a6abb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -45,6 +45,7 @@
### Fixed
+- Open Figma files that use slots with each instance's own slot content instead of its component's default, keep slot properties, their settings, and instance content when saving back to `.fig`, and keep an instance's slot content when you switch its variant.
- Stop showing a “signal is aborted without reason” error when you switch pages again before the previous page has finished loading.
- Export layers with two shadows as one `effects` prop instead of repeating the `shadow` attribute, background blurs as `backgroundBlur` instead of a layer blur, hidden children with `visible={false}` instead of leaving them out, and per-corner radii even when the uniform radius is 0.
- Apply `strokeAlign`, `strokeDash`, `minH`, and `maxH` in design JSX, which were accepted but ignored, and make `minW` and `maxW` set the layer's minimum and maximum width rather than only clamping its initial width.
diff --git a/packages/core/src/clipboard.ts b/packages/core/src/clipboard.ts
index a0383a97b..f78407914 100644
--- a/packages/core/src/clipboard.ts
+++ b/packages/core/src/clipboard.ts
@@ -1,8 +1,9 @@
import { embedClipboardImages, encodeFigmaClipboard } from '@open-pencil/fig/clipboard'
export { parseFigmaClipboard, figmaNodesBounds } from '@open-pencil/fig/clipboard'
+import { placeSlotContent } from '@open-pencil/fig/node-change'
import { initCodec } from '@open-pencil/kiwi/fig/codec'
import type { GUID, NodeChange as KiwiNodeChange } from '@open-pencil/kiwi/fig/codec'
-import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import { ownsSlotContent, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
import {
appendVariableNodeChanges,
@@ -16,7 +17,8 @@ import {
sceneNodeToKiwi,
makeDocumentNodeChange,
makeCanvasNodeChange,
- buildFontDigestMap
+ buildFontDigestMap,
+ fractionalPosition
} from './kiwi/fig/node-change/serialize'
import { randomInt } from './random'
import { buildDerivedTextDataV4 } from './text/derived-text/clipboard'
@@ -81,6 +83,7 @@ export async function buildFigmaClipboardHTML(
nodeIdToGuid,
assignedGuidValues
)
+ const slotContentRecords: KiwiNodeChange[] = []
for (let i = 0; i < nodes.length; i++) {
collectTextNodes(nodes[i])
nodeChanges.push(
@@ -89,7 +92,8 @@ export async function buildFigmaClipboardHTML(
fontDigestMap,
varIdToGuid: variableIds,
assignedGuidValues,
- modeIdToGuid: modeIds
+ modeIdToGuid: modeIds,
+ slotContentRecords
})
)
}
@@ -119,7 +123,11 @@ export async function buildFigmaClipboardHTML(
for (const node of graph.getAllNodes())
if (node.sharedStyleType && !selected.has(node.id)) dependencies.set(node.id, node)
const dependencyCanvas = { sessionID: 0, localID: 2 }
- if (dependencies.size || graph.variableCollections.size)
+ const hasSlotContent = [...selected].some((id) => {
+ const node = graph.getNode(id)
+ return !!node && ownsSlotContent(graph, node)
+ })
+ if (dependencies.size || graph.variableCollections.size || hasSlotContent)
nodeChanges.push({
...makeCanvasNodeChange(dependencyCanvas, docGuid, '"', 'Clipboard dependencies'),
internalOnly: true
@@ -132,17 +140,32 @@ export async function buildFigmaClipboardHTML(
fontDigestMap,
varIdToGuid: variableIds,
assignedGuidValues,
- modeIdToGuid: modeIds
+ modeIdToGuid: modeIds,
+ slotContentRecords
})
)
}
-
appendVariableNodeChanges(graph, nodeChanges, dependencyCanvas, variableIds, modeIds)
- const textNodeQueue = [...exportedTextNodes]
+ // Slot content is collected while instances serialize; it follows the canvas's other records.
+ const written = nodeChanges.filter(
+ (change) =>
+ change.parentIndex?.guid.sessionID === dependencyCanvas.sessionID &&
+ change.parentIndex.guid.localID === dependencyCanvas.localID
+ ).length
+ placeSlotContent(slotContentRecords, dependencyCanvas, written, fractionalPosition)
+ nodeChanges.push(...slotContentRecords)
+ // Pair each text record with the node it was written from; instance content and slot
+ // content are not emitted in traversal order.
+ const textById = new Map(exportedTextNodes.map((node) => [node.id, node]))
+ const sourceByGuid = new Map<string, SceneNode>()
+ for (const [id, guid] of nodeIdToGuid) {
+ const node = textById.get(id)
+ if (node) sourceByGuid.set(`${guid.sessionID}:${guid.localID}`, node)
+ }
await Promise.all(
nodeChanges.map(async (change) => {
- if (change.type !== 'TEXT') return
- const source = textNodeQueue.shift()
+ if (change.type !== 'TEXT' || !change.guid) return
+ const source = sourceByGuid.get(`${change.guid.sessionID}:${change.guid.localID}`)
if (!source) return
change.textAutoResize = 'NONE'
change.textUserLayoutVersion = 5
diff --git a/packages/core/src/figma-api/components.ts b/packages/core/src/figma-api/components.ts
index dee125373..f9028f41f 100644
--- a/packages/core/src/figma-api/components.ts
+++ b/packages/core/src/figma-api/components.ts
@@ -1,4 +1,5 @@
import type {
+ ComponentPropertyReferenceField,
ComponentPropertyDefinition,
ComponentPropertyType,
SceneGraph,
@@ -251,13 +252,16 @@ function editPropertyDefinitions(
})
return propertyName(updated)
}
-function propertyReferenceField(field: string): 'TEXT' | 'VISIBLE' | 'INSTANCE_SWAP' {
+function propertyReferenceField(field: string): ComponentPropertyReferenceField {
if (field === 'mainComponent') return 'INSTANCE_SWAP'
+ if (field === 'slotContentId') return 'SLOT_CONTENT'
return field === 'characters' ? 'TEXT' : 'VISIBLE'
}
-function propertyReferenceName(field: 'TEXT' | 'VISIBLE' | 'INSTANCE_SWAP'): string {
+/** Figma's names: `slotContentId` is what a slot frame reports for its slot property. */
+function propertyReferenceName(field: ComponentPropertyReferenceField): string {
if (field === 'INSTANCE_SWAP') return 'mainComponent'
+ if (field === 'SLOT_CONTENT') return 'slotContentId'
return field === 'TEXT' ? 'characters' : 'visible'
}
function applyProperty(
diff --git a/packages/core/src/io/formats/fig/export.ts b/packages/core/src/io/formats/fig/export.ts
index 23e18ec05..4ecaa4823 100644
--- a/packages/core/src/io/formats/fig/export.ts
+++ b/packages/core/src/io/formats/fig/export.ts
@@ -6,6 +6,7 @@ import { toUint8Array } from 'js-base64'
import { compressFigDataSync } from '@open-pencil/fig'
import {
buildComponentPropIndex,
+ placeSlotContent,
exportCanvasGuides,
importCanvasGuides,
stringToGuid
@@ -13,7 +14,7 @@ import {
import { initCodec, getCompiledSchema, getSchemaBytes } from '@open-pencil/kiwi/fig/codec'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { decodeBinarySchema, compileSchema, ByteBuffer } from '@open-pencil/kiwi/schema-runtime'
-import type { SceneGraph } from '@open-pencil/scene-graph'
+import { ownsSlotContent, type SceneGraph } from '@open-pencil/scene-graph'
import type { GUID } from '@open-pencil/scene-graph/primitives'
import type { SkiaRenderer } from '#core/canvas'
@@ -204,7 +205,11 @@ function buildCanvasEntries(
}
const hasSharedStyles = [...graph.nodes.values()].some((node) => node.sharedStyleType !== null)
- if ((graph.variableCollections.size > 0 || hasSharedStyles) && internalCanvasGuid === null) {
+ const hasSlotContent = [...graph.nodes.values()].some((node) => ownsSlotContent(graph, node))
+ if (
+ (graph.variableCollections.size > 0 || hasSharedStyles || hasSlotContent) &&
+ internalCanvasGuid === null
+ ) {
internalCanvasGuid = { sessionID: 0, localID: localIdCounter.value++ }
assignedGuidValues.add(`${internalCanvasGuid.sessionID}:${internalCanvasGuid.localID}`)
canvasEntries.push({
@@ -430,6 +435,7 @@ export async function exportFigFile(
...canvasEntries.filter((entry) => entry.page.internalOnly),
...canvasEntries.filter((entry) => !entry.page.internalOnly)
]
+ const slotContentRecords: KiwiNodeChange[] = []
for (const { page, canvasGuid } of orderedCanvasEntries) {
const children = graph
.getChildren(page.id)
@@ -446,11 +452,17 @@ export async function exportFigFile(
assignedGuidValues,
componentPropertyDefinitionsById,
modeIdToGuid,
- propertyIdToGuid
+ propertyIdToGuid,
+ slotContentRecords
})
)
}
}
+ if (internalCanvasGuid) {
+ const first = countCanvasChildren(nodeChanges, internalCanvasGuid)
+ placeSlotContent(slotContentRecords, internalCanvasGuid, first, fractionalPosition)
+ nodeChanges.push(...slotContentRecords)
+ }
const msg: Record<string, unknown> = {
type: 'NODE_CHANGES',
diff --git a/packages/core/src/kiwi/fig/session/options.ts b/packages/core/src/kiwi/fig/session/options.ts
index 4c50411c4..a40bda688 100644
--- a/packages/core/src/kiwi/fig/session/options.ts
+++ b/packages/core/src/kiwi/fig/session/options.ts
@@ -8,12 +8,14 @@ export type FigReaderDiagnostic =
| { kind: 'assignment'; diagnostic: Parameters<Handler<'onUnresolvedAssignment'>>[0] }
| { kind: 'binding'; diagnostic: Parameters<Handler<'onUnresolvedBinding'>>[0] }
| { kind: 'component'; diagnostic: Parameters<Handler<'onMissingComponent'>>[0] }
+ | { kind: 'slot-content'; diagnostic: Parameters<Handler<'onMissingSlotContent'>>[0] }
/**
* Figma retains override and binding records that address nodes it later deleted, and
* instances of deleted components, and the reader has no replacement to guess at. Opening
* a file skips those records, keeps such instances childless, and reports both, including a
- * swap whose target layer is gone. An ambiguous address means the path is wrong, not stale,
+ * swap whose target layer is gone. A slot whose assigned content frame is gone keeps its
+ * component's content. An ambiguous address means the path is wrong, not stale,
* and still fails.
*/
export function readerSessionOptions(sink: FigReaderDiagnostic[]): DocumentAssemblyOptions {
@@ -22,6 +24,7 @@ export function readerSessionOptions(sink: FigReaderDiagnostic[]): DocumentAssem
onUnresolvedProperty: (diagnostic) => sink.push({ kind: 'property', diagnostic }),
onUnresolvedAssignment: (diagnostic) => sink.push({ kind: 'assignment', diagnostic }),
onUnresolvedBinding: (diagnostic) => sink.push({ kind: 'binding', diagnostic }),
- onMissingComponent: (diagnostic) => sink.push({ kind: 'component', diagnostic })
+ onMissingComponent: (diagnostic) => sink.push({ kind: 'component', diagnostic }),
+ onMissingSlotContent: (diagnostic) => sink.push({ kind: 'slot-content', diagnostic })
}
}
diff --git a/packages/core/tests/io/formats/fig/roundtrip/slots.test.ts b/packages/core/tests/io/formats/fig/roundtrip/slots.test.ts
new file mode 100644
index 000000000..56264122a
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/roundtrip/slots.test.ts
@@ -0,0 +1,106 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import {
+ exportFigFile,
+ initCodec,
+ parseFigFile,
+ type SceneGraph,
+ type SceneNode
+} from '@open-pencil/core'
+import { parseFigBuffer } from '@open-pencil/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { slotPropertyId } from '@open-pencil/scene-graph'
+
+import { FIXTURES } from '#core-tests/helpers/fig/fixtures'
+
+let original: SceneGraph
+let reopened: SceneGraph
+let records: NodeChange[]
+
+type SlotRecord = NodeChange & {
+ isSlotContent?: boolean
+ componentPropDefs?: Array<{ type?: string; slotPropConfig?: unknown }>
+ componentPropAssignments?: Array<{ varValue?: { dataType?: string } }>
+ parameterConsumptionMap?: { entries?: Array<{ variableField?: string }> }
+}
+
+/** Every instance's slot content, by instance name, in layer order. */
+function slotContents(graph: SceneGraph): Record<string, string[]> {
+ const page = graph.getPages().find((candidate) => candidate.name === 'Slots fixture')
+ const result: Record<string, string[]> = {}
+ const names = (node: SceneNode): string[] =>
+ graph
+ .getChildren(node.id)
+ .flatMap((child) => [child.name, ...names(child).map((name) => `${child.name}/${name}`)])
+ for (const node of page ? graph.getChildren(page.id) : []) {
+ if (node.type !== 'INSTANCE') continue
+ const slot = graph.getChildren(node.id).find((child) => slotPropertyId(child))
+ if (slot) result[node.name] = names(slot)
+ }
+ return result
+}
+
+beforeAll(async () => {
+ await initCodec()
+ original = await parseFigFile(await Bun.file(`${FIXTURES}/slots.fig`).arrayBuffer())
+ // An unedited document exports its original archive; an edit makes the export re-encode.
+ const untouched = original.getPages().find((page) => page.name === 'Page 1')
+ if (!untouched) throw new Error('Missing Page 1')
+ original.updateNode(untouched.id, { name: 'Page 1 (edited)' })
+ const exported = await exportFigFile(original)
+ expect(exported).not.toEqual(new Uint8Array(await Bun.file(`${FIXTURES}/slots.fig`).arrayBuffer()))
+ records = parseFigBuffer(exported.slice().buffer).nodeChanges
+ reopened = await parseFigFile(exported.slice().buffer)
+})
+
+describe('slots round trip', () => {
+ test('every instance keeps its slot content', () => {
+ const before = slotContents(original)
+ expect(before['A filled']).toEqual(['Added text', 'Added rectangle'])
+ expect(slotContents(reopened)).toEqual(before)
+ })
+
+ test('slot properties are written as SLOT definitions with their settings', () => {
+ const definitions = records.flatMap(
+ (record) => (record as SlotRecord).componentPropDefs ?? []
+ )
+ const slots = definitions.filter((definition) => definition.type === 'SLOT')
+ // Card empty slot, Card default content, List, Panel, and Panel's two variants. Figma
+ // links a variant's definition to the set's through `parentPropDefId`; the exporter
+ // writes every variant definition in full, as it does for the other property types.
+ expect(slots).toHaveLength(6)
+ expect(slots.filter((definition) => definition.slotPropConfig)).toHaveLength(1)
+ })
+
+ test('slot frames are bound through the parameter map', () => {
+ const bound = records.filter((record) =>
+ (record as SlotRecord).parameterConsumptionMap?.entries?.some(
+ (entry) => entry.variableField === 'SLOT_CONTENT_ID'
+ )
+ )
+ expect(bound.map((record) => record.name ?? '').toSorted()).toEqual([
+ 'Body',
+ 'Content',
+ 'Content',
+ 'Content',
+ 'Items'
+ ])
+ })
+
+ test('assigned content is written as content frames on the internal canvas', () => {
+ const internal = records.find((record) => record.type === 'CANVAS' && record.internalOnly)
+ const frames = records.filter((record) => (record as SlotRecord).isSlotContent)
+ const assignments = records.flatMap((record) =>
+ ((record as SlotRecord).componentPropAssignments ?? []).filter(
+ (assignment) => assignment.varValue?.dataType === 'SLOT_CONTENT_ID'
+ )
+ )
+ // Nine assigned slots: the reset instance assigns nothing, and the cleared one is empty.
+ expect(frames).toHaveLength(9)
+ expect(assignments).toHaveLength(9)
+ for (const frame of frames) {
+ expect(frame.parentIndex?.guid).toEqual(internal?.guid)
+ expect((frame as SlotRecord).parameterConsumptionMap).toBeUndefined()
+ }
+ })
+})
diff --git a/packages/docs/development/roadmap.md b/packages/docs/development/roadmap.md
index 1d78144e9..9aa6c646e 100644
--- a/packages/docs/development/roadmap.md
+++ b/packages/docs/development/roadmap.md
@@ -186,7 +186,7 @@ Figma's design documentation groups features into these areas:
| Components | ✅ | ✅ | ◐ | ✅ | ✅ | Component metadata, descriptions, links, and publish fields mostly round-trip. |
| Component sets / variants | ✅ | ✅ | ◐ | ✅ | ✅ | Multidimensional variant definitions and common instance properties are editable; slots and broader Figma-specific property parity remain incomplete. |
| Instances / overrides | ✅ | ✅ | ◐ | ✅ | ✅ | Component-property refs and typed assignments are modeled and editable; raw symbol overrides and derived data remain preserved for fidelity. |
-| Slots | ↩ | ◐ | — | ↩ | — | Some component property payloads may survive round-trip, but Figma slots are not a first-class workflow. |
+| Slots | ✅ | ✅ | — | ✅ | ◐ | Slot properties, settings, and instance slot content import, render, and round-trip; the editor cannot create or fill slots yet. |
| Connectors | ◐ | ◐ | — | ◐ | ◐ | Type exists, but Figma connector semantics are weak. |
| Shape-with-text / FigJam shapes | ◐ | ◐ | — | ◐ | ◐ | Type exists, but not a full FigJam feature implementation. |
| Slices | ◐ | — | ◐ | ◐ | ✅ | Slice-like export regions exist via tooling, not as true Figma slice nodes. |
diff --git a/packages/fig/docs/instance-evaluation.md b/packages/fig/docs/instance-evaluation.md
index d4a98dcb3..e1da6dfcb 100644
--- a/packages/fig/docs/instance-evaluation.md
+++ b/packages/fig/docs/instance-evaluation.md
@@ -126,7 +126,7 @@ Figma retains such records after deletions, so the application reader opts into
- [Interpreter](../src/instance-overrides/interpret.ts)
- [Static source routing](../src/instance-overrides/source-index.ts)
-- [Occurrence path resolution](../src/instance-overrides/occurrence-path.ts)
+- [Occurrence path resolution](../src/instance-overrides/occurrence/path.ts)
- [Binding evaluation](../src/instance-overrides/interpret-bindings.ts)
- [Text provenance](../src/instance-overrides/text-provenance.ts)
- [Addressing tests](../tests/instance/addressing.test.ts)
diff --git a/packages/fig/src/document/component/checkpoint.ts b/packages/fig/src/document/component/checkpoint.ts
index 7955d340c..5b496ce8e 100644
--- a/packages/fig/src/document/component/checkpoint.ts
+++ b/packages/fig/src/document/component/checkpoint.ts
@@ -1,4 +1,4 @@
-import type { InstanceOccurrence } from '#fig/instance-overrides/interpret'
+import type { InstanceOccurrence } from '#fig/instance-overrides/occurrence/types'
import type { MaterializedComponentOccurrence } from '#fig/instance-overrides/source-children'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
diff --git a/packages/fig/src/document/component/dependencies.ts b/packages/fig/src/document/component/dependencies.ts
index 97a548ab6..e9be41af8 100644
--- a/packages/fig/src/document/component/dependencies.ts
+++ b/packages/fig/src/document/component/dependencies.ts
@@ -1,4 +1,5 @@
import {
+ assignedSlotContent,
forEachOverrideRecord,
symbolDataOf,
type ComponentPropAssignment
@@ -33,8 +34,9 @@ export function componentDependencies(
add(override?.overriddenSymbolID)
for (const definition of (source.componentPropDefs as DependencyDefinition[] | undefined) ??
[]) {
- if (definition.type === 'INSTANCE_SWAP') {
+ if (definition.type === 'INSTANCE_SWAP')
assignment({ value: definition.initialValue, varValue: definition.varValue })
+ if (definition.type === 'INSTANCE_SWAP' || definition.type === 'SLOT') {
for (const preferred of definition.preferredValues?.instanceSwapValues ?? []) {
if (!preferred.key) continue
const id = resolveReference?.({
@@ -57,3 +59,17 @@ export function componentDependencies(
})
return dependencies
}
+
+/** Content frames that instance slot assignments name; they live on the internal canvas. */
+export function slotContentDependencies(node: NodeChange): ReadonlySet<string> {
+ const dependencies = new Set<string>()
+ forEachOverrideRecord(node, (source) => {
+ for (const value of (source.componentPropAssignments as
+ | ComponentPropAssignment[]
+ | undefined) ?? []) {
+ const content = assignedSlotContent(value.varValue?.value)
+ if (content) dependencies.add(guidToString(content))
+ }
+ })
+ return dependencies
+}
diff --git a/packages/fig/src/document/components.ts b/packages/fig/src/document/components.ts
index 26b88b7cb..f573edb72 100644
--- a/packages/fig/src/document/components.ts
+++ b/packages/fig/src/document/components.ts
@@ -1,8 +1,8 @@
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { guidToString } from '@open-pencil/kiwi/fig/guid'
-import type { InstanceOccurrence } from '../instance-overrides/interpret'
-import { occurrences } from '../instance-overrides/occurrence-path'
+import { occurrences } from '../instance-overrides/occurrence/path'
+import type { InstanceOccurrence } from '../instance-overrides/occurrence/types'
import { parentIdOf } from '../instance-overrides/source-index'
export interface ComponentConstruction {
diff --git a/packages/fig/src/document/dependency-closure.ts b/packages/fig/src/document/dependency-closure.ts
index 958cea7a6..5ca655568 100644
--- a/packages/fig/src/document/dependency-closure.ts
+++ b/packages/fig/src/document/dependency-closure.ts
@@ -1,12 +1,12 @@
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { idOf, parentIdOf, type SourceIndex } from '../instance-overrides/source-index'
-import { componentDependencies } from './component/dependencies'
+import { componentDependencies, slotContentDependencies } from './component/dependencies'
import { createResourceResolver } from './resource-reference'
import { styleDependencies } from './style-dependencies'
export interface SceneDependencyClosure {
- /** Live page trees plus explicitly referenced component trees. */
+ /** Live page trees plus explicitly referenced component and slot content trees. */
contentIds: ReadonlySet<string>
/** Required ownership containers, without automatically including their siblings. */
ancestorIds: ReadonlySet<string>
@@ -14,6 +14,8 @@ export interface SceneDependencyClosure {
missingIds: ReadonlySet<string>
/** Components instances or defaults reference that Figma has since deleted. */
missingComponentIds: ReadonlySet<string>
+ /** Slot content frames instance assignments name that the archive does not contain. */
+ missingSlotContentIds: ReadonlySet<string>
externalPreferredKeys: ReadonlySet<string>
}
@@ -67,6 +69,8 @@ export function collectSceneDependencies(
const missingIds = new Set<string>()
const missingComponentIds = new Set<string>()
const componentReferences = new Set<string>()
+ const slotContentReferences = new Set<string>()
+ const missingSlotContentIds = new Set<string>()
validatePageSelection(sources, pageIds)
const pending = changes
.filter(
@@ -81,6 +85,7 @@ export function collectSceneDependencies(
const node = sources.get(id)
if (!node) {
if (componentReferences.has(id)) missingComponentIds.add(id)
+ else if (slotContentReferences.has(id)) missingSlotContentIds.add(id)
else missingIds.add(id)
continue
}
@@ -89,12 +94,22 @@ export function collectSceneDependencies(
externalPreferredKeys.add(key)
)
for (const component of components) componentReferences.add(component)
+ const slotContent = slotContentDependencies(node)
+ for (const content of slotContent) slotContentReferences.add(content)
pending.push(
...(children.get(id) ?? []).flatMap((child) => idOf(child) ?? []),
...styleDependencies(node, resolveReference, availableIds),
- ...components
+ ...components,
+ ...slotContent
)
}
collectAncestors(sources, contentIds, ancestorIds, missingIds)
- return { contentIds, ancestorIds, missingIds, missingComponentIds, externalPreferredKeys }
+ return {
+ contentIds,
+ ancestorIds,
+ missingIds,
+ missingComponentIds,
+ missingSlotContentIds,
+ externalPreferredKeys
+ }
}
diff --git a/packages/fig/src/document/materialize.ts b/packages/fig/src/document/materialize.ts
index 0732c80c3..617c9f649 100644
--- a/packages/fig/src/document/materialize.ts
+++ b/packages/fig/src/document/materialize.ts
@@ -1,9 +1,12 @@
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
-import type { InstanceOccurrence, InterpretInstanceOptions } from '../instance-overrides/interpret'
import { reconcileLiveComponentEdits } from '../instance-overrides/live-component-edits'
import { materializeInstance } from '../instance-overrides/materialize-instance'
+import type {
+ InstanceOccurrence,
+ InterpretInstanceOptions
+} from '../instance-overrides/occurrence/types'
import {
reconcileOccurrenceStructure,
linkInstanceSourceChildren,
diff --git a/packages/fig/src/document/property-records.ts b/packages/fig/src/document/property-records.ts
index cd34ee7af..0f42e6acd 100644
--- a/packages/fig/src/document/property-records.ts
+++ b/packages/fig/src/document/property-records.ts
@@ -7,6 +7,8 @@ interface PropertyDefinition {
varValue?: ComponentPropAssignment['varValue']
}
+const BOUND_FIELDS = new Set(['VISIBLE', 'TEXT_DATA', 'OVERRIDDEN_SYMBOL_ID', 'SLOT_CONTENT_ID'])
+
/** Adapt current typed property values to the interpreter's common representation. */
function normalizeDefaults(node: NodeChange): void {
for (const definition of (node.componentPropDefs as PropertyDefinition[] | undefined) ?? []) {
@@ -25,7 +27,7 @@ export function normalizeComponentPropertyRecords(node: NodeChange): void {
for (const entry of parameters?.entries ?? []) {
const id = entry.variableData?.value?.propRefValue?.defId
if (entry.variableData?.dataType !== 'PROP_REF' || !id || !entry.variableField) continue
- if (!['VISIBLE', 'TEXT_DATA', 'OVERRIDDEN_SYMBOL_ID'].includes(entry.variableField)) continue
+ if (!BOUND_FIELDS.has(entry.variableField)) continue
const ref = { defID: structuredClone(id), componentPropNodeField: entry.variableField }
const index = refs.findIndex(
(candidate) => candidate.componentPropNodeField === entry.variableField
diff --git a/packages/fig/src/document/read.ts b/packages/fig/src/document/read.ts
index f5565ee84..86f72c928 100644
--- a/packages/fig/src/document/read.ts
+++ b/packages/fig/src/document/read.ts
@@ -2,10 +2,8 @@ import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { guidToString } from '@open-pencil/kiwi/fig/guid'
import { parseFigBuffer } from '../archive'
-import {
- createOccurrenceInterpreter,
- type InterpretInstanceOptions
-} from '../instance-overrides/interpret'
+import { createOccurrenceInterpreter } from '../instance-overrides/interpret'
+import type { InterpretInstanceOptions } from '../instance-overrides/occurrence/types'
import {
bySavedPosition,
createSourceIndex,
@@ -152,7 +150,10 @@ function createScopedReader(
bindingDiagnostics,
readPage(id: string, options: InterpretInstanceOptions = {}) {
if (!knownPageIds.has(id)) throw new Error(`Unknown page ${id}`)
- return interpreter.page(id, options)
+ 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>[],
diff --git a/packages/fig/src/instance-overrides/bindings/properties.ts b/packages/fig/src/instance-overrides/bindings/properties.ts
index 31f208c2d..856906958 100644
--- a/packages/fig/src/instance-overrides/bindings/properties.ts
+++ b/packages/fig/src/instance-overrides/bindings/properties.ts
@@ -36,6 +36,7 @@ function assignmentValue(assignment: ComponentPropAssignment): ComponentPropValu
if (variable?.boolValue !== undefined) return { boolValue: variable.boolValue }
if (variable?.textValue !== undefined) return { textValue: variable.textValue }
if (variable?.textDataValue !== undefined) return { textDataValue: variable.textDataValue }
+ if (variable?.slotContentIdValue) return { slotContentIdValue: variable.slotContentIdValue }
return undefined
}
@@ -85,7 +86,7 @@ export function componentBindings(source: NodeChange): PropertyBinding[] {
export interface BoundPropertyClaim {
definitionId: GUID
- field: 'visible' | 'textData' | 'symbolData'
+ field: 'visible' | 'textData' | 'symbolData' | 'slotContent'
origin: PropertyBinding['origin']
}
@@ -122,6 +123,9 @@ export function bindSourceProperties(
} else if (ref.componentPropNodeField === 'OVERRIDDEN_SYMBOL_ID' && value.guidValue) {
result.symbolData = { ...result.symbolData, symbolID: value.guidValue }
claim('symbolData')
+ } else if (ref.componentPropNodeField === 'SLOT_CONTENT_ID' && value.slotContentIdValue) {
+ // The record keeps its fields; the expansion reads the content from the claim's binding.
+ claim('slotContent')
}
}
return result
diff --git a/packages/fig/src/instance-overrides/bindings/variables.ts b/packages/fig/src/instance-overrides/bindings/variables.ts
index 8c0936b61..b25c6aee8 100644
--- a/packages/fig/src/instance-overrides/bindings/variables.ts
+++ b/packages/fig/src/instance-overrides/bindings/variables.ts
@@ -8,7 +8,7 @@ import { linearVariableExpression } from '#fig/node-change/variable/expression'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { setInstanceOverride, type SceneNode } from '@open-pencil/scene-graph'
-import type { InstanceOccurrence } from '../interpret'
+import type { InstanceOccurrence } from '../occurrence/types'
import { uniformScaleOf } from '../types'
export function occurrenceScale(occurrence: InstanceOccurrence): number {
diff --git a/packages/fig/src/instance-overrides/component-closure.ts b/packages/fig/src/instance-overrides/component-closure.ts
index cb26341ba..6b8638916 100644
--- a/packages/fig/src/instance-overrides/component-closure.ts
+++ b/packages/fig/src/instance-overrides/component-closure.ts
@@ -4,13 +4,10 @@ import type { SceneGraph } from '@open-pencil/scene-graph'
import { componentDependencies } from '../document/component/dependencies'
import { linkComponentPropertyValues } from '../document/component/values'
import { createResourceResolver } from '../document/resource-reference'
-import {
- createOccurrenceInterpreter,
- type InstanceOccurrence,
- type InterpretInstanceOptions
-} from './interpret'
+import { createOccurrenceInterpreter } from './interpret'
import { materializeInstance } from './materialize-instance'
-import { occurrences } from './occurrence-path'
+import { occurrences } from './occurrence/path'
+import type { InstanceOccurrence, InterpretInstanceOptions } from './occurrence/types'
import {
linkInstanceSourceChildren,
mapInstanceSourceChildren,
diff --git a/packages/fig/src/instance-overrides/derived-symbol-data.ts b/packages/fig/src/instance-overrides/derived-symbol-data.ts
index 7698fba63..3a42a5494 100644
--- a/packages/fig/src/instance-overrides/derived-symbol-data.ts
+++ b/packages/fig/src/instance-overrides/derived-symbol-data.ts
@@ -1,4 +1,4 @@
-import type { InstanceOccurrence } from './interpret'
+import type { InstanceOccurrence } from './occurrence/types'
import type { DerivedSymbolOverride } from './types'
/** Copy one saved occurrence-derived record onto its target; a cache, not a claim. */
diff --git a/packages/fig/src/instance-overrides/index.ts b/packages/fig/src/instance-overrides/index.ts
index 15b1ae179..9c0726cd1 100644
--- a/packages/fig/src/instance-overrides/index.ts
+++ b/packages/fig/src/instance-overrides/index.ts
@@ -4,7 +4,7 @@ export type {
InstanceOccurrence,
InterpretInstanceOptions,
InstancePathDiagnostic
-} from './interpret'
+} from './occurrence/types'
export { materializeInstance } from './materialize-instance'
export { materializeComponentClosure } from './component-closure'
export { linkInstanceSourceChildren, mapInstanceSourceChildren } from './source-children'
diff --git a/packages/fig/src/instance-overrides/interpret.ts b/packages/fig/src/instance-overrides/interpret.ts
index 9e4358c67..199bb116b 100644
--- a/packages/fig/src/instance-overrides/interpret.ts
+++ b/packages/fig/src/instance-overrides/interpret.ts
@@ -1,6 +1,5 @@
import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
import { guidToString } from '@open-pencil/kiwi/fig/guid'
-import type { Vector } from '@open-pencil/scene-graph'
import { cloneRecord } from '../node-change/clone'
import { mergeVariableConsumptionMaps } from '../node-change/variable/bindings'
@@ -29,12 +28,14 @@ import {
pathError,
resolveOccurrencePath,
SegmentError
-} from './occurrence-path'
+} from './occurrence/path'
+import type { InstanceOccurrence, InterpretInstanceOptions } from './occurrence/types'
import { applyPlacedConstraints } from './resize'
import { applyInstanceLayoutScale } from './scale/layout'
import {
createSourceIndex,
findStaticSegment,
+ idOf,
readOverrideKey,
recordMatches,
resolvesInSourceComponent,
@@ -43,7 +44,11 @@ import {
type SourceIndex
} from './source-index'
import { invalidateInheritedTextData } from './text-provenance'
-import type { ComponentPropAssignment, DerivedSymbolOverride } from './types'
+import {
+ assignedSlotContent,
+ type ComponentPropAssignment,
+ type DerivedSymbolOverride
+} from './types'
/**
* Figma's instance model reduces to three things: an instance expands its component's
@@ -58,69 +63,7 @@ import type { ComponentPropAssignment, DerivedSymbolOverride } from './types'
* after inner ones by construction. Saved derived data is a cache, applied last.
*/
-/** An explicit claim keeps the complete path relative to its owning occurrence. */
-export interface InstancePropertyClaim {
- /** Source record declaring the claim; preserved when inherited by another occurrence. */
- declaredBy: string
- path: readonly GUID[]
- properties: Record<string, unknown>
-}
-
-/** One occurrence, not a shared source node or a SceneGraph editing clone. */
-export interface InstanceOccurrence {
- readonly sourceId: string
- readonly overrideKey: GUID | undefined
- mainComponentId: string | null
- mainComponentOverrideKey?: GUID
- sourceComponentOverrideKey?: GUID
- sourceComponentId?: GUID
- properties: NodeChange
- children: InstanceOccurrence[]
- /** Explicit property records declared by this occurrence's source. */
- propertyClaims: InstancePropertyClaim[]
- bindingClaims: BoundPropertyClaim[]
- derivedSize?: Vector
- /** Cumulative scale for unresolved layout-distance variable values. */
- layoutScale?: number
- /** Per-field declaration-space multipliers, composed as owners expand. */
- variableBindingScales?: Record<string, number>
- /** Whether this expansion supplies a name rather than only inheriting it. */
- hasOwnName: boolean
- defaultInstanceName?: string
-}
-
-export interface InstancePathDiagnostic {
- ownerId: string
- mainComponentId?: string | null
- path: readonly GUID[]
- reason: 'missing-target' | 'ambiguous-target'
-}
-
-export interface InstanceAssignmentDiagnostic extends InstancePathDiagnostic {
- assignments: readonly ComponentPropAssignment[]
-}
-
-/** An instance whose main component the archive no longer contains. */
-export interface MissingComponentDiagnostic {
- ownerId: string
- componentId: string
-}
-
-export { resolveOccurrencePath } from './occurrence-path'
-
-export interface InterpretInstanceOptions {
- /** Apply explicitly saved effective bounds, geometry and typography; no inferred scaling or layout. */
- derivedBounds?: boolean
- /** Unresolved property overrides are skipped only when a diagnostic receiver is supplied. */
- onUnresolvedProperty?: (diagnostic: InstancePathDiagnostic) => void
- /** Explicit partial evaluation: report and skip missing assignment targets. Swaps remain fatal. */
- onUnresolvedAssignment?: (diagnostic: InstanceAssignmentDiagnostic) => void
- /**
- * Keep an instance of a deleted component as a childless instance that retains its
- * saved reference, the way Figma does, instead of rejecting the document.
- */
- onMissingComponent?: (diagnostic: MissingComponentDiagnostic) => void
-}
+export { resolveOccurrencePath } from './occurrence/path'
export function interpretInstance(
changes: readonly NodeChange[],
@@ -376,10 +319,13 @@ function interpretRoot(
bound: Map<string, number>
/** Swap values earlier owners assigned before a later one replaced them. */
superseded: GUID[]
+ /** The content frame an assignment put in this slot frame. */
+ slotContent: string | undefined
} => {
const claims: BoundPropertyClaim[] = []
const bound = new Map<string, number>()
const superseded: GUID[] = []
+ let slotContent: string | undefined
const source = bindSourceProperties(raw, bindings, (claim, binding) => {
claims.push(claim)
if (binding.origin === 'assignment' && binding.rank !== undefined)
@@ -387,8 +333,17 @@ function interpretRoot(
if (claim.field === 'symbolData')
for (const value of binding.superseded ?? [])
if (value.guidValue) superseded.push(value.guidValue)
+ if (claim.field === 'slotContent') {
+ const content = assignedSlotContent(binding.value)
+ slotContent = content ? guidToString(content) : undefined
+ }
})
- return { source, claims, bound, superseded }
+ if (slotContent && !sources.has(slotContent)) {
+ if (!options.onMissingSlotContent) throw new Error(`Missing slot content ${slotContent}`)
+ options.onMissingSlotContent({ slotId: idOf(raw) ?? '', slotContentId: slotContent })
+ slotContent = undefined
+ }
+ return { source, claims, bound, superseded, slotContent }
}
/**
@@ -412,10 +367,13 @@ function interpretRoot(
const own = ownLayers(source, owner)
const structural = [...own.structural, ...layers].sort((a, b) => b.owner.rank - a.owner.rank)
const root = resolveRoot(raw, source, record.superseded, structural, rank)
- const subtree = root.effective
- ? expandBase(owner, { ...root, effective: root.effective }, rank)
- : expandChildren(id, source, bindings, root.groups, root.descendant, rank)
+ let subtree: Subtree
+ if (root.effective) subtree = expandBase(owner, { ...root, effective: root.effective }, rank)
+ else if (record.slotContent)
+ subtree = expandSlotContent(record.slotContent, root.descendant, rank)
+ else subtree = expandChildren(id, source, bindings, root.groups, root.descendant, rank)
const occurrence = createOccurrence(id, raw, source, root, subtree, record.claims)
+ if (record.slotContent) occurrence.slotContentId = record.slotContent
assignedFields.set(occurrence, record.bound)
if (subtree.base && root.replaced.length) replacedComponents.set(occurrence, root.replaced)
declareSourceVariableBindingUnits(occurrence, source)
@@ -498,6 +456,29 @@ function interpretRoot(
return { base: null, children: expanded }
}
+ /**
+ * Slot content is the instance's own layers, saved under a content frame. Component
+ * property bindings do not reach into a slot, so its layers expand outside that scope.
+ */
+ const expandSlotContent = (
+ contentId: string,
+ descendant: readonly StructuralLayer[],
+ rank: number
+ ): Subtree => {
+ const routed = routeToChildren(contentId, descendant)
+ const expanded = (children.get(contentId) ?? []).map((child) => {
+ if (!child.guid) throw new Error('Indexed child has no GUID')
+ const childId = guidToString(child.guid)
+ return expand(childId, [], routed.get(childId) ?? [], rank + 1)
+ })
+ return { base: null, children: expanded }
+ }
+
+ const namesMissingSlotContent = (assignment: ComponentPropAssignment): boolean => {
+ const content = assignedSlotContent(assignment.varValue?.value)
+ return !!content && !sources.has(guidToString(content))
+ }
+
/** Identity and provenance an occurrence inherits from the subtree it expands. */
const inheritedFromBase = (
base: InstanceOccurrence | null
@@ -556,7 +537,10 @@ function interpretRoot(
children: expanded
}
if (source.type === 'INSTANCE')
- occurrence.properties.componentPropAssignments = groups.flatMap((g) => g.assignments)
+ occurrence.properties.componentPropAssignments = groups
+ .flatMap((g) => g.assignments)
+ // A slot whose content frame is gone falls back to its component's content.
+ .filter((assignment) => !namesMissingSlotContent(assignment))
// A swapped instance without a name of its own takes the replacement's default name.
if (base && replaced.length && !occurrence.hasOwnName)
occurrence.properties.name = base.defaultInstanceName ?? base.properties.name
diff --git a/packages/fig/src/instance-overrides/layers.ts b/packages/fig/src/instance-overrides/layers.ts
index b843455a3..7a7cc981f 100644
--- a/packages/fig/src/instance-overrides/layers.ts
+++ b/packages/fig/src/instance-overrides/layers.ts
@@ -1,6 +1,6 @@
import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
-import type { InstanceAssignmentDiagnostic } from './interpret'
+import type { InstanceAssignmentDiagnostic } from './occurrence/types'
import { symbolOverridesOf, type ComponentPropAssignment } from './types'
/** Mutable per-owner frame shared by the layers an owner declares. */
diff --git a/packages/fig/src/instance-overrides/materialize-instance.ts b/packages/fig/src/instance-overrides/materialize-instance.ts
index e621d272f..e64453fd6 100644
--- a/packages/fig/src/instance-overrides/materialize-instance.ts
+++ b/packages/fig/src/instance-overrides/materialize-instance.ts
@@ -10,7 +10,8 @@ import {
occurrenceScale
} from './bindings/variables'
import { OVERRIDE_FIELDS, type OverrideField, type RawOverrideField } from './fields'
-import { resolveOccurrencePath, type InstanceOccurrence } from './interpret'
+import { resolveOccurrencePath } from './interpret'
+import type { InstanceOccurrence } from './occurrence/types'
import { symbolDataOf } from './types'
function occurrenceMetadata(
diff --git a/packages/fig/src/instance-overrides/occurrence-path.ts b/packages/fig/src/instance-overrides/occurrence/path.ts
similarity index 97%
rename from packages/fig/src/instance-overrides/occurrence-path.ts
rename to packages/fig/src/instance-overrides/occurrence/path.ts
index 6b78b75bf..76da1b087 100644
--- a/packages/fig/src/instance-overrides/occurrence-path.ts
+++ b/packages/fig/src/instance-overrides/occurrence/path.ts
@@ -1,9 +1,9 @@
import type { GUID } from '@open-pencil/kiwi/fig/codec'
import { guidToString } from '@open-pencil/kiwi/fig/guid'
-import type { InstanceOccurrence, InstancePathDiagnostic } from './interpret'
-import { sameGuid } from './source-index'
-import { descendants, findWithinBoundary, type TreeShape } from './tree'
+import { sameGuid } from '../source-index'
+import { descendants, findWithinBoundary, type TreeShape } from '../tree'
+import type { InstanceOccurrence, InstancePathDiagnostic } from './types'
export const OCCURRENCE_TREE: TreeShape<InstanceOccurrence> = {
childrenOf: (node) => node.children,
diff --git a/packages/fig/src/instance-overrides/occurrence/types.ts b/packages/fig/src/instance-overrides/occurrence/types.ts
new file mode 100644
index 000000000..fee79140b
--- /dev/null
+++ b/packages/fig/src/instance-overrides/occurrence/types.ts
@@ -0,0 +1,82 @@
+import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
+import type { Vector } from '@open-pencil/scene-graph'
+
+import type { BoundPropertyClaim } from '../bindings/properties'
+import type { ComponentPropAssignment } from '../types'
+
+/** An explicit claim keeps the complete path relative to its owning occurrence. */
+export interface InstancePropertyClaim {
+ /** Source record declaring the claim; preserved when inherited by another occurrence. */
+ declaredBy: string
+ path: readonly GUID[]
+ properties: Record<string, unknown>
+}
+
+/** One occurrence, not a shared source node or a SceneGraph editing clone. */
+export interface InstanceOccurrence {
+ readonly sourceId: string
+ readonly overrideKey: GUID | undefined
+ mainComponentId: string | null
+ mainComponentOverrideKey?: GUID
+ sourceComponentOverrideKey?: GUID
+ sourceComponentId?: GUID
+ properties: NodeChange
+ children: InstanceOccurrence[]
+ /** Explicit property records declared by this occurrence's source. */
+ propertyClaims: InstancePropertyClaim[]
+ bindingClaims: BoundPropertyClaim[]
+ derivedSize?: Vector
+ /** Cumulative scale for unresolved layout-distance variable values. */
+ layoutScale?: number
+ /** Per-field declaration-space multipliers, composed as owners expand. */
+ variableBindingScales?: Record<string, number>
+ /** Whether this expansion supplies a name rather than only inheriting it. */
+ hasOwnName: boolean
+ /**
+ * Set on a slot frame whose instance assigned it content: the source id of the content
+ * frame its children were expanded from. Those children belong to the instance, not to
+ * the component, so they have no counterpart in the component's expansion.
+ */
+ slotContentId?: string
+ defaultInstanceName?: string
+}
+
+export interface InstancePathDiagnostic {
+ ownerId: string
+ mainComponentId?: string | null
+ path: readonly GUID[]
+ reason: 'missing-target' | 'ambiguous-target'
+}
+
+export interface InstanceAssignmentDiagnostic extends InstancePathDiagnostic {
+ assignments: readonly ComponentPropAssignment[]
+}
+
+/** An instance whose main component the archive no longer contains. */
+export interface MissingComponentDiagnostic {
+ ownerId: string
+ componentId: string
+}
+
+/** A slot assignment naming a content frame the archive no longer contains. */
+export interface MissingSlotContentDiagnostic {
+ /** The slot frame being expanded, as the source record that declares it. */
+ slotId: string
+ slotContentId: string
+}
+
+export interface InterpretInstanceOptions {
+ /** Apply explicitly saved effective bounds, geometry and typography; no inferred scaling or layout. */
+ derivedBounds?: boolean
+ /** Unresolved property overrides are skipped only when a diagnostic receiver is supplied. */
+ onUnresolvedProperty?: (diagnostic: InstancePathDiagnostic) => void
+ /** Explicit partial evaluation: report and skip missing assignment targets. Swaps remain fatal. */
+ onUnresolvedAssignment?: (diagnostic: InstanceAssignmentDiagnostic) => void
+ /**
+ * Keep an instance of a deleted component as a childless instance that retains its
+ * saved reference, the way Figma does, instead of rejecting the document.
+ */
+ onMissingComponent?: (diagnostic: MissingComponentDiagnostic) => void
+ /** Keep the component's own slot content where the assigned content frame is gone. */
+ onMissingSlotContent?: (diagnostic: MissingSlotContentDiagnostic) => void
+}
diff --git a/packages/fig/src/instance-overrides/resize.ts b/packages/fig/src/instance-overrides/resize.ts
index 89b3e5103..fe5f85dbc 100644
--- a/packages/fig/src/instance-overrides/resize.ts
+++ b/packages/fig/src/instance-overrides/resize.ts
@@ -1,6 +1,6 @@
import type { NodeChange, Vector } from '@open-pencil/kiwi/fig/codec'
-import type { InstanceOccurrence } from './interpret'
+import type { InstanceOccurrence } from './occurrence/types'
import { uniformScaleOf } from './types'
export function applyPlacedConstraints(
diff --git a/packages/fig/src/instance-overrides/scale/layout.ts b/packages/fig/src/instance-overrides/scale/layout.ts
index 05a25da6e..b818fecf1 100644
--- a/packages/fig/src/instance-overrides/scale/layout.ts
+++ b/packages/fig/src/instance-overrides/scale/layout.ts
@@ -1,8 +1,8 @@
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { LAYOUT_DISTANCE_FIELDS } from '../fields'
-import type { InstanceOccurrence } from '../interpret'
-import { occurrences } from '../occurrence-path'
+import { occurrences } from '../occurrence/path'
+import type { InstanceOccurrence } from '../occurrence/types'
import { uniformScaleOf } from '../types'
import { scaleTextLayout } from './text'
diff --git a/packages/fig/src/instance-overrides/source-children.ts b/packages/fig/src/instance-overrides/source-children.ts
index 493ba3de4..d5df13491 100644
--- a/packages/fig/src/instance-overrides/source-children.ts
+++ b/packages/fig/src/instance-overrides/source-children.ts
@@ -1,8 +1,8 @@
import { setInstanceOverride, type SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
-import type { InstanceOccurrence } from './interpret'
import type { MaterializedInstance } from './materialize-instance'
-import { occurrences } from './occurrence-path'
+import { occurrences } from './occurrence/path'
+import type { InstanceOccurrence } from './occurrence/types'
export interface MaterializedComponentOccurrence {
occurrence: InstanceOccurrence
@@ -88,6 +88,8 @@ export function linkInstanceSourceChildren(
throw new Error(`Missing materialized correspondence for ${child.sourceId}`)
}
links.push({ owner, target: targetNode, source: sourceNode })
+ // Slot content is the instance's own; its instances are owners in their own right.
+ if (child.slotContentId) continue
if (child.mainComponentId === counterpart.mainComponentId) {
match(child, counterpart, owner, sourceNodes)
}
@@ -136,6 +138,7 @@ export function mapInstanceSourceChildren(
if (!node) throw new Error(`Unmaterialized source child ${counterpart.sourceId}`)
result.set(child, node.id)
if (child.mainComponentId !== null) expand(child)
+ else if (child.slotContentId) for (const content of child.children) visit(content)
else matchChildren(child, counterpart, nodes)
}
}
diff --git a/packages/fig/src/instance-overrides/types.ts b/packages/fig/src/instance-overrides/types.ts
index 54cdd8f68..6e6b3e146 100644
--- a/packages/fig/src/instance-overrides/types.ts
+++ b/packages/fig/src/instance-overrides/types.ts
@@ -54,6 +54,21 @@ export type ComponentPropValue = {
textValue?: ComponentPropTextValue
textDataValue?: { characters?: string }
guidValue?: GUID
+ /** A slot's content frame; the all-ones GUID means the component's own content. */
+ slotContentIdValue?: { guid?: GUID }
+}
+
+/** Figma's slot value for "the component's own content", the default of every slot property. */
+export const DEFAULT_SLOT_CONTENT: Readonly<GUID> = { sessionID: 0xffffffff, localID: 0xffffffff }
+
+/** The content frame a slot value names, unless it names the component's own content. */
+export function assignedSlotContent(value: ComponentPropValue | undefined): GUID | undefined {
+ const guid = value?.slotContentIdValue?.guid
+ if (!guid) return undefined
+ return guid.sessionID === DEFAULT_SLOT_CONTENT.sessionID &&
+ guid.localID === DEFAULT_SLOT_CONTENT.localID
+ ? undefined
+ : guid
}
export interface ComponentPropAssignment {
@@ -65,6 +80,7 @@ export interface ComponentPropAssignment {
textValue?: string
textDataValue?: { characters?: string }
symbolIdValue?: { guid?: GUID }
+ slotContentIdValue?: { guid?: GUID }
}
}
}
diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.ts
index c9c605926..22d2c374c 100644
--- a/packages/fig/src/node-change/convert.ts
+++ b/packages/fig/src/node-change/convert.ts
@@ -62,6 +62,7 @@ import type {
SharedStyleType,
VectorNetwork,
ComponentPropertyDefinition,
+ SlotSettings,
ComponentPropertyReference,
ComponentPropertyType,
SymbolLink,
@@ -705,7 +706,8 @@ const COMPONENT_PROP_TYPE_MAP: Record<string, ComponentPropertyType> = {
TEXT: 'TEXT',
BOOL: 'BOOLEAN',
BOOLEAN: 'BOOLEAN',
- INSTANCE_SWAP: 'INSTANCE_SWAP'
+ INSTANCE_SWAP: 'INSTANCE_SWAP',
+ SLOT: 'SLOT'
}
function componentPropValueToString(value: unknown): string {
@@ -728,10 +730,29 @@ interface RawComponentPropDef {
name?: string
type?: string
initialValue?: unknown
+ description?: string
preferredValues?: {
stringValues?: string[]
instanceSwapValues?: Array<{ key?: string }>
}
+ slotPropConfig?: {
+ stretchChildOnInsert?: boolean
+ displayByDefault?: boolean
+ minChildren?: number
+ maxChildren?: number
+ allowPreferredValuesOnly?: boolean
+ }
+}
+
+function slotSettings(config: NonNullable<RawComponentPropDef['slotPropConfig']>): SlotSettings {
+ const settings: SlotSettings = {
+ allowPreferredValuesOnly: config.allowPreferredValuesOnly ?? false,
+ displayEmptyByDefault: config.displayByDefault ?? false,
+ stretchChildOnInsert: config.stretchChildOnInsert ?? false
+ }
+ if (config.minChildren !== undefined) settings.minChildren = config.minChildren
+ if (config.maxChildren !== undefined) settings.maxChildren = config.maxChildren
+ return settings
}
interface RawComponentPropRef {
@@ -771,19 +792,23 @@ function extractComponentPropertyDefs(nc: NodeChange): ComponentPropertyDefiniti
for (const def of defs) {
if (!def.id || !def.name) continue
const propType = COMPONENT_PROP_TYPE_MAP[def.type ?? ''] ?? 'VARIANT'
- result.push({
+ const definition: ComponentPropertyDefinition = {
id: guidToString(def.id),
name: def.name,
type: propType,
defaultValue: componentPropValueToString(def.initialValue),
variantOptions: propType === 'VARIANT' ? def.preferredValues?.stringValues : undefined,
preferredValues:
- propType === 'INSTANCE_SWAP'
+ propType === 'INSTANCE_SWAP' || propType === 'SLOT'
? def.preferredValues?.instanceSwapValues
?.map((value) => value.key)
.filter((value): value is string => value !== undefined)
: undefined
- })
+ }
+ if (def.description) definition.description = def.description
+ if (propType === 'SLOT' && def.slotPropConfig)
+ definition.slotSettings = slotSettings(def.slotPropConfig)
+ result.push(definition)
}
return result
}
@@ -795,9 +820,11 @@ function extractComponentPropertyRefs(nc: NodeChange): ComponentPropertyReferenc
'0': 'VISIBLE',
'1': 'TEXT',
'2': 'INSTANCE_SWAP',
+ '4': 'SLOT_CONTENT',
VISIBLE: 'VISIBLE',
TEXT_DATA: 'TEXT',
- OVERRIDDEN_SYMBOL_ID: 'INSTANCE_SWAP'
+ OVERRIDDEN_SYMBOL_ID: 'INSTANCE_SWAP',
+ SLOT_CONTENT_ID: 'SLOT_CONTENT'
}
return refs.flatMap((ref) => {
const field = fieldMap[String(ref.componentPropNodeField)]
diff --git a/packages/fig/src/node-change/export/context.ts b/packages/fig/src/node-change/export/context.ts
index 5210c9d8a..5eb7b6734 100644
--- a/packages/fig/src/node-change/export/context.ts
+++ b/packages/fig/src/node-change/export/context.ts
@@ -57,6 +57,11 @@ export interface SceneNodeToKiwiContext {
* variantPropSpecs pointing at the same property reuse the same GUID. */
propertyIdToGuid: Map<string, GUID>
componentPropertyDefinitionsById: ReadonlyMap<string, ComponentPropertyDefinition>
+ /**
+ * Receives the content frames of instance slots. Figma stores them on the internal canvas,
+ * so the caller re-parents the `isSlotContent` roots there after serializing its nodes.
+ */
+ slotContentRecords?: KiwiNodeChange[]
fractionalPosition: (index: number) => string
mapToFigmaType: (type: SceneNode['type']) => string
fillToKiwiPaint: (fill: SceneNode['fills'][number]) => Paint
diff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.ts
index cbf6a98fc..f9b623823 100644
--- a/packages/fig/src/node-change/export/node.ts
+++ b/packages/fig/src/node-change/export/node.ts
@@ -40,6 +40,7 @@ import {
type SceneNodeToKiwiContext
} from './context'
import { mergeOverrides, serializeRuntimePropertyOverrides } from './override-claims'
+import { slotContentAssignment, slotDefinitionFields } from './slots'
export type { KiwiNodeChange, SceneNodeToKiwiContext } from './context'
@@ -535,7 +536,10 @@ function componentPropertyPreferredValues(
definition: ComponentPropertyDefinition,
context: SceneNodeToKiwiContext
) {
- if (definition.type === 'INSTANCE_SWAP' && definition.preferredValues?.length) {
+ if (
+ (definition.type === 'INSTANCE_SWAP' || definition.type === 'SLOT') &&
+ definition.preferredValues?.length
+ ) {
return {
instanceSwapValues: definition.preferredValues.map((value) => {
const target = context.graph.getNode(value)
@@ -553,6 +557,7 @@ function componentPropertyPreferredValues(
function componentPropertyNodeField(field: ComponentPropertyReferenceField): string {
if (field === 'TEXT') return 'TEXT_DATA'
if (field === 'INSTANCE_SWAP') return 'OVERRIDDEN_SYMBOL_ID'
+ if (field === 'SLOT_CONTENT') return 'SLOT_CONTENT_ID'
return 'VISIBLE'
}
@@ -612,7 +617,8 @@ function applyParameterReferences(nc: KiwiNodeChange, refs: ExportedPropertyRefe
const types: Record<string, string> = {
VISIBLE: 'BOOLEAN',
TEXT_DATA: 'STRING',
- OVERRIDDEN_SYMBOL_ID: 'SYMBOL_ID'
+ OVERRIDDEN_SYMBOL_ID: 'SYMBOL_ID',
+ SLOT_CONTENT_ID: 'SLOT_CONTENT_ID'
}
for (const ref of refs)
entries.push({
@@ -646,31 +652,60 @@ function applyComponentMetadata(
}
if (node.symbolDescription) nc.symbolDescription = node.symbolDescription
if (node.symbolLinks.length > 0) nc.symbolLinks = structuredClone(node.symbolLinks)
- const componentPropDefs = node.componentPropertyDefinitions.map((def) => ({
- id: getOrCreatePropertyGuid(context, def.id, localIdCounter),
- name: def.name,
- type: componentPropertyTypeForKiwi(def.type),
- initialValue: componentPropertyValue(def.type, def.defaultValue, context, localIdCounter),
- varValue: componentPropertyVariableValue(def.type, def.defaultValue, context, localIdCounter),
- preferredValues: componentPropertyPreferredValues(def, context)
- }))
+ const componentPropDefs = node.componentPropertyDefinitions.map((def) => {
+ const record: Record<string, unknown> = {
+ id: getOrCreatePropertyGuid(context, def.id, localIdCounter),
+ name: def.name,
+ type: componentPropertyTypeForKiwi(def.type),
+ preferredValues: componentPropertyPreferredValues(def, context)
+ }
+ if (def.type === 'SLOT') Object.assign(record, slotDefinitionFields(def))
+ else {
+ record.initialValue = componentPropertyValue(
+ def.type,
+ def.defaultValue,
+ context,
+ localIdCounter
+ )
+ record.varValue = componentPropertyVariableValue(
+ def.type,
+ def.defaultValue,
+ context,
+ localIdCounter
+ )
+ }
+ if (def.description) record.description = def.description
+ return record
+ })
if (shouldSerializeRawBackedField(node, 'componentPropDefs', componentPropDefs.length > 0)) {
nc.componentPropDefs = componentPropDefs
}
- const componentPropRefs = node.componentPropertyReferences.map((ref) => ({
+ const parameterRefs = node.componentPropertyReferences.map((ref) => ({
defID: getOrCreatePropertyGuid(context, ref.propertyId, localIdCounter),
componentPropNodeField: componentPropertyNodeField(ref.field)
}))
+ // Figma binds a slot frame only through its parameter map, never a legacy property ref.
+ const componentPropRefs = parameterRefs.filter(
+ (ref) => ref.componentPropNodeField !== 'SLOT_CONTENT_ID'
+ )
if (shouldSerializeRawBackedField(node, 'componentPropRefs', componentPropRefs.length > 0)) {
nc.componentPropRefs = componentPropRefs
}
- applyParameterReferences(nc, componentPropRefs)
+ applyParameterReferences(nc, parameterRefs)
const componentPropAssignments = Object.entries(node.componentPropertyAssignments)
.map(([propertyId, value]) => {
const definition = context.componentPropertyDefinitionsById.get(propertyId)
if (!definition) return null
+ if (definition.type === 'SLOT')
+ return slotContentAssignment(
+ context,
+ node,
+ propertyId,
+ getOrCreatePropertyGuid(context, propertyId, localIdCounter),
+ localIdCounter
+ )
return {
defID: getOrCreatePropertyGuid(context, propertyId, localIdCounter),
value: componentPropertyValue(definition.type, value, context, localIdCounter),
diff --git a/packages/fig/src/node-change/export/override-claims.ts b/packages/fig/src/node-change/export/override-claims.ts
index ae44da5e2..20d701e09 100644
--- a/packages/fig/src/node-change/export/override-claims.ts
+++ b/packages/fig/src/node-change/export/override-claims.ts
@@ -1,7 +1,7 @@
import { SCENE_OVERRIDE_FIELDS } from '#fig/instance-overrides/fields'
import { stringToGuid } from '@open-pencil/kiwi/fig/guid'
-import { forEachInstanceOverride, type SceneNode } from '@open-pencil/scene-graph'
+import { forEachInstanceOverride, ownsSlotContent, type SceneNode } from '@open-pencil/scene-graph'
import type { GUID, Vector } from '@open-pencil/scene-graph/primitives'
import { instanceExportAddress } from '../instance/geometry'
@@ -180,6 +180,8 @@ export function serializeRuntimePropertyOverrides(
)
if (claim) result.push(claim)
})
+ // Slot content the instance owns carries its own values; it has no component address.
+ if (ownsSlotContent(context.graph, node)) return
for (const child of context.graph.getChildren(node.id)) visit(child)
}
visit(instance)
diff --git a/packages/fig/src/node-change/export/slots.ts b/packages/fig/src/node-change/export/slots.ts
new file mode 100644
index 000000000..106529f25
--- /dev/null
+++ b/packages/fig/src/node-change/export/slots.ts
@@ -0,0 +1,117 @@
+import { DEFAULT_SLOT_CONTENT } from '#fig/instance-overrides/types'
+
+import {
+ ownsSlotContent,
+ slotPropertyId,
+ type ComponentPropertyDefinition,
+ type SceneNode
+} from '@open-pencil/scene-graph'
+import type { GUID } from '@open-pencil/scene-graph/primitives'
+
+import type { KiwiNodeChange, SceneNodeToKiwiContext } from './context'
+
+function slotContentValue(guid: GUID) {
+ return {
+ value: { slotContentIdValue: { guid } },
+ dataType: 'SLOT_CONTENT_ID',
+ resolvedDataType: 'SLOT_CONTENT_ID'
+ }
+}
+
+/** Slot-specific fields of a `SLOT` property definition record. */
+export function slotDefinitionFields(
+ definition: ComponentPropertyDefinition
+): Record<string, unknown> {
+ const fields: Record<string, unknown> = {
+ varValue: slotContentValue({ ...DEFAULT_SLOT_CONTENT })
+ }
+ const settings = definition.slotSettings
+ if (!settings) return fields
+ const config: Record<string, unknown> = {
+ stretchChildOnInsert: settings.stretchChildOnInsert,
+ displayByDefault: settings.displayEmptyByDefault,
+ allowPreferredValuesOnly: settings.allowPreferredValuesOnly
+ }
+ if (settings.minChildren !== undefined) config.minChildren = settings.minChildren
+ if (settings.maxChildren !== undefined) config.maxChildren = settings.maxChildren
+ fields.slotPropConfig = config
+ return fields
+}
+
+/** The frame in this instance whose children are its content for a slot property. */
+function ownedSlotFrame(
+ context: SceneNodeToKiwiContext,
+ instance: SceneNode,
+ propertyId: string
+): SceneNode | undefined {
+ const visit = (node: SceneNode): SceneNode | undefined => {
+ for (const child of context.graph.getChildren(node.id)) {
+ if (slotPropertyId(child) === propertyId && ownsSlotContent(context.graph, child))
+ return child
+ // A nested instance's slots are assigned by that instance, not this one.
+ if (child.type === 'INSTANCE') continue
+ const found = visit(child)
+ if (found) return found
+ }
+ return undefined
+ }
+ return visit(instance)
+}
+
+/**
+ * Figma keeps an instance's slot content as a frame on the internal canvas, marked as slot
+ * content, and assigns the slot property that frame's GUID. Its records go to
+ * `context.slotContentRecords`, which the caller parents under its internal canvas; without
+ * that sink the assignment is not written and the instance shows the component's content.
+ */
+export function slotContentAssignment(
+ context: SceneNodeToKiwiContext,
+ instance: SceneNode,
+ propertyId: string,
+ defID: GUID,
+ localIdCounter: { value: number }
+) {
+ const sink = context.slotContentRecords
+ const frame = ownedSlotFrame(context, instance, propertyId)
+ if (!sink || !frame) return null
+ const records = context.sceneNodeToKiwi(
+ frame,
+ { ...DEFAULT_SLOT_CONTENT },
+ 0,
+ localIdCounter,
+ context
+ )
+ const root = records.at(0)
+ if (!root?.guid) return null
+ markSlotContent(root)
+ sink.push(...records)
+ return { defID, varValue: slotContentValue(root.guid) }
+}
+
+/** A content frame holds the content; the binding that made its source a slot stays behind. */
+function markSlotContent(record: KiwiNodeChange): void {
+ record.isSlotContent = true
+ Reflect.deleteProperty(record, 'componentPropRefs')
+ const parameters = record.parameterConsumptionMap as
+ | { entries?: Array<{ variableField?: string }> }
+ | undefined
+ const entries = parameters?.entries?.filter((entry) => entry.variableField !== 'SLOT_CONTENT_ID')
+ if (entries?.length) record.parameterConsumptionMap = { entries }
+ else Reflect.deleteProperty(record, 'parameterConsumptionMap')
+}
+
+/**
+ * Parent the slot content frames among `records` under `canvas` (the internal canvas, or a
+ * clipboard's dependency canvas), numbering from `firstIndex` after what is already there.
+ */
+export function placeSlotContent(
+ records: readonly KiwiNodeChange[],
+ canvas: GUID,
+ firstIndex: number,
+ position: (index: number) => string
+): void {
+ let index = firstIndex
+ for (const record of records)
+ if (record.isSlotContent === true)
+ record.parentIndex = { guid: canvas, position: position(index++) }
+}
diff --git a/packages/fig/src/node-change/index.ts b/packages/fig/src/node-change/index.ts
index 7e15abcb9..525eb7db1 100644
--- a/packages/fig/src/node-change/index.ts
+++ b/packages/fig/src/node-change/index.ts
@@ -5,6 +5,7 @@ export * from './derived-text/data'
export * from './derived-text/glyphs'
export * from './export/node'
export * from './export/runtime'
+export { placeSlotContent } from './export/slots'
export * from './font/features'
export * from './font/style'
export * from './font/variations'
diff --git a/packages/fig/src/node-change/instance/geometry.ts b/packages/fig/src/node-change/instance/geometry.ts
index 49f7f66ef..792e99435 100644
--- a/packages/fig/src/node-change/instance/geometry.ts
+++ b/packages/fig/src/node-change/instance/geometry.ts
@@ -4,6 +4,7 @@ import type { GUID } from '@open-pencil/kiwi/fig/codec'
import {
findInstanceAncestor,
getInstanceOverride,
+ ownsSlotContent,
type SceneGraph,
type SceneNode
} from '@open-pencil/scene-graph'
@@ -99,7 +100,8 @@ export function snapshotInstanceGeometry(
throw new Error(`Ambiguous instance geometry address ${id} under ${owner.id}`)
visited.add(id)
entries.set(id, { ...entries.get(id), guidPath: { guids: path }, ...geometry(child) })
- visit(child)
+ // Slot content the instance owns is written as its own records, not as derived data.
+ if (!ownsSlotContent(graph, child)) visit(child)
}
}
visit(owner)
diff --git a/packages/fig/src/node-change/serialize.ts b/packages/fig/src/node-change/serialize.ts
index 09980e6a7..c87d38a70 100644
--- a/packages/fig/src/node-change/serialize.ts
+++ b/packages/fig/src/node-change/serialize.ts
@@ -520,6 +520,7 @@ export interface SceneNodeToKiwiOptions {
componentPropertyDefinitionsById?: ReadonlyMap<string, ComponentPropertyDefinition>
modeIdToGuid?: Map<string, GUID>
propertyIdToGuid?: Map<string, GUID>
+ slotContentRecords?: KiwiNodeChange[]
}
export function sceneNodeToKiwi(
@@ -541,7 +542,8 @@ export function sceneNodeToKiwi(
runtime = EMPTY_EXPORT_RUNTIME,
componentPropertyDefinitionsById = buildComponentPropIndex(graph),
modeIdToGuid,
- propertyIdToGuid = new Map<string, GUID>()
+ propertyIdToGuid = new Map<string, GUID>(),
+ slotContentRecords
} = options
// Raw paints retain library asset refs; effects use this map because their
// Kiwi schema accepts only GUID-backed aliases.
@@ -559,6 +561,7 @@ export function sceneNodeToKiwi(
assetRefToVarGuid,
componentPropertyDefinitionsById,
propertyIdToGuid,
+ slotContentRecords,
fractionalPosition,
mapToFigmaType,
fillToKiwiPaint,
diff --git a/packages/fig/tests/document/slots.test.ts b/packages/fig/tests/document/slots.test.ts
new file mode 100644
index 000000000..f05867a99
--- /dev/null
+++ b/packages/fig/tests/document/slots.test.ts
@@ -0,0 +1,217 @@
+import { beforeAll, describe, expect, test } from 'bun:test'
+
+import { readFixtureArrayBuffer } from '#fig-tests/helpers/fig-fixtures'
+import { guid } from '#fig-tests/helpers/guid'
+import { materializeDocument, materializeFigArchive } from '#fig/document/materialize'
+import { DEFAULT_SLOT_CONTENT } from '#fig/instance-overrides/types'
+
+import type { GUID, NodeChange } from '@open-pencil/kiwi/fig/codec'
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+/**
+ * `slots.fig` was built with Figma's plugin API (`createSlot`, `appendChild`, `resetSlot`,
+ * `setProperties`) and saved from Figma. Each instance's expected slot content below is
+ * what Figma's `SlotNode.children` reported for that instance before the save.
+ */
+let graph: SceneGraph
+
+function topLevel(name: string): SceneNode {
+ const page = graph.getPages().find((candidate) => candidate.name === 'Slots fixture')
+ const node = page && graph.getChildren(page.id).find((child) => child.name === name)
+ if (!node) throw new Error(`Missing ${name}`)
+ return node
+}
+
+function slotFrame(node: SceneNode, from = graph): SceneNode {
+ const frame = from
+ .getChildren(node.id)
+ .find((child) => child.componentPropertyReferences.some((ref) => ref.field === 'SLOT_CONTENT'))
+ if (!frame) throw new Error(`No slot frame in ${node.name}`)
+ return frame
+}
+
+function slotChildren(name: string): string[] {
+ return graph.getChildren(slotFrame(topLevel(name)).id).map((child) => child.name)
+}
+
+beforeAll(() => {
+ graph = materializeFigArchive(readFixtureArrayBuffer('slots.fig')).graph
+})
+
+describe('slot properties', () => {
+ test('a slot is a SLOT property bound to a frame of its component', () => {
+ const card = topLevel('Card empty slot')
+ const [definition] = card.componentPropertyDefinitions
+ expect(definition).toMatchObject({ name: 'Content', type: 'SLOT' })
+ expect(slotFrame(card).componentPropertyReferences).toEqual([
+ { propertyId: definition.id, field: 'SLOT_CONTENT' }
+ ])
+ })
+
+ test('settings, description and preferred components are kept', () => {
+ const [definition] = topLevel('List').componentPropertyDefinitions
+ expect(definition).toMatchObject({
+ name: 'Items',
+ type: 'SLOT',
+ description: 'Put list items here',
+ preferredValues: ['dd573203ee6ffb4302ba13e151f637f67afdcd94'],
+ slotSettings: {
+ minChildren: 1,
+ maxChildren: 3,
+ allowPreferredValuesOnly: true,
+ displayEmptyByDefault: true,
+ stretchChildOnInsert: true
+ }
+ })
+ })
+
+ test('variants sharing a slot each bind their own definition', () => {
+ const panel = topLevel('Panel')
+ expect(panel.componentPropertyDefinitions.map(({ name, type }) => [name, type])).toEqual([
+ ['Content', 'SLOT'],
+ ['Size', 'VARIANT']
+ ])
+ for (const variant of graph.getChildren(panel.id)) {
+ const [definition] = variant.componentPropertyDefinitions
+ expect(definition.type).toBe('SLOT')
+ expect(slotFrame(variant).componentPropertyReferences[0].propertyId).toBe(definition.id)
+ }
+ })
+})
+
+describe('instance slot content', () => {
+ test('an untouched instance shows the component content and assigns nothing', () => {
+ expect(slotChildren('A untouched')).toEqual([])
+ expect(slotChildren('B untouched')).toEqual(['Default body', 'Default image'])
+ expect(slotChildren('B reset')).toEqual(['Default body', 'Default image'])
+ expect(topLevel('B untouched').componentPropertyAssignments).toEqual({})
+ })
+
+ test('assigned content replaces the default, in its saved order', () => {
+ expect(slotChildren('A filled')).toEqual(['Added text', 'Added rectangle'])
+ expect(slotChildren('B modified')).toEqual([
+ 'Inserted first',
+ 'Default image',
+ 'Added after default'
+ ])
+ expect(slotChildren('B cleared')).toEqual([])
+ })
+
+ test('the instance owns assigned content, which links to no component layer', () => {
+ const instance = topLevel('B modified')
+ const [definition] = topLevel('Card default content').componentPropertyDefinitions
+ expect(Object.keys(instance.componentPropertyAssignments)).toEqual([definition.id])
+ for (const child of graph.getChildren(slotFrame(instance).id))
+ expect(child.componentId).toBeNull()
+ })
+
+ test('instances in a slot keep their own component', () => {
+ const item = topLevel('Item')
+ const content = graph.getChildren(slotFrame(topLevel('D violations')).id)
+ expect(content.map((child) => child.type)).toEqual([
+ 'INSTANCE',
+ 'INSTANCE',
+ 'INSTANCE',
+ 'INSTANCE',
+ 'ROUNDED_RECTANGLE'
+ ])
+ for (const child of content.slice(0, 4)) expect(child.componentId).toBe(item.id)
+ })
+
+ test('content survives a variant switch', () => {
+ expect(slotChildren('Panel small filled')).toEqual(['Slot content'])
+ expect(slotChildren('Panel switched to large')).toEqual(['Survives variant switch?'])
+ })
+
+ test('an instance in a slot can fill its own slot', () => {
+ const [inner] = graph.getChildren(slotFrame(topLevel('A nested')).id)
+ expect(inner.name).toBe('Card default content')
+ expect(graph.getChildren(slotFrame(inner).id).map((child) => child.name)).toEqual([
+ 'Default body',
+ 'Default image',
+ 'Inner added'
+ ])
+ })
+
+ test('content frames are not layers of the internal canvas', () => {
+ const internal = graph.getPages(true).find((page) => page.internalOnly)
+ if (!internal) throw new Error('Missing internal canvas')
+ expect(graph.getChildren(internal.id)).toEqual([])
+ })
+})
+
+describe('missing slot content', () => {
+ /** A card whose slot holds `Default`, and an instance assigning a content frame that is gone. */
+ const records = (): NodeChange[] => {
+ const slotValue = (target: GUID) => ({
+ value: { slotContentIdValue: { guid: target } },
+ dataType: 'SLOT_CONTENT_ID',
+ resolvedDataType: 'SLOT_CONTENT_ID'
+ })
+ return [
+ { guid: guid(1), type: 'DOCUMENT' },
+ { guid: guid(2), type: 'CANVAS', parentIndex: { guid: guid(1), position: '!' } },
+ {
+ guid: guid(3),
+ type: 'SYMBOL',
+ name: 'Card',
+ parentIndex: { guid: guid(2), position: 'a' },
+ componentPropDefs: [
+ { id: guid(10), name: 'Content', type: 'SLOT', varValue: slotValue(DEFAULT_SLOT_CONTENT) }
+ ]
+ },
+ {
+ guid: guid(4),
+ type: 'FRAME',
+ name: 'Content',
+ parentIndex: { guid: guid(3), position: 'a' },
+ parameterConsumptionMap: {
+ entries: [
+ {
+ variableField: 'SLOT_CONTENT_ID',
+ variableData: {
+ value: { propRefValue: { defId: guid(10) } },
+ dataType: 'PROP_REF',
+ resolvedDataType: 'SLOT_CONTENT_ID'
+ }
+ }
+ ]
+ }
+ },
+ {
+ guid: guid(5),
+ type: 'TEXT',
+ name: 'Default',
+ parentIndex: { guid: guid(4), position: 'a' },
+ textData: { characters: 'Default' }
+ },
+ {
+ guid: guid(6),
+ type: 'INSTANCE',
+ name: 'Card',
+ parentIndex: { guid: guid(2), position: 'b' },
+ symbolData: { symbolID: guid(3) },
+ componentPropAssignments: [{ defID: guid(10), varValue: slotValue(guid(99)) }]
+ }
+ ] as NodeChange[]
+ }
+
+ test('is fatal in strict reads', () => {
+ expect(() => materializeDocument(records())).toThrow('Missing slot content')
+ })
+
+ test('is reported, and the slot keeps its component content', () => {
+ const reported: unknown[] = []
+ const result = materializeDocument(records(), [], {
+ onMissingSlotContent: (diagnostic) => reported.push(diagnostic)
+ })
+ const instance = result.sources.get('1:6')
+ const node = instance && result.graph.getNode(instance)
+ if (!node) throw new Error('Missing instance')
+ const content = result.graph.getChildren(slotFrame(node, result.graph).id)
+ expect(content.map((child) => child.name)).toEqual(['Default'])
+ // Without the assignment the slot keeps following its component.
+ expect(node.componentPropertyAssignments).toEqual({})
+ expect(reported).toEqual([{ slotId: '1:4', slotContentId: '1:99' }])
+ })
+})
diff --git a/packages/fig/tests/helpers/errors.ts b/packages/fig/tests/helpers/errors.ts
index bb07aef88..369ffd80c 100644
--- a/packages/fig/tests/helpers/errors.ts
+++ b/packages/fig/tests/helpers/errors.ts
@@ -1,7 +1,7 @@
import { expect } from 'bun:test'
-import type { InstancePathDiagnostic } from '#fig/instance-overrides/interpret'
-import { InstancePathError } from '#fig/instance-overrides/occurrence-path'
+import { InstancePathError } from '#fig/instance-overrides/occurrence/path'
+import type { InstancePathDiagnostic } from '#fig/instance-overrides/occurrence/types'
/**
* Assert why a path failed to resolve rather than how the message reads. A count of
diff --git a/packages/fig/tests/instance-overrides/materialize.test.ts b/packages/fig/tests/instance-overrides/materialize.test.ts
index 2bffdedb4..615d1cc66 100644
--- a/packages/fig/tests/instance-overrides/materialize.test.ts
+++ b/packages/fig/tests/instance-overrides/materialize.test.ts
@@ -1,12 +1,9 @@
import { expect, test } from 'bun:test'
import { guid } from '#fig-tests/helpers/guid'
-import {
- interpretComponent,
- interpretInstance,
- type MissingComponentDiagnostic
-} from '#fig/instance-overrides/interpret'
+import { interpretComponent, interpretInstance } from '#fig/instance-overrides/interpret'
import { materializeInstance } from '#fig/instance-overrides/materialize-instance'
+import type { MissingComponentDiagnostic } from '#fig/instance-overrides/occurrence/types'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { SceneGraph } from '@open-pencil/scene-graph'
diff --git a/packages/fig/tests/instance-overrides/source-closure.test.ts b/packages/fig/tests/instance-overrides/source-closure.test.ts
index bb2e6f099..b8ac1bba1 100644
--- a/packages/fig/tests/instance-overrides/source-closure.test.ts
+++ b/packages/fig/tests/instance-overrides/source-closure.test.ts
@@ -1,10 +1,10 @@
import { expect, test } from 'bun:test'
-import {
- interpretInstance,
- type InstanceOccurrence,
- type InstancePathDiagnostic
-} from '#fig/instance-overrides/interpret'
+import { interpretInstance } from '#fig/instance-overrides/interpret'
+import type {
+ InstanceOccurrence,
+ InstancePathDiagnostic
+} from '#fig/instance-overrides/occurrence/types'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
diff --git a/packages/fig/tests/instance-overrides/stale-path.test.ts b/packages/fig/tests/instance-overrides/stale-path.test.ts
index e16e0bd18..7e0bfb149 100644
--- a/packages/fig/tests/instance-overrides/stale-path.test.ts
+++ b/packages/fig/tests/instance-overrides/stale-path.test.ts
@@ -2,7 +2,8 @@ import { expect, test } from 'bun:test'
import { expectPathError } from '#fig-tests/helpers/errors'
import { guid } from '#fig-tests/helpers/guid'
-import { interpretInstance, type InstancePathDiagnostic } from '#fig/instance-overrides/interpret'
+import { interpretInstance } from '#fig/instance-overrides/interpret'
+import type { InstancePathDiagnostic } from '#fig/instance-overrides/occurrence/types'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
diff --git a/packages/fig/tests/instance-overrides/unresolved-assignments.test.ts b/packages/fig/tests/instance-overrides/unresolved-assignments.test.ts
index ae1104a70..df9842d52 100644
--- a/packages/fig/tests/instance-overrides/unresolved-assignments.test.ts
+++ b/packages/fig/tests/instance-overrides/unresolved-assignments.test.ts
@@ -2,10 +2,8 @@ import { expect, test } from 'bun:test'
import { expectPathError } from '#fig-tests/helpers/errors'
import { guid } from '#fig-tests/helpers/guid'
-import {
- interpretInstance,
- type InstanceAssignmentDiagnostic
-} from '#fig/instance-overrides/interpret'
+import { interpretInstance } from '#fig/instance-overrides/interpret'
+import type { InstanceAssignmentDiagnostic } from '#fig/instance-overrides/occurrence/types'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
diff --git a/packages/scene-graph/src/components/slots.ts b/packages/scene-graph/src/components/slots.ts
new file mode 100644
index 000000000..1a364d006
--- /dev/null
+++ b/packages/scene-graph/src/components/slots.ts
@@ -0,0 +1,104 @@
+import type { SceneGraph } from '../index'
+import type { SceneNode } from '../types'
+
+/** The slot property a frame holds the content of, if it is a slot. */
+export function slotPropertyId(node: SceneNode): string | undefined {
+ return node.componentPropertyReferences.find((reference) => reference.field === 'SLOT_CONTENT')
+ ?.propertyId
+}
+
+/**
+ * Whether this slot frame's children belong to its instance rather than its component: the
+ * nearest enclosing instance assigns the slot. Such content is never synced from the component.
+ */
+export function ownsSlotContent(
+ graph: SceneGraph,
+ node: SceneNode,
+ propertyId = slotPropertyId(node)
+): boolean {
+ if (!propertyId) return false
+ let owner = node.parentId ? graph.nodes.get(node.parentId) : undefined
+ while (owner && owner.type !== 'INSTANCE')
+ owner = owner.parentId ? graph.nodes.get(owner.parentId) : undefined
+ return !!owner && Object.hasOwn(owner.componentPropertyAssignments, propertyId)
+}
+
+/** The name of a slot property as its component (or the component's set) defines it. */
+function slotName(graph: SceneGraph, componentId: string | null, propertyId: string) {
+ const component = componentId ? graph.nodes.get(componentId) : undefined
+ const set = component?.parentId ? graph.nodes.get(component.parentId) : undefined
+ return [component, set]
+ .flatMap((node) => node?.componentPropertyDefinitions ?? [])
+ .find((definition) => definition.id === propertyId && definition.type === 'SLOT')?.name
+}
+
+/** An instance's slot frames, without entering nested instances, whose slots are their own. */
+function slotFrames(graph: SceneGraph, instance: SceneNode): SceneNode[] {
+ const frames: SceneNode[] = []
+ const visit = (node: SceneNode): void => {
+ for (const childId of node.childIds) {
+ const child = graph.nodes.get(childId)
+ if (!child) continue
+ if (slotPropertyId(child)) frames.push(child)
+ else if (child.type !== 'INSTANCE') visit(child)
+ }
+ }
+ visit(instance)
+ return frames
+}
+
+/** Owned slot content parked under its instance while the instance's component changes. */
+export interface ParkedSlotContent {
+ /** Content layer ids by slot name, in layer order. */
+ content: Map<string, string[]>
+ /** The slot assignments the content was parked from. */
+ propertyIds: string[]
+}
+
+/**
+ * Park an instance's own slot content directly under the instance, by slot name, so the
+ * instance's component can be replaced. Figma keeps that content when a variant switch or
+ * swap lands on a component with a slot of the same name.
+ */
+export function detachOwnedSlotContent(graph: SceneGraph, instance: SceneNode): ParkedSlotContent {
+ const parked: ParkedSlotContent = { content: new Map(), propertyIds: [] }
+ for (const frame of slotFrames(graph, instance)) {
+ const propertyId = slotPropertyId(frame)
+ if (!propertyId || !Object.hasOwn(instance.componentPropertyAssignments, propertyId)) continue
+ parked.propertyIds.push(propertyId)
+ const name = slotName(graph, instance.componentId, propertyId)
+ if (!name || parked.content.has(name)) continue
+ const content = [...frame.childIds]
+ for (const id of content) graph.reorderChild(id, instance.id, instance.childIds.length)
+ parked.content.set(name, content)
+ }
+ return parked
+}
+
+/** Move parked content into the new component's slots of the same name and reassign them. */
+export function restoreOwnedSlotContent(
+ graph: SceneGraph,
+ instance: SceneNode,
+ parked: ParkedSlotContent
+): void {
+ if (!parked.propertyIds.length) return
+ const assignments = Object.fromEntries(
+ Object.entries(instance.componentPropertyAssignments).filter(
+ ([id]) => !parked.propertyIds.includes(id)
+ )
+ )
+ const placed = new Set<string>()
+ for (const frame of slotFrames(graph, instance)) {
+ const propertyId = slotPropertyId(frame)
+ const name = propertyId && slotName(graph, instance.componentId, propertyId)
+ const content = name ? parked.content.get(name) : undefined
+ if (!propertyId || !name || !content || placed.has(name)) continue
+ for (const id of Array.from(frame.childIds)) graph.deleteNode(id)
+ for (const [index, id] of content.entries()) graph.reorderChild(id, frame.id, index)
+ assignments[propertyId] = ''
+ placed.add(name)
+ }
+ for (const [name, content] of parked.content)
+ if (!placed.has(name)) for (const id of content) graph.deleteNode(id)
+ graph.updateNode(instance.id, { componentPropertyAssignments: assignments })
+}
diff --git a/packages/scene-graph/src/copy.ts b/packages/scene-graph/src/copy.ts
index e1a1368b1..30ed782e4 100644
--- a/packages/scene-graph/src/copy.ts
+++ b/packages/scene-graph/src/copy.ts
@@ -200,7 +200,8 @@ function copyPropertyDefs(
defs?.map((d) => ({
...d,
variantOptions: d.variantOptions ? [...d.variantOptions] : undefined,
- preferredValues: d.preferredValues ? [...d.preferredValues] : undefined
+ preferredValues: d.preferredValues ? [...d.preferredValues] : undefined,
+ slotSettings: d.slotSettings ? { ...d.slotSettings } : undefined
})) ?? []
)
}
diff --git a/packages/scene-graph/src/index.ts b/packages/scene-graph/src/index.ts
index 64d9bc8d8..53b7e9351 100644
--- a/packages/scene-graph/src/index.ts
+++ b/packages/scene-graph/src/index.ts
@@ -9,6 +9,7 @@ export * from './transfer'
export * from './instance-overrides'
export * from './images'
export * from './components/properties'
+export * from './components/slots'
export * from './copy'
export { createDefaultNode } from './node-defaults'
export {
diff --git a/packages/scene-graph/src/instances.ts b/packages/scene-graph/src/instances.ts
index cc8d4ee29..b3cf21168 100644
--- a/packages/scene-graph/src/instances.ts
+++ b/packages/scene-graph/src/instances.ts
@@ -1,4 +1,5 @@
import type { SceneGraph, SceneNode } from './'
+import { detachOwnedSlotContent, restoreOwnedSlotContent } from './components/slots'
import type { NodeCloneMode } from './copy'
import {
clearInstanceOverrides,
@@ -114,9 +115,11 @@ export function swapInstanceComponent(
if (!previousComponent || instance.name === previousComponent.name) updates.name = component.name
const childIds = Array.from(instance.childIds)
+ const slotContent = detachOwnedSlotContent(graph, instance)
for (const childId of childIds) graph.deleteNode(childId)
graph.updateNode(instanceId, updates)
cloneChildrenWithMapping(graph, componentId, instanceId)
+ restoreOwnedSlotContent(graph, instance, slotContent)
}
const syncingComponentsByGraph = new WeakMap<SceneGraph, Set<string>>()
diff --git a/packages/scene-graph/src/instances/sync.ts b/packages/scene-graph/src/instances/sync.ts
index 8075b215c..80f27ff4f 100644
--- a/packages/scene-graph/src/instances/sync.ts
+++ b/packages/scene-graph/src/instances/sync.ts
@@ -2,6 +2,7 @@
import { isEqual } from 'es-toolkit/predicate'
import type { SceneGraph, SceneNode } from '../'
+import { ownsSlotContent, slotPropertyId } from '../components/slots'
import { cloneNodeProps, copyEffects, copyFills, copyStrokes, copyStyleRuns } from '../copy'
import type { NodeCloneMode } from '../copy'
import {
@@ -382,7 +383,10 @@ export function syncChildren(
if (
compChild.childIds.length > 0 &&
- !hasNodeInstanceOverride(overrides, instParentId, instChild.id, 'componentId')
+ !hasNodeInstanceOverride(overrides, instParentId, instChild.id, 'componentId') &&
+ // The component's frame is the authority on which slot this is; instance copies of
+ // its bindings are not synced.
+ !ownsSlotContent(graph, instChild, slotPropertyId(compChild))
) {
syncChildren(graph, compChildId, instChild.id, overrides)
}
diff --git a/packages/scene-graph/src/types.ts b/packages/scene-graph/src/types.ts
index 4d1e75e20..5bcee959d 100644
--- a/packages/scene-graph/src/types.ts
+++ b/packages/scene-graph/src/types.ts
@@ -587,15 +587,30 @@ export interface SceneNode {
textPathBox: Rect | null
}
-export type ComponentPropertyType = 'VARIANT' | 'TEXT' | 'BOOLEAN' | 'INSTANCE_SWAP'
+export type ComponentPropertyType = 'VARIANT' | 'TEXT' | 'BOOLEAN' | 'INSTANCE_SWAP' | 'SLOT'
-export type ComponentPropertyReferenceField = 'VISIBLE' | 'TEXT' | 'INSTANCE_SWAP'
+/** `SLOT_CONTENT` marks a frame whose children are the slot's content. */
+export type ComponentPropertyReferenceField = 'VISIBLE' | 'TEXT' | 'INSTANCE_SWAP' | 'SLOT_CONTENT'
export interface ComponentPropertyReference {
propertyId: string
field: ComponentPropertyReferenceField
}
+/** Guidance for a slot property; Figma reports a breach but still accepts the content. */
+export interface SlotSettings {
+ minChildren?: number
+ maxChildren?: number
+ allowPreferredValuesOnly: boolean
+ displayEmptyByDefault: boolean
+ /** Content added to the slot fills its counter axis. */
+ stretchChildOnInsert: boolean
+}
+
+/**
+ * For a `SLOT` property, an instance assignment (whatever its value) means the instance owns
+ * that slot's content: the slot frame's children in the instance, which component sync keeps.
+ */
export interface ComponentPropertyDefinition {
id: string
name: string
@@ -603,6 +618,8 @@ export interface ComponentPropertyDefinition {
defaultValue: string
variantOptions?: string[]
preferredValues?: string[]
+ description?: string
+ slotSettings?: SlotSettings
}
export type VariableType = 'COLOR' | 'FLOAT' | 'STRING' | 'BOOLEAN'
diff --git a/packages/scene-graph/tests/components/slots.test.ts b/packages/scene-graph/tests/components/slots.test.ts
new file mode 100644
index 000000000..82c9b1d31
--- /dev/null
+++ b/packages/scene-graph/tests/components/slots.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, test } from 'bun:test'
+
+import { SceneGraph, slotPropertyId, type SceneNode } from '@open-pencil/scene-graph'
+
+/** A component set with a Small and a Large variant, each with a `Content` slot. */
+function panel(graph: SceneGraph, page: SceneNode) {
+ const set = graph.createNode('COMPONENT_SET', page.id, { name: 'Panel' })
+ const variant = (name: string, propertyId: string, slotName = 'Content') => {
+ const component = graph.createNode('COMPONENT', set.id, {
+ name,
+ componentPropertyDefinitions: [
+ { id: propertyId, name: slotName, type: 'SLOT', defaultValue: '' }
+ ]
+ })
+ const slot = graph.createNode('FRAME', component.id, {
+ name: slotName,
+ componentPropertyReferences: [{ propertyId, field: 'SLOT_CONTENT' }]
+ })
+ graph.createNode('TEXT', slot.id, { name: 'Default', text: 'Default' })
+ return component
+ }
+ return {
+ small: variant('Size=Small', 'small:content'),
+ large: variant('Size=Large', 'large:content'),
+ other: variant('Size=Other', 'other:body', 'Body')
+ }
+}
+
+function slotChildren(graph: SceneGraph, instance: SceneNode): string[] {
+ const slot = graph.getChildren(instance.id).find((child) => slotPropertyId(child))
+ return slot ? graph.getChildren(slot.id).map((child) => child.name) : []
+}
+
+/** An instance of `component` whose own content replaced the slot's default. */
+function filled(graph: SceneGraph, page: SceneNode, component: SceneNode, propertyId: string) {
+ const instance = graph.createInstance(component.id, page.id)
+ if (!instance) throw new Error('No instance')
+ const slot = graph.getChildren(instance.id)[0]
+ for (const id of Array.from(slot.childIds)) graph.deleteNode(id)
+ graph.createNode('TEXT', slot.id, { name: 'Mine', text: 'Mine' })
+ graph.updateNode(instance.id, { componentPropertyAssignments: { [propertyId]: '' } })
+ return instance
+}
+
+describe('instance slot content', () => {
+ test('component sync keeps the content an instance owns', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const { small } = panel(graph, page)
+ const owned = filled(graph, page, small, 'small:content')
+ const untouched = graph.createInstance(small.id, page.id)
+ if (!untouched) throw new Error('No instance')
+
+ const defaultText = graph.getChildren(graph.getChildren(small.id)[0].id)[0]
+ graph.updateNode(defaultText.id, { name: 'Edited default' })
+ graph.syncInstances(small.id)
+
+ expect(slotChildren(graph, owned)).toEqual(['Mine'])
+ expect(slotChildren(graph, untouched)).toEqual(['Edited default'])
+ })
+
+ test('a variant switch carries content to the slot of the same name', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const { small, large } = panel(graph, page)
+ const instance = filled(graph, page, small, 'small:content')
+
+ graph.swapInstanceComponent(instance.id, large.id)
+
+ expect(slotChildren(graph, instance)).toEqual(['Mine'])
+ expect(instance.componentPropertyAssignments).toEqual({ 'large:content': '' })
+ })
+
+ test('content without a slot of the same name in the new component is dropped', () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const { small, other } = panel(graph, page)
+ const instance = filled(graph, page, small, 'small:content')
+ const mine = slotChildren(graph, instance)
+
+ graph.swapInstanceComponent(instance.id, other.id)
+
+ expect(mine).toEqual(['Mine'])
+ expect(slotChildren(graph, instance)).toEqual(['Default'])
+ expect(instance.componentPropertyAssignments).toEqual({})
+ expect([...graph.getAllNodes()].filter((node) => node.name === 'Mine')).toEqual([])
+ })
+})
diff --git a/tests/engine/clipboard/figma/html.test.ts b/tests/engine/clipboard/figma/html.test.ts
index 5800b52ff..20a9cfd05 100644
--- a/tests/engine/clipboard/figma/html.test.ts
+++ b/tests/engine/clipboard/figma/html.test.ts
@@ -7,6 +7,7 @@ import {
parseFigmaClipboard,
SceneGraph
} from '@open-pencil/core'
+import { slotPropertyId } from '@open-pencil/scene-graph'
import { expectDefined } from '#tests/helpers/assert'
@@ -47,6 +48,51 @@ describe('buildFigmaClipboardHTML', () => {
expect(html).toContain('figma')
})
+ it('writes slot content and pairs every text record with its own text', async () => {
+ const graph = new SceneGraph()
+ const page = graph.getPages()[0]
+ const card = graph.createNode('COMPONENT', page.id, {
+ name: 'Card',
+ width: 200,
+ height: 100,
+ componentPropertyDefinitions: [
+ { id: 'card:body', name: 'Body', type: 'SLOT', defaultValue: '' }
+ ]
+ })
+ graph.createNode('FRAME', card.id, {
+ name: 'Body',
+ width: 200,
+ height: 100,
+ componentPropertyReferences: [{ propertyId: 'card:body', field: 'SLOT_CONTENT' }]
+ })
+ const instance = expectDefined(graph.createInstance(card.id, page.id), 'instance')
+ const slot = expectDefined(
+ graph.getChildren(instance.id).find((child) => slotPropertyId(child)),
+ 'slot'
+ )
+ const style = { fontFamily: 'Inter', fontWeight: 400, fontSize: 16, width: 200, height: 24 }
+ graph.createNode('TEXT', slot.id, { ...style, name: 'Slotted', text: 'In the slot' })
+ graph.updateNode(instance.id, { componentPropertyAssignments: { 'card:body': '' } })
+ const after = graph.createNode('TEXT', page.id, { ...style, name: 'After', text: 'Hi' })
+
+ const parsed = await parseFigmaClipboard(
+ expectDefined(await buildFigmaClipboardHTML([instance, after], graph), 'html')
+ )
+ const records = parsed?.nodes ?? []
+ const content = records.filter((node) => node.isSlotContent === true)
+ expect(content.map((node) => node.name)).toEqual(['Body'])
+ for (const name of ['Slotted', 'After']) {
+ const text = expectDefined(
+ records.find((node) => node.name === name),
+ name
+ )
+ const characters = text.textData?.characters ?? ''
+ expect(text.derivedTextData?.logicalIndexToCharacterOffsetMap?.length).toBe(
+ characters.length + 1
+ )
+ }
+ })
+
it('encodes text nodes with style runs', async () => {
const graph = new SceneGraph()
const page = graph.getPages()[0]
diff --git a/tests/fixtures/slots.fig b/tests/fixtures/slots.fig
new file mode 100644
index 000000000..6bab973a5
--- /dev/null
+++ b/tests/fixtures/slots.fig
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:5d3c0855b44db5552c8ac801225062b5f4d88bed08fc7e1a72b829cbb00b29a6
+size 45710