@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
@@ -1,6 +1,7 @@
1
- import { field, isObject } from "../fields.js";
2
- import { styleBackedList } from "../styles.js";
1
+ import { field, guidText, isObject } from "../fields.js";
2
+ import { isDetachedStyle, styleBackedList } from "../styles.js";
3
3
  import { framedBase, hexColor, readNumbers } from "./shared.js";
4
+ import { sizeLimitsOf } from "./layout.js";
4
5
  const ALIGN = { LEFT: "left", CENTER: "center", RIGHT: "right", JUSTIFIED: "justify" };
5
6
  const VERTICAL_ALIGN = { TOP: "top", CENTER: "middle", BOTTOM: "bottom" };
6
7
  const AUTO_RESIZE = { NONE: "none", HEIGHT: "height", WIDTH_AND_HEIGHT: "width-and-height" };
@@ -106,8 +107,15 @@ export const convertText = (node, walk) => {
106
107
  if (id !== 0 && override === undefined)
107
108
  missingIds += 1;
108
109
  const textStyle = textStyleOfEntry(override);
109
- const fields = styleFields(filled, entryFilled(override), textStyle?.change);
110
- const boundLineHeight = keptLineHeight ?? boundLineHeightOf(change, override, textStyle?.change, where, walk.variableNumber);
110
+ const instance = override?.["styleIdForText"] === undefined ? walk.instanceTypography : undefined;
111
+ let under = textStyle?.change;
112
+ if (under && instance) {
113
+ const local = Object.fromEntries(Object.values(TEXT_VARIABLE_FIELDS).filter(([, name]) => name in instance)
114
+ .map(([, name]) => [name, instance[name]]));
115
+ under = { ...under, ...local };
116
+ }
117
+ const fields = styleFields(filled, entryFilled(override), under);
118
+ const boundLineHeight = keptLineHeight ?? boundLineHeightOf(change, override, textStyle?.change, where, walk.typographyVariable ? undefined : walk.variableNumber);
111
119
  const said = [];
112
120
  const own = runStyle(fields, lookups, (kind, reason) => said.push([kind, reason]), where, boundLineHeight);
113
121
  sizes.set(id, { fontSize: own.fontSize ?? 12, lineHeight: own.lineHeight ?? AUTO_LINE_HEIGHT });
@@ -122,14 +130,61 @@ export const convertText = (node, walk) => {
122
130
  }
123
131
  const bothAuto = textStyle !== undefined && boundLineHeight === undefined && autoLineHeight(fields) && autoLineHeight(textStyle.change);
124
132
  style = textStyle?.shared === undefined ? { overrides: own } : linkedRun(textStyle.shared, own, bothAuto);
125
- if (walk.fontSizeVariable) {
126
- const data = runBinding(change, override, textStyle?.change, where, "FONT_SIZE", "fontSize");
127
- if (data !== undefined) {
128
- const variable = walk.fontSizeVariable(data);
129
- // An omitted style binding is reported on the definition, once for all its users.
130
- if (variable || !textStyle?.shared || data !== bindingIn(textStyle.change, "FONT_SIZE", where))
131
- Object.assign(style, { fileFontSize: variable });
133
+ const rangeLink = override?.["hyperlink"];
134
+ const hyperlink = hyperlinkOf(rangeLink === undefined ? change["hyperlink"] : rangeLink, report);
135
+ if (hyperlink)
136
+ style.hyperlink = hyperlink;
137
+ const paints = fields["fillPaints"];
138
+ // A range with its own paints replaces the layer's style, even if the colours match.
139
+ const source = override && ("styleIdForFill" in override || "fillPaints" in override) ? override : change;
140
+ const reference = source["styleIdForFill"];
141
+ if (reference && walk.textFillStyle && !isDetachedStyle(reference)) {
142
+ const guid = walk.textFillStyle(reference);
143
+ if (guid)
144
+ Object.assign(style, walk.plainTextPaint?.(override) ? { filePlainFillStyle: guid } : { fileFillStyle: guid });
145
+ }
146
+ const paint = Array.isArray(paints) && lookups.colors.get(paints)?.paint;
147
+ if (paint && paint["colorVar"] !== undefined && walk.textColorVariable) {
148
+ const variable = walk.textColorVariable(paint["colorVar"]);
149
+ Object.assign(style, walk.plainTextPaint?.(override) ? { filePlainTextColor: variable } : { fileTextColor: variable });
150
+ const opacity = field(paint, "opacity", "number", where) ?? 1;
151
+ if (variable && opacity !== 1 && !walk.copiedPaintAlpha?.(paint, opacity))
152
+ Object.assign(style, { filePaintOpacity: opacity });
153
+ }
154
+ if (walk.typographyVariable) {
155
+ const bindings = {};
156
+ // The bindings an instance override makes itself, even to the main's variable: Figma keeps them as overrides.
157
+ const authored = walk.instanceTypography?.[OWN_TYPOGRAPHY];
158
+ const ownBindings = {};
159
+ for (const [field, [key, name]] of Object.entries(TEXT_VARIABLE_FIELDS)) {
160
+ if (key === "lineHeight" && keptLineHeight !== undefined)
161
+ continue;
162
+ const data = runBinding(change, override, textStyle?.change, where, field, name, instance, true);
163
+ if (data === undefined)
164
+ continue;
165
+ const variable = walk.typographyVariable(field, data);
166
+ if (variable && key === "lineHeight") {
167
+ const pixels = walk.variableNumber?.(data);
168
+ const fontSize = own.fontSize ?? 12;
169
+ if (pixels !== undefined) {
170
+ sizes.set(id, { fontSize, lineHeight: pixels / fontSize });
171
+ // The stored frame was measured with this leading in the source layer's mode.
172
+ Object.assign(style, { fileLineHeightPx: pixels });
173
+ }
174
+ }
175
+ if (variable && key === "letterSpacing" && isObject(fields["letterSpacing"]) && fields["letterSpacing"]["units"] === "PERCENT")
176
+ Object.assign(style, { filePercentTracking: true });
177
+ // A failed style alias is reported once on its definition.
178
+ if (variable || !textStyle?.shared || data !== bindingIn(textStyle.change, field, where))
179
+ bindings[key] = variable;
180
+ if (variable && isObject(authored) && (bindingIn(authored, field, where) !== undefined
181
+ || authored["textData"] === true && override !== undefined && bindingIn(override, field, where) !== undefined))
182
+ ownBindings[key] = variable;
132
183
  }
184
+ if (Object.keys(bindings).length)
185
+ Object.assign(style, { fileTypography: bindings });
186
+ if (Object.keys(ownBindings).length)
187
+ Object.assign(style, { fileOwnTypography: ownBindings });
133
188
  }
134
189
  // A run that keeps its style's auto line height has the style's, which may come from another layer's font metadata.
135
190
  const keepsStyleLineHeight = bothAuto && textStyle.shared !== undefined && style.overrides?.lineHeight === undefined;
@@ -202,7 +257,12 @@ export const convertText = (node, walk) => {
202
257
  if (missingIds > 0) {
203
258
  report("approximated", `${String(missingIds)} style id${missingIds === 1 ? " is" : "s are"} not in the style override table; their characters use the node's style`);
204
259
  }
205
- reportLeftOut(change, textData, table, report, where, nodeTextStyle?.change);
260
+ reportLeftOut(change, report, where);
261
+ const firstLineHeight = (paragraph) => {
262
+ const id = paragraph?.runs[0] === undefined ? undefined : runIds.get(paragraph.runs[0]);
263
+ const size = sizes.get(id ?? 0) ?? { fontSize: 12, lineHeight: AUTO_LINE_HEIGHT };
264
+ return size.fontSize * size.lineHeight;
265
+ };
206
266
  const autoResize = AUTO_RESIZE[field(change, "textAutoResize", "string", where) ?? "NONE"];
207
267
  if (autoResize === undefined)
208
268
  report("approximated", `textAutoResize ${String(change["textAutoResize"])} is imported as a fixed size`);
@@ -219,6 +279,7 @@ export const convertText = (node, walk) => {
219
279
  autoResize: autoResize ?? "none",
220
280
  wrap: autoResize === "width-and-height" ? "none" : "word",
221
281
  ...(spacing > 0 ? { paragraphSpacing: spacing } : {}),
282
+ ...truncationOf(change, base.frame.height, autoResize ?? "none", firstLineHeight(paragraphs[0]), where),
222
283
  };
223
284
  // Taco draws every run at the layer's bound font size where it keeps that binding (`bindLayerVariables`), so a line
224
285
  // height from a variable is a multiple of that size instead of the stored one, and the drawn line height is the variable's.
@@ -241,8 +302,54 @@ export const convertText = (node, walk) => {
241
302
  };
242
303
  /** Most distinct report reasons one text node adds; the rest are counted in one closing line. */
243
304
  const MAX_REPORTS = 20;
244
- /** The fields `runStyle` reads. */
305
+ /** Native palette key and authored Figma field for each typography binding. */
306
+ export const TEXT_VARIABLE_FIELDS = {
307
+ FONT_SIZE: ["size", "fontSize"], FONT_FAMILY: ["family", "fontName"], FONT_STYLE: ["style", "fontName"],
308
+ FONT_WEIGHT: ["weight", "fontName"], LINE_HEIGHT: ["lineHeight", "lineHeight"], LETTER_SPACING: ["letterSpacing", "letterSpacing"],
309
+ };
310
+ /** Figma's text cases, as Taco's. */
311
+ const TEXT_CASES = {
312
+ UPPER: "upper", LOWER: "lower", TITLE: "title", SMALL_CAPS: "smallCaps", SMALL_CAPS_FORCED: "smallCapsForced",
313
+ };
314
+ /** The fields read by runStyle. */
245
315
  const STYLE_FIELDS = ["fontName", "fontSize", "lineHeight", "letterSpacing", "textDecoration", "fontVariations", "fillPaints"];
316
+ const FEATURE_SWITCHES = {
317
+ fontVariantCommonLigatures: ["liga", "clig"],
318
+ fontVariantContextualLigatures: ["calt"],
319
+ fontVariantDiscretionaryLigatures: ["dlig"],
320
+ fontVariantHistoricalLigatures: ["hlig"],
321
+ fontVariantOrdinal: ["ordn"],
322
+ fontVariantSlashedZero: ["zero"],
323
+ };
324
+ const FEATURE_CHOICES = {
325
+ fontVariantNumericFigure: { LINING: ["lnum"], OLDSTYLE: ["onum"] },
326
+ fontVariantNumericSpacing: { PROPORTIONAL: ["pnum"], TABULAR: ["tnum"] },
327
+ fontVariantNumericFraction: { DIAGONAL: ["frac"], STACKED: ["afrc"] },
328
+ fontVariantCaps: { SMALL: ["smcp"], ALL_SMALL: ["smcp", "c2sc"], PETITE: ["pcap"], ALL_PETITE: ["pcap", "c2pc"], UNICASE: ["unic"], TITLING: ["titl"] },
329
+ fontVariantPosition: { SUB: ["subs"], SUPER: ["sups"] },
330
+ };
331
+ const FEATURE_VARIANTS = [...Object.keys(FEATURE_SWITCHES), ...Object.keys(FEATURE_CHOICES)];
332
+ /** Figma stores the deviations from its feature defaults in separate on and off lists. */
333
+ export const OPEN_TYPE_TOGGLES = ["toggledOnOTFeatures", "toggledOffOTFeatures"];
334
+ /** Figma fields that specify OpenType features on a layer, range or instance override. */
335
+ export const OPEN_TYPE_FIELDS = [...FEATURE_VARIANTS, ...OPEN_TYPE_TOGGLES];
336
+ /** Keeps omitted toggle lists inherited, except for tags explicitly toggled the other way. */
337
+ export function inheritOpenTypeToggles(base, own) {
338
+ const merged = {};
339
+ for (const [index, name] of OPEN_TYPE_TOGGLES.entries()) {
340
+ const value = own[name] ?? base?.[name];
341
+ if (value === undefined)
342
+ continue;
343
+ const opposite = own[OPEN_TYPE_TOGGLES[1 - index]];
344
+ if (own[name] === undefined && Array.isArray(value) && Array.isArray(opposite) && opposite.length > 0) {
345
+ const tags = new Set(opposite);
346
+ merged[name] = value.filter(tag => !tags.has(tag));
347
+ }
348
+ else
349
+ merged[name] = value;
350
+ }
351
+ return merged;
352
+ }
246
353
  /**
247
354
  * The fields a run reads, in this order: an override entry's own, then for
248
355
  * typography the Figma text style they name (`under`), then the node's. As in
@@ -264,28 +371,47 @@ function styleFields(change, override, under) {
264
371
  if (value !== undefined)
265
372
  style[name] = value;
266
373
  }
267
- return style;
374
+ // The layer's case beats its text style's, as for the feature switches.
375
+ for (const name of [...FEATURE_VARIANTS, "textCase"]) {
376
+ const value = override?.[name] ?? change[name] ?? under?.[name];
377
+ if (value !== undefined)
378
+ style[name] = value;
379
+ }
380
+ // A layer can set its own features alongside a shared typography style. An explicitly empty list clears that side.
381
+ const toggles = inheritOpenTypeToggles(under, change);
382
+ return { ...style, ...(override ? inheritOpenTypeToggles(toggles, override) : toggles) };
268
383
  }
269
384
  /**
270
385
  * The variable data a run's `variableField` (`LINE_HEIGHT` or `FONT_SIZE`) is bound to, read where `styleFields` reads
271
386
  * the field it binds (`name`): an override entry's own binding, or none when the entry sets its own value; else the text
272
387
  * style's (`under`), else the node's.
273
388
  */
274
- function runBinding(change, override, under, where, variableField, name) {
389
+ /** Override field naming the typography sources an instance override authors itself: its own variable map, and
390
+ * `textData: true` when its range table is its own. Set by `instances.ts`, read when the text converts. */
391
+ export const OWN_TYPOGRAPHY = "ownTypography";
392
+ function runBinding(change, override, under, where, variableField, name, instance, native = false) {
275
393
  const bound = (fields) => bindingIn(fields, variableField, where);
276
394
  if (override !== undefined) {
277
395
  const own = bound(override);
278
396
  if (own !== undefined || Object.hasOwn(override, name))
279
397
  return own;
280
398
  }
281
- return under !== undefined && under[name] !== undefined ? bound(under) : bound(change);
399
+ // Figma detaches a text style when a layer field is bound, so a layer binding stored beside a linked style is stale.
400
+ // Only an instance override that sets or binds the field itself replaces the style's source.
401
+ const claimed = instance !== undefined && (instance[name] !== undefined || bound(instance) !== undefined);
402
+ if (native && override?.["styleIdForText"] === undefined && (claimed || under === undefined)) {
403
+ const local = bound(change);
404
+ if (local !== undefined || claimed)
405
+ return local;
406
+ }
407
+ return under && (under[name] !== undefined || bound(under) !== undefined) ? bound(under) : bound(change);
282
408
  }
283
409
  /** The variable data Figma fields bind `variableField` to, or `undefined`. */
284
410
  function bindingIn(fields, variableField, where) {
285
411
  const map = field(fields, "variableConsumptionMap", "object", where);
286
412
  const entry = (map && field(map, "entries", "list", `${where} variableConsumptionMap`) || [])
287
413
  .find((item) => isObject(item) && item["variableField"] === variableField);
288
- return isObject(entry) ? entry["variableData"] : undefined;
414
+ return isObject(entry) ? entry["variableData"] ?? null : undefined;
289
415
  }
290
416
  /** A run's line height in pixels from the variable it is bound to (`runBinding`), or `undefined` without one. */
291
417
  function boundLineHeightOf(change, override, under, where, variableNumber) {
@@ -294,8 +420,22 @@ function boundLineHeightOf(change, override, under, where, variableNumber) {
294
420
  const lineData = runBinding(change, override, under, where, "LINE_HEIGHT", "lineHeight");
295
421
  return lineData === undefined ? undefined : variableNumber(lineData);
296
422
  }
423
+ /** An empty range hyperlink explicitly clears the layer's hyperlink. */
424
+ export function hyperlinkOf(value, report) {
425
+ if (value === undefined || (isObject(value) && Object.keys(value).length === 0))
426
+ return undefined;
427
+ if (isObject(value)) {
428
+ if (typeof value["url"] === "string" && value["url"] !== "")
429
+ return { kind: "url", url: value["url"] };
430
+ const guid = value["guid"];
431
+ if (isObject(guid) && Number.isInteger(guid["sessionID"]) && Number.isInteger(guid["localID"]))
432
+ return { kind: "target", guid: guidText(guid, "hyperlink") };
433
+ }
434
+ report("property-left-out", "invalid text hyperlink");
435
+ return undefined;
436
+ }
297
437
  /** The fields a style has that turn off when a run leaves them out, with the value that turns each off. */
298
- const STYLE_OFF = [["italic", false], ["underline", false], ["strikethrough", false], ["letterSpacing", 0], ["fontVariations", {}]];
438
+ const STYLE_OFF = [["italic", false], ["underline", false], ["strikethrough", false], ["letterSpacing", 0], ["fontVariations", {}], ["openTypeFeatures", {}], ["textCase", "original"]];
299
439
  /**
300
440
  * A run linked to its shared style, with the fields of `own` that differ from
301
441
  * the style's as its overrides. With `bothAuto` (the run's line height and the
@@ -412,6 +552,16 @@ function runStyle(style, lookups, report, where, boundLineHeight) {
412
552
  out.underline = true;
413
553
  if (decoration === "STRIKETHROUGH")
414
554
  out.strikethrough = true;
555
+ const features = openTypeFeatures(style, report, where);
556
+ if (features !== undefined)
557
+ out.openTypeFeatures = features;
558
+ const textCase = field(style, "textCase", "string", where);
559
+ if (textCase !== undefined && textCase !== "ORIGINAL") {
560
+ if (Object.hasOwn(TEXT_CASES, textCase))
561
+ out.textCase = TEXT_CASES[textCase];
562
+ else
563
+ report("property-left-out", `text case ${textCase} is not imported; the characters are kept as typed`);
564
+ }
415
565
  const axes = field(style, "fontVariations", "list", where) ?? [];
416
566
  let variations = lookups.variations.get(axes);
417
567
  if (variations === undefined) {
@@ -433,12 +583,41 @@ function runStyle(style, lookups, report, where, boundLineHeight) {
433
583
  color = textColor(paints, report, where);
434
584
  lookups.colors.set(paints, color);
435
585
  }
436
- out.color = color;
586
+ out.color = color.value;
437
587
  return out;
438
588
  }
589
+ /** Converts Figma's typography switches and then its explicit feature toggles, which take precedence. */
590
+ function openTypeFeatures(style, report, where) {
591
+ const features = new Map();
592
+ for (const [name, tags] of Object.entries(FEATURE_SWITCHES)) {
593
+ const value = field(style, name, "boolean", where);
594
+ if (value !== undefined)
595
+ for (const tag of tags)
596
+ features.set(tag, value);
597
+ }
598
+ for (const [name, choices] of Object.entries(FEATURE_CHOICES)) {
599
+ const choice = field(style, name, "string", where);
600
+ if (choice !== undefined && Object.hasOwn(choices, choice))
601
+ for (const tag of choices[choice])
602
+ features.set(tag, true);
603
+ }
604
+ for (const name of OPEN_TYPE_TOGGLES) {
605
+ for (const tag of field(style, name, "list", where) ?? []) {
606
+ if (typeof tag === "string" && tag.length === 4 && /^[ -~]+$/.test(tag))
607
+ features.set(tag.toLowerCase(), name === "toggledOnOTFeatures");
608
+ else
609
+ report("property-left-out", "an invalid OpenType feature tag is left out");
610
+ }
611
+ }
612
+ if (features.size > 256)
613
+ report("property-left-out", "OpenType feature settings beyond the first 256 tags are left out");
614
+ if (features.size > 0)
615
+ return Object.fromEntries([...features.keys()].sort().slice(0, 256).map(tag => [tag, features.get(tag)]));
616
+ }
439
617
  /** The top visible solid fill as a colour with the paint's opacity in its alpha; other fills are reported. */
440
- function textColor(paints, report, where) {
618
+ export function textColor(paints, report = () => undefined, where = "text fill") {
441
619
  let color;
620
+ let shown;
442
621
  for (let i = paints.length - 1; i >= 0; i--) {
443
622
  const paint = paints[i];
444
623
  if (!isObject(paint) || field(paint, "visible", "boolean", where) === false)
@@ -449,13 +628,14 @@ function textColor(paints, report, where) {
449
628
  report("property-left-out", `a ${type} text fill is left out: only the top solid fill is imported`);
450
629
  continue;
451
630
  }
631
+ shown = paint;
452
632
  color = hexColor({ ...channels, a: channels.a * (field(paint, "opacity", "number", where) ?? 1) });
453
633
  const blend = field(paint, "blendMode", "string", where);
454
634
  if (blend !== undefined && blend !== "NORMAL" && blend !== "PASS_THROUGH")
455
635
  report("property-left-out", `the text fill's blend mode ${blend} is left out; its colour is kept`);
456
636
  }
457
637
  // No visible fill draws no glyphs; the text keeps its layout.
458
- return color ?? "#00000000";
638
+ return { value: color ?? "#00000000", paint: shown };
459
639
  }
460
640
  /** A spacing in pixels from the Figma text style (`style`), else the node, else 0; negative values are 0. */
461
641
  /**
@@ -515,20 +695,56 @@ function bulletAdvancesOf(change, characters) {
515
695
  }
516
696
  return advances;
517
697
  }
698
+ /**
699
+ * A field the importer adds to a text layer's Figma fields, never one Figma writes: the lines Figma laid this layer out
700
+ * in for an instance (its `derivedSymbolData` entry's `derivedTextData.baselines`), which replace the component's stored
701
+ * lines when the line limit a box holds is counted; an empty list where the instance changes how its lines are set but
702
+ * stores none, so the count follows the instance's own first line.
703
+ */
704
+ export const LAID_OUT_LINES_FIELD = "tacoLaidOutLines";
705
+ /**
706
+ * Figma's ending truncation as `truncate` and `maxLines`. Figma reads `maxLines` only while truncation is on. A
707
+ * fixed-size box ends at its last whole line, and so does auto-height text at its maximum height, so the line count is
708
+ * the lines that fit that height (at least one line), or `maxLines` where that is fewer.
709
+ */
710
+ function truncationOf(change, height, autoResize, firstLineHeight, where) {
711
+ if (field(change, "textTruncation", "string", where) !== "ENDING")
712
+ return {};
713
+ const stored = Math.floor(field(change, "maxLines", "number", where) ?? 0);
714
+ const limit = autoResize === "none" ? height : autoResize === "height" ? sizeLimitsOf(change).maxHeight : undefined;
715
+ const fitting = limit === undefined ? undefined : linesWithin(change, limit, firstLineHeight);
716
+ const maxLines = stored > 0 ? Math.min(stored, fitting ?? stored) : fitting;
717
+ return { ...(maxLines !== undefined ? { maxLines } : {}), truncate: "ellipsis" };
718
+ }
719
+ /**
720
+ * How many lines fit `height`, at least one: Figma's laid-out lines (each at its own top and height, so uneven line
721
+ * heights and paragraph spacing count) that end within it, then lines of the last one's height in the space below
722
+ * them. Without laid-out lines, every line is `firstLineHeight` tall.
723
+ */
724
+ function linesWithin(change, height, firstLineHeight) {
725
+ const own = change[LAID_OUT_LINES_FIELD];
726
+ const derived = isObject(change["derivedTextData"]) ? change["derivedTextData"]["baselines"] : undefined;
727
+ const lines = Array.isArray(own) ? own : Array.isArray(derived) ? derived : [];
728
+ let count = 0, bottom = 0, last = firstLineHeight;
729
+ for (const line of lines) {
730
+ const lineHeight = isObject(line) ? line["lineHeight"] : undefined;
731
+ if (typeof lineHeight !== "number" || !(lineHeight > 0))
732
+ break;
733
+ const top = isObject(line) && typeof line["lineY"] === "number" ? line["lineY"] : bottom;
734
+ if (top + lineHeight > height + 0.01)
735
+ return Math.max(1, count);
736
+ count += 1;
737
+ bottom = top + lineHeight;
738
+ last = lineHeight;
739
+ }
740
+ const more = (height - bottom + 0.01) / last;
741
+ return Number.isFinite(more) && last > 0 ? Math.max(1, count + Math.max(0, Math.floor(more))) : undefined;
742
+ }
518
743
  /** Reports the text fields Taco does not import yet, one entry for each field. */
519
- function reportLeftOut(change, textData, table, report, where, textStyle) {
520
- // The text style's case applies where the node has none of its own.
521
- const styles = [change, ...table.values(), ...(textStyle !== undefined && change["textCase"] === undefined ? [textStyle] : [])];
522
- const textCase = styles.map((style) => field(style, "textCase", "string", where)).find((value) => value !== undefined && value !== "ORIGINAL");
523
- if (textCase !== undefined)
524
- report("property-left-out", `text case ${textCase} is not imported; the characters are kept as typed`);
744
+ function reportLeftOut(change, report, where) {
525
745
  const truncation = field(change, "textTruncation", "string", where);
526
- if (truncation !== undefined && truncation !== "DISABLED")
746
+ if (truncation !== undefined && truncation !== "DISABLED" && truncation !== "ENDING")
527
747
  report("property-left-out", `text truncation ${truncation} is not imported`);
528
- if ((field(change, "maxLines", "number", where) ?? 0) > 0)
529
- report("property-left-out", "the maximum line count is not imported");
530
- if (styles.some((style) => isObject(style["hyperlink"]) && Object.keys(style["hyperlink"]).length > 0))
531
- report("property-left-out", "links are not imported");
532
748
  }
533
749
  const LIST_KIND = { ORDERED_LIST: "ordered", UNORDERED_LIST: "unordered" };
534
750
  /**
@@ -1,8 +1,9 @@
1
- import { type DashCap, type LineNode, type PathNode, type Stroke, type TransformMatrix } from "../../../model/index.ts";
1
+ import { type LineNode, type PathNode, type Stroke, type TransformMatrix } from "../../../model/index.ts";
2
+ import type { StrokeCap } from "../../../model/types.ts";
2
3
  import { type FigmaObject } from "../fields.ts";
3
4
  import type { FigmaTreeNode } from "../tree.ts";
4
5
  import type { FigmaNodeConverter, NodeWalk } from "../walk.ts";
5
- import type { Box } from "./gradient.ts";
6
+ import type { PaintBounds } from "./gradient.ts";
6
7
  /**
7
8
  * The most paths in one node's `fillGeometry` and the most drawing commands
8
9
  * in all of them together. A node over either is left out and reported.
@@ -27,12 +28,6 @@ export declare const VECTOR_GEOMETRY_LIMITS: {
27
28
  */
28
29
  export declare const VECTOR_GEOMETRY_PROBLEMS: readonly ["no-geometry", "not-a-path", "unknown-winding-rule", "blob-missing", "blob-too-short", "unknown-command", "not-finite", "draw-before-move", "too-many-paths", "too-many-commands", "import-command-limit"];
29
30
  export type VectorGeometryProblem = (typeof VECTOR_GEOMETRY_PROBLEMS)[number];
30
- /**
31
- * The most paints and gradient stops `placedFills` may copy into a VECTOR's
32
- * regions in total. Over it the node's gradients stay on one box, so a short
33
- * paint list cannot be copied into thousands of regions.
34
- */
35
- export declare const REGION_FILL_COPY_LIMIT = 100000;
36
31
  /**
37
32
  * A path node's Figma `transform` as its Taco transform (Taco's [a, b, c, d,
38
33
  * e, f] is Figma's [m00, m10, m01, m11, m02, m12]), or `null` after reporting
@@ -44,9 +39,9 @@ export declare function pathTransform(node: FigmaTreeNode, walk: NodeWalk): Tran
44
39
  * and dashes from Figma's `strokeCap`; a cap Taco has no match for is
45
40
  * reported and imported flat.
46
41
  */
47
- export declare function pathStrokes(node: FigmaTreeNode, walk: NodeWalk, box: Box | undefined): {
42
+ export declare function pathStrokes(node: FigmaTreeNode, walk: NodeWalk, box: PaintBounds | undefined): {
48
43
  strokes: Stroke[];
49
- cap: DashCap;
44
+ cap: StrokeCap;
50
45
  };
51
46
  /**
52
47
  * A Figma VECTOR as a Taco path. The shape is the node's editable vector
@@ -62,10 +57,36 @@ export declare function pathStrokes(node: FigmaTreeNode, walk: NodeWalk, box: Bo
62
57
  */
63
58
  export declare const convertVector: FigmaNodeConverter;
64
59
  /**
65
- * A Figma BOOLEAN_OPERATION as a Taco path drawn from its `fillGeometry`, the
66
- * outline Figma stores for the result; Taco has no live boolean, so the
67
- * operands are not imported (the walk reports the flattening once). Without
68
- * a `fillGeometry` outline the node is left out, as before.
60
+ * Moondraft patch 0010: how a Figma BOOLEAN_OPERATION imports. A live boolean
61
+ * group (`operation`, Moondraft's name for it) when Moondraft's boolean group
62
+ * can stand for it: an operation it has, a transform that only moves and
63
+ * turns, a node that does not fill its auto layout parent (a group cannot),
64
+ * and shown operands that are all shapes, nested boolean operations or groups
65
+ * of those (a boolean group skips any other layer, such as text, and a mask).
66
+ * Otherwise `why` says what keeps it flattened to its outline.
67
+ */
68
+ export declare function liveBooleanOf(node: FigmaTreeNode, inFlow?: boolean): {
69
+ readonly operation: string;
70
+ } | {
71
+ readonly why: string;
72
+ };
73
+ /** Moondraft patch 0010: why a boolean operation was flattened, for the walk's report line, if it says. */
74
+ export declare function whyFlattened(node: FigmaTreeNode, inFlow?: boolean): string | undefined;
75
+ /**
76
+ * A Figma BOOLEAN_OPERATION. Moondraft patch 0010: one `liveBooleanOf` passes
77
+ * is a frame holding its operands, which the walk imports as its layers; it
78
+ * carries its operation (`metadata.figma.boolean`) for Moondraft's adapter,
79
+ * which makes it a boolean group. Its frame is the operation's own, and it
80
+ * takes the constraints its operands share, as the flattened path does. Its
81
+ * look (fills, strokes, effects) is the one the outline would have. The
82
+ * outline Figma stores for the result (`fillGeometry`) is carried too, as the
83
+ * group's first result, so it draws as the flattened path did until an edit
84
+ * recuts it; without one (Figma often stores none for a nested operation) the
85
+ * renderer cuts the result from the operands, and one in an auto layout flow
86
+ * whose operands do not fill its box carries `fixedBox`, for a frame of its
87
+ * own size around the group. Any other is a Taco path drawn
88
+ * from its `fillGeometry`, its operands not imported (the walk reports the
89
+ * flattening once, with the reason), or is left out without one, as before.
69
90
  */
70
91
  export declare const convertBooleanOperation: FigmaNodeConverter;
71
92
  /**
@@ -79,6 +100,6 @@ export declare const convertBooleanOperation: FigmaNodeConverter;
79
100
  * VECTORs and LINEs. A line's stroke is drawn centred, as Figma draws the
80
101
  * stroke of an open path.
81
102
  */
82
- export declare function lineWhereItFills(path: PathNode, change: FigmaObject): PathNode | LineNode;
103
+ export declare function lineWhereItFills(path: PathNode, change: FigmaObject, endpointCaps?: Readonly<Record<string, StrokeCap>>): PathNode | LineNode;
83
104
  /** Moondraft patch (../carry.ts): a STAR or REGULAR_POLYGON as its `fillGeometry` path (as a VECTOR), its parameters carried. */
84
105
  export declare const convertStarOrPolygon: FigmaNodeConverter;