@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
package/dist/report.js CHANGED
@@ -1,36 +1,180 @@
1
- /** Groups entries by kind and description, summing counts and keeping unique layer IDs. */
1
+ /** The most layer IDs a grouped entry keeps as examples. */
2
+ export const EXAMPLE_IDS = 5;
3
+ /** The most distinct values a grouped entry lists in place of one varying part of its description. */
4
+ const LISTED = 3;
5
+ // The parts of a description that vary between entries of one kind: quoted names (with escaped quotes inside), Figma
6
+ // node IDs, numbers and Figma's upper-case enum values ("fill 2 blend mode LINEAR_BURN", "override field \"size\"").
7
+ // Entries that differ only in these parts group.
8
+ const QUOTED = /"(?:[^"\\]|\\.)*"/y;
9
+ const UNQUOTED = /\b\d+:\d+\b|-?\b\d+(?:\.\d+)?\b|\b[A-Z][A-Z\d]*_[A-Z\d_]*\b|\b[A-Z]{2,}[A-Z\d]*\b/g;
10
+ /**
11
+ * Splits a description into its varying parts and the literal text around them (`literals` has one more item). A
12
+ * quote with no closing quote after it is literal text, and so is every quote after it, so the scan stays linear.
13
+ */
14
+ function varying(what) {
15
+ const literals = [], parts = [];
16
+ let literal = '', at = 0;
17
+ const unquoted = (end) => {
18
+ const text = what.slice(at, end);
19
+ let last = 0;
20
+ for (const m of text.matchAll(UNQUOTED)) {
21
+ literals.push(literal + text.slice(last, m.index));
22
+ parts.push(m[0]);
23
+ literal = '';
24
+ last = m.index + m[0].length;
25
+ }
26
+ literal += text.slice(last);
27
+ at = end;
28
+ };
29
+ for (let quote = what.indexOf('"'); quote !== -1; quote = what.indexOf('"', at)) {
30
+ QUOTED.lastIndex = quote;
31
+ const m = QUOTED.exec(what);
32
+ if (!m)
33
+ break;
34
+ unquoted(quote);
35
+ literals.push(literal);
36
+ parts.push(m[0]);
37
+ literal = '';
38
+ at = quote + m[0].length;
39
+ }
40
+ unquoted(what.length);
41
+ literals.push(literal);
42
+ return { literals, parts };
43
+ }
44
+ /** A reader entry's description and its occurrence count, which the reader gives as a field when it is more than one. */
45
+ export function readerCount(entry) {
46
+ return { what: entry.reason, count: entry.count ?? 1 };
47
+ }
48
+ /** Lists a part's distinct values: all of them up to `LISTED`, then the first ones and how many more. */
49
+ function listed(values) {
50
+ return values.length <= LISTED ? values.join(', ') : `${values.slice(0, LISTED).join(', ')} and ${values.length - LISTED} more`;
51
+ }
52
+ /**
53
+ * Groups entries by kind and description, summing counts and keeping up to `EXAMPLE_IDS` unique layer IDs. Entries
54
+ * that are not fonts also group when their descriptions differ only in quoted names, numbers or upper-case enum values;
55
+ * the grouped description lists each varying part's values in order of appearance.
56
+ */
2
57
  export function grouped(entries) {
3
58
  const out = new Map();
4
59
  for (const e of entries) {
5
- const key = `${e.kind}\u0000${e.what}`, had = out.get(key);
60
+ const split = e.kind === 'font' ? null : varying(e.what);
61
+ const key = `${e.kind}\u0000${split ? split.literals.join('\u0001') : e.what}`, had = out.get(key);
62
+ const parts = split && split.parts;
6
63
  if (had) {
7
- had.count += e.count;
8
- if (e.ids)
9
- (had.ids ??= []).push(...e.ids);
64
+ had.entry.count += e.count;
65
+ if (e.assetIds)
66
+ (had.entry.assetIds ??= []).push(...e.assetIds);
67
+ had.parts?.forEach((values, i) => values.add(parts[i]));
10
68
  }
11
69
  else
12
- out.set(key, { ...e, ...(e.ids && { ids: [...e.ids] }) });
70
+ out.set(key, { entry: { ...e, ...(e.assetIds && { assetIds: [...e.assetIds] }) }, ids: new Set(), parts: parts && parts.map(p => new Set([p])) });
71
+ const { ids } = out.get(key);
72
+ for (const id of e.ids ?? [])
73
+ if (ids.size < EXAMPLE_IDS)
74
+ ids.add(id);
75
+ }
76
+ return [...out.values()].map(({ entry, ids, parts }) => {
77
+ if (parts?.some(values => values.size > 1)) {
78
+ const { literals } = varying(entry.what);
79
+ entry.what = literals.map((text, i) => i < parts.length ? text + listed([...parts[i]]) : text).join('');
80
+ }
81
+ if (entry.assetIds)
82
+ entry.assetIds = [...new Set(entry.assetIds)];
83
+ if (ids.size)
84
+ entry.ids = [...ids];
85
+ else
86
+ delete entry.ids;
87
+ return entry;
88
+ });
89
+ }
90
+ /** Report descriptions of Figma features the importer leaves out without converting any part of them. */
91
+ export const DROPPED_FEATURES = {
92
+ interactions: 'prototype interactions are not imported',
93
+ };
94
+ const present = (value) => Array.isArray(value) ? value.some(item => item?.isDeleted !== true) : typeof value === 'string' && value.trim() !== '';
95
+ const guidOf = (value) => Number.isInteger(value?.sessionID) && Number.isInteger(value?.localID) ? `${value.sessionID}:${value.localID}` : undefined;
96
+ /**
97
+ * Describes what a Figma layer the import left out loses with it. That layer has no layer of its own in the result to
98
+ * point to, so the description names it.
99
+ * @param what - What is lost.
100
+ * @param name - The Figma layer's name, or its type when it has none.
101
+ * @returns The description.
102
+ */
103
+ export const onLeftOutLayer = (what, name) => `${what} for the left-out layer ${JSON.stringify(name)}`;
104
+ /**
105
+ * Lists the Figma nodes the import left out with no imported copy. The reader's omitted subtrees also hold content
106
+ * that is imported elsewhere, such as a slot's content frame, which is imported as the content of the instances that
107
+ * fill the slot; a node that is imported, or holds a node that is, is not left out.
108
+ * @param sources - The reader's tree, its omitted subtrees and the nodes it imported.
109
+ * @returns The Figma IDs of the left-out nodes.
110
+ */
111
+ export function leftOutIds(sources) {
112
+ const ids = new Set(), pending = [...sources.omittedSubtrees];
113
+ while (pending.length) {
114
+ const node = pending.pop();
115
+ if (ids.has(node.id))
116
+ continue;
117
+ ids.add(node.id);
118
+ pending.push(...node.children);
119
+ }
120
+ for (const { figma } of sources.imported)
121
+ for (let at = figma; at && ids.delete(at.id); at = at.parentId === undefined ? undefined : sources.tree.nodes.get(at.parentId))
122
+ ;
123
+ return ids;
124
+ }
125
+ /**
126
+ * Unsupported features in source order. Linking supplies their final layer IDs later, except on left-out layers,
127
+ * whose entries name the layer instead.
128
+ */
129
+ export function* droppedFeatures(changes, leftOut) {
130
+ for (const change of changes ?? []) {
131
+ const n = change, figmaId = guidOf(n?.guid);
132
+ if (figmaId === undefined)
133
+ continue;
134
+ const named = leftOut.has(figmaId);
135
+ if (present(n.prototypeInteractions))
136
+ yield { figmaId, leftOut: named,
137
+ what: named ? onLeftOutLayer(DROPPED_FEATURES.interactions, typeof n.name === 'string' && n.name ? n.name : String(n.type)) : DROPPED_FEATURES.interactions };
13
138
  }
14
- for (const e of out.values())
15
- if (e.ids)
16
- e.ids = [...new Set(e.ids)];
17
- return [...out.values()];
18
139
  }
19
140
  /** Builds a lookup from reader IDs to their converted layers. */
20
141
  export function layersBySource(document) {
21
142
  const ids = new Map();
22
- for (const model of document.models) {
23
- const { sourceId } = model;
24
- if (sourceId === undefined)
25
- continue;
26
- const found = ids.get(sourceId);
27
- if (found)
28
- found.push(model.id);
29
- else
30
- ids.set(sourceId, [model.id]);
31
- }
143
+ for (const model of document.models)
144
+ indexLayer(ids, model);
32
145
  return ids;
33
146
  }
147
+ function indexLayer(ids, model) {
148
+ if (model.sourceId === undefined)
149
+ return;
150
+ const found = ids.get(model.sourceId);
151
+ if (found)
152
+ found.push(model.id);
153
+ else
154
+ ids.set(model.sourceId, [model.id]);
155
+ }
156
+ /** Collect file diagnostics and strip reader IDs before handing the models to the editor. */
157
+ export function figmaReportLayers(document, file) {
158
+ const bySource = new Map(), pages = [];
159
+ let derive = !!document.shared;
160
+ const models = document.models;
161
+ for (const [i, layer] of models.entries()) {
162
+ let model = layer;
163
+ indexLayer(bySource, model);
164
+ if (model.kind === 'page')
165
+ pages.push(model.id);
166
+ if (file) {
167
+ // A copy without the reader ID: deleting a field leaves V8 a slow, larger hash table for the record.
168
+ if (Object.hasOwn(model, 'sourceId')) {
169
+ const { sourceId: _, ...rest } = model;
170
+ models[i] = model = rest;
171
+ }
172
+ if (model.kind === 'frame' && (model.variantSet || model.props))
173
+ derive = true;
174
+ }
175
+ }
176
+ return { bySource, pages, derive };
177
+ }
34
178
  /** Turns adapter diagnostics into import reports. */
35
179
  export function convertEntries(report, details = false) {
36
180
  const entries = (counts, category, kind, prefix = '') => [...counts].map(([what, count]) => {
@@ -52,18 +196,20 @@ export function convertEntries(report, details = false) {
52
196
  */
53
197
  export function fontEntries(document) {
54
198
  const entries = [];
199
+ for (const m of document.models)
200
+ collectFaces(m, entries);
201
+ return entries;
202
+ }
203
+ function collectFaces(m, entries) {
55
204
  function faces(styles, id) {
56
205
  for (const what of new Set(styles?.map(s => s.family + '/' + s.style)))
57
206
  entries.push({ kind: 'font', what, count: 1, ids: [id] });
58
207
  }
59
- for (const m of document.models) {
60
- if (m.kind === 'page')
61
- continue;
62
- if (m.styles)
63
- faces(m.styles, m.id);
64
- for (const [path, override] of Object.entries(m.overrides ?? {}))
65
- if (override.styles)
66
- faces(override.styles, m.id + ';' + path);
67
- }
68
- return entries;
208
+ if (m.kind === 'page')
209
+ return;
210
+ if (m.styles)
211
+ faces(m.styles, m.id);
212
+ for (const [path, override] of Object.entries(m.overrides ?? {}))
213
+ if (override.styles)
214
+ faces(override.styles, m.id + ';' + path);
69
215
  }
@@ -0,0 +1,7 @@
1
+ import type { DocumentJSON } from '@moondraft/editor/schema';
2
+ /**
3
+ * Writes the compact JSON of an imported document in chunks suitable for a file or stream.
4
+ * @param document - The plain document returned by the importer.
5
+ * @returns Strings in JSON.stringify order, with one layer or resource encoded at a time.
6
+ */
7
+ export declare function serializeImportDocument(document: DocumentJSON): Generator<string>;
@@ -0,0 +1,79 @@
1
+ const CHUNK = 64 * 1024;
2
+ // Keep large image URLs out of the encoder's temporary strings. Align chunk boundaries so
3
+ // JSON.stringify leaves valid surrogate pairs together and escapes lone surrogates as usual.
4
+ function* assetFields(asset) {
5
+ yield '{';
6
+ let separator = '';
7
+ for (const [key, value] of Object.entries(asset)) {
8
+ if (value === undefined)
9
+ continue;
10
+ yield separator + JSON.stringify(key) + ':';
11
+ separator = ',';
12
+ if (typeof value !== 'string' || value.length <= CHUNK) {
13
+ yield JSON.stringify(value);
14
+ continue;
15
+ }
16
+ yield '"';
17
+ for (let start = 0; start < value.length;) {
18
+ let end = Math.min(start + CHUNK, value.length);
19
+ const last = value.charCodeAt(end - 1);
20
+ if (end < value.length && last >= 0xd800 && last <= 0xdbff)
21
+ end--;
22
+ const piece = value.slice(start, end);
23
+ yield /["\\\u0000-\u001f\ud800-\udfff]/.test(piece) ? JSON.stringify(piece).slice(1, -1) : piece;
24
+ start = end;
25
+ }
26
+ yield '"';
27
+ }
28
+ yield '}';
29
+ }
30
+ function* documentParts(document) {
31
+ yield '{';
32
+ let comma = '';
33
+ for (const [key, value] of Object.entries(document)) {
34
+ if (value === undefined)
35
+ continue;
36
+ yield comma + JSON.stringify(key) + ':';
37
+ comma = ',';
38
+ let separator = '';
39
+ if (Array.isArray(value)) {
40
+ yield '[';
41
+ for (const item of value) {
42
+ yield separator + (JSON.stringify(item) ?? 'null');
43
+ separator = ',';
44
+ }
45
+ yield ']';
46
+ }
47
+ else if (key === 'assets' && document.assets) {
48
+ yield '{';
49
+ for (const [id, asset] of Object.entries(document.assets)) {
50
+ if (asset === undefined)
51
+ continue;
52
+ yield separator + JSON.stringify(id) + ':';
53
+ yield* assetFields(asset);
54
+ separator = ',';
55
+ }
56
+ yield '}';
57
+ }
58
+ else
59
+ yield JSON.stringify(value);
60
+ }
61
+ yield '}';
62
+ }
63
+ /**
64
+ * Writes the compact JSON of an imported document in chunks suitable for a file or stream.
65
+ * @param document - The plain document returned by the importer.
66
+ * @returns Strings in JSON.stringify order, with one layer or resource encoded at a time.
67
+ */
68
+ export function* serializeImportDocument(document) {
69
+ let chunk = '';
70
+ for (const part of documentParts(document)) {
71
+ chunk += part;
72
+ if (chunk.length >= CHUNK) {
73
+ yield chunk;
74
+ chunk = '';
75
+ }
76
+ }
77
+ if (chunk)
78
+ yield chunk;
79
+ }
@@ -1,3 +1,4 @@
1
+ import { type RootArrayItem } from "../kiwi/message.ts";
1
2
  import type { KiwiObject, KiwiSchema } from "../kiwi/types.ts";
2
3
  /**
3
4
  * The 8-byte names a Kiwi container may start with: Figma design files and
@@ -23,6 +24,8 @@ export interface KiwiContainer {
23
24
  readonly message: KiwiObject;
24
25
  }
25
26
  export interface KiwiContainerOptions {
27
+ /** Allows a file importer to compact each decoded root array item before reading the next. */
28
+ readonly onRootArrayItem?: RootArrayItem;
26
29
  /** Defaults to `FIGMA_READ_LIMITS.maxDecompressedChunkBytes`. */
27
30
  readonly maxDecompressedChunkBytes?: number;
28
31
  }
@@ -56,6 +56,6 @@ export function readKiwiContainer(bytes, options = {}) {
56
56
  throw new FigmaReadError("too-few-chunks", `the container has ${chunks.length} chunk${chunks.length === 1 ? "" : "s"}, but needs a schema and a message`, at);
57
57
  }
58
58
  const schema = decodeKiwiSchema(decompressChunk(chunks[0], chunkOffsets[0], maxBytes));
59
- const message = decodeKiwiMessage(schema, FIGMA_MESSAGE_ROOT_TYPE, decompressChunk(chunks[1], chunkOffsets[1], maxBytes));
59
+ const message = decodeKiwiMessage(schema, FIGMA_MESSAGE_ROOT_TYPE, decompressChunk(chunks[1], chunkOffsets[1], maxBytes), options.onRootArrayItem);
60
60
  return { header: { magic, version }, chunks, schema, message };
61
61
  }
@@ -40,6 +40,9 @@ export function readFigFile(bytes, options = {}) {
40
40
  }
41
41
  const images = new Map();
42
42
  for (const [name, data] of entries) {
43
+ const video = /^videos\/([0-9a-f]{40})(?:\.(?:mp4|webm|mov))?$/i.exec(name);
44
+ if (video)
45
+ images.set(video[1].toLowerCase(), data);
43
46
  if (name.startsWith(IMAGES_FOLDER) && name.length > IMAGES_FOLDER.length && !name.endsWith("/")) {
44
47
  images.set(name.slice(IMAGES_FOLDER.length), data);
45
48
  }
@@ -1,11 +1,24 @@
1
- import type { SceneNode } from "../../model/index.ts";
1
+ import type { SceneNode, TransformMatrix } from "../../model/index.ts";
2
+ export interface FigmaImageCrop {
3
+ readonly matrix: TransformMatrix;
4
+ readonly aspect?: number;
5
+ }
2
6
  /** Marks a Taco shadow as one Figma shows behind its node. */
3
7
  export declare function markShadowBehind(shadow: object): void;
4
8
  /** Marks a Taco image paint as one Figma tiles at `scale`. */
5
9
  export declare function markTile(paint: object, scale: number): void;
10
+ /** Carries a Figma matrix from layer UVs to image UVs to the adapter. */
11
+ export declare function markImageCrop(paint: object, crop: FigmaImageCrop): void;
12
+ export declare function imageCropOf(paint: unknown): FigmaImageCrop | undefined;
13
+ /** Reads tiling directly from a region paint, which has no layer metadata index. */
14
+ export declare function imageTileOf(paint: object): number | undefined;
15
+ /** Includes the crop when comparing paints for instance and variant overrides. */
16
+ export declare function withImageCrop(_key: string, value: unknown): unknown;
6
17
  /** Moves a mark to a copy of the marked object. */
7
18
  export declare function moveMark(from: object, to: object): void;
8
19
  /** Adds `data` to the layer's `metadata.figma`. */
9
20
  export declare function carry(node: SceneNode, data: NonNullable<SceneNode["metadata"]>): void;
21
+ /** Clears a layer's constraints where Figma does not apply them. */
22
+ export declare function clearConstraints(node: SceneNode): void;
10
23
  /** Carries the marks on a converted layer's shadows and fills into its metadata. */
11
24
  export declare function carryMarks(node: SceneNode): void;
@@ -1,3 +1,4 @@
1
+ import { isObject } from "./fields.js";
1
2
  const marks = new WeakMap();
2
3
  /** Marks a Taco shadow as one Figma shows behind its node. */
3
4
  export function markShadowBehind(shadow) {
@@ -7,6 +8,22 @@ export function markShadowBehind(shadow) {
7
8
  export function markTile(paint, scale) {
8
9
  marks.set(paint, { tile: scale });
9
10
  }
11
+ /** Carries a Figma matrix from layer UVs to image UVs to the adapter. */
12
+ export function markImageCrop(paint, crop) {
13
+ marks.set(paint, { crop });
14
+ }
15
+ export function imageCropOf(paint) {
16
+ return paint !== null && typeof paint === "object" ? marks.get(paint)?.crop : undefined;
17
+ }
18
+ /** Reads tiling directly from a region paint, which has no layer metadata index. */
19
+ export function imageTileOf(paint) {
20
+ return marks.get(paint)?.tile;
21
+ }
22
+ /** Includes the crop when comparing paints for instance and variant overrides. */
23
+ export function withImageCrop(_key, value) {
24
+ const crop = imageCropOf(value);
25
+ return crop ? { ...value, crop } : value;
26
+ }
10
27
  /** Moves a mark to a copy of the marked object. */
11
28
  export function moveMark(from, to) {
12
29
  const mark = marks.get(from);
@@ -19,12 +36,28 @@ export function carry(node, data) {
19
36
  const had = typeof figma === "object" && figma !== null && !Array.isArray(figma) ? figma : {};
20
37
  Object.assign(node, { metadata: { ...metadata, figma: { ...had, ...data } } });
21
38
  }
39
+ /** Clears a layer's constraints where Figma does not apply them. */
40
+ export function clearConstraints(node) {
41
+ if ("constraints" in node)
42
+ delete node.constraints;
43
+ if (node.type !== "group" || node.metadata === undefined)
44
+ return;
45
+ const { figma, ...rest } = node.metadata;
46
+ if (!isObject(figma) || !Object.hasOwn(figma, "groupConstraints"))
47
+ return;
48
+ const { groupConstraints: _constraints, ...remaining } = figma;
49
+ const metadata = Object.keys(remaining).length > 0 ? { ...rest, figma: remaining } : rest;
50
+ if (Object.keys(metadata).length > 0)
51
+ Object.assign(node, { metadata });
52
+ else
53
+ delete node.metadata;
54
+ }
22
55
  /** Carries the marks on a converted layer's shadows and fills into its metadata. */
23
56
  export function carryMarks(node) {
24
57
  const style = node.style;
25
58
  const behind = (style?.shadows ?? []).flatMap((shadow, index) => marks.get(shadow)?.behind === true ? [index] : []);
26
59
  const tiles = (style?.fills ?? []).flatMap((paint, index) => {
27
- const scale = marks.get(paint)?.tile;
60
+ const scale = imageTileOf(paint);
28
61
  return scale === undefined ? [] : [[index, scale]];
29
62
  });
30
63
  if (behind.length === 0 && tiles.length === 0)
@@ -30,11 +30,16 @@ export declare function propertyNameOf(name: string, taken: ReadonlySet<string>)
30
30
  * with its `preferredValues` mapped the same way and its `slotPropConfig`
31
31
  * settings (`slotSettingsOf`); its default content is the
32
32
  * frames bound to it. VARIANT defs are not properties here: each variant
33
- * imports as its own component. Other types are reported, and so is a name
33
+ * imports as its own component. A deleted def (one with neither a type nor a
34
+ * name, as Figma keeps it after the property is removed) is skipped without a
35
+ * report. Other types are reported, and so is a name
34
36
  * changed to be unique or
35
- * to drop characters no name can hold (`propertyNameOf`).
37
+ * to drop characters no name can hold (`propertyNameOf`). Each dropped
38
+ * preferred value is reported once, not once per variant that reads the def:
39
+ * `reported` holds the defs already reported, so share one set across the
40
+ * symbols of an import.
36
41
  */
37
- export declare function propertiesOf(symbol: FigmaTreeNode, nodes: ReadonlyMap<string, FigmaTreeNode>, componentOf: (symbolId: string) => ComponentId | undefined, componentsByKey: ComponentsByKey, report: PropertyReport): ImportedProperty[];
42
+ export declare function propertiesOf(symbol: FigmaTreeNode, nodes: ReadonlyMap<string, FigmaTreeNode>, componentOf: (symbolId: string) => ComponentId | undefined, componentsByKey: ComponentsByKey, report: PropertyReport, reported?: WeakSet<FigmaObject>): ImportedProperty[];
38
43
  /** The Taco components a Figma component key names: a COMPONENT key its SYMBOL, a STATE_GROUP key its set's variants. */
39
44
  export type ComponentsByKey = (type: "COMPONENT" | "STATE_GROUP", key: string) => readonly ComponentId[];
40
45
  /**
@@ -63,6 +68,7 @@ export declare function variantDefIds(symbol: FigmaTreeNode, nodes: ReadonlyMap<
63
68
  export interface AssignedValue {
64
69
  readonly bool?: boolean;
65
70
  readonly text?: string;
71
+ readonly textData?: FigmaObject;
66
72
  /** The SYMBOL an instance swap value names. */
67
73
  readonly symbolId?: string;
68
74
  }
@@ -81,4 +87,4 @@ export declare function assignedValueOf(assignment: FigmaObject, at: string): As
81
87
  * in the message, or a swap `leftOutSwap` gives a reason to leave out (it
82
88
  * would nest a component in itself), is reported and left out.
83
89
  */
84
- export declare function assignedPropertyValues(list: readonly unknown[] | undefined, properties: readonly ImportedProperty[], variantDefs: ReadonlySet<string>, componentOf: (symbolId: string) => ComponentId | undefined, leftOutSwap: (symbolId: string, property: ComponentPropertyId) => string | undefined, where: string, report: PropertyReport): Record<string, ComponentPropertyValue>;
90
+ export declare function assignedPropertyValues(list: readonly unknown[] | undefined, properties: readonly ImportedProperty[], variantDefs: ReadonlySet<string>, componentOf: (symbolId: string) => ComponentId | undefined, leftOutSwap: (symbolId: string, property: ComponentPropertyId) => string | undefined, where: string, report: PropertyReport, textAssignment?: (id: ComponentPropertyId, data: FigmaObject, characters: string) => void): Record<string, ComponentPropertyValue>;
@@ -50,11 +50,16 @@ function setDefsOf(symbol, nodes) {
50
50
  * with its `preferredValues` mapped the same way and its `slotPropConfig`
51
51
  * settings (`slotSettingsOf`); its default content is the
52
52
  * frames bound to it. VARIANT defs are not properties here: each variant
53
- * imports as its own component. Other types are reported, and so is a name
53
+ * imports as its own component. A deleted def (one with neither a type nor a
54
+ * name, as Figma keeps it after the property is removed) is skipped without a
55
+ * report. Other types are reported, and so is a name
54
56
  * changed to be unique or
55
- * to drop characters no name can hold (`propertyNameOf`).
57
+ * to drop characters no name can hold (`propertyNameOf`). Each dropped
58
+ * preferred value is reported once, not once per variant that reads the def:
59
+ * `reported` holds the defs already reported, so share one set across the
60
+ * symbols of an import.
56
61
  */
57
- export function propertiesOf(symbol, nodes, componentOf, componentsByKey, report) {
62
+ export function propertiesOf(symbol, nodes, componentOf, componentsByKey, report, reported = new WeakSet()) {
58
63
  const setDefs = setDefsOf(symbol, nodes);
59
64
  const where = `node ${symbol.id} componentPropDefs`;
60
65
  const names = new Set();
@@ -62,9 +67,11 @@ export function propertiesOf(symbol, nodes, componentOf, componentsByKey, report
62
67
  const properties = [];
63
68
  for (const [ownId, own] of defsById(symbol)) {
64
69
  const parentId = own["parentPropDefId"] === undefined ? undefined : guidText(own["parentPropDefId"], where);
70
+ // The def whose preferred values this reading takes: the variant's own when it has some, else the set's.
71
+ const source = own["preferredValues"] !== undefined ? own : (parentId === undefined ? undefined : setDefs.get(parentId)) ?? own;
65
72
  const def = { ...(parentId === undefined ? {} : setDefs.get(parentId)), ...own };
66
73
  const type = field(def, "type", "string", where);
67
- if (type === "VARIANT")
74
+ if (type === "VARIANT" || (type === undefined && def["name"] === undefined))
68
75
  continue;
69
76
  const figmaName = field(def, "name", "string", where) ?? "";
70
77
  const initial = field(def, "initialValue", "object", where) ?? {};
@@ -86,12 +93,12 @@ export function propertiesOf(symbol, nodes, componentOf, componentsByKey, report
86
93
  report("property-left-out", "an instance swap property is left out: its default component is not in the message");
87
94
  continue;
88
95
  }
89
- const preferred = preferredOf(def, componentsByKey, where, report);
96
+ const preferred = preferredOf(def, componentsByKey, where, onceFor(source, reported, report));
90
97
  definition = { ...base, kind: "instance", defaultValue: component, ...(preferred.length === 0 ? {} : { preferred }) };
91
98
  }
92
99
  else if (type === "SLOT") {
93
100
  // The default content is the bound frames' own children, so a slot has no default value.
94
- const preferred = preferredOf(def, componentsByKey, where, report, "a slot");
101
+ const preferred = preferredOf(def, componentsByKey, where, onceFor(source, reported, report), "a slot");
95
102
  definition = { ...base, kind: "slot", ...(preferred.length === 0 ? {} : { preferred }), ...slotSettingsOf(def, where, report) };
96
103
  }
97
104
  else {
@@ -169,11 +176,16 @@ export function componentsByKeyOf(nodes, componentOf) {
169
176
  return members.flatMap((member) => componentOf(member.id) ?? []);
170
177
  };
171
178
  }
179
+ /** `report` for the first reading of `def` that reports anything, and a report that drops everything for later ones. */
180
+ function onceFor(def, reported, report) {
181
+ if (reported.has(def))
182
+ return () => undefined;
183
+ return (kind, reason) => { reported.add(def); report(kind, reason); };
184
+ }
172
185
  /**
173
186
  * The components an INSTANCE_SWAP or SLOT def's `preferredValues.instanceSwapValues`
174
187
  * name, in order and each once (`what` names the property in the report). A key of a component the import does not
175
- * hold, or of another type, is dropped and reported each time a symbol
176
- * reads the def, so a set's def counts once per variant.
188
+ * hold, or of another type, is dropped and reported (`propertiesOf` reports them for one reading of the def only).
177
189
  */
178
190
  function preferredOf(def, componentsByKey, where, report, what = "an instance swap") {
179
191
  const values = field(def, "preferredValues", "object", where);
@@ -259,13 +271,15 @@ export function assignedValueOf(assignment, at) {
259
271
  const varValue = field(assignment, "varValue", "object", at);
260
272
  const varAt = `${at}.varValue.value`;
261
273
  const held = (varValue === undefined ? undefined : field(varValue, "value", "object", `${at}.varValue`)) ?? {};
262
- const textOf = (object, where) => (object === undefined ? undefined : field(object, "characters", "string", where));
263
274
  const bool = field(value, "boolValue", "boolean", at) ?? field(held, "boolValue", "boolean", varAt);
264
- const text = textOf(field(value, "textValue", "object", at), at) ?? textOf(field(held, "textDataValue", "object", varAt), varAt);
275
+ const plain = field(value, "textValue", "object", at);
276
+ const legacyText = plain && field(plain, "characters", "string", at);
277
+ const textData = legacyText === undefined ? field(held, "textDataValue", "object", varAt) : plain;
278
+ const text = legacyText ?? (textData && field(textData, "characters", "string", varAt));
265
279
  const swap = field(held, "symbolIdValue", "object", varAt);
266
280
  const symbolId = value["guidValue"] !== undefined ? guidText(value["guidValue"], at)
267
281
  : swap?.["guid"] !== undefined ? guidText(swap["guid"], `${varAt}.symbolIdValue`) : undefined;
268
- return { ...(bool === undefined ? {} : { bool }), ...(text === undefined ? {} : { text }), ...(symbolId === undefined ? {} : { symbolId }) };
282
+ return { ...(bool === undefined ? {} : { bool }), ...(text === undefined ? {} : { text, textData: textData }), ...(symbolId === undefined ? {} : { symbolId }) };
269
283
  }
270
284
  /**
271
285
  * `componentPropAssignments` as Taco values of `properties`. A VARIANT value
@@ -275,7 +289,7 @@ export function assignedValueOf(assignment, at) {
275
289
  * in the message, or a swap `leftOutSwap` gives a reason to leave out (it
276
290
  * would nest a component in itself), is reported and left out.
277
291
  */
278
- export function assignedPropertyValues(list, properties, variantDefs, componentOf, leftOutSwap, where, report) {
292
+ export function assignedPropertyValues(list, properties, variantDefs, componentOf, leftOutSwap, where, report, textAssignment) {
279
293
  const values = {};
280
294
  (list ?? []).forEach((assignment, index) => {
281
295
  const at = `${where} componentPropAssignments[${String(index)}]`;
@@ -294,8 +308,10 @@ export function assignedPropertyValues(list, properties, variantDefs, componentO
294
308
  const value = assignedValueOf(assignment, at);
295
309
  if (definition.kind === "boolean" && value.bool !== undefined)
296
310
  values[definition.id] = value.bool;
297
- else if (definition.kind === "text" && value.text !== undefined)
311
+ else if (definition.kind === "text" && value.text !== undefined) {
298
312
  values[definition.id] = value.text;
313
+ textAssignment?.(definition.id, value.textData, value.text);
314
+ }
299
315
  else if (definition.kind === "instance" && value.symbolId !== undefined) {
300
316
  const component = componentOf(value.symbolId);
301
317
  const leftOut = component === undefined ? undefined : leftOutSwap(value.symbolId, definition.id);
@@ -18,6 +18,8 @@ export interface ComponentSetInput {
18
18
  /** Every imported SYMBOL's component, in import order. */
19
19
  readonly variants: readonly ImportedVariant[];
20
20
  readonly figmaNodes: ReadonlyMap<string, FigmaTreeNode>;
21
+ /** Layers that carry source-specific metadata and must keep their identity across variants. */
22
+ readonly distinctLayers?: ReadonlySet<NodeId>;
21
23
  readonly newId: () => NodeId;
22
24
  /** The key of the set's component, from the set node. */
23
25
  readonly keyOf: (set: FigmaTreeNode) => string;
@@ -642,6 +642,6 @@ export function mergeComponentSets(input) {
642
642
  roots: plan.variants.map((variant) => variant.root.id), values: plan.values, properties: plan.properties,
643
643
  presence: (indices) => factored(plan.properties, indices.map((at) => plan.properties.map((property) => plan.values[at][property.id]))) || "true",
644
644
  split: (node, count, fields) => input.report(plan.set, "approximated", `split layer ${node} into ${String(count)} groups: ${fields.join(", ")}`),
645
- })), input.theme);
645
+ })), input.theme, input.distinctLayers);
646
646
  return { nodes: trees.nodes, components, componentOf, layerOf: trees.layerOf };
647
647
  }
@@ -1,16 +1,6 @@
1
1
  import type { VisualStyle } from "../../../model/index.ts";
2
2
  import type { FigmaTreeNode } from "../tree.ts";
3
3
  import type { NodeWalk } from "../walk.ts";
4
- /**
5
- * True when the renderer draws a node with `style` as a plain rectangle, the
6
- * only shape whose drop shadow it shrinks for a negative spread
7
- * (`drawShadowedRect` in packages/render-core/cpp/skia/skia_adapter.cc); every
8
- * other shape's drop shadow ignores a negative spread (`buildPreparedShadows`).
9
- * Frames are drawn so when their corners are square; rectangles also need at
10
- * most one plain solid fill or a stroke with unequal per-side weights, or they are drawn as a path
11
- * (`compileRectangle` and `needsRegionFillPaints` in packages/render-core/src/page-compiler.ts).
12
- */
13
- export declare function drawnAsPlainRectangle(style: VisualStyle, isFrame: boolean): boolean;
14
4
  /**
15
5
  * The node's Figma `effects` as Taco shadows, layer blur and background blur,
16
6
  * shadows in Figma's order; a node with an effect style takes the style's
@@ -25,7 +15,7 @@ export declare function drawnAsPlainRectangle(style: VisualStyle, isFrame: boole
25
15
  * (src/converter/style.py, `convert_effects`), absent offset, radius and
26
16
  * spread are 0. Taco has no hidden shadow or blur, one layer blur and one
27
17
  * background blur, and at most 16 shadows; what does not fit is reported.
28
- * A drop shadow keeps a negative spread only when `plainRectangle` is true
29
- * (see `drawnAsPlainRectangle`); elsewhere it is drawn with spread 0 and reported.
18
+ * Moondraft patch: a negative spread is kept on every shape; the renderer
19
+ * shrinks drop shadows and grows inner shadows' holes by it.
30
20
  */
31
- export declare function nodeEffects(node: FigmaTreeNode, walk: NodeWalk, plainRectangle?: boolean): Pick<VisualStyle, "shadows" | "layerBlur" | "backgroundBlur">;
21
+ export declare function nodeEffects(node: FigmaTreeNode, walk: NodeWalk): Pick<VisualStyle, "shadows" | "layerBlur" | "backgroundBlur">;