@moondraft/import 0.2.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 (56) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/SOURCE.md +115 -1
  3. package/dist/adapter/convert.d.ts +2 -0
  4. package/dist/adapter/convert.js +175 -84
  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 +2 -1
  9. package/dist/adapter/file-components.js +5 -2
  10. package/dist/adapter/file-resources.js +234 -25
  11. package/dist/adapter/file-typography.d.ts +6 -0
  12. package/dist/adapter/file-typography.js +44 -0
  13. package/dist/adapter/link.d.ts +7 -0
  14. package/dist/adapter/link.js +87 -24
  15. package/dist/adapter/payload.js +2 -2
  16. package/dist/adapter/variables.d.ts +1 -1
  17. package/dist/figma-file.d.ts +1 -0
  18. package/dist/figma-file.js +1 -0
  19. package/dist/figma.d.ts +1 -0
  20. package/dist/figma.js +41 -19
  21. package/dist/report.d.ts +37 -6
  22. package/dist/report.js +91 -18
  23. package/dist/taco/figma-import/figFile.js +3 -0
  24. package/dist/taco/figma-import/import/converters/effects.d.ts +3 -13
  25. package/dist/taco/figma-import/import/converters/effects.js +4 -34
  26. package/dist/taco/figma-import/import/converters/exportSettings.js +26 -0
  27. package/dist/taco/figma-import/import/converters/frame.d.ts +1 -1
  28. package/dist/taco/figma-import/import/converters/frame.js +8 -7
  29. package/dist/taco/figma-import/import/converters/grid.d.ts +12 -0
  30. package/dist/taco/figma-import/import/converters/grid.js +97 -0
  31. package/dist/taco/figma-import/import/converters/image.d.ts +1 -0
  32. package/dist/taco/figma-import/import/converters/image.js +38 -5
  33. package/dist/taco/figma-import/import/converters/layout.d.ts +5 -3
  34. package/dist/taco/figma-import/import/converters/layout.js +26 -16
  35. package/dist/taco/figma-import/import/converters/rectangle.js +2 -2
  36. package/dist/taco/figma-import/import/converters/section.js +2 -2
  37. package/dist/taco/figma-import/import/converters/shared.d.ts +2 -1
  38. package/dist/taco/figma-import/import/converters/shared.js +8 -5
  39. package/dist/taco/figma-import/import/converters/text.d.ts +24 -0
  40. package/dist/taco/figma-import/import/converters/text.js +114 -29
  41. package/dist/taco/figma-import/import/instances.d.ts +9 -3
  42. package/dist/taco/figma-import/import/instances.js +319 -43
  43. package/dist/taco/figma-import/import/types.d.ts +8 -0
  44. package/dist/taco/figma-import/import/variables.d.ts +2 -0
  45. package/dist/taco/figma-import/import/variables.js +28 -1
  46. package/dist/taco/figma-import/import/variantTrees.js +2 -0
  47. package/dist/taco/figma-import/import/walk.d.ts +9 -2
  48. package/dist/taco/figma-import/import/walk.js +69 -30
  49. package/dist/taco/figma-import/kiwi/message.js +52 -10
  50. package/dist/taco/model/codec.d.ts +1 -1
  51. package/dist/taco/model/codec.js +40 -6
  52. package/dist/taco/model/instance-resolver.js +3 -1
  53. package/dist/taco/model/types.d.ts +36 -6
  54. package/dist/taco/model/types.js +4 -0
  55. package/dist/taco/svg-import/style/computed.js +1 -0
  56. package/package.json +2 -2
@@ -7,7 +7,8 @@
7
7
  // show unlike the main's. The effective records (the main's layers with those overrides applied) equal the expanded
8
8
  // ones in every field the renderer draws, so the page looks the same; an instance whose expansion differs in a field
9
9
  // that takes no override (a path's network change beyond layout, a stroke's position or weight, a layer the main lacks, the root's own
10
- // fills) stays expanded, and so do the instances inside it, which are linked on their own when they can be. A stroke's
10
+ // fills) stays expanded, and so do the instances inside it, which are linked on their own when they can be; the
11
+ // import report gives each one's reason (expansionReason). A stroke's
11
12
  // other colour is a paint override (the renderer draws a stroke's paint in place of its compact colour).
12
13
  // - A component whose root is on the page has it as its main. Any other gets a hidden main under '@components' (core's
13
14
  // parent of mains that are not drawn): a copy of its largest expanded instance with every layer its other expansions
@@ -30,6 +31,7 @@
30
31
  // instance whose layers draw outside it, a 114 px logo in a 29 px frame that does not clip or a card's shadow that
31
32
  // reaches well past it, stays expanded); its text body field carries the text's box (see difference).
32
33
  // The markers are removed whether or not anything is linked.
34
+ import { supportsTextField } from './file-typography.js';
33
35
  import { Properties, TextStyleSchema } from '@moondraft/editor/schema';
34
36
  import { instanceLayout, legacyAuto, netBounds, sizingOf } from '@moondraft/editor/core';
35
37
  /** The converter's markers on the expanded models (instanceOf, mainOf, and setOf: an instance's variant set name). */
@@ -42,6 +44,33 @@ const componentOf = (vk) => vk.split('\u0000')[0];
42
44
  */
43
45
  export const unmark = (m) => { for (const k of MARKERS)
44
46
  delete m[k]; };
47
+ /** Plain descriptions of the fields an expansion can differ in (difference, match), for the import report. */
48
+ const FIELD_WORDS = {
49
+ fills: 'fills', stroke: 'stroke', 'look.stroke': 'stroke position, cap or join', strokeWidth: 'stroke weight',
50
+ 'look.stroke.paint': 'stroke paint', effects: 'shadows or blurs', clip: 'clipping', layout: 'auto layout settings',
51
+ net: 'vector network', kind: 'layer type', result: 'boolean result', 'radius bindings': 'corner radius bindings',
52
+ };
53
+ /**
54
+ * Describes in plain words why an instance stays expanded, from linking's reason for it (LinkCounts.unlinked).
55
+ * @param reason - Linking's reason.
56
+ * @returns What the report says after "expanded instance: ".
57
+ */
58
+ export function expansionReason(reason) {
59
+ const fixed = {
60
+ 'used once': 'its component has no main on the page and no other instance', 'no main': 'its component has no main',
61
+ 'not a frame': 'it is not a frame', 'content outside the instance': 'its content draws outside its box',
62
+ 'inside its main': 'it is inside its own main', 'layer order': 'its layers are in another order than its main\'s',
63
+ 'a layer the main lacks': 'it has a layer its main lacks', 'conflicting bound swaps': 'one swap property selects different mains in it',
64
+ net: 'a vector network its main\'s layout does not give',
65
+ };
66
+ if (fixed[reason])
67
+ return fixed[reason];
68
+ if (reason.startsWith('root ')) {
69
+ const k = reason.slice(5);
70
+ return `its own ${FIELD_WORDS[k] ?? k}, unlike its main's`;
71
+ }
72
+ return `a layer's ${FIELD_WORDS[reason] ?? reason}, unlike its main's`;
73
+ }
45
74
  /** Keys that draw nothing, or name the node and its place: never compared. */
46
75
  const IGNORED = new Set(['id', 'parent', 'children', 'z', 'order', 'sourceId', 'fileInstance', 'fileSlotHost', 'fileFills', 'name', 'component', 'overrides', 'instanceOf', 'mainOf', 'setOf', 'variant',
47
76
  'layoutData', 'keepSize', 'remeasured', 'storedHeight', 'storedRow', 'storedBox', 'boxScale', 'locked', 'runs', 'styleAt', 'fill', 'look']);
@@ -79,7 +108,7 @@ const supportsFrameOverrides = 'layoutData.flow' in Properties;
79
108
  const linkedTextColor = (style) => style.fileFillStyle ? supportsRunPaint : !!style.fileTextColor;
80
109
  /** Can this occurrence inherit the main's fitted runs, including their colour sources? */
81
110
  function inheritsTextRuns(occurrence, main, runs, mainRuns, nativeFile) {
82
- const bound = occurrence.styles.some(linkedTextColor);
111
+ const bound = occurrence.styles.some((style) => linkedTextColor(style) || style.fileTypography);
83
112
  // A link alone cannot own a native instance palette. Wording with its own unbound formatting can.
84
113
  if (!bound && !(nativeFile && occurrence.content === main.content &&
85
114
  [...occurrence.styles, ...main.styles].some(style => style.link || style.figmaHyperlink)))
@@ -96,7 +125,12 @@ function inheritsTextRuns(occurrence, main, runs, mainRuns, nativeFile) {
96
125
  // A shared variable can draw a different literal in the occurrence's mode.
97
126
  if (!inherited)
98
127
  return false;
99
- const fitted = linkedTextColor(style) ? { ...style, color: inherited.color } : style;
128
+ const { fileOwnTypography: _own, ...fitted } = style;
129
+ if (linkedTextColor(style))
130
+ fitted.color = inherited.color;
131
+ for (const [field, ref] of Object.entries(style.fileTypography ?? {}))
132
+ if (ref && supportsTextField(field) && ref === inherited.fileTypography?.[field])
133
+ fitted[field] = inherited[field];
100
134
  if (!same(fitted, inherited)) {
101
135
  if (!nativeFile || !same({ ...fitted, link: inherited.link, figmaHyperlink: inherited.figmaHyperlink }, inherited))
102
136
  return false;
@@ -113,6 +147,10 @@ function applied(record, over) {
113
147
  for (const [key, value] of Object.entries(over)) {
114
148
  if (key === 'storedBox')
115
149
  continue;
150
+ if (key === 'layoutData.gridCell') {
151
+ out.layoutData = { ...out.layoutData, gridCell: { ...out.layoutData?.gridCell, ...value } };
152
+ continue;
153
+ }
116
154
  if (key === 'layoutData.flow') {
117
155
  const flow = value, data = out.layoutData;
118
156
  out.layoutData = { ...data, layout: { ...data?.layout, ...flow }, padding: { ...data?.layout?.padding, ...data?.padding, ...flow.padding } };
@@ -176,10 +214,9 @@ function difference(E, R, own, rootOverride = false, omitLink) {
176
214
  }
177
215
  else if (k === 'content' || k === 'styles' || k === 'para')
178
216
  continue; // the text body, below
179
- // An instance cannot override a text's line limit or ellipsis, so a linked instance shows its main's rather than
180
- // losing its link over them.
217
+ // A text's own line limit and ellipsis; null takes away its main's.
181
218
  else if (k === 'maxLines' || k === 'truncate')
182
- continue;
219
+ rec[k] = E[k] ?? null;
183
220
  else if ((k === 'stroke' || k === 'strokeWidth') && E.kind !== 'text')
184
221
  continue; // the stroke, below
185
222
  else
@@ -263,6 +300,12 @@ function dataOverride(own = {}, main = {}) {
263
300
  for (const k of new Set([...Object.keys(own), ...Object.keys(main)])) {
264
301
  if (same(own[k], main[k]))
265
302
  continue;
303
+ if (k === 'gridCell' && own[k]) {
304
+ if (Object.keys(main[k] ?? {}).some(field => !(field in own[k])))
305
+ return { layoutData: own };
306
+ out['layoutData.gridCell'] = Object.fromEntries(Object.entries(own[k]).filter(([field, v]) => v !== main[k]?.[field]));
307
+ continue;
308
+ }
266
309
  if (own[k] === undefined && !(k in NEUTRAL))
267
310
  return { layoutData: own };
268
311
  out[`layoutData.${k}`] = own[k] ?? NEUTRAL[k];
@@ -274,16 +317,22 @@ function withData(data, over) {
274
317
  if (!over)
275
318
  return data;
276
319
  let out = over.layoutData ?? data;
277
- for (const [k, v] of Object.entries(over))
278
- if (k.startsWith('layoutData.'))
320
+ for (const [k, v] of Object.entries(over)) {
321
+ if (k === 'layoutData.gridCell')
322
+ out = { ...out, gridCell: { ...out?.gridCell, ...v } };
323
+ else if (k.startsWith('layoutData.'))
279
324
  out = { ...out, [k.slice(11)]: v };
325
+ }
280
326
  return out;
281
327
  }
328
+ /** The axes on which layer E fills its auto layout parent P (Figma's layout grow or stretch) where P does not hug. */
329
+ const fillsIn = (E, P) => ['width', 'height'].filter((axis) => E.layoutData?.resizing?.[axis] === 'fill'
330
+ && sizingOf(P?.layoutData, axis) !== 'hug' && !!P?.layoutData?.layout && P.layoutData.layout.kind !== 'absolute');
282
331
  /** The content settings this frame changes relative to its component, including individual padding sides. */
283
- function flowOverride(own = {}, main = {}) {
332
+ function flowOverride(own = {}, main = {}, fills = []) {
284
333
  const a = own.layout ?? {}, b = main.layout ?? {};
285
334
  const flow = {};
286
- const defaults = { kind: 'absolute', gap: 0, align: 'start', justify: 'start', wrap: false,
335
+ const defaults = { kind: 'absolute', columnTracks: [], rowTracks: [], columnGap: 0, rowGap: 0, gap: 0, align: 'start', justify: 'start', wrap: false,
287
336
  wrapGap: a.gap ?? 0, alignContent: 'auto', widthSizing: 'fixed', heightSizing: 'fixed', strokesIncluded: false };
288
337
  for (const [key, fallback] of Object.entries(defaults)) {
289
338
  if (!same(a[key] ?? fallback, b[key] ?? fallback))
@@ -293,8 +342,12 @@ function flowOverride(own = {}, main = {}) {
293
342
  if (a.kind && a.kind !== 'absolute')
294
343
  for (const axis of ['width', 'height']) {
295
344
  const local = sizingOf(own, axis), inherited = sizingOf(main, axis);
296
- if (local !== inherited)
345
+ // Core reads a flow's sizing as the frame's own, over its fill and stored sizing (components.ts
346
+ // withInstanceSpacing): none where it shows the main's, nor where it fills its parent (Figma's fill wins there).
347
+ if (local !== inherited && !fills.includes(axis))
297
348
  flow[axis + 'Sizing'] = local;
349
+ else
350
+ delete flow[axis + 'Sizing'];
298
351
  }
299
352
  const pad = { ...a.padding, ...own.padding }, base = { ...b.padding, ...main.padding };
300
353
  const sides = Object.fromEntries(['top', 'right', 'bottom', 'left'].filter(k => (pad[k] ?? 0) !== (base[k] ?? 0)).map(k => [k, pad[k] ?? 0]));
@@ -315,10 +368,20 @@ function instanceData(E, P) {
315
368
  data.sizing = fixed(data.sizing);
316
369
  if (data.resizing)
317
370
  data.resizing = fixed(data.resizing);
318
- const auto = ['horizontal', 'vertical'].includes(E.layoutData?.layout?.kind);
371
+ const auto = ['horizontal', 'vertical', 'grid'].includes(E.layoutData?.layout?.kind);
319
372
  for (const axis of ['width', 'height'])
320
373
  if (auto && sizingOf(E.layoutData, axis) === 'fill' && sizingOf(P?.layoutData, axis) === 'hug')
321
374
  data.sizing = { ...data.sizing, [axis]: 'fixed' };
375
+ // Figma's fill (layout grow, stretch) wins over the frame's own Fixed sizing: the occurrence fills there (a navigation
376
+ // list across a fixed header), as its main's layer does.
377
+ for (const axis of auto ? fillsIn(E, P) : [])
378
+ if (data.sizing?.[axis] === 'fixed') {
379
+ const { [axis]: _held, ...rest } = data.sizing;
380
+ if (Object.keys(rest).length)
381
+ data.sizing = rest;
382
+ else
383
+ delete data.sizing;
384
+ }
322
385
  return data;
323
386
  }
324
387
  /** How far core's layout of a linked instance may place a layer from its expanded box (px; 1e-4 of the linear part)
@@ -368,9 +431,9 @@ export function linkWithLayers(doc, trackLayers = true, swapBinding, nativeFile
368
431
  const skip = new Set();
369
432
  for (;;) {
370
433
  const d = { models: doc.models }, aliases = new Map();
371
- const { once, omittedLinks, ...r } = linkOnce(d, skip, each, compareCosts, report ? aliases : undefined, swapBinding, nativeFile);
434
+ const { once, omittedLinks, expandedReasons, ...r } = linkOnce(d, skip, each, compareCosts, report ? aliases : undefined, swapBinding, nativeFile);
372
435
  if (!once.length)
373
- return { d, r, aliases, omittedLinks };
436
+ return { d, r, aliases, omittedLinks, expandedReasons };
374
437
  for (const comp of once)
375
438
  skip.add(comp);
376
439
  }
@@ -384,11 +447,11 @@ export function linkWithLayers(doc, trackLayers = true, swapBinding, nativeFile
384
447
  const W = 3, of = (m, c) => { const [n, k] = m.get(c) ?? [0, 0]; return n * W + k; };
385
448
  chosen = new Set([...sets].filter((c) => of(split, c) <= of(shared, c)));
386
449
  }
387
- const { d, r: { cost: _cost, ...r }, aliases, omittedLinks } = run(chosen, false, trackLayers);
450
+ const { d, r: { cost: _cost, ...r }, aliases, omittedLinks, expandedReasons } = run(chosen, false, trackLayers);
388
451
  // Detach only the linked output. Trial passes and discarded expansions never need deep copies.
389
452
  doc.models = nativeFile ? d.models : structuredClone(d.models);
390
453
  const counts = { ...r, variantSets: chosen.size, sharedSets: sets.size - chosen.size };
391
- return { counts, aliases, omittedLinks };
454
+ return { counts, aliases, omittedLinks, expandedReasons };
392
455
  }
393
456
  /** linkComponents with no hidden main for the components in `skip`; also returns the components whose hidden main is
394
457
  * used once (once). */
@@ -427,14 +490,12 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
427
490
  const before = doc.models.length;
428
491
  // Whether the layers under a frame draw outside its box, with their drop shadows and layer blurs where they reach
429
492
  // further than SLACK, as the renderer reaches them (the offset plus 1.5 blur and the spread; crates/scn-core
430
- // derived.rs effect_reach, with the spread shadow_spread draws: below 0 only on a frame with square corners);
431
- // clipping frames bound their own children.
432
- const square = (m) => m.kind === 'frame' && (Array.isArray(m.radius) ? m.radius.every((r) => !r) : !m.radius);
493
+ // derived.rs effect_reach); clipping frames bound their own children.
433
494
  const reach = (m) => {
434
495
  const blur = 1.5 * (m.look?.layerBlur?.radius ?? 0), out = [blur, blur, blur, blur]; // left, top, right, bottom
435
496
  for (const s of m.look?.shadows ?? [])
436
497
  if (!s.inner && s.c?.[3] !== 0) {
437
- const spread = square(m) ? s.spread ?? 0 : Math.max(0, s.spread ?? 0), x = s.x ?? 0, y = s.y ?? 0;
498
+ const spread = s.spread ?? 0, x = s.x ?? 0, y = s.y ?? 0;
438
499
  const e = 1.5 * (s.blur ?? 0) + spread;
439
500
  out[0] = Math.max(out[0], e - x);
440
501
  out[1] = Math.max(out[1], e - y);
@@ -672,7 +733,7 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
672
733
  if (typeof own === 'string')
673
734
  return own;
674
735
  }
675
- const inputs = n.instance ? flowOverride(E.layoutData, R.layoutData) : {};
736
+ const inputs = n.instance ? flowOverride(E.layoutData, R.layoutData, fillsIn(E, byId.get(E.parent))) : {};
676
737
  if (!supportsFrameOverrides && inputs['layoutData.flow'])
677
738
  return 'layout';
678
739
  if (n.instance)
@@ -751,7 +812,8 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
751
812
  }
752
813
  }
753
814
  }
754
- const state = new Map(), reasons = new Map();
815
+ // Per instance left expanded (by its id in the output): its first difference from its main.
816
+ const state = new Map(), reasons = new Map(), expandedReasons = new Map();
755
817
  let linked = 0;
756
818
  const ensure = (main) => { if (state.has(main))
757
819
  return; state.set(main, 'busy'); for (const c of [...kidsOf(main)])
@@ -772,7 +834,7 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
772
834
  if (typeof root === 'string')
773
835
  return `root ${root}`;
774
836
  const overrides = {}, geometry = new Map();
775
- const content = flowOverride(E.layoutData, M.layoutData);
837
+ const content = flowOverride(E.layoutData, M.layoutData, fillsIn(E, byId.get(E.parent)));
776
838
  if (!supportsFrameOverrides && content['layoutData.flow'])
777
839
  return 'root layout';
778
840
  if (root || Object.keys(content).length)
@@ -830,6 +892,7 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
830
892
  if (!r)
831
893
  return;
832
894
  reasons.set(r, (reasons.get(r) ?? 0) + 1);
895
+ expandedReasons.set(id, r);
833
896
  }
834
897
  for (const c of [...kidsOf(id)])
835
898
  walk(c);
@@ -888,5 +951,5 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
888
951
  for (const c of kidsOf('@components'))
889
952
  emit(c);
890
953
  doc.models = models;
891
- return { omittedLinks, cost, before, after: models.length, linked, mains: mains.size - hidden.size, hidden: [...hidden.keys()].filter((id) => used.has(id)).length, unlinked: reasons, once };
954
+ return { omittedLinks, expandedReasons, cost, before, after: models.length, linked, mains: mains.size - hidden.size, hidden: [...hidden.keys()].filter((id) => used.has(id)).length, unlinked: reasons, once };
892
955
  }
@@ -47,8 +47,8 @@ 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
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 };
@@ -29,7 +29,7 @@ type Modes = Record<string, string>;
29
29
  * @param collections - Source collections indexed by ID.
30
30
  * @returns A resolver that takes a variable name or ID and optional collection modes.
31
31
  */
32
- export declare function variableResolver(collections?: Record<string, VariableCollection>): (name: string, modes?: Modes, aliases?: Aliases) => 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;
33
33
  /**
34
34
  * The collections as taco's expression evaluator reads them (it follows no aliases, and reads a chosen mode only when
35
35
  * the collection's modes table has it): each collection with a modes table (made from the modes it names when it has
@@ -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
@@ -4,14 +4,14 @@ import { base64 } from './adapter/figma.js';
4
4
  import { fileComponents } from './adapter/file-components.js';
5
5
  import { keepDescription } from './adapter/figma-descriptions.js';
6
6
  import { figmaLayoutGrids, gridSources } from './adapter/figma-grids.js';
7
- import { figmaHandoff, handoffSources } from './adapter/figma-handoff.js';
7
+ import { figmaHandoff, handoffOverrides, handoffSources } from './adapter/figma-handoff.js';
8
8
  import { figmaHyperlinks } from './adapter/figma-hyperlinks.js';
9
9
  import { isObject } from './taco/figma-import/import/fields.js';
10
10
  import { sha256Hex } from './taco/model/sha256.js';
11
11
  import { expandedRadiusRoots, fileResources } from './adapter/file-resources.js';
12
12
  import { readFileMessage, walkMessage } from './taco/figma-import/import/walk.js';
13
13
  import { allPages, figmaClipboardPage } from './adapter/convert.js';
14
- import { convertEntries, droppedFeatures, figmaReportLayers, grouped, readerCount } from './report.js';
14
+ import { convertEntries, droppedFeatures, figmaReportLayers, fontEntries, grouped, leftOutIds, readerCount } from './report.js';
15
15
  import { checkAbort } from './figma-file.js';
16
16
  import { readFigFile, readFigmaClipboardHtml } from './taco/figma-import/index.js';
17
17
  /**
@@ -25,9 +25,13 @@ export const MISSING_IMAGES = clipboard.MISSING_IMAGE_REPORT;
25
25
  const STAND_IN = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
26
26
  const ids = () => { let next = 0; return () => `f${++next}`; };
27
27
  function reportOf(result, converted, features, extra, file = false) {
28
- const { bySource, pages, fonts, derive } = figmaReportLayers(converted.doc, file);
28
+ const { bySource, pages, derive } = figmaReportLayers(converted.doc, file);
29
29
  const dropped = [];
30
- for (const { figmaId, what } of features) {
30
+ for (const { figmaId, what, leftOut } of features) {
31
+ if (leftOut) {
32
+ dropped.push({ kind: 'left-out', what, count: 1 });
33
+ continue;
34
+ }
31
35
  const layer = result.layerIds[figmaId];
32
36
  if (layer === undefined)
33
37
  continue;
@@ -39,9 +43,9 @@ function reportOf(result, converted, features, extra, file = false) {
39
43
  const layer = result.layerIds[entry.nodeId];
40
44
  const pageId = pageIds.get(entry.nodeId);
41
45
  const ids = pageId ? [pageId] : layer === undefined ? undefined : bySource.get(layer);
42
- return { kind: entry.kind === 'approximated' ? 'approximated' : 'left-out', ...readerCount(entry.reason), ...(ids && { ids }) };
46
+ return { kind: entry.kind === 'approximated' ? 'approximated' : 'left-out', ...readerCount(entry), ...(ids && { ids }) };
43
47
  });
44
- return { report: grouped([...reader, ...dropped, ...convertEntries(converted.report, true), ...extra, ...fonts]), derive };
48
+ return { report: [...reader, ...dropped, ...convertEntries(converted.report, true), ...extra], derive };
45
49
  }
46
50
  /**
47
51
  * Imports Figma clipboard HTML as editable layers.
@@ -50,14 +54,15 @@ function reportOf(result, converted, features, extra, file = false) {
50
54
  * @throws An error if the input contains no readable Figma layers.
51
55
  */
52
56
  export function readFigmaClipboard(html) {
53
- const { meta, message } = readFigmaClipboardHtml(html), missing = new Set();
57
+ const { meta, message } = readFigmaClipboardHtml(html);
54
58
  const { result, sources } = walkMessage(message, {
55
59
  idSource: ids(), roots: 'clipboard-selection', bindVariables: false, textStyles: false,
56
- images: (hash) => { missing.add(`figma-image-${hash}`); return { bytes: STAND_IN, mimeType: 'image/png' }; },
60
+ images: () => ({ bytes: STAND_IN, mimeType: 'image/png', placeholder: true }),
57
61
  }, false, tree => new Set([...handoffSources(tree), ...gridSources(tree)]));
58
62
  const instanceSources = new Map();
59
63
  const converted = figmaClipboardPage(figmaDocument(result, 'Pasted'), instanceSources);
60
- const extra = figmaHandoff(result, sources, converted.doc, { instanceSources });
64
+ const leftOut = leftOutIds(sources);
65
+ const extra = figmaHandoff(result, sources, converted.doc, { instanceSources, leftOut, overrides: handoffOverrides(sources.tree) });
61
66
  extra.push(...figmaHyperlinks(result, sources, converted.doc, { instanceSources }));
62
67
  let fileKey = meta.fileKey;
63
68
  for (const entry of figmaLayoutGrids(sources, converted.doc, { instanceSources,
@@ -78,15 +83,16 @@ export function readFigmaClipboard(html) {
78
83
  keepDescription(source, model, extra);
79
84
  }
80
85
  const { payload } = toPayload(converted);
81
- const assetIds = [...missing].filter((id) => Object.hasOwn(payload.assets, id));
86
+ const assetIds = Object.values(result.assets).filter(a => a.placeholder && Object.hasOwn(payload.assets, a.id)).map(a => a.id);
82
87
  for (const id of assetIds)
83
88
  delete payload.assets[id];
84
89
  if (assetIds.length)
85
90
  extra.push({ kind: 'left-out', what: MISSING_IMAGES, count: assetIds.length, assetIds });
86
- return { payload, report: reportOf(result, converted, droppedFeatures(message.nodeChanges), extra).report };
91
+ return { payload, report: grouped(reportOf(result, converted, droppedFeatures(message.nodeChanges, leftOut), extra).report) };
87
92
  }
88
93
  /**
89
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.
90
96
  * @param bytes - Saved Figma design file.
91
97
  * @param options - Cancellation and progress options.
92
98
  * @returns All public pages in file order, editable component and resource records, images and a report of font faces and conversion losses.
@@ -113,14 +119,23 @@ export function readFigmaFile(bytes, options = {}) {
113
119
  for (const model of doc.models)
114
120
  if (model.kind === 'frame' && model.overrides)
115
121
  model.overrides = core.doc.owned(model.overrides, undefined, true);
116
- core.prepareOwnedLoad(doc)();
117
- document = core.toJSON();
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();
118
128
  }
119
129
  // Only surviving assets need data URLs. Keep their encoded strings out of the layout and linking passes.
120
- for (const [id, asset] of Object.entries(document.assets ?? {}))
121
- asset.src += base64(images[id].bytes);
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
+ }
122
137
  checkpoint('convert', total, total);
123
- return { document, report };
138
+ return { document, report: grouped([...report, ...fontEntries(document)]) };
124
139
  }
125
140
  // Derived instance entries describe Figma's layout. Their path, box and stored line
126
141
  // heights are the inputs to instanceFields. Authored overrides are read separately.
@@ -186,7 +201,10 @@ function convertFile(bytes, decoded) {
186
201
  yield change;
187
202
  }
188
203
  }
189
- const features = [...droppedFeatures(sources())];
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)];
190
208
  const geometry = figmaDocument(result, undefined, () => '');
191
209
  if (result.sources.variables)
192
210
  geometry.variableAliases = result.sources.variables.aliases;
@@ -201,7 +219,11 @@ function convertFile(bytes, decoded) {
201
219
  assetSrc: (_id, asset) => `data:${asset.mimeType};base64,`,
202
220
  });
203
221
  const extra = [];
204
- const { occurrences, setSources } = fileComponents(result, converted.doc, converted.nestedBooleans, extra);
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);
205
227
  let fileKey = key;
206
228
  const fileId = () => String(fileKey ||= sha256Hex(bytes));
207
229
  fileResources(result, converted.doc, occurrences, converted.expanded, expandedRadii, extra, fileId);
@@ -216,7 +238,7 @@ function convertFile(bytes, decoded) {
216
238
  }
217
239
  for (const entry of figmaHyperlinks(result, result.sources, converted.doc, { setSources }))
218
240
  extra.push(entry);
219
- for (const entry of figmaHandoff(result, result.sources, converted.doc, { setSources }))
241
+ for (const entry of figmaHandoff(result, result.sources, converted.doc, { setSources, leftOut, overrides }))
220
242
  extra.push(entry);
221
243
  for (const entry of figmaLayoutGrids(result.sources, converted.doc, { setSources, fileId }))
222
244
  extra.push(entry);
package/dist/report.d.ts CHANGED
@@ -1,10 +1,14 @@
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
+ import type { FigmaTreeNode } from './taco/figma-import/import/tree.ts';
4
5
  /** The most layer IDs a grouped entry keeps as examples. */
5
6
  export declare const EXAMPLE_IDS = 5;
6
- /** The occurrence count a reader summary carries in its reason (`… (3 times, first here)`), moved into `count`. */
7
- export declare function readerCount(reason: string): {
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
+ }): {
8
12
  what: string;
9
13
  count: number;
10
14
  };
@@ -18,10 +22,38 @@ export declare function grouped(entries: Iterable<ImportReportEntry>): ImportRep
18
22
  export declare const DROPPED_FEATURES: {
19
23
  readonly interactions: 'prototype interactions are not imported';
20
24
  };
21
- /** Unsupported features in source order. Linking supplies their final layer IDs later. */
22
- export declare function droppedFeatures(changes: Iterable<unknown> | undefined): Generator<{
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<{
23
54
  figmaId: string;
24
- what: "prototype interactions are not imported";
55
+ leftOut: boolean;
56
+ what: string;
25
57
  }, void, unknown>;
26
58
  /** Builds a lookup from reader IDs to their converted layers. */
27
59
  export declare function layersBySource(document: DocumentJSON): Map<string, string[]>;
@@ -29,7 +61,6 @@ export declare function layersBySource(document: DocumentJSON): Map<string, stri
29
61
  export declare function figmaReportLayers(document: DocumentJSON, file: boolean): {
30
62
  bySource: Map<string, string[]>;
31
63
  pages: string[];
32
- fonts: ImportReportEntry[];
33
64
  derive: boolean;
34
65
  };
35
66
  /** Turns adapter diagnostics into import reports. */