@nodii/dev 0.6.124 → 0.6.126

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.
package/dist/surface.js CHANGED
@@ -32,7 +32,7 @@ import { CliError, VERSION, devRequest, readConfig } from "./core.js";
32
32
  import { createRenderer } from "./vendor/render-templates.mjs";
33
33
 
34
34
  /** Bumped whenever the emitted code changes shape for the same inputs. */
35
- export const GENERATOR_FORMAT = 8;
35
+ export const GENERATOR_FORMAT = 9;
36
36
  export const TREE_DIR = "docs/figma-ux-ds/figma/surface-trees";
37
37
  export const GENERATED_SUFFIX = ".surface.generated.tsx";
38
38
  /** Where every generated product page lives, as a git glob (NODII-DEV-CLI-77). */
@@ -373,7 +373,17 @@ export function trimTree(entry, { row, version }) {
373
373
  if (Object.keys(exposed).length) out.instance.exposed = exposed;
374
374
  }
375
375
  // A library instance is the template's to draw: only its slots' content is the Surface's.
376
- const children = main.remote ? (node.children ?? []).filter((c) => c.type === "SLOT") : (node.children ?? []);
376
+ // A slot can sit inside the component's own frames (the App Frame's `mainContent` in its
377
+ // Main column, the Data Table Toolbar's `trailing` in its toolbar row), so every slot of
378
+ // this instance is kept, down to (not into) a nested instance or another slot
379
+ // (NODII-DEV-CLI-81).
380
+ const slotsOf = function* (parent) {
381
+ for (const child of parent.children ?? []) {
382
+ if (child.type === "SLOT") yield child;
383
+ else if (child.type !== "INSTANCE") yield* slotsOf(child);
384
+ }
385
+ };
386
+ const children = main.remote ? [...slotsOf(node)] : (node.children ?? []);
377
387
  if (children.length) out.children = children.map((c) => trim(c, box));
378
388
  return out;
379
389
  }
@@ -496,17 +506,20 @@ export function emitSurface(tree, row, ds) {
496
506
  used.add(state);
497
507
  const fn = `${pascal(state)}View`;
498
508
  const note = (path, kind, detail) => unmapped.push({ variant: variant.name, path, kind, detail });
499
- const emitted = emitNode(variant.root, { depth: 2, parent: null, path: variant.name, ds, imports, note, root: true, scopes }) ?? "";
500
- // A refused root is only a comment, and `return ({/* … */})` is an object, not JSX.
501
- const body = emitted.trimStart().startsWith("{/*") ? [" <>", indent(emitted.trim(), 3), " </>"].join("\n") : emitted;
502
- return { state, fn, body };
509
+ const emitted = emitNode(pageBody(variant, row), { depth: 2, parent: null, path: variant.name, ds, imports, note, root: true, scopes, state }) ?? "";
510
+ // A view the generator can't lay out is no page at all: generation fails rather than ship
511
+ // an empty view (NODII-DEV-CLI-81).
512
+ if (emitted.trimStart().startsWith("{/*")) {
513
+ throw new CliError("SURFACE_VIEW_NOT_LAID_OUT", `${row.id}: view ${JSON.stringify(variant.name)} has no auto layout, so it would generate as an empty page; give the variant (or the App Frame's mainContent) auto layout in Figma, publish, and refetch`, 1);
514
+ }
515
+ return { state, fn, body: emitted };
503
516
  });
504
517
  const component = `${pascal(row.id)}Surface`;
505
518
  const stateType = `${component}State`;
506
519
  const propsType = `${component}Props`;
507
520
  resolveScopes(views, scopes);
508
521
  const data = dataProps(views);
509
- const reactTypes = [data.size && "ComponentProps", [...data.values()].some((d) => d.child) && "ReactNode"].filter(Boolean);
522
+ const reactTypes = [data.size && "ComponentProps", [...data.values()].some((d) => /\bReactNode\b/.test(propType(d))) && "ReactNode"].filter(Boolean);
510
523
  const drawn = [...data.values()].some((d) => [...d.attrs.values(), ...[...d.members.values()].flatMap((refs) => [...refs.values()])].some((r) => r.keys));
511
524
  const header = [
512
525
  "// GENERATED by `nodii-dev surface generate` from Code Connect (MW8-17). Do not edit:",
@@ -544,6 +557,34 @@ export function emitSurface(tree, row, ds) {
544
557
  return { code: lines.join("\n"), unmapped, states: views.map((v) => v.state) };
545
558
  }
546
559
 
560
+ /**
561
+ * The DS App Frame (sidebar, navbar and the page in its `mainContent` slot). The
562
+ * frontend's /app shell owns the frame, so a view drawn inside it generates only
563
+ * the page: the slot's content (NODII-DEV-CLI-81).
564
+ */
565
+ export const APP_FRAME = { set: "App Frame", slot: "mainContent" };
566
+
567
+ /**
568
+ * What a view generates as its page: the App Frame's `mainContent` slot when
569
+ * the view draws its page in the App Frame, else the variant itself. An App
570
+ * Frame beside other layers, or one whose tree has no `mainContent` (read before
571
+ * nested slots were kept), is refused, never guessed.
572
+ */
573
+ export function pageBody(variant, row) {
574
+ const root = variant.root;
575
+ const shown = (root.children ?? []).filter((c) => c.visible !== false);
576
+ const frames = shown.filter((c) => c.instance?.remote && c.instance.set === APP_FRAME.set);
577
+ if (!frames.length) return root;
578
+ if (frames.length > 1 || shown.length > 1) {
579
+ throw new CliError("SURFACE_VIEW_NOT_LAID_OUT", `${row.id}: view ${JSON.stringify(variant.name)} draws the App Frame beside ${shown.length - 1} other layer${shown.length === 2 ? "" : "s"}; a page in the App Frame puts all of its content in mainContent`, 1);
580
+ }
581
+ const slot = (frames[0].children ?? []).find((c) => c.type === "SLOT" && c.slot === APP_FRAME.slot);
582
+ if (!slot) {
583
+ throw new CliError("SURFACE_TREE_STALE", `${row.id}: view ${JSON.stringify(variant.name)} draws the App Frame, but its committed tree holds no ${APP_FRAME.slot} slot (it was read before nested slots were kept); refetch it with \`nodii-dev surface generate ${row.componentSetKey} --fetch --write\``, 1);
584
+ }
585
+ return { ...slot, name: root.name };
586
+ }
587
+
547
588
  /**
548
589
  * The free identifiers the templates emit (`onSelect={onSelect}`, a child
549
590
  * `{title}`, `size={file.size}`): the page's data and callbacks, lifted into
@@ -556,12 +597,20 @@ const JS_LITERALS = new Set(["true", "false", "null", "undefined", "this"]);
556
597
  /** Strings blanked to spaces of the same length, so a position still points into `code`. */
557
598
  const maskStrings = (code) => code.replace(/"(?:[^"\\\n]|\\.)*"|`[^`]*`/g, (s) => `"${" ".repeat(s.length - 2)}"`);
558
599
 
600
+ /** A list the generator lifts opens `{rows.map((row) => (`: [{ at, list, param }] in order. */
601
+ const LIST_OPEN = /\{([A-Za-z_][A-Za-z0-9_]*)\.map\(\(([a-z][A-Za-z0-9]*)\) => \(/g;
602
+ const listOpeners = (code) => [...code.matchAll(LIST_OPEN)].map((m) => ({ at: m.index, list: m[1], param: m[2] }));
603
+ /** The list whose item `param` names at position `at`: the nearest opener before it that binds it. */
604
+ const listAt = (openers, at, param) => openers.filter((o) => o.at < at && o.param === param).at(-1)?.list ?? null;
605
+
559
606
  /** Every free identifier a template emits in `code`: [{ at, name }], in the three forms dataProps reads. */
560
607
  function freeIdentifiers(code) {
561
608
  const masked = maskStrings(code);
562
609
  const found = new Map();
610
+ // A lifted list's item (`row` in `rows.map((row) => …)`) is bound, not free.
611
+ const params = new Set(listOpeners(masked).map((o) => o.param));
563
612
  const add = (at, name) => {
564
- if (!JS_LITERALS.has(name)) found.set(at, name);
613
+ if (!JS_LITERALS.has(name) && !params.has(name)) found.set(at, name);
565
614
  };
566
615
  for (const m of masked.matchAll(/([A-Za-z][\w-]*)=\{([a-z][A-Za-z0-9]*)(?:\.[A-Za-z][A-Za-z0-9]*)?\}/g)) add(m.index + m[1].length + 2, m[2]);
567
616
  for (const m of masked.matchAll(/(^|>)(\s*)\{([a-z][A-Za-z0-9]*)\}/gm)) add(m.index + m[1].length + m[2].length + 1, m[3]);
@@ -577,11 +626,75 @@ function freeIdentifiers(code) {
577
626
  function scopeName(node) {
578
627
  const props = node.instance?.props ?? {};
579
628
  const text = [props.label, props.title].find((v) => typeof v === "string" && /[A-Za-z0-9]/.test(v)) ?? node.name ?? "";
580
- const words = text.match(/[A-Za-z0-9]+/g) ?? [];
629
+ return camelName(text);
630
+ }
631
+
632
+ /** Text in camelCase as an identifier (`Subject kind` → `subjectKind`, `2FA` → `field2fa`). */
633
+ function camelName(text) {
634
+ const words = String(text ?? "").match(/[A-Za-z0-9]+/g) ?? [];
581
635
  const name = words.map((w, i) => (i === 0 ? w.toLowerCase() : w[0].toUpperCase() + w.slice(1).toLowerCase())).join("");
582
636
  return /^[a-z]/.test(name) ? name : `field${name.replace(/^./, (c) => c.toUpperCase())}`;
583
637
  }
584
638
 
639
+ /** `name` marked with `scope` (`__s<n>_name`), as scopeIdentifiers marks a template's identifiers. */
640
+ function mark(ctx, scope, name) {
641
+ if (!ctx.scopes) return name;
642
+ if (!ctx.scopes.has(scope)) ctx.scopes.set(scope, ctx.scopes.size);
643
+ return `__s${ctx.scopes.get(scope)}_${name}`;
644
+ }
645
+
646
+ /** What the generator lifted from Figma's sample into the page's props: listed, not counted (NODII-DEV-CLI-82). */
647
+ const LIFTED = "lifted";
648
+
649
+ /**
650
+ * Slots whose content is the page's data, never Figma's sample: the template
651
+ * passes them as a prop, so the generator passes the page's own node through
652
+ * (NODII-DEV-CLI-83: the Data Table Toolbar's `trailing` holds the list's filter controls).
653
+ */
654
+ export const DATA_SLOTS = new Map([["Data Table Toolbar", new Set(["trailing"])]]);
655
+
656
+ const LITERAL = String.raw`(?:"(?:[^"\\\n]|\\.)*"|\{"(?:[^"\\\n]|\\.)*"\})`;
657
+ const literalText = (lit) => JSON.parse(lit.startsWith("{") ? lit.slice(1, -1) : lit);
658
+
659
+ /**
660
+ * A record's values that a template draws from Figma's sample, lifted into
661
+ * the page's props so a real tenant never sees an invented record
662
+ * (NODII-DEV-CLI-82). Each rule is keyed by what the template emits:
663
+ * - a Dialog's or AlertDialog's title and description: `<view state>Title`,
664
+ * `<view state>Description`;
665
+ * - a DescriptionItem's value, named by its label (the label is copy and stays);
666
+ * - a StatusPill's label and tone, named by where it sits.
667
+ * A run of sibling DescriptionLists and a table's body rows are lifted as lists
668
+ * (liftedDescriptionList, tableOf). Real copy (headings, labels, buttons) stays.
669
+ */
670
+ function liftRecordData(code, node, ctx, path) {
671
+ const lifted = [];
672
+ const lift = (scope, name) => (lifted.push(name), mark(ctx, scope, name));
673
+ let out = code.replace(new RegExp(String.raw`<((?:Alert)?Dialog(Title|Description))\b([^>]*)>\{"(?:[^"\\\n]|\\.)*"\}</\1>`, "g"), (_, tag, part, attrs) => `<${tag}${attrs}>{${lift(camelName(ctx.state ?? "dialog"), part.toLowerCase())}}</${tag}>`);
674
+ out = out.replace(/<DescriptionItem\b([^>]*?)\/>/g, (all, attrs) => {
675
+ const value = new RegExp(String.raw`\bvalue=${LITERAL}`).exec(attrs);
676
+ if (!value) return all;
677
+ const label = new RegExp(String.raw`\blabel=(${LITERAL})`).exec(attrs);
678
+ const scope = camelName(label ? literalText(label[1]) : node.name);
679
+ return `<DescriptionItem${attrs.replace(value[0], `value={${lift(scope, "value")}}`)}/>`;
680
+ });
681
+ out = out.replace(/<StatusPill\b([^>]*?)(\/?)>/g, (all, attrs, close) => {
682
+ const label = new RegExp(String.raw`\blabel=${LITERAL}`).exec(attrs);
683
+ if (!label) return all;
684
+ const siblings = (ctx.parent?.children ?? []).filter((c) => c.visible !== false && c.instance?.set === node.instance?.set);
685
+ const scope = camelName(`${ctx.parent?.name ?? "status"} status${siblings.length > 1 ? ` ${siblings.indexOf(node) + 1}` : ""}`);
686
+ const tone = new RegExp(String.raw`\btone=${LITERAL}`).exec(attrs);
687
+ let next = attrs.replace(label[0], `label={${lift(scope, "label")}}`);
688
+ next = tone ? next.replace(tone[0], `tone={${lift(scope, "tone")}}`) : next.replace(`label={`, `tone={${lift(scope, "tone")}} label={`);
689
+ return `<StatusPill${next}${close}>`;
690
+ });
691
+ if (lifted.length) ctx.note(path, LIFTED, `${[...new Set(lifted)].join(", ")} lifted from Figma's sample into the page's props (NODII-DEV-CLI-82)`);
692
+ return out;
693
+ }
694
+
695
+ /** Tabs the page controls: its tab is a prop, and choosing one calls back (NODII-DEV-CLI-83). */
696
+ const CONTROLLED_TABS = (value, onChange) => `<Tabs panelless value={${value}} onValueChange={${onChange}}>`;
697
+
585
698
  /**
586
699
  * Marks each free identifier in one instance's code with its instance's
587
700
  * scope (`__s<n>_date`); resolveScopes later keeps the plain name or scopes it.
@@ -616,17 +729,35 @@ function resolveScopes(views, scopes) {
616
729
 
617
730
  function dataProps(views) {
618
731
  const data = new Map();
619
- const entry = (name) => data.get(name) ?? data.set(name, { attrs: new Map(), child: false, nested: false, members: new Map() }).get(name);
732
+ const entry = (name) => data.get(name) ?? data.set(name, { attrs: new Map(), child: false, nested: false, members: new Map(), list: false }).get(name);
733
+ const member = (d, name) => d.members.get(name) ?? d.members.set(name, new Map()).get(name);
620
734
  for (const view of views) {
621
735
  view.uses = new Set();
622
736
  const body = view.body;
737
+ // A lifted list (`{rows.map((row) => (`): its item's reads are the list's members.
738
+ const openers = listOpeners(body);
739
+ for (const o of openers) {
740
+ entry(o.list).list = true;
741
+ view.uses.add(o.list);
742
+ }
743
+ const itemList = (at, name) => (openers.some((o) => o.param === name) ? listAt(openers, at, name) : null);
623
744
  for (const m of body.matchAll(/([A-Za-z][\w-]*)=\{([a-z][A-Za-z0-9]*)(?:\.([A-Za-z][A-Za-z0-9]*))?\}/g)) {
624
745
  if (JS_LITERALS.has(m[2])) continue;
746
+ const list = m[3] ? itemList(m.index, m[2]) : null;
747
+ // A list item's React key is its own: a string, never a DS prop.
748
+ if (list && m[1] === "key") {
749
+ member(entry(list), m[3]).set("\u0000key", { raw: "string" });
750
+ continue;
751
+ }
625
752
  const start = openingTag(body, m.index);
626
753
  if (start === null) continue;
627
- const d = entry(m[2]);
628
- addDrawn(m[3] ? (d.members.get(m[3]) ?? d.members.set(m[3], new Map()).get(m[3])) : d.attrs, drawnProps(body, start), m[1]);
629
- view.uses.add(m[2]);
754
+ const d = entry(list ?? m[2]);
755
+ addDrawn(m[3] ? member(d, m[3]) : d.attrs, drawnProps(body, start), m[1]);
756
+ if (!list) view.uses.add(m[2]);
757
+ }
758
+ for (const m of body.matchAll(/(^|>)\s*\{([a-z][A-Za-z0-9]*)\.([A-Za-z][A-Za-z0-9]*)\}/gm)) {
759
+ const list = itemList(m.index, m[2]);
760
+ if (list) member(entry(list), m[3]).set("\u0000child", { raw: "ReactNode" });
630
761
  }
631
762
  for (const m of body.matchAll(/(^|>)\s*\{([a-z][A-Za-z0-9]*)\}/gm)) {
632
763
  if (JS_LITERALS.has(m[2])) continue;
@@ -693,7 +824,8 @@ function addDrawn(refs, drawn, attr) {
693
824
  }
694
825
 
695
826
  /** A prop's type: `Drawn<ComponentProps<typeof Tag>, keys, literals>["attr"]`, or the plain props when unnarrowed. */
696
- function drawnRef({ tag, attr, keys, literals }) {
827
+ function drawnRef({ tag, attr, keys, literals, raw }) {
828
+ if (raw) return raw;
697
829
  const props = `ComponentProps<typeof ${tag}>`;
698
830
  if (!keys) return `${props}[${JSON.stringify(attr)}]`;
699
831
  const lits = [...literals.entries()].sort(([a], [b]) => a.localeCompare(b));
@@ -772,7 +904,10 @@ function tagAttributes(body, at) {
772
904
  const propType = (d) => {
773
905
  // A value nested in an object prop has no ComponentProps path the generator can name.
774
906
  const parts = [...[...d.attrs.values()].map(drawnRef), ...(d.child ? ["ReactNode"] : []), ...(d.nested ? ["any"] : [])];
775
- if (d.members.size) parts.push(`{ ${[...d.members.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([k, refs]) => `${k}: ${[...refs.values()].map(drawnRef).join(" & ")}`).join("; ")} }`);
907
+ const shape = `{ ${[...d.members.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([k, refs]) => `${k}: ${[...refs.values()].map(drawnRef).join(" & ")}`).join("; ")} }`;
908
+ // A lifted list is an array of its items (NODII-DEV-CLI-82).
909
+ if (d.list) parts.push(`Array<${shape}>`);
910
+ else if (d.members.size) parts.push(shape);
776
911
  return parts.join(" & ");
777
912
  };
778
913
 
@@ -867,7 +1002,7 @@ function colour(prefix, paint, scope, ds, report) {
867
1002
  const BOUND_TEXT = "bound-text";
868
1003
  /** What the generator assembled from Code Connect parts (MW8-17.3): listed, not counted. */
869
1004
  const ASSEMBLED = "assembled";
870
- const LISTED_ONLY = new Set([BOUND_TEXT, ASSEMBLED]);
1005
+ const LISTED_ONLY = new Set([BOUND_TEXT, ASSEMBLED, LIFTED]);
871
1006
  const counted = (unmapped) => unmapped.filter((u) => !LISTED_ONLY.has(u.kind));
872
1007
 
873
1008
  /** DS parts whose text should be a component property, not slot content (the Q-211 Lock-Change). */
@@ -901,6 +1036,10 @@ function emitNode(node, ctx) {
901
1036
  .map(([layer, e]) => [layer, { nodeId: ds.byKey.get(e.key), values: valuesOf(e.props) }]),
902
1037
  );
903
1038
  const slotContent = (prop) => {
1039
+ if (DATA_SLOTS.get(node.instance.set)?.has(prop)) {
1040
+ note(`${path} › ${prop}`, LIFTED, `slot ${prop} of ${node.instance.set} is the page's own content, passed through as a prop (NODII-DEV-CLI-83)`);
1041
+ return `<>{${prop}}</>`;
1042
+ }
904
1043
  const slotNode = (node.children ?? []).find((c) => c.type === "SLOT" && c.slot === prop);
905
1044
  if (slotNode && !slotNode.layout && (slotNode.children ?? []).filter((c) => c.visible !== false && !c.absolute).length > 1) {
906
1045
  note(`${path} › ${prop}`, "layout", `slot ${prop} has no auto layout`);
@@ -919,7 +1058,12 @@ function emitNode(node, ctx) {
919
1058
  }
920
1059
  ctx.imports.push(...rendered.imports);
921
1060
  const sizing = ctx.bare ? [] : sizeClasses(node, parent, false);
922
- const code = ctx.scopes ? scopeIdentifiers(rendered.code.trim(), scopeName(node), ctx.scopes) : rendered.code.trim();
1061
+ // A data slot passed straight to a prop is that prop (`trailing={<>{trailing}</>}` → `trailing={trailing}`).
1062
+ let own = rendered.code.trim().replace(/=\{<>\{([a-z][A-Za-z0-9]*)\}<\/>\}/g, "={$1}");
1063
+ // A tab strip the page controls (tabOf reads the template's own strip first, to gather a run).
1064
+ if (!ctx.tabProbe) own = own.replace(/<Tabs panelless(?: defaultValue="[^"]*")?>/g, CONTROLLED_TABS("tab", "onTabChange"));
1065
+ own = liftRecordData(own, node, ctx, path);
1066
+ const code = ctx.scopes ? scopeIdentifiers(own, scopeName(node), ctx.scopes) : own;
923
1067
  // A Table part is valid only inside the DS Table. One the generator could not assemble
924
1068
  // into a Table stays reported, never passed off as mapped (MW8-17.3).
925
1069
  const tag = /^<([A-Za-z]+)/.exec(code)?.[1];
@@ -988,15 +1132,22 @@ function emitNode(node, ctx) {
988
1132
  function emitChildren(children, emitOne, ctx) {
989
1133
  const out = [];
990
1134
  let run = [];
1135
+ let runKind = null;
991
1136
  const flush = () => {
992
- if (run.length >= 2) out.push(tabStrip(run, ctx));
1137
+ if (run.length >= 2 && runKind === "tab") out.push(tabStrip(run, ctx));
1138
+ else if (run.length >= 2) out.push(descriptionRun(run, ctx));
993
1139
  else out.push(...run.map(emitOne).filter((x) => x !== null));
994
1140
  run = [];
1141
+ runKind = null;
995
1142
  };
996
1143
  for (const c of children) {
997
1144
  if (c.visible === false) continue;
998
- if (tabOf(c, ctx)) run.push(c);
999
- else {
1145
+ const kind = tabOf(c, ctx) ? "tab" : descriptionOf(c, ctx) ? `dl${descriptionOf(c, ctx).open}` : null;
1146
+ if (kind && kind !== runKind) flush();
1147
+ if (kind) {
1148
+ run.push(c);
1149
+ runKind = kind;
1150
+ } else {
1000
1151
  flush();
1001
1152
  const code = emitOne(c);
1002
1153
  if (code !== null) out.push(code);
@@ -1006,13 +1157,48 @@ function emitChildren(children, emitOne, ctx) {
1006
1157
  return out;
1007
1158
  }
1008
1159
 
1160
+ /** What the DescriptionList template emits for one field: one DescriptionItem in its list. */
1161
+ const ONE_DESCRIPTION = /^<DescriptionList((?:\s[^>]*)?)>\n\s*<DescriptionItem\b[^>]*?\/>\n\s*<\/DescriptionList>$/;
1162
+
1163
+ /** A DS instance whose template emits a one-field DescriptionList: { open, imports } (its list's attributes), else null. */
1164
+ function descriptionOf(node, ctx) {
1165
+ if (!node.instance?.remote || node.visible === false) return null;
1166
+ const imports = [];
1167
+ const code = emitNode(node, { ...ctx, depth: 0, parent: null, bare: true, inTable: false, tabProbe: true, scopes: null, imports, note: () => {} });
1168
+ const m = ONE_DESCRIPTION.exec(code?.trim() ?? "");
1169
+ return m ? { open: m[1], imports } : null;
1170
+ }
1171
+
1172
+ /**
1173
+ * A run of sibling one-field DescriptionLists is a record's fields, or a list
1174
+ * (a cart's lines): either way the page's data, never Figma's sample. It is one
1175
+ * DescriptionList over an `items` prop of { label, value } (NODII-DEV-CLI-82).
1176
+ */
1177
+ function descriptionRun(run, ctx) {
1178
+ const { depth, path } = ctx;
1179
+ const { open, imports } = descriptionOf(run[0], ctx);
1180
+ ctx.imports.push(...imports);
1181
+ const items = mark(ctx, scopeName(ctx.parent ?? { name: "items" }), "items");
1182
+ ctx.note(path, LIFTED, `${run.length} sibling Description Lists lifted as one list of items (NODII-DEV-CLI-82)`);
1183
+ const list = [
1184
+ `<DescriptionList${open}>`,
1185
+ ` {${items}.map((item) => (`,
1186
+ " <DescriptionItem key={item.label} label={item.label} value={item.value} />",
1187
+ " ))}",
1188
+ "</DescriptionList>",
1189
+ ];
1190
+ const sizing = sizeClasses(run[0], ctx.parent, false);
1191
+ if (!sizing.length) return indent(list.join("\n"), depth);
1192
+ return [indent(`<div className="${cls(["flex", "flex-col", ...sizing])}">`, depth), indent(list.join("\n"), depth + 1), indent("</div>", depth)].join("\n");
1193
+ }
1194
+
1009
1195
  /** The single-tab strip the Tab template emits: Tabs › TabsList › one TabsTrigger. */
1010
1196
  const TAB_STRIP = /^<Tabs panelless( defaultValue="tab")?>\n\s*<TabsList>\n(\s*)(<TabsTrigger\b[\s\S]*?<\/TabsTrigger>)\n\s*<\/TabsList>\n\s*<\/Tabs>$/;
1011
1197
 
1012
1198
  /** A DS instance whose template emits one tab: { selected, trigger } (trigger dedented to column 0), else null. */
1013
1199
  function tabOf(node, ctx, { imports = [], note = () => {} } = {}) {
1014
1200
  if (!node.instance?.remote || node.visible === false) return null;
1015
- const code = emitNode(node, { ...ctx, depth: 0, parent: null, bare: true, inTable: false, imports, note });
1201
+ const code = emitNode(node, { ...ctx, depth: 0, parent: null, bare: true, inTable: false, tabProbe: true, imports, note });
1016
1202
  const m = TAB_STRIP.exec(code?.trim() ?? "");
1017
1203
  if (!m || (m[3].match(/<TabsTrigger\b/g) ?? []).length !== 1) return null;
1018
1204
  const pad = m[2].length;
@@ -1023,11 +1209,11 @@ function tabOf(node, ctx, { imports = [], note = () => {} } = {}) {
1023
1209
  function tabStrip(run, ctx) {
1024
1210
  const { depth, path } = ctx;
1025
1211
  const tabs = run.map((c) => tabOf(c, { ...ctx, path: `${path} › ${c.name}` }, { imports: ctx.imports, note: ctx.note }));
1026
- const selected = tabs.findIndex((t) => t.selected);
1027
- ctx.note(path, ASSEMBLED, `${run.length} sibling Tabs gathered into one DS Tab strip (MW8-17.3)`);
1212
+ ctx.note(path, ASSEMBLED, `${run.length} sibling Tabs gathered into one DS Tab strip (MW8-17.3)`);
1028
1213
  const triggers = tabs.map((t, i) => indent(t.trigger.replace(/(<TabsTrigger\b[\s\S]*?)\bvalue="tab"/, `$1value="tab-${i + 1}"`), 2));
1029
1214
  return [
1030
- indent(`<Tabs panelless${selected >= 0 ? ` defaultValue="tab-${selected + 1}"` : ""}>`, depth),
1215
+ // The page controls which tab is shown (NODII-DEV-CLI-83); Figma's selected tab is only the drawn one.
1216
+ indent(CONTROLLED_TABS(mark(ctx, scopeName(ctx.parent ?? { name: "tabs" }), "tab"), mark(ctx, scopeName(ctx.parent ?? { name: "tabs" }), "onTabChange")), depth),
1031
1217
  indent(" <TabsList>", depth),
1032
1218
  ...triggers.map((t) => indent(t, depth)),
1033
1219
  indent(" </TabsList>", depth),
@@ -1070,13 +1256,32 @@ export function columnWidth(cell) {
1070
1256
  const widthAttr = (w) => (w === null ? "" : typeof w === "number" ? ` width={${w}}` : ` width="${w}"`);
1071
1257
  /** Add `width` to a TableHead/TableCell's opening tag, unless its template already declares one. */
1072
1258
  function withWidth(code, w) {
1073
- if (w === null || !code) return code;
1259
+ if (!code) return code;
1260
+ // A cell whose sizing says no width takes none: the placeholder is never left for the page to fill.
1261
+ if (w === null) return code.replace(/^(\s*<Table[A-Za-z]*\b[^>]*?)\swidth=\{(?:__s\d+_)?width\}/, "$1");
1074
1262
  const m = /^(\s*<Table[A-Za-z]*)([\s>/])/.exec(code);
1075
1263
  if (!m) return code;
1076
1264
  const tagEnd = code.indexOf(">", m[0].length - 1);
1077
- if (/\bwidth=/.test(code.slice(0, tagEnd === -1 ? code.length : tagEnd))) return code;
1265
+ const open = code.slice(0, tagEnd === -1 ? code.length : tagEnd);
1266
+ // The Table templates pass the column's width as the frame-sized placeholder `width={width}`:
1267
+ // it is bound here, per placed cell, from the cell's own sizing (DESIGN-SYSTEM-252, NODII-DEV-CLI-79).
1268
+ if (/\bwidth=\{(?:__s\d+_)?width\}/.test(open)) return code.replace(/\swidth=\{(?:__s\d+_)?width\}/, widthAttr(w));
1269
+ if (/\bwidth=/.test(open)) return code;
1078
1270
  return code.replace(m[1], `${m[1]}${widthAttr(w)}`);
1079
1271
  }
1272
+ /** Where a JSX opening tag that starts `code` ends (its `>`), stepping over braces and strings. */
1273
+ function openTagEnd(code) {
1274
+ let depth = 0;
1275
+ for (let i = 0; i < code.length; i++) {
1276
+ const c = code[i];
1277
+ if (c === '"' || c === "'" || c === "`") {
1278
+ for (i++; i < code.length && code[i] !== c; i++) if (code[i] === "\\") i++;
1279
+ } else if (c === "{") depth++;
1280
+ else if (c === "}") depth--;
1281
+ else if (c === ">" && depth === 0) return i;
1282
+ }
1283
+ return code.length - 1;
1284
+ }
1080
1285
  function tableOf(node, ctx) {
1081
1286
  const shown = (node.children ?? []).filter((c) => c.visible !== false);
1082
1287
  // What follows the rows (a table's Empty State, bare or in its own frame) follows the Table:
@@ -1144,6 +1349,7 @@ function tableOf(node, ctx) {
1144
1349
  if (p.kind) continue;
1145
1350
  if (p.cells.length !== columns) return null;
1146
1351
  p.kind = "body";
1352
+ p.framesOnly = true;
1147
1353
  }
1148
1354
  const module = imports.map((s) => /\{[^}]*\bTable[A-Za-z]*(Cell|Head)\b[^}]*\}\s+from\s+["']([^"']+)["']/.exec(s)?.[2]).find(Boolean);
1149
1355
  if (!module) return null;
@@ -1179,7 +1385,7 @@ function tableOf(node, ctx) {
1179
1385
  ASSEMBLED,
1180
1386
  `${rows.length} row${rows.length === 1 ? "" : "s"} of Table parts${plain ? ` (${plain} of them frame cells only)` : ""} assembled into one DS Table${skeleton ? ` (its ${loadingRows.length} row${loadingRows.length === 1 ? "" : "s"} of loading cells as one ${SKELETON_ROWS})` : ""} (MW8-17.3)`,
1181
1387
  );
1182
- ctx.imports.push(...imports, `import { Table, TableBody, TableHeader, TableRow${skeleton ? `, ${SKELETON_ROWS}` : ""} } from "${module}";`);
1388
+ ctx.imports.push(...imports, `import { Table, TableBody, TableCell, TableHeader, TableRow${skeleton ? `, ${SKELETON_ROWS}` : ""} } from "${module}";`);
1183
1389
  const { depth } = ctx;
1184
1390
  // A cell the generator wraps has no template to say its density, so it takes the one
1185
1391
  // its row's template cells declare, or the table's: a row is one height in Figma.
@@ -1220,6 +1426,45 @@ function tableOf(node, ctx) {
1220
1426
  const cellProps = props.some((p) => p.length) ? ` cellProps={[${props.map((p) => (p.length ? `{ ${p.join(", ")} }` : "{}")).join(", ")}]}` : "";
1221
1427
  return indent(`<${SKELETON_ROWS} columns={${columnCount}} rows={${loadingRows.length}}${cellProps} />`, depth + 2);
1222
1428
  };
1429
+ // The body's rows are the page's records, never Figma's sample: one row, drawn as the
1430
+ // first body row draws its cells, mapped over a `rows` prop, each column a ReactNode named
1431
+ // by its header (NODII-DEV-CLI-82). Rows that differ in their cells, or a row the generator
1432
+ // couldn't recognise, stay as drawn.
1433
+ const dataRows = parsed.filter((p) => p.kind === "body");
1434
+ const liftable = !skeleton && dataRows.length > 0 && dataRows.every((p) => !p.unrecognised && !p.framesOnly && p.cells.length === dataRows[0].cells.length) && (!headRow || headRow.cells.length === dataRows[0].cells.length);
1435
+ const liftedRows = () => {
1436
+ const keys = [];
1437
+ const first = dataRows[0];
1438
+ first.cells.forEach((_, i) => {
1439
+ const head = headRow?.cells[i];
1440
+ const text = head?.code ? (/\{"((?:[^"\\\n]|\\.)*)"\}/.exec(head.code)?.[1] ?? /\blabel="([^"]*)"/.exec(head.code)?.[1] ?? "") : "";
1441
+ let key = /[A-Za-z0-9]/.test(text) ? camelName(text) : `column${i + 1}`;
1442
+ while (keys.includes(key) || key === "id") key = `${key}${i + 1}`;
1443
+ keys.push(key);
1444
+ });
1445
+ const rowsName = mark(ctx, scopeName(node), "rows");
1446
+ ctx.note(ctx.path, LIFTED, `${dataRows.length} body row${dataRows.length === 1 ? "" : "s"} lifted as data: rows of { id, ${keys.join(", ")} } (NODII-DEV-CLI-82)`);
1447
+ const cells = first.cells.map((c, i) => {
1448
+ const w = columnWidth(c.cell);
1449
+ let open = `<TableCell${wrapperAttrs(w, first.row)}>`;
1450
+ let close = "</TableCell>";
1451
+ if (c.code && !c.held) {
1452
+ const own = withWidth(emitNode(c.cell, { ...ctx, depth: 0, parent: null, path: `${ctx.path} › ${first.row.name}`, root: false, bare: true, inTable: true, scopes: null, note: () => {} }), w).trim();
1453
+ const end = openTagEnd(own);
1454
+ const tag = /^<([A-Za-z]+)/.exec(own)[1];
1455
+ open = own.slice(0, end + 1).replace(/\s*\/>$/, ">");
1456
+ close = `</${tag}>`;
1457
+ }
1458
+ return indent(`${open}{row.${keys[i]}}${close}`, depth + 4);
1459
+ });
1460
+ return [
1461
+ indent(`{${rowsName}.map((row) => (`, depth + 2),
1462
+ indent("<TableRow key={row.id}>", depth + 3),
1463
+ ...cells,
1464
+ indent("</TableRow>", depth + 3),
1465
+ indent("))}", depth + 2),
1466
+ ];
1467
+ };
1223
1468
  const section = (kind, tag) => {
1224
1469
  const list = parsed.filter((p) => p.kind === kind);
1225
1470
  if (!list.length) return [];
@@ -1227,6 +1472,8 @@ function tableOf(node, ctx) {
1227
1472
  indent(`<${tag}>`, depth + 1),
1228
1473
  ...(kind === "body" && skeleton
1229
1474
  ? [skeletonRows()]
1475
+ : kind === "body" && liftable
1476
+ ? liftedRows()
1230
1477
  : list.flatMap((p) => (p.unrecognised ? [indent(comment(p.unrecognised), depth + 2)] : [indent("<TableRow>", depth + 2), ...p.cells.map((c) => cellCode(c, p.row, depth + 3)), indent("</TableRow>", depth + 2)]))),
1231
1478
  indent(`</${tag}>`, depth + 1),
1232
1479
  ];
@@ -1265,7 +1512,7 @@ export function unmappedMarkdown(files) {
1265
1512
  const lines = [
1266
1513
  "# Surface layers with no Code Connect mapping (U08-14)",
1267
1514
  "",
1268
- "Generated by `nodii-dev surface generate --report`. Kinds: `instance` (a library instance the generator cannot emit through a template), `text` (text missing a DS text style or colour role, or text in a part that should own it as a property), `frame` (a frame that paints its own fill, stroke, radius or effect: only its layout is generated), `table` (a Table part outside any table the generator recognises), `layout` (a frame or slot with no auto layout), `shape` (a rectangle, ellipse or vector: marked, not drawn), `token` (a text colour that matches no colour v2 role: left out), `bound-text` (text bound to a DS text style and colour role, with no Code Connect mapping: listed, not counted against a Surface being clean), `assembled` (rows of Table parts assembled into one DS Table, or sibling Tabs gathered into one Tab strip, MW8-17.3: listed, not counted).",
1515
+ "Generated by `nodii-dev surface generate --report`. Kinds: `instance` (a library instance the generator cannot emit through a template), `text` (text missing a DS text style or colour role, or text in a part that should own it as a property), `frame` (a frame that paints its own fill, stroke, radius or effect: only its layout is generated), `table` (a Table part outside any table the generator recognises), `layout` (a frame or slot with no auto layout), `shape` (a rectangle, ellipse or vector: marked, not drawn), `token` (a text colour that matches no colour v2 role: left out), `bound-text` (text bound to a DS text style and colour role, with no Code Connect mapping: listed, not counted against a Surface being clean), `assembled` (rows of Table parts assembled into one DS Table, or sibling Tabs gathered into one Tab strip, MW8-17.3: listed, not counted), `lifted` (a record's values, a table's body rows, a run of Description Lists or a data slot taken out of Figma's sample into the page's props, NODII-DEV-CLI-82/-83: listed, not counted).",
1269
1516
  "",
1270
1517
  ];
1271
1518
  for (const [fileKey, file] of Object.entries(files)) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.124",
3
+ "version": "0.6.126",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {