@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
@@ -6,8 +6,9 @@
6
6
  // frame naming the main, with no children, whose overrides (by layer path, SPEC 19.3) hold what its expanded layers
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
- // 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
9
+ // that takes no override (a path's network that core's layout of the instance does not give, a stroke's position or
10
+ // weight, a layer the main lacks, the root's own fills) stays expanded, and so do the instances inside it, which are
11
+ // linked on their own when they can be; the 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
@@ -21,15 +22,20 @@
21
22
  // differ, beside the transforms and sizes the page was linked with (settle.mjs makes those the editor's own). Core
22
23
  // lays an instance out again (packages/editor/src/core/layout/layout.ts instanceLayout) only when it or its main
23
24
  // changes, and the transforms and sizes it writes then are its output alone; where that layout, run here, does not
24
- // give a layer's linked box (within 0.01 px), the box is stored too (storedBox, with the instance's size), and core's
25
- // layout starts from it until the main edits that layer's box.
25
+ // give a layer's linked box (within 0.01 px), the box is stored too, whole (storedBox: transform and size, with the
26
+ // instance's size), and core's layout starts from it until the main edits that layer's box. A layer an auto layout
27
+ // places where the expansion holds its main's box (Figma stated none) stores none and shows the layout's place.
26
28
  // - An instance has no children to hug: where its expanded root is an auto layout filling a parent that hugs it, the
27
29
  // parent hugged that root's content (layout.mjs natural), so the instance keeps its size there ('fixed') and the
28
30
  // parent lays out as it did.
29
- // - What the renderer does differently from core is avoided: it culls an instance's content by the instance's box (an
30
- // 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
- // reaches well past it, stays expanded); its text body field carries the text's box (see difference).
31
+ // - A path's network that the instance's resize reshapes (scale or stretch constraints, a fill) is layout's output, as
32
+ // its box is: linked where core's layout of the instance gives it (keep, within EPSILON), and stored beside the
33
+ // boxes, so a later edit of the main's network reaches the instance scaled.
34
+ // - Content that draws outside the instance's box links too: the renderer bounds an instance by its content's paint
35
+ // (crates/scn-core instances.rs instance_subtree_bounds). Its text body field carries the text's box (see
36
+ // difference).
32
37
  // The markers are removed whether or not anything is linked.
38
+ import { supportsTextField } from './file-typography.js';
33
39
  import { Properties, TextStyleSchema } from '@moondraft/editor/schema';
34
40
  import { instanceLayout, legacyAuto, netBounds, sizingOf } from '@moondraft/editor/core';
35
41
  /** The converter's markers on the expanded models (instanceOf, mainOf, and setOf: an instance's variant set name). */
@@ -42,6 +48,35 @@ const componentOf = (vk) => vk.split('\u0000')[0];
42
48
  */
43
49
  export const unmark = (m) => { for (const k of MARKERS)
44
50
  delete m[k]; };
51
+ /** Plain descriptions of the fields an expansion can differ in (difference, match), for the import report. */
52
+ const FIELD_WORDS = {
53
+ fills: 'fills', stroke: 'stroke', 'look.stroke': 'stroke position, cap or join', strokeWidth: 'stroke weight',
54
+ 'look.stroke.paint': 'stroke paint', effects: 'shadows or blurs', clip: 'clipping', layout: 'auto layout settings',
55
+ net: 'vector network', kind: 'layer type', result: 'boolean result', 'radius bindings': 'corner radius bindings',
56
+ };
57
+ /**
58
+ * Describes in plain words why an instance stays expanded, from linking's reason for it (LinkCounts.unlinked).
59
+ * @param reason - Linking's reason.
60
+ * @returns What the report says after "expanded instance: ".
61
+ */
62
+ export function expansionReason(reason) {
63
+ const fixed = {
64
+ 'used once': 'its component has no main on the page and no other instance', 'no main': 'its component has no main',
65
+ 'not a frame': 'it is not a frame',
66
+ 'inside its main': 'it is inside its own main', 'layer order': 'its layers are in another order than its main\'s',
67
+ 'a layer the main lacks': 'it has a layer its main lacks', 'conflicting bound swaps': 'one swap property selects different mains in it',
68
+ 'conflicting bound text': 'texts bound to one text property show different wording in it',
69
+ net: 'a vector network its main\'s layout does not give',
70
+ 'partial box': 'a layer with a width but no height, or the reverse, whose box its main\'s layout does not give',
71
+ };
72
+ if (fixed[reason])
73
+ return fixed[reason];
74
+ if (reason.startsWith('root ')) {
75
+ const k = reason.slice(5);
76
+ return `its own ${FIELD_WORDS[k] ?? k}, unlike its main's`;
77
+ }
78
+ return `a layer's ${FIELD_WORDS[reason] ?? reason}, unlike its main's`;
79
+ }
45
80
  /** Keys that draw nothing, or name the node and its place: never compared. */
46
81
  const IGNORED = new Set(['id', 'parent', 'children', 'z', 'order', 'sourceId', 'fileInstance', 'fileSlotHost', 'fileFills', 'name', 'component', 'overrides', 'instanceOf', 'mainOf', 'setOf', 'variant',
47
82
  'layoutData', 'keepSize', 'remeasured', 'storedHeight', 'storedRow', 'storedBox', 'boxScale', 'locked', 'runs', 'styleAt', 'fill', 'look']);
@@ -79,7 +114,7 @@ const supportsFrameOverrides = 'layoutData.flow' in Properties;
79
114
  const linkedTextColor = (style) => style.fileFillStyle ? supportsRunPaint : !!style.fileTextColor;
80
115
  /** Can this occurrence inherit the main's fitted runs, including their colour sources? */
81
116
  function inheritsTextRuns(occurrence, main, runs, mainRuns, nativeFile) {
82
- const bound = occurrence.styles.some(linkedTextColor);
117
+ const bound = occurrence.styles.some((style) => linkedTextColor(style) || style.fileTypography);
83
118
  // A link alone cannot own a native instance palette. Wording with its own unbound formatting can.
84
119
  if (!bound && !(nativeFile && occurrence.content === main.content &&
85
120
  [...occurrence.styles, ...main.styles].some(style => style.link || style.figmaHyperlink)))
@@ -96,7 +131,12 @@ function inheritsTextRuns(occurrence, main, runs, mainRuns, nativeFile) {
96
131
  // A shared variable can draw a different literal in the occurrence's mode.
97
132
  if (!inherited)
98
133
  return false;
99
- const fitted = linkedTextColor(style) ? { ...style, color: inherited.color } : style;
134
+ const { fileOwnTypography: _own, ...fitted } = style;
135
+ if (linkedTextColor(style))
136
+ fitted.color = inherited.color;
137
+ for (const [field, ref] of Object.entries(style.fileTypography ?? {}))
138
+ if (ref && supportsTextField(field) && ref === inherited.fileTypography?.[field])
139
+ fitted[field] = inherited[field];
100
140
  if (!same(fitted, inherited)) {
101
141
  if (!nativeFile || !same({ ...fitted, link: inherited.link, figmaHyperlink: inherited.figmaHyperlink }, inherited))
102
142
  return false;
@@ -113,6 +153,10 @@ function applied(record, over) {
113
153
  for (const [key, value] of Object.entries(over)) {
114
154
  if (key === 'storedBox')
115
155
  continue;
156
+ if (key === 'layoutData.gridCell') {
157
+ out.layoutData = { ...out.layoutData, gridCell: { ...out.layoutData?.gridCell, ...value } };
158
+ continue;
159
+ }
116
160
  if (key === 'layoutData.flow') {
117
161
  const flow = value, data = out.layoutData;
118
162
  out.layoutData = { ...data, layout: { ...data?.layout, ...flow }, padding: { ...data?.layout?.padding, ...data?.padding, ...flow.padding } };
@@ -155,7 +199,7 @@ function difference(E, R, own, rootOverride = false, omitLink) {
155
199
  rec.w = E.w;
156
200
  rec.h = E.h;
157
201
  }
158
- // Layout owns a stretched path's network override. keep() checks it against the
202
+ // Layout owns a resized path's network override. keep() checks it against the
159
203
  // main laid out with all sibling overrides and stored boxes before accepting the link.
160
204
  else if (k === 'net' && E.kind === 'path' && own)
161
205
  rec.net = E.net;
@@ -176,10 +220,9 @@ function difference(E, R, own, rootOverride = false, omitLink) {
176
220
  }
177
221
  else if (k === 'content' || k === 'styles' || k === 'para')
178
222
  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.
223
+ // A text's own line limit and ellipsis; null takes away its main's.
181
224
  else if (k === 'maxLines' || k === 'truncate')
182
- continue;
225
+ rec[k] = E[k] ?? null;
183
226
  else if ((k === 'stroke' || k === 'strokeWidth') && E.kind !== 'text')
184
227
  continue; // the stroke, below
185
228
  else
@@ -263,6 +306,12 @@ function dataOverride(own = {}, main = {}) {
263
306
  for (const k of new Set([...Object.keys(own), ...Object.keys(main)])) {
264
307
  if (same(own[k], main[k]))
265
308
  continue;
309
+ if (k === 'gridCell' && own[k]) {
310
+ if (Object.keys(main[k] ?? {}).some(field => !(field in own[k])))
311
+ return { layoutData: own };
312
+ out['layoutData.gridCell'] = Object.fromEntries(Object.entries(own[k]).filter(([field, v]) => v !== main[k]?.[field]));
313
+ continue;
314
+ }
266
315
  if (own[k] === undefined && !(k in NEUTRAL))
267
316
  return { layoutData: own };
268
317
  out[`layoutData.${k}`] = own[k] ?? NEUTRAL[k];
@@ -274,16 +323,22 @@ function withData(data, over) {
274
323
  if (!over)
275
324
  return data;
276
325
  let out = over.layoutData ?? data;
277
- for (const [k, v] of Object.entries(over))
278
- if (k.startsWith('layoutData.'))
326
+ for (const [k, v] of Object.entries(over)) {
327
+ if (k === 'layoutData.gridCell')
328
+ out = { ...out, gridCell: { ...out?.gridCell, ...v } };
329
+ else if (k.startsWith('layoutData.'))
279
330
  out = { ...out, [k.slice(11)]: v };
331
+ }
280
332
  return out;
281
333
  }
334
+ /** The axes on which layer E fills its auto layout parent P (Figma's layout grow or stretch) where P does not hug. */
335
+ const fillsIn = (E, P) => ['width', 'height'].filter((axis) => E.layoutData?.resizing?.[axis] === 'fill'
336
+ && sizingOf(P?.layoutData, axis) !== 'hug' && !!P?.layoutData?.layout && P.layoutData.layout.kind !== 'absolute');
282
337
  /** The content settings this frame changes relative to its component, including individual padding sides. */
283
- function flowOverride(own = {}, main = {}) {
338
+ function flowOverride(own = {}, main = {}, fills = []) {
284
339
  const a = own.layout ?? {}, b = main.layout ?? {};
285
340
  const flow = {};
286
- const defaults = { kind: 'absolute', gap: 0, align: 'start', justify: 'start', wrap: false,
341
+ const defaults = { kind: 'absolute', columnTracks: [], rowTracks: [], columnGap: 0, rowGap: 0, gap: 0, align: 'start', justify: 'start', wrap: false,
287
342
  wrapGap: a.gap ?? 0, alignContent: 'auto', widthSizing: 'fixed', heightSizing: 'fixed', strokesIncluded: false };
288
343
  for (const [key, fallback] of Object.entries(defaults)) {
289
344
  if (!same(a[key] ?? fallback, b[key] ?? fallback))
@@ -293,8 +348,12 @@ function flowOverride(own = {}, main = {}) {
293
348
  if (a.kind && a.kind !== 'absolute')
294
349
  for (const axis of ['width', 'height']) {
295
350
  const local = sizingOf(own, axis), inherited = sizingOf(main, axis);
296
- if (local !== inherited)
351
+ // Core reads a flow's sizing as the frame's own, over its fill and stored sizing (components.ts
352
+ // withInstanceSpacing): none where it shows the main's, nor where it fills its parent (Figma's fill wins there).
353
+ if (local !== inherited && !fills.includes(axis))
297
354
  flow[axis + 'Sizing'] = local;
355
+ else
356
+ delete flow[axis + 'Sizing'];
298
357
  }
299
358
  const pad = { ...a.padding, ...own.padding }, base = { ...b.padding, ...main.padding };
300
359
  const sides = Object.fromEntries(['top', 'right', 'bottom', 'left'].filter(k => (pad[k] ?? 0) !== (base[k] ?? 0)).map(k => [k, pad[k] ?? 0]));
@@ -315,27 +374,63 @@ function instanceData(E, P) {
315
374
  data.sizing = fixed(data.sizing);
316
375
  if (data.resizing)
317
376
  data.resizing = fixed(data.resizing);
318
- const auto = ['horizontal', 'vertical'].includes(E.layoutData?.layout?.kind);
377
+ const auto = ['horizontal', 'vertical', 'grid'].includes(E.layoutData?.layout?.kind);
319
378
  for (const axis of ['width', 'height'])
320
379
  if (auto && sizingOf(E.layoutData, axis) === 'fill' && sizingOf(P?.layoutData, axis) === 'hug')
321
380
  data.sizing = { ...data.sizing, [axis]: 'fixed' };
381
+ // Figma's fill (layout grow, stretch) wins over the frame's own Fixed sizing: the occurrence fills there (a navigation
382
+ // list across a fixed header), as its main's layer does.
383
+ for (const axis of auto ? fillsIn(E, P) : [])
384
+ if (data.sizing?.[axis] === 'fixed') {
385
+ const { [axis]: _held, ...rest } = data.sizing;
386
+ if (Object.keys(rest).length)
387
+ data.sizing = rest;
388
+ else
389
+ delete data.sizing;
390
+ }
322
391
  return data;
323
392
  }
324
393
  /** How far core's layout of a linked instance may place a layer from its expanded box (px; 1e-4 of the linear part)
325
394
  * before the box is stored. */
326
395
  const EPSILON = 0.01;
327
- /** How far (px) a layer's shadow or blur may reach past its box and still count as inside it (overflows). The renderer
328
- * bounds an instance by its own box and its root's effects, not its content's: a card's 56 px shadow tail inside a
329
- * Modal instance was cut 22 px below it, while the HeroUI pages' tails of up to 8 px drew as expanded. */
330
- const SLACK = 8;
331
- /** Whether core's layout of an instance (laid: its output for the layer, absent where it shows its main's R) gives the
332
- * expanded record E's transform and size. */
333
- function gives(laid, { E, R }) {
334
- const t = laid?.t ?? R.t ?? [1, 0, 0, 1, 0, 0], e = E.t ?? [1, 0, 0, 1, 0, 0];
335
- if (t.some((v, i) => Math.abs(v - e[i]) > (i < 4 ? 1e-4 : EPSILON)))
396
+ const IDENTITY = [1, 0, 0, 1, 0, 0];
397
+ const nearT = (a, b) => !(a ?? IDENTITY).some((v, i) => Math.abs(v - (b ?? IDENTITY)[i]) > (i < 4 ? 1e-4 : EPSILON));
398
+ const near = (a, b) => a === b || (a !== undefined && b !== undefined && Math.abs(a - b) <= EPSILON);
399
+ /** Whether the expanded record E (in its parent P) has a box of its own: a transform or a size other than its main's
400
+ * layer R shows (as Figma's derived entry for a layer gives its box whole, a part it leaves out being its main's). A
401
+ * layer of an auto layout at its main's size is one Figma stated no size for where its main's box no longer fits its
402
+ * parent's width (outside: a layer that fills its parent at its main's width in a narrower parent, a layer past the end
403
+ * of a narrower parent) or Figma laid it out anew (layoutData.relaid, rehug: a nested instance re-hugging its text): the instance's
404
+ * auto layout sizes and places it, as a load's layout of the expanded layers does, whatever place the expansion gives
405
+ * it. That layout moves no other layer: one that still fits, a group (its box is its layers') and one outside a flow
406
+ * (its constraints act only on a resize) keep their boxes, so each has one. */
407
+ function states(E, R, P) {
408
+ const flows = ['horizontal', 'vertical', 'grid'].includes(P?.layoutData?.layout?.kind) && E.layoutData?.layoutPositioning !== 'absolute';
409
+ const free = flows && !E.group && (outside(E, P) || !!E.layoutData?.relaid || !!E.layoutData?.rehug);
410
+ return !free || !near(E.w, R.w) || !near(E.h, R.h);
411
+ }
412
+ /** Whether layer E's box (unrotated) reaches past either side of its parent P's width. Only the width: a load's layout
413
+ * of the expanded layers keeps one past its parent's bottom where it was (a third line in a two-line box). */
414
+ function outside(E, P) {
415
+ const t = E.t ?? IDENTITY;
416
+ if (!P || P.w === undefined || !nearT([...t.slice(0, 4), 0, 0], IDENTITY) || E.w === undefined)
336
417
  return false;
337
- const size = (k) => (laid && k in laid ? laid[k] : R[k]);
338
- return ['w', 'h'].every((k) => E[k] === size(k) || (E[k] !== undefined && size(k) !== undefined && Math.abs(E[k] - size(k)) <= EPSILON));
418
+ return t[4] < -EPSILON || t[4] + E.w > P.w + EPSILON;
419
+ }
420
+ /** Whether core's layout of an instance (laid: its output for the layer, absent where it shows its main's R) gives
421
+ * the expanded record E's transform and size, where E has a box of its own (own). */
422
+ function gives(laid, { E, R, own }) {
423
+ if (!own)
424
+ return true;
425
+ return nearT(laid?.t ?? R.t, E.t) && ['w', 'h'].every((k) => near(E[k], laid && k in laid ? laid[k] : R[k]));
426
+ }
427
+ /** The box stored for a layer whose own box the instance's layout does not give (keep): E's transform and size, whole,
428
+ * at the instance's size `at`. A stored box holds both sizes or neither, so a layer with a width but no height, or the
429
+ * reverse, has none (undefined): the instance stays expanded. */
430
+ function wholeBox(E, at) {
431
+ if (('w' in E) !== ('h' in E))
432
+ return undefined;
433
+ return { t: [...(E.t ?? IDENTITY)], ...('w' in E && { w: E.w, h: E.h }), at };
339
434
  }
340
435
  /** Links the instances of a converted page (its models, in file order) to their mains, in place. Returns counts.
341
436
  * A hidden main only one instance would use (not a main on the page) costs more than that instance's expansion, so
@@ -348,7 +443,7 @@ export function linkComponents(doc) {
348
443
  return linkWithLayers(doc, false).counts;
349
444
  }
350
445
  /** @internal Links components and tracks where their expanded layers went for import reports. */
351
- export function linkWithLayers(doc, trackLayers = true, swapBinding, nativeFile = false) {
446
+ export function linkWithLayers(doc, trackLayers = true, binding, nativeFile = false) {
352
447
  // Variant sets (convert.ts markSet): one hidden main per variant used, so each instance's main is its own variant
353
448
  // and its overrides are its own changes alone; but a showcase of a set (each variant once or twice) costs a main per
354
449
  // variant. So per set: the page is linked both ways and a set keeps a main per variant where that stores no more
@@ -368,9 +463,9 @@ export function linkWithLayers(doc, trackLayers = true, swapBinding, nativeFile
368
463
  const skip = new Set();
369
464
  for (;;) {
370
465
  const d = { models: doc.models }, aliases = new Map();
371
- const { once, omittedLinks, ...r } = linkOnce(d, skip, each, compareCosts, report ? aliases : undefined, swapBinding, nativeFile);
466
+ const { once, omittedLinks, expandedReasons, ...r } = linkOnce(d, skip, each, compareCosts, report ? aliases : undefined, binding, nativeFile);
372
467
  if (!once.length)
373
- return { d, r, aliases, omittedLinks };
468
+ return { d, r, aliases, omittedLinks, expandedReasons };
374
469
  for (const comp of once)
375
470
  skip.add(comp);
376
471
  }
@@ -384,15 +479,15 @@ export function linkWithLayers(doc, trackLayers = true, swapBinding, nativeFile
384
479
  const W = 3, of = (m, c) => { const [n, k] = m.get(c) ?? [0, 0]; return n * W + k; };
385
480
  chosen = new Set([...sets].filter((c) => of(split, c) <= of(shared, c)));
386
481
  }
387
- const { d, r: { cost: _cost, ...r }, aliases, omittedLinks } = run(chosen, false, trackLayers);
482
+ const { d, r: { cost: _cost, ...r }, aliases, omittedLinks, expandedReasons } = run(chosen, false, trackLayers);
388
483
  // Detach only the linked output. Trial passes and discarded expansions never need deep copies.
389
484
  doc.models = nativeFile ? d.models : structuredClone(d.models);
390
485
  const counts = { ...r, variantSets: chosen.size, sharedSets: sets.size - chosen.size };
391
- return { counts, aliases, omittedLinks };
486
+ return { counts, aliases, omittedLinks, expandedReasons };
392
487
  }
393
488
  /** linkComponents with no hidden main for the components in `skip`; also returns the components whose hidden main is
394
489
  * used once (once). */
395
- function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFile = false) {
490
+ function linkOnce(doc, skip, each, compareCosts, aliases, binding, nativeFile = false) {
396
491
  const omittedLinks = new Map();
397
492
  const recordAlias = (from, to) => {
398
493
  if (!aliases)
@@ -425,43 +520,6 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
425
520
  const kidsOf = (id) => kids.get(id) ?? [];
426
521
  const size = (id) => 1 + kidsOf(id).reduce((n, c) => n + size(c), 0);
427
522
  const before = doc.models.length;
428
- // Whether the layers under a frame draw outside its box, with their drop shadows and layer blurs where they reach
429
- // 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);
433
- const reach = (m) => {
434
- const blur = 1.5 * (m.look?.layerBlur?.radius ?? 0), out = [blur, blur, blur, blur]; // left, top, right, bottom
435
- for (const s of m.look?.shadows ?? [])
436
- 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;
438
- const e = 1.5 * (s.blur ?? 0) + spread;
439
- out[0] = Math.max(out[0], e - x);
440
- out[1] = Math.max(out[1], e - y);
441
- out[2] = Math.max(out[2], e + x);
442
- out[3] = Math.max(out[3], e + y);
443
- }
444
- return out.map((v) => (v > SLACK ? v : 0));
445
- };
446
- const mul = (A, B) => [A[0] * B[0] + A[2] * B[1], A[1] * B[0] + A[3] * B[1], A[0] * B[2] + A[2] * B[3], A[1] * B[2] + A[3] * B[3], A[0] * B[4] + A[2] * B[5] + A[4], A[1] * B[4] + A[3] * B[5] + A[5]];
447
- function overflows(root) {
448
- const R = byId.get(root), stack = kidsOf(root).map((c) => [c, byId.get(c).t]);
449
- while (stack.length) {
450
- const [id, T] = stack.pop(), m = byId.get(id);
451
- if (m.visible === false)
452
- continue;
453
- const b = m.kind === 'path' ? netBounds(m.net) : { x: 0, y: 0, width: m.w ?? 0, height: m.h ?? 0 }, [l, t, r, u] = reach(m);
454
- for (const [x, y] of [[b.x - l, b.y - t], [b.x + b.width + r, b.y - t], [b.x - l, b.y + b.height + u], [b.x + b.width + r, b.y + b.height + u]]) {
455
- const X = T[0] * x + T[2] * y + T[4], Y = T[1] * x + T[3] * y + T[5];
456
- if (X < -0.5 || Y < -0.5 || X > R.w + 0.5 || Y > R.h + 0.5)
457
- return true;
458
- }
459
- if (!m.clip)
460
- for (const c of kidsOf(id))
461
- stack.push([c, mul(T, byId.get(c).t)]);
462
- }
463
- return false;
464
- }
465
523
  const key = (m) => m.fileInstance ?? m.sourceId ?? `~${m.kind}~${m.name ?? ''}`;
466
524
  // Hidden mains (taken before anything is linked): a copy of each component's largest expansion, with every layer
467
525
  // another expansion has and it lacks, hidden (see union).
@@ -573,22 +631,21 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
573
631
  root.name = vk === comp ? E0.setOf : `${E0.setOf}/${E0.variant}`;
574
632
  unmark(root);
575
633
  root.mainOf = comp;
576
- // An expansion that stays expanded whatever its main (its layers draw outside it, or in another order) adds nothing.
577
- for (const id of frames.slice(1))
578
- if (byId.get(id).clip || !overflows(id)) {
579
- const p = plan(id, root.id);
580
- if (p)
581
- union(root.id, p);
582
- }
634
+ // An expansion that stays expanded whatever its main (its layers in another order) adds nothing.
635
+ for (const id of frames.slice(1)) {
636
+ const p = plan(id, root.id);
637
+ if (p)
638
+ union(root.id, p);
639
+ }
583
640
  mains.set(vk, root.id);
584
641
  hidden.set(root.id, vk);
585
642
  }
586
643
  const isInstance = (m) => m?.kind === 'frame' && m.component !== undefined && m.component !== m.id;
587
644
  // A main's effective tree: per layer, its path (from the main's child down), what it shows and its children.
588
- const trees = new Map();
645
+ const trees = new Map(), laidOut = new WeakMap();
589
646
  function swappedNode(n, main) {
590
647
  ensure(main);
591
- return { ...n, main, rec: n.recordOf(main), kids: n.childrenOf(main) };
648
+ return { ...n, main, rec: n.recordOf(main), raw: undefined, kids: n.childrenOf(main) };
592
649
  }
593
650
  function reroot(n, prefix, overrides) {
594
651
  const over = overrides?.[n.path];
@@ -596,7 +653,18 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
596
653
  n = swappedNode(n, over.component);
597
654
  // Keep each holder's overrides in scope when a later placement chooses another main.
598
655
  const underHolder = (child) => reroot(child, prefix, overrides);
599
- return { ...n, path: `${prefix};${n.path}`, rec: over ? applied(n.rec, over) : n.rec,
656
+ // raw: what it shows with the boxes its holders' links had before keep gave them the layout's (laidOut): what the
657
+ // expansion of an instance around it holds where Figma stated no box of its own.
658
+ const was = over && laidOut.get(over), rawOver = was && { ...over };
659
+ if (rawOver)
660
+ for (const k of ['t', 'w', 'h']) {
661
+ if (k in was)
662
+ rawOver[k] = was[k];
663
+ else
664
+ delete rawOver[k];
665
+ }
666
+ const raw = rawOver ? applied(n.raw ?? n.rec, rawOver) : over && n.raw ? applied(n.raw, over) : n.raw;
667
+ return { ...n, path: `${prefix};${n.path}`, rec: over ? applied(n.rec, over) : n.rec, raw,
600
668
  ...(n.instance && over && { recordOf: (main) => applied(n.recordOf(main), over) }),
601
669
  ...(n.instance && { childrenOf: (main) => n.childrenOf(main).map(underHolder) }),
602
670
  kids: n.kids.map(underHolder), data: withData(n.data, over) };
@@ -604,10 +672,15 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
604
672
  function tree(main) {
605
673
  if (trees.has(main))
606
674
  return trees.get(main);
675
+ const mainSource = byId.get(main)?.sourceId;
607
676
  const build = (id, path, inDefinition = true) => {
608
677
  const m = byId.get(id);
609
- if (!isInstance(m))
610
- return { path, rec: m, kids: kidsOf(id).map((c) => build(c, `${path};${c}`, inDefinition && !m.fileInstance)) };
678
+ if (!isInstance(m)) {
679
+ // The property a text of the main's own takes its wording from (match); texts of an instance left expanded in
680
+ // the main belong to its component.
681
+ const textProperty = inDefinition && m.kind === 'text' && m.sourceId !== undefined ? binding?.(m.sourceId, 'characters', mainSource) : undefined;
682
+ return { path, rec: m, ...(textProperty && { textProperty }), kids: kidsOf(id).map((c) => build(c, `${path};${c}`, inDefinition && !m.fileInstance)) };
683
+ }
611
684
  const own = Object.fromEntries(Object.entries(m).filter(([key]) => OWN.has(key) || key === 'fileInstance'));
612
685
  const recordOf = (main) => {
613
686
  const root = Object.fromEntries(Object.entries(byId.get(main)).filter(([key]) => !OWN.has(key)));
@@ -615,8 +688,8 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
615
688
  return m.overrides?.[''] ? applied(rec, m.overrides['']) : rec;
616
689
  };
617
690
  const childrenOf = (main) => tree(main).map((child) => reroot(child, path, m.overrides));
618
- const binding = inDefinition && m.fileInstance && swapBinding?.(m.fileInstance);
619
- return { path, binding, rec: recordOf(m.component), main: m.component, recordOf, instance: true, data: m.layoutData ?? {}, childrenOf, kids: childrenOf(m.component) };
691
+ const swapProperty = inDefinition && m.fileInstance && binding?.(m.fileInstance, 'componentId');
692
+ return { path, binding: swapProperty, rec: recordOf(m.component), main: m.component, recordOf, instance: true, data: m.layoutData ?? {}, childrenOf, kids: childrenOf(m.component) };
620
693
  };
621
694
  const t = kidsOf(main).map((c) => build(c, c));
622
695
  trees.set(main, t);
@@ -660,19 +733,26 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
660
733
  }
661
734
  if (E.kind !== R.kind)
662
735
  return 'kind';
736
+ // Core shows one property's value in every text bound to it on an occurrence: texts that show different wording
737
+ // keep it only expanded.
738
+ const textProperty = E.kind === 'text' && n.textProperty;
739
+ if (textProperty) {
740
+ const k = 'characters\0' + textProperty;
741
+ if (bound.has(k) && bound.get(k) !== E.content)
742
+ return 'conflicting bound text';
743
+ bound.set(k, E.content);
744
+ }
663
745
  // A nested instance's appearance is its main's (the renderer draws its template root): only its own keys differ.
664
746
  const d = difference(E, R, true, false, linkPaths && (() => linkPaths.add(n.path)));
665
747
  if (typeof d === 'string')
666
748
  return d;
667
749
  const fillPath = E.kind === 'path' && fillsPath(E);
668
- if (d?.net && !fillPath)
669
- return 'net';
670
750
  if (n.instance && !E.fileInstance) {
671
751
  const own = difference(E, R, false);
672
752
  if (typeof own === 'string')
673
753
  return own;
674
754
  }
675
- const inputs = n.instance ? flowOverride(E.layoutData, R.layoutData) : {};
755
+ const inputs = n.instance ? flowOverride(E.layoutData, R.layoutData, fillsIn(E, byId.get(E.parent))) : {};
676
756
  if (!supportsFrameOverrides && inputs['layoutData.flow'])
677
757
  return 'layout';
678
758
  if (n.instance)
@@ -696,9 +776,8 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
696
776
  Object.assign(inputs, { storedHeight: a.storedHeight, storedRow: a.storedRow });
697
777
  }
698
778
  }
699
- // The box the expansion has where it differs from the main's, kept (keep) where core's layout of the instance does
700
- // not give it.
701
- geometry.set(n.path, { E, R, fillPath, box: { ...(d && 't' in d && { t: d.t }), ...(d && 'w' in d && { w: d.w, h: d.h }), at: size } });
779
+ // The expansion's box, kept whole (keep) where core's layout of the instance does not give what it states.
780
+ geometry.set(n.path, { E, R, fillPath, net: fillPath || !!d?.net, own: states(E, R === n.rec ? n.raw ?? R : R, byId.get(E.parent)), at: size });
702
781
  if (d || Object.keys(inputs).length)
703
782
  out[n.path] = { ...out[n.path], ...d, ...inputs };
704
783
  if (E.fileSlotHost && fills?.includes(E.fileSlotHost))
@@ -727,9 +806,9 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
727
806
  };
728
807
  // Stores the boxes (storedBox) of instance I's layers that core's layout of it (layout.ts instanceLayout: from the
729
808
  // main at its size, with its other overrides, resized to the instance's) does not give, within EPSILON. A box only
730
- // constraints or auto layout give is not stored, so a later edit of the main reaches it. A stored box changes how
731
- // the others lay out (the instance then starts at the imported size), so they are checked again with it until none
732
- // is added.
809
+ // constraints or auto layout give, or one an auto layout places where the expansion holds its main's, is not
810
+ // stored, so a later edit of the main reaches it. A stored box changes how the others lay out (the instance then starts at the imported size), so
811
+ // they are checked again with it until none is added.
733
812
  function keep(I, geometry) {
734
813
  const stored = new Set(), get = (x) => (x === I.id ? { ...I, children: [] } : view(x));
735
814
  for (let round = 0; round <= geometry.size; round++) {
@@ -738,20 +817,56 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
738
817
  for (const [path, g] of geometry)
739
818
  if (!stored.has(path) && !gives(laid.get(path), g)) {
740
819
  stored.add(path);
741
- I.overrides[path] = { ...I.overrides[path], storedBox: g.box };
820
+ const box = wholeBox(g.E, g.at);
821
+ if (!box)
822
+ return 'partial box';
823
+ I.overrides[path] = { ...I.overrides[path], storedBox: box };
742
824
  added = true;
743
825
  }
744
826
  if (!added) {
745
- for (const [path, { E, R, fillPath }] of geometry) {
746
- // The direct resize and a resize through the main may differ by roundoff.
747
- if (fillPath && !same(E.net, laid.get(path)?.net ?? R.net, 1e-6))
827
+ for (const [path, { E, R, fillPath, net }] of geometry) {
828
+ // The direct resize and a resize through the main may differ by roundoff; Figma's stored network of a
829
+ // constraint-scaled path is single precision, so it differs from core's by up to EPSILON.
830
+ if (net && !same(E.net, laid.get(path)?.net ?? R.net, fillPath ? 1e-6 : EPSILON))
748
831
  return 'net';
749
832
  }
833
+ // A layer with no box of its own (states) whose main's box no longer fits its parent (outside) shows on load
834
+ // the place the instance's auto layout gives it, and the size on an axis it fills, as the expanded layers do
835
+ // after a load's layout (a layer that fills its parent at its main's width in a narrower parent, a layer past the
836
+ // end of a narrower parent). A size it hugs waits for the measure of its texts (this layout has none), and so does the
837
+ // place of one whose parent or a sibling it does not fill would show another size than this layout gave it
838
+ // (settled).
839
+ const box = (path) => { const { R } = geometry.get(path); return { t: R.t, w: R.w, h: R.h, ...laid.get(path) }; };
840
+ const fills = (E, k) => sizingOf(E.layoutData, k === 'w' ? 'width' : 'height') === 'fill';
841
+ const sized = (path) => { const g = path ? geometry.get(path) : undefined; return !g || ['w', 'h'].every((k) => (!g.own && fills(g.E, k)) || near(g.E[k], box(path)[k])); };
842
+ const parentOf = (path) => path.slice(0, Math.max(0, path.lastIndexOf(';'))), siblings = new Map();
843
+ for (const path of geometry.keys()) {
844
+ const p = parentOf(path);
845
+ if (!siblings.has(p))
846
+ siblings.set(p, []);
847
+ siblings.get(p).push(path);
848
+ }
849
+ const settled = (path) => sized(parentOf(path)) && siblings.get(parentOf(path)).every(sized);
850
+ for (const [path, g] of geometry) {
851
+ const o = I.overrides[path], L = box(path);
852
+ if (g.own || o?.storedBox || !outside(g.E, byId.get(g.E.parent)) || gives(L, { ...g, own: true }) || !settled(path))
853
+ continue;
854
+ const shown = { ...o }, was = Object.fromEntries(['t', 'w', 'h'].filter((k) => o && k in o).map((k) => [k, o[k]]));
855
+ for (const k of ['t', 'w', 'h']) {
856
+ if (L[k] === undefined || (k !== 't' && !fills(g.E, k)))
857
+ continue;
858
+ if (k in shown || !(k === 't' ? nearT(L.t, g.R.t) : near(L[k], g.R[k])))
859
+ shown[k] = k === 't' ? [...L.t] : L[k];
860
+ }
861
+ I.overrides[path] = shown;
862
+ laidOut.set(shown, was);
863
+ }
750
864
  return;
751
865
  }
752
866
  }
753
867
  }
754
- const state = new Map(), reasons = new Map();
868
+ // Per instance left expanded (by its id in the output): its first difference from its main.
869
+ const state = new Map(), reasons = new Map(), expandedReasons = new Map();
755
870
  let linked = 0;
756
871
  const ensure = (main) => { if (state.has(main))
757
872
  return; state.set(main, 'busy'); for (const c of [...kidsOf(main)])
@@ -762,8 +877,6 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
762
877
  return skip.has(variantKey(E)) ? 'used once' : 'no main';
763
878
  if (E.kind !== 'frame')
764
879
  return 'not a frame';
765
- if (!E.clip && overflows(id))
766
- return 'content outside the instance';
767
880
  if (state.get(main) === 'busy')
768
881
  return 'inside its main';
769
882
  ensure(main);
@@ -772,7 +885,7 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
772
885
  if (typeof root === 'string')
773
886
  return `root ${root}`;
774
887
  const overrides = {}, geometry = new Map();
775
- const content = flowOverride(E.layoutData, M.layoutData);
888
+ const content = flowOverride(E.layoutData, M.layoutData, fillsIn(E, byId.get(E.parent)));
776
889
  if (!supportsFrameOverrides && content['layoutData.flow'])
777
890
  return 'root layout';
778
891
  if (root || Object.keys(content).length)
@@ -830,6 +943,7 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
830
943
  if (!r)
831
944
  return;
832
945
  reasons.set(r, (reasons.get(r) ?? 0) + 1);
946
+ expandedReasons.set(id, r);
833
947
  }
834
948
  for (const c of [...kidsOf(id)])
835
949
  walk(c);
@@ -888,5 +1002,5 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
888
1002
  for (const c of kidsOf('@components'))
889
1003
  emit(c);
890
1004
  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 };
1005
+ 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
1006
  }
@@ -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.