@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
@@ -398,6 +398,28 @@ export function readFigmaVariables(nodes, newId, report, keepAliases = false) {
398
398
  },
399
399
  };
400
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"];
401
423
  /** The Taco property a Figma `variableField` binds, or why Taco has no binding for it. */
402
424
  const FIELD_PROPERTIES = {
403
425
  CORNER_RADIUS: "cornerRadius",
@@ -532,6 +554,11 @@ export function bindLayerVariables(layer, figma, variables, report, overridden =
532
554
  const map = field(change, "variableConsumptionMap", "object", where);
533
555
  const entries = (map && field(map, "entries", "list", `${where} variableConsumptionMap`) || []).filter(isObject);
534
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);
535
562
  // Taco has no binding for a font style name, so a text layer takes the bound style as a fixed weight, below.
536
563
  const styleBound = layer.type === "text" && variables !== undefined && byField.has("FONT_STYLE");
537
564
  const styleData = styleBound ? byField.get("FONT_STYLE") : undefined;
@@ -576,7 +603,7 @@ export function bindLayerVariables(layer, figma, variables, report, overridden =
576
603
  .some((paint) => isObject(paint) && paint["colorVar"] !== undefined && JSON.stringify(paint["colorVar"]) !== layerColor)
577
604
  || (field(field(entry, "variableConsumptionMap", "object", where) ?? {}, "entries", "list", where) ?? [])
578
605
  .some((item) => !isObject(item) || JSON.stringify(item["variableData"]) !== layerFields.get(item["variableField"]))).length;
579
- if (styleBound && layer.type === "text") {
606
+ if (styleBound && layer.type === "text" && !variables?.sources.size) {
580
607
  const resolved = variables.fontStyleOf(styleData, figma, `${where} FONT_STYLE`, shownBy);
581
608
  const weight = "style" in resolved ? fontStyleWeight(resolved.style) : undefined;
582
609
  if ("missing" in resolved)
@@ -192,6 +192,8 @@ function remainder(document, member, root) {
192
192
  rest["vectorStrokeCaps"] = figma.vectorStrokeCaps;
193
193
  if (figma?.firstOnTop === true)
194
194
  rest["firstOnTop"] = true;
195
+ if (figma?.gridCell !== undefined)
196
+ rest["gridCell"] = figma.gridCell;
195
197
  if (figma?.fillSizing !== undefined)
196
198
  rest["fillSizing"] = figma.fillSizing;
197
199
  if (figma?.groupConstraints !== undefined)
@@ -32,6 +32,10 @@ export interface NodeWalk {
32
32
  image(hashHex: string, size?: {
33
33
  width: number;
34
34
  height: number;
35
+ }, media?: {
36
+ video?: boolean;
37
+ bytes?: Uint8Array;
38
+ poster?: FigmaImportedImage;
35
39
  }): FigmaImportedImage | string | null;
36
40
  /** Records the source indexes of paints accepted by the native file adapter.
37
41
  * @param source - Original Figma paint list.
@@ -81,15 +85,18 @@ export interface NodeWalk {
81
85
  * @returns Whether the colour already supplies this opacity.
82
86
  */
83
87
  copiedPaintAlpha?(paint: FigmaObject, opacity: number): boolean;
84
- /** 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.
85
90
  * @param data - Figma variable binding.
86
91
  * @returns The local variable ID, or null for an unresolved binding.
87
92
  */
88
- fontSizeVariable?(data: unknown): string | null;
93
+ typographyVariable?(field: string, data: unknown): string | null;
89
94
  /** Local variable ID for the solid paint drawn by a saved text run, or null to keep its literal. */
90
95
  textColorVariable?(data: unknown): string | null;
91
96
  /** Source GUID of a named fill style on a saved text run. */
92
97
  textFillStyle?(reference: unknown): string | undefined;
98
+ /** Local instance fields that can override typography from a shared text style. */
99
+ instanceTypography?: FigmaObject;
93
100
  /** Whether a run draws paint authored in this file instance override. */
94
101
  plainTextPaint?(range: FigmaObject | undefined): boolean;
95
102
  /** The font size Taco draws text `layer`, converted from this node, at where it keeps the node's font size binding (`keptFontSize`). */
@@ -2,8 +2,9 @@ import { formatExpressionName, buildParentMap, componentNestingGraph, entryOf, f
2
2
  import { field, guidText, isObject } from "./fields.js";
3
3
  import { isDetachedStyle } from "./styles.js";
4
4
  import { convertEllipse } from "./converters/ellipse.js";
5
- import { sniffImageMimeType } from "./converters/image.js";
5
+ import { sniffImageMimeType, sniffVideoMimeType } from "./converters/image.js";
6
6
  import { convertFrame, isFigmaGroup } from "./converters/frame.js";
7
+ import { gridAxis, gridCell } from "./converters/grid.js";
7
8
  import { stackChildFields } from "./converters/layout.js";
8
9
  import { convertGroup } from "./converters/group.js";
9
10
  import { convertLine } from "./converters/line.js";
@@ -20,7 +21,7 @@ import { blobReader } from "./blobs.js";
20
21
  import { carry, carryMarks, clearConstraints, withImageCrop } from "./carry.js";
21
22
  import { nodeEffects } from "./converters/effects.js";
22
23
  import { frameGeometry, visualStyle } from "./converters/shared.js";
23
- import { bindLayerVariables, figmaVariableModes, foldsVariableAlpha, keptFontSize, readFigmaVariables } from "./variables.js";
24
+ import { bindLayerVariables, figmaVariableModes, foldsVariableAlpha, keptFontSize, typographyVariable, readFigmaVariables } from "./variables.js";
24
25
  import { buildFigmaTree, chooseRoots, rootSourceOf, withAncestorTransforms } from "./tree.js";
25
26
  import { DEFAULT_FIGMA_IMPORT_LIMITS, FigmaImportError } from "./types.js";
26
27
  /**
@@ -196,22 +197,28 @@ export function walkMessage(message, options, native, distinctSources) {
196
197
  const blob = blobReader(message);
197
198
  const assets = {};
198
199
  const missingImages = new Set();
199
- const image = (hash, size) => {
200
- const id = `figma-image-${hash}`;
201
- if (Object.hasOwn(assets, id))
202
- return assets[id];
203
- if (missingImages.has(hash))
200
+ const image = (hash, size, media) => {
201
+ const id = `figma-${media?.video ? "video" : "image"}-${hash}`;
202
+ const cached = assets[id];
203
+ if (cached && !(cached.placeholder && media?.bytes)) {
204
+ if (media?.poster && !cached.poster)
205
+ return assets[id] = { ...cached, poster: media.poster };
206
+ return cached;
207
+ }
208
+ if (missingImages.has(id) && !media?.bytes)
204
209
  return null;
205
- missingImages.add(hash);
206
- const supplied = options.images?.(hash);
210
+ missingImages.add(id);
211
+ const supplied = media?.bytes ? { bytes: media.bytes } : options.images?.(hash);
207
212
  if (supplied === undefined)
208
213
  return `image ${hash.slice(0, 8)} was not supplied`;
209
- const mimeType = supplied.mimeType ?? sniffImageMimeType(supplied.bytes);
214
+ const mimeType = supplied.mimeType ?? (media?.video ? sniffVideoMimeType(supplied.bytes) : sniffImageMimeType(supplied.bytes));
215
+ if (media?.video && !mimeType?.startsWith("video/"))
216
+ return "video bytes were not supplied";
210
217
  if (mimeType === undefined)
211
218
  return `image ${hash.slice(0, 8)} is not a PNG, JPEG, GIF or WebP file`;
212
219
  const width = supplied.width ?? size?.width;
213
220
  const height = supplied.height ?? size?.height;
214
- return assets[id] = { id, hash, mimeType, bytes: supplied.bytes, ...(width !== undefined ? { width } : {}), ...(height !== undefined ? { height } : {}) };
221
+ return assets[id] = { id, hash, mimeType, bytes: supplied.bytes, ...(supplied.placeholder && { placeholder: true }), ...(media?.poster && { poster: media.poster }), ...(width !== undefined ? { width } : {}), ...(height !== undefined ? { height } : {}) };
215
222
  };
216
223
  const paintIndices = new Map();
217
224
  const effectFields = new Map();
@@ -221,10 +228,10 @@ export function walkMessage(message, options, native, distinctSources) {
221
228
  } : {};
222
229
  const vectorCommands = { left: limits.vectorCommands, limit: limits.vectorCommands };
223
230
  // `withLayersInside`: the entry leaves out the layers inside the node too.
224
- const add = (link, kind, reason, withLayersInside = false) => {
231
+ const add = (link, kind, reason, withLayersInside = false, count = 1) => {
225
232
  const { node } = link;
226
233
  const layersInside = withLayersInside ? layersInsideByType(node, insideCache) : [];
227
- report.push({ nodeId: node.id, nodeType: node.type, nodePath: pathText(link), layerType: layerTypeOf(node), kind, reason, layersInside });
234
+ report.push({ nodeId: node.id, nodeType: node.type, nodePath: pathText(link), layerType: layerTypeOf(node), kind, reason, layersInside, ...(count > 1 && { count }) });
228
235
  };
229
236
  for (const id of chosen.missing) {
230
237
  report.push({ nodeId: id, nodeType: "", nodePath: "", layerType: "", kind: "node-left-out", reason: "the copied node is not in the message", layersInside: [] });
@@ -352,7 +359,7 @@ export function walkMessage(message, options, native, distinctSources) {
352
359
  const variable = variables.variableOf(data, node.id);
353
360
  return "id" in variable && variable.type === "color" ? variable.id : null;
354
361
  },
355
- fontSizeVariable: (data) => variables.positiveLengthOf(data, node.id),
362
+ typographyVariable: (field, data) => typographyVariable(variables, field, data, node.id),
356
363
  }),
357
364
  keptFontSize: (layer) => keptFontSize(layer, node, variables, shownBy),
358
365
  };
@@ -373,7 +380,7 @@ export function walkMessage(message, options, native, distinctSources) {
373
380
  use = { change: node.change };
374
381
  else {
375
382
  const id = options.idSource();
376
- const style = figmaTextStyle(node.change, node.name, say, `text style ${node.id}`, [...(layer === undefined ? [] : [layer]), ...layersNaming(node)], variableNumberOf(node).variableNumber);
383
+ const style = figmaTextStyle(node.change, node.name, say, `text style ${node.id}`, [...(layer === undefined ? [] : [layer]), ...layersNaming(node)], native ? undefined : variableNumberOf(node).variableNumber);
377
384
  textStyles[id] = style;
378
385
  use = { change: node.change, shared: { id, style } };
379
386
  }
@@ -560,7 +567,7 @@ export function walkMessage(message, options, native, distinctSources) {
560
567
  let leftOut = false;
561
568
  const converted = converter(node, {
562
569
  newId: () => "override", convertChildren: () => [], blob, image, vectorCommands: aloneCommands, textStyle: textStyleFor(null), styleList, ...trackPaints, ...variableNumberOf(node, shownBy),
563
- ...(native && { plainTextPaint: (range) => range?.["fillPaints"] !== undefined || range?.["styleIdForFill"] !== undefined
570
+ ...(native && { instanceTypography: fields, plainTextPaint: (range) => range?.["fillPaints"] !== undefined || range?.["styleIdForFill"] !== undefined
564
571
  ? fields["textData"] !== undefined : fields["fillPaints"] !== undefined || fields["styleIdForFill"] !== undefined }),
565
572
  report: (kind) => { if (kind === "node-left-out")
566
573
  leftOut = true; },
@@ -624,8 +631,7 @@ export function walkMessage(message, options, native, distinctSources) {
624
631
  const everyImported = [];
625
632
  const omittedSubtrees = new Set();
626
633
  /** Runs the steps on `stack` until it is empty. `walkVisited` holds the nodes this walk imported; `imported` the converted node of each. */
627
- // Moondraft patch 0010: whether the walk places a node in a horizontal or vertical stack it imported (a grid imports
628
- // as absolute, and a root has no imported parent), and the node is not absolute in it.
634
+ // The layer participates in an imported stack or grid. A root has no imported parent.
629
635
  const inAutoLayoutFlow = (step) => step.inStack === true && step.node.change["stackPositioning"] !== "ABSOLUTE";
630
636
  const runSteps = (walkVisited, imported, rootList) => {
631
637
  for (let step = stack.pop(); step !== undefined; step = stack.pop()) {
@@ -964,17 +970,32 @@ export function walkMessage(message, options, native, distinctSources) {
964
970
  delete stub["propertyValues"];
965
971
  delete stub["slots"];
966
972
  const fields = new Map();
973
+ const watchPath = (holder, path) => {
974
+ let paths = readers.get(holder);
975
+ if (!paths)
976
+ readers.set(holder, paths = new Map());
977
+ let used = paths.get(path);
978
+ if (!used)
979
+ paths.set(path, used = new Set());
980
+ used.add(entry);
981
+ };
967
982
  const made = instanceFields(figma, component, self, {
968
983
  ...(native && {
984
+ nestedTextFields(holder, path) {
985
+ watchPath(holder, path);
986
+ return occurrenceFields.get(holder.id)?.get(path);
987
+ },
969
988
  fileOverride(path, change) {
970
989
  fields.set(path, { ...fields.get(path), ...change });
971
990
  },
972
- fileLayout(boxes, fillOnly) {
991
+ fileLayout(boxes, fillOnly, texts) {
973
992
  const id = stub["id"];
974
993
  instanceBoxes.delete(id);
975
994
  instanceFillSizes.delete(id);
976
995
  if (boxes.size)
977
996
  (fillOnly ? instanceFillSizes : instanceBoxes).set(id, boxes);
997
+ if (texts.size)
998
+ instanceBoxes.set(id, texts);
978
999
  },
979
1000
  }),
980
1001
  slotFills: entry.slotFills,
@@ -982,13 +1003,7 @@ export function walkMessage(message, options, native, distinctSources) {
982
1003
  refusedSwaps,
983
1004
  hasSourceKey,
984
1005
  nestedSwaps(holder, path) {
985
- let paths = readers.get(holder);
986
- if (!paths)
987
- readers.set(holder, paths = new Map());
988
- let used = paths.get(path);
989
- if (!used)
990
- paths.set(path, used = new Set());
991
- used.add(entry);
1006
+ watchPath(holder, path);
992
1007
  return pathSwaps.get(holder)?.get(path);
993
1008
  },
994
1009
  nodes: nodeRecord,
@@ -1015,6 +1030,7 @@ export function walkMessage(message, options, native, distinctSources) {
1015
1030
  seen.count += 1;
1016
1031
  }),
1017
1032
  });
1033
+ const previousFields = occurrenceFields.get(stub["id"]);
1018
1034
  if (fields.size)
1019
1035
  occurrenceFields.set(stub["id"], fields);
1020
1036
  else
@@ -1024,7 +1040,10 @@ export function walkMessage(message, options, native, distinctSources) {
1024
1040
  pathSwaps.set(holder, made.pathSwaps);
1025
1041
  for (const [path, used] of readers.get(holder) ?? []) {
1026
1042
  const before = previous?.get(path), after = made.pathSwaps.get(path);
1027
- if (before?.symbol !== after?.symbol || JSON.stringify(before?.properties) !== JSON.stringify(after?.properties)) {
1043
+ const prior = previousFields?.get(path), current = fields.get(path);
1044
+ const changedFields = prior !== current && (!prior || !current || Object.keys(prior).length !== Object.keys(current).length
1045
+ || Object.keys(prior).some(key => prior[key] !== current[key]));
1046
+ if (changedFields || before?.symbol !== after?.symbol || JSON.stringify(before?.properties) !== JSON.stringify(after?.properties)) {
1028
1047
  for (const reader of used)
1029
1048
  pending.add(reader);
1030
1049
  }
@@ -1354,13 +1373,13 @@ export function walkMessage(message, options, native, distinctSources) {
1354
1373
  const frame = { id: walk.newId(), type: "frame", name: node.name, visible: true, locked: false, opacity: 1, rotation: 0,
1355
1374
  frame: { x: 0, y: 0, width: Number(size?.["x"] ?? 1), height: Number(size?.["y"] ?? 1) },
1356
1375
  children: [], layout: { kind: "absolute" }, clipContent: false,
1357
- style: type === "FILL" ? visualStyle(size ? node : { ...node, change: { ...node.change, size: { x: 1, y: 1 } } }, walk) : nodeEffects(node, walk, true) };
1376
+ style: type === "FILL" ? visualStyle(size ? node : { ...node, change: { ...node.change, size: { x: 1, y: 1 } } }, walk) : nodeEffects(node, walk) };
1358
1377
  carryMarks(frame);
1359
1378
  styleLayers.set(node.id, frame);
1360
1379
  }
1361
1380
  }
1362
1381
  for (const { link, kind, reason, count } of counted.values()) {
1363
- add(link, kind, count === 1 ? reason : `${reason} (${String(count)} times, first here)`);
1382
+ add(link, kind, reason, false, count);
1364
1383
  }
1365
1384
  for (const orphan of tree.orphans) {
1366
1385
  if (skipStyle(orphan) || visited.has(orphan.id) || inComponents.has(orphan.id) || slotContents.has(orphan.id) || orphan.type === "VARIABLE" || orphan.type === "VARIABLE_SET")
@@ -1435,10 +1454,11 @@ function settleStacks(stacks, add, refits) {
1435
1454
  const entry = imported.get(child);
1436
1455
  return entry !== undefined && members.has(entry.node.id) ? entry : undefined;
1437
1456
  };
1457
+ const grid = stack.node.type === "frame" && stack.node.layout.kind === "grid";
1438
1458
  const flow = stack.figma.children.filter((child) => child.change["stackPositioning"] !== "ABSOLUTE");
1439
1459
  const blocker = flow.find((child) => {
1440
1460
  const entry = member(child);
1441
- return entry === undefined || (entry.node.visible && refits(entry.node));
1461
+ return grid ? entry === undefined && child.change.visible !== false : entry === undefined || (entry.node.visible && refits(entry.node));
1442
1462
  });
1443
1463
  const firstOnTop = stack.figma.change["stackReverseZIndex"] === true;
1444
1464
  if (blocker !== undefined) {
@@ -1452,6 +1472,25 @@ function settleStacks(stacks, add, refits) {
1452
1472
  }
1453
1473
  if (firstOnTop)
1454
1474
  carry(stack.node, { firstOnTop: true });
1475
+ if (grid) {
1476
+ const rows = gridAxis(stack.figma.change, "gridRows", () => { }).indices;
1477
+ const columns = gridAxis(stack.figma.change, "gridColumns", () => { }).indices;
1478
+ for (const child of stack.figma.children) {
1479
+ const entry = member(child);
1480
+ const lost = (field) => add(entry?.link ?? stack.link, "property-left-out", `grid layout field ${field}`);
1481
+ if (!entry) {
1482
+ for (const field of Object.keys(child.change))
1483
+ if (field.startsWith("grid"))
1484
+ lost(field);
1485
+ continue;
1486
+ }
1487
+ const cell = gridCell(child.change, rows, columns, lost);
1488
+ if (Object.keys(cell).length)
1489
+ carry(entry.node, { gridCell: cell });
1490
+ Object.assign(entry.node, stackChildFields(child.change, false, false, entry.node, (kind, reason) => add(entry.link, kind, reason)));
1491
+ }
1492
+ continue;
1493
+ }
1455
1494
  const vertical = stack.node.type === "frame" && stack.node.layout.kind === "vertical";
1456
1495
  const wraps = stack.figma.change["stackWrap"] === "WRAP";
1457
1496
  for (const child of stack.figma.children) {
@@ -23,8 +23,13 @@ export function decodeKiwiMessage(schema, rootTypeName, bytes, onRootArrayItem)
23
23
  throw new KiwiDecodeError(`the root type ${rootTypeName} is an enum, not a struct or message`, null);
24
24
  }
25
25
  const reader = new ByteReader(bytes);
26
+ const structs = new Map();
27
+ for (const definition of definitions.values()) {
28
+ if (definition.kind === "STRUCT" && definition.fields.length > 0 && definition.fields.every((field) => !field.isArray && NUMBERS.has(field.native)))
29
+ structs.set(definition, new Map());
30
+ }
26
31
  try {
27
- const value = readObject(reader, root, 1, onRootArrayItem);
32
+ const value = readObject(reader, root, 1, structs, onRootArrayItem);
28
33
  if (reader.remaining > 0) {
29
34
  throw reader.fail(`${reader.remaining} unread bytes after the ${rootTypeName}`);
30
35
  }
@@ -36,35 +41,72 @@ export function decodeKiwiMessage(schema, rootTypeName, bytes, onRootArrayItem)
36
41
  throw error;
37
42
  }
38
43
  }
39
- function readObject(reader, definition, depth, onArrayItem) {
44
+ const NUMBERS = new Set(["uint", "int", "float"]);
45
+ function readStruct(reader, definition, values) {
46
+ const { fields } = definition;
47
+ const read = fields.map((field) => {
48
+ try {
49
+ return readNative(reader, field.native);
50
+ }
51
+ catch (error) {
52
+ if (error instanceof KiwiDecodeError)
53
+ error.within(field.name);
54
+ throw error;
55
+ }
56
+ });
57
+ let level = values;
58
+ for (let i = 0; i < read.length - 1; i += 1) {
59
+ // Map keys treat -0 as 0, but a varfloat never decodes to -0.
60
+ const key = read[i];
61
+ let next = level.get(key);
62
+ if (next === undefined)
63
+ level.set(key, (next = new Map()));
64
+ level = next;
65
+ }
66
+ const key = read[read.length - 1];
67
+ const shared = level.get(key);
68
+ if (shared !== undefined)
69
+ return shared;
70
+ const result = {};
71
+ for (const [i, field] of fields.entries())
72
+ setField(result, field.name, read[i]);
73
+ level.set(key, Object.freeze(result));
74
+ return result;
75
+ }
76
+ function readObject(reader, definition, depth, structs, onArrayItem) {
40
77
  if (depth > KIWI_LIMITS.maxNestingDepth) {
41
78
  throw reader.fail(`nesting is deeper than KIWI_LIMITS.maxNestingDepth (${KIWI_LIMITS.maxNestingDepth})`);
42
79
  }
80
+ const shared = structs.get(definition);
81
+ if (shared !== undefined)
82
+ return readStruct(reader, definition, shared);
43
83
  const result = {};
44
84
  if (definition.kind === "STRUCT") {
45
85
  for (const field of definition.fields) {
46
- setField(result, field.name, readFieldValue(reader, field, depth, onArrayItem));
86
+ setField(result, field.name, readFieldValue(reader, field, depth, structs, onArrayItem));
47
87
  }
48
88
  return result;
49
89
  }
50
90
  for (;;) {
51
91
  const idOffset = reader.offset;
52
92
  const id = reader.readVarUint();
93
+ // A message fills its fields by computed name, and V8 keeps an object written that way with more than a
94
+ // few fields as a hash table. A copy has fast properties, several times smaller for a node change.
53
95
  if (id === 0)
54
- return result;
96
+ return { ...result };
55
97
  const field = definition.fieldsById.get(id);
56
98
  if (field === undefined) {
57
99
  throw reader.fail(`field id ${id} is not in message ${definition.name}`, idOffset);
58
100
  }
59
101
  if (Object.hasOwn(result, field.name))
60
102
  throw reader.fail(`field ${field.name} (id ${id}) appears twice`, idOffset);
61
- setField(result, field.name, readFieldValue(reader, field, depth, onArrayItem));
103
+ setField(result, field.name, readFieldValue(reader, field, depth, structs, onArrayItem));
62
104
  }
63
105
  }
64
- function readFieldValue(reader, field, depth, onArrayItem) {
106
+ function readFieldValue(reader, field, depth, structs, onArrayItem) {
65
107
  try {
66
108
  if (!field.isArray)
67
- return readSingle(reader, field, depth);
109
+ return readSingle(reader, field, depth, structs);
68
110
  const lengthOffset = reader.offset;
69
111
  const length = reader.readVarUint();
70
112
  if (field.native === "byte") {
@@ -85,7 +127,7 @@ function readFieldValue(reader, field, depth, onArrayItem) {
85
127
  const values = length <= 1024 ? new Array(length) : [];
86
128
  for (let index = 0; index < length; index += 1) {
87
129
  try {
88
- const value = readSingle(reader, field, depth);
130
+ const value = readSingle(reader, field, depth, structs);
89
131
  onArrayItem?.(field.name, value);
90
132
  values[index] = value;
91
133
  }
@@ -103,12 +145,12 @@ function readFieldValue(reader, field, depth, onArrayItem) {
103
145
  throw error;
104
146
  }
105
147
  }
106
- function readSingle(reader, field, depth) {
148
+ function readSingle(reader, field, depth, structs) {
107
149
  if (field.native !== null)
108
150
  return readNative(reader, field.native);
109
151
  const definition = field.definition;
110
152
  if (definition.kind !== "ENUM")
111
- return readObject(reader, definition, depth + 1);
153
+ return readObject(reader, definition, depth + 1, structs);
112
154
  const offset = reader.offset;
113
155
  const number = reader.readVarUint();
114
156
  const name = definition.enumNames.get(number);
@@ -134,7 +134,7 @@ export declare const paintFieldNames: {
134
134
  /** The fields a `LayerOverride` may hold. */
135
135
  export declare const layerOverrideFieldNames: readonly string[];
136
136
  /** The fields of `TextStyleOverrides`, as the codec checks them. */
137
- export declare const textStyleOverrideFieldNames: readonly ["fontFamily", "fontStyle", "fontAssetId", "fontFallbackAssetIds", "language", "fontSize", "fontWeight", "lineHeight", "letterSpacing", "color", "italic", "underline", "strikethrough", "openTypeFeatures", "fontVariations"];
137
+ export declare const textStyleOverrideFieldNames: readonly ["fontFamily", "fontStyle", "fontAssetId", "fontFallbackAssetIds", "language", "fontSize", "fontWeight", "lineHeight", "letterSpacing", "color", "italic", "underline", "strikethrough", "textCase", "openTypeFeatures", "fontVariations"];
138
138
  /** Validates a standalone authored run or list-marker text-style override. */
139
139
  export declare function assertTextStyleOverrides(value: unknown): asserts value is TextStyleOverrides;
140
140
  /** The fields a `TextParagraph` takes, as the codec checks them. */
@@ -391,6 +391,9 @@ function validateOpenTypeTag(tag, path) {
391
391
  fail("INVALID_SCHEMA", "OpenType tags must contain exactly four printable ASCII characters", path);
392
392
  }
393
393
  }
394
+ function textCase(value, path) {
395
+ oneOf(value, ["original", "upper", "lower", "title", "smallCaps", "smallCapsForced"], path);
396
+ }
394
397
  function validateOpenTypeFeatures(value, path, allowEmpty = false) {
395
398
  const settings = record(value, path);
396
399
  const entries = Object.entries(settings);
@@ -567,7 +570,7 @@ const LAYER_OVERRIDE_KEYS = [
567
570
  "conditional",
568
571
  "visible", "opacity", "name", "characters", "paragraphs", "textStyleId", "textStyle", "textAlign", "maxLines", "truncate", "styleId",
569
572
  "fills", "strokes", "shadows", "layerBlur", "backgroundBlur", "imageAssetId", "componentId",
570
- "clipContent", "cornerSmoothing", "layout", "sizing", "padding", "variableBindings", "propertyValues",
573
+ "clipContent", "cornerSmoothing", "layout", "gridCell", "sizing", "padding", "variableBindings", "propertyValues",
571
574
  ];
572
575
  /** The fields a `LayerOverride` may hold. */
573
576
  export const layerOverrideFieldNames = LAYER_OVERRIDE_KEYS;
@@ -940,7 +943,7 @@ function validateLayout(value, path) {
940
943
  : kind === "grid"
941
944
  ? [
942
945
  "kind",
943
- "columns",
946
+ "columns", "columnTracks", "rowTracks",
944
947
  "columnGap",
945
948
  "rowGap",
946
949
  "padding",
@@ -974,6 +977,18 @@ function validateLayout(value, path) {
974
977
  if (integer(candidate, candidatePath) <= 0)
975
978
  fail("INVALID_SCHEMA", "Grid columns must be positive", candidatePath);
976
979
  }, item.columns, `${path}.columns`);
980
+ for (const field of ["columnTracks", "rowTracks"])
981
+ optional(item[field], `${path}.${field}`, (value, at) => {
982
+ array(value, at).forEach((v, i) => {
983
+ const where = `${at}[${i}]`, track = record(v, where);
984
+ const kind = oneOf(track.kind, ["auto", "fixed", "fill"], where + ".kind");
985
+ exactKeys(track, kind === "fixed" ? ["kind", "size"] : kind === "fill" ? ["kind", "weight"] : ["kind"], where);
986
+ if (kind === "fixed")
987
+ nonNegativeNumber(track.size, where + ".size");
988
+ if (kind === "fill")
989
+ optional(track.weight, where + ".weight", positiveNumber);
990
+ });
991
+ });
977
992
  attempt(number, item.rowGap, `${path}.rowGap`);
978
993
  return;
979
994
  }
@@ -1053,6 +1068,7 @@ export const textStyleOverrideFieldNames = [
1053
1068
  "italic",
1054
1069
  "underline",
1055
1070
  "strikethrough",
1071
+ "textCase",
1056
1072
  "openTypeFeatures",
1057
1073
  "fontVariations",
1058
1074
  ];
@@ -1192,6 +1208,7 @@ function validateTextStyleOverrides(value, path) {
1192
1208
  optional(overrides.italic, `${path}.italic`, boolean);
1193
1209
  optional(overrides.underline, `${path}.underline`, boolean);
1194
1210
  optional(overrides.strikethrough, `${path}.strikethrough`, boolean);
1211
+ optional(overrides.textCase, `${path}.textCase`, textCase);
1195
1212
  optional(overrides.openTypeFeatures, `${path}.openTypeFeatures`, (value, at) => validateOpenTypeFeatures(value, at, true));
1196
1213
  optional(overrides.fontVariations, `${path}.fontVariations`, validateFontVariations);
1197
1214
  }
@@ -1348,13 +1365,28 @@ function validateLayerOverride(value, path) {
1348
1365
  exactKeys(item, LAYER_OVERRIDE_KEYS, path);
1349
1366
  optional(item.clipContent, `${path}.clipContent`, boolean);
1350
1367
  optional(item.cornerSmoothing, `${path}.cornerSmoothing`, unitIntervalNumber);
1368
+ optional(item.gridCell, `${path}.gridCell`, (value, at) => {
1369
+ const cell = record(value, at);
1370
+ exactKeys(cell, ["row", "column", "rowSpan", "columnSpan", "alignX", "alignY"], at);
1371
+ for (const key of ["row", "column", "rowSpan", "columnSpan"])
1372
+ optional(cell[key], at + "." + key, (v, where) => {
1373
+ const n = integer(v, where);
1374
+ if (n < (key.endsWith("Span") ? 1 : 0) || n > 65535)
1375
+ fail("INVALID_SCHEMA", "Invalid grid cell coordinate or span", where);
1376
+ });
1377
+ for (const key of ["alignX", "alignY"])
1378
+ optional(cell[key], at + "." + key, (v, where) => oneOf(v, ["start", "center", "end", "stretch"], where));
1379
+ });
1351
1380
  optional(item.layout, `${path}.layout`, (value, at) => {
1352
1381
  const layout = record(value, at);
1353
- exactKeys(layout, ["kind", "gap", "align", "justify", "wrap", "wrapGap", "alignContent"], at);
1382
+ const gridFields = ["columns", "columnTracks", "rowTracks", "columnGap", "rowGap"];
1383
+ const grid = layout.kind === "grid" || gridFields.some(key => key in layout);
1354
1384
  if (layout.kind !== undefined)
1355
- oneOf(layout.kind, ["absolute", "horizontal", "vertical"], `${at}.kind`);
1356
- validateLayout({ gap: 0, align: "start", justify: "start", padding: { top: 0, right: 0, bottom: 0, left: 0 },
1357
- widthSizing: "fixed", heightSizing: "fixed", ...layout, kind: "horizontal" }, at);
1385
+ oneOf(layout.kind, ["absolute", "horizontal", "vertical", "grid"], `${at}.kind`);
1386
+ exactKeys(layout, ["kind", ...(grid ? gridFields : ["gap", "align", "justify", "wrap", "wrapGap", "alignContent"])], at);
1387
+ validateLayout({ ...(grid ? { columns: 1, rowGap: 0, columnGap: 0 } : { gap: 0, align: "start", justify: "start" }),
1388
+ padding: { top: 0, right: 0, bottom: 0, left: 0 }, widthSizing: "fixed", heightSizing: "fixed",
1389
+ ...layout, kind: grid ? "grid" : "horizontal" }, at);
1358
1390
  });
1359
1391
  optional(item.conditional, `${path}.conditional`, (candidate, candidatePath) => {
1360
1392
  array(candidate, candidatePath).forEach((value, index) => {
@@ -2292,6 +2324,7 @@ function validateTheme(value, path) {
2292
2324
  "italic",
2293
2325
  "underline",
2294
2326
  "strikethrough",
2327
+ "textCase",
2295
2328
  "openTypeFeatures",
2296
2329
  "fontVariations",
2297
2330
  ], stylePath);
@@ -2309,6 +2342,7 @@ function validateTheme(value, path) {
2309
2342
  optional(styleRecord.italic, `${stylePath}.italic`, boolean);
2310
2343
  optional(styleRecord.underline, `${stylePath}.underline`, boolean);
2311
2344
  optional(styleRecord.strikethrough, `${stylePath}.strikethrough`, boolean);
2345
+ optional(styleRecord.textCase, `${stylePath}.textCase`, textCase);
2312
2346
  optional(styleRecord.openTypeFeatures, `${stylePath}.openTypeFeatures`, validateOpenTypeFeatures);
2313
2347
  optional(styleRecord.fontVariations, `${stylePath}.fontVariations`, validateFontVariations);
2314
2348
  }
@@ -601,7 +601,7 @@ function resolveBindings(bindings, override) {
601
601
  if (property !== undefined)
602
602
  delete next[property];
603
603
  }
604
- for (const key of ["gap", "wrapGap"])
604
+ for (const key of ["gap", "wrapGap", "columnGap", "rowGap"])
605
605
  if (override.layout?.[key] !== undefined)
606
606
  delete next[key];
607
607
  for (const side of Object.keys(override.padding ?? {})) {
@@ -644,6 +644,8 @@ function mergeOverrides(inner, outer) {
644
644
  if (inner.textStyle !== undefined && outer.textStyle !== undefined)
645
645
  merged.textStyle = { ...inner.textStyle, ...outer.textStyle };
646
646
  // Padding is overridden side by side, so an outer side keeps the inner override's other sides.
647
+ if (inner.gridCell && outer.gridCell)
648
+ merged.gridCell = { ...inner.gridCell, ...outer.gridCell };
647
649
  if (inner.layout && outer.layout)
648
650
  merged.layout = { ...inner.layout, ...outer.layout };
649
651
  if (inner.sizing !== undefined && outer.sizing !== undefined)