@nodii/dev 0.6.120 → 0.6.122
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 +1 -1
- package/dist/review.js +27 -4
- package/dist/surface.js +232 -26
- package/dist/vendor/render-templates.mjs +7 -4
- package/package.json +1 -1
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.
|
|
7
|
+
export const VERSION = "0.6.122";
|
|
8
8
|
export const configPath = () =>
|
|
9
9
|
process.env.NODII_DEV_CONFIG_PATH ??
|
|
10
10
|
join(homedir(), ".config/nodii-dev/config.json");
|
package/dist/review.js
CHANGED
|
@@ -13,6 +13,7 @@ import { CliError, encode } from "./core.js";
|
|
|
13
13
|
import { pickerPrompt } from "./gather.js";
|
|
14
14
|
import { componentSetsIn, designCatalogSets } from "./figma-scope.js";
|
|
15
15
|
import { gitPrivatePath } from "./safety.js";
|
|
16
|
+
import { GENERATED_PAGE_GLOB, GENERATED_SUFFIX, hasGeneratedPageStamp } from "./surface.js";
|
|
16
17
|
|
|
17
18
|
const execFileAsync = promisify(execFile);
|
|
18
19
|
export const CHECKS = ["rules", "figma", "code"];
|
|
@@ -128,8 +129,17 @@ export async function repoGeneratedPaths(request, repo) {
|
|
|
128
129
|
*/
|
|
129
130
|
export const GENERATED_DATA_PATHS = ["docs/figma-ux-ds/figma/surface-trees/"];
|
|
130
131
|
|
|
131
|
-
/**
|
|
132
|
-
|
|
132
|
+
/**
|
|
133
|
+
* NODII-DEV-CLI-77: a generated product page is the generator's output from
|
|
134
|
+
* its Surface tree, and the surface-gen-equal gate refuses one that differs.
|
|
135
|
+
* It is left out only while it carries the generator's stamp; a page without
|
|
136
|
+
* the stamp is reviewed like any hand-written file.
|
|
137
|
+
*/
|
|
138
|
+
export const GENERATED_PAGE_PATHS = [GENERATED_PAGE_GLOB];
|
|
139
|
+
const isGeneratedPagePath = (path) => path.startsWith(GENERATED_PAGE_GLOB.slice(0, GENERATED_PAGE_GLOB.indexOf("*"))) && path.endsWith(GENERATED_SUFFIX);
|
|
140
|
+
|
|
141
|
+
/** One exclude pathspec per prefix or glob, never per file, so a big regeneration cannot hit E2BIG. A prefix covers everything under it. */
|
|
142
|
+
export const generatedPathspecs = (prefixes) => prefixes.map((prefix) => `:(exclude,glob)${prefix.includes("*") ? prefix : `${prefix}**`}`);
|
|
133
143
|
|
|
134
144
|
/**
|
|
135
145
|
* DEV-REV-6: the worktree against its origin/main merge base, tracked and
|
|
@@ -144,12 +154,20 @@ export async function laneDiff(cwd, { exec = execFileAsync, generatedPaths = []
|
|
|
144
154
|
const mergeBase = (await git("merge-base", "origin/main", "HEAD")).trim();
|
|
145
155
|
const changedNames = async (...specs) => (await git("diff", "--name-only", mergeBase, ...(specs.length ? ["--", ".", ...specs] : []))).split("\n").map((x) => x.trim()).filter(Boolean);
|
|
146
156
|
const untrackedNames = async (...specs) => (await git("ls-files", "--others", "--exclude-standard", "-z", ...(specs.length ? ["--", ".", ...specs] : []))).split("\0").filter(Boolean);
|
|
147
|
-
const specs = generatedPathspecs([...GENERATED_DATA_PATHS, ...generatedPaths]);
|
|
157
|
+
const specs = generatedPathspecs([...GENERATED_DATA_PATHS, ...GENERATED_PAGE_PATHS, ...generatedPaths]);
|
|
148
158
|
const tracked = await git("diff", "--no-color", "--no-ext-diff", mergeBase);
|
|
149
159
|
const names = await changedNames();
|
|
150
160
|
const untracked = await untrackedNames();
|
|
151
161
|
const kept = new Set(specs.length ? [...await changedNames(...specs), ...await untrackedNames(...specs)] : [...names, ...untracked]);
|
|
152
162
|
const paths = [...new Set([...names, ...untracked])];
|
|
163
|
+
// A page left out by the glob alone, without the generator's stamp, goes back to the reviewer.
|
|
164
|
+
// A deleted page has no text to stamp; its removal is not hand-written code.
|
|
165
|
+
const unstamped = [];
|
|
166
|
+
for (const path of paths) {
|
|
167
|
+
if (kept.has(path) || !isGeneratedPagePath(path) || generatedPaths.some((prefix) => !prefix.includes("*") && path.startsWith(prefix))) continue;
|
|
168
|
+
const text = await readFile(join(cwd, path), "utf8").catch((error) => { if (error.code === "ENOENT") return null; throw error; });
|
|
169
|
+
if (text !== null && !hasGeneratedPageStamp(text)) { kept.add(path); unstamped.push(path); }
|
|
170
|
+
}
|
|
153
171
|
const generated = paths.filter((path) => !kept.has(path));
|
|
154
172
|
const added = [];
|
|
155
173
|
const reviewAdded = [];
|
|
@@ -161,7 +179,12 @@ export async function laneDiff(cwd, { exec = execFileAsync, generatedPaths = []
|
|
|
161
179
|
added.push(chunk);
|
|
162
180
|
if (kept.has(path)) reviewAdded.push(chunk);
|
|
163
181
|
}
|
|
164
|
-
const
|
|
182
|
+
const unstampedTracked = unstamped.filter((path) => names.includes(path));
|
|
183
|
+
// Every tracked path kept (unstamped pages included): the whole diff is the review text.
|
|
184
|
+
const reviewTracked = names.some((path) => !kept.has(path))
|
|
185
|
+
? await git("diff", "--no-color", "--no-ext-diff", mergeBase, "--", ".", ...specs) +
|
|
186
|
+
(unstampedTracked.length ? await git("diff", "--no-color", "--no-ext-diff", mergeBase, "--", ...unstampedTracked.map((path) => `:(literal)${path}`)) : "")
|
|
187
|
+
: tracked;
|
|
165
188
|
return { mergeBase, text: tracked + added.join(""), reviewText: reviewTracked + reviewAdded.join(""), paths, generated };
|
|
166
189
|
}
|
|
167
190
|
|
package/dist/surface.js
CHANGED
|
@@ -32,9 +32,14 @@ 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 =
|
|
35
|
+
export const GENERATOR_FORMAT = 8;
|
|
36
36
|
export const TREE_DIR = "docs/figma-ux-ds/figma/surface-trees";
|
|
37
37
|
export const GENERATED_SUFFIX = ".surface.generated.tsx";
|
|
38
|
+
/** Where every generated product page lives, as a git glob (NODII-DEV-CLI-77). */
|
|
39
|
+
export const GENERATED_PAGE_GLOB = `packages/blocks/src/product-pages/**/*${GENERATED_SUFFIX}`;
|
|
40
|
+
const PAGE_STAMP = /^\/\/ GENERATED by `nodii-dev surface generate` [^\n]*\n\/\/ regenerate with [^\n]*\n\/\/ Surface: [^\n]+ · Figma file \S+ @ version \S+ · format \d+\n/;
|
|
41
|
+
/** True when a product page's text opens with the stamp `surface generate` writes (the header below). */
|
|
42
|
+
export const hasGeneratedPageStamp = (text) => PAGE_STAMP.test(text);
|
|
38
43
|
const CATALOG_PATH = "packages/blocks/src/product-pages/catalog.ts";
|
|
39
44
|
const DS_FILE_META = "infra/figma/figma-file.json";
|
|
40
45
|
const ONE_TO_ONE_SNAPSHOT = "docs/figma-ux-ds/figma/1to1/figma-file.snapshot.json";
|
|
@@ -319,12 +324,33 @@ export function trimTree(entry, { row, version }) {
|
|
|
319
324
|
|
|
320
325
|
if (node.type === "INSTANCE") {
|
|
321
326
|
const main = components[node.componentId] ?? {};
|
|
322
|
-
|
|
323
|
-
|
|
327
|
+
// An instance's own layers, down to (not into) its slots, which are the Surface's.
|
|
328
|
+
const layersOf = function* (parent) {
|
|
329
|
+
for (const child of parent.children ?? []) {
|
|
330
|
+
if (child.type === "SLOT") continue;
|
|
331
|
+
yield child;
|
|
332
|
+
yield* layersOf(child);
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
// A swap keeps the swapped instance's own property values: a Field's
|
|
336
|
+
// control is a swap, and its typed value is an override on that instance, not the default.
|
|
337
|
+
const propsOf = (instance) => {
|
|
338
|
+
const swapped = new Map();
|
|
339
|
+
for (const layer of layersOf(instance)) {
|
|
340
|
+
const ref = layer.type === "INSTANCE" ? layer.componentPropertyReferences?.mainComponent : null;
|
|
341
|
+
if (ref && !swapped.has(ref)) swapped.set(ref, layer);
|
|
342
|
+
}
|
|
343
|
+
return Object.fromEntries(
|
|
324
344
|
Object.entries(instance.componentProperties ?? {})
|
|
325
345
|
.filter(([, p]) => p.type !== "SLOT")
|
|
326
|
-
.map(([name, p]) =>
|
|
346
|
+
.map(([name, p]) => {
|
|
347
|
+
if (p.type !== "INSTANCE_SWAP") return [stripPropId(name), p.value];
|
|
348
|
+
const layer = swapped.get(name);
|
|
349
|
+
const own = layer?.componentProperties && keyOf(layer.componentId) === keyOf(p.value) ? propsOf(layer) : null;
|
|
350
|
+
return [stripPropId(name), own && Object.keys(own).length ? { swap: keyOf(p.value), props: own } : { swap: keyOf(p.value) }];
|
|
351
|
+
}),
|
|
327
352
|
);
|
|
353
|
+
};
|
|
328
354
|
out.instance = {
|
|
329
355
|
key: main.key ?? null,
|
|
330
356
|
component: main.name ?? null,
|
|
@@ -332,17 +358,18 @@ export function trimTree(entry, { row, version }) {
|
|
|
332
358
|
remote: Boolean(main.remote),
|
|
333
359
|
props: propsOf(node),
|
|
334
360
|
};
|
|
335
|
-
//
|
|
336
|
-
//
|
|
337
|
-
|
|
361
|
+
// A nested instance the Surface sets (an exposed one, or one whose properties it
|
|
362
|
+
// overrides, as a Tabs Group's tab1..tab6 labels) is read only by a template's
|
|
363
|
+
// findInstance, so its properties are kept by layer name (DESIGN-SYSTEM-324).
|
|
364
|
+
if (main.remote) {
|
|
365
|
+
const overridden = new Set((node.overrides ?? []).filter((o) => o.overriddenFields?.length).map((o) => o.id));
|
|
338
366
|
const exposed = {};
|
|
339
|
-
const
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
367
|
+
for (const layer of layersOf(node)) {
|
|
368
|
+
if (layer.type !== "INSTANCE" || exposed[layer.name]) continue;
|
|
369
|
+
if (layer.isExposedInstance || overridden.has(layer.id) || layer.overrides?.some((o) => o.overriddenFields?.length)) {
|
|
370
|
+
exposed[layer.name] = { key: keyOf(layer.componentId), props: propsOf(layer) };
|
|
343
371
|
}
|
|
344
|
-
}
|
|
345
|
-
walk(node);
|
|
372
|
+
}
|
|
346
373
|
if (Object.keys(exposed).length) out.instance.exposed = exposed;
|
|
347
374
|
}
|
|
348
375
|
// A library instance is the template's to draw: only its slots' content is the Surface's.
|
|
@@ -462,13 +489,14 @@ export function emitSurface(tree, row, ds) {
|
|
|
462
489
|
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);
|
|
463
490
|
}
|
|
464
491
|
const used = new Set();
|
|
492
|
+
const scopes = new Map();
|
|
465
493
|
const views = tree.variants.map((variant) => {
|
|
466
494
|
let state = variant.state;
|
|
467
495
|
while (used.has(state)) state += "-x";
|
|
468
496
|
used.add(state);
|
|
469
497
|
const fn = `${pascal(state)}View`;
|
|
470
498
|
const note = (path, kind, detail) => unmapped.push({ variant: variant.name, path, kind, detail });
|
|
471
|
-
const emitted = emitNode(variant.root, { depth: 2, parent: null, path: variant.name, ds, imports, note, root: true }) ?? "";
|
|
499
|
+
const emitted = emitNode(variant.root, { depth: 2, parent: null, path: variant.name, ds, imports, note, root: true, scopes }) ?? "";
|
|
472
500
|
// A refused root is only a comment, and `return ({/* … */})` is an object, not JSX.
|
|
473
501
|
const body = emitted.trimStart().startsWith("{/*") ? [" <>", indent(emitted.trim(), 3), " </>"].join("\n") : emitted;
|
|
474
502
|
return { state, fn, body };
|
|
@@ -476,8 +504,10 @@ export function emitSurface(tree, row, ds) {
|
|
|
476
504
|
const component = `${pascal(row.id)}Surface`;
|
|
477
505
|
const stateType = `${component}State`;
|
|
478
506
|
const propsType = `${component}Props`;
|
|
507
|
+
resolveScopes(views, scopes);
|
|
479
508
|
const data = dataProps(views);
|
|
480
509
|
const reactTypes = [data.size && "ComponentProps", [...data.values()].some((d) => d.child) && "ReactNode"].filter(Boolean);
|
|
510
|
+
const drawn = [...data.values()].some((d) => [...d.attrs.values(), ...[...d.members.values()].flatMap((refs) => [...refs.values()])].some((r) => r.keys));
|
|
481
511
|
const header = [
|
|
482
512
|
"// GENERATED by `nodii-dev surface generate` from Code Connect (MW8-17). Do not edit:",
|
|
483
513
|
`// regenerate with \`nodii-dev surface generate ${row.componentSetKey} --write\`.`,
|
|
@@ -490,6 +520,7 @@ export function emitSurface(tree, row, ds) {
|
|
|
490
520
|
"",
|
|
491
521
|
`export type ${stateType} = ${views.map((v) => JSON.stringify(v.state)).join(" | ")};`,
|
|
492
522
|
"",
|
|
523
|
+
...(drawn ? [...DRAWN_TYPE, ""] : []),
|
|
493
524
|
`export const ${pascal(row.id).replace(/^./, (c) => c.toLowerCase())}SurfaceStates: readonly ${stateType}[] = [${views.map((v) => JSON.stringify(v.state)).join(", ")}];`,
|
|
494
525
|
"",
|
|
495
526
|
...(data.size
|
|
@@ -522,20 +553,79 @@ export function emitSurface(tree, row, ds) {
|
|
|
522
553
|
*/
|
|
523
554
|
const JS_LITERALS = new Set(["true", "false", "null", "undefined", "this"]);
|
|
524
555
|
|
|
556
|
+
/** Strings blanked to spaces of the same length, so a position still points into `code`. */
|
|
557
|
+
const maskStrings = (code) => code.replace(/"(?:[^"\\\n]|\\.)*"|`[^`]*`/g, (s) => `"${" ".repeat(s.length - 2)}"`);
|
|
558
|
+
|
|
559
|
+
/** Every free identifier a template emits in `code`: [{ at, name }], in the three forms dataProps reads. */
|
|
560
|
+
function freeIdentifiers(code) {
|
|
561
|
+
const masked = maskStrings(code);
|
|
562
|
+
const found = new Map();
|
|
563
|
+
const add = (at, name) => {
|
|
564
|
+
if (!JS_LITERALS.has(name)) found.set(at, name);
|
|
565
|
+
};
|
|
566
|
+
for (const m of masked.matchAll(/([A-Za-z][\w-]*)=\{([a-z][A-Za-z0-9]*)(?:\.[A-Za-z][A-Za-z0-9]*)?\}/g)) add(m.index + m[1].length + 2, m[2]);
|
|
567
|
+
for (const m of masked.matchAll(/(^|>)(\s*)\{([a-z][A-Za-z0-9]*)\}/gm)) add(m.index + m[1].length + m[2].length + 1, m[3]);
|
|
568
|
+
for (const m of masked.matchAll(/\b[A-Za-z_]\w*:\s*([a-z][A-Za-z0-9]*)(?=\s*[,}\]])/g)) add(m.index + m[0].length - m[1].length, m[1]);
|
|
569
|
+
return [...found.entries()].map(([at, name]) => ({ at, name })).sort((a, b) => a.at - b.at);
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* The name a DS instance's data is grouped under: its label
|
|
574
|
+
* or title property, else its layer name, in camelCase (`Subject kind` →
|
|
575
|
+
* `subjectKind`).
|
|
576
|
+
*/
|
|
577
|
+
function scopeName(node) {
|
|
578
|
+
const props = node.instance?.props ?? {};
|
|
579
|
+
const text = [props.label, props.title].find((v) => typeof v === "string" && /[A-Za-z0-9]/.test(v)) ?? node.name ?? "";
|
|
580
|
+
const words = text.match(/[A-Za-z0-9]+/g) ?? [];
|
|
581
|
+
const name = words.map((w, i) => (i === 0 ? w.toLowerCase() : w[0].toUpperCase() + w.slice(1).toLowerCase())).join("");
|
|
582
|
+
return /^[a-z]/.test(name) ? name : `field${name.replace(/^./, (c) => c.toUpperCase())}`;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* Marks each free identifier in one instance's code with its instance's
|
|
587
|
+
* scope (`__s<n>_date`); resolveScopes later keeps the plain name or scopes it.
|
|
588
|
+
* An identifier already marked (an inner instance's, in a slot) keeps its own.
|
|
589
|
+
*/
|
|
590
|
+
function scopeIdentifiers(code, scope, scopes) {
|
|
591
|
+
if (!scopes.has(scope)) scopes.set(scope, scopes.size);
|
|
592
|
+
const n = scopes.get(scope);
|
|
593
|
+
let out = code;
|
|
594
|
+
for (const { at, name } of freeIdentifiers(code).reverse()) out = `${out.slice(0, at)}__s${n}_${name}${out.slice(at + name.length)}`;
|
|
595
|
+
return out;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* Each identifier two or more instances emit becomes one per instance: a
|
|
600
|
+
* Date Picker's `date` and `setDate` under "Expires" become
|
|
601
|
+
* `expiresDate` and `setExpiresDate`, so two inputs never share a value, a list
|
|
602
|
+
* of options or a setter. An identifier one instance alone emits keeps its name.
|
|
603
|
+
*/
|
|
604
|
+
function resolveScopes(views, scopes) {
|
|
605
|
+
const names = [...scopes.keys()];
|
|
606
|
+
const marked = /__s(\d+)_([a-z][A-Za-z0-9]*)/g;
|
|
607
|
+
const users = new Map();
|
|
608
|
+
for (const view of views) for (const m of view.body.matchAll(marked)) (users.get(m[2]) ?? users.set(m[2], new Set()).get(m[2])).add(m[1]);
|
|
609
|
+
const scoped = (scope, name) => {
|
|
610
|
+
const cap = (s) => s[0].toUpperCase() + s.slice(1);
|
|
611
|
+
const m = /^(set|on)([A-Z]\w*)$/.exec(name);
|
|
612
|
+
return m ? `${m[1]}${cap(scope)}${m[2]}` : `${scope}${cap(name)}`;
|
|
613
|
+
};
|
|
614
|
+
for (const view of views) view.body = view.body.replace(marked, (_, n, name) => (users.get(name).size > 1 ? scoped(names[Number(n)], name) : name));
|
|
615
|
+
}
|
|
616
|
+
|
|
525
617
|
function dataProps(views) {
|
|
526
618
|
const data = new Map();
|
|
527
|
-
const entry = (name) => data.get(name) ?? data.set(name, { attrs: new
|
|
619
|
+
const entry = (name) => data.get(name) ?? data.set(name, { attrs: new Map(), child: false, nested: false, members: new Map() }).get(name);
|
|
528
620
|
for (const view of views) {
|
|
529
621
|
view.uses = new Set();
|
|
530
622
|
const body = view.body;
|
|
531
623
|
for (const m of body.matchAll(/([A-Za-z][\w-]*)=\{([a-z][A-Za-z0-9]*)(?:\.([A-Za-z][A-Za-z0-9]*))?\}/g)) {
|
|
532
624
|
if (JS_LITERALS.has(m[2])) continue;
|
|
533
|
-
const
|
|
534
|
-
if (
|
|
535
|
-
const ref = `ComponentProps<typeof ${tag}>[${JSON.stringify(m[1])}]`;
|
|
625
|
+
const start = openingTag(body, m.index);
|
|
626
|
+
if (start === null) continue;
|
|
536
627
|
const d = entry(m[2]);
|
|
537
|
-
|
|
538
|
-
else d.attrs.add(ref);
|
|
628
|
+
addDrawn(m[3] ? (d.members.get(m[3]) ?? d.members.set(m[3], new Map()).get(m[3])) : d.attrs, drawnProps(body, start), m[1]);
|
|
539
629
|
view.uses.add(m[2]);
|
|
540
630
|
}
|
|
541
631
|
for (const m of body.matchAll(/(^|>)\s*\{([a-z][A-Za-z0-9]*)\}/gm)) {
|
|
@@ -555,7 +645,7 @@ function dataProps(views) {
|
|
|
555
645
|
return data;
|
|
556
646
|
}
|
|
557
647
|
|
|
558
|
-
/**
|
|
648
|
+
/** Where the opening tag of the component holding position `at` starts, walking back over balanced braces. */
|
|
559
649
|
function openingTag(body, at) {
|
|
560
650
|
let depth = 0;
|
|
561
651
|
for (let i = at - 1; i >= 0; i--) {
|
|
@@ -563,15 +653,126 @@ function openingTag(body, at) {
|
|
|
563
653
|
if (c === "}") depth++;
|
|
564
654
|
else if (c === "{") depth--;
|
|
565
655
|
else if (depth === 0 && c === ">" && body[i - 1] !== "=") return null;
|
|
566
|
-
else if (depth === 0 && c === "<") return /^<
|
|
656
|
+
else if (depth === 0 && c === "<") return /^<[A-Z]/.test(body.slice(i, i + 2)) ? i : null;
|
|
657
|
+
}
|
|
658
|
+
return null;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* The props of the component whose opening tag starts at `start`, narrowed to
|
|
663
|
+
* the member of its props union this tag draws: a DS
|
|
664
|
+
* component whose props are a union (DatePicker single | range) types a data
|
|
665
|
+
* prop as that member's, not the union's. The tag's attribute names (and
|
|
666
|
+
* `children` unless it closes itself) are what it passes; a literal attribute
|
|
667
|
+
* (`mode="range"`, a bare `showReject`, `={false}`) is what it picks. A tag that
|
|
668
|
+
* spreads props is not narrowed.
|
|
669
|
+
*/
|
|
670
|
+
function drawnProps(body, start) {
|
|
671
|
+
const tag = /^<([A-Z][\w.]*)/.exec(body.slice(start))[1];
|
|
672
|
+
const attrs = tagAttributes(body, start + tag.length + 1);
|
|
673
|
+
if (!attrs) return { tag, keys: null, literals: null };
|
|
674
|
+
return { tag, keys: new Set([...attrs.names, ...(attrs.selfClosing ? [] : ["children"])]), literals: attrs.literals };
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
/**
|
|
678
|
+
* One prop read through the same component's same attribute at several tags
|
|
679
|
+
* (a PiiText in every row, a page-size select in every view) is one reference:
|
|
680
|
+
* the keys every tag passes and the literals every tag gives alike.
|
|
681
|
+
*/
|
|
682
|
+
function addDrawn(refs, drawn, attr) {
|
|
683
|
+
const id = `${drawn.tag}\u0000${attr}`;
|
|
684
|
+
const had = refs.get(id);
|
|
685
|
+
if (!had) return refs.set(id, { ...drawn, attr });
|
|
686
|
+
if (!had.keys || !drawn.keys) return refs.set(id, { tag: drawn.tag, attr, keys: null, literals: null });
|
|
687
|
+
refs.set(id, {
|
|
688
|
+
tag: drawn.tag,
|
|
689
|
+
attr,
|
|
690
|
+
keys: new Set([...had.keys].filter((k) => drawn.keys.has(k))),
|
|
691
|
+
literals: new Map([...had.literals].filter(([k, v]) => drawn.literals.get(k) === v)),
|
|
692
|
+
});
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/** A prop's type: `Drawn<ComponentProps<typeof Tag>, keys, literals>["attr"]`, or the plain props when unnarrowed. */
|
|
696
|
+
function drawnRef({ tag, attr, keys, literals }) {
|
|
697
|
+
const props = `ComponentProps<typeof ${tag}>`;
|
|
698
|
+
if (!keys) return `${props}[${JSON.stringify(attr)}]`;
|
|
699
|
+
const lits = [...literals.entries()].sort(([a], [b]) => a.localeCompare(b));
|
|
700
|
+
const lit = lits.length ? `, { ${lits.map(([k, v]) => `${/^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k)}: ${v}`).join("; ")} }` : "";
|
|
701
|
+
return `Drawn<${props}, ${keys.size ? [...keys].sort().map((k) => JSON.stringify(k)).join(" | ") : "never"}${lit}>[${JSON.stringify(attr)}]`;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
/** The type the generated file declares for drawnProps (see there). */
|
|
705
|
+
const DRAWN_TYPE = [
|
|
706
|
+
"/** A DS component's props, narrowed to the member of their union this call draws: every required prop passed, every literal one fitting. */",
|
|
707
|
+
"type Drawn<P, K extends PropertyKey, L = {}> = [DrawnOf<P, K, L>] extends [never] ? P : DrawnOf<P, K, L>;",
|
|
708
|
+
"type DrawnOf<P, K extends PropertyKey, L> = P extends unknown",
|
|
709
|
+
" ? [Exclude<{ [k in keyof P]-?: {} extends Pick<P, k> ? never : k }[keyof P], K>] extends [never]",
|
|
710
|
+
" ? [{ [k in keyof L]: k extends keyof P ? (L[k] extends P[k] ? never : k) : never }[keyof L]] extends [never]",
|
|
711
|
+
" ? P",
|
|
712
|
+
" : never",
|
|
713
|
+
" : never",
|
|
714
|
+
" : never;",
|
|
715
|
+
];
|
|
716
|
+
|
|
717
|
+
/**
|
|
718
|
+
* An opening tag's attributes from `at` (just after its name) to its `>`:
|
|
719
|
+
* every name, the literal ones' values as TS literal types, and whether it
|
|
720
|
+
* closes itself. Null for a spread or a tag it cannot read.
|
|
721
|
+
*/
|
|
722
|
+
function tagAttributes(body, at) {
|
|
723
|
+
const names = [];
|
|
724
|
+
const literals = new Map();
|
|
725
|
+
let i = at;
|
|
726
|
+
const skipString = (q) => {
|
|
727
|
+
for (i++; i < body.length && body[i] !== q; i++) if (body[i] === "\\") i++;
|
|
728
|
+
i++;
|
|
729
|
+
};
|
|
730
|
+
const braced = () => {
|
|
731
|
+
const from = i;
|
|
732
|
+
let depth = 0;
|
|
733
|
+
for (; i < body.length; i++) {
|
|
734
|
+
const c = body[i];
|
|
735
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
736
|
+
skipString(c);
|
|
737
|
+
i--;
|
|
738
|
+
} else if (c === "{") depth++;
|
|
739
|
+
else if (c === "}" && --depth === 0) return body.slice(from + 1, i++);
|
|
740
|
+
}
|
|
741
|
+
return null;
|
|
742
|
+
};
|
|
743
|
+
while (i < body.length) {
|
|
744
|
+
while (/\s/.test(body[i] ?? "")) i++;
|
|
745
|
+
if (body.startsWith("/>", i)) return { names, literals, selfClosing: true };
|
|
746
|
+
if (body[i] === ">") return { names, literals, selfClosing: false };
|
|
747
|
+
if (body[i] === "{") return null;
|
|
748
|
+
const name = /^[A-Za-z_][\w:-]*/.exec(body.slice(i))?.[0];
|
|
749
|
+
if (!name) return null;
|
|
750
|
+
names.push(name);
|
|
751
|
+
i += name.length;
|
|
752
|
+
if (body[i] !== "=") {
|
|
753
|
+
literals.set(name, "true");
|
|
754
|
+
continue;
|
|
755
|
+
}
|
|
756
|
+
i++;
|
|
757
|
+
if (body[i] === '"' || body[i] === "'") {
|
|
758
|
+
const from = i;
|
|
759
|
+
skipString(body[i]);
|
|
760
|
+
literals.set(name, JSON.stringify(body.slice(from + 1, i - 1)));
|
|
761
|
+
continue;
|
|
762
|
+
}
|
|
763
|
+
if (body[i] !== "{") return null;
|
|
764
|
+
const inner = braced();
|
|
765
|
+
if (inner === null) return null;
|
|
766
|
+
const value = inner.trim();
|
|
767
|
+
if (/^(true|false|-?\d+(\.\d+)?|"(?:[^"\\\n]|\\.)*")$/.test(value)) literals.set(name, value);
|
|
567
768
|
}
|
|
568
769
|
return null;
|
|
569
770
|
}
|
|
570
771
|
|
|
571
772
|
const propType = (d) => {
|
|
572
773
|
// A value nested in an object prop has no ComponentProps path the generator can name.
|
|
573
|
-
const parts = [...d.attrs, ...(d.child ? ["ReactNode"] : []), ...(d.nested ? ["any"] : [])];
|
|
574
|
-
if (d.members.size) parts.push(`{ ${[...d.members.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([k, refs]) => `${k}: ${[...refs].join(" & ")}`).join("; ")} }`);
|
|
774
|
+
const parts = [...[...d.attrs.values()].map(drawnRef), ...(d.child ? ["ReactNode"] : []), ...(d.nested ? ["any"] : [])];
|
|
775
|
+
if (d.members.size) parts.push(`{ ${[...d.members.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([k, refs]) => `${k}: ${[...refs.values()].map(drawnRef).join(" & ")}`).join("; ")} }`);
|
|
575
776
|
return parts.join(" & ");
|
|
576
777
|
};
|
|
577
778
|
|
|
@@ -686,8 +887,13 @@ function emitNode(node, ctx) {
|
|
|
686
887
|
// A DS library instance: exactly what its Code Connect template emits for this instance's properties.
|
|
687
888
|
if (node.instance?.remote) {
|
|
688
889
|
const dsNode = node.instance.key ? ds.byKey.get(node.instance.key) : null;
|
|
890
|
+
// A swap is the swapped component's node id, with its own values when the Surface set any.
|
|
891
|
+
const swapOf = (value) => {
|
|
892
|
+
const nodeId = ds.byKey.get(value.swap) ?? value.swap;
|
|
893
|
+
return value.props ? { nodeId, values: valuesOf(value.props) } : nodeId;
|
|
894
|
+
};
|
|
689
895
|
const valuesOf = (props) =>
|
|
690
|
-
Object.fromEntries(Object.entries(props).map(([name, value]) => [name, value && typeof value === "object" && "swap" in value ? (
|
|
896
|
+
Object.fromEntries(Object.entries(props).map(([name, value]) => [name, value && typeof value === "object" && "swap" in value ? swapOf(value) : value]));
|
|
691
897
|
const values = valuesOf(node.instance.props);
|
|
692
898
|
const nested = Object.fromEntries(
|
|
693
899
|
Object.entries(node.instance.exposed ?? {})
|
|
@@ -713,7 +919,7 @@ function emitNode(node, ctx) {
|
|
|
713
919
|
}
|
|
714
920
|
ctx.imports.push(...rendered.imports);
|
|
715
921
|
const sizing = ctx.bare ? [] : sizeClasses(node, parent, false);
|
|
716
|
-
const code = rendered.code.trim();
|
|
922
|
+
const code = ctx.scopes ? scopeIdentifiers(rendered.code.trim(), scopeName(node), ctx.scopes) : rendered.code.trim();
|
|
717
923
|
// A Table part is valid only inside the DS Table. One the generator could not assemble
|
|
718
924
|
// into a Table stays reported, never passed off as mapped (MW8-17.3).
|
|
719
925
|
const tag = /^<([A-Za-z]+)/.exec(code)?.[1];
|
|
@@ -318,8 +318,11 @@ export function createRenderer(root, docs, options = {}) {
|
|
|
318
318
|
getEnum: (name, options) =>
|
|
319
319
|
mapValue(name, options, need(name, "VARIANT").value),
|
|
320
320
|
getInstanceSwap: (name) => {
|
|
321
|
-
|
|
322
|
-
|
|
321
|
+
// A swap is a node id, or { nodeId, values } when the caller has the
|
|
322
|
+
// swapped instance's own property values (renderInstance's `values`).
|
|
323
|
+
const value = need(name, "INSTANCE_SWAP").value;
|
|
324
|
+
const swap = value && typeof value === "object" ? value : { nodeId: value };
|
|
325
|
+
return swapHandle(context, String(swap.nodeId), depth, label, swap.values);
|
|
323
326
|
},
|
|
324
327
|
getSlot: (name) => {
|
|
325
328
|
need(name, "SLOT");
|
|
@@ -344,7 +347,7 @@ export function createRenderer(root, docs, options = {}) {
|
|
|
344
347
|
};
|
|
345
348
|
}
|
|
346
349
|
|
|
347
|
-
function swapHandle(context, targetId, depth, label) {
|
|
350
|
+
function swapHandle(context, targetId, depth, label, values = {}) {
|
|
348
351
|
const { byId } = context;
|
|
349
352
|
const found = docForComponent(context, targetId);
|
|
350
353
|
const node = byId.get(targetId);
|
|
@@ -376,7 +379,7 @@ export function createRenderer(root, docs, options = {}) {
|
|
|
376
379
|
makeInstance(
|
|
377
380
|
context,
|
|
378
381
|
setNode,
|
|
379
|
-
propsFor(setNode, found.node,
|
|
382
|
+
propsFor(setNode, found.node, values),
|
|
380
383
|
depth + 1,
|
|
381
384
|
`${label} > ${setNode.name}`
|
|
382
385
|
)
|