@nodii/dev 0.6.144 → 0.6.146

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/core.js CHANGED
@@ -4,7 +4,7 @@ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
4
  import { homedir, platform } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
 
7
- export const VERSION = "0.6.144";
7
+ export const VERSION = "0.6.146";
8
8
  export const configPath = () =>
9
9
  process.env.NODII_DEV_CONFIG_PATH ??
10
10
  join(homedir(), ".config/nodii-dev/config.json");
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 = 16;
35
+ export const GENERATOR_FORMAT = 17;
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). */
@@ -496,7 +496,15 @@ export function loadDesignSystem(root, { exec = execFileSync, docs } = {}) {
496
496
  const colours = colourCatalog.map((role) => ({ name: role.name, cls: role.name.replace(/\//g, "-"), light: String(role.light ?? "").toLowerCase(), scopes: role.scopes ?? [] }));
497
497
  const edges = existsSync(join(root, TYPE_EDGES_CATALOG)) ? readJson(join(root, TYPE_EDGES_CATALOG)) : {};
498
498
  const textStyles = new Map((edges.type ?? []).filter((t) => t.figma?.style).map((t) => [t.figma.style, t.utility]));
499
- return { dsFileKey, renderer, byKey, colours, textStyles };
499
+ // Each component's optional props, from its templates' `metadata.optionalProps` (DESIGN-SYSTEM-507).
500
+ const optionalProps = new Map();
501
+ for (const doc of Array.isArray(parsed) ? parsed : []) {
502
+ const listed = optionalPropsOf(doc);
503
+ if (!doc.component || !listed.size) continue;
504
+ const set = optionalProps.get(doc.component) ?? optionalProps.set(doc.component, new Set()).get(doc.component);
505
+ for (const name of listed) set.add(name);
506
+ }
507
+ return { dsFileKey, renderer, byKey, colours, textStyles, optionalProps };
500
508
  }
501
509
 
502
510
  /** `figma connect parse`, the repository's own Code Connect compile, into memory. */
@@ -532,13 +540,15 @@ export function emitSurface(tree, row, ds) {
532
540
  const layers = new Map();
533
541
  // Each list's columns by name, across views (listScope).
534
542
  const shapes = new Map();
543
+ // The marked identifiers a template lists as optional, and the ones it doesn't (DESIGN-SYSTEM-507).
544
+ const optionals = { optional: new Set(), required: new Set() };
535
545
  const views = tree.variants.map((variant) => {
536
546
  let state = variant.state;
537
547
  while (used.has(state)) state += "-x";
538
548
  used.add(state);
539
549
  const fn = `${pascal(state)}View`;
540
550
  const note = (path, kind, detail) => unmapped.push({ variant: variant.name, path, kind, detail });
541
- const emitted = emitNode(pageBody(variant, row), { depth: 2, parent: null, path: variant.name, row, ds, imports, note, root: true, scopes, layers, layer: "", state, lists: new Map(), shapes, handlers: new Map() }) ?? "";
551
+ const emitted = emitNode(pageBody(variant, row), { depth: 2, parent: null, path: variant.name, row, ds, imports, note, root: true, scopes, layers, layer: "", state, lists: new Map(), shapes, handlers: new Map(), shown: new Map(), optionals }) ?? "";
542
552
  // A view the generator can't lay out is no page at all: generation fails rather than ship
543
553
  // an empty view (NODII-DEV-CLI-81).
544
554
  if (emitted.trimStart().startsWith("{/*")) {
@@ -549,8 +559,15 @@ export function emitSurface(tree, row, ds) {
549
559
  const component = `${pascal(row.id)}Surface`;
550
560
  const stateType = `${component}State`;
551
561
  const propsType = `${component}Props`;
552
- resolveScopes(views, scopes, layers);
562
+ const named = resolveScopes(views, scopes, layers);
553
563
  const data = dataProps(views, propsType);
564
+ // A prop is optional when every template that draws it lists it in `metadata.optionalProps`.
565
+ const optionalNames = new Map();
566
+ for (const [token, name] of named) {
567
+ if (optionals.optional.has(token)) optionalNames.set(name, optionalNames.get(name) ?? true);
568
+ else if (optionals.required.has(token)) optionalNames.set(name, false);
569
+ }
570
+ for (const [name, optional] of optionalNames) if (optional && data.has(name)) data.get(name).optional = true;
554
571
  const reactTypes = [data.size && "ComponentProps", [...data.values()].some((d) => /\bReactNode\b/.test(propType(d))) && "ReactNode"].filter(Boolean);
555
572
  const drawn = [...data.values()].some((d) => [...d.attrs.values(), ...[...d.members.values()].flatMap((refs) => [...refs.values()])].some((r) => r.keys));
556
573
  const header = [
@@ -1095,27 +1112,98 @@ function nameHandlers(code, node, ctx, path, scope) {
1095
1112
  const GLYPH_WORDS = [[/^[‹«←⟨]+$/, "Previous"], [/^[›»→⟩]+$/, "Next"], [/^[↑]+$/, "Up"], [/^[↓]+$/, "Down"]];
1096
1113
 
1097
1114
  /**
1098
- * The prop that hides a button the page shows only sometimes (a permission, a
1099
- * state): `show<what it does>`, the words and the place of its own handler
1100
- * (`onStateEstablishmentSizeClick` → `showStateEstablishmentSize`), so two
1101
- * buttons never share one (hub-478). Optional: a page that passes nothing
1102
- * shows the button. Null for a part that is not a button, for a probe, and for
1103
- * a button a table row or another part's slot holds: a row's actions are the
1104
- * row's, and an Alert's action hides with its Alert.
1115
+ * When a part the page shows only sometimes (a permission, data being present,
1116
+ * a state) is drawn (hub-478), or null when it always is. A page that passes
1117
+ * nothing still draws it:
1118
+ * - a button, an Alert, a badge or the pager: `show<X>?: boolean`. A button's
1119
+ * X is its own handler's (`onStateEstablishmentSizeClick` →
1120
+ * `showStateEstablishmentSize`); the others' is their title or label, in at
1121
+ * most five words, with the place a button's handler would take, so two parts
1122
+ * never share one;
1123
+ * - a record's lone description row: its value is non-null, so a page passes
1124
+ * null for a field the record leaves out.
1125
+ * Null for a probe, and for a part a table row or another part's slot holds: a
1126
+ * row's parts are the row's, and an Alert's action hides with its Alert.
1127
+ * `code` is the part's code with its identifiers marked.
1105
1128
  */
1106
1129
  const SHOWN_TAGS = new Set(["Button", "IconButton", "DecisionButton"]);
1107
- function showFlag(code, node, ctx, path) {
1130
+ const FLAGGED_TAGS = new Set(["Alert", "Badge", "StatusPill", "Chip", "Pagination", "CursorPagination"]);
1131
+ const LONE_DESCRIPTION = /^<DescriptionList\b[^>]*>\s*<DescriptionItem\b[^>]*?\bvalue=\{(__s\d+_[a-z][A-Za-z0-9]*)\}[^>]*\/>\s*<\/DescriptionList>$/;
1132
+ function showCondition(code, node, ctx, path) {
1108
1133
  if (!ctx.scopes || ctx.tabProbe || ctx.inTable || ctx.inSlot) return null;
1109
1134
  const tag = /^<([A-Za-z]+)/.exec(code)?.[1];
1110
- if (!SHOWN_TAGS.has(tag)) return null;
1135
+ const lone = LONE_DESCRIPTION.exec(code.trim());
1136
+ if (lone) return `${lone[1]} != null`;
1137
+ if (!SHOWN_TAGS.has(tag) && !FLAGGED_TAGS.has(tag)) return null;
1111
1138
  const end = openTagEnd(code);
1112
1139
  const attrs = code.slice(tag.length + 1, end);
1113
- const own = new RegExp(String.raw`\b${HANDLER_ATTR[tag]}=\{(__s\d+)_on([A-Z]\w*)Click\}`).exec(attrs);
1114
- if (own) return `${own[1]}_show${own[2]}`;
1115
- // A template that draws no handler: the words and place nameHandlers would give it.
1116
- const label = handlerLabel(tag, attrs, code.slice(end), node) ?? scopeName(node, code, ctx);
1117
- const { scope, name } = handlerScope(node, ctx, path, null, label, 0);
1118
- return mark(ctx, scope, name.replace(/^on(\w+)Click$/, "show$1"));
1140
+ const own = SHOWN_TAGS.has(tag) && new RegExp(String.raw`\b${HANDLER_ATTR[tag]}=\{(__s\d+)_on([A-Z]\w*)Click\}`).exec(attrs);
1141
+ if (own) return `${own[1]}_show${own[2]} !== false`;
1142
+ // A button whose template draws no handler takes the words and place nameHandlers would
1143
+ // give it; any other part, the title or label it draws as copy. A label lifted as the
1144
+ // record's (a status Badge's "Processed") is Figma's sample, never a name (hub-468): the
1145
+ // part is named by its kind. Numbered apart from the handlers.
1146
+ const props = node.instance?.props ?? {};
1147
+ const copy = [props.title, props.Title, props.label, props.Label].find((v) => typeof v === "string" && v.trim() && code.includes(v));
1148
+ const label = (SHOWN_TAGS.has(tag) ? handlerLabel(tag, attrs, code.slice(end), node) : handlerWords(copy)) ?? camelName(tag);
1149
+ const { scope, name } = handlerScope(node, { ...ctx, handlers: ctx.shown }, path, null, label, 0);
1150
+ return `${mark(ctx, scope, name.replace(/^on(\w+)Click$/, "show$1"))} !== false`;
1151
+ }
1152
+
1153
+ /**
1154
+ * What a template draws inside one part that the page may still hide (hub-478),
1155
+ * in its marked code:
1156
+ * - an Alert's AlertAction: shown while its button's `show<X>` allows, the
1157
+ * whole AlertAction, so an Alert never keeps an empty one;
1158
+ * - a lone Tab's one trigger (the template's own strip): gated by the strip's
1159
+ * `visibleTabs`, its value its label (`Positions` → `positions`), as a run's
1160
+ * are (tabStrip).
1161
+ */
1162
+ function hideable(code) {
1163
+ let out = code.replace(/<AlertAction>([\s\S]*?)<\/AlertAction>/g, (block, inner) => {
1164
+ const flagOf = (part) => {
1165
+ const own = /\bonClick=\{(__s\d+)_on([A-Z]\w*)Click\}/.exec(part);
1166
+ return own ? `${own[1]}_show${own[2]}` : null;
1167
+ };
1168
+ const buttons = buttonsIn(inner);
1169
+ if (buttons.length <= 1) {
1170
+ const flag = flagOf(inner);
1171
+ return flag ? `{${flag} !== false && (${block})}` : block;
1172
+ }
1173
+ // Two or more actions: each its own, inside the one AlertAction.
1174
+ let held = inner;
1175
+ for (const b of buttons.reverse()) {
1176
+ const flag = flagOf(b.code);
1177
+ if (flag) held = `${held.slice(0, b.at)}{${flag} !== false && (${b.code})}${held.slice(b.at + b.code.length)}`;
1178
+ }
1179
+ return `<AlertAction>${held}</AlertAction>`;
1180
+ });
1181
+ const strip = /<Tabs panelless value=\{(__s\d+)_tab\}/.exec(out);
1182
+ const triggers = out.match(/<TabsTrigger\b/g) ?? [];
1183
+ if (strip && triggers.length === 1) {
1184
+ out = out.replace(/^([ \t]*)(<TabsTrigger\b[\s\S]*?<\/TabsTrigger>)/m, (_, pad, trigger) => {
1185
+ const label = /\{("(?:[^"\\\n]|\\.)*")\}/.exec(trigger);
1186
+ const value = (label && slug(JSON.parse(label[1]))) || "tab";
1187
+ const body = trigger.replace(/\bvalue="tab"/, `value="${value}"`).split("\n").map((line, i) => (i === 0 ? `${pad} ${line}` : line ? ` ${line}` : line)).join("\n");
1188
+ return `${pad}{(${strip[1]}_visibleTabs?.includes(${JSON.stringify(value)}) ?? true) && (\n${body}\n${pad})}`;
1189
+ });
1190
+ }
1191
+ return out;
1192
+ }
1193
+
1194
+ /** Each Button or Icon Button element in `code`: [{ at, code }], its end found past braces (`icon={<X />}`). */
1195
+ function buttonsIn(code) {
1196
+ const found = [];
1197
+ for (const m of code.matchAll(/<(Button|IconButton)(?=[\s/>])/g)) {
1198
+ if (found.some((b) => m.index < b.at + b.code.length)) continue;
1199
+ // openTagEnd is the opening tag's `>`.
1200
+ const gt = m.index + openTagEnd(code.slice(m.index));
1201
+ const selfClosing = /\/\s*$/.test(code.slice(m.index, gt));
1202
+ const close = selfClosing ? gt : code.indexOf(`</${m[1]}>`, gt);
1203
+ if (close === -1) continue;
1204
+ found.push({ at: m.index, code: code.slice(m.index, selfClosing ? gt + 1 : close + m[1].length + 3) });
1205
+ }
1206
+ return found;
1119
1207
  }
1120
1208
 
1121
1209
  /** `drawn` (indented one deeper than `depth`) drawn only while `condition` holds. */
@@ -1216,6 +1304,18 @@ function titleBefore(target, chain) {
1216
1304
  return null;
1217
1305
  }
1218
1306
 
1307
+ /**
1308
+ * The identifiers a template lists as optional (`metadata: { optionalProps: ["type", "error"] }`):
1309
+ * the props a page need not pass, so a page already adopted still typechecks when a template
1310
+ * gains one (DESIGN-SYSTEM-507). Read from the template's own source; empty when it lists none.
1311
+ */
1312
+ function optionalPropsOf(template) {
1313
+ // `figma connect parse` keeps a template's metadata on its doc; its source is the fallback.
1314
+ if (Array.isArray(template?.metadata?.optionalProps)) return new Set(template.metadata.optionalProps.filter((n) => typeof n === "string"));
1315
+ const list = /\boptionalProps\s*:\s*\[([^\]]*)\]/.exec(template?.template ?? "")?.[1];
1316
+ return new Set(list ? [...list.matchAll(/["'`]([A-Za-z_$][\w$]*)["'`]/g)].map((m) => m[1]) : []);
1317
+ }
1318
+
1219
1319
  /** A Checkbox or Switch: on or off is the page's, never Figma's sample (DESIGN-SYSTEM-508, hub-468). */
1220
1320
  const TOGGLE = /^<(?:Checkbox|Switch)\b/;
1221
1321
 
@@ -1443,6 +1543,7 @@ function resolveScopes(views, scopes, layers = new Map()) {
1443
1543
  });
1444
1544
  }
1445
1545
  for (const view of views) view.body = view.body.replace(marked, (token) => named.get(token));
1546
+ return named;
1446
1547
  }
1447
1548
 
1448
1549
  /** `scope` then `name` in camelCase, a word they share at the join said once (`recordSwitcherScope` + `ScopeValue`). */
@@ -1941,16 +2042,33 @@ function emitNode(node, ctx) {
1941
2042
  const scope = control ? fieldScope(node, ctx, own) : toggle ? camelName(toggle) : scopeName(node, own, ctx);
1942
2043
  own = nameHandlers(own, node, ctx, path, scope);
1943
2044
  own = controlHalfControlled(liftRecordData(own, node, ctx, path, scope));
1944
- const code = ctx.scopes ? scopeIdentifiers(own, scope, ctx.scopes, ctx.layer) : own;
2045
+ let code = ctx.scopes ? scopeIdentifiers(own, scope, ctx.scopes, ctx.layer) : own;
2046
+ if (ctx.optionals && ctx.scopes) {
2047
+ // Each identifier is its drawing tag's: the outer template's own list, or, for a part it
2048
+ // draws through executeTemplate (a Field's Input), that part's template's (DESIGN-SYSTEM-507).
2049
+ const outer = optionalPropsOf(rendered.template);
2050
+ const outerTag = /^<([A-Z][\w.]*)/.exec(own)?.[1];
2051
+ const mine = new Set([...own.matchAll(/__s\d+_[a-z][A-Za-z0-9]*/g)].map((m) => m[0]));
2052
+ for (const m of code.matchAll(/__s\d+_([a-z][A-Za-z0-9]*)/g)) {
2053
+ if (mine.has(m[0])) continue;
2054
+ // From before the `{` that holds it (`type={…}`), so that brace isn't counted.
2055
+ const start = code[m.index - 1] === "{" ? openingTag(code, m.index - 1) : null;
2056
+ const tag = start === null ? outerTag : /^<([A-Z][\w.]*)/.exec(code.slice(start))?.[1];
2057
+ const listed = tag && tag !== outerTag ? (ds.optionalProps?.get(tag) ?? new Set()) : outer;
2058
+ (listed.has(m[1]) ? ctx.optionals.optional : ctx.optionals.required).add(m[0]);
2059
+ }
2060
+ }
2061
+ // What the page may still hide inside this part, after the optional props are read (hub-478).
2062
+ if (ctx.scopes && !ctx.tabProbe) code = hideable(code);
1945
2063
  // A Table part is valid only inside the DS Table. One the generator could not assemble
1946
2064
  // into a Table stays reported, never passed off as mapped (MW8-17.3).
1947
2065
  const tag = /^<([A-Za-z]+)/.exec(code)?.[1];
1948
2066
  if (!ctx.inTable && (tablePart(tag) || tag === SKELETON_ROWS)) note(path, "table", `${describe(node)} is a Table part outside any table the generator recognises`);
1949
- const flag = showFlag(own, node, ctx, path);
1950
- const at = flag ? depth + 1 : depth;
2067
+ const shown = showCondition(code, node, ctx, path);
2068
+ const at = shown ? depth + 1 : depth;
1951
2069
  // Layout around a DS component is the page's; the component itself takes no className (U07-19).
1952
2070
  const drawn = !sizing.length ? indent(code, at) : [indent(`<div className="${cls(["flex", "flex-col", ...sizing])}">`, at), indent(code, at + 1), indent("</div>", at)].join("\n");
1953
- return flag ? shownWhen(`${flag} !== false`, drawn, depth) : drawn;
2071
+ return shown ? shownWhen(shown, drawn, depth) : drawn;
1954
2072
  }
1955
2073
 
1956
2074
  if (node.type === "TEXT") {
@@ -2004,10 +2122,37 @@ function emitNode(node, ctx) {
2004
2122
  return indent(comment(`unmapped: ${node.type.toLowerCase()} ${JSON.stringify(node.name)} has no auto layout`), depth);
2005
2123
  }
2006
2124
  const classes = cls([...sizeClasses(node, parent, root), ...layoutClasses(node), node.clips ? "overflow-hidden" : null]);
2125
+ const shown = root ? null : sectionCondition(node, ctx, path);
2007
2126
  const kids = emitChildren(node.children ?? [], child, { ...ctx, depth: depth + 1, parent: node, grand: parent, path, root: false, chain });
2008
2127
  const open = `<div${classes ? ` className="${classes}"` : ""}`;
2009
- if (!kids.length) return indent(`${open} />`, depth);
2010
- return [indent(`${open}>`, depth), ...kids, indent("</div>", depth)].join("\n");
2128
+ const drawn = !kids.length ? indent(`${open} />`, depth) : [indent(`${open}>`, depth), ...kids, indent("</div>", depth)].join("\n");
2129
+ return shown ? shownWhen(shown, indent(drawn, 1), depth) : drawn;
2130
+ }
2131
+
2132
+ /**
2133
+ * When a section, card, rail or row the page shows only sometimes is drawn
2134
+ * (hub-478): a frame the Surfaces name as a place, `<Kind> · <Name>`
2135
+ * ("Card · Peer invitation", "Rail · Your decision", "Fact · Close note"),
2136
+ * takes `show<Name>?: boolean`, its name's words with the place a button's
2137
+ * handler would take, numbered apart from the handlers. So does a frame that
2138
+ * opens with its own heading ("Peer-feedback invitations" over its rows),
2139
+ * named by the heading; a heading with a figure is the record's, never a name.
2140
+ * A page that passes nothing draws it. Null for a frame of a table's own
2141
+ * anatomy, one a table row or another part's slot holds, and a probe.
2142
+ */
2143
+ const PLACE_FRAME = /^\s*([A-Za-z][A-Za-z ]*?)\s*·\s*(.*[A-Za-z].*)$/;
2144
+ const TABLE_ANATOMY = new Set(["table", "cell"]);
2145
+ function sectionCondition(node, ctx, path) {
2146
+ if (!ctx.scopes || ctx.tabProbe || ctx.inTable || ctx.inSlot || node.instance) return null;
2147
+ const m = PLACE_FRAME.exec(node.name ?? "");
2148
+ // A head of only text (a title and its subtitle) is not the section: its body sits beside it.
2149
+ const [first, ...rest] = (node.children ?? []).filter((c) => c.visible !== false);
2150
+ const body = rest.some((c) => c.type !== "TEXT");
2151
+ const heading = body && first?.type === "TEXT" && HEADING_STYLE.test(first.textStyle ?? "") && !RECORD_TEXT(first.text ?? "") ? first.text : null;
2152
+ const words = m ? (TABLE_ANATOMY.has(m[1].trim().toLowerCase()) ? null : handlerWords(m[2])) : handlerWords(heading);
2153
+ if (!words) return null;
2154
+ const { scope, name } = handlerScope(node, { ...ctx, handlers: ctx.shown }, path, null, words, 0);
2155
+ return `${mark(ctx, scope, name.replace(/^on(\w+)Click$/, "show$1"))} !== false`;
2011
2156
  }
2012
2157
 
2013
2158
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.144",
3
+ "version": "0.6.146",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {