@moondraft/import 0.1.0 → 0.3.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.
Files changed (98) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +2 -2
  3. package/SOURCE.md +343 -4
  4. package/dist/adapter/convert.d.ts +26 -2
  5. package/dist/adapter/convert.js +817 -217
  6. package/dist/adapter/figma-descriptions.d.ts +7 -0
  7. package/dist/adapter/figma-descriptions.js +34 -0
  8. package/dist/adapter/figma-grids.d.ts +12 -0
  9. package/dist/adapter/figma-grids.js +175 -0
  10. package/dist/adapter/figma-handoff.d.ts +34 -0
  11. package/dist/adapter/figma-handoff.js +188 -0
  12. package/dist/adapter/figma-hyperlinks.d.ts +13 -0
  13. package/dist/adapter/figma-hyperlinks.js +77 -0
  14. package/dist/adapter/figma.d.ts +4 -1
  15. package/dist/adapter/figma.js +15 -4
  16. package/dist/adapter/file-components.d.ts +10 -3
  17. package/dist/adapter/file-components.js +126 -33
  18. package/dist/adapter/file-resources.js +545 -47
  19. package/dist/adapter/file-typography.d.ts +6 -0
  20. package/dist/adapter/file-typography.js +44 -0
  21. package/dist/adapter/image-crop.d.ts +18 -0
  22. package/dist/adapter/image-crop.js +30 -0
  23. package/dist/adapter/link.d.ts +12 -1
  24. package/dist/adapter/link.js +380 -113
  25. package/dist/adapter/payload.js +3 -3
  26. package/dist/adapter/variables.d.ts +2 -1
  27. package/dist/adapter/variables.js +5 -2
  28. package/dist/figma-file.d.ts +1 -0
  29. package/dist/figma-file.js +1 -0
  30. package/dist/figma.d.ts +1 -0
  31. package/dist/figma.js +191 -35
  32. package/dist/index.d.ts +1 -0
  33. package/dist/index.js +1 -0
  34. package/dist/report.d.ts +59 -1
  35. package/dist/report.js +176 -30
  36. package/dist/serialize.d.ts +7 -0
  37. package/dist/serialize.js +79 -0
  38. package/dist/taco/figma-import/container/kiwiContainer.d.ts +3 -0
  39. package/dist/taco/figma-import/container/kiwiContainer.js +1 -1
  40. package/dist/taco/figma-import/figFile.js +3 -0
  41. package/dist/taco/figma-import/import/carry.d.ts +14 -1
  42. package/dist/taco/figma-import/import/carry.js +34 -1
  43. package/dist/taco/figma-import/import/componentProps.d.ts +10 -4
  44. package/dist/taco/figma-import/import/componentProps.js +29 -13
  45. package/dist/taco/figma-import/import/componentSets.d.ts +2 -0
  46. package/dist/taco/figma-import/import/componentSets.js +1 -1
  47. package/dist/taco/figma-import/import/converters/effects.d.ts +3 -13
  48. package/dist/taco/figma-import/import/converters/effects.js +4 -34
  49. package/dist/taco/figma-import/import/converters/exportSettings.d.ts +4 -0
  50. package/dist/taco/figma-import/import/converters/exportSettings.js +75 -0
  51. package/dist/taco/figma-import/import/converters/frame.d.ts +1 -1
  52. package/dist/taco/figma-import/import/converters/frame.js +15 -6
  53. package/dist/taco/figma-import/import/converters/gradient.d.ts +2 -0
  54. package/dist/taco/figma-import/import/converters/gradient.js +3 -1
  55. package/dist/taco/figma-import/import/converters/grid.d.ts +12 -0
  56. package/dist/taco/figma-import/import/converters/grid.js +97 -0
  57. package/dist/taco/figma-import/import/converters/group.d.ts +2 -4
  58. package/dist/taco/figma-import/import/converters/group.js +6 -15
  59. package/dist/taco/figma-import/import/converters/image.d.ts +2 -1
  60. package/dist/taco/figma-import/import/converters/image.js +60 -16
  61. package/dist/taco/figma-import/import/converters/layout.d.ts +8 -7
  62. package/dist/taco/figma-import/import/converters/layout.js +66 -37
  63. package/dist/taco/figma-import/import/converters/rectangle.d.ts +1 -1
  64. package/dist/taco/figma-import/import/converters/rectangle.js +3 -3
  65. package/dist/taco/figma-import/import/converters/section.d.ts +2 -3
  66. package/dist/taco/figma-import/import/converters/section.js +5 -11
  67. package/dist/taco/figma-import/import/converters/shared.d.ts +9 -5
  68. package/dist/taco/figma-import/import/converters/shared.js +23 -10
  69. package/dist/taco/figma-import/import/converters/text.d.ts +38 -1
  70. package/dist/taco/figma-import/import/converters/text.js +248 -32
  71. package/dist/taco/figma-import/import/converters/vector.d.ts +36 -15
  72. package/dist/taco/figma-import/import/converters/vector.js +214 -73
  73. package/dist/taco/figma-import/import/converters/vectorNetwork.d.ts +19 -3
  74. package/dist/taco/figma-import/import/converters/vectorNetwork.js +147 -29
  75. package/dist/taco/figma-import/import/instances.d.ts +32 -5
  76. package/dist/taco/figma-import/import/instances.js +613 -130
  77. package/dist/taco/figma-import/import/styles.d.ts +2 -0
  78. package/dist/taco/figma-import/import/styles.js +6 -0
  79. package/dist/taco/figma-import/import/types.d.ts +8 -0
  80. package/dist/taco/figma-import/import/variables.d.ts +5 -2
  81. package/dist/taco/figma-import/import/variables.js +65 -31
  82. package/dist/taco/figma-import/import/variantTrees.d.ts +1 -1
  83. package/dist/taco/figma-import/import/variantTrees.js +46 -4
  84. package/dist/taco/figma-import/import/walk.d.ts +62 -7
  85. package/dist/taco/figma-import/import/walk.js +328 -122
  86. package/dist/taco/figma-import/kiwi/message.d.ts +4 -2
  87. package/dist/taco/figma-import/kiwi/message.js +59 -15
  88. package/dist/taco/model/codec.d.ts +2 -2
  89. package/dist/taco/model/codec.js +72 -8
  90. package/dist/taco/model/component-evaluation.d.ts +2 -0
  91. package/dist/taco/model/component-evaluation.js +7 -0
  92. package/dist/taco/model/instance-resolver.d.ts +6 -2
  93. package/dist/taco/model/instance-resolver.js +50 -18
  94. package/dist/taco/model/sha256.js +13 -8
  95. package/dist/taco/model/types.d.ts +57 -5
  96. package/dist/taco/model/types.js +4 -0
  97. package/dist/taco/svg-import/style/computed.js +1 -0
  98. package/package.json +3 -2
@@ -10,13 +10,17 @@
10
10
  // The taco records are read as JSON, field by field and loosely (any): the converter reads fields of several schema
11
11
  // versions and of the HeroUI kit export that taco's model types do not declare, so the source side is untyped and the
12
12
  // result is checked against DocumentJSON where it leaves.
13
- import { fontStyleName, layoutFrame, layoutData, localBox, mul, pathBounds, resize, scalePath, wrapped } from '@moondraft/editor/core';
13
+ import { box, commands, fontStyleName, inv, layoutFrame, layoutData, localBox, mul, netBounds, pathBounds, resize, scalePath, sizingOf, transformNet, wrapped } from '@moondraft/editor/core';
14
14
  import { shapes } from '@moondraft/editor/core';
15
- import { paintBox, resolveLinearCall } from '../taco/model/linear-call.js';
15
+ import * as editorSchema from '@moondraft/editor/schema';
16
+ import { STROKE_CAPS } from '@moondraft/editor/schema';
17
+ import { imageCropOf, imageTileOf } from '../taco/figma-import/import/carry.js';
18
+ import { linearEndpoints, paintBox, resolveLinearCall } from '../taco/model/linear-call.js';
16
19
  import { arcCubics, arcNetwork, ellipseNetwork, network } from './shapes.js';
20
+ import { imageCropPlacement } from './image-crop.js';
17
21
  import { expressionCollections, variableResolver } from './variables.js';
18
22
  import { BLEND_MODES } from '../taco/model/types.js';
19
- import { applyComputedFields, checkComponentProgram, evaluateComponentProgram, filledPropertyValues } from '../taco/model/component-evaluation.js';
23
+ import { applyComputedFields, checkComponentProgram, evaluateComponentProgram, filledPropertyValues, linkedParagraphsMatch } from '../taco/model/component-evaluation.js';
20
24
  import { componentExpressionEnvironment, componentValueEnvironment, computableFieldType, storedFieldValue } from '../taco/model/component-expressions.js';
21
25
  import { ExpressionCache } from '../taco/model/expressions/cache.js';
22
26
  import { evaluateExpression } from '../taco/model/expressions/evaluate.js';
@@ -24,7 +28,57 @@ import { EXPRESSION_TYPES } from '../taco/model/expressions/types.js';
24
28
  import { expressionColorToHex } from '../taco/model/expressions/values.js';
25
29
  import { withoutTextMeasurement } from '../taco/model/text-reads.js';
26
30
  import { createInstanceResolveCache, resolveComponent, resolveInstance } from '../taco/model/instance-resolver.js';
31
+ import { applyFileTypography } from './file-typography.js';
27
32
  import { linkWithLayers, unmark } from './link.js';
33
+ const supportsGrid = 'layoutData.gridCell' in editorSchema.Properties;
34
+ // Figma stores float32 sizes. Comparing after layout or instance scaling can
35
+ // also include rounding from the arithmetic that produced the two sizes.
36
+ function sameFigmaSize(a, b, absoluteTolerance = 0) {
37
+ const difference = Math.abs(a - b);
38
+ return difference <= absoluteTolerance || difference < Math.max(Math.abs(a), Math.abs(b)) * 1e-6;
39
+ }
40
+ // fit() takes the union of the child boxes after layout. Only allocate an axis
41
+ // that the fitted bounds track under scale, including after a collapse. A
42
+ // smaller path needs a proportionally larger group minimum to keep its shape.
43
+ function fittedGroupAxis(size, children, axis) {
44
+ if (!size || !children.length)
45
+ return;
46
+ const horizontal = axis === 'width', index = horizontal ? 0 : 1;
47
+ let near = Infinity, far = -Infinity, minimum = 1e-3;
48
+ for (const child of children) {
49
+ const { model, node } = child;
50
+ if (node.constraints?.[horizontal ? 'horizontal' : 'vertical'] !== 'scale' || node.aspectRatioLocked ||
51
+ model.mask || model.t[1] || model.t[2] || Math.abs(model.t[0] * model.t[3]) < 1e-12)
52
+ return;
53
+ const bounds = box(model), extent = bounds[index + 2] - bounds[index];
54
+ near = Math.min(near, bounds[index]);
55
+ far = Math.max(far, bounds[index + 2]);
56
+ if (model.kind === 'path' && extent > 0) {
57
+ const measured = model.layoutData?.box?.[axis] ?? extent;
58
+ if (!measured)
59
+ return;
60
+ minimum = Math.max(minimum, 1e-3 * (size / measured));
61
+ }
62
+ else if (model.group) {
63
+ const nestedSize = horizontal ? model.w : model.h;
64
+ const nested = fittedGroupAxis(nestedSize, child.children, axis);
65
+ if (!nested || !sameFigmaSize(nested.extent, nestedSize, 1e-9))
66
+ return;
67
+ minimum = Math.max(minimum, nested.minimum * (size / nestedSize));
68
+ }
69
+ else if (model.kind !== 'rect' && model.kind !== 'path')
70
+ return;
71
+ }
72
+ // Converted vertices have four decimal places. Start subsequent resizes at
73
+ // the converted extent so the rounding error cannot grow with the group.
74
+ if (Math.abs(near) >= 1e-9 || !sameFigmaSize(far, size, 0.00005))
75
+ return;
76
+ minimum = Math.max(1e-3, minimum * (far / size));
77
+ if (minimum <= far)
78
+ return { extent: far, minimum };
79
+ }
80
+ const supportsVideo = 'mediaType' in editorSchema.AssetSchema.properties &&
81
+ editorSchema.firstError(editorSchema.PaintSchema, { k: 'video', asset: 'clip' }) === null;
28
82
  /** Converts a reader colour to the RGBA precision used by imported paints.
29
83
  * @param hex - Source hex colour or expression colour.
30
84
  * @returns Normalized channels, or null for a non-colour value.
@@ -50,24 +104,37 @@ export function rgba(hex) {
50
104
  */
51
105
  export function runStyle(s) {
52
106
  const size = s.fontSize ?? 16, weight = s.fontWeight ?? 400;
107
+ const features = Object.entries(s.openTypeFeatures ?? {});
53
108
  return {
54
109
  family: s.fontFamily ?? 'Inter', style: s.fontStyle ?? fontStyleName(weight, !!s.italic),
110
+ ...(features.length > 0 && { features: Object.fromEntries(features.map(([tag, value]) => [tag, Number(value)])) }),
55
111
  ...(s.fontVariations && { variations: s.fontVariations }), size, lineHeight: +(size * (s.lineHeight ?? 1.2)).toFixed(3),
56
112
  weight, italic: !!s.italic, underline: !!s.underline, ...(s.strikethrough ? { strikethrough: true } : {}),
113
+ ...(s.textCase && s.textCase !== 'original' && { textCase: s.textCase }),
57
114
  color: rgba(s.color) ?? [0, 0, 0, 1], letterSpacing: s.letterSpacing ?? 0,
58
115
  };
59
116
  }
60
117
  const EXPORT_QUALITY = { low: 0.5, medium: 0.75, high: 0.92 };
118
+ /** Most export rows the editor keeps on one layer (its schema's `exports` limit). */
119
+ const MAX_EXPORTS = 32;
61
120
  /** A source layer's export rows as the editor's `exports`: the format, the constraint as a scale, a width or a
62
- * height, the suffix, and for JPEG the quality as a number. The rest of a row (resampling, overlapping layers, id
63
- * attributes) has no counterpart. */
64
- function exportsOf(rows) {
121
+ * height, the suffix, and for JPEG the quality as a number. The rest of a row has no counterpart; `lost` hears of
122
+ * each field that differs from what the editor exports anyway (rows past the editor's limit, basic resampling, a
123
+ * drawing of overlapping layers, SVG id attributes). */
124
+ function exportsOf(rows, lost) {
65
125
  if (!rows?.length)
66
126
  return undefined;
67
- return rows.slice(0, 32).map(({ format, constraint, suffix, quality }) => ({
68
- format, [constraint.type]: constraint.value, suffix,
69
- ...(format === 'jpeg' && { quality: EXPORT_QUALITY[quality] }),
70
- }));
127
+ for (let n = rows.length - MAX_EXPORTS; n > 0; n--)
128
+ lost(`export setting beyond the editor's ${MAX_EXPORTS}-row limit`);
129
+ return rows.slice(0, MAX_EXPORTS).map(({ format, constraint, suffix, quality, resampling, ignoreOverlappingLayers, includeIdAttribute }) => {
130
+ if (resampling !== 'detailed' && format !== 'svg')
131
+ lost('export setting resampling (basic)');
132
+ if (!ignoreOverlappingLayers && format !== 'pdf')
133
+ lost('export setting contents only (off: overlapping layers drawn)');
134
+ if (includeIdAttribute && format === 'svg')
135
+ lost('export setting SVG id attributes (always)');
136
+ return { format, [constraint.type]: constraint.value, suffix, ...(format === 'jpeg' && { quality: EXPORT_QUALITY[quality] }) };
137
+ });
71
138
  }
72
139
  /**
73
140
  * Converts one page of a Taco document to Moondraft records.
@@ -83,18 +150,32 @@ export function toDocument(doc, pageRef, options = {}) {
83
150
  throw new Error(`no page ${pageRef}; pages: ${pages.map((p) => p.name).join(', ')}`);
84
151
  return convert(doc, [page], options, false);
85
152
  }
153
+ /** Converts the clipboard selection for the Figma adapter's subsequent GUID resolution pass. @internal */
154
+ export function figmaClipboardPage(doc, instanceSources) {
155
+ return convert(doc, [doc.pages[doc.pageOrder[0]]], { instanceSources }, false, undefined, true);
156
+ }
86
157
  /** Converts all file pages and keeps the appearance of each linked occurrence.
87
158
  * @param doc - Source document.
88
159
  * @param options - Asset and conversion settings.
89
- * @returns Linked document, conversion report and the pre-link instance literals.
160
+ * @returns Linked document, conversion report, pre-link literals and nested boolean assignments.
90
161
  * @internal
91
162
  */
92
163
  export function allPages(doc, options) {
93
- const expanded = new Map();
94
- return { ...convert(doc, doc.pageOrder.map((id) => doc.pages[id]), options, true, expanded), expanded };
164
+ const file = { expanded: new Map(), nestedBooleans: new Map(), omittedLinks: new Map(), expandedReasons: new Map() };
165
+ return { ...convert(doc, doc.pageOrder.map((id) => doc.pages[id]), options, true, file, true), ...file };
95
166
  }
96
- function convert(doc, pages, options, explicit, expanded) {
167
+ // The boolean group operations (FrameNode.boolean) a live Figma boolean operation carries.
168
+ const BOOLEAN_OPS = new Set(['union', 'subtract', 'intersect', 'exclude']);
169
+ // The override and expression fields that leave a boolean operand's shape and visibility as they are (an operand's look
170
+ // is not drawn).
171
+ const LOOK_ONLY = new Set(['opacity', 'name', 'fills', 'strokes', 'effects', 'startCap', 'endCap', 'shadows', 'layerBlur', 'backgroundBlur', 'styleId', 'imageAssetId']);
172
+ // The model fields that are a boolean group's own (its operation, result and look), moved off a fixed-size wrapper.
173
+ const BOOLEAN_OWN = ['group', 'boolean', 'result', 'fill', 'look', 'stroke', 'strokeWidth', 'radius', 'smoothing'];
174
+ function expand(doc, pages, options, explicit, file, deferHyperlinks) {
97
175
  const kitFixes = options.kitFixes ?? false;
176
+ const nestedBooleans = file && new WeakMap();
177
+ // The boolean group inside each fixed-size wrapper the conversion made (see `fixedBox` below), by wrapper model.
178
+ const wrappedBoolean = new WeakMap();
98
179
  const dropped = new Map(), notes = new Map(), approximations = new Map();
99
180
  const affected = new Map();
100
181
  let active, probing = 0;
@@ -115,7 +196,14 @@ function convert(doc, pages, options, explicit, expanded) {
115
196
  };
116
197
  const rootOf = new Map(Object.values(doc.components).map((c) => [c.rootId, c]));
117
198
  // Children of slot frames: an instance fills a slot by re-pointing them, hidden ones included (below).
118
- const slotChildren = new Set(Object.values(doc.nodes).flatMap((n) => (n.slot ? n.children ?? [] : [])));
199
+ const slotChildren = new Set(), extraRoots = [];
200
+ for (const node of Object.values(doc.nodes)) {
201
+ if (node.slot)
202
+ for (const child of node.children ?? [])
203
+ slotChildren.add(child);
204
+ if (explicit && (node.slotHost || node.fileStyle))
205
+ extraRoots.push(node);
206
+ }
119
207
  // An expanded instance of a component with variant properties names its set (link.ts names its hidden main
120
208
  // "Button/variant=primary, size=sm" with it, so the editor groups a set's variants and no other's).
121
209
  // It names its variant too (its variant properties' values, "variant=primary, size=sm"): link.ts makes one hidden
@@ -158,13 +246,13 @@ function convert(doc, pages, options, explicit, expanded) {
158
246
  // (resolveInstance; resolveComponent for a component met on the page). Each layer takes from its ResolvedLayer what
159
247
  // overrides set apart from sizes: visibility (conditions included), paints, effects, opacity, name, blend mode, text
160
248
  // content, colour and alignment, the component an instance shows (swaps) and its property values, and the content
161
- // a slot frame shows. The resolver lays its layers out again; their sizes and positions are not read here. The
249
+ // a slot frame shows. File conversion supplies geometry itself and skips the resolver's layout. The
162
250
  // converter's own override maps (overridesFor) still feed its size rules: sizing, padding, line boxes, scale and
163
251
  // variant sizes. Computed texts keep their stored frames (withoutTextMeasurement), as in `evaluated` below.
164
- const resolveCache = createInstanceResolveCache();
252
+ const resolveOptions = { cache: createInstanceResolveCache(!file), layout: !file };
165
253
  function resolvedLayer(n, definition) {
166
254
  try {
167
- return withoutTextMeasurement(() => definition ? resolveComponent(model, definition.id, { cache: resolveCache }) : resolveInstance(model, n.id, { cache: resolveCache }).root);
255
+ return withoutTextMeasurement(() => definition ? resolveComponent(model, definition.id, resolveOptions) : resolveInstance(model, n.id, resolveOptions).root);
168
256
  }
169
257
  catch (e) {
170
258
  // Counted by kind; taco's message (a refused document or an evaluator failure alike) is the detail.
@@ -172,11 +260,13 @@ function convert(doc, pages, options, explicit, expanded) {
172
260
  return false;
173
261
  }
174
262
  }
175
- // A layer's node in the document: a nested instance layer stands for its instance node, any other for its source.
263
+ // Nested instance wrappers can contribute diagnostics even during a size trial.
264
+ const containsInstance = (layer) => layer.instance !== undefined || layer.children.some(containsInstance);
265
+ // A nested instance layer stands for its instance node, any other for its source.
176
266
  const layerNodeId = (layer) => layer.instance?.instanceId ?? layer.sourceNodeId;
177
267
  // Override fields the size rules read; the rest of an override map comes from the resolved layer.
178
- const SIZE_OVERRIDES = new Set(['sizing', 'padding', 'textStyle', 'lineBoxOnly', 'frame', 'x', 'y', 'width', 'height', 'resizing', 'layoutPositioning', 'constraints', 'layout', 'variableModes', 'variableBindings', 'expressions']);
179
- const SIZE_BINDINGS = new Set(['width', 'height', 'gap', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'fontFamily']);
268
+ const SIZE_OVERRIDES = new Set(['sizing', 'padding', 'gridCell', 'textStyle', 'lineBoxOnly', 'frame', 'x', 'y', 'width', 'height', 'resizing', 'layoutPositioning', 'constraints', 'layout', 'variableModes', 'variableBindings', 'expressions']);
269
+ const SIZE_BINDINGS = new Set(['width', 'height', 'gap', 'columnGap', 'rowGap', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'fontFamily']);
180
270
  function sizeOverrides(o) {
181
271
  const out = {};
182
272
  for (const [k, v] of Object.entries(o)) {
@@ -199,7 +289,7 @@ function convert(doc, pages, options, explicit, expanded) {
199
289
  return out;
200
290
  }
201
291
  // Expressions whose result the resolved layer holds (with any override over it): the converter evaluates the rest.
202
- const RESOLVED_FIELDS = new Set(['visible', 'opacity', 'fills', 'strokes', 'shadows', 'effects', 'cornerRadii', 'characters', 'textColor', 'componentId']);
292
+ const RESOLVED_FIELDS = new Set(['visible', 'opacity', 'fills', 'strokes', 'shadows', 'effects', 'cornerRadii', 'characters', 'textColor', 'componentId', 'startCap', 'endCap']);
203
293
  const resolvedField = (key) => RESOLVED_FIELDS.has(key) || key.startsWith('propertyValues.');
204
294
  const programs = new Map();
205
295
  function programOf(comp) {
@@ -465,6 +555,17 @@ function convert(doc, pages, options, explicit, expanded) {
465
555
  out[key.slice(prefix.length)] = value;
466
556
  return out;
467
557
  }
558
+ function boxAt(scopes, id) {
559
+ let inner;
560
+ for (const { boxes, prefix, fillScale } of scopes ?? []) {
561
+ const box = boxes.get(prefix + id);
562
+ if (box && !box.inner)
563
+ return { box, fillScale };
564
+ if (box)
565
+ inner ??= fillScale === undefined ? { box } : { box, fillScale };
566
+ }
567
+ return inner;
568
+ }
468
569
  function descendSlots(map, instanceId) {
469
570
  const out = {}, prefix = `${instanceId};`;
470
571
  for (const [key, value] of Object.entries(map))
@@ -569,12 +670,14 @@ function convert(doc, pages, options, explicit, expanded) {
569
670
  // DatePicker: its DateField's label draws 24 px, not the 20 px box line; p15 calendar days keep theirs).
570
671
  : ctx.comps.slice(0, ctx.comps.indexOf(scope)).some((c) => c.definition === true) && ctx.comps.at(-1) !== scope ? 'nested' : 'instance');
571
672
  }
673
+ if (o.layout?.gap !== undefined && out.variableBindings && !o.variableBindings?.gap)
674
+ delete out.variableBindings.gap;
572
675
  for (const [k, v] of Object.entries(o)) {
573
676
  if (k === 'conditional' || k === 'lineBoxOnly')
574
677
  continue; // a name (a layer renamed in an instance) is kept
575
678
  if (k === 'propertyValues')
576
679
  out.propertyValues = { ...out.propertyValues, ...v };
577
- else if (['textStyle', 'variableBindings', 'variableModes', 'expressions', 'style', 'sizing', 'padding'].includes(k))
680
+ else if (['textStyle', 'variableBindings', 'variableModes', 'expressions', 'style', 'sizing', 'padding', 'layout', 'gridCell'].includes(k))
578
681
  out[k] = { ...out[k], ...v };
579
682
  else
580
683
  out[k] = v;
@@ -586,13 +689,19 @@ function convert(doc, pages, options, explicit, expanded) {
586
689
  }
587
690
  }
588
691
  // ---- Paints and colours.
692
+ const posters = new Map();
589
693
  const stops = (s) => s.map((x) => [Math.min(1, Math.max(0, x.offset)), rgba(x.color) ?? [0, 0, 0, 1]]);
590
694
  // Whether a model draws a fill: its compact one, or a shown paint in look.fills.
591
695
  const shownFills = (m) => !!m.fill || !!m.look?.fills?.some((p) => p.visible !== false);
592
696
  // A paint for the wire (packages/editor/src/renderer/wire.ts paint()), or null when dropped. A hidden paint keeps its
593
697
  // place in the list (visible: false), as Figma keeps it; one that would be dropped is left out without counting.
594
698
  // tile: the scale of an image fill Figma tiles (figma-import's metadata.figma.tiles, see taco/.../carry.ts).
699
+ // A paint's blend mode goes on the wire as its code (blend; normal is none).
595
700
  function paint(p, tile) {
701
+ if (p.blendMode !== undefined && p.blendMode !== 'normal') {
702
+ const q = paint({ ...p, blendMode: undefined }, tile);
703
+ return q && { ...q, blend: BLEND_MODES.indexOf(p.blendMode) };
704
+ }
596
705
  if (p.visible === false) {
597
706
  const had = new Map(dropped), q = paint({ ...p, visible: true }, tile);
598
707
  dropped.clear();
@@ -614,30 +723,49 @@ function convert(doc, pages, options, explicit, expanded) {
614
723
  return { k: 'solid', c, o };
615
724
  }
616
725
  if (p.kind === 'linear-gradient') {
617
- if (!p.from || !p.to)
618
- throw new Error('Linear gradient requires from and to endpoints');
726
+ const ok = (e) => Number.isFinite(e?.x) && Number.isFinite(e?.y);
727
+ if (!ok(p.from) || !ok(p.to)) {
728
+ drop('linear gradient: no endpoints');
729
+ return null;
730
+ }
619
731
  return { k: 'linear', from: [p.from.x, p.from.y], to: [p.to.x, p.to.y], stops: stops(p.stops), o };
620
732
  }
621
733
  if (p.kind === 'radial-gradient')
622
734
  return { k: 'radial', cx: p.center?.x ?? 0.5, cy: p.center?.y ?? 0.5, rx: p.radius?.x || 0.5, ry: p.radius?.y || 0.5, stops: stops(p.stops), o };
623
735
  if (p.kind === 'angular-gradient')
624
736
  return { k: 'angular', cx: p.center?.x ?? 0.5, cy: p.center?.y ?? 0.5, start: p.angle ?? 0, stops: stops(p.stops), o };
625
- // Image fills: the source keeps only the asset and its fit (none = Figma FILL, i.e. cover; 'fill' = STRETCH).
626
- // Figma's crop transform and tile mode are not in the source, so CROP draws stretched and TILE draws as cover, unless
627
- // supplement.mjs supplies them from the plugin export (a tile becomes fit 3 with its scale, wire.ts paint()).
628
737
  if (p.kind === 'image') {
629
738
  const asset = doc.assets?.[p.assetId];
630
- if (asset?.kind !== 'image' || asset.source?.kind !== 'data') {
739
+ if ((asset?.kind !== 'image' && asset?.kind !== 'video') || asset.source?.kind !== 'data') {
631
740
  drop('image fill: asset missing or not inline data');
632
741
  return null;
633
742
  }
634
- return { k: 'image', asset: p.assetId, fit: { contain: 0, fit: 0, cover: 1, fill: 2, stretch: 2 }[p.fit] ?? 1, o };
743
+ let kind = asset.kind;
744
+ if (kind === 'video' && !supportsVideo) {
745
+ if (!posters.has(p.assetId)) {
746
+ const header = typeof asset.poster === 'string' && /^data:(image\/[a-z0-9.+-]+);base64,/i.exec(asset.poster);
747
+ if (!header) {
748
+ drop('Video fill requires a newer editor');
749
+ return null;
750
+ }
751
+ posters.set(p.assetId, { id: p.assetId, kind: 'image', width: asset.width, height: asset.height,
752
+ mimeType: header[1], source: { kind: 'data', data: asset.poster.slice(header[0].length) } });
753
+ }
754
+ approximate('Video fill requires a newer editor, kept its poster');
755
+ kind = 'image';
756
+ }
757
+ return { k: kind, asset: p.assetId, fit: { contain: 0, fit: 0, cover: 1, fill: 2, stretch: 2 }[p.fit] ?? 1, o };
635
758
  }
636
759
  drop(`paint ${p.kind}`);
637
760
  return null;
638
761
  }
639
762
  // ---- Nodes.
640
763
  const models = [];
764
+ // An enclosing auto-layout frame can move or resize an already converted child.
765
+ // Link the stored Figma geometry after the layout passes have finished.
766
+ const stacksWithStoredFill = [];
767
+ const storedFillSizes = new Map();
768
+ const keptGeometry = new Map();
641
769
  // Instance roots that are bare hug wrappers, with their variant root and padding (see the check after conversion).
642
770
  const wrappers = [];
643
771
  let serial = 0, depthMax = 0;
@@ -658,7 +786,7 @@ function convert(doc, pages, options, explicit, expanded) {
658
786
  // place: an instance's frame and rotation, for a component root expanded in its place.
659
787
  // rs: how the parent's size changed from its stored one ({ dw, dh, sx, sy }), when it has no auto layout: the node
660
788
  // follows its constraints (an instance sized unlike its component, or a frame resized by that).
661
- const STYLE_KEYS = ['fills', 'strokes', 'shadows', 'cornerRadii', 'cornerRadius'];
789
+ const STYLE_KEYS = ['fills', 'strokes', 'shadows', 'cornerRadii', 'cornerRadius', 'cornerSmoothing'];
662
790
  // The style keys a component's `effects` expression computes.
663
791
  const EFFECT_KINDS = ['shadows', 'backgroundBlur', 'layerBlur'];
664
792
  // A Figma mask (mask: true; maskType alpha, the default, vector or luminance) becomes the renderer's mask flag (SPEC
@@ -672,20 +800,35 @@ function convert(doc, pages, options, explicit, expanded) {
672
800
  const previous = active;
673
801
  active = {};
674
802
  try {
675
- if (!n.mask && !n.isMask)
676
- return visitNode(n, parent, ctx, place, depth, rs, layer);
677
- const type = String(n.maskType ?? n.metadata?.figma?.maskType ?? 'alpha').toLowerCase();
803
+ const saved = !probing && !place ? boxAt(ctx.boxScopes, n.id) : undefined;
804
+ const kept = probing ? undefined : place?.box ?? (saved?.fillScale === undefined ? saved?.box : undefined);
805
+ const mask = n.mask || n.isMask;
806
+ const type = mask && String(n.maskType ?? n.metadata?.figma?.maskType ?? 'alpha').toLowerCase();
678
807
  if (type === 'luminance') {
679
808
  drop('luminance mask (no renderer equivalent; mask skipped, siblings unmasked)');
680
809
  return;
681
810
  }
682
- const item = visitNode(n, parent, ctx, place, depth, rs, layer);
683
- if (!item)
811
+ const item = visitNode(n, parent, ctx, place, depth, rs, layer, kept);
812
+ if (item && saved?.fillScale !== undefined) {
813
+ applyFillSize(item, saved.box, saved.fillScale);
814
+ storedFillSizes.set(item.model, fillSize(item.model));
815
+ }
816
+ if (kept && item) {
817
+ // An opacity wrapper and its region path share one stored Figma box.
818
+ for (const { model } of [item, ...(n.type === 'shape' ? item.children : [])]) {
819
+ const { t, w, h, net, layoutData } = model;
820
+ if (model.kind === 'path' || model.group)
821
+ storedFillSizes.set(model, fillSize(model));
822
+ keptGeometry.set(model, { t: [...t], ...(net ? { net } : { w, h }), box: layoutData?.box });
823
+ }
824
+ }
825
+ if (!mask || !item)
684
826
  return item;
685
827
  item.model.mask = true;
686
828
  note('masks');
687
829
  if (type === 'vector') {
688
- const m = item.model;
830
+ // A boolean group in a fixed-size wrapper masks with its own outline: the wrapper keeps only the mask flag.
831
+ const m = wrappedBoolean.get(item.model) ?? item.model;
689
832
  if (m.kind === 'text')
690
833
  drop('vector mask on text (masked by its glyph alpha)');
691
834
  else {
@@ -693,6 +836,8 @@ function convert(doc, pages, options, explicit, expanded) {
693
836
  delete m.stroke;
694
837
  delete m.strokeWidth;
695
838
  delete m.look;
839
+ for (const region of m.net?.regions ?? [])
840
+ delete region.fills;
696
841
  note('vector masks sent opaque');
697
842
  }
698
843
  }
@@ -711,8 +856,9 @@ function convert(doc, pages, options, explicit, expanded) {
711
856
  if (at < 0)
712
857
  return;
713
858
  const rest = children.slice(at + 1);
859
+ // Children are emitted in preorder. The last child owns the entire suffix.
714
860
  if (!rest.length) {
715
- removeSubtree(children[at].model.id);
861
+ models.length = models.lastIndexOf(children[at].model);
716
862
  note('masks with nothing after them (not drawn)');
717
863
  return;
718
864
  }
@@ -726,18 +872,7 @@ function convert(doc, pages, options, explicit, expanded) {
726
872
  note('masks nested in a wrapper frame');
727
873
  applyMasks(wrapper, inner);
728
874
  }
729
- function removeSubtree(id) {
730
- const gone = new Set([id]);
731
- for (const m of models)
732
- if (gone.has(m.parent))
733
- gone.add(m.id);
734
- let j = 0;
735
- for (const m of models)
736
- if (!gone.has(m.id))
737
- models[j++] = m;
738
- models.length = j;
739
- }
740
- function visitNode(n, parent, ctx, place = null, depth = 0, rs = null, layer) {
875
+ function visitNode(n, parent, ctx, place, depth, rs, layer, kept) {
741
876
  depthMax = Math.max(depthMax, depth);
742
877
  if (depth > 64) {
743
878
  drop('instance nesting deeper than 64');
@@ -751,13 +886,41 @@ function convert(doc, pages, options, explicit, expanded) {
751
886
  layer = resolvedLayer(n, definition);
752
887
  const L = layer || undefined, r = L?.node;
753
888
  const full = overridesFor(n.id, ctx), o = L ? sizeOverrides(full) : full, eff = { ...n, ...o };
754
- ctx = { ...ctx, modes: { ...ctx.modes, ...n.variableModes, ...o.variableModes, ...place?.variableModes } };
889
+ if (o.layout)
890
+ eff.layout = { ...n.layout, ...o.layout };
891
+ const figma = n.metadata?.figma;
892
+ if (eff.layout?.kind === 'grid') {
893
+ const { columns, ...grid } = eff.layout;
894
+ if (supportsGrid)
895
+ eff.layout = { ...grid, columnTracks: grid.columnTracks ?? Array.from({ length: columns }, () => ({ kind: 'fill' })) };
896
+ else {
897
+ for (const field of Object.keys(grid))
898
+ drop(`Grid layout ${field} requires a newer editor`);
899
+ eff.layout = { kind: 'absolute' };
900
+ }
901
+ }
902
+ const cell = place ? place.gridCell : o.gridCell ? { ...figma?.gridCell, ...o.gridCell } : figma?.gridCell;
903
+ if (cell) {
904
+ if (supportsGrid)
905
+ eff.gridCell = cell;
906
+ else {
907
+ delete eff.gridCell;
908
+ for (const field of Object.keys(cell))
909
+ drop(`Grid child ${field} requires a newer editor`);
910
+ }
911
+ }
912
+ if (figma?.fillSizing)
913
+ eff.resizing = { ...figma.fillSizing, ...eff.resizing };
914
+ if (figma?.groupConstraints)
915
+ eff.constraints = { ...figma.groupConstraints, ...eff.constraints };
916
+ if (n.variableModes || o.variableModes || place?.variableModes)
917
+ ctx = { ...ctx, modes: { ...ctx.modes, ...n.variableModes, ...o.variableModes, ...place?.variableModes } };
755
918
  // Resolve bindings on the effective stored paints first; expressions replace these
756
919
  // fallbacks below. Clone paints so expanding one instance never changes another.
757
920
  // A resolved layer's paints have its overrides, computed fields and bound variables applied.
758
921
  const style = L ? { ...r.style } : { ...n.style, ...o.style };
759
922
  if (!L)
760
- for (const k of ['fills', 'strokes', 'shadows', 'backgroundBlur', 'layerBlur', 'cornerRadii', 'cornerRadius'])
923
+ for (const k of ['fills', 'strokes', 'shadows', 'backgroundBlur', 'layerBlur', 'cornerRadii', 'cornerRadius', 'cornerSmoothing'])
761
924
  if (o[k] !== undefined)
762
925
  style[k] = o[k];
763
926
  if (L) {
@@ -781,10 +944,18 @@ function convert(doc, pages, options, explicit, expanded) {
781
944
  }
782
945
  // An instance's root keeps its own opacity: the instance's replaces it by the variant opacity rule (variantOpacity).
783
946
  Object.assign(eff, place ? {} : { opacity: r.opacity }, { name: r.name, blendMode: r.blendMode });
947
+ if (n.type === 'frame')
948
+ eff.clipContent = r.clipContent;
784
949
  if (n.type === 'instance')
785
950
  eff.componentId = L.instance.componentId;
951
+ if (n.type === 'shape')
952
+ Object.assign(eff, { startCap: r.startCap, endCap: r.endCap });
786
953
  }
787
954
  const allBindings = { ...n.variableBindings, ...o.variableBindings };
955
+ // A literal instance gap replaces the main's binding. A binding authored on the same override still wins.
956
+ for (const gap of ['gap', 'columnGap', 'rowGap'])
957
+ if (o.layout?.[gap] !== undefined && !o.variableBindings?.[gap])
958
+ delete allBindings[gap];
788
959
  const bindings = L ? Object.fromEntries(Object.entries(allBindings).filter(([k]) => SIZE_BINDINGS.has(k) || (place && k === 'opacity'))) : allBindings;
789
960
  for (const key of ['fillColor', 'strokeColor', 'textColor']) {
790
961
  if (!bindings[key] || (explicit && key !== 'textColor'))
@@ -831,8 +1002,8 @@ function convert(doc, pages, options, explicit, expanded) {
831
1002
  eff[key] = v;
832
1003
  else if (key === 'opacity')
833
1004
  eff.opacity = v;
834
- else if (key === 'gap')
835
- eff.layout = { ...eff.layout, gap: v };
1005
+ else if (key === 'gap' || key === 'columnGap' || key === 'rowGap')
1006
+ eff.layout = { ...eff.layout, [key]: v };
836
1007
  else if (pad)
837
1008
  eff.layout = { ...eff.layout, padding: { ...eff.layout?.padding, [pad[1].toLowerCase()]: v } };
838
1009
  else if (key === 'cornerRadius') {
@@ -910,8 +1081,6 @@ function convert(doc, pages, options, explicit, expanded) {
910
1081
  note('hidden nodes skipped');
911
1082
  return;
912
1083
  }
913
- if (n.flipX || n.flipY)
914
- drop('instance flip');
915
1084
  const frame = place?.frame ?? eff.frame, rotation = place?.rotation ?? eff.rotation ?? 0;
916
1085
  // The layer's name: the source's (an override may rename it); a component root expanded in an instance's place takes
917
1086
  // the instance's name, as Figma's layers panel shows it.
@@ -920,7 +1089,7 @@ function convert(doc, pages, options, explicit, expanded) {
920
1089
  common.visible = false;
921
1090
  active.id = common.id;
922
1091
  // The layer's export settings (an instance's own go to its expanded root, never its component's).
923
- const exports = place ? place.exports : exportsOf(eff.exportSettings);
1092
+ const exports = place ? place.exports : exportsOf(eff.exportSettings, drop);
924
1093
  if (exports)
925
1094
  common.exports = exports;
926
1095
  // The node's blend mode (an instance's applies to its expanded root, which takes this common record).
@@ -958,6 +1127,17 @@ function convert(doc, pages, options, explicit, expanded) {
958
1127
  const variant = (!asStored(frame, root.frame) && atVariantSize(frame, root, props, ctx.modes))
959
1128
  || (ctx.ovr.length > 0 && !!ctx.comps.at(-1)?.variant && [true, 'kept'].includes(ctx.comps.at(-1).definition));
960
1129
  const inner = { owner: props, comps: [...ctx.comps, { componentId: comp.id, props, definition: asStored(frame, root.frame) || variant, variant }], ovr, modes: ctx.modes, slots, keptLayout: ctx.keptLayout };
1130
+ const boxes = eff.componentId === n.componentId ? doc.instanceBoxes?.get(n.id) : undefined;
1131
+ const fills = eff.componentId === n.componentId ? doc.instanceFillSizes?.get(n.id) : undefined;
1132
+ const fillScope = fills && { boxes: fills, prefix: '', fillScale: 1 };
1133
+ if (boxes || fills || ctx.boxScopes) {
1134
+ const scopes = ctx.boxScopes?.map(scope => ({ ...scope, prefix: scope.prefix + n.id + ';' })) ?? [];
1135
+ if (boxes)
1136
+ scopes.push({ boxes, prefix: '' });
1137
+ if (fillScope)
1138
+ scopes.push(fillScope);
1139
+ inner.boxScopes = scopes;
1140
+ }
961
1141
  // The opacity stored on an instance is a copy of its variant root's when it equals that root's opacity in the
962
1142
  // stored variant; such a copy follows the variant an enclosing override or expression picks (p25's swatches
963
1143
  // disabled by an outer override), while a different value is the instance's own and is kept (p64's hidden check).
@@ -968,7 +1148,7 @@ function convert(doc, pages, options, explicit, expanded) {
968
1148
  if (eff.opacity !== undefined && (setOpacity || sameVariant || n.opacity !== storedOpacity(doc.nodes[target], stored, ctx.modes)))
969
1149
  inner.variantOpacity = { id: target, opacity: common.opacity };
970
1150
  note('instances expanded');
971
- const placed = { name: common.name, blendMode: eff.blendMode, exports, stored: root.frame, frame: { ...root.frame, ...frame, width: eff.width ?? frame.width, height: eff.height ?? frame.height, x: eff.x ?? frame.x, y: eff.y ?? frame.y }, rotation, sizing: eff.sizing, resizing: eff.resizing, layoutPositioning: eff.layoutPositioning, constraints: eff.constraints, variableModes: { ...n.variableModes, ...o.variableModes }, layer, ...(ownKeys.length ? { moved: ownKeys } : {}) };
1151
+ const placed = { name: common.name, blendMode: eff.blendMode, exports, stored: root.frame, frame: { ...root.frame, ...frame, width: eff.width ?? frame.width, height: eff.height ?? frame.height, x: eff.x ?? frame.x, y: eff.y ?? frame.y }, rotation, gridCell: eff.gridCell, sizing: eff.sizing, resizing: eff.resizing, layoutPositioning: eff.layoutPositioning, constraints: eff.constraints, variableModes: { ...n.variableModes, ...o.variableModes }, layer, ...(ownKeys.length ? { moved: ownKeys } : {}) };
972
1152
  if (ownKeys.length)
973
1153
  inner.moved = { id: target, style: Object.fromEntries(ownKeys.map((k) => [k, r.style?.[k]])) };
974
1154
  // A swapped component (an override or expression changed componentId) keeps the instance's size only when that
@@ -977,7 +1157,7 @@ function convert(doc, pages, options, explicit, expanded) {
977
1157
  // An instance on the page scaled with Figma's scale tool (and possibly resized), shown by its overrides
978
1158
  // (overrideScale): the overrides it scaled are taken back to the component's scale for the layout at size / s.
979
1159
  let scaled = 1;
980
- if (trials === 0 && !ctx.ovr.length && eff.componentId === n.componentId) {
1160
+ if (!boxes && trials === 0 && !ctx.ovr.length && eff.componentId === n.componentId) {
981
1161
  const { s, sure } = overrideScale(eff.overrides, comp, props, ctx.modes);
982
1162
  if (s !== 1) {
983
1163
  const unscaled = unscale(eff.overrides, s), resizing = unscale(placed.resizing, s);
@@ -1123,8 +1303,8 @@ function convert(doc, pages, options, explicit, expanded) {
1123
1303
  note('nested hug instances that follow kept line boxes');
1124
1304
  }
1125
1305
  }
1126
- let s = scaled !== 1 ? scaled : ctx.ovr.length || place?.trial ? 1 : instanceScale(root, parent, inner, placed, depth);
1127
- if (s === 1 && scaled === 1 && trials === 0 && !ctx.ovr.length && !place?.trial) {
1306
+ let s = scaled !== 1 ? scaled : boxes || ctx.ovr.length || place?.trial ? 1 : instanceScale(root, parent, inner, placed, depth);
1307
+ if (!boxes && s === 1 && scaled === 1 && trials === 0 && !ctx.ovr.length && !place?.trial) {
1128
1308
  // Scaled below 1 and resized, with no padding override: line heights that agree on one k (see lineHeightScale).
1129
1309
  const k = lineHeightScale(eff.overrides);
1130
1310
  if (k !== 1) {
@@ -1148,13 +1328,27 @@ function convert(doc, pages, options, explicit, expanded) {
1148
1328
  }
1149
1329
  const markInstance = (item) => {
1150
1330
  active.id = item.model.id;
1331
+ if (!kept && (n.flipX || n.flipY)) {
1332
+ // Reflect about the expanded root's local center, before its rotation and scale.
1333
+ const m = item.model, { x, y, width, height } = localBox(m);
1334
+ m.t = mul(m.t, [n.flipX ? -1 : 1, 0, 0, n.flipY ? -1 : 1,
1335
+ n.flipX ? 2 * x + width : 0, n.flipY ? 2 * y + height : 0]).map(v => +v.toFixed(6));
1336
+ }
1151
1337
  item.fromInstance = true;
1338
+ if (!probing)
1339
+ options.instanceSources?.set(item.model.id, n.id);
1152
1340
  if (explicit && eff.visible === false)
1153
1341
  item.model.visible = false;
1154
1342
  if (explicit && !doc.componentPlacements?.[n.id]) {
1155
1343
  item.model.fileInstance = n.id;
1156
1344
  if (n.slots?.[''])
1157
1345
  item.model.fileFills = Object.values(n.slots['']);
1346
+ // If an enclosing instance expands to a frame, its assignments must follow each surviving nested occurrence.
1347
+ if (nestedBooleans && full.propertyValues) {
1348
+ const assignments = Object.entries(full.propertyValues).filter((entry) => typeof entry[1] === 'boolean');
1349
+ if (assignments.length)
1350
+ nestedBooleans.set(item.model, { componentId: comp.id, values: Object.fromEntries(assignments) });
1351
+ }
1158
1352
  }
1159
1353
  if (doc.componentPlacements?.[n.id] === comp.id)
1160
1354
  item.model.mainOf = comp.id;
@@ -1163,12 +1357,14 @@ function convert(doc, pages, options, explicit, expanded) {
1163
1357
  markSet(item.model, comp, props);
1164
1358
  }
1165
1359
  };
1360
+ if (kept)
1361
+ placed.box = kept;
1166
1362
  if (s === 1) {
1167
1363
  const item = visit(root, parent, inner, placed, depth + 1);
1168
1364
  if (item) {
1169
- markInstance(item);
1170
1365
  if (kitFixes)
1171
1366
  topAlignTallInput(item, comp);
1367
+ markInstance(item);
1172
1368
  }
1173
1369
  return item;
1174
1370
  }
@@ -1177,23 +1373,45 @@ function convert(doc, pages, options, explicit, expanded) {
1177
1373
  ovr[0] = unscale(eff.overrides, s);
1178
1374
  // A scaled instance (Figma's scale tool): its contents are laid out at size / s and drawn scaled by s.
1179
1375
  note('instances scaled (scale inferred from their natural size)');
1180
- const item = visit(root, parent, inner, { ...placed, frame: { ...placed.frame, width: placed.frame.width / s, height: placed.frame.height / s } }, depth + 1);
1181
- if (item) {
1182
- if (kitFixes)
1183
- topAlignTallInput(item, comp);
1184
- for (let i = 0; i < 4; i++)
1185
- item.model.t[i] = +(item.model.t[i] * s).toFixed(6);
1186
- markInstance(item);
1376
+ const unscaledFrame = { ...placed.frame, width: placed.frame.width / s, height: placed.frame.height / s };
1377
+ if (fillScope)
1378
+ fillScope.fillScale = s;
1379
+ const item = visit(root, parent, inner, { ...placed, frame: unscaledFrame }, depth + 1);
1380
+ if (!item)
1381
+ return;
1382
+ if (kitFixes)
1383
+ topAlignTallInput(item, comp);
1384
+ const t = item.model.t;
1385
+ for (let i = 0; i < 4; i++)
1386
+ t[i] = +(t[i] * s).toFixed(6);
1387
+ if (!kept && rotation && (n.flipX || n.flipY)) {
1388
+ // Restore the rotation pivot of the placed box before reflecting the root.
1389
+ const full = transformOf(placed.frame, rotation), unscaled = transformOf(unscaledFrame, rotation);
1390
+ t[4] += full[4] - unscaled[4];
1391
+ t[5] += full[5] - unscaled[5];
1187
1392
  }
1393
+ markInstance(item);
1188
1394
  return item;
1189
1395
  }
1396
+ if (n.flipX || n.flipY)
1397
+ drop('layer flip');
1190
1398
  const f = { ...frame };
1191
1399
  for (const k of ['x', 'y', 'width', 'height'])
1192
1400
  if ((!place || ((place.trial || place.swapped) && k in (eff.variantSize ?? {}))) && eff[k] !== undefined)
1193
1401
  f[k] = eff[k];
1194
1402
  // A path follows its constraint in shapeNode, from its stored place (moved here too, it would move twice).
1195
- if (rs && !place && f.width !== undefined && n.shape !== 'path')
1196
- follow(f, eff.constraints, rs);
1403
+ if (kept && !kept.inner) {
1404
+ const [a, b, c, d, x, y] = kept.transform;
1405
+ const { width, height } = kept;
1406
+ Object.assign(f, { width, height, x: x + ((a - 1) * width + c * height) / 2, y: y + (b * width + (d - 1) * height) / 2 });
1407
+ }
1408
+ else {
1409
+ if (rs && !place && f.width !== undefined && n.shape !== 'path')
1410
+ follow(f, eff.constraints, rs);
1411
+ // A text Figma measured at its size there (`inner`) keeps that size, placed by its constraints.
1412
+ if (kept)
1413
+ Object.assign(f, { width: kept.width, height: kept.height });
1414
+ }
1197
1415
  // Absolute children follow constraints; auto-layout children are positioned below.
1198
1416
  // A size from the component's own expressions is the variant's size, which its children were placed in.
1199
1417
  const from = place?.stored ?? { ...frame, ...eff.variantSize }, free = !eff.layout || eff.layout.kind === 'absolute';
@@ -1208,12 +1426,28 @@ function convert(doc, pages, options, explicit, expanded) {
1208
1426
  if (n.type === 'group' && !(place?.constraints ?? eff.constraints) && transformOf(f, rotation).slice(0, 4).join() === '1,0,0,1') {
1209
1427
  mine = rs && { ...rs, at: [(rs.at?.[0] ?? 0) + (f.x ?? 0), (rs.at?.[1] ?? 0) + (f.y ?? 0)] };
1210
1428
  }
1211
- for (const k of ['fills', 'strokes', 'shadows', 'backgroundBlur', 'layerBlur', 'cornerRadii', 'cornerRadius'])
1429
+ for (const k of ['fills', 'strokes', 'shadows', 'backgroundBlur', 'layerBlur', 'cornerRadii', 'cornerRadius', 'cornerSmoothing'])
1212
1430
  if (eff[`style.${k}`] !== undefined)
1213
1431
  style[k] = eff[`style.${k}`];
1214
1432
  if (n.type === 'frame' || n.type === 'group') {
1215
- const m = { ...common, kind: 'frame', t: transformOf(f, rotation), w: f.width, h: f.height, clip: !!(eff.clipContent) };
1433
+ const m = { ...common, kind: 'frame', t: kept ? [...kept.transform] : transformOf(f, rotation), w: f.width, h: f.height, clip: !!(eff.clipContent) };
1434
+ // naturalSize only reads the trial root's dimensions. Children can size a hug frame
1435
+ // or a boolean group. An ordinary fixed frame only applies its layout minimums.
1436
+ if (file && L && place?.trial && n.type === 'frame' && !n.metadata?.figma?.boolean) {
1437
+ const node = { ...eff, sizing: { width: n.layout?.widthSizing, height: n.layout?.heightSizing },
1438
+ resizing: { ...eff.resizing, ...place.resizing } };
1439
+ const item = { model: m, node, children: [] };
1440
+ const fixed = (!node.layout || node.layout.kind === 'absolute') ||
1441
+ (sizingOf(node, 'width') !== 'hug' && sizingOf(node, 'height') !== 'hug');
1442
+ if (fixed && !L.children.some(containsInstance)) {
1443
+ layoutFrame(item);
1444
+ return item;
1445
+ }
1446
+ }
1216
1447
  appearance(m, style, 'frame', n.metadata?.figma);
1448
+ if (n.metadata?.figma?.strokesIncluded === true && (eff.layout && eff.layout.kind !== 'absolute')) {
1449
+ eff.layout = { ...eff.layout, strokesIncluded: true };
1450
+ }
1217
1451
  const r = radii(style);
1218
1452
  if (r)
1219
1453
  m.radius = r;
@@ -1225,6 +1459,13 @@ function convert(doc, pages, options, explicit, expanded) {
1225
1459
  m.group = true;
1226
1460
  note('groups marked as groups');
1227
1461
  }
1462
+ // A Figma boolean operation figma-import keeps live (metadata.figma.boolean, taco patch 0010) is a boolean group.
1463
+ const bool = n.type === 'frame' ? n.metadata?.figma?.boolean : undefined;
1464
+ if (bool && BOOLEAN_OPS.has(bool.operation)) {
1465
+ m.group = true;
1466
+ m.boolean = bool.operation;
1467
+ note('Figma boolean operations as boolean groups');
1468
+ }
1228
1469
  models.push(m);
1229
1470
  // The outermost instance that fills a slot wins, as an outer override does (p7 Autocomplete: the selected state's
1230
1471
  // search field fills its tag list with five tags; the tag list instance inside it fills the same slot with three).
@@ -1270,6 +1511,8 @@ function convert(doc, pages, options, explicit, expanded) {
1270
1511
  children.push(converted);
1271
1512
  }
1272
1513
  }
1514
+ if (n.type === 'group' && figma?.fillSizing)
1515
+ fitGroupFill(eff.resizing, m, children);
1273
1516
  const viewportTransform = n.metadata?.svgViewportTransform;
1274
1517
  if (viewportTransform)
1275
1518
  for (const { model } of children)
@@ -1284,7 +1527,60 @@ function convert(doc, pages, options, explicit, expanded) {
1284
1527
  else
1285
1528
  delete c.model.storedHeight;
1286
1529
  }
1287
- stretchLines(n, children);
1530
+ stretchLines(n, children, m, eff.layout?.strokesIncluded);
1531
+ // A boolean group fits its layers' boxes, as the editor's layout fits a group (layout.ts fitGroup), so that it
1532
+ // does not move them when the document loads. Its first result is the outline Figma stored for it (carried in the
1533
+ // operation's own space), as the path it was flattened to (resized with its constraints in a resized instance, as
1534
+ // that path was), moved into the fitted group's space, so it draws as that path did. The renderer recuts it
1535
+ // when an instance changes an operand through overrides, properties or stored geometry.
1536
+ if (m.boolean) {
1537
+ const own = bool.fixedBox ? { t: m.t, w: m.w, h: m.h } : undefined;
1538
+ const kids = children.map((c) => c.model).filter(Boolean), boxes = kids.map((k) => box(k));
1539
+ if (boxes.length) {
1540
+ const x = Math.min(...boxes.map((b) => b[0])), y = Math.min(...boxes.map((b) => b[1]));
1541
+ for (const k of kids) {
1542
+ k.t = [...k.t.slice(0, 4), k.t[4] - x, k.t[5] - y];
1543
+ // Restore the stored box in the fitted group's coordinates after layout.
1544
+ const saved = keptGeometry.get(k);
1545
+ if (saved) {
1546
+ saved.t[4] = saved.t[4] - x;
1547
+ saved.t[5] = saved.t[5] - y;
1548
+ }
1549
+ }
1550
+ m.t = mul(m.t, [1, 0, 0, 1, x, y]);
1551
+ m.w = Math.max(...boxes.map((b) => b[2])) - x;
1552
+ m.h = Math.max(...boxes.map((b) => b[3])) - y;
1553
+ }
1554
+ const reshaped = (id) => doc.nodes[id]?.children?.some((c) => ctx.ovr?.some((o) => Object.keys(o?.[c] ?? {}).some((k) => !LOOK_ONLY.has(k)))
1555
+ || (ctx.comps?.length && (doc.nodes[c]?.condition !== undefined || Object.keys(doc.nodes[c]?.expressions ?? {}).some((k) => !LOOK_ONLY.has(k)))) || reshaped(c)) ?? false;
1556
+ const hasStoredOperand = (item) => keptGeometry.has(item.model) || item.children.some(hasStoredOperand);
1557
+ const recut = !!bool.vectorNetwork && (reshaped(n.id) || (ctx.boxScopes && children.some(hasStoredOperand)));
1558
+ if (recut)
1559
+ note('Figma boolean operations an instance reshapes, cut by the renderer rather than drawn from their stored outline');
1560
+ if (bool.vectorNetwork && bool.transform && frame && (rs || !mine) && !recut) {
1561
+ const before = models.length;
1562
+ const flat = shapeNode({ type: 'shape', shape: 'path', vectorNetwork: bool.vectorNetwork, transform: mul(transformOf(frame, rotation), bool.transform) }, { constraints: eff.constraints, aspectRatioLocked: eff.aspectRatioLocked, aspectRatio: eff.aspectRatio }, { id: 'outline' }, {}, 0, {}, rs);
1563
+ models.length = before; // scratch geometry, not a layer
1564
+ if (flat?.kind === 'path')
1565
+ m.result = transformNet(flat.net, mul(inv(m.t), flat.t));
1566
+ }
1567
+ // One with no stored outline in an auto layout flow, whose operands do not fill its box (figma-import's
1568
+ // `fixedBox`), sits in a plain frame of the operation's own box, so the flow places its siblings as Figma did.
1569
+ if (bool.fixedBox && !m.result && own) {
1570
+ const inner = { id: newId(), parent: m.id, name: m.name, opacity: 1, kind: 'frame', t: mul(inv(own.t), m.t), w: m.w, h: m.h, clip: false };
1571
+ for (const k of BOOLEAN_OWN)
1572
+ if (k in m) {
1573
+ inner[k] = m[k];
1574
+ delete m[k];
1575
+ }
1576
+ for (const k of kids)
1577
+ k.parent = inner.id;
1578
+ Object.assign(m, own);
1579
+ models.splice(models.indexOf(m) + 1, 0, inner);
1580
+ wrappedBoolean.set(m, inner);
1581
+ note('Figma boolean operations with no stored outline kept at their own size in a flow, in a plain frame');
1582
+ }
1583
+ }
1288
1584
  // A trial layout (instanceScale) or a swapped component sizes the root as its component does, except that a
1289
1585
  // swapped instance filling its parent keeps filling it (Figma keeps the slot's fill across a swap: p7
1290
1586
  // Autocomplete's search field fills its 248 px list box instead of hugging its component's 280 px; p0 Cover menu
@@ -1305,6 +1601,9 @@ function convert(doc, pages, options, explicit, expanded) {
1305
1601
  note('hug frames around stale-box text kept inside instances stored shorter than their contents');
1306
1602
  }
1307
1603
  m.layoutData = layoutData(item.node, item.instance);
1604
+ const flow = m.layoutData.layout?.kind;
1605
+ if (n.type === 'frame' && n.metadata?.figma?.firstOnTop === true && (flow && flow !== 'absolute'))
1606
+ m.firstOnTop = true;
1308
1607
  // Figma lays out again an instance it re-hugs, nested instances and all, and stores the result: where the stored
1309
1608
  // main-axis size is not what its children's stored sizes add up to, the nested ones were laid out anew and the
1310
1609
  // editor must not hold them at their stored sizes either (`relaid`, scene.ts fit; p67 TextField fields are 88 px
@@ -1315,7 +1614,7 @@ function convert(doc, pages, options, explicit, expanded) {
1315
1614
  const lay = item.node.layout, axis = lay?.kind === 'horizontal' ? 'w' : 'h';
1316
1615
  if (item.instance && ['horizontal', 'vertical'].includes(lay?.kind) && !lay.wrap && [undefined, 'start', 'center', 'end'].includes(lay.justify) && lay[axis === 'w' ? 'widthSizing' : 'heightSizing'] === 'hug' && (item.remeasured || !wrapped(item))) {
1317
1616
  const flowing = children.filter((c) => c.model && c.node.visible !== false && c.node.layoutPositioning !== 'absolute');
1318
- const pad = { top: 0, right: 0, bottom: 0, left: 0, ...lay.padding, ...item.node.padding };
1617
+ const pad = commands.insetsIn(m);
1319
1618
  const sum = flowing.reduce((t, c) => t + c.model[axis], 0) + (lay.gap ?? 0) * Math.max(0, flowing.length - 1) + (axis === 'w' ? pad.left + pad.right : pad.top + pad.bottom);
1320
1619
  if (flowing.length && (item.remeasured ? Math.abs(sum - m[axis]) : sum - m[axis]) > 0.5) {
1321
1620
  m.layoutData.relaid = true;
@@ -1339,10 +1638,14 @@ function convert(doc, pages, options, explicit, expanded) {
1339
1638
  unfreeze(item);
1340
1639
  }
1341
1640
  }
1641
+ if ((flow === 'horizontal' || flow === 'vertical') && children.some(({ model }) => storedFillSizes.has(model) &&
1642
+ (model.layoutData?.resizing?.width === 'fill' || model.layoutData?.resizing?.height === 'fill'))) {
1643
+ stacksWithStoredFill.push(item);
1644
+ }
1342
1645
  const variant = wrapped(item);
1343
1646
  if (variant)
1344
- wrappers.push([m, variant.model, { top: 0, right: 0, bottom: 0, left: 0, ...item.node.layout.padding, ...item.node.padding }]);
1345
- layoutFrame(item);
1647
+ wrappers.push([m, variant.model, commands.insetsIn(m)]);
1648
+ layoutFrame(item, kept && !m.group ? { width: kept.width, height: kept.height } : undefined);
1346
1649
  // A hug frame stored as resizing 'fixed' hugs here, but where hugging gives back its stored size the editor keeps
1347
1650
  // that size: a later re-measure (of text, say) must not move what already matches Figma. A frame holding text an
1348
1651
  // override changed (which the editor measures) still hugs, as Figma re-hugs it: p73's "Bold", "Italic" and
@@ -1350,7 +1653,7 @@ function convert(doc, pages, options, explicit, expanded) {
1350
1653
  // keeps an instance root at its placed size, so what hugging gives back is its children's extent (p75 Overview
1351
1654
  // Cards: a 60 px stored body whose texts hug to 52 re-hugs, as Figma did).
1352
1655
  for (const [axis, key] of [['width', 'w'], ['height', 'h']]) {
1353
- if (item.node.sizing?.[axis] === undefined && item.node.resizing?.[axis] === 'fixed' && item.node.layout?.[`${axis}Sizing`] === 'hug' && Math.abs((item.instance ? hugged(item, axis) ?? m[key] : m[key]) - f[axis]) < 0.01 && !item.remeasured) {
1656
+ if (flow !== 'grid' && item.node.sizing?.[axis] === undefined && item.node.resizing?.[axis] === 'fixed' && item.node.layout?.[`${axis}Sizing`] === 'hug' && Math.abs((item.instance ? hugged(item, axis) ?? m[key] : m[key]) - f[axis]) < 0.01 && !item.remeasured) {
1354
1657
  m.layoutData.sizing = { ...m.layoutData.sizing, [axis]: 'fixed' };
1355
1658
  (item.frozen ??= []).push(axis);
1356
1659
  }
@@ -1363,7 +1666,7 @@ function convert(doc, pages, options, explicit, expanded) {
1363
1666
  const main = lay?.kind === 'horizontal' ? 'width' : 'height';
1364
1667
  const hugAxes = ['width', 'height'].filter((axis) => (item.node.sizing?.[axis] ?? lay?.[`${axis}Sizing`]) === 'hug');
1365
1668
  const fromStart = hugAxes.every((axis) => [undefined, 'start'].includes(axis === main ? lay?.justify : lay?.align));
1366
- if (!ctx.comps.length && !place && hugAxes.length && fromStart) {
1669
+ if (flow !== 'grid' && !ctx.comps.length && !place && hugAxes.length && fromStart) {
1367
1670
  m.keepSize = true;
1368
1671
  if (Math.abs(m.w - f.width) > 0.01 || Math.abs(m.h - f.height) > 0.01)
1369
1672
  approximate('page-level hug frames laid out at other than their stored size');
@@ -1373,24 +1676,33 @@ function convert(doc, pages, options, explicit, expanded) {
1373
1676
  // The visual frame a hug wrapper root gave that kept height holds it too (layoutFrame's wrapper allocation); a
1374
1677
  // component swapped in there takes its own size.
1375
1678
  if (place?.keepHeight && !children[0]?.swapped && eff.layout?.kind === 'vertical' && eff.layout.heightSizing === 'hug' && children.length === 1 && ['horizontal', 'vertical'].includes(children[0].model.layoutData?.layout?.kind)) {
1376
- const p = eff.layout?.padding ?? {};
1377
- resize(children[0], { height: Math.max(0, m.h - (p.top ?? 0) - (p.bottom ?? 0)) });
1679
+ const p = commands.insetsIn(m);
1680
+ resize(children[0], { height: Math.max(0, m.h - p.top - p.bottom) });
1378
1681
  children[0].model.layoutData.sizing = { ...children[0].model.layoutData.sizing, height: 'fixed' };
1379
1682
  }
1380
1683
  applyMasks(m, children);
1381
1684
  return item;
1382
1685
  }
1383
1686
  if (n.type === 'text') {
1384
- const model = textNode(n, L ? { ...eff, ...resolvedText(r, full, eff, copiedColours) } : eff, o, common, f, rotation, style);
1687
+ const model = textNode(n, L ? { ...eff, ...resolvedText(r, full, eff, copiedColours) } : eff, o, common, f, rotation, style, ctx.modes);
1688
+ if (kept) {
1689
+ if (!kept.inner)
1690
+ model.t = [...kept.transform];
1691
+ model.h = kept.height;
1692
+ if (model.autoResize)
1693
+ model.keepSize = true;
1694
+ delete model.storedHeight;
1695
+ }
1385
1696
  model.layoutData = layoutData(eff);
1386
1697
  const stored = (n.paragraphs ?? []).map((p) => (p.runs ?? []).map((r) => r.text ?? '').join('')).join('\n');
1387
1698
  return { model, node: eff, children: [], changedText: eff.autoResize === 'width-and-height' && model.content !== stored };
1388
1699
  }
1389
1700
  if (n.type === 'shape') {
1390
- const model = shapeNode(n, eff, common, f, rotation, style, rs);
1701
+ const children = [];
1702
+ const model = shapeNode(n, eff, common, f, rotation, style, kept ? null : rs, kept, children);
1391
1703
  if (model)
1392
1704
  model.layoutData = { ...layoutData(eff), ...model.layoutData };
1393
- return model ? { model, node: eff, children: [] } : undefined;
1705
+ return model ? { model, node: eff, children } : undefined;
1394
1706
  }
1395
1707
  drop(`node type ${n.type}`);
1396
1708
  }
@@ -1398,12 +1710,13 @@ function convert(doc, pages, options, explicit, expanded) {
1398
1710
  // auto-layout row or column that spans the frame's whole stored inner cross size is a stretched divider: it fills the
1399
1711
  // cross axis, so it shortens with added padding (p73 ToggleButtonGroup dividers: 32 px stored, 20 px in Figma once the
1400
1712
  // group pads them by 10 px).
1401
- function stretchLines(n, children) {
1713
+ function stretchLines(n, children, model, strokesIncluded) {
1402
1714
  const layout = n.layout;
1403
1715
  if (!['horizontal', 'vertical'].includes(layout?.kind) || layout.wrap || !n.frame)
1404
1716
  return;
1405
1717
  const [cross, main] = layout.kind === 'horizontal' ? ['height', 'width'] : ['width', 'height'];
1406
- const p = { top: 0, right: 0, bottom: 0, left: 0, ...layout.padding };
1718
+ const p = strokesIncluded ? commands.insetsIn({ ...model, layoutData: { layout: { ...layout, strokesIncluded } } })
1719
+ : { top: 0, right: 0, bottom: 0, left: 0, ...layout.padding };
1407
1720
  const inner = n.frame[cross] - (cross === 'height' ? p.top + p.bottom : p.left + p.right);
1408
1721
  for (const child of children) {
1409
1722
  if (child.model.kind !== 'path' || child.node.resizing || child.node.layoutPositioning === 'absolute')
@@ -1486,7 +1799,7 @@ function convert(doc, pages, options, explicit, expanded) {
1486
1799
  const [a, b, cc, d] = c.model.t;
1487
1800
  return axis === 'width' ? Math.abs(a) * c.model.w + Math.abs(cc) * c.model.h : Math.abs(b) * c.model.w + Math.abs(d) * c.model.h;
1488
1801
  };
1489
- const p = { top: 0, right: 0, bottom: 0, left: 0, ...layout.padding, ...item.node.padding };
1802
+ const p = commands.insetsIn(item.model);
1490
1803
  const pad = axis === 'width' ? p.left + p.right : p.top + p.bottom, sizes = kids.map(box);
1491
1804
  const along = (layout.kind === 'horizontal') === (axis === 'width');
1492
1805
  return pad + (along ? sizes.reduce((x, y) => x + y, 0) + (layout.gap ?? 0) * (kids.length - 1) : Math.max(...sizes));
@@ -1509,7 +1822,9 @@ function convert(doc, pages, options, explicit, expanded) {
1509
1822
  return o.textStyle?.lineHeight !== undefined;
1510
1823
  if (key === 'padding')
1511
1824
  return o.padding !== undefined || o.layout?.padding !== undefined;
1512
- if (['gap', 'align', 'justify'].includes(key))
1825
+ if (key === 'direction' || key === 'layout.kind')
1826
+ return o.layout?.kind !== undefined;
1827
+ if (['gap', 'columnGap', 'rowGap', 'align', 'justify', 'wrap', 'wrapGap'].includes(key))
1513
1828
  return o.layout?.[key] !== undefined;
1514
1829
  if (key === 'layout.widthSizing' || key === 'resizing.width')
1515
1830
  return o.sizing?.width !== undefined;
@@ -1669,6 +1984,10 @@ function convert(doc, pages, options, explicit, expanded) {
1669
1984
  eff.characters = v;
1670
1985
  return;
1671
1986
  }
1987
+ if ((key === 'startCap' || key === 'endCap') && STROKE_CAPS.includes(v)) {
1988
+ eff[key] = v;
1989
+ return;
1990
+ }
1672
1991
  if (key === 'fontFamily' && typeof v === 'string') {
1673
1992
  eff.fontFamily = v;
1674
1993
  return;
@@ -1702,7 +2021,7 @@ function convert(doc, pages, options, explicit, expanded) {
1702
2021
  eff['style.cornerRadii'] = num ? { topLeft: v, topRight: v, bottomRight: v, bottomLeft: v } : v;
1703
2022
  return;
1704
2023
  }
1705
- if (['gap', 'padding', 'align', 'justify', 'direction'].includes(key)) {
2024
+ if (['gap', 'columnGap', 'rowGap', 'padding', 'align', 'justify', 'direction'].includes(key)) {
1706
2025
  // Expressions spell the stored 'space-between' as the enum case .space_between.
1707
2026
  if (key === 'justify' && v === 'space_between')
1708
2027
  v = 'space-between';
@@ -1731,14 +2050,27 @@ function convert(doc, pages, options, explicit, expanded) {
1731
2050
  }
1732
2051
  return style.cornerRadius > 0 ? style.cornerRadius : null;
1733
2052
  }
2053
+ // Older Taco records can store a CSS angle in place of linear gradient endpoints.
2054
+ const paintInBox = (p, m) => p?.kind === 'linear-gradient' && !p.from && !p.to && Number.isFinite(p.angle ?? 180)
2055
+ ? { ...p, ...linearEndpoints(p.angle ?? 180, localBox(m)) } : resolveLinearCall(p, () => localBox(m));
2056
+ function fillPaint(p, tile, m, cropLayerBox, cropPaintBox) {
2057
+ const converted = paint(paintInBox(p, m), tile);
2058
+ const crop = (converted?.k === 'image' || converted?.k === 'video') && imageCropOf(p);
2059
+ if (!crop)
2060
+ return converted;
2061
+ const placement = imageCropPlacement(crop, cropPaintBox ?? localBox(m), cropLayerBox);
2062
+ if (placement)
2063
+ return { ...converted, ...placement };
2064
+ approximate('image crop cannot be represented by the paint transform');
2065
+ return converted;
2066
+ }
1734
2067
  // Fills, the first stroke and effects. One shown solid fill goes in the compact record; anything more in look.fills.
1735
2068
  // carried: what figma-import carries in the node's metadata.figma (taco/figma-import/import/carry.ts), whose fill and
1736
2069
  // shadow indexes are into the node's own style lists.
1737
- function appearance(m, style, kind, carried = {}) {
2070
+ function appearance(m, style, kind, carried = {}, cropLayerBox) {
1738
2071
  const tiles = new Map(Array.isArray(carried.tiles) ? carried.tiles : []);
1739
- const inBox = (p) => resolveLinearCall(p, () => localBox(m));
1740
- const fills = (style.fills ?? []).map((p, i) => paint(inBox(p), tiles.get(i))).filter(Boolean), look = {};
1741
- if (fills.length === 1 && fills[0].k === 'solid' && fills[0].o === 1 && fills[0].visible !== false)
2072
+ const fills = (style.fills ?? []).map((p, i) => fillPaint(p, tiles.get(i), m, cropLayerBox)).filter(Boolean), look = {};
2073
+ if (fills.length === 1 && fills[0].k === 'solid' && fills[0].o === 1 && fills[0].visible !== false && !fills[0].blend)
1742
2074
  m.fill = fills[0].c;
1743
2075
  else if (fills.length)
1744
2076
  look.fills = fills;
@@ -1748,25 +2080,25 @@ function convert(doc, pages, options, explicit, expanded) {
1748
2080
  note('tiled image fills');
1749
2081
  const strokes = (style.strokes ?? []).filter((s) => s.paint?.visible !== false && (s.width > 0 || s.fileBoundWidth && s.width === 0));
1750
2082
  if (strokes.length) {
1751
- const s = strokes[0], p = paint(inBox(s.paint));
2083
+ const s = strokes[0], p = paint(paintInBox(s.paint, m));
1752
2084
  if (strokes.length > 1)
1753
2085
  drop('additional strokes', strokes.length - 1);
1754
2086
  if (p) {
1755
2087
  m.stroke = p.k === 'solid' ? p.c : [0, 0, 0, 1];
1756
2088
  m.strokeWidth = s.width;
1757
2089
  const st = { position: { center: 0, inside: 1, outside: 2 }[s.position] ?? 0, join: { miter: 0, bevel: 1, round: 2 }[s.join] ?? null, cap: { none: 0, round: 1, square: 2 }[s.dashCap] ?? 0 };
1758
- if (p.k !== 'solid' || p.o !== 1) {
2090
+ if (p.k !== 'solid' || p.o !== 1 || p.blend) {
1759
2091
  st.paint = p;
1760
2092
  if (p.k !== 'solid')
1761
- note(`sent: ${p.k}${p.k === 'image' ? '' : ' gradient'} strokes`);
2093
+ note(`sent: ${p.k}${p.k === 'image' || p.k === 'video' ? '' : ' gradient'} strokes`);
1762
2094
  }
1763
2095
  if (s.dash?.length)
1764
2096
  st.dash = s.dash;
1765
- // Per-side weights (strokeTopWeight etc.). The scene keeps them on containers only; on a path, equal sides are
2097
+ // The scene keeps side weights on containers, including native rectangles. On a path, equal sides are
1766
2098
  // its stroke width (all 398 path cases in the kit: checkbox bases at 1 px on every side), unequal ones are dropped.
1767
2099
  if (s.sides) {
1768
2100
  const v = [s.sides.top, s.sides.right, s.sides.bottom, s.sides.left].map((x) => x ?? 0);
1769
- if (kind === 'frame')
2101
+ if (kind === 'frame' || kind === 'rect')
1770
2102
  st.sides = v;
1771
2103
  else if (v.every((x) => x === v[0])) {
1772
2104
  m.strokeWidth = v[0];
@@ -1798,7 +2130,7 @@ function convert(doc, pages, options, explicit, expanded) {
1798
2130
  look.backgroundBlur = { radius: style.backgroundBlur };
1799
2131
  for (const p of fills)
1800
2132
  if (p.k !== 'solid')
1801
- note(`sent: ${p.k}${p.k === 'image' ? '' : ' gradient'} fills`);
2133
+ note(`sent: ${p.k}${p.k === 'image' || p.k === 'video' ? '' : ' gradient'} fills`);
1802
2134
  if (shadows.length)
1803
2135
  note('sent: nodes with shadows');
1804
2136
  if (look.layerBlur)
@@ -1827,10 +2159,64 @@ function convert(doc, pages, options, explicit, expanded) {
1827
2159
  axis(c.horizontal, 'x', 'width', rs.dw, rs.sx, rs.at?.[0] ?? 0);
1828
2160
  axis(c.vertical, 'y', 'height', rs.dh, rs.sy, rs.at?.[1] ?? 0);
1829
2161
  }
1830
- function shapeNode(n, eff, common, f, rotation, style, rs) {
1831
- let net, t, box, shape, regionFills = [];
2162
+ // The renderer samples region images in the union of the regions' bounds, excluding unfilled edges and vertices.
2163
+ function regionImageBox(net) {
2164
+ const ids = new Set();
2165
+ for (const region of net.regions ?? [])
2166
+ for (const loop of region.loops)
2167
+ for (const [id] of loop.refs)
2168
+ ids.add(id);
2169
+ const segments = net.segments.filter(s => ids.has(s.id));
2170
+ const endpoints = new Set(segments.flatMap(s => [s.a, s.b]));
2171
+ return netBounds({ vertices: net.vertices.filter(v => endpoints.has(v.id)), segments });
2172
+ }
2173
+ // A component's vector network is read once for every layer that shows it: instances and the trial layouts that size
2174
+ // them convert the same source many times. Converted networks are values that layout and linking replace, never edit.
2175
+ const sharedNets = new Map();
2176
+ function pathNet(vn) {
2177
+ const r4 = (x) => (Number.isInteger(x) ? x : +x.toFixed(4)) || 0;
2178
+ let at;
2179
+ // An elliptical arc (svg-import keeps SVG's) becomes cubics of at most 90 degrees, through new vertices; its id
2180
+ // stands for them all in the regions' loops (`parts`).
2181
+ const vertices = vn.vertices.map((v) => ({ id: v.id, x: r4(v.x), y: r4(v.y) })), segments = [], parts = new Map();
2182
+ let arcs = 0, lostSegments = 0;
2183
+ for (const s of vn.segments) {
2184
+ if (s.kind === 'elliptical-arc')
2185
+ at ??= new Map(vn.vertices.map((v) => [v.id, [v.x, v.y]]));
2186
+ if (s.kind === 'elliptical-arc' && at?.has(s.start) && at.has(s.end)) {
2187
+ const { points, handles } = arcCubics(at.get(s.start), at.get(s.end), s.radiusX, s.radiusY, s.xAxisRotation ?? 0, !!s.largeArc, !!s.sweep);
2188
+ if (handles.length) {
2189
+ arcs++;
2190
+ const ids = points.map((_, i) => `${s.id}~v${i + 1}`);
2191
+ points.forEach(([x, y], i) => vertices.push({ id: ids[i], x: r4(x), y: r4(y) }));
2192
+ const ends = [s.start, ...ids, s.end], own = handles.map((_, i) => (i ? `${s.id}~${i}` : s.id));
2193
+ handles.forEach(([ha, hb], i) => segments.push({ id: own[i], a: ends[i], b: ends[i + 1], ha: ha.map(r4), hb: hb.map(r4) }));
2194
+ parts.set(s.id, own);
2195
+ continue;
2196
+ }
2197
+ }
2198
+ else if (s.kind !== 'line' && s.kind !== 'cubic')
2199
+ lostSegments++;
2200
+ segments.push({ id: s.id, a: s.start, b: s.end, ha: s.kind === 'cubic' ? [s.startHandle.dx, s.startHandle.dy].map(r4) : [0, 0], hb: s.kind === 'cubic' ? [s.endHandle.dx, s.endHandle.dy].map(r4) : [0, 0] });
2201
+ }
2202
+ const seg = new Map(segments.map((s) => [s.id, s]));
2203
+ const regions = (vn.regions ?? []).filter((r) => r.loops.length);
2204
+ const outlines = regions.map((r) => ({ w: r.windingRule === 'evenodd' ? 1 : 0, loops: r.loops.map((l) => {
2205
+ const refs = l.segments.flatMap((x) => {
2206
+ const rev = x.direction === 'reverse', ids = parts.get(x.segmentId) ?? [x.segmentId];
2207
+ return (rev ? [...ids].reverse() : ids).map((id) => [id, rev]);
2208
+ });
2209
+ const end = ([id, rev]) => (rev ? seg.get(id).a : seg.get(id).b), start = ([id, rev]) => (rev ? seg.get(id).b : seg.get(id).a);
2210
+ return { refs, open: start(refs[0]) !== end(refs[refs.length - 1]) };
2211
+ }) }));
2212
+ return { vertices, segments, next: vertices.length + segments.length, regions: outlines, fills: regions.map((r) => r.fills), lostSegments, arcs };
2213
+ }
2214
+ function shapeNode(n, eff, common, f, rotation, style, rs, kept, children) {
2215
+ let net, t, box, shape;
2216
+ let regionFills = [];
2217
+ let cropLayerBox;
1832
2218
  if (explicit && n.shape === 'rectangle') {
1833
- const m = { ...common, kind: 'rect', t: transformOf(f, rotation), w: f.width, h: f.height, radius: radii(style) ?? 0 };
2219
+ const m = { ...common, kind: 'rect', t: kept ? [...kept.transform] : transformOf(f, rotation), w: f.width, h: f.height, radius: radii(style) ?? 0 };
1834
2220
  if (style.cornerSmoothing)
1835
2221
  m.smoothing = style.cornerSmoothing;
1836
2222
  appearance(m, style, 'rect', n.metadata?.figma);
@@ -1838,44 +2224,31 @@ function convert(doc, pages, options, explicit, expanded) {
1838
2224
  return m;
1839
2225
  }
1840
2226
  if (n.shape === 'path') {
1841
- const vn = n.vectorNetwork, r4 = (x) => +x.toFixed(4) || 0;
1842
- const at = new Map(vn.vertices.map((v) => [v.id, [v.x, v.y]]));
1843
- // An elliptical arc (svg-import keeps SVG's) becomes cubics of at most 90 degrees, through new vertices; its id
1844
- // stands for them all in the regions' loops (`parts`).
1845
- const vertices = vn.vertices.map((v) => ({ id: v.id, x: r4(v.x), y: r4(v.y) })), segments = [], parts = new Map();
1846
- let arcs = 0;
1847
- for (const s of vn.segments) {
1848
- if (s.kind === 'elliptical-arc' && at.has(s.start) && at.has(s.end)) {
1849
- const { points, handles } = arcCubics(at.get(s.start), at.get(s.end), s.radiusX, s.radiusY, s.xAxisRotation ?? 0, !!s.largeArc, !!s.sweep);
1850
- if (handles.length) {
1851
- arcs++;
1852
- const ids = points.map((_, i) => `${s.id}~v${i + 1}`);
1853
- points.forEach(([x, y], i) => vertices.push({ id: ids[i], x: r4(x), y: r4(y) }));
1854
- const ends = [s.start, ...ids, s.end], own = handles.map((_, i) => (i ? `${s.id}~${i}` : s.id));
1855
- handles.forEach(([ha, hb], i) => segments.push({ id: own[i], a: ends[i], b: ends[i + 1], ha: ha.map(r4), hb: hb.map(r4) }));
1856
- parts.set(s.id, own);
1857
- continue;
1858
- }
2227
+ const vn = n.vectorNetwork;
2228
+ const shared = sharedNets.get(vn) ?? pathNet(vn);
2229
+ sharedNets.set(vn, shared);
2230
+ for (let k = 0; k < shared.lostSegments; k++)
2231
+ drop('path segment kind');
2232
+ if (shared.arcs)
2233
+ approximate('elliptical arcs split into cubics');
2234
+ // Each model owns its network and region records (region fills are its own); the geometry is shared.
2235
+ net = { vertices: shared.vertices, segments: shared.segments, loops: [], next: shared.next,
2236
+ regions: shared.regions.map(({ w, loops }) => ({ w, loops })) };
2237
+ regionFills = shared.fills;
2238
+ t = (kept?.transform ?? eff.exprTransform ?? n.transform ?? [1, 0, 0, 1, f.x ?? 0, f.y ?? 0]).map((v) => +v.toFixed(6));
2239
+ if (kept?.pathScale) {
2240
+ let [sx, sy] = kept.pathScale;
2241
+ // Free-layout boxes can also describe a flow child in a nested stack.
2242
+ if ((sx === 0 && eff.resizing?.width === 'fill') || (sy === 0 && eff.resizing?.height === 'fill')) {
2243
+ const bounds = pathBounds({ t, net });
2244
+ if (sx === 0 && eff.resizing?.width === 'fill' && bounds.width)
2245
+ sx = 1e-3 / bounds.width;
2246
+ if (sy === 0 && eff.resizing?.height === 'fill' && bounds.height)
2247
+ sy = 1e-3 / bounds.height;
1859
2248
  }
1860
- else if (s.kind !== 'line' && s.kind !== 'cubic')
1861
- drop('path segment kind');
1862
- segments.push({ id: s.id, a: s.start, b: s.end, ha: s.kind === 'cubic' ? [s.startHandle.dx, s.startHandle.dy].map(r4) : [0, 0], hb: s.kind === 'cubic' ? [s.endHandle.dx, s.endHandle.dy].map(r4) : [0, 0] });
2249
+ if (sx !== 1 || sy !== 1)
2250
+ net = transformNet(net, [sx, 0, 0, sy, 0, 0]);
1863
2251
  }
1864
- if (arcs)
1865
- approximate('elliptical arcs split into cubics');
1866
- net = { vertices, segments, loops: [], next: vertices.length + segments.length };
1867
- const seg = new Map(net.segments.map((s) => [s.id, s]));
1868
- const kept = (vn.regions ?? []).filter((r) => r.loops.length);
1869
- net.regions = kept.map((r) => ({ w: r.windingRule === 'evenodd' ? 1 : 0, loops: r.loops.map((l) => {
1870
- const refs = l.segments.flatMap((x) => {
1871
- const rev = x.direction === 'reverse', ids = parts.get(x.segmentId) ?? [x.segmentId];
1872
- return (rev ? [...ids].reverse() : ids).map((id) => [id, rev]);
1873
- });
1874
- const end = ([id, rev]) => (rev ? seg.get(id).a : seg.get(id).b), start = ([id, rev]) => (rev ? seg.get(id).b : seg.get(id).a);
1875
- return { refs, open: start(refs[0]) !== end(refs[refs.length - 1]) };
1876
- }) }));
1877
- regionFills = kept.map((r) => r.fills);
1878
- t = (eff.exprTransform ?? n.transform ?? [1, 0, 0, 1, f.x ?? 0, f.y ?? 0]).map((v) => +v.toFixed(6));
1879
2252
  // A path has no frame: its network scales under a scale or stretch constraint, and its translation moves with
1880
2253
  // the constraint. A stretched path keeps its outline's near edge, which is not its translation when it is turned
1881
2254
  // or its outline does not start at its origin. As in host-layout's resize, a path squeezed to nothing keeps a
@@ -1918,19 +2291,20 @@ function convert(doc, pages, options, explicit, expanded) {
1918
2291
  // A Figma STAR or REGULAR_POLYGON (figma-import carries its parameters, metadata.figma.shape) is the parametric
1919
2292
  // polygon or star (core/shapes.ts) in its box, as Figma draws it: outer points on the box's ellipse, from the top.
1920
2293
  // A rounded one, or one resized with its parent, keeps Figma's outline.
1921
- const sp = n.metadata?.figma?.shape;
1922
- if ((sp?.type === 'polygon' || sp?.type === 'star') && sp.width > 0 && sp.height > 0 && !rs && !(style.cornerRadius > 0)) {
2294
+ const sp = n.metadata?.figma?.shape, width = kept?.width ?? sp?.width, height = kept?.height ?? sp?.height;
2295
+ if ((sp?.type === 'polygon' || sp?.type === 'star') && width > 0 && height > 0 && !rs && !(style.cornerRadius > 0)
2296
+ && regionFills.every(fills => fills === undefined)) {
1923
2297
  const count = Math.min(60, Math.max(3, Math.round(sp.count)));
1924
2298
  shape = sp.type === 'star' ? { type: 'star', count, ratio: Math.min(1, Math.max(0, sp.ratio ?? 0.382)) } : { type: 'polygon', count };
1925
- net = shapes.shapeNet(shape, { x: 0, y: 0, width: sp.width, height: sp.height });
1926
- box = pathBounds({ t, net: network([[0, 0], [sp.width, 0], [sp.width, sp.height], [0, sp.height]], true) });
1927
- regionFills = [];
2299
+ cropLayerBox = { x: 0, y: 0, width, height };
2300
+ net = shapes.shapeNet(shape, cropLayerBox);
2301
+ box = pathBounds({ t, net: network([[0, 0], [width, 0], [width, height], [0, height]], true) });
1928
2302
  note('Figma stars and polygons drawn as parametric shapes');
1929
2303
  }
1930
2304
  }
1931
2305
  else {
1932
2306
  const w = f.width, h = f.height;
1933
- t = transformOf(f, rotation);
2307
+ t = kept ? [...kept.transform] : transformOf(f, rotation);
1934
2308
  if (n.shape === 'rectangle')
1935
2309
  net = network([[0, 0], [w, 0], [w, h], [0, h]], true);
1936
2310
  else if (n.shape === 'line')
@@ -1940,7 +2314,8 @@ function convert(doc, pages, options, explicit, expanded) {
1940
2314
  net = ellipseNetwork(w, h);
1941
2315
  const a = n.arc, lo = Math.min(a?.startingAngle ?? 0, a?.endingAngle ?? 360), hi = Math.max(a?.startingAngle ?? 0, a?.endingAngle ?? 360);
1942
2316
  const whole = !a || ((a.endingAngle ?? 360) - (a.startingAngle ?? 0)) % 360 === 0;
1943
- // An arc keeps its ellipse's box for layout (see host-layout's pathBox).
2317
+ // An arc keeps its full ellipse box for layout and Figma's crop coordinates.
2318
+ cropLayerBox = { x: 0, y: 0, width: w, height: h };
1944
2319
  if (a && a.innerRadius >= 0.99 && hi - lo < 360 && style.strokes?.length) {
1945
2320
  box = pathBounds({ t, net });
1946
2321
  net = arcNetwork(rx, ry, lo, hi);
@@ -1958,7 +2333,7 @@ function convert(doc, pages, options, explicit, expanded) {
1958
2333
  else if (a && (a.innerRadius > 0 || !whole)) {
1959
2334
  box = pathBounds({ t, net });
1960
2335
  shape = { type: 'ellipse', start: whole ? 0 : lo * Math.PI / 180, end: whole ? 2 * Math.PI : Math.min(hi, lo + 360) * Math.PI / 180, ratio: Math.min(1, Math.max(0, a.innerRadius ?? 0)) };
1961
- net = shapes.shapeNet(shape, { x: 0, y: 0, width: w, height: h });
2336
+ net = shapes.shapeNet(shape, cropLayerBox);
1962
2337
  note('ellipse arcs, pies and rings drawn as parametric ellipses');
1963
2338
  }
1964
2339
  }
@@ -1967,21 +2342,19 @@ function convert(doc, pages, options, explicit, expanded) {
1967
2342
  return;
1968
2343
  }
1969
2344
  }
1970
- // Regions with fills of their own (Figma's region styles, or gradients figma-import places on each region's box):
1971
- // the scene fills a path's regions with one list, so the path becomes a group of one path per region, in order,
1972
- // then one with the stroke. A mask stays one path (its outline is what masks).
1973
- if (regionFills.some((x) => x !== undefined) && !n.mask && !n.isMask) {
1974
- if (regionFills.length === 1)
1975
- style = { ...style, fills: regionFills[0] };
1976
- else
1977
- return regionGroup(n, common, t, net, style, regionFills);
1978
- }
1979
2345
  const m = { ...common, kind: 'path', t, net };
2346
+ const cropSize = n.metadata?.figma?.regionCropSize;
2347
+ const regionCropLayerBox = cropSize && { x: 0, y: 0, width: kept?.width ?? cropSize.width, height: kept?.height ?? cropSize.height };
2348
+ const regionCropPaintBox = regionFills.some(fills => fills?.some(imageCropOf)) ? regionImageBox(net) : undefined;
2349
+ for (const [i, fills] of regionFills.entries()) {
2350
+ if (fills !== undefined)
2351
+ net.regions[i].fills = fills.map(p => fillPaint(p, imageTileOf(p), m, regionCropLayerBox, regionCropPaintBox)).filter(Boolean);
2352
+ }
1980
2353
  if (shape)
1981
2354
  m.shape = shape;
1982
2355
  if (box)
1983
2356
  m.layoutData = { box };
1984
- appearance(m, style, 'path', n.metadata?.figma);
2357
+ appearance(m, style, 'path', n.metadata?.figma, cropLayerBox);
1985
2358
  if (n.shape === 'rectangle') {
1986
2359
  const r = radii(style);
1987
2360
  if (r) {
@@ -1991,61 +2364,109 @@ function convert(doc, pages, options, explicit, expanded) {
1991
2364
  delete m.corners;
1992
2365
  }
1993
2366
  }
1994
- strokeCaps(m, n);
2367
+ strokeCaps(m, eff);
2368
+ // A leaf applies opacity to each paint. Isolate these paths so the region fills and stroke composite at full
2369
+ // opacity before applying the layer opacity once, as with the former multi-path group.
2370
+ if (common.opacity > 0 && common.opacity < 1 && regionFills.length > 1 && regionFills.some(fills => fills !== undefined)
2371
+ && !n.mask && !n.isMask) {
2372
+ const b = pathBounds(m);
2373
+ const group = {
2374
+ ...common, kind: 'frame', group: true, clip: false, w: b.width, h: b.height,
2375
+ t: [1, 0, 0, 1, t[4] + b.x, t[5] + b.y],
2376
+ };
2377
+ const path = { ...m, id: newId(), parent: group.id, opacity: 1, t: [t[0], t[1], t[2], t[3], -b.x, -b.y] };
2378
+ for (const key of ['sourceId', 'blend', 'exports', 'visible'])
2379
+ delete path[key];
2380
+ const fills = eff.resizing?.width === 'fill' || eff.resizing?.height === 'fill';
2381
+ const constrained = ['scale', 'left-right'].includes(eff.constraints?.horizontal) ||
2382
+ ['scale', 'top-bottom'].includes(eff.constraints?.vertical);
2383
+ if (children && (fills || constrained)) {
2384
+ const node = { constraints: { horizontal: 'scale', vertical: 'scale' } };
2385
+ path.layoutData = { ...path.layoutData, ...node };
2386
+ children.push({ model: path, node, children: [] });
2387
+ if (fills) {
2388
+ eff.resizing = { ...eff.resizing };
2389
+ fitGroupFill(eff.resizing, group, children);
2390
+ }
2391
+ }
2392
+ models.push(group, path);
2393
+ return group;
2394
+ }
1995
2395
  models.push(m);
1996
2396
  return m;
1997
2397
  }
1998
- // Stroke caps need an open chain whose two ends each appear once (SPEC 3.6).
1999
2398
  function strokeCaps(m, n) {
2000
- const cap = { none: 0, round: 1, square: 2 }, net = m.net;
2001
- if ((n.startCap && n.startCap !== 'none') || (n.endCap && n.endCap !== 'none')) {
2002
- const count = new Map();
2003
- for (const s of net.segments)
2004
- for (const v of [s.a, s.b])
2005
- count.set(v, (count.get(v) ?? 0) + 1);
2006
- const first = net.segments[0], last = net.segments[net.segments.length - 1];
2007
- if (m.stroke && first && count.get(first.a) === 1 && count.get(last.b) === 1 && n.startCap in cap && n.endCap in cap)
2008
- m.caps = [cap[n.startCap], cap[n.endCap]];
2009
- else if (m.stroke && first && !(count.get(first.a) === 2 && count.get(last.b) === 2))
2399
+ const { net } = m;
2400
+ if (!m.stroke || !net.segments.length)
2401
+ return;
2402
+ const start = n.startCap ?? 'none', end = n.endCap ?? 'none';
2403
+ const overrides = n.metadata?.figma?.vectorStrokeCaps;
2404
+ const hasOverrides = overrides !== undefined && Object.keys(overrides).length > 0;
2405
+ // A vector converted to a stretchable line carries explicit flat ends in its pair.
2406
+ const flatLineEnds = n.shape === 'line' && n.startCap === 'none' && n.endCap === 'none' && Boolean(m.look?.stroke?.cap);
2407
+ if (start === 'none' && end === 'none' && !hasOverrides && !flatLineEnds)
2408
+ return;
2409
+ const degree = new Map();
2410
+ for (const { a, b } of net.segments) {
2411
+ degree.set(a, (degree.get(a) ?? 0) + 1);
2412
+ degree.set(b, (degree.get(b) ?? 0) + 1);
2413
+ }
2414
+ const first = net.segments[0].a, last = net.segments.at(-1).b;
2415
+ const pairEligible = degree.get(first) === 1 && degree.get(last) === 1;
2416
+ const codes = [STROKE_CAPS.indexOf(start), STROKE_CAPS.indexOf(end)];
2417
+ if (overrides === undefined) {
2418
+ if (pairEligible && codes.every(code => code >= 0))
2419
+ m.caps = codes;
2420
+ else if (degree.get(first) !== 2 || degree.get(last) !== 2)
2010
2421
  drop('stroke caps (network ends not single)');
2422
+ return;
2011
2423
  }
2012
- }
2013
- // A path whose regions have fills of their own, as a group (the node's id, name, opacity, effects and layout) of one
2014
- // path per filled region, in the network's order, and one with the stroke on top; each keeps the whole network.
2015
- function regionGroup(n, common, t, net, style, regionFills) {
2016
- const b = pathBounds({ t, net });
2017
- const g = { ...common, kind: 'frame', group: true, t: [1, 0, 0, 1, +(t[4] + b.x).toFixed(4), +(t[5] + b.y).toFixed(4)], w: b.width, h: b.height, clip: false };
2018
- appearance(g, { shadows: style.shadows, layerBlur: style.layerBlur, backgroundBlur: style.backgroundBlur }, 'frame', n.metadata?.figma);
2019
- models.push(g);
2020
- const inner = [t[0], t[1], t[2], t[3], +(-b.x).toFixed(4), +(-b.y).toFixed(4)];
2021
- net.regions.forEach((r, i) => {
2022
- const fills = regionFills[i] ?? style.fills;
2023
- if (!fills?.length)
2024
- return;
2025
- const p = { id: newId(), parent: g.id, name: `${common.name} ${i + 1}`, opacity: 1, kind: 'path', t: inner, net: { ...net, regions: [r] } };
2026
- appearance(p, { fills }, 'path', regionFills[i] === undefined ? n.metadata?.figma : {});
2027
- models.push(p);
2424
+ // Keep the existing pair for a single ordered chain. Vertex caps leave every other network's joins and regions intact.
2425
+ if (!hasOverrides && pairEligible && degree.size === net.segments.length + 1
2426
+ && net.segments.every((s, i) => i === 0 || s.a === net.segments[i - 1].b)) {
2427
+ m.caps = codes;
2428
+ return;
2429
+ }
2430
+ const vertices = net.vertices.map(v => {
2431
+ if (degree.get(v.id) !== 1)
2432
+ return v;
2433
+ const own = overrides[v.id];
2434
+ if (own !== undefined)
2435
+ return { ...v, cap: own };
2436
+ if (start === end || v.id === first)
2437
+ return start === 'none' ? v : { ...v, cap: start };
2438
+ return v.id === last && end !== 'none' ? { ...v, cap: end } : v;
2028
2439
  });
2029
- if (style.strokes?.length) {
2030
- const p = { id: newId(), parent: g.id, name: `${common.name} stroke`, opacity: 1, kind: 'path', t: inner, net: { ...net, regions: [] } };
2031
- appearance(p, { strokes: style.strokes }, 'path');
2032
- strokeCaps(p, n);
2033
- models.push(p);
2440
+ m.net = { ...net, vertices };
2441
+ }
2442
+ function fitGroupFill(resizing, group, children) {
2443
+ for (const [axis, size, min, max] of [['width', group.w, 'minWidth', 'maxWidth'], ['height', group.h, 'minHeight', 'maxHeight']]) {
2444
+ if (resizing[axis] !== 'fill')
2445
+ continue;
2446
+ const fitted = fittedGroupAxis(size, children, axis);
2447
+ if (!fitted || fitted.minimum > (resizing[max] ?? Infinity)) {
2448
+ delete resizing[axis];
2449
+ drop(`group Fill on ${axis} left out because fitting its children cannot preserve the allocation`);
2450
+ }
2451
+ else {
2452
+ group[axis === 'width' ? 'w' : 'h'] = fitted.extent;
2453
+ resizing[min] = Math.max(resizing[min] ?? 0, fitted.minimum);
2454
+ }
2034
2455
  }
2035
- note('paths with per-region fills split into one path per region');
2036
- return g;
2037
2456
  }
2038
2457
  // Text: runs take the theme style, then the run's overrides, then the instance's textStyle override and the
2039
2458
  // node's expressions.
2040
2459
  const weights = new Map();
2041
2460
  // What sizes a run's glyphs (not its colour or decoration).
2042
- const faceOf = (s) => JSON.stringify([s.fontFamily, s.fontStyle, s.fontVariations, s.fontSize ?? 16, s.fontWeight ?? 400, !!s.italic, s.lineHeight ?? 1.2, s.letterSpacing ?? 0]);
2461
+ const faceOf = (s) => JSON.stringify([s.fontFamily, s.fontStyle, s.fontVariations, s.openTypeFeatures, s.textCase === 'original' ? undefined : s.textCase, s.fontSize ?? 16, s.fontWeight ?? 400, !!s.italic, s.lineHeight ?? 1.2, s.letterSpacing ?? 0]);
2043
2462
  const runColour = (run) => ({ ...doc.theme?.textStyles?.[run.styleId], ...run.overrides }).color;
2044
2463
  const hexOf = (c) => (typeof c === 'string' ? c : c?.hex)?.toLowerCase();
2045
2464
  // A text's paragraphs: stored, or set as characters (each line one paragraph in the first run's style).
2046
2465
  function textParagraphs(paragraphs, characters) {
2047
2466
  if (characters === undefined)
2048
2467
  return paragraphs ?? [];
2468
+ if (paragraphs && linkedParagraphsMatch(characters, paragraphs))
2469
+ return paragraphs;
2049
2470
  const first = paragraphs?.[0]?.runs?.[0] ?? {};
2050
2471
  return characters.split(/\n|\u2029/).map((line) => ({ ...paragraphs?.[0], runs: [{ ...first, text: line }] }));
2051
2472
  }
@@ -2060,7 +2481,7 @@ function convert(doc, pages, options, explicit, expanded) {
2060
2481
  let color = runColour(run);
2061
2482
  if (computed !== undefined && copies.has(hexOf(color)))
2062
2483
  color = computed;
2063
- return { ...from, text: run.text, overrides: color === undefined ? from?.overrides : { ...from?.overrides, color } };
2484
+ return { ...from, text: run.text, hyperlink: run.hyperlink, overrides: color === undefined ? from?.overrides : { ...from?.overrides, color } };
2064
2485
  };
2065
2486
  const same = shown.length === base.length && shown.every((p, i) => p.runs?.length === base[i].runs?.length);
2066
2487
  if (!same)
@@ -2068,7 +2489,7 @@ function convert(doc, pages, options, explicit, expanded) {
2068
2489
  const paragraphs = shown.map((p, i) => ({ ...(same ? base[i] : p), align: p.align, runs: (p.runs ?? []).map((run, j) => restyle(run, same ? base[i].runs[j] : base[0]?.runs?.[0] ?? run)) }));
2069
2490
  if (computed !== undefined)
2070
2491
  note('text override colours kept from the text colour expression');
2071
- return { paragraphs, characters: undefined, textColor: undefined, textAlign: undefined };
2492
+ return { paragraphs, characters: undefined, textColor: undefined, textAlign: undefined, maxLines: r.maxLines, truncate: r.truncate };
2072
2493
  }
2073
2494
  // A kit export fix, so it reads the export's override maps. The exporter writes a text override that changes only the
2074
2495
  // characters or the line height with the run colours it saw: the stored run colour (p64 _TableHeaderCell "Member",
@@ -2090,7 +2511,7 @@ function convert(doc, pages, options, explicit, expanded) {
2090
2511
  const shown = (r.paragraphs ?? []).flatMap((p) => (p.runs ?? []).map((run) => hexOf(runColour(run))));
2091
2512
  return shown.some((c) => copies.has(c)) ? copies : undefined;
2092
2513
  }
2093
- function textNode(n, eff, o, common, f, rotation, style) {
2514
+ function textNode(n, eff, o, common, f, rotation, style, modes) {
2094
2515
  let paragraphs = textParagraphs(eff.paragraphs, eff.characters);
2095
2516
  if (style.shadows?.length || style.layerBlur || style.backgroundBlur)
2096
2517
  drop('effects on text');
@@ -2149,10 +2570,40 @@ function convert(doc, pages, options, explicit, expanded) {
2149
2570
  faces.add(faceOf(styleLine === undefined ? s : { ...s, lineHeight: styleLine }));
2150
2571
  weights.set(weight, (weights.get(weight) ?? 0) + 1);
2151
2572
  const want = runStyle(s);
2573
+ if (r.hyperlink && !editorSchema.hyperlinkUrlAllowed)
2574
+ drop('Text hyperlink requires a newer editor');
2575
+ else if (r.hyperlink?.kind === 'url') {
2576
+ if (editorSchema.hyperlinkUrlAllowed(r.hyperlink.url))
2577
+ want.link = r.hyperlink.url;
2578
+ else
2579
+ drop('Text hyperlink with an invalid or unsupported URL');
2580
+ }
2581
+ else if (r.hyperlink?.kind === 'target') {
2582
+ // The Figma workflows resolve GUIDs after assigning native component and page IDs.
2583
+ if (deferHyperlinks)
2584
+ want.figmaHyperlink = r.hyperlink.guid;
2585
+ else
2586
+ drop('Text hyperlink whose target was not imported');
2587
+ }
2152
2588
  if (explicit && r.styleId && doc.theme?.textStyles?.[r.styleId])
2153
2589
  Object.assign(want, { textStyle: r.styleId });
2154
- if (explicit && r.fileFontSize !== undefined)
2155
- Object.assign(want, { fileFontSize: r.fileFontSize });
2590
+ if (file && r.fileTypography) {
2591
+ Object.assign(want, { fileTypography: r.fileTypography, ...(r.fileOwnTypography && { fileOwnTypography: r.fileOwnTypography }) });
2592
+ applyFileTypography(want, r.fileTypography, !!r.filePercentTracking, id => resolveVariable(id, modes, doc.variableAliases));
2593
+ }
2594
+ if (file && (r.fileTextColor !== undefined || r.filePlainTextColor !== undefined)) {
2595
+ const field = r.filePlainTextColor !== undefined ? 'filePlainTextColor' : 'fileTextColor';
2596
+ const ref = r[field];
2597
+ Object.assign(want, { [field]: ref });
2598
+ if (ref)
2599
+ want.color = rgba(resolveVariable(ref, modes, doc.variableAliases)) ?? want.color;
2600
+ }
2601
+ if (file && r.fileFillStyle)
2602
+ Object.assign(want, { fileFillStyle: r.fileFillStyle });
2603
+ if (file && r.filePlainFillStyle)
2604
+ Object.assign(want, { filePlainFillStyle: r.filePlainFillStyle });
2605
+ if (file && r.filePaintOpacity !== undefined)
2606
+ want.paintOpacity = r.filePaintOpacity;
2156
2607
  const key = JSON.stringify(want);
2157
2608
  if (!keys.has(key)) {
2158
2609
  keys.set(key, styles.length);
@@ -2183,7 +2634,8 @@ function convert(doc, pages, options, explicit, expanded) {
2183
2634
  let h = f.height, storedHeight;
2184
2635
  const first = (eff.paragraphs ?? n.paragraphs)?.[0]?.runs?.[0], stored = n.paragraphs?.[0]?.runs?.[0];
2185
2636
  if (first && stored && styles.length && ['height', 'width-and-height'].includes(eff.autoResize)) {
2186
- const base = { ...doc.theme?.textStyles?.[stored.styleId], ...stored.overrides }, was = (base.fontSize ?? 16) * (base.lineHeight ?? 1.2);
2637
+ const base = { ...doc.theme?.textStyles?.[stored.styleId], ...stored.overrides };
2638
+ const was = stored.fileLineHeightPx ?? (base.fontSize ?? 16) * (base.lineHeight ?? 1.2);
2187
2639
  const now = boxLine || Math.max(...styles.map((x) => x.lineHeight));
2188
2640
  // Changed text: estimate its line count from an average Inter advance (0.55 em), as no shaper runs here.
2189
2641
  const storedText = (n.paragraphs ?? []).map((p) => (p.runs ?? []).map((r) => r.text ?? '').join('')).join('\n'), text = lines.join('\n');
@@ -2204,6 +2656,10 @@ function convert(doc, pages, options, explicit, expanded) {
2204
2656
  wrap: eff.autoResize === 'width-and-height' || eff.wrap === 'none' ? 0 : 1, valign: { top: 0, middle: 1, center: 1, bottom: 2 }[n.verticalAlign] ?? 0, para };
2205
2657
  if (storedHeight > h)
2206
2658
  m.storedHeight = storedHeight;
2659
+ if (eff.maxLines)
2660
+ m.maxLines = eff.maxLines;
2661
+ if (eff.truncate === 'ellipsis')
2662
+ m.truncate = 'ellipsis';
2207
2663
  // Figma does not re-measure an auto-size box (3,816 of the kit's 13,795 visible ones are 4 px shorter than their
2208
2664
  // line height): the editor keeps a box whose text, faces, mode and wrap width are the stored ones, and measures
2209
2665
  // the rest (changed by an override or expression), as an edit would.
@@ -2247,9 +2703,8 @@ function convert(doc, pages, options, explicit, expanded) {
2247
2703
  for (const component of Object.values(doc.components))
2248
2704
  if (!placed.has(component.id))
2249
2705
  visit(doc.nodes[component.rootId], '@components', ctx);
2250
- for (const source of Object.values(doc.nodes))
2251
- if (source.slotHost || source.fileStyle)
2252
- visit(source, '', ctx);
2706
+ for (const source of extraRoots)
2707
+ visit(source, '', ctx);
2253
2708
  }
2254
2709
  // A wrapper instance holds a box Figma laid out: the editor keeps it and its variant root there (wrapped in
2255
2710
  // layout.mjs; p35 DropdownItems stay 48 px, not the 56 their contents hug; p63's 86 px Tabs, though its converted
@@ -2263,28 +2718,173 @@ function convert(doc, pages, options, explicit, expanded) {
2263
2718
  else
2264
2719
  v.layoutData.instance = true;
2265
2720
  }
2721
+ function fillSize(model) {
2722
+ return model.kind === 'path' ? model.layoutData?.box ?? pathBounds(model) : { width: model.w, height: model.h };
2723
+ }
2724
+ function applyFillSize(item, saved, scale) {
2725
+ const { model } = item, original = fillSize(model);
2726
+ // Scale a path's actual outline by the change in its Figma box. Core
2727
+ // resize keeps a nonempty outline recoverable when an axis goes to zero.
2728
+ const size = saved.pathScale
2729
+ ? { width: original.width * saved.pathScale[0] / scale, height: original.height * saved.pathScale[1] / scale }
2730
+ : { width: saved.width / scale, height: saved.height / scale };
2731
+ if (model.group && saved.pathScale) {
2732
+ // The path inside an opacity group needs the same recoverable extent.
2733
+ if (size.width === 0 && original.width)
2734
+ size.width = 1e-3;
2735
+ if (size.height === 0 && original.height)
2736
+ size.height = 1e-3;
2737
+ }
2738
+ resize(item, size);
2739
+ if (!model.group)
2740
+ return;
2741
+ // If fixed children cannot fit a stored group size, retain the allocation
2742
+ // in a plain frame. The editor would otherwise fit it back on settle.
2743
+ if (sameFigmaSize(size.width, original.width) && sameFigmaSize(size.height, original.height))
2744
+ return;
2745
+ const fitted = [Infinity, Infinity, -Infinity, -Infinity];
2746
+ for (const child of item.children) {
2747
+ const [x0, y0, x1, y1] = box(child.model);
2748
+ fitted[0] = Math.min(fitted[0], x0);
2749
+ fitted[1] = Math.min(fitted[1], y0);
2750
+ fitted[2] = Math.max(fitted[2], x1);
2751
+ fitted[3] = Math.max(fitted[3], y1);
2752
+ }
2753
+ for (const [axis, index] of [['width', 0], ['height', 1]]) {
2754
+ if (sameFigmaSize(size[axis], original[axis]))
2755
+ continue;
2756
+ const fits = Math.abs(fitted[index]) < 1e-6 && sameFigmaSize(fitted[index + 2], size[axis], 1e-6);
2757
+ const min = item.node.resizing?.[axis === 'width' ? 'minWidth' : 'minHeight'] ?? 0;
2758
+ if (fits && (size[axis] >= min || sameFigmaSize(size[axis], min)))
2759
+ continue;
2760
+ delete model.group;
2761
+ const resizing = { ...item.node.resizing };
2762
+ delete resizing[axis];
2763
+ item.node.resizing = resizing;
2764
+ model.layoutData.resizing = resizing;
2765
+ approximate(`group Fill on ${axis} held in a frame at the stored instance size`, 1, model);
2766
+ }
2767
+ }
2768
+ // Stacks were collected after their children. Finalize each parent's
2769
+ // allocation before comparing its children's shares to their saved sizes.
2770
+ for (const stack of stacksWithStoredFill.reverse()) {
2771
+ const pending = stack.children.flatMap(child => {
2772
+ const size = storedFillSizes.get(child.model);
2773
+ return size ? [{ child, size }] : [];
2774
+ });
2775
+ for (const [axis, min, max] of [['width', 'minWidth', 'maxWidth'], ['height', 'minHeight', 'maxHeight']]) {
2776
+ let fills = pending.filter(({ child }) => child.node.resizing?.[axis] === 'fill');
2777
+ while (fills.length) {
2778
+ const mismatches = new Set(fills.filter(({ child, size }) => !sameFigmaSize(fillSize(child.model)[axis], size[axis], 1e-6)));
2779
+ if (!mismatches.size)
2780
+ break;
2781
+ for (const { child, size } of mismatches) {
2782
+ const { node, model } = child, value = size[axis];
2783
+ node.resizing = { ...node.resizing, [min]: value, [max]: value };
2784
+ model.layoutData.resizing = node.resizing;
2785
+ approximate(`fill ${axis} held at the stored instance size`, 1, model);
2786
+ }
2787
+ layoutFrame(stack, { width: stack.model.w, height: stack.model.h });
2788
+ fills = fills.filter(s => !mismatches.has(s));
2789
+ }
2790
+ }
2791
+ }
2792
+ for (const [model, { box, ...geometry }] of keptGeometry) {
2793
+ Object.assign(model, geometry);
2794
+ if (box)
2795
+ model.layoutData.box = box;
2796
+ }
2266
2797
  // Image assets the models use, listed in out.assets (and in the report, with their bytes).
2267
2798
  const assets = {}, used = new Set(), files = [];
2268
- for (const m of models)
2269
- for (const p of [...m.look?.fills ?? [], m.look?.stroke?.paint])
2270
- if (p?.k === 'image')
2271
- used.add(p.asset);
2799
+ const collectImage = (p) => { if (p?.k === 'image' || p?.k === 'video')
2800
+ used.add(p.asset); };
2801
+ for (const m of models) {
2802
+ for (const p of m.look?.fills ?? [])
2803
+ collectImage(p);
2804
+ collectImage(m.look?.stroke?.paint);
2805
+ for (const region of m.net?.regions ?? [])
2806
+ for (const p of region.fills ?? [])
2807
+ collectImage(p);
2808
+ }
2272
2809
  for (const id of [...used].sort()) {
2273
- const a = doc.assets[id], src = options.assetSrc?.(id, a) ?? `assets/${id}.${a.mimeType === 'image/jpeg' ? 'jpg' : a.mimeType.split('/')[1]}`;
2810
+ const a = posters.get(id) ?? doc.assets[id];
2811
+ const src = options.assetSrc?.(id, a) ?? `assets/${id}.${a.mimeType === 'image/jpeg' ? 'jpg' : a.mimeType.split('/')[1]}`;
2274
2812
  files.push({ id, src, mimeType: a.mimeType, data: a.source.data });
2275
- assets[id] = { src, w: a.width, h: a.height };
2813
+ assets[id] = { src, w: a.width, h: a.height, ...(a.kind === 'video' && { mediaType: 'video',
2814
+ ...(a.poster && { poster: a.poster }), ...(a.duration !== undefined && { duration: a.duration }) }) };
2276
2815
  }
2277
2816
  const out = { leading: 'half', ...(!explicit && { page: pages[0].name }), ...(options.source !== undefined ? { source: options.source } : {}), models, ...(used.size ? { assets } : {}) };
2278
- const linked = options.link === false ? null : linkWithLayers(out);
2279
- if (expanded && linked) {
2280
- const original = new Map(models.map(m => [m.id, m]));
2281
- for (const m of models)
2817
+ return { out, affected, nestedBooleans, counts: { dropped, expressionErrors, notes, approximations, weights }, depth: depthMax, files };
2818
+ }
2819
+ function convert(doc, pages, options, explicit, file, deferHyperlinks = false) {
2820
+ // Drop the resolver, trial layouts and pre-layout geometry before indexing linked layers.
2821
+ const { out, affected, nestedBooleans, counts, depth, files } = expand(doc, pages, options, explicit, file, deferHyperlinks);
2822
+ const models = out.models;
2823
+ const linked = options.link === false ? null : linkWithLayers(out, true, file && (id => doc.nodes[id]?.expressions?.componentId), !!file);
2824
+ if (linked && !explicit) {
2825
+ // Clipboard mains synthesized from expansions get their presets from the source definition. A variant set's main
2826
+ // is the set's root showing one variant, a frame of the root's: the main is that variant, so it takes the
2827
+ // variant's presets and the frame keeps none.
2828
+ const lost = (what) => counts.dropped.set(what, (counts.dropped.get(what) ?? 0) + 1);
2829
+ for (const main of out.models) {
2830
+ if (main.kind !== 'frame' || main.parent !== '@components' || main.component !== main.id)
2831
+ continue;
2832
+ const source = doc.nodes[main.sourceId ?? ''];
2833
+ const set = source !== undefined && Object.values(doc.components).some(c => c.rootId === source.id && c.properties?.some((p) => p.kind === 'enum'));
2834
+ const variant = set ? out.models.find(m => m.parent === main.id && (source.children ?? []).includes(m.sourceId ?? '')) : undefined;
2835
+ const exports = variant ? variant.exports : exportsOf(source?.exportSettings, lost);
2836
+ if (variant)
2837
+ delete variant.exports;
2838
+ if (exports)
2839
+ main.exports = exports;
2840
+ }
2841
+ }
2842
+ if (options.instanceSources && linked) {
2843
+ const sources = options.instanceSources;
2844
+ const hiddenRoots = new Set(out.models.filter(m => m.parent === '@components').map(m => m.id));
2845
+ for (const [id, copies] of linked.aliases) {
2846
+ const source = sources.get(id);
2847
+ if (source === undefined)
2848
+ continue;
2849
+ // A hidden main's root represents the component. Its descendants keep their own occurrence IDs.
2850
+ for (const copy of copies)
2851
+ if (!copy.includes(';') && !hiddenRoots.has(copy))
2852
+ sources.set(copy, source);
2853
+ }
2854
+ }
2855
+ if (file && linked) {
2856
+ file.omittedLinks = linked.omittedLinks;
2857
+ file.expandedReasons = linked.expandedReasons;
2858
+ const { expanded } = file;
2859
+ // Only appearance and text are needed after linking. The resource stage may replace
2860
+ // paints on a surviving layer, so retain the pre-link look and stroke containers.
2861
+ const original = new Map();
2862
+ const remember = (id, layer) => {
2863
+ const look = layer.look && { ...layer.look, ...(layer.look.stroke && { stroke: { ...layer.look.stroke } }) };
2864
+ expanded.set(id, { content: layer.content, styles: layer.styles, runs: layer.runs, styleAt: layer.styleAt, fill: layer.fill, stroke: layer.stroke, look });
2865
+ const assignments = nestedBooleans?.get(layer);
2866
+ if (assignments)
2867
+ file.nestedBooleans.set(id, assignments);
2868
+ };
2869
+ for (const m of models) {
2870
+ original.set(m.id, m);
2282
2871
  if (m.fileInstance)
2283
- expanded.set(m.id, m);
2284
- // Hidden main copies are recorded before the occurrences linked against them.
2285
- for (const [id, paths] of linked.aliases)
2286
- for (const path of paths)
2287
- expanded.set(path, original.get(id) ?? expanded.get(id));
2872
+ remember(m.id, m);
2873
+ }
2874
+ // A hidden main copy can itself be the source of later aliases.
2875
+ for (const [id, paths] of linked.aliases) {
2876
+ const layer = original.get(id);
2877
+ for (const path of paths) {
2878
+ if (layer)
2879
+ remember(path, layer);
2880
+ else {
2881
+ expanded.set(path, expanded.get(id));
2882
+ const assignments = file.nestedBooleans.get(id);
2883
+ if (assignments)
2884
+ file.nestedBooleans.set(path, assignments);
2885
+ }
2886
+ }
2887
+ }
2288
2888
  }
2289
2889
  if (options.link === false && !options.markers)
2290
2890
  for (const m of out.models)
@@ -2298,5 +2898,5 @@ function convert(doc, pages, options, explicit, expanded) {
2298
2898
  const layerIds = new Map([...affected].map(([key, layers]) => [
2299
2899
  key, [...new Set([...layers].flatMap(({ id }) => id === undefined ? [] : affectedIds(id)))],
2300
2900
  ]));
2301
- return { doc: out, report: { dropped, expressionErrors, notes, approximations, weights, layerIds, depth: depthMax, links: linked?.counts ?? null, assets: files } };
2901
+ return { doc: out, report: { ...counts, layerIds, depth, links: linked?.counts ?? null, assets: files } };
2302
2902
  }