@moondraft/import 0.2.0 → 0.4.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 (61) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/SOURCE.md +138 -1
  3. package/dist/adapter/convert.d.ts +2 -0
  4. package/dist/adapter/convert.js +192 -85
  5. package/dist/adapter/figma-handoff.d.ts +24 -2
  6. package/dist/adapter/figma-handoff.js +39 -18
  7. package/dist/adapter/figma.js +2 -1
  8. package/dist/adapter/file-components.d.ts +20 -1
  9. package/dist/adapter/file-components.js +91 -12
  10. package/dist/adapter/file-resources.d.ts +5 -0
  11. package/dist/adapter/file-resources.js +286 -40
  12. package/dist/adapter/file-typography.d.ts +6 -0
  13. package/dist/adapter/file-typography.js +44 -0
  14. package/dist/adapter/link.d.ts +8 -1
  15. package/dist/adapter/link.js +219 -105
  16. package/dist/adapter/payload.js +2 -2
  17. package/dist/adapter/variables.d.ts +1 -1
  18. package/dist/figma-file.d.ts +1 -0
  19. package/dist/figma-file.js +1 -0
  20. package/dist/figma.d.ts +1 -0
  21. package/dist/figma.js +41 -19
  22. package/dist/report.d.ts +37 -6
  23. package/dist/report.js +91 -18
  24. package/dist/taco/figma-import/figFile.js +3 -0
  25. package/dist/taco/figma-import/import/carry.d.ts +11 -1
  26. package/dist/taco/figma-import/import/carry.js +8 -0
  27. package/dist/taco/figma-import/import/converters/effects.d.ts +3 -13
  28. package/dist/taco/figma-import/import/converters/effects.js +4 -34
  29. package/dist/taco/figma-import/import/converters/exportSettings.js +26 -0
  30. package/dist/taco/figma-import/import/converters/frame.d.ts +1 -1
  31. package/dist/taco/figma-import/import/converters/frame.js +8 -7
  32. package/dist/taco/figma-import/import/converters/grid.d.ts +12 -0
  33. package/dist/taco/figma-import/import/converters/grid.js +97 -0
  34. package/dist/taco/figma-import/import/converters/group.d.ts +1 -0
  35. package/dist/taco/figma-import/import/converters/group.js +5 -2
  36. package/dist/taco/figma-import/import/converters/image.d.ts +1 -0
  37. package/dist/taco/figma-import/import/converters/image.js +38 -5
  38. package/dist/taco/figma-import/import/converters/layout.d.ts +5 -3
  39. package/dist/taco/figma-import/import/converters/layout.js +26 -16
  40. package/dist/taco/figma-import/import/converters/rectangle.js +2 -2
  41. package/dist/taco/figma-import/import/converters/section.js +2 -2
  42. package/dist/taco/figma-import/import/converters/shared.d.ts +2 -1
  43. package/dist/taco/figma-import/import/converters/shared.js +8 -5
  44. package/dist/taco/figma-import/import/converters/text.d.ts +24 -0
  45. package/dist/taco/figma-import/import/converters/text.js +121 -31
  46. package/dist/taco/figma-import/import/instances.d.ts +19 -3
  47. package/dist/taco/figma-import/import/instances.js +337 -60
  48. package/dist/taco/figma-import/import/types.d.ts +8 -0
  49. package/dist/taco/figma-import/import/variables.d.ts +2 -0
  50. package/dist/taco/figma-import/import/variables.js +28 -1
  51. package/dist/taco/figma-import/import/variantTrees.js +2 -0
  52. package/dist/taco/figma-import/import/walk.d.ts +9 -2
  53. package/dist/taco/figma-import/import/walk.js +69 -30
  54. package/dist/taco/figma-import/kiwi/message.js +52 -10
  55. package/dist/taco/model/codec.d.ts +1 -1
  56. package/dist/taco/model/codec.js +40 -6
  57. package/dist/taco/model/instance-resolver.js +3 -1
  58. package/dist/taco/model/types.d.ts +36 -6
  59. package/dist/taco/model/types.js +4 -0
  60. package/dist/taco/svg-import/style/computed.js +1 -0
  61. package/package.json +3 -3
@@ -1,4 +1,5 @@
1
1
  import { isObject } from '../taco/figma-import/import/fields.js';
2
+ import { onLeftOutLayer } from '../report.js';
2
3
  const feature = {
3
4
  annotations: 'developer annotations are not imported',
4
5
  measurements: 'developer measurements are not imported',
@@ -52,6 +53,25 @@ function* canvasStatuses(tree) {
52
53
  }
53
54
  }
54
55
  }
56
+ const overrideFields = ['annotations', 'measurements'];
57
+ /**
58
+ * Finds the instances whose overrides hold active annotations or measurements. Read it before the instances' override
59
+ * data is released.
60
+ * @param tree - The reader's Figma tree.
61
+ * @returns The handoff fields set by each such instance's overrides, by Figma ID.
62
+ */
63
+ export function handoffOverrides(tree) {
64
+ const found = new Map();
65
+ for (const node of tree.nodes.values()) {
66
+ const overrides = isObject(node.change.symbolData) ? node.change.symbolData.symbolOverrides : undefined;
67
+ if (!Array.isArray(overrides))
68
+ continue;
69
+ const fields = overrideFields.filter(field => overrides.some(entry => isObject(entry) && activeList(entry[field]) !== undefined));
70
+ if (fields.length)
71
+ found.set(node.id, fields);
72
+ }
73
+ return found;
74
+ }
55
75
  /** Keeps handoff-bearing clipboard layers distinct when merging variant trees. */
56
76
  export function handoffSources(tree) {
57
77
  const ids = new Set();
@@ -66,8 +86,12 @@ export function handoffSources(tree) {
66
86
  ids.add(target);
67
87
  return ids;
68
88
  }
69
- /** Installs Figma handoff metadata on the layers that survived conversion and reports any omitted fields. */
70
- export function figmaHandoff(result, sources, doc, options = {}) {
89
+ /**
90
+ * Installs Figma handoff metadata on the layers that survived conversion and reports any omitted fields: those of
91
+ * layers left out (`leftOut`, named in the report) and the handoff that instances set in overrides (`overrides`), which
92
+ * is not kept.
93
+ */
94
+ export function figmaHandoff(result, sources, doc, options) {
71
95
  const entries = [];
72
96
  const report = (what, ids) => {
73
97
  entries.push({ kind: 'left-out', what, count: 1, ...(ids?.length && { ids }) });
@@ -85,7 +109,7 @@ export function figmaHandoff(result, sources, doc, options = {}) {
85
109
  else if (status !== undefined)
86
110
  mappedStatus.set(target, { status, pageId });
87
111
  }
88
- const hasHandoff = (node) => node !== undefined && (mappedStatus.has(node.id) || handoffFields.some(field => node.change[field] !== undefined));
112
+ const hasHandoff = (node) => node !== undefined && (mappedStatus.has(node.id) || options.overrides.has(node.id) || handoffFields.some(field => node.change[field] !== undefined));
89
113
  const byReaderId = new Map();
90
114
  const layers = new Map();
91
115
  for (const { node, figma } of sources.imported)
@@ -111,23 +135,14 @@ export function figmaHandoff(result, sources, doc, options = {}) {
111
135
  for (const { nodeId, kind } of result.report)
112
136
  if (kind === 'node-left-out' && hasHandoff(sources.tree.nodes.get(nodeId)))
113
137
  scoped.add(nodeId);
114
- const visited = new Set();
115
- const pending = [...sources.omittedSubtrees];
116
- while (pending.length) {
117
- const node = pending.pop();
118
- if (visited.has(node.id))
119
- continue;
120
- visited.add(node.id);
121
- if (hasHandoff(node))
122
- scoped.add(node.id);
123
- for (const child of node.children)
124
- pending.push(child);
125
- }
138
+ for (const id of options.leftOut)
139
+ if (hasHandoff(sources.tree.nodes.get(id)))
140
+ scoped.add(id);
126
141
  for (const [id, { pageId }] of mappedStatus)
127
142
  if (pageId !== undefined)
128
143
  scoped.add(id);
129
144
  for (const id of scoped) {
130
- const change = sources.tree.nodes.get(id)?.change;
145
+ const node = sources.tree.nodes.get(id), change = node?.change;
131
146
  const targets = layers.get(id) ?? [];
132
147
  const ids = targets.map(layer => layer.id);
133
148
  const mapped = mappedStatus.get(id);
@@ -155,8 +170,14 @@ export function figmaHandoff(result, sources, doc, options = {}) {
155
170
  else
156
171
  omitted.add(feature[field]);
157
172
  }
158
- for (const what of omitted)
159
- report(what, ids.length || mapped?.pageId === undefined ? ids : [mapped.pageId]);
173
+ for (const field of options.overrides.get(id) ?? [])
174
+ omitted.add(feature[field]);
175
+ for (const what of omitted) {
176
+ if (options.leftOut.has(id) && node)
177
+ report(onLeftOutLayer(what, node.name || node.type));
178
+ else
179
+ report(what, ids.length || mapped?.pageId === undefined ? ids : [mapped.pageId]);
180
+ }
160
181
  if (Object.keys(data).length)
161
182
  for (const layer of targets) {
162
183
  const existing = layer.data?.figma;
@@ -35,6 +35,7 @@ export function figmaDocument(result, name, encodeImage = base64) {
35
35
  components[c.id] = c;
36
36
  const assets = {};
37
37
  for (const i of Object.values(result.assets))
38
- assets[i.id] = { id: i.id, kind: 'image', mimeType: i.mimeType, ...(i.width !== undefined ? { width: i.width } : {}), ...(i.height !== undefined ? { height: i.height } : {}), source: { kind: 'data', data: encodeImage(i.bytes) } };
38
+ assets[i.id] = { id: i.id, kind: i.mimeType.startsWith('video/') ? 'video' : 'image',
39
+ ...(i.poster && { poster: `data:${i.poster.mimeType};base64,${encodeImage(i.poster.bytes)}` }), mimeType: i.mimeType, ...(i.width !== undefined ? { width: i.width } : {}), ...(i.height !== undefined ? { height: i.height } : {}), source: { kind: 'data', data: encodeImage(i.bytes) } };
39
40
  return { pageOrder, pages, nodes, components, assets, componentPlacements: result.componentPlacements, theme: { variableCollections: result.variableCollections, textStyles: result.textStyles ?? {} } };
40
41
  }
@@ -7,14 +7,33 @@ import type { NestedBooleanAssignments } from './convert.ts';
7
7
  * @internal
8
8
  */
9
9
  export type FileMessage = ReturnType<typeof readFileMessage>;
10
+ /** Per source layer, the component whose properties its expressions bind to (fileComponents): each layer of a
11
+ * component's tree, a later component's tree winning.
12
+ * @internal
13
+ */
14
+ export declare function layerComponents<C extends {
15
+ rootId: string;
16
+ }>(components: Iterable<C>, children: (id: string) => readonly string[] | undefined): Map<string, C>;
17
+ /** The expression a source layer's text takes from a component property where fileComponents binds it: a property,
18
+ * other than a variant or slot, of the component it is a layer of, in that component's main (`main`, its root).
19
+ * @internal
20
+ */
21
+ export declare function boundTextExpression(expression: string | undefined, component: {
22
+ rootId: string;
23
+ properties?: readonly {
24
+ name: string;
25
+ kind: string;
26
+ }[];
27
+ } | undefined, main: string | undefined): string | undefined;
10
28
  /** Installs local property IDs, their bindings, instance assignments and slot content.
11
29
  * @param result - Original Figma component declarations and placements.
12
30
  * @param doc - Linked document, with source IDs for the original nodes.
13
31
  * @param nestedBooleans - Enclosing instance assignments carried through expanded layers and their linked paths.
14
32
  * @param report - Receives occurrences the native document cannot represent.
33
+ * @param expandedReasons - Per instance linking left expanded, by layer ID: linking's reason, which its report entry names.
15
34
  * @returns Authored override fields and the Figma sources of newly created sets.
16
35
  */
17
- export declare function fileComponents(result: FileMessage, doc: DocumentJSON, nestedBooleans: ReadonlyMap<string, NestedBooleanAssignments>, report: ImportReportEntry[]): {
36
+ export declare function fileComponents(result: FileMessage, doc: DocumentJSON, nestedBooleans: ReadonlyMap<string, NestedBooleanAssignments>, report: ImportReportEntry[], expandedReasons?: ReadonlyMap<string, string>): {
18
37
  occurrences: Map<string, Map<string, Readonly<Record<string, unknown>>>>;
19
38
  setSources: Map<string, FigmaTreeNode>;
20
39
  };
@@ -1,15 +1,44 @@
1
1
  import { definitions as propertyDefinitions, effectiveRecord, isInstance, ownerOf, resolveVirtual, splitVirtual } from '@moondraft/editor/core';
2
2
  import { guidText } from '../taco/figma-import/import/fields.js';
3
- import { formatExpressionName, parseLayerPath } from '../taco/model/index.js';
3
+ import { formatExpressionName, layerPathKey, parseLayerPath } from '../taco/model/index.js';
4
4
  import { keepDescription } from './figma-descriptions.js';
5
+ import { withOverrideFields } from './file-resources.js';
6
+ import { expansionReason } from './link.js';
7
+ /** Per source layer, the component whose properties its expressions bind to (fileComponents): each layer of a
8
+ * component's tree, a later component's tree winning.
9
+ * @internal
10
+ */
11
+ export function layerComponents(components, children) {
12
+ const of = new Map();
13
+ for (const c of components) {
14
+ const pending = [c.rootId];
15
+ while (pending.length) {
16
+ const id = pending.pop();
17
+ of.set(id, c);
18
+ for (const child of children(id) ?? [])
19
+ pending.push(child);
20
+ }
21
+ }
22
+ return of;
23
+ }
24
+ /** The expression a source layer's text takes from a component property where fileComponents binds it: a property,
25
+ * other than a variant or slot, of the component it is a layer of, in that component's main (`main`, its root).
26
+ * @internal
27
+ */
28
+ export function boundTextExpression(expression, component, main) {
29
+ const p = expression === undefined || component === undefined || component.rootId !== main ? undefined
30
+ : component.properties?.find(p => formatExpressionName(p.name) === expression);
31
+ return p && p.kind !== 'enum' && p.kind !== 'slot' ? expression : undefined;
32
+ }
5
33
  /** Installs local property IDs, their bindings, instance assignments and slot content.
6
34
  * @param result - Original Figma component declarations and placements.
7
35
  * @param doc - Linked document, with source IDs for the original nodes.
8
36
  * @param nestedBooleans - Enclosing instance assignments carried through expanded layers and their linked paths.
9
37
  * @param report - Receives occurrences the native document cannot represent.
38
+ * @param expandedReasons - Per instance linking left expanded, by layer ID: linking's reason, which its report entry names.
10
39
  * @returns Authored override fields and the Figma sources of newly created sets.
11
40
  */
12
- export function fileComponents(result, doc, nestedBooleans, report) {
41
+ export function fileComponents(result, doc, nestedBooleans, report, expandedReasons = new Map()) {
13
42
  const models = doc.models;
14
43
  const byId = new Map(models.map(m => [m.id, m]));
15
44
  const mains = new Map(), bySource = new Map();
@@ -118,7 +147,6 @@ export function fileComponents(result, doc, nestedBooleans, report) {
118
147
  definitions.set(member.componentId, refs);
119
148
  }
120
149
  }
121
- const sourceComponent = new Map();
122
150
  for (const c of result.components) {
123
151
  const main = mains.get(c.id);
124
152
  main.key = c.key;
@@ -134,14 +162,8 @@ export function fileComponents(result, doc, nestedBooleans, report) {
134
162
  if (value !== shared.default)
135
163
  report.push({ kind: 'approximated', what: 'variant member property default', count: 1, ids: [main.id] });
136
164
  }
137
- const pending = [c.rootId];
138
- while (pending.length) {
139
- const id = pending.pop(), layer = source.get(id);
140
- sourceComponent.set(id, c);
141
- for (const child of layer.children ?? [])
142
- pending.push(child);
143
- }
144
165
  }
166
+ const sourceComponent = layerComponents(result.components, id => source.get(id).children);
145
167
  const componentOfMain = (id) => componentOfRoot.get(byId.get(id)?.sourceId);
146
168
  function values(component, assignments, id) {
147
169
  const refs = definitions.get(component);
@@ -167,6 +189,28 @@ export function fileComponents(result, doc, nestedBooleans, report) {
167
189
  }).join(';');
168
190
  }
169
191
  const occurrences = new Map();
192
+ // A linked instance inside an expanded one also shows what the expanded instances above it override through it
193
+ // (paints, styles, bindings), as a layer of the expansion does (file-resources expandedFields): their fields join its
194
+ // own at each of its paths, the outer instance's winning.
195
+ function throughExpanded(m, own) {
196
+ let fields = own;
197
+ const path = [m.sourceId];
198
+ for (let parent = byId.get(m.parent); parent; parent = byId.get(parent.parent)) {
199
+ if (source.get(parent.sourceId)?.type !== 'instance')
200
+ continue;
201
+ const outer = parent.component ? undefined : result.sources.occurrenceFields.get(parent.sourceId), prefix = layerPathKey(path);
202
+ for (const [key, over] of outer ?? []) {
203
+ if (key !== prefix && !key.startsWith(prefix + ';'))
204
+ continue;
205
+ const inner = key.slice(prefix.length + 1);
206
+ if (fields === own)
207
+ fields = new Map(own);
208
+ fields.set(inner, withOverrideFields(fields.get(inner) ?? {}, over));
209
+ }
210
+ path.unshift(parent.sourceId);
211
+ }
212
+ return fields;
213
+ }
170
214
  const instanceOverrides = new Map();
171
215
  const hosts = new Set(result.nodes.filter(n => n.type === 'frame' && n.slotHost).map(n => n.id));
172
216
  const usedHosts = new Set();
@@ -224,10 +268,11 @@ export function fileComponents(result, doc, nestedBooleans, report) {
224
268
  count: Object.keys(nested).length, ids: [m.id] });
225
269
  }
226
270
  if (!m.component) {
227
- report.push({ kind: 'approximated', what: 'expanded instance', count: 1, ids: [m.id] });
271
+ const reason = expandedReasons.get(m.id);
272
+ report.push({ kind: 'approximated', what: reason ? `expanded instance: ${expansionReason(reason)}` : 'expanded instance', count: 1, ids: [m.id] });
228
273
  continue;
229
274
  }
230
- const fields = result.sources.occurrenceFields.get(n.id);
275
+ const fields = throughExpanded(m, result.sources.occurrenceFields.get(n.id));
231
276
  if (fields)
232
277
  occurrences.set(m.id, new Map([...fields].map(([key, change]) => [overridePath(key), change])));
233
278
  // The editor resolves a stored bound swap from the enclosing main or set's declaration.
@@ -318,6 +363,40 @@ export function fileComponents(result, doc, nestedBooleans, report) {
318
363
  (owner.props ??= {})[binding] = entry.component;
319
364
  }
320
365
  }
366
+ // A linked occurrence whose text, bound to a text property, shows other wording than the property gives it there (a
367
+ // Figma text override, not an assignment) assigns that wording to the property: core derives a bound text's content
368
+ // from its property and drops the override. Wording the property already gives stays as it is. What it gives is read
369
+ // from the converted overrides, not from assignments this loop adds, so the order of the instances does not matter.
370
+ // Linking leaves expanded an occurrence whose texts bound to one property show different wording (link.ts match).
371
+ for (const holder of models) {
372
+ if (!isInstance(holder))
373
+ continue;
374
+ for (const [path, entry] of Object.entries(holder.overrides ?? {})) {
375
+ if (typeof entry.content !== 'string')
376
+ continue;
377
+ const target = resolveVirtual(get, holder.id + ';' + path, true);
378
+ const binding = target?.layer.bind?.content;
379
+ if (!target || !binding)
380
+ continue;
381
+ const at = target.levels.at(-1)[1], ownerPath = target.parts.slice(1, at + 1).join(';');
382
+ if (binding in ((at === 0 ? holder : holder.overrides[ownerPath])?.props ?? {}))
383
+ continue;
384
+ // An enclosing main's assignment to the occurrence or its own wording of the text, outermost first, else the default.
385
+ let given;
386
+ for (const [level, j] of target.levels.slice(1)) {
387
+ const assigned = j === at ? level.props : level.overrides?.[target.parts.slice(j + 1, at + 1).join(';')]?.props;
388
+ given = assigned?.[binding] ?? level.overrides?.[target.parts.slice(j + 1).join(';')]?.content;
389
+ if (typeof given === 'string')
390
+ break;
391
+ }
392
+ const shown = at === 0 ? holder.component : resolveVirtual(get, holder.id + ';' + ownerPath, true)?.component;
393
+ given ??= propertyDefinitions(ownerOf(get, get(shown))).find(p => p.id === binding)?.default;
394
+ if (given === entry.content)
395
+ continue;
396
+ const owner = at === 0 ? holder : (holder.overrides[ownerPath] ??= {});
397
+ (owner.props ??= {})[binding] = entry.content;
398
+ }
399
+ }
321
400
  // A flattened ancestor can also leave an assignment inside a surviving linked instance.
322
401
  // Apply inherited paths before the longer paths of the instances that use them.
323
402
  for (const [id, inherited] of [...nestedBooleans].filter(([id]) => id.includes(';')).sort(([a], [b]) => a.length - b.length)) {
@@ -9,6 +9,11 @@ type Corner = {
9
9
  specific: boolean;
10
10
  };
11
11
  };
12
+ type Change = Record<string, any>;
13
+ /** `change` with an enclosing instance's override fields (`own`) merged in: its plain fields replace the change's
14
+ * (unbinding the fields they set), and its bindings and modes replace only those of the same fields and collections.
15
+ * A list of paints in the override drops the change's style of that slot unless the override names one. */
16
+ export declare function withOverrideFields(change: Change, own: Change): Change;
12
17
  /** Finds instance roots that need their own radius bindings. Native instance roots take bindings from their main.
13
18
  * @param result - File definitions and original instance fields.
14
19
  * @returns The effective corners for each root that must remain an expanded frame.