@nodii/dev 0.6.196 → 0.6.198

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, lstat, mkdir, readFile, rename, rm, writeFile } from "node:fs/pr
4
4
  import { homedir, platform } from "node:os";
5
5
  import { basename, dirname, join } from "node:path";
6
6
 
7
- export const VERSION = "0.6.196";
7
+ export const VERSION = "0.6.198";
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
@@ -34,7 +34,7 @@ import { MIN_FIGMA_INTERVAL_MS, figmaRest } from "./figma-rest.js";
34
34
  import { createRenderer } from "./vendor/render-templates.mjs";
35
35
 
36
36
  /** Bumped whenever the emitted code changes shape for the same inputs. */
37
- export const GENERATOR_FORMAT = 49;
37
+ export const GENERATOR_FORMAT = 52;
38
38
  /**
39
39
  * DS parts that are an item of their parent's own list or grid, so they take no sizing
40
40
  * wrapper: a Detail Section / Row's facts are the section grid's cells, a Right Pane / Row
@@ -644,13 +644,15 @@ export function emitSurface(tree, row, ds) {
644
644
  const shapes = new Map();
645
645
  // The marked identifiers a template lists as optional, and the ones it doesn't (DESIGN-SYSTEM-507).
646
646
  const optionals = { optional: new Set(), required: new Set() };
647
+ // Each list the generator assembles from sibling parts (alertRun): its members a page may leave out, and any narrowed type.
648
+ const items = new Map();
647
649
  const views = graftAbsentSlots(tree.variants).map((variant) => {
648
650
  let state = variant.state;
649
651
  while (used.has(state)) state += "-x";
650
652
  used.add(state);
651
653
  const fn = `${pascal(state)}View`;
652
654
  const note = (path, kind, detail) => unmapped.push({ variant: variant.name, path, kind, detail });
653
- 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 }) ?? "";
655
+ 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, items }) ?? "";
654
656
  // A view the generator can't lay out is no page at all: generation fails rather than ship
655
657
  // an empty view (NODII-DEV-CLI-81).
656
658
  if (emitted.trimStart().startsWith("{/*")) {
@@ -675,6 +677,12 @@ export function emitSurface(tree, row, ds) {
675
677
  else if (optionals.required.has(token)) optionalNames.set(name, false);
676
678
  }
677
679
  for (const [name, optional] of optionalNames) if (optional && data.has(name)) data.get(name).optional = true;
680
+ for (const [token, item] of items) {
681
+ const d = data.get(named.get(token));
682
+ if (!d) continue;
683
+ for (const k of item.optional) d.members.get(k)?.set(OPTIONAL_MEMBER, { optional: true });
684
+ for (const [k, raw] of item.narrow) d.members.get(k)?.set(NARROW_MEMBER, { raw });
685
+ }
678
686
  const reactTypes = [data.size && "ComponentProps", [...data.values()].some((d) => /\bReactNode\b/.test(propType(d))) && "ReactNode"].filter(Boolean);
679
687
  const drawn = [...data.values()].some((d) => [...d.attrs.values(), ...[...d.members.values()].flatMap((refs) => [...refs.values()])].some((r) => r.keys));
680
688
  const header = [
@@ -1320,6 +1328,15 @@ function liftRecordData(code, node, ctx, path, scope = scopeName(node)) {
1320
1328
  }
1321
1329
  return next;
1322
1330
  });
1331
+ // A Chart With Range's series are the page's data, each one's key and label with its points
1332
+ // (generator plan, section a): the template draws two series under Figma's sample labels
1333
+ // ("Email", "SMS"), so a report with three providers showed them under the wrong legend.
1334
+ // The whole array is one prop, typed by the DS's own `series` (NODII-DEV-CLI-222).
1335
+ out = rewriteTags(out, "ChartWithRange", (attrs) => {
1336
+ const at = topLevelAttr(attrs, "series");
1337
+ if (!at) return attrs;
1338
+ return `${attrs.slice(0, at.from)}series={${lift(scope, "series")}}${attrs.slice(at.to)}`;
1339
+ });
1323
1340
  out = rewriteTags(out, "PageSizeSelect", (attrs) => attrs.replace(/\bvalue=\{(?:\d+|Number\("(?:[^"\\\n]|\\.)*"\))\}/, () => `value={${lift(scope, "pageSize")}}`));
1324
1341
  out = rewriteTags(out, "CopyField", (attrs) => {
1325
1342
  const value = new RegExp(String.raw`\bvalue=${LITERAL}`).exec(attrs);
@@ -1687,7 +1704,27 @@ function textNextTo(node, ctx) {
1687
1704
  }
1688
1705
  return null;
1689
1706
  };
1690
- return beside(ctx.parent, node) ?? (ctx.grand ? beside(ctx.grand, ctx.parent) : null);
1707
+ return beside(ctx.parent, node) ?? (ctx.grand ? beside(ctx.grand, ctx.parent) : null) ?? fieldGroupLabel(ctx.slotOwner);
1708
+ }
1709
+
1710
+ /**
1711
+ * A FieldGroup labels its group, never its controls. A box or switch drawn
1712
+ * alone in its slot, with no text beside it, is named by the group's label:
1713
+ * else it has no accessible name (hub-629). With several toggles
1714
+ * each needs its own text, so none borrows the group's.
1715
+ */
1716
+ function fieldGroupLabel(owner) {
1717
+ if (owner?.instance?.set !== "FieldGroup") return null;
1718
+ const label = owner.instance.props?.label;
1719
+ if (typeof label !== "string" || !/[A-Za-z]/.test(label)) return null;
1720
+ let toggles = 0;
1721
+ const count = (n) => {
1722
+ if (!n || n.visible === false) return;
1723
+ if (n !== owner && (n.instance?.set === "Switch" || n.instance?.set === "Checkbox")) toggles += 1;
1724
+ for (const c of n.children ?? []) count(c);
1725
+ };
1726
+ count(owner);
1727
+ return toggles === 1 ? label : null;
1691
1728
  }
1692
1729
 
1693
1730
  /** The form controls the page owns: a value it passes and a change it hears (NODII-DEV-CLI-82, -83). */
@@ -1930,6 +1967,30 @@ function bareAttr(attrs, name) {
1930
1967
  return m ? m.index + m[1].length : null;
1931
1968
  }
1932
1969
 
1970
+ /**
1971
+ * Where an attribute `name={…}` stands in `attrs`, outside strings and other
1972
+ * attributes' braces: { from, to } over the whole `name={…}`, its braces balanced;
1973
+ * else null.
1974
+ */
1975
+ function topLevelAttr(attrs, name) {
1976
+ const flat = maskStrings(attrs);
1977
+ let depth = 0;
1978
+ for (let i = 0; i < flat.length; i++) {
1979
+ const c = flat[i];
1980
+ if (depth === 0 && flat.startsWith(`${name}={`, i) && (i === 0 || /\s/.test(flat[i - 1]))) {
1981
+ let d = 0;
1982
+ for (let j = i + name.length + 1; j < flat.length; j++) {
1983
+ if (flat[j] === "{") d++;
1984
+ else if (flat[j] === "}" && --d === 0) return { from: i, to: j + 1 };
1985
+ }
1986
+ return null;
1987
+ }
1988
+ if (c === "{") depth++;
1989
+ else if (c === "}") depth--;
1990
+ }
1991
+ return null;
1992
+ }
1993
+
1933
1994
  /** Tabs the page controls: its tab is a prop, and choosing one calls back (NODII-DEV-CLI-83). */
1934
1995
  const CONTROLLED_TABS = (value, onChange) => `<Tabs panelless value={${value}} onValueChange={${onChange}}>`;
1935
1996
 
@@ -2458,11 +2519,18 @@ function nestedType(body, at, key) {
2458
2519
  return null;
2459
2520
  }
2460
2521
 
2522
+ const OPTIONAL_MEMBER = "\u0000optional";
2523
+ const NARROW_MEMBER = "\u0000narrow";
2461
2524
  const propType = (d) => {
2462
2525
  // A value nested in an object prop is typed by its path from the DS prop (nestedType); `any` only when it has none.
2463
2526
  const nested = d.nested ? (d.untyped || !d.nestedTypes?.size ? ["any"] : [...d.nestedTypes]) : [];
2464
2527
  const parts = [...[...d.attrs.values()].map(drawnRef), ...(d.child ? ["ReactNode"] : []), ...nested];
2465
- const shape = `{ ${[...d.members.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([k, refs]) => `${k}: ${[...refs.values()].map(drawnRef).join(" & ")}`).join("; ")} }`;
2528
+ // A member a page may leave out is optional; a narrowed one is typed by its narrowing alone (alertRun).
2529
+ const field = ([k, refs]) => {
2530
+ const types = refs.has(NARROW_MEMBER) ? [refs.get(NARROW_MEMBER)] : [...refs].filter(([id]) => id !== OPTIONAL_MEMBER).map(([, r]) => r);
2531
+ return `${k}${refs.has(OPTIONAL_MEMBER) ? "?" : ""}: ${types.map(drawnRef).join(" & ")}`;
2532
+ };
2533
+ const shape = `{ ${[...d.members.entries()].sort(([a], [b]) => a.localeCompare(b)).map(field).join("; ")} }`;
2466
2534
  // A lifted list is an array of its items (NODII-DEV-CLI-82).
2467
2535
  if (d.list) parts.push(`Array<${shape}>`);
2468
2536
  else if (d.members.size) parts.push(shape);
@@ -2826,6 +2894,7 @@ function emitChildren(children, emitOne, ctx) {
2826
2894
  const flush = () => {
2827
2895
  if (run.length >= 2 && runKind === "tab") out.push(tabStrip(run, ctx));
2828
2896
  else if (run.length >= 2 && runKind === "step") out.push(...stepRun(run, emitOne, ctx));
2897
+ else if (run.length >= 2 && runKind === "alert") out.push(...alertRun(run, emitOne, ctx));
2829
2898
  else if (run.length >= 2) out.push(descriptionRun(run, ctx));
2830
2899
  else out.push(...run.map(emitOne).filter((x) => x !== null));
2831
2900
  run = [];
@@ -2835,7 +2904,7 @@ function emitChildren(children, emitOne, ctx) {
2835
2904
  if (c.visible === false) continue;
2836
2905
  // Description lists side by side are columns of the layout, each its own list; only a run
2837
2906
  // down a column is one list of items (hub-454).
2838
- const kind = tabOf(c, ctx) ? "tab" : stepOf(c, ctx) ? "step" : !across && descriptionOf(c, ctx) ? `dl${descriptionOf(c, ctx).open}` : null;
2907
+ const kind = alertOf(c) ? "alert" : tabOf(c, ctx) ? "tab" : stepOf(c, ctx) ? "step" : !across && descriptionOf(c, ctx) ? `dl${descriptionOf(c, ctx).open}` : null;
2839
2908
  if (kind && kind !== runKind) flush();
2840
2909
  if (kind) {
2841
2910
  run.push(c);
@@ -2901,6 +2970,165 @@ function stepRun(run, emitOne, ctx) {
2901
2970
  return [indent(["<Stepper", " steps={[", ...items, " ]}", ...attrs.map((a) => ` ${a}`), "/>"].join("\n"), ctx.depth)];
2902
2971
  }
2903
2972
 
2973
+ /** A DS Alert instance: a run of two or more siblings is the page's list of alerts (alertRun). */
2974
+ const ALERT_SET = "Alert";
2975
+ /** The DS Alert's tones (alert.tsx), each with its own leading-icon swap in Figma. */
2976
+ const ALERT_TONES = ["default", "info", "success", "warning", "destructive"];
2977
+ const alertOf = (node) => Boolean(node.instance?.remote) && node.instance.set === ALERT_SET && node.visible !== false;
2978
+
2979
+ /** An attribute as JSX, from its literal (tagAttributes): `variant="outline"`, a bare `disabled`, `count={2}`. */
2980
+ const literalAttr = (name, literal) => (literal === "true" ? name : literal.startsWith('"') ? `${name}=${literal}` : `${name}={${literal}}`);
2981
+
2982
+ /**
2983
+ * One Alert as its template draws it, read for what an item of a list of alerts holds:
2984
+ * its tone, its icon, whether it draws a description, and each action button's literal
2985
+ * attributes (at most two buttons, each with plain text). Null when the template draws
2986
+ * anything else (a body, an Icon Button, a button with an icon), so the run stays as drawn.
2987
+ * Emitted as a probe, with no scopes: nothing it names becomes a prop.
2988
+ */
2989
+ function drawnAlert(node, ctx) {
2990
+ const imports = [];
2991
+ const notes = [];
2992
+ const probe = { ...ctx, depth: 0, bare: true, inTable: false, scopes: null, imports, note: (...n) => notes.push(n) };
2993
+ const code = emitNode(node, probe)?.trim() ?? "";
2994
+ const open = /^<Alert(?: tone="([a-z]+)")?>/.exec(code);
2995
+ if (!open || !code.endsWith("</Alert>") || /<AlertBody\b/.test(code)) return null;
2996
+ let rest = code.slice(open[0].length, -"</Alert>".length);
2997
+ const take = (re) => {
2998
+ const m = re.exec(rest);
2999
+ if (m) rest = rest.slice(0, m.index) + rest.slice(m.index + m[0].length);
3000
+ return m;
3001
+ };
3002
+ const icon = take(/^\s*(<[A-Z][A-Za-z0-9]*(?: [a-z][\w-]*="[^"\n]*")* \/>)/)?.[1] ?? null;
3003
+ if (!take(/^\s*<AlertTitle>[^\n]*?<\/AlertTitle>/)) return null;
3004
+ const description = Boolean(take(/^\s*<AlertDescription>[^\n]*?<\/AlertDescription>/));
3005
+ const action = take(/^\s*<AlertAction>([\s\S]*)<\/AlertAction>/);
3006
+ if (rest.trim()) return null;
3007
+ const buttons = [];
3008
+ if (action) {
3009
+ const found = buttonsIn(action[1]);
3010
+ let left = action[1];
3011
+ for (const b of found) left = left.replace(b.code, "");
3012
+ if (!found.length || found.length > 2 || left.replace(/<>|<\/>/g, "").trim()) return null;
3013
+ for (const b of found) {
3014
+ if (!/^<Button[\s>]/.test(b.code)) return null;
3015
+ const attrs = tagAttributes(b.code, "<Button".length);
3016
+ if (!attrs || attrs.selfClosing) return null;
3017
+ const own = new Map();
3018
+ for (const name of attrs.names) {
3019
+ if (name === "onClick") continue;
3020
+ const literal = attrs.literals.get(name);
3021
+ if (literal === undefined || literal.includes("\\")) return null;
3022
+ own.set(name, literal);
3023
+ }
3024
+ const label = b.code.slice(openTagEnd(b.code) + 1, b.code.lastIndexOf("</Button>")).trim();
3025
+ if (!label || label.includes("<")) return null;
3026
+ buttons.push(own);
3027
+ }
3028
+ }
3029
+ return { tone: open[1] ?? "default", icon, description, buttons, imports, notes };
3030
+ }
3031
+
3032
+ /**
3033
+ * A run of two or more sibling Alerts is the page's list of alerts (NODII-DEV-CLI-222).
3034
+ * Each Alert drew Figma's sample as copy: its title, its description and its action
3035
+ * ("Payment overdue to A*** N*** (SMS) failed twice." on Notification Overview), so a live
3036
+ * page showed the designer's alerts, always four of them. The run is one prop, `alerts`
3037
+ * (named by its section, as a table's rows are; listScope), drawn with `.map`, each item
3038
+ * `{ id, tone, title, description?, actionLabel?, onAction?, secondaryActionLabel?,
3039
+ * onSecondaryAction? }` typed by the DS parts it reaches. The drawing stays the frame's:
3040
+ * the icon each tone takes, and a button attribute every drawn alert gives alike
3041
+ * (`size="small"`); one the alerts draw differently (`variant`) is the item's own
3042
+ * (`actionVariant`). Tones drawn alike stay literal; tones drawn apart are the item's, each
3043
+ * with the icon the Alert's own per-tone swap gives it (an item's tone is narrowed only to
3044
+ * the tones that have one). Alerts drawn with a body, an icon on some and not others, an
3045
+ * icon that is not its tone's swap, more than two actions, or other sizes stay as drawn. A
3046
+ * lone Alert stays as drawn.
3047
+ */
3048
+ function alertRun(run, emitOne, ctx) {
3049
+ const asDrawn = () => run.map(emitOne).filter((x) => x !== null);
3050
+ const alerts = run.map((node) => drawnAlert(node, ctx));
3051
+ if (alerts.some((a) => a === null)) return asDrawn();
3052
+ const sizing = run.map((node) => sizeClasses(node, ctx.parent, false));
3053
+ if (new Set(sizing.map((s) => s.join(" "))).size > 1) return asDrawn();
3054
+ if (new Set(alerts.map((a) => a.icon === null)).size > 1) return asDrawn();
3055
+ const drawnTones = [...new Set(alerts.map((a) => a.tone))].sort();
3056
+ const oneTone = drawnTones.length === 1;
3057
+ const iconed = alerts[0].icon !== null;
3058
+ // The icon each tone takes is the Alert's own per-tone swap: the first alert drawn in every
3059
+ // tone, so an item may take a tone the frame doesn't draw. A tone the template draws no icon
3060
+ // for (or doesn't draw) is left out, and the item's tone is narrowed to the tones it can take.
3061
+ const icons = new Map();
3062
+ if (iconed && !oneTone) {
3063
+ for (const tone of ALERT_TONES) {
3064
+ const probe = drawnAlert({ ...run[0], instance: { ...run[0].instance, props: { ...run[0].instance.props, tone } } }, ctx);
3065
+ if (probe?.tone !== tone || probe.icon === null) continue;
3066
+ icons.set(tone, probe.icon);
3067
+ ctx.imports.push(...probe.imports);
3068
+ }
3069
+ }
3070
+ for (const a of alerts) if (iconed && !oneTone && icons.get(a.tone) !== a.icon) return asDrawn();
3071
+ if (oneTone && new Set(alerts.map((a) => a.icon)).size > 1) return asDrawn();
3072
+ const tones = [...icons.keys()].sort();
3073
+ const optional = new Set();
3074
+ // Each action button by its place: the attributes every alert that draws it gives alike stay drawn.
3075
+ const actions = [0, 1].map((k) => alerts.map((a) => a.buttons[k]).filter(Boolean)).filter((drawn) => drawn.length);
3076
+ const prefixes = ["action", "secondaryAction"];
3077
+ const buttons = actions.map((drawn, k) => {
3078
+ const prefix = prefixes[k];
3079
+ const names = [...new Set(drawn.flatMap((b) => [...b.keys()]))];
3080
+ const attrs = names.map((name) => {
3081
+ const same = drawn.every((b) => b.get(name) === drawn[0].get(name));
3082
+ if (same) return literalAttr(name, drawn[0].get(name));
3083
+ const member = `${prefix}${cap(name)}`;
3084
+ optional.add(member);
3085
+ return `${name}={alert.${member}}`;
3086
+ });
3087
+ const label = `${prefix}Label`;
3088
+ const handler = `on${cap(prefix)}`;
3089
+ optional.add(label).add(handler);
3090
+ return { label, handler, open: `<Button${attrs.map((a) => ` ${a}`).join("")} onClick={alert.${handler}}>` };
3091
+ });
3092
+ // A description is optional in every Alert, drawn or not: one list keeps one shape in every view.
3093
+ optional.add("description");
3094
+ const shape = `alerts:${oneTone ? `${drawnTones[0]}=${alerts[0].icon}` : tones.map((t) => `${t}=${icons.get(t)}`).join(",")}:${buttons.map((b) => b.open).join(",")}`;
3095
+ const scope = listScope(run[0], ctx, "alerts", shape);
3096
+ // A list named by no heading is `alerts`, numbered (`alerts2`) when another list holds the name.
3097
+ const list = mark(ctx, scope, /^alerts\d*$/.test(scope) ? scope : "alerts", null);
3098
+ const iconLine = !iconed ? [] : oneTone ? [alerts[0].icon] : [`{{ ${tones.map((t) => `${t}: ${icons.get(t)}`).join(", ")} }[alert.tone]}`];
3099
+ const toneAttr = oneTone ? (drawnTones[0] === "default" ? "" : ` tone="${drawnTones[0]}"`) : " tone={alert.tone}";
3100
+ const buttonLines = (b) => [b.open, ` {alert.${b.label}}`, "</Button>"];
3101
+ const actionLines = !buttons.length
3102
+ ? []
3103
+ : [
3104
+ `{alert.${buttons[0].label} != null && (`,
3105
+ " <AlertAction>",
3106
+ ...buttonLines(buttons[0]).map((l) => ` ${l}`),
3107
+ ...(buttons[1] ? [` {alert.${buttons[1].label} != null && (`, ...buttonLines(buttons[1]).map((l) => ` ${l}`), " )}"] : []),
3108
+ " </AlertAction>",
3109
+ ")}",
3110
+ ];
3111
+ const body = [
3112
+ `<Alert${toneAttr}>`,
3113
+ ...iconLine.map((l) => ` ${l}`),
3114
+ " <AlertTitle>{alert.title}</AlertTitle>",
3115
+ " {alert.description != null && <AlertDescription>{alert.description}</AlertDescription>}",
3116
+ ...actionLines.map((l) => ` ${l}`),
3117
+ "</Alert>",
3118
+ ];
3119
+ const item = sizing[0].length ? [`<div key={alert.id} className="${cls(["flex", "flex-col", ...sizing[0]])}">`, ...body.map((l) => ` ${l}`), "</div>"] : [body[0].replace(/^<Alert/, "<Alert key={alert.id}"), ...body.slice(1)];
3120
+ for (const a of alerts) {
3121
+ ctx.imports.push(...a.imports);
3122
+ for (const n of a.notes) if (n[1] !== LIFTED) ctx.note(...n);
3123
+ }
3124
+ // An icon is looked up by its tone, so the item's tone is always one: never null or left out.
3125
+ const tone = 'NonNullable<ComponentProps<typeof Alert>["tone"]>';
3126
+ const narrow = !iconed || oneTone ? null : tones.length < ALERT_TONES.length ? `Extract<${tone}, ${tones.map((t) => JSON.stringify(t)).join(" | ")}>` : tone;
3127
+ ctx.items?.set(list, { optional, narrow: new Map(narrow ? [["tone", narrow]] : []) });
3128
+ ctx.note(ctx.path, LIFTED, `${run.length} sibling Alerts lifted as the page's list of alerts: Figma's sample titles, descriptions and actions are the page's (NODII-DEV-CLI-222)`);
3129
+ return [indent([`{${list}.map((alert) => (`, ...item.map((l) => ` ${l}`), "))}"].join("\n"), ctx.depth)];
3130
+ }
3131
+
2904
3132
  const LABEL_FOR = /<Label\b[^>]*?\bhtmlFor=\{([A-Za-z_$][\w$]*)\}/;
2905
3133
  const LABELLED_CONTROL = /<(?:Checkbox|Switch|RadioGroupItem|Textarea|Input|SelectField)(?=[\s/>])/;
2906
3134
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodii/dev",
3
- "version": "0.6.196",
3
+ "version": "0.6.198",
4
4
  "description": "Agent CLI for Nodii Dev, reached through the platform edge",
5
5
  "type": "module",
6
6
  "bin": {