@moondraft/import 0.3.0 → 0.5.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 (39) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +25 -0
  3. package/SOURCE.md +49 -0
  4. package/dist/adapter/convert.js +34 -1
  5. package/dist/adapter/file-components.d.ts +18 -0
  6. package/dist/adapter/file-components.js +96 -11
  7. package/dist/adapter/file-resources.d.ts +6 -1
  8. package/dist/adapter/file-resources.js +126 -28
  9. package/dist/adapter/link.d.ts +1 -1
  10. package/dist/adapter/link.js +138 -87
  11. package/dist/figma-file.d.ts +3 -2
  12. package/dist/figma-file.js +7 -2
  13. package/dist/figma-worker.d.ts +5 -0
  14. package/dist/figma-worker.js +6 -1
  15. package/dist/figma.d.ts +7 -1
  16. package/dist/figma.js +29 -10
  17. package/dist/index.d.ts +6 -1
  18. package/dist/index.js +3 -1
  19. package/dist/lazy.d.ts +111 -0
  20. package/dist/lazy.js +363 -0
  21. package/dist/report.js +6 -1
  22. package/dist/serialize.d.ts +9 -0
  23. package/dist/serialize.js +54 -0
  24. package/dist/taco/figma-import/import/carry.d.ts +11 -1
  25. package/dist/taco/figma-import/import/carry.js +8 -0
  26. package/dist/taco/figma-import/import/converters/effects.js +11 -3
  27. package/dist/taco/figma-import/import/converters/group.d.ts +1 -0
  28. package/dist/taco/figma-import/import/converters/group.js +5 -2
  29. package/dist/taco/figma-import/import/converters/section.d.ts +2 -1
  30. package/dist/taco/figma-import/import/converters/section.js +4 -1
  31. package/dist/taco/figma-import/import/converters/shared.d.ts +21 -2
  32. package/dist/taco/figma-import/import/converters/shared.js +53 -7
  33. package/dist/taco/figma-import/import/converters/text.js +39 -5
  34. package/dist/taco/figma-import/import/converters/vector.js +5 -3
  35. package/dist/taco/figma-import/import/instances.d.ts +10 -0
  36. package/dist/taco/figma-import/import/instances.js +22 -21
  37. package/dist/taco/figma-import/import/variables.js +8 -2
  38. package/dist/taco/figma-import/import/walk.js +8 -2
  39. package/package.json +3 -3
@@ -6,9 +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; the
11
- // import report gives each one's reason (expansionReason). 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
12
12
  // other colour is a paint override (the renderer draws a stroke's paint in place of its compact colour).
13
13
  // - A component whose root is on the page has it as its main. Any other gets a hidden main under '@components' (core's
14
14
  // parent of mains that are not drawn): a copy of its largest expanded instance with every layer its other expansions
@@ -22,14 +22,18 @@
22
22
  // differ, beside the transforms and sizes the page was linked with (settle.mjs makes those the editor's own). Core
23
23
  // lays an instance out again (packages/editor/src/core/layout/layout.ts instanceLayout) only when it or its main
24
24
  // changes, and the transforms and sizes it writes then are its output alone; where that layout, run here, does not
25
- // give a layer's linked box (within 0.01 px), the box is stored too (storedBox, with the instance's size), and core's
26
- // 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.
27
28
  // - An instance has no children to hug: where its expanded root is an auto layout filling a parent that hugs it, the
28
29
  // parent hugged that root's content (layout.mjs natural), so the instance keeps its size there ('fixed') and the
29
30
  // parent lays out as it did.
30
- // - What the renderer does differently from core is avoided: it culls an instance's content by the instance's box (an
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
32
- // 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).
33
37
  // The markers are removed whether or not anything is linked.
34
38
  import { supportsTextField } from './file-typography.js';
35
39
  import { Properties, TextStyleSchema } from '@moondraft/editor/schema';
@@ -58,10 +62,12 @@ const FIELD_WORDS = {
58
62
  export function expansionReason(reason) {
59
63
  const fixed = {
60
64
  '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',
65
+ 'not a frame': 'it is not a frame',
62
66
  'inside its main': 'it is inside its own main', 'layer order': 'its layers are in another order than its main\'s',
63
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',
64
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',
65
71
  };
66
72
  if (fixed[reason])
67
73
  return fixed[reason];
@@ -193,7 +199,7 @@ function difference(E, R, own, rootOverride = false, omitLink) {
193
199
  rec.w = E.w;
194
200
  rec.h = E.h;
195
201
  }
196
- // 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
197
203
  // main laid out with all sibling overrides and stored boxes before accepting the link.
198
204
  else if (k === 'net' && E.kind === 'path' && own)
199
205
  rec.net = E.net;
@@ -387,18 +393,44 @@ function instanceData(E, P) {
387
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)
388
394
  * before the box is stored. */
389
395
  const EPSILON = 0.01;
390
- /** How far (px) a layer's shadow or blur may reach past its box and still count as inside it (overflows). The renderer
391
- * 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
392
- * Modal instance was cut 22 px below it, while the HeroUI pages' tails of up to 8 px drew as expanded. */
393
- const SLACK = 8;
394
- /** Whether core's layout of an instance (laid: its output for the layer, absent where it shows its main's R) gives the
395
- * expanded record E's transform and size. */
396
- function gives(laid, { E, R }) {
397
- const t = laid?.t ?? R.t ?? [1, 0, 0, 1, 0, 0], e = E.t ?? [1, 0, 0, 1, 0, 0];
398
- 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)
399
417
  return false;
400
- const size = (k) => (laid && k in laid ? laid[k] : R[k]);
401
- 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 };
402
434
  }
403
435
  /** Links the instances of a converted page (its models, in file order) to their mains, in place. Returns counts.
404
436
  * A hidden main only one instance would use (not a main on the page) costs more than that instance's expansion, so
@@ -411,7 +443,7 @@ export function linkComponents(doc) {
411
443
  return linkWithLayers(doc, false).counts;
412
444
  }
413
445
  /** @internal Links components and tracks where their expanded layers went for import reports. */
414
- export function linkWithLayers(doc, trackLayers = true, swapBinding, nativeFile = false) {
446
+ export function linkWithLayers(doc, trackLayers = true, binding, nativeFile = false) {
415
447
  // Variant sets (convert.ts markSet): one hidden main per variant used, so each instance's main is its own variant
416
448
  // and its overrides are its own changes alone; but a showcase of a set (each variant once or twice) costs a main per
417
449
  // variant. So per set: the page is linked both ways and a set keeps a main per variant where that stores no more
@@ -431,7 +463,7 @@ export function linkWithLayers(doc, trackLayers = true, swapBinding, nativeFile
431
463
  const skip = new Set();
432
464
  for (;;) {
433
465
  const d = { models: doc.models }, aliases = new Map();
434
- const { once, omittedLinks, expandedReasons, ...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);
435
467
  if (!once.length)
436
468
  return { d, r, aliases, omittedLinks, expandedReasons };
437
469
  for (const comp of once)
@@ -455,7 +487,7 @@ export function linkWithLayers(doc, trackLayers = true, swapBinding, nativeFile
455
487
  }
456
488
  /** linkComponents with no hidden main for the components in `skip`; also returns the components whose hidden main is
457
489
  * used once (once). */
458
- function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFile = false) {
490
+ function linkOnce(doc, skip, each, compareCosts, aliases, binding, nativeFile = false) {
459
491
  const omittedLinks = new Map();
460
492
  const recordAlias = (from, to) => {
461
493
  if (!aliases)
@@ -488,41 +520,6 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
488
520
  const kidsOf = (id) => kids.get(id) ?? [];
489
521
  const size = (id) => 1 + kidsOf(id).reduce((n, c) => n + size(c), 0);
490
522
  const before = doc.models.length;
491
- // Whether the layers under a frame draw outside its box, with their drop shadows and layer blurs where they reach
492
- // further than SLACK, as the renderer reaches them (the offset plus 1.5 blur and the spread; crates/scn-core
493
- // derived.rs effect_reach); clipping frames bound their own children.
494
- const reach = (m) => {
495
- const blur = 1.5 * (m.look?.layerBlur?.radius ?? 0), out = [blur, blur, blur, blur]; // left, top, right, bottom
496
- for (const s of m.look?.shadows ?? [])
497
- if (!s.inner && s.c?.[3] !== 0) {
498
- const spread = s.spread ?? 0, x = s.x ?? 0, y = s.y ?? 0;
499
- const e = 1.5 * (s.blur ?? 0) + spread;
500
- out[0] = Math.max(out[0], e - x);
501
- out[1] = Math.max(out[1], e - y);
502
- out[2] = Math.max(out[2], e + x);
503
- out[3] = Math.max(out[3], e + y);
504
- }
505
- return out.map((v) => (v > SLACK ? v : 0));
506
- };
507
- 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]];
508
- function overflows(root) {
509
- const R = byId.get(root), stack = kidsOf(root).map((c) => [c, byId.get(c).t]);
510
- while (stack.length) {
511
- const [id, T] = stack.pop(), m = byId.get(id);
512
- if (m.visible === false)
513
- continue;
514
- 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);
515
- 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]]) {
516
- const X = T[0] * x + T[2] * y + T[4], Y = T[1] * x + T[3] * y + T[5];
517
- if (X < -0.5 || Y < -0.5 || X > R.w + 0.5 || Y > R.h + 0.5)
518
- return true;
519
- }
520
- if (!m.clip)
521
- for (const c of kidsOf(id))
522
- stack.push([c, mul(T, byId.get(c).t)]);
523
- }
524
- return false;
525
- }
526
523
  const key = (m) => m.fileInstance ?? m.sourceId ?? `~${m.kind}~${m.name ?? ''}`;
527
524
  // Hidden mains (taken before anything is linked): a copy of each component's largest expansion, with every layer
528
525
  // another expansion has and it lacks, hidden (see union).
@@ -634,22 +631,21 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
634
631
  root.name = vk === comp ? E0.setOf : `${E0.setOf}/${E0.variant}`;
635
632
  unmark(root);
636
633
  root.mainOf = comp;
637
- // An expansion that stays expanded whatever its main (its layers draw outside it, or in another order) adds nothing.
638
- for (const id of frames.slice(1))
639
- if (byId.get(id).clip || !overflows(id)) {
640
- const p = plan(id, root.id);
641
- if (p)
642
- union(root.id, p);
643
- }
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
+ }
644
640
  mains.set(vk, root.id);
645
641
  hidden.set(root.id, vk);
646
642
  }
647
643
  const isInstance = (m) => m?.kind === 'frame' && m.component !== undefined && m.component !== m.id;
648
644
  // A main's effective tree: per layer, its path (from the main's child down), what it shows and its children.
649
- const trees = new Map();
645
+ const trees = new Map(), laidOut = new WeakMap();
650
646
  function swappedNode(n, main) {
651
647
  ensure(main);
652
- 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) };
653
649
  }
654
650
  function reroot(n, prefix, overrides) {
655
651
  const over = overrides?.[n.path];
@@ -657,7 +653,18 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
657
653
  n = swappedNode(n, over.component);
658
654
  // Keep each holder's overrides in scope when a later placement chooses another main.
659
655
  const underHolder = (child) => reroot(child, prefix, overrides);
660
- 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,
661
668
  ...(n.instance && over && { recordOf: (main) => applied(n.recordOf(main), over) }),
662
669
  ...(n.instance && { childrenOf: (main) => n.childrenOf(main).map(underHolder) }),
663
670
  kids: n.kids.map(underHolder), data: withData(n.data, over) };
@@ -665,10 +672,15 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
665
672
  function tree(main) {
666
673
  if (trees.has(main))
667
674
  return trees.get(main);
675
+ const mainSource = byId.get(main)?.sourceId;
668
676
  const build = (id, path, inDefinition = true) => {
669
677
  const m = byId.get(id);
670
- if (!isInstance(m))
671
- 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
+ }
672
684
  const own = Object.fromEntries(Object.entries(m).filter(([key]) => OWN.has(key) || key === 'fileInstance'));
673
685
  const recordOf = (main) => {
674
686
  const root = Object.fromEntries(Object.entries(byId.get(main)).filter(([key]) => !OWN.has(key)));
@@ -676,8 +688,8 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
676
688
  return m.overrides?.[''] ? applied(rec, m.overrides['']) : rec;
677
689
  };
678
690
  const childrenOf = (main) => tree(main).map((child) => reroot(child, path, m.overrides));
679
- const binding = inDefinition && m.fileInstance && swapBinding?.(m.fileInstance);
680
- 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) };
681
693
  };
682
694
  const t = kidsOf(main).map((c) => build(c, c));
683
695
  trees.set(main, t);
@@ -721,13 +733,20 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
721
733
  }
722
734
  if (E.kind !== R.kind)
723
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
+ }
724
745
  // A nested instance's appearance is its main's (the renderer draws its template root): only its own keys differ.
725
746
  const d = difference(E, R, true, false, linkPaths && (() => linkPaths.add(n.path)));
726
747
  if (typeof d === 'string')
727
748
  return d;
728
749
  const fillPath = E.kind === 'path' && fillsPath(E);
729
- if (d?.net && !fillPath)
730
- return 'net';
731
750
  if (n.instance && !E.fileInstance) {
732
751
  const own = difference(E, R, false);
733
752
  if (typeof own === 'string')
@@ -757,9 +776,8 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
757
776
  Object.assign(inputs, { storedHeight: a.storedHeight, storedRow: a.storedRow });
758
777
  }
759
778
  }
760
- // The box the expansion has where it differs from the main's, kept (keep) where core's layout of the instance does
761
- // not give it.
762
- 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 });
763
781
  if (d || Object.keys(inputs).length)
764
782
  out[n.path] = { ...out[n.path], ...d, ...inputs };
765
783
  if (E.fileSlotHost && fills?.includes(E.fileSlotHost))
@@ -788,9 +806,9 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
788
806
  };
789
807
  // Stores the boxes (storedBox) of instance I's layers that core's layout of it (layout.ts instanceLayout: from the
790
808
  // main at its size, with its other overrides, resized to the instance's) does not give, within EPSILON. A box only
791
- // constraints or auto layout give is not stored, so a later edit of the main reaches it. A stored box changes how
792
- // the others lay out (the instance then starts at the imported size), so they are checked again with it until none
793
- // 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.
794
812
  function keep(I, geometry) {
795
813
  const stored = new Set(), get = (x) => (x === I.id ? { ...I, children: [] } : view(x));
796
814
  for (let round = 0; round <= geometry.size; round++) {
@@ -799,15 +817,50 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
799
817
  for (const [path, g] of geometry)
800
818
  if (!stored.has(path) && !gives(laid.get(path), g)) {
801
819
  stored.add(path);
802
- 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 };
803
824
  added = true;
804
825
  }
805
826
  if (!added) {
806
- for (const [path, { E, R, fillPath }] of geometry) {
807
- // The direct resize and a resize through the main may differ by roundoff.
808
- 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))
809
831
  return 'net';
810
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
+ }
811
864
  return;
812
865
  }
813
866
  }
@@ -824,8 +877,6 @@ function linkOnce(doc, skip, each, compareCosts, aliases, swapBinding, nativeFil
824
877
  return skip.has(variantKey(E)) ? 'used once' : 'no main';
825
878
  if (E.kind !== 'frame')
826
879
  return 'not a frame';
827
- if (!E.clip && overflows(id))
828
- return 'content outside the instance';
829
880
  if (state.get(main) === 'busy')
830
881
  return 'inside its main';
831
882
  ensure(main);
@@ -1,4 +1,5 @@
1
- import type { ImportDocument, ImportEnv, ImportSignal } from '@moondraft/editor/core';
1
+ import type { ImportDocument, ImportSignal } from '@moondraft/editor/core';
2
+ import type { ReadFigmaOptions } from './figma.ts';
2
3
  /** The subset of a module worker used to read a .fig file. */
3
4
  export interface WorkerLike {
4
5
  /**
@@ -22,7 +23,7 @@ export interface WorkerLike {
22
23
  terminate(): void;
23
24
  }
24
25
  /** Options for reading a .fig file. */
25
- export interface OpenFigmaOptions extends Pick<ImportEnv, 'signal' | 'progress'> {
26
+ export interface OpenFigmaOptions extends Pick<ReadFigmaOptions, 'signal' | 'progress' | 'limits' | 'pages'> {
26
27
  /** Factory for a dedicated worker. Defaults to a module worker when available. Pass null to read on this thread. */
27
28
  worker?: (() => WorkerLike) | null;
28
29
  }
@@ -24,7 +24,9 @@ export async function openFigmaFile(bytes, options = {}) {
24
24
  }
25
25
  if (!worker) {
26
26
  const { readFigmaFile } = await import('./figma.js');
27
- return readFigmaFile(bytes, { signal, progress });
27
+ return readFigmaFile(bytes, {
28
+ signal, progress, ...(options.limits && { limits: options.limits }), ...(options.pages && { pages: options.pages }),
29
+ });
28
30
  }
29
31
  const own = bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength ? bytes : bytes.slice();
30
32
  try {
@@ -53,8 +55,11 @@ export async function openFigmaFile(bytes, options = {}) {
53
55
  });
54
56
  worker.addEventListener('messageerror', () => { finish(); reject(new Error('the Figma importer sent a reply that could not be read')); });
55
57
  worker.addEventListener('error', ({ message }) => { finish(); reject(new Error(`the Figma importer failed to run: ${message ?? 'worker error'}`)); });
58
+ const request = {
59
+ bytes: own, ...(options.limits && { limits: options.limits }), ...(options.pages && { pages: options.pages }),
60
+ };
56
61
  try {
57
- worker.postMessage(own, [own.buffer]);
62
+ worker.postMessage(request, [own.buffer]);
58
63
  }
59
64
  catch (error) {
60
65
  finish();
@@ -1,4 +1,5 @@
1
1
  import type { ImportDocument, ImportProgress } from '@moondraft/editor/core';
2
+ import { type ReadFigmaOptions } from './figma.ts';
2
3
  /** Replies sent by the module worker after it is ready. */
3
4
  export type FigmaWorkerReply = {
4
5
  progress: ImportProgress;
@@ -9,3 +10,7 @@ export type FigmaWorkerReply = {
9
10
  ok: false;
10
11
  error: string;
11
12
  };
13
+ /** A .fig file read request sent to the module worker. */
14
+ export type FigmaWorkerRequest = {
15
+ bytes: Uint8Array;
16
+ } & Pick<ReadFigmaOptions, 'limits' | 'pages'>;
@@ -2,7 +2,12 @@ import { readFigmaFile } from './figma.js';
2
2
  const scope = globalThis;
3
3
  scope.onmessage = ({ data }) => {
4
4
  try {
5
- const value = readFigmaFile(data, { progress: (progress) => scope.postMessage({ progress }) });
5
+ const request = data instanceof Uint8Array ? { bytes: data } : data;
6
+ const value = readFigmaFile(request.bytes, {
7
+ progress: (progress) => scope.postMessage({ progress }),
8
+ ...(request.limits && { limits: request.limits }),
9
+ ...(request.pages && { pages: request.pages }),
10
+ });
6
11
  scope.postMessage({ ok: true, value });
7
12
  }
8
13
  catch (error) {
package/dist/figma.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type ImportDocument, type ImportEnv, type ImportPayload } from '@moondraft/editor/core';
2
+ import type { FigmaImportLimits } from './taco/figma-import/import/types.ts';
2
3
  /**
3
4
  * Checks for the markers Figma adds to clipboard HTML.
4
5
  * @param html - Clipboard HTML to inspect.
@@ -15,7 +16,12 @@ export declare const MISSING_IMAGES = "Unresolved images (shown as placeholders)
15
16
  */
16
17
  export declare function readFigmaClipboard(html: string): ImportPayload;
17
18
  /** Options for reading a Figma file synchronously. */
18
- export type ReadFigmaOptions = Pick<ImportEnv, 'signal' | 'progress'>;
19
+ export interface ReadFigmaOptions extends Pick<ImportEnv, 'signal' | 'progress'> {
20
+ /** Overrides the reader's node, depth and vector-command limits. */
21
+ limits?: Partial<FigmaImportLimits>;
22
+ /** Imports only public pages whose names appear here (defaults to every public page). */
23
+ pages?: readonly string[];
24
+ }
19
25
  /**
20
26
  * Reads a saved Figma design file on the calling thread.
21
27
  * Values in the result may be shared between layers; copy before mutating in place.
package/dist/figma.js CHANGED
@@ -10,6 +10,7 @@ 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
+ import { namesNode } from './taco/figma-import/import/converters/shared.js';
13
14
  import { allPages, figmaClipboardPage } from './adapter/convert.js';
14
15
  import { convertEntries, droppedFeatures, figmaReportLayers, fontEntries, grouped, leftOutIds, readerCount } from './report.js';
15
16
  import { checkAbort } from './figma-file.js';
@@ -24,7 +25,7 @@ export const holdsFigmaData = (html) => html.includes('(figmeta)') && html.inclu
24
25
  export const MISSING_IMAGES = clipboard.MISSING_IMAGE_REPORT;
25
26
  const STAND_IN = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
26
27
  const ids = () => { let next = 0; return () => `f${++next}`; };
27
- function reportOf(result, converted, features, extra, file = false) {
28
+ function reportOf(result, converted, features, extra, nodes, file = false) {
28
29
  const { bySource, pages, derive } = figmaReportLayers(converted.doc, file);
29
30
  const dropped = [];
30
31
  for (const { figmaId, what, leftOut } of features) {
@@ -43,7 +44,10 @@ function reportOf(result, converted, features, extra, file = false) {
43
44
  const layer = result.layerIds[entry.nodeId];
44
45
  const pageId = pageIds.get(entry.nodeId);
45
46
  const ids = pageId ? [pageId] : layer === undefined ? undefined : bySource.get(layer);
46
- return { kind: entry.kind === 'approximated' ? 'approximated' : 'left-out', ...readerCount(entry), ...(ids && { ids }) };
47
+ // Moondraft patch 0055: an entry about a corrupt number or a replaced key names its Figma node, which a left-out
48
+ // node has no layer in the result to show.
49
+ const named = namesNode(entry.reason) ? [{ id: entry.nodeId, name: nodes.get(entry.nodeId)?.name ?? '' }] : undefined;
50
+ return { kind: entry.kind === 'approximated' ? 'approximated' : 'left-out', ...readerCount(entry), ...(ids && { ids }), ...(named && { sources: named }) };
47
51
  });
48
52
  return { report: [...reader, ...dropped, ...convertEntries(converted.report, true), ...extra], derive };
49
53
  }
@@ -88,7 +92,7 @@ export function readFigmaClipboard(html) {
88
92
  delete payload.assets[id];
89
93
  if (assetIds.length)
90
94
  extra.push({ kind: 'left-out', what: MISSING_IMAGES, count: assetIds.length, assetIds });
91
- return { payload, report: grouped(reportOf(result, converted, droppedFeatures(message.nodeChanges, leftOut), extra).report) };
95
+ return { payload, report: grouped(reportOf(result, converted, droppedFeatures(message.nodeChanges, leftOut), extra, sources.tree.nodes).report) };
92
96
  }
93
97
  /**
94
98
  * Reads a saved Figma design file on the calling thread.
@@ -109,7 +113,7 @@ export function readFigmaFile(bytes, options = {}) {
109
113
  const { doc, images, report, total, derive } = convertFile(bytes, () => {
110
114
  checkpoint('decode', 1, 1);
111
115
  checkpoint('convert', 0);
112
- });
116
+ }, options);
113
117
  // Use the same derived pass as editor.load so saved literals include mode choices and nested property assignments.
114
118
  let document = doc;
115
119
  if (derive) {
@@ -125,6 +129,7 @@ export function readFigmaFile(bytes, options = {}) {
125
129
  for (const field of fields)
126
130
  report.push({ kind: 'approximated', what: `typography binding kept as value for text field "${field}"`, count: 1, ids: [id] });
127
131
  document = core.releaseJSON();
132
+ checkpoint('derive', 1, 1);
128
133
  }
129
134
  // Only surviving assets need data URLs. Keep their encoded strings out of the layout and linking passes.
130
135
  for (const [id, asset] of Object.entries(document.assets ?? {})) {
@@ -176,17 +181,28 @@ function compactFileRecord(field, change) {
176
181
  change.derivedTextData = metrics;
177
182
  }
178
183
  }
179
- function readFileSource(bytes, decoded) {
184
+ function readFileSource(bytes, decoded, options) {
180
185
  const file = readFigFile(bytes, { onRootArrayItem: compactFileRecord });
181
186
  decoded();
182
- const result = readFileMessage(file.message, {
183
- idSource: ids(), roots: 'pages',
187
+ let message = file.message;
188
+ // Pages left out of `pages` are read as internal ones, so their layers never reach the walk.
189
+ if (options.pages !== undefined && isObject(message) && Array.isArray(message.nodeChanges)) {
190
+ const wanted = new Set(options.pages);
191
+ const nodeChanges = message.nodeChanges.map((change) => isObject(change) && change.type === 'CANVAS' && change.internalOnly !== true && !wanted.has(String(change.name ?? ''))
192
+ ? { ...change, internalOnly: true }
193
+ : change);
194
+ message = { ...message, nodeChanges };
195
+ }
196
+ const result = readFileMessage(message, {
197
+ idSource: ids(), roots: 'pages', ...(options.limits && { limits: options.limits }),
184
198
  images: (hash) => { const bytes = file.images.get(hash); return bytes ? { bytes } : undefined; },
185
199
  });
186
200
  return { result, key: file.meta?.fileKey || file.message.fileKey };
187
201
  }
188
- function convertFile(bytes, decoded) {
189
- const { result, key } = readFileSource(bytes, decoded);
202
+ function convertFile(bytes, decoded, options = {}) {
203
+ const stage = (name) => options.progress?.({ stage: name, done: 1 });
204
+ const { result, key } = readFileSource(bytes, decoded, options);
205
+ stage('walk');
190
206
  // Geometry and overrides now live on the converted nodes. Release their wire
191
207
  // representations while collecting diagnostics in source order. Resource and
192
208
  // metadata adapters still see the original paint lists and all other fields.
@@ -218,15 +234,18 @@ function convertFile(bytes, decoded) {
218
234
  const converted = allPages(geometry, {
219
235
  assetSrc: (_id, asset) => `data:${asset.mimeType};base64,`,
220
236
  });
237
+ stage('pages');
221
238
  const extra = [];
222
239
  // Roots that bind their own radii stay expanded before linking (convert.ts leaves them unmarked).
223
240
  for (const m of converted.doc.models)
224
241
  if (m.fileInstance !== undefined && expandedRadii.has(m.fileInstance))
225
242
  converted.expandedReasons.set(m.id, 'root radius bindings');
226
243
  const { occurrences, setSources } = fileComponents(result, converted.doc, converted.nestedBooleans, extra, converted.expandedReasons);
244
+ stage('components');
227
245
  let fileKey = key;
228
246
  const fileId = () => String(fileKey ||= sha256Hex(bytes));
229
247
  fileResources(result, converted.doc, occurrences, converted.expanded, expandedRadii, extra, fileId);
248
+ stage('resources');
230
249
  for (const layer of converted.doc.models) {
231
250
  if (layer.kind !== 'frame')
232
251
  continue;
@@ -243,7 +262,7 @@ function convertFile(bytes, decoded) {
243
262
  for (const entry of figmaLayoutGrids(result.sources, converted.doc, { setSources, fileId }))
244
263
  extra.push(entry);
245
264
  const reader = result.report.filter(e => !e.reason.startsWith('variable bindings left out, their values kept:'));
246
- const { report, derive } = reportOf({ ...result, report: reader }, converted, features, extra, true);
265
+ const { report, derive } = reportOf({ ...result, report: reader }, converted, features, extra, result.sources.tree.nodes, true);
247
266
  const images = result.assets;
248
267
  for (const id of Object.keys(images))
249
268
  if (!Object.hasOwn(converted.doc.assets ?? {}, id))
package/dist/index.d.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  import type { Importer } from '@moondraft/editor/core';
2
2
  import { type SvgParse } from './taco/svg-import/public-types.ts';
3
+ import type { FigmaImportLimits } from './taco/figma-import/import/types.ts';
3
4
  import type { OpenFigmaOptions } from './figma-file.ts';
4
5
  export type { ImportDocument, ImportEnv, ImportInput, ImportPayload, ImportProgress, ImportRead, ImportReportEntry, Importer } from '@moondraft/editor/core';
5
6
  export { openFigmaFile, type OpenFigmaOptions, type WorkerLike } from './figma-file.ts';
7
+ export type { FigmaImportLimits } from './taco/figma-import/import/types.ts';
6
8
  /** Options for registering an SVG importer. */
7
9
  export interface SvgImporterOptions {
8
10
  /** Parses markup into an element tree (default: the browser's DOMParser). */
@@ -18,6 +20,8 @@ export declare function svgImporter(options?: SvgImporterOptions): Importer;
18
20
  export interface FigmaImporterOptions {
19
21
  /** Factory for a dedicated worker. Defaults to a module worker when available. Pass null to read on this thread. */
20
22
  worker?: OpenFigmaOptions['worker'];
23
+ /** Overrides the reader's node, depth and vector-command limits. */
24
+ limits?: Partial<FigmaImportLimits>;
21
25
  }
22
26
  /**
23
27
  * Imports Figma clipboard HTML as editable layers and .fig files as full documents.
@@ -26,4 +30,5 @@ export interface FigmaImporterOptions {
26
30
  */
27
31
  export declare function figmaImporter(options?: FigmaImporterOptions): Importer;
28
32
  export { payloadFromSyntax } from './syntax.ts';
29
- export { serializeImportDocument } from './serialize.ts';
33
+ export { serializeImportDocument, serializeImportNdjson } from './serialize.ts';
34
+ export { bundleFileName, componentRefsOf, createLazyBundle, type LazyBundle, type LazyBundleComponent, type LazyBundleFile, type LazyBundleIndex, type LazyBundleOptions, type LazyBundlePage } from './lazy.ts';