@nodii/dev 0.6.72 → 0.6.74
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/README.md +150 -7
- package/dist/cli.js +84 -16
- package/dist/core.js +2 -2
- package/dist/design.js +46 -2
- package/dist/doctor.js +17 -7
- package/dist/figma.js +44 -0
- package/dist/flags.js +5 -1
- package/dist/freeze.js +12 -0
- package/dist/gather.js +51 -23
- package/dist/harness.js +8 -4
- package/dist/hooks.js +1 -25
- package/dist/lanes.js +74 -23
- package/dist/managed-hooks.js +60 -9
- package/dist/nudges.js +166 -2
- package/dist/receipt.js +365 -0
- package/dist/review.js +76 -4
- package/dist/safety.js +8 -1
- package/dist/session-kind.js +243 -0
- package/dist/setup.js +8 -6
- package/dist/surface.js +847 -0
- package/dist/vendor/render-templates.mjs +740 -0
- package/package.json +1 -1
package/dist/surface.js
ADDED
|
@@ -0,0 +1,847 @@
|
|
|
1
|
+
// `nodii-dev surface generate`: a Figma Surface → its product page's
|
|
2
|
+
// presentational code, mechanically, from Code Connect (MW8-17, MW2-37.1;
|
|
3
|
+
// DESIGN-SYSTEM-249).
|
|
4
|
+
//
|
|
5
|
+
// It runs in a design-system checkout and reads only that repository and
|
|
6
|
+
// Figma: the product-page catalog (packages/blocks/src/product-pages/
|
|
7
|
+
// catalog.ts) names each Surface by its published component-set key (MW8-20,
|
|
8
|
+
// never a node id); the Surface's frame tree is read from Figma's REST nodes
|
|
9
|
+
// API at a pinned file version and committed, trimmed, under
|
|
10
|
+
// docs/figma-ux-ds/figma/surface-trees/; every DS instance is emitted through
|
|
11
|
+
// its Code Connect template exactly as the template gives it (component,
|
|
12
|
+
// props, import), run by the design system's own template harness
|
|
13
|
+
// (./vendor/render-templates.mjs, vendored byte-for-byte); auto-layout becomes
|
|
14
|
+
// flex and grid; loose text takes the DS type utility and colour role; a frame
|
|
15
|
+
// keeps only its layout, and a shape or an instance with no template is a
|
|
16
|
+
// marked gap, never a look-alike (MW2-37.2). Every such layer is reported as
|
|
17
|
+
// having no Code Connect mapping (U08-14).
|
|
18
|
+
//
|
|
19
|
+
// The design system keeps no copy of this generator: its `surface-gen-equal`
|
|
20
|
+
// CI gate runs this same command with --check, which regenerates from the
|
|
21
|
+
// committed trees (no Figma call) and refuses any product page whose
|
|
22
|
+
// generated file differs.
|
|
23
|
+
//
|
|
24
|
+
// Figma reads (only with --fetch) are paced to one call per 8 s or slower;
|
|
25
|
+
// a 429 waits out Retry-After, or 30 s doubling when Figma sends none.
|
|
26
|
+
import { execFileSync } from "node:child_process";
|
|
27
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
28
|
+
import { tmpdir } from "node:os";
|
|
29
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
30
|
+
import { CliError } from "./core.js";
|
|
31
|
+
import { createRenderer } from "./vendor/render-templates.mjs";
|
|
32
|
+
|
|
33
|
+
/** Bumped whenever the emitted code changes shape for the same inputs. */
|
|
34
|
+
export const GENERATOR_FORMAT = 4;
|
|
35
|
+
export const TREE_DIR = "docs/figma-ux-ds/figma/surface-trees";
|
|
36
|
+
export const GENERATED_SUFFIX = ".surface.generated.tsx";
|
|
37
|
+
const CATALOG_PATH = "packages/blocks/src/product-pages/catalog.ts";
|
|
38
|
+
const DS_FILE_META = "infra/figma/figma-file.json";
|
|
39
|
+
const ONE_TO_ONE_SNAPSHOT = "docs/figma-ux-ds/figma/1to1/figma-file.snapshot.json";
|
|
40
|
+
const COLOUR_CATALOG = "packages/tokens/src/generated/colour-v2-catalog.json";
|
|
41
|
+
const TYPE_EDGES_CATALOG = "packages/tokens/src/generated/type-edges-v2-catalog.json";
|
|
42
|
+
const SURFACE_REFERENCE = "docs/figma-ux-ds/figma/surface-reference.json";
|
|
43
|
+
const FIGMA_API = "https://api.figma.com/v1";
|
|
44
|
+
export const MIN_FIGMA_INTERVAL_MS = 8_000;
|
|
45
|
+
const BACKOFF_429_MS = 30_000;
|
|
46
|
+
const SET_KEY = /^[0-9a-f]{40}$/;
|
|
47
|
+
|
|
48
|
+
export const SURFACE_USAGE =
|
|
49
|
+
"surface generate <componentSetKey|route> [--write] [--check] [--fetch] [--figma-version V] [--report FILE]\n" +
|
|
50
|
+
"surface generate --all [--module M] [--type page|dialog] [--write] [--check] [--fetch] [--report FILE]";
|
|
51
|
+
|
|
52
|
+
// ---------------------------------------------------------------------------
|
|
53
|
+
// Repository inputs
|
|
54
|
+
// ---------------------------------------------------------------------------
|
|
55
|
+
|
|
56
|
+
/** The design-system checkout this runs in: the nearest directory holding the product-page catalog. */
|
|
57
|
+
export function findRepoRoot(start = process.cwd()) {
|
|
58
|
+
for (let dir = resolve(start); ; dir = dirname(dir)) {
|
|
59
|
+
if (existsSync(join(dir, CATALOG_PATH)) && existsSync(join(dir, "figma.config.json"))) return dir;
|
|
60
|
+
if (dirname(dir) === dir)
|
|
61
|
+
throw new CliError("NOT_A_DESIGN_SYSTEM_CHECKOUT", `surface generate runs in a design-system checkout (no ${CATALOG_PATH} at or above ${start})`, 2);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const readJson = (path) => JSON.parse(readFileSync(path, "utf8"));
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The Node that loads the catalog. tsx's `--import` hook is a Node loader: when
|
|
69
|
+
* the launcher runs this CLI on Bun, `process.execPath` is bun, which cannot
|
|
70
|
+
* load it, so the catalog is read by the `node` on PATH instead.
|
|
71
|
+
*/
|
|
72
|
+
export const catalogNode = (runtime = process) => (runtime.versions?.bun ? "node" : runtime.execPath);
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The catalog rows that name a Surface, read through the repository's own
|
|
76
|
+
* TypeScript loader (tsx), so the catalog stays the one lookup (MW8-17.1).
|
|
77
|
+
*/
|
|
78
|
+
export function loadCatalog(root, { exec = execFileSync, runtime = process } = {}) {
|
|
79
|
+
const script = [
|
|
80
|
+
`const { productPageCatalog } = await import(${JSON.stringify(join(root, CATALOG_PATH))});`,
|
|
81
|
+
"const rows = productPageCatalog.map((x) => ({ id: x.id, title: x.title, product: x.product, surfaceType: x.surfaceType, frontendRoute: x.frontendRoute ?? null, sourcePath: x.sourcePath, fileKey: x.figma?.fileKey ?? null, componentSetKey: x.figma?.componentSetKey ?? null, componentSetName: x.figma?.componentSetName ?? null, states: x.figma?.states ?? {} }));",
|
|
82
|
+
"process.stdout.write(JSON.stringify(rows));",
|
|
83
|
+
].join("\n");
|
|
84
|
+
let out;
|
|
85
|
+
try {
|
|
86
|
+
out = exec(catalogNode(runtime), ["--import", "tsx", "--input-type=module", "-e", script], { cwd: root, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
|
|
87
|
+
} catch (error) {
|
|
88
|
+
throw new CliError("CATALOG_UNREADABLE", `Cannot load ${CATALOG_PATH} with tsx (run pnpm install in the design-system checkout): ${String(error.stderr || error.message).trim().split("\n").slice(-3).join(" ")}`, 1);
|
|
89
|
+
}
|
|
90
|
+
return JSON.parse(out);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const normalRoute = (route) => (route.length > 1 ? route.replace(/\/+$/, "") : route);
|
|
94
|
+
|
|
95
|
+
/** The catalog Surfaces a target names: a component-set key, a frontend route, or --all (narrowed by --module, --type). */
|
|
96
|
+
export function selectTargets(rows, target, { all = false, module, type } = {}) {
|
|
97
|
+
const generable = rows.filter((x) => x.componentSetKey && x.surfaceType !== "kit");
|
|
98
|
+
if (all) {
|
|
99
|
+
const picked = generable.filter((x) => (!module || x.product === module) && (!type || x.surfaceType === type));
|
|
100
|
+
if (!picked.length) throw new CliError("NO_SURFACES", `No catalog Surface matches --all${module ? ` --module ${module}` : ""}${type ? ` --type ${type}` : ""}`, 1);
|
|
101
|
+
return picked;
|
|
102
|
+
}
|
|
103
|
+
if (!target) throw new CliError("USAGE", SURFACE_USAGE, 2);
|
|
104
|
+
if (SET_KEY.test(target)) {
|
|
105
|
+
const row = generable.find((x) => x.componentSetKey === target);
|
|
106
|
+
if (!row) throw new CliError("SURFACE_NOT_IN_CATALOG", `No product-page catalog entry has componentSetKey ${target} (MW8-17.1)`, 1);
|
|
107
|
+
return [row];
|
|
108
|
+
}
|
|
109
|
+
if (target.startsWith("/")) {
|
|
110
|
+
const picked = generable.filter((x) => x.frontendRoute && normalRoute(x.frontendRoute) === normalRoute(target));
|
|
111
|
+
if (!picked.length) throw new CliError("SURFACE_NOT_IN_CATALOG", `No product-page catalog Surface has frontendRoute ${target} (MW8-17.1)`, 1);
|
|
112
|
+
return picked;
|
|
113
|
+
}
|
|
114
|
+
throw new CliError("USAGE", `The target is a 40-hex component-set key or a frontend route starting with /, never a node id (MW8-20): got ${target}`, 2);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Where a Surface's trimmed tree is committed. */
|
|
118
|
+
export const treePath = (root, row) => join(root, TREE_DIR, row.fileKey, `${row.componentSetKey}.json`);
|
|
119
|
+
/** Where a Surface's generated presentational code goes: beside the hand-built page. */
|
|
120
|
+
export const generatedPath = (root, row) => join(root, row.sourcePath.replace(/\.tsx$/, GENERATED_SUFFIX));
|
|
121
|
+
|
|
122
|
+
// ---------------------------------------------------------------------------
|
|
123
|
+
// Figma: paced reads
|
|
124
|
+
// ---------------------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* A Figma REST GET paced to one call per `minIntervalMs` across the whole run.
|
|
128
|
+
* A 429 waits Retry-After seconds, or 30 s doubling; a 5xx waits 30 s doubling.
|
|
129
|
+
*/
|
|
130
|
+
export function pacedFigma(token, { fetchImpl = fetch, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), now = () => Date.now(), minIntervalMs = MIN_FIGMA_INTERVAL_MS, attempts = 5, log = () => {} } = {}) {
|
|
131
|
+
let last = -Infinity;
|
|
132
|
+
return async function figmaGet(path) {
|
|
133
|
+
for (let attempt = 1; ; attempt++) {
|
|
134
|
+
const wait = last + minIntervalMs - now();
|
|
135
|
+
if (wait > 0) await sleep(wait);
|
|
136
|
+
last = now();
|
|
137
|
+
let response;
|
|
138
|
+
try {
|
|
139
|
+
response = await fetchImpl(`${FIGMA_API}${path}`, { headers: { "X-Figma-Token": token }, signal: AbortSignal.timeout(180_000) });
|
|
140
|
+
} catch (error) {
|
|
141
|
+
if (attempt >= attempts) throw new CliError("FIGMA_UNREACHABLE", `Cannot reach Figma: ${error.message}`);
|
|
142
|
+
await sleep(BACKOFF_429_MS);
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (response.ok) return response.json();
|
|
146
|
+
if ((response.status === 429 || response.status >= 500) && attempt < attempts) {
|
|
147
|
+
const after = Number(response.headers?.get?.("retry-after"));
|
|
148
|
+
const ms = response.status === 429 && Number.isFinite(after) && after > 0 ? after * 1000 : BACKOFF_429_MS * 2 ** (attempt - 1);
|
|
149
|
+
log(`Figma answered ${response.status} for ${path.split("?")[0]}; waiting ${Math.round(ms / 1000)} s`);
|
|
150
|
+
await sleep(ms);
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
const code = { 404: "FIGMA_NOT_FOUND", 403: "FIGMA_FORBIDDEN", 429: "FIGMA_RATE_LIMITED" }[response.status] ?? "FIGMA_ERROR";
|
|
154
|
+
throw new CliError(code, `Figma answered ${response.status} for ${path.split("?")[0]}`, 1, { status: response.status });
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** component-set key → node id in one Surfaces file, one call per file per run. */
|
|
160
|
+
export async function setIndex(figmaGet, fileKey) {
|
|
161
|
+
const body = await figmaGet(`/files/${encodeURIComponent(fileKey)}/component_sets`);
|
|
162
|
+
return new Map((body.meta?.component_sets ?? []).map((x) => [x.key, x.node_id]));
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Read one Surface set at a file version and trim it to what the generator reads. */
|
|
166
|
+
export async function fetchSurfaceTree(figmaGet, row, { index, version }) {
|
|
167
|
+
const nodeId = index.get(row.componentSetKey);
|
|
168
|
+
if (!nodeId) throw new CliError("SURFACE_NOT_PUBLISHED", `${row.componentSetName ?? row.id}: component set ${row.componentSetKey} is not among ${row.fileKey}'s published component sets`, 1);
|
|
169
|
+
const body = await figmaGet(`/files/${encodeURIComponent(row.fileKey)}/nodes?ids=${encodeURIComponent(nodeId)}${version ? `&version=${encodeURIComponent(version)}` : ""}`);
|
|
170
|
+
const entry = body.nodes?.[nodeId];
|
|
171
|
+
if (!entry?.document) throw new CliError("FIGMA_NOT_FOUND", `Figma returned no document for ${row.componentSetName ?? row.id}`, 1);
|
|
172
|
+
return trimTree(entry, { row, version: version ?? body.version ?? null });
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// ---------------------------------------------------------------------------
|
|
176
|
+
// The trimmed tree: Figma's facts the generator reads, and nothing else
|
|
177
|
+
// ---------------------------------------------------------------------------
|
|
178
|
+
|
|
179
|
+
const round = (n) => (typeof n === "number" ? Math.round(n * 100) / 100 : n);
|
|
180
|
+
const stripPropId = (name) => name.replace(/#[^#]*$/, "");
|
|
181
|
+
/** A remote variable's id is `VariableID:<key>/<local id>`: the key survives files. */
|
|
182
|
+
const variableKey = (alias) => {
|
|
183
|
+
const id = alias?.id ?? "";
|
|
184
|
+
const match = /^VariableID:([0-9a-f]{40})\//.exec(id);
|
|
185
|
+
return match ? match[1] : id || null;
|
|
186
|
+
};
|
|
187
|
+
const hex = ({ r, g, b }, a = 1) => `#${[r, g, b].map((c) => Math.round(c * 255).toString(16).padStart(2, "0")).join("")}${a < 1 ? Math.round(a * 255).toString(16).padStart(2, "0") : ""}`;
|
|
188
|
+
|
|
189
|
+
function paints(list) {
|
|
190
|
+
return (list ?? [])
|
|
191
|
+
.filter((p) => p.visible !== false && p.type === "SOLID")
|
|
192
|
+
.map((p) => ({ variable: p.boundVariables?.color ? variableKey(p.boundVariables.color) : null, hex: hex(p.color, (p.opacity ?? 1) * (p.color?.a ?? 1)) }));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export function trimTree(entry, { row, version }) {
|
|
196
|
+
const components = entry.components ?? {};
|
|
197
|
+
const sets = entry.componentSets ?? {};
|
|
198
|
+
const styles = entry.styles ?? {};
|
|
199
|
+
const keyOf = (componentId) => components[componentId]?.key ?? null;
|
|
200
|
+
|
|
201
|
+
const trim = (node, parentBox) => {
|
|
202
|
+
const out = { type: node.type, name: node.name };
|
|
203
|
+
if (node.visible === false) return { ...out, visible: false };
|
|
204
|
+
const box = node.absoluteBoundingBox;
|
|
205
|
+
if (box) {
|
|
206
|
+
out.width = round(box.width);
|
|
207
|
+
out.height = round(box.height);
|
|
208
|
+
if (parentBox) {
|
|
209
|
+
out.x = round(box.x - parentBox.x);
|
|
210
|
+
out.y = round(box.y - parentBox.y);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
if (node.layoutMode && node.layoutMode !== "NONE") {
|
|
214
|
+
out.layout = {
|
|
215
|
+
mode: node.layoutMode,
|
|
216
|
+
gap: round(node.itemSpacing ?? 0),
|
|
217
|
+
padding: [node.paddingTop, node.paddingRight, node.paddingBottom, node.paddingLeft].map((p) => round(p ?? 0)),
|
|
218
|
+
primary: node.primaryAxisAlignItems ?? "MIN",
|
|
219
|
+
counter: node.counterAxisAlignItems ?? "MIN",
|
|
220
|
+
};
|
|
221
|
+
if (node.layoutWrap === "WRAP") Object.assign(out.layout, { wrap: true, counterGap: round(node.counterAxisSpacing ?? node.itemSpacing ?? 0) });
|
|
222
|
+
if (node.layoutMode === "GRID") Object.assign(out.layout, { columns: node.gridColumnCount ?? null, rows: node.gridRowCount ?? null, rowGap: round(node.gridRowGap ?? 0), columnGap: round(node.gridColumnGap ?? 0) });
|
|
223
|
+
}
|
|
224
|
+
if (node.layoutSizingHorizontal || node.layoutSizingVertical) out.sizing = [node.layoutSizingHorizontal ?? "FIXED", node.layoutSizingVertical ?? "FIXED"];
|
|
225
|
+
if (node.layoutPositioning === "ABSOLUTE") out.absolute = true;
|
|
226
|
+
if (node.minWidth) out.minWidth = round(node.minWidth);
|
|
227
|
+
if (node.maxWidth) out.maxWidth = round(node.maxWidth);
|
|
228
|
+
if (node.clipsContent) out.clips = true;
|
|
229
|
+
|
|
230
|
+
if (node.type === "TEXT") {
|
|
231
|
+
out.text = node.characters ?? "";
|
|
232
|
+
const style = styles[node.styles?.text];
|
|
233
|
+
if (style) out.textStyle = style.name;
|
|
234
|
+
const fill = paints(node.fills)[0];
|
|
235
|
+
if (fill) out.color = fill;
|
|
236
|
+
const align = node.style?.textAlignHorizontal;
|
|
237
|
+
if (align && align !== "LEFT") out.align = align;
|
|
238
|
+
if (node.style?.maxLines) out.maxLines = node.style.maxLines;
|
|
239
|
+
return out;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const fills = paints(node.fills);
|
|
243
|
+
const strokes = paints(node.strokes);
|
|
244
|
+
if (fills.length) out.fills = fills;
|
|
245
|
+
if (strokes.length) {
|
|
246
|
+
out.strokes = strokes;
|
|
247
|
+
const w = node.individualStrokeWeights;
|
|
248
|
+
out.strokeWeights = w ? [w.top, w.right, w.bottom, w.left].map(round) : Array(4).fill(round(node.strokeWeight ?? 1));
|
|
249
|
+
}
|
|
250
|
+
if (node.cornerRadius) out.radius = round(node.cornerRadius);
|
|
251
|
+
else if (node.rectangleCornerRadii?.some(Boolean)) out.radius = node.rectangleCornerRadii.map(round);
|
|
252
|
+
const effects = (node.effects ?? []).filter((e) => e.visible !== false);
|
|
253
|
+
if (effects.length) out.effects = styles[node.styles?.effect]?.name ?? effects.map((e) => e.type).join(",");
|
|
254
|
+
|
|
255
|
+
if (node.type === "INSTANCE") {
|
|
256
|
+
const main = components[node.componentId] ?? {};
|
|
257
|
+
out.instance = {
|
|
258
|
+
key: main.key ?? null,
|
|
259
|
+
component: main.name ?? null,
|
|
260
|
+
set: sets[main.componentSetId]?.name ?? null,
|
|
261
|
+
remote: Boolean(main.remote),
|
|
262
|
+
props: Object.fromEntries(
|
|
263
|
+
Object.entries(node.componentProperties ?? {})
|
|
264
|
+
.filter(([, p]) => p.type !== "SLOT")
|
|
265
|
+
.map(([name, p]) => [stripPropId(name), p.type === "INSTANCE_SWAP" ? { swap: keyOf(p.value) } : p.value]),
|
|
266
|
+
),
|
|
267
|
+
};
|
|
268
|
+
// A library instance is the template's to draw: only its slots' content is the Surface's.
|
|
269
|
+
const children = main.remote ? (node.children ?? []).filter((c) => c.type === "SLOT") : (node.children ?? []);
|
|
270
|
+
if (children.length) out.children = children.map((c) => trim(c, box));
|
|
271
|
+
return out;
|
|
272
|
+
}
|
|
273
|
+
if (node.type === "SLOT") {
|
|
274
|
+
const ref = node.componentPropertyReferences?.slotContentId;
|
|
275
|
+
if (ref) out.slot = stripPropId(ref);
|
|
276
|
+
}
|
|
277
|
+
if (node.children?.length) out.children = node.children.map((c) => trim(c, box));
|
|
278
|
+
return out;
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
const doc = entry.document;
|
|
282
|
+
// The catalog's `figma.states` names each state by its variant's node id (its own contract, which
|
|
283
|
+
// the frame-conformance check reads too). The join happens here, inside the fetch, and the tree
|
|
284
|
+
// keeps only the state's name: no node id crosses into the committed tree or a later hop (MW8-20).
|
|
285
|
+
const nodeToState = new Map(Object.entries(row.states ?? {}).map(([state, nodeId]) => [nodeId, state]));
|
|
286
|
+
const variants = (doc.type === "COMPONENT_SET" ? doc.children : [doc]).map((variant) => ({ name: variant.name, state: nodeToState.get(variant.id) ?? slug(variantValue(variant.name)), root: trim(variant, null) }));
|
|
287
|
+
return {
|
|
288
|
+
$comment: "Generated by `nodii-dev surface generate --fetch --write` from Figma's REST nodes API (read-only). The input of the product page's generated file; never edit by hand.",
|
|
289
|
+
generator: "nodii-dev surface generate",
|
|
290
|
+
fileKey: row.fileKey,
|
|
291
|
+
componentSetKey: row.componentSetKey,
|
|
292
|
+
componentSetName: doc.name,
|
|
293
|
+
figmaVersion: version,
|
|
294
|
+
variants,
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// ---------------------------------------------------------------------------
|
|
299
|
+
// Emitting
|
|
300
|
+
// ---------------------------------------------------------------------------
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* px → a Tailwind spacing step: a multiple of 0.25 (4 px = 1), so a whole px
|
|
304
|
+
* is exact and a fractional one rounds to the nearest px. Never an arbitrary
|
|
305
|
+
* `[…px]` value, which the DS style rules refuse (no-arbitrary-tailwind).
|
|
306
|
+
*/
|
|
307
|
+
const step = (px) => String(Math.round(px) / 4);
|
|
308
|
+
const space = step;
|
|
309
|
+
const pascal = (s) => s.replace(/(^|[^a-zA-Z0-9]+)([a-zA-Z0-9])/g, (_, __, c) => c.toUpperCase()).replace(/^[0-9]/, (d) => `S${d}`);
|
|
310
|
+
const slug = (s) => s.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
|
311
|
+
/** A variant name (`View=Default, Size=sm`) → its property values (`Default sm`). */
|
|
312
|
+
const variantValue = (name) => (name.includes("=") ? name.split(",").map((p) => p.split("=")[1]?.trim()).join(" ") : name);
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* `import { A, B } from "m";` statements merged per module, keeping the names
|
|
316
|
+
* `body` uses (a template imports what any of its cases may draw); anything
|
|
317
|
+
* else is kept verbatim.
|
|
318
|
+
*/
|
|
319
|
+
export function mergeImports(statements, body = null) {
|
|
320
|
+
const used = (name) => body === null || new RegExp(`\\b${name.replace(/^type /, "")}\\b`).test(body);
|
|
321
|
+
const named = new Map();
|
|
322
|
+
const other = new Set();
|
|
323
|
+
for (const s of statements) {
|
|
324
|
+
const m = /^import\s+(type\s+)?\{([^}]*)\}\s+from\s+["']([^"']+)["'];?\s*$/.exec(s.trim());
|
|
325
|
+
if (!m) {
|
|
326
|
+
other.add(s.trim().replace(/;?$/, ";"));
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
const set = named.get(m[3]) ?? new Set();
|
|
330
|
+
for (const name of m[2].split(",").map((x) => x.trim()).filter(Boolean)) if (used(name)) set.add(m[1] ? `type ${name}` : name);
|
|
331
|
+
named.set(m[3], set);
|
|
332
|
+
}
|
|
333
|
+
const lines = [...named.entries()]
|
|
334
|
+
.filter(([, names]) => names.size > 0)
|
|
335
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
336
|
+
.map(([mod, names]) => `import { ${[...names].sort((a, b) => a.replace(/^type /, "").localeCompare(b.replace(/^type /, ""))).join(", ")} } from "${mod}";`);
|
|
337
|
+
return [...lines, ...[...other].sort()];
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** The design system's inputs to emitting: templates, the key index, tokens and text utilities. */
|
|
341
|
+
export function loadDesignSystem(root, { exec = execFileSync, docs } = {}) {
|
|
342
|
+
const dsFileKey = readJson(join(root, DS_FILE_META)).fileKey;
|
|
343
|
+
const parsed = docs ?? parseCodeConnect(root, { exec });
|
|
344
|
+
const renderer = createRenderer(root, parsed, { fileSnapshot: join(root, ONE_TO_ONE_SNAPSHOT) });
|
|
345
|
+
const snapshot = readJson(join(root, ONE_TO_ONE_SNAPSHOT));
|
|
346
|
+
const byKey = new Map();
|
|
347
|
+
for (const c of snapshot.published?.components ?? []) byKey.set(c.figmaComponentKey, c.nodeId);
|
|
348
|
+
for (const c of snapshot.published?.component_sets ?? []) byKey.set(c.figmaComponentKey ?? c.key, c.nodeId);
|
|
349
|
+
// The DS's published token catalogs: loose text takes the type utility and the colour v2 role.
|
|
350
|
+
const colourCatalog = existsSync(join(root, COLOUR_CATALOG)) ? readJson(join(root, COLOUR_CATALOG)) : [];
|
|
351
|
+
const colours = colourCatalog.map((role) => ({ name: role.name, cls: role.name.replace(/\//g, "-"), light: String(role.light ?? "").toLowerCase(), scopes: role.scopes ?? [] }));
|
|
352
|
+
const edges = existsSync(join(root, TYPE_EDGES_CATALOG)) ? readJson(join(root, TYPE_EDGES_CATALOG)) : {};
|
|
353
|
+
const textStyles = new Map((edges.type ?? []).filter((t) => t.figma?.style).map((t) => [t.figma.style, t.utility]));
|
|
354
|
+
return { dsFileKey, renderer, byKey, colours, textStyles };
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** `figma connect parse`, the repository's own Code Connect compile, into memory. */
|
|
358
|
+
export function parseCodeConnect(root, { exec = execFileSync } = {}) {
|
|
359
|
+
const out = join(tmpdir(), `nodii-surface-cc-${process.pid}-${Date.now()}.json`);
|
|
360
|
+
try {
|
|
361
|
+
exec("pnpm", ["exec", "figma", "connect", "parse", "--skip-update-check", "--outFile", out], { cwd: root, stdio: ["ignore", "ignore", "pipe"] });
|
|
362
|
+
return readJson(out);
|
|
363
|
+
} catch (error) {
|
|
364
|
+
throw new CliError("CODE_CONNECT_PARSE_FAILED", `figma connect parse failed in ${root}: ${String(error.stderr || error.message).trim().split("\n").slice(-3).join(" ")}`, 1);
|
|
365
|
+
} finally {
|
|
366
|
+
rmSync(out, { force: true });
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** A text style name (`Type v2/label/sm`) → the DS utility that sets it (`text-label-sm`), from the type catalog. */
|
|
371
|
+
export const textUtility = (styleName, textStyles) => (styleName ? (textStyles.get(styleName) ?? null) : null);
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* Emit one Surface's generated file. Returns { code, unmapped, states }:
|
|
375
|
+
* `unmapped` lists every layer that has no Code Connect mapping (U08-14).
|
|
376
|
+
*/
|
|
377
|
+
export function emitSurface(tree, row, ds) {
|
|
378
|
+
const imports = [];
|
|
379
|
+
const unmapped = [];
|
|
380
|
+
// A tree from before the state name was joined at fetch time still carries a node id (MW8-20).
|
|
381
|
+
if (tree.variants.some((v) => "nodeId" in v || !v.state)) {
|
|
382
|
+
throw new CliError("SURFACE_TREE_STALE", `${row.id}: the committed tree names its variants by node id; refetch it with \`nodii-dev surface generate ${row.componentSetKey} --fetch --write\``, 1);
|
|
383
|
+
}
|
|
384
|
+
const used = new Set();
|
|
385
|
+
const views = tree.variants.map((variant) => {
|
|
386
|
+
let state = variant.state;
|
|
387
|
+
while (used.has(state)) state += "-x";
|
|
388
|
+
used.add(state);
|
|
389
|
+
const fn = `${pascal(state)}View`;
|
|
390
|
+
const note = (path, kind, detail) => unmapped.push({ variant: variant.name, path, kind, detail });
|
|
391
|
+
const body = emitNode(variant.root, { depth: 2, parent: null, path: variant.name, ds, imports, note, root: true });
|
|
392
|
+
return { state, fn, body };
|
|
393
|
+
});
|
|
394
|
+
const component = `${pascal(row.id)}Surface`;
|
|
395
|
+
const stateType = `${component}State`;
|
|
396
|
+
const propsType = `${component}Props`;
|
|
397
|
+
const data = dataProps(views);
|
|
398
|
+
const reactTypes = [data.size && "ComponentProps", [...data.values()].some((d) => d.child) && "ReactNode"].filter(Boolean);
|
|
399
|
+
const header = [
|
|
400
|
+
"// GENERATED by `nodii-dev surface generate` from Code Connect (MW8-17). Do not edit:",
|
|
401
|
+
`// regenerate with \`nodii-dev surface generate ${row.componentSetKey} --write\`.`,
|
|
402
|
+
`// Surface: ${tree.componentSetName} · Figma file ${tree.fileKey} @ version ${tree.figmaVersion ?? "latest"} · format ${GENERATOR_FORMAT}`,
|
|
403
|
+
"// The surface-gen-equal CI gate refuses this file when it differs from the generator's output.",
|
|
404
|
+
];
|
|
405
|
+
const lines = [
|
|
406
|
+
...header,
|
|
407
|
+
...mergeImports([...imports, ...(reactTypes.length ? [`import type { ${reactTypes.join(", ")} } from "react";`] : [])], [...views.map((v) => v.body), reactTypes.join(" ")].join("\n")),
|
|
408
|
+
"",
|
|
409
|
+
`export type ${stateType} = ${views.map((v) => JSON.stringify(v.state)).join(" | ")};`,
|
|
410
|
+
"",
|
|
411
|
+
`export const ${pascal(row.id).replace(/^./, (c) => c.toLowerCase())}SurfaceStates: readonly ${stateType}[] = [${views.map((v) => JSON.stringify(v.state)).join(", ")}];`,
|
|
412
|
+
"",
|
|
413
|
+
...(data.size
|
|
414
|
+
? [
|
|
415
|
+
"/** The data and callbacks the Surface's Code Connect templates take (DS-BLK-1): each typed as the DS component it reaches. */",
|
|
416
|
+
`export interface ${propsType} {`,
|
|
417
|
+
...[...data.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([name, d]) => ` ${name}: ${propType(d)};`),
|
|
418
|
+
"}",
|
|
419
|
+
"",
|
|
420
|
+
]
|
|
421
|
+
: []),
|
|
422
|
+
`/** ${row.title}: the Surface's ${views.length} variant${views.length === 1 ? "" : "s"}, drawn as Figma composes them. */`,
|
|
423
|
+
data.size ? `export function ${component}({ state, ...data }: { state: ${stateType} } & ${propsType}) {` : `export function ${component}({ state }: { state: ${stateType} }) {`,
|
|
424
|
+
" switch (state) {",
|
|
425
|
+
...views.flatMap((v) => [` case ${JSON.stringify(v.state)}:`, ` return <${v.fn}${v.uses.size ? " {...data}" : ""} />;`]),
|
|
426
|
+
" }",
|
|
427
|
+
"}",
|
|
428
|
+
...views.flatMap((v) => ["", v.uses.size ? `function ${v.fn}({ ${[...v.uses].sort().join(", ")} }: ${propsType}) {` : `function ${v.fn}() {`, " return (", v.body, " );", "}"]),
|
|
429
|
+
"",
|
|
430
|
+
];
|
|
431
|
+
return { code: lines.join("\n"), unmapped, states: views.map((v) => v.state) };
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* The free identifiers the templates emit (`onSelect={onSelect}`, a child
|
|
436
|
+
* `{title}`, `size={file.size}`): the page's data and callbacks, lifted into
|
|
437
|
+
* the generated component's props (DS-BLK-1). Each is typed by where it goes:
|
|
438
|
+
* `ComponentProps<typeof Tag>["attr"]` for a prop, ReactNode for a child, an
|
|
439
|
+
* object of those for a member read. Sets each view's `uses`.
|
|
440
|
+
*/
|
|
441
|
+
function dataProps(views) {
|
|
442
|
+
const data = new Map();
|
|
443
|
+
const entry = (name) => data.get(name) ?? data.set(name, { attrs: new Set(), child: false, members: new Map() }).get(name);
|
|
444
|
+
for (const view of views) {
|
|
445
|
+
view.uses = new Set();
|
|
446
|
+
const body = view.body;
|
|
447
|
+
for (const m of body.matchAll(/([A-Za-z][\w-]*)=\{([a-z][A-Za-z0-9]*)(?:\.([A-Za-z][A-Za-z0-9]*))?\}/g)) {
|
|
448
|
+
const tag = openingTag(body, m.index);
|
|
449
|
+
if (!tag) continue;
|
|
450
|
+
const ref = `ComponentProps<typeof ${tag}>[${JSON.stringify(m[1])}]`;
|
|
451
|
+
const d = entry(m[2]);
|
|
452
|
+
if (m[3]) (d.members.get(m[3]) ?? d.members.set(m[3], new Set()).get(m[3])).add(ref);
|
|
453
|
+
else d.attrs.add(ref);
|
|
454
|
+
view.uses.add(m[2]);
|
|
455
|
+
}
|
|
456
|
+
for (const m of body.matchAll(/(^|>)\s*\{([a-z][A-Za-z0-9]*)\}/gm)) {
|
|
457
|
+
entry(m[2]).child = true;
|
|
458
|
+
view.uses.add(m[2]);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
return data;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** The component whose opening tag holds position `at`, walking back over balanced braces. */
|
|
465
|
+
function openingTag(body, at) {
|
|
466
|
+
let depth = 0;
|
|
467
|
+
for (let i = at - 1; i >= 0; i--) {
|
|
468
|
+
const c = body[i];
|
|
469
|
+
if (c === "}") depth++;
|
|
470
|
+
else if (c === "{") depth--;
|
|
471
|
+
else if (depth === 0 && c === ">" && body[i - 1] !== "=") return null;
|
|
472
|
+
else if (depth === 0 && c === "<") return /^<([A-Z][\w.]*)/.exec(body.slice(i))?.[1] ?? null;
|
|
473
|
+
}
|
|
474
|
+
return null;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
const propType = (d) => {
|
|
478
|
+
const parts = [...d.attrs, ...(d.child ? ["ReactNode"] : [])];
|
|
479
|
+
if (d.members.size) parts.push(`{ ${[...d.members.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([k, refs]) => `${k}: ${[...refs].join(" & ")}`).join("; ")} }`);
|
|
480
|
+
return parts.join(" & ");
|
|
481
|
+
};
|
|
482
|
+
|
|
483
|
+
const indent = (code, depth) => code.split("\n").map((line) => (line ? `${" ".repeat(depth)}${line}` : line)).join("\n");
|
|
484
|
+
|
|
485
|
+
function sizeClasses(node, parent, root) {
|
|
486
|
+
const out = [];
|
|
487
|
+
const [h, v] = node.sizing ?? ["FIXED", "FIXED"];
|
|
488
|
+
const pm = parent?.layout?.mode;
|
|
489
|
+
if (node.absolute) out.push("absolute", `left-${step(node.x ?? 0)}`, `top-${step(node.y ?? 0)}`);
|
|
490
|
+
else if (parent && !pm && node.x !== undefined) out.push("absolute", `left-${step(node.x)}`, `top-${step(node.y)}`);
|
|
491
|
+
if (node.width === undefined) return out;
|
|
492
|
+
if (root || h === "FIXED") out.push(`w-${step(node.width)}`, ...(pm === "HORIZONTAL" ? ["shrink-0"] : []));
|
|
493
|
+
else if (h === "FILL") out.push(...(pm === "HORIZONTAL" ? ["min-w-0", "flex-1"] : pm === "VERTICAL" ? ["self-stretch"] : ["w-full"]));
|
|
494
|
+
if (!root && v === "FIXED") out.push(`h-${step(node.height)}`, ...(pm === "VERTICAL" ? ["shrink-0"] : []));
|
|
495
|
+
else if (!root && v === "FILL") out.push(...(pm === "VERTICAL" ? ["min-h-0", "flex-1"] : pm === "HORIZONTAL" ? ["self-stretch"] : ["h-full"]));
|
|
496
|
+
if (node.minWidth) out.push(`min-w-${step(node.minWidth)}`);
|
|
497
|
+
if (node.maxWidth) out.push(`max-w-${step(node.maxWidth)}`);
|
|
498
|
+
return out;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
function layoutClasses(node) {
|
|
502
|
+
const l = node.layout;
|
|
503
|
+
if (!l) return node.children?.length ? ["relative"] : [];
|
|
504
|
+
const out = [];
|
|
505
|
+
if (l.mode === "GRID") {
|
|
506
|
+
out.push("grid");
|
|
507
|
+
if (l.columns) out.push(`grid-cols-${l.columns}`);
|
|
508
|
+
if (l.rowGap || l.columnGap) out.push(...(l.rowGap === l.columnGap ? [`gap-${space(l.rowGap)}`] : [`gap-x-${space(l.columnGap)}`, `gap-y-${space(l.rowGap)}`]));
|
|
509
|
+
} else {
|
|
510
|
+
out.push("flex", l.mode === "HORIZONTAL" ? "flex-row" : "flex-col");
|
|
511
|
+
if (l.wrap) out.push("flex-wrap");
|
|
512
|
+
if (l.wrap && l.counterGap !== l.gap) {
|
|
513
|
+
const [main, cross] = l.mode === "HORIZONTAL" ? ["x", "y"] : ["y", "x"];
|
|
514
|
+
if (l.gap) out.push(`gap-${main}-${space(l.gap)}`);
|
|
515
|
+
if (l.counterGap) out.push(`gap-${cross}-${space(l.counterGap)}`);
|
|
516
|
+
} else if (l.gap) out.push(`gap-${space(l.gap)}`);
|
|
517
|
+
out.push(...({ CENTER: ["justify-center"], MAX: ["justify-end"], SPACE_BETWEEN: ["justify-between"] }[l.primary] ?? []));
|
|
518
|
+
out.push(...({ MIN: ["items-start"], CENTER: ["items-center"], MAX: ["items-end"], BASELINE: ["items-baseline"] }[l.counter] ?? []));
|
|
519
|
+
}
|
|
520
|
+
const [t, r, b, lft] = l.padding;
|
|
521
|
+
if (t === r && r === b && b === lft) {
|
|
522
|
+
if (t) out.push(`p-${space(t)}`);
|
|
523
|
+
} else {
|
|
524
|
+
if (lft === r && lft) out.push(`px-${space(lft)}`);
|
|
525
|
+
else {
|
|
526
|
+
if (lft) out.push(`pl-${space(lft)}`);
|
|
527
|
+
if (r) out.push(`pr-${space(r)}`);
|
|
528
|
+
}
|
|
529
|
+
if (t === b && t) out.push(`py-${space(t)}`);
|
|
530
|
+
else {
|
|
531
|
+
if (t) out.push(`pt-${space(t)}`);
|
|
532
|
+
if (b) out.push(`pb-${space(b)}`);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
return out;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/**
|
|
539
|
+
* A text colour as a DS colour-role class. Figma's REST API names a bound
|
|
540
|
+
* variable only by key, so the role is the colour v2 TEXT_FILL role whose
|
|
541
|
+
* light value it is. A colour bound to no variable, or to none in the
|
|
542
|
+
* catalog, gets no class and is reported: never a raw value (MW2-37.1).
|
|
543
|
+
*/
|
|
544
|
+
function colour(prefix, paint, scope, ds, report) {
|
|
545
|
+
const role = paint.variable ? ds.colours.find((r) => r.scopes.includes(scope) && r.light === paint.hex.toLowerCase()) : null;
|
|
546
|
+
if (role) return `${prefix}-${role.cls}`;
|
|
547
|
+
report(paint.variable ? `colour ${paint.hex} is bound to a variable that matches no colour v2 role for ${scope}` : `colour ${paint.hex} is bound to no variable`);
|
|
548
|
+
return null;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
const SHAPES = new Set(["RECTANGLE", "ELLIPSE", "LINE", "VECTOR", "BOOLEAN_OPERATION", "STAR", "REGULAR_POLYGON"]);
|
|
552
|
+
const cls = (list) => [...new Set(list.filter(Boolean))].join(" ");
|
|
553
|
+
const describe = (node) => (node.instance ? `${node.instance.set ?? node.instance.component ?? "component"}${node.instance.set ? ` [${node.instance.component}]` : ""}` : node.type);
|
|
554
|
+
const comment = (text) => `{/* ${text.replace(/\*\//g, "* /")} */}`;
|
|
555
|
+
|
|
556
|
+
function emitNode(node, ctx) {
|
|
557
|
+
if (node.visible === false) return null;
|
|
558
|
+
const { ds, note, depth, parent, root } = ctx;
|
|
559
|
+
const path = root ? ctx.path : `${ctx.path} › ${node.name}`;
|
|
560
|
+
const child = (c) => emitNode(c, { ...ctx, depth: depth + 1, parent: node, path, root: false });
|
|
561
|
+
const report = (detail) => note(path, "token", detail);
|
|
562
|
+
|
|
563
|
+
// A DS library instance: exactly what its Code Connect template emits for this instance's properties.
|
|
564
|
+
if (node.instance?.remote) {
|
|
565
|
+
const dsNode = node.instance.key ? ds.byKey.get(node.instance.key) : null;
|
|
566
|
+
const values = Object.fromEntries(
|
|
567
|
+
Object.entries(node.instance.props).map(([name, value]) => [name, value && typeof value === "object" && "swap" in value ? (ds.byKey.get(value.swap) ?? value.swap) : value]),
|
|
568
|
+
);
|
|
569
|
+
const slotContent = (prop) => {
|
|
570
|
+
const slotNode = (node.children ?? []).find((c) => c.type === "SLOT" && c.slot === prop);
|
|
571
|
+
const inner = (slotNode?.children ?? []).map((c) => emitNode(c, { ...ctx, depth: 0, parent: slotNode, path: `${path} › ${prop}`, root: false })).filter((x) => x !== null);
|
|
572
|
+
return inner.length === 0 ? "<></>" : inner.length === 1 ? inner[0] : `<>\n${inner.map((x) => indent(x, 1)).join("\n")}\n</>`;
|
|
573
|
+
};
|
|
574
|
+
const rendered = dsNode ? ds.renderer.renderInstance(ds.dsFileKey, dsNode, values, { slot: slotContent }) : null;
|
|
575
|
+
if (!rendered || rendered.error || !rendered.code?.trim()) {
|
|
576
|
+
const why = !dsNode ? "not a published DS library component" : !rendered ? "no Code Connect template" : rendered.error ? `template error: ${rendered.error}` : "the template emits no code";
|
|
577
|
+
note(path, "instance", `${describe(node)}: ${why}`);
|
|
578
|
+
return indent(comment(`unmapped: ${describe(node)} (${why})`), depth);
|
|
579
|
+
}
|
|
580
|
+
ctx.imports.push(...rendered.imports);
|
|
581
|
+
const sizing = ctx.bare ? [] : sizeClasses(node, parent, false);
|
|
582
|
+
const code = rendered.code.trim();
|
|
583
|
+
if (!sizing.length) return indent(code, depth);
|
|
584
|
+
// Layout around a DS component is the page's; the component itself takes no className (U07-19).
|
|
585
|
+
return [indent(`<div className="${cls(["flex", "flex-col", ...sizing])}">`, depth), indent(code, depth + 1), indent("</div>", depth)].join("\n");
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
if (node.type === "TEXT") {
|
|
589
|
+
const utility = textUtility(node.textStyle, ds.textStyles);
|
|
590
|
+
note(path, "text", `loose text ${JSON.stringify(node.text.length > 60 ? `${node.text.slice(0, 57)}…` : node.text)}${utility ? "" : ` (style ${node.textStyle ?? "none"} has no DS text utility)`}`);
|
|
591
|
+
const classes = cls([
|
|
592
|
+
...sizeClasses(node, parent, false).filter((c) => !c.startsWith("h-")),
|
|
593
|
+
utility,
|
|
594
|
+
node.color ? colour("text", node.color, "TEXT_FILL", ds, report) : null,
|
|
595
|
+
{ CENTER: "text-center", RIGHT: "text-right", JUSTIFIED: "text-justify" }[node.align],
|
|
596
|
+
node.maxLines === 1 ? "truncate" : node.maxLines ? `line-clamp-${node.maxLines}` : null,
|
|
597
|
+
]);
|
|
598
|
+
return indent(`<span${classes ? ` className="${classes}"` : ""}>{${JSON.stringify(node.text)}}</span>`, depth);
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// A shape is not a DS part: it is marked and reported, never drawn as a look-alike (MW2-37.2).
|
|
602
|
+
if (SHAPES.has(node.type)) {
|
|
603
|
+
note(path, "shape", `${node.type.toLowerCase()} drawn on the Surface`);
|
|
604
|
+
return indent(comment(`unmapped: ${node.type.toLowerCase()} ${JSON.stringify(node.name)}`), depth);
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
const table = tableOf(node, { ...ctx, path });
|
|
608
|
+
if (table) return table;
|
|
609
|
+
|
|
610
|
+
// A frame, group, local component instance or slot: its layout only. A fill,
|
|
611
|
+
// stroke, radius or effect it paints itself is not drawn, which would be a
|
|
612
|
+
// look-alike of a DS part (MW2-37.2); it is reported as a missing DS part.
|
|
613
|
+
const painted = Boolean(node.fills?.length || node.strokes?.length || node.radius || node.effects);
|
|
614
|
+
if (painted)
|
|
615
|
+
note(path, "frame", `${node.instance ? `local component ${describe(node)}` : node.type.toLowerCase()} draws its own ${[node.fills?.length && "fill", node.strokes?.length && "stroke", node.radius && "radius", node.effects && `effect ${node.effects}`].filter(Boolean).join(", ")}`);
|
|
616
|
+
const classes = cls([...sizeClasses(node, parent, root), ...layoutClasses(node), node.clips ? "overflow-hidden" : null]);
|
|
617
|
+
const kids = (node.children ?? []).map(child).filter((x) => x !== null);
|
|
618
|
+
const open = `<div${classes ? ` className="${classes}"` : ""}`;
|
|
619
|
+
if (!kids.length) return indent(`${open} />`, depth);
|
|
620
|
+
return [indent(`${open}>`, depth), ...kids, indent("</div>", depth)].join("\n");
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* A table a Surface draws as frames: rows of Table-part instances (what the
|
|
625
|
+
* templates emit as TableHead or TableCell). Those parts are valid only inside
|
|
626
|
+
* the DS Table's own anatomy, so the rows are put in it, mechanically:
|
|
627
|
+
* Table › TableHeader | TableBody › TableRow, imported from the module the
|
|
628
|
+
* part's template imports from. A frame cell (content Figma lays out inside a
|
|
629
|
+
* row) becomes a TableCell holding that content. Returns null for anything else.
|
|
630
|
+
*/
|
|
631
|
+
const tablePart = (tag) => (/^Table[A-Za-z]*Head$/.test(tag ?? "") ? "head" : /^Table[A-Za-z]*Cell$/.test(tag ?? "") ? "body" : null);
|
|
632
|
+
/**
|
|
633
|
+
* A column's width as Figma sizes the cell (DESIGN-SYSTEM-177; the DS
|
|
634
|
+
* `TableColumnWidth`): px for FIXED, "fill" for FILL, "hug" for HUG. A template
|
|
635
|
+
* can't read layout sizing, so the generator declares it on each head and cell.
|
|
636
|
+
*/
|
|
637
|
+
export function columnWidth(cell) {
|
|
638
|
+
const h = cell.sizing?.[0];
|
|
639
|
+
if (h === "FIXED" && typeof cell.width === "number" && cell.width > 0) return Math.round(cell.width);
|
|
640
|
+
if (h === "FILL") return "fill";
|
|
641
|
+
if (h === "HUG") return "hug";
|
|
642
|
+
return null;
|
|
643
|
+
}
|
|
644
|
+
const widthAttr = (w) => (w === null ? "" : typeof w === "number" ? ` width={${w}}` : ` width="${w}"`);
|
|
645
|
+
/** Add `width` to a TableHead/TableCell's opening tag, unless its template already declares one. */
|
|
646
|
+
function withWidth(code, w) {
|
|
647
|
+
if (w === null || !code) return code;
|
|
648
|
+
const m = /^(\s*<Table[A-Za-z]*)([\s>/])/.exec(code);
|
|
649
|
+
if (!m) return code;
|
|
650
|
+
const tagEnd = code.indexOf(">", m[0].length - 1);
|
|
651
|
+
if (/\bwidth=/.test(code.slice(0, tagEnd === -1 ? code.length : tagEnd))) return code;
|
|
652
|
+
return code.replace(m[1], `${m[1]}${widthAttr(w)}`);
|
|
653
|
+
}
|
|
654
|
+
function tableOf(node, ctx) {
|
|
655
|
+
const rows = (node.children ?? []).filter((c) => c.visible !== false);
|
|
656
|
+
if (!rows.length || rows.some((r) => r.instance?.remote || r.type === "TEXT" || r.layout?.mode !== "HORIZONTAL")) return null;
|
|
657
|
+
const imports = [];
|
|
658
|
+
const parsed = [];
|
|
659
|
+
for (const row of rows) {
|
|
660
|
+
const cells = [];
|
|
661
|
+
let kind = null;
|
|
662
|
+
for (const cell of (row.children ?? []).filter((c) => c.visible !== false)) {
|
|
663
|
+
if (cell.instance?.remote) {
|
|
664
|
+
const local = [];
|
|
665
|
+
const code = emitNode(cell, { ...ctx, depth: 0, parent: null, path: `${ctx.path} › ${row.name}`, root: false, bare: true, imports: local, note: () => {} });
|
|
666
|
+
const part = tablePart(/^<([A-Za-z]+)/.exec(code ?? "")?.[1]);
|
|
667
|
+
if (!part || (kind && kind !== part)) return null;
|
|
668
|
+
kind = part;
|
|
669
|
+
imports.push(...local);
|
|
670
|
+
cells.push({ cell, code });
|
|
671
|
+
} else if (cell.layout || cell.type === "TEXT") cells.push({ cell, code: null });
|
|
672
|
+
else return null;
|
|
673
|
+
}
|
|
674
|
+
if (!kind) return null;
|
|
675
|
+
parsed.push({ row, kind, cells });
|
|
676
|
+
}
|
|
677
|
+
const module = imports.map((s) => /\{[^}]*\bTable[A-Za-z]*(Cell|Head)\b[^}]*\}\s+from\s+["']([^"']+)["']/.exec(s)?.[2]).find(Boolean);
|
|
678
|
+
if (!module) return null;
|
|
679
|
+
ctx.note(ctx.path, "frame", `table drawn as frames (${rows.length} row${rows.length === 1 ? "" : "s"}); assembled into the DS Table's parts`);
|
|
680
|
+
ctx.imports.push(...imports, `import { Table, TableBody, TableHeader, TableRow } from "${module}";`);
|
|
681
|
+
const { depth } = ctx;
|
|
682
|
+
const cellCode = ({ cell, code }, row, d) => {
|
|
683
|
+
const w = columnWidth(cell);
|
|
684
|
+
if (code) {
|
|
685
|
+
// Re-emit for real, so the cell's own unmapped layers are reported.
|
|
686
|
+
return withWidth(emitNode(cell, { ...ctx, depth: d, parent: null, path: `${ctx.path} › ${row.name}`, root: false, bare: true }), w);
|
|
687
|
+
}
|
|
688
|
+
// The frame stood in for the cell: its size and padding are the TableCell's now.
|
|
689
|
+
const inner = emitNode({ ...cell, sizing: ["HUG", "HUG"], x: undefined, fills: undefined, strokes: undefined, radius: undefined, ...(cell.layout ? { layout: { ...cell.layout, padding: [0, 0, 0, 0] } } : {}) }, { ...ctx, depth: d + 1, parent: null, path: `${ctx.path} › ${row.name}`, root: false });
|
|
690
|
+
return [indent(`<TableCell${widthAttr(w)}>`, d), inner, indent("</TableCell>", d)].join("\n");
|
|
691
|
+
};
|
|
692
|
+
// Every column held at px or fill is a fixed table layout; a hug column needs the browser's auto layout.
|
|
693
|
+
const widths = parsed.flatMap((p) => p.cells.map((c) => columnWidth(c.cell)));
|
|
694
|
+
const fixed = widths.length > 0 && widths.every((w) => w !== null && w !== "hug");
|
|
695
|
+
const section = (kind, tag) => {
|
|
696
|
+
const list = parsed.filter((p) => p.kind === kind);
|
|
697
|
+
if (!list.length) return [];
|
|
698
|
+
return [
|
|
699
|
+
indent(`<${tag}>`, depth + 1),
|
|
700
|
+
...list.flatMap((p) => [indent("<TableRow>", depth + 2), ...p.cells.map((c) => cellCode(c, p.row, depth + 3)), indent("</TableRow>", depth + 2)]),
|
|
701
|
+
indent(`</${tag}>`, depth + 1),
|
|
702
|
+
];
|
|
703
|
+
};
|
|
704
|
+
const sizing = sizeClasses(node, ctx.parent, ctx.root);
|
|
705
|
+
const table = [indent(fixed ? '<Table layout="fixed">' : "<Table>", depth), ...section("head", "TableHeader"), ...section("body", "TableBody"), indent("</Table>", depth)];
|
|
706
|
+
if (!sizing.length) return table.join("\n");
|
|
707
|
+
return [indent(`<div className="${cls(["flex", "flex-col", ...sizing])}">`, depth), ...table.map((line) => indent(line, 1)), indent("</div>", depth)].join("\n");
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
// ---------------------------------------------------------------------------
|
|
711
|
+
// The command
|
|
712
|
+
// ---------------------------------------------------------------------------
|
|
713
|
+
|
|
714
|
+
/** The Figma version to read: --figma-version, the committed tree's, or the Surface reference's pin. */
|
|
715
|
+
function pinnedVersion(root, row, flag) {
|
|
716
|
+
if (flag && flag !== true) return String(flag);
|
|
717
|
+
const path = treePath(root, row);
|
|
718
|
+
if (existsSync(path)) return readJson(path).figmaVersion ?? null;
|
|
719
|
+
const reference = existsSync(join(root, SURFACE_REFERENCE)) ? readJson(join(root, SURFACE_REFERENCE)) : null;
|
|
720
|
+
return reference?.files?.[row.fileKey]?.figmaVersion ?? null;
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
function figmaTokenFrom(env) {
|
|
724
|
+
const token = env.FIGMA_PAT || env.FIGMA_TOKEN;
|
|
725
|
+
if (!token) throw new CliError("FIGMA_TOKEN_REQUIRED", "--fetch reads the Surface from Figma's REST API: set FIGMA_PAT to a token that can read the Surfaces file.", 2);
|
|
726
|
+
return token;
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/** Unmapped layers grouped per Surfaces file, then per Surface (the U08-14 list). */
|
|
730
|
+
export function unmappedReport(results) {
|
|
731
|
+
const files = {};
|
|
732
|
+
for (const r of results) {
|
|
733
|
+
const file = (files[r.row.fileKey] ??= { surfaces: [] });
|
|
734
|
+
const counts = {};
|
|
735
|
+
for (const u of r.unmapped) counts[u.kind] = (counts[u.kind] ?? 0) + 1;
|
|
736
|
+
file.surfaces.push({ id: r.row.id, componentSetKey: r.row.componentSetKey, componentSetName: r.tree.componentSetName, counts, layers: r.unmapped });
|
|
737
|
+
}
|
|
738
|
+
return files;
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
export function unmappedMarkdown(files) {
|
|
742
|
+
const lines = [
|
|
743
|
+
"# Surface layers with no Code Connect mapping (U08-14)",
|
|
744
|
+
"",
|
|
745
|
+
"Generated by `nodii-dev surface generate --report`. Kinds: `instance` (a library instance the generator cannot emit through a template), `text` (loose text, drawn with the DS type utility and colour role), `frame` (a frame that paints its own fill, stroke, radius or effect: only its layout is generated), `shape` (a rectangle, ellipse or vector: marked, not drawn), `token` (a text colour that matches no colour v2 role: left out).",
|
|
746
|
+
"",
|
|
747
|
+
];
|
|
748
|
+
for (const [fileKey, file] of Object.entries(files)) {
|
|
749
|
+
const total = file.surfaces.reduce((n, s) => n + s.layers.length, 0);
|
|
750
|
+
lines.push(`## Figma file ${fileKey}: ${total} layer${total === 1 ? "" : "s"} across ${file.surfaces.length} Surface${file.surfaces.length === 1 ? "" : "s"}`, "");
|
|
751
|
+
for (const s of file.surfaces) {
|
|
752
|
+
lines.push(`### ${s.componentSetName} (\`${s.id}\`, set ${s.componentSetKey})`, "", `Counts: ${Object.entries(s.counts).map(([k, n]) => `${k} ${n}`).join(", ") || "none"}`, "");
|
|
753
|
+
for (const u of s.layers) lines.push(`- **${u.kind}** · ${u.path}: ${u.detail}`);
|
|
754
|
+
lines.push("");
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
return lines.join("\n");
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/**
|
|
761
|
+
* surface generate: read (or --fetch) each Surface's tree, emit its file,
|
|
762
|
+
* then print, --write or --check. Exit 1 on a --check difference.
|
|
763
|
+
*/
|
|
764
|
+
export async function surfaceCommand(action, rest, f, deps = {}) {
|
|
765
|
+
if (action !== "generate") throw new CliError("USAGE", SURFACE_USAGE, 2);
|
|
766
|
+
if (rest.length > 1 || (rest.length && f.all)) throw new CliError("USAGE", SURFACE_USAGE, 2);
|
|
767
|
+
if (f.write && f.check) throw new CliError("USAGE", "--write and --check are separate runs: --write updates the files, --check refuses a difference", 2);
|
|
768
|
+
if (f.check && f.fetch) throw new CliError("USAGE", "--check regenerates from the committed trees and never reads Figma; drop --fetch", 2);
|
|
769
|
+
const { env = process.env, exec = execFileSync, log = (line) => process.stderr.write(`${line}\n`), figmaGet: injected, docs, cwd } = deps;
|
|
770
|
+
const root = findRepoRoot(cwd);
|
|
771
|
+
const rows = deps.catalog ?? loadCatalog(root, { exec });
|
|
772
|
+
const selected = selectTargets(rows, rest[0], { all: Boolean(f.all), module: f.module === true ? undefined : f.module, type: f.type === true ? undefined : f.type });
|
|
773
|
+
// --all without --fetch covers the Surfaces already generated (a committed tree or a generated
|
|
774
|
+
// file); the rest are listed as not generated yet. A generated file without its tree fails below.
|
|
775
|
+
const generated = (row) => existsSync(treePath(root, row)) || existsSync(generatedPath(root, row));
|
|
776
|
+
const targets = f.all && !f.fetch ? selected.filter(generated) : selected;
|
|
777
|
+
const notYet = f.all && !f.fetch ? selected.filter((row) => !generated(row)).map((row) => row.id) : [];
|
|
778
|
+
|
|
779
|
+
let figmaGet = injected;
|
|
780
|
+
const indexes = new Map();
|
|
781
|
+
const trees = new Map();
|
|
782
|
+
for (const row of targets) {
|
|
783
|
+
const path = treePath(root, row);
|
|
784
|
+
if (f.fetch) {
|
|
785
|
+
figmaGet ??= pacedFigma(figmaTokenFrom(env), { log });
|
|
786
|
+
if (!indexes.has(row.fileKey)) indexes.set(row.fileKey, await setIndex(figmaGet, row.fileKey));
|
|
787
|
+
log(`reading ${row.componentSetName ?? row.id} from Figma`);
|
|
788
|
+
trees.set(row, await fetchSurfaceTree(figmaGet, row, { index: indexes.get(row.fileKey), version: pinnedVersion(root, row, f["figma-version"]) }));
|
|
789
|
+
} else if (existsSync(path)) {
|
|
790
|
+
trees.set(row, readJson(path));
|
|
791
|
+
} else {
|
|
792
|
+
throw new CliError("SURFACE_TREE_MISSING", `${row.id}: no committed tree at ${relative(root, path)}; run \`nodii-dev surface generate ${row.componentSetKey} --fetch --write\``, 1);
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
const ds = loadDesignSystem(root, { exec, docs });
|
|
797
|
+
const results = targets.map((row) => {
|
|
798
|
+
const tree = trees.get(row);
|
|
799
|
+
if (tree.componentSetKey !== row.componentSetKey) throw new CliError("SURFACE_TREE_MISMATCH", `${relative(root, treePath(root, row))} holds set ${tree.componentSetKey}, not ${row.componentSetKey}`, 1);
|
|
800
|
+
return { row, tree, ...emitSurface(tree, row, ds) };
|
|
801
|
+
});
|
|
802
|
+
|
|
803
|
+
const stable = (value) => `${JSON.stringify(value, null, 2)}\n`;
|
|
804
|
+
const differences = [];
|
|
805
|
+
for (const r of results) {
|
|
806
|
+
const out = generatedPath(root, r.row);
|
|
807
|
+
r.file = relative(root, out);
|
|
808
|
+
if (f.write) {
|
|
809
|
+
if (f.fetch) {
|
|
810
|
+
mkdirSync(dirname(treePath(root, r.row)), { recursive: true });
|
|
811
|
+
writeFileSync(treePath(root, r.row), stable(r.tree));
|
|
812
|
+
}
|
|
813
|
+
writeFileSync(out, r.code);
|
|
814
|
+
} else if (f.check) {
|
|
815
|
+
const current = existsSync(out) ? readFileSync(out, "utf8") : null;
|
|
816
|
+
if (current !== r.code) differences.push({ id: r.row.id, file: r.file, reason: current === null ? "missing" : "differs" });
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
const report = unmappedReport(results);
|
|
821
|
+
if (f.report && f.report !== true) {
|
|
822
|
+
const target = resolve(cwd ?? process.cwd(), String(f.report));
|
|
823
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
824
|
+
writeFileSync(target, target.endsWith(".json") ? stable(report) : unmappedMarkdown(report));
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
const payload = {
|
|
828
|
+
data: {
|
|
829
|
+
mode: f.check ? "check" : f.write ? "write" : "print",
|
|
830
|
+
surfaces: results.map((r) => ({ id: r.row.id, componentSetKey: r.row.componentSetKey, file: r.file, states: r.states, unmapped: r.unmapped.length })),
|
|
831
|
+
differences,
|
|
832
|
+
notGeneratedYet: notYet,
|
|
833
|
+
unmapped: report,
|
|
834
|
+
},
|
|
835
|
+
};
|
|
836
|
+
const human = () => {
|
|
837
|
+
if (!f.write && !f.check && results.length === 1) return results[0].code;
|
|
838
|
+
const lines = results.map(
|
|
839
|
+
(r) => `${f.write ? "wrote" : f.check ? (differences.some((d) => d.id === r.row.id) ? "DIFFERS" : "equal") : "generated"}\t${r.file}\t${r.states.length} state${r.states.length === 1 ? "" : "s"}\t${r.unmapped.length} unmapped layer${r.unmapped.length === 1 ? "" : "s"}`,
|
|
840
|
+
);
|
|
841
|
+
if (notYet.length) lines.push(`not generated yet: ${notYet.length} catalog Surface${notYet.length === 1 ? "" : "s"} (no committed tree); generate one with \`nodii-dev surface generate <componentSetKey> --fetch --write\``);
|
|
842
|
+
if (f.check && differences.length)
|
|
843
|
+
lines.push(`SURFACE_GEN_DIFFERS: ${differences.length} product page${differences.length === 1 ? " differs" : "s differ"} from the generator's output; run \`nodii-dev surface generate --all --write\` and commit, never hand-edit a generated file`);
|
|
844
|
+
return lines.join("\n");
|
|
845
|
+
};
|
|
846
|
+
return { payload, human, exitCode: f.check && differences.length ? 1 : 0 };
|
|
847
|
+
}
|