@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
@@ -1,4 +1,4 @@
1
- import { formatExpressionName, componentNestingGraph, entryOf, findComponentCycle, fitAllGroups, layerPathKey, ownedChildIds, } from "../../model/index.js";
1
+ import { formatExpressionName, buildParentMap, componentNestingGraph, entryOf, findComponentCycle, fitAllGroups, layerPathKey, nodeLocalTransform, ownedChildIds, parseLayerPath, } from "../../model/index.js";
2
2
  import { field, guidText, isObject } from "./fields.js";
3
3
  import { isDetachedStyle } from "./styles.js";
4
4
  import { convertEllipse } from "./converters/ellipse.js";
@@ -15,9 +15,9 @@ import { mergeComponentSets, planSet, withoutVariantParts } from "./componentSet
15
15
  import { nestingMemo, nestingSearch, swapsToCut } from "./nestingCycles.js";
16
16
  import { convertSection } from "./converters/section.js";
17
17
  import { convertText, figmaTextStyle } from "./converters/text.js";
18
- import { convertBooleanOperation, convertStarOrPolygon, convertVector } from "./converters/vector.js";
18
+ import { convertBooleanOperation, convertStarOrPolygon, convertVector, whyFlattened } from "./converters/vector.js";
19
19
  import { blobReader } from "./blobs.js";
20
- import { carryMarks } from "./carry.js";
20
+ import { carry, carryMarks, clearConstraints, withImageCrop } from "./carry.js";
21
21
  import { nodeEffects } from "./converters/effects.js";
22
22
  import { frameGeometry, visualStyle } from "./converters/shared.js";
23
23
  import { bindLayerVariables, figmaVariableModes, foldsVariableAlpha, keptFontSize, readFigmaVariables } from "./variables.js";
@@ -35,6 +35,7 @@ const CONVERTERS = {
35
35
  FRAME: convertFrame,
36
36
  GROUP: convertGroup,
37
37
  LINE: convertLine,
38
+ RECTANGLE: convertRectangle,
38
39
  REGULAR_POLYGON: convertStarOrPolygon,
39
40
  ROUNDED_RECTANGLE: convertRectangle,
40
41
  SECTION: convertSection,
@@ -147,11 +148,45 @@ export function readFileMessage(message, options) {
147
148
  const { result, sources } = walkMessage(message, options, true);
148
149
  return { ...result, sources };
149
150
  }
150
- function walkMessage(message, options, native) {
151
+ // Keep the exported lookup independent of the layer walk's temporary maps and blob reader.
152
+ function styleLookup(tree) {
153
+ let stylesByKey;
154
+ const styleKey = (styleType, key) => `${styleType}\u0000${key}`;
155
+ return (reference, styleType) => {
156
+ if (!isObject(reference))
157
+ return undefined;
158
+ const guid = reference["guid"];
159
+ let found;
160
+ if (isObject(guid) && Number.isInteger(guid["sessionID"]) && Number.isInteger(guid["localID"]))
161
+ found = tree.nodes.get(guidText(guid, "style reference"));
162
+ if (found?.change["styleType"] !== styleType) {
163
+ const key = isObject(reference["assetRef"]) ? reference["assetRef"]["key"] : undefined;
164
+ if (typeof key !== "string")
165
+ return undefined;
166
+ if (stylesByKey === undefined) {
167
+ stylesByKey = new Map();
168
+ for (const node of tree.nodes.values()) {
169
+ const nodeKey = node.change["key"];
170
+ const nodeType = node.change["styleType"];
171
+ if (typeof nodeType !== "string" || typeof nodeKey !== "string")
172
+ continue;
173
+ const byKey = styleKey(nodeType, nodeKey);
174
+ if (!stylesByKey.has(byKey))
175
+ stylesByKey.set(byKey, node);
176
+ }
177
+ }
178
+ found = stylesByKey.get(styleKey(styleType, key));
179
+ }
180
+ return found;
181
+ };
182
+ }
183
+ /** Reads converted layers with their original Figma nodes for Moondraft's adapters. */
184
+ export function walkMessage(message, options, native, distinctSources) {
151
185
  const rootSource = rootSourceOf(message, options.roots);
152
186
  const limits = { ...DEFAULT_FIGMA_IMPORT_LIMITS[rootSource], ...options.limits };
153
187
  const tree = buildFigmaTree(message, limits);
154
188
  const sharedStyle = (node) => ["TEXT", "FILL", "EFFECT"].includes(String(node.change["styleType"]));
189
+ const skipStyle = (node) => node.change["styleType"] === "GRID" || native && sharedStyle(node);
155
190
  const chosen = chooseRoots(message, tree, rootSource);
156
191
  const insideCache = { counts: new Map(), kept: new Set(), named: new Set() };
157
192
  for (const group of chosen.groups)
@@ -164,7 +199,7 @@ function walkMessage(message, options, native) {
164
199
  const image = (hash, size) => {
165
200
  const id = `figma-image-${hash}`;
166
201
  if (Object.hasOwn(assets, id))
167
- return { assetId: id };
202
+ return assets[id];
168
203
  if (missingImages.has(hash))
169
204
  return null;
170
205
  missingImages.add(hash);
@@ -176,8 +211,7 @@ function walkMessage(message, options, native) {
176
211
  return `image ${hash.slice(0, 8)} is not a PNG, JPEG, GIF or WebP file`;
177
212
  const width = supplied.width ?? size?.width;
178
213
  const height = supplied.height ?? size?.height;
179
- assets[id] = { id, hash, mimeType, bytes: supplied.bytes, ...(width !== undefined ? { width } : {}), ...(height !== undefined ? { height } : {}) };
180
- return { assetId: id };
214
+ return assets[id] = { id, hash, mimeType, bytes: supplied.bytes, ...(width !== undefined ? { width } : {}), ...(height !== undefined ? { height } : {}) };
181
215
  };
182
216
  const paintIndices = new Map();
183
217
  const effectFields = new Map();
@@ -260,35 +294,9 @@ function walkMessage(message, options, native) {
260
294
  }
261
295
  return textStylesByKey.get(key);
262
296
  };
263
- // The Figma effect and colour styles that `styleIdForEffect`, `styleIdForFill` and `styleIdForStrokeFill` references
264
- // name: by guid, else by the library key a copy of the style in the message carries.
265
- let stylesByKey;
266
- const styleKey = (styleType, key) => `${styleType}\u0000${key}`;
297
+ const styleNodeFor = styleLookup(tree);
267
298
  const styleList = (reference, styleType) => {
268
- if (!isObject(reference))
269
- return undefined;
270
- const guid = reference["guid"];
271
- let found;
272
- if (isObject(guid) && Number.isInteger(guid["sessionID"]) && Number.isInteger(guid["localID"]))
273
- found = tree.nodes.get(guidText(guid, "style reference"));
274
- if (found?.change["styleType"] !== styleType) {
275
- const key = isObject(reference["assetRef"]) ? reference["assetRef"]["key"] : undefined;
276
- if (typeof key !== "string")
277
- return undefined;
278
- if (stylesByKey === undefined) {
279
- stylesByKey = new Map();
280
- for (const node of tree.nodes.values()) {
281
- const nodeKey = node.change["key"];
282
- const nodeType = node.change["styleType"];
283
- if (typeof nodeType !== "string" || typeof nodeKey !== "string")
284
- continue;
285
- const byKey = styleKey(nodeType, nodeKey);
286
- if (!stylesByKey.has(byKey))
287
- stylesByKey.set(byKey, node);
288
- }
289
- }
290
- found = stylesByKey.get(styleKey(styleType, key));
291
- }
299
+ const found = styleNodeFor(reference, styleType);
292
300
  if (found === undefined)
293
301
  return undefined;
294
302
  const list = styleType === "EFFECT" ? "effects" : "fillPaints";
@@ -339,6 +347,11 @@ function walkMessage(message, options, native) {
339
347
  },
340
348
  ...(native && {
341
349
  copiedPaintAlpha: (paint, opacity) => foldsVariableAlpha(paint, opacity, node, variables, node.id, shownBy),
350
+ textFillStyle: (reference) => styleNodeFor(reference, "FILL")?.id,
351
+ textColorVariable: (data) => {
352
+ const variable = variables.variableOf(data, node.id);
353
+ return "id" in variable && variable.type === "color" ? variable.id : null;
354
+ },
342
355
  fontSizeVariable: (data) => variables.positiveLengthOf(data, node.id),
343
356
  }),
344
357
  keptFontSize: (layer) => keptFontSize(layer, node, variables, shownBy),
@@ -540,13 +553,15 @@ function walkMessage(message, options, native) {
540
553
  // Converts a layer on its own for instance overrides: no children, no reports, its own vector budget. The same layer with the
541
554
  // same override fields is converted once, so instances that repeat an override spend no more of the budget.
542
555
  const aloneCommands = { left: limits.vectorCommands, limit: limits.vectorCommands };
543
- const convertAloneOnce = (node, shownBy) => {
556
+ const convertAloneOnce = (node, fields, shownBy) => {
544
557
  const converter = node.type === "INSTANCE" || node.type === "SYMBOL" ? convertFrame : converterFor(node.type);
545
558
  if (converter === undefined)
546
559
  return null;
547
560
  let leftOut = false;
548
561
  const converted = converter(node, {
549
562
  newId: () => "override", convertChildren: () => [], blob, image, vectorCommands: aloneCommands, textStyle: textStyleFor(null), styleList, ...trackPaints, ...variableNumberOf(node, shownBy),
563
+ ...(native && { plainTextPaint: (range) => range?.["fillPaints"] !== undefined || range?.["styleIdForFill"] !== undefined
564
+ ? fields["textData"] !== undefined : fields["fillPaints"] !== undefined || fields["styleIdForFill"] !== undefined }),
550
565
  report: (kind) => { if (kind === "node-left-out")
551
566
  leftOut = true; },
552
567
  });
@@ -579,7 +594,7 @@ function walkMessage(message, options, native) {
579
594
  }
580
595
  return cached.layer;
581
596
  }
582
- const converted = convertAloneOnce(Object.keys(fields).length === 0 ? node : { ...node, change: { ...node.change, ...fields } }, shownBy);
597
+ const converted = convertAloneOnce(Object.keys(fields).length === 0 ? node : { ...node, change: { ...node.change, ...fields } }, fields, shownBy);
583
598
  byFields.set(key, { layer: converted, fields });
584
599
  return converted;
585
600
  };
@@ -607,7 +622,11 @@ function walkMessage(message, options, native) {
607
622
  const stack = [];
608
623
  // Every node converted, by any walk (page or component), for the variable bindings once stacks are settled.
609
624
  const everyImported = [];
625
+ const omittedSubtrees = new Set();
610
626
  /** Runs the steps on `stack` until it is empty. `walkVisited` holds the nodes this walk imported; `imported` the converted node of each. */
627
+ // Moondraft patch 0010: whether the walk places a node in a horizontal or vertical stack it imported (a grid imports
628
+ // as absolute, and a root has no imported parent), and the node is not absolute in it.
629
+ const inAutoLayoutFlow = (step) => step.inStack === true && step.node.change["stackPositioning"] !== "ABSOLUTE";
611
630
  const runSteps = (walkVisited, imported, rootList) => {
612
631
  for (let step = stack.pop(); step !== undefined; step = stack.pop()) {
613
632
  const { depth, node, component } = step;
@@ -620,16 +639,18 @@ function walkMessage(message, options, native) {
620
639
  continue;
621
640
  }
622
641
  if (isSlotContent(node) && step.host !== true) {
642
+ omittedSubtrees.add(step.source ?? node);
623
643
  add(link, "node-left-out", "a slot's content frame is imported only as the content of the instances that put it in a slot");
624
644
  continue;
625
645
  }
626
646
  walkVisited.add(node.id);
627
647
  // A parent is converted before its children, so a parent with a layer has it by now.
628
- if (native && (sharedStyle(node) || node.type === "VARIABLE" || node.type === "VARIABLE_SET"))
648
+ if (skipStyle(node) || native && (node.type === "VARIABLE" || node.type === "VARIABLE_SET"))
629
649
  continue;
630
650
  const parentLayer = step.parent === null || !Object.hasOwn(layerIds, step.parent.node.id) ? undefined : layerIds[step.parent.node.id];
631
651
  // A left-out node takes the layers inside it along; the reason says how many.
632
652
  const leaveOut = (reason) => {
653
+ omittedSubtrees.add(step.source ?? node);
633
654
  if (parentLayer !== undefined && !Object.hasOwn(layerIds, node.id))
634
655
  layerIds[node.id] = parentLayer;
635
656
  const inside = node.children.length === 0 ? 0 : countLayersInside(node, insideCache);
@@ -690,6 +711,7 @@ function walkMessage(message, options, native) {
690
711
  converted = converter(node, {
691
712
  newId: () => options.idSource(),
692
713
  convertChildren: () => (childIds ??= []),
714
+ inFlow: inAutoLayoutFlow(step),
693
715
  report: (kind, reason) => (kind === "node-left-out" ? leaveOut(reason) : add(link, kind, reason)),
694
716
  blob,
695
717
  image,
@@ -702,8 +724,8 @@ function walkMessage(message, options, native) {
702
724
  if (converted === null)
703
725
  continue;
704
726
  carryMarks(converted);
705
- if (step.inSection === true && "constraints" in converted)
706
- delete converted.constraints;
727
+ if (step.inSection === true)
728
+ clearConstraints(converted);
707
729
  let slotFrame = step.inSlotFrame === true;
708
730
  if (component !== undefined && step.content === true)
709
731
  inComponents.add(node.id);
@@ -717,8 +739,8 @@ function walkMessage(message, options, native) {
717
739
  const key = overrideKeyOf(node);
718
740
  if (!component.layers.has(key))
719
741
  component.layers.set(key, { figma: node, node: converted });
720
- if (node.type === "BOOLEAN_OPERATION") {
721
- // Its operands are not layers, so an override of one names the boolean operation in its report line.
742
+ if (node.type === "BOOLEAN_OPERATION" && childIds === undefined) {
743
+ // A flattened one's operands are not layers, so an override of one names the boolean operation in its report line.
722
744
  const operands = [...node.children];
723
745
  for (let i = 0; i < operands.length; i++) {
724
746
  const operand = operands[i];
@@ -751,18 +773,25 @@ function walkMessage(message, options, native) {
751
773
  if (step.into === rootList)
752
774
  roots.push(converted);
753
775
  if (childIds === undefined) {
754
- if (node.type === "BOOLEAN_OPERATION")
755
- add(link, "approximated", "the boolean operation is flattened to its outline; its operands are not imported", true);
776
+ if (node.type === "BOOLEAN_OPERATION") {
777
+ for (const child of node.children)
778
+ omittedSubtrees.add(child);
779
+ const why = whyFlattened(node, inAutoLayoutFlow(step));
780
+ add(link, "approximated", `the boolean operation is flattened to its outline; its operands are not imported${why === undefined ? "" : `: ${why}`}`, true);
781
+ }
756
782
  else if (node.children.length > 0 && node.type !== "INSTANCE" && node.type !== "SYMBOL") {
783
+ for (const child of node.children)
784
+ omittedSubtrees.add(child);
757
785
  add(link, "property-left-out", `${layersText(countLayersInside(node, insideCache))} left out: a ${node.type} has no children in Taco`, true);
758
786
  }
759
787
  continue;
760
788
  }
761
789
  const inSection = node.type === "SECTION" || (step.inSection === true && converted.type === "group");
790
+ const inStack = converted.type === "frame" && converted.layout.kind !== "absolute";
762
791
  for (let i = node.children.length - 1; i >= 0; i--) {
763
792
  stack.push({
764
793
  node: node.children[i], depth: depth + 1, parent: link, into: childIds, inSection, ...(component !== undefined ? { component } : {}),
765
- ...(step.content === true ? { content: true } : {}), ...(slotFrame ? { inSlotFrame: true } : {}),
794
+ ...(step.content === true ? { content: true } : {}), ...(slotFrame ? { inSlotFrame: true } : {}), ...(inStack ? { inStack: true } : {}),
766
795
  });
767
796
  }
768
797
  }
@@ -794,15 +823,17 @@ function walkMessage(message, options, native) {
794
823
  return name !== "" ? name : set !== undefined ? componentNameOf(set) : "Component";
795
824
  };
796
825
  const setProperties = new Map();
826
+ // The property defs whose dropped preferred values are already reported (`propertiesOf`).
827
+ const reportedDefs = new WeakSet();
797
828
  for (const symbol of symbolOrder) {
798
829
  const symbolLink = linkOf(symbol);
799
830
  const report = (kind, reason) => addCounted(symbolLink, kind, reason);
800
- const properties = propertiesOf(symbol, tree.nodes, componentOf, componentsByKey, report);
831
+ const properties = propertiesOf(symbol, tree.nodes, componentOf, componentsByKey, report, reportedDefs);
801
832
  const set = native && setOf(symbol);
802
833
  if (set) {
803
834
  let shared = setProperties.get(set);
804
835
  if (!shared) {
805
- shared = propertiesOf(set, tree.nodes, componentOf, componentsByKey, (kind, reason) => add(variableLinkOf(set), kind, reason));
836
+ shared = propertiesOf(set, tree.nodes, componentOf, componentsByKey, (kind, reason) => add(variableLinkOf(set), kind, reason), reportedDefs);
806
837
  setProperties.set(set, shared);
807
838
  }
808
839
  const own = new Set(properties.map(p => p.definition.id));
@@ -903,7 +934,27 @@ function walkMessage(message, options, native) {
903
934
  const finished = instances.map((entry) => ({ ...entry, refusedSwaps: new Map(), swaps: new Set(), nested: new Map(), heldSizing: new Map(), filledSlots: [], said: [] }));
904
935
  const nodeRecord = Object.fromEntries(nodes.map((node) => [node.id, node]));
905
936
  const occurrenceFields = new Map();
906
- const finish = (entry) => {
937
+ const instanceBoxes = new Map();
938
+ const instanceFillSizes = new Map();
939
+ // Resolve inherited swaps by imported layer IDs. A holder can be finished later in file order or lose a
940
+ // swap in the cycle check. Revisit just the instances that consulted a path whose answer changed.
941
+ const pathSwaps = new Map();
942
+ const readers = new Map();
943
+ let sourceOverrideKeys;
944
+ const hasSourceKey = (key) => {
945
+ if (tree.nodes.has(key))
946
+ return true;
947
+ if (!sourceOverrideKeys) {
948
+ sourceOverrideKeys = new Set();
949
+ for (const node of tree.nodes.values()) {
950
+ const guid = node.change["overrideKey"];
951
+ if (isObject(guid) && Number.isInteger(guid["sessionID"]) && Number.isInteger(guid["localID"]))
952
+ sourceOverrideKeys.add(overrideKeyOf(node));
953
+ }
954
+ }
955
+ return sourceOverrideKeys.has(key);
956
+ };
957
+ const finish = (entry, pending) => {
907
958
  const { stub, figma, self, link, refusedSwaps, said } = entry;
908
959
  const component = importedComponents.get(shownSymbol(figma));
909
960
  if (component === undefined)
@@ -914,12 +965,32 @@ function walkMessage(message, options, native) {
914
965
  delete stub["slots"];
915
966
  const fields = new Map();
916
967
  const made = instanceFields(figma, component, self, {
917
- ...(native && { fileOverride(path, change) {
968
+ ...(native && {
969
+ fileOverride(path, change) {
918
970
  fields.set(path, { ...fields.get(path), ...change });
919
- } }),
971
+ },
972
+ fileLayout(boxes, fillOnly) {
973
+ const id = stub["id"];
974
+ instanceBoxes.delete(id);
975
+ instanceFillSizes.delete(id);
976
+ if (boxes.size)
977
+ (fillOnly ? instanceFillSizes : instanceBoxes).set(id, boxes);
978
+ },
979
+ }),
920
980
  slotFills: entry.slotFills,
921
981
  component: (symbolId) => importedComponents.get(symbolId),
922
982
  refusedSwaps,
983
+ hasSourceKey,
984
+ nestedSwaps(holder, path) {
985
+ let paths = readers.get(holder);
986
+ if (!paths)
987
+ readers.set(holder, paths = new Map());
988
+ let used = paths.get(path);
989
+ if (!used)
990
+ paths.set(path, used = new Set());
991
+ used.add(entry);
992
+ return pathSwaps.get(holder)?.get(path);
993
+ },
923
994
  nodes: nodeRecord,
924
995
  convertAlone,
925
996
  bindingsOf,
@@ -946,14 +1017,34 @@ function walkMessage(message, options, native) {
946
1017
  });
947
1018
  if (fields.size)
948
1019
  occurrenceFields.set(stub["id"], fields);
1020
+ else
1021
+ occurrenceFields.delete(stub["id"]);
1022
+ const holder = nodeRecord[stub["id"]];
1023
+ const previous = pathSwaps.get(holder);
1024
+ pathSwaps.set(holder, made.pathSwaps);
1025
+ for (const [path, used] of readers.get(holder) ?? []) {
1026
+ const before = previous?.get(path), after = made.pathSwaps.get(path);
1027
+ if (before?.symbol !== after?.symbol || JSON.stringify(before?.properties) !== JSON.stringify(after?.properties)) {
1028
+ for (const reader of used)
1029
+ pending.add(reader);
1030
+ }
1031
+ }
949
1032
  Object.assign(stub, made.fields);
950
1033
  entry.swaps = made.swaps;
951
1034
  entry.nested = made.nested;
952
1035
  entry.heldSizing = made.heldSizing;
953
1036
  entry.filledSlots = made.filledSlots;
954
1037
  };
955
- for (const entry of finished)
956
- finish(entry);
1038
+ const finishAll = (pending) => {
1039
+ const touched = new Set();
1040
+ for (const entry of pending) {
1041
+ pending.delete(entry);
1042
+ finish(entry, pending);
1043
+ touched.add(entry);
1044
+ }
1045
+ return touched;
1046
+ };
1047
+ finishAll(new Set(finished));
957
1048
  // The nesting check, over the walks that resolving a component or a page instance can take from a component into another
958
1049
  // (`nestingSearch`): through the instances placed inside components, and through each swap an instance makes by an override
959
1050
  // or an instance swap property value, from the component whose layer it swaps, while the component that holds that instance
@@ -961,28 +1052,27 @@ function walkMessage(message, options, native) {
961
1052
  // components are checked first, then each page instance's swaps against those kept, so a cycle that a page instance closes
962
1053
  // costs that instance's swap, not a swap every instance of a component shows. Each cycle found loses a swap, by file order
963
1054
  // (`swapsToCut`). A swap left out takes along what the instance sets inside the component that swap would show, so an
964
- // instance made again only loses swaps.
1055
+ // enclosing override may now resolve against a different component.
965
1056
  {
966
1057
  const symbolOf = new Map([...componentIds].map(([symbolId, componentId]) => [componentId, symbolId]));
967
1058
  const kept = new Map();
968
- const keep = (from, to) => {
969
- let set = kept.get(from);
970
- if (set === undefined)
971
- kept.set(from, set = new Set());
972
- set.add(to);
973
- };
974
1059
  const nodesById = new Map(nodes.map((node) => [node.id, node]));
975
- for (const { symbol, root } of importedComponents.values()) {
1060
+ const refreshKept = (symbolId) => {
1061
+ const targets = new Set();
1062
+ kept.set(symbolId, targets);
1063
+ const root = importedComponents.get(symbolId).root;
976
1064
  for (const pending = [root.id], seen = new Set(); pending.length > 0;) {
977
1065
  const id = pending.pop();
978
1066
  const node = seen.has(id) ? undefined : nodesById.get(id);
979
1067
  seen.add(id);
980
1068
  if (node?.type === "instance")
981
- keep(symbol.id, symbolOf.get(node.componentId));
1069
+ targets.add(symbolOf.get(node.componentId));
982
1070
  if (node !== undefined)
983
1071
  pending.push(...ownedChildIds(node));
984
1072
  }
985
- }
1073
+ };
1074
+ for (const symbolId of importedComponents.keys())
1075
+ refreshKept(symbolId);
986
1076
  const order = symbolOrder.map((symbol) => symbol.id);
987
1077
  const fileIndex = new Map(order.map((id, at) => [id, at]));
988
1078
  const componentEntries = finished.filter((entry) => entry.owner !== undefined);
@@ -1002,48 +1092,76 @@ function walkMessage(message, options, native) {
1002
1092
  byOwner.set(ownerOf(entry), list = []);
1003
1093
  list.push(entry);
1004
1094
  }
1005
- const memo = nestingMemo();
1095
+ let memo = nestingMemo();
1006
1096
  // The swaps each entry of `cutting` makes, as the search holds them.
1007
1097
  const made = new Map(cutting.map((entry) => [entry, swapsOf([entry])]));
1008
- const search = nestingSearch(order, kept, [...fixed, ...[...made.values()].flat()]);
1009
- for (const [root, rootOwner] of roots) {
1010
- for (let cycle = search(root, rootOwner, memo); cycle !== null; cycle = search(root, rootOwner, memo)) {
1011
- const keptSteps = new Map();
1012
- const swaps = [];
1013
- for (const { from, to, owner } of cycle) {
1014
- if (owner !== undefined && byOwner.has(owner))
1015
- swaps.push(`${from}>${to}`);
1016
- else
1017
- keptSteps.set(from, new Set([to]));
1018
- }
1019
- const ids = cycle.map((step) => step.from).sort((a, b) => fileIndex.get(a) - fileIndex.get(b));
1020
- const cut = swapsToCut(ids, keptSteps, swaps);
1021
- if (cut.size === 0)
1022
- throw new Error(`the nesting check found a cycle with no swap to leave out, through ${ids.map(nameOf).join(" > ")}`);
1023
- const touched = new Set();
1024
- for (const { from, to, owner } of cycle) {
1025
- const swap = `${from}>${to}`;
1026
- if (!cut.has(swap))
1098
+ const buildSearch = () => nestingSearch(order, kept, [...fixed, ...[...made.values()].flat()]);
1099
+ let search = buildSearch();
1100
+ for (let i = 0; i < roots.length;) {
1101
+ const [root, rootOwner] = roots[i];
1102
+ const cycle = search(root, rootOwner, memo);
1103
+ if (cycle === null) {
1104
+ i++;
1105
+ continue;
1106
+ }
1107
+ const keptSteps = new Map();
1108
+ const swaps = [];
1109
+ for (const { from, to, owner } of cycle) {
1110
+ if (owner !== undefined && byOwner.has(owner))
1111
+ swaps.push(`${from}>${to}`);
1112
+ else
1113
+ keptSteps.set(from, new Set([to]));
1114
+ }
1115
+ const ids = cycle.map((step) => step.from).sort((a, b) => fileIndex.get(a) - fileIndex.get(b));
1116
+ const cut = swapsToCut(ids, keptSteps, swaps);
1117
+ if (cut.size === 0)
1118
+ throw new Error(`the nesting check found a cycle with no swap to leave out, through ${ids.map(nameOf).join(" > ")}`);
1119
+ const changed = new Set();
1120
+ for (const { from, to, owner } of cycle) {
1121
+ const swap = `${from}>${to}`;
1122
+ if (!cut.has(swap))
1123
+ continue;
1124
+ const reason = from === to ? `to ${nameOf(to)} inside ${nameOf(from)} itself is left out: it would nest a component in itself`
1125
+ : `to ${nameOf(to)} inside ${nameOf(from)} is left out: ${nameOf(to)} can contain ${nameOf(from)}, so it would nest a component in itself`;
1126
+ for (const entry of byOwner.get(owner)) {
1127
+ if (!entry.swaps.has(swap))
1027
1128
  continue;
1028
- const reason = from === to ? `to ${nameOf(to)} inside ${nameOf(from)} itself is left out: it would nest a component in itself`
1029
- : `to ${nameOf(to)} inside ${nameOf(from)} is left out: ${nameOf(to)} can contain ${nameOf(from)}, so it would nest a component in itself`;
1030
- for (const entry of byOwner.get(owner)) {
1031
- if (!entry.swaps.has(swap))
1032
- continue;
1033
- entry.refusedSwaps.set(swap, reason);
1034
- finish(entry);
1035
- touched.add(entry);
1036
- }
1129
+ entry.refusedSwaps.set(swap, reason);
1130
+ changed.add(entry);
1131
+ }
1132
+ }
1133
+ const gone = [];
1134
+ let gained = false;
1135
+ const slotOwners = new Set();
1136
+ for (const entry of finishAll(changed)) {
1137
+ // A newly reachable slot host can contain instances even if its holder gained no swap.
1138
+ if (entry.owner !== undefined && entry.slotFills.length)
1139
+ slotOwners.add(entry.owner);
1140
+ const previous = made.get(entry);
1141
+ if (!previous)
1142
+ continue; // Page swaps are checked after the component swaps settle.
1143
+ const retained = previous.filter(swap => entry.swaps.has(`${swap.from}>${swap.to}`));
1144
+ if (retained.length < entry.swaps.size) {
1145
+ made.set(entry, swapsOf([entry]));
1146
+ gained = true;
1147
+ }
1148
+ else if (retained.length < previous.length) {
1149
+ made.set(entry, retained);
1150
+ for (const swap of previous)
1151
+ if (!entry.swaps.has(`${swap.from}>${swap.to}`))
1152
+ gone.push(swap);
1037
1153
  }
1038
- // A swap an entry no longer makes leaves the search; cuts only take swaps away, so the search is not built again.
1039
- search.remove([...touched].flatMap((entry) => {
1040
- const [left, gone] = [[], []];
1041
- for (const swap of made.get(entry))
1042
- (entry.swaps.has(`${swap.from}>${swap.to}`) ? left : gone).push(swap);
1043
- made.set(entry, left);
1044
- return gone;
1045
- }));
1046
1154
  }
1155
+ if (gained || slotOwners.size > 0) {
1156
+ for (const owner of slotOwners)
1157
+ refreshKept(owner);
1158
+ // A previously safe root can now reach the new edge. Its cached walk ends are stale too.
1159
+ search = buildSearch();
1160
+ memo = nestingMemo();
1161
+ i = 0;
1162
+ }
1163
+ else
1164
+ search.remove(gone);
1047
1165
  }
1048
1166
  };
1049
1167
  check(componentEntries, [], order.map((id) => [id, undefined]));
@@ -1095,6 +1213,17 @@ function walkMessage(message, options, native) {
1095
1213
  // A group whose frame changes when fitted to its layers (`fitGroups`) would move its stack's other children.
1096
1214
  const fitted = stacks.length === 0 ? {} : fitAllGroups(Object.fromEntries(nodes.map((node) => [node.id, node])));
1097
1215
  settleStacks(stacks, add, (node) => node.type === "group" && entryOf(fitted, node.id) !== node);
1216
+ // Fill is decided here, after resolving instance paths. Discard candidate
1217
+ // allocations for paths whose rotation or stack prevented importing Fill.
1218
+ for (const [id, boxes] of instanceFillSizes) {
1219
+ for (const path of boxes.keys()) {
1220
+ const figma = nodeRecord[parseLayerPath(path).at(-1)]?.metadata?.["figma"];
1221
+ if (!isObject(figma) || !figma["fillSizing"])
1222
+ boxes.delete(path);
1223
+ }
1224
+ if (!boxes.size)
1225
+ instanceFillSizes.delete(id);
1226
+ }
1098
1227
  const componentRoots = new Set([...importedComponents.values()].map(({ root }) => root.id));
1099
1228
  for (const { stub, heldSizing } of finished) {
1100
1229
  dropUnheldSizing(stub["overrides"], heldSizing);
@@ -1142,7 +1271,7 @@ function walkMessage(message, options, native) {
1142
1271
  const folded = boundSelf.style?.[name];
1143
1272
  if (rootOverride[name] === undefined || folded === undefined)
1144
1273
  continue;
1145
- if (JSON.stringify(folded) === JSON.stringify(component.root.style?.[name] ?? []))
1274
+ if (JSON.stringify(folded, withImageCrop) === JSON.stringify(component.root.style?.[name] ?? [], withImageCrop))
1146
1275
  delete rootOverride[name];
1147
1276
  else
1148
1277
  rootOverride[name] = folded;
@@ -1184,7 +1313,11 @@ function walkMessage(message, options, native) {
1184
1313
  }
1185
1314
  // The literal reader merges variant trees. The native file adapter needs the original member mains.
1186
1315
  const fittedNodes = fitAllGroups(Object.fromEntries(nodes.map((node) => [node.id, node])));
1316
+ if (instanceBoxes.size && nodes.some(node => node.type === "group")) {
1317
+ fitInstanceBoxes(instanceBoxes, nodeRecord, fittedNodes);
1318
+ }
1187
1319
  const fittedList = nodes.map((node) => entryOf(fittedNodes, node.id) ?? node);
1320
+ const distinct = distinctSources?.(tree);
1188
1321
  const sets = native ? { nodes: fittedList, components, layerOf: new Map(), componentOf: new Map() } : mergeComponentSets({
1189
1322
  theme: {
1190
1323
  defaultTextStyleId: "figma-import-default",
@@ -1193,6 +1326,7 @@ function walkMessage(message, options, native) {
1193
1326
  textStyles: { "figma-import-default": figmaTextStyle({}, "Default", () => undefined, "component sets"), ...textStyles },
1194
1327
  },
1195
1328
  nodes: fittedList, components, figmaNodes: tree.nodes, newId: () => options.idSource(), keyOf, nameOf: componentNameOf,
1329
+ ...(distinct?.size && { distinctLayers: new Set(everyImported.filter(({ figma }) => distinct.has(figma.id)).map(({ node }) => node.id)) }),
1196
1330
  variants: [...importedComponents.values()].map(({ symbol, componentId, root }) => ({ symbol, componentId, root })),
1197
1331
  report: (node, kind, reason) => addCounted(linkOf(node), kind, reason),
1198
1332
  });
@@ -1208,7 +1342,7 @@ function walkMessage(message, options, native) {
1208
1342
  if (typeof plan === "string")
1209
1343
  add(variableLinkOf(node), "approximated", plan);
1210
1344
  else
1211
- variants.set(node.id, { plan, properties: setProperties.get(node) ?? propertiesOf(node, tree.nodes, componentOf, componentsByKey, (kind, reason) => add(variableLinkOf(node), kind, reason)) });
1345
+ variants.set(node.id, { plan, properties: setProperties.get(node) ?? propertiesOf(node, tree.nodes, componentOf, componentsByKey, (kind, reason) => add(variableLinkOf(node), kind, reason), reportedDefs) });
1212
1346
  }
1213
1347
  const type = node.change["styleType"];
1214
1348
  if (type === "TEXT")
@@ -1229,7 +1363,7 @@ function walkMessage(message, options, native) {
1229
1363
  add(link, kind, count === 1 ? reason : `${reason} (${String(count)} times, first here)`);
1230
1364
  }
1231
1365
  for (const orphan of tree.orphans) {
1232
- if ((native && sharedStyle(orphan)) || visited.has(orphan.id) || inComponents.has(orphan.id) || slotContents.has(orphan.id) || orphan.type === "VARIABLE" || orphan.type === "VARIABLE_SET")
1366
+ if (skipStyle(orphan) || visited.has(orphan.id) || inComponents.has(orphan.id) || slotContents.has(orphan.id) || orphan.type === "VARIABLE" || orphan.type === "VARIABLE_SET")
1233
1367
  continue;
1234
1368
  const reason = orphan.parentId === undefined ? "the node has no parentIndex" : `its parent ${orphan.parentId} is not in the message`;
1235
1369
  add({ node: orphan, parent: null }, "node-left-out", `${reason}; it and ${layersText(countLayersInside(orphan, insideCache))} are not imported`, true);
@@ -1245,13 +1379,42 @@ function walkMessage(message, options, native) {
1245
1379
  componentGuids[figmaId] = componentId;
1246
1380
  const componentPlacements = Object.fromEntries([...placements].flatMap(([layer, symbol]) => sets.componentOf.has(symbol) ? [] : [[layer, componentGuids[symbol]]]));
1247
1381
  return {
1248
- sources: { variables, variants, tree, styleLayers, textStyleUses, paintIndices, effectFields, occurrenceFields, imported: everyImported },
1382
+ sources: { variables, variants, tree, styleLayers, styleNodeFor, textStyleUses, paintIndices, effectFields, occurrenceFields, instanceBoxes, instanceFillSizes, imported: everyImported, omittedSubtrees },
1249
1383
  result: {
1250
1384
  rootSource, roots: roots.map((root) => mergedById.get(root.id) ?? root), nodes: sets.nodes, pages, report, assets, layerIds, components: sets.components, componentIds: componentGuids, componentPlacements,
1251
1385
  variableCollections: variables?.collections ?? {}, textStyles,
1252
1386
  },
1253
1387
  };
1254
1388
  }
1389
+ /** Rebase Figma's boxes into the local coordinates of the fitted groups. */
1390
+ function fitInstanceBoxes(instanceBoxes, original, fitted) {
1391
+ const parents = buildParentMap(original);
1392
+ const origins = new Map();
1393
+ function groupOrigin(id) {
1394
+ if (id === undefined || original[id]?.type !== "group")
1395
+ return [0, 0];
1396
+ const found = origins.get(id);
1397
+ if (found)
1398
+ return found;
1399
+ const [a, b, c, d, x, y] = nodeLocalTransform(original[id]);
1400
+ const [, , , , fittedX, fittedY] = nodeLocalTransform(fitted[id]);
1401
+ const [px, py] = groupOrigin(parents.get(id));
1402
+ const dx = fittedX - x + px, dy = fittedY - y + py;
1403
+ const offset = [a * dx + b * dy, c * dx + d * dy];
1404
+ origins.set(id, offset);
1405
+ return offset;
1406
+ }
1407
+ for (const boxes of instanceBoxes.values())
1408
+ for (const [path, box] of boxes) {
1409
+ const id = parseLayerPath(path).at(-1);
1410
+ const [px, py] = groupOrigin(parents.get(id));
1411
+ const [dx, dy] = groupOrigin(id);
1412
+ if (px === 0 && py === 0 && dx === 0 && dy === 0)
1413
+ continue;
1414
+ const [a, b, c, d, x, y] = box.transform;
1415
+ boxes.set(path, { ...box, transform: [a, b, c, d, x + a * dx + c * dy - px, y + b * dx + d * dy - py] });
1416
+ }
1417
+ }
1255
1418
  /**
1256
1419
  * Keeps each imported stack only when every Figma child in its flow (all but
1257
1420
  * "Ignore auto layout" children) was imported into it: a left-out child would
@@ -1277,21 +1440,25 @@ function settleStacks(stacks, add, refits) {
1277
1440
  const entry = member(child);
1278
1441
  return entry === undefined || (entry.node.visible && refits(entry.node));
1279
1442
  });
1443
+ const firstOnTop = stack.figma.change["stackReverseZIndex"] === true;
1280
1444
  if (blocker !== undefined) {
1281
1445
  const why = member(blocker) !== undefined ? "changes size or position when fitted to its layers, as a Taco group is"
1282
1446
  : imported.has(blocker) ? "was imported on its own, outside this frame" : "was not imported";
1283
1447
  add(stack.link, "property-left-out", `auto layout is left off, so children keep their positions: child ${blocker.type} ${JSON.stringify(blocker.name)} ${why}`);
1448
+ if (firstOnTop)
1449
+ add(stack.link, "property-left-out", "stackReverseZIndex (first child on top) requires auto layout");
1284
1450
  Object.assign(stack.node, { layout: { kind: "absolute" } });
1285
1451
  continue;
1286
1452
  }
1453
+ if (firstOnTop)
1454
+ carry(stack.node, { firstOnTop: true });
1287
1455
  const vertical = stack.node.type === "frame" && stack.node.layout.kind === "vertical";
1456
+ const wraps = stack.figma.change["stackWrap"] === "WRAP";
1288
1457
  for (const child of stack.figma.children) {
1289
1458
  const entry = member(child);
1290
1459
  if (entry === undefined)
1291
1460
  continue;
1292
- // Taco lets neither a group nor a path fill its parent.
1293
- const cannotFill = entry.node.type === "group" ? "a group" : entry.node.type === "shape" && entry.node.shape === "path" ? "a path" : undefined;
1294
- Object.assign(entry.node, stackChildFields(entry.figma.change, vertical, entry.node, (kind, reason) => add(entry.link, kind, reason), cannotFill));
1461
+ Object.assign(entry.node, stackChildFields(entry.figma.change, vertical, wraps, entry.node, (kind, reason) => add(entry.link, kind, reason)));
1295
1462
  }
1296
1463
  }
1297
1464
  }