@moondraft/import 0.1.0 → 0.2.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 (84) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +2 -2
  3. package/SOURCE.md +229 -4
  4. package/dist/adapter/convert.d.ts +24 -2
  5. package/dist/adapter/convert.js +669 -160
  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 +12 -0
  11. package/dist/adapter/figma-handoff.js +167 -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 +14 -4
  16. package/dist/adapter/file-components.d.ts +9 -3
  17. package/dist/adapter/file-components.js +122 -32
  18. package/dist/adapter/file-resources.js +316 -27
  19. package/dist/adapter/image-crop.d.ts +18 -0
  20. package/dist/adapter/image-crop.js +30 -0
  21. package/dist/adapter/link.d.ts +5 -1
  22. package/dist/adapter/link.js +308 -104
  23. package/dist/adapter/payload.js +1 -1
  24. package/dist/adapter/variables.d.ts +2 -1
  25. package/dist/adapter/variables.js +5 -2
  26. package/dist/figma.js +167 -33
  27. package/dist/index.d.ts +1 -0
  28. package/dist/index.js +1 -0
  29. package/dist/report.d.ts +28 -1
  30. package/dist/report.js +102 -29
  31. package/dist/serialize.d.ts +7 -0
  32. package/dist/serialize.js +79 -0
  33. package/dist/taco/figma-import/container/kiwiContainer.d.ts +3 -0
  34. package/dist/taco/figma-import/container/kiwiContainer.js +1 -1
  35. package/dist/taco/figma-import/import/carry.d.ts +14 -1
  36. package/dist/taco/figma-import/import/carry.js +34 -1
  37. package/dist/taco/figma-import/import/componentProps.d.ts +10 -4
  38. package/dist/taco/figma-import/import/componentProps.js +29 -13
  39. package/dist/taco/figma-import/import/componentSets.d.ts +2 -0
  40. package/dist/taco/figma-import/import/componentSets.js +1 -1
  41. package/dist/taco/figma-import/import/converters/exportSettings.d.ts +4 -0
  42. package/dist/taco/figma-import/import/converters/exportSettings.js +49 -0
  43. package/dist/taco/figma-import/import/converters/frame.js +8 -0
  44. package/dist/taco/figma-import/import/converters/gradient.d.ts +2 -0
  45. package/dist/taco/figma-import/import/converters/gradient.js +3 -1
  46. package/dist/taco/figma-import/import/converters/group.d.ts +2 -4
  47. package/dist/taco/figma-import/import/converters/group.js +6 -15
  48. package/dist/taco/figma-import/import/converters/image.d.ts +1 -1
  49. package/dist/taco/figma-import/import/converters/image.js +22 -11
  50. package/dist/taco/figma-import/import/converters/layout.d.ts +3 -4
  51. package/dist/taco/figma-import/import/converters/layout.js +40 -21
  52. package/dist/taco/figma-import/import/converters/rectangle.d.ts +1 -1
  53. package/dist/taco/figma-import/import/converters/rectangle.js +1 -1
  54. package/dist/taco/figma-import/import/converters/section.d.ts +2 -3
  55. package/dist/taco/figma-import/import/converters/section.js +3 -9
  56. package/dist/taco/figma-import/import/converters/shared.d.ts +7 -4
  57. package/dist/taco/figma-import/import/converters/shared.js +15 -5
  58. package/dist/taco/figma-import/import/converters/text.d.ts +14 -1
  59. package/dist/taco/figma-import/import/converters/text.js +143 -12
  60. package/dist/taco/figma-import/import/converters/vector.d.ts +36 -15
  61. package/dist/taco/figma-import/import/converters/vector.js +214 -73
  62. package/dist/taco/figma-import/import/converters/vectorNetwork.d.ts +19 -3
  63. package/dist/taco/figma-import/import/converters/vectorNetwork.js +147 -29
  64. package/dist/taco/figma-import/import/instances.d.ts +25 -4
  65. package/dist/taco/figma-import/import/instances.js +324 -117
  66. package/dist/taco/figma-import/import/styles.d.ts +2 -0
  67. package/dist/taco/figma-import/import/styles.js +6 -0
  68. package/dist/taco/figma-import/import/variables.d.ts +3 -2
  69. package/dist/taco/figma-import/import/variables.js +37 -30
  70. package/dist/taco/figma-import/import/variantTrees.d.ts +1 -1
  71. package/dist/taco/figma-import/import/variantTrees.js +44 -4
  72. package/dist/taco/figma-import/import/walk.d.ts +53 -5
  73. package/dist/taco/figma-import/import/walk.js +273 -106
  74. package/dist/taco/figma-import/kiwi/message.d.ts +4 -2
  75. package/dist/taco/figma-import/kiwi/message.js +13 -11
  76. package/dist/taco/model/codec.d.ts +1 -1
  77. package/dist/taco/model/codec.js +37 -7
  78. package/dist/taco/model/component-evaluation.d.ts +2 -0
  79. package/dist/taco/model/component-evaluation.js +7 -0
  80. package/dist/taco/model/instance-resolver.d.ts +6 -2
  81. package/dist/taco/model/instance-resolver.js +48 -18
  82. package/dist/taco/model/sha256.js +13 -8
  83. package/dist/taco/model/types.d.ts +23 -1
  84. 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
  }
@@ -24,7 +24,7 @@ export function decodeKiwiMessage(schema, rootTypeName, bytes) {
24
24
  }
25
25
  const reader = new ByteReader(bytes);
26
26
  try {
27
- const value = readObject(reader, root, 1);
27
+ const value = readObject(reader, root, 1, onRootArrayItem);
28
28
  if (reader.remaining > 0) {
29
29
  throw reader.fail(`${reader.remaining} unread bytes after the ${rootTypeName}`);
30
30
  }
@@ -36,18 +36,17 @@ export function decodeKiwiMessage(schema, rootTypeName, bytes) {
36
36
  throw error;
37
37
  }
38
38
  }
39
- function readObject(reader, definition, depth) {
39
+ function readObject(reader, definition, depth, onArrayItem) {
40
40
  if (depth > KIWI_LIMITS.maxNestingDepth) {
41
41
  throw reader.fail(`nesting is deeper than KIWI_LIMITS.maxNestingDepth (${KIWI_LIMITS.maxNestingDepth})`);
42
42
  }
43
43
  const result = {};
44
44
  if (definition.kind === "STRUCT") {
45
45
  for (const field of definition.fields) {
46
- setField(result, field.name, readFieldValue(reader, field, depth));
46
+ setField(result, field.name, readFieldValue(reader, field, depth, onArrayItem));
47
47
  }
48
48
  return result;
49
49
  }
50
- const seen = new Set();
51
50
  for (;;) {
52
51
  const idOffset = reader.offset;
53
52
  const id = reader.readVarUint();
@@ -57,13 +56,12 @@ function readObject(reader, definition, depth) {
57
56
  if (field === undefined) {
58
57
  throw reader.fail(`field id ${id} is not in message ${definition.name}`, idOffset);
59
58
  }
60
- if (seen.has(id))
59
+ if (Object.hasOwn(result, field.name))
61
60
  throw reader.fail(`field ${field.name} (id ${id}) appears twice`, idOffset);
62
- seen.add(id);
63
- setField(result, field.name, readFieldValue(reader, field, depth));
61
+ setField(result, field.name, readFieldValue(reader, field, depth, onArrayItem));
64
62
  }
65
63
  }
66
- function readFieldValue(reader, field, depth) {
64
+ function readFieldValue(reader, field, depth, onArrayItem) {
67
65
  try {
68
66
  if (!field.isArray)
69
67
  return readSingle(reader, field, depth);
@@ -82,10 +80,14 @@ function readFieldValue(reader, field, depth) {
82
80
  if (length * elementBytes > reader.remaining) {
83
81
  throw reader.fail(`array length ${length} needs at least ${length * elementBytes} bytes but ${reader.remaining} remain`, lengthOffset);
84
82
  }
85
- const values = [];
83
+ // Small arrays are common in node changes. Avoid the spare slots of a growing array.
84
+ // Keep large untrusted counts incremental until their elements have actually been read.
85
+ const values = length <= 1024 ? new Array(length) : [];
86
86
  for (let index = 0; index < length; index += 1) {
87
87
  try {
88
- values.push(readSingle(reader, field, depth));
88
+ const value = readSingle(reader, field, depth);
89
+ onArrayItem?.(field.name, value);
90
+ values[index] = value;
89
91
  }
90
92
  catch (error) {
91
93
  if (error instanceof KiwiDecodeError)
@@ -140,7 +140,7 @@ export declare function assertTextStyleOverrides(value: unknown): asserts value
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,10 @@ 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 validateOpenTypeFeatures(value, path, allowEmpty = false) {
388
395
  const settings = record(value, path);
389
396
  const entries = Object.entries(settings);
390
- if (entries.length === 0) {
397
+ if (entries.length === 0 && !allowEmpty) {
391
398
  fail("INVALID_SCHEMA", "Empty OpenType feature settings must be omitted", path);
392
399
  }
393
400
  for (const [tag, rawSetting] of entries) {
@@ -558,9 +565,9 @@ function validateShadows(value, path) {
558
565
  }
559
566
  const LAYER_OVERRIDE_KEYS = [
560
567
  "conditional",
561
- "visible", "opacity", "name", "characters", "paragraphs", "textStyleId", "textStyle", "textAlign", "styleId",
568
+ "visible", "opacity", "name", "characters", "paragraphs", "textStyleId", "textStyle", "textAlign", "maxLines", "truncate", "styleId",
562
569
  "fills", "strokes", "shadows", "layerBlur", "backgroundBlur", "imageAssetId", "componentId",
563
- "sizing", "padding", "variableBindings", "propertyValues",
570
+ "clipContent", "cornerSmoothing", "layout", "sizing", "padding", "variableBindings", "propertyValues",
564
571
  ];
565
572
  /** The fields a `LayerOverride` may hold. */
566
573
  export const layerOverrideFieldNames = LAYER_OVERRIDE_KEYS;
@@ -1185,7 +1192,7 @@ function validateTextStyleOverrides(value, path) {
1185
1192
  optional(overrides.italic, `${path}.italic`, boolean);
1186
1193
  optional(overrides.underline, `${path}.underline`, boolean);
1187
1194
  optional(overrides.strikethrough, `${path}.strikethrough`, boolean);
1188
- optional(overrides.openTypeFeatures, `${path}.openTypeFeatures`, validateOpenTypeFeatures);
1195
+ optional(overrides.openTypeFeatures, `${path}.openTypeFeatures`, (value, at) => validateOpenTypeFeatures(value, at, true));
1189
1196
  optional(overrides.fontVariations, `${path}.fontVariations`, validateFontVariations);
1190
1197
  }
1191
1198
  /** Validates a standalone authored run or list-marker text-style override. */
@@ -1269,7 +1276,7 @@ function validateExportSettings(value, path) {
1269
1276
  /** The fields a `TextParagraph` takes, as the codec checks them. */
1270
1277
  export const textParagraphFieldNames = ["runs", "direction", "align", "spacingBefore", "spacingAfter", "indent", "list"];
1271
1278
  /** 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"];
1279
+ export const textRunFieldNames = ["text", "styleId", "overrides", "hyperlink"];
1273
1280
  /** Checks one `TextRun` on its own; its style reference is checked by the document. */
1274
1281
  function validateTextRun(run, runPath) {
1275
1282
  const runRecord = record(run, runPath);
@@ -1277,6 +1284,13 @@ function validateTextRun(run, runPath) {
1277
1284
  attempt(string, runRecord.text, `${runPath}.text`);
1278
1285
  optional(runRecord.styleId, `${runPath}.styleId`, nonEmptyString);
1279
1286
  optional(runRecord.overrides, `${runPath}.overrides`, validateTextStyleOverrides);
1287
+ optional(runRecord.hyperlink, `${runPath}.hyperlink`, (candidate, path) => {
1288
+ const link = record(candidate, path);
1289
+ const kind = oneOf(link.kind, ["url", "target"], `${path}.kind`);
1290
+ const field = kind === "url" ? "url" : "guid";
1291
+ exactKeys(link, ["kind", field], path);
1292
+ attempt(nonEmptyString, link[field], `${path}.${field}`);
1293
+ });
1280
1294
  }
1281
1295
  /** Checks one list marker on its own; its style reference is checked by the document. */
1282
1296
  function validateListMarker(entry, entryPath) {
@@ -1332,6 +1346,16 @@ function validateTextParagraph(paragraph, paragraphPath) {
1332
1346
  function validateLayerOverride(value, path) {
1333
1347
  const item = record(value, path);
1334
1348
  exactKeys(item, LAYER_OVERRIDE_KEYS, path);
1349
+ optional(item.clipContent, `${path}.clipContent`, boolean);
1350
+ optional(item.cornerSmoothing, `${path}.cornerSmoothing`, unitIntervalNumber);
1351
+ optional(item.layout, `${path}.layout`, (value, at) => {
1352
+ const layout = record(value, at);
1353
+ exactKeys(layout, ["kind", "gap", "align", "justify", "wrap", "wrapGap", "alignContent"], at);
1354
+ 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);
1358
+ });
1335
1359
  optional(item.conditional, `${path}.conditional`, (candidate, candidatePath) => {
1336
1360
  array(candidate, candidatePath).forEach((value, index) => {
1337
1361
  const at = `${candidatePath}[${index}]`;
@@ -1359,6 +1383,10 @@ function validateLayerOverride(value, path) {
1359
1383
  optional(item.textStyleId, `${path}.textStyleId`, nonEmptyString);
1360
1384
  optional(item.textStyle, `${path}.textStyle`, validateTextStyleOverrides);
1361
1385
  optional(item.textAlign, `${path}.textAlign`, (candidate, candidatePath) => oneOf(candidate, ["left", "center", "right", "justify"], candidatePath));
1386
+ if (item.maxLines !== null)
1387
+ optional(item.maxLines, `${path}.maxLines`, positiveInteger);
1388
+ if (item.truncate !== null)
1389
+ optional(item.truncate, `${path}.truncate`, (candidate, candidatePath) => oneOf(candidate, ["ellipsis"], candidatePath));
1362
1390
  if (item.styleId !== null)
1363
1391
  optional(item.styleId, `${path}.styleId`, nonEmptyString);
1364
1392
  optional(item.fills, `${path}.fills`, (candidate, candidatePath) => {
@@ -1641,7 +1669,7 @@ export function sceneNodeFieldNames(kind) {
1641
1669
  const variantKeys = {
1642
1670
  frame: ["constraintSize", "children", "layout", "style", "clipContent", "guides", "slot", "slotHost"],
1643
1671
  group: ["children", "clipContent"],
1644
- text: ["paragraphs", "verticalAlign", "overflow", "autoResize", "wrap", "paragraphSpacing"],
1672
+ text: ["paragraphs", "verticalAlign", "overflow", "autoResize", "wrap", "paragraphSpacing", "maxLines", "truncate"],
1645
1673
  code: [
1646
1674
  "source",
1647
1675
  "language",
@@ -1780,6 +1808,8 @@ function validateNode(value, path) {
1780
1808
  attempt((candidate, candidatePath) => oneOf(candidate, AUTO_RESIZE_MODES, candidatePath), item.autoResize, `${path}.autoResize`);
1781
1809
  attempt((candidate, candidatePath) => oneOf(candidate, ["none", "word", "character"], candidatePath), item.wrap, `${path}.wrap`);
1782
1810
  optional(item.paragraphSpacing, `${path}.paragraphSpacing`, nonNegativeNumber);
1811
+ optional(item.maxLines, `${path}.maxLines`, positiveInteger);
1812
+ optional(item.truncate, `${path}.truncate`, (candidate, candidatePath) => oneOf(candidate, ["ellipsis"], candidatePath));
1783
1813
  return;
1784
1814
  case "code": {
1785
1815
  const source = attempt(string, item.source, `${path}.source`);
@@ -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"])
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,8 @@ 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.layout && outer.layout)
648
+ merged.layout = { ...inner.layout, ...outer.layout };
641
649
  if (inner.sizing !== undefined && outer.sizing !== undefined)
642
650
  merged.sizing = { ...inner.sizing, ...outer.sizing };
643
651
  if (inner.padding !== undefined && outer.padding !== undefined)
@@ -718,7 +726,7 @@ function overriddenStyle(style, override) {
718
726
  next.styleId = override.styleId;
719
727
  changed = true;
720
728
  }
721
- for (const field of ["fills", "strokes", "shadows", "layerBlur", "backgroundBlur"]) {
729
+ for (const field of ["fills", "strokes", "shadows", "layerBlur", "backgroundBlur", "cornerSmoothing"]) {
722
730
  if (override[field] === undefined)
723
731
  continue;
724
732
  next[field] = override[field];
@@ -744,7 +752,15 @@ function withoutFillSizing(override) {
744
752
  function applyOverride(document, node, override) {
745
753
  if (override === undefined)
746
754
  return node;
755
+ if (node.type === "frame" && override.layout) {
756
+ const layout = override.layout.kind === "absolute" ? { kind: "absolute" } :
757
+ { gap: 0, align: "start", justify: "start", padding: { top: 0, right: 0, bottom: 0, left: 0 },
758
+ widthSizing: "fixed", heightSizing: "fixed", ...node.layout, ...override.layout };
759
+ node = { ...node, layout };
760
+ }
747
761
  const base = { ...node };
762
+ if (node.type === "frame" && override.clipContent !== undefined)
763
+ base.clipContent = override.clipContent;
748
764
  if (override.visible !== undefined)
749
765
  base.visible = override.visible;
750
766
  if (override.opacity !== undefined)
@@ -768,6 +784,12 @@ function applyOverride(document, node, override) {
768
784
  if (node.autoResize !== "none")
769
785
  base.frame = getDerivedAutoSizedTextFrame(document, node, paragraphs);
770
786
  }
787
+ for (const key of ["maxLines", "truncate"]) {
788
+ if (override[key] === null)
789
+ delete base[key];
790
+ else if (override[key] !== undefined)
791
+ base[key] = override[key];
792
+ }
771
793
  }
772
794
  if (node.type === "image" && override.imageAssetId !== undefined)
773
795
  base.assetId = override.imageAssetId;
@@ -1077,12 +1099,12 @@ function expandInstance(expansion, instance, virtualId, prefix, absolutePrefix,
1077
1099
  expansion.texts.push({ virtualId: layerId, sourceNodeId: nodeId, path, node: placed, ...pathInstance });
1078
1100
  }
1079
1101
  // Without layout, frames stay as stored.
1080
- if (!expansion.textOnly && placed.type === "group" && unbound.type === "group") {
1102
+ if (expansion.layout && placed.type === "group" && unbound.type === "group") {
1081
1103
  // A mode that resizes the group scales its layers, as a group resize does.
1082
1104
  scaleGroupChildren(expansion.nodes, placed, unbound.frame);
1083
1105
  fitGroup(expansion.nodes, placed);
1084
1106
  }
1085
- if (!expansion.textOnly && placed.type === "frame" && stored.type === "frame" && filled === undefined) {
1107
+ if (expansion.layout && placed.type === "frame" && stored.type === "frame" && filled === undefined) {
1086
1108
  // A computed size or a mode that resizes the frame: children follow
1087
1109
  // their constraints from the stored size, deepest frames first
1088
1110
  // (`expandNode` returns after its children). Slot content is placed
@@ -1107,7 +1129,7 @@ function expandInstance(expansion, instance, virtualId, prefix, absolutePrefix,
1107
1129
  const rootNode = applyOverride(document, computed.nodes.get(root.id) ?? root, rootOverride);
1108
1130
  const childIds = shownChildren(rootNode.children).map((childId) => expandNode(childId, [childId], depth + 1, instanceModes));
1109
1131
  putEntry(expansion.nodes, virtualId, applyVariableBindings(document, instanceFrame(instance, rootNode, virtualId, childIds), instanceModes));
1110
- if (!expansion.textOnly) {
1132
+ if (expansion.layout) {
1111
1133
  // A resized instance, or one whose size a mode changes: children follow
1112
1134
  // their constraints from the stored root size, which their positions are
1113
1135
  // relative to, whatever size an expression computes for the root. In an
@@ -1229,11 +1251,11 @@ function expandStored(expansion, nodeId, depth, parentModes, stack) {
1229
1251
  expansion.texts.push({ virtualId: nodeId, sourceNodeId: nodeId, path: [nodeId], node: placed });
1230
1252
  }
1231
1253
  // Without layout, frames stay as stored.
1232
- if (!expansion.textOnly && placed.type === "group" && stored.type === "group") {
1254
+ if (expansion.layout && placed.type === "group" && stored.type === "group") {
1233
1255
  scaleGroupChildren(expansion.nodes, placed, stored.frame);
1234
1256
  fitGroup(expansion.nodes, placed);
1235
1257
  }
1236
- if (!expansion.textOnly && placed.type === "frame" && stored.type === "frame") {
1258
+ if (expansion.layout && placed.type === "frame" && stored.type === "frame") {
1237
1259
  constrainChildren(expansion.nodes, nodeId, stored.frame, placed.frame).forEach((child) => {
1238
1260
  putEntry(expansion.nodes, child.id, child);
1239
1261
  });
@@ -1387,9 +1409,10 @@ function buildLayers(expansion, layers, id) {
1387
1409
  layers.set(id, layer);
1388
1410
  return layer;
1389
1411
  }
1390
- function resolveInstanceUncached(document, instance, cache, modes, enclosing = []) {
1391
- const expansion = expandStoredInstance(document, instance, cache, modes, enclosing, false);
1392
- layoutExpansion(expansion);
1412
+ function resolveInstanceUncached(document, instance, cache, modes, enclosing = [], layout = true) {
1413
+ const expansion = expandStoredInstance(document, instance, cache, modes, enclosing, false, layout);
1414
+ if (layout)
1415
+ layoutExpansion(expansion);
1393
1416
  const layers = new Map();
1394
1417
  const root = buildLayers(expansion, layers, instance.id);
1395
1418
  const result = { instanceId: instance.id, componentId: instance.componentId, root,
@@ -1403,7 +1426,7 @@ function resolveInstanceUncached(document, instance, cache, modes, enclosing = [
1403
1426
  return result;
1404
1427
  }
1405
1428
  /** The flattened tree of a stored instance, before layout. */
1406
- function expandStoredInstance(document, instance, cache, modes, enclosing, textOnly) {
1429
+ function expandStoredInstance(document, instance, cache, modes, enclosing, textOnly, layout = !textOnly) {
1407
1430
  const expansion = {
1408
1431
  document,
1409
1432
  instanceId: instance.id,
@@ -1417,6 +1440,7 @@ function expandStoredInstance(document, instance, cache, modes, enclosing, textO
1417
1440
  cache,
1418
1441
  content: [],
1419
1442
  textOnly,
1443
+ layout,
1420
1444
  texts: [],
1421
1445
  consulted: [],
1422
1446
  };
@@ -1501,8 +1525,10 @@ export function resolveInstance(document, instanceId, options) {
1501
1525
  const cache = options?.cache;
1502
1526
  const modes = options?.variableModes ?? inheritedVariableModes(document, instanceId);
1503
1527
  if (!isCacheState(cache))
1504
- return resolveInstanceUncached(document, node, undefined, modes);
1528
+ return resolveInstanceUncached(document, node, undefined, modes, [], options?.layout);
1505
1529
  syncCache(cache, document);
1530
+ if (!cache.retainTrees || options?.layout === false)
1531
+ return resolveInstanceUncached(document, node, cache, modes, [], options?.layout);
1506
1532
  const modesKey = `modes:${variableModesKey(document.theme, modes)}`;
1507
1533
  const entries = cache.instances.get(node) ?? equalNodeEntries(cache, node) ?? [];
1508
1534
  if (cache.lastInstanceNodes.get(instanceId)?.deref() !== node) {
@@ -1543,10 +1569,11 @@ function resolveComponentUncached(document, componentId, options, componentIds)
1543
1569
  }
1544
1570
  componentIds.push(componentId);
1545
1571
  const state = isCacheState(options?.cache) ? options.cache : undefined;
1572
+ const layout = options?.layout !== false;
1546
1573
  const resolveNested = (node) => {
1547
1574
  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]);
1575
+ ? resolveInstance(document, node.id, { ...(options?.cache && { cache: options.cache }), layout })
1576
+ : resolveInstanceUncached(document, node, state, inheritedVariableModes(document, node.id), [componentId], layout);
1550
1577
  resolvedInstanceComponents(resolved).forEach((id) => { if (!componentIds.includes(id))
1551
1578
  componentIds.push(id); });
1552
1579
  return resolved;
@@ -1604,7 +1631,7 @@ function resolveComponentUncached(document, componentId, options, componentIds)
1604
1631
  const children = node.children.filter((childId) => !computed.leftOut.has(childId));
1605
1632
  node = { ...rebound(node), children };
1606
1633
  children.forEach((childId) => collect(childId, depth + 1));
1607
- if (node.type === "frame" && stored.type === "frame") {
1634
+ if (layout && node.type === "frame" && stored.type === "frame") {
1608
1635
  // A computed size: children follow their constraints from the stored size.
1609
1636
  putEntry(nodes, nodeId, node);
1610
1637
  constrainChildren(nodes, nodeId, node.constraintSize ?? stored.frame, node.frame).forEach((child) => {
@@ -1615,12 +1642,13 @@ function resolveComponentUncached(document, componentId, options, componentIds)
1615
1642
  if (node.type !== "instance" && !isContainerNode(node))
1616
1643
  node = rebound(node);
1617
1644
  putEntry(nodes, nodeId, node);
1618
- if (node.type === "group")
1645
+ if (layout && node.type === "group")
1619
1646
  fitGroup(nodes, node);
1620
1647
  depths.set(nodeId, depth);
1621
1648
  };
1622
1649
  collect(component.rootId, 0);
1623
- settleLayout(nodes, depths);
1650
+ if (layout)
1651
+ settleLayout(nodes, depths);
1624
1652
  const visit = (nodeId) => {
1625
1653
  const node = entryOf(nodes, nodeId);
1626
1654
  if (node.type === "instance") {
@@ -1657,6 +1685,8 @@ export function resolveComponent(document, componentId, options) {
1657
1685
  return resolveComponentUncached(document, componentId, options, []);
1658
1686
  syncCache(cache, document);
1659
1687
  const drawn = [];
1688
+ if (!cache.retainTrees || options?.layout === false)
1689
+ return resolveComponentUncached(document, componentId, options, drawn);
1660
1690
  const cached = cache.components.get(componentId);
1661
1691
  if (cached !== undefined && cached.signature === cacheSignature(cache, cached.componentIds) && reusable(cached.result)) {
1662
1692
  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];
@@ -972,6 +972,14 @@ export interface GroupNode extends FramedNodeBase {
972
972
  /** A span of text sharing one style. */
973
973
  export interface TextRun {
974
974
  readonly text: string;
975
+ /** A web address or a target GUID to resolve when adapting a Figma document. */
976
+ readonly hyperlink?: {
977
+ readonly kind: "url";
978
+ readonly url: string;
979
+ } | {
980
+ readonly kind: "target";
981
+ readonly guid: string;
982
+ };
975
983
  /** The theme text style; the theme's `defaultTextStyleId` when omitted. */
976
984
  readonly styleId?: TextStyleId;
977
985
  /** Direct formatting on top of the style. */
@@ -1031,6 +1039,10 @@ export interface TextNode extends FramedNodeBase {
1031
1039
  * @since 0.40.0
1032
1040
  */
1033
1041
  readonly paragraphSpacing?: number;
1042
+ /** The most lines drawn, a positive integer; every line when left out. */
1043
+ readonly maxLines?: number;
1044
+ /** `ellipsis` ends the last drawn line with an ellipsis when `maxLines` hides lines. */
1045
+ readonly truncate?: "ellipsis";
1034
1046
  }
1035
1047
  /** Nodes that hold editable rich text. Currently only `TextNode`. */
1036
1048
  export type TextualNode = TextNode;
@@ -1702,7 +1714,7 @@ export type LayerOverrideVariableBindings = Readonly<Partial<Record<VariableProp
1702
1714
  * The changes one instance makes to one layer of its component, stored in
1703
1715
  * `InstanceNode.overrides` under the layer's path. Every field replaces the
1704
1716
  * layer's resolved value as a whole (`padding` side by side, `textStyle` member by member); a field that is
1705
- * absent follows the component. Structure (layers, layout kind and gaps, geometry of inner
1717
+ * absent follows the component. Structure (layers, geometry of inner
1706
1718
  * layers, masks, blend modes) is not overridable: that needs an edit to the
1707
1719
  * component, or Detach.
1708
1720
  *
@@ -1769,6 +1781,10 @@ export interface LayerOverride {
1769
1781
  * @since 0.36.0
1770
1782
  */
1771
1783
  readonly textAlign?: TextParagraph["align"];
1784
+ /** Text: the layer's `maxLines`; `null` takes the component's away. */
1785
+ readonly maxLines?: number | null;
1786
+ /** Text: the layer's `truncate`; `null` takes the component's away. */
1787
+ readonly truncate?: "ellipsis" | null;
1772
1788
  /** Frames and shapes: the node style to use; `null` clears the layer's. */
1773
1789
  readonly styleId?: NodeStyleId | null;
1774
1790
  readonly fills?: readonly Paint[];
@@ -1780,6 +1796,12 @@ export interface LayerOverride {
1780
1796
  readonly imageAssetId?: AssetId;
1781
1797
  /** Nested instance layers: the component to show instead (a swap). */
1782
1798
  readonly componentId?: ComponentId;
1799
+ readonly clipContent?: boolean;
1800
+ readonly cornerSmoothing?: number;
1801
+ /** Per-member stack settings. Padding sides and sizing axes have their own overrides. */
1802
+ readonly layout?: Partial<Omit<StackAutoLayout, "kind" | "padding" | "widthSizing" | "heightSizing">> & {
1803
+ readonly kind?: "absolute" | "horizontal" | "vertical";
1804
+ };
1783
1805
  /** Frame layers, and the component root for the instance's own size. */
1784
1806
  readonly sizing?: LayerSizingOverride;
1785
1807
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moondraft/import",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "description": "Editable SVG and Figma import for Moondraft.",
6
6
  "sideEffects": false,
@@ -30,6 +30,7 @@
30
30
  },
31
31
  "dependencies": {
32
32
  "@chenglou/pretext": "0.0.8",
33
+ "entities": "6.0.1",
33
34
  "fflate": "0.8.3",
34
35
  "fzstd": "0.1.1",
35
36
  "svg-pathdata": "9.0.0"
@@ -51,6 +52,6 @@
51
52
  "access": "public"
52
53
  },
53
54
  "peerDependencies": {
54
- "@moondraft/editor": ">=0.3.0 <0.4.0"
55
+ "@moondraft/editor": ">=0.4.0 <0.5.0"
55
56
  }
56
57
  }