@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
@@ -47,10 +47,10 @@ export function toPayload(converted, options = {}) {
47
47
  }
48
48
  const assets = {};
49
49
  for (const a of report.assets) {
50
- const size = doc.assets?.[a.id];
51
- assets[a.id] = { src: `data:${a.mimeType};base64,${a.data}`, ...(size?.w !== undefined ? { w: size.w } : {}), ...(size?.h !== undefined ? { h: size.h } : {}) };
50
+ const { w, h, ...asset } = doc.assets?.[a.id] ?? {};
51
+ assets[a.id] = { ...asset, ...(w !== undefined && { w }), ...(h !== undefined && { h }), src: `data:${a.mimeType};base64,${a.data}` };
52
52
  }
53
- const payload = { format: clipboard.FORMAT, version: clipboard.VERSION, client: options.client ?? 'moondraft-import', roots, nodes, assets, ...(Object.keys(mains).length ? { mains } : {}) };
53
+ const payload = { format: clipboard.FORMAT, version: clipboard.VERSION, client: options.client ?? 'moondraft-import', roots, nodes, assets, ...(doc.shared?.length && { shared: doc.shared }), ...(Object.keys(mains).length ? { mains } : {}) };
54
54
  return { payload, report };
55
55
  }
56
56
  const base64 = (bytes) => { let s = ''; for (let i = 0; i < bytes.length; i += 0x8000)
@@ -22,13 +22,14 @@ export interface VariableCollection {
22
22
  }
23
23
  /** A resolved scalar variable value. */
24
24
  export type VariableValue = number | boolean | string;
25
+ type Aliases = ReadonlyMap<string, ReadonlyMap<string, string>>;
25
26
  type Modes = Record<string, string>;
26
27
  /**
27
28
  * Builds a resolver for variables and aliases in the source model.
28
29
  * @param collections - Source collections indexed by ID.
29
30
  * @returns A resolver that takes a variable name or ID and optional collection modes.
30
31
  */
31
- export declare function variableResolver(collections?: Record<string, VariableCollection>): (name: string, modes?: Modes) => VariableValue | undefined;
32
+ export declare function variableResolver<T extends Omit<VariableCollection, 'modeOrder'> = VariableCollection>(collections?: Record<string, T>): (name: string, modes?: Modes, aliases?: Aliases) => VariableValue | undefined;
32
33
  /**
33
34
  * The collections as taco's expression evaluator reads them (it follows no aliases, and reads a chosen mode only when
34
35
  * the collection's modes table has it): each collection with a modes table (made from the modes it names when it has
@@ -39,11 +39,14 @@ function lookup(collections) {
39
39
  return resolve(byId.get(target) ?? byName.get(target), modes, seen);
40
40
  return plainValue(value) ? value : undefined;
41
41
  }
42
- function resolve(entry, modes, seen) {
42
+ function resolve(entry, modes, seen, aliases) {
43
43
  if (!entry || seen.has(entry.id))
44
44
  return undefined;
45
45
  seen.add(entry.id);
46
46
  const values = entry.variable.values ?? {}, mode = modeOf(entry, modes), fallback = entry.collection.defaultModeId;
47
+ const target = mode !== undefined && aliases?.get(entry.id)?.get(mode);
48
+ if (target)
49
+ return resolve(byId.get(target), modes, seen, aliases);
47
50
  const value = mode !== undefined && Object.hasOwn(values, mode) ? values[mode] : fallback !== undefined && Object.hasOwn(values, fallback) ? values[fallback] : undefined;
48
51
  return plain(value, modes, seen);
49
52
  }
@@ -56,7 +59,7 @@ function lookup(collections) {
56
59
  */
57
60
  export function variableResolver(collections = {}) {
58
61
  const { byName, byId, resolve } = lookup(collections);
59
- return (name, modes = {}) => resolve(byName.get(name) ?? byId.get(name), modes, new Set());
62
+ return (name, modes = {}, aliases) => resolve(byName.get(name) ?? byId.get(name), modes, new Set(), aliases);
60
63
  }
61
64
  const HEX = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
62
65
  // Whether `value` is one taco's evaluator reads as a variable of `type` (it reads a colour from a hex string and a
@@ -30,6 +30,7 @@ export interface OpenFigmaOptions extends Pick<ImportEnv, 'signal' | 'progress'>
30
30
  export declare function checkAbort(signal?: ImportSignal): void;
31
31
  /**
32
32
  * Reads and converts all public pages in a .fig file. Transfers the input buffer when using a worker.
33
+ * Values in the result may be shared between layers; copy before mutating in place.
33
34
  * @param bytes - Saved Figma design file.
34
35
  * @param options - Worker, cancellation and progress options.
35
36
  * @returns The converted document and report.
@@ -8,6 +8,7 @@ export function checkAbort(signal) {
8
8
  }
9
9
  /**
10
10
  * Reads and converts all public pages in a .fig file. Transfers the input buffer when using a worker.
11
+ * Values in the result may be shared between layers; copy before mutating in place.
11
12
  * @param bytes - Saved Figma design file.
12
13
  * @param options - Worker, cancellation and progress options.
13
14
  * @returns The converted document and report.
package/dist/figma.d.ts CHANGED
@@ -18,6 +18,7 @@ export declare function readFigmaClipboard(html: string): ImportPayload;
18
18
  export type ReadFigmaOptions = Pick<ImportEnv, 'signal' | 'progress'>;
19
19
  /**
20
20
  * Reads a saved Figma design file on the calling thread.
21
+ * Values in the result may be shared between layers; copy before mutating in place.
21
22
  * @param bytes - Saved Figma design file.
22
23
  * @param options - Cancellation and progress options.
23
24
  * @returns All public pages in file order, editable component and resource records, images and a report of font faces and conversion losses.
package/dist/figma.js CHANGED
@@ -1,13 +1,19 @@
1
1
  import { clipboard, createCore } from '@moondraft/editor/core';
2
- import { figmaDocument, toDocument, toPayload } from './adapter/index.js';
2
+ import { figmaDocument, toPayload } from './adapter/index.js';
3
+ import { base64 } from './adapter/figma.js';
3
4
  import { fileComponents } from './adapter/file-components.js';
5
+ import { keepDescription } from './adapter/figma-descriptions.js';
6
+ import { figmaLayoutGrids, gridSources } from './adapter/figma-grids.js';
7
+ import { figmaHandoff, handoffOverrides, handoffSources } from './adapter/figma-handoff.js';
8
+ import { figmaHyperlinks } from './adapter/figma-hyperlinks.js';
9
+ import { isObject } from './taco/figma-import/import/fields.js';
4
10
  import { sha256Hex } from './taco/model/sha256.js';
5
11
  import { expandedRadiusRoots, fileResources } from './adapter/file-resources.js';
6
- import { readFileMessage } from './taco/figma-import/import/walk.js';
7
- import { allPages } from './adapter/convert.js';
8
- import { convertEntries, fontEntries, grouped, layersBySource } from './report.js';
12
+ import { readFileMessage, walkMessage } from './taco/figma-import/import/walk.js';
13
+ import { allPages, figmaClipboardPage } from './adapter/convert.js';
14
+ import { convertEntries, droppedFeatures, figmaReportLayers, fontEntries, grouped, leftOutIds, readerCount } from './report.js';
9
15
  import { checkAbort } from './figma-file.js';
10
- import { importFigmaMessage, readFigFile, readFigmaClipboardHtml } from './taco/figma-import/index.js';
16
+ import { readFigFile, readFigmaClipboardHtml } from './taco/figma-import/index.js';
11
17
  /**
12
18
  * Checks for the markers Figma adds to clipboard HTML.
13
19
  * @param html - Clipboard HTML to inspect.
@@ -18,17 +24,28 @@ export const holdsFigmaData = (html) => html.includes('(figmeta)') && html.inclu
18
24
  export const MISSING_IMAGES = clipboard.MISSING_IMAGE_REPORT;
19
25
  const STAND_IN = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
20
26
  const ids = () => { let next = 0; return () => `f${++next}`; };
21
- function reportOf(result, converted, extra = []) {
22
- const bySource = layersBySource(converted.doc);
23
- const pages = converted.doc.models.filter(m => m.kind === 'page');
24
- const pageIds = new Map(result.pages.map((page, i) => [page.figmaId, pages[i]?.id]));
27
+ function reportOf(result, converted, features, extra, file = false) {
28
+ const { bySource, pages, derive } = figmaReportLayers(converted.doc, file);
29
+ const dropped = [];
30
+ for (const { figmaId, what, leftOut } of features) {
31
+ if (leftOut) {
32
+ dropped.push({ kind: 'left-out', what, count: 1 });
33
+ continue;
34
+ }
35
+ const layer = result.layerIds[figmaId];
36
+ if (layer === undefined)
37
+ continue;
38
+ const ids = bySource.get(layer);
39
+ dropped.push({ kind: 'left-out', what, count: 1, ...(ids?.length && { ids }) });
40
+ }
41
+ const pageIds = new Map(result.pages.map((page, i) => [page.figmaId, pages[i]]));
25
42
  const reader = result.report.filter(entry => entry.nodeType !== 'CANVAS' || entry.reason === 'variable mode').map((entry) => {
26
43
  const layer = result.layerIds[entry.nodeId];
27
44
  const pageId = pageIds.get(entry.nodeId);
28
45
  const ids = pageId ? [pageId] : layer === undefined ? undefined : bySource.get(layer);
29
- return { kind: entry.kind === 'approximated' ? 'approximated' : 'left-out', what: entry.reason, count: 1, ...(ids && { ids }) };
46
+ return { kind: entry.kind === 'approximated' ? 'approximated' : 'left-out', ...readerCount(entry), ...(ids && { ids }) };
30
47
  });
31
- return grouped([...reader, ...convertEntries(converted.report, true), ...extra]);
48
+ return { report: [...reader, ...dropped, ...convertEntries(converted.report, true), ...extra], derive };
32
49
  }
33
50
  /**
34
51
  * Imports Figma clipboard HTML as editable layers.
@@ -37,19 +54,45 @@ function reportOf(result, converted, extra = []) {
37
54
  * @throws An error if the input contains no readable Figma layers.
38
55
  */
39
56
  export function readFigmaClipboard(html) {
40
- const { message } = readFigmaClipboardHtml(html), missing = new Set();
41
- const result = importFigmaMessage(message, {
57
+ const { meta, message } = readFigmaClipboardHtml(html);
58
+ const { result, sources } = walkMessage(message, {
42
59
  idSource: ids(), roots: 'clipboard-selection', bindVariables: false, textStyles: false,
43
- images: (hash) => { missing.add(`figma-image-${hash}`); return { bytes: STAND_IN, mimeType: 'image/png' }; },
44
- });
45
- const converted = toDocument(figmaDocument(result, 'Pasted'), 0), { payload } = toPayload(converted);
46
- const assetIds = [...missing].filter((id) => Object.hasOwn(payload.assets, id));
60
+ images: () => ({ bytes: STAND_IN, mimeType: 'image/png', placeholder: true }),
61
+ }, false, tree => new Set([...handoffSources(tree), ...gridSources(tree)]));
62
+ const instanceSources = new Map();
63
+ const converted = figmaClipboardPage(figmaDocument(result, 'Pasted'), instanceSources);
64
+ const leftOut = leftOutIds(sources);
65
+ const extra = figmaHandoff(result, sources, converted.doc, { instanceSources, leftOut, overrides: handoffOverrides(sources.tree) });
66
+ extra.push(...figmaHyperlinks(result, sources, converted.doc, { instanceSources }));
67
+ let fileKey = meta.fileKey;
68
+ for (const entry of figmaLayoutGrids(sources, converted.doc, { instanceSources,
69
+ fileId: () => fileKey ||= sha256Hex(new TextEncoder().encode(html)) }))
70
+ extra.push(entry);
71
+ const definitions = new Map(result.components.map(c => [c.id, c.rootId]));
72
+ const sourceOfRoot = new Map();
73
+ for (const [guid, component] of Object.entries(result.componentIds)) {
74
+ const root = definitions.get(component), node = sources.tree.nodes.get(guid);
75
+ if (root && node && (!sourceOfRoot.has(root) || node.change.isStateGroup === true))
76
+ sourceOfRoot.set(root, node);
77
+ }
78
+ for (const model of converted.doc.models) {
79
+ if (model.kind !== 'frame' || model.component !== model.id)
80
+ continue;
81
+ const source = sourceOfRoot.get(model.sourceId ?? '');
82
+ if (source)
83
+ keepDescription(source, model, extra);
84
+ }
85
+ const { payload } = toPayload(converted);
86
+ const assetIds = Object.values(result.assets).filter(a => a.placeholder && Object.hasOwn(payload.assets, a.id)).map(a => a.id);
47
87
  for (const id of assetIds)
48
88
  delete payload.assets[id];
49
- return { payload, report: reportOf(result, converted, assetIds.length ? [{ kind: 'left-out', what: MISSING_IMAGES, count: assetIds.length, assetIds }] : []) };
89
+ if (assetIds.length)
90
+ extra.push({ kind: 'left-out', what: MISSING_IMAGES, count: assetIds.length, assetIds });
91
+ return { payload, report: grouped(reportOf(result, converted, droppedFeatures(message.nodeChanges, leftOut), extra).report) };
50
92
  }
51
93
  /**
52
94
  * Reads a saved Figma design file on the calling thread.
95
+ * Values in the result may be shared between layers; copy before mutating in place.
53
96
  * @param bytes - Saved Figma design file.
54
97
  * @param options - Cancellation and progress options.
55
98
  * @returns All public pages in file order, editable component and resource records, images and a report of font faces and conversion losses.
@@ -63,34 +106,147 @@ export function readFigmaFile(bytes, options = {}) {
63
106
  checkAbort(signal);
64
107
  }
65
108
  checkpoint('decode', 0, 1);
66
- const file = readFigFile(bytes);
67
- checkpoint('decode', 1, 1);
68
- checkpoint('convert', 0);
109
+ const { doc, images, report, total, derive } = convertFile(bytes, () => {
110
+ checkpoint('decode', 1, 1);
111
+ checkpoint('convert', 0);
112
+ });
113
+ // Use the same derived pass as editor.load so saved literals include mode choices and nested property assignments.
114
+ let document = doc;
115
+ if (derive) {
116
+ const core = createCore({ trackLayout: false });
117
+ // Conversion owns these records. Linking can share override entries, which the
118
+ // editor updates in place while installing derived properties and resource values.
119
+ for (const model of doc.models)
120
+ if (model.kind === 'frame' && model.overrides)
121
+ model.overrides = core.doc.owned(model.overrides, undefined, true);
122
+ core.prepareImportLoad(doc)();
123
+ // A main's typography binding over a range that crosses an instance's own text runs stays a value there (issue 867).
124
+ for (const { id, fields } of core.keptTypography())
125
+ for (const field of fields)
126
+ report.push({ kind: 'approximated', what: `typography binding kept as value for text field "${field}"`, count: 1, ids: [id] });
127
+ document = core.releaseJSON();
128
+ }
129
+ // Only surviving assets need data URLs. Keep their encoded strings out of the layout and linking passes.
130
+ for (const [id, asset] of Object.entries(document.assets ?? {})) {
131
+ const media = images[id];
132
+ const pixels = asset.mediaType === 'video' ? media : media.poster ?? media;
133
+ asset.src += base64(pixels.bytes);
134
+ if (asset.mediaType === 'video' && media.poster)
135
+ asset.poster = `data:${media.poster.mimeType};base64,${base64(media.poster.bytes)}`;
136
+ }
137
+ checkpoint('convert', total, total);
138
+ return { document, report: grouped([...report, ...fontEntries(document)]) };
139
+ }
140
+ // Derived instance entries describe Figma's layout. Their path, box and stored line
141
+ // heights are the inputs to instanceFields. Authored overrides are read separately.
142
+ function compactFileRecord(field, change) {
143
+ if (field !== 'nodeChanges' || !isObject(change))
144
+ return;
145
+ // History and plugin payloads have no converted fields. Only authored overrides
146
+ // use parameterConsumptionMap, and those are nested under symbolData.
147
+ for (const key of ['editInfo', 'libraryMoveHistory', 'pluginData', 'parameterConsumptionMap'])
148
+ if (Object.hasOwn(change, key))
149
+ change[key] = undefined;
150
+ if (Array.isArray(change.derivedSymbolData)) {
151
+ for (const [i, entry] of change.derivedSymbolData.entries()) {
152
+ if (!isObject(entry))
153
+ continue;
154
+ const layout = {};
155
+ for (const key of ['guidPath', 'size', 'transform'])
156
+ if (entry[key] !== undefined)
157
+ layout[key] = entry[key];
158
+ const text = entry.derivedTextData;
159
+ if (isObject(text))
160
+ layout.derivedTextData = text.baselines === undefined ? {} : { baselines: text.baselines };
161
+ else if (text !== undefined)
162
+ layout.derivedTextData = text;
163
+ change.derivedSymbolData[i] = layout;
164
+ }
165
+ }
166
+ // Text import uses glyph advances only for list markers (glyphs without a character).
167
+ const text = change.derivedTextData;
168
+ if (isObject(text)) {
169
+ const metrics = {};
170
+ if (text.baselines !== undefined)
171
+ metrics.baselines = text.baselines;
172
+ if (text.fontMetaData !== undefined)
173
+ metrics.fontMetaData = text.fontMetaData;
174
+ if (Array.isArray(text.glyphs))
175
+ metrics.glyphs = text.glyphs.filter(glyph => isObject(glyph) && glyph.firstCharacter === undefined);
176
+ change.derivedTextData = metrics;
177
+ }
178
+ }
179
+ function readFileSource(bytes, decoded) {
180
+ const file = readFigFile(bytes, { onRootArrayItem: compactFileRecord });
181
+ decoded();
69
182
  const result = readFileMessage(file.message, {
70
183
  idSource: ids(), roots: 'pages',
71
184
  images: (hash) => { const bytes = file.images.get(hash); return bytes ? { bytes } : undefined; },
72
185
  });
73
- const total = result.pages.length;
74
- const geometry = figmaDocument(result);
186
+ return { result, key: file.meta?.fileKey || file.message.fileKey };
187
+ }
188
+ function convertFile(bytes, decoded) {
189
+ const { result, key } = readFileSource(bytes, decoded);
190
+ // Geometry and overrides now live on the converted nodes. Release their wire
191
+ // representations while collecting diagnostics in source order. Resource and
192
+ // metadata adapters still see the original paint lists and all other fields.
193
+ const releasedFields = ['derivedTextData', 'derivedSymbolData', 'symbolData', 'fillGeometry', 'strokeGeometry',
194
+ 'vectorData'];
195
+ function* sources() {
196
+ for (const node of result.sources.tree.nodes.values()) {
197
+ const change = node.change;
198
+ for (const field of releasedFields)
199
+ if (Object.hasOwn(change, field))
200
+ change[field] = undefined;
201
+ yield change;
202
+ }
203
+ }
204
+ // Read before `sources` releases the instances' overrides.
205
+ const overrides = handoffOverrides(result.sources.tree);
206
+ const leftOut = leftOutIds(result.sources);
207
+ const features = [...droppedFeatures(sources(), leftOut)];
208
+ const geometry = figmaDocument(result, undefined, () => '');
209
+ if (result.sources.variables)
210
+ geometry.variableAliases = result.sources.variables.aliases;
211
+ geometry.instanceBoxes = result.sources.instanceBoxes;
212
+ geometry.instanceFillSizes = result.sources.instanceFillSizes;
75
213
  const expandedRadii = expandedRadiusRoots(result);
76
214
  for (const id of expandedRadii.keys())
77
215
  geometry.nodes[id] = { ...geometry.nodes[id], fileExpanded: true };
78
216
  for (const layer of result.sources.styleLayers.values())
79
217
  geometry.nodes[layer.id] = { ...layer, fileStyle: true };
80
218
  const converted = allPages(geometry, {
81
- assetSrc: (_id, asset) => `data:${asset.mimeType};base64,${asset.source.data}`,
219
+ assetSrc: (_id, asset) => `data:${asset.mimeType};base64,`,
82
220
  });
83
221
  const extra = [];
84
- const occurrences = fileComponents(result, converted.doc, extra);
85
- let fileId = file.meta?.fileKey || file.message.fileKey;
86
- fileResources(result, converted.doc, occurrences, converted.expanded, expandedRadii, extra, () => String(fileId ||= sha256Hex(bytes)));
222
+ // Roots that bind their own radii stay expanded before linking (convert.ts leaves them unmarked).
223
+ for (const m of converted.doc.models)
224
+ if (m.fileInstance !== undefined && expandedRadii.has(m.fileInstance))
225
+ converted.expandedReasons.set(m.id, 'root radius bindings');
226
+ const { occurrences, setSources } = fileComponents(result, converted.doc, converted.nestedBooleans, extra, converted.expandedReasons);
227
+ let fileKey = key;
228
+ const fileId = () => String(fileKey ||= sha256Hex(bytes));
229
+ fileResources(result, converted.doc, occurrences, converted.expanded, expandedRadii, extra, fileId);
230
+ for (const layer of converted.doc.models) {
231
+ if (layer.kind !== 'frame')
232
+ continue;
233
+ for (const path of converted.omittedLinks.get(layer.id) ?? []) {
234
+ // An explicitly painted occurrence keeps its resolved links in its own palette.
235
+ if (!layer.overrides?.[path]?.styles)
236
+ extra.push({ kind: 'left-out', what: 'instance text link override not kept', count: 1, ids: [layer.id + ';' + path] });
237
+ }
238
+ }
239
+ for (const entry of figmaHyperlinks(result, result.sources, converted.doc, { setSources }))
240
+ extra.push(entry);
241
+ for (const entry of figmaHandoff(result, result.sources, converted.doc, { setSources, leftOut, overrides }))
242
+ extra.push(entry);
243
+ for (const entry of figmaLayoutGrids(result.sources, converted.doc, { setSources, fileId }))
244
+ extra.push(entry);
87
245
  const reader = result.report.filter(e => !e.reason.startsWith('variable bindings left out, their values kept:'));
88
- const report = reportOf({ ...result, report: reader }, converted, [...extra, ...fontEntries(converted.doc)]);
89
- for (const model of converted.doc.models)
90
- delete model.sourceId;
91
- // Use the same derived pass as editor.load so saved literals include mode choices and nested property assignments.
92
- const document = converted.doc.shared || converted.doc.models.some(m => m.kind === 'frame' && (m.variantSet || m.props))
93
- ? createCore({ document: converted.doc, trackLayout: false }).toJSON() : converted.doc;
94
- checkpoint('convert', total, total);
95
- return { document, report };
246
+ const { report, derive } = reportOf({ ...result, report: reader }, converted, features, extra, true);
247
+ const images = result.assets;
248
+ for (const id of Object.keys(images))
249
+ if (!Object.hasOwn(converted.doc.assets ?? {}, id))
250
+ delete images[id];
251
+ return { doc: converted.doc, images, report, derive, total: result.pages.length };
96
252
  }
package/dist/index.d.ts CHANGED
@@ -26,3 +26,4 @@ export interface FigmaImporterOptions {
26
26
  */
27
27
  export declare function figmaImporter(options?: FigmaImporterOptions): Importer;
28
28
  export { payloadFromSyntax } from './syntax.ts';
29
+ export { serializeImportDocument } from './serialize.ts';
package/dist/index.js CHANGED
@@ -47,3 +47,4 @@ export function figmaImporter(options = {}) {
47
47
  };
48
48
  }
49
49
  export { payloadFromSyntax } from './syntax.js';
50
+ export { serializeImportDocument } from './serialize.js';
package/dist/report.d.ts CHANGED
@@ -1,10 +1,68 @@
1
1
  import type { ImportReportEntry } from '@moondraft/editor/core';
2
2
  import type { DocumentJSON } from '@moondraft/editor/schema';
3
3
  import type { ConvertReport } from './adapter/convert.ts';
4
- /** Groups entries by kind and description, summing counts and keeping unique layer IDs. */
4
+ import type { FigmaTreeNode } from './taco/figma-import/import/tree.ts';
5
+ /** The most layer IDs a grouped entry keeps as examples. */
6
+ export declare const EXAMPLE_IDS = 5;
7
+ /** A reader entry's description and its occurrence count, which the reader gives as a field when it is more than one. */
8
+ export declare function readerCount(entry: {
9
+ reason: string;
10
+ count?: number;
11
+ }): {
12
+ what: string;
13
+ count: number;
14
+ };
15
+ /**
16
+ * Groups entries by kind and description, summing counts and keeping up to `EXAMPLE_IDS` unique layer IDs. Entries
17
+ * that are not fonts also group when their descriptions differ only in quoted names, numbers or upper-case enum values;
18
+ * the grouped description lists each varying part's values in order of appearance.
19
+ */
5
20
  export declare function grouped(entries: Iterable<ImportReportEntry>): ImportReportEntry[];
21
+ /** Report descriptions of Figma features the importer leaves out without converting any part of them. */
22
+ export declare const DROPPED_FEATURES: {
23
+ readonly interactions: 'prototype interactions are not imported';
24
+ };
25
+ /**
26
+ * Describes what a Figma layer the import left out loses with it. That layer has no layer of its own in the result to
27
+ * point to, so the description names it.
28
+ * @param what - What is lost.
29
+ * @param name - The Figma layer's name, or its type when it has none.
30
+ * @returns The description.
31
+ */
32
+ export declare const onLeftOutLayer: (what: string, name: string) => string;
33
+ /**
34
+ * Lists the Figma nodes the import left out with no imported copy. The reader's omitted subtrees also hold content
35
+ * that is imported elsewhere, such as a slot's content frame, which is imported as the content of the instances that
36
+ * fill the slot; a node that is imported, or holds a node that is, is not left out.
37
+ * @param sources - The reader's tree, its omitted subtrees and the nodes it imported.
38
+ * @returns The Figma IDs of the left-out nodes.
39
+ */
40
+ export declare function leftOutIds(sources: {
41
+ tree: {
42
+ nodes: ReadonlyMap<string, FigmaTreeNode>;
43
+ };
44
+ omittedSubtrees: Iterable<FigmaTreeNode>;
45
+ imported: Iterable<{
46
+ figma: FigmaTreeNode;
47
+ }>;
48
+ }): Set<string>;
49
+ /**
50
+ * Unsupported features in source order. Linking supplies their final layer IDs later, except on left-out layers,
51
+ * whose entries name the layer instead.
52
+ */
53
+ export declare function droppedFeatures(changes: Iterable<unknown> | undefined, leftOut: ReadonlySet<string>): Generator<{
54
+ figmaId: string;
55
+ leftOut: boolean;
56
+ what: string;
57
+ }, void, unknown>;
6
58
  /** Builds a lookup from reader IDs to their converted layers. */
7
59
  export declare function layersBySource(document: DocumentJSON): Map<string, string[]>;
60
+ /** Collect file diagnostics and strip reader IDs before handing the models to the editor. */
61
+ export declare function figmaReportLayers(document: DocumentJSON, file: boolean): {
62
+ bySource: Map<string, string[]>;
63
+ pages: string[];
64
+ derive: boolean;
65
+ };
8
66
  /** Turns adapter diagnostics into import reports. */
9
67
  export declare function convertEntries(report: ConvertReport, details?: boolean): ImportReportEntry[];
10
68
  /**