@moondraft/import 0.2.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 (56) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/SOURCE.md +115 -1
  3. package/dist/adapter/convert.d.ts +2 -0
  4. package/dist/adapter/convert.js +175 -84
  5. package/dist/adapter/figma-handoff.d.ts +24 -2
  6. package/dist/adapter/figma-handoff.js +39 -18
  7. package/dist/adapter/figma.js +2 -1
  8. package/dist/adapter/file-components.d.ts +2 -1
  9. package/dist/adapter/file-components.js +5 -2
  10. package/dist/adapter/file-resources.js +234 -25
  11. package/dist/adapter/file-typography.d.ts +6 -0
  12. package/dist/adapter/file-typography.js +44 -0
  13. package/dist/adapter/link.d.ts +7 -0
  14. package/dist/adapter/link.js +87 -24
  15. package/dist/adapter/payload.js +2 -2
  16. package/dist/adapter/variables.d.ts +1 -1
  17. package/dist/figma-file.d.ts +1 -0
  18. package/dist/figma-file.js +1 -0
  19. package/dist/figma.d.ts +1 -0
  20. package/dist/figma.js +41 -19
  21. package/dist/report.d.ts +37 -6
  22. package/dist/report.js +91 -18
  23. package/dist/taco/figma-import/figFile.js +3 -0
  24. package/dist/taco/figma-import/import/converters/effects.d.ts +3 -13
  25. package/dist/taco/figma-import/import/converters/effects.js +4 -34
  26. package/dist/taco/figma-import/import/converters/exportSettings.js +26 -0
  27. package/dist/taco/figma-import/import/converters/frame.d.ts +1 -1
  28. package/dist/taco/figma-import/import/converters/frame.js +8 -7
  29. package/dist/taco/figma-import/import/converters/grid.d.ts +12 -0
  30. package/dist/taco/figma-import/import/converters/grid.js +97 -0
  31. package/dist/taco/figma-import/import/converters/image.d.ts +1 -0
  32. package/dist/taco/figma-import/import/converters/image.js +38 -5
  33. package/dist/taco/figma-import/import/converters/layout.d.ts +5 -3
  34. package/dist/taco/figma-import/import/converters/layout.js +26 -16
  35. package/dist/taco/figma-import/import/converters/rectangle.js +2 -2
  36. package/dist/taco/figma-import/import/converters/section.js +2 -2
  37. package/dist/taco/figma-import/import/converters/shared.d.ts +2 -1
  38. package/dist/taco/figma-import/import/converters/shared.js +8 -5
  39. package/dist/taco/figma-import/import/converters/text.d.ts +24 -0
  40. package/dist/taco/figma-import/import/converters/text.js +114 -29
  41. package/dist/taco/figma-import/import/instances.d.ts +9 -3
  42. package/dist/taco/figma-import/import/instances.js +319 -43
  43. package/dist/taco/figma-import/import/types.d.ts +8 -0
  44. package/dist/taco/figma-import/import/variables.d.ts +2 -0
  45. package/dist/taco/figma-import/import/variables.js +28 -1
  46. package/dist/taco/figma-import/import/variantTrees.js +2 -0
  47. package/dist/taco/figma-import/import/walk.d.ts +9 -2
  48. package/dist/taco/figma-import/import/walk.js +69 -30
  49. package/dist/taco/figma-import/kiwi/message.js +52 -10
  50. package/dist/taco/model/codec.d.ts +1 -1
  51. package/dist/taco/model/codec.js +40 -6
  52. package/dist/taco/model/instance-resolver.js +3 -1
  53. package/dist/taco/model/types.d.ts +36 -6
  54. package/dist/taco/model/types.js +4 -0
  55. package/dist/taco/svg-import/style/computed.js +1 -0
  56. package/package.json +2 -2
@@ -1,14 +1,17 @@
1
1
  import { constrainChildren, entryOf, formatExpressionName, getNodeBounds, layerPathKey, paragraphsFromCharacters, parseLayerPath, PROPERTIES_DROPPED_BY_FIELD, TEXT_STYLE_PROPERTIES, } from "../../model/index.js";
2
- import { stackLayoutOf } from "./converters/layout.js";
2
+ import { gridAxis, gridCell, gridChildFields } from "./converters/grid.js";
3
+ import { autoLayoutOf } from "./converters/layout.js";
3
4
  import { withImageCrop } from "./carry.js";
4
5
  import { field, guidText, isObject } from "./fields.js";
5
6
  import { isDetachedStyle, STYLE_REFERENCE_FIELDS, styleBackedList } from "./styles.js";
6
7
  import { assignedPropertyValues, assignedValueOf, propertyByFigmaId } from "./componentProps.js";
7
8
  import { frameGeometry, readNumbers, STROKE_CAPS } from "./converters/shared.js";
8
- import { hyperlinkOf, inheritOpenTypeToggles, KEPT_LINE_HEIGHT_FIELD, OPEN_TYPE_FIELDS, OPEN_TYPE_TOGGLES } from "./converters/text.js";
9
+ import { hyperlinkOf, inheritOpenTypeToggles, KEPT_LINE_HEIGHT_FIELD, LAID_OUT_LINES_FIELD, OWN_TYPOGRAPHY, TEXT_VARIABLE_FIELDS, OPEN_TYPE_FIELDS, OPEN_TYPE_TOGGLES } from "./converters/text.js";
9
10
  import { exportSettingsOf } from "./converters/exportSettings.js";
10
11
  /** The `variableConsumptionMap` fields that bind each merged override field. */
11
12
  const BOUND_BY_OVERRIDE = {
13
+ fontName: ["FONT_FAMILY", "FONT_STYLE", "FONT_WEIGHT"], fontSize: ["FONT_SIZE"],
14
+ lineHeight: ["LINE_HEIGHT"], letterSpacing: ["LETTER_SPACING"],
12
15
  size: ["WIDTH", "HEIGHT"], visible: ["VISIBLE"], opacity: ["OPACITY"],
13
16
  strokeWeight: ["STROKE_WEIGHT", "BORDER_TOP_WEIGHT", "BORDER_RIGHT_WEIGHT", "BORDER_BOTTOM_WEIGHT", "BORDER_LEFT_WEIGHT"],
14
17
  };
@@ -40,9 +43,12 @@ function overriddenBindingFields(name, value, before) {
40
43
  * `change` with the `overridden` fields merged in and without the component's bindings of the fields they change:
41
44
  * Figma unbinds a field that an override sets, so the instance takes the override's value, not the component's variable.
42
45
  */
43
- function withOverrides(change, overridden) {
46
+ function withOverrides(change, overridden, replacesTextStyle) {
44
47
  const merged = { ...change, ...overridden };
45
48
  const unbound = new Set(Object.entries(overridden).flatMap(([name, value]) => overriddenBindingFields(name, value, change[name])));
49
+ if (replacesTextStyle)
50
+ for (const field of Object.keys(TEXT_VARIABLE_FIELDS))
51
+ unbound.add(field);
46
52
  const map = change["variableConsumptionMap"];
47
53
  if (unbound.size === 0 || !isObject(map) || !Array.isArray(map["entries"]))
48
54
  return merged;
@@ -111,6 +117,50 @@ function withBindingEntries(map, over) {
111
117
  const named = new Set(overEntries.map(fieldOf));
112
118
  return { ...isObject(map) ? map : {}, entries: [...entriesOf(map).filter((entry) => !named.has(fieldOf(entry))), ...overEntries] };
113
119
  }
120
+ const typographyFields = new Set(["styleIdForText", ...Object.values(TEXT_VARIABLE_FIELDS).map(([, name]) => name)]);
121
+ function typographyEntries(change) {
122
+ const map = change["variableConsumptionMap"];
123
+ if (!isObject(map) || !Array.isArray(map["entries"]))
124
+ return [];
125
+ return map["entries"].filter((entry) => isObject(entry) && typeof entry["variableField"] === "string" && Object.hasOwn(TEXT_VARIABLE_FIELDS, entry["variableField"]));
126
+ }
127
+ function hasRangeTypography(data) {
128
+ if (!isObject(data) || !Array.isArray(data["styleOverrideTable"]))
129
+ return false;
130
+ return data["styleOverrideTable"].some(range => isObject(range) &&
131
+ (Object.keys(range).some(name => typographyFields.has(name)) || typographyEntries(range).length > 0));
132
+ }
133
+ /** The typography already applied to this text by instances inside the one being converted. */
134
+ function innerTextFields(target, context) {
135
+ if (target.layer.node.type !== "text" || !context.nestedTextFields)
136
+ return;
137
+ let inherited;
138
+ for (let i = target.through.length - 1; i >= 0; i--) {
139
+ const { instance, inner } = target.through[i];
140
+ const change = context.nestedTextFields(instance, inner);
141
+ if (!change)
142
+ continue;
143
+ const fields = {};
144
+ for (const name of typographyFields)
145
+ if (name in change)
146
+ fields[name] = change[name];
147
+ // What the inner instance shows of the truncation, so an outer override reads against it (`mergeOverrides`).
148
+ for (const name of ["textTruncation", "maxLines"])
149
+ if (name in change)
150
+ fields[name] = change[name];
151
+ const data = change["textData"];
152
+ // A replacement range table can introduce bindings or remove ones on the underlying text.
153
+ if (data && (hasRangeTypography(data) || hasRangeTypography(inherited?.["textData"] ?? target.layer.figma.change["textData"])))
154
+ fields["textData"] = data;
155
+ const entries = typographyEntries(change);
156
+ if (!Object.keys(fields).length && !entries.length)
157
+ continue;
158
+ const base = { ...target.layer.figma.change, ...inherited };
159
+ const unbound = withOverrides(base, fields, fields["styleIdForText"] !== undefined);
160
+ inherited = { ...inherited, ...fields, variableConsumptionMap: withBindingEntries(unbound["variableConsumptionMap"], { entries }) };
161
+ }
162
+ return inherited;
163
+ }
114
164
  /**
115
165
  * Writes `null` in each override for a binding the model would keep from a nested instance's own override (`mergeOverrides`
116
166
  * in the model) of a field the override sets plainly. Runs once every instance has its overrides, since the nested instances
@@ -136,10 +186,13 @@ export function unbindInnerBindings(overrides, nested) {
136
186
  overrides[key] = { ...override, variableBindings: { ...override.variableBindings, ...nulls } };
137
187
  }
138
188
  }
139
- /** The key an override path step names a layer by: its `overrideKey`, else its guid. */
189
+ /** The `overrideKey` Figma writes on a layer that has none of its own (both halves `0xFFFFFFFF`). */
190
+ const NO_OVERRIDE_KEY = "4294967295:4294967295";
191
+ /** The key an override path step names a layer by: its `overrideKey`, else (none, or the no-key marker) its guid. */
140
192
  export function overrideKeyOf(node) {
141
193
  const key = node.change["overrideKey"];
142
- return key === undefined ? node.id : guidText(key, `node ${node.id} overrideKey`);
194
+ const text = key === undefined ? undefined : guidText(key, `node ${node.id} overrideKey`);
195
+ return text === undefined || text === NO_OVERRIDE_KEY ? node.id : text;
143
196
  }
144
197
  /**
145
198
  * Override fields whose effect the walk reads by converting the layer with
@@ -156,7 +209,9 @@ const CONVERTED_FIELDS = new Set([
156
209
  /** Fields applied to a frame or to the component root shown by a nested instance. */
157
210
  const STACK_FIELDS = { gap: "stackSpacing", align: "stackCounterAlignItems", justify: "stackPrimaryAlignItems",
158
211
  wrap: "stackWrap", wrapGap: "stackCounterSpacing", alignContent: "stackCounterAlignContent" };
159
- const FRAME_FIELDS = new Set(["stackPrimarySizing", "stackCounterSizing", "stackMode", ...Object.values(STACK_FIELDS),
212
+ const GRID_FIELDS = { columns: "gridColumns", columnTracks: "gridColumnsSizing", rowTracks: "gridRowsSizing",
213
+ columnGap: "gridColumnGap", rowGap: "gridRowGap" };
214
+ const FRAME_FIELDS = new Set(["stackPrimarySizing", "stackCounterSizing", "stackMode", ...Object.values(STACK_FIELDS), "gridRows", ...Object.values(GRID_FIELDS),
160
215
  "frameMaskDisabled", "cornerSmoothing"]);
161
216
  /** Keep only changed members, including explicit defaults which clear an inherited setting. */
162
217
  function frameOverrides(base, next, authored = {}) {
@@ -171,6 +226,12 @@ function frameOverrides(base, next, authored = {}) {
171
226
  layout[key] = after[key] ?? (key === "wrap" ? false : key === "alignContent" ? "auto" : after.gap);
172
227
  }
173
228
  }
229
+ if (after.kind === "grid") {
230
+ for (const key of Object.keys(GRID_FIELDS)) {
231
+ if (before.kind !== "grid" || !same(before[key], after[key]) || GRID_FIELDS[key] in authored)
232
+ layout[key] = after[key];
233
+ }
234
+ }
174
235
  const sizing = before.kind === "absolute" && after.kind !== "absolute" ? { width: after.widthSizing, height: after.heightSizing } : undefined;
175
236
  return { ...(Object.keys(layout).length && { layout }), ...(sizing && { sizing }),
176
237
  ...(before.kind === "absolute" && after.kind !== "absolute" && { padding: after.padding }),
@@ -178,7 +239,7 @@ function frameOverrides(base, next, authored = {}) {
178
239
  }
179
240
  /**
180
241
  * Padding override fields and the side each sets (`stackPadding`, Figma's older single value, sets every side the
181
- * entry does not set on its own), as `stackLayoutOf` reads them.
242
+ * entry does not set on its own), as `autoLayoutOf` reads them.
182
243
  */
183
244
  const PADDING_FIELDS = {
184
245
  stackHorizontalPadding: ["left"], stackPaddingRight: ["right"], stackVerticalPadding: ["top"], stackPaddingBottom: ["bottom"],
@@ -194,8 +255,8 @@ const PADDING_FIELDS_OF_SIDE = {
194
255
  const BOOKKEEPING_FIELDS = new Set([
195
256
  "guidPath", "overrideLevel", "textUserLayoutVersion", "vectorOperationVersion", "fontVersion",
196
257
  ]);
258
+ /** Dev Mode annotations and measurements. The editor adapter reports them with the layer's own (`figmaHandoff`). */
197
259
  const HANDOFF_OVERRIDE_FIELDS = new Set(["annotations", "measurements"]);
198
- const activeHandoffOverride = (value) => value !== undefined && (!Array.isArray(value) || value.some((item) => !isObject(item) || item["isDeleted"] !== true));
199
260
  /** The parts of a converted layer an instance can override, as `LayerOverride` fields, plus those it cannot. */
200
261
  const STYLE_OVERRIDES = ["cornerSmoothing", "fills", "strokes", "shadows", "layerBlur", "backgroundBlur"];
201
262
  const same = (a, b) => JSON.stringify(a, withImageCrop) === JSON.stringify(b, withImageCrop);
@@ -338,7 +399,7 @@ function overrideBetween(base, next, report) {
338
399
  /**
339
400
  * The `LayerOverride.sizing` that turns the Hug or Fixed sizing of `base` (a
340
401
  * component layer, converted on its own) into that of `next` (the same layer
341
- * with an instance's override fields, converted), both by `stackLayoutOf`, or
402
+ * with an instance's override fields, converted), both by `autoLayoutOf`, or
342
403
  * `undefined` when nothing differs or either is not a stack. An axis where the
343
404
  * layer fills its stack is taken off later, by `dropSizingWhereFilled`.
344
405
  */
@@ -426,6 +487,14 @@ export function dropSizingWhereFilled(overrides, nodes, roots) {
426
487
  const INSIDE_LEFT_OUT = "inside a left-out swap";
427
488
  /** The override fields that give a text layer another line height, so an instance that sets one keeps its own. */
428
489
  const LINE_HEIGHT_SETTERS = ["lineHeight", "styleIdForText", "fontSize"];
490
+ /** Override fields that set a text's lines otherwise than its component's. */
491
+ const LINE_SETTERS = [...LINE_HEIGHT_SETTERS, "textData", "fontName", "letterSpacing", "paragraphSpacing", "listSpacing", "fontVariations", KEPT_LINE_HEIGHT_FIELD];
492
+ /** Whether override fields bind a variable to the line height or font size. */
493
+ function bindsLeading(fields, where) {
494
+ const map = field(fields, "variableConsumptionMap", "object", where);
495
+ return (map && field(map, "entries", "list", `${where} variableConsumptionMap`) || [])
496
+ .some((item) => isObject(item) && (item["variableField"] === "LINE_HEIGHT" || item["variableField"] === "FONT_SIZE"));
497
+ }
429
498
  /**
430
499
  * The one line height in pixels Figma laid out every line of a text at, read from its stored layout (`derivedTextData`,
431
500
  * on a text node or a `derivedSymbolData` entry), or `undefined` without lines or with lines of different heights.
@@ -737,9 +806,13 @@ export function instanceFields(instance, component, self, context) {
737
806
  }
738
807
  }
739
808
  // A sparse INSTANCE can omit its entire stack and clip flag. Only authored fields replace the template.
740
- if (ownFields.stackMode === undefined || rootFields.stackMode !== undefined || ownFields.stackMode !== component.symbol.change["stackMode"]) {
741
- const stack = Object.keys(ownFields).some(key => FRAME_FIELDS.has(key) && key.startsWith("stack") || Object.hasOwn(PADDING_FIELDS, key));
742
- const layout = stack ? stackLayoutOf({ ...component.symbol.change, ...ownFields }, () => { }) : undefined;
809
+ if (component.root.layout.kind === "grid" || ownFields.stackMode === undefined || rootFields.stackMode !== undefined || ownFields.stackMode !== component.symbol.change["stackMode"]) {
810
+ const stack = Object.keys(ownFields).some(key => FRAME_FIELDS.has(key) && (key.startsWith("stack") || key.startsWith("grid")) || Object.hasOwn(PADDING_FIELDS, key));
811
+ const layout = stack || Object.keys(ownFields).some(key => key.startsWith("grid"))
812
+ ? autoLayoutOf({ ...component.symbol.change, ...ownFields }, () => { }, field => {
813
+ if (Object.hasOwn(ownFields, field.split(".")[0]))
814
+ context.report("property-left-out", `grid layout field ${field}`);
815
+ }) : undefined;
743
816
  self = { ...self, layout: layout ?? (ownFields.stackMode === undefined ? component.root.layout : self.layout) };
744
817
  }
745
818
  Object.assign(overrideAt(rootKey), frameOverrides(component.root, {
@@ -795,8 +868,9 @@ export function instanceFields(instance, component, self, context) {
795
868
  }
796
869
  return undefined;
797
870
  };
798
- // A placement's own assignment takes precedence over its enclosing holders.
799
- const propertySwap = (layer, inComponent, parentKey, through) => {
871
+ // A placement's own assignment takes precedence over its enclosing holders. With `ownOnly`, only this instance's
872
+ // own assignments at `parentKey` count.
873
+ const propertySwap = (layer, inComponent, parentKey, through, ownOnly = false) => {
800
874
  let symbolId;
801
875
  for (const ref of field(layer.change, "componentPropRefs", "list", `node ${layer.id}`) ?? []) {
802
876
  if (!isObject(ref) || ref["componentPropNodeField"] !== "OVERRIDDEN_SYMBOL_ID" || ref["defID"] === undefined || ref["isDeleted"] === true)
@@ -812,7 +886,7 @@ export function instanceFields(instance, component, self, context) {
812
886
  continue;
813
887
  own = assignedValueOf(assignment, `${where} componentPropAssignments`).symbolId ?? own;
814
888
  }
815
- symbolId = own ?? (swaps.has(parentKey) ? undefined : heldPropertySwap(through, property.definition.id)) ?? symbolId;
889
+ symbolId = own ?? (ownOnly || swaps.has(parentKey) ? undefined : heldPropertySwap(through, property.definition.id)) ?? symbolId;
816
890
  }
817
891
  return symbolId;
818
892
  };
@@ -827,6 +901,20 @@ export function instanceFields(instance, component, self, context) {
827
901
  return context.component(swapped);
828
902
  if (leftOutSwaps.has(key))
829
903
  return INSIDE_LEFT_OUT;
904
+ // This instance's own swap property value outranks a swap a nested instance authored below it. A Taco swap override
905
+ // outranks a property value, so where such a swap differs the value is written as this instance's swap too.
906
+ const assigned = through.length === 0 ? undefined : propertySwap(layer, inComponent, keys.slice(0, -1).join("/"), through, true);
907
+ if (assigned !== undefined) {
908
+ if (refusedSwap(inComponent, assigned) !== undefined)
909
+ return INSIDE_LEFT_OUT;
910
+ const componentId = componentIdOf(assigned);
911
+ if (componentId !== undefined && through.some(({ instance, inner }) => (context.nestedSwaps(instance, inner)?.symbol ?? assigned) !== assigned)) {
912
+ const key = layerPathKey([through[0].instance.id, ...parseLayerPath(through[0].inner)]);
913
+ overrideAt(key)["componentId"] = componentId;
914
+ swapsAtPath(key).symbol = assigned;
915
+ }
916
+ return context.component(assigned);
917
+ }
830
918
  for (const holder of through) {
831
919
  const inherited = context.nestedSwaps(holder.instance, holder.inner)?.symbol;
832
920
  if (inherited !== undefined)
@@ -912,22 +1000,98 @@ export function instanceFields(instance, component, self, context) {
912
1000
  }
913
1001
  return reset;
914
1002
  };
1003
+ /**
1004
+ * Gives the nested instances inside the instance at `keys` (`[]` for this one), which shows `shown`, the values in `list` that
1005
+ * name a property `shown` does not declare but a component shown by one of those instances does: each goes to the
1006
+ * shallowest nested instances whose shown component declares it, read against that component, where the instance's
1007
+ * `derivedSymbolData` lays out a layer bound to that property inside it (Figma ignores a stale value). Returns the other values.
1008
+ */
1009
+ let derivedPaths;
1010
+ // Whether the instance's `derivedSymbolData` lays out a layer of `nested`, shown at `keys`, that is bound to `defId`'s property.
1011
+ const laysOutBound = (nested, keys, defId) => {
1012
+ derivedPaths ??= new Set((field(instance.change, "derivedSymbolData", "list", where) ?? []).flatMap((entry, index) => {
1013
+ const at = `${where} derivedSymbolData[${String(index)}]`;
1014
+ const path = isObject(entry) ? field(entry, "guidPath", "object", at) : undefined;
1015
+ return path === undefined ? [] : [(field(path, "guids", "list", `${at}.guidPath`) ?? []).map(guid => guidText(guid, `${at}.guidPath`)).join("/")];
1016
+ }));
1017
+ const property = propertyByFigmaId(nested.properties, defId);
1018
+ for (const [key, layer] of nested.layers) {
1019
+ const bound = (field(layer.figma.change, "componentPropRefs", "list", `node ${layer.figma.id}`) ?? []).some(ref => isObject(ref) && ref["defID"] !== undefined
1020
+ && ref["isDeleted"] !== true && propertyByFigmaId(nested.properties, guidText(ref["defID"], `node ${layer.figma.id} componentPropRefs`)) === property);
1021
+ if (bound && derivedPaths.has([...keys, key].join("/")))
1022
+ return true;
1023
+ }
1024
+ return false;
1025
+ };
1026
+ const assignNestedValues = (list, shown, keys, at) => {
1027
+ if (list === undefined)
1028
+ return list;
1029
+ const own = [];
1030
+ const below = new Map();
1031
+ for (const assignment of list) {
1032
+ const defId = isObject(assignment) && assignment["defID"] !== undefined ? guidText(assignment["defID"], `${at} componentPropAssignments`) : undefined;
1033
+ if (defId === undefined || shown.variantDefs.has(defId) || propertyByFigmaId(shown.properties, defId) !== undefined) {
1034
+ own.push(assignment);
1035
+ continue;
1036
+ }
1037
+ const found = [];
1038
+ for (let level = [{ keys, component: shown }]; level.length > 0 && found.length === 0;) {
1039
+ const next = [];
1040
+ for (const { keys: outer, component: inside } of level) {
1041
+ for (const [key, layer] of inside.layers) {
1042
+ if (layer.figma.type !== "INSTANCE")
1043
+ continue;
1044
+ const path = [...outer, key];
1045
+ const target = resolve(path);
1046
+ if (target === undefined || target === INSIDE_LEFT_OUT || "flattenedInto" in target || target.layer !== layer)
1047
+ continue;
1048
+ const nested = shownAt(path, layer.figma, inside, target.through);
1049
+ if (nested === undefined || nested === INSIDE_LEFT_OUT)
1050
+ continue;
1051
+ if (propertyByFigmaId(nested.properties, defId) !== undefined) {
1052
+ if (laysOutBound(nested, [...outer, key], defId))
1053
+ found.push({ target, shown: nested });
1054
+ }
1055
+ else
1056
+ next.push({ keys: path, component: nested });
1057
+ }
1058
+ }
1059
+ level = next;
1060
+ }
1061
+ if (found.length === 0)
1062
+ own.push(assignment);
1063
+ for (const { target, shown: nested } of found) {
1064
+ let gathered = below.get(target.key);
1065
+ if (gathered === undefined)
1066
+ below.set(target.key, gathered = { shown: nested, list: [] });
1067
+ gathered.list.push(assignment);
1068
+ }
1069
+ }
1070
+ for (const [key, { shown: nested, list: values }] of below) {
1071
+ const read = assignedPropertyValues(values, nested.properties, nested.variantDefs, componentIdOf, leftOutValue(nested, key), at, context.report, captureLinks(nested, key));
1072
+ const override = overrideAt(key);
1073
+ if (Object.keys(read).length > 0)
1074
+ override["propertyValues"] = { ...read, ...override["propertyValues"] };
1075
+ }
1076
+ return own;
1077
+ };
915
1078
  const insideLeftOut = new Set();
916
1079
  const pending = new Map();
917
1080
  const targets = [];
918
1081
  let rootExports;
1082
+ const symbolKey = overrideKeyOf(component.symbol);
919
1083
  // Swaps first, shorter paths before longer ones, so property values and deeper paths are read against the component swapped in.
920
1084
  for (const { keys, entry, at } of entries) {
921
- // A path naming the component itself targets the instance, which already carries those values.
922
- if (keys.length === 1 && keys[0] === component.symbol.id) {
923
- for (const name of HANDOFF_OVERRIDE_FIELDS)
924
- if (activeHandoffOverride(entry[name]))
925
- context.leftOutField(name);
926
- if (entry["exportSettings"] !== undefined)
927
- rootExports = entry["exportSettings"];
1085
+ // A path of one step naming the component's root, by its guid or by its override key, holds the instance's own
1086
+ // export presets.
1087
+ const rootPath = keys.length === 1 && (keys[0] === component.symbol.id || keys[0] === symbolKey);
1088
+ if (rootPath && entry["exportSettings"] !== undefined)
1089
+ rootExports = entry["exportSettings"];
1090
+ // A path naming the component itself by guid targets the instance, which already carries those values; one naming
1091
+ // it by override key goes on as an override of the root layer.
1092
+ if (keys.length === 1 && keys[0] === component.symbol.id)
928
1093
  continue;
929
- }
930
- if (entry["exportSettings"] !== undefined) {
1094
+ if (!rootPath && entry["exportSettings"] !== undefined) {
931
1095
  context.report("property-left-out", "an export settings override on an inherited layer is left out");
932
1096
  }
933
1097
  const target = keys.length === 0 ? undefined : resolve(keys);
@@ -972,7 +1136,7 @@ export function instanceFields(instance, component, self, context) {
972
1136
  swapsKept.add(`${target.component.symbol.id}>${symbolId}`);
973
1137
  }
974
1138
  }
975
- const boxes = new Map();
1139
+ const boxes = new Map(), texts = new Map();
976
1140
  const from = component.root.frame;
977
1141
  const resizedFreeFrame = component.root.layout.kind === "absolute" && (self.frame.width !== from.width || self.frame.height !== from.height);
978
1142
  if (context.fileLayout) {
@@ -982,7 +1146,7 @@ export function instanceFields(instance, component, self, context) {
982
1146
  authored.set(key, { ...authored.get(key), ...entry });
983
1147
  }
984
1148
  for (const [index, entry] of (field(instance.change, "derivedSymbolData", "list", where) ?? []).entries()) {
985
- if (!isObject(entry) || (!resizedFreeFrame && entry["size"] === undefined))
1149
+ if (!isObject(entry) || (!resizedFreeFrame && entry["size"] === undefined && entry["derivedTextData"] === undefined))
986
1150
  continue;
987
1151
  const at = `${where} derivedSymbolData[${String(index)}]`;
988
1152
  const path = field(entry, "guidPath", "object", at);
@@ -997,13 +1161,20 @@ export function instanceFields(instance, component, self, context) {
997
1161
  const requestsFill = change["stackPositioning"] !== "ABSOLUTE" &&
998
1162
  (Number(change["stackChildPrimaryGrow"]) > 0 || change["stackChildAlignSelf"] === "STRETCH");
999
1163
  const fillLayer = layer.type === "group" || (layer.type === "shape" && layer.shape === "path");
1000
- if (!resizedFreeFrame && !(fillLayer && requestsFill))
1164
+ // A self-sizing text keeps the size Figma measured it at here (its text or font may be overridden): measured
1165
+ // again, without the document's fonts, it would come out at another size. An entry with the text's glyphs and no
1166
+ // size is one Figma measured at the size it has without the entry (`inner`).
1167
+ const sizesItself = layer.type === "text"
1168
+ && ["WIDTH_AND_HEIGHT", "HEIGHT"].includes(String(authored.get(keys.join("/"))?.["textAutoResize"] ?? change["textAutoResize"]));
1169
+ if (!resizedFreeFrame && !(fillLayer && requestsFill) && !sizesItself)
1001
1170
  continue;
1002
1171
  const box = storedBox(target.layer, entry, authored.get(keys.join("/")));
1003
- if (box)
1172
+ if (box && !resizedFreeFrame && sizesItself)
1173
+ texts.set(target.key, entry["size"] === undefined ? { ...box, inner: true } : box);
1174
+ else if (box)
1004
1175
  boxes.set(target.key, box);
1005
1176
  }
1006
- context.fileLayout(boxes, !resizedFreeFrame);
1177
+ context.fileLayout(boxes, !resizedFreeFrame, texts);
1007
1178
  }
1008
1179
  if (component.root.layout.kind === "absolute") {
1009
1180
  // A nested instance layer of the component that this instance swaps (by an override or a property value) to a component of another size.
@@ -1023,18 +1194,83 @@ export function instanceFields(instance, component, self, context) {
1023
1194
  context.report("approximated", "the layers of a resized instance follow their constraints to sizes or positions other than the ones Figma laid out for it");
1024
1195
  }
1025
1196
  }
1197
+ // Grid cell anchors are GUIDs in the source and indices in the model. Resolve an
1198
+ // occurrence's authored and inherited anchors against the same final track order.
1199
+ const gridParents = new Map();
1200
+ const rememberGrid = (owner, source, prefix, fields) => {
1201
+ if (fields.gridRows === undefined && fields.gridColumns === undefined)
1202
+ return;
1203
+ const parent = layersByFigmaId(owner).get(source.id);
1204
+ if (!parent)
1205
+ return;
1206
+ const key = layerPathKey([...prefix, parent.node.id]);
1207
+ gridParents.set(key, { source, owner, prefix, fields: { ...gridParents.get(key)?.fields, ...fields } });
1208
+ };
1209
+ rememberGrid(component, component.symbol, [], ownFields);
1210
+ for (const { gathered: { target }, keys, entry } of targets) {
1211
+ if (entry.gridRows === undefined && entry.gridColumns === undefined)
1212
+ continue;
1213
+ const path = parseLayerPath(target.key);
1214
+ if (target.layer.figma.type === "INSTANCE") {
1215
+ const shown = shownAt(keys, target.layer.figma, target.component, target.through);
1216
+ if (shown && shown !== INSIDE_LEFT_OUT)
1217
+ rememberGrid(shown, shown.symbol, path, entry);
1218
+ }
1219
+ else
1220
+ rememberGrid(target.component, target.layer.figma, path.slice(0, -1), entry);
1221
+ }
1222
+ const axesOf = (frame) => ({ rows: gridAxis(frame, "gridRows", () => { }).indices,
1223
+ columns: gridAxis(frame, "gridColumns", () => { }).indices });
1224
+ const gridAxes = new Map();
1225
+ for (const [key, { owner, source, fields, prefix }] of gridParents) {
1226
+ const effective = { ...source.change, ...fields };
1227
+ if (effective.stackMode !== "GRID")
1228
+ continue;
1229
+ const axes = axesOf(effective), original = axesOf(source.change);
1230
+ gridAxes.set(key, axes);
1231
+ for (const child of source.children) {
1232
+ const layer = layersByFigmaId(owner).get(child.id);
1233
+ if (!layer)
1234
+ continue;
1235
+ const anchors = { ...(fields.gridRows !== undefined && { gridRowAnchor: child.change.gridRowAnchor }),
1236
+ ...(fields.gridColumns !== undefined && { gridColumnAnchor: child.change.gridColumnAnchor }) };
1237
+ const cell = gridCell(anchors, axes.rows, axes.columns, field => context.leftOutField(field), true);
1238
+ const inherited = gridCell(anchors, original.rows, original.columns, () => { }, true);
1239
+ const changed = Object.entries(cell).filter(([axis, value]) => inherited?.[axis] !== value);
1240
+ if (changed.length)
1241
+ overrideAt(layerPathKey([...prefix, layer.node.id])).gridCell = Object.fromEntries(changed);
1242
+ }
1243
+ }
1026
1244
  const modeOverrides = new Map();
1027
1245
  for (const { keys, entry, at, gathered } of targets) {
1028
1246
  const { target } = gathered;
1029
1247
  const isInstance = target.layer.figma.type === "INSTANCE";
1248
+ let readCell = false;
1030
1249
  for (const [name, value] of Object.entries(entry)) {
1250
+ if (gridChildFields.has(name)) {
1251
+ if (readCell)
1252
+ continue;
1253
+ readCell = true;
1254
+ const parentId = target.layer.figma.parentId;
1255
+ const parent = parentId && layersByFigmaId(target.component).get(parentId);
1256
+ const key = parent && layerPathKey([...parseLayerPath(target.key).slice(0, -1), parent.node.id]);
1257
+ if (parent && key && (gridAxes.has(key) || parent.figma.change.stackMode === "GRID")) {
1258
+ const axes = gridAxes.get(key) ?? axesOf(parent.figma.change);
1259
+ gridAxes.set(key, axes);
1260
+ const cell = gridCell(entry, axes.rows, axes.columns, field => context.leftOutField(field), true);
1261
+ if (Object.keys(cell).length)
1262
+ gathered.override.gridCell = { ...gathered.override.gridCell, ...cell };
1263
+ }
1264
+ else
1265
+ for (const field of Object.keys(entry))
1266
+ if (gridChildFields.has(field))
1267
+ context.leftOutField(field);
1268
+ continue;
1269
+ }
1031
1270
  if (BOOKKEEPING_FIELDS.has(name) || name === "exportSettings" || (name === "overriddenSymbolID" && isInstance))
1032
1271
  continue;
1033
- if (HANDOFF_OVERRIDE_FIELDS.has(name)) {
1034
- if (activeHandoffOverride(value))
1035
- context.leftOutField(name);
1272
+ if (HANDOFF_OVERRIDE_FIELDS.has(name))
1036
1273
  continue;
1037
- }
1038
1274
  // Figma's record of the variable bindings this override set, which `variableConsumptionMap` beside it holds too.
1039
1275
  if (name === "parameterConsumptionMap" && entry["variableConsumptionMap"] !== undefined) {
1040
1276
  const extras = parameterMapExtras(value, entry["variableConsumptionMap"]);
@@ -1048,9 +1284,19 @@ export function instanceFields(instance, component, self, context) {
1048
1284
  insideLeftOut.add(entry);
1049
1285
  if (shown === undefined || shown === INSIDE_LEFT_OUT)
1050
1286
  continue;
1051
- const values = assignedPropertyValues(field(entry, name, "list", at), shown.properties, shown.variantDefs, componentIdOf, leftOutValue(shown, target.key), at, context.report, captureLinks(shown, target.key));
1287
+ const values = assignedPropertyValues(assignNestedValues(field(entry, name, "list", at), shown, keys, at), shown.properties, shown.variantDefs, componentIdOf, leftOutValue(shown, target.key), at, context.report, captureLinks(shown, target.key));
1052
1288
  if (Object.keys(values).length > 0)
1053
1289
  gathered.override["propertyValues"] = { ...gathered.override["propertyValues"], ...values };
1290
+ // Each swap-bound layer the values reach shows the value over a swap made below this instance (`shownAt`).
1291
+ for (const [key, layer] of shown.layers) {
1292
+ if (layer.figma.type !== "INSTANCE" || !(field(layer.figma.change, "componentPropRefs", "list", `node ${layer.figma.id}`) ?? [])
1293
+ .some(ref => isObject(ref) && ref["componentPropNodeField"] === "OVERRIDDEN_SYMBOL_ID"))
1294
+ continue;
1295
+ const path = [...keys, key];
1296
+ const bound = resolve(path);
1297
+ if (bound !== undefined && bound !== INSIDE_LEFT_OUT && !("flattenedInto" in bound) && bound.layer === layer)
1298
+ shownAt(path, layer.figma, shown, bound.through);
1299
+ }
1054
1300
  }
1055
1301
  else if (name === "variableModeBySetMap" && (target.through.length === 0 || context.fileOverride)) {
1056
1302
  // The instance's modes on a layer of the component reach the bound font styles under it; Taco keeps no other part.
@@ -1096,6 +1342,9 @@ export function instanceFields(instance, component, self, context) {
1096
1342
  // The native override supports radii directly. fileOverride has recorded the authored values.
1097
1343
  continue;
1098
1344
  }
1345
+ else if (name === "textTruncation" && value !== "DISABLED" && value !== "ENDING") {
1346
+ context.report("property-left-out", `an override's text truncation ${String(value)} is not imported; the layer keeps its component's`);
1347
+ }
1099
1348
  else if (CONVERTED_FIELDS.has(name) || name === "variableConsumptionMap") {
1100
1349
  gathered.fields[name] = value;
1101
1350
  // A style the override names but the message lacks is reported as on a text layer; Figma's detach id is no style.
@@ -1143,7 +1392,9 @@ export function instanceFields(instance, component, self, context) {
1143
1392
  if (own === undefined || Math.abs(stored - own) <= 0.01)
1144
1393
  continue;
1145
1394
  const pathText = keys.join("/");
1146
- if (entries.some((set) => set.keys.join("/") === pathText && LINE_HEIGHT_SETTERS.some((name) => Object.hasOwn(set.entry, name))))
1395
+ // An override that binds the line height or size to a variable draws at the variable's value instead.
1396
+ if (entries.some((set) => set.keys.join("/") === pathText && (LINE_HEIGHT_SETTERS.some((name) => Object.hasOwn(set.entry, name))
1397
+ || bindsLeading(set.entry, at))))
1147
1398
  continue;
1148
1399
  let gathered = pending.get(target.key);
1149
1400
  if (gathered === undefined)
@@ -1151,6 +1402,27 @@ export function instanceFields(instance, component, self, context) {
1151
1402
  gathered.fields[KEPT_LINE_HEIGHT_FIELD] = stored;
1152
1403
  context.report("approximated", "instance keeps Figma's stored line height from before its text style changed");
1153
1404
  }
1405
+ // A text's line limit counts the lines this instance stores for it, not its component's, where it sets them otherwise.
1406
+ const laidOut = new Map();
1407
+ for (const [index, entry] of (field(instance.change, "derivedSymbolData", "list", where) ?? []).entries()) {
1408
+ const derived = isObject(entry) && isObject(entry["derivedTextData"]) ? entry["derivedTextData"]["baselines"] : undefined;
1409
+ if (!Array.isArray(derived))
1410
+ continue;
1411
+ const at = `${where} derivedSymbolData[${String(index)}]`;
1412
+ const path = field(entry, "guidPath", "object", at);
1413
+ const target = path === undefined ? undefined : resolve((field(path, "guids", "list", `${at}.guidPath`) ?? []).map((guid) => guidText(guid, `${at}.guidPath`)));
1414
+ if (target !== undefined && target !== INSIDE_LEFT_OUT && !("flattenedInto" in target))
1415
+ laidOut.set(target.key, derived);
1416
+ }
1417
+ for (const { target, fields } of pending.values()) {
1418
+ if (target.layer.node.type !== "text" || Object.keys(fields).length === 0)
1419
+ continue;
1420
+ const own = laidOut.get(target.key);
1421
+ if (own !== undefined)
1422
+ fields[LAID_OUT_LINES_FIELD] = own;
1423
+ else if (LINE_SETTERS.some((name) => name in fields))
1424
+ fields[LAID_OUT_LINES_FIELD] = [];
1425
+ }
1154
1426
  const heldSizing = new Map();
1155
1427
  for (const { target, fields, override, frame } of pending.values()) {
1156
1428
  if (frame !== undefined) {
@@ -1192,11 +1464,16 @@ export function instanceFields(instance, component, self, context) {
1192
1464
  if (list in plain && !(ref in plain))
1193
1465
  plain[ref] = undefined;
1194
1466
  const shownBy = direct ? { instance, symbol: component.symbol, modes: modeOverrides } : undefined;
1195
- const base = context.convertAlone(figma);
1196
- // A text's line height is converted from its variable, so the bindings the override supplies or replaces go in too.
1197
- const textBindings = ownMap !== undefined && target.layer.node.type === "text"
1198
- && (bindsField({ variableConsumptionMap: ownMap }, "LINE_HEIGHT") || bindsField({ variableConsumptionMap: ownMap }, "FONT_SIZE"));
1199
- const converted = textBindings ? { ...plain, variableConsumptionMap: withBindingEntries(figma.change["variableConsumptionMap"], ownMap) } : plain;
1467
+ const inherited = innerTextFields(target, context);
1468
+ const base = context.convertAlone(figma, inherited);
1469
+ // Convert each text run with the sources left after applying the instance's literals and bindings.
1470
+ const replacesTextStyle = !!context.fileOverride && plain["styleIdForText"] !== undefined;
1471
+ const textBindings = target.layer.node.type === "text" && (ownMap !== undefined || replacesTextStyle || context.fileOverride && Object.keys(plain).some(k => ["fontName", "fontSize", "lineHeight", "letterSpacing"].includes(k)));
1472
+ const unbound = withOverrides(inherited ? { ...figma.change, ...inherited } : figma.change, plain, replacesTextStyle);
1473
+ const mergedMap = ownMap === undefined ? unbound["variableConsumptionMap"] : withBindingEntries(unbound["variableConsumptionMap"], ownMap);
1474
+ const own = target.layer.node.type === "text" && (ownMap !== undefined || plain["textData"] !== undefined)
1475
+ ? { [OWN_TYPOGRAPHY]: { ...(ownMap !== undefined && { variableConsumptionMap: ownMap }), ...(plain["textData"] !== undefined && { textData: true }) } } : {};
1476
+ const converted = textBindings || inherited ? { ...inherited, ...plain, variableConsumptionMap: mergedMap, ...own } : { ...plain, ...own };
1200
1477
  // Only a layer that reads its instance's modes converts once per instance; the rest share one conversion.
1201
1478
  const next = context.convertAlone(figma, converted, readsModes(target.layer) || textBindings ? shownBy : undefined);
1202
1479
  if (base === null || next === null) {
@@ -1210,8 +1487,7 @@ export function instanceFields(instance, component, self, context) {
1210
1487
  context.report("property-left-out", `an override of a layer's stroke cap to ${cap} is left out: Taco has no such cap`);
1211
1488
  }
1212
1489
  // The bindings the override makes: a variable it binds, and `null` for a component binding of a field it sets plainly.
1213
- const unbound = withOverrides(figma.change, plain);
1214
- const nextFigma = { ...figma, change: ownMap === undefined ? unbound : { ...unbound, variableConsumptionMap: withBindingEntries(unbound["variableConsumptionMap"], ownMap) } };
1490
+ const nextFigma = { ...figma, change: ownMap === undefined ? unbound : { ...unbound, variableConsumptionMap: mergedMap } };
1215
1491
  const before = context.bindingsOf(base, figma);
1216
1492
  const after = context.bindingsOf(next, nextFigma, shownBy);
1217
1493
  // Between the bound layers, so that a font style the override binds, or this instance's modes give, reaches the text.
@@ -1246,7 +1522,7 @@ export function instanceFields(instance, component, self, context) {
1246
1522
  return found;
1247
1523
  };
1248
1524
  // The property values this instance gives its component, read here for the slot frames they show or hide.
1249
- const propertyValues = assignedPropertyValues(field(instance.change, "componentPropAssignments", "list", where), component.properties, component.variantDefs, componentIdOf, leftOutValue(component, ""), where, context.report, captureLinks(component, ""));
1525
+ const propertyValues = assignedPropertyValues(assignNestedValues(field(instance.change, "componentPropAssignments", "list", where), component, [], where), component.properties, component.variantDefs, componentIdOf, leftOutValue(component, ""), where, context.report, captureLinks(component, ""));
1250
1526
  for (const { shown, path, id, text, data } of assignedLinks.values()) {
1251
1527
  const table = new Map();
1252
1528
  for (const row of data["styleOverrideTable"]) {
@@ -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.
@@ -98,6 +98,8 @@ export interface ShownBy {
98
98
  * @returns Variable definitions and lookup functions.
99
99
  */
100
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;
101
103
  /**
102
104
  * Sets the variable bindings and variable modes of `layer`, converted from `figma`. A paint's `colorVar` binds
103
105
  * `fillColor` or `strokeColor` when it is the bottom fill or the first stroke and solid (a text layer's colour is its