@moondraft/import 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +2 -2
  3. package/SOURCE.md +229 -4
  4. package/dist/adapter/convert.d.ts +24 -2
  5. package/dist/adapter/convert.js +669 -160
  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 +12 -0
  11. package/dist/adapter/figma-handoff.js +167 -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 +14 -4
  16. package/dist/adapter/file-components.d.ts +9 -3
  17. package/dist/adapter/file-components.js +122 -32
  18. package/dist/adapter/file-resources.js +316 -27
  19. package/dist/adapter/image-crop.d.ts +18 -0
  20. package/dist/adapter/image-crop.js +30 -0
  21. package/dist/adapter/link.d.ts +5 -1
  22. package/dist/adapter/link.js +308 -104
  23. package/dist/adapter/payload.js +1 -1
  24. package/dist/adapter/variables.d.ts +2 -1
  25. package/dist/adapter/variables.js +5 -2
  26. package/dist/figma.js +167 -33
  27. package/dist/index.d.ts +1 -0
  28. package/dist/index.js +1 -0
  29. package/dist/report.d.ts +28 -1
  30. package/dist/report.js +102 -29
  31. package/dist/serialize.d.ts +7 -0
  32. package/dist/serialize.js +79 -0
  33. package/dist/taco/figma-import/container/kiwiContainer.d.ts +3 -0
  34. package/dist/taco/figma-import/container/kiwiContainer.js +1 -1
  35. package/dist/taco/figma-import/import/carry.d.ts +14 -1
  36. package/dist/taco/figma-import/import/carry.js +34 -1
  37. package/dist/taco/figma-import/import/componentProps.d.ts +10 -4
  38. package/dist/taco/figma-import/import/componentProps.js +29 -13
  39. package/dist/taco/figma-import/import/componentSets.d.ts +2 -0
  40. package/dist/taco/figma-import/import/componentSets.js +1 -1
  41. package/dist/taco/figma-import/import/converters/exportSettings.d.ts +4 -0
  42. package/dist/taco/figma-import/import/converters/exportSettings.js +49 -0
  43. package/dist/taco/figma-import/import/converters/frame.js +8 -0
  44. package/dist/taco/figma-import/import/converters/gradient.d.ts +2 -0
  45. package/dist/taco/figma-import/import/converters/gradient.js +3 -1
  46. package/dist/taco/figma-import/import/converters/group.d.ts +2 -4
  47. package/dist/taco/figma-import/import/converters/group.js +6 -15
  48. package/dist/taco/figma-import/import/converters/image.d.ts +1 -1
  49. package/dist/taco/figma-import/import/converters/image.js +22 -11
  50. package/dist/taco/figma-import/import/converters/layout.d.ts +3 -4
  51. package/dist/taco/figma-import/import/converters/layout.js +40 -21
  52. package/dist/taco/figma-import/import/converters/rectangle.d.ts +1 -1
  53. package/dist/taco/figma-import/import/converters/rectangle.js +1 -1
  54. package/dist/taco/figma-import/import/converters/section.d.ts +2 -3
  55. package/dist/taco/figma-import/import/converters/section.js +3 -9
  56. package/dist/taco/figma-import/import/converters/shared.d.ts +7 -4
  57. package/dist/taco/figma-import/import/converters/shared.js +15 -5
  58. package/dist/taco/figma-import/import/converters/text.d.ts +14 -1
  59. package/dist/taco/figma-import/import/converters/text.js +143 -12
  60. package/dist/taco/figma-import/import/converters/vector.d.ts +36 -15
  61. package/dist/taco/figma-import/import/converters/vector.js +214 -73
  62. package/dist/taco/figma-import/import/converters/vectorNetwork.d.ts +19 -3
  63. package/dist/taco/figma-import/import/converters/vectorNetwork.js +147 -29
  64. package/dist/taco/figma-import/import/instances.d.ts +25 -4
  65. package/dist/taco/figma-import/import/instances.js +324 -117
  66. package/dist/taco/figma-import/import/styles.d.ts +2 -0
  67. package/dist/taco/figma-import/import/styles.js +6 -0
  68. package/dist/taco/figma-import/import/variables.d.ts +3 -2
  69. package/dist/taco/figma-import/import/variables.js +37 -30
  70. package/dist/taco/figma-import/import/variantTrees.d.ts +1 -1
  71. package/dist/taco/figma-import/import/variantTrees.js +44 -4
  72. package/dist/taco/figma-import/import/walk.d.ts +53 -5
  73. package/dist/taco/figma-import/import/walk.js +273 -106
  74. package/dist/taco/figma-import/kiwi/message.d.ts +4 -2
  75. package/dist/taco/figma-import/kiwi/message.js +13 -11
  76. package/dist/taco/model/codec.d.ts +1 -1
  77. package/dist/taco/model/codec.js +37 -7
  78. package/dist/taco/model/component-evaluation.d.ts +2 -0
  79. package/dist/taco/model/component-evaluation.js +7 -0
  80. package/dist/taco/model/instance-resolver.d.ts +6 -2
  81. package/dist/taco/model/instance-resolver.js +48 -18
  82. package/dist/taco/model/sha256.js +13 -8
  83. package/dist/taco/model/types.d.ts +23 -1
  84. 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';
@@ -25,6 +29,52 @@ 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';
27
31
  import { linkWithLayers, unmark } from './link.js';
32
+ // Figma stores float32 sizes. Comparing after layout or instance scaling can
33
+ // also include rounding from the arithmetic that produced the two sizes.
34
+ function sameFigmaSize(a, b, absoluteTolerance = 0) {
35
+ const difference = Math.abs(a - b);
36
+ return difference <= absoluteTolerance || difference < Math.max(Math.abs(a), Math.abs(b)) * 1e-6;
37
+ }
38
+ // fit() takes the union of the child boxes after layout. Only allocate an axis
39
+ // that the fitted bounds track under scale, including after a collapse. A
40
+ // smaller path needs a proportionally larger group minimum to keep its shape.
41
+ function fittedGroupAxis(size, children, axis) {
42
+ if (!size || !children.length)
43
+ return;
44
+ const horizontal = axis === 'width', index = horizontal ? 0 : 1;
45
+ let near = Infinity, far = -Infinity, minimum = 1e-3;
46
+ for (const child of children) {
47
+ const { model, node } = child;
48
+ if (node.constraints?.[horizontal ? 'horizontal' : 'vertical'] !== 'scale' || node.aspectRatioLocked ||
49
+ model.mask || model.t[1] || model.t[2] || Math.abs(model.t[0] * model.t[3]) < 1e-12)
50
+ return;
51
+ const bounds = box(model), extent = bounds[index + 2] - bounds[index];
52
+ near = Math.min(near, bounds[index]);
53
+ far = Math.max(far, bounds[index + 2]);
54
+ if (model.kind === 'path' && extent > 0) {
55
+ const measured = model.layoutData?.box?.[axis] ?? extent;
56
+ if (!measured)
57
+ return;
58
+ minimum = Math.max(minimum, 1e-3 * (size / measured));
59
+ }
60
+ else if (model.group) {
61
+ const nestedSize = horizontal ? model.w : model.h;
62
+ const nested = fittedGroupAxis(nestedSize, child.children, axis);
63
+ if (!nested || !sameFigmaSize(nested.extent, nestedSize, 1e-9))
64
+ return;
65
+ minimum = Math.max(minimum, nested.minimum * (size / nestedSize));
66
+ }
67
+ else if (model.kind !== 'rect' && model.kind !== 'path')
68
+ return;
69
+ }
70
+ // Converted vertices have four decimal places. Start subsequent resizes at
71
+ // the converted extent so the rounding error cannot grow with the group.
72
+ if (Math.abs(near) >= 1e-9 || !sameFigmaSize(far, size, 0.00005))
73
+ return;
74
+ minimum = Math.max(1e-3, minimum * (far / size));
75
+ if (minimum <= far)
76
+ return { extent: far, minimum };
77
+ }
28
78
  /** Converts a reader colour to the RGBA precision used by imported paints.
29
79
  * @param hex - Source hex colour or expression colour.
30
80
  * @returns Normalized channels, or null for a non-colour value.
@@ -50,8 +100,10 @@ export function rgba(hex) {
50
100
  */
51
101
  export function runStyle(s) {
52
102
  const size = s.fontSize ?? 16, weight = s.fontWeight ?? 400;
103
+ const features = Object.entries(s.openTypeFeatures ?? {});
53
104
  return {
54
105
  family: s.fontFamily ?? 'Inter', style: s.fontStyle ?? fontStyleName(weight, !!s.italic),
106
+ ...(features.length > 0 && { features: Object.fromEntries(features.map(([tag, value]) => [tag, Number(value)])) }),
55
107
  ...(s.fontVariations && { variations: s.fontVariations }), size, lineHeight: +(size * (s.lineHeight ?? 1.2)).toFixed(3),
56
108
  weight, italic: !!s.italic, underline: !!s.underline, ...(s.strikethrough ? { strikethrough: true } : {}),
57
109
  color: rgba(s.color) ?? [0, 0, 0, 1], letterSpacing: s.letterSpacing ?? 0,
@@ -83,18 +135,32 @@ export function toDocument(doc, pageRef, options = {}) {
83
135
  throw new Error(`no page ${pageRef}; pages: ${pages.map((p) => p.name).join(', ')}`);
84
136
  return convert(doc, [page], options, false);
85
137
  }
138
+ /** Converts the clipboard selection for the Figma adapter's subsequent GUID resolution pass. @internal */
139
+ export function figmaClipboardPage(doc, instanceSources) {
140
+ return convert(doc, [doc.pages[doc.pageOrder[0]]], { instanceSources }, false, undefined, true);
141
+ }
86
142
  /** Converts all file pages and keeps the appearance of each linked occurrence.
87
143
  * @param doc - Source document.
88
144
  * @param options - Asset and conversion settings.
89
- * @returns Linked document, conversion report and the pre-link instance literals.
145
+ * @returns Linked document, conversion report, pre-link literals and nested boolean assignments.
90
146
  * @internal
91
147
  */
92
148
  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 };
149
+ const file = { expanded: new Map(), nestedBooleans: new Map(), omittedLinks: new Map() };
150
+ return { ...convert(doc, doc.pageOrder.map((id) => doc.pages[id]), options, true, file, true), ...file };
95
151
  }
96
- function convert(doc, pages, options, explicit, expanded) {
152
+ // The boolean group operations (FrameNode.boolean) a live Figma boolean operation carries.
153
+ const BOOLEAN_OPS = new Set(['union', 'subtract', 'intersect', 'exclude']);
154
+ // The override and expression fields that leave a boolean operand's shape and visibility as they are (an operand's look
155
+ // is not drawn).
156
+ const LOOK_ONLY = new Set(['opacity', 'name', 'fills', 'strokes', 'effects', 'startCap', 'endCap', 'shadows', 'layerBlur', 'backgroundBlur', 'styleId', 'imageAssetId']);
157
+ // The model fields that are a boolean group's own (its operation, result and look), moved off a fixed-size wrapper.
158
+ const BOOLEAN_OWN = ['group', 'boolean', 'result', 'fill', 'look', 'stroke', 'strokeWidth', 'radius', 'smoothing'];
159
+ function expand(doc, pages, options, explicit, file, deferHyperlinks) {
97
160
  const kitFixes = options.kitFixes ?? false;
161
+ const nestedBooleans = file && new WeakMap();
162
+ // The boolean group inside each fixed-size wrapper the conversion made (see `fixedBox` below), by wrapper model.
163
+ const wrappedBoolean = new WeakMap();
98
164
  const dropped = new Map(), notes = new Map(), approximations = new Map();
99
165
  const affected = new Map();
100
166
  let active, probing = 0;
@@ -115,7 +181,14 @@ function convert(doc, pages, options, explicit, expanded) {
115
181
  };
116
182
  const rootOf = new Map(Object.values(doc.components).map((c) => [c.rootId, c]));
117
183
  // 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 ?? [] : [])));
184
+ const slotChildren = new Set(), extraRoots = [];
185
+ for (const node of Object.values(doc.nodes)) {
186
+ if (node.slot)
187
+ for (const child of node.children ?? [])
188
+ slotChildren.add(child);
189
+ if (explicit && (node.slotHost || node.fileStyle))
190
+ extraRoots.push(node);
191
+ }
119
192
  // An expanded instance of a component with variant properties names its set (link.ts names its hidden main
120
193
  // "Button/variant=primary, size=sm" with it, so the editor groups a set's variants and no other's).
121
194
  // It names its variant too (its variant properties' values, "variant=primary, size=sm"): link.ts makes one hidden
@@ -158,13 +231,13 @@ function convert(doc, pages, options, explicit, expanded) {
158
231
  // (resolveInstance; resolveComponent for a component met on the page). Each layer takes from its ResolvedLayer what
159
232
  // overrides set apart from sizes: visibility (conditions included), paints, effects, opacity, name, blend mode, text
160
233
  // 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
234
+ // a slot frame shows. File conversion supplies geometry itself and skips the resolver's layout. The
162
235
  // converter's own override maps (overridesFor) still feed its size rules: sizing, padding, line boxes, scale and
163
236
  // variant sizes. Computed texts keep their stored frames (withoutTextMeasurement), as in `evaluated` below.
164
- const resolveCache = createInstanceResolveCache();
237
+ const resolveOptions = { cache: createInstanceResolveCache(!file), layout: !file };
165
238
  function resolvedLayer(n, definition) {
166
239
  try {
167
- return withoutTextMeasurement(() => definition ? resolveComponent(model, definition.id, { cache: resolveCache }) : resolveInstance(model, n.id, { cache: resolveCache }).root);
240
+ return withoutTextMeasurement(() => definition ? resolveComponent(model, definition.id, resolveOptions) : resolveInstance(model, n.id, resolveOptions).root);
168
241
  }
169
242
  catch (e) {
170
243
  // Counted by kind; taco's message (a refused document or an evaluator failure alike) is the detail.
@@ -172,7 +245,9 @@ function convert(doc, pages, options, explicit, expanded) {
172
245
  return false;
173
246
  }
174
247
  }
175
- // A layer's node in the document: a nested instance layer stands for its instance node, any other for its source.
248
+ // Nested instance wrappers can contribute diagnostics even during a size trial.
249
+ const containsInstance = (layer) => layer.instance !== undefined || layer.children.some(containsInstance);
250
+ // A nested instance layer stands for its instance node, any other for its source.
176
251
  const layerNodeId = (layer) => layer.instance?.instanceId ?? layer.sourceNodeId;
177
252
  // Override fields the size rules read; the rest of an override map comes from the resolved layer.
178
253
  const SIZE_OVERRIDES = new Set(['sizing', 'padding', 'textStyle', 'lineBoxOnly', 'frame', 'x', 'y', 'width', 'height', 'resizing', 'layoutPositioning', 'constraints', 'layout', 'variableModes', 'variableBindings', 'expressions']);
@@ -199,7 +274,7 @@ function convert(doc, pages, options, explicit, expanded) {
199
274
  return out;
200
275
  }
201
276
  // 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']);
277
+ const RESOLVED_FIELDS = new Set(['visible', 'opacity', 'fills', 'strokes', 'shadows', 'effects', 'cornerRadii', 'characters', 'textColor', 'componentId', 'startCap', 'endCap']);
203
278
  const resolvedField = (key) => RESOLVED_FIELDS.has(key) || key.startsWith('propertyValues.');
204
279
  const programs = new Map();
205
280
  function programOf(comp) {
@@ -465,6 +540,14 @@ function convert(doc, pages, options, explicit, expanded) {
465
540
  out[key.slice(prefix.length)] = value;
466
541
  return out;
467
542
  }
543
+ function boxAt(scopes, id) {
544
+ for (const { boxes, prefix, fillScale } of scopes ?? []) {
545
+ const box = boxes.get(prefix + id);
546
+ if (box)
547
+ return { box, fillScale };
548
+ }
549
+ return undefined;
550
+ }
468
551
  function descendSlots(map, instanceId) {
469
552
  const out = {}, prefix = `${instanceId};`;
470
553
  for (const [key, value] of Object.entries(map))
@@ -569,12 +652,14 @@ function convert(doc, pages, options, explicit, expanded) {
569
652
  // DatePicker: its DateField's label draws 24 px, not the 20 px box line; p15 calendar days keep theirs).
570
653
  : ctx.comps.slice(0, ctx.comps.indexOf(scope)).some((c) => c.definition === true) && ctx.comps.at(-1) !== scope ? 'nested' : 'instance');
571
654
  }
655
+ if (o.layout?.gap !== undefined && out.variableBindings && !o.variableBindings?.gap)
656
+ delete out.variableBindings.gap;
572
657
  for (const [k, v] of Object.entries(o)) {
573
658
  if (k === 'conditional' || k === 'lineBoxOnly')
574
659
  continue; // a name (a layer renamed in an instance) is kept
575
660
  if (k === 'propertyValues')
576
661
  out.propertyValues = { ...out.propertyValues, ...v };
577
- else if (['textStyle', 'variableBindings', 'variableModes', 'expressions', 'style', 'sizing', 'padding'].includes(k))
662
+ else if (['textStyle', 'variableBindings', 'variableModes', 'expressions', 'style', 'sizing', 'padding', 'layout'].includes(k))
578
663
  out[k] = { ...out[k], ...v };
579
664
  else
580
665
  out[k] = v;
@@ -614,17 +699,17 @@ function convert(doc, pages, options, explicit, expanded) {
614
699
  return { k: 'solid', c, o };
615
700
  }
616
701
  if (p.kind === 'linear-gradient') {
617
- if (!p.from || !p.to)
618
- throw new Error('Linear gradient requires from and to endpoints');
702
+ const ok = (e) => Number.isFinite(e?.x) && Number.isFinite(e?.y);
703
+ if (!ok(p.from) || !ok(p.to)) {
704
+ drop('linear gradient: no endpoints');
705
+ return null;
706
+ }
619
707
  return { k: 'linear', from: [p.from.x, p.from.y], to: [p.to.x, p.to.y], stops: stops(p.stops), o };
620
708
  }
621
709
  if (p.kind === 'radial-gradient')
622
710
  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
711
  if (p.kind === 'angular-gradient')
624
712
  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
713
  if (p.kind === 'image') {
629
714
  const asset = doc.assets?.[p.assetId];
630
715
  if (asset?.kind !== 'image' || asset.source?.kind !== 'data') {
@@ -638,6 +723,11 @@ function convert(doc, pages, options, explicit, expanded) {
638
723
  }
639
724
  // ---- Nodes.
640
725
  const models = [];
726
+ // An enclosing auto-layout frame can move or resize an already converted child.
727
+ // Link the stored Figma geometry after the layout passes have finished.
728
+ const stacksWithStoredFill = [];
729
+ const storedFillSizes = new Map();
730
+ const keptGeometry = new Map();
641
731
  // Instance roots that are bare hug wrappers, with their variant root and padding (see the check after conversion).
642
732
  const wrappers = [];
643
733
  let serial = 0, depthMax = 0;
@@ -658,7 +748,7 @@ function convert(doc, pages, options, explicit, expanded) {
658
748
  // place: an instance's frame and rotation, for a component root expanded in its place.
659
749
  // rs: how the parent's size changed from its stored one ({ dw, dh, sx, sy }), when it has no auto layout: the node
660
750
  // follows its constraints (an instance sized unlike its component, or a frame resized by that).
661
- const STYLE_KEYS = ['fills', 'strokes', 'shadows', 'cornerRadii', 'cornerRadius'];
751
+ const STYLE_KEYS = ['fills', 'strokes', 'shadows', 'cornerRadii', 'cornerRadius', 'cornerSmoothing'];
662
752
  // The style keys a component's `effects` expression computes.
663
753
  const EFFECT_KINDS = ['shadows', 'backgroundBlur', 'layerBlur'];
664
754
  // A Figma mask (mask: true; maskType alpha, the default, vector or luminance) becomes the renderer's mask flag (SPEC
@@ -672,20 +762,35 @@ function convert(doc, pages, options, explicit, expanded) {
672
762
  const previous = active;
673
763
  active = {};
674
764
  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();
765
+ const saved = !probing && !place ? boxAt(ctx.boxScopes, n.id) : undefined;
766
+ const kept = probing ? undefined : place?.box ?? (saved?.fillScale === undefined ? saved?.box : undefined);
767
+ const mask = n.mask || n.isMask;
768
+ const type = mask && String(n.maskType ?? n.metadata?.figma?.maskType ?? 'alpha').toLowerCase();
678
769
  if (type === 'luminance') {
679
770
  drop('luminance mask (no renderer equivalent; mask skipped, siblings unmasked)');
680
771
  return;
681
772
  }
682
- const item = visitNode(n, parent, ctx, place, depth, rs, layer);
683
- if (!item)
773
+ const item = visitNode(n, parent, ctx, place, depth, rs, layer, kept);
774
+ if (item && saved?.fillScale !== undefined) {
775
+ applyFillSize(item, saved.box, saved.fillScale);
776
+ storedFillSizes.set(item.model, fillSize(item.model));
777
+ }
778
+ if (kept && item) {
779
+ // An opacity wrapper and its region path share one stored Figma box.
780
+ for (const { model } of [item, ...(n.type === 'shape' ? item.children : [])]) {
781
+ const { t, w, h, net, layoutData } = model;
782
+ if (model.kind === 'path' || model.group)
783
+ storedFillSizes.set(model, fillSize(model));
784
+ keptGeometry.set(model, { t: [...t], ...(net ? { net } : { w, h }), box: layoutData?.box });
785
+ }
786
+ }
787
+ if (!mask || !item)
684
788
  return item;
685
789
  item.model.mask = true;
686
790
  note('masks');
687
791
  if (type === 'vector') {
688
- const m = item.model;
792
+ // A boolean group in a fixed-size wrapper masks with its own outline: the wrapper keeps only the mask flag.
793
+ const m = wrappedBoolean.get(item.model) ?? item.model;
689
794
  if (m.kind === 'text')
690
795
  drop('vector mask on text (masked by its glyph alpha)');
691
796
  else {
@@ -693,6 +798,8 @@ function convert(doc, pages, options, explicit, expanded) {
693
798
  delete m.stroke;
694
799
  delete m.strokeWidth;
695
800
  delete m.look;
801
+ for (const region of m.net?.regions ?? [])
802
+ delete region.fills;
696
803
  note('vector masks sent opaque');
697
804
  }
698
805
  }
@@ -711,8 +818,9 @@ function convert(doc, pages, options, explicit, expanded) {
711
818
  if (at < 0)
712
819
  return;
713
820
  const rest = children.slice(at + 1);
821
+ // Children are emitted in preorder. The last child owns the entire suffix.
714
822
  if (!rest.length) {
715
- removeSubtree(children[at].model.id);
823
+ models.length = models.lastIndexOf(children[at].model);
716
824
  note('masks with nothing after them (not drawn)');
717
825
  return;
718
826
  }
@@ -726,18 +834,7 @@ function convert(doc, pages, options, explicit, expanded) {
726
834
  note('masks nested in a wrapper frame');
727
835
  applyMasks(wrapper, inner);
728
836
  }
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) {
837
+ function visitNode(n, parent, ctx, place, depth, rs, layer, kept) {
741
838
  depthMax = Math.max(depthMax, depth);
742
839
  if (depth > 64) {
743
840
  drop('instance nesting deeper than 64');
@@ -751,13 +848,21 @@ function convert(doc, pages, options, explicit, expanded) {
751
848
  layer = resolvedLayer(n, definition);
752
849
  const L = layer || undefined, r = L?.node;
753
850
  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 } };
851
+ if (o.layout)
852
+ eff.layout = { ...n.layout, ...o.layout };
853
+ const figma = n.metadata?.figma;
854
+ if (figma?.fillSizing)
855
+ eff.resizing = { ...figma.fillSizing, ...eff.resizing };
856
+ if (figma?.groupConstraints)
857
+ eff.constraints = { ...figma.groupConstraints, ...eff.constraints };
858
+ if (n.variableModes || o.variableModes || place?.variableModes)
859
+ ctx = { ...ctx, modes: { ...ctx.modes, ...n.variableModes, ...o.variableModes, ...place?.variableModes } };
755
860
  // Resolve bindings on the effective stored paints first; expressions replace these
756
861
  // fallbacks below. Clone paints so expanding one instance never changes another.
757
862
  // A resolved layer's paints have its overrides, computed fields and bound variables applied.
758
863
  const style = L ? { ...r.style } : { ...n.style, ...o.style };
759
864
  if (!L)
760
- for (const k of ['fills', 'strokes', 'shadows', 'backgroundBlur', 'layerBlur', 'cornerRadii', 'cornerRadius'])
865
+ for (const k of ['fills', 'strokes', 'shadows', 'backgroundBlur', 'layerBlur', 'cornerRadii', 'cornerRadius', 'cornerSmoothing'])
761
866
  if (o[k] !== undefined)
762
867
  style[k] = o[k];
763
868
  if (L) {
@@ -781,10 +886,17 @@ function convert(doc, pages, options, explicit, expanded) {
781
886
  }
782
887
  // An instance's root keeps its own opacity: the instance's replaces it by the variant opacity rule (variantOpacity).
783
888
  Object.assign(eff, place ? {} : { opacity: r.opacity }, { name: r.name, blendMode: r.blendMode });
889
+ if (n.type === 'frame')
890
+ eff.clipContent = r.clipContent;
784
891
  if (n.type === 'instance')
785
892
  eff.componentId = L.instance.componentId;
893
+ if (n.type === 'shape')
894
+ Object.assign(eff, { startCap: r.startCap, endCap: r.endCap });
786
895
  }
787
896
  const allBindings = { ...n.variableBindings, ...o.variableBindings };
897
+ // A literal instance gap replaces the main's binding. A binding authored on the same override still wins.
898
+ if (o.layout?.gap !== undefined && !o.variableBindings?.gap)
899
+ delete allBindings.gap;
788
900
  const bindings = L ? Object.fromEntries(Object.entries(allBindings).filter(([k]) => SIZE_BINDINGS.has(k) || (place && k === 'opacity'))) : allBindings;
789
901
  for (const key of ['fillColor', 'strokeColor', 'textColor']) {
790
902
  if (!bindings[key] || (explicit && key !== 'textColor'))
@@ -910,8 +1022,6 @@ function convert(doc, pages, options, explicit, expanded) {
910
1022
  note('hidden nodes skipped');
911
1023
  return;
912
1024
  }
913
- if (n.flipX || n.flipY)
914
- drop('instance flip');
915
1025
  const frame = place?.frame ?? eff.frame, rotation = place?.rotation ?? eff.rotation ?? 0;
916
1026
  // The layer's name: the source's (an override may rename it); a component root expanded in an instance's place takes
917
1027
  // the instance's name, as Figma's layers panel shows it.
@@ -958,6 +1068,17 @@ function convert(doc, pages, options, explicit, expanded) {
958
1068
  const variant = (!asStored(frame, root.frame) && atVariantSize(frame, root, props, ctx.modes))
959
1069
  || (ctx.ovr.length > 0 && !!ctx.comps.at(-1)?.variant && [true, 'kept'].includes(ctx.comps.at(-1).definition));
960
1070
  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 };
1071
+ const boxes = eff.componentId === n.componentId ? doc.instanceBoxes?.get(n.id) : undefined;
1072
+ const fills = eff.componentId === n.componentId ? doc.instanceFillSizes?.get(n.id) : undefined;
1073
+ const fillScope = fills && { boxes: fills, prefix: '', fillScale: 1 };
1074
+ if (boxes || fills || ctx.boxScopes) {
1075
+ const scopes = ctx.boxScopes?.map(scope => ({ ...scope, prefix: scope.prefix + n.id + ';' })) ?? [];
1076
+ if (boxes)
1077
+ scopes.push({ boxes, prefix: '' });
1078
+ if (fillScope)
1079
+ scopes.push(fillScope);
1080
+ inner.boxScopes = scopes;
1081
+ }
961
1082
  // The opacity stored on an instance is a copy of its variant root's when it equals that root's opacity in the
962
1083
  // stored variant; such a copy follows the variant an enclosing override or expression picks (p25's swatches
963
1084
  // disabled by an outer override), while a different value is the instance's own and is kept (p64's hidden check).
@@ -977,7 +1098,7 @@ function convert(doc, pages, options, explicit, expanded) {
977
1098
  // An instance on the page scaled with Figma's scale tool (and possibly resized), shown by its overrides
978
1099
  // (overrideScale): the overrides it scaled are taken back to the component's scale for the layout at size / s.
979
1100
  let scaled = 1;
980
- if (trials === 0 && !ctx.ovr.length && eff.componentId === n.componentId) {
1101
+ if (!boxes && trials === 0 && !ctx.ovr.length && eff.componentId === n.componentId) {
981
1102
  const { s, sure } = overrideScale(eff.overrides, comp, props, ctx.modes);
982
1103
  if (s !== 1) {
983
1104
  const unscaled = unscale(eff.overrides, s), resizing = unscale(placed.resizing, s);
@@ -1123,8 +1244,8 @@ function convert(doc, pages, options, explicit, expanded) {
1123
1244
  note('nested hug instances that follow kept line boxes');
1124
1245
  }
1125
1246
  }
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) {
1247
+ let s = scaled !== 1 ? scaled : boxes || ctx.ovr.length || place?.trial ? 1 : instanceScale(root, parent, inner, placed, depth);
1248
+ if (!boxes && s === 1 && scaled === 1 && trials === 0 && !ctx.ovr.length && !place?.trial) {
1128
1249
  // Scaled below 1 and resized, with no padding override: line heights that agree on one k (see lineHeightScale).
1129
1250
  const k = lineHeightScale(eff.overrides);
1130
1251
  if (k !== 1) {
@@ -1148,13 +1269,27 @@ function convert(doc, pages, options, explicit, expanded) {
1148
1269
  }
1149
1270
  const markInstance = (item) => {
1150
1271
  active.id = item.model.id;
1272
+ if (!kept && (n.flipX || n.flipY)) {
1273
+ // Reflect about the expanded root's local center, before its rotation and scale.
1274
+ const m = item.model, { x, y, width, height } = localBox(m);
1275
+ m.t = mul(m.t, [n.flipX ? -1 : 1, 0, 0, n.flipY ? -1 : 1,
1276
+ n.flipX ? 2 * x + width : 0, n.flipY ? 2 * y + height : 0]).map(v => +v.toFixed(6));
1277
+ }
1151
1278
  item.fromInstance = true;
1279
+ if (!probing)
1280
+ options.instanceSources?.set(item.model.id, n.id);
1152
1281
  if (explicit && eff.visible === false)
1153
1282
  item.model.visible = false;
1154
1283
  if (explicit && !doc.componentPlacements?.[n.id]) {
1155
1284
  item.model.fileInstance = n.id;
1156
1285
  if (n.slots?.[''])
1157
1286
  item.model.fileFills = Object.values(n.slots['']);
1287
+ // If an enclosing instance expands to a frame, its assignments must follow each surviving nested occurrence.
1288
+ if (nestedBooleans && full.propertyValues) {
1289
+ const assignments = Object.entries(full.propertyValues).filter((entry) => typeof entry[1] === 'boolean');
1290
+ if (assignments.length)
1291
+ nestedBooleans.set(item.model, { componentId: comp.id, values: Object.fromEntries(assignments) });
1292
+ }
1158
1293
  }
1159
1294
  if (doc.componentPlacements?.[n.id] === comp.id)
1160
1295
  item.model.mainOf = comp.id;
@@ -1163,12 +1298,14 @@ function convert(doc, pages, options, explicit, expanded) {
1163
1298
  markSet(item.model, comp, props);
1164
1299
  }
1165
1300
  };
1301
+ if (kept)
1302
+ placed.box = kept;
1166
1303
  if (s === 1) {
1167
1304
  const item = visit(root, parent, inner, placed, depth + 1);
1168
1305
  if (item) {
1169
- markInstance(item);
1170
1306
  if (kitFixes)
1171
1307
  topAlignTallInput(item, comp);
1308
+ markInstance(item);
1172
1309
  }
1173
1310
  return item;
1174
1311
  }
@@ -1177,22 +1314,39 @@ function convert(doc, pages, options, explicit, expanded) {
1177
1314
  ovr[0] = unscale(eff.overrides, s);
1178
1315
  // A scaled instance (Figma's scale tool): its contents are laid out at size / s and drawn scaled by s.
1179
1316
  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);
1317
+ const unscaledFrame = { ...placed.frame, width: placed.frame.width / s, height: placed.frame.height / s };
1318
+ if (fillScope)
1319
+ fillScope.fillScale = s;
1320
+ const item = visit(root, parent, inner, { ...placed, frame: unscaledFrame }, depth + 1);
1321
+ if (!item)
1322
+ return;
1323
+ if (kitFixes)
1324
+ topAlignTallInput(item, comp);
1325
+ const t = item.model.t;
1326
+ for (let i = 0; i < 4; i++)
1327
+ t[i] = +(t[i] * s).toFixed(6);
1328
+ if (!kept && rotation && (n.flipX || n.flipY)) {
1329
+ // Restore the rotation pivot of the placed box before reflecting the root.
1330
+ const full = transformOf(placed.frame, rotation), unscaled = transformOf(unscaledFrame, rotation);
1331
+ t[4] += full[4] - unscaled[4];
1332
+ t[5] += full[5] - unscaled[5];
1187
1333
  }
1334
+ markInstance(item);
1188
1335
  return item;
1189
1336
  }
1337
+ if (n.flipX || n.flipY)
1338
+ drop('layer flip');
1190
1339
  const f = { ...frame };
1191
1340
  for (const k of ['x', 'y', 'width', 'height'])
1192
1341
  if ((!place || ((place.trial || place.swapped) && k in (eff.variantSize ?? {}))) && eff[k] !== undefined)
1193
1342
  f[k] = eff[k];
1194
1343
  // 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')
1344
+ if (kept) {
1345
+ const [a, b, c, d, x, y] = kept.transform;
1346
+ const { width, height } = kept;
1347
+ Object.assign(f, { width, height, x: x + ((a - 1) * width + c * height) / 2, y: y + (b * width + (d - 1) * height) / 2 });
1348
+ }
1349
+ else if (rs && !place && f.width !== undefined && n.shape !== 'path')
1196
1350
  follow(f, eff.constraints, rs);
1197
1351
  // Absolute children follow constraints; auto-layout children are positioned below.
1198
1352
  // A size from the component's own expressions is the variant's size, which its children were placed in.
@@ -1208,12 +1362,28 @@ function convert(doc, pages, options, explicit, expanded) {
1208
1362
  if (n.type === 'group' && !(place?.constraints ?? eff.constraints) && transformOf(f, rotation).slice(0, 4).join() === '1,0,0,1') {
1209
1363
  mine = rs && { ...rs, at: [(rs.at?.[0] ?? 0) + (f.x ?? 0), (rs.at?.[1] ?? 0) + (f.y ?? 0)] };
1210
1364
  }
1211
- for (const k of ['fills', 'strokes', 'shadows', 'backgroundBlur', 'layerBlur', 'cornerRadii', 'cornerRadius'])
1365
+ for (const k of ['fills', 'strokes', 'shadows', 'backgroundBlur', 'layerBlur', 'cornerRadii', 'cornerRadius', 'cornerSmoothing'])
1212
1366
  if (eff[`style.${k}`] !== undefined)
1213
1367
  style[k] = eff[`style.${k}`];
1214
1368
  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) };
1369
+ const m = { ...common, kind: 'frame', t: kept ? [...kept.transform] : transformOf(f, rotation), w: f.width, h: f.height, clip: !!(eff.clipContent) };
1370
+ // naturalSize only reads the trial root's dimensions. Children can size a hug frame
1371
+ // or a boolean group. An ordinary fixed frame only applies its layout minimums.
1372
+ if (file && L && place?.trial && n.type === 'frame' && !n.metadata?.figma?.boolean) {
1373
+ const node = { ...eff, sizing: { width: n.layout?.widthSizing, height: n.layout?.heightSizing },
1374
+ resizing: { ...eff.resizing, ...place.resizing } };
1375
+ const item = { model: m, node, children: [] };
1376
+ const fixed = !['horizontal', 'vertical'].includes(node.layout?.kind) ||
1377
+ (sizingOf(node, 'width') !== 'hug' && sizingOf(node, 'height') !== 'hug');
1378
+ if (fixed && !L.children.some(containsInstance)) {
1379
+ layoutFrame(item);
1380
+ return item;
1381
+ }
1382
+ }
1216
1383
  appearance(m, style, 'frame', n.metadata?.figma);
1384
+ if (n.metadata?.figma?.strokesIncluded === true && (eff.layout?.kind === 'horizontal' || eff.layout?.kind === 'vertical')) {
1385
+ eff.layout = { ...eff.layout, strokesIncluded: true };
1386
+ }
1217
1387
  const r = radii(style);
1218
1388
  if (r)
1219
1389
  m.radius = r;
@@ -1225,6 +1395,13 @@ function convert(doc, pages, options, explicit, expanded) {
1225
1395
  m.group = true;
1226
1396
  note('groups marked as groups');
1227
1397
  }
1398
+ // A Figma boolean operation figma-import keeps live (metadata.figma.boolean, taco patch 0010) is a boolean group.
1399
+ const bool = n.type === 'frame' ? n.metadata?.figma?.boolean : undefined;
1400
+ if (bool && BOOLEAN_OPS.has(bool.operation)) {
1401
+ m.group = true;
1402
+ m.boolean = bool.operation;
1403
+ note('Figma boolean operations as boolean groups');
1404
+ }
1228
1405
  models.push(m);
1229
1406
  // The outermost instance that fills a slot wins, as an outer override does (p7 Autocomplete: the selected state's
1230
1407
  // search field fills its tag list with five tags; the tag list instance inside it fills the same slot with three).
@@ -1270,6 +1447,8 @@ function convert(doc, pages, options, explicit, expanded) {
1270
1447
  children.push(converted);
1271
1448
  }
1272
1449
  }
1450
+ if (n.type === 'group' && figma?.fillSizing)
1451
+ fitGroupFill(eff.resizing, m, children);
1273
1452
  const viewportTransform = n.metadata?.svgViewportTransform;
1274
1453
  if (viewportTransform)
1275
1454
  for (const { model } of children)
@@ -1284,7 +1463,60 @@ function convert(doc, pages, options, explicit, expanded) {
1284
1463
  else
1285
1464
  delete c.model.storedHeight;
1286
1465
  }
1287
- stretchLines(n, children);
1466
+ stretchLines(n, children, m, eff.layout?.strokesIncluded);
1467
+ // A boolean group fits its layers' boxes, as the editor's layout fits a group (layout.ts fitGroup), so that it
1468
+ // does not move them when the document loads. Its first result is the outline Figma stored for it (carried in the
1469
+ // operation's own space), as the path it was flattened to (resized with its constraints in a resized instance, as
1470
+ // that path was), moved into the fitted group's space, so it draws as that path did. The renderer recuts it
1471
+ // when an instance changes an operand through overrides, properties or stored geometry.
1472
+ if (m.boolean) {
1473
+ const own = bool.fixedBox ? { t: m.t, w: m.w, h: m.h } : undefined;
1474
+ const kids = children.map((c) => c.model).filter(Boolean), boxes = kids.map((k) => box(k));
1475
+ if (boxes.length) {
1476
+ const x = Math.min(...boxes.map((b) => b[0])), y = Math.min(...boxes.map((b) => b[1]));
1477
+ for (const k of kids) {
1478
+ k.t = [...k.t.slice(0, 4), k.t[4] - x, k.t[5] - y];
1479
+ // Restore the stored box in the fitted group's coordinates after layout.
1480
+ const saved = keptGeometry.get(k);
1481
+ if (saved) {
1482
+ saved.t[4] = saved.t[4] - x;
1483
+ saved.t[5] = saved.t[5] - y;
1484
+ }
1485
+ }
1486
+ m.t = mul(m.t, [1, 0, 0, 1, x, y]);
1487
+ m.w = Math.max(...boxes.map((b) => b[2])) - x;
1488
+ m.h = Math.max(...boxes.map((b) => b[3])) - y;
1489
+ }
1490
+ const reshaped = (id) => doc.nodes[id]?.children?.some((c) => ctx.ovr?.some((o) => Object.keys(o?.[c] ?? {}).some((k) => !LOOK_ONLY.has(k)))
1491
+ || (ctx.comps?.length && (doc.nodes[c]?.condition !== undefined || Object.keys(doc.nodes[c]?.expressions ?? {}).some((k) => !LOOK_ONLY.has(k)))) || reshaped(c)) ?? false;
1492
+ const hasStoredOperand = (item) => keptGeometry.has(item.model) || item.children.some(hasStoredOperand);
1493
+ const recut = !!bool.vectorNetwork && (reshaped(n.id) || (ctx.boxScopes && children.some(hasStoredOperand)));
1494
+ if (recut)
1495
+ note('Figma boolean operations an instance reshapes, cut by the renderer rather than drawn from their stored outline');
1496
+ if (bool.vectorNetwork && bool.transform && frame && (rs || !mine) && !recut) {
1497
+ const before = models.length;
1498
+ 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);
1499
+ models.length = before; // scratch geometry, not a layer
1500
+ if (flat?.kind === 'path')
1501
+ m.result = transformNet(flat.net, mul(inv(m.t), flat.t));
1502
+ }
1503
+ // One with no stored outline in an auto layout flow, whose operands do not fill its box (figma-import's
1504
+ // `fixedBox`), sits in a plain frame of the operation's own box, so the flow places its siblings as Figma did.
1505
+ if (bool.fixedBox && !m.result && own) {
1506
+ 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 };
1507
+ for (const k of BOOLEAN_OWN)
1508
+ if (k in m) {
1509
+ inner[k] = m[k];
1510
+ delete m[k];
1511
+ }
1512
+ for (const k of kids)
1513
+ k.parent = inner.id;
1514
+ Object.assign(m, own);
1515
+ models.splice(models.indexOf(m) + 1, 0, inner);
1516
+ wrappedBoolean.set(m, inner);
1517
+ note('Figma boolean operations with no stored outline kept at their own size in a flow, in a plain frame');
1518
+ }
1519
+ }
1288
1520
  // A trial layout (instanceScale) or a swapped component sizes the root as its component does, except that a
1289
1521
  // swapped instance filling its parent keeps filling it (Figma keeps the slot's fill across a swap: p7
1290
1522
  // Autocomplete's search field fills its 248 px list box instead of hugging its component's 280 px; p0 Cover menu
@@ -1305,6 +1537,9 @@ function convert(doc, pages, options, explicit, expanded) {
1305
1537
  note('hug frames around stale-box text kept inside instances stored shorter than their contents');
1306
1538
  }
1307
1539
  m.layoutData = layoutData(item.node, item.instance);
1540
+ const flow = m.layoutData.layout?.kind;
1541
+ if (n.type === 'frame' && n.metadata?.figma?.firstOnTop === true && (flow === 'horizontal' || flow === 'vertical'))
1542
+ m.firstOnTop = true;
1308
1543
  // Figma lays out again an instance it re-hugs, nested instances and all, and stores the result: where the stored
1309
1544
  // main-axis size is not what its children's stored sizes add up to, the nested ones were laid out anew and the
1310
1545
  // editor must not hold them at their stored sizes either (`relaid`, scene.ts fit; p67 TextField fields are 88 px
@@ -1315,7 +1550,7 @@ function convert(doc, pages, options, explicit, expanded) {
1315
1550
  const lay = item.node.layout, axis = lay?.kind === 'horizontal' ? 'w' : 'h';
1316
1551
  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
1552
  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 };
1553
+ const pad = commands.insetsIn(m);
1319
1554
  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
1555
  if (flowing.length && (item.remeasured ? Math.abs(sum - m[axis]) : sum - m[axis]) > 0.5) {
1321
1556
  m.layoutData.relaid = true;
@@ -1339,10 +1574,14 @@ function convert(doc, pages, options, explicit, expanded) {
1339
1574
  unfreeze(item);
1340
1575
  }
1341
1576
  }
1577
+ if ((flow === 'horizontal' || flow === 'vertical') && children.some(({ model }) => storedFillSizes.has(model) &&
1578
+ (model.layoutData?.resizing?.width === 'fill' || model.layoutData?.resizing?.height === 'fill'))) {
1579
+ stacksWithStoredFill.push(item);
1580
+ }
1342
1581
  const variant = wrapped(item);
1343
1582
  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);
1583
+ wrappers.push([m, variant.model, commands.insetsIn(m)]);
1584
+ layoutFrame(item, kept && !m.group ? { width: kept.width, height: kept.height } : undefined);
1346
1585
  // A hug frame stored as resizing 'fixed' hugs here, but where hugging gives back its stored size the editor keeps
1347
1586
  // that size: a later re-measure (of text, say) must not move what already matches Figma. A frame holding text an
1348
1587
  // override changed (which the editor measures) still hugs, as Figma re-hugs it: p73's "Bold", "Italic" and
@@ -1373,24 +1612,32 @@ function convert(doc, pages, options, explicit, expanded) {
1373
1612
  // The visual frame a hug wrapper root gave that kept height holds it too (layoutFrame's wrapper allocation); a
1374
1613
  // component swapped in there takes its own size.
1375
1614
  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)) });
1615
+ const p = commands.insetsIn(m);
1616
+ resize(children[0], { height: Math.max(0, m.h - p.top - p.bottom) });
1378
1617
  children[0].model.layoutData.sizing = { ...children[0].model.layoutData.sizing, height: 'fixed' };
1379
1618
  }
1380
1619
  applyMasks(m, children);
1381
1620
  return item;
1382
1621
  }
1383
1622
  if (n.type === 'text') {
1384
- const model = textNode(n, L ? { ...eff, ...resolvedText(r, full, eff, copiedColours) } : eff, o, common, f, rotation, style);
1623
+ const model = textNode(n, L ? { ...eff, ...resolvedText(r, full, eff, copiedColours) } : eff, o, common, f, rotation, style, ctx.modes);
1624
+ if (kept) {
1625
+ model.t = [...kept.transform];
1626
+ model.h = kept.height;
1627
+ if (model.autoResize)
1628
+ model.keepSize = true;
1629
+ delete model.storedHeight;
1630
+ }
1385
1631
  model.layoutData = layoutData(eff);
1386
1632
  const stored = (n.paragraphs ?? []).map((p) => (p.runs ?? []).map((r) => r.text ?? '').join('')).join('\n');
1387
1633
  return { model, node: eff, children: [], changedText: eff.autoResize === 'width-and-height' && model.content !== stored };
1388
1634
  }
1389
1635
  if (n.type === 'shape') {
1390
- const model = shapeNode(n, eff, common, f, rotation, style, rs);
1636
+ const children = [];
1637
+ const model = shapeNode(n, eff, common, f, rotation, style, kept ? null : rs, kept, children);
1391
1638
  if (model)
1392
1639
  model.layoutData = { ...layoutData(eff), ...model.layoutData };
1393
- return model ? { model, node: eff, children: [] } : undefined;
1640
+ return model ? { model, node: eff, children } : undefined;
1394
1641
  }
1395
1642
  drop(`node type ${n.type}`);
1396
1643
  }
@@ -1398,12 +1645,13 @@ function convert(doc, pages, options, explicit, expanded) {
1398
1645
  // auto-layout row or column that spans the frame's whole stored inner cross size is a stretched divider: it fills the
1399
1646
  // cross axis, so it shortens with added padding (p73 ToggleButtonGroup dividers: 32 px stored, 20 px in Figma once the
1400
1647
  // group pads them by 10 px).
1401
- function stretchLines(n, children) {
1648
+ function stretchLines(n, children, model, strokesIncluded) {
1402
1649
  const layout = n.layout;
1403
1650
  if (!['horizontal', 'vertical'].includes(layout?.kind) || layout.wrap || !n.frame)
1404
1651
  return;
1405
1652
  const [cross, main] = layout.kind === 'horizontal' ? ['height', 'width'] : ['width', 'height'];
1406
- const p = { top: 0, right: 0, bottom: 0, left: 0, ...layout.padding };
1653
+ const p = strokesIncluded ? commands.insetsIn({ ...model, layoutData: { layout: { ...layout, strokesIncluded } } })
1654
+ : { top: 0, right: 0, bottom: 0, left: 0, ...layout.padding };
1407
1655
  const inner = n.frame[cross] - (cross === 'height' ? p.top + p.bottom : p.left + p.right);
1408
1656
  for (const child of children) {
1409
1657
  if (child.model.kind !== 'path' || child.node.resizing || child.node.layoutPositioning === 'absolute')
@@ -1486,7 +1734,7 @@ function convert(doc, pages, options, explicit, expanded) {
1486
1734
  const [a, b, cc, d] = c.model.t;
1487
1735
  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
1736
  };
1489
- const p = { top: 0, right: 0, bottom: 0, left: 0, ...layout.padding, ...item.node.padding };
1737
+ const p = commands.insetsIn(item.model);
1490
1738
  const pad = axis === 'width' ? p.left + p.right : p.top + p.bottom, sizes = kids.map(box);
1491
1739
  const along = (layout.kind === 'horizontal') === (axis === 'width');
1492
1740
  return pad + (along ? sizes.reduce((x, y) => x + y, 0) + (layout.gap ?? 0) * (kids.length - 1) : Math.max(...sizes));
@@ -1509,7 +1757,9 @@ function convert(doc, pages, options, explicit, expanded) {
1509
1757
  return o.textStyle?.lineHeight !== undefined;
1510
1758
  if (key === 'padding')
1511
1759
  return o.padding !== undefined || o.layout?.padding !== undefined;
1512
- if (['gap', 'align', 'justify'].includes(key))
1760
+ if (key === 'direction' || key === 'layout.kind')
1761
+ return o.layout?.kind !== undefined;
1762
+ if (['gap', 'align', 'justify', 'wrap', 'wrapGap'].includes(key))
1513
1763
  return o.layout?.[key] !== undefined;
1514
1764
  if (key === 'layout.widthSizing' || key === 'resizing.width')
1515
1765
  return o.sizing?.width !== undefined;
@@ -1669,6 +1919,10 @@ function convert(doc, pages, options, explicit, expanded) {
1669
1919
  eff.characters = v;
1670
1920
  return;
1671
1921
  }
1922
+ if ((key === 'startCap' || key === 'endCap') && STROKE_CAPS.includes(v)) {
1923
+ eff[key] = v;
1924
+ return;
1925
+ }
1672
1926
  if (key === 'fontFamily' && typeof v === 'string') {
1673
1927
  eff.fontFamily = v;
1674
1928
  return;
@@ -1731,13 +1985,26 @@ function convert(doc, pages, options, explicit, expanded) {
1731
1985
  }
1732
1986
  return style.cornerRadius > 0 ? style.cornerRadius : null;
1733
1987
  }
1988
+ // Older Taco records can store a CSS angle in place of linear gradient endpoints.
1989
+ const paintInBox = (p, m) => p?.kind === 'linear-gradient' && !p.from && !p.to && Number.isFinite(p.angle ?? 180)
1990
+ ? { ...p, ...linearEndpoints(p.angle ?? 180, localBox(m)) } : resolveLinearCall(p, () => localBox(m));
1991
+ function fillPaint(p, tile, m, cropLayerBox, cropPaintBox) {
1992
+ const converted = paint(paintInBox(p, m), tile);
1993
+ const crop = converted?.k === 'image' && imageCropOf(p);
1994
+ if (!crop)
1995
+ return converted;
1996
+ const placement = imageCropPlacement(crop, cropPaintBox ?? localBox(m), cropLayerBox);
1997
+ if (placement)
1998
+ return { ...converted, ...placement };
1999
+ approximate('image crop cannot be represented by the paint transform');
2000
+ return converted;
2001
+ }
1734
2002
  // Fills, the first stroke and effects. One shown solid fill goes in the compact record; anything more in look.fills.
1735
2003
  // carried: what figma-import carries in the node's metadata.figma (taco/figma-import/import/carry.ts), whose fill and
1736
2004
  // shadow indexes are into the node's own style lists.
1737
- function appearance(m, style, kind, carried = {}) {
2005
+ function appearance(m, style, kind, carried = {}, cropLayerBox) {
1738
2006
  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 = {};
2007
+ const fills = (style.fills ?? []).map((p, i) => fillPaint(p, tiles.get(i), m, cropLayerBox)).filter(Boolean), look = {};
1741
2008
  if (fills.length === 1 && fills[0].k === 'solid' && fills[0].o === 1 && fills[0].visible !== false)
1742
2009
  m.fill = fills[0].c;
1743
2010
  else if (fills.length)
@@ -1748,7 +2015,7 @@ function convert(doc, pages, options, explicit, expanded) {
1748
2015
  note('tiled image fills');
1749
2016
  const strokes = (style.strokes ?? []).filter((s) => s.paint?.visible !== false && (s.width > 0 || s.fileBoundWidth && s.width === 0));
1750
2017
  if (strokes.length) {
1751
- const s = strokes[0], p = paint(inBox(s.paint));
2018
+ const s = strokes[0], p = paint(paintInBox(s.paint, m));
1752
2019
  if (strokes.length > 1)
1753
2020
  drop('additional strokes', strokes.length - 1);
1754
2021
  if (p) {
@@ -1762,11 +2029,11 @@ function convert(doc, pages, options, explicit, expanded) {
1762
2029
  }
1763
2030
  if (s.dash?.length)
1764
2031
  st.dash = s.dash;
1765
- // Per-side weights (strokeTopWeight etc.). The scene keeps them on containers only; on a path, equal sides are
2032
+ // The scene keeps side weights on containers, including native rectangles. On a path, equal sides are
1766
2033
  // its stroke width (all 398 path cases in the kit: checkbox bases at 1 px on every side), unequal ones are dropped.
1767
2034
  if (s.sides) {
1768
2035
  const v = [s.sides.top, s.sides.right, s.sides.bottom, s.sides.left].map((x) => x ?? 0);
1769
- if (kind === 'frame')
2036
+ if (kind === 'frame' || kind === 'rect')
1770
2037
  st.sides = v;
1771
2038
  else if (v.every((x) => x === v[0])) {
1772
2039
  m.strokeWidth = v[0];
@@ -1827,10 +2094,23 @@ function convert(doc, pages, options, explicit, expanded) {
1827
2094
  axis(c.horizontal, 'x', 'width', rs.dw, rs.sx, rs.at?.[0] ?? 0);
1828
2095
  axis(c.vertical, 'y', 'height', rs.dh, rs.sy, rs.at?.[1] ?? 0);
1829
2096
  }
1830
- function shapeNode(n, eff, common, f, rotation, style, rs) {
1831
- let net, t, box, shape, regionFills = [];
2097
+ // The renderer samples region images in the union of the regions' bounds, excluding unfilled edges and vertices.
2098
+ function regionImageBox(net) {
2099
+ const ids = new Set();
2100
+ for (const region of net.regions ?? [])
2101
+ for (const loop of region.loops)
2102
+ for (const [id] of loop.refs)
2103
+ ids.add(id);
2104
+ const segments = net.segments.filter(s => ids.has(s.id));
2105
+ const endpoints = new Set(segments.flatMap(s => [s.a, s.b]));
2106
+ return netBounds({ vertices: net.vertices.filter(v => endpoints.has(v.id)), segments });
2107
+ }
2108
+ function shapeNode(n, eff, common, f, rotation, style, rs, kept, children) {
2109
+ let net, t, box, shape;
2110
+ let regionFills = [];
2111
+ let cropLayerBox;
1832
2112
  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 };
2113
+ const m = { ...common, kind: 'rect', t: kept ? [...kept.transform] : transformOf(f, rotation), w: f.width, h: f.height, radius: radii(style) ?? 0 };
1834
2114
  if (style.cornerSmoothing)
1835
2115
  m.smoothing = style.cornerSmoothing;
1836
2116
  appearance(m, style, 'rect', n.metadata?.figma);
@@ -1838,14 +2118,16 @@ function convert(doc, pages, options, explicit, expanded) {
1838
2118
  return m;
1839
2119
  }
1840
2120
  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]]));
2121
+ const vn = n.vectorNetwork, r4 = (x) => (Number.isInteger(x) ? x : +x.toFixed(4)) || 0;
2122
+ let at;
1843
2123
  // An elliptical arc (svg-import keeps SVG's) becomes cubics of at most 90 degrees, through new vertices; its id
1844
2124
  // stands for them all in the regions' loops (`parts`).
1845
2125
  const vertices = vn.vertices.map((v) => ({ id: v.id, x: r4(v.x), y: r4(v.y) })), segments = [], parts = new Map();
1846
2126
  let arcs = 0;
1847
2127
  for (const s of vn.segments) {
1848
- if (s.kind === 'elliptical-arc' && at.has(s.start) && at.has(s.end)) {
2128
+ if (s.kind === 'elliptical-arc')
2129
+ at ??= new Map(vn.vertices.map((v) => [v.id, [v.x, v.y]]));
2130
+ if (s.kind === 'elliptical-arc' && at?.has(s.start) && at.has(s.end)) {
1849
2131
  const { points, handles } = arcCubics(at.get(s.start), at.get(s.end), s.radiusX, s.radiusY, s.xAxisRotation ?? 0, !!s.largeArc, !!s.sweep);
1850
2132
  if (handles.length) {
1851
2133
  arcs++;
@@ -1865,8 +2147,8 @@ function convert(doc, pages, options, explicit, expanded) {
1865
2147
  approximate('elliptical arcs split into cubics');
1866
2148
  net = { vertices, segments, loops: [], next: vertices.length + segments.length };
1867
2149
  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) => {
2150
+ const regions = (vn.regions ?? []).filter((r) => r.loops.length);
2151
+ net.regions = regions.map((r) => ({ w: r.windingRule === 'evenodd' ? 1 : 0, loops: r.loops.map((l) => {
1870
2152
  const refs = l.segments.flatMap((x) => {
1871
2153
  const rev = x.direction === 'reverse', ids = parts.get(x.segmentId) ?? [x.segmentId];
1872
2154
  return (rev ? [...ids].reverse() : ids).map((id) => [id, rev]);
@@ -1874,8 +2156,21 @@ function convert(doc, pages, options, explicit, expanded) {
1874
2156
  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
2157
  return { refs, open: start(refs[0]) !== end(refs[refs.length - 1]) };
1876
2158
  }) }));
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));
2159
+ regionFills = regions.map((r) => r.fills);
2160
+ t = (kept?.transform ?? eff.exprTransform ?? n.transform ?? [1, 0, 0, 1, f.x ?? 0, f.y ?? 0]).map((v) => +v.toFixed(6));
2161
+ if (kept?.pathScale) {
2162
+ let [sx, sy] = kept.pathScale;
2163
+ // Free-layout boxes can also describe a flow child in a nested stack.
2164
+ if ((sx === 0 && eff.resizing?.width === 'fill') || (sy === 0 && eff.resizing?.height === 'fill')) {
2165
+ const bounds = pathBounds({ t, net });
2166
+ if (sx === 0 && eff.resizing?.width === 'fill' && bounds.width)
2167
+ sx = 1e-3 / bounds.width;
2168
+ if (sy === 0 && eff.resizing?.height === 'fill' && bounds.height)
2169
+ sy = 1e-3 / bounds.height;
2170
+ }
2171
+ if (sx !== 1 || sy !== 1)
2172
+ net = transformNet(net, [sx, 0, 0, sy, 0, 0]);
2173
+ }
1879
2174
  // A path has no frame: its network scales under a scale or stretch constraint, and its translation moves with
1880
2175
  // the constraint. A stretched path keeps its outline's near edge, which is not its translation when it is turned
1881
2176
  // or its outline does not start at its origin. As in host-layout's resize, a path squeezed to nothing keeps a
@@ -1918,19 +2213,20 @@ function convert(doc, pages, options, explicit, expanded) {
1918
2213
  // A Figma STAR or REGULAR_POLYGON (figma-import carries its parameters, metadata.figma.shape) is the parametric
1919
2214
  // polygon or star (core/shapes.ts) in its box, as Figma draws it: outer points on the box's ellipse, from the top.
1920
2215
  // 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)) {
2216
+ const sp = n.metadata?.figma?.shape, width = kept?.width ?? sp?.width, height = kept?.height ?? sp?.height;
2217
+ if ((sp?.type === 'polygon' || sp?.type === 'star') && width > 0 && height > 0 && !rs && !(style.cornerRadius > 0)
2218
+ && regionFills.every(fills => fills === undefined)) {
1923
2219
  const count = Math.min(60, Math.max(3, Math.round(sp.count)));
1924
2220
  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 = [];
2221
+ cropLayerBox = { x: 0, y: 0, width, height };
2222
+ net = shapes.shapeNet(shape, cropLayerBox);
2223
+ box = pathBounds({ t, net: network([[0, 0], [width, 0], [width, height], [0, height]], true) });
1928
2224
  note('Figma stars and polygons drawn as parametric shapes');
1929
2225
  }
1930
2226
  }
1931
2227
  else {
1932
2228
  const w = f.width, h = f.height;
1933
- t = transformOf(f, rotation);
2229
+ t = kept ? [...kept.transform] : transformOf(f, rotation);
1934
2230
  if (n.shape === 'rectangle')
1935
2231
  net = network([[0, 0], [w, 0], [w, h], [0, h]], true);
1936
2232
  else if (n.shape === 'line')
@@ -1940,7 +2236,8 @@ function convert(doc, pages, options, explicit, expanded) {
1940
2236
  net = ellipseNetwork(w, h);
1941
2237
  const a = n.arc, lo = Math.min(a?.startingAngle ?? 0, a?.endingAngle ?? 360), hi = Math.max(a?.startingAngle ?? 0, a?.endingAngle ?? 360);
1942
2238
  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).
2239
+ // An arc keeps its full ellipse box for layout and Figma's crop coordinates.
2240
+ cropLayerBox = { x: 0, y: 0, width: w, height: h };
1944
2241
  if (a && a.innerRadius >= 0.99 && hi - lo < 360 && style.strokes?.length) {
1945
2242
  box = pathBounds({ t, net });
1946
2243
  net = arcNetwork(rx, ry, lo, hi);
@@ -1958,7 +2255,7 @@ function convert(doc, pages, options, explicit, expanded) {
1958
2255
  else if (a && (a.innerRadius > 0 || !whole)) {
1959
2256
  box = pathBounds({ t, net });
1960
2257
  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 });
2258
+ net = shapes.shapeNet(shape, cropLayerBox);
1962
2259
  note('ellipse arcs, pies and rings drawn as parametric ellipses');
1963
2260
  }
1964
2261
  }
@@ -1967,21 +2264,19 @@ function convert(doc, pages, options, explicit, expanded) {
1967
2264
  return;
1968
2265
  }
1969
2266
  }
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
2267
  const m = { ...common, kind: 'path', t, net };
2268
+ const cropSize = n.metadata?.figma?.regionCropSize;
2269
+ const regionCropLayerBox = cropSize && { x: 0, y: 0, width: kept?.width ?? cropSize.width, height: kept?.height ?? cropSize.height };
2270
+ const regionCropPaintBox = regionFills.some(fills => fills?.some(imageCropOf)) ? regionImageBox(net) : undefined;
2271
+ for (const [i, fills] of regionFills.entries()) {
2272
+ if (fills !== undefined)
2273
+ net.regions[i].fills = fills.map(p => fillPaint(p, imageTileOf(p), m, regionCropLayerBox, regionCropPaintBox)).filter(Boolean);
2274
+ }
1980
2275
  if (shape)
1981
2276
  m.shape = shape;
1982
2277
  if (box)
1983
2278
  m.layoutData = { box };
1984
- appearance(m, style, 'path', n.metadata?.figma);
2279
+ appearance(m, style, 'path', n.metadata?.figma, cropLayerBox);
1985
2280
  if (n.shape === 'rectangle') {
1986
2281
  const r = radii(style);
1987
2282
  if (r) {
@@ -1991,61 +2286,109 @@ function convert(doc, pages, options, explicit, expanded) {
1991
2286
  delete m.corners;
1992
2287
  }
1993
2288
  }
1994
- strokeCaps(m, n);
2289
+ strokeCaps(m, eff);
2290
+ // A leaf applies opacity to each paint. Isolate these paths so the region fills and stroke composite at full
2291
+ // opacity before applying the layer opacity once, as with the former multi-path group.
2292
+ if (common.opacity > 0 && common.opacity < 1 && regionFills.length > 1 && regionFills.some(fills => fills !== undefined)
2293
+ && !n.mask && !n.isMask) {
2294
+ const b = pathBounds(m);
2295
+ const group = {
2296
+ ...common, kind: 'frame', group: true, clip: false, w: b.width, h: b.height,
2297
+ t: [1, 0, 0, 1, t[4] + b.x, t[5] + b.y],
2298
+ };
2299
+ const path = { ...m, id: newId(), parent: group.id, opacity: 1, t: [t[0], t[1], t[2], t[3], -b.x, -b.y] };
2300
+ for (const key of ['sourceId', 'blend', 'exports', 'visible'])
2301
+ delete path[key];
2302
+ const fills = eff.resizing?.width === 'fill' || eff.resizing?.height === 'fill';
2303
+ const constrained = ['scale', 'left-right'].includes(eff.constraints?.horizontal) ||
2304
+ ['scale', 'top-bottom'].includes(eff.constraints?.vertical);
2305
+ if (children && (fills || constrained)) {
2306
+ const node = { constraints: { horizontal: 'scale', vertical: 'scale' } };
2307
+ path.layoutData = { ...path.layoutData, ...node };
2308
+ children.push({ model: path, node, children: [] });
2309
+ if (fills) {
2310
+ eff.resizing = { ...eff.resizing };
2311
+ fitGroupFill(eff.resizing, group, children);
2312
+ }
2313
+ }
2314
+ models.push(group, path);
2315
+ return group;
2316
+ }
1995
2317
  models.push(m);
1996
2318
  return m;
1997
2319
  }
1998
- // Stroke caps need an open chain whose two ends each appear once (SPEC 3.6).
1999
2320
  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))
2321
+ const { net } = m;
2322
+ if (!m.stroke || !net.segments.length)
2323
+ return;
2324
+ const start = n.startCap ?? 'none', end = n.endCap ?? 'none';
2325
+ const overrides = n.metadata?.figma?.vectorStrokeCaps;
2326
+ const hasOverrides = overrides !== undefined && Object.keys(overrides).length > 0;
2327
+ // A vector converted to a stretchable line carries explicit flat ends in its pair.
2328
+ const flatLineEnds = n.shape === 'line' && n.startCap === 'none' && n.endCap === 'none' && Boolean(m.look?.stroke?.cap);
2329
+ if (start === 'none' && end === 'none' && !hasOverrides && !flatLineEnds)
2330
+ return;
2331
+ const degree = new Map();
2332
+ for (const { a, b } of net.segments) {
2333
+ degree.set(a, (degree.get(a) ?? 0) + 1);
2334
+ degree.set(b, (degree.get(b) ?? 0) + 1);
2335
+ }
2336
+ const first = net.segments[0].a, last = net.segments.at(-1).b;
2337
+ const pairEligible = degree.get(first) === 1 && degree.get(last) === 1;
2338
+ const codes = [STROKE_CAPS.indexOf(start), STROKE_CAPS.indexOf(end)];
2339
+ if (overrides === undefined) {
2340
+ if (pairEligible && codes.every(code => code >= 0))
2341
+ m.caps = codes;
2342
+ else if (degree.get(first) !== 2 || degree.get(last) !== 2)
2010
2343
  drop('stroke caps (network ends not single)');
2344
+ return;
2011
2345
  }
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);
2346
+ // Keep the existing pair for a single ordered chain. Vertex caps leave every other network's joins and regions intact.
2347
+ if (!hasOverrides && pairEligible && degree.size === net.segments.length + 1
2348
+ && net.segments.every((s, i) => i === 0 || s.a === net.segments[i - 1].b)) {
2349
+ m.caps = codes;
2350
+ return;
2351
+ }
2352
+ const vertices = net.vertices.map(v => {
2353
+ if (degree.get(v.id) !== 1)
2354
+ return v;
2355
+ const own = overrides[v.id];
2356
+ if (own !== undefined)
2357
+ return { ...v, cap: own };
2358
+ if (start === end || v.id === first)
2359
+ return start === 'none' ? v : { ...v, cap: start };
2360
+ return v.id === last && end !== 'none' ? { ...v, cap: end } : v;
2028
2361
  });
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);
2362
+ m.net = { ...net, vertices };
2363
+ }
2364
+ function fitGroupFill(resizing, group, children) {
2365
+ for (const [axis, size, min, max] of [['width', group.w, 'minWidth', 'maxWidth'], ['height', group.h, 'minHeight', 'maxHeight']]) {
2366
+ if (resizing[axis] !== 'fill')
2367
+ continue;
2368
+ const fitted = fittedGroupAxis(size, children, axis);
2369
+ if (!fitted || fitted.minimum > (resizing[max] ?? Infinity)) {
2370
+ delete resizing[axis];
2371
+ drop(`group Fill on ${axis} left out because fitting its children cannot preserve the allocation`);
2372
+ }
2373
+ else {
2374
+ group[axis === 'width' ? 'w' : 'h'] = fitted.extent;
2375
+ resizing[min] = Math.max(resizing[min] ?? 0, fitted.minimum);
2376
+ }
2034
2377
  }
2035
- note('paths with per-region fills split into one path per region');
2036
- return g;
2037
2378
  }
2038
2379
  // Text: runs take the theme style, then the run's overrides, then the instance's textStyle override and the
2039
2380
  // node's expressions.
2040
2381
  const weights = new Map();
2041
2382
  // 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]);
2383
+ const faceOf = (s) => JSON.stringify([s.fontFamily, s.fontStyle, s.fontVariations, s.openTypeFeatures, s.fontSize ?? 16, s.fontWeight ?? 400, !!s.italic, s.lineHeight ?? 1.2, s.letterSpacing ?? 0]);
2043
2384
  const runColour = (run) => ({ ...doc.theme?.textStyles?.[run.styleId], ...run.overrides }).color;
2044
2385
  const hexOf = (c) => (typeof c === 'string' ? c : c?.hex)?.toLowerCase();
2045
2386
  // A text's paragraphs: stored, or set as characters (each line one paragraph in the first run's style).
2046
2387
  function textParagraphs(paragraphs, characters) {
2047
2388
  if (characters === undefined)
2048
2389
  return paragraphs ?? [];
2390
+ if (paragraphs && linkedParagraphsMatch(characters, paragraphs))
2391
+ return paragraphs;
2049
2392
  const first = paragraphs?.[0]?.runs?.[0] ?? {};
2050
2393
  return characters.split(/\n|\u2029/).map((line) => ({ ...paragraphs?.[0], runs: [{ ...first, text: line }] }));
2051
2394
  }
@@ -2060,7 +2403,7 @@ function convert(doc, pages, options, explicit, expanded) {
2060
2403
  let color = runColour(run);
2061
2404
  if (computed !== undefined && copies.has(hexOf(color)))
2062
2405
  color = computed;
2063
- return { ...from, text: run.text, overrides: color === undefined ? from?.overrides : { ...from?.overrides, color } };
2406
+ return { ...from, text: run.text, hyperlink: run.hyperlink, overrides: color === undefined ? from?.overrides : { ...from?.overrides, color } };
2064
2407
  };
2065
2408
  const same = shown.length === base.length && shown.every((p, i) => p.runs?.length === base[i].runs?.length);
2066
2409
  if (!same)
@@ -2068,7 +2411,7 @@ function convert(doc, pages, options, explicit, expanded) {
2068
2411
  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
2412
  if (computed !== undefined)
2070
2413
  note('text override colours kept from the text colour expression');
2071
- return { paragraphs, characters: undefined, textColor: undefined, textAlign: undefined };
2414
+ return { paragraphs, characters: undefined, textColor: undefined, textAlign: undefined, maxLines: r.maxLines, truncate: r.truncate };
2072
2415
  }
2073
2416
  // A kit export fix, so it reads the export's override maps. The exporter writes a text override that changes only the
2074
2417
  // characters or the line height with the run colours it saw: the stored run colour (p64 _TableHeaderCell "Member",
@@ -2090,7 +2433,7 @@ function convert(doc, pages, options, explicit, expanded) {
2090
2433
  const shown = (r.paragraphs ?? []).flatMap((p) => (p.runs ?? []).map((run) => hexOf(runColour(run))));
2091
2434
  return shown.some((c) => copies.has(c)) ? copies : undefined;
2092
2435
  }
2093
- function textNode(n, eff, o, common, f, rotation, style) {
2436
+ function textNode(n, eff, o, common, f, rotation, style, modes) {
2094
2437
  let paragraphs = textParagraphs(eff.paragraphs, eff.characters);
2095
2438
  if (style.shadows?.length || style.layerBlur || style.backgroundBlur)
2096
2439
  drop('effects on text');
@@ -2149,10 +2492,38 @@ function convert(doc, pages, options, explicit, expanded) {
2149
2492
  faces.add(faceOf(styleLine === undefined ? s : { ...s, lineHeight: styleLine }));
2150
2493
  weights.set(weight, (weights.get(weight) ?? 0) + 1);
2151
2494
  const want = runStyle(s);
2495
+ if (r.hyperlink && !editorSchema.hyperlinkUrlAllowed)
2496
+ drop('Text hyperlink requires a newer editor');
2497
+ else if (r.hyperlink?.kind === 'url') {
2498
+ if (editorSchema.hyperlinkUrlAllowed(r.hyperlink.url))
2499
+ want.link = r.hyperlink.url;
2500
+ else
2501
+ drop('Text hyperlink with an invalid or unsupported URL');
2502
+ }
2503
+ else if (r.hyperlink?.kind === 'target') {
2504
+ // The Figma workflows resolve GUIDs after assigning native component and page IDs.
2505
+ if (deferHyperlinks)
2506
+ want.figmaHyperlink = r.hyperlink.guid;
2507
+ else
2508
+ drop('Text hyperlink whose target was not imported');
2509
+ }
2152
2510
  if (explicit && r.styleId && doc.theme?.textStyles?.[r.styleId])
2153
2511
  Object.assign(want, { textStyle: r.styleId });
2154
2512
  if (explicit && r.fileFontSize !== undefined)
2155
2513
  Object.assign(want, { fileFontSize: r.fileFontSize });
2514
+ if (file && (r.fileTextColor !== undefined || r.filePlainTextColor !== undefined)) {
2515
+ const field = r.filePlainTextColor !== undefined ? 'filePlainTextColor' : 'fileTextColor';
2516
+ const ref = r[field];
2517
+ Object.assign(want, { [field]: ref });
2518
+ if (ref)
2519
+ want.color = rgba(resolveVariable(ref, modes, doc.variableAliases)) ?? want.color;
2520
+ }
2521
+ if (file && r.fileFillStyle)
2522
+ Object.assign(want, { fileFillStyle: r.fileFillStyle });
2523
+ if (file && r.filePlainFillStyle)
2524
+ Object.assign(want, { filePlainFillStyle: r.filePlainFillStyle });
2525
+ if (file && r.filePaintOpacity !== undefined)
2526
+ want.paintOpacity = r.filePaintOpacity;
2156
2527
  const key = JSON.stringify(want);
2157
2528
  if (!keys.has(key)) {
2158
2529
  keys.set(key, styles.length);
@@ -2204,6 +2575,10 @@ function convert(doc, pages, options, explicit, expanded) {
2204
2575
  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
2576
  if (storedHeight > h)
2206
2577
  m.storedHeight = storedHeight;
2578
+ if (eff.maxLines)
2579
+ m.maxLines = eff.maxLines;
2580
+ if (eff.truncate === 'ellipsis')
2581
+ m.truncate = 'ellipsis';
2207
2582
  // 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
2583
  // line height): the editor keeps a box whose text, faces, mode and wrap width are the stored ones, and measures
2209
2584
  // the rest (changed by an override or expression), as an edit would.
@@ -2247,9 +2622,8 @@ function convert(doc, pages, options, explicit, expanded) {
2247
2622
  for (const component of Object.values(doc.components))
2248
2623
  if (!placed.has(component.id))
2249
2624
  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);
2625
+ for (const source of extraRoots)
2626
+ visit(source, '', ctx);
2253
2627
  }
2254
2628
  // A wrapper instance holds a box Figma laid out: the editor keeps it and its variant root there (wrapped in
2255
2629
  // layout.mjs; p35 DropdownItems stay 48 px, not the 56 their contents hug; p63's 86 px Tabs, though its converted
@@ -2263,28 +2637,163 @@ function convert(doc, pages, options, explicit, expanded) {
2263
2637
  else
2264
2638
  v.layoutData.instance = true;
2265
2639
  }
2640
+ function fillSize(model) {
2641
+ return model.kind === 'path' ? model.layoutData?.box ?? pathBounds(model) : { width: model.w, height: model.h };
2642
+ }
2643
+ function applyFillSize(item, saved, scale) {
2644
+ const { model } = item, original = fillSize(model);
2645
+ // Scale a path's actual outline by the change in its Figma box. Core
2646
+ // resize keeps a nonempty outline recoverable when an axis goes to zero.
2647
+ const size = saved.pathScale
2648
+ ? { width: original.width * saved.pathScale[0] / scale, height: original.height * saved.pathScale[1] / scale }
2649
+ : { width: saved.width / scale, height: saved.height / scale };
2650
+ if (model.group && saved.pathScale) {
2651
+ // The path inside an opacity group needs the same recoverable extent.
2652
+ if (size.width === 0 && original.width)
2653
+ size.width = 1e-3;
2654
+ if (size.height === 0 && original.height)
2655
+ size.height = 1e-3;
2656
+ }
2657
+ resize(item, size);
2658
+ if (!model.group)
2659
+ return;
2660
+ // If fixed children cannot fit a stored group size, retain the allocation
2661
+ // in a plain frame. The editor would otherwise fit it back on settle.
2662
+ if (sameFigmaSize(size.width, original.width) && sameFigmaSize(size.height, original.height))
2663
+ return;
2664
+ const fitted = [Infinity, Infinity, -Infinity, -Infinity];
2665
+ for (const child of item.children) {
2666
+ const [x0, y0, x1, y1] = box(child.model);
2667
+ fitted[0] = Math.min(fitted[0], x0);
2668
+ fitted[1] = Math.min(fitted[1], y0);
2669
+ fitted[2] = Math.max(fitted[2], x1);
2670
+ fitted[3] = Math.max(fitted[3], y1);
2671
+ }
2672
+ for (const [axis, index] of [['width', 0], ['height', 1]]) {
2673
+ if (sameFigmaSize(size[axis], original[axis]))
2674
+ continue;
2675
+ const fits = Math.abs(fitted[index]) < 1e-6 && sameFigmaSize(fitted[index + 2], size[axis], 1e-6);
2676
+ const min = item.node.resizing?.[axis === 'width' ? 'minWidth' : 'minHeight'] ?? 0;
2677
+ if (fits && (size[axis] >= min || sameFigmaSize(size[axis], min)))
2678
+ continue;
2679
+ delete model.group;
2680
+ const resizing = { ...item.node.resizing };
2681
+ delete resizing[axis];
2682
+ item.node.resizing = resizing;
2683
+ model.layoutData.resizing = resizing;
2684
+ approximate(`group Fill on ${axis} held in a frame at the stored instance size`, 1, model);
2685
+ }
2686
+ }
2687
+ // Stacks were collected after their children. Finalize each parent's
2688
+ // allocation before comparing its children's shares to their saved sizes.
2689
+ for (const stack of stacksWithStoredFill.reverse()) {
2690
+ const pending = stack.children.flatMap(child => {
2691
+ const size = storedFillSizes.get(child.model);
2692
+ return size ? [{ child, size }] : [];
2693
+ });
2694
+ for (const [axis, min, max] of [['width', 'minWidth', 'maxWidth'], ['height', 'minHeight', 'maxHeight']]) {
2695
+ let fills = pending.filter(({ child }) => child.node.resizing?.[axis] === 'fill');
2696
+ while (fills.length) {
2697
+ const mismatches = new Set(fills.filter(({ child, size }) => !sameFigmaSize(fillSize(child.model)[axis], size[axis], 1e-6)));
2698
+ if (!mismatches.size)
2699
+ break;
2700
+ for (const { child, size } of mismatches) {
2701
+ const { node, model } = child, value = size[axis];
2702
+ node.resizing = { ...node.resizing, [min]: value, [max]: value };
2703
+ model.layoutData.resizing = node.resizing;
2704
+ approximate(`fill ${axis} held at the stored instance size`, 1, model);
2705
+ }
2706
+ layoutFrame(stack, { width: stack.model.w, height: stack.model.h });
2707
+ fills = fills.filter(s => !mismatches.has(s));
2708
+ }
2709
+ }
2710
+ }
2711
+ for (const [model, { box, ...geometry }] of keptGeometry) {
2712
+ Object.assign(model, geometry);
2713
+ if (box)
2714
+ model.layoutData.box = box;
2715
+ }
2266
2716
  // Image assets the models use, listed in out.assets (and in the report, with their bytes).
2267
2717
  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);
2718
+ const collectImage = (p) => { if (p?.k === 'image')
2719
+ used.add(p.asset); };
2720
+ for (const m of models) {
2721
+ for (const p of m.look?.fills ?? [])
2722
+ collectImage(p);
2723
+ collectImage(m.look?.stroke?.paint);
2724
+ for (const region of m.net?.regions ?? [])
2725
+ for (const p of region.fills ?? [])
2726
+ collectImage(p);
2727
+ }
2272
2728
  for (const id of [...used].sort()) {
2273
2729
  const a = doc.assets[id], src = options.assetSrc?.(id, a) ?? `assets/${id}.${a.mimeType === 'image/jpeg' ? 'jpg' : a.mimeType.split('/')[1]}`;
2274
2730
  files.push({ id, src, mimeType: a.mimeType, data: a.source.data });
2275
2731
  assets[id] = { src, w: a.width, h: a.height };
2276
2732
  }
2277
2733
  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)
2734
+ return { out, affected, nestedBooleans, counts: { dropped, expressionErrors, notes, approximations, weights }, depth: depthMax, files };
2735
+ }
2736
+ function convert(doc, pages, options, explicit, file, deferHyperlinks = false) {
2737
+ // Drop the resolver, trial layouts and pre-layout geometry before indexing linked layers.
2738
+ const { out, affected, nestedBooleans, counts, depth, files } = expand(doc, pages, options, explicit, file, deferHyperlinks);
2739
+ const models = out.models;
2740
+ const linked = options.link === false ? null : linkWithLayers(out, true, file && (id => doc.nodes[id]?.expressions?.componentId), !!file);
2741
+ if (linked && !explicit) {
2742
+ // Clipboard mains synthesized from expansions get their presets from the source definition.
2743
+ for (const main of out.models) {
2744
+ if (main.kind !== 'frame' || main.parent !== '@components' || main.component !== main.id)
2745
+ continue;
2746
+ const source = doc.nodes[main.sourceId ?? ''];
2747
+ const exports = exportsOf(source?.exportSettings);
2748
+ if (exports)
2749
+ main.exports = exports;
2750
+ }
2751
+ }
2752
+ if (options.instanceSources && linked) {
2753
+ const sources = options.instanceSources;
2754
+ const hiddenRoots = new Set(out.models.filter(m => m.parent === '@components').map(m => m.id));
2755
+ for (const [id, copies] of linked.aliases) {
2756
+ const source = sources.get(id);
2757
+ if (source === undefined)
2758
+ continue;
2759
+ // A hidden main's root represents the component. Its descendants keep their own occurrence IDs.
2760
+ for (const copy of copies)
2761
+ if (!copy.includes(';') && !hiddenRoots.has(copy))
2762
+ sources.set(copy, source);
2763
+ }
2764
+ }
2765
+ if (file && linked) {
2766
+ file.omittedLinks = linked.omittedLinks;
2767
+ const { expanded } = file;
2768
+ // Only appearance and text are needed after linking. The resource stage may replace
2769
+ // paints on a surviving layer, so retain the pre-link look and stroke containers.
2770
+ const original = new Map();
2771
+ const remember = (id, layer) => {
2772
+ const look = layer.look && { ...layer.look, ...(layer.look.stroke && { stroke: { ...layer.look.stroke } }) };
2773
+ expanded.set(id, { content: layer.content, styles: layer.styles, runs: layer.runs, styleAt: layer.styleAt, fill: layer.fill, stroke: layer.stroke, look });
2774
+ const assignments = nestedBooleans?.get(layer);
2775
+ if (assignments)
2776
+ file.nestedBooleans.set(id, assignments);
2777
+ };
2778
+ for (const m of models) {
2779
+ original.set(m.id, m);
2282
2780
  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));
2781
+ remember(m.id, m);
2782
+ }
2783
+ // A hidden main copy can itself be the source of later aliases.
2784
+ for (const [id, paths] of linked.aliases) {
2785
+ const layer = original.get(id);
2786
+ for (const path of paths) {
2787
+ if (layer)
2788
+ remember(path, layer);
2789
+ else {
2790
+ expanded.set(path, expanded.get(id));
2791
+ const assignments = file.nestedBooleans.get(id);
2792
+ if (assignments)
2793
+ file.nestedBooleans.set(path, assignments);
2794
+ }
2795
+ }
2796
+ }
2288
2797
  }
2289
2798
  if (options.link === false && !options.markers)
2290
2799
  for (const m of out.models)
@@ -2298,5 +2807,5 @@ function convert(doc, pages, options, explicit, expanded) {
2298
2807
  const layerIds = new Map([...affected].map(([key, layers]) => [
2299
2808
  key, [...new Set([...layers].flatMap(({ id }) => id === undefined ? [] : affectedIds(id)))],
2300
2809
  ]));
2301
- return { doc: out, report: { dropped, expressionErrors, notes, approximations, weights, layerIds, depth: depthMax, links: linked?.counts ?? null, assets: files } };
2810
+ return { doc: out, report: { ...counts, layerIds, depth, links: linked?.counts ?? null, assets: files } };
2302
2811
  }