figme-mcp 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Fields bound to variables, evaluated in the variable modes in force (F28, F29).
3
+ *
4
+ * A layer binds a field to a variable in `variableConsumptionMap` and in the newer
5
+ * `parameterConsumptionMap` (which also carries component-property bindings, `propRefValue`):
6
+ * `entries[] { variableField, variableData: { value: { alias } } }`; a paint, a gradient stop or
7
+ * an effect binds its colour in `colorVar`. The value written beside a binding — the node's
8
+ * `visible`, the paint's `color` — was resolved where the layer is defined: for a component's
9
+ * layer, in the component's own modes. An instance that picks other modes shows other values,
10
+ * and Figma stores none of them (no derived record ever carries `visible` or paints). So a layer
11
+ * inside an instance is evaluated here, in the modes in force at it; a stored layer keeps the
12
+ * values Figma stored for it, which were resolved where it stands.
13
+ */
14
+ import type { NodeChange } from '../fig/parse.js';
15
+ import type { KiwiObject } from '../fig/kiwi.js';
16
+ import type { TreeNode } from './tree.js';
17
+ import { type ModeMap, type VariableIndex } from './variables.js';
18
+ /** The variable `node` binds `field` to (a `VariableID`), or undefined when it binds none. */
19
+ export declare function boundVariable(node: NodeChange, field: string): KiwiObject | undefined;
20
+ export interface BoundNode {
21
+ readonly node: NodeChange;
22
+ /** Bound fields that took their variable's value in the modes in force. */
23
+ readonly applied: number;
24
+ /** Bound fields whose value cannot be known from this file; they keep the cached value. */
25
+ readonly unresolved: number;
26
+ }
27
+ /** F28 — `visible` from the variable the node binds it to, read in the modes in force. */
28
+ export declare function applyVisibility(idx: VariableIndex, node: NodeChange, modes: ModeMap): BoundNode;
29
+ /**
30
+ * Paints with every colour bound to a variable read in `modes` (F29) — for a paint list picked at
31
+ * draw time, such as a style a text run or vector region names.
32
+ */
33
+ export declare function boundPaints(idx: VariableIndex, paints: KiwiObject[], modes: ModeMap): KiwiObject[];
34
+ /**
35
+ * F29 — every colour the node binds to a variable, read in the modes in force: its fills, strokes
36
+ * and effects, and the paints of its text-run and vector-region style entries. Apply it after
37
+ * colour styles are resolved (F19), since a style's paints can be bound too.
38
+ */
39
+ export declare function applyColours(idx: VariableIndex, node: NodeChange, modes: ModeMap): BoundNode;
40
+ /** F28 and F29 together: the node's visibility and colours, read in the modes in force. */
41
+ export declare function applyBindings(idx: VariableIndex, node: NodeChange, modes: ModeMap): BoundNode;
42
+ /**
43
+ * The modes the inspection tools read a layer's colour bindings in: those of a layer inside an
44
+ * instance (a virtual scene node, model/scene.ts). A stored layer — or a node that is not a scene
45
+ * node — keeps the values Figma stored for it, so this is undefined for it.
46
+ */
47
+ export declare function bindingModesOf(t: TreeNode): ModeMap | undefined;
48
+ //# sourceMappingURL=bindings.d.ts.map
@@ -0,0 +1,129 @@
1
+ import { bool, num, obj, objArr, str } from './access.js';
2
+ import { variableValueIn } from './variables.js';
3
+ /** The maps that bind a node's fields; Figma writes both, the newer first. */
4
+ const BINDING_MAPS = ['parameterConsumptionMap', 'variableConsumptionMap'];
5
+ /** The variable `node` binds `field` to (a `VariableID`), or undefined when it binds none. */
6
+ export function boundVariable(node, field) {
7
+ for (const map of BINDING_MAPS) {
8
+ for (const entry of objArr(obj(node, map), 'entries')) {
9
+ if (str(entry, 'variableField') !== field)
10
+ continue;
11
+ const alias = obj(obj(obj(entry, 'variableData'), 'value'), 'alias');
12
+ if (alias)
13
+ return alias;
14
+ }
15
+ }
16
+ return undefined;
17
+ }
18
+ /** F28 — `visible` from the variable the node binds it to, read in the modes in force. */
19
+ export function applyVisibility(idx, node, modes) {
20
+ const alias = boundVariable(node, 'VISIBLE');
21
+ if (!alias)
22
+ return { node, applied: 0, unresolved: 0 };
23
+ const visible = bool(variableValueIn(idx, alias, modes), 'boolValue');
24
+ if (visible === undefined)
25
+ return { node, applied: 0, unresolved: 1 };
26
+ const same = visible === (bool(node, 'visible') !== false);
27
+ return { node: same ? node : { ...node, visible }, applied: 1, unresolved: 0 };
28
+ }
29
+ function sameColour(a, b) {
30
+ return ['r', 'g', 'b', 'a'].every((c) => num(a, c) === num(b, c));
31
+ }
32
+ /**
33
+ * A paint, gradient stop or effect with its `color` taken from the variable its `colorVar`
34
+ * names. The variable's colour carries its own alpha; a paint's `opacity` is a separate field,
35
+ * with a binding of its own (`opacityVar`), and is left alone.
36
+ */
37
+ function withBoundColour(idx, holder, modes, tally) {
38
+ const alias = obj(obj(obj(holder, 'colorVar'), 'value'), 'alias');
39
+ if (!alias)
40
+ return holder;
41
+ const colour = obj(variableValueIn(idx, alias, modes), 'colorValue');
42
+ if (!colour) {
43
+ tally.unresolved += 1;
44
+ return holder;
45
+ }
46
+ tally.applied += 1;
47
+ return sameColour(colour, obj(holder, 'color')) ? holder : { ...holder, color: colour };
48
+ }
49
+ /** The same list when nothing in it changed, so callers can tell. */
50
+ function mapSame(list, fn) {
51
+ let changed = false;
52
+ const out = list.map((item) => {
53
+ const next = fn(item);
54
+ if (next !== item)
55
+ changed = true;
56
+ return next;
57
+ });
58
+ return changed ? out : list;
59
+ }
60
+ function paintsIn(idx, paints, modes, tally) {
61
+ return mapSame(paints, (paint) => {
62
+ const own = withBoundColour(idx, paint, modes, tally);
63
+ const stops = objArr(paint, 'stops');
64
+ const bound = mapSame(stops, (stop) => withBoundColour(idx, stop, modes, tally));
65
+ return bound === stops ? own : { ...own, stops: bound };
66
+ });
67
+ }
68
+ /**
69
+ * Paints with every colour bound to a variable read in `modes` (F29) — for a paint list picked at
70
+ * draw time, such as a style a text run or vector region names.
71
+ */
72
+ export function boundPaints(idx, paints, modes) {
73
+ return paintsIn(idx, paints, modes, { applied: 0, unresolved: 0 });
74
+ }
75
+ /**
76
+ * F29 — every colour the node binds to a variable, read in the modes in force: its fills, strokes
77
+ * and effects, and the paints of its text-run and vector-region style entries. Apply it after
78
+ * colour styles are resolved (F19), since a style's paints can be bound too.
79
+ */
80
+ export function applyColours(idx, node, modes) {
81
+ const tally = { applied: 0, unresolved: 0 };
82
+ let out = node;
83
+ for (const field of ['fillPaints', 'strokePaints']) {
84
+ const paints = objArr(out, field);
85
+ const bound = paintsIn(idx, paints, modes, tally);
86
+ if (bound !== paints)
87
+ out = { ...out, [field]: bound };
88
+ }
89
+ const effects = objArr(out, 'effects');
90
+ const boundEffects = mapSame(effects, (e) => withBoundColour(idx, e, modes, tally));
91
+ if (boundEffects !== effects)
92
+ out = { ...out, effects: boundEffects };
93
+ for (const holder of ['textData', 'vectorData']) {
94
+ const data = obj(out, holder);
95
+ const table = objArr(data, 'styleOverrideTable');
96
+ const bound = mapSame(table, (entry) => {
97
+ let next = entry;
98
+ for (const field of ['fillPaints', 'strokePaints']) {
99
+ const paints = objArr(next, field);
100
+ const boundPaints = paintsIn(idx, paints, modes, tally);
101
+ if (boundPaints !== paints)
102
+ next = { ...next, [field]: boundPaints };
103
+ }
104
+ return next;
105
+ });
106
+ if (bound !== table)
107
+ out = { ...out, [holder]: { ...data, styleOverrideTable: bound } };
108
+ }
109
+ return { node: out, ...tally };
110
+ }
111
+ /** F28 and F29 together: the node's visibility and colours, read in the modes in force. */
112
+ export function applyBindings(idx, node, modes) {
113
+ const visibility = applyVisibility(idx, node, modes);
114
+ const colours = applyColours(idx, visibility.node, modes);
115
+ return {
116
+ node: colours.node,
117
+ applied: visibility.applied + colours.applied,
118
+ unresolved: visibility.unresolved + colours.unresolved,
119
+ };
120
+ }
121
+ /**
122
+ * The modes the inspection tools read a layer's colour bindings in: those of a layer inside an
123
+ * instance (a virtual scene node, model/scene.ts). A stored layer — or a node that is not a scene
124
+ * node — keeps the values Figma stored for it, so this is undefined for it.
125
+ */
126
+ export function bindingModesOf(t) {
127
+ const layer = t;
128
+ return layer.virtual === true ? layer.modes : undefined;
129
+ }
@@ -1,5 +1,5 @@
1
1
  import { guidKey, breadcrumb } from './tree.js';
2
- import { resolveOverridePath } from './instance.js';
2
+ import { assignmentValue, propValueOfVariableData, resolveOverridePath } from './instance.js';
3
3
  import { bool, colorHex, compact, jsonSafe, num, obj, objArr, r2, str } from './access.js';
4
4
  import { cornerRadiusOf, effectView, paintBox, paintView, sideWeights, styleRefsOf, textBasics, } from './summarize.js';
5
5
  import { describeVariableData } from './variables.js';
@@ -29,12 +29,16 @@ function componentPropValue(idx, value) {
29
29
  const keys = Object.keys(value);
30
30
  return keys.length ? { [keys[0]]: jsonSafe(value[keys[0]]) } : undefined;
31
31
  }
32
- /** Component-property assignments with the property names resolved. */
32
+ /**
33
+ * Component-property assignments with the property names resolved. The value is read from
34
+ * whichever slot holds it (F26); one this view cannot evaluate — a PROP_REF to the enclosing
35
+ * instance, a variable — is described as the variable data it is.
36
+ */
33
37
  function propAssignmentViews(idx, assignments) {
34
38
  return assignments.map((a) => {
35
39
  const defID = guidKey(obj(a, 'defID')) ?? '?';
36
40
  const def = idx.propDefs().get(defID);
37
- const value = componentPropValue(idx, obj(a, 'value'));
41
+ const value = componentPropValue(idx, assignmentValue(idx, a));
38
42
  return compact({
39
43
  defID,
40
44
  name: def?.name,
@@ -56,7 +60,8 @@ export function componentView(idx, t) {
56
60
  return compact({
57
61
  name: str(d, 'name') ?? resolved?.name,
58
62
  type: str(d, 'type') ?? resolved?.type,
59
- default: componentPropValue(idx, obj(d, 'initialValue')),
63
+ // An INSTANCE_SWAP default may exist only as variable data (F26).
64
+ default: componentPropValue(idx, obj(d, 'initialValue') ?? propValueOfVariableData(idx, obj(d, 'varValue'))),
60
65
  });
61
66
  })
62
67
  .filter((d) => d.name !== undefined);
@@ -39,12 +39,19 @@ export declare class FileIndex {
39
39
  private searchIndex;
40
40
  private overrideIdentityIndex;
41
41
  private propDefIndex;
42
+ private componentKeyIndex;
42
43
  constructor(fig: ParsedFig);
43
44
  get root(): TreeNode | undefined;
44
45
  get nodeCount(): number;
45
46
  node(guid: string): TreeNode | undefined;
46
47
  /** Resolve a `{assetRef:{key}}` reference to the local node defining it, when it is local. */
47
48
  resolveAssetRef(ref: KiwiObject | undefined): TreeNode | undefined;
49
+ /**
50
+ * A component (SYMBOL) by its publish key — `componentKey`, else `key` — for a reference that
51
+ * names a component by `assetRef` instead of by guid (F26). Only components present in this
52
+ * file resolve. Built on first use.
53
+ */
54
+ componentByKey(key: string): TreeNode | undefined;
48
55
  /** DFS pre-order slice of a subtree, so pagination and cursors are stable. */
49
56
  subtreeRange(root: TreeNode): {
50
57
  start: number;
@@ -18,6 +18,7 @@ export class FileIndex {
18
18
  searchIndex;
19
19
  overrideIdentityIndex;
20
20
  propDefIndex;
21
+ componentKeyIndex;
21
22
  constructor(fig) {
22
23
  this.fig = fig;
23
24
  this.tree = buildTree(fig.nodeChanges);
@@ -94,6 +95,24 @@ export class FileIndex {
94
95
  const key = assetRefKey(ref);
95
96
  return key ? this.byAssetKey.get(key) : undefined;
96
97
  }
98
+ /**
99
+ * A component (SYMBOL) by its publish key — `componentKey`, else `key` — for a reference that
100
+ * names a component by `assetRef` instead of by guid (F26). Only components present in this
101
+ * file resolve. Built on first use.
102
+ */
103
+ componentByKey(key) {
104
+ if (!this.componentKeyIndex) {
105
+ const map = new Map();
106
+ for (const t of this.symbols) {
107
+ for (const k of [str(t.node, 'componentKey'), str(t.node, 'key')]) {
108
+ if (k && !map.has(k))
109
+ map.set(k, t);
110
+ }
111
+ }
112
+ this.componentKeyIndex = map;
113
+ }
114
+ return this.componentKeyIndex.get(key);
115
+ }
97
116
  /** DFS pre-order slice of a subtree, so pagination and cursors are stable. */
98
117
  subtreeRange(root) {
99
118
  let end = root.order + 1;
@@ -21,7 +21,8 @@
21
21
  * an instance gives the component's properties. A symbol descendant bound to a property through
22
22
  * `componentPropRefs` takes its `visible`, its text or its symbol from the assignment. Not one of
23
23
  * the sample's 29 877 BOOLEAN=false assignments is mirrored by a `visible:false` record, so the
24
- * assignments have to be evaluated, not read back.
24
+ * assignments have to be evaluated, not read back. An assignment keeps its value in `value` or,
25
+ * in files from current Figma, only in `varValue` (F26) — `assignmentValue` reads both.
25
26
  */
26
27
  import type { KiwiObject } from '../fig/kiwi.js';
27
28
  import type { NodeChange } from '../fig/parse.js';
@@ -29,15 +30,39 @@ import type { FileIndex } from './index.js';
29
30
  import { type TreeNode } from './tree.js';
30
31
  /** Record map for one instance level: identity path (joined by '/') → partial NodeChange. */
31
32
  export type OverrideRecords = ReadonlyMap<string, KiwiObject>;
32
- /** Component-property assignments of one instance: defID → `{textValue|boolValue|guidValue}`. */
33
+ /**
34
+ * Component-property assignments of one instance: defID → the value in `ComponentPropValue`
35
+ * shape, `{textValue|boolValue|guidValue}`, whichever slot the file stored it in.
36
+ */
33
37
  export type PropAssignments = ReadonlyMap<string, KiwiObject>;
38
+ /** The index lookups the instance resolver needs. */
39
+ type ResolverIndex = Pick<FileIndex, 'node' | 'componentByKey'>;
34
40
  export interface ResolvedInstance {
35
41
  readonly symbol: TreeNode;
36
42
  readonly records: OverrideRecords;
37
43
  readonly props: PropAssignments;
38
44
  }
39
45
  /**
40
- * `{ ...base, ...patch }` minus the addressing fields.
46
+ * A component property's value held as `VariableData` — the `varValue` of an assignment or of a
47
+ * property definition — in the `ComponentPropValue` shape the rest of the resolver reads, or
48
+ * undefined when it holds nothing this file can turn into one (F26).
49
+ *
50
+ * The names differ between the two shapes: a swap is `symbolIdValue { guid | assetRef }`, not
51
+ * `guidValue`, and text is `textDataValue`, because a `VariableAnyValue`'s `textValue` is a plain
52
+ * string. A `propRefValue` (a property of the enclosing instance) or an `alias` (a variable)
53
+ * carries no value of its own and is left to the caller.
54
+ */
55
+ export declare function propValueOfVariableData(index: Pick<FileIndex, 'componentByKey'>, data: KiwiObject | undefined): KiwiObject | undefined;
56
+ /**
57
+ * The value one assignment gives its property, in `ComponentPropValue` shape: the `value` slot
58
+ * when the file wrote it, else what `varValue` holds — a value of its own (F26), or a PROP_REF to
59
+ * a property of the enclosing instance, looked up in `outerProps`. Undefined when the assignment
60
+ * carries nothing usable, and the component's own default then stands.
61
+ */
62
+ export declare function assignmentValue(index: ResolverIndex, assignment: KiwiObject, outerProps?: PropAssignments): KiwiObject | undefined;
63
+ /**
64
+ * `{ ...base, ...patch }` minus the addressing fields, with property assignments merged per
65
+ * definition and binding maps per bound field.
41
66
  *
42
67
  * Figma re-derives geometry only for nodes that paint something (F20): of the sample's 22 097
43
68
  * resized painted nodes, 18 lack it. A record that resizes a node without supplying geometry
@@ -56,7 +81,7 @@ export declare function mergeNode(base: NodeChange, patch: KiwiObject | undefine
56
81
  * which an assignment of this instance may point at instead of carrying a value (PROP_REF —
57
82
  * none in the sample, so this path is untested against real data).
58
83
  */
59
- export declare function resolveInstance(index: FileIndex, node: NodeChange, inherited?: OverrideRecords, outerProps?: PropAssignments): ResolvedInstance | undefined;
84
+ export declare function resolveInstance(index: ResolverIndex, node: NodeChange, inherited?: OverrideRecords, outerProps?: PropAssignments): ResolvedInstance | undefined;
60
85
  /**
61
86
  * The records an enclosing instance contributes to a nested one: every entry whose path starts
62
87
  * with the nested instance's own identity, with that segment removed.
@@ -77,6 +102,27 @@ export interface AppliedProps {
77
102
  * wrong words — so the caller reports it instead.
78
103
  */
79
104
  export declare function applyProps(node: NodeChange, props: PropAssignments, outlinesFromRecord: boolean): AppliedProps;
105
+ /**
106
+ * F27 — the stored record of a nested instance whose component is swapped, as the swapped-in
107
+ * component shows it. The record is complete for the component it was written for, so it holds
108
+ * copies of that component root's own appearance — an icon's filled circle and round corners —
109
+ * that are not overrides. Swapped, the instance keeps only what it overrides: every unit of
110
+ * `ROOT_APPEARANCE` equal to the old root's takes the new root's value (or none, where the new
111
+ * root has none), and the outline, which traced the old component's shape, is dropped.
112
+ */
113
+ export declare function swapAppearance(stored: NodeChange, from: NodeChange, to: NodeChange): NodeChange;
114
+ export interface ShownLayer extends AppliedProps {
115
+ /** True when a property value changed the layer. */
116
+ readonly propsApplied: boolean;
117
+ }
118
+ /**
119
+ * A component layer as the instance that expands it shows it: the stored node merged with its
120
+ * record, with the instance's property values applied (F17, F18) — and, for a nested instance
121
+ * whose component that swaps, with the copies of the old component's root appearance taken out
122
+ * before the record goes on top (F27). Shared by the exporter and the scene, so the picture and
123
+ * the inspection tools see the same layer.
124
+ */
125
+ export declare function showLayer(index: Pick<FileIndex, 'node'>, t: TreeNode, records: OverrideRecords, props: PropAssignments): ShownLayer;
80
126
  /**
81
127
  * The node a record path addresses, walked exactly the way the renderer expands the instance:
82
128
  * each segment names a node inside the current symbol by identity, and a segment that lands on a
@@ -84,4 +130,5 @@ export declare function applyProps(node: NodeChange, props: PropAssignments, out
84
130
  * enclosing level's records and property assignments, which may have swapped it.
85
131
  */
86
132
  export declare function resolveOverridePath(index: FileIndex, instance: TreeNode, path: readonly string[]): TreeNode | undefined;
133
+ export {};
87
134
  //# sourceMappingURL=instance.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import { guidKey, overrideIdentity } from './tree.js';
2
- import { bool, num, obj, objArr, str } from './access.js';
2
+ import { assetRefKey, bool, num, obj, objArr, str } from './access.js';
3
3
  /** Addressing fields that must never be merged into a node as content. */
4
4
  const OVERRIDE_META = new Set(['guidPath', 'overrideLevel', 'guid', 'phase', 'parentIndex']);
5
5
  function pathOf(record) {
@@ -11,6 +11,55 @@ function pathOf(record) {
11
11
  function defIdOf(assignment) {
12
12
  return guidKey(obj(assignment, 'defID'));
13
13
  }
14
+ /**
15
+ * A component property's value held as `VariableData` — the `varValue` of an assignment or of a
16
+ * property definition — in the `ComponentPropValue` shape the rest of the resolver reads, or
17
+ * undefined when it holds nothing this file can turn into one (F26).
18
+ *
19
+ * The names differ between the two shapes: a swap is `symbolIdValue { guid | assetRef }`, not
20
+ * `guidValue`, and text is `textDataValue`, because a `VariableAnyValue`'s `textValue` is a plain
21
+ * string. A `propRefValue` (a property of the enclosing instance) or an `alias` (a variable)
22
+ * carries no value of its own and is left to the caller.
23
+ */
24
+ export function propValueOfVariableData(index, data) {
25
+ const value = obj(data, 'value');
26
+ if (!value)
27
+ return undefined;
28
+ const flag = bool(value, 'boolValue');
29
+ if (flag !== undefined)
30
+ return { boolValue: flag };
31
+ const text = obj(value, 'textDataValue');
32
+ if (text)
33
+ return { textValue: text };
34
+ const symbol = obj(value, 'symbolIdValue');
35
+ if (symbol) {
36
+ const byGuid = obj(symbol, 'guid');
37
+ if (guidKey(byGuid))
38
+ return { guidValue: byGuid };
39
+ const key = assetRefKey(symbol);
40
+ const local = key ? index.componentByKey(key) : undefined;
41
+ const guid = local ? obj(local.node, 'guid') : undefined;
42
+ if (guid)
43
+ return { guidValue: guid };
44
+ }
45
+ return undefined;
46
+ }
47
+ /**
48
+ * The value one assignment gives its property, in `ComponentPropValue` shape: the `value` slot
49
+ * when the file wrote it, else what `varValue` holds — a value of its own (F26), or a PROP_REF to
50
+ * a property of the enclosing instance, looked up in `outerProps`. Undefined when the assignment
51
+ * carries nothing usable, and the component's own default then stands.
52
+ */
53
+ export function assignmentValue(index, assignment, outerProps) {
54
+ const value = obj(assignment, 'value');
55
+ if (value && Object.keys(value).length > 0)
56
+ return value;
57
+ const varValue = obj(assignment, 'varValue');
58
+ const ref = guidKey(obj(obj(obj(varValue, 'value'), 'propRefValue'), 'defId'));
59
+ if (ref)
60
+ return outerProps?.get(ref);
61
+ return propValueOfVariableData(index, varValue);
62
+ }
14
63
  /**
15
64
  * Property assignments merge per definition: a record that reassigns a nested instance's
16
65
  * properties lists only the ones it changes (1 251 of the sample's 2 591 such records are
@@ -36,8 +85,36 @@ function sizeDiffers(a, b) {
36
85
  return (Math.abs((num(a, 'x') ?? 0) - (num(b, 'x') ?? 0)) > 1e-3 ||
37
86
  Math.abs((num(a, 'y') ?? 0) - (num(b, 'y') ?? 0)) > 1e-3);
38
87
  }
88
+ /** The maps that bind a node's fields to variables and properties (model/bindings.ts). */
89
+ const BINDING_MAPS = new Set(['variableConsumptionMap', 'parameterConsumptionMap']);
39
90
  /**
40
- * `{ ...base, ...patch }` minus the addressing fields.
91
+ * F28 — binding maps merge per bound field. A record lists only the bindings it changes: one
92
+ * that restyles a text writes an EMPTY `variableConsumptionMap` beside its text style, and its
93
+ * layer stays bound — Figma's own layout of the instance still follows the binding — so replacing
94
+ * the map would unbind every field of every restyled layer. An entry that names a field but has
95
+ * no `variableData` unbinds that field.
96
+ */
97
+ function mergeBindings(base, patch) {
98
+ const out = new Map();
99
+ for (const entry of objArr(base, 'entries')) {
100
+ const field = str(entry, 'variableField');
101
+ if (field)
102
+ out.set(field, entry);
103
+ }
104
+ for (const entry of objArr(patch, 'entries')) {
105
+ const field = str(entry, 'variableField');
106
+ if (!field)
107
+ continue;
108
+ if (obj(entry, 'variableData'))
109
+ out.set(field, entry);
110
+ else
111
+ out.delete(field);
112
+ }
113
+ return { ...patch, entries: [...out.values()] };
114
+ }
115
+ /**
116
+ * `{ ...base, ...patch }` minus the addressing fields, with property assignments merged per
117
+ * definition and binding maps per bound field.
41
118
  *
42
119
  * Figma re-derives geometry only for nodes that paint something (F20): of the sample's 22 097
43
120
  * resized painted nodes, 18 lack it. A record that resizes a node without supplying geometry
@@ -51,7 +128,10 @@ export function mergeNode(base, patch) {
51
128
  for (const [k, v] of Object.entries(patch)) {
52
129
  if (OVERRIDE_META.has(k))
53
130
  continue;
54
- out[k] = k === 'componentPropAssignments' ? mergeAssignments(base[k], v) : v;
131
+ out[k] =
132
+ k === 'componentPropAssignments' ? mergeAssignments(base[k], v)
133
+ : BINDING_MAPS.has(k) ? mergeBindings(base[k], v)
134
+ : v;
55
135
  }
56
136
  if (sizeDiffers(obj(base, 'size'), obj(patch, 'size'))) {
57
137
  if (patch['fillGeometry'] === undefined)
@@ -105,8 +185,7 @@ export function resolveInstance(index, node, inherited, outerProps) {
105
185
  const id = defIdOf(a);
106
186
  if (!id)
107
187
  continue;
108
- const ref = obj(obj(obj(obj(a, 'varValue'), 'value'), 'propRefValue'), 'defId');
109
- const value = obj(a, 'value') ?? (ref ? outerProps?.get(guidKey(ref) ?? '') : undefined);
188
+ const value = assignmentValue(index, a, outerProps);
110
189
  if (value)
111
190
  props.set(id, value);
112
191
  }
@@ -177,6 +256,103 @@ export function applyProps(node, props, outlinesFromRecord) {
177
256
  }
178
257
  return { node: out, staleOutlines };
179
258
  }
259
+ /**
260
+ * The fields of an instance's own box that come from its component's root unless the instance
261
+ * overrides them, in the units Figma writes together: paints with their style reference, the
262
+ * stroke-weight group, the corner group (F27).
263
+ */
264
+ const ROOT_APPEARANCE = [
265
+ ['fillPaints', 'styleIdForFill'],
266
+ ['strokePaints', 'styleIdForStrokeFill'],
267
+ ['strokeWeight', 'borderStrokeWeightsIndependent', 'borderTopWeight', 'borderRightWeight',
268
+ 'borderBottomWeight', 'borderLeftWeight'],
269
+ ['strokeAlign'],
270
+ ['strokeJoin'],
271
+ ['strokeCap'],
272
+ ['dashPattern'],
273
+ ['effects', 'styleIdForEffect'],
274
+ ['cornerRadius', 'rectangleCornerRadiiIndependent', 'rectangleTopLeftCornerRadius',
275
+ 'rectangleTopRightCornerRadius', 'rectangleBottomRightCornerRadius', 'rectangleBottomLeftCornerRadius'],
276
+ ['cornerSmoothing'],
277
+ ['opacity'],
278
+ ['blendMode'],
279
+ ['frameMaskDisabled'],
280
+ ];
281
+ /** Structural equality of two decoded values: primitives, bytes, arrays and records. */
282
+ function sameValue(a, b) {
283
+ if (a === b)
284
+ return true;
285
+ if (a instanceof Uint8Array || b instanceof Uint8Array) {
286
+ return a instanceof Uint8Array && b instanceof Uint8Array &&
287
+ a.length === b.length && a.every((v, i) => v === b[i]);
288
+ }
289
+ if (Array.isArray(a) || Array.isArray(b)) {
290
+ return Array.isArray(a) && Array.isArray(b) &&
291
+ a.length === b.length && a.every((v, i) => sameValue(v, b[i]));
292
+ }
293
+ if (a && b && typeof a === 'object' && typeof b === 'object') {
294
+ const ka = Object.keys(a);
295
+ const kb = Object.keys(b);
296
+ return ka.length === kb.length &&
297
+ ka.every((k) => Object.hasOwn(b, k) && sameValue(a[k], b[k]));
298
+ }
299
+ return false;
300
+ }
301
+ /** The component an INSTANCE record shows: its swap target, else its own symbol. */
302
+ function componentOf(node) {
303
+ return (guidKey(obj(node, 'overriddenSymbolID')) ??
304
+ guidKey(obj(obj(node, 'symbolData'), 'symbolID')));
305
+ }
306
+ /**
307
+ * F27 — the stored record of a nested instance whose component is swapped, as the swapped-in
308
+ * component shows it. The record is complete for the component it was written for, so it holds
309
+ * copies of that component root's own appearance — an icon's filled circle and round corners —
310
+ * that are not overrides. Swapped, the instance keeps only what it overrides: every unit of
311
+ * `ROOT_APPEARANCE` equal to the old root's takes the new root's value (or none, where the new
312
+ * root has none), and the outline, which traced the old component's shape, is dropped.
313
+ */
314
+ export function swapAppearance(stored, from, to) {
315
+ const out = { ...stored };
316
+ delete out['fillGeometry'];
317
+ delete out['strokeGeometry'];
318
+ for (const unit of ROOT_APPEARANCE) {
319
+ if (!unit.every((field) => sameValue(stored[field], from[field])))
320
+ continue;
321
+ for (const field of unit) {
322
+ if (to[field] === undefined)
323
+ delete out[field];
324
+ else
325
+ out[field] = to[field];
326
+ }
327
+ }
328
+ return out;
329
+ }
330
+ /**
331
+ * A component layer as the instance that expands it shows it: the stored node merged with its
332
+ * record, with the instance's property values applied (F17, F18) — and, for a nested instance
333
+ * whose component that swaps, with the copies of the old component's root appearance taken out
334
+ * before the record goes on top (F27). Shared by the exporter and the scene, so the picture and
335
+ * the inspection tools see the same layer.
336
+ */
337
+ export function showLayer(index, t, records, props) {
338
+ const record = records.get(overrideIdentity(t));
339
+ const outlines = record?.['derivedTextData'] !== undefined;
340
+ const merged = mergeNode(t.node, record);
341
+ const applied = applyProps(merged, props, outlines);
342
+ if (str(t.node, 'type') === 'INSTANCE') {
343
+ const from = componentOf(t.node);
344
+ const to = componentOf(applied.node);
345
+ const old = from && to && from !== to ? index.node(from) : undefined;
346
+ const swapped = old && to ? index.node(to) : undefined;
347
+ if (old && swapped) {
348
+ // A component missing from the file (a library one) cannot be compared; nothing changes.
349
+ const cleaned = mergeNode(swapAppearance(t.node, old.node, swapped.node), record);
350
+ const reapplied = applyProps(cleaned, props, outlines);
351
+ return { ...reapplied, propsApplied: reapplied.node !== cleaned };
352
+ }
353
+ }
354
+ return { ...applied, propsApplied: applied.node !== merged };
355
+ }
180
356
  /**
181
357
  * The node a record path addresses, walked exactly the way the renderer expands the instance:
182
358
  * each segment names a node inside the current symbol by identity, and a segment that lands on a
@@ -2,6 +2,7 @@ import type { KiwiObject } from '../fig/kiwi.js';
2
2
  import type { FileIndex } from './index.js';
3
3
  import { type TreeNode } from './tree.js';
4
4
  import { type ResolvedInstance } from './instance.js';
5
+ import { type ModeMap } from './variables.js';
5
6
  /** The records and property values in force for the layers of one expanded instance. */
6
7
  export interface Level {
7
8
  /** Guid of the outermost, stored instance: the first segment of every sublayer id. */
@@ -11,6 +12,12 @@ export interface Level {
11
12
  readonly instance: ResolvedInstance;
12
13
  /** Symbols expanded on the way here, so a self-referential component cannot loop. */
13
14
  readonly active: ReadonlySet<string>;
15
+ /**
16
+ * The variable modes in force at the instance this level expands — its own picks over those
17
+ * of the layers above it (F28). The component root's own picks do not apply: the instance's
18
+ * record stands in for the root.
19
+ */
20
+ readonly modes: ModeMap;
14
21
  }
15
22
  export interface SceneNode extends TreeNode {
16
23
  /** The stored node this layer shows: itself, or the symbol descendant for a sublayer. */
@@ -19,6 +26,8 @@ export interface SceneNode extends TreeNode {
19
26
  readonly virtual: boolean;
20
27
  /** For a sublayer, the expansion it belongs to. */
21
28
  readonly level: Level | undefined;
29
+ /** The variable modes in force at this layer: its own picks over those above it (F28). */
30
+ readonly modes: ModeMap;
22
31
  readonly children: SceneNode[];
23
32
  }
24
33
  export declare function isSublayerId(id: string): boolean;
@@ -1,5 +1,7 @@
1
1
  import { guidKey, overrideIdentity } from './tree.js';
2
- import { applyProps, descend, mergeNode, resolveInstance, } from './instance.js';
2
+ import { descend, resolveInstance, showLayer } from './instance.js';
3
+ import { applyVisibility } from './bindings.js';
4
+ import { NO_MODES, withModes } from './variables.js';
3
5
  import { obj, objArr, str } from './access.js';
4
6
  /** Instances nested deeper than this are almost certainly a cycle in a damaged file. */
5
7
  const MAX_INSTANCE_DEPTH = 24;
@@ -21,6 +23,7 @@ class Layer {
21
23
  parentLayer;
22
24
  expanded;
23
25
  expansion;
26
+ modeMap;
24
27
  constructor(index, init) {
25
28
  this.index = index;
26
29
  this.key = init.key;
@@ -51,6 +54,10 @@ class Layer {
51
54
  this.expanded ??= this.expand();
52
55
  return this.expanded;
53
56
  }
57
+ get modes() {
58
+ this.modeMap ??= withModes(this.index, this.parent?.modes ?? NO_MODES, this.node);
59
+ return this.modeMap;
60
+ }
54
61
  /** The expansion this INSTANCE opens — its symbol, records and property values. */
55
62
  instanceLevel() {
56
63
  if (this.expansion === undefined)
@@ -75,6 +82,7 @@ class Layer {
75
82
  path: outer ? [...outer.path, identity] : [],
76
83
  instance,
77
84
  active: new Set([...active, instance.symbol.key]),
85
+ modes: this.modes,
78
86
  };
79
87
  }
80
88
  expand() {
@@ -88,14 +96,16 @@ class Layer {
88
96
  return this.source.children.map((c) => new Layer(this.index, { key: c.key, node: c.node, source: c, parent: this }));
89
97
  }
90
98
  }
91
- /** A symbol descendant as the instance expanded at `level` shows it. */
99
+ /**
100
+ * A symbol descendant as the instance expanded at `level` shows it — including a visibility it
101
+ * binds to a variable, read in the modes in force at it (F28), as the renderer reads it.
102
+ */
92
103
  function sublayer(index, c, level, parent) {
93
- const identity = overrideIdentity(c);
94
- const record = level.instance.records.get(identity);
95
- const node = applyProps(mergeNode(c.node, record), level.instance.props, record?.['derivedTextData'] !== undefined).node;
104
+ const { records, props } = level.instance;
105
+ const shown = showLayer(index, c, records, props).node;
96
106
  return new Layer(index, {
97
- key: `I${level.root};${[...level.path, identity].join(';')}`,
98
- node,
107
+ key: `I${level.root};${[...level.path, overrideIdentity(c)].join(';')}`,
108
+ node: applyVisibility(index, shown, withModes(index, parent.modes, shown)).node,
99
109
  source: c,
100
110
  level,
101
111
  parent,
@@ -11,6 +11,14 @@ import type { NodeChange } from '../fig/parse.js';
11
11
  import type { KiwiObject } from '../fig/kiwi.js';
12
12
  import type { FileIndex } from './index.js';
13
13
  import { type TreeNode } from './tree.js';
14
+ import { type ApplyStylesOptions } from './styles.js';
15
+ /**
16
+ * `node` — the layer `t`, or one of its partial run entries — with paints, effects and typography
17
+ * as Figma shows them: a referenced style wins over the copy cached beside it (F19, F22), and for
18
+ * a layer inside an instance a colour bound to a variable is read in the modes in force there
19
+ * (F29), exactly as the renderer reads it.
20
+ */
21
+ export declare function shownStyle(idx: FileIndex, t: TreeNode, node?: NodeChange, opts?: ApplyStylesOptions): NodeChange;
14
22
  export interface NodeSummary {
15
23
  guid: string;
16
24
  type: string;
@@ -3,6 +3,18 @@ import { breadcrumb, guidKey } from './tree.js';
3
3
  import { assetRefString, bool, bytes, colorHex, compact, hex, jsonSafe, num, obj, objArr, r2, str, } from './access.js';
4
4
  import { describeVariableData } from './variables.js';
5
5
  import { applyStyles, DETACHED_STYLE_GUID, resolveStyle } from './styles.js';
6
+ import { applyColours, bindingModesOf } from './bindings.js';
7
+ /**
8
+ * `node` — the layer `t`, or one of its partial run entries — with paints, effects and typography
9
+ * as Figma shows them: a referenced style wins over the copy cached beside it (F19, F22), and for
10
+ * a layer inside an instance a colour bound to a variable is read in the modes in force there
11
+ * (F29), exactly as the renderer reads it.
12
+ */
13
+ export function shownStyle(idx, t, node = t.node, opts = { text: true }) {
14
+ const styled = applyStyles(idx, node, opts);
15
+ const modes = bindingModesOf(t);
16
+ return modes ? applyColours(idx, styled, modes).node : styled;
17
+ }
6
18
  export function summarize(t, opts = {}) {
7
19
  const size = obj(t.node, 'size');
8
20
  const w = num(size, 'x');
@@ -530,8 +542,8 @@ function orUndefined(o) {
530
542
  }
531
543
  export function nodeDetail(idx, t, opts = {}) {
532
544
  const node = t.node;
533
- // Paints, effects and typography as Figma shows them: a referenced style wins (F19, F22).
534
- const live = applyStyles(idx, node, { text: true });
545
+ // Paints, effects and typography as Figma shows them (F19, F22, F29).
546
+ const live = shownStyle(idx, t);
535
547
  const maxChildren = opts.maxChildren ?? 100;
536
548
  const box = paintBox(node);
537
549
  const fills = objArr(live, 'fillPaints').map((p) => paintView(idx, p, box));
@@ -688,8 +700,8 @@ export function styleBlock(idx, t) {
688
700
  left: r2(num(node, 'stackChildMarginLeft')),
689
701
  })),
690
702
  }));
691
- // Paints, effects and typography as Figma shows them: a referenced style wins (F19, F22).
692
- const live = applyStyles(idx, node, { text: true });
703
+ // Paints, effects and typography as Figma shows them (F19, F22, F29).
704
+ const live = shownStyle(idx, t);
693
705
  const box = paintBox(node);
694
706
  const fills = objArr(live, 'fillPaints').map((p) => paintView(idx, p, box));
695
707
  const strokes = objArr(live, 'strokePaints').map((p) => paintView(idx, p, box));
@@ -1,6 +1,5 @@
1
1
  import { compact, num, obj, objArr, str } from './access.js';
2
- import { typography } from './summarize.js';
3
- import { applyStyles } from './styles.js';
2
+ import { shownStyle, typography } from './summarize.js';
4
3
  /**
5
4
  * The four fields a copy inventory actually needs, ~6x cheaper than the full typography. Text
6
5
  * painted with more than one fill, or with a gradient or image, has no single colour: its fills
@@ -29,11 +28,12 @@ export function textView(idx, t, includeRuns) {
29
28
  const ids = textData?.['characterStyleIDs'] ?? [];
30
29
  const hasStyledRuns = ids.some((id) => id !== 0);
31
30
  // The typography Figma lays the text out with: a referenced style wins over the cached copy
32
- // (F19, F22), for the node and for each run's override entry alike.
31
+ // (F19, F22), and inside an instance a bound colour takes the instance's mode (F29) — for the
32
+ // node and for each run's override entry alike.
33
33
  const view = {
34
34
  characters,
35
35
  characterCount: characters.length,
36
- baseStyle: orUndefined(typography(idx, applyStyles(idx, t.node, { text: true }))),
36
+ baseStyle: orUndefined(typography(idx, shownStyle(idx, t))),
37
37
  hasStyledRuns,
38
38
  };
39
39
  if (!includeRuns)
@@ -58,7 +58,7 @@ export function textView(idx, t, includeRuns) {
58
58
  text: characters.slice(start, i),
59
59
  styleID,
60
60
  style: override
61
- ? orUndefined(typography(idx, applyStyles(idx, override, { text: true, partial: true })))
61
+ ? orUndefined(typography(idx, shownStyle(idx, t, override, { text: true, partial: true })))
62
62
  : undefined,
63
63
  }));
64
64
  start = i;
@@ -5,10 +5,38 @@
5
5
  * Consumption sites carry a `VariableData` whose `value.alias` points at a variable either by
6
6
  * local GUID or by library `assetRef`. Local aliases are followed (with a cycle guard); library
7
7
  * aliases are surfaced as-is, since the library is not in the file.
8
+ *
9
+ * Which of a variable's values a layer shows depends on the MODE in force there (F28): a layer
10
+ * may pick a mode per collection (`variableModeBySetMap`), and otherwise inherits the pick of the
11
+ * nearest layer above it that made one, else the collection's default mode — its first.
12
+ * `withModes` and `variableValueIn` evaluate that.
8
13
  */
14
+ import type { NodeChange } from '../fig/parse.js';
9
15
  import type { FileIndex } from './index.js';
10
16
  import type { TreeNode } from './tree.js';
11
17
  import type { KiwiObject } from '../fig/kiwi.js';
18
+ /** The index lookups variable resolution needs. */
19
+ export type VariableIndex = Pick<FileIndex, 'node' | 'resolveAssetRef'>;
20
+ /** The variable modes in force at a layer: collection identity (`collectionKey`) → mode guid. */
21
+ export type ModeMap = ReadonlyMap<string, string>;
22
+ /** No mode picked anywhere: every collection is in its default mode. */
23
+ export declare const NO_MODES: ModeMap;
24
+ /**
25
+ * The identity of a variable collection, however a reference spells it (a `VariableSetID`:
26
+ * `guid` and/or `assetRef`). A collection is known by its publish key when it has one — the key
27
+ * is what other references use, and a file may hold more than one copy of a library collection —
28
+ * else by its guid.
29
+ */
30
+ export declare function collectionKey(idx: VariableIndex, ref: KiwiObject | undefined): string | undefined;
31
+ /** `base` with the modes `node` picks itself (`variableModeBySetMap`) taking precedence. */
32
+ export declare function withModes(idx: VariableIndex, base: ModeMap, node: NodeChange): ModeMap;
33
+ /**
34
+ * The value a variable takes under `modes` — the `VariableAnyValue` at the end of its alias
35
+ * chain, each variable read in the mode in force for its own collection — or undefined when that
36
+ * cannot be known here: a variable or collection not in the file, a mode it has no value for, an
37
+ * extended collection's mode, or a chain deeper than the guard.
38
+ */
39
+ export declare function variableValueIn(idx: VariableIndex, alias: KiwiObject | undefined, modes: ModeMap, depth?: number): KiwiObject | undefined;
12
40
  export interface VariableRef {
13
41
  /** Local variable name when resolvable, else undefined. */
14
42
  name?: string;
@@ -19,7 +47,7 @@ export interface VariableRef {
19
47
  values?: Record<string, unknown>;
20
48
  unresolved?: true;
21
49
  }
22
- export declare function variableSetOf(idx: FileIndex, variable: TreeNode): TreeNode | undefined;
50
+ export declare function variableSetOf(idx: VariableIndex, variable: TreeNode): TreeNode | undefined;
23
51
  /** Per-mode values of one VARIABLE node, following local alias chains. */
24
52
  export declare function variableValues(idx: FileIndex, variable: TreeNode, depth?: number): Record<string, unknown>;
25
53
  /** Resolve a `VariableID` (`{guid}` or `{assetRef}`) to a named local variable when possible. */
@@ -1,6 +1,81 @@
1
- import { assetRefString, bool, colorHex, compact, num, obj, objArr, r2, str, jsonSafe } from './access.js';
1
+ import { assetRefKey, assetRefString, bool, colorHex, compact, num, obj, objArr, r2, str, jsonSafe, } from './access.js';
2
2
  import { guidKey } from './tree.js';
3
3
  const MAX_ALIAS_DEPTH = 8;
4
+ /** No mode picked anywhere: every collection is in its default mode. */
5
+ export const NO_MODES = new Map();
6
+ /**
7
+ * A mode this reader cannot evaluate: one picked in an extended collection, whose overrides of
8
+ * the base collection's values are not read. A value looked up under it is unknown, and the
9
+ * value cached beside the binding stands.
10
+ */
11
+ const UNKNOWN_MODE = '';
12
+ /**
13
+ * The identity of a variable collection, however a reference spells it (a `VariableSetID`:
14
+ * `guid` and/or `assetRef`). A collection is known by its publish key when it has one — the key
15
+ * is what other references use, and a file may hold more than one copy of a library collection —
16
+ * else by its guid.
17
+ */
18
+ export function collectionKey(idx, ref) {
19
+ if (!ref)
20
+ return undefined;
21
+ const g = guidKey(obj(ref, 'guid'));
22
+ const local = (g ? idx.node(g) : undefined) ?? idx.resolveAssetRef(ref);
23
+ if (local)
24
+ return str(local.node, 'key') ?? local.key;
25
+ return assetRefKey(ref) ?? g;
26
+ }
27
+ /** `base` with the modes `node` picks itself (`variableModeBySetMap`) taking precedence. */
28
+ export function withModes(idx, base, node) {
29
+ let out;
30
+ for (const entry of objArr(obj(node, 'variableModeBySetMap'), 'entries')) {
31
+ const set = collectionKey(idx, obj(entry, 'variableSetID'));
32
+ const mode = guidKey(obj(entry, 'variableModeID'));
33
+ if (!set || !mode)
34
+ continue;
35
+ (out ??= new Map(base)).set(set, obj(entry, 'variableSetExtensionID') ? UNKNOWN_MODE : mode);
36
+ }
37
+ return out ?? base;
38
+ }
39
+ /** A collection's default mode: the first of its modes, in their fractional-index order. */
40
+ function defaultMode(set) {
41
+ let first;
42
+ for (const mode of objArr(set.node, 'variableSetModes')) {
43
+ const at = str(mode, 'sortPosition');
44
+ const best = str(first, 'sortPosition');
45
+ // Raw code-unit comparison, as for sibling order (fig-reading-solution.md §11.4).
46
+ if (!first || (at !== undefined && best !== undefined && at < best))
47
+ first = mode;
48
+ }
49
+ return guidKey(obj(first, 'id'));
50
+ }
51
+ /**
52
+ * The value a variable takes under `modes` — the `VariableAnyValue` at the end of its alias
53
+ * chain, each variable read in the mode in force for its own collection — or undefined when that
54
+ * cannot be known here: a variable or collection not in the file, a mode it has no value for, an
55
+ * extended collection's mode, or a chain deeper than the guard.
56
+ */
57
+ export function variableValueIn(idx, alias, modes, depth = 0) {
58
+ if (!alias || depth > MAX_ALIAS_DEPTH)
59
+ return undefined;
60
+ const g = guidKey(obj(alias, 'guid'));
61
+ const variable = (g ? idx.node(g) : undefined) ?? idx.resolveAssetRef(alias);
62
+ if (!variable || str(variable.node, 'type') !== 'VARIABLE')
63
+ return undefined;
64
+ const set = variableSetOf(idx, variable);
65
+ const key = set ? (str(set.node, 'key') ?? set.key) : collectionKey(idx, obj(variable.node, 'variableSetID'));
66
+ const picked = key === undefined ? undefined : modes.get(key);
67
+ const mode = picked ?? (set ? defaultMode(set) : undefined);
68
+ const entries = objArr(obj(variable.node, 'variableDataValues'), 'entries');
69
+ let entry = mode === undefined ? undefined : entries.find((e) => guidKey(obj(e, 'modeID')) === mode);
70
+ // A collection that is not in the file has an unknown default; a single value needs none.
71
+ if (!entry && picked === undefined && !set && entries.length === 1)
72
+ entry = entries[0];
73
+ if (!entry)
74
+ return undefined;
75
+ const value = obj(obj(entry, 'variableData'), 'value');
76
+ const next = obj(value, 'alias');
77
+ return next ? variableValueIn(idx, next, modes, depth + 1) : value;
78
+ }
4
79
  /** A concrete (non-alias) `VariableAnyValue` rendered compactly; aliases return undefined. */
5
80
  function concreteValue(value) {
6
81
  if (!value)
@@ -13,6 +13,7 @@ import type { CacheEntry } from '../cache.js';
13
13
  import type { NodeChange } from '../fig/parse.js';
14
14
  import { type TreeNode } from '../model/tree.js';
15
15
  import { type OverrideRecords, type PropAssignments } from './instance.js';
16
+ import { type ModeMap } from '../model/variables.js';
16
17
  import { type Box } from './matrix.js';
17
18
  import { ReportBuilder } from './report.js';
18
19
  export declare const DEFAULT_MAX_NODES = 20000;
@@ -53,6 +54,10 @@ export interface ExportContext {
53
54
  readonly scope: string;
54
55
  /** Symbols already being expanded around the root, for the recursion guard. */
55
56
  readonly active: Iterable<string>;
57
+ /** The component that instance expands, whose root the instance stands in for. */
58
+ readonly symbol: TreeNode;
59
+ /** The variable modes in force at that instance (F28). */
60
+ readonly modes: ModeMap;
56
61
  }
57
62
  export interface ExportOptions {
58
63
  readonly maxNodes?: number;
@@ -1,7 +1,9 @@
1
1
  import { overrideIdentity } from '../model/tree.js';
2
2
  import { bool, bytes, num, obj, objArr, str } from '../model/access.js';
3
3
  import { BoundsCache, effectMargins } from './bounds.js';
4
- import { applyProps, descend, instanceShapeNode, mergeNode, resolveInstance, } from './instance.js';
4
+ import { descend, instanceShapeNode, mergeNode, resolveInstance, showLayer, } from './instance.js';
5
+ import { applyBindings, applyColours, boundPaints } from '../model/bindings.js';
6
+ import { NO_MODES, withModes } from '../model/variables.js';
5
7
  import { applyStyles, runPaints } from './style.js';
6
8
  import { expandBox, fromFigma, isIdentity, transformBox, unionBox } from './matrix.js';
7
9
  import { classify, clipsChildren, hasFillGeometry, isBooleanOperation, isInstance, isMask, isVisible, nodeOpacity, nodeSize, nodeType, strokeAlign, } from './node.js';
@@ -76,6 +78,14 @@ class Exporter {
76
78
  activeSymbols = new Set();
77
79
  /** Distinguishes ids for the same symbol node drawn under different instances. */
78
80
  defScope = '';
81
+ /** The component the innermost enclosing INSTANCE expands. */
82
+ levelSymbol;
83
+ /** Variable modes in force at the innermost enclosing INSTANCE (F28). */
84
+ levelModes = NO_MODES;
85
+ /** Modes in force at a layer, per instance scope and layer (F28). */
86
+ modeMemo = new Map();
87
+ /** Layers already reported for a binding they could not resolve, per scope. */
88
+ unresolvedBindings = new Set();
79
89
  constructor(entry, root, opts) {
80
90
  this.entry = entry;
81
91
  this.root = root;
@@ -91,6 +101,8 @@ class Exporter {
91
101
  this.frame = opts.context.records;
92
102
  this.props = opts.context.props;
93
103
  this.defScope = opts.context.scope;
104
+ this.levelSymbol = opts.context.symbol;
105
+ this.levelModes = opts.context.modes;
94
106
  for (const symbol of opts.context.active)
95
107
  this.activeSymbols.add(symbol);
96
108
  }
@@ -116,23 +128,83 @@ class Exporter {
116
128
  }
117
129
  /**
118
130
  * The node as this instance sees it: the tree node merged with the active overrides and with
119
- * the enclosing instance's property assignments applied (F17, F18), then with every colour or
120
- * effect style it references resolved to that style's live value (F19).
131
+ * the enclosing instance's property assignments applied (F17, F18) — a nested instance whose
132
+ * component that swaps losing the old component's appearance (F27) — then with every colour or
133
+ * effect style it references resolved to that style's live value (F19), and, inside an
134
+ * instance, its visibility and colours bound to variables read in the modes in force (F28,
135
+ * F29).
121
136
  */
122
137
  effective(t) {
123
138
  let node = t.node;
139
+ let staleOutlines = false;
124
140
  if (this.frame) {
125
- const record = this.frame.get(overrideIdentity(t));
126
- node = mergeNode(node, record);
127
- const applied = applyProps(node, this.props, record?.['derivedTextData'] !== undefined);
128
- if (applied.node !== node) {
141
+ const shown = showLayer(this.entry.index, t, this.frame, this.props);
142
+ if (shown.propsApplied)
129
143
  this.report.seen('instance-property');
130
- node = applied.node;
131
- if (applied.staleOutlines)
132
- this.staleOutlines.add(node);
144
+ node = shown.node;
145
+ staleOutlines = shown.staleOutlines;
146
+ }
147
+ let live = applyStyles(this.entry.index, node);
148
+ // A stored layer's values were resolved where it stands; a component's layer drawn inside an
149
+ // instance carries the component's, so its bindings are read again here.
150
+ if (this.frame)
151
+ live = this.bindVariables(t, live);
152
+ // Marked on the node `emitText` is handed: each step above may return a new record.
153
+ if (staleOutlines)
154
+ this.staleOutlines.add(live);
155
+ return live;
156
+ }
157
+ /** F28, F29 — the layer's visibility and colours, read in the variable modes in force at it. */
158
+ bindVariables(t, node) {
159
+ const modes = this.modesAt(t, node);
160
+ const bound = applyBindings(this.entry.index, node, modes);
161
+ this.noteBindings(t, bound, modes);
162
+ return bound.node;
163
+ }
164
+ noteBindings(t, bound, modes) {
165
+ if (bound.applied > 0)
166
+ this.report.seen('variable-binding');
167
+ // Only a mode picked somewhere can make the cached value the wrong one.
168
+ if (bound.unresolved > 0 && modes.size > 0) {
169
+ const key = `${this.defScope}${t.key}`;
170
+ if (!this.unresolvedBindings.has(key)) {
171
+ this.unresolvedBindings.add(key);
172
+ this.report.approximated('variable-unresolved', t.key);
133
173
  }
134
174
  }
135
- return applyStyles(this.entry.index, node);
175
+ }
176
+ /**
177
+ * Inside an instance, the paints a text run or vector region picks at draw time — a style an
178
+ * entry names — read in the modes in force at the layer (F29); outside one, as stored.
179
+ */
180
+ runBinder(t, node) {
181
+ if (!this.frame)
182
+ return undefined;
183
+ const modes = this.modesAt(t, node);
184
+ return (paints) => boundPaints(this.entry.index, paints, modes);
185
+ }
186
+ /** The variable modes in force at `t`, shown as `node`: its own picks over those above it. */
187
+ modesAt(t, node) {
188
+ return withModes(this.entry.index, this.modesAbove(t), node);
189
+ }
190
+ /**
191
+ * The modes in force at `t`'s parent. Inside an instance that is the instance's own modes
192
+ * with the picks of the component's layers between its root and `t`, each as this instance
193
+ * shows it; the component root's own picks do not count, since the instance stands in for
194
+ * the root. Outside an instance it is the picks of the stored layers above `t`.
195
+ */
196
+ modesAbove(t) {
197
+ const parent = t.parent;
198
+ if (!parent || parent === this.levelSymbol)
199
+ return this.frame ? this.levelModes : NO_MODES;
200
+ const key = `${this.defScope}${parent.key}`;
201
+ let modes = this.modeMemo.get(key);
202
+ if (!modes) {
203
+ const shown = this.frame ? mergeNode(parent.node, this.frame.get(overrideIdentity(parent))) : parent.node;
204
+ modes = withModes(this.entry.index, this.modesAbove(parent), shown);
205
+ this.modeMemo.set(key, modes);
206
+ }
207
+ return modes;
136
208
  }
137
209
  /** Def keys must not collide between two instances of the same symbol with different fills. */
138
210
  defKey(kind, t) {
@@ -342,17 +414,28 @@ class Exporter {
342
414
  this.report.unsupported('instance-recursive', t.key);
343
415
  return;
344
416
  }
417
+ // The modes in force at the instance, read in its own context before entering it (F28).
418
+ const modes = this.modesAt(t, node);
419
+ const nested = this.frame !== undefined;
345
420
  const savedFrame = this.frame;
346
421
  const savedProps = this.props;
347
422
  const savedScope = this.defScope;
423
+ const savedSymbol = this.levelSymbol;
424
+ const savedModes = this.levelModes;
348
425
  this.frame = resolved.records;
349
426
  this.props = resolved.props;
350
427
  this.defScope = `${this.defScope}${t.key}~`;
428
+ this.levelSymbol = resolved.symbol;
429
+ this.levelModes = modes;
351
430
  this.activeSymbols.add(resolved.symbol.key);
352
431
  try {
353
432
  // The instance's own box: the symbol root with its override applied, overlaid by whatever
354
433
  // the instance itself (as seen in its context) already carries resolved.
355
- const shape = applyStyles(this.entry.index, instanceShapeNode(node, resolved.symbol, resolved.records));
434
+ let shape = applyStyles(this.entry.index, instanceShapeNode(node, resolved.symbol, resolved.records));
435
+ // A nested instance's own colours were read in its context by `effective`, but a style
436
+ // resolved again just above hands back the style's paints as stored (F29).
437
+ if (nested)
438
+ shape = applyColours(this.entry.index, shape, modes).node;
356
439
  this.emitOwnContent(t, shape, 'container', resolved.symbol.children);
357
440
  }
358
441
  finally {
@@ -360,6 +443,8 @@ class Exporter {
360
443
  this.frame = savedFrame;
361
444
  this.props = savedProps;
362
445
  this.defScope = savedScope;
446
+ this.levelSymbol = savedSymbol;
447
+ this.levelModes = savedModes;
363
448
  }
364
449
  }
365
450
  /** One `<path>` per (geometry, visible paint) pair. */
@@ -371,6 +456,7 @@ class Exporter {
371
456
  }
372
457
  const box = Exporter.box(node);
373
458
  const paintField = field === 'fillGeometry' ? 'fillPaints' : 'strokePaints';
459
+ const bind = this.runBinder(t, node);
374
460
  for (const path of geometry) {
375
461
  const raw = this.blob(num(path, 'commandsBlob'));
376
462
  if (!raw || raw.length === 0)
@@ -388,7 +474,7 @@ class Exporter {
388
474
  }
389
475
  // SVG's default fill-rule is nonzero, so it is only written when the winding is ODD.
390
476
  const rule = str(path, 'windingRule') === 'ODD' ? 'evenodd' : undefined;
391
- const styled = runPaints(this.entry.index, node, num(path, 'styleID'), paintField);
477
+ const styled = runPaints(this.entry.index, node, num(path, 'styleID'), paintField, bind);
392
478
  for (const paint of styled ?? paints) {
393
479
  const attrs = paintAttrs(paint, box, this.env, t.key);
394
480
  if (!attrs)
@@ -547,7 +633,8 @@ class Exporter {
547
633
  }
548
634
  const box = Exporter.box(node);
549
635
  const own = objArr(node, 'fillPaints');
550
- const paintsFor = (styleID) => runPaints(this.entry.index, node, styleID, 'fillPaints') ?? own;
636
+ const bind = this.runBinder(t, node);
637
+ const paintsFor = (styleID) => runPaints(this.entry.index, node, styleID, 'fillPaints', bind) ?? own;
551
638
  for (const run of draw.glyphs) {
552
639
  for (const paint of paintsFor(run.styleID)) {
553
640
  const attrs = paintAttrs(paint, box, this.env, t.key);
@@ -24,6 +24,8 @@ function resolveRoot(entry, guid) {
24
24
  props: level.instance.props,
25
25
  scope: `${[level.root, ...level.path].join('~')}~`,
26
26
  active: level.active,
27
+ symbol: level.instance.symbol,
28
+ modes: level.modes,
27
29
  },
28
30
  };
29
31
  }
@@ -1,7 +1,7 @@
1
1
  import type { NodeChange } from '../fig/parse.js';
2
2
  import { type TreeNode } from '../model/tree.js';
3
3
  import { type OverrideRecords } from '../model/instance.js';
4
- export { applyProps, descend, mergeNode, resolveInstance, type AppliedProps, type OverrideRecords, type PropAssignments, type ResolvedInstance, } from '../model/instance.js';
4
+ export { applyProps, descend, mergeNode, resolveInstance, showLayer, swapAppearance, type AppliedProps, type OverrideRecords, type PropAssignments, type ResolvedInstance, type ShownLayer, } from '../model/instance.js';
5
5
  /**
6
6
  * How the instance's own box should be drawn: the symbol root with its override applied, then
7
7
  * any of the shape fields the instance itself carries (13 835 instances have their own
@@ -1,7 +1,7 @@
1
1
  import { num, obj } from '../model/access.js';
2
2
  import { overrideIdentity } from '../model/tree.js';
3
3
  import { mergeNode } from '../model/instance.js';
4
- export { applyProps, descend, mergeNode, resolveInstance, } from '../model/instance.js';
4
+ export { applyProps, descend, mergeNode, resolveInstance, showLayer, swapAppearance, } from '../model/instance.js';
5
5
  /**
6
6
  * Fields that describe how a node paints ITSELF. When an instance carries one of these it has
7
7
  * already been resolved for this instance; otherwise the symbol root's (overridden) value wins.
@@ -38,7 +38,7 @@ export interface RenderReport {
38
38
  * Appendix D. Parameterised keys are formed with the helpers below so a typo cannot silently
39
39
  * create a new feature that the coverage matrix will never recognise.
40
40
  */
41
- export declare const FEATURES: readonly ['image-missing', 'image-crop', 'image-rotation', 'image-filters', 'gradient-singular', 'emoji', 'glyph-rotation', 'text-without-outlines', 'text-property-without-outlines', 'text-stroke', 'text-decoration', 'text-truncation', 'stroke-dashed', 'stroke-without-geometry', 'vector-without-geometry', 'geometry:corrupt', 'geometry:synthesised', 'mask-hidden', 'oversize', 'svg-rejected', 'instance-unresolved', 'instance-recursive', 'instance-property', 'instance-swap', 'node-failed'];
41
+ export declare const FEATURES: readonly ['image-missing', 'image-crop', 'image-rotation', 'image-filters', 'gradient-singular', 'emoji', 'glyph-rotation', 'text-without-outlines', 'text-property-without-outlines', 'text-stroke', 'text-decoration', 'text-truncation', 'stroke-dashed', 'stroke-without-geometry', 'vector-without-geometry', 'geometry:corrupt', 'geometry:synthesised', 'mask-hidden', 'oversize', 'svg-rejected', 'instance-unresolved', 'instance-recursive', 'instance-property', 'instance-swap', 'variable-binding', 'variable-unresolved', 'node-failed'];
42
42
  /** Prefixes of the parameterised keys built by `feat` below. */
43
43
  export declare const FEATURE_PREFIXES: readonly ['node-type:', 'paint:', 'effect:', 'blend:', 'mask:', 'stroke-align:', 'image-mode:', 'image-format:'];
44
44
  /** True when `feature` is part of the frozen vocabulary; used to guard against typos. */
@@ -27,6 +27,8 @@ export const FEATURES = [
27
27
  'instance-recursive',
28
28
  'instance-property',
29
29
  'instance-swap',
30
+ 'variable-binding',
31
+ 'variable-unresolved',
30
32
  'node-failed',
31
33
  ];
32
34
  /** Prefixes of the parameterised keys built by `feat` below. */
@@ -20,6 +20,7 @@ export { applyStyles, styleEffects, stylePaints } from '../model/styles.js';
20
20
  * `styleOverrideTable`, which carries only the fields that differ from the node's own. An entry
21
21
  * may name a colour style instead of carrying paints, so the style is followed first. Returns
22
22
  * undefined when nothing overrides the field, and the caller falls back to the node's paints.
23
+ * `bind`, when given, reads the colours the chosen paints bind to variables (F29).
23
24
  */
24
- export declare function runPaints(index: FileIndex, node: NodeChange, styleID: number | undefined, field: 'fillPaints' | 'strokePaints'): KiwiObject[] | undefined;
25
+ export declare function runPaints(index: FileIndex, node: NodeChange, styleID: number | undefined, field: 'fillPaints' | 'strokePaints', bind?: (paints: KiwiObject[]) => KiwiObject[]): KiwiObject[] | undefined;
25
26
  //# sourceMappingURL=style.d.ts.map
@@ -6,8 +6,9 @@ export { applyStyles, styleEffects, stylePaints } from '../model/styles.js';
6
6
  * `styleOverrideTable`, which carries only the fields that differ from the node's own. An entry
7
7
  * may name a colour style instead of carrying paints, so the style is followed first. Returns
8
8
  * undefined when nothing overrides the field, and the caller falls back to the node's paints.
9
+ * `bind`, when given, reads the colours the chosen paints bind to variables (F29).
9
10
  */
10
- export function runPaints(index, node, styleID, field) {
11
+ export function runPaints(index, node, styleID, field, bind = (paints) => paints) {
11
12
  if (!styleID)
12
13
  return undefined;
13
14
  const styleField = field === 'fillPaints' ? 'styleIdForFill' : 'styleIdForStrokeFill';
@@ -21,9 +22,9 @@ export function runPaints(index, node, styleID, field) {
21
22
  continue;
22
23
  const styled = stylePaints(index, override[styleField]);
23
24
  if (styled)
24
- return styled;
25
+ return bind(styled);
25
26
  if (Array.isArray(override[field]))
26
- return objArr(override, field);
27
+ return bind(objArr(override, field));
27
28
  }
28
29
  }
29
30
  return undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "figme-mcp",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "mcpName": "io.github.ntson9p/figme-mcp",
5
5
  "private": false,
6
6
  "description": "MCP server that reads local Figma .fig files, fully offline",