@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
package/CHANGELOG.md CHANGED
@@ -2,6 +2,26 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.5.0 — 2026-11-30
6
+
7
+ - Saved Figma files stream into newline-delimited JSON and split into lazy bundles. `serializeImportNdjson(document)` yields NDJSON lines (`meta`, `shared`, `asset`, `model`): pages first, then component subtrees in dependency order, then page layers, so a streaming reader never creates an instance before its main. `createLazyBundle(document, { assets })` yields a `moondraft-lazy-v2` bundle: an `index.json` manifest, `shared.ndjson`, one file per component subtree under `components/` (main components and variant sets on public pages included, grouped into strongly connected components in topological order, whose index is each subtree's `scc`), one file per non-empty page under `pages/`, and base64 data-URL media sources as files under `assets/`. A video's poster stays an embedded data URL, the only poster the editor takes. Layers may come in any order; a layer whose parent is missing, or parents that form a cycle, make it throw. Swap property defaults, preferred lists and swap values count as dependencies alongside instances and swapped overrides (`componentRefsOf`). Subtree and page files are named by `bundleFileName(id)`, which is one to one and has no `%`, so IDs such as `12:34` (`12_3A34`) survive servers that decode request paths.
8
+ - `openFigmaFile` and `readFigmaFile` accept `pages` (the public page names to import) and `limits` (node, depth and vector-command ceilings), and `figmaImporter({ limits })` passes its limits on, on the calling thread and to the module worker. Progress callbacks also report the `walk`, `pages`, `components`, `resources` and `derive` stages.
9
+ - `FigmaImportLimits` (the `nodes`, `depth` and `vectorCommands` ceilings) is exported, to type a `limits` option.
10
+ - Corrupt values in large saved files no longer abort the whole import. A frame, group, instance or other layer with a non-finite size or transform (`NaN` or infinity) keeps its children: a non-finite width, height or position reads as 0, a non-finite rotation or scale as none, and the layer is reported as approximated. A vector with a non-finite transform is left out. A non-finite colour drops only that paint, gradient stop, shadow, text fill or variable mode value; a non-finite shadow offset, spread or radius, or blur radius, drops only that effect; a non-finite font size takes the size beneath it (the text style's or the layer's), else the default, and is reported as approximated. A variable mode entry without a `variableModeID` is skipped, so the layer inherits its parent's mode.
11
+ - Variables that share a name inside one Figma collection import as `Name`, `Name 2`, `Name 3`, … (IDs, so aliases, unchanged), and components and variant sets that share a `componentKey` keep it on the first in the file while the others take their `figma-<id>` fallback key, so the editor no longer refuses the document. The import report lists each rename and replaced key.
12
+ - Import report entries have an optional `sources` list (`ImportReportSource[]`) naming the source-file layers they are about by ID and name. The Figma importer fills it for the entries above, so a layer left out of a large file can be found there.
13
+
14
+ ## 0.4.0 — 2026-11-28
15
+
16
+ - The peer dependency on `@moondraft/editor` is now `>=0.6.0 <0.7.0`. Install the editor 0.6.0 or later in the
17
+ 0.6 line.
18
+
19
+ - A Figma instance left expanded into plain layers keeps the fills and strokes the instance overrides, also on layers inside nested and swapped instances: before, it showed its main's paints where the main's style or variable binding was installed. An override's size bindings and variable modes are added to the main's, and a plain paint over a nested instance's colour variable drops that variable, linked or expanded.
20
+ - Figma text layers and groups keep their drop shadows, inner shadows, layer blur and background blur; editor 0.6.0 draws them.
21
+ - Figma instances stay linked to their mains far more often: a path that the instance's resize scales by its constraints, and content that draws outside the instance's box, no longer expand the instance into plain layers, so main edits, property references and variable bindings keep reaching it. The import report gives the reason for each instance still expanded ("expanded instance: …"). A linked instance inside an expanded one keeps the paints, styles and bindings the expanded instance overrides on its layers.
22
+ - A Figma instance left expanded keeps a text property's assigned wording where an override only restyles the bound text (its letter spacing, font or paint): before, the text showed the component's default wording in the new style.
23
+ - A linked Figma instance keeps a text override on a text bound to a text property: the wording is assigned to the property, so it no longer shows the property's default. An instance whose texts bound to one property show different wording stays expanded, so each keeps its own; this counts only texts of the instance's own component, not those of an instance left expanded inside its main.
24
+
5
25
  ## 0.3.0 — 2026-11-27
6
26
 
7
27
  - The peer dependency on `@moondraft/editor` is now `>=0.5.0 <0.6.0`. Install the editor 0.5.0 or later in the
package/README.md CHANGED
@@ -32,6 +32,31 @@ await writeFile('design.json', serializeImportDocument(document))
32
32
  console.log(report)
33
33
  ```
34
34
 
35
+ For very large files whose JSON would exceed the JavaScript string limit, write newline-delimited JSON with
36
+ `serializeImportNdjson(document)` instead, or split the document into a lazy bundle with `createLazyBundle(document)`:
37
+
38
+ ```js
39
+ import { mkdir, readFile, writeFile } from 'node:fs/promises'
40
+ import { dirname, join } from 'node:path'
41
+ import { createLazyBundle, openFigmaFile } from '@moondraft/import'
42
+
43
+ const { document } = await openFigmaFile(await readFile('design.fig'), {
44
+ limits: { nodes: 1_000_000 }, // optional: raise the reader's node cap (also depth, vectorCommands)
45
+ pages: ['Page 1', 'Page 2'], // optional: import only these public pages
46
+ })
47
+ const bundle = createLazyBundle(document) // pass { assets: false } to keep data URLs inline
48
+ for (const file of bundle.files()) {
49
+ const path = join('out', file.path)
50
+ await mkdir(dirname(path), { recursive: true })
51
+ await writeFile(path, file.content, { flag: file.append ? 'a' : 'w' })
52
+ }
53
+ ```
54
+
55
+ A lazy bundle (`index.json`, `shared.ndjson`, `components/*.ndjson`, `pages/*.ndjson`, `assets/*`) lists every page up
56
+ front and groups component subtrees — including mains living on public pages — in topological order, so a host can
57
+ load only the page being viewed and fetch each referenced main component before inserting the instances that use it.
58
+ Subtree and page files are named `bundleFileName(id)`; `componentRefsOf(layer)` lists the mains a layer can name.
59
+
35
60
  In Node, `runImport` from `@moondraft/editor/core` can also select a registered importer. Supply `svgImporter({ parseSvg })` with an XML parser that returns the SVG root element. Host importers can use `payloadFromSyntax(text)` to create paste payloads from the agent build tool's layer syntax.
36
61
 
37
62
  See [CHANGELOG.md](CHANGELOG.md) for releases, [SOURCE.md](SOURCE.md) for reader provenance and [LICENSE](LICENSE) for licensing.
package/SOURCE.md CHANGED
@@ -479,6 +479,12 @@ an object written that way with more than a few fields as a hash table; the copy
479
479
  takes about a fifth of the memory, which cuts the decoded tree of a layer-heavy file by about 100 MB. Values are
480
480
  unchanged.
481
481
 
482
+ ### `patches/0049-text-group-effects.patch`
483
+
484
+ Text layers and groups keep their shadows, layer blur and background blur. Taco's text and group nodes have no
485
+ style, so `nodeEffects` reads them as it does for shapes and `carryEffects` (carry.ts) carries them in
486
+ `metadata.figma.effects`, with `shadowBehind` indexing into its shadows; "effects are not imported yet" is no longer
487
+ reported for them. The adapter writes them to the layer's `look`, and the renderer draws a text's from its glyphs.
482
488
 
483
489
  ### `patches/0050-kiwi-shared-structs.patch`
484
490
 
@@ -506,3 +512,46 @@ reaches, whether or not a deeper override path goes through it. A property value
506
512
  component does not declare goes to the shallowest nested instances whose shown component (after swaps) declares it,
507
513
  read against that component, but only where the instance's `derivedSymbolData` lays out a layer bound to that property
508
514
  inside the nested instance (Figma ignores a stale value); any other such value is still reported.
515
+
516
+ ### `patches/0053-bound-text-style-overrides.patch`
517
+
518
+ An override that restyles a text bound to a text property (its letter spacing, font or paint) without wording of its own
519
+ (no `textData`) keeps the property's assigned value. Such an override converts to full `paragraphs`, which carried the
520
+ text's stored wording and so showed the component's default over the assigned value wherever the instance stays
521
+ expanded. The assigned characters now replace that wording in the override's formatting, as they already did for an
522
+ assignment with links; every text assignment is kept for this, a value passed down from a holder yielding to the
523
+ nested instance's own. An override with its own wording or links is left as it is. `convert-instance.test.ts` covers
524
+ this, marked "Moondraft patch 0053".
525
+
526
+ ### `patches/0054-export-override-merges.patch`
527
+
528
+ `withOverrides` and `withBindingEntries` are exported, so that the adapter merges the overrides it applies to a layer
529
+ of an expanded instance (`src/adapter/file-resources.ts`) as an override is converted for a linked one: a field the
530
+ override sets drops the main's binding of it, and the override's bindings replace only the main's of the same fields.
531
+ The functions themselves are unchanged.
532
+
533
+ ### `patches/0055-non-finite-numbers-and-stale-modes.patch`
534
+
535
+ Large saved files can carry isolated corrupt numbers or stale references that should not abort every page of the
536
+ import. `readNumbers` reads a non-finite number (`NaN` or infinity) like a missing field instead of refusing the
537
+ message with `not-node-changes`; a field of the wrong type (a string, say) still refuses it. Where that would drop
538
+ more than the corrupt value, the readers say what they keep:
539
+
540
+ - `frameGeometry` reads a non-finite width, height or position (`m02`, `m12`) as 0, and a rotation or scale part
541
+ (`m00`, `m01`, `m10`, `m11`) with a non-finite number as no rotation and no scale, so a frame, group, instance or
542
+ other framed layer keeps its children; `framedBase` reports it as approximated. `pathTransform` still leaves out a
543
+ vector whose transform has a non-finite number.
544
+ - A paint, shadow or text fill with a non-finite colour, or a gradient stop with a non-finite colour or position,
545
+ drops only itself, and a colour variable value with a non-finite channel drops only that mode's value. A shadow
546
+ with a non-finite offset, spread or radius, or a blur with a non-finite radius, drops only that effect. Each is
547
+ reported, naming the non-finite number (`NON_FINITE`).
548
+ - `styleFields` passes over a non-finite `fontSize` to the next size beneath it (the text style's, then the node's),
549
+ or leaves it absent so the default applies; `runStyle` reports it as approximated.
550
+ - The adapter places gradient stop bindings (`src/adapter/file-resources.ts`) without the stops the reader left out.
551
+ - `readFigmaVariables` skips a `variableModeBySetMap` or explicit-mode entry that has no `variableModeID`, so the layer
552
+ inherits its parent's mode; a `variableModeID` that is present but not a GUID still refuses the message.
553
+ - The walk reports a component whose repeated `componentKey` the file's key source replaced (`DUPLICATE_KEY`), as the
554
+ adapter does for variant sets. The adapter names the Figma node (ID and name, `sources`) in every entry whose reason
555
+ `namesNode` matches.
556
+
557
+ Covered in `convert-vector.test.ts` and `convert-variables.test.ts`, marked "Moondraft patch 0055".
@@ -30,6 +30,7 @@ import { withoutTextMeasurement } from '../taco/model/text-reads.js';
30
30
  import { createInstanceResolveCache, resolveComponent, resolveInstance } from '../taco/model/instance-resolver.js';
31
31
  import { applyFileTypography } from './file-typography.js';
32
32
  import { linkWithLayers, unmark } from './link.js';
33
+ import { boundTextExpression, layerComponents } from './file-components.js';
33
34
  const supportsGrid = 'layoutData.gridCell' in editorSchema.Properties;
34
35
  // Figma stores float32 sizes. Comparing after layout or instance scaling can
35
36
  // also include rounding from the arithmetic that produced the two sizes.
@@ -923,6 +924,11 @@ function expand(doc, pages, options, explicit, file, deferHyperlinks) {
923
924
  for (const k of ['fills', 'strokes', 'shadows', 'backgroundBlur', 'layerBlur', 'cornerRadii', 'cornerRadius', 'cornerSmoothing'])
924
925
  if (o[k] !== undefined)
925
926
  style[k] = o[k];
927
+ // A .fig text layer's or group's shadows and blurs, which Taco's model keeps on shapes and frames only
928
+ // (metadata.figma.effects, taco patch 0049).
929
+ if ((n.type === 'text' || n.type === 'group') && figma?.effects)
930
+ for (const [k, v] of Object.entries(figma.effects))
931
+ style[k] ??= v;
926
932
  if (L) {
927
933
  // The resolver writes a bound or computed radius as one cornerRadius; a layer that stores per-corner radii keeps
928
934
  // them as four equal ones, as the converter writes them.
@@ -1445,6 +1451,8 @@ function expand(doc, pages, options, explicit, file, deferHyperlinks) {
1445
1451
  }
1446
1452
  }
1447
1453
  appearance(m, style, 'frame', n.metadata?.figma);
1454
+ if (n.type === 'frame' && n.metadata?.figma?.section === true)
1455
+ m.section = true;
1448
1456
  if (n.metadata?.figma?.strokesIncluded === true && (eff.layout && eff.layout.kind !== 'absolute')) {
1449
1457
  eff.layout = { ...eff.layout, strokesIncluded: true };
1450
1458
  }
@@ -2685,6 +2693,7 @@ function expand(doc, pages, options, explicit, file, deferHyperlinks) {
2685
2693
  s.lineHeight = +(s.size * trimmed).toFixed(3);
2686
2694
  approximate('leading trim (cap height) taken from a box at the cap height');
2687
2695
  }
2696
+ appearance(m, { shadows: style.shadows, layerBlur: style.layerBlur, backgroundBlur: style.backgroundBlur }, 'text', n.metadata?.figma);
2688
2697
  models.push(m);
2689
2698
  return m;
2690
2699
  }
@@ -2816,11 +2825,34 @@ function expand(doc, pages, options, explicit, file, deferHyperlinks) {
2816
2825
  const out = { leading: 'half', ...(!explicit && { page: pages[0].name }), ...(options.source !== undefined ? { source: options.source } : {}), models, ...(used.size ? { assets } : {}) };
2817
2826
  return { out, affected, nestedBooleans, counts: { dropped, expressionErrors, notes, approximations, weights }, depth: depthMax, files };
2818
2827
  }
2828
+ /** A section stays one only on a page or inside another section, the editor's rule and Figma's: anywhere else (a
2829
+ * clipboard selection pasted whole, a layer the conversion re-parented) it imports as the plain frame it draws as.
2830
+ * Parents precede their children in the models. */
2831
+ function keepSections(models) {
2832
+ const holds = new Set(models.filter((m) => m.kind === 'page').map((m) => m.id));
2833
+ for (const m of models) {
2834
+ if (m.kind !== 'frame' || m.section !== true)
2835
+ continue;
2836
+ if (!m.parent || holds.has(m.parent))
2837
+ holds.add(m.id);
2838
+ else
2839
+ delete m.section;
2840
+ }
2841
+ }
2819
2842
  function convert(doc, pages, options, explicit, file, deferHyperlinks = false) {
2820
2843
  // Drop the resolver, trial layouts and pre-layout geometry before indexing linked layers.
2821
2844
  const { out, affected, nestedBooleans, counts, depth, files } = expand(doc, pages, options, explicit, file, deferHyperlinks);
2822
2845
  const models = out.models;
2823
- const linked = options.link === false ? null : linkWithLayers(out, true, file && (id => doc.nodes[id]?.expressions?.componentId), !!file);
2846
+ // A text's expression counts where the file's components bind it (file-components.ts).
2847
+ let owners;
2848
+ const binding = (id, field, main) => {
2849
+ const expression = doc.nodes[id]?.expressions?.[field];
2850
+ if (field !== 'characters')
2851
+ return expression;
2852
+ owners ??= layerComponents(Object.values(doc.components), (id) => doc.nodes[id]?.children);
2853
+ return boundTextExpression(expression, owners.get(id), main);
2854
+ };
2855
+ const linked = options.link === false ? null : linkWithLayers(out, true, file && binding, !!file);
2824
2856
  if (linked && !explicit) {
2825
2857
  // Clipboard mains synthesized from expansions get their presets from the source definition. A variant set's main
2826
2858
  // is the set's root showing one variant, a frame of the root's: the main is that variant, so it takes the
@@ -2889,6 +2921,7 @@ function convert(doc, pages, options, explicit, file, deferHyperlinks = false) {
2889
2921
  if (options.link === false && !options.markers)
2890
2922
  for (const m of out.models)
2891
2923
  unmark(m);
2924
+ keepSections(out.models);
2892
2925
  const remaining = new Set(out.models.map((m) => m.id));
2893
2926
  function affectedIds(id) {
2894
2927
  const aliases = linked?.aliases.get(id) ?? [];
@@ -7,6 +7,24 @@ import type { NestedBooleanAssignments } from './convert.ts';
7
7
  * @internal
8
8
  */
9
9
  export type FileMessage = ReturnType<typeof readFileMessage>;
10
+ /** Per source layer, the component whose properties its expressions bind to (fileComponents): each layer of a
11
+ * component's tree, a later component's tree winning.
12
+ * @internal
13
+ */
14
+ export declare function layerComponents<C extends {
15
+ rootId: string;
16
+ }>(components: Iterable<C>, children: (id: string) => readonly string[] | undefined): Map<string, C>;
17
+ /** The expression a source layer's text takes from a component property where fileComponents binds it: a property,
18
+ * other than a variant or slot, of the component it is a layer of, in that component's main (`main`, its root).
19
+ * @internal
20
+ */
21
+ export declare function boundTextExpression(expression: string | undefined, component: {
22
+ rootId: string;
23
+ properties?: readonly {
24
+ name: string;
25
+ kind: string;
26
+ }[];
27
+ } | undefined, main: string | undefined): string | undefined;
10
28
  /** Installs local property IDs, their bindings, instance assignments and slot content.
11
29
  * @param result - Original Figma component declarations and placements.
12
30
  * @param doc - Linked document, with source IDs for the original nodes.
@@ -1,8 +1,36 @@
1
1
  import { definitions as propertyDefinitions, effectiveRecord, isInstance, ownerOf, resolveVirtual, splitVirtual } from '@moondraft/editor/core';
2
2
  import { guidText } from '../taco/figma-import/import/fields.js';
3
- import { formatExpressionName, parseLayerPath } from '../taco/model/index.js';
3
+ import { DUPLICATE_KEY } from '../taco/figma-import/import/converters/shared.js';
4
+ import { formatExpressionName, layerPathKey, parseLayerPath } from '../taco/model/index.js';
4
5
  import { keepDescription } from './figma-descriptions.js';
6
+ import { withOverrideFields } from './file-resources.js';
5
7
  import { expansionReason } from './link.js';
8
+ /** Per source layer, the component whose properties its expressions bind to (fileComponents): each layer of a
9
+ * component's tree, a later component's tree winning.
10
+ * @internal
11
+ */
12
+ export function layerComponents(components, children) {
13
+ const of = new Map();
14
+ for (const c of components) {
15
+ const pending = [c.rootId];
16
+ while (pending.length) {
17
+ const id = pending.pop();
18
+ of.set(id, c);
19
+ for (const child of children(id) ?? [])
20
+ pending.push(child);
21
+ }
22
+ }
23
+ return of;
24
+ }
25
+ /** The expression a source layer's text takes from a component property where fileComponents binds it: a property,
26
+ * other than a variant or slot, of the component it is a layer of, in that component's main (`main`, its root).
27
+ * @internal
28
+ */
29
+ export function boundTextExpression(expression, component, main) {
30
+ const p = expression === undefined || component === undefined || component.rootId !== main ? undefined
31
+ : component.properties?.find(p => formatExpressionName(p.name) === expression);
32
+ return p && p.kind !== 'enum' && p.kind !== 'slot' ? expression : undefined;
33
+ }
6
34
  /** Installs local property IDs, their bindings, instance assignments and slot content.
7
35
  * @param result - Original Figma component declarations and placements.
8
36
  * @param doc - Linked document, with source IDs for the original nodes.
@@ -68,6 +96,7 @@ export function fileComponents(result, doc, nestedBooleans, report, expandedReas
68
96
  const importedSets = new Map(result.sources.imported.filter(({ figma }) => figma.change.isStateGroup === true)
69
97
  .map(({ node, figma }) => [figma.id, node.id]));
70
98
  const setSources = new Map();
99
+ const setKeys = new Set();
71
100
  for (const [guid, { plan, properties }] of result.sources.variants) {
72
101
  const members = plan.variants;
73
102
  const sourceId = importedSets.get(guid);
@@ -80,7 +109,14 @@ export function fileComponents(result, doc, nestedBooleans, report, expandedReas
80
109
  models.push(set);
81
110
  byId.set(set.id, set);
82
111
  }
83
- set.key = plan.set.change.componentKey || 'figma-' + guid;
112
+ // The editor refuses two sets of one key. The first set in the file's node order keeps a repeated Figma key; the
113
+ // others take their fallback key, so library links by that key reach only the first.
114
+ const authored = plan.set.change.componentKey;
115
+ set.key = typeof authored === 'string' && authored !== '' && !setKeys.has(authored) ? authored : 'figma-' + guid;
116
+ if (set.key !== authored && typeof authored === 'string' && authored !== '') {
117
+ report.push({ kind: 'approximated', what: DUPLICATE_KEY, count: 1, ids: [set.id], sources: [{ id: guid, name: plan.set.name }] });
118
+ }
119
+ setKeys.add(set.key);
84
120
  keepDescription(plan.set, set, report);
85
121
  const variantDefs = new Map(plan.set.change.componentPropDefs.map(d => ['figma-' + guidText(d.id, guid), d]));
86
122
  const orders = new Map((plan.set.change.stateGroupPropertyValueOrders ?? []).map(o => [o.property, o.values]));
@@ -120,7 +156,6 @@ export function fileComponents(result, doc, nestedBooleans, report, expandedReas
120
156
  definitions.set(member.componentId, refs);
121
157
  }
122
158
  }
123
- const sourceComponent = new Map();
124
159
  for (const c of result.components) {
125
160
  const main = mains.get(c.id);
126
161
  main.key = c.key;
@@ -136,14 +171,8 @@ export function fileComponents(result, doc, nestedBooleans, report, expandedReas
136
171
  if (value !== shared.default)
137
172
  report.push({ kind: 'approximated', what: 'variant member property default', count: 1, ids: [main.id] });
138
173
  }
139
- const pending = [c.rootId];
140
- while (pending.length) {
141
- const id = pending.pop(), layer = source.get(id);
142
- sourceComponent.set(id, c);
143
- for (const child of layer.children ?? [])
144
- pending.push(child);
145
- }
146
174
  }
175
+ const sourceComponent = layerComponents(result.components, id => source.get(id).children);
147
176
  const componentOfMain = (id) => componentOfRoot.get(byId.get(id)?.sourceId);
148
177
  function values(component, assignments, id) {
149
178
  const refs = definitions.get(component);
@@ -169,6 +198,28 @@ export function fileComponents(result, doc, nestedBooleans, report, expandedReas
169
198
  }).join(';');
170
199
  }
171
200
  const occurrences = new Map();
201
+ // A linked instance inside an expanded one also shows what the expanded instances above it override through it
202
+ // (paints, styles, bindings), as a layer of the expansion does (file-resources expandedFields): their fields join its
203
+ // own at each of its paths, the outer instance's winning.
204
+ function throughExpanded(m, own) {
205
+ let fields = own;
206
+ const path = [m.sourceId];
207
+ for (let parent = byId.get(m.parent); parent; parent = byId.get(parent.parent)) {
208
+ if (source.get(parent.sourceId)?.type !== 'instance')
209
+ continue;
210
+ const outer = parent.component ? undefined : result.sources.occurrenceFields.get(parent.sourceId), prefix = layerPathKey(path);
211
+ for (const [key, over] of outer ?? []) {
212
+ if (key !== prefix && !key.startsWith(prefix + ';'))
213
+ continue;
214
+ const inner = key.slice(prefix.length + 1);
215
+ if (fields === own)
216
+ fields = new Map(own);
217
+ fields.set(inner, withOverrideFields(fields.get(inner) ?? {}, over));
218
+ }
219
+ path.unshift(parent.sourceId);
220
+ }
221
+ return fields;
222
+ }
172
223
  const instanceOverrides = new Map();
173
224
  const hosts = new Set(result.nodes.filter(n => n.type === 'frame' && n.slotHost).map(n => n.id));
174
225
  const usedHosts = new Set();
@@ -230,7 +281,7 @@ export function fileComponents(result, doc, nestedBooleans, report, expandedReas
230
281
  report.push({ kind: 'approximated', what: reason ? `expanded instance: ${expansionReason(reason)}` : 'expanded instance', count: 1, ids: [m.id] });
231
282
  continue;
232
283
  }
233
- const fields = result.sources.occurrenceFields.get(n.id);
284
+ const fields = throughExpanded(m, result.sources.occurrenceFields.get(n.id));
234
285
  if (fields)
235
286
  occurrences.set(m.id, new Map([...fields].map(([key, change]) => [overridePath(key), change])));
236
287
  // The editor resolves a stored bound swap from the enclosing main or set's declaration.
@@ -321,6 +372,40 @@ export function fileComponents(result, doc, nestedBooleans, report, expandedReas
321
372
  (owner.props ??= {})[binding] = entry.component;
322
373
  }
323
374
  }
375
+ // A linked occurrence whose text, bound to a text property, shows other wording than the property gives it there (a
376
+ // Figma text override, not an assignment) assigns that wording to the property: core derives a bound text's content
377
+ // from its property and drops the override. Wording the property already gives stays as it is. What it gives is read
378
+ // from the converted overrides, not from assignments this loop adds, so the order of the instances does not matter.
379
+ // Linking leaves expanded an occurrence whose texts bound to one property show different wording (link.ts match).
380
+ for (const holder of models) {
381
+ if (!isInstance(holder))
382
+ continue;
383
+ for (const [path, entry] of Object.entries(holder.overrides ?? {})) {
384
+ if (typeof entry.content !== 'string')
385
+ continue;
386
+ const target = resolveVirtual(get, holder.id + ';' + path, true);
387
+ const binding = target?.layer.bind?.content;
388
+ if (!target || !binding)
389
+ continue;
390
+ const at = target.levels.at(-1)[1], ownerPath = target.parts.slice(1, at + 1).join(';');
391
+ if (binding in ((at === 0 ? holder : holder.overrides[ownerPath])?.props ?? {}))
392
+ continue;
393
+ // An enclosing main's assignment to the occurrence or its own wording of the text, outermost first, else the default.
394
+ let given;
395
+ for (const [level, j] of target.levels.slice(1)) {
396
+ const assigned = j === at ? level.props : level.overrides?.[target.parts.slice(j + 1, at + 1).join(';')]?.props;
397
+ given = assigned?.[binding] ?? level.overrides?.[target.parts.slice(j + 1).join(';')]?.content;
398
+ if (typeof given === 'string')
399
+ break;
400
+ }
401
+ const shown = at === 0 ? holder.component : resolveVirtual(get, holder.id + ';' + ownerPath, true)?.component;
402
+ given ??= propertyDefinitions(ownerOf(get, get(shown))).find(p => p.id === binding)?.default;
403
+ if (given === entry.content)
404
+ continue;
405
+ const owner = at === 0 ? holder : (holder.overrides[ownerPath] ??= {});
406
+ (owner.props ??= {})[binding] = entry.content;
407
+ }
408
+ }
324
409
  // A flattened ancestor can also leave an assignment inside a surviving linked instance.
325
410
  // Apply inherited paths before the longer paths of the instances that use them.
326
411
  for (const [id, inherited] of [...nestedBooleans].filter(([id]) => id.includes(';')).sort(([a], [b]) => a.length - b.length)) {
@@ -1,4 +1,4 @@
1
- import type { ImportReportEntry } from '@moondraft/editor/core';
1
+ import { type ImportReportEntry } from '@moondraft/editor/core';
2
2
  import { type DocumentJSON } from '@moondraft/editor/schema';
3
3
  import { type FigmaObject } from '../taco/figma-import/import/fields.ts';
4
4
  import type { FileMessage } from './file-components.ts';
@@ -9,6 +9,11 @@ type Corner = {
9
9
  specific: boolean;
10
10
  };
11
11
  };
12
+ type Change = Record<string, any>;
13
+ /** `change` with an enclosing instance's override fields (`own`) merged in: its plain fields replace the change's
14
+ * (unbinding the fields they set), and its bindings and modes replace only those of the same fields and collections.
15
+ * A list of paints in the override drops the change's style of that slot unless the override names one. */
16
+ export declare function withOverrideFields(change: Change, own: Change): Change;
12
17
  /** Finds instance roots that need their own radius bindings. Native instance roots take bindings from their main.
13
18
  * @param result - File definitions and original instance fields.
14
19
  * @returns The effective corners for each root that must remain an expanded frame.