figme-mcp 1.1.1 → 1.2.0

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.
@@ -45,6 +45,9 @@ export const INSTRUCTIONS = [
45
45
  'Node guids are "sessionID:localID" strings such as "2:1339". A Figma link spells the same',
46
46
  'id with a dash - node-id=3017-121 is guid "3017:121" - and every guid argument also accepts',
47
47
  'that form, the percent-encoded form, or the whole link, so pass along whatever the user had.',
48
+ 'A layer inside a component instance has an id like "I2:1329;0:2528" - the instance, then the',
49
+ 'layer - exactly as Figma names it. fig_tree lists those layers with their overrides applied,',
50
+ 'and every tool accepts their ids; fig_text with a scope includes the text instances show.',
48
51
  '',
49
52
  'These tools read a .fig saved on disk and cannot open a figma.com URL. Given a link but no',
50
53
  'file path, ask the user for the path. Never fetch the link, and never infer the design from',
@@ -6,6 +6,7 @@ import { z } from 'zod';
6
6
  import type { FileCache, CacheEntry } from '../../cache.js';
7
7
  import type { FileIndex } from '../../model/index.js';
8
8
  import { type TreeNode } from '../../model/tree.js';
9
+ import { type SceneNode } from '../../model/scene.js';
9
10
  import { type CallToolResult } from '../respond.js';
10
11
  export interface ToolContext {
11
12
  readonly cache: FileCache;
@@ -16,6 +17,15 @@ export declare function load(ctx: ToolContext, file: string): CacheEntry;
16
17
  export declare function requireNode(index: FileIndex, guid: string): TreeNode;
17
18
  /** Resolve an optional scope argument to a subtree root, defaulting to the DOCUMENT. */
18
19
  export declare function resolveRoot(index: FileIndex, guid: string | undefined): TreeNode;
20
+ /**
21
+ * A stored node, or a layer inside a component instance (`I<instance>;<layer>…`), as Figma shows
22
+ * it: instances expand into their layers (model/scene.ts).
23
+ */
24
+ export declare function requireScene(index: FileIndex, guid: string): SceneNode;
25
+ /** `requireScene` for an optional scope argument, defaulting to the DOCUMENT. */
26
+ export declare function resolveSceneRoot(index: FileIndex, guid: string | undefined): SceneNode;
27
+ /** Shared description of the `instances` argument of the traversing tools. */
28
+ export declare const instancesArg: (fallback: string) => z.ZodOptional<z.ZodBoolean>;
19
29
  /**
20
30
  * Uniform handler wrapper: turns thrown errors into an MCP error result instead of crashing the
21
31
  * server, and keeps the message actionable (the thrown text is already user-facing).
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { z } from 'zod';
6
6
  import { canonicalGuid, guidNotFound } from '../../model/tree.js';
7
+ import { resolveScene, sceneOf } from '../../model/scene.js';
7
8
  import { errorResult } from '../respond.js';
8
9
  export const fileArg = z
9
10
  .string()
@@ -31,6 +32,32 @@ export function resolveRoot(index, guid) {
31
32
  throw new Error('this file has no DOCUMENT node');
32
33
  return root;
33
34
  }
35
+ /**
36
+ * A stored node, or a layer inside a component instance (`I<instance>;<layer>…`), as Figma shows
37
+ * it: instances expand into their layers (model/scene.ts).
38
+ */
39
+ export function requireScene(index, guid) {
40
+ const key = canonicalGuid(guid);
41
+ const s = resolveScene(index, key);
42
+ if (!s)
43
+ throw new Error(guidNotFound(guid, key));
44
+ return s;
45
+ }
46
+ /** `requireScene` for an optional scope argument, defaulting to the DOCUMENT. */
47
+ export function resolveSceneRoot(index, guid) {
48
+ if (guid)
49
+ return requireScene(index, guid);
50
+ const root = index.root;
51
+ if (!root)
52
+ throw new Error('this file has no DOCUMENT node');
53
+ return sceneOf(index, root);
54
+ }
55
+ /** Shared description of the `instances` argument of the traversing tools. */
56
+ export const instancesArg = (fallback) => z
57
+ .boolean()
58
+ .optional()
59
+ .describe('Walk into component instances and list the layers they show, with their overrides ' +
60
+ `applied (ids like "I2:1329;0:2528"). ${fallback}`);
34
61
  /**
35
62
  * Uniform handler wrapper: turns thrown errors into an MCP error result instead of crashing the
36
63
  * server, and keeps the message actionable (the thrown text is already user-facing).
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { cursorArg, fileArg, handler, load, requireNode } from './context.js';
2
+ import { cursorArg, fileArg, handler, instancesArg, load, requireNode, resolveSceneRoot, } from './context.js';
3
3
  import { Packer, decodeCursor, encodeCursor, jsonResult, measure } from '../respond.js';
4
4
  import { summarize } from '../../model/summarize.js';
5
5
  import { breadcrumb } from '../../model/tree.js';
@@ -10,9 +10,33 @@ export const DESCRIPTION = [
10
10
  'restricted to node types and/or a subtree. Each hit comes back with the page it lives on, a',
11
11
  'breadcrumb of ancestor names, and which field matched — so you can jump straight to a guid',
12
12
  'and then call fig_node / fig_style. Omit `query` to list every node of the given types.',
13
+ 'instances:true also searches the layers component instances show, with their overrides.',
13
14
  ].join(' ');
14
15
  const DEFAULT_LIMIT = 50;
15
16
  const TEXT_PREVIEW = 160;
17
+ /** The prebuilt search index over the stored nodes, restricted to a stored subtree. */
18
+ function* storedCandidates(index, scope) {
19
+ const range = scope ? index.subtreeRange(scope) : { start: 0, end: index.nodeCount };
20
+ const entries = index.search();
21
+ for (let i = range.start; i < range.end; i++)
22
+ yield entries[i];
23
+ }
24
+ /** Every layer under `root` as Figma shows it, instances opened, depth-first and pre-order. */
25
+ function* sceneCandidates(root) {
26
+ const stack = [root];
27
+ while (stack.length) {
28
+ const t = stack.pop();
29
+ const characters = str(obj(t.node, 'textData'), 'characters');
30
+ yield {
31
+ t,
32
+ nameLower: (str(t.node, 'name') ?? '').toLowerCase(),
33
+ textLower: characters?.toLowerCase(),
34
+ };
35
+ const kids = t.children;
36
+ for (let i = kids.length - 1; i >= 0; i--)
37
+ stack.push(kids[i]);
38
+ }
39
+ }
16
40
  export function register(server, ctx) {
17
41
  server.registerTool(NAME, {
18
42
  title: 'Search layers and text',
@@ -26,6 +50,7 @@ export function register(server, ctx) {
26
50
  types: z.array(z.string()).optional().describe('Restrict to node types, e.g. ["TEXT"].'),
27
51
  scope: z.string().optional().describe('Only search inside this guid subtree. A Figma node-id or link works too.'),
28
52
  limit: z.number().int().min(1).max(300).optional().describe(`Default ${DEFAULT_LIMIT}.`),
53
+ instances: instancesArg('Default false: the search covers the layers stored in the file. Best with a `scope`.'),
29
54
  cursor: cursorArg,
30
55
  },
31
56
  annotations: { readOnlyHint: true, openWorldHint: false },
@@ -36,16 +61,21 @@ export function register(server, ctx) {
36
61
  }
37
62
  const needle = args.query?.toLowerCase();
38
63
  const typeFilter = args.types?.length ? new Set(args.types) : undefined;
39
- const scope = args.scope ? requireNode(index, args.scope) : undefined;
40
- const range = scope ? index.subtreeRange(scope) : { start: 0, end: index.nodeCount };
64
+ const expand = args.instances === true;
65
+ const scope = args.scope
66
+ ? expand
67
+ ? resolveSceneRoot(index, args.scope)
68
+ : requireNode(index, args.scope)
69
+ : undefined;
70
+ const candidates = expand
71
+ ? sceneCandidates(scope ?? resolveSceneRoot(index, undefined))
72
+ : storedCandidates(index, scope);
41
73
  const { after } = decodeCursor(args.cursor);
42
74
  const packer = new Packer({ limit: args.limit ?? DEFAULT_LIMIT });
43
- const entries = index.search();
44
75
  let skipping = after !== undefined;
45
76
  let lastGuid;
46
77
  let totalMatches = 0;
47
- for (let i = range.start; i < range.end; i++) {
48
- const e = entries[i];
78
+ for (const e of candidates) {
49
79
  if (typeFilter && !typeFilter.has(str(e.t.node, 'type') ?? ''))
50
80
  continue;
51
81
  let matchedOn;
@@ -2,7 +2,7 @@
2
2
  import * as fs from 'node:fs';
3
3
  import * as path from 'node:path';
4
4
  import { z } from 'zod';
5
- import { fileArg, handler, load, requireNode } from './context.js';
5
+ import { fileArg, handler, load, requireScene } from './context.js';
6
6
  import { jsonResult } from '../respond.js';
7
7
  import { sniffImage } from '../../fig/imagemeta.js';
8
8
  import { nodeImageHashes } from '../../model/index.js';
@@ -44,7 +44,8 @@ export function register(server, ctx) {
44
44
  }
45
45
  let hash = args.hash;
46
46
  if (!hash && args.guid) {
47
- const t = requireNode(index, args.guid);
47
+ // A layer inside an instance carries the image paints its overrides gave it.
48
+ const t = requireScene(index, args.guid);
48
49
  const hashes = nodeImageHashes(t.node);
49
50
  if (hashes.length === 0) {
50
51
  throw new Error(`node ${args.guid} (${str(t.node, 'type') ?? '?'}) has no image fills — ` +
@@ -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) {
@@ -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
2
  import { 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,20 @@ 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
+ /** Component-property assignments with the property names resolved. */
33
+ function propAssignmentViews(idx, assignments) {
34
+ return assignments.map((a) => {
35
+ const defID = guidKey(obj(a, 'defID')) ?? '?';
36
+ const def = idx.propDefs().get(defID);
37
+ const value = componentPropValue(idx, obj(a, 'value'));
38
+ return compact({
39
+ defID,
40
+ name: def?.name,
41
+ type: def?.type,
42
+ value: value ?? describeVariableData(idx, obj(a, 'varValue')),
43
+ });
44
+ });
45
+ }
31
46
  export function componentView(idx, t) {
32
47
  const node = t.node;
33
48
  const size = obj(node, 'size');
@@ -63,40 +78,65 @@ export function componentView(idx, t) {
63
78
  }
64
79
  /** Map one partial NodeChange (an override or a derived record) to a compact field set. */
65
80
  export function overrideFields(idx, partial) {
81
+ // A record that names a style shows the style's live value, not the copy cached beside the
82
+ // reference — or the nothing there when the record carries only the reference (F19, F22).
83
+ const live = applyStyles(idx, partial, { text: true, partial: true });
66
84
  const size = obj(partial, 'size');
67
85
  const transform = obj(partial, 'transform');
68
- const fills = objArr(partial, 'fillPaints');
69
- const strokes = objArr(partial, 'strokePaints');
70
- const effects = objArr(partial, 'effects');
86
+ const fills = objArr(live, 'fillPaints');
87
+ const strokes = objArr(live, 'strokePaints');
88
+ const effects = objArr(live, 'effects');
71
89
  const w = num(size, 'x');
72
90
  const h = num(size, 'y');
91
+ const swap = guidKey(obj(partial, 'overriddenSymbolID'));
92
+ const assignments = objArr(partial, 'componentPropAssignments');
73
93
  const fields = compact({
94
+ name: str(partial, 'name'),
74
95
  size: w !== undefined && h !== undefined ? `${r2(w)}x${r2(h)}` : undefined,
75
96
  x: r2(num(transform, 'm02')),
76
97
  y: r2(num(transform, 'm12')),
77
98
  visible: bool(partial, 'visible'),
78
99
  opacity: r2(num(partial, 'opacity')),
79
100
  // 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,
101
+ fills: 'fillPaints' in live ? fills.map((p) => paintView(idx, p, paintBox(partial))) : undefined,
102
+ fillsCleared: 'fillPaints' in live && fills.length === 0 ? true : undefined,
103
+ strokes: 'strokePaints' in live ? strokes.map((p) => paintView(idx, p, paintBox(partial))) : undefined,
104
+ strokesCleared: 'strokePaints' in live && strokes.length === 0 ? true : undefined,
105
+ // A record writes the stroke-side and corner groups whole, so they read like a node's.
106
+ strokeWeight: r2(num(partial, 'strokeWeight')),
107
+ strokeWeights: sideWeights(partial),
84
108
  effects: effects.length ? effects.map((e) => effectView(idx, e)) : undefined,
85
- text: textBasics(partial),
86
- cornerRadius: r2(num(partial, 'cornerRadius')),
109
+ text: textBasics(live),
110
+ cornerRadius: 'rectangleCornerRadiiIndependent' in partial
111
+ ? cornerRadiusOf(partial)
112
+ : r2(num(partial, 'cornerRadius')),
87
113
  symbolID: guidKey(obj(obj(partial, 'symbolData'), 'symbolID')),
114
+ // A nested instance swapped for another component, or given other property values.
115
+ swappedTo: swap ? compact({ guid: swap, name: str(idx.node(swap)?.node, 'name') }) : undefined,
116
+ propAssignments: assignments.length ? propAssignmentViews(idx, assignments) : undefined,
117
+ styles: styleRefsOf(idx, partial),
88
118
  });
89
119
  const known = new Set([
90
- 'size', 'transform', 'visible', 'opacity', 'fillPaints', 'strokePaints', 'effects',
91
- 'textData', 'fontName', 'fontSize', 'lineHeight', 'letterSpacing', 'cornerRadius',
92
- 'symbolData',
120
+ 'name', 'size', 'transform', 'visible', 'opacity', 'fillPaints', 'strokePaints', 'effects',
121
+ 'strokeWeight', 'borderStrokeWeightsIndependent', 'borderTopWeight', 'borderRightWeight',
122
+ 'borderBottomWeight', 'borderLeftWeight',
123
+ 'textData', 'fontName', 'fontSize', 'lineHeight', 'letterSpacing', 'paragraphSpacing',
124
+ 'textAlignHorizontal', 'textAlignVertical', 'textCase', 'textDecoration', 'textAutoResize',
125
+ 'cornerRadius', 'rectangleCornerRadiiIndependent', 'rectangleTopLeftCornerRadius',
126
+ 'rectangleTopRightCornerRadius', 'rectangleBottomRightCornerRadius',
127
+ 'rectangleBottomLeftCornerRadius',
128
+ 'symbolData', 'overriddenSymbolID', 'componentPropAssignments',
129
+ 'styleIdForFill', 'styleIdForStrokeFill', 'styleIdForText', 'styleIdForEffect',
130
+ 'styleIdForGrid',
93
131
  ]);
94
132
  const otherFields = Object.keys(partial).filter((k) => !known.has(k) && !OVERRIDE_META.has(k));
95
133
  return { fields, otherFields };
96
134
  }
97
135
  export function instanceOverrides(idx, t, field) {
98
136
  const symbolData = field === 'symbolOverrides' ? obj(t.node, 'symbolData') : t.node;
99
- const records = objArr(symbolData, field);
137
+ return overrideViews(idx, t, objArr(symbolData, field));
138
+ }
139
+ function overrideViews(idx, t, records, inherited = false) {
100
140
  return records.map((record) => {
101
141
  const path = objArr(obj(record, 'guidPath'), 'guids')
102
142
  .map((g) => guidKey(g))
@@ -114,25 +154,22 @@ export function instanceOverrides(idx, t, field) {
114
154
  targetType: target ? str(target.node, 'type') : undefined,
115
155
  fields,
116
156
  otherFields: otherFields.length ? otherFields : undefined,
157
+ inherited: inherited || undefined,
117
158
  });
118
159
  });
119
160
  }
120
- export function instanceView(idx, t) {
161
+ /**
162
+ * `inherited` are the records enclosing instances apply inside this one when it is itself a
163
+ * layer of an instance (model/scene.ts `inheritedOverrides`), already re-addressed from it.
164
+ */
165
+ export function instanceView(idx, t, inherited = []) {
121
166
  const symbolData = obj(t.node, 'symbolData');
122
- const symbolId = guidKey(obj(symbolData, 'symbolID'));
167
+ // A layer inside an instance may have had its symbol swapped by a record or a property.
168
+ const symbolId = guidKey(obj(t.node, 'overriddenSymbolID')) ??
169
+ guidKey(obj(symbolData, 'symbolID'));
123
170
  const symbol = symbolId ? idx.node(symbolId) : undefined;
124
171
  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
- });
172
+ const assignments = propAssignmentViews(idx, objArr(t.node, 'componentPropAssignments'));
136
173
  return compact({
137
174
  guid: t.key,
138
175
  name: str(t.node, 'name'),
@@ -150,7 +187,10 @@ export function instanceView(idx, t) {
150
187
  })
151
188
  : undefined,
152
189
  propAssignments: assignments.length ? assignments : undefined,
153
- overrides: instanceOverrides(idx, t, 'symbolOverrides'),
190
+ overrides: [
191
+ ...instanceOverrides(idx, t, 'symbolOverrides'),
192
+ ...overrideViews(idx, t, inherited, true),
193
+ ],
154
194
  derivedRecords: objArr(t.node, 'derivedSymbolData').length || undefined,
155
195
  scaleFactor: num(symbolData, 'uniformScaleFactor') === 1 ? undefined : num(symbolData, 'uniformScaleFactor'),
156
196
  });