figme-mcp 1.1.2 → 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.
Files changed (42) hide show
  1. package/README.md +226 -223
  2. package/dist/mcp/create.js +3 -0
  3. package/dist/mcp/tools/context.d.ts +10 -0
  4. package/dist/mcp/tools/context.js +27 -0
  5. package/dist/mcp/tools/find.js +36 -6
  6. package/dist/mcp/tools/image.js +3 -2
  7. package/dist/mcp/tools/instance.js +6 -3
  8. package/dist/mcp/tools/node.js +8 -4
  9. package/dist/mcp/tools/render.js +2 -1
  10. package/dist/mcp/tools/style.js +5 -3
  11. package/dist/mcp/tools/text.js +29 -6
  12. package/dist/mcp/tools/tree.js +25 -11
  13. package/dist/model/bindings.d.ts +48 -0
  14. package/dist/model/bindings.js +129 -0
  15. package/dist/model/components.d.ts +8 -1
  16. package/dist/model/components.js +75 -30
  17. package/dist/model/index.d.ts +7 -0
  18. package/dist/model/index.js +19 -0
  19. package/dist/model/instance.d.ts +51 -4
  20. package/dist/model/instance.js +181 -5
  21. package/dist/model/scene.d.ts +50 -0
  22. package/dist/model/scene.js +192 -0
  23. package/dist/model/styles.d.ts +56 -0
  24. package/dist/model/styles.js +90 -0
  25. package/dist/model/summarize.d.ts +52 -5
  26. package/dist/model/summarize.js +255 -46
  27. package/dist/model/text.d.ts +5 -1
  28. package/dist/model/text.js +14 -4
  29. package/dist/model/tree.d.ts +12 -3
  30. package/dist/model/tree.js +24 -7
  31. package/dist/model/variables.d.ts +29 -1
  32. package/dist/model/variables.js +76 -1
  33. package/dist/render/export.d.ts +25 -0
  34. package/dist/render/export.js +118 -20
  35. package/dist/render/index.js +27 -4
  36. package/dist/render/instance.d.ts +1 -1
  37. package/dist/render/instance.js +1 -1
  38. package/dist/render/report.d.ts +1 -1
  39. package/dist/render/report.js +2 -0
  40. package/dist/render/style.d.ts +10 -15
  41. package/dist/render/style.js +7 -43
  42. package/package.json +3 -3
@@ -1,7 +1,8 @@
1
1
  import { z } from 'zod';
2
- import { fileArg, handler, load, requireNode } from './context.js';
2
+ import { fileArg, handler, load, requireScene } from './context.js';
3
3
  import { jsonResult } from '../respond.js';
4
4
  import { instanceView } from '../../model/components.js';
5
+ import { inheritedOverrides } from '../../model/scene.js';
5
6
  import { str } from '../../model/access.js';
6
7
  export const NAME = 'fig_instance';
7
8
  export const DESCRIPTION = [
@@ -9,6 +10,8 @@ export const DESCRIPTION = [
9
10
  'assignments with the property names resolved, and every override it applies — each with the',
10
11
  'path down into the component, the node that path addresses, and the fields it changes.',
11
12
  'Use it to see how an instance differs from its component without diffing two subtrees.',
13
+ 'An instance nested inside another (an id like "I2:1329;0:2528") also lists, as inherited,',
14
+ 'the overrides the enclosing instance applies inside it.',
12
15
  ].join(' ');
13
16
  const MAX_OVERRIDES = 60;
14
17
  export function register(server, ctx) {
@@ -22,13 +25,13 @@ export function register(server, ctx) {
22
25
  annotations: { readOnlyHint: true, openWorldHint: false },
23
26
  }, handler((args) => {
24
27
  const { index } = load(ctx, args.file);
25
- const t = requireNode(index, args.guid);
28
+ const t = requireScene(index, args.guid);
26
29
  const type = str(t.node, 'type');
27
30
  if (type !== 'INSTANCE') {
28
31
  throw new Error(`node ${args.guid} is a ${type}, not an INSTANCE — ` +
29
32
  'use fig_node for other node types, or fig_components to list SYMBOLs');
30
33
  }
31
- const { overrides = [], ...instance } = instanceView(index, t);
34
+ const { overrides = [], ...instance } = instanceView(index, t, inheritedOverrides(t));
32
35
  const truncated = overrides.length > MAX_OVERRIDES;
33
36
  return jsonResult({
34
37
  instance,
@@ -1,10 +1,11 @@
1
1
  import { z } from 'zod';
2
- import { fileArg, handler, load, requireNode } from './context.js';
2
+ import { fileArg, handler, load, requireScene } from './context.js';
3
3
  import { jsonResult } from '../respond.js';
4
4
  import { nodeDetail, nodeRaw, summarize } from '../../model/summarize.js';
5
5
  export const NAME = 'fig_node';
6
6
  export const DESCRIPTION = [
7
- 'Inspect one node by guid (e.g. "2:1339").',
7
+ 'Inspect one node by guid (e.g. "2:1339"), or a layer inside a component instance by the id',
8
+ 'fig_tree lists for it (e.g. "I2:1329;0:2528").',
8
9
  'detail:"full" (default) gives geometry, fills/strokes/effects as hex colours, corner radii,',
9
10
  'auto-layout, text basics, component and variable links, plus child summaries.',
10
11
  'detail:"raw" returns the decoded Figma record verbatim — the escape hatch for fields this',
@@ -26,7 +27,7 @@ export function register(server, ctx) {
26
27
  annotations: { readOnlyHint: true, openWorldHint: false },
27
28
  }, handler((args) => {
28
29
  const { index } = load(ctx, args.file);
29
- const t = requireNode(index, args.guid);
30
+ const t = requireScene(index, args.guid);
30
31
  const detail = args.detail ?? 'full';
31
32
  const includeChildren = args.includeChildren !== false;
32
33
  if (detail === 'summary') {
@@ -38,7 +39,10 @@ export function register(server, ctx) {
38
39
  detail,
39
40
  node: nodeRaw(t),
40
41
  children: includeChildren ? t.children.map((c) => summarize(c)) : undefined,
41
- note: 'raw = the decoded NodeChange as stored in the file; bytes are hex, int64 are strings',
42
+ note: t.virtual
43
+ ? `raw = the record of component layer ${t.source.key} as this instance shows it, ` +
44
+ 'with the override records and property values merged in; bytes are hex, int64 are strings'
45
+ : 'raw = the decoded NodeChange as stored in the file; bytes are hex, int64 are strings',
42
46
  });
43
47
  }
44
48
  return jsonResult({
@@ -13,7 +13,8 @@ export const DESCRIPTION = [
13
13
  'from the file. Rendering is best-effort: read `approximated` and `unsupported` in the report',
14
14
  'before trusting fine details; exact values remain available from fig_node / fig_style /',
15
15
  'fig_text. Default output is PNG at 2x, capped to 1568 px on the longest edge; use `savePath`',
16
- 'to write a file instead of inlining it.',
16
+ 'to write a file instead of inlining it. A layer inside a component instance (an id like',
17
+ '"I2:1329;0:2528" from fig_tree) is drawn as that instance shows it.',
17
18
  ].join(' ');
18
19
  /** Above this, base64 inlining costs the caller more than it is worth. */
19
20
  const MAX_INLINE_PNG = 2 * 1024 * 1024;
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { fileArg, handler, load, requireNode } from './context.js';
2
+ import { fileArg, handler, load, requireScene } from './context.js';
3
3
  import { jsonResult } from '../respond.js';
4
4
  import { styleBlock } from '../../model/summarize.js';
5
5
  import { textView } from '../../model/text.js';
@@ -10,7 +10,9 @@ export const DESCRIPTION = [
10
10
  'corner radii, typography, and auto-layout translated into CSS flexbox terms',
11
11
  '(display, direction, gap, padding, justifyContent, alignItems, sizing) plus how the node',
12
12
  'behaves inside its parent layout (flexGrow, alignSelf, margin).',
13
- 'Shared styles and variable bindings are named whenever they resolve inside this file.',
13
+ 'Shared styles and variable bindings are named whenever they resolve inside this file, and a',
14
+ 'value that comes from a shared style is that style\'s live value. A layer inside a component',
15
+ 'instance (an id like "I2:1329;0:2528" from fig_tree) is styled as that instance shows it.',
14
16
  ].join(' ');
15
17
  export function register(server, ctx) {
16
18
  server.registerTool(NAME, {
@@ -27,7 +29,7 @@ export function register(server, ctx) {
27
29
  annotations: { readOnlyHint: true, openWorldHint: false },
28
30
  }, handler((args) => {
29
31
  const { index } = load(ctx, args.file);
30
- const t = requireNode(index, args.guid);
32
+ const t = requireScene(index, args.guid);
31
33
  const style = styleBlock(index, t);
32
34
  const text = str(t.node, 'type') === 'TEXT' ? textView(index, t, args.includeRuns === true) : undefined;
33
35
  return jsonResult({
@@ -1,17 +1,37 @@
1
1
  import { z } from 'zod';
2
- import { cursorArg, fileArg, handler, load, requireNode } from './context.js';
2
+ import { cursorArg, fileArg, handler, instancesArg, load, resolveSceneRoot, } from './context.js';
3
3
  import { Packer, decodeCursor, encodeCursor, jsonResult, measure } from '../respond.js';
4
4
  import { compactStyle, textView } from '../../model/text.js';
5
5
  import { breadcrumb } from '../../model/tree.js';
6
+ import { isHidden } from '../../model/scene.js';
6
7
  import { str } from '../../model/access.js';
7
8
  export const NAME = 'fig_text';
8
9
  export const DESCRIPTION = [
9
10
  'Extract every string of copy in the file (or in one subtree via `scope`), in document order:',
10
11
  'guid, layer name, the characters, the page, and the base typography (font, size, line-height,',
11
12
  'colour). With includeRuns:true each node also carries its styled runs — the mixed-format',
12
- 'spans Figma stores per UTF-16 code unit — with only the fields each run overrides.',
13
+ 'spans Figma stores per UTF-16 code unit — with only the fields each run overrides. With a',
14
+ '`scope`, the text inside component instances is included as those instances show it.',
13
15
  'Use this for copy audits and translation passes rather than walking the tree.',
14
16
  ].join(' ');
17
+ /** Every node under `root`, depth-first and pre-order; instances are opened only when asked. */
18
+ function* walk(root, expand) {
19
+ const stack = [root];
20
+ while (stack.length) {
21
+ const t = stack.pop();
22
+ yield t;
23
+ if (!expand && str(t.node, 'type') === 'INSTANCE')
24
+ continue;
25
+ const kids = t.children;
26
+ for (let i = kids.length - 1; i >= 0; i--)
27
+ stack.push(kids[i]);
28
+ }
29
+ }
30
+ /** The stored nodes in DFS order — the whole-file inventory, without walking any instance. */
31
+ function* stored(index) {
32
+ for (const t of index.tree.ordered)
33
+ yield t;
34
+ }
15
35
  export function register(server, ctx) {
16
36
  server.registerTool(NAME, {
17
37
  title: 'Text inventory',
@@ -31,13 +51,16 @@ export function register(server, ctx) {
31
51
  .boolean()
32
52
  .optional()
33
53
  .describe('Include the ancestor breadcrumb per node (default false; costs tokens).'),
54
+ instances: instancesArg('Default true with a `scope`; for the whole file the default lists the text layers ' +
55
+ 'stored in it (component definitions included) without walking every instance.'),
34
56
  cursor: cursorArg,
35
57
  },
36
58
  annotations: { readOnlyHint: true, openWorldHint: false },
37
59
  }, handler((args) => {
38
60
  const { index } = load(ctx, args.file);
39
- const scope = args.scope ? requireNode(index, args.scope) : undefined;
40
- const range = scope ? index.subtreeRange(scope) : { start: 0, end: index.nodeCount };
61
+ const expand = args.instances ?? args.scope !== undefined;
62
+ const scope = args.scope ? resolveSceneRoot(index, args.scope) : undefined;
63
+ const nodes = scope || expand ? walk(scope ?? resolveSceneRoot(index, undefined), expand) : stored(index);
41
64
  const includeRuns = args.includeRuns === true;
42
65
  const includeStyle = args.includeStyle !== false;
43
66
  const { after } = decodeCursor(args.cursor);
@@ -45,8 +68,7 @@ export function register(server, ctx) {
45
68
  let skipping = after !== undefined;
46
69
  let lastGuid;
47
70
  let totalTextNodes = 0;
48
- for (let i = range.start; i < range.end; i++) {
49
- const t = index.tree.ordered[i];
71
+ for (const t of nodes) {
50
72
  if (str(t.node, 'type') !== 'TEXT')
51
73
  continue;
52
74
  const view = textView(index, t, includeRuns);
@@ -66,6 +88,7 @@ export function register(server, ctx) {
66
88
  characters: view.characters,
67
89
  page: t.page ? str(t.page.node, 'name') : undefined,
68
90
  path: args.includePath === true ? breadcrumb(t) || undefined : undefined,
91
+ hidden: isHidden(t) || undefined,
69
92
  style: includeStyle ? compactStyle(view.baseStyle) : undefined,
70
93
  hasStyledRuns: view.hasStyledRuns || undefined,
71
94
  runs: includeRuns ? view.runs : undefined,
@@ -1,16 +1,20 @@
1
1
  import { z } from 'zod';
2
- import { cursorArg, fileArg, handler, load, resolveRoot } from './context.js';
2
+ import { cursorArg, fileArg, handler, instancesArg, load, resolveRoot, resolveSceneRoot, } from './context.js';
3
3
  import { Packer, decodeCursor, encodeCursor, jsonResult, measure, textResult } from '../respond.js';
4
4
  import { outlineLine, summarize } from '../../model/summarize.js';
5
+ import { canonicalGuid } from '../../model/tree.js';
6
+ import { isSublayerId } from '../../model/scene.js';
5
7
  import { str } from '../../model/access.js';
6
8
  export const NAME = 'fig_tree';
7
9
  export const DESCRIPTION = [
8
10
  'List the layers under a node, breadth-limited by depth (default 2, max 6).',
9
11
  'Returns a FLAT list in document order; each entry carries `depth` (relative to the requested',
10
12
  'root) and `parent`, so the hierarchy is reconstructable, and `children` (count) so you can',
11
- 'see where to deepen. format:"outline" returns indented text lines instead of JSON and is',
12
- 'roughly 4x denser for browsing. Large subtrees are truncated with truncated:true and a',
13
- 'nextCursor you can pass back to continue.',
13
+ 'see where to deepen. Component instances are walked into, so the layers an instance shows',
14
+ 'come back with their overrides applied and ids like "I2:1329;0:2528", which every tool',
15
+ 'accepts; hidden layers are flagged. format:"outline" returns indented text lines instead of',
16
+ 'JSON and is roughly 4x denser for browsing. Large subtrees are truncated with truncated:true',
17
+ 'and a nextCursor you can pass back to continue.',
14
18
  ].join(' ');
15
19
  const MAX_DEPTH = 6;
16
20
  export function register(server, ctx) {
@@ -35,26 +39,36 @@ export function register(server, ctx) {
35
39
  .optional()
36
40
  .describe('Only include these node types, e.g. ["FRAME","TEXT"]. Depth still applies.'),
37
41
  format: z.enum(['json', 'outline']).optional().describe('Default "json".'),
42
+ instances: instancesArg('Default true; false lists only the layers stored in the file.'),
38
43
  cursor: cursorArg,
39
44
  },
40
45
  annotations: { readOnlyHint: true, openWorldHint: false },
41
46
  }, handler((args) => {
42
47
  const { index } = load(ctx, args.file);
43
- const rootNode = resolveRoot(index, args.root);
48
+ const expand = args.instances !== false;
49
+ // Without expansion a stored root is walked exactly as stored; a layer inside an
50
+ // instance can only be reached through the scene, nested instances left closed.
51
+ const rootNode = expand || (args.root !== undefined && isSublayerId(canonicalGuid(args.root)))
52
+ ? resolveSceneRoot(index, args.root)
53
+ : resolveRoot(index, args.root);
54
+ const childrenOf = (t) => !expand && str(t.node, 'type') === 'INSTANCE' ? [] : t.children;
44
55
  const depth = args.depth ?? 2;
45
56
  const format = args.format ?? 'json';
46
57
  const typeFilter = args.types?.length ? new Set(args.types) : undefined;
47
58
  const { after } = decodeCursor(args.cursor);
48
- const { start, end } = index.subtreeRange(rootNode);
49
59
  const packer = new Packer();
50
60
  let skipping = after !== undefined;
51
61
  let lastGuid;
52
62
  let matched = 0;
53
- for (let i = start; i < end; i++) {
54
- const t = index.tree.ordered[i];
55
- const relDepth = t.depth - rootNode.depth;
56
- if (relDepth > depth)
57
- continue;
63
+ // Depth-first, pre-order, never below `depth`: the same order the stored tree has.
64
+ const stack = [[rootNode, 0]];
65
+ while (stack.length) {
66
+ const [t, relDepth] = stack.pop();
67
+ if (relDepth < depth) {
68
+ const kids = childrenOf(t);
69
+ for (let i = kids.length - 1; i >= 0; i--)
70
+ stack.push([kids[i], relDepth + 1]);
71
+ }
58
72
  if (typeFilter && !typeFilter.has(str(t.node, 'type') ?? ''))
59
73
  continue;
60
74
  if (skipping) {
@@ -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
+ }
@@ -9,6 +9,7 @@
9
9
  * definitions live on the component set (a FRAME with `isStateGroup`).
10
10
  */
11
11
  import type { NodeChange } from '../fig/parse.js';
12
+ import type { KiwiObject } from '../fig/kiwi.js';
12
13
  import type { FileIndex } from './index.js';
13
14
  import { type TreeNode } from './tree.js';
14
15
  export interface ComponentView {
@@ -39,6 +40,8 @@ export interface OverrideView {
39
40
  fields: Record<string, unknown>;
40
41
  /** Field names present in the record that this mapper did not translate. */
41
42
  otherFields?: string[];
43
+ /** Applied by an enclosing instance to this nested one, rather than by this instance. */
44
+ inherited?: boolean;
42
45
  }
43
46
  /** Map one partial NodeChange (an override or a derived record) to a compact field set. */
44
47
  export declare function overrideFields(idx: FileIndex, partial: NodeChange): {
@@ -68,5 +71,9 @@ export interface InstanceView {
68
71
  derivedRecords?: number;
69
72
  scaleFactor?: number;
70
73
  }
71
- export declare function instanceView(idx: FileIndex, t: TreeNode): InstanceView;
74
+ /**
75
+ * `inherited` are the records enclosing instances apply inside this one when it is itself a
76
+ * layer of an instance (model/scene.ts `inheritedOverrides`), already re-addressed from it.
77
+ */
78
+ export declare function instanceView(idx: FileIndex, t: TreeNode, inherited?: readonly KiwiObject[]): InstanceView;
72
79
  //# sourceMappingURL=components.d.ts.map
@@ -1,8 +1,9 @@
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
- import { effectView, paintView, textBasics } from './summarize.js';
4
+ import { cornerRadiusOf, effectView, paintBox, paintView, sideWeights, styleRefsOf, textBasics, } from './summarize.js';
5
5
  import { describeVariableData } from './variables.js';
6
+ import { applyStyles } from './styles.js';
6
7
  /** Fields present on every override/derived record that are addressing, not content. */
7
8
  const OVERRIDE_META = new Set(['guidPath', 'overrideLevel', 'guid', 'phase', 'parentIndex']);
8
9
  function componentPropValue(idx, value) {
@@ -28,6 +29,24 @@ function componentPropValue(idx, value) {
28
29
  const keys = Object.keys(value);
29
30
  return keys.length ? { [keys[0]]: jsonSafe(value[keys[0]]) } : undefined;
30
31
  }
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
+ */
37
+ function propAssignmentViews(idx, assignments) {
38
+ return assignments.map((a) => {
39
+ const defID = guidKey(obj(a, 'defID')) ?? '?';
40
+ const def = idx.propDefs().get(defID);
41
+ const value = componentPropValue(idx, assignmentValue(idx, a));
42
+ return compact({
43
+ defID,
44
+ name: def?.name,
45
+ type: def?.type,
46
+ value: value ?? describeVariableData(idx, obj(a, 'varValue')),
47
+ });
48
+ });
49
+ }
31
50
  export function componentView(idx, t) {
32
51
  const node = t.node;
33
52
  const size = obj(node, 'size');
@@ -41,7 +60,8 @@ export function componentView(idx, t) {
41
60
  return compact({
42
61
  name: str(d, 'name') ?? resolved?.name,
43
62
  type: str(d, 'type') ?? resolved?.type,
44
- 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'))),
45
65
  });
46
66
  })
47
67
  .filter((d) => d.name !== undefined);
@@ -63,40 +83,65 @@ export function componentView(idx, t) {
63
83
  }
64
84
  /** Map one partial NodeChange (an override or a derived record) to a compact field set. */
65
85
  export function overrideFields(idx, partial) {
86
+ // A record that names a style shows the style's live value, not the copy cached beside the
87
+ // reference — or the nothing there when the record carries only the reference (F19, F22).
88
+ const live = applyStyles(idx, partial, { text: true, partial: true });
66
89
  const size = obj(partial, 'size');
67
90
  const transform = obj(partial, 'transform');
68
- const fills = objArr(partial, 'fillPaints');
69
- const strokes = objArr(partial, 'strokePaints');
70
- const effects = objArr(partial, 'effects');
91
+ const fills = objArr(live, 'fillPaints');
92
+ const strokes = objArr(live, 'strokePaints');
93
+ const effects = objArr(live, 'effects');
71
94
  const w = num(size, 'x');
72
95
  const h = num(size, 'y');
96
+ const swap = guidKey(obj(partial, 'overriddenSymbolID'));
97
+ const assignments = objArr(partial, 'componentPropAssignments');
73
98
  const fields = compact({
99
+ name: str(partial, 'name'),
74
100
  size: w !== undefined && h !== undefined ? `${r2(w)}x${r2(h)}` : undefined,
75
101
  x: r2(num(transform, 'm02')),
76
102
  y: r2(num(transform, 'm12')),
77
103
  visible: bool(partial, 'visible'),
78
104
  opacity: r2(num(partial, 'opacity')),
79
105
  // An empty fills array is itself an override ("remove all fills"), so report the count.
80
- fills: 'fillPaints' in partial ? fills.map((p) => paintView(idx, p)) : undefined,
81
- fillsCleared: 'fillPaints' in partial && fills.length === 0 ? true : undefined,
82
- strokes: 'strokePaints' in partial ? strokes.map((p) => paintView(idx, p)) : undefined,
83
- strokesCleared: 'strokePaints' in partial && strokes.length === 0 ? true : undefined,
106
+ fills: 'fillPaints' in live ? fills.map((p) => paintView(idx, p, paintBox(partial))) : undefined,
107
+ fillsCleared: 'fillPaints' in live && fills.length === 0 ? true : undefined,
108
+ strokes: 'strokePaints' in live ? strokes.map((p) => paintView(idx, p, paintBox(partial))) : undefined,
109
+ strokesCleared: 'strokePaints' in live && strokes.length === 0 ? true : undefined,
110
+ // A record writes the stroke-side and corner groups whole, so they read like a node's.
111
+ strokeWeight: r2(num(partial, 'strokeWeight')),
112
+ strokeWeights: sideWeights(partial),
84
113
  effects: effects.length ? effects.map((e) => effectView(idx, e)) : undefined,
85
- text: textBasics(partial),
86
- cornerRadius: r2(num(partial, 'cornerRadius')),
114
+ text: textBasics(live),
115
+ cornerRadius: 'rectangleCornerRadiiIndependent' in partial
116
+ ? cornerRadiusOf(partial)
117
+ : r2(num(partial, 'cornerRadius')),
87
118
  symbolID: guidKey(obj(obj(partial, 'symbolData'), 'symbolID')),
119
+ // A nested instance swapped for another component, or given other property values.
120
+ swappedTo: swap ? compact({ guid: swap, name: str(idx.node(swap)?.node, 'name') }) : undefined,
121
+ propAssignments: assignments.length ? propAssignmentViews(idx, assignments) : undefined,
122
+ styles: styleRefsOf(idx, partial),
88
123
  });
89
124
  const known = new Set([
90
- 'size', 'transform', 'visible', 'opacity', 'fillPaints', 'strokePaints', 'effects',
91
- 'textData', 'fontName', 'fontSize', 'lineHeight', 'letterSpacing', 'cornerRadius',
92
- 'symbolData',
125
+ 'name', 'size', 'transform', 'visible', 'opacity', 'fillPaints', 'strokePaints', 'effects',
126
+ 'strokeWeight', 'borderStrokeWeightsIndependent', 'borderTopWeight', 'borderRightWeight',
127
+ 'borderBottomWeight', 'borderLeftWeight',
128
+ 'textData', 'fontName', 'fontSize', 'lineHeight', 'letterSpacing', 'paragraphSpacing',
129
+ 'textAlignHorizontal', 'textAlignVertical', 'textCase', 'textDecoration', 'textAutoResize',
130
+ 'cornerRadius', 'rectangleCornerRadiiIndependent', 'rectangleTopLeftCornerRadius',
131
+ 'rectangleTopRightCornerRadius', 'rectangleBottomRightCornerRadius',
132
+ 'rectangleBottomLeftCornerRadius',
133
+ 'symbolData', 'overriddenSymbolID', 'componentPropAssignments',
134
+ 'styleIdForFill', 'styleIdForStrokeFill', 'styleIdForText', 'styleIdForEffect',
135
+ 'styleIdForGrid',
93
136
  ]);
94
137
  const otherFields = Object.keys(partial).filter((k) => !known.has(k) && !OVERRIDE_META.has(k));
95
138
  return { fields, otherFields };
96
139
  }
97
140
  export function instanceOverrides(idx, t, field) {
98
141
  const symbolData = field === 'symbolOverrides' ? obj(t.node, 'symbolData') : t.node;
99
- const records = objArr(symbolData, field);
142
+ return overrideViews(idx, t, objArr(symbolData, field));
143
+ }
144
+ function overrideViews(idx, t, records, inherited = false) {
100
145
  return records.map((record) => {
101
146
  const path = objArr(obj(record, 'guidPath'), 'guids')
102
147
  .map((g) => guidKey(g))
@@ -114,25 +159,22 @@ export function instanceOverrides(idx, t, field) {
114
159
  targetType: target ? str(target.node, 'type') : undefined,
115
160
  fields,
116
161
  otherFields: otherFields.length ? otherFields : undefined,
162
+ inherited: inherited || undefined,
117
163
  });
118
164
  });
119
165
  }
120
- export function instanceView(idx, t) {
166
+ /**
167
+ * `inherited` are the records enclosing instances apply inside this one when it is itself a
168
+ * layer of an instance (model/scene.ts `inheritedOverrides`), already re-addressed from it.
169
+ */
170
+ export function instanceView(idx, t, inherited = []) {
121
171
  const symbolData = obj(t.node, 'symbolData');
122
- const symbolId = guidKey(obj(symbolData, 'symbolID'));
172
+ // A layer inside an instance may have had its symbol swapped by a record or a property.
173
+ const symbolId = guidKey(obj(t.node, 'overriddenSymbolID')) ??
174
+ guidKey(obj(symbolData, 'symbolID'));
123
175
  const symbol = symbolId ? idx.node(symbolId) : undefined;
124
176
  const symbolParent = symbol?.parent;
125
- const assignments = objArr(t.node, 'componentPropAssignments').map((a) => {
126
- const defID = guidKey(obj(a, 'defID')) ?? '?';
127
- const def = idx.propDefs().get(defID);
128
- const value = componentPropValue(idx, obj(a, 'value'));
129
- return compact({
130
- defID,
131
- name: def?.name,
132
- type: def?.type,
133
- value: value ?? describeVariableData(idx, obj(a, 'varValue')),
134
- });
135
- });
177
+ const assignments = propAssignmentViews(idx, objArr(t.node, 'componentPropAssignments'));
136
178
  return compact({
137
179
  guid: t.key,
138
180
  name: str(t.node, 'name'),
@@ -150,7 +192,10 @@ export function instanceView(idx, t) {
150
192
  })
151
193
  : undefined,
152
194
  propAssignments: assignments.length ? assignments : undefined,
153
- overrides: instanceOverrides(idx, t, 'symbolOverrides'),
195
+ overrides: [
196
+ ...instanceOverrides(idx, t, 'symbolOverrides'),
197
+ ...overrideViews(idx, t, inherited, true),
198
+ ],
154
199
  derivedRecords: objArr(t.node, 'derivedSymbolData').length || undefined,
155
200
  scaleFactor: num(symbolData, 'uniformScaleFactor') === 1 ? undefined : num(symbolData, 'uniformScaleFactor'),
156
201
  });