Skip to content

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

fix(fig): size nested instances in the variable mode their outer instance sets (#1683)

Andrew Avsenindc676ffc8487
diff --git a/changes/1683/fixed.md b/changes/1683/fixed.md
new file mode 100644
index 000000000..6c02fa32f
--- /dev/null
+++ b/changes/1683/fixed.md
@@ -0,0 +1 @@
+- A nested instance in a `.fig` file sizes in the variable mode its outer instance sets, and an override that clears a collection's mode opens, edits and saves per collection.
diff --git a/packages/core/tests/io/formats/fig/export/override-mode-map.test.ts b/packages/core/tests/io/formats/fig/export/override-mode-map.test.ts
new file mode 100644
index 000000000..4012d9b06
--- /dev/null
+++ b/packages/core/tests/io/formats/fig/export/override-mode-map.test.ts
@@ -0,0 +1,293 @@
+import { expect, test } from 'bun:test'
+
+import { expectDefined } from '#core-tests/helpers/assert'
+
+import { FigmaAPI } from '@open-pencil/core/figma-api'
+import { exportFigFile } from '@open-pencil/core/io/formats/fig'
+import { materializeDocument, parseFigBuffer } from '@open-pencil/fig'
+import type { SymbolData } from '@open-pencil/fig/instance-overrides'
+import { initCodec, type NodeChange } from '@open-pencil/kiwi/fig/codec'
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+
+const guid = (localID: number) => ({ sessionID: 1, localID })
+const child = (parent: number, position: string) => ({
+ parentIndex: { guid: guid(parent), position }
+})
+
+const SIZES = { guid: guid(3) }
+const COMPACT = 10
+const WIDE = 11
+const clearSizes = { variableModeBySetMap: { entries: [{ variableSetID: SIZES }] } }
+const wideSizes = { entries: [{ variableSetID: SIZES, variableModeID: guid(WIDE) }] }
+
+function pin(mode: number | undefined): Partial<NodeChange> {
+ return mode === undefined
+ ? {}
+ : { variableModeBySetMap: { entries: [{ variableSetID: SIZES, variableModeID: guid(mode) }] } }
+}
+
+interface Fixture {
+ leafPin?: number
+ nestedPin?: number
+ nestedOverride?: Record<string, unknown>
+}
+
+function records({ leafPin = WIDE, nestedPin, nestedOverride }: Fixture = {}): NodeChange[] {
+ const symbolOverrides = nestedOverride
+ ? [{ guidPath: { guids: [guid(6)] }, ...nestedOverride }]
+ : []
+ return [
+ { guid: guid(1), type: 'DOCUMENT' },
+ { guid: guid(2), type: 'CANVAS', name: 'Page', ...child(1, '!') },
+ {
+ guid: guid(3),
+ type: 'VARIABLE_SET',
+ name: 'Sizes',
+ variableSetModes: [
+ { id: guid(COMPACT), name: 'Compact', sortPosition: 'a' },
+ { id: guid(WIDE), name: 'Wide', sortPosition: 'b' }
+ ]
+ },
+ {
+ guid: guid(20),
+ type: 'SYMBOL',
+ name: 'Leaf',
+ size: { x: 64, y: 10 },
+ ...child(2, 'a'),
+ ...pin(leafPin)
+ },
+ { guid: guid(5), type: 'SYMBOL', name: 'Card', size: { x: 100, y: 10 }, ...child(2, 'b') },
+ {
+ guid: guid(6),
+ type: 'INSTANCE',
+ name: 'Nested',
+ size: { x: 64, y: 10 },
+ ...child(5, 'a'),
+ symbolData: { symbolID: guid(20) },
+ ...pin(nestedPin)
+ },
+ {
+ guid: guid(7),
+ type: 'INSTANCE',
+ name: 'Outer',
+ size: { x: 100, y: 10 },
+ ...child(2, 'c'),
+ symbolData: { symbolID: guid(5), symbolOverrides } as NodeChange['symbolData']
+ }
+ ]
+}
+
+function nestedOf(graph: SceneGraph): SceneNode {
+ const outer = expectDefined(
+ [...graph.getAllNodes()].find((node) => node.type === 'INSTANCE' && node.name === 'Outer'),
+ 'outer instance'
+ )
+ return expectDefined(graph.getChildren(outer.id)[0], 'nested instance')
+}
+
+function sizesOf(graph: SceneGraph) {
+ return expectDefined(
+ [...graph.variableCollections.values()].find((collection) => collection.name === 'Sizes'),
+ 'collection'
+ )
+}
+
+function nestedModeName(graph: SceneGraph): string | undefined {
+ const sizes = sizesOf(graph)
+ const modeId = graph.getNodeVariableModeId(nestedOf(graph).id, sizes.id)
+ return sizes.modes.find((mode) => mode.modeId === modeId)?.name
+}
+
+function setNestedMode(graph: SceneGraph, name: string): void {
+ const sizes = sizesOf(graph)
+ const mode = expectDefined(
+ sizes.modes.find((candidate) => candidate.name === name),
+ 'mode'
+ )
+ const nested = new FigmaAPI(graph).wrapNode(nestedOf(graph).id)
+ nested.setExplicitVariableModeForCollection(sizes.id, mode.modeId)
+}
+
+function clearNestedMode(graph: SceneGraph): void {
+ const nested = new FigmaAPI(graph).wrapNode(nestedOf(graph).id)
+ nested.clearExplicitVariableModeForCollection(sizesOf(graph).id)
+}
+
+async function exported(graph: SceneGraph) {
+ await initCodec()
+ const bytes = await exportFigFile(graph)
+ const parsed = parseFigBuffer(bytes.slice().buffer)
+ const outer = parsed.nodeChanges.find((node) => node.name === 'Outer')
+ const overrides = (outer?.symbolData as SymbolData | undefined)?.symbolOverrides ?? []
+ const { graph: reopened } = materializeDocument(parsed.nodeChanges, parsed.blobs, {
+ derivedBounds: true
+ })
+ return {
+ modeMaps: overrides.flatMap((override) => override.variableModeBySetMap ?? []),
+ reopened
+ }
+}
+
+function opened(fixture?: Fixture): SceneGraph {
+ return materializeDocument(records(fixture), [], { derivedBounds: true }).graph
+}
+
+test('an override that clears the component mode round trips through export', async () => {
+ const graph = opened({ nestedOverride: clearSizes })
+ expect(nestedModeName(graph)).toBe('Compact')
+
+ const { modeMaps, reopened } = await exported(graph)
+
+ expect(modeMaps).toEqual([clearSizes.variableModeBySetMap])
+ expect(nestedModeName(reopened)).toBe('Compact')
+})
+
+test('an override that repeats the component mode stays explicit through export', async () => {
+ const graph = opened({ nestedOverride: pin(WIDE) })
+
+ const { modeMaps, reopened } = await exported(graph)
+
+ expect(modeMaps).toEqual([wideSizes])
+ expect(nestedModeName(reopened)).toBe('Wide')
+})
+
+test('a component mode cleared in the session is exported as cleared', async () => {
+ const graph = opened()
+ expect(nestedModeName(graph)).toBe('Wide')
+ clearNestedMode(graph)
+
+ const { modeMaps, reopened } = await exported(graph)
+
+ expect(modeMaps).toEqual([clearSizes.variableModeBySetMap])
+ expect(nestedModeName(reopened)).toBe('Compact')
+})
+
+test('a mode set over the nested layer of the outer component survives export', async () => {
+ const graph = opened({ leafPin: WIDE, nestedPin: COMPACT })
+ expect(nestedModeName(graph)).toBe('Compact')
+ setNestedMode(graph, 'Wide')
+
+ const { reopened } = await exported(graph)
+
+ expect(nestedModeName(reopened)).toBe('Wide')
+})
+
+test('a cleared mode of the nested layer in the outer component survives export', async () => {
+ const graph = opened({ leafPin: undefined, nestedPin: WIDE })
+ expect(nestedModeName(graph)).toBe('Wide')
+ clearNestedMode(graph)
+
+ const { reopened } = await exported(graph)
+
+ expect(nestedModeName(reopened)).toBe('Compact')
+})
+
+test('a component mode the nested instance only inherits is not written as an override', async () => {
+ const graph = opened()
+
+ const { modeMaps, reopened } = await exported(graph)
+
+ expect(modeMaps).toEqual([])
+ expect(nestedModeName(reopened)).toBe('Wide')
+})
+
+interface TwoLevelFixture {
+ leafPin?: number
+ swappedPin?: number
+}
+
+function twoLevelRecords({ leafPin, swappedPin }: TwoLevelFixture): NodeChange[] {
+ const leaf = { guid: guid(31), type: 'INSTANCE', name: 'Leaf', size: { x: 64, y: 10 } } as const
+ return [
+ ...records().slice(0, 3),
+ {
+ guid: guid(20),
+ type: 'SYMBOL',
+ name: 'Plain',
+ size: { x: 64, y: 10 },
+ ...child(2, 'a'),
+ ...pin(leafPin)
+ },
+ {
+ guid: guid(21),
+ type: 'SYMBOL',
+ name: 'Swapped',
+ size: { x: 64, y: 10 },
+ ...child(2, 'b'),
+ ...pin(swappedPin)
+ },
+ { guid: guid(30), type: 'SYMBOL', name: 'Inner', size: { x: 80, y: 10 }, ...child(2, 'c') },
+ { ...leaf, ...child(30, 'a'), symbolData: { symbolID: guid(20) } },
+ { guid: guid(5), type: 'SYMBOL', name: 'Card', size: { x: 100, y: 10 }, ...child(2, 'd') },
+ {
+ guid: guid(6),
+ type: 'INSTANCE',
+ name: 'Middle',
+ size: { x: 80, y: 10 },
+ ...child(5, 'a'),
+ symbolData: {
+ symbolID: guid(30),
+ symbolOverrides: [{ guidPath: { guids: [guid(31)] }, overriddenSymbolID: guid(21) }]
+ } as NodeChange['symbolData']
+ },
+ {
+ guid: guid(7),
+ type: 'INSTANCE',
+ name: 'Outer',
+ size: { x: 100, y: 10 },
+ ...child(2, 'e'),
+ symbolData: { symbolID: guid(5), symbolOverrides: [] } as NodeChange['symbolData']
+ }
+ ]
+}
+
+function swappedLeafOf(graph: SceneGraph): SceneNode {
+ return expectDefined(graph.getChildren(nestedOf(graph).id)[0], 'swapped leaf')
+}
+
+function swappedModeName(graph: SceneGraph): string | undefined {
+ const sizes = sizesOf(graph)
+ const modeId = graph.getNodeVariableModeId(swappedLeafOf(graph).id, sizes.id)
+ return sizes.modes.find((mode) => mode.modeId === modeId)?.name
+}
+
+function openTwoLevel(fixture: TwoLevelFixture): SceneGraph {
+ return materializeDocument(twoLevelRecords(fixture), [], { derivedBounds: true }).graph
+}
+
+test('a swap two levels down keeps the mode of the component it swaps in through export', async () => {
+ const graph = openTwoLevel({ leafPin: WIDE, swappedPin: COMPACT })
+ expect(swappedModeName(graph)).toBe('Compact')
+
+ const { reopened } = await exported(graph)
+
+ expect(swappedModeName(reopened)).toBe('Compact')
+})
+
+test('a mode set on a layer swapped two levels down survives export', async () => {
+ const graph = openTwoLevel({ leafPin: WIDE, swappedPin: COMPACT })
+ const sizes = sizesOf(graph)
+ const wide = expectDefined(
+ sizes.modes.find((mode) => mode.name === 'Wide'),
+ 'mode'
+ )
+ new FigmaAPI(graph)
+ .wrapNode(swappedLeafOf(graph).id)
+ .setExplicitVariableModeForCollection(sizes.id, wide.modeId)
+
+ const { reopened } = await exported(graph)
+
+ expect(swappedModeName(reopened)).toBe('Wide')
+})
+
+test('a mode cleared on a layer swapped two levels down survives export', async () => {
+ const graph = openTwoLevel({ swappedPin: WIDE })
+ expect(swappedModeName(graph)).toBe('Wide')
+ new FigmaAPI(graph)
+ .wrapNode(swappedLeafOf(graph).id)
+ .clearExplicitVariableModeForCollection(sizesOf(graph).id)
+
+ const { reopened } = await exported(graph)
+
+ expect(swappedModeName(reopened)).toBe('Compact')
+})
diff --git a/packages/fig/src/document/read.ts b/packages/fig/src/document/read.ts
index b0f9acf19..b65fad565 100644
--- a/packages/fig/src/document/read.ts
+++ b/packages/fig/src/document/read.ts
@@ -10,6 +10,7 @@ import {
bySavedPosition,
createSourceIndex,
parentIdOf,
+ type InterpreterIndex,
type SourceIndex
} from '../instance-overrides/source-index'
import { symbolOverridesOf } from '../instance-overrides/types'
@@ -24,6 +25,7 @@ import { DecodedMap } from './decoded-map'
import { collectSceneDependencies } from './dependency-closure'
import { inheritComponentPropertyDefinitions, inheritFromAncestors } from './property-inheritance'
import { vectorStyleTable } from './style-dependencies'
+import { createDocumentVariables, type DocumentVariables } from './variables'
/** Indexed source document. Resources remain separate from scene occurrences. */
export function createDocumentReader(source: readonly NodeChange[], pageIds?: ReadonlySet<string>) {
@@ -81,7 +83,8 @@ interface ReaderRecords {
/** Whole records kept for the document: components the interpreter reads, and styles. */
shared: WholeRecord
/** Indexes whole records, for the interpreter that reads components on demand. */
- interpreterIndex(): SourceIndex
+ interpreterIndex(): InterpreterIndex
+ readonly variables: DocumentVariables
}
function assetIds(records: readonly NodeChange[]): Map<string, string> {
@@ -125,13 +128,18 @@ function wholeRecords(source: readonly NodeChange[]): ReaderRecords {
const assets = assetIds(records)
for (const node of records) resolveStyleFields(index.sources, node, assets)
const same: WholeRecord = (record) => record
+ const variables = createDocumentVariables(records)
return {
records,
index,
bindingDiagnostics,
scope: () => same,
shared: same,
- interpreterIndex: () => createSourceIndex(records.filter((record) => !isResource(record)))
+ interpreterIndex: () => ({
+ ...createSourceIndex(records.filter((record) => !isResource(record))),
+ variables
+ }),
+ variables
}
}
@@ -197,10 +205,12 @@ function archiveRecords(headers: readonly NodeChange[]): ReaderRecords {
}
return record
}
- const interpreterIndex = (): SourceIndex => {
+ const variables = createDocumentVariables(records, decodeRecord)
+ const interpreterIndex = (): InterpreterIndex => {
const { sources, children } = createSourceIndex(records.filter((record) => !isResource(record)))
const lists = new WeakMap<readonly NodeChange[], NodeChange[]>()
return {
+ variables,
sources: new DecodedMap(sources, shared),
children: new DecodedMap(children, (list) => {
let whole = lists.get(list)
@@ -228,7 +238,8 @@ function archiveRecords(headers: readonly NodeChange[]): ReaderRecords {
return whole
},
shared,
- interpreterIndex
+ interpreterIndex,
+ variables
}
}
@@ -276,7 +287,10 @@ function createScopedReader(
)
.map(whole)
const sourceInterpreter = shared.sourceInterpreter
- const interpreter = createIndexedOccurrenceInterpreter(createSourceIndex(sceneChanges))
+ const interpreter = createIndexedOccurrenceInterpreter({
+ ...createSourceIndex(sceneChanges),
+ variables: shared.records.variables
+ })
const pages = changes
.filter((change) => change.type === 'CANVAS')
.toSorted(bySavedPosition)
diff --git a/packages/fig/src/document/variables.ts b/packages/fig/src/document/variables.ts
index 0f34612e1..03c674d95 100644
--- a/packages/fig/src/document/variables.ts
+++ b/packages/fig/src/document/variables.ts
@@ -17,6 +17,7 @@ import {
} from '@open-pencil/scene-graph/variables'
import { extractPluginData } from '../node-change/plugin-data'
+import { visitVariableReferences } from '../node-change/variable/expression'
import { formulaOperatorOfFigmaFunction } from '../node-change/variable/formula'
import { readVariableMetadata } from '../node-change/variable/metadata'
import {
@@ -199,6 +200,116 @@ function modesInListedOrder(resource: NodeChange): SavedMode[] {
])
}
+export function defaultModesByCollection(records: readonly NodeChange[]): Map<string, string> {
+ const defaults = new Map<string, string>()
+ for (const record of records) {
+ if (record.type !== 'VARIABLE_SET' || !record.guid) {
+ continue
+ }
+ const first = modesInListedOrder(record).at(0)
+ if (first) {
+ defaults.set(guidToString(record.guid), guidToString(first.id))
+ }
+ }
+ return defaults
+}
+
+export interface DocumentVariables {
+ readonly defaultModes: ReadonlyMap<string, string>
+ readonly variableIdOf: (reference: NodeChange['variableSetID']) => string | undefined
+ collectionsReachedFrom(variableId: string): ReadonlySet<string>
+}
+
+interface VariableLinks {
+ readonly collection: string | undefined
+ readonly aliases: readonly string[]
+}
+
+function isVariableResource(record: NodeChange): boolean {
+ return record.type === 'VARIABLE' || record.type === 'VARIABLE_SET'
+}
+
+export function createDocumentVariables(
+ records: readonly NodeChange[],
+ whole: (record: NodeChange) => NodeChange = (record) => record
+): DocumentVariables {
+ const resources = records.filter(isVariableResource)
+ const resolve = createResourceResolver(resources)
+ const variables = new Map<string, NodeChange>()
+ for (const resource of resources) {
+ if (resource.type === 'VARIABLE' && resource.guid) {
+ variables.set(guidToString(resource.guid), resource)
+ }
+ }
+ const links = new Map<string, VariableLinks | undefined>()
+ const linksOf = (id: string): VariableLinks | undefined => {
+ if (!links.has(id)) {
+ const header = variables.get(id)
+ links.set(id, header ? variableLinks(whole(header), resolve) : undefined)
+ }
+ return links.get(id)
+ }
+ const reached = new Map<string, ReadonlySet<string>>()
+ let defaultModes: ReadonlyMap<string, string> | undefined
+ return {
+ get defaultModes() {
+ defaultModes ??= defaultModesByCollection(
+ resources.filter((resource) => resource.type === 'VARIABLE_SET').map(whole)
+ )
+ return defaultModes
+ },
+ variableIdOf: resolve,
+ collectionsReachedFrom(variableId) {
+ let collections = reached.get(variableId)
+ if (!collections) {
+ collections = collectionsThrough(variableId, linksOf)
+ reached.set(variableId, collections)
+ }
+ return collections
+ }
+ }
+}
+
+function variableLinks(
+ variable: NodeChange,
+ resolve: ReturnType<typeof createResourceResolver>
+): VariableLinks {
+ const collection = variable.variableSetID
+ ? resolve(variable.variableSetID)
+ : variable.parentIndex?.guid && guidToString(variable.parentIndex.guid)
+ const aliases: string[] = []
+ for (const entry of variable.variableDataValues?.entries ?? []) {
+ visitVariableReferences(entry.variableData, (reference) => {
+ const alias = resolve(reference)
+ if (alias) {
+ aliases.push(alias)
+ }
+ })
+ }
+ return { collection: collection || undefined, aliases }
+}
+
+function collectionsThrough(
+ variableId: string,
+ linksOf: (id: string) => VariableLinks | undefined
+): ReadonlySet<string> {
+ const collections = new Set<string>()
+ const seen = new Set<string>()
+ const pending = [variableId]
+ for (let id = pending.pop(); id !== undefined; id = pending.pop()) {
+ if (seen.has(id)) {
+ continue
+ }
+ seen.add(id)
+ const links = linksOf(id)
+ if (links?.collection) {
+ collections.add(links.collection)
+ }
+ pending.push(...(links?.aliases ?? []))
+ }
+ return collections
+}
+
/** No invented values or fallback collections: unsupported resources remain explicit. */
export function materializeVariableResources(
graph: SceneGraph,
diff --git a/packages/fig/src/instance-overrides/fields.ts b/packages/fig/src/instance-overrides/fields.ts
index f1b9702d1..7b2850f6a 100644
--- a/packages/fig/src/instance-overrides/fields.ts
+++ b/packages/fig/src/instance-overrides/fields.ts
@@ -22,6 +22,7 @@ export interface OverrideField {
| 'size'
| 'layout-distance'
| 'layout-mode'
+ | 'variable-modes'
| 'node'
/** A placed-space distance that an instance's uniform scale multiplies. */
readonly length?: true
@@ -38,7 +39,7 @@ export const OVERRIDE_FIELDS = {
opacity: { scene: ['opacity'], kind: 'scalar' },
fontSize: { scene: ['fontSize'], kind: 'scalar', length: true },
visible: { scene: ['visible'], kind: 'visible' },
- variableModeBySetMap: { scene: ['variableModes'], kind: 'node', absent: { entries: [] } },
+ variableModeBySetMap: { scene: ['variableModes'], kind: 'variable-modes' },
// Figma claims styled ranges and list lines with the characters (desktop 126).
textData: { scene: ['text', 'styleRuns', 'textParagraphs'], kind: 'text' },
styleIdForText: { scene: ['textStyleId'], kind: 'text-style' },
diff --git a/packages/fig/src/instance-overrides/interpret.ts b/packages/fig/src/instance-overrides/interpret.ts
index dd226ffa4..5500cb027 100644
--- a/packages/fig/src/instance-overrides/interpret.ts
+++ b/packages/fig/src/instance-overrides/interpret.ts
@@ -5,7 +5,7 @@ import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { guidToString } from '@open-pencil/kiwi/fig/guid'
import { cloneRecord } from '../node-change/clone'
-import { mergeVariableConsumptionMaps } from '../node-change/variable/bindings'
+import { claimedVariableMaps, mergeVariableConsumptionMaps } from '../node-change/variable/bindings'
import {
bindSourceProperties,
componentBindings,
@@ -27,6 +27,7 @@ import {
type PropertyLayer,
type StructuralLayer
} from './layers'
+import { createModeScopes, type ModeScope } from './occurrence/modes'
import {
findSegment,
isRootGuid,
@@ -38,7 +39,7 @@ import type { InstanceOccurrence, InterpretInstanceOptions } from './occurrence/
import { applyPlacedConstraints } from './resize'
import { applyInstanceLayoutScale } from './scale/layout'
import {
- createSourceIndex,
+ createInterpreterIndex,
findStaticSegment,
idOf,
readOverrideKey,
@@ -46,7 +47,7 @@ import {
resolvesInSourceComponent,
sameGuid,
terminalComponent,
- type SourceIndex
+ type InterpreterIndex
} from './source-index'
import { invalidateInheritedTextData } from './text-provenance'
import {
@@ -88,11 +89,11 @@ export function interpretComponent(
/** One source index per document; evaluation state remains local to each call. */
export function createOccurrenceInterpreter(changes: readonly NodeChange[]) {
- return createIndexedOccurrenceInterpreter(createSourceIndex(changes))
+ return createIndexedOccurrenceInterpreter(createInterpreterIndex(changes))
}
/** An interpreter over an index built elsewhere, such as one that decodes records as read. */
-export function createIndexedOccurrenceInterpreter(index: SourceIndex) {
+export function createIndexedOccurrenceInterpreter(index: InterpreterIndex) {
return {
instance: (id: string, options: InterpretInstanceOptions = {}) =>
interpretRoot(index, id, 'INSTANCE', options),
@@ -104,13 +105,14 @@ export function createIndexedOccurrenceInterpreter(index: SourceIndex) {
}
function interpretRoot(
- index: SourceIndex,
+ index: InterpreterIndex,
rootId: string,
expectedType: 'INSTANCE' | 'SYMBOL' | 'CANVAS',
options: InterpretInstanceOptions
): InstanceOccurrence {
const { sources, children } = index
const expanding = new Set<string>()
+ const modeScopes = createModeScopes(index)
/** Fields set by an owner's assignment, by the rank of that owner. */
const assignedFields = new WeakMap<InstanceOccurrence, Map<string, number>>()
/** Components an occurrence expanded before an outer decision replaced them. */
@@ -256,7 +258,7 @@ function interpretRoot(
Object.assign(
target.properties,
cloneRecord(retained),
- mergeVariableConsumptionMaps(target.properties, retained as NodeChange)
+ claimedVariableMaps(target.properties, retained as NodeChange)
)
if ('name' in retained) target.hasOwnName = true
owner.propertyClaims.push({
@@ -364,7 +366,8 @@ function interpretRoot(
id: string,
bindings: readonly PropertyBinding[],
layers: readonly StructuralLayer[],
- rank: number
+ rank: number,
+ inherited: ModeScope
): InstanceOccurrence => {
if (expanding.has(id)) throw new Error(`Cyclic component expansion at ${id}`)
options.onProgress?.()
@@ -378,11 +381,15 @@ 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 modes = modeScopes.enter(inherited, raw, root.effective, own.claims)
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)
+ if (root.effective) {
+ subtree = expandBase(owner, { ...root, effective: root.effective }, rank, modes)
+ } else if (record.slotContent) {
+ subtree = expandSlotContent(record.slotContent, root.descendant, rank, modes)
+ } else {
+ subtree = expandChildren(id, source, bindings, root.groups, root.descendant, rank, modes)
+ }
const occurrence = createOccurrence(id, raw, source, root, subtree, record.claims)
if (record.slotContent) occurrence.slotContentId = record.slotContent
assignedFields.set(occurrence, record.bound)
@@ -391,7 +398,7 @@ function interpretRoot(
const claims = subtree.dangling
? own.claims.filter(({ path }) => path.length === 1 && isRootGuid(occurrence, path[0]))
: own.claims
- finishOccurrence(occurrence, subtree.base, source, claims, rank, !subtree.dangling)
+ finishOccurrence(occurrence, subtree.base, source, claims, rank, !subtree.dangling, modes)
for (const diagnostic of owner.unresolved)
options.onUnresolvedAssignment?.({
...diagnostic,
@@ -417,7 +424,8 @@ function interpretRoot(
const expandBase = (
owner: Owner,
{ effective, replaced, groups, descendant }: RootResolution & { effective: GUID },
- rank: number
+ rank: number,
+ modes: ModeScope
): Subtree => {
const componentId = guidToString(effective)
if (!sources.has(componentId)) {
@@ -438,7 +446,7 @@ function interpretRoot(
path: [],
assignments: group.assignments
}))
- const base = expand(guidToString(effective), [], [...rootLayers, ...crossing], rank + 1)
+ const base = expand(componentId, [], [...rootLayers, ...crossing], rank + 1, modes)
return { base, children: base.children }
}
@@ -449,7 +457,8 @@ function interpretRoot(
bindings: readonly PropertyBinding[],
groups: readonly AssignmentGroup[],
descendant: readonly StructuralLayer[],
- rank: number
+ rank: number,
+ modes: ModeScope
): Subtree => {
const scoped =
source.type === 'SYMBOL'
@@ -462,7 +471,7 @@ function interpretRoot(
const expanded = (children.get(id) ?? []).map((child) => {
if (!child.guid) throw new Error('Indexed child has no GUID')
const childId = guidToString(child.guid)
- return expand(childId, scoped, routed.get(childId) ?? [], rank + 1)
+ return expand(childId, scoped, routed.get(childId) ?? [], rank + 1, modes)
})
return { base: null, children: expanded }
}
@@ -474,13 +483,14 @@ function interpretRoot(
const expandSlotContent = (
contentId: string,
descendant: readonly StructuralLayer[],
- rank: number
+ rank: number,
+ modes: ModeScope
): 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 expand(childId, [], routed.get(childId) ?? [], rank + 1, modes)
})
return { base: null, children: expanded }
}
@@ -572,7 +582,8 @@ function interpretRoot(
source: NodeChange,
claims: readonly PropertyLayer[],
rank: number,
- derived: boolean
+ derived: boolean,
+ modes: ModeScope
): void => {
for (const claim of claims) {
const target = resolveClaimTarget(occurrence, claim.path)
@@ -580,13 +591,7 @@ function interpretRoot(
}
applyInstanceLayoutScale(occurrence, source)
applyPlacedConstraints(occurrence, base, source)
- if (source.type === 'INSTANCE' && source.size) {
- occurrence.properties.size = structuredClone(source.size)
- // The size the file keeps for the instance is its own content laid out, such as a hug
- // frame around longer text than its component's, which a sync with the component must
- // not replace.
- occurrence.derivedSize = structuredClone(source.size)
- }
+ modeScopes.applySavedSize(occurrence, source, modes)
if (derived) applyDerivedBounds(occurrence, source)
}
@@ -594,5 +599,5 @@ function interpretRoot(
const kind = { INSTANCE: 'an instance', SYMBOL: 'a component', CANVAS: 'a page' }[expectedType]
throw new Error(`Expected ${kind} source`)
}
- return expand(rootId, [], [], 0)
+ return expand(rootId, [], [], 0, modeScopes.atParentOf(rootId))
}
diff --git a/packages/fig/src/instance-overrides/materialize-instance.ts b/packages/fig/src/instance-overrides/materialize-instance.ts
index 14946732e..96326a9b6 100644
--- a/packages/fig/src/instance-overrides/materialize-instance.ts
+++ b/packages/fig/src/instance-overrides/materialize-instance.ts
@@ -1,11 +1,12 @@
import { isEqual } from 'es-toolkit/predicate'
-import type { Effect as KiwiEffect, Paint } from '@open-pencil/kiwi/fig/codec'
+import type { Effect as KiwiEffect, NodeChange, Paint } from '@open-pencil/kiwi/fig/codec'
import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import { scaleGeometryPaths } from '@open-pencil/scene-graph/copy'
import {
bindingOverrideField,
- setInstanceOverride
+ setInstanceOverride,
+ variableModeOverrideField
} from '@open-pencil/scene-graph/instances/overrides'
import { createDefaultSourceMetadata } from '@open-pencil/scene-graph/node-defaults'
import { EFFECT_BINDING_PROPERTIES, effectBindingField } from '@open-pencil/scene-graph/variables'
@@ -13,6 +14,7 @@ import { EFFECT_BINDING_PROPERTIES, effectBindingField } from '@open-pencil/scen
import { nodeChangeToProps } from '../node-change'
import { numericVariableBindingScales } from '../node-change/variable/bindings'
import { EFFECT_VARIABLE_FIELDS } from '../node-change/variable/effects'
+import { variableModeLayer } from '../node-change/variable/maps'
import {
recordVariableBindingClaims,
occurrenceAssignmentScales,
@@ -291,6 +293,16 @@ function recordPaintBindingClaims(
if (declared) setInstanceOverride(owner.instanceOverrides, owner.id, target.id, 'boundVariables')
}
+function recordVariableModeClaims(owner: SceneNode, target: SceneNode, claim: NodeChange): void {
+ if (!claim.variableModeBySetMap) {
+ return
+ }
+ for (const collection of variableModeLayer(claim).keys()) {
+ const field = variableModeOverrideField(collection)
+ setInstanceOverride(owner.instanceOverrides, owner.id, target.id, field)
+ }
+}
+
/** A claimed effect carries its properties' aliases, so its bindings are part of the claim too. */
function recordEffectBindingClaims(owner: SceneNode, target: SceneNode, effects: unknown): void {
if (!Array.isArray(effects)) return
@@ -338,6 +350,7 @@ function recordPropertyClaims(nodes: ReadonlyMap<InstanceOccurrence, SceneNode>)
if (raw === 'effects') recordEffectBindingClaims(owner, target, claim.properties[raw])
}
recordVariableBindingClaims(owner, target, claim.properties)
+ recordVariableModeClaims(owner, target, claim.properties)
}
}
}
diff --git a/packages/fig/src/instance-overrides/occurrence/bound-collections.ts b/packages/fig/src/instance-overrides/occurrence/bound-collections.ts
new file mode 100644
index 000000000..7a4de768e
--- /dev/null
+++ b/packages/fig/src/instance-overrides/occurrence/bound-collections.ts
@@ -0,0 +1,76 @@
+import { variableConsumptionEntries } from '#fig/node-change/variable/bindings'
+import { visitVariableReferences } from '#fig/node-change/variable/expression'
+
+import type { GUID } from '@open-pencil/kiwi/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+
+import { idOf, type InterpreterIndex } from '../source-index'
+import { symbolDataOf, symbolOverridesOf } from '../types'
+
+type Collections = ReadonlySet<string>
+
+const NO_COLLECTIONS: Collections = new Set()
+const collectionsByRecord = new WeakMap<NodeChange, Collections>()
+
+type VariableIdOf = InterpreterIndex['variables']['variableIdOf']
+
+function variablesBoundBy(holder: NodeChange, variableIdOf: VariableIdOf, found: Set<string>) {
+ for (const entry of variableConsumptionEntries(holder)) {
+ visitVariableReferences(entry.variableData, (reference) => {
+ const id = variableIdOf(reference)
+ if (id) {
+ found.add(id)
+ }
+ })
+ }
+ for (const range of holder.textData?.styleOverrideTable ?? []) {
+ variablesBoundBy(range, variableIdOf, found)
+ }
+ for (const override of symbolOverridesOf(holder)) {
+ variablesBoundBy(override, variableIdOf, found)
+ }
+}
+
+function componentsUsedBy(record: NodeChange): GUID[] {
+ const saved = symbolDataOf(record)?.symbolID
+ const swapped = symbolOverridesOf(record).flatMap(({ overriddenSymbolID }) =>
+ overriddenSymbolID ? [overriddenSymbolID] : []
+ )
+ return saved ? [saved, ...swapped] : swapped
+}
+
+export function createBoundCollections({ sources, children, variables }: InterpreterIndex) {
+ const collectionsUnder = (record: NodeChange): Collections => {
+ const known = collectionsByRecord.get(record)
+ if (known) {
+ return known
+ }
+ collectionsByRecord.set(record, NO_COLLECTIONS)
+ const bound = new Set<string>()
+ variablesBoundBy(record, variables.variableIdOf, bound)
+ const collections = new Set<string>()
+ for (const variable of bound) {
+ for (const collection of variables.collectionsReachedFrom(variable)) {
+ collections.add(collection)
+ }
+ }
+ const include = (layer: NodeChange | undefined): void => {
+ for (const collection of layer ? collectionsUnder(layer) : NO_COLLECTIONS) {
+ collections.add(collection)
+ }
+ }
+ const id = idOf(record)
+ const layers = id ? children.get(id) : undefined
+ for (const layer of layers ?? []) {
+ include(layer)
+ }
+ for (const component of componentsUsedBy(record)) {
+ include(sources.get(guidToString(component)))
+ }
+ const result = collections.size ? collections : NO_COLLECTIONS
+ collectionsByRecord.set(record, result)
+ return result
+ }
+ return collectionsUnder
+}
diff --git a/packages/fig/src/instance-overrides/occurrence/modes.ts b/packages/fig/src/instance-overrides/occurrence/modes.ts
new file mode 100644
index 000000000..a172b0da7
--- /dev/null
+++ b/packages/fig/src/instance-overrides/occurrence/modes.ts
@@ -0,0 +1,237 @@
+import { variableModeLayer } from '#fig/node-change/variable/maps'
+
+import type { GUID } from '@open-pencil/kiwi/fig'
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+
+import type { PropertyLayer } from '../layers'
+import { parentIdOf, recordMatches, sameGuid, type InterpreterIndex } from '../source-index'
+import { createBoundCollections } from './bound-collections'
+import type { InstanceOccurrence } from './types'
+
+type ModesByCollection = ReadonlyMap<string, string>
+type ModeLayer = ReadonlyMap<string, string | undefined>
+type Sources = InterpreterIndex['sources']
+
+interface ModeClaim {
+ readonly path: readonly GUID[]
+ readonly modes: ModeLayer
+}
+
+export interface ModeScope {
+ readonly placed: ModesByCollection
+ readonly descendantClaims: readonly ModeClaim[]
+ readonly expandedComponent?: NodeChange
+}
+
+const NO_MODES: ModesByCollection = new Map()
+const NO_CLAIMS: readonly ModeClaim[] = []
+const extractedModes = new WeakMap<object, ModeLayer>()
+const documentModes = new WeakMap<Sources, Map<string, ModesByCollection>>()
+
+function modesSetBy(holder: NodeChange | undefined): ModeLayer | undefined {
+ const map = holder?.variableModeBySetMap
+ if (!holder || typeof map !== 'object' || map === null) {
+ return undefined
+ }
+ const known = extractedModes.get(map)
+ if (known) {
+ return known
+ }
+ const modes = variableModeLayer(holder)
+ extractedModes.set(map, modes)
+ return modes
+}
+
+function layered(base: ModesByCollection, ...layers: (ModeLayer | undefined)[]): ModesByCollection {
+ const present = layers.filter((layer): layer is ModeLayer => !!layer?.size)
+ if (present.length === 0) {
+ return base
+ }
+ const modes = new Map(base)
+ for (const [collection, mode] of present.flatMap((layer) => [...layer])) {
+ const effective = mode ?? base.get(collection)
+ if (effective) {
+ modes.set(collection, effective)
+ } else {
+ modes.delete(collection)
+ }
+ }
+ return modes
+}
+
+function documentOf(sources: Sources): Map<string, ModesByCollection> {
+ const known = documentModes.get(sources)
+ if (known) {
+ return known
+ }
+ const created = new Map<string, ModesByCollection>()
+ documentModes.set(sources, created)
+ return created
+}
+
+function claimsOfOwner(claims: readonly PropertyLayer[]): ModeClaim[] {
+ return claims.flatMap(({ path, props }) => {
+ const modes = modesSetBy(props)
+ return modes && path.length ? [{ path, modes }] : []
+ })
+}
+
+function insideComponent(
+ claims: readonly ModeClaim[],
+ isComponentRoot: (segment: GUID) => boolean
+): ModeClaim[] {
+ return claims.flatMap((claim) => {
+ const path = isComponentRoot(claim.path[0]) ? claim.path.slice(1) : claim.path
+ return path.length ? [{ path, modes: claim.modes }] : []
+ })
+}
+
+interface ClaimRouting {
+ readonly ending: ModeLayer | undefined
+ readonly continuing: readonly ModeClaim[]
+ readonly passing: readonly ModeClaim[]
+}
+
+function outerFirstWins(layers: readonly ModeLayer[]): ModeLayer | undefined {
+ if (layers.length < 2) {
+ return layers[0]
+ }
+ const merged = new Map<string, string | undefined>()
+ for (const [collection, mode] of layers.flatMap((layer) => [...layer])) {
+ if (!merged.has(collection)) {
+ merged.set(collection, mode)
+ }
+ }
+ return merged
+}
+
+function routeClaims(claims: readonly ModeClaim[], record: NodeChange): ClaimRouting | undefined {
+ const ending: ModeLayer[] = []
+ const continuing: ModeClaim[] = []
+ const passing: ModeClaim[] = []
+ for (const claim of claims) {
+ if (!recordMatches(record, claim.path[0])) {
+ passing.push(claim)
+ } else if (claim.path.length === 1) {
+ ending.push(claim.modes)
+ } else {
+ const next = { path: claim.path.slice(1), modes: claim.modes }
+ continuing.push(next)
+ passing.push(next)
+ }
+ }
+ if (ending.length === 0 && continuing.length === 0) {
+ return undefined
+ }
+ return { ending: outerFirstWins(ending), continuing, passing }
+}
+
+export function createModeScopes(index: InterpreterIndex) {
+ const { sources, variables } = index
+ const byRecord = documentOf(sources)
+ const collectionsUnder = createBoundCollections(index)
+
+ const recordOf = (component: GUID | undefined): NodeChange | undefined =>
+ component ? sources.get(guidToString(component)) : undefined
+
+ const modesInDocument = (id: string): ModesByCollection => {
+ const known = byRecord.get(id)
+ if (known) {
+ return known
+ }
+ const record = sources.get(id)
+ const parentId = record ? parentIdOf(record) : undefined
+ const inherited = parentId ? modesInDocument(parentId) : NO_MODES
+ const component =
+ record?.type === 'INSTANCE' ? recordOf(record.symbolData?.symbolID) : undefined
+ const modes = layered(inherited, modesSetBy(record) ?? modesSetBy(component))
+ byRecord.set(id, modes)
+ return modes
+ }
+
+ const modeIn = (modes: ModesByCollection, collection: string): string | undefined =>
+ modes.get(collection) ?? variables.defaultModes.get(collection)
+
+ const differsFromDocument = (scope: ModeScope, source: NodeChange, id: string): boolean => {
+ const laidOut = modesInDocument(id)
+ if (scope.placed === laidOut) {
+ return false
+ }
+ const bound = collectionsUnder(source)
+ const swappedIn = scope.expandedComponent ? collectionsUnder(scope.expandedComponent) : bound
+ const differsAt = (collection: string): boolean =>
+ (bound.has(collection) || swappedIn.has(collection)) &&
+ modeIn(scope.placed, collection) !== modeIn(laidOut, collection)
+ return [...scope.placed.keys(), ...laidOut.keys()].some(differsAt)
+ }
+
+ const expansionClaims = (
+ record: NodeChange,
+ component: GUID,
+ claims: readonly ModeClaim[]
+ ): readonly ModeClaim[] => {
+ if (claims.length === 0) {
+ return NO_CLAIMS
+ }
+ const savedComponent = record.symbolData?.symbolID
+ const roots = [recordOf(component), recordOf(savedComponent)]
+ const isComponentRoot = (segment: GUID): boolean =>
+ sameGuid(segment, component) ||
+ sameGuid(savedComponent, segment) ||
+ roots.some((root) => root !== undefined && recordMatches(root, segment))
+ return insideComponent(claims, isComponentRoot)
+ }
+
+ return {
+ atParentOf(id: string): ModeScope {
+ const record = sources.get(id)
+ const parentId = record ? parentIdOf(record) : undefined
+ const placed = parentId ? modesInDocument(parentId) : NO_MODES
+ return { placed, descendantClaims: NO_CLAIMS }
+ },
+ enter(
+ scope: ModeScope,
+ record: NodeChange,
+ component: GUID | undefined,
+ ownClaims: readonly PropertyLayer[]
+ ): ModeScope {
+ if (scope.expandedComponent === record) {
+ return scope
+ }
+ const routing = scope.descendantClaims.length
+ ? routeClaims(scope.descendantClaims, record)
+ : undefined
+ const own = modesSetBy(record)
+ const claimed = routing?.ending
+ if (!component) {
+ if (!own && !routing) {
+ return scope
+ }
+ return {
+ placed: layered(scope.placed, own, claimed),
+ descendantClaims: routing?.passing ?? scope.descendantClaims
+ }
+ }
+ const expandedComponent = recordOf(component)
+ const claims = [...(routing?.continuing ?? NO_CLAIMS), ...claimsOfOwner(ownClaims)]
+ return {
+ placed: layered(scope.placed, own ?? modesSetBy(expandedComponent), claimed),
+ descendantClaims: expansionClaims(record, component, claims),
+ expandedComponent
+ }
+ },
+ applySavedSize(occurrence: InstanceOccurrence, source: NodeChange, scope: ModeScope): void {
+ if (source.type !== 'INSTANCE' || !source.size) {
+ return
+ }
+ occurrence.properties.size = structuredClone(source.size)
+ // The size the file keeps for the instance is its own content laid out, such as a hug
+ // frame around longer text than its component's, which a sync with the component must
+ // not replace.
+ if (!differsFromDocument(scope, source, occurrence.sourceId)) {
+ occurrence.derivedSize = structuredClone(source.size)
+ }
+ }
+ }
+}
diff --git a/packages/fig/src/instance-overrides/source-index.ts b/packages/fig/src/instance-overrides/source-index.ts
index 1c84955e7..c0610eb36 100644
--- a/packages/fig/src/instance-overrides/source-index.ts
+++ b/packages/fig/src/instance-overrides/source-index.ts
@@ -1,3 +1,5 @@
+import { createDocumentVariables, type DocumentVariables } from '#fig/document/variables'
+
import type { GUID } from '@open-pencil/kiwi/fig'
import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
import { guidToString, isUnsetGuid } from '@open-pencil/kiwi/fig/guid'
@@ -10,6 +12,10 @@ export interface SourceIndex {
readonly children: ReadonlyMap<string, readonly NodeChange[]>
}
+export interface InterpreterIndex extends SourceIndex {
+ readonly variables: DocumentVariables
+}
+
/** A record's archive identity, or undefined for the rare record without a GUID. */
export function idOf(record: NodeChange): string | undefined {
return record.guid ? guidToString(record.guid) : undefined
@@ -55,6 +61,10 @@ export function createSourceIndex(changes: readonly NodeChange[]): SourceIndex {
return { sources, children }
}
+export function createInterpreterIndex(changes: readonly NodeChange[]): InterpreterIndex {
+ return { ...createSourceIndex(changes), variables: createDocumentVariables(changes) }
+}
+
export function sameGuid(left: GUID | undefined, right: GUID): boolean {
return left?.sessionID === right.sessionID && left.localID === right.localID
}
diff --git a/packages/fig/src/node-change/convert.ts b/packages/fig/src/node-change/convert.ts
index 47bf79156..aa8cb280e 100644
--- a/packages/fig/src/node-change/convert.ts
+++ b/packages/fig/src/node-change/convert.ts
@@ -92,15 +92,9 @@ import type { Vector, GUID } from '@open-pencil/scene-graph/primitives'
import { savedFace } from './font/style'
import { numericVariableAssignmentScales, sourceVariableBindingScales } from './variable/bindings'
export { VARIABLE_BINDING_FIELDS, VARIABLE_BINDING_FIELDS_INVERSE } from './variable/bindings'
+import type { FigVariableModeMap } from './variable/maps'
-interface FigVariableModeMap {
- entries?: Array<{
- variableSetID?: { guid?: GUID }
- variableModeID?: GUID
- }>
-}
-
-function extractVariableModes(nc: NodeChange): VariableModeMap {
+export function extractVariableModes(nc: NodeChange): VariableModeMap {
const result: VariableModeMap = {}
const modeMap = nc.variableModeBySetMap as FigVariableModeMap | undefined
for (const entry of modeMap?.entries ?? []) {
diff --git a/packages/fig/src/node-change/export/node.ts b/packages/fig/src/node-change/export/node.ts
index 97ad78c5f..ecbf4db40 100644
--- a/packages/fig/src/node-change/export/node.ts
+++ b/packages/fig/src/node-change/export/node.ts
@@ -61,6 +61,7 @@ import { mergeOverrides, serializeRuntimePropertyOverrides } from './override-cl
import { exportedNode } from './resolved-bindings'
import { slotDefinitionFields } from './slots'
import { serializeText } from './text'
+import { applyVariableModes } from './variable-modes'
export type { KiwiNodeChange, SceneNodeToKiwiContext } from './context'
@@ -113,29 +114,6 @@ function componentPropertyTypeForKiwi(type: string) {
return type
}
-function serializeVariableModes(
- node: SceneNode,
- variableIdToGuid?: Map<string, GUID>,
- modeIdToGuid?: Map<string, GUID>
-): NonNullable<KiwiNodeChange['variableModeBySetMap']> | undefined {
- const entries = Object.entries(node.variableModes).flatMap(([collectionId, modeId]) => {
- const collectionGuid = variableIdToGuid?.get(collectionId) ?? parseGuidOrNull(collectionId)
- const modeGuid = modeIdToGuid?.get(modeId) ?? parseGuidOrNull(modeId)
- if (!collectionGuid || !modeGuid) return []
- return [{ variableSetID: { guid: collectionGuid }, variableModeID: modeGuid }]
- })
- return entries.length > 0 ? { entries } : undefined
-}
-
-function applyVariableModes(
- context: SceneNodeToKiwiContext,
- node: SceneNode,
- record: KiwiNodeChange
-): void {
- const modes = serializeVariableModes(node, context.varIdToGuid, context.modeIdToGuid)
- if (modes) record.variableModeBySetMap = modes
-}
-
const FIGMA_PAYLOAD_VARIABLE_MAP_FIELDS = new Set([
'variableConsumptionMap',
'parameterConsumptionMap'
diff --git a/packages/fig/src/node-change/export/override-claims.ts b/packages/fig/src/node-change/export/override-claims.ts
index 1f01242ee..ea1899c54 100644
--- a/packages/fig/src/node-change/export/override-claims.ts
+++ b/packages/fig/src/node-change/export/override-claims.ts
@@ -17,6 +17,7 @@ import { paintBindingTarget } from '@open-pencil/scene-graph/variables'
import { instanceExportAddress } from '../instance/geometry'
import { mergeVariableConsumptionMaps, overrideVariableBindingEntry } from '../variable/bindings'
+import { mergeVariableModeClaims } from '../variable/maps'
import { nestedPropertyAssignments } from './assignments/nested'
import {
createFillPaints,
@@ -31,6 +32,7 @@ import {
} from './context'
import { fillsOwnSizingAxis } from './fill-sizing'
import { exportedNode } from './resolved-bindings'
+import { claimedVariableModes } from './variable-modes'
function unscaledRootSize(instance: SceneNode, target: SceneNode): Vector {
const scale = instance.componentScale
@@ -82,6 +84,7 @@ function layoutDistanceClaim(
interface ClaimInput {
context: SceneNodeToKiwiContext
instance: SceneNode
+ owner: SceneNode
target: SceneNode
/** The recorded override value, when the override stored one. */
value: unknown
@@ -126,7 +129,7 @@ function rawClaim(
raw: string,
definition: OverrideField,
field: keyof SceneNode,
- { context, instance, target, value, nodeFields }: ClaimInput
+ { context, instance, owner, target, value, nodeFields }: ClaimInput
): Omit<KiwiSymbolOverridePayload, 'guidPath'> | undefined {
switch (definition.kind) {
case 'node': {
@@ -159,6 +162,10 @@ function rawClaim(
return layoutDistanceClaim(raw, target[field], instance)
case 'layout-mode':
return layoutModeClaim(raw, target[field], context.graph, target)
+ case 'variable-modes': {
+ const modes = claimedVariableModes(context, instance, owner, target)
+ return modes.entries.length > 0 ? { variableModeBySetMap: modes } : undefined
+ }
default:
return undefined
}
@@ -250,7 +257,15 @@ export function serializeRuntimePropertyOverrides(
const resolved = resolveTarget(node, nodeId)
if (!resolved) return
const claim = overrideClaim(
- { context, instance, target: resolved.target, value, records, writeNodeFields },
+ {
+ context,
+ instance,
+ owner: node,
+ target: resolved.target,
+ value,
+ records,
+ writeNodeFields
+ },
field,
resolved.path,
localIdCounter
@@ -300,7 +315,8 @@ export function mergeOverrides(
symbolOverrides[existingIndex] = {
...symbolOverrides[existingIndex],
...override,
- ...mergeVariableConsumptionMaps(symbolOverrides[existingIndex], override)
+ ...mergeVariableConsumptionMaps(symbolOverrides[existingIndex], override),
+ ...mergeVariableModeClaims(symbolOverrides[existingIndex], override)
}
}
}
diff --git a/packages/fig/src/node-change/export/variable-modes.ts b/packages/fig/src/node-change/export/variable-modes.ts
new file mode 100644
index 000000000..e0e4f8f4f
--- /dev/null
+++ b/packages/fig/src/node-change/export/variable-modes.ts
@@ -0,0 +1,101 @@
+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import {
+ getInstanceOverride,
+ variableModeOverrideCollection
+} from '@open-pencil/scene-graph/instances/overrides'
+
+import type { FigVariableModeMap } from '../variable/maps'
+import { parseGuidOrNull, type KiwiNodeChange, type SceneNodeToKiwiContext } from './context'
+
+type VariableModeEntry = NonNullable<FigVariableModeMap['entries']>[number]
+type ModeContext = Pick<SceneNodeToKiwiContext, 'graph' | 'varIdToGuid' | 'modeIdToGuid'>
+
+function modeEntry(
+ context: ModeContext,
+ collectionId: string,
+ modeId: string | undefined
+): VariableModeEntry[] {
+ const collectionGuid = context.varIdToGuid?.get(collectionId) ?? parseGuidOrNull(collectionId)
+ if (!collectionGuid) {
+ return []
+ }
+ if (modeId === undefined) {
+ return [{ variableSetID: { guid: collectionGuid } }]
+ }
+ const modeGuid = context.modeIdToGuid?.get(modeId) ?? parseGuidOrNull(modeId)
+ return modeGuid ? [{ variableSetID: { guid: collectionGuid }, variableModeID: modeGuid }] : []
+}
+
+function ownFields(owner: SceneNode, layer: SceneNode): ReadonlyMap<string, unknown> {
+ const state = owner.instanceOverrides
+ return (layer.id === owner.id ? state.self : state.descendants.get(layer.id)) ?? new Map()
+}
+
+function setsOwnModes(node: SceneNode): boolean {
+ return node.type !== 'INSTANCE' || ownFields(node, node).has('variableModes')
+}
+
+export function applyVariableModes(
+ context: ModeContext,
+ node: SceneNode,
+ record: KiwiNodeChange
+): void {
+ if (!setsOwnModes(node)) {
+ return
+ }
+ const entries = Object.entries(node.variableModes).flatMap(([collectionId, modeId]) =>
+ modeEntry(context, collectionId, modeId)
+ )
+ if (entries.length > 0 || node.type === 'INSTANCE') {
+ record.variableModeBySetMap = { entries }
+ }
+}
+
+function sourceIn(scope: SceneNode, layer: SceneNode): string | undefined {
+ const state = scope.instanceOverrides
+ const source = getInstanceOverride(state, scope.id, layer.id, 'sourceComponentId')
+ return typeof source === 'string' ? source : undefined
+}
+
+function nearestSource(graph: SceneGraph, layer: SceneNode): string | undefined {
+ let scope = layer.parentId ? graph.getNode(layer.parentId) : undefined
+ while (scope) {
+ const source = scope.type === 'INSTANCE' ? sourceIn(scope, layer) : undefined
+ if (source !== undefined) {
+ return source
+ }
+ scope = scope.parentId ? graph.getNode(scope.parentId) : undefined
+ }
+ return undefined
+}
+
+function sourceLayer(
+ graph: SceneGraph,
+ claimedIn: SceneNode,
+ layer: SceneNode
+): SceneNode | undefined {
+ const source = sourceIn(claimedIn, layer) ?? nearestSource(graph, layer) ?? layer.componentId
+ return source ? graph.getNode(source) : undefined
+}
+
+export function claimedVariableModes(
+ context: ModeContext,
+ claimedIn: SceneNode,
+ owner: SceneNode,
+ layer: SceneNode
+): { entries: VariableModeEntry[] } {
+ const modes = layer.variableModes
+ const sourceModes = sourceLayer(context.graph, claimedIn, layer)?.variableModes ?? {}
+ const recorded = [...ownFields(owner, layer).keys()].flatMap(
+ (field) => variableModeOverrideCollection(field) ?? []
+ )
+ const changed = [...Object.keys(modes), ...Object.keys(sourceModes)].filter(
+ (collectionId) => modes[collectionId] !== sourceModes[collectionId]
+ )
+ const claimed = new Set([...recorded, ...changed])
+ return {
+ entries: [...claimed].flatMap((collectionId) =>
+ modeEntry(context, collectionId, modes[collectionId])
+ )
+ }
+}
diff --git a/packages/fig/src/node-change/variable/bindings.ts b/packages/fig/src/node-change/variable/bindings.ts
index 16699e5f3..394b9defb 100644
--- a/packages/fig/src/node-change/variable/bindings.ts
+++ b/packages/fig/src/node-change/variable/bindings.ts
@@ -14,6 +14,7 @@ import { boundNumberValue, isNumericVariableBindingField } from '@open-pencil/sc
import { cloneRecord } from '../clone'
import { linearVariableExpression } from './expression'
+import { mergeVariableModeMaps } from './maps'
export const VARIABLE_BINDING_FIELDS: Record<string, string> = {
cornerRadius: 'CORNER_RADIUS',
@@ -109,6 +110,13 @@ export function mergeVariableConsumptionMaps(
return { parameterConsumptionMap: { entries } }
}
+export function claimedVariableMaps(
+ layer: VariableConsumptionSource,
+ claim: VariableConsumptionSource
+): Record<string, unknown> {
+ return { ...mergeVariableConsumptionMaps(layer, claim), ...mergeVariableModeMaps(layer, claim) }
+}
+
export function variableBindingEntry(
field: string,
variableId: string | undefined,
diff --git a/packages/fig/src/node-change/variable/maps.ts b/packages/fig/src/node-change/variable/maps.ts
new file mode 100644
index 000000000..b150bda17
--- /dev/null
+++ b/packages/fig/src/node-change/variable/maps.ts
@@ -0,0 +1,83 @@
+import type { GUID } from '@open-pencil/kiwi/fig'
+import { guidToString } from '@open-pencil/kiwi/fig/guid'
+
+import type { VariableConsumptionSource } from './bindings'
+
+export interface FigVariableModeMap {
+ entries?: Array<{
+ variableSetID?: { guid?: GUID }
+ variableModeID?: GUID
+ }>
+}
+
+type VariableModeEntry = NonNullable<FigVariableModeMap['entries']>[number]
+
+const NO_FIELDS: Readonly<Record<string, unknown>> = {}
+
+function variableModeEntries(node: VariableConsumptionSource): VariableModeEntry[] {
+ return (node.variableModeBySetMap as FigVariableModeMap | undefined)?.entries ?? []
+}
+
+function collectionKey(entry: VariableModeEntry): string | undefined {
+ const collection = entry.variableSetID?.guid
+ return collection ? guidToString(collection) : undefined
+}
+
+export function variableModeLayer(
+ node: VariableConsumptionSource
+): Map<string, string | undefined> {
+ const layer = new Map<string, string | undefined>()
+ for (const entry of variableModeEntries(node)) {
+ const key = collectionKey(entry)
+ if (key) {
+ layer.set(key, entry.variableModeID ? guidToString(entry.variableModeID) : undefined)
+ }
+ }
+ return layer
+}
+
+export function mergeVariableModeMaps(
+ base: VariableConsumptionSource,
+ patch: VariableConsumptionSource
+): Readonly<Record<string, unknown>> {
+ if (!('variableModeBySetMap' in patch)) {
+ return NO_FIELDS
+ }
+ return mergedModeMap(base, patch, 'clear')
+}
+
+export function mergeVariableModeClaims(
+ earlier: VariableConsumptionSource,
+ later: VariableConsumptionSource
+): Readonly<Record<string, unknown>> {
+ if (!('variableModeBySetMap' in later) || !('variableModeBySetMap' in earlier)) {
+ return NO_FIELDS
+ }
+ return mergedModeMap(earlier, later, 'keep')
+}
+
+/**
+ * One mode map from two, the later entry winning per collection. A cleared entry, one without
+ * a mode, either clears the collection (`clear`, applying a layer) or stays as a claim to clear
+ * it (`keep`, merging claims for export).
+ */
+function mergedModeMap(
+ earlier: VariableConsumptionSource,
+ later: VariableConsumptionSource,
+ cleared: 'clear' | 'keep'
+): Readonly<Record<string, unknown>> {
+ const unresolved: VariableModeEntry[] = []
+ const byCollection = new Map<string, VariableModeEntry>()
+ for (const entry of [...variableModeEntries(earlier), ...variableModeEntries(later)]) {
+ const key = collectionKey(entry)
+ if (!key) {
+ unresolved.push(entry)
+ } else if (entry.variableModeID || cleared === 'keep') {
+ byCollection.set(key, entry)
+ } else {
+ byCollection.delete(key)
+ }
+ }
+ const entries = [...byCollection.values(), ...unresolved]
+ return { variableModeBySetMap: { entries: structuredClone(entries) } }
+}
diff --git a/packages/fig/tests/instance-overrides/occurrence/modes.test.ts b/packages/fig/tests/instance-overrides/occurrence/modes.test.ts
new file mode 100644
index 000000000..3505a1b6c
--- /dev/null
+++ b/packages/fig/tests/instance-overrides/occurrence/modes.test.ts
@@ -0,0 +1,391 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import { materializeDocument } from '#fig/document/materialize'
+import { createOccurrenceInterpreter } from '#fig/instance-overrides/interpret'
+import { occurrences } from '#fig/instance-overrides/occurrence/path'
+
+import type { NodeChange } from '@open-pencil/kiwi/fig/codec'
+
+const SIZES = 3
+const COMPACT = 10
+const WIDE = 11
+const THEME = 8
+const LIGHT = 12
+const DARK = 13
+const WIDTH = 4
+const THEMED_WIDTH = 9
+const WIDTH_BY_MODE = { [COMPACT]: 40, [WIDE]: 64 }
+const SAVED_WIDTH = 41
+
+const LEAF = 20
+const WIDE_LEAF = 21
+const CARD = 5
+const NESTED = 6
+const OUTER = 7
+const PANEL = 30
+const PANEL_CARD = 31
+const OUTER_PANEL = 32
+const CARD_FRAME = 40
+
+type Patches = Partial<Record<number, Partial<NodeChange>>>
+
+function modes(...entries: [collection: number, mode: number][]): Partial<NodeChange> {
+ return {
+ variableModeBySetMap: {
+ entries: entries.map(([collection, mode]) => ({
+ variableSetID: { guid: guid(collection) },
+ variableModeID: guid(mode)
+ }))
+ }
+ }
+}
+
+function at(path: number[], props: Record<string, unknown>): Record<string, unknown> {
+ return { guidPath: { guids: path.map((id) => guid(id)) }, ...props }
+}
+
+function instanceOf(component: number, symbolOverrides: unknown[] = []): Partial<NodeChange> {
+ const symbolData = { symbolID: guid(component), symbolOverrides }
+ return { symbolData: symbolData as NodeChange['symbolData'] }
+}
+
+function child(parent: number, position: string): { parentIndex: NodeChange['parentIndex'] } {
+ return { parentIndex: { guid: guid(parent), position } }
+}
+
+function collection(id: number, modeIds: number[]): NodeChange {
+ return {
+ guid: guid(id),
+ type: 'VARIABLE_SET',
+ variableSetModes: modeIds.map((mode, index) => ({
+ id: guid(mode),
+ name: `Mode ${mode}`,
+ sortPosition: String.fromCharCode(97 + index)
+ }))
+ }
+}
+
+function fixture(patches: Patches = {}): NodeChange[] {
+ const changes: NodeChange[] = [
+ { guid: guid(1), type: 'DOCUMENT' },
+ { guid: guid(2), type: 'CANVAS', ...child(1, '!') },
+ collection(SIZES, [COMPACT, WIDE]),
+ collection(THEME, [LIGHT, DARK]),
+ {
+ guid: guid(WIDTH),
+ type: 'VARIABLE',
+ variableResolvedType: 'FLOAT',
+ variableSetID: { guid: guid(SIZES) },
+ variableDataValues: {
+ entries: Object.entries(WIDTH_BY_MODE).map(([mode, width]) => ({
+ modeID: guid(Number(mode)),
+ variableData: { dataType: 'FLOAT', value: { floatValue: width } }
+ }))
+ }
+ },
+ {
+ guid: guid(THEMED_WIDTH),
+ type: 'VARIABLE',
+ variableResolvedType: 'FLOAT',
+ variableSetID: { guid: guid(THEME) },
+ variableDataValues: {
+ entries: [LIGHT, DARK].map((mode) => ({
+ modeID: guid(mode),
+ variableData: { dataType: 'ALIAS', value: { alias: { guid: guid(WIDTH) } } }
+ }))
+ }
+ },
+ { guid: guid(LEAF), type: 'SYMBOL', size: { x: 40, y: 10 }, ...child(2, 'a') },
+ {
+ guid: guid(WIDE_LEAF),
+ type: 'SYMBOL',
+ size: { x: 64, y: 10 },
+ ...child(2, 'b'),
+ ...modes([SIZES, WIDE])
+ },
+ { guid: guid(CARD_FRAME), type: 'FRAME', size: { x: 200, y: 10 }, ...child(2, 'c') },
+ { guid: guid(CARD), type: 'SYMBOL', size: { x: 100, y: 10 }, ...child(2, 'd') },
+ {
+ guid: guid(NESTED),
+ type: 'INSTANCE',
+ size: { x: SAVED_WIDTH, y: 10 },
+ ...child(CARD, 'a'),
+ ...instanceOf(LEAF),
+ variableConsumptionMap: {
+ entries: [
+ {
+ variableField: 'WIDTH',
+ variableData: { dataType: 'ALIAS', value: { alias: { guid: guid(WIDTH) } } }
+ }
+ ]
+ }
+ },
+ {
+ guid: guid(OUTER),
+ type: 'INSTANCE',
+ size: { x: 100, y: 10 },
+ ...child(2, 'e'),
+ ...instanceOf(CARD)
+ },
+ { guid: guid(PANEL), type: 'SYMBOL', size: { x: 100, y: 10 }, ...child(2, 'f') },
+ {
+ guid: guid(PANEL_CARD),
+ type: 'INSTANCE',
+ size: { x: 100, y: 10 },
+ ...child(PANEL, 'a'),
+ ...instanceOf(CARD)
+ },
+ {
+ guid: guid(OUTER_PANEL),
+ type: 'INSTANCE',
+ size: { x: 100, y: 10 },
+ ...child(2, 'g'),
+ ...instanceOf(PANEL)
+ }
+ ]
+ return changes.map((change) => ({ ...change, ...patches[change.guid?.localID ?? 0] }))
+}
+
+function nestedNode(changes: NodeChange[], outer = OUTER, depth = 1) {
+ const { graph, sources } = materializeDocument(changes, [], { derivedBounds: true })
+ let id = sources.get(`1:${outer}`)
+ for (let level = 0; level < depth; level++) {
+ id = id ? graph.getChildren(id)[0]?.id : undefined
+ }
+ const nested = id ? graph.nodes.get(id) : undefined
+ if (!nested) {
+ throw new Error('Missing nested instance')
+ }
+ return { graph, nested }
+}
+
+function nestedWidth(changes: NodeChange[], outer = OUTER, depth = 1): number {
+ return nestedNode(changes, outer, depth).nested.width
+}
+
+test('a nested instance takes its bound size from the mode its outer instance sets', () => {
+ expect(nestedWidth(fixture({ [OUTER]: modes([SIZES, WIDE]) }))).toBe(WIDTH_BY_MODE[WIDE])
+})
+
+test('a nested instance keeps its saved size where no outer mode differs', () => {
+ expect(nestedWidth(fixture())).toBe(SAVED_WIDTH)
+})
+
+test('derived data the outer instance saved wins over the nested instance mode', () => {
+ const derivedWidth = 70
+ const derived = {
+ derivedSymbolData: [{ guidPath: { guids: [guid(NESTED)] }, size: { x: derivedWidth, y: 10 } }]
+ }
+ expect(nestedWidth(fixture({ [OUTER]: { ...modes([SIZES, WIDE]), ...derived } }))).toBe(
+ derivedWidth
+ )
+})
+
+test('a mode the outer instance sets on the nested instance through its overrides applies', () => {
+ const outer = instanceOf(CARD, [at([NESTED], modes([SIZES, WIDE]))])
+ expect(nestedWidth(fixture({ [OUTER]: outer }))).toBe(WIDTH_BY_MODE[WIDE])
+})
+
+test('a mode set through overrides two instance levels down applies', () => {
+ const outer = instanceOf(PANEL, [at([PANEL_CARD, NESTED], modes([SIZES, WIDE]))])
+ expect(nestedWidth(fixture({ [OUTER_PANEL]: outer }), OUTER_PANEL, 2)).toBe(WIDTH_BY_MODE[WIDE])
+})
+
+test('an explicit default mode where the component is defined matches an absent one', () => {
+ const patches = {
+ [CARD_FRAME]: modes([SIZES, COMPACT]),
+ [CARD]: child(CARD_FRAME, 'a')
+ }
+ expect(nestedWidth(fixture(patches))).toBe(SAVED_WIDTH)
+})
+
+test('an explicit default mode on the outer instance matches an absent one', () => {
+ expect(nestedWidth(fixture({ [OUTER]: modes([SIZES, COMPACT]) }))).toBe(SAVED_WIDTH)
+})
+
+const SAVED_IN_WIDE = 63
+
+function pinnedCard(outer: Partial<NodeChange>): Patches {
+ return {
+ [CARD]: modes([SIZES, WIDE]),
+ [NESTED]: { size: { x: SAVED_IN_WIDE, y: 10 } },
+ [OUTER]: outer
+ }
+}
+
+test('an instance record that repeats its component root mode keeps the saved size', () => {
+ const outer = modes([SIZES, WIDE], [THEME, LIGHT])
+ expect(nestedWidth(fixture(pinnedCard(outer)))).toBe(SAVED_IN_WIDE)
+})
+
+test('an instance record mode map replaces the modes its component root sets', () => {
+ expect(nestedWidth(fixture(pinnedCard(modes([THEME, LIGHT]))))).toBe(WIDTH_BY_MODE[COMPACT])
+})
+
+test('a swapped nested instance takes the mode of the component that replaced it', () => {
+ const outer = instanceOf(CARD, [at([NESTED], { overriddenSymbolID: guid(WIDE_LEAF) })])
+ expect(nestedWidth(fixture({ [OUTER]: outer }))).toBe(WIDTH_BY_MODE[WIDE])
+})
+
+test('a mode of a collection the nested instance does not bind keeps its saved size', () => {
+ expect(nestedWidth(fixture({ [OUTER]: modes([THEME, DARK]) }))).toBe(SAVED_WIDTH)
+})
+
+test('a collection the nested binding reaches through an alias drops its saved size', () => {
+ const themed = {
+ variableConsumptionMap: {
+ entries: [
+ {
+ variableField: 'WIDTH',
+ variableData: { dataType: 'ALIAS', value: { alias: { guid: guid(THEMED_WIDTH) } } }
+ }
+ ]
+ }
+ }
+ const changes = fixture({ [NESTED]: themed, [OUTER]: modes([SIZES, WIDE]) })
+ const outer = createOccurrenceInterpreter(changes).instance(`1:${OUTER}`)
+ const nested = [...occurrences(outer)].find(({ sourceId }) => sourceId === `1:${NESTED}`)
+
+ expect(nested?.properties.size).toEqual({ x: SAVED_WIDTH, y: 10 })
+ expect(nested?.derivedSize).toBeUndefined()
+})
+
+function modeUnset(collection: number): Partial<NodeChange> {
+ return { variableModeBySetMap: { entries: [{ variableSetID: { guid: guid(collection) } }] } }
+}
+
+test('an override naming a collection without a mode clears the nested component mode', () => {
+ const patches = {
+ [NESTED]: { ...instanceOf(WIDE_LEAF), size: { x: WIDTH_BY_MODE[WIDE], y: 10 } },
+ [OUTER]: instanceOf(CARD, [at([NESTED], modeUnset(SIZES))])
+ }
+ const { graph, nested } = nestedNode(fixture(patches))
+
+ expect(graph.getNodeVariableModeId(nested.id, `1:${SIZES}`)).toBe(`1:${COMPACT}`)
+})
+
+test('an override naming a collection without a mode clears the nested layer mode', () => {
+ const patches = {
+ [NESTED]: { ...modes([SIZES, WIDE]), size: { x: WIDTH_BY_MODE[WIDE], y: 10 } },
+ [OUTER]: instanceOf(CARD, [at([NESTED], modeUnset(SIZES))])
+ }
+ expect(nestedWidth(fixture(patches))).toBe(WIDTH_BY_MODE[COMPACT])
+})
+
+test('a cleared component mode drops the saved size of the nested instance', () => {
+ const patches = {
+ [NESTED]: { ...instanceOf(WIDE_LEAF), size: { x: WIDTH_BY_MODE[WIDE], y: 10 } },
+ [OUTER]: instanceOf(CARD, [at([NESTED], modeUnset(SIZES))])
+ }
+ expect(nestedWidth(fixture(patches))).toBe(WIDTH_BY_MODE[COMPACT])
+})
+
+test('a cleared mode takes the mode the outer instance sets', () => {
+ const patches = {
+ [NESTED]: { ...modes([SIZES, COMPACT]), size: { x: WIDTH_BY_MODE[COMPACT], y: 10 } },
+ [OUTER]: { ...modes([SIZES, WIDE]), ...instanceOf(CARD, [at([NESTED], modeUnset(SIZES))]) }
+ }
+ expect(nestedWidth(fixture(patches))).toBe(WIDTH_BY_MODE[WIDE])
+})
+
+test('an override mode replaces the nested layer mode of the same collection', () => {
+ const patches = {
+ [NESTED]: { ...modes([SIZES, WIDE]), size: { x: WIDTH_BY_MODE[WIDE], y: 10 } },
+ [OUTER]: instanceOf(CARD, [at([NESTED], modes([SIZES, COMPACT]))])
+ }
+ expect(nestedWidth(fixture(patches))).toBe(WIDTH_BY_MODE[COMPACT])
+})
+
+test('an override of one collection keeps the nested layer mode of another', () => {
+ const patches = {
+ [NESTED]: { ...modes([SIZES, WIDE], [THEME, DARK]), size: { x: WIDTH_BY_MODE[WIDE], y: 10 } },
+ [OUTER]: instanceOf(CARD, [at([NESTED], modeUnset(THEME))])
+ }
+ const { graph, nested } = nestedNode(fixture(patches))
+
+ expect(nested.width).toBe(WIDTH_BY_MODE[WIDE])
+ expect(nested.variableModes).toEqual({ [`1:${SIZES}`]: `1:${WIDE}` })
+ expect(graph.getNodeVariableModeId(nested.id, `1:${THEME}`)).toBe(`1:${LIGHT}`)
+})
+
+test('an instance record mode map stands for all of its modes', () => {
+ const patches = {
+ [NESTED]: { ...instanceOf(WIDE_LEAF), ...modes([THEME, DARK]) },
+ [OUTER]: instanceOf(CARD)
+ }
+ const { nested } = nestedNode(fixture(patches))
+
+ expect(nested.variableModes).toEqual({ [`1:${THEME}`]: `1:${DARK}` })
+})
+
+function twoLevelClaims(outerModes: Partial<NodeChange>, innerModes: Partial<NodeChange>): Patches {
+ return {
+ [PANEL_CARD]: instanceOf(CARD, [at([NESTED], innerModes)]),
+ [OUTER_PANEL]: instanceOf(PANEL, [at([PANEL_CARD, NESTED], outerModes)])
+ }
+}
+
+test('modes two owners set on one nested instance for different collections all apply', () => {
+ const patches = twoLevelClaims(modes([THEME, DARK]), modes([SIZES, WIDE]))
+ const { graph, nested } = nestedNode(fixture(patches), OUTER_PANEL, 2)
+ expect(nested.width).toBe(WIDTH_BY_MODE[WIDE])
+ expect(graph.getNodeVariableModeId(nested.id, `1:${THEME}`)).toBe(`1:${DARK}`)
+})
+
+test('the outer owner mode wins where two owners set one collection on a nested instance', () => {
+ const patches = twoLevelClaims(modes([SIZES, WIDE]), modes([SIZES, COMPACT]))
+ expect(nestedWidth(fixture(patches), OUTER_PANEL, 2)).toBe(WIDTH_BY_MODE[WIDE])
+})
+
+const CARD_BODY = 41
+
+function withCardBody(changes: NodeChange[]): NodeChange[] {
+ const body: NodeChange = {
+ guid: guid(CARD_BODY),
+ type: 'FRAME',
+ size: { x: 100, y: 10 },
+ ...child(CARD, 'a')
+ }
+ return [...changes, body]
+}
+
+test('a mode addressed through a frame inside the component reaches the nested instance', () => {
+ const patches = {
+ [NESTED]: child(CARD_BODY, 'a'),
+ [OUTER]: instanceOf(CARD, [at([CARD_BODY, NESTED], modes([SIZES, WIDE]))])
+ }
+ expect(nestedWidth(withCardBody(fixture(patches)), OUTER, 2)).toBe(WIDTH_BY_MODE[WIDE])
+})
+
+test('the outer owner mode wins over an inner one addressed through a frame', () => {
+ const patches = {
+ [NESTED]: child(CARD_BODY, 'a'),
+ [PANEL_CARD]: instanceOf(CARD, [at([CARD_BODY, NESTED], modes([SIZES, COMPACT]))]),
+ [OUTER_PANEL]: instanceOf(PANEL, [at([PANEL_CARD, NESTED], modes([SIZES, WIDE]))])
+ }
+ expect(nestedWidth(withCardBody(fixture(patches)), OUTER_PANEL, 3)).toBe(WIDTH_BY_MODE[WIDE])
+})
+
+test('a binding to a library variable by asset reference drops the saved size', () => {
+ const libraryBinding = {
+ variableConsumptionMap: {
+ entries: [
+ {
+ variableField: 'WIDTH',
+ variableData: { dataType: 'ALIAS', value: { alias: { assetRef: { key: 'width' } } } }
+ }
+ ]
+ }
+ }
+ const patches = {
+ [WIDTH]: { key: 'width' },
+ [NESTED]: libraryBinding,
+ [OUTER]: modes([SIZES, WIDE])
+ } as Patches
+ const outer = createOccurrenceInterpreter(fixture(patches)).instance(`1:${OUTER}`)
+ const nested = [...occurrences(outer)].find(({ sourceId }) => sourceId === `1:${NESTED}`)
+
+ expect(nested?.derivedSize).toBeUndefined()
+ expect(nestedWidth(fixture(patches))).toBe(WIDTH_BY_MODE[WIDE])
+})
diff --git a/packages/fig/tests/node-change/export/override-claims.test.ts b/packages/fig/tests/node-change/export/override-claims.test.ts
index 422197aaf..aee73a519 100644
--- a/packages/fig/tests/node-change/export/override-claims.test.ts
+++ b/packages/fig/tests/node-change/export/override-claims.test.ts
@@ -40,3 +40,31 @@ describe('merging symbol overrides', () => {
])
})
})
+
+describe('merging variable mode claims', () => {
+ const sizes = { guid: { sessionID: 1, localID: 3 } }
+ const theme = { guid: { sessionID: 1, localID: 8 } }
+ const wide = { sessionID: 1, localID: 11 }
+
+ test('two claims at one path keep the collections each of them claims', () => {
+ const overrides: KiwiSymbolOverridePayload[] = [
+ { guidPath: at(1), variableModeBySetMap: { entries: [{ variableSetID: theme }] } }
+ ]
+
+ mergeOverrides(overrides, [
+ {
+ guidPath: at(1),
+ variableModeBySetMap: { entries: [{ variableSetID: sizes, variableModeID: wide }] }
+ }
+ ])
+
+ expect(overrides).toEqual([
+ {
+ guidPath: at(1),
+ variableModeBySetMap: {
+ entries: [{ variableSetID: theme }, { variableSetID: sizes, variableModeID: wide }]
+ }
+ }
+ ])
+ })
+})
diff --git a/packages/fig/tests/node-change/export/variable-modes.test.ts b/packages/fig/tests/node-change/export/variable-modes.test.ts
new file mode 100644
index 000000000..b8510c44a
--- /dev/null
+++ b/packages/fig/tests/node-change/export/variable-modes.test.ts
@@ -0,0 +1,89 @@
+import { expect, test } from 'bun:test'
+
+import type { KiwiNodeChange } from '#fig/node-change/export/context'
+import { applyVariableModes, claimedVariableModes } from '#fig/node-change/export/variable-modes'
+
+import { SceneGraph, type SceneNode } from '@open-pencil/scene-graph'
+import {
+ setInstanceOverride,
+ variableModeOverrideField
+} from '@open-pencil/scene-graph/instances/overrides'
+
+const SIZES = '1:3'
+const COMPACT = '1:10'
+const WIDE = '1:11'
+const sizes = { variableSetID: { guid: { sessionID: 1, localID: 3 } } }
+const modeOf = (localID: number) => ({ ...sizes, variableModeID: { sessionID: 1, localID } })
+
+function cardWithNestedLeaf() {
+ const graph = new SceneGraph()
+ graph.addCollection({
+ id: SIZES,
+ name: 'Sizes',
+ modes: [
+ { modeId: COMPACT, name: 'Compact' },
+ { modeId: WIDE, name: 'Wide' }
+ ],
+ defaultModeId: COMPACT,
+ variableIds: []
+ })
+ const page = graph.getPages()[0]
+ const leaf = graph.createNode('COMPONENT', page.id, {
+ name: 'Leaf',
+ variableModes: { [SIZES]: WIDE }
+ })
+ const card = graph.createNode('COMPONENT', page.id, { name: 'Card' })
+ const placed = graph.createInstance(leaf.id, card.id)
+ if (!placed) {
+ throw new Error('Missing nested instance')
+ }
+ graph.updateNode(placed.id, { variableModes: { [SIZES]: COMPACT } })
+ const outer = graph.createInstance(card.id, page.id)
+ const nested = outer ? graph.getChildren(outer.id)[0] : undefined
+ if (!outer || !nested) {
+ throw new Error('Missing outer instance')
+ }
+ return { graph, outer, nested }
+}
+
+function claimWith(variableModes: Record<string, string>, recorded = false) {
+ const { graph, outer, nested } = cardWithNestedLeaf()
+ graph.updateNode(nested.id, { variableModes })
+ if (recorded) {
+ const field = variableModeOverrideField(SIZES)
+ setInstanceOverride(outer.instanceOverrides, outer.id, nested.id, field)
+ }
+ const layer: SceneNode | undefined = graph.getNode(nested.id)
+ if (!layer) {
+ throw new Error('Missing nested layer')
+ }
+ return claimedVariableModes({ graph }, outer, outer, layer).entries
+}
+
+test('a mode the nested layer of the outer component sets is not claimed again', () => {
+ expect(claimWith({ [SIZES]: COMPACT })).toEqual([])
+})
+
+test('a mode that differs from the nested layer is claimed, even when the main sets it', () => {
+ expect(claimWith({ [SIZES]: WIDE })).toEqual([modeOf(11)])
+})
+
+test('a mode the nested layer no longer has is claimed without a mode', () => {
+ expect(claimWith({})).toEqual([sizes])
+})
+
+test('a collection the file claimed stays explicit when it matches the nested layer', () => {
+ expect(claimWith({ [SIZES]: COMPACT }, true)).toEqual([modeOf(10)])
+})
+
+test('an instance record follows its component unless it sets its own modes', () => {
+ const { graph, outer } = cardWithNestedLeaf()
+ const followed: KiwiNodeChange = {}
+ applyVariableModes({ graph }, outer, followed)
+ setInstanceOverride(outer.instanceOverrides, outer.id, outer.id, 'variableModes')
+ const own: KiwiNodeChange = {}
+ applyVariableModes({ graph }, outer, own)
+
+ expect(followed.variableModeBySetMap).toBeUndefined()
+ expect(own.variableModeBySetMap).toEqual({ entries: [] })
+})
diff --git a/packages/fig/tests/node-change/variable/maps.test.ts b/packages/fig/tests/node-change/variable/maps.test.ts
new file mode 100644
index 000000000..7a13d9846
--- /dev/null
+++ b/packages/fig/tests/node-change/variable/maps.test.ts
@@ -0,0 +1,68 @@
+import { expect, test } from 'bun:test'
+
+import { guid } from '#fig-tests/helpers/guid'
+import {
+ mergeVariableModeClaims,
+ mergeVariableModeMaps,
+ variableModeLayer
+} from '#fig/node-change/variable/maps'
+
+const SIZES = 3
+const THEME = 8
+const COMPACT = 10
+const WIDE = 11
+const DARK = 13
+
+function entry(collection: number, mode?: number) {
+ return mode === undefined
+ ? { variableSetID: { guid: guid(collection) } }
+ : { variableSetID: { guid: guid(collection) }, variableModeID: guid(mode) }
+}
+
+function modeMap(...entries: ReturnType<typeof entry>[]) {
+ return { variableModeBySetMap: { entries } }
+}
+
+test('a mode replaces the mode of its own collection only', () => {
+ const merged = mergeVariableModeMaps(
+ modeMap(entry(SIZES, WIDE), entry(THEME, DARK)),
+ modeMap(entry(SIZES, COMPACT))
+ )
+ expect(merged).toEqual(modeMap(entry(SIZES, COMPACT), entry(THEME, DARK)))
+})
+
+test('an entry without a mode clears its collection', () => {
+ const merged = mergeVariableModeMaps(
+ modeMap(entry(SIZES, WIDE), entry(THEME, DARK)),
+ modeMap(entry(SIZES))
+ )
+ expect(merged).toEqual(modeMap(entry(THEME, DARK)))
+})
+
+test('a record without a mode map leaves the modes alone', () => {
+ expect(mergeVariableModeMaps(modeMap(entry(SIZES, WIDE)), {})).toEqual({})
+})
+
+test('an entry whose collection is not resolved is kept', () => {
+ const unresolved = { variableSetID: {}, variableModeID: guid(WIDE) }
+ const merged = mergeVariableModeMaps(modeMap(entry(SIZES, WIDE)), {
+ variableModeBySetMap: { entries: [unresolved] }
+ })
+ expect(merged).toEqual({ variableModeBySetMap: { entries: [entry(SIZES, WIDE), unresolved] } })
+})
+
+test('a mode layer marks a cleared collection without a mode', () => {
+ const layer = variableModeLayer(modeMap(entry(SIZES, WIDE), entry(THEME)))
+ expect([...layer]).toEqual([
+ [`1:${SIZES}`, `1:${WIDE}`],
+ [`1:${THEME}`, undefined]
+ ])
+})
+
+test('claims combine per collection and keep a cleared collection', () => {
+ const merged = mergeVariableModeClaims(
+ modeMap(entry(SIZES, WIDE), entry(THEME, DARK)),
+ modeMap(entry(SIZES), entry(THEME, DARK))
+ )
+ expect(merged).toEqual(modeMap(entry(SIZES), entry(THEME, DARK)))
+})
diff --git a/packages/fig/tests/node-change/variable-token.test.ts b/packages/fig/tests/node-change/variable/token.test.ts
similarity index 100%
rename from packages/fig/tests/node-change/variable-token.test.ts
rename to packages/fig/tests/node-change/variable/token.test.ts
diff --git a/packages/scene-graph/src/instances/overrides.ts b/packages/scene-graph/src/instances/overrides.ts
index 6cf281508..1917eb281 100644
--- a/packages/scene-graph/src/instances/overrides.ts
+++ b/packages/scene-graph/src/instances/overrides.ts
@@ -109,6 +109,19 @@ export function cloneInstanceOverrideState(state: InstanceOverrideState): Instan
export interface InstanceOverrideReferenceMapper {
node: (id: string) => string
variable: (id: string) => string
+ collection?: (id: string) => string | undefined
+}
+
+const VARIABLE_MODE_FIELD_PREFIX = 'variableModes/'
+
+export function variableModeOverrideField(collectionId: string): InstanceOverrideField {
+ return `${VARIABLE_MODE_FIELD_PREFIX}${collectionId}`
+}
+
+export function variableModeOverrideCollection(field: InstanceOverrideField): string | undefined {
+ return field.startsWith(VARIABLE_MODE_FIELD_PREFIX)
+ ? field.slice(VARIABLE_MODE_FIELD_PREFIX.length)
+ : undefined
}
/** Remap runtime identities only; ordinary strings and source-format payloads stay opaque. */
@@ -122,8 +135,21 @@ export function remapInstanceOverrideState(
if (overriddenBindingField(field) !== null) return references.variable(value)
return value
}
+ const remapField = (field: string): string | undefined => {
+ const collection = variableModeOverrideCollection(field)
+ if (collection === undefined || !references.collection) {
+ return field
+ }
+ const mapped = references.collection(collection)
+ return mapped === undefined ? undefined : variableModeOverrideField(mapped)
+ }
const fields = (entries: ReadonlyMap<string, unknown>) =>
- new Map([...entries].map(([field, value]) => [field, remapValue(field, value)]))
+ new Map(
+ [...entries].flatMap(([field, value]) => {
+ const mapped = remapField(field)
+ return mapped === undefined ? [] : [[mapped, remapValue(field, value)] as const]
+ })
+ )
const descendants = new Map<string, Map<string, unknown>>()
for (const [id, entries] of state.descendants) {
const mapped = references.node(id)
diff --git a/packages/scene-graph/src/transfer/nodes.ts b/packages/scene-graph/src/transfer/nodes.ts
index e4842177c..9cac283ae 100644
--- a/packages/scene-graph/src/transfer/nodes.ts
+++ b/packages/scene-graph/src/transfer/nodes.ts
@@ -65,7 +65,8 @@ export function prepareNodeTransfer(
result.componentId = source.componentId ? node(source.componentId) : null
result.instanceOverrides = remapInstanceOverrideState(source.instanceOverrides, {
node,
- variable
+ variable,
+ collection: (id) => refs.collections.get(id)
})
result.boundVariables = Object.fromEntries(
Object.entries(source.boundVariables).map(([field, id]) => [field, variable(id)])
diff --git a/packages/scene-graph/tests/components/override-transfer.test.ts b/packages/scene-graph/tests/components/override-transfer.test.ts
index cf68afa22..d58a15405 100644
--- a/packages/scene-graph/tests/components/override-transfer.test.ts
+++ b/packages/scene-graph/tests/components/override-transfer.test.ts
@@ -2,7 +2,8 @@ import { expect, test } from 'bun:test'
import {
createInstanceOverrideState,
- remapInstanceOverrideState
+ remapInstanceOverrideState,
+ variableModeOverrideField
} from '@open-pencil/scene-graph/instances/overrides'
test('override transfer remaps typed identities without rewriting equal text', () => {
@@ -22,7 +23,8 @@ test('override transfer remaps typed identities without rewriting equal text', (
const before = structuredClone(state)
const result = remapInstanceOverrideState(state, {
node: (id) => `node/${id}`,
- variable: (id) => `variable/${id}`
+ variable: (id) => `variable/${id}`,
+ collection: (id) => `collection/${id}`
})
expect(result.self.get('componentId')).toBe('node/source')
expect(result.self.get('text')).toBe('source')
@@ -43,6 +45,54 @@ test('override transfer rejects colliding target mappings', () => {
state.descendants.set('a', new Map())
state.descendants.set('b', new Map())
expect(() =>
- remapInstanceOverrideState(state, { node: () => 'same', variable: (id) => id })
+ remapInstanceOverrideState(state, {
+ node: () => 'same',
+ variable: (id) => id,
+ collection: (id) => id
+ })
).toThrow('Duplicate remapped override target')
})
+
+test('override transfer remaps the collection a mode override is keyed by', () => {
+ const state = createInstanceOverrideState()
+ state.descendants.set(
+ 'child',
+ new Map<string, unknown>([
+ [variableModeOverrideField('sizes'), true],
+ [variableModeOverrideField('gone'), true]
+ ])
+ )
+ const result = remapInstanceOverrideState(state, {
+ node: (id) => id,
+ variable: (id) => id,
+ collection: (id) => (id === 'sizes' ? 'pasted-sizes' : undefined)
+ })
+ expect(result.descendants.get('child')).toEqual(
+ new Map<string, unknown>([[variableModeOverrideField('pasted-sizes'), true]])
+ )
+})
+
+test('override transfer remaps the collection of a self mode override', () => {
+ const state = createInstanceOverrideState()
+ state.self.set(variableModeOverrideField('sizes'), true)
+ const result = remapInstanceOverrideState(state, {
+ node: (id) => id,
+ variable: (id) => id,
+ collection: (id) => (id === 'sizes' ? 'pasted-sizes' : undefined)
+ })
+ expect(result.self).toEqual(
+ new Map<string, unknown>([[variableModeOverrideField('pasted-sizes'), true]])
+ )
+})
+
+test('override transfer without a collection mapper keeps mode override keys', () => {
+ const state = createInstanceOverrideState()
+ state.descendants.set(
+ 'child',
+ new Map<string, unknown>([[variableModeOverrideField('sizes'), true]])
+ )
+ const result = remapInstanceOverrideState(state, { node: (id) => id, variable: (id) => id })
+ expect(result.descendants.get('child')).toEqual(
+ new Map<string, unknown>([[variableModeOverrideField('sizes'), true]])
+ )
+})
diff --git a/packages/scene-graph/tests/transfer/nodes.test.ts b/packages/scene-graph/tests/transfer/nodes.test.ts
index 612d019d4..dc23d119b 100644
--- a/packages/scene-graph/tests/transfer/nodes.test.ts
+++ b/packages/scene-graph/tests/transfer/nodes.test.ts
@@ -1,6 +1,7 @@
import { expect, test } from 'bun:test'
import { SceneGraph } from '@open-pencil/scene-graph'
+import { variableModeOverrideField } from '@open-pencil/scene-graph/instances/overrides'
import { prepareNodeTransfer, type NodeTransferReferences } from '@open-pencil/scene-graph/transfer'
const references = (): NodeTransferReferences => ({
@@ -55,3 +56,13 @@ test('node preparation fails on missing runtime references before destination mu
const node = graph.createNode('INSTANCE', graph.getPages()[0].id, { componentId: 'missing' })
expect(() => prepareNodeTransfer(node, references())).toThrow('Missing node transfer mapping')
})
+
+test('node preparation remaps the collection a mode override is keyed by', () => {
+ const graph = new SceneGraph()
+ const node = graph.createNode('INSTANCE', graph.getPages()[0].id, { componentId: 'component' })
+ node.instanceOverrides.self.set(variableModeOverrideField('set'), true)
+ const result = prepareNodeTransfer(node, references())
+ expect(result.instanceOverrides?.self).toEqual(
+ new Map<string, unknown>([[variableModeOverrideField('new-set'), true]])
+ )
+})