@moondraft/import 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +2 -2
  3. package/SOURCE.md +343 -4
  4. package/dist/adapter/convert.d.ts +26 -2
  5. package/dist/adapter/convert.js +817 -217
  6. package/dist/adapter/figma-descriptions.d.ts +7 -0
  7. package/dist/adapter/figma-descriptions.js +34 -0
  8. package/dist/adapter/figma-grids.d.ts +12 -0
  9. package/dist/adapter/figma-grids.js +175 -0
  10. package/dist/adapter/figma-handoff.d.ts +34 -0
  11. package/dist/adapter/figma-handoff.js +188 -0
  12. package/dist/adapter/figma-hyperlinks.d.ts +13 -0
  13. package/dist/adapter/figma-hyperlinks.js +77 -0
  14. package/dist/adapter/figma.d.ts +4 -1
  15. package/dist/adapter/figma.js +15 -4
  16. package/dist/adapter/file-components.d.ts +10 -3
  17. package/dist/adapter/file-components.js +126 -33
  18. package/dist/adapter/file-resources.js +545 -47
  19. package/dist/adapter/file-typography.d.ts +6 -0
  20. package/dist/adapter/file-typography.js +44 -0
  21. package/dist/adapter/image-crop.d.ts +18 -0
  22. package/dist/adapter/image-crop.js +30 -0
  23. package/dist/adapter/link.d.ts +12 -1
  24. package/dist/adapter/link.js +380 -113
  25. package/dist/adapter/payload.js +3 -3
  26. package/dist/adapter/variables.d.ts +2 -1
  27. package/dist/adapter/variables.js +5 -2
  28. package/dist/figma-file.d.ts +1 -0
  29. package/dist/figma-file.js +1 -0
  30. package/dist/figma.d.ts +1 -0
  31. package/dist/figma.js +191 -35
  32. package/dist/index.d.ts +1 -0
  33. package/dist/index.js +1 -0
  34. package/dist/report.d.ts +59 -1
  35. package/dist/report.js +176 -30
  36. package/dist/serialize.d.ts +7 -0
  37. package/dist/serialize.js +79 -0
  38. package/dist/taco/figma-import/container/kiwiContainer.d.ts +3 -0
  39. package/dist/taco/figma-import/container/kiwiContainer.js +1 -1
  40. package/dist/taco/figma-import/figFile.js +3 -0
  41. package/dist/taco/figma-import/import/carry.d.ts +14 -1
  42. package/dist/taco/figma-import/import/carry.js +34 -1
  43. package/dist/taco/figma-import/import/componentProps.d.ts +10 -4
  44. package/dist/taco/figma-import/import/componentProps.js +29 -13
  45. package/dist/taco/figma-import/import/componentSets.d.ts +2 -0
  46. package/dist/taco/figma-import/import/componentSets.js +1 -1
  47. package/dist/taco/figma-import/import/converters/effects.d.ts +3 -13
  48. package/dist/taco/figma-import/import/converters/effects.js +4 -34
  49. package/dist/taco/figma-import/import/converters/exportSettings.d.ts +4 -0
  50. package/dist/taco/figma-import/import/converters/exportSettings.js +75 -0
  51. package/dist/taco/figma-import/import/converters/frame.d.ts +1 -1
  52. package/dist/taco/figma-import/import/converters/frame.js +15 -6
  53. package/dist/taco/figma-import/import/converters/gradient.d.ts +2 -0
  54. package/dist/taco/figma-import/import/converters/gradient.js +3 -1
  55. package/dist/taco/figma-import/import/converters/grid.d.ts +12 -0
  56. package/dist/taco/figma-import/import/converters/grid.js +97 -0
  57. package/dist/taco/figma-import/import/converters/group.d.ts +2 -4
  58. package/dist/taco/figma-import/import/converters/group.js +6 -15
  59. package/dist/taco/figma-import/import/converters/image.d.ts +2 -1
  60. package/dist/taco/figma-import/import/converters/image.js +60 -16
  61. package/dist/taco/figma-import/import/converters/layout.d.ts +8 -7
  62. package/dist/taco/figma-import/import/converters/layout.js +66 -37
  63. package/dist/taco/figma-import/import/converters/rectangle.d.ts +1 -1
  64. package/dist/taco/figma-import/import/converters/rectangle.js +3 -3
  65. package/dist/taco/figma-import/import/converters/section.d.ts +2 -3
  66. package/dist/taco/figma-import/import/converters/section.js +5 -11
  67. package/dist/taco/figma-import/import/converters/shared.d.ts +9 -5
  68. package/dist/taco/figma-import/import/converters/shared.js +23 -10
  69. package/dist/taco/figma-import/import/converters/text.d.ts +38 -1
  70. package/dist/taco/figma-import/import/converters/text.js +248 -32
  71. package/dist/taco/figma-import/import/converters/vector.d.ts +36 -15
  72. package/dist/taco/figma-import/import/converters/vector.js +214 -73
  73. package/dist/taco/figma-import/import/converters/vectorNetwork.d.ts +19 -3
  74. package/dist/taco/figma-import/import/converters/vectorNetwork.js +147 -29
  75. package/dist/taco/figma-import/import/instances.d.ts +32 -5
  76. package/dist/taco/figma-import/import/instances.js +613 -130
  77. package/dist/taco/figma-import/import/styles.d.ts +2 -0
  78. package/dist/taco/figma-import/import/styles.js +6 -0
  79. package/dist/taco/figma-import/import/types.d.ts +8 -0
  80. package/dist/taco/figma-import/import/variables.d.ts +5 -2
  81. package/dist/taco/figma-import/import/variables.js +65 -31
  82. package/dist/taco/figma-import/import/variantTrees.d.ts +1 -1
  83. package/dist/taco/figma-import/import/variantTrees.js +46 -4
  84. package/dist/taco/figma-import/import/walk.d.ts +62 -7
  85. package/dist/taco/figma-import/import/walk.js +328 -122
  86. package/dist/taco/figma-import/kiwi/message.d.ts +4 -2
  87. package/dist/taco/figma-import/kiwi/message.js +59 -15
  88. package/dist/taco/model/codec.d.ts +2 -2
  89. package/dist/taco/model/codec.js +72 -8
  90. package/dist/taco/model/component-evaluation.d.ts +2 -0
  91. package/dist/taco/model/component-evaluation.js +7 -0
  92. package/dist/taco/model/instance-resolver.d.ts +6 -2
  93. package/dist/taco/model/instance-resolver.js +50 -18
  94. package/dist/taco/model/sha256.js +13 -8
  95. package/dist/taco/model/types.d.ts +57 -5
  96. package/dist/taco/model/types.js +4 -0
  97. package/dist/taco/svg-import/style/computed.js +1 -0
  98. package/package.json +3 -2
@@ -35,6 +35,8 @@ export type StyleBackedList = keyof typeof STYLE_BACKED;
35
35
  export declare const STYLE_REFERENCE_FIELDS: ReadonlyMap<string, StyleBackedList>;
36
36
  /** Figma's style reference for "no style": a guid with both parts 0xffffffff, written when a layer or an override detaches a style. */
37
37
  export declare function isDetachedStyle(reference: unknown): boolean;
38
+ /** A grid style reference, including the GUID used in older files. A detach takes precedence over a legacy ID. */
39
+ export declare function gridStyleReference(change: FigmaObject): unknown;
38
40
  /**
39
41
  * The `effects`, `fillPaints` or `strokePaints` Figma draws for a layer whose fields are `change`: those of the style
40
42
  * the layer names (`styleIdForEffect`, `styleIdForFill`, `styleIdForStrokeFill`), else the layer's own. Figma draws a
@@ -15,6 +15,12 @@ export function isDetachedStyle(reference) {
15
15
  const guid = isObject(reference) ? reference["guid"] : undefined;
16
16
  return isObject(guid) && guid["sessionID"] === 0xffffffff && guid["localID"] === 0xffffffff;
17
17
  }
18
+ /** A grid style reference, including the GUID used in older files. A detach takes precedence over a legacy ID. */
19
+ export function gridStyleReference(change) {
20
+ const legacy = change["inheritGridStyleID"];
21
+ const reference = change["styleIdForGrid"] ?? (legacy === undefined ? undefined : { guid: legacy });
22
+ return isDetachedStyle(reference) ? undefined : reference;
23
+ }
18
24
  /** The report reason for a layer whose `list` names a style the message does not have. */
19
25
  function missingStyleReason(list) {
20
26
  const { style, what } = STYLE_BACKED[list];
@@ -84,6 +84,8 @@ export interface FigmaComponentSource {
84
84
  }
85
85
  /** The bytes of one image, as the host supplies them. */
86
86
  export interface FigmaSuppliedImage {
87
+ /** A temporary image supplied for an unresolved hash. */
88
+ readonly placeholder?: boolean;
87
89
  readonly bytes: Uint8Array;
88
90
  readonly mimeType?: string;
89
91
  readonly width?: number;
@@ -95,9 +97,13 @@ export interface FigmaSuppliedImage {
95
97
  * Taco `ImageAsset`, such as with `source: { kind: "data", data: <bytes as base64> }`.
96
98
  */
97
99
  export interface FigmaImportedImage {
100
+ /** A temporary image supplied for an unresolved hash. */
101
+ readonly placeholder?: boolean;
98
102
  readonly id: AssetId;
99
103
  /** The image's SHA-1 hash as 40 lowercase hex digits. */
100
104
  readonly hash: string;
105
+ /** Still image embedded alongside a video, when supplied by Figma. */
106
+ readonly poster?: FigmaImportedImage;
101
107
  readonly mimeType: string;
102
108
  readonly bytes: Uint8Array;
103
109
  readonly width?: number;
@@ -121,6 +127,8 @@ export interface FigmaImportReportEntry {
121
127
  readonly kind: FigmaImportReportKind;
122
128
  /** What was left out or changed, in plain words. */
123
129
  readonly reason: string;
130
+ /** How many times the import met this reason, when more than once; the entry is the first occurrence. */
131
+ readonly count?: number;
124
132
  /**
125
133
  * The layers inside the node that this entry leaves out with it, counted
126
134
  * by `layerType` in the order first met; empty when it leaves none out.
@@ -86,8 +86,9 @@ export interface ShownBy {
86
86
  * every `VARIABLE` in it with a value for each mode. A set or variable Figma marks deleted (`isSoftDeleted`) is left
87
87
  * out, as is a variable whose set is not in the message or whose type Taco lacks; each is reported. Taco variables
88
88
  * hold no aliases, so an alias takes the value it resolves to: in the same mode within its own collection, else in
89
- * the other collection's default mode. A mode without a value takes the default mode's. Two collections of one name
90
- * get a number, so that `var('collection/name')` can tell them apart. A number variable scoped to opacity alone (layer
89
+ * the other collection's default mode. A mode without a value takes the default mode's. Without `keepAliases`, two
90
+ * collections of one name get a number, so that `var('collection/name')` can tell them apart; with it, each keeps
91
+ * its Figma name. A number variable scoped to opacity alone (layer
91
92
  * or color opacity) holds Figma's percentage, so it is imported divided by 100, on Taco's 0 to 1 scale. Ids come from
92
93
  * `newId`.
93
94
  * @param nodes - Source nodes in file order.
@@ -97,6 +98,8 @@ export interface ShownBy {
97
98
  * @returns Variable definitions and lookup functions.
98
99
  */
99
100
  export declare function readFigmaVariables(nodes: Iterable<FigmaTreeNode>, newId: () => string, report: Report, keepAliases?: boolean): FigmaVariables;
101
+ /** Looks up a variable that can supply this typography field in every mode. */
102
+ export declare function typographyVariable(variables: FigmaVariables, name: string, data: unknown, where: string): string | null;
100
103
  /**
101
104
  * Sets the variable bindings and variable modes of `layer`, converted from `figma`. A paint's `colorVar` binds
102
105
  * `fillColor` or `strokeColor` when it is the bottom fill or the first stroke and solid (a text layer's colour is its
@@ -26,13 +26,20 @@ function bySortPosition(items, position) {
26
26
  .map(({ item }) => item);
27
27
  }
28
28
  const quoted = (text) => JSON.stringify(text);
29
+ // Parsing callbacks belong to the read stage. The returned variable lookups must
30
+ // not retain the walk's report callback (and with it the decoded file and all its caches).
31
+ function leaveOutVariable(known, node, report, why) {
32
+ known.set(node, { missing: `the variable ${quoted(node.name)} is not imported: ${why}` });
33
+ report(node, "node-left-out", `the variable is not imported: ${why}`);
34
+ }
29
35
  /**
30
36
  * Every `VARIABLE_SET` of the message as a collection, its modes in Figma's order (the first is the default), and
31
37
  * every `VARIABLE` in it with a value for each mode. A set or variable Figma marks deleted (`isSoftDeleted`) is left
32
38
  * out, as is a variable whose set is not in the message or whose type Taco lacks; each is reported. Taco variables
33
39
  * hold no aliases, so an alias takes the value it resolves to: in the same mode within its own collection, else in
34
- * the other collection's default mode. A mode without a value takes the default mode's. Two collections of one name
35
- * get a number, so that `var('collection/name')` can tell them apart. A number variable scoped to opacity alone (layer
40
+ * the other collection's default mode. A mode without a value takes the default mode's. Without `keepAliases`, two
41
+ * collections of one name get a number, so that `var('collection/name')` can tell them apart; with it, each keeps
42
+ * its Figma name. A number variable scoped to opacity alone (layer
36
43
  * or color opacity) holds Figma's percentage, so it is imported divided by 100, on Taco's 0 to 1 scale. Ids come from
37
44
  * `newId`.
38
45
  * @param nodes - Source nodes in file order.
@@ -87,24 +94,28 @@ export function readFigmaVariables(nodes, newId, report, keepAliases = false) {
87
94
  sources.set(id, node);
88
95
  setVariables.set(id, {});
89
96
  const modeNames = new Set();
90
- const set = { node, id, modes: modes.map((mode, index) => {
91
- const base = mode.name || `Mode ${String(index + 1)}`;
92
- let name = base;
93
- if (keepAliases) {
94
- for (let i = 2; modeNames.has(name); i++)
95
- name = base + " " + String(i);
96
- if (name !== base)
97
- report(node, "approximated", `variable mode renamed from ${quoted(base)} to ${quoted(name)}`);
98
- modeNames.add(name);
99
- }
100
- return { ...mode, id: newId(), name };
101
- }) };
97
+ const namedModes = [];
98
+ for (const [index, mode] of modes.entries()) {
99
+ const base = mode.name || `Mode ${String(index + 1)}`;
100
+ let name = base;
101
+ if (keepAliases) {
102
+ for (let i = 2; modeNames.has(name); i++)
103
+ name = base + " " + String(i);
104
+ if (name !== base)
105
+ report(node, "approximated", `variable mode renamed from ${quoted(base)} to ${quoted(name)}`);
106
+ modeNames.add(name);
107
+ }
108
+ namedModes.push({ ...mode, id: newId(), name });
109
+ }
110
+ const set = { node, id, modes: namedModes };
102
111
  for (const at of keys)
103
112
  setsByKey.set(at, set);
104
113
  const base = node.name || "Collection";
105
114
  let name = base;
106
- for (let seen = 2; names.has(name); seen++)
107
- name = `${base} ${String(seen)}`;
115
+ // Native file records name collections by id, as Figma does, so only the literal reader numbers a repeated name.
116
+ if (!keepAliases)
117
+ for (let seen = 2; names.has(name); seen++)
118
+ name = `${base} ${String(seen)}`;
108
119
  names.add(name);
109
120
  if (name !== base)
110
121
  report(node, "approximated", `the variable collection is imported as ${quoted(name)}: another collection is named ${quoted(base)}`);
@@ -173,13 +184,8 @@ export function readFigmaVariables(nodes, newId, report, keepAliases = false) {
173
184
  };
174
185
  const known = new Map();
175
186
  let scoped;
176
- let described;
177
187
  for (const node of bySortPosition(variables, (variable) => field(variable.change, "sortPosition", "string", `node ${variable.id}`))) {
178
188
  const where = `node ${node.id}`;
179
- const leaveOut = (why) => {
180
- known.set(node, { missing: `the variable ${quoted(node.name)} is not imported: ${why}` });
181
- report(node, "node-left-out", `the variable is not imported: ${why}`);
182
- };
183
189
  if (deleted(node)) {
184
190
  known.set(node, { missing: `the variable ${quoted(node.name)} is deleted in Figma` });
185
191
  report(node, "node-left-out", "the variable is deleted in Figma; it is not imported");
@@ -187,13 +193,13 @@ export function readFigmaVariables(nodes, newId, report, keepAliases = false) {
187
193
  }
188
194
  const set = setOf(node);
189
195
  if (typeof set === "string") {
190
- leaveOut(set);
196
+ leaveOutVariable(known, node, report, set);
191
197
  continue;
192
198
  }
193
199
  const figmaType = field(node.change, "variableResolvedType", "string", where);
194
200
  const type = figmaType === undefined || !Object.hasOwn(TYPES, figmaType) ? undefined : TYPES[figmaType];
195
201
  if (type === undefined) {
196
- leaveOut(`Taco variables have no ${figmaType ?? "typeless"} type`);
202
+ leaveOutVariable(known, node, report, `Taco variables have no ${figmaType ?? "typeless"} type`);
197
203
  continue;
198
204
  }
199
205
  const resolved = set.modes.map((mode) => {
@@ -202,7 +208,7 @@ export function readFigmaVariables(nodes, newId, report, keepAliases = false) {
202
208
  });
203
209
  const fallback = resolved[0].value !== undefined ? resolved[0] : resolved.find((entry) => entry.value !== undefined);
204
210
  if (fallback?.value === undefined) {
205
- leaveOut(`no mode has a value Taco can hold (${resolved.map(({ mode, reason }) => `${quoted(mode.name)}: ${reason ?? ""}`).join(", ")})`);
211
+ leaveOutVariable(known, node, report, `no mode has a value Taco can hold (${resolved.map(({ mode, reason }) => `${quoted(mode.name)}: ${reason ?? ""}`).join(", ")})`);
206
212
  continue;
207
213
  }
208
214
  const scopes = field(node.change, "variableScopes", "list", where) ?? [];
@@ -219,10 +225,8 @@ export function readFigmaVariables(nodes, newId, report, keepAliases = false) {
219
225
  if (!keepAliases && aliased.length > 0) {
220
226
  report(node, "approximated", `aliases are imported as the values they resolve to, so the variable no longer follows them: ${aliased.map(({ mode, aliases }) => `${quoted(mode.name)} → ${aliases.map(quoted).join(" → ")}`).join(", ")}`);
221
227
  }
222
- if (scopes.some((scope) => scope !== "ALL_SCOPES"))
228
+ if (!keepAliases && scopes.some((scope) => scope !== "ALL_SCOPES"))
223
229
  scoped = { node: scoped?.node ?? node, count: (scoped?.count ?? 0) + 1 };
224
- if ((field(node.change, "description", "string", where) ?? "") !== "")
225
- described = { node: described?.node ?? node, count: (described?.count ?? 0) + 1 };
226
230
  const id = newId();
227
231
  if (keepAliases) {
228
232
  sources.set(id, node);
@@ -270,9 +274,6 @@ export function readFigmaVariables(nodes, newId, report, keepAliases = false) {
270
274
  if (scoped !== undefined) {
271
275
  report(scoped.node, "property-left-out", `Figma variable scopes are not imported: ${String(scoped.count)} scoped variable${scoped.count === 1 ? " is" : "s are"} offered for every property of ${scoped.count === 1 ? "its" : "their"} type, first this one`);
272
276
  }
273
- if (described !== undefined) {
274
- report(described.node, "property-left-out", `variable descriptions are not imported: ${String(described.count)} variable${described.count === 1 ? " has" : "s have"} one, first this one`);
275
- }
276
277
  // The value of the variable an `ALIAS` binding `data` of layer `figma` names, in the mode the layer uses (`fontStyleOf`).
277
278
  const valueAt = (data, type, figma, where, shownBy) => {
278
279
  if (!isObject(data) || field(data, "dataType", "string", where) !== "ALIAS")
@@ -397,6 +398,28 @@ export function readFigmaVariables(nodes, newId, report, keepAliases = false) {
397
398
  },
398
399
  };
399
400
  }
401
+ /** Looks up a variable that can supply this typography field in every mode. */
402
+ export function typographyVariable(variables, name, data, where) {
403
+ if (name === "FONT_SIZE" || name === "LINE_HEIGHT")
404
+ return variables.positiveLengthOf(data, where);
405
+ if (name === "FONT_STYLE" && isObject(data) && data["dataType"] === "FONT_STYLE") {
406
+ const value = data["value"];
407
+ const style = isObject(value) && value["fontStyleValue"];
408
+ data = isObject(style) ? style["asString"] : undefined;
409
+ }
410
+ const v = variables.variableOf(data, where);
411
+ if (!("id" in v))
412
+ return null;
413
+ if (name === "FONT_FAMILY" || name === "FONT_STYLE")
414
+ return v.type === "string" && variables.valuesMatch(v.id, s => typeof s === "string" && !!s.trim()) ? v.id : null;
415
+ if (v.type !== "number" || v.opacity)
416
+ return null;
417
+ if (name === "FONT_WEIGHT")
418
+ return variables.valuesMatch(v.id, n => typeof n === "number" && n >= 1 && n <= 1000) ? v.id : null;
419
+ return name === "LETTER_SPACING" ? v.id : null;
420
+ }
421
+ /** The variable fields a text style sets. */
422
+ const TYPOGRAPHY_FIELDS = ["FONT_FAMILY", "FONT_STYLE", "FONT_WEIGHT", "FONT_SIZE", "LINE_HEIGHT", "LETTER_SPACING"];
400
423
  /** The Taco property a Figma `variableField` binds, or why Taco has no binding for it. */
401
424
  const FIELD_PROPERTIES = {
402
425
  CORNER_RADIUS: "cornerRadius",
@@ -531,6 +554,11 @@ export function bindLayerVariables(layer, figma, variables, report, overridden =
531
554
  const map = field(change, "variableConsumptionMap", "object", where);
532
555
  const entries = (map && field(map, "entries", "list", `${where} variableConsumptionMap`) || []).filter(isObject);
533
556
  const byField = new Map(entries.map((entry) => [field(entry, "variableField", "string", `${where} variableConsumptionMap`) ?? "", entry["variableData"]]));
557
+ // Figma detaches a text style when a typography field is bound, so such a binding beside a linked style is stale. The
558
+ // native adapter takes each run's typography source from the style, a range or an instance override instead.
559
+ if (variables?.sources.size && layer.type === "text" && change["styleIdForText"] !== undefined)
560
+ for (const name of TYPOGRAPHY_FIELDS)
561
+ byField.delete(name);
534
562
  // Taco has no binding for a font style name, so a text layer takes the bound style as a fixed weight, below.
535
563
  const styleBound = layer.type === "text" && variables !== undefined && byField.has("FONT_STYLE");
536
564
  const styleData = styleBound ? byField.get("FONT_STYLE") : undefined;
@@ -544,6 +572,12 @@ export function bindLayerVariables(layer, figma, variables, report, overridden =
544
572
  const bound = group.fields.filter((name) => byField.has(name));
545
573
  if (bound.length === 0)
546
574
  continue;
575
+ // Saved files install these fields independently from their original records in the native adapter.
576
+ if (variables?.sources.size) {
577
+ for (const name of bound)
578
+ byField.delete(name);
579
+ continue;
580
+ }
547
581
  const keys = bound.map((name) => JSON.stringify(byField.get(name)));
548
582
  if (bound.length === group.fields.length && keys.every((key) => key === keys[0])) {
549
583
  candidates.push({ label: bound.join(", "), property: group.property, data: byField.get(bound[0]) });
@@ -569,7 +603,7 @@ export function bindLayerVariables(layer, figma, variables, report, overridden =
569
603
  .some((paint) => isObject(paint) && paint["colorVar"] !== undefined && JSON.stringify(paint["colorVar"]) !== layerColor)
570
604
  || (field(field(entry, "variableConsumptionMap", "object", where) ?? {}, "entries", "list", where) ?? [])
571
605
  .some((item) => !isObject(item) || JSON.stringify(item["variableData"]) !== layerFields.get(item["variableField"]))).length;
572
- if (styleBound && layer.type === "text") {
606
+ if (styleBound && layer.type === "text" && !variables?.sources.size) {
573
607
  const resolved = variables.fontStyleOf(styleData, figma, `${where} FONT_STYLE`, shownBy);
574
608
  const weight = "style" in resolved ? fontStyleWeight(resolved.style) : undefined;
575
609
  if ("missing" in resolved)
@@ -14,7 +14,7 @@ export declare function remapVariantNode(node: SceneNode, mapping: ReadonlyMap<N
14
14
  componentId: ComponentDefinition["id"];
15
15
  condition: string;
16
16
  }>): SceneNode;
17
- export declare function mergeVariantTrees(nodes: readonly SceneNode[], components: readonly ComponentDefinition[], plans: readonly VariantTreePlan[], theme: DocumentTheme): {
17
+ export declare function mergeVariantTrees(nodes: readonly SceneNode[], components: readonly ComponentDefinition[], plans: readonly VariantTreePlan[], theme: DocumentTheme, distinctLayers?: ReadonlySet<NodeId>): {
18
18
  nodes: SceneNode[];
19
19
  layerOf: ReadonlyMap<NodeId, NodeId>;
20
20
  };
@@ -1,6 +1,10 @@
1
1
  import { EXPRESSION_TYPES, checkExpressionSource, componentExpressionEnvironment, componentValueEnvironment, evaluateExpression, expressionValuesEqual, computableFieldsOf, computableFieldType, expressionValueSource, formatExpressionString, layerPathKey, parseExpression, parseLayerPath, resolveTextStyle, storedFieldValue, variablePropertiesOfField, variablesByExpressionName, variableExpressionType, writeValueTable, } from "../../model/index.js";
2
- const stable = (value) => JSON.stringify(value, (_, item) => item !== null && typeof item === "object" && !Array.isArray(item)
3
- ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : item);
2
+ import { imageCropOf, imageTileOf, withImageCrop } from "./carry.js";
3
+ const stable = (value) => JSON.stringify(value, (key, item) => {
4
+ const carried = withImageCrop(key, item);
5
+ return carried !== null && typeof carried === "object" && !Array.isArray(carried)
6
+ ? Object.fromEntries(Object.entries(carried).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : carried;
7
+ });
4
8
  const same = (values) => {
5
9
  const first = stable(values[0]);
6
10
  return values.every((value) => stable(value) === first);
@@ -180,6 +184,33 @@ function remainder(document, member, root) {
180
184
  // Moondraft patch (carry.ts): metadata (what figma-import carries) does not split a layer; the merged layer keeps the first variant's.
181
185
  for (const key of ["id", "children", "expressions", "condition", "metadata"])
182
186
  delete rest[key];
187
+ // Geometry and layout settings carried for Moondraft can differ between variants and split the layer.
188
+ const figma = node.metadata?.["figma"];
189
+ if (figma?.boolean !== undefined)
190
+ rest["boolean"] = figma.boolean;
191
+ if (figma?.vectorStrokeCaps && Object.keys(figma.vectorStrokeCaps).length > 0)
192
+ rest["vectorStrokeCaps"] = figma.vectorStrokeCaps;
193
+ if (figma?.firstOnTop === true)
194
+ rest["firstOnTop"] = true;
195
+ if (figma?.gridCell !== undefined)
196
+ rest["gridCell"] = figma.gridCell;
197
+ if (figma?.fillSizing !== undefined)
198
+ rest["fillSizing"] = figma.fillSizing;
199
+ if (figma?.groupConstraints !== undefined)
200
+ rest["groupConstraints"] = figma.groupConstraints;
201
+ // Region paints keep image placement in WeakMap marks, which structuredClone cannot copy.
202
+ if (node.type === "shape" && node.shape === "path") {
203
+ const placement = node.vectorNetwork.regions.flatMap((region, regionIndex) => (region.fills ?? []).flatMap((paint, paintIndex) => {
204
+ if (paint.kind !== "image")
205
+ return [];
206
+ const tile = imageTileOf(paint), crop = imageCropOf(paint);
207
+ return tile === undefined && crop === undefined ? [] : [{ regionIndex, paintIndex, tile, crop }];
208
+ }));
209
+ if (placement.length > 0)
210
+ rest["regionImagePlacement"] = placement;
211
+ if (figma?.regionCropSize !== undefined)
212
+ rest["regionCropSize"] = figma.regionCropSize;
213
+ }
183
214
  if (root)
184
215
  for (const key of ["name", "aspectRatio", "aspectRatioLocked"])
185
216
  delete rest[key];
@@ -210,8 +241,12 @@ function remainder(document, member, root) {
210
241
  if (layout !== undefined && layout["kind"] !== "absolute") {
211
242
  for (const key of ["gap", "wrapGap", "columnGap", "rowGap", "padding", "align", "justify", "wrap"])
212
243
  delete layout[key];
213
- if (["horizontal", "vertical"].includes(String(layout["kind"])))
244
+ if (["horizontal", "vertical"].includes(String(layout["kind"]))) {
214
245
  layout["kind"] = "stack";
246
+ const figma = node.metadata?.["figma"];
247
+ if (figma?.strokesIncluded === true)
248
+ layout["strokesIncluded"] = true;
249
+ }
215
250
  }
216
251
  if (node.type === "instance") {
217
252
  delete rest["propertyValues"];
@@ -269,7 +304,7 @@ export function remapVariantNode(node, mapping, scopes = new Map()) {
269
304
  }
270
305
  return { ...node, overrides, ...(slots === undefined ? {} : { slots }) };
271
306
  }
272
- export function mergeVariantTrees(nodes, components, plans, theme) {
307
+ export function mergeVariantTrees(nodes, components, plans, theme, distinctLayers) {
273
308
  const byId = new Map(nodes.map((node) => [node.id, node]));
274
309
  const document = { nodes: Object.fromEntries(byId), components: Object.fromEntries(components.map((component) => [component.id, component])), theme };
275
310
  const mapping = new Map();
@@ -334,6 +369,8 @@ export function mergeVariantTrees(nodes, components, plans, theme) {
334
369
  const members = group.members.map((member) => member.remapped ? member : ({ ...member, node: remapVariantNode(member.node, mapping, scopes), remapped: true }));
335
370
  const base = members[0].node;
336
371
  const id = base.id;
372
+ if (distinctLayers?.size)
373
+ fail("layer metadata", members.map(({ node }) => distinctLayers.has(node.id) ? node.id : undefined));
337
374
  const rest = members.map((member) => remainder(document, member, root));
338
375
  for (const other of rest.slice(1))
339
376
  for (const field of differences(rest[0], other)) {
@@ -361,6 +398,11 @@ export function mergeVariantTrees(nodes, components, plans, theme) {
361
398
  const bound = members.map(({ node }) => variablePropertiesOfField(field).map((key) => node.variableBindings?.[key]));
362
399
  if (same(values) && same(existing) && same(bound))
363
400
  continue;
401
+ // A fill expression cannot carry crop marks on the paints it creates.
402
+ if (field === "fills" && values.some((value) => value?.kind === "list" && value.items.some((item) => item.kind === "paint" && imageCropOf(item.value)))) {
403
+ fail(field, values);
404
+ continue;
405
+ }
364
406
  // A text expression changes every run; differing rich runs cannot be represented by one field.
365
407
  if (base.type === "text" && members.some(({ node }) => node.type === "text" && (node.paragraphs.length !== 1 || node.paragraphs[0].runs.length !== 1)) && !["width", "height", "visible", "opacity"].includes(field)) {
366
408
  fail(`paragraphs (${field})`, members.map(({ node }) => node.type === "text" ? node.paragraphs : undefined));
@@ -1,9 +1,10 @@
1
1
  import { type AssetId, type ComponentDefinition, type ComponentId, type NodeId, type SceneNode, type TextNode, type TextStyle, type TextStyleId } from "../../model/index.ts";
2
2
  import { type FigmaObject } from "./fields.ts";
3
3
  import { type FigmaStyleList } from "./styles.ts";
4
+ import { type StoredFigmaBox } from "./instances.ts";
4
5
  import { type ImportedProperty } from "./componentProps.ts";
5
6
  import { planSet } from "./componentSets.ts";
6
- import { type FigmaTreeNode } from "./tree.ts";
7
+ import { type FigmaTree, type FigmaTreeNode } from "./tree.ts";
7
8
  import { type FigmaImportedPage, type FigmaImportOptions } from "./types.ts";
8
9
  import type { FigmaImportedImage, FigmaImportReportEntry, FigmaImportReportKind, FigmaImportResult } from "./types.ts";
9
10
  /** What a converter gets besides the node it converts. */
@@ -18,6 +19,8 @@ export interface NodeWalk {
18
19
  convertChildren(): readonly NodeId[];
19
20
  /** Adds a report entry about this node. */
20
21
  report(kind: FigmaImportReportKind, reason: string): void;
22
+ /** Moondraft patch 0010: whether the node is placed by its parent's auto layout (not absolute in it). */
23
+ readonly inFlow?: boolean;
21
24
  /** The bytes of a blob the node refers to (see `blobReader`), or `undefined` when the message has no such blob. */
22
25
  blob(reference: number): Uint8Array | undefined;
23
26
  /**
@@ -29,9 +32,11 @@ export interface NodeWalk {
29
32
  image(hashHex: string, size?: {
30
33
  width: number;
31
34
  height: number;
32
- }): {
33
- assetId: AssetId;
34
- } | string | null;
35
+ }, media?: {
36
+ video?: boolean;
37
+ bytes?: Uint8Array;
38
+ poster?: FigmaImportedImage;
39
+ }): FigmaImportedImage | string | null;
35
40
  /** Records the source indexes of paints accepted by the native file adapter.
36
41
  * @param source - Original Figma paint list.
37
42
  * @param indices - Original indexes in output order.
@@ -80,11 +85,20 @@ export interface NodeWalk {
80
85
  * @returns Whether the colour already supplies this opacity.
81
86
  */
82
87
  copiedPaintAlpha?(paint: FigmaObject, opacity: number): boolean;
83
- /** Looks up the numeric variable controlling one imported text range.
88
+ /** Looks up the typography variable controlling one imported text range.
89
+ * @param field - Figma typography field.
84
90
  * @param data - Figma variable binding.
85
91
  * @returns The local variable ID, or null for an unresolved binding.
86
92
  */
87
- fontSizeVariable?(data: unknown): string | null;
93
+ typographyVariable?(field: string, data: unknown): string | null;
94
+ /** Local variable ID for the solid paint drawn by a saved text run, or null to keep its literal. */
95
+ textColorVariable?(data: unknown): string | null;
96
+ /** Source GUID of a named fill style on a saved text run. */
97
+ textFillStyle?(reference: unknown): string | undefined;
98
+ /** Local instance fields that can override typography from a shared text style. */
99
+ instanceTypography?: FigmaObject;
100
+ /** Whether a run draws paint authored in this file instance override. */
101
+ plainTextPaint?(range: FigmaObject | undefined): boolean;
88
102
  /** The font size Taco draws text `layer`, converted from this node, at where it keeps the node's font size binding (`keptFontSize`). */
89
103
  keptFontSize?(layer: TextNode): number | undefined;
90
104
  }
@@ -127,13 +141,17 @@ export declare function readFileMessage(message: unknown, options: FigmaImportOp
127
141
  plan: Exclude<ReturnType<typeof planSet>, string>;
128
142
  properties: ImportedProperty[];
129
143
  }>;
130
- tree: import("./tree.ts").FigmaTree;
144
+ tree: FigmaTree;
131
145
  styleLayers: Map<string, SceneNode>;
146
+ styleNodeFor: (reference: unknown, styleType: string) => FigmaTreeNode | undefined;
132
147
  textStyleUses: Map<FigmaTreeNode, FigmaTextStyleUse>;
133
148
  paintIndices: Map<readonly unknown[], number[]>;
134
149
  effectFields: Map<Readonly<Record<string, unknown>>, string>;
135
150
  occurrenceFields: Map<string, Map<string, Readonly<Record<string, unknown>>>>;
151
+ instanceBoxes: Map<string, Map<string, StoredFigmaBox>>;
152
+ instanceFillSizes: Map<string, Map<string, StoredFigmaBox>>;
136
153
  imported: ImportedNode[];
154
+ omittedSubtrees: Set<FigmaTreeNode>;
137
155
  };
138
156
  rootSource: import("./types.ts").FigmaRootSource;
139
157
  roots: SceneNode[];
@@ -150,6 +168,43 @@ export declare function readFileMessage(message: unknown, options: FigmaImportOp
150
168
  variableCollections: Readonly<Record<string, import("../../model/types.ts").VariableCollection>>;
151
169
  textStyles: Record<string, TextStyle>;
152
170
  };
171
+ /** Reads converted layers with their original Figma nodes for Moondraft's adapters. */
172
+ export declare function walkMessage(message: unknown, options: FigmaImportOptions, native: boolean, distinctSources?: (tree: FigmaTree) => ReadonlySet<string>): {
173
+ sources: {
174
+ variables: import("./variables.ts").FigmaVariables | undefined;
175
+ variants: Map<string, {
176
+ plan: Exclude<ReturnType<typeof planSet>, string>;
177
+ properties: ImportedProperty[];
178
+ }>;
179
+ tree: FigmaTree;
180
+ styleLayers: Map<string, SceneNode>;
181
+ styleNodeFor: (reference: unknown, styleType: string) => FigmaTreeNode | undefined;
182
+ textStyleUses: Map<FigmaTreeNode, FigmaTextStyleUse>;
183
+ paintIndices: Map<readonly unknown[], number[]>;
184
+ effectFields: Map<Readonly<Record<string, unknown>>, string>;
185
+ occurrenceFields: Map<string, Map<string, Readonly<Record<string, unknown>>>>;
186
+ instanceBoxes: Map<string, Map<string, StoredFigmaBox>>;
187
+ instanceFillSizes: Map<string, Map<string, StoredFigmaBox>>;
188
+ imported: ImportedNode[];
189
+ omittedSubtrees: Set<FigmaTreeNode>;
190
+ };
191
+ result: {
192
+ rootSource: import("./types.ts").FigmaRootSource;
193
+ roots: SceneNode[];
194
+ nodes: SceneNode[];
195
+ pages: FigmaImportedPage[];
196
+ report: FigmaImportReportEntry[];
197
+ assets: Record<AssetId, FigmaImportedImage>;
198
+ layerIds: Record<string, NodeId>;
199
+ components: ComponentDefinition[];
200
+ componentIds: Record<string, ComponentId>;
201
+ componentPlacements: {
202
+ [k: string]: ComponentId;
203
+ };
204
+ variableCollections: Readonly<Record<string, import("../../model/types.ts").VariableCollection>>;
205
+ textStyles: Record<string, TextStyle>;
206
+ };
207
+ };
153
208
  /** A converted node with the Figma node it came from and its path. */
154
209
  interface ImportedNode {
155
210
  readonly node: SceneNode;