@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,4 +1,6 @@
1
- import type { KiwiObject, KiwiSchema } from "./types.ts";
1
+ import type { KiwiObject, KiwiSchema, KiwiValue } from "./types.ts";
2
+ /** Receives each item in a root array after its complete wire value has been validated. */
3
+ export type RootArrayItem = (field: string, value: KiwiValue) => void;
2
4
  /**
3
5
  * Decodes `bytes` as one value of the struct or message `rootTypeName` in
4
6
  * `schema`. A struct reads every field in order; a message reads
@@ -7,4 +9,4 @@ import type { KiwiObject, KiwiSchema } from "./types.ts";
7
9
  * arrays longer than the remaining bytes allow, nesting deeper than
8
10
  * `KIWI_LIMITS.maxNestingDepth`, and bytes left over after the root.
9
11
  */
10
- export declare function decodeKiwiMessage(schema: KiwiSchema, rootTypeName: string, bytes: Uint8Array): KiwiObject;
12
+ export declare function decodeKiwiMessage(schema: KiwiSchema, rootTypeName: string, bytes: Uint8Array, onRootArrayItem?: RootArrayItem): KiwiObject;
@@ -10,7 +10,7 @@ import { indexKiwiSchema } from "./schema.js";
10
10
  * arrays longer than the remaining bytes allow, nesting deeper than
11
11
  * `KIWI_LIMITS.maxNestingDepth`, and bytes left over after the root.
12
12
  */
13
- export function decodeKiwiMessage(schema, rootTypeName, bytes) {
13
+ export function decodeKiwiMessage(schema, rootTypeName, bytes, onRootArrayItem) {
14
14
  if (!(bytes instanceof Uint8Array)) {
15
15
  throw new TypeError("decodeKiwiMessage expects a Uint8Array");
16
16
  }
@@ -23,8 +23,13 @@ export function decodeKiwiMessage(schema, rootTypeName, bytes) {
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);
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,37 +41,72 @@ export function decodeKiwiMessage(schema, rootTypeName, bytes) {
36
41
  throw error;
37
42
  }
38
43
  }
39
- function readObject(reader, definition, depth) {
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));
86
+ setField(result, field.name, readFieldValue(reader, field, depth, structs, onArrayItem));
47
87
  }
48
88
  return result;
49
89
  }
50
- const seen = new Set();
51
90
  for (;;) {
52
91
  const idOffset = reader.offset;
53
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.
54
95
  if (id === 0)
55
- return result;
96
+ return { ...result };
56
97
  const field = definition.fieldsById.get(id);
57
98
  if (field === undefined) {
58
99
  throw reader.fail(`field id ${id} is not in message ${definition.name}`, idOffset);
59
100
  }
60
- if (seen.has(id))
101
+ if (Object.hasOwn(result, field.name))
61
102
  throw reader.fail(`field ${field.name} (id ${id}) appears twice`, idOffset);
62
- seen.add(id);
63
- setField(result, field.name, readFieldValue(reader, field, depth));
103
+ setField(result, field.name, readFieldValue(reader, field, depth, structs, onArrayItem));
64
104
  }
65
105
  }
66
- function readFieldValue(reader, field, depth) {
106
+ function readFieldValue(reader, field, depth, structs, onArrayItem) {
67
107
  try {
68
108
  if (!field.isArray)
69
- return readSingle(reader, field, depth);
109
+ return readSingle(reader, field, depth, structs);
70
110
  const lengthOffset = reader.offset;
71
111
  const length = reader.readVarUint();
72
112
  if (field.native === "byte") {
@@ -82,10 +122,14 @@ function readFieldValue(reader, field, depth) {
82
122
  if (length * elementBytes > reader.remaining) {
83
123
  throw reader.fail(`array length ${length} needs at least ${length * elementBytes} bytes but ${reader.remaining} remain`, lengthOffset);
84
124
  }
85
- const values = [];
125
+ // Small arrays are common in node changes. Avoid the spare slots of a growing array.
126
+ // Keep large untrusted counts incremental until their elements have actually been read.
127
+ const values = length <= 1024 ? new Array(length) : [];
86
128
  for (let index = 0; index < length; index += 1) {
87
129
  try {
88
- values.push(readSingle(reader, field, depth));
130
+ const value = readSingle(reader, field, depth, structs);
131
+ onArrayItem?.(field.name, value);
132
+ values[index] = value;
89
133
  }
90
134
  catch (error) {
91
135
  if (error instanceof KiwiDecodeError)
@@ -101,12 +145,12 @@ function readFieldValue(reader, field, depth) {
101
145
  throw error;
102
146
  }
103
147
  }
104
- function readSingle(reader, field, depth) {
148
+ function readSingle(reader, field, depth, structs) {
105
149
  if (field.native !== null)
106
150
  return readNative(reader, field.native);
107
151
  const definition = field.definition;
108
152
  if (definition.kind !== "ENUM")
109
- return readObject(reader, definition, depth + 1);
153
+ return readObject(reader, definition, depth + 1, structs);
110
154
  const offset = reader.offset;
111
155
  const number = reader.readVarUint();
112
156
  const name = definition.enumNames.get(number);
@@ -134,13 +134,13 @@ 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. */
141
141
  export declare const textParagraphFieldNames: readonly ["runs", "direction", "align", "spacingBefore", "spacingAfter", "indent", "list"];
142
142
  /** The fields a `TextRun` takes, as the codec checks them; its size, colour and weight go in `overrides`. */
143
- export declare const textRunFieldNames: readonly ["text", "styleId", "overrides"];
143
+ export declare const textRunFieldNames: readonly ["text", "styleId", "overrides", "hyperlink"];
144
144
  /**
145
145
  * A kind of node: its `type`, plus its `shape` for a shape node, because a
146
146
  * path has no `frame`. Any `SceneNode` is one.
@@ -193,6 +193,13 @@ function unitIntervalNumber(value, path) {
193
193
  }
194
194
  return result;
195
195
  }
196
+ function positiveInteger(value, path) {
197
+ const result = integer(value, path);
198
+ if (result < 1) {
199
+ fail("INVALID_SCHEMA", "Expected a positive integer", path);
200
+ }
201
+ return result;
202
+ }
196
203
  function integer(value, path) {
197
204
  const result = number(value, path);
198
205
  if (!Number.isInteger(result)) {
@@ -384,10 +391,13 @@ function validateOpenTypeTag(tag, path) {
384
391
  fail("INVALID_SCHEMA", "OpenType tags must contain exactly four printable ASCII characters", path);
385
392
  }
386
393
  }
387
- function validateOpenTypeFeatures(value, path) {
394
+ function textCase(value, path) {
395
+ oneOf(value, ["original", "upper", "lower", "title", "smallCaps", "smallCapsForced"], path);
396
+ }
397
+ function validateOpenTypeFeatures(value, path, allowEmpty = false) {
388
398
  const settings = record(value, path);
389
399
  const entries = Object.entries(settings);
390
- if (entries.length === 0) {
400
+ if (entries.length === 0 && !allowEmpty) {
391
401
  fail("INVALID_SCHEMA", "Empty OpenType feature settings must be omitted", path);
392
402
  }
393
403
  for (const [tag, rawSetting] of entries) {
@@ -558,9 +568,9 @@ function validateShadows(value, path) {
558
568
  }
559
569
  const LAYER_OVERRIDE_KEYS = [
560
570
  "conditional",
561
- "visible", "opacity", "name", "characters", "paragraphs", "textStyleId", "textStyle", "textAlign", "styleId",
571
+ "visible", "opacity", "name", "characters", "paragraphs", "textStyleId", "textStyle", "textAlign", "maxLines", "truncate", "styleId",
562
572
  "fills", "strokes", "shadows", "layerBlur", "backgroundBlur", "imageAssetId", "componentId",
563
- "sizing", "padding", "variableBindings", "propertyValues",
573
+ "clipContent", "cornerSmoothing", "layout", "gridCell", "sizing", "padding", "variableBindings", "propertyValues",
564
574
  ];
565
575
  /** The fields a `LayerOverride` may hold. */
566
576
  export const layerOverrideFieldNames = LAYER_OVERRIDE_KEYS;
@@ -933,7 +943,7 @@ function validateLayout(value, path) {
933
943
  : kind === "grid"
934
944
  ? [
935
945
  "kind",
936
- "columns",
946
+ "columns", "columnTracks", "rowTracks",
937
947
  "columnGap",
938
948
  "rowGap",
939
949
  "padding",
@@ -967,6 +977,18 @@ function validateLayout(value, path) {
967
977
  if (integer(candidate, candidatePath) <= 0)
968
978
  fail("INVALID_SCHEMA", "Grid columns must be positive", candidatePath);
969
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
+ });
970
992
  attempt(number, item.rowGap, `${path}.rowGap`);
971
993
  return;
972
994
  }
@@ -1046,6 +1068,7 @@ export const textStyleOverrideFieldNames = [
1046
1068
  "italic",
1047
1069
  "underline",
1048
1070
  "strikethrough",
1071
+ "textCase",
1049
1072
  "openTypeFeatures",
1050
1073
  "fontVariations",
1051
1074
  ];
@@ -1185,7 +1208,8 @@ function validateTextStyleOverrides(value, path) {
1185
1208
  optional(overrides.italic, `${path}.italic`, boolean);
1186
1209
  optional(overrides.underline, `${path}.underline`, boolean);
1187
1210
  optional(overrides.strikethrough, `${path}.strikethrough`, boolean);
1188
- optional(overrides.openTypeFeatures, `${path}.openTypeFeatures`, validateOpenTypeFeatures);
1211
+ optional(overrides.textCase, `${path}.textCase`, textCase);
1212
+ optional(overrides.openTypeFeatures, `${path}.openTypeFeatures`, (value, at) => validateOpenTypeFeatures(value, at, true));
1189
1213
  optional(overrides.fontVariations, `${path}.fontVariations`, validateFontVariations);
1190
1214
  }
1191
1215
  /** Validates a standalone authored run or list-marker text-style override. */
@@ -1269,7 +1293,7 @@ function validateExportSettings(value, path) {
1269
1293
  /** The fields a `TextParagraph` takes, as the codec checks them. */
1270
1294
  export const textParagraphFieldNames = ["runs", "direction", "align", "spacingBefore", "spacingAfter", "indent", "list"];
1271
1295
  /** The fields a `TextRun` takes, as the codec checks them; its size, colour and weight go in `overrides`. */
1272
- export const textRunFieldNames = ["text", "styleId", "overrides"];
1296
+ export const textRunFieldNames = ["text", "styleId", "overrides", "hyperlink"];
1273
1297
  /** Checks one `TextRun` on its own; its style reference is checked by the document. */
1274
1298
  function validateTextRun(run, runPath) {
1275
1299
  const runRecord = record(run, runPath);
@@ -1277,6 +1301,13 @@ function validateTextRun(run, runPath) {
1277
1301
  attempt(string, runRecord.text, `${runPath}.text`);
1278
1302
  optional(runRecord.styleId, `${runPath}.styleId`, nonEmptyString);
1279
1303
  optional(runRecord.overrides, `${runPath}.overrides`, validateTextStyleOverrides);
1304
+ optional(runRecord.hyperlink, `${runPath}.hyperlink`, (candidate, path) => {
1305
+ const link = record(candidate, path);
1306
+ const kind = oneOf(link.kind, ["url", "target"], `${path}.kind`);
1307
+ const field = kind === "url" ? "url" : "guid";
1308
+ exactKeys(link, ["kind", field], path);
1309
+ attempt(nonEmptyString, link[field], `${path}.${field}`);
1310
+ });
1280
1311
  }
1281
1312
  /** Checks one list marker on its own; its style reference is checked by the document. */
1282
1313
  function validateListMarker(entry, entryPath) {
@@ -1332,6 +1363,31 @@ function validateTextParagraph(paragraph, paragraphPath) {
1332
1363
  function validateLayerOverride(value, path) {
1333
1364
  const item = record(value, path);
1334
1365
  exactKeys(item, LAYER_OVERRIDE_KEYS, path);
1366
+ optional(item.clipContent, `${path}.clipContent`, boolean);
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
+ });
1380
+ optional(item.layout, `${path}.layout`, (value, at) => {
1381
+ const layout = record(value, at);
1382
+ const gridFields = ["columns", "columnTracks", "rowTracks", "columnGap", "rowGap"];
1383
+ const grid = layout.kind === "grid" || gridFields.some(key => key in layout);
1384
+ if (layout.kind !== undefined)
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);
1390
+ });
1335
1391
  optional(item.conditional, `${path}.conditional`, (candidate, candidatePath) => {
1336
1392
  array(candidate, candidatePath).forEach((value, index) => {
1337
1393
  const at = `${candidatePath}[${index}]`;
@@ -1359,6 +1415,10 @@ function validateLayerOverride(value, path) {
1359
1415
  optional(item.textStyleId, `${path}.textStyleId`, nonEmptyString);
1360
1416
  optional(item.textStyle, `${path}.textStyle`, validateTextStyleOverrides);
1361
1417
  optional(item.textAlign, `${path}.textAlign`, (candidate, candidatePath) => oneOf(candidate, ["left", "center", "right", "justify"], candidatePath));
1418
+ if (item.maxLines !== null)
1419
+ optional(item.maxLines, `${path}.maxLines`, positiveInteger);
1420
+ if (item.truncate !== null)
1421
+ optional(item.truncate, `${path}.truncate`, (candidate, candidatePath) => oneOf(candidate, ["ellipsis"], candidatePath));
1362
1422
  if (item.styleId !== null)
1363
1423
  optional(item.styleId, `${path}.styleId`, nonEmptyString);
1364
1424
  optional(item.fills, `${path}.fills`, (candidate, candidatePath) => {
@@ -1641,7 +1701,7 @@ export function sceneNodeFieldNames(kind) {
1641
1701
  const variantKeys = {
1642
1702
  frame: ["constraintSize", "children", "layout", "style", "clipContent", "guides", "slot", "slotHost"],
1643
1703
  group: ["children", "clipContent"],
1644
- text: ["paragraphs", "verticalAlign", "overflow", "autoResize", "wrap", "paragraphSpacing"],
1704
+ text: ["paragraphs", "verticalAlign", "overflow", "autoResize", "wrap", "paragraphSpacing", "maxLines", "truncate"],
1645
1705
  code: [
1646
1706
  "source",
1647
1707
  "language",
@@ -1780,6 +1840,8 @@ function validateNode(value, path) {
1780
1840
  attempt((candidate, candidatePath) => oneOf(candidate, AUTO_RESIZE_MODES, candidatePath), item.autoResize, `${path}.autoResize`);
1781
1841
  attempt((candidate, candidatePath) => oneOf(candidate, ["none", "word", "character"], candidatePath), item.wrap, `${path}.wrap`);
1782
1842
  optional(item.paragraphSpacing, `${path}.paragraphSpacing`, nonNegativeNumber);
1843
+ optional(item.maxLines, `${path}.maxLines`, positiveInteger);
1844
+ optional(item.truncate, `${path}.truncate`, (candidate, candidatePath) => oneOf(candidate, ["ellipsis"], candidatePath));
1783
1845
  return;
1784
1846
  case "code": {
1785
1847
  const source = attempt(string, item.source, `${path}.source`);
@@ -2262,6 +2324,7 @@ function validateTheme(value, path) {
2262
2324
  "italic",
2263
2325
  "underline",
2264
2326
  "strikethrough",
2327
+ "textCase",
2265
2328
  "openTypeFeatures",
2266
2329
  "fontVariations",
2267
2330
  ], stylePath);
@@ -2279,6 +2342,7 @@ function validateTheme(value, path) {
2279
2342
  optional(styleRecord.italic, `${stylePath}.italic`, boolean);
2280
2343
  optional(styleRecord.underline, `${stylePath}.underline`, boolean);
2281
2344
  optional(styleRecord.strikethrough, `${stylePath}.strikethrough`, boolean);
2345
+ optional(styleRecord.textCase, `${stylePath}.textCase`, textCase);
2282
2346
  optional(styleRecord.openTypeFeatures, `${stylePath}.openTypeFeatures`, validateOpenTypeFeatures);
2283
2347
  optional(styleRecord.fontVariations, `${stylePath}.fontVariations`, validateFontVariations);
2284
2348
  }
@@ -72,6 +72,8 @@ export declare function filledPropertyValues(component: ComponentDefinition, val
72
72
  * layer and its sublayers.
73
73
  */
74
74
  export declare function evaluateComponentProgram(document: DesignDocument, component: ComponentDefinition, program: ComponentProgram, propertyValues?: ComponentPropertyValues, modes?: VariableModes): ComputedComponent;
75
+ /** Whether a characters value leaves the linked source runs unchanged. */
76
+ export declare function linkedParagraphsMatch(characters: string, source: readonly TextParagraph[]): boolean;
75
77
  /**
76
78
  * Text layers: the whole text as one plain string, paragraphs separated by
77
79
  * `"\n"`, every character taking the style of the first run and every
@@ -154,6 +154,11 @@ export function evaluateComponentProgram(document, component, program, propertyV
154
154
  // Writing results into model fields
155
155
  const atLeastZero = (value) => Math.max(0, value);
156
156
  const between = (value, low, high) => Math.min(high, Math.max(low, value));
157
+ /** Whether a characters value leaves the linked source runs unchanged. */
158
+ export function linkedParagraphsMatch(characters, source) {
159
+ return source.some(paragraph => paragraph.runs.some(run => run.hyperlink !== undefined))
160
+ && characters.replaceAll("\u2029", "\n") === source.map(paragraph => paragraph.runs.map(run => run.text).join("")).join("\n");
161
+ }
157
162
  /**
158
163
  * Text layers: the whole text as one plain string, paragraphs separated by
159
164
  * `"\n"`, every character taking the style of the first run and every
@@ -163,6 +168,8 @@ const between = (value, low, high) => Math.min(high, Math.max(low, value));
163
168
  * them apart.
164
169
  */
165
170
  export function paragraphsFromCharacters(characters, source) {
171
+ if (linkedParagraphsMatch(characters, source))
172
+ return source;
166
173
  const first = source[0];
167
174
  const firstRun = first?.runs[0];
168
175
  const { runs: _runs, ...paragraphFields } = first ?? { runs: [] };
@@ -179,6 +179,8 @@ export interface InstanceResolveCache {
179
179
  }
180
180
  /** @since 0.23.0 */
181
181
  export interface ResolveInstanceOptions {
182
+ /** Resolve layer content and appearance without computing geometry for a host that lays out the result. */
183
+ readonly layout?: boolean;
182
184
  readonly cache?: InstanceResolveCache;
183
185
  /**
184
186
  * The variable modes the instance inherits from its parent, as
@@ -216,8 +218,10 @@ export declare function noteComponentTreesChanged(cache: InstanceResolveCache, c
216
218
  * @since 0.37.0
217
219
  */
218
220
  export declare function resolvedTextSizesChangedSince(document: DesignDocument, result: ResolvedInstance, version: number): boolean;
219
- /** Makes an `InstanceResolveCache` to pass to `resolveInstance`. */
220
- export declare function createInstanceResolveCache(): InstanceResolveCache;
221
+ /** Makes an instance cache. A one-pass consumer may keep component computations
222
+ * without retaining the complete resolved tree of every occurrence.
223
+ */
224
+ export declare function createInstanceResolveCache(retainTrees?: boolean): InstanceResolveCache;
221
225
  /**
222
226
  * The cache that everything resolving the open document's instances shares:
223
227
  * the layout cascade, the page compiler, the accessibility tree, the
@@ -214,9 +214,12 @@ function sameValue(left, right) {
214
214
  }
215
215
  return true;
216
216
  }
217
- /** Makes an `InstanceResolveCache` to pass to `resolveInstance`. */
218
- export function createInstanceResolveCache() {
217
+ /** Makes an instance cache. A one-pass consumer may keep component computations
218
+ * without retaining the complete resolved tree of every occurrence.
219
+ */
220
+ export function createInstanceResolveCache(retainTrees = true) {
219
221
  const state = {
222
+ retainTrees,
220
223
  lastNodes: undefined,
221
224
  lastTheme: undefined,
222
225
  lastAssets: undefined,
@@ -598,6 +601,9 @@ function resolveBindings(bindings, override) {
598
601
  if (property !== undefined)
599
602
  delete next[property];
600
603
  }
604
+ for (const key of ["gap", "wrapGap", "columnGap", "rowGap"])
605
+ if (override.layout?.[key] !== undefined)
606
+ delete next[key];
601
607
  for (const side of Object.keys(override.padding ?? {})) {
602
608
  const property = PADDING_PROPERTIES[side];
603
609
  if (property !== undefined)
@@ -638,6 +644,10 @@ function mergeOverrides(inner, outer) {
638
644
  if (inner.textStyle !== undefined && outer.textStyle !== undefined)
639
645
  merged.textStyle = { ...inner.textStyle, ...outer.textStyle };
640
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 };
649
+ if (inner.layout && outer.layout)
650
+ merged.layout = { ...inner.layout, ...outer.layout };
641
651
  if (inner.sizing !== undefined && outer.sizing !== undefined)
642
652
  merged.sizing = { ...inner.sizing, ...outer.sizing };
643
653
  if (inner.padding !== undefined && outer.padding !== undefined)
@@ -718,7 +728,7 @@ function overriddenStyle(style, override) {
718
728
  next.styleId = override.styleId;
719
729
  changed = true;
720
730
  }
721
- for (const field of ["fills", "strokes", "shadows", "layerBlur", "backgroundBlur"]) {
731
+ for (const field of ["fills", "strokes", "shadows", "layerBlur", "backgroundBlur", "cornerSmoothing"]) {
722
732
  if (override[field] === undefined)
723
733
  continue;
724
734
  next[field] = override[field];
@@ -744,7 +754,15 @@ function withoutFillSizing(override) {
744
754
  function applyOverride(document, node, override) {
745
755
  if (override === undefined)
746
756
  return node;
757
+ if (node.type === "frame" && override.layout) {
758
+ const layout = override.layout.kind === "absolute" ? { kind: "absolute" } :
759
+ { gap: 0, align: "start", justify: "start", padding: { top: 0, right: 0, bottom: 0, left: 0 },
760
+ widthSizing: "fixed", heightSizing: "fixed", ...node.layout, ...override.layout };
761
+ node = { ...node, layout };
762
+ }
747
763
  const base = { ...node };
764
+ if (node.type === "frame" && override.clipContent !== undefined)
765
+ base.clipContent = override.clipContent;
748
766
  if (override.visible !== undefined)
749
767
  base.visible = override.visible;
750
768
  if (override.opacity !== undefined)
@@ -768,6 +786,12 @@ function applyOverride(document, node, override) {
768
786
  if (node.autoResize !== "none")
769
787
  base.frame = getDerivedAutoSizedTextFrame(document, node, paragraphs);
770
788
  }
789
+ for (const key of ["maxLines", "truncate"]) {
790
+ if (override[key] === null)
791
+ delete base[key];
792
+ else if (override[key] !== undefined)
793
+ base[key] = override[key];
794
+ }
771
795
  }
772
796
  if (node.type === "image" && override.imageAssetId !== undefined)
773
797
  base.assetId = override.imageAssetId;
@@ -1077,12 +1101,12 @@ function expandInstance(expansion, instance, virtualId, prefix, absolutePrefix,
1077
1101
  expansion.texts.push({ virtualId: layerId, sourceNodeId: nodeId, path, node: placed, ...pathInstance });
1078
1102
  }
1079
1103
  // Without layout, frames stay as stored.
1080
- if (!expansion.textOnly && placed.type === "group" && unbound.type === "group") {
1104
+ if (expansion.layout && placed.type === "group" && unbound.type === "group") {
1081
1105
  // A mode that resizes the group scales its layers, as a group resize does.
1082
1106
  scaleGroupChildren(expansion.nodes, placed, unbound.frame);
1083
1107
  fitGroup(expansion.nodes, placed);
1084
1108
  }
1085
- if (!expansion.textOnly && placed.type === "frame" && stored.type === "frame" && filled === undefined) {
1109
+ if (expansion.layout && placed.type === "frame" && stored.type === "frame" && filled === undefined) {
1086
1110
  // A computed size or a mode that resizes the frame: children follow
1087
1111
  // their constraints from the stored size, deepest frames first
1088
1112
  // (`expandNode` returns after its children). Slot content is placed
@@ -1107,7 +1131,7 @@ function expandInstance(expansion, instance, virtualId, prefix, absolutePrefix,
1107
1131
  const rootNode = applyOverride(document, computed.nodes.get(root.id) ?? root, rootOverride);
1108
1132
  const childIds = shownChildren(rootNode.children).map((childId) => expandNode(childId, [childId], depth + 1, instanceModes));
1109
1133
  putEntry(expansion.nodes, virtualId, applyVariableBindings(document, instanceFrame(instance, rootNode, virtualId, childIds), instanceModes));
1110
- if (!expansion.textOnly) {
1134
+ if (expansion.layout) {
1111
1135
  // A resized instance, or one whose size a mode changes: children follow
1112
1136
  // their constraints from the stored root size, which their positions are
1113
1137
  // relative to, whatever size an expression computes for the root. In an
@@ -1229,11 +1253,11 @@ function expandStored(expansion, nodeId, depth, parentModes, stack) {
1229
1253
  expansion.texts.push({ virtualId: nodeId, sourceNodeId: nodeId, path: [nodeId], node: placed });
1230
1254
  }
1231
1255
  // Without layout, frames stay as stored.
1232
- if (!expansion.textOnly && placed.type === "group" && stored.type === "group") {
1256
+ if (expansion.layout && placed.type === "group" && stored.type === "group") {
1233
1257
  scaleGroupChildren(expansion.nodes, placed, stored.frame);
1234
1258
  fitGroup(expansion.nodes, placed);
1235
1259
  }
1236
- if (!expansion.textOnly && placed.type === "frame" && stored.type === "frame") {
1260
+ if (expansion.layout && placed.type === "frame" && stored.type === "frame") {
1237
1261
  constrainChildren(expansion.nodes, nodeId, stored.frame, placed.frame).forEach((child) => {
1238
1262
  putEntry(expansion.nodes, child.id, child);
1239
1263
  });
@@ -1387,9 +1411,10 @@ function buildLayers(expansion, layers, id) {
1387
1411
  layers.set(id, layer);
1388
1412
  return layer;
1389
1413
  }
1390
- function resolveInstanceUncached(document, instance, cache, modes, enclosing = []) {
1391
- const expansion = expandStoredInstance(document, instance, cache, modes, enclosing, false);
1392
- layoutExpansion(expansion);
1414
+ function resolveInstanceUncached(document, instance, cache, modes, enclosing = [], layout = true) {
1415
+ const expansion = expandStoredInstance(document, instance, cache, modes, enclosing, false, layout);
1416
+ if (layout)
1417
+ layoutExpansion(expansion);
1393
1418
  const layers = new Map();
1394
1419
  const root = buildLayers(expansion, layers, instance.id);
1395
1420
  const result = { instanceId: instance.id, componentId: instance.componentId, root,
@@ -1403,7 +1428,7 @@ function resolveInstanceUncached(document, instance, cache, modes, enclosing = [
1403
1428
  return result;
1404
1429
  }
1405
1430
  /** The flattened tree of a stored instance, before layout. */
1406
- function expandStoredInstance(document, instance, cache, modes, enclosing, textOnly) {
1431
+ function expandStoredInstance(document, instance, cache, modes, enclosing, textOnly, layout = !textOnly) {
1407
1432
  const expansion = {
1408
1433
  document,
1409
1434
  instanceId: instance.id,
@@ -1417,6 +1442,7 @@ function expandStoredInstance(document, instance, cache, modes, enclosing, textO
1417
1442
  cache,
1418
1443
  content: [],
1419
1444
  textOnly,
1445
+ layout,
1420
1446
  texts: [],
1421
1447
  consulted: [],
1422
1448
  };
@@ -1501,8 +1527,10 @@ export function resolveInstance(document, instanceId, options) {
1501
1527
  const cache = options?.cache;
1502
1528
  const modes = options?.variableModes ?? inheritedVariableModes(document, instanceId);
1503
1529
  if (!isCacheState(cache))
1504
- return resolveInstanceUncached(document, node, undefined, modes);
1530
+ return resolveInstanceUncached(document, node, undefined, modes, [], options?.layout);
1505
1531
  syncCache(cache, document);
1532
+ if (!cache.retainTrees || options?.layout === false)
1533
+ return resolveInstanceUncached(document, node, cache, modes, [], options?.layout);
1506
1534
  const modesKey = `modes:${variableModesKey(document.theme, modes)}`;
1507
1535
  const entries = cache.instances.get(node) ?? equalNodeEntries(cache, node) ?? [];
1508
1536
  if (cache.lastInstanceNodes.get(instanceId)?.deref() !== node) {
@@ -1543,10 +1571,11 @@ function resolveComponentUncached(document, componentId, options, componentIds)
1543
1571
  }
1544
1572
  componentIds.push(componentId);
1545
1573
  const state = isCacheState(options?.cache) ? options.cache : undefined;
1574
+ const layout = options?.layout !== false;
1546
1575
  const resolveNested = (node) => {
1547
1576
  const resolved = node === entryOf(document.nodes, node.id)
1548
- ? resolveInstance(document, node.id, options?.cache === undefined ? undefined : { cache: options.cache })
1549
- : resolveInstanceUncached(document, node, state, inheritedVariableModes(document, node.id), [componentId]);
1577
+ ? resolveInstance(document, node.id, { ...(options?.cache && { cache: options.cache }), layout })
1578
+ : resolveInstanceUncached(document, node, state, inheritedVariableModes(document, node.id), [componentId], layout);
1550
1579
  resolvedInstanceComponents(resolved).forEach((id) => { if (!componentIds.includes(id))
1551
1580
  componentIds.push(id); });
1552
1581
  return resolved;
@@ -1604,7 +1633,7 @@ function resolveComponentUncached(document, componentId, options, componentIds)
1604
1633
  const children = node.children.filter((childId) => !computed.leftOut.has(childId));
1605
1634
  node = { ...rebound(node), children };
1606
1635
  children.forEach((childId) => collect(childId, depth + 1));
1607
- if (node.type === "frame" && stored.type === "frame") {
1636
+ if (layout && node.type === "frame" && stored.type === "frame") {
1608
1637
  // A computed size: children follow their constraints from the stored size.
1609
1638
  putEntry(nodes, nodeId, node);
1610
1639
  constrainChildren(nodes, nodeId, node.constraintSize ?? stored.frame, node.frame).forEach((child) => {
@@ -1615,12 +1644,13 @@ function resolveComponentUncached(document, componentId, options, componentIds)
1615
1644
  if (node.type !== "instance" && !isContainerNode(node))
1616
1645
  node = rebound(node);
1617
1646
  putEntry(nodes, nodeId, node);
1618
- if (node.type === "group")
1647
+ if (layout && node.type === "group")
1619
1648
  fitGroup(nodes, node);
1620
1649
  depths.set(nodeId, depth);
1621
1650
  };
1622
1651
  collect(component.rootId, 0);
1623
- settleLayout(nodes, depths);
1652
+ if (layout)
1653
+ settleLayout(nodes, depths);
1624
1654
  const visit = (nodeId) => {
1625
1655
  const node = entryOf(nodes, nodeId);
1626
1656
  if (node.type === "instance") {
@@ -1657,6 +1687,8 @@ export function resolveComponent(document, componentId, options) {
1657
1687
  return resolveComponentUncached(document, componentId, options, []);
1658
1688
  syncCache(cache, document);
1659
1689
  const drawn = [];
1690
+ if (!cache.retainTrees || options?.layout === false)
1691
+ return resolveComponentUncached(document, componentId, options, drawn);
1660
1692
  const cached = cache.components.get(componentId);
1661
1693
  if (cached !== undefined && cached.signature === cacheSignature(cache, cached.componentIds) && reusable(cached.result)) {
1662
1694
  cache.stats.hits += 1;
@@ -22,18 +22,23 @@ const encoder = new TextEncoder();
22
22
  export function sha256Hex(input) {
23
23
  const bytes = typeof input === "string" ? encoder.encode(input) : input;
24
24
  // The message, a 1 bit, zeros, and the bit length in the last 8 bytes, in 64-byte blocks.
25
- const padded = new Uint8Array((((bytes.length + 8) >> 6) + 1) << 6);
26
- padded.set(bytes);
27
- padded[bytes.length] = 0x80;
28
- const view = new DataView(padded.buffer);
25
+ const complete = bytes.length - bytes.length % 64;
26
+ const remainder = bytes.length - complete;
27
+ const tail = new Uint8Array(remainder < 56 ? 64 : 128);
28
+ tail.set(bytes.subarray(complete));
29
+ tail[remainder] = 0x80;
30
+ const blocks = new DataView(bytes.buffer, bytes.byteOffset, complete);
31
+ const padding = new DataView(tail.buffer);
29
32
  const bits = bytes.length * 8;
30
- view.setUint32(padded.length - 8, Math.floor(bits / 0x1_0000_0000));
31
- view.setUint32(padded.length - 4, bits >>> 0);
33
+ padding.setUint32(tail.length - 8, Math.floor(bits / 0x1_0000_0000));
34
+ padding.setUint32(tail.length - 4, bits >>> 0);
32
35
  let h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372, h3 = 0xa54ff53a;
33
36
  let h4 = 0x510e527f, h5 = 0x9b05688c, h6 = 0x1f83d9ab, h7 = 0x5be0cd19;
34
- for (let offset = 0; offset < padded.length; offset += 64) {
37
+ for (let offset = 0; offset < complete + tail.length; offset += 64) {
38
+ const view = offset < complete ? blocks : padding;
39
+ const at = offset < complete ? offset : offset - complete;
35
40
  for (let index = 0; index < 16; index += 1)
36
- words[index] = view.getUint32(offset + index * 4);
41
+ words[index] = view.getUint32(at + index * 4);
37
42
  for (let index = 16; index < 64; index += 1) {
38
43
  const before = words[index - 15];
39
44
  const near = words[index - 2];