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
@@ -19,7 +19,11 @@ export interface TextView {
19
19
  /** True when `characterStyleIDs` is present and mentions any non-zero id. */
20
20
  hasStyledRuns: boolean;
21
21
  }
22
- /** The four fields a copy inventory actually needs, ~6x cheaper than the full typography. */
22
+ /**
23
+ * The four fields a copy inventory actually needs, ~6x cheaper than the full typography. Text
24
+ * painted with more than one fill, or with a gradient or image, has no single colour: its fills
25
+ * come back instead.
26
+ */
23
27
  export declare function compactStyle(style: Record<string, unknown> | undefined): Record<string, unknown> | undefined;
24
28
  /**
25
29
  * Group `characterStyleIDs` into maximal runs of equal id. Consecutive characters sharing an id
@@ -1,6 +1,10 @@
1
1
  import { compact, num, obj, objArr, str } from './access.js';
2
- import { typography } from './summarize.js';
3
- /** The four fields a copy inventory actually needs, ~6x cheaper than the full typography. */
2
+ import { shownStyle, typography } from './summarize.js';
3
+ /**
4
+ * The four fields a copy inventory actually needs, ~6x cheaper than the full typography. Text
5
+ * painted with more than one fill, or with a gradient or image, has no single colour: its fills
6
+ * come back instead.
7
+ */
4
8
  export function compactStyle(style) {
5
9
  if (!style)
6
10
  return undefined;
@@ -9,6 +13,7 @@ export function compactStyle(style) {
9
13
  size: style['fontSize'],
10
14
  lineHeight: style['lineHeight'],
11
15
  color: style['color'],
16
+ fills: style['color'] === undefined ? style['fills'] : undefined,
12
17
  });
13
18
  }
14
19
  /**
@@ -22,10 +27,13 @@ export function textView(idx, t, includeRuns) {
22
27
  return undefined;
23
28
  const ids = textData?.['characterStyleIDs'] ?? [];
24
29
  const hasStyledRuns = ids.some((id) => id !== 0);
30
+ // The typography Figma lays the text out with: a referenced style wins over the cached copy
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.
25
33
  const view = {
26
34
  characters,
27
35
  characterCount: characters.length,
28
- baseStyle: orUndefined(typography(idx, t.node)),
36
+ baseStyle: orUndefined(typography(idx, shownStyle(idx, t))),
29
37
  hasStyledRuns,
30
38
  };
31
39
  if (!includeRuns)
@@ -49,7 +57,9 @@ export function textView(idx, t, includeRuns) {
49
57
  end: i,
50
58
  text: characters.slice(start, i),
51
59
  styleID,
52
- style: override ? orUndefined(typography(idx, override)) : undefined,
60
+ style: override
61
+ ? orUndefined(typography(idx, shownStyle(idx, t, override, { text: true, partial: true })))
62
+ : undefined,
53
63
  }));
54
64
  start = i;
55
65
  }
@@ -18,8 +18,10 @@ export declare function guidKey(g: Guid | undefined): string | undefined;
18
18
  *
19
19
  * Figma writes node ids with a dash in links (`node-id=3017-121`), older links percent-encode
20
20
  * the colon, and people paste the whole link. A guid is always two integers, so `3017-121` can
21
- * never be a valid one itself and rewriting it is unambiguous. Anything unrecognised is handed
22
- * back untouched, so a genuine typo still fails loudly instead of being guessed at.
21
+ * never be a valid one itself and rewriting it is unambiguous. A layer inside a component
22
+ * instance has an id of the form `I<guid>;<guid>…` (model/scene.ts), which links write as
23
+ * `I3017-121%3B5-6`; it is canonicalised segment by segment. Anything unrecognised is handed back
24
+ * untouched, so a genuine typo still fails loudly instead of being guessed at.
23
25
  */
24
26
  export declare function canonicalGuid(input: string): string;
25
27
  /** One wording for a missing guid, shared by the MCP tools and the renderer. */
@@ -36,13 +38,20 @@ export interface TreeNode {
36
38
  /** Nearest CANVAS ancestor (the page a node lives on); undefined for DOCUMENT and pages. */
37
39
  page: TreeNode | undefined;
38
40
  }
41
+ /**
42
+ * The "no value" guid Figma writes into a guid field that is unset: a detached style reference
43
+ * (render-implementation-plan.md F19) and an `overrideKey` that names nothing.
44
+ */
45
+ export declare const NO_GUID = "4294967295:4294967295";
39
46
  /**
40
47
  * The identity that instance override paths (`symbolData.symbolOverrides[].guidPath.guids` and
41
48
  * `derivedSymbolData[].guidPath.guids`) use for a component descendant: its `overrideKey` when
42
49
  * it has one — a node created by copying a component keeps the original's — else its own guid.
43
50
  *
44
51
  * Measured on the sample: 8 893 of 10 480 symbol descendants carry an explicit key; the other
45
- * 1 587 are addressed by guid, by 30 061 of the file's 303 833 records.
52
+ * 1 587 are addressed by guid, by 30 061 of the file's 303 833 records. An `overrideKey` of
53
+ * `NO_GUID` is no key at all (F23): on the iOS 16 UI Kit 30 of the 44 keyed layers carry it, no
54
+ * record path ever names it, and 31 record path segments name those layers by their guid.
46
55
  */
47
56
  export declare function overrideIdentity(t: TreeNode): string;
48
57
  export interface Tree {
@@ -9,14 +9,22 @@ export function guidKey(g) {
9
9
  *
10
10
  * Figma writes node ids with a dash in links (`node-id=3017-121`), older links percent-encode
11
11
  * the colon, and people paste the whole link. A guid is always two integers, so `3017-121` can
12
- * never be a valid one itself and rewriting it is unambiguous. Anything unrecognised is handed
13
- * back untouched, so a genuine typo still fails loudly instead of being guessed at.
12
+ * never be a valid one itself and rewriting it is unambiguous. A layer inside a component
13
+ * instance has an id of the form `I<guid>;<guid>…` (model/scene.ts), which links write as
14
+ * `I3017-121%3B5-6`; it is canonicalised segment by segment. Anything unrecognised is handed back
15
+ * untouched, so a genuine typo still fails loudly instead of being guessed at.
14
16
  */
15
17
  export function canonicalGuid(input) {
16
18
  const raw = input.trim();
17
19
  const inLink = /(?:^|[?&#])node-id=([^&#\s]+)/i.exec(raw);
18
- const pair = /^(\d+)[:-](\d+)$/.exec(decode(inLink ? inLink[1] : raw).trim());
19
- return pair ? `${pair[1]}:${pair[2]}` : raw;
20
+ const text = decode(inLink ? inLink[1] : raw).trim();
21
+ const pair = /^(\d+)[:-](\d+)$/.exec(text);
22
+ if (pair)
23
+ return `${pair[1]}:${pair[2]}`;
24
+ const sublayer = /^I(\d+[:-]\d+(?:;\d+[:-]\d+)+)$/.exec(text);
25
+ if (sublayer)
26
+ return `I${sublayer[1].split(';').map((g) => g.replace('-', ':')).join(';')}`;
27
+ return raw;
20
28
  }
21
29
  function decode(s) {
22
30
  try {
@@ -31,21 +39,30 @@ export function guidNotFound(input, key) {
31
39
  const read = key === input.trim() ? '' : ` (read as ${JSON.stringify(key)})`;
32
40
  return (`no node with guid ${JSON.stringify(input)}${read} in this file. ` +
33
41
  'Guids look like "2:1339"; a Figma link spells the same id "node-id=3017-121", and ' +
34
- 'that form, or the whole link, is accepted. Use fig_find or fig_tree to find guids.');
42
+ 'that form, or the whole link, is accepted. A layer inside a component instance is ' +
43
+ '"I<instance guid>;<layer guid>", as fig_tree lists it. Use fig_find or fig_tree to find guids.');
35
44
  }
36
45
  export function readGuid(obj, field) {
37
46
  return guidKey(obj?.[field]);
38
47
  }
48
+ /**
49
+ * The "no value" guid Figma writes into a guid field that is unset: a detached style reference
50
+ * (render-implementation-plan.md F19) and an `overrideKey` that names nothing.
51
+ */
52
+ export const NO_GUID = '4294967295:4294967295';
39
53
  /**
40
54
  * The identity that instance override paths (`symbolData.symbolOverrides[].guidPath.guids` and
41
55
  * `derivedSymbolData[].guidPath.guids`) use for a component descendant: its `overrideKey` when
42
56
  * it has one — a node created by copying a component keeps the original's — else its own guid.
43
57
  *
44
58
  * Measured on the sample: 8 893 of 10 480 symbol descendants carry an explicit key; the other
45
- * 1 587 are addressed by guid, by 30 061 of the file's 303 833 records.
59
+ * 1 587 are addressed by guid, by 30 061 of the file's 303 833 records. An `overrideKey` of
60
+ * `NO_GUID` is no key at all (F23): on the iOS 16 UI Kit 30 of the 44 keyed layers carry it, no
61
+ * record path ever names it, and 31 record path segments name those layers by their guid.
46
62
  */
47
63
  export function overrideIdentity(t) {
48
- return readGuid(t.node, 'overrideKey') ?? t.key;
64
+ const key = readGuid(t.node, 'overrideKey');
65
+ return key !== undefined && key !== NO_GUID ? key : t.key;
49
66
  }
50
67
  /** Raw code-unit comparison — see pitfall §11.4. */
51
68
  function comparePosition(a, b) {
@@ -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)
@@ -10,7 +10,10 @@
10
10
  * and recorded in the report.
11
11
  */
12
12
  import type { CacheEntry } from '../cache.js';
13
+ import type { NodeChange } from '../fig/parse.js';
13
14
  import { type TreeNode } from '../model/tree.js';
15
+ import { type OverrideRecords, type PropAssignments } from './instance.js';
16
+ import { type ModeMap } from '../model/variables.js';
14
17
  import { type Box } from './matrix.js';
15
18
  import { ReportBuilder } from './report.js';
16
19
  export declare const DEFAULT_MAX_NODES = 20000;
@@ -25,6 +28,11 @@ export declare const VISIT_FACTOR = 12;
25
28
  export declare const HARD_MAX_VISITS = 400000;
26
29
  /** A render whose SVG exceeds this is refused rather than handed to the rasterizer. */
27
30
  export declare const MAX_SVG_BYTES: number;
31
+ /**
32
+ * Per-corner radii in SVG order: top-left, top-right, bottom-right, bottom-left. With independent
33
+ * corners a corner the record does not write is square, not the uniform radius (F24).
34
+ */
35
+ export declare function cornerRadii(node: NodeChange): [number, number, number, number];
28
36
  /** A stop that must abort the whole render rather than being isolated to one node. */
29
37
  export declare class RenderBudgetError extends Error {
30
38
  }
@@ -35,11 +43,28 @@ export interface NodeBox {
35
43
  readonly name?: string;
36
44
  readonly box: Box;
37
45
  }
46
+ /**
47
+ * The instance a layer is drawn inside of, when the root is a layer of an instance rather than a
48
+ * stored node (model/scene.ts): the records and property values of the expansion it belongs to.
49
+ */
50
+ export interface ExportContext {
51
+ readonly records: OverrideRecords;
52
+ readonly props: PropAssignments;
53
+ /** Def-id scope, unique to the instance, so its ids never collide with the symbol's own. */
54
+ readonly scope: string;
55
+ /** Symbols already being expanded around the root, for the recursion guard. */
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;
61
+ }
38
62
  export interface ExportOptions {
39
63
  readonly maxNodes?: number;
40
64
  readonly collectBoxes?: boolean;
41
65
  /** CSS colour painted behind everything; omitted for a transparent render. */
42
66
  readonly background?: string;
67
+ readonly context?: ExportContext;
43
68
  }
44
69
  export interface ExportResult {
45
70
  readonly svg: string;
@@ -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';
@@ -35,17 +37,20 @@ const RECTANGULAR = new Set([
35
37
  'SECTION',
36
38
  'GROUP',
37
39
  ]);
38
- /** Per-corner radii in SVG order: top-left, top-right, bottom-right, bottom-left. */
39
- function cornerRadii(node) {
40
+ /**
41
+ * Per-corner radii in SVG order: top-left, top-right, bottom-right, bottom-left. With independent
42
+ * corners a corner the record does not write is square, not the uniform radius (F24).
43
+ */
44
+ export function cornerRadii(node) {
40
45
  const uniform = num(node, 'cornerRadius') ?? 0;
41
46
  if (bool(node, 'rectangleCornerRadiiIndependent') !== true) {
42
47
  return [uniform, uniform, uniform, uniform];
43
48
  }
44
49
  return [
45
- num(node, 'rectangleTopLeftCornerRadius') ?? uniform,
46
- num(node, 'rectangleTopRightCornerRadius') ?? uniform,
47
- num(node, 'rectangleBottomRightCornerRadius') ?? uniform,
48
- num(node, 'rectangleBottomLeftCornerRadius') ?? uniform,
50
+ num(node, 'rectangleTopLeftCornerRadius') ?? 0,
51
+ num(node, 'rectangleTopRightCornerRadius') ?? 0,
52
+ num(node, 'rectangleBottomRightCornerRadius') ?? 0,
53
+ num(node, 'rectangleBottomLeftCornerRadius') ?? 0,
49
54
  ];
50
55
  }
51
56
  /** A stop that must abort the whole render rather than being isolated to one node. */
@@ -73,6 +78,14 @@ class Exporter {
73
78
  activeSymbols = new Set();
74
79
  /** Distinguishes ids for the same symbol node drawn under different instances. */
75
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();
76
89
  constructor(entry, root, opts) {
77
90
  this.entry = entry;
78
91
  this.root = root;
@@ -83,6 +96,16 @@ class Exporter {
83
96
  this.maxVisits = Math.min(maxNodes * VISIT_FACTOR, HARD_MAX_VISITS);
84
97
  this.collectBoxes = opts.collectBoxes === true;
85
98
  this.background = opts.background;
99
+ if (opts.context) {
100
+ // A layer of an instance: start inside that instance, exactly as emitInstance would.
101
+ this.frame = opts.context.records;
102
+ this.props = opts.context.props;
103
+ this.defScope = opts.context.scope;
104
+ this.levelSymbol = opts.context.symbol;
105
+ this.levelModes = opts.context.modes;
106
+ for (const symbol of opts.context.active)
107
+ this.activeSymbols.add(symbol);
108
+ }
86
109
  }
87
110
  blob(index) {
88
111
  if (index === undefined)
@@ -105,23 +128,83 @@ class Exporter {
105
128
  }
106
129
  /**
107
130
  * The node as this instance sees it: the tree node merged with the active overrides and with
108
- * the enclosing instance's property assignments applied (F17, F18), then with every colour or
109
- * 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).
110
136
  */
111
137
  effective(t) {
112
138
  let node = t.node;
139
+ let staleOutlines = false;
113
140
  if (this.frame) {
114
- const record = this.frame.get(overrideIdentity(t));
115
- node = mergeNode(node, record);
116
- const applied = applyProps(node, this.props, record?.['derivedTextData'] !== undefined);
117
- if (applied.node !== node) {
141
+ const shown = showLayer(this.entry.index, t, this.frame, this.props);
142
+ if (shown.propsApplied)
118
143
  this.report.seen('instance-property');
119
- node = applied.node;
120
- if (applied.staleOutlines)
121
- 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);
122
173
  }
123
174
  }
124
- 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;
125
208
  }
126
209
  /** Def keys must not collide between two instances of the same symbol with different fills. */
127
210
  defKey(kind, t) {
@@ -331,17 +414,28 @@ class Exporter {
331
414
  this.report.unsupported('instance-recursive', t.key);
332
415
  return;
333
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;
334
420
  const savedFrame = this.frame;
335
421
  const savedProps = this.props;
336
422
  const savedScope = this.defScope;
423
+ const savedSymbol = this.levelSymbol;
424
+ const savedModes = this.levelModes;
337
425
  this.frame = resolved.records;
338
426
  this.props = resolved.props;
339
427
  this.defScope = `${this.defScope}${t.key}~`;
428
+ this.levelSymbol = resolved.symbol;
429
+ this.levelModes = modes;
340
430
  this.activeSymbols.add(resolved.symbol.key);
341
431
  try {
342
432
  // The instance's own box: the symbol root with its override applied, overlaid by whatever
343
433
  // the instance itself (as seen in its context) already carries resolved.
344
- 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;
345
439
  this.emitOwnContent(t, shape, 'container', resolved.symbol.children);
346
440
  }
347
441
  finally {
@@ -349,6 +443,8 @@ class Exporter {
349
443
  this.frame = savedFrame;
350
444
  this.props = savedProps;
351
445
  this.defScope = savedScope;
446
+ this.levelSymbol = savedSymbol;
447
+ this.levelModes = savedModes;
352
448
  }
353
449
  }
354
450
  /** One `<path>` per (geometry, visible paint) pair. */
@@ -360,6 +456,7 @@ class Exporter {
360
456
  }
361
457
  const box = Exporter.box(node);
362
458
  const paintField = field === 'fillGeometry' ? 'fillPaints' : 'strokePaints';
459
+ const bind = this.runBinder(t, node);
363
460
  for (const path of geometry) {
364
461
  const raw = this.blob(num(path, 'commandsBlob'));
365
462
  if (!raw || raw.length === 0)
@@ -377,7 +474,7 @@ class Exporter {
377
474
  }
378
475
  // SVG's default fill-rule is nonzero, so it is only written when the winding is ODD.
379
476
  const rule = str(path, 'windingRule') === 'ODD' ? 'evenodd' : undefined;
380
- const styled = runPaints(this.entry.index, node, num(path, 'styleID'), paintField);
477
+ const styled = runPaints(this.entry.index, node, num(path, 'styleID'), paintField, bind);
381
478
  for (const paint of styled ?? paints) {
382
479
  const attrs = paintAttrs(paint, box, this.env, t.key);
383
480
  if (!attrs)
@@ -536,7 +633,8 @@ class Exporter {
536
633
  }
537
634
  const box = Exporter.box(node);
538
635
  const own = objArr(node, 'fillPaints');
539
- 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;
540
638
  for (const run of draw.glyphs) {
541
639
  for (const paint of paintsFor(run.styleID)) {
542
640
  const attrs = paintAttrs(paint, box, this.env, t.key);
@@ -1,4 +1,5 @@
1
1
  import { canonicalGuid, guidNotFound } from '../model/tree.js';
2
+ import { isSublayerId, resolveScene } from '../model/scene.js';
2
3
  import { str } from '../model/access.js';
3
4
  import { pageBackground } from './color.js';
4
5
  import { DEFAULT_MAX_NODES, HARD_MAX_NODES, MAX_SVG_BYTES, exportSubtree, } from './export.js';
@@ -9,16 +10,35 @@ export const DEFAULT_MAX_SIZE = 1568;
9
10
  export const HARD_MAX_SIZE = 4096;
10
11
  function resolveRoot(entry, guid) {
11
12
  const key = canonicalGuid(guid);
13
+ if (isSublayerId(key)) {
14
+ // A layer inside an instance: draw its component layer inside that instance's expansion.
15
+ const scene = resolveScene(entry.index, key);
16
+ if (!scene)
17
+ throw new Error(guidNotFound(guid, key));
18
+ const level = scene.level;
19
+ return {
20
+ root: scene.source,
21
+ scene,
22
+ context: level && {
23
+ records: level.instance.records,
24
+ props: level.instance.props,
25
+ scope: `${[level.root, ...level.path].join('~')}~`,
26
+ active: level.active,
27
+ symbol: level.instance.symbol,
28
+ modes: level.modes,
29
+ },
30
+ };
31
+ }
12
32
  const t = entry.index.node(key);
13
33
  if (!t)
14
34
  throw new Error(guidNotFound(guid, key));
15
35
  if (nodeType(t.node) === 'DOCUMENT') {
16
36
  throw new Error('cannot render the DOCUMENT node — render a page or a node inside one');
17
37
  }
18
- return t;
38
+ return { root: t };
19
39
  }
20
40
  export async function renderNode(entry, guid, opts = {}) {
21
- const root = resolveRoot(entry, guid);
41
+ const { root, scene, context } = resolveRoot(entry, guid);
22
42
  const maxNodes = Math.min(opts.maxNodes ?? DEFAULT_MAX_NODES, HARD_MAX_NODES);
23
43
  const range = entry.index.subtreeRange(root);
24
44
  const subtreeSize = range.end - range.start;
@@ -26,12 +46,14 @@ export async function renderNode(entry, guid, opts = {}) {
26
46
  throw new Error(`node ${guid} covers ${subtreeSize} nodes, above maxNodes (${maxNodes}); ` +
27
47
  'render a smaller node or raise maxNodes');
28
48
  }
29
- const background = opts.background === 'page' ? pageBackground(root) : undefined;
49
+ // A layer of an instance sits on the instance's page, not on its component's.
50
+ const background = opts.background === 'page' ? pageBackground(scene ?? root) : undefined;
30
51
  const startedExport = performance.now();
31
52
  const exported = exportSubtree(entry, root, {
32
53
  maxNodes,
33
54
  collectBoxes: opts.collectBoxes,
34
55
  background,
56
+ context,
35
57
  });
36
58
  const renderMs = performance.now() - startedExport;
37
59
  if (exported.svg.length > MAX_SVG_BYTES) {
@@ -67,8 +89,9 @@ export async function renderNode(entry, guid, opts = {}) {
67
89
  rasterizerMissing = true;
68
90
  }
69
91
  }
92
+ const shown = scene ?? root;
70
93
  const report = exported.report.finish({
71
- root: { guid: root.key, name: str(root.node, 'name'), type: nodeType(root.node) },
94
+ root: { guid: shown.key, name: str(shown.node, 'name'), type: nodeType(shown.node) },
72
95
  bounds,
73
96
  width,
74
97
  height,
@@ -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