@skillstech/thunderlang 1.2.0 → 1.3.0
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/CHANGELOG.md +131 -0
- package/dist/core.cjs +2080 -278
- package/dist/index.cjs +12742 -10943
- package/dist/learn.cjs +2716 -345
- package/package.json +1 -1
- package/src/cli.mjs +31 -6
- package/src/core/ThunderRuntime.cs +1367 -0
- package/src/core/check.mjs +158 -2
- package/src/core/cli.mjs +148 -8
- package/src/core/csharp-run.mjs +184 -0
- package/src/core/diagnostics.mjs +13 -1
- package/src/core/engine-core.mjs +285 -2
- package/src/core/engine-values.mjs +1 -1
- package/src/core/format.mjs +191 -3
- package/src/core/go-run.mjs +106 -0
- package/src/core/index.mjs +2 -1
- package/src/core/java/thunder/T.java +6 -0
- package/src/core/java/thunder/ThunderRuntime.java +1374 -0
- package/src/core/java-run.mjs +89 -0
- package/src/core/parser.mjs +331 -5
- package/src/core/project.mjs +31 -6
- package/src/core/react-run.mjs +96 -0
- package/src/core/runtime-go/thunder_runtime.go +3038 -0
- package/src/core/runtime-react.mjs +133 -0
- package/src/core/rust/thunder_runtime.rs +1645 -0
- package/src/core/rust-run.mjs +192 -0
- package/src/core/screen-values.mjs +30 -0
- package/src/core/target-csharp.mjs +484 -0
- package/src/core/target-go.mjs +555 -0
- package/src/core/target-java.mjs +587 -0
- package/src/core/target-react.mjs +270 -0
- package/src/core/target-rust.mjs +534 -0
- package/src/core/target-typescript.mjs +2 -2
- package/src/core.d.ts +18 -0
- package/src/core.mjs +1 -0
- package/src/emit.mjs +1 -1
- package/src/faithful.mjs +30 -0
- package/src/libraries.mjs +10 -3
- package/src/model.mjs +50 -8
- package/src/read-level.mjs +48 -2
- package/src/read-repo-fs.mjs +3 -1
- package/src/read.mjs +28 -5
- package/src/replay-cli.mjs +123 -0
- package/src/say-less.mjs +152 -11
- package/src/screens.mjs +833 -0
- package/src/steps.mjs +430 -19
- package/src/term.mjs +43 -0
package/src/screens.mjs
ADDED
|
@@ -0,0 +1,833 @@
|
|
|
1
|
+
// Screens: React components and Angular components read as what a person sees and does.
|
|
2
|
+
//
|
|
3
|
+
// A screen is a part of an app's interface: what it receives (props, @Input / input()), what it remembers (useState,
|
|
4
|
+
// useReducer, class fields, signals), what it shows (the JSX it returns, or the Angular template), what happens when
|
|
5
|
+
// someone acts on it (onClick, (click), …), what runs when it appears or changes (useEffect, ngOnInit), and the events
|
|
6
|
+
// it sends (@Output / output()). Everything comes from the code; anything Thunder cannot read is listed as not read,
|
|
7
|
+
// never guessed. Browser-safe: no Node APIs (templateUrl files are looked up among the files given).
|
|
8
|
+
|
|
9
|
+
import { sayCodeCondition, withLanguage } from './steps.mjs';
|
|
10
|
+
|
|
11
|
+
const words = (s) => String(s).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').toLowerCase().trim();
|
|
12
|
+
const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
|
|
13
|
+
const lineAt = (src, i) => src.slice(0, Math.max(0, i)).split('\n').length;
|
|
14
|
+
const squash = (s) => String(s).replace(/\s+/g, ' ').trim();
|
|
15
|
+
const clip = (s, n = 80) => { s = squash(s); return s.length > n ? `${s.slice(0, n - 1)}…` : s; };
|
|
16
|
+
const SIMPLE_PATH = /^[A-Za-z_$][\w$]*(?:\??\.[A-Za-z_$][\w$]*|\(\))*$/;
|
|
17
|
+
|
|
18
|
+
/** A simple path in words: total → "total", item.name → "item's name", order.customer.name → "the name of order's customer". */
|
|
19
|
+
export function pathWords(path) {
|
|
20
|
+
const parts = String(path).replace(/\?\./g, '.').replace(/\(\)/g, '').split('.').filter(Boolean).map(words);
|
|
21
|
+
if (parts.length === 1) return parts[0];
|
|
22
|
+
if (parts.length === 2) return parts[1] === 'length' ? `how many ${parts[0]}` : `${parts[0]}'s ${parts[1]}`;
|
|
23
|
+
return `the ${parts[parts.length - 1]} of ${parts.slice(0, -1).join("'s ")}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A condition in words, with the shapes screens use most said plainly. */
|
|
27
|
+
export function conditionWords(code) {
|
|
28
|
+
// (A signal is read by calling it: `todos()` is todos.)
|
|
29
|
+
const c = squash(code).replace(/^\((.*)\)$/, '$1').replace(/\b([a-z]\w*)\(\)/g, '$1');
|
|
30
|
+
let m;
|
|
31
|
+
if ((m = /^!\s*([\w$.?]+)\.length$/.exec(c)) || (m = /^([\w$.?]+)\.length\s*===?\s*0$/.exec(c))) return `${pathWords(m[1])} is empty`;
|
|
32
|
+
if ((m = /^([\w$.?]+)\.length(?:\s*>\s*0)?$/.exec(c))) return `${pathWords(m[1])} is not empty`;
|
|
33
|
+
if ((m = /^!\s*([\w$.?]+)$/.exec(c))) return `not ${pathWords(m[1])}`;
|
|
34
|
+
// A yes/no name reads as itself ("when open"); anything else is "set" when it has a value ("when user is set").
|
|
35
|
+
if (SIMPLE_PATH.test(c)) return /(?:^|\.)(?:is|has|can|should|show|open|visible|loading|enabled|disabled|active|checked|selected|done|ready|expanded|editing|valid)[A-Z\w]*$/.test(c) ? pathWords(c) : `${pathWords(c)} is set`;
|
|
36
|
+
try { return withLanguage('typescript', () => sayCodeCondition(c)); } catch { return `\`${clip(c, 60)}\``; }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// ── Scanning code: balanced braces, strings, template literals, and JSX inside expressions ─────────────────────────
|
|
40
|
+
|
|
41
|
+
/** The index just past the string or template literal starting at i. */
|
|
42
|
+
function skipString(src, i) {
|
|
43
|
+
const q = src[i];
|
|
44
|
+
for (let j = i + 1; j < src.length; j++) {
|
|
45
|
+
if (src[j] === '\\') { j++; continue; }
|
|
46
|
+
if (q === '`' && src[j] === '$' && src[j + 1] === '{') { j = matchBrace(src, j + 1) ; continue; }
|
|
47
|
+
if (src[j] === q) return j + 1;
|
|
48
|
+
}
|
|
49
|
+
return src.length;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Could a "<" at i start JSX (not a comparison)? It must follow an operator, a bracket, or `return`, and open a tag. */
|
|
53
|
+
function jsxStartsAt(src, i) {
|
|
54
|
+
if (src[i] !== '<' || !/[A-Za-z>]/.test(src[i + 1] ?? '')) return false;
|
|
55
|
+
const before = src.slice(Math.max(0, i - 12), i).replace(/\s+$/, '');
|
|
56
|
+
return before === '' || /(?:[(,{[?:=&|!]|=>|\breturn|\bdefault)$/.test(before);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The index of the bracket closing the one at i ( { [ ( ), skipping strings, comments, and JSX. */
|
|
60
|
+
export function matchBrace(src, i) {
|
|
61
|
+
const open = src[i], close = { '{': '}', '(': ')', '[': ']' }[open];
|
|
62
|
+
let depth = 0;
|
|
63
|
+
for (let j = i; j < src.length; j++) {
|
|
64
|
+
const c = src[j];
|
|
65
|
+
if (c === '"' || c === "'" || c === '`') { j = skipString(src, j) - 1; continue; }
|
|
66
|
+
if (c === '/' && src[j + 1] === '/') { const e = src.indexOf('\n', j); j = e < 0 ? src.length : e; continue; }
|
|
67
|
+
if (c === '/' && src[j + 1] === '*') { const e = src.indexOf('*/', j + 2); j = e < 0 ? src.length : e + 1; continue; }
|
|
68
|
+
if (c === '<' && jsxStartsAt(src, j)) { const r = parseJsx(src, j); if (r) { j = r.end - 1; continue; } }
|
|
69
|
+
if (c === open) depth++;
|
|
70
|
+
else if (c === close && --depth === 0) return j;
|
|
71
|
+
}
|
|
72
|
+
return -1;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// ── JSX: a small tolerant parser into a shared tree ──────────────────────────────────────────────────────────────
|
|
76
|
+
// Nodes: { type: 'el', tag, attrs: [{ name, value, kind: 'text'|'expr'|'flag'|'spread' }], kids, line }
|
|
77
|
+
// { type: 'text', parts: [string | { expr }], line }
|
|
78
|
+
// { type: 'expr', code, line } (a {…} child, analyzed later)
|
|
79
|
+
|
|
80
|
+
export function parseJsx(src, i) {
|
|
81
|
+
if (src[i] !== '<') return null;
|
|
82
|
+
const line = lineAt(src, i);
|
|
83
|
+
let j = i + 1;
|
|
84
|
+
if (src[j] === '>') { // fragment
|
|
85
|
+
const kids = jsxChildren(src, j + 1, '');
|
|
86
|
+
return kids ? { node: { type: 'el', tag: 'Fragment', attrs: [], kids: kids.kids, line }, end: kids.end } : null;
|
|
87
|
+
}
|
|
88
|
+
const tm = /^[A-Za-z][\w.:-]*/.exec(src.slice(j));
|
|
89
|
+
if (!tm) return null;
|
|
90
|
+
const tag = tm[0];
|
|
91
|
+
j += tag.length;
|
|
92
|
+
const attrs = [];
|
|
93
|
+
for (;;) {
|
|
94
|
+
while (/\s/.test(src[j] ?? '')) j++;
|
|
95
|
+
if (j >= src.length) return null;
|
|
96
|
+
if (src.startsWith('/>', j)) return { node: { type: 'el', tag, attrs, kids: [], line }, end: j + 2 };
|
|
97
|
+
if (src[j] === '>') { const kids = jsxChildren(src, j + 1, tag); return kids ? { node: { type: 'el', tag, attrs, kids: kids.kids, line }, end: kids.end } : null; }
|
|
98
|
+
if (src[j] === '{') {
|
|
99
|
+
const e = matchBrace(src, j); if (e < 0) return null;
|
|
100
|
+
const code = src.slice(j + 1, e).trim();
|
|
101
|
+
attrs.push(code.startsWith('...') ? { name: '...', value: code.slice(3), kind: 'spread' } : { name: '?', value: code, kind: 'expr' });
|
|
102
|
+
j = e + 1; continue;
|
|
103
|
+
}
|
|
104
|
+
const am = /^[^\s=/>{]+/.exec(src.slice(j));
|
|
105
|
+
if (!am) return null;
|
|
106
|
+
const name = am[0]; j += name.length;
|
|
107
|
+
while (/\s/.test(src[j] ?? '')) j++;
|
|
108
|
+
if (src[j] !== '=') { attrs.push({ name, value: true, kind: 'flag' }); continue; }
|
|
109
|
+
j++;
|
|
110
|
+
while (/\s/.test(src[j] ?? '')) j++;
|
|
111
|
+
if (src[j] === '"' || src[j] === "'") { const e = src.indexOf(src[j], j + 1); if (e < 0) return null; attrs.push({ name, value: src.slice(j + 1, e), kind: 'text' }); j = e + 1; }
|
|
112
|
+
else if (src[j] === '{') { const e = matchBrace(src, j); if (e < 0) return null; attrs.push({ name, value: src.slice(j + 1, e).trim(), kind: 'expr' }); j = e + 1; }
|
|
113
|
+
else return null;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function jsxChildren(src, j, tag) {
|
|
118
|
+
const kids = [];
|
|
119
|
+
let text = [], textLine = lineAt(src, j);
|
|
120
|
+
// (JSX drops whitespace that holds a line break and keeps a single space otherwise: "Hello, {name}".)
|
|
121
|
+
const flush = () => { const t = text.join('').replace(/\s*\n\s*/g, '').replace(/\s+/g, ' '); if (t.trim()) kids.push({ type: 'text', parts: [t], line: textLine }); text = []; };
|
|
122
|
+
while (j < src.length) {
|
|
123
|
+
if (src.startsWith('</', j)) {
|
|
124
|
+
flush();
|
|
125
|
+
const e = src.indexOf('>', j);
|
|
126
|
+
if (e < 0) return null;
|
|
127
|
+
return { kids, end: e + 1 };
|
|
128
|
+
}
|
|
129
|
+
if (src[j] === '<') { flush(); const r = parseJsx(src, j); if (!r) return null; kids.push(r.node); j = r.end; textLine = lineAt(src, j); continue; }
|
|
130
|
+
if (src[j] === '{') {
|
|
131
|
+
flush();
|
|
132
|
+
const e = matchBrace(src, j); if (e < 0) return null;
|
|
133
|
+
const code = src.slice(j + 1, e).trim();
|
|
134
|
+
if (code && !/^\/\*[\s\S]*\*\/$/.test(code)) kids.push({ type: 'expr', code, line: lineAt(src, j) });
|
|
135
|
+
j = e + 1; textLine = lineAt(src, j); continue;
|
|
136
|
+
}
|
|
137
|
+
if (!text.length) textLine = lineAt(src, j);
|
|
138
|
+
text.push(src[j]); j++;
|
|
139
|
+
}
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// ── Angular templates: HTML with Angular's bindings and control flow, into the same tree ────────────────────────────
|
|
144
|
+
|
|
145
|
+
const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
|
|
146
|
+
|
|
147
|
+
/** Parse an Angular template (offset: where it starts in the file, for line numbers). */
|
|
148
|
+
export function parseTemplate(html, fileSrc = null, offset = 0) {
|
|
149
|
+
const lineOf = (i) => (fileSrc ? lineAt(fileSrc, offset + i) : lineAt(html, i));
|
|
150
|
+
let i = 0;
|
|
151
|
+
const parseNodes = (stopTag, stopBrace) => {
|
|
152
|
+
const out = [];
|
|
153
|
+
let text = '', tl = lineOf(i);
|
|
154
|
+
const flush = () => { if (text.trim()) out.push(textNode(text, tl)); text = ''; };
|
|
155
|
+
while (i < html.length) {
|
|
156
|
+
if (stopBrace && html[i] === '}') { flush(); i++; return out; }
|
|
157
|
+
if (html.startsWith('<!--', i)) { flush(); const e = html.indexOf('-->', i); i = e < 0 ? html.length : e + 3; continue; }
|
|
158
|
+
if (html.startsWith('</', i)) { flush(); const e = html.indexOf('>', i); i = e < 0 ? html.length : e + 1; return out; }
|
|
159
|
+
if (html[i] === '@' && /^@(if|for|switch|defer|else|empty|case|default)\b/.test(html.slice(i))) { flush(); const b = parseBlock(); if (b) out.push(b); tl = lineOf(i); continue; }
|
|
160
|
+
if (html[i] === '<' && /[A-Za-z]/.test(html[i + 1] ?? '')) { flush(); const el = parseElement(); if (el) out.push(el); tl = lineOf(i); continue; }
|
|
161
|
+
if (!text) tl = lineOf(i);
|
|
162
|
+
text += html[i]; i++;
|
|
163
|
+
}
|
|
164
|
+
flush();
|
|
165
|
+
return out;
|
|
166
|
+
};
|
|
167
|
+
const textNode = (t, line) => {
|
|
168
|
+
const parts = [];
|
|
169
|
+
let rest = squash(t), m;
|
|
170
|
+
while ((m = /\{\{\s*([\s\S]*?)\s*\}\}/.exec(rest))) { if (m.index) parts.push(rest.slice(0, m.index)); parts.push({ expr: m[1] }); rest = rest.slice(m.index + m[0].length); }
|
|
171
|
+
if (rest) parts.push(rest);
|
|
172
|
+
return { type: 'text', parts, line };
|
|
173
|
+
};
|
|
174
|
+
const parseElement = () => {
|
|
175
|
+
const line = lineOf(i);
|
|
176
|
+
const tm = /^<([A-Za-z][\w:-]*)/.exec(html.slice(i));
|
|
177
|
+
const tag = tm[1];
|
|
178
|
+
i += tm[0].length;
|
|
179
|
+
const attrs = [];
|
|
180
|
+
for (;;) {
|
|
181
|
+
while (/\s/.test(html[i] ?? '')) i++;
|
|
182
|
+
if (i >= html.length) break;
|
|
183
|
+
if (html.startsWith('/>', i)) { i += 2; return { type: 'el', tag, attrs, kids: [], line }; }
|
|
184
|
+
if (html[i] === '>') { i++; break; }
|
|
185
|
+
const am = /^[^\s=/>]+/.exec(html.slice(i));
|
|
186
|
+
if (!am) { i++; continue; }
|
|
187
|
+
const name = am[0]; i += name.length;
|
|
188
|
+
while (/\s/.test(html[i] ?? '')) i++;
|
|
189
|
+
if (html[i] !== '=') { attrs.push({ name, value: true, kind: 'flag' }); continue; }
|
|
190
|
+
i++;
|
|
191
|
+
while (/\s/.test(html[i] ?? '')) i++;
|
|
192
|
+
let value;
|
|
193
|
+
if (html[i] === '"' || html[i] === "'") { const e = html.indexOf(html[i], i + 1); value = html.slice(i + 1, e < 0 ? html.length : e); i = e < 0 ? html.length : e + 1; }
|
|
194
|
+
else { const vm = /^[^\s>]+/.exec(html.slice(i)); value = vm ? vm[0] : ''; i += value.length; }
|
|
195
|
+
// [prop], (event), [(two-way)], *structural are bindings: the value is code. Plain attributes are text.
|
|
196
|
+
attrs.push({ name, value, kind: /^[[(*]/.test(name) ? 'expr' : 'text' });
|
|
197
|
+
}
|
|
198
|
+
const kids = VOID.has(tag.toLowerCase()) ? [] : parseNodes(tag, false);
|
|
199
|
+
return { type: 'el', tag, attrs, kids, line };
|
|
200
|
+
};
|
|
201
|
+
const parseBlock = () => {
|
|
202
|
+
const line = lineOf(i);
|
|
203
|
+
const m = /^@(\w+)\s*(?:\(([^)]*(?:\([^)]*\)[^)]*)*)\))?\s*\{/.exec(html.slice(i));
|
|
204
|
+
if (!m) { const e = html.indexOf('\n', i); i = e < 0 ? html.length : e; return null; }
|
|
205
|
+
i += m[0].length;
|
|
206
|
+
const body = parseNodes(null, true);
|
|
207
|
+
return { type: 'block', kind: m[1], head: (m[2] ?? '').trim(), kids: body, line };
|
|
208
|
+
};
|
|
209
|
+
const nodes = parseNodes(null, false);
|
|
210
|
+
// Join @if / @else if / @else and @for / @empty into one node each.
|
|
211
|
+
const join = (list) => {
|
|
212
|
+
const out = [];
|
|
213
|
+
for (const n of list) {
|
|
214
|
+
if (n.type === 'el') { n.kids = join(n.kids); out.push(n); continue; }
|
|
215
|
+
if (n.type !== 'block') { out.push(n); continue; }
|
|
216
|
+
n.kids = join(n.kids);
|
|
217
|
+
const prev = out[out.length - 1];
|
|
218
|
+
if (n.kind === 'else' && prev?.type === 'cond') {
|
|
219
|
+
let tail = prev; while (tail.otherwise?.length === 1 && tail.otherwise[0].type === 'cond') tail = tail.otherwise[0];
|
|
220
|
+
const ei = /^if\s*\((.*)\)$/s.exec(n.head) || (/^if\b/.test(n.head) ? [null, n.head.replace(/^if\s*/, '')] : null);
|
|
221
|
+
tail.otherwise = ei ? [{ type: 'cond', test: ei[1], then: n.kids, otherwise: null, line: n.line }] : n.kids;
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
if (n.kind === 'empty' && prev?.type === 'each') { prev.empty = n.kids; continue; }
|
|
225
|
+
if (n.kind === 'if') { out.push({ type: 'cond', test: n.head.replace(/;\s*as\s+\w+$/, ''), then: n.kids, otherwise: null, line: n.line }); continue; }
|
|
226
|
+
if (n.kind === 'for') {
|
|
227
|
+
const f = /^(?:let\s+)?(\w+)\s+of\s+([^;]+)/.exec(n.head);
|
|
228
|
+
out.push(f ? { type: 'each', item: f[1], list: f[2].trim(), body: n.kids, line: n.line } : { type: 'unread', code: `@for (${n.head})`, why: 'a loop Thunder does not read yet', line: n.line });
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
out.push({ type: 'unread', code: `@${n.kind} (${n.head})`, why: `an @${n.kind} block, not read yet`, line: n.line, kids: n.kids });
|
|
232
|
+
}
|
|
233
|
+
return out;
|
|
234
|
+
};
|
|
235
|
+
return join(nodes);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// ── Turning the tree into what a person sees ─────────────────────────────────────────────────────────────────────
|
|
239
|
+
|
|
240
|
+
const CONTAINERS = new Set(['div', 'span', 'section', 'main', 'article', 'aside', 'Fragment', 'React.Fragment', 'ng-container', 'ng-template', 'template', 'body', 'html']);
|
|
241
|
+
const INLINE = new Set(['strong', 'em', 'b', 'i', 'small', 'code', 'mark', 'u', 'sup', 'sub', 'abbr', 'time']);
|
|
242
|
+
const SKIP = new Set(['br', 'hr', 'wbr', 'script', 'style', 'meta', 'link']);
|
|
243
|
+
const TAG_WORDS = {
|
|
244
|
+
h1: 'a heading', h2: 'a heading', h3: 'a heading', h4: 'a heading', h5: 'a heading', h6: 'a heading',
|
|
245
|
+
p: 'a paragraph', button: 'a button', a: 'a link', img: 'an image', textarea: 'a text area', select: 'a dropdown',
|
|
246
|
+
option: 'a choice', label: 'a label', li: 'a row', tr: 'a row', td: 'a cell', th: 'a column heading', table: 'a table',
|
|
247
|
+
ul: 'a list', ol: 'a numbered list', form: 'a form', nav: 'a navigation bar', header: 'a header', footer: 'a footer',
|
|
248
|
+
svg: 'a drawing', video: 'a video', audio: 'a sound player', dialog: 'a dialog', iframe: 'an embedded page', progress: 'a progress bar',
|
|
249
|
+
thead: 'the table heading', tbody: 'the table rows', fieldset: 'a group of fields', legend: 'a group title', blockquote: 'a quote', pre: 'a block of code',
|
|
250
|
+
'router-outlet': 'the page for the current address',
|
|
251
|
+
};
|
|
252
|
+
const INPUT_WORDS = { checkbox: 'a checkbox', radio: 'a choice button', submit: 'a submit button', email: 'an email box', password: 'a password box', number: 'a number box', search: 'a search box', date: 'a date box', file: 'a file picker', range: 'a slider', tel: 'a phone box', url: 'an address box', hidden: null, color: 'a color picker' };
|
|
253
|
+
const EVENT_WORDS = { click: 'is pressed', dblclick: 'is double-clicked', change: 'changes', input: 'is typed in', submit: 'is sent', ngsubmit: 'is sent', keydown: 'gets a key press', keyup: 'gets a key press', keypress: 'gets a key press', blur: 'is left', focus: 'is chosen', mouseenter: 'is pointed at', mouseleave: 'is no longer pointed at', scroll: 'is scrolled', load: 'loads', select: 'is selected' };
|
|
254
|
+
|
|
255
|
+
const attr = (el, ...names) => el.attrs.find((a) => names.includes(a.name));
|
|
256
|
+
const attrText = (el, ...names) => { const a = attr(el, ...names); return a && a.kind === 'text' ? a.value : null; };
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Describe a screen's tree. ctx: { framework, screensByName, selectors, members, state, inputs, outputs, notRead, events }.
|
|
260
|
+
* Gives back outline lines: [{ says, line, kids? }].
|
|
261
|
+
*/
|
|
262
|
+
function describe(nodes, ctx) {
|
|
263
|
+
const out = [];
|
|
264
|
+
for (const n of nodes) {
|
|
265
|
+
if (n.type === 'text') { const t = textWords(n.parts, ctx); if (t) out.push({ says: `text: ${t}`, line: n.line }); continue; }
|
|
266
|
+
if (n.type === 'expr') { out.push(...exprChild(n, ctx)); continue; }
|
|
267
|
+
if (n.type === 'cond') { out.push(condLine(n.test, describe(n.then, ctx), n.otherwise ? describe(n.otherwise, ctx) : null, n.line, ctx)); continue; }
|
|
268
|
+
if (n.type === 'each') { out.push(eachLine(n, describe(n.body, ctx), n.empty ? describe(n.empty, ctx) : null)); continue; }
|
|
269
|
+
if (n.type === 'unread') { ctx.notRead.push({ line: n.line, code: clip(n.code), why: n.why }); out.push({ says: `not read: \`${clip(n.code, 60)}\``, line: n.line, notRead: true, code: clip(n.code, 60) }); continue; }
|
|
270
|
+
if (n.type === 'el') out.push(...elementLines(n, ctx));
|
|
271
|
+
}
|
|
272
|
+
return out;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function elementLines(el, ctx) {
|
|
276
|
+
// Angular structural directives wrap the element they sit on.
|
|
277
|
+
const ngIf = attr(el, '*ngIf');
|
|
278
|
+
if (ngIf) {
|
|
279
|
+
const [test, elseRef] = String(ngIf.value).split(/;\s*else\s+/);
|
|
280
|
+
const inner = { ...el, attrs: el.attrs.filter((a) => a !== ngIf) };
|
|
281
|
+
if (elseRef) ctx.notRead.push({ line: el.line, code: `*ngIf="${clip(ngIf.value, 50)}"`, why: 'the "else" template is elsewhere; it is not shown here' });
|
|
282
|
+
return [condLine(test.trim(), elementLines(inner, ctx), null, el.line, ctx)];
|
|
283
|
+
}
|
|
284
|
+
const ngFor = attr(el, '*ngFor');
|
|
285
|
+
if (ngFor) {
|
|
286
|
+
const m = /^\s*let\s+(\w+)\s+of\s+([^;]+)/.exec(String(ngFor.value));
|
|
287
|
+
const inner = { ...el, attrs: el.attrs.filter((a) => a !== ngFor) };
|
|
288
|
+
if (!m) { ctx.notRead.push({ line: el.line, code: `*ngFor="${clip(ngFor.value, 50)}"`, why: 'a repeat Thunder does not read yet' }); return [{ says: `not read: \`*ngFor="${clip(ngFor.value, 40)}"\``, line: el.line, notRead: true, code: `*ngFor="${clip(ngFor.value, 40)}"` }]; }
|
|
289
|
+
return [eachLine({ item: m[1], list: m[2].trim(), line: el.line }, elementLines(inner, ctx))];
|
|
290
|
+
}
|
|
291
|
+
const otherStructural = el.attrs.find((a) => /^\*/.test(a.name));
|
|
292
|
+
if (otherStructural) ctx.notRead.push({ line: el.line, code: `${otherStructural.name}="${clip(otherStructural.value, 40)}"`, why: 'a directive Thunder does not read yet' });
|
|
293
|
+
for (const a of el.attrs) if (a.kind === 'spread') ctx.notRead.push({ line: el.line, code: `{...${clip(a.value, 40)}}`, why: 'spread props: which values they hold is not known here' });
|
|
294
|
+
|
|
295
|
+
const tag = el.tag;
|
|
296
|
+
if (SKIP.has(tag)) return [];
|
|
297
|
+
const kids = describe(el.kids.filter((k) => !(k.type === 'el' && INLINE.has(k.tag))), ctx);
|
|
298
|
+
if (CONTAINERS.has(tag) && !eventsOf(el, ctx, 'it').length) return kids;
|
|
299
|
+
const what = elementWhat(el, ctx);
|
|
300
|
+
if (!what) return kids;
|
|
301
|
+
const label = elementLabel(el, ctx);
|
|
302
|
+
const labelFromText = label != null && !attrText(el, 'aria-label', 'alt', 'placeholder', 'title', 'name');
|
|
303
|
+
const extra = [];
|
|
304
|
+
const disabled = attr(el, 'disabled', '[disabled]');
|
|
305
|
+
if (disabled?.kind === 'expr') extra.push(`turned off when ${conditionWords(disabled.value)}`);
|
|
306
|
+
else if (disabled?.kind === 'flag') extra.push('turned off');
|
|
307
|
+
const shown = attr(el, 'value', '[value]', 'checked', '[checked]', '[(ngModel)]', '[ngModel]', 'v-model');
|
|
308
|
+
if (shown?.kind === 'expr' && SIMPLE_PATH.test(String(shown.value).trim())) extra.push(`${/ngModel/.test(shown.name) && shown.name.startsWith('[(') ? 'showing and changing' : 'showing'} ${pathWords(shown.value.trim())}`);
|
|
309
|
+
const to = attrText(el, 'href', 'routerLink', 'to') ?? (attr(el, '[routerLink]', 'to')?.kind === 'expr' ? `«${clip(attr(el, '[routerLink]', 'to').value, 40)}»` : null);
|
|
310
|
+
if (to && (tag === 'a' || attr(el, 'routerLink', '[routerLink]'))) extra.push(`to ${to}`);
|
|
311
|
+
const evs = eventsOf(el, ctx, label ?? what.replace(/^an? /, 'the '));
|
|
312
|
+
const says = `${what}${label ? `: ${label}` : ''}${extra.length ? ` (${extra.join('; ')})` : ''}${evs.length ? `; when it ${evs.map((e) => `${e.verb}: ${e.runs}`).join('; when it ')}` : ''}`;
|
|
313
|
+
const keepKids = labelFromText ? kids.filter((k) => !k.says.startsWith('text: ')) : kids;
|
|
314
|
+
return [{ says, line: el.line, ...(keepKids.length ? { kids: keepKids } : {}) }];
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** What an element is, in words: a heading, a button, the Cart screen, … (null for a plain container). */
|
|
318
|
+
function elementWhat(el, ctx) {
|
|
319
|
+
const tag = el.tag;
|
|
320
|
+
if (tag === 'input') { const type = (attrText(el, 'type') ?? 'text').toLowerCase(); return type in INPUT_WORDS ? INPUT_WORDS[type] : 'a text box'; }
|
|
321
|
+
if (TAG_WORDS[tag]) return TAG_WORDS[tag];
|
|
322
|
+
const screen = /^[A-Z]/.test(tag) ? ctx.screensByName.get(tag.split('.').pop()) : ctx.selectors.get(tag);
|
|
323
|
+
if (screen) { ctx.uses.add(screen.name); return `the ${screen.label} screen`; }
|
|
324
|
+
if (/^[A-Z]/.test(tag)) { ctx.uses.add(tag); return `the ${tag} component`; }
|
|
325
|
+
if (tag.includes('-')) { ctx.uses.add(tag); return `the <${tag}> element`; }
|
|
326
|
+
return null;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** An element's visible words: its text, or what describes it (alt, placeholder, aria-label, a label's text). */
|
|
330
|
+
function elementLabel(el, ctx) {
|
|
331
|
+
const inline = (kids) => kids.flatMap((k) => (k.type === 'text' ? k.parts : k.type === 'el' && INLINE.has(k.tag) ? inline(k.kids) : k.type === 'expr' && SIMPLE_PATH.test(k.code) ? [{ expr: k.code }] : []));
|
|
332
|
+
const parts = inline(el.kids);
|
|
333
|
+
const hasOther = el.kids.some((k) => (k.type === 'el' && !INLINE.has(k.tag)) || (k.type === 'expr' && !SIMPLE_PATH.test(k.code)));
|
|
334
|
+
if (parts.length && !hasOther) return textWords(parts, ctx);
|
|
335
|
+
const a = attrText(el, 'aria-label', 'alt', 'placeholder', 'title', 'name');
|
|
336
|
+
return a ? `"${a}"` : null;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function textWords(parts, ctx) {
|
|
340
|
+
const t = parts.map((p) => (typeof p === 'string' ? p : SIMPLE_PATH.test(squash(p.expr)) ? `{${pathWords(squash(p.expr))}}` : `{${clip(p.expr, 40)}}`)).join('').replace(/\s+/g, ' ').trim();
|
|
341
|
+
if (!t) return null;
|
|
342
|
+
return parts.length === 1 && typeof parts[0] === 'string' ? `"${t}"` : `"${t}"`;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/** The events on an element: each with the words for what happens and what runs. */
|
|
346
|
+
function eventsOf(el, ctx, who) {
|
|
347
|
+
const out = [];
|
|
348
|
+
for (const a of el.attrs) {
|
|
349
|
+
let name = null;
|
|
350
|
+
if (/^on[A-Z]/.test(a.name) && a.kind === 'expr') name = a.name.slice(2).toLowerCase();
|
|
351
|
+
else if (/^\(([\w.]+)\)$/.test(a.name)) name = a.name.slice(1, -1).toLowerCase().split('.')[0];
|
|
352
|
+
if (!name) continue;
|
|
353
|
+
const verb = EVENT_WORDS[name] ?? `gets "${name}"`;
|
|
354
|
+
const runs = handlerWords(String(a.value), ctx);
|
|
355
|
+
out.push({ verb, runs });
|
|
356
|
+
ctx.events.push({ on: who, event: name, when: `When ${who} ${verb}`, runs: runs.text ?? runs, line: el.line, ...(runs.member ? { member: runs.member } : {}) });
|
|
357
|
+
}
|
|
358
|
+
return out.map((e) => ({ verb: e.verb, runs: e.runs.text ?? e.runs }));
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** What a handler does, in words: runs checkout, sets coupon to the typed value, sends the checkout event, … */
|
|
362
|
+
function handlerWords(code, ctx) {
|
|
363
|
+
let c = squash(code).replace(/;$/, '');
|
|
364
|
+
// `() => x`, `(e) => x`, `e => { x; y }` → the body.
|
|
365
|
+
const arrow = /^(?:async\s*)?(?:\(([^)]*)\)|(\w+))\s*=>\s*([\s\S]+)$/.exec(c);
|
|
366
|
+
if (arrow) c = arrow[3].replace(/^\{([\s\S]*)\}$/, '$1').trim().replace(/;$/, '');
|
|
367
|
+
const statements = c.split(/;\s*/).filter(Boolean);
|
|
368
|
+
const said = statements.map((s) => statementWords(s.trim(), ctx));
|
|
369
|
+
if (said.some((s) => s == null)) { ctx.notRead.push({ line: null, code: clip(code), why: 'an event handler Thunder does not read yet' }); return { text: `runs \`${clip(code, 50)}\`` }; }
|
|
370
|
+
const member = statements.length === 1 ? said[0].member : null;
|
|
371
|
+
return { text: said.map((s) => s.text).join(', then '), ...(member ? { member } : {}) };
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function statementWords(s, ctx) {
|
|
375
|
+
let m;
|
|
376
|
+
// A named handler given as is: onClick={checkout} / (click)="checkout()".
|
|
377
|
+
if (SIMPLE_PATH.test(s) || (m = /^([\w$.]+)\(\)$/.exec(s))) {
|
|
378
|
+
const name = (m ? m[1] : s).replace(/\(\)$/, '').replace(/^this\./, '');
|
|
379
|
+
if (ctx.outputs.has(name.replace(/\.emit$/, ''))) return { text: `sends the ${words(name.replace(/\.emit$/, ''))} event` };
|
|
380
|
+
if (ctx.inputs.has(name)) return { text: `tells the parent (${words(name)})` };
|
|
381
|
+
return { text: `runs ${words(name.split('.').pop())}`, member: ctx.memberOf(name.split('.').pop()) };
|
|
382
|
+
}
|
|
383
|
+
// setX(value): the state setter of x.
|
|
384
|
+
if ((m = /^(set[A-Z]\w*)\(([\s\S]*)\)$/.exec(s)) && ctx.setters.has(m[1])) {
|
|
385
|
+
const target = ctx.setters.get(m[1]);
|
|
386
|
+
const v = m[2].trim();
|
|
387
|
+
return { text: `sets ${words(target)} to ${valueWords(v, target)}` };
|
|
388
|
+
}
|
|
389
|
+
// signal.set(v) / signal.update(fn).
|
|
390
|
+
if ((m = /^(?:this\.)?(\w+)\.(set|update)\(([\s\S]*)\)$/.exec(s)) && ctx.stateNames.has(m[1])) return { text: m[2] === 'set' ? `sets ${words(m[1])} to ${valueWords(m[3].trim(), m[1])}` : `changes ${words(m[1])}` };
|
|
391
|
+
// output.emit(x) / props callback(x).
|
|
392
|
+
if ((m = /^(?:this\.)?(\w+)\.emit\(([\s\S]*)\)$/.exec(s)) && ctx.outputs.has(m[1])) return { text: `sends the ${words(m[1])} event${m[2].trim() ? ` with ${valueWords(m[2].trim())}` : ''}` };
|
|
393
|
+
if ((m = /^(?:this\.)?(\w+)\(([\s\S]*)\)$/.exec(s))) {
|
|
394
|
+
const args = m[2].trim();
|
|
395
|
+
if (ctx.inputs.has(m[1])) return { text: `tells the parent (${words(m[1])})${args ? ` with ${valueWords(args)}` : ''}` };
|
|
396
|
+
if (/^[\w$.]*$|^[\w$.]+(?:,\s*[\w$.]+)*$/.test(args)) return { text: `runs ${words(m[1])}${args ? ` with ${args.split(/,\s*/).map((a) => valueWords(a)).join(' and ')}` : ''}`, member: ctx.memberOf(m[1]) };
|
|
397
|
+
return null;
|
|
398
|
+
}
|
|
399
|
+
// x = value (Angular templates assign fields).
|
|
400
|
+
if ((m = /^(?:this\.)?(\w+)\s*=\s*([^=][\s\S]*)$/.exec(s))) return { text: `sets ${words(m[1])} to ${valueWords(m[2].trim(), m[1])}` };
|
|
401
|
+
return null;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function valueWords(v, target = null) {
|
|
405
|
+
const s = squash(v).replace(/\b([a-z]\w*)\(\)/g, '$1');
|
|
406
|
+
if (/^(?:e|event|ev|\$event)\.target\.(?:value|checked)$/.test(s) || s === '$event') return 'what was typed or chosen';
|
|
407
|
+
if (/^["'`]/.test(s)) return `"${s.slice(1, -1)}"`;
|
|
408
|
+
if (/^-?\d+(\.\d+)?$/.test(s)) return s;
|
|
409
|
+
if (s === 'true') return 'yes'; if (s === 'false') return 'no';
|
|
410
|
+
if (s === 'null' || s === 'undefined') return 'nothing';
|
|
411
|
+
if (s === '[]') return 'an empty list'; if (s === '{}') return 'nothing yet';
|
|
412
|
+
if (target && (m2(s, target))) return m2(s, target);
|
|
413
|
+
if (SIMPLE_PATH.test(s)) return pathWords(s);
|
|
414
|
+
return `\`${clip(s, 40)}\``;
|
|
415
|
+
}
|
|
416
|
+
function m2(s, target) {
|
|
417
|
+
// count + 1, !open, prev => prev + 1
|
|
418
|
+
let m;
|
|
419
|
+
if ((m = new RegExp(`^(?:\\(?\\w+\\)?\\s*=>\\s*)?(?:${target}|\\w+)\\s*([+-])\\s*(\\d+)$`).exec(s))) return `${words(target)} ${m[1] === '+' ? 'plus' : 'minus'} ${m[2]}`;
|
|
420
|
+
if ((m = new RegExp(`^!\\s*${target}$`).exec(s))) return `the opposite of ${words(target)}`;
|
|
421
|
+
return null;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/** A {…} child in JSX: a condition, a list, a value shown as text, or not read. */
|
|
425
|
+
function exprChild(n, ctx) {
|
|
426
|
+
let c = n.code.trim();
|
|
427
|
+
while (/^\(/.test(c) && matchBrace(c, 0) === c.length - 1) c = c.slice(1, -1).trim();
|
|
428
|
+
const jsxIn = (code) => {
|
|
429
|
+
const t = code.trim().replace(/^\(([\s\S]*)\)$/, '$1').trim();
|
|
430
|
+
if (t === 'null' || t === 'undefined' || t === 'false' || t === "''" || t === '""') return [];
|
|
431
|
+
if (t.startsWith('<')) { const r = parseJsx(t, 0); return r ? describe([shiftLines(r.node, n.line - 1)], ctx) : null; }
|
|
432
|
+
if (/^["'`]/.test(t) && skipString(t, 0) === t.length) return [{ says: `text: "${t.slice(1, -1)}"`, line: n.line }];
|
|
433
|
+
if (SIMPLE_PATH.test(t)) return [{ says: `text: {${pathWords(t)}}`, line: n.line }];
|
|
434
|
+
return null;
|
|
435
|
+
};
|
|
436
|
+
// cond && <X/>
|
|
437
|
+
const and = topLevelSplit(c, '&&');
|
|
438
|
+
if (and && /^\s*\(?\s*</.test(and[1])) { const then = jsxIn(and[1]); if (then) return [condLine(and[0], then, null, n.line, ctx)]; }
|
|
439
|
+
// cond ? A : B
|
|
440
|
+
const tern = ternary(c);
|
|
441
|
+
if (tern) { const a = jsxIn(tern[1]), b = jsxIn(tern[2]); if (a && b) return [condLine(tern[0], a, b.length ? b : null, n.line, ctx)]; }
|
|
442
|
+
// list.map((item) => <X/>)
|
|
443
|
+
const mp = /^([\s\S]+?)\.map\(\s*(?:\(\s*(\w+)(?:\s*,\s*\w+)?\s*\)|(\w+))\s*=>\s*([\s\S]+)\)$/.exec(c);
|
|
444
|
+
if (mp) {
|
|
445
|
+
let body = mp[4].trim();
|
|
446
|
+
const block = /^\{\s*return\s+([\s\S]*?);?\s*\}$/.exec(body);
|
|
447
|
+
if (block) body = block[1];
|
|
448
|
+
const kids = jsxIn(body);
|
|
449
|
+
if (kids) return [eachLine({ item: mp[2] ?? mp[3], list: mp[1].trim(), line: n.line }, kids)];
|
|
450
|
+
}
|
|
451
|
+
if (SIMPLE_PATH.test(c)) return [{ says: `text: {${pathWords(c)}}`, line: n.line }];
|
|
452
|
+
ctx.notRead.push({ line: n.line, code: clip(c), why: 'an expression in what it shows that Thunder does not read yet' });
|
|
453
|
+
return [{ says: `not read: \`{${clip(c, 60)}}\``, line: n.line, notRead: true, code: `{${clip(c, 60)}}` }];
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function topLevelSplit(c, op) {
|
|
457
|
+
let depth = 0;
|
|
458
|
+
for (let i = 0; i < c.length - 1; i++) {
|
|
459
|
+
const ch = c[i];
|
|
460
|
+
if (ch === '"' || ch === "'" || ch === '`') { i = skipString(c, i) - 1; continue; }
|
|
461
|
+
if (ch === '<' && jsxStartsAt(c, i)) return null; // JSX before the operator: not this shape
|
|
462
|
+
if ('([{'.includes(ch)) depth++; else if (')]}'.includes(ch)) depth--;
|
|
463
|
+
else if (depth === 0 && c.startsWith(op, i)) return [c.slice(0, i).trim(), c.slice(i + op.length).trim()];
|
|
464
|
+
}
|
|
465
|
+
return null;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function ternary(c) {
|
|
469
|
+
let depth = 0, q = -1;
|
|
470
|
+
for (let i = 0; i < c.length; i++) {
|
|
471
|
+
const ch = c[i];
|
|
472
|
+
if (ch === '"' || ch === "'" || ch === '`') { i = skipString(c, i) - 1; continue; }
|
|
473
|
+
if (ch === '<' && jsxStartsAt(c, i)) { const r = parseJsx(c, i); if (r) { i = r.end - 1; continue; } }
|
|
474
|
+
if ('([{'.includes(ch)) depth++; else if (')]}'.includes(ch)) depth--;
|
|
475
|
+
else if (depth === 0 && ch === '?' && c[i + 1] !== '.' && c[i + 1] !== '?' && q < 0) q = i;
|
|
476
|
+
else if (depth === 0 && ch === ':' && q >= 0) return [c.slice(0, q).trim(), c.slice(q + 1, i).trim(), c.slice(i + 1).trim()];
|
|
477
|
+
}
|
|
478
|
+
return null;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
function condLine(test, then, otherwise, line, ctx) {
|
|
482
|
+
const words0 = conditionWords(test);
|
|
483
|
+
const line0 = { says: `when ${words0}, it shows:`, line, kids: then.length ? then : [{ says: 'nothing', line }] };
|
|
484
|
+
if (otherwise) return { ...line0, otherwise: { says: 'otherwise, it shows:', line, kids: otherwise } };
|
|
485
|
+
return line0;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
function eachLine(n, kids, empty = null) {
|
|
489
|
+
const list = SIMPLE_PATH.test(n.list) ? pathWords(n.list) : `\`${clip(n.list, 40)}\``;
|
|
490
|
+
return { says: `one of these per ${words(n.item)} in ${list}:`, line: n.line, kids, ...(empty ? { otherwise: { says: `when ${list} is empty, it shows:`, line: n.line, kids: empty } } : {}) };
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
// ── Finding screens in a file ────────────────────────────────────────────────────────────────────────────────────
|
|
494
|
+
|
|
495
|
+
/** React components in a TS/JS file: capitalized functions or arrows that return JSX. */
|
|
496
|
+
function reactComponents(src) {
|
|
497
|
+
const out = [];
|
|
498
|
+
const seen = new Set();
|
|
499
|
+
const re = /(?:^|\n)[ \t]*(?:export\s+(?:default\s+)?)?(?:function\s+([A-Z]\w*)\s*(?:<[^>]*>)?\s*\(|(?:const|let)\s+([A-Z]\w*)\s*(?::[^=\n]+)?=\s*(?:(?:React\.)?(?:memo|forwardRef)\s*(?:<[^>]*>)?\(\s*)?(?:function\s*\w*\s*)?(?:async\s*)?(?:<[^>]*>)?\()/g;
|
|
500
|
+
let m;
|
|
501
|
+
while ((m = re.exec(src))) {
|
|
502
|
+
const name = m[1] ?? m[2];
|
|
503
|
+
const pOpen = m.index + m[0].length - 1;
|
|
504
|
+
const pClose = matchBrace(src, pOpen);
|
|
505
|
+
if (pClose < 0) continue;
|
|
506
|
+
let j = pClose + 1;
|
|
507
|
+
const ret = /^\s*(?::\s*[^={]+?)?\s*(=>)?\s*/.exec(src.slice(j));
|
|
508
|
+
j += ret[0].length;
|
|
509
|
+
let body, bodyStart, exprBody = false;
|
|
510
|
+
if (src[j] === '{') { const e = matchBrace(src, j); if (e < 0) continue; body = src.slice(j + 1, e); bodyStart = j + 1; }
|
|
511
|
+
else if (ret[1]) {
|
|
512
|
+
// An arrow whose body is one expression: `(…) => (<div/>)` or `=> <div/>`.
|
|
513
|
+
if (src[j] === '(') { const e = matchBrace(src, j); if (e < 0) continue; body = `return ${src.slice(j, e + 1)};`; bodyStart = j - 7; }
|
|
514
|
+
else if (src[j] === '<') { const r = parseJsx(src, j); if (!r) continue; body = `return ${src.slice(j, r.end)};`; bodyStart = j - 7; }
|
|
515
|
+
else continue;
|
|
516
|
+
exprBody = true;
|
|
517
|
+
} else continue;
|
|
518
|
+
if (!/\breturn\s*\(?\s*</.test(body)) continue;
|
|
519
|
+
if (seen.has(name)) continue;
|
|
520
|
+
seen.add(name);
|
|
521
|
+
out.push({ name, params: src.slice(pOpen + 1, pClose), body, bodyStart, start: m.index + (src[m.index] === '\n' ? 1 : 0), end: bodyStart + body.length, exprBody });
|
|
522
|
+
}
|
|
523
|
+
return out;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/** Top-level statements of a function body (by ; and newlines at depth 0), with their offsets. */
|
|
527
|
+
function topStatements(body) {
|
|
528
|
+
const out = [];
|
|
529
|
+
let depth = 0, start = 0;
|
|
530
|
+
for (let i = 0; i < body.length; i++) {
|
|
531
|
+
const c = body[i];
|
|
532
|
+
if (c === '"' || c === "'" || c === '`') { i = skipString(body, i) - 1; continue; }
|
|
533
|
+
if (c === '/' && body[i + 1] === '/') { const e = body.indexOf('\n', i); i = e < 0 ? body.length : e; continue; }
|
|
534
|
+
if (c === '<' && jsxStartsAt(body, i)) { const r = parseJsx(body, i); if (r) { i = r.end - 1; continue; } }
|
|
535
|
+
if ('([{'.includes(c)) depth++;
|
|
536
|
+
else if (')]}'.includes(c)) { depth--; if (depth === 0 && c === '}') { const rest = body.slice(i + 1).match(/^\s*(else\b)?/); if (!rest[1] && !/^\s*[).,;:?]/.test(body.slice(i + 1))) { out.push({ text: body.slice(start, i + 1).trim(), at: start }); start = i + 1; } } }
|
|
537
|
+
else if (depth === 0 && c === ';') { out.push({ text: body.slice(start, i).trim(), at: start }); start = i + 1; }
|
|
538
|
+
}
|
|
539
|
+
if (body.slice(start).trim()) out.push({ text: body.slice(start).trim(), at: start });
|
|
540
|
+
return out.filter((s) => s.text);
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
function startWords(init) {
|
|
544
|
+
const s = squash(init ?? '');
|
|
545
|
+
if (!s || s === 'undefined') return 'nothing';
|
|
546
|
+
return valueWords(s);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** A TypeScript type in words, for props and inputs. */
|
|
550
|
+
function typeWords(t) {
|
|
551
|
+
const s = squash(t ?? '').replace(/;$/, '');
|
|
552
|
+
if (!s) return null;
|
|
553
|
+
if (/=>/.test(s)) return 'an action to run';
|
|
554
|
+
if (s === 'string') return 'text';
|
|
555
|
+
if (/^\[\s*\]$/.test(s)) return 'a list';
|
|
556
|
+
if (s === 'number') return 'a number';
|
|
557
|
+
if (s === 'boolean') return 'yes or no';
|
|
558
|
+
let m;
|
|
559
|
+
if ((m = /^(\w+)\[\]$/.exec(s)) || (m = /^(?:Array|ReadonlyArray)<(\w+)>$/.exec(s))) return `a list of ${typeWords(m[1])?.replace(/^an? /, '') ?? m[1]}`;
|
|
560
|
+
if ((m = /^(.+?)\s*\|\s*(?:null|undefined)$/.exec(s))) return `${typeWords(m[1]) ?? m[1]}, or nothing`;
|
|
561
|
+
if (/^['"]/.test(s)) return `one of ${s.split('|').map((x) => x.trim()).join(', ')}`;
|
|
562
|
+
return /^[A-Z]/.test(s) ? `a ${s}` : s;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/** Fields of an interface or type alias in the file: name → { type, optional }. */
|
|
566
|
+
function typeFields(src, typeName) {
|
|
567
|
+
const m = new RegExp(`(?:interface\\s+${typeName}\\b[^{]*|type\\s+${typeName}\\s*=\\s*)\\{`).exec(src);
|
|
568
|
+
if (!m) return null;
|
|
569
|
+
const open = m.index + m[0].length - 1, close = matchBrace(src, open);
|
|
570
|
+
if (close < 0) return null;
|
|
571
|
+
const fields = new Map();
|
|
572
|
+
for (const f of src.slice(open + 1, close).split(/[;\n]/)) {
|
|
573
|
+
const fm = /^\s*(?:readonly\s+)?(\w+)(\?)?\s*:\s*(.+?)\s*,?\s*$/.exec(f);
|
|
574
|
+
if (fm) fields.set(fm[1], { type: fm[3], optional: !!fm[2] });
|
|
575
|
+
}
|
|
576
|
+
return fields;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
function reactScreen(file, src, comp, ctxBase) {
|
|
580
|
+
const ctx = { ...ctxBase, notRead: [], events: [], uses: new Set(), setters: new Map(), stateNames: new Set(), inputs: new Set(), outputs: new Set() };
|
|
581
|
+
const line0 = lineAt(src, comp.start);
|
|
582
|
+
// Inputs: destructured props, or props.x, with types from the props type when the file declares it.
|
|
583
|
+
const inputs = [];
|
|
584
|
+
const p = comp.params.trim();
|
|
585
|
+
const typed = /:\s*([A-Z]\w*)\s*$/.exec(p.replace(/=\s*\{\s*\}\s*$/, '').trim());
|
|
586
|
+
const fcType = /:\s*(?:React\.)?FC<\s*(\w+)\s*>/.exec(src.slice(comp.start, comp.start + 200));
|
|
587
|
+
const fields = typeFields(src, typed?.[1] ?? fcType?.[1] ?? `${comp.name}Props`) ?? new Map();
|
|
588
|
+
const destr = /^\{([\s\S]*)\}/.exec(p);
|
|
589
|
+
if (destr) {
|
|
590
|
+
for (const part of destr[1].split(',').map((x) => x.trim()).filter(Boolean)) {
|
|
591
|
+
if (part.startsWith('...')) { ctx.notRead.push({ line: line0, code: `{${clip(part)}}`, why: 'the rest of its props are passed on without names' }); continue; }
|
|
592
|
+
const nm = /^(\w+)(?:\s*:\s*\w+)?(?:\s*=\s*([\s\S]+))?$/.exec(part);
|
|
593
|
+
if (nm) inputs.push({ name: nm[1], ...(nm[2] ? { start: startWords(nm[2]) } : {}) });
|
|
594
|
+
}
|
|
595
|
+
} else if (/^(\w+)/.test(p)) {
|
|
596
|
+
const pn = /^(\w+)/.exec(p)[1];
|
|
597
|
+
const used = [...new Set([...comp.body.matchAll(new RegExp(`\\b${pn}\\.(\\w+)`, 'g'))].map((x) => x[1]))];
|
|
598
|
+
inputs.push(...used.filter((u) => u !== 'children' || true).map((name) => ({ name })));
|
|
599
|
+
}
|
|
600
|
+
for (const i of inputs) {
|
|
601
|
+
const f = fields.get(i.name);
|
|
602
|
+
i.label = words(i.name);
|
|
603
|
+
if (f) { i.kind = typeWords(f.type); if (f.optional) i.optional = true; }
|
|
604
|
+
if (/^on[A-Z]/.test(i.name) || i.kind === 'an action to run') i.callback = true;
|
|
605
|
+
ctx.inputs.add(i.name);
|
|
606
|
+
}
|
|
607
|
+
// State, context, and hooks.
|
|
608
|
+
const state = [];
|
|
609
|
+
const effects = [];
|
|
610
|
+
const early = [];
|
|
611
|
+
let main = null;
|
|
612
|
+
for (const st of topStatements(comp.body)) {
|
|
613
|
+
const t = st.text, line = lineAt(src, comp.bodyStart + st.at + (comp.body.slice(st.at).length - comp.body.slice(st.at).trimStart().length));
|
|
614
|
+
let m;
|
|
615
|
+
if ((m = /^(?:const|let)\s+\[\s*(\w+)\s*,\s*(\w+)\s*\]\s*=\s*(?:React\.)?useState(?:<[^>]*>)?\(([\s\S]*)\)$/.exec(t))) { state.push({ name: m[1], label: words(m[1]), start: startWords(m[3]), how: 'useState', line }); ctx.setters.set(m[2], m[1]); ctx.stateNames.add(m[1]); continue; }
|
|
616
|
+
if ((m = /^(?:const|let)\s+\[\s*(\w+)\s*,\s*(\w+)\s*\]\s*=\s*(?:React\.)?useReducer\(\s*(\w+)\s*,\s*([\s\S]*)\)$/.exec(t))) { state.push({ name: m[1], label: words(m[1]), start: startWords(m[4]), how: `useReducer (changed by ${words(m[3])} when ${words(m[2])} is called)`, line }); ctx.stateNames.add(m[1]); continue; }
|
|
617
|
+
if ((m = /^(?:const|let)\s+(\w+|\{[^}]*\})\s*=\s*(?:React\.)?useContext\(\s*(\w+)\s*\)$/.exec(t))) { state.push({ name: m[1], label: words(m[1].replace(/[{}]/g, '')), start: `from the app's ${words(m[2].replace(/Context$/, ''))}`, how: 'useContext', line }); continue; }
|
|
618
|
+
if ((m = /^(?:const|let)\s+(\w+)\s*=\s*(?:React\.)?useMemo\(\s*\(\)\s*=>\s*([\s\S]+?),\s*\[[^\]]*\]\s*\)$/.exec(t))) { state.push({ name: m[1], label: words(m[1]), start: `worked out from ${valueWords(m[2])}`, how: 'useMemo', line }); continue; }
|
|
619
|
+
if ((m = /^(?:const|let)\s+(\w+|\{[^}]*\}|\[[^\]]*\])\s*=\s*(use[A-Z]\w*)\(([\s\S]*)\)$/.exec(t)) && !/^use(State|Reducer|Context|Memo|Callback|Ref|Effect|LayoutEffect)$/.test(m[2])) { state.push({ name: m[1], label: words(m[1].replace(/[{}[\]]/g, '')), start: `from ${words(m[2])}`, how: m[2], line }); continue; }
|
|
620
|
+
if ((m = /^(?:React\.)?use(?:Layout)?Effect\(\s*(?:async\s*)?\(\)\s*=>\s*([\s\S]*?)(?:,\s*\[([^\]]*)\])?\s*\)$/.exec(t))) {
|
|
621
|
+
const deps = m[2] == null ? null : m[2].split(',').map((x) => x.trim()).filter(Boolean);
|
|
622
|
+
const when = deps == null ? 'After every change' : deps.length ? `When ${deps.map((d) => pathWords(d)).join(' or ')} changes` : 'When the screen first shows';
|
|
623
|
+
const bodyText = m[1].trim().replace(/^\{([\s\S]*)\}$/, '$1');
|
|
624
|
+
const runs = topStatements(bodyText).map((s) => statementWords(s.text.replace(/^await\s+/, ''), ctx));
|
|
625
|
+
effects.push({ when, runs: runs.every(Boolean) && runs.length ? runs.map((r) => r.text).join(', then ') : `runs \`${clip(bodyText, 60)}\``, line });
|
|
626
|
+
if (!runs.every(Boolean)) ctx.notRead.push({ line, code: clip(bodyText), why: 'what this effect does is not read yet' });
|
|
627
|
+
continue;
|
|
628
|
+
}
|
|
629
|
+
if ((m = /^if\s*\(([\s\S]+?)\)\s*(?:\{\s*)?return\s+([\s\S]*?);?\s*\}?$/.exec(t)) && !main) {
|
|
630
|
+
const r = m[2].trim();
|
|
631
|
+
const shows = r === 'null' || r === '' ? [] : r.replace(/^\(([\s\S]*)\)$/, '$1').trim().startsWith('<') ? (() => { const x = parseJsx(r.replace(/^\(([\s\S]*)\)$/, '$1').trim(), 0); return x ? describe([shiftLines(x.node, line - 1)], ctx) : null; })() : null;
|
|
632
|
+
if (shows) { early.push({ when: conditionWords(m[1]), shows, line }); continue; }
|
|
633
|
+
}
|
|
634
|
+
if ((m = /^return\s*\(?\s*</.exec(t))) {
|
|
635
|
+
const lead = comp.body.slice(st.at).length - comp.body.slice(st.at).trimStart().length;
|
|
636
|
+
const at = comp.bodyStart + st.at + lead + t.indexOf('<');
|
|
637
|
+
const r = parseJsx(src, at);
|
|
638
|
+
if (r) main = describe([r.node], ctx);
|
|
639
|
+
else ctx.notRead.push({ line, code: clip(t), why: 'what it shows could not be read' });
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
return {
|
|
643
|
+
framework: 'react', name: comp.name, label: cap(words(comp.name)), file, lines: [line0, lineAt(src, comp.end)],
|
|
644
|
+
inputs, state, shows: main ?? [], ...(early.length ? { early } : {}), events: ctx.events, effects, outputs: [],
|
|
645
|
+
uses: [...ctx.uses], notRead: ctx.notRead,
|
|
646
|
+
};
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/** Shift the line numbers of a tree parsed from a slice (so they match the file). */
|
|
650
|
+
function shiftLines(node, by) {
|
|
651
|
+
const s = (n) => { if (n.line) n.line += by; for (const k of n.kids ?? []) s(k); return n; };
|
|
652
|
+
return s(node);
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
/** Angular @Component classes in a file. `files` gives templateUrl files by path. */
|
|
656
|
+
function angularComponents(file, src, files) {
|
|
657
|
+
const out = [];
|
|
658
|
+
const re = /@Component\s*\(\s*\{/g;
|
|
659
|
+
let m;
|
|
660
|
+
while ((m = re.exec(src))) {
|
|
661
|
+
const open = m.index + m[0].length - 1, close = matchBrace(src, open);
|
|
662
|
+
if (close < 0) continue;
|
|
663
|
+
const meta = src.slice(open + 1, close);
|
|
664
|
+
const cls = /export\s+(?:default\s+)?class\s+(\w+)[^{]*\{/.exec(src.slice(close));
|
|
665
|
+
if (!cls) continue;
|
|
666
|
+
const cOpen = close + cls.index + cls[0].length - 1, cClose = matchBrace(src, cOpen);
|
|
667
|
+
const selector = /selector\s*:\s*['"`]([^'"`]+)['"`]/.exec(meta)?.[1] ?? null;
|
|
668
|
+
let template = null, templateAt = null, templateFile = null, missing = null;
|
|
669
|
+
const tm = /template\s*:\s*(`|'|")/.exec(meta);
|
|
670
|
+
if (tm) { const s = open + 1 + tm.index + tm[0].length - 1; const e = skipString(src, s); template = src.slice(s + 1, e - 1); templateAt = s + 1; }
|
|
671
|
+
const tu = /templateUrl\s*:\s*['"`]([^'"`]+)['"`]/.exec(meta);
|
|
672
|
+
if (tu) {
|
|
673
|
+
const dir = file.includes('/') ? file.slice(0, file.lastIndexOf('/') + 1) : '';
|
|
674
|
+
const want = normalize(dir + tu[1]);
|
|
675
|
+
const hit = files.find((f) => normalize(f.path) === want) ?? files.find((f) => f.path.endsWith(tu[1].replace(/^\.\//, '')));
|
|
676
|
+
if (hit) { template = hit.source; templateFile = hit.path; } else missing = tu[1];
|
|
677
|
+
}
|
|
678
|
+
out.push({ name: cls[1], selector, template, templateAt, templateFile, missing, start: m.index, classOpen: cOpen, classBody: src.slice(cOpen + 1, cClose), classEnd: cClose });
|
|
679
|
+
}
|
|
680
|
+
return out;
|
|
681
|
+
}
|
|
682
|
+
const normalize = (p) => { const out = []; for (const seg of p.split('/')) { if (seg === '..') out.pop(); else if (seg && seg !== '.') out.push(seg); } return out.join('/'); };
|
|
683
|
+
|
|
684
|
+
function angularScreen(file, src, comp, ctxBase) {
|
|
685
|
+
const ctx = { ...ctxBase, notRead: [], events: [], uses: new Set(), setters: new Map(), stateNames: new Set(), inputs: new Set(), outputs: new Set() };
|
|
686
|
+
const inputs = [], outputs = [], state = [], effects = [], services = [];
|
|
687
|
+
const body = comp.classBody;
|
|
688
|
+
const lineIn = (i) => lineAt(src, comp.classOpen + 1 + i);
|
|
689
|
+
let m;
|
|
690
|
+
const fieldRe = /(@Input\([^)]*\)\s*|@Output\(\)\s*)?(?:(?:public|private|protected|readonly|override)\s+)*(\w+)\s*([!?])?\s*(?::\s*([^=;\n]+?))?\s*(?:=\s*([^;\n]+))?;/g;
|
|
691
|
+
// Only class-level lines (depth 0 inside the class) are fields.
|
|
692
|
+
let depth = 0, k = 0;
|
|
693
|
+
const level0 = [];
|
|
694
|
+
for (let i = 0; i < body.length; i++) {
|
|
695
|
+
const c = body[i];
|
|
696
|
+
if (c === '"' || c === "'" || c === '`') { i = skipString(body, i) - 1; continue; }
|
|
697
|
+
if (c === '{' || c === '(' || c === '[') { if (depth === 0) level0.push([k, i]); depth++; }
|
|
698
|
+
else if (c === '}' || c === ')' || c === ']') { depth--; if (depth === 0) k = i + 1; }
|
|
699
|
+
}
|
|
700
|
+
level0.push([k, body.length]);
|
|
701
|
+
const flat = body.replace(/\{[^{}]*\}/g, (x) => ' '.repeat(x.length)); // method bodies blanked (one level)
|
|
702
|
+
while ((m = fieldRe.exec(flat))) {
|
|
703
|
+
const [, deco, name, mark, type, init] = m;
|
|
704
|
+
if (/^(constructor|if|return|for|while|switch|const|let|var)$/.test(name)) continue;
|
|
705
|
+
const before = flat.slice(Math.max(0, m.index - 2), m.index);
|
|
706
|
+
if (/[(.]/.test(before.trim().slice(-1))) continue;
|
|
707
|
+
const line = lineIn(m.index + (deco ? 0 : 0));
|
|
708
|
+
const initS = squash(body.slice(m.index, m.index + m[0].length).replace(/^[\s\S]*?=\s*/, '').replace(/;$/, ''));
|
|
709
|
+
if (deco?.startsWith('@Input')) { inputs.push({ name, label: words(name), ...(type ? { kind: typeWords(type) } : {}), ...(/required\s*:\s*true/.test(deco) || mark === '!' ? { required: true } : {}), ...(init ? { start: startWords(initS) } : {}), line }); ctx.inputs.add(name); continue; }
|
|
710
|
+
if (deco?.startsWith('@Output')) { outputs.push({ name, label: words(name), line }); ctx.outputs.add(name); continue; }
|
|
711
|
+
if (init) {
|
|
712
|
+
let s;
|
|
713
|
+
if ((s = /^input(?:\.required)?(?:<([^>]+)>)?\(([\s\S]*)\)$/.exec(initS))) { inputs.push({ name, label: words(name), ...(s[1] ? { kind: typeWords(s[1]) } : {}), ...(/^input\.required/.test(initS) ? { required: true } : s[2].trim() ? { start: startWords(s[2]) } : {}), line }); ctx.inputs.add(name); continue; }
|
|
714
|
+
if (/^output(?:<[^>]*>)?\(\)$/.test(initS) || /^new EventEmitter/.test(initS)) { outputs.push({ name, label: words(name), line }); ctx.outputs.add(name); continue; }
|
|
715
|
+
if ((s = /^signal(?:<[^>]*>)?\(([\s\S]*)\)$/.exec(initS))) { state.push({ name, label: words(name), start: startWords(s[1]), how: 'signal', line }); ctx.stateNames.add(name); continue; }
|
|
716
|
+
if ((s = /^computed\(\s*\(\)\s*=>\s*([\s\S]*)\)$/.exec(initS))) { state.push({ name, label: words(name), start: `worked out from ${valueWords(s[1].replace(/this\./g, ''))}`, how: 'computed', line }); continue; }
|
|
717
|
+
if (/^inject\(/.test(initS)) { services.push(/^inject\(\s*(\w+)/.exec(initS)?.[1] ?? name); continue; }
|
|
718
|
+
state.push({ name, label: words(name), start: startWords(initS), how: 'field', line }); ctx.stateNames.add(name); continue;
|
|
719
|
+
}
|
|
720
|
+
if (type && !/\(/.test(type)) { state.push({ name, label: words(name), ...(typeWords(type) ? { kind: typeWords(type) } : {}), start: 'nothing yet', how: 'field', line }); ctx.stateNames.add(name); }
|
|
721
|
+
}
|
|
722
|
+
const ctor = /constructor\s*\(([^)]*)\)/.exec(body);
|
|
723
|
+
if (ctor) for (const p of ctor[1].split(',')) { const pm = /(\w+)\s*:\s*(\w+)/.exec(p); if (pm) services.push(pm[2]); }
|
|
724
|
+
for (const [hook, when] of [['ngOnInit', 'When the screen first shows'], ['ngOnChanges', 'When an input changes'], ['ngAfterViewInit', 'After the screen is drawn'], ['ngOnDestroy', 'When the screen goes away']]) {
|
|
725
|
+
const hm = new RegExp(`\\b${hook}\\s*\\(`).exec(body);
|
|
726
|
+
if (hm) effects.push({ when, runs: `runs ${words(hook.replace(/^ng/, ''))} (its steps are in that function)`, member: ctx.memberOf(hook), line: lineIn(hm.index) });
|
|
727
|
+
}
|
|
728
|
+
let shows = [];
|
|
729
|
+
if (comp.template != null) {
|
|
730
|
+
const tree = parseTemplate(comp.template, comp.templateFile ? null : src, comp.templateAt ?? 0);
|
|
731
|
+
shows = describe(tree, ctx);
|
|
732
|
+
if (comp.templateFile) for (const e of [...ctx.events, ...ctx.notRead]) e.file = comp.templateFile;
|
|
733
|
+
} else if (comp.missing) ctx.notRead.push({ line: lineAt(src, comp.start), code: `templateUrl: '${comp.missing}'`, why: `its template file (${comp.missing}) was not among the files read` });
|
|
734
|
+
return {
|
|
735
|
+
framework: 'angular', name: comp.name, label: cap(words(comp.name.replace(/Component$/, ''))), file, lines: [lineAt(src, comp.start), lineAt(src, comp.classEnd)],
|
|
736
|
+
...(comp.selector ? { selector: comp.selector } : {}), ...(comp.templateFile ? { template: comp.templateFile } : {}),
|
|
737
|
+
inputs, state, shows, events: ctx.events, effects, outputs, ...(services.length ? { services: [...new Set(services)] } : {}),
|
|
738
|
+
uses: [...ctx.uses], notRead: ctx.notRead,
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/**
|
|
743
|
+
* The screens in a set of files: [{ id, framework, name, label, file, lines, inputs, state, shows, events, effects,
|
|
744
|
+
* outputs, uses, notRead, … }]. `members` (the model's) link events and effects to the functions they run.
|
|
745
|
+
*/
|
|
746
|
+
export function readScreens(files, { members = [] } = {}) {
|
|
747
|
+
const ts = files.filter((f) => /\.(tsx|jsx|ts|js|mjs)$/.test(f.path) && f.source);
|
|
748
|
+
// First pass: names and selectors, so a screen that shows another can name it.
|
|
749
|
+
const found = [];
|
|
750
|
+
for (const f of ts) {
|
|
751
|
+
const reacts = /<[A-Za-z]/.test(f.source) && /\.(tsx|jsx|js)$/.test(f.path) ? reactComponents(f.source) : [];
|
|
752
|
+
const angulars = /@Component\s*\(/.test(f.source) ? angularComponents(f.path, f.source, files) : [];
|
|
753
|
+
for (const c of reacts) found.push({ f, c, kind: 'react' });
|
|
754
|
+
for (const c of angulars) found.push({ f, c, kind: 'angular' });
|
|
755
|
+
}
|
|
756
|
+
const screensByName = new Map(found.map(({ c, kind }) => [c.name, { name: c.name, label: cap(words(kind === 'angular' ? c.name.replace(/Component$/, '') : c.name)) }]));
|
|
757
|
+
const selectors = new Map(found.filter((x) => x.kind === 'angular' && x.c.selector).map(({ c }) => [c.selector, screensByName.get(c.name)]));
|
|
758
|
+
const screens = [];
|
|
759
|
+
for (const { f, c, kind } of found) {
|
|
760
|
+
const memberOf = (name) => members.find((mm) => mm.file === f.path && mm.name === name)?.id ?? members.find((mm) => mm.name === name)?.id ?? null;
|
|
761
|
+
const base = { screensByName, selectors, memberOf };
|
|
762
|
+
let s;
|
|
763
|
+
try { s = kind === 'react' ? reactScreen(f.path, f.source, c, base) : angularScreen(f.path, f.source, c, base); }
|
|
764
|
+
catch (e) { s = { framework: kind, name: c.name, label: cap(words(c.name)), file: f.path, lines: [lineAt(f.source, c.start ?? 0), lineAt(f.source, c.start ?? 0)], inputs: [], state: [], shows: [], events: [], effects: [], outputs: [], uses: [], notRead: [{ line: lineAt(f.source, c.start ?? 0), code: c.name, why: `this screen could not be read: ${e.message}` }] }; }
|
|
765
|
+
for (const e of s.events) if (e.line == null) delete e.line;
|
|
766
|
+
for (const n of s.notRead) { if (n.line == null) delete n.line; }
|
|
767
|
+
screens.push({ id: `${f.path}#screen:${c.name}`, kind: 'screen', symbol: 'screen', ...s });
|
|
768
|
+
}
|
|
769
|
+
const byName = new Map(screens.map((s) => [s.name, s]));
|
|
770
|
+
const bySelector = new Map(screens.filter((s) => s.selector).map((s) => [s.selector, s]));
|
|
771
|
+
for (const s of screens) {
|
|
772
|
+
s.uses = s.uses.map((u) => { const t = byName.get(u) ?? bySelector.get(u); return t ? { id: t.id, label: t.label } : { label: u, outside: true }; });
|
|
773
|
+
s.usedBy = [];
|
|
774
|
+
}
|
|
775
|
+
for (const s of screens) for (const u of s.uses) if (u.id) { const t = screens.find((x) => x.id === u.id); if (t && !t.usedBy.some((x) => x.id === s.id)) t.usedBy.push({ id: s.id, label: s.label }); }
|
|
776
|
+
// Which screens are pages: a Next.js page file, or a component a router opens (Angular Routes, React Router).
|
|
777
|
+
// Otherwise "top" (no other screen shows it) or "part" (shown inside another screen). Never guessed from names.
|
|
778
|
+
const routed = routedNames(files);
|
|
779
|
+
for (const s of screens) {
|
|
780
|
+
const page = pageFile(s.file);
|
|
781
|
+
if (page) { s.role = 'page'; s.roleWhy = page; }
|
|
782
|
+
else if (routed.has(s.name)) { s.role = 'page'; s.roleWhy = `a router opens it (${routed.get(s.name)})`; }
|
|
783
|
+
else if (s.usedBy.length) { s.role = 'part'; s.roleWhy = `shown inside ${s.usedBy.map((u) => u.label).join(', ')}`; }
|
|
784
|
+
else { s.role = 'top'; s.roleWhy = 'no other screen here shows it'; }
|
|
785
|
+
}
|
|
786
|
+
return screens;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/** A Next.js page or layout file, in words; null for any other file. */
|
|
790
|
+
function pageFile(file) {
|
|
791
|
+
const f = file.replace(/\\/g, '/');
|
|
792
|
+
if (/(^|\/)app\/(.+\/)?page\.(tsx|jsx|ts|js)$/.test(f)) return 'a Next.js page file (app router)';
|
|
793
|
+
if (/(^|\/)pages\/(?!api\/)(?!_app\.|_document\.|_error\.)[^]*\.(tsx|jsx|ts|js)$/.test(f)) return 'a Next.js page file (pages folder)';
|
|
794
|
+
return null;
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/** Components a router opens: Angular `component: X` in Routes, React Router `element={<X` and `Component: X`. */
|
|
798
|
+
function routedNames(files) {
|
|
799
|
+
const out = new Map();
|
|
800
|
+
for (const f of files) {
|
|
801
|
+
const src = f.source ?? '';
|
|
802
|
+
if (/\bRoutes\b|RouterModule|provideRouter/.test(src)) for (const m of src.matchAll(/\bcomponent\s*:\s*([A-Z]\w*)/g)) if (!out.has(m[1])) out.set(m[1], `${f.path}, line ${lineAt(src, m.index)}`);
|
|
803
|
+
if (/<Route\b|createBrowserRouter|createRoutesFromElements/.test(src)) for (const m of src.matchAll(/(?:\belement\s*[=:]\s*\{?\s*<|\bComponent\s*:\s*)([A-Z]\w*)/g)) if (!out.has(m[1])) out.set(m[1], `${f.path}, line ${lineAt(src, m.index)}`);
|
|
804
|
+
}
|
|
805
|
+
return out;
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
// ── Text ─────────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
809
|
+
|
|
810
|
+
function outlineLines(items, depth, out) {
|
|
811
|
+
for (const it of items) {
|
|
812
|
+
out.push(`${' '.repeat(depth)}- ${it.says}${it.line ? ` (line ${it.line})` : ''}`);
|
|
813
|
+
if (it.kids) outlineLines(it.kids, depth + 1, out);
|
|
814
|
+
if (it.otherwise) { out.push(`${' '.repeat(depth)}- ${it.otherwise.says}`); outlineLines(it.otherwise.kids, depth + 1, out); }
|
|
815
|
+
}
|
|
816
|
+
return out;
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/** A screen as Thunder Text. */
|
|
820
|
+
export function screenText(s) {
|
|
821
|
+
const L = [`${s.label}: ${s.framework === 'react' ? 'a React' : 'an Angular'} screen${s.selector ? ` (<${s.selector}>)` : ''}`];
|
|
822
|
+
if (s.role === 'page') L.push(` It is a page: ${s.roleWhy}`);
|
|
823
|
+
if (s.inputs.length) L.push(` It receives: ${s.inputs.map((i) => `${i.label}${i.kind ? ` (${i.kind}${i.optional ? ', optional' : ''}${i.required ? ', required' : ''})` : i.required ? ' (required)' : ''}${i.start ? `, ${i.start} if not given` : ''}`).join('; ')}`);
|
|
824
|
+
if (s.state.length) L.push(` It remembers: ${s.state.map((x) => `${x.label}${x.start ? ` (${/^(from|worked out)/.test(x.start) ? x.start : `starts as ${x.start}`})` : ''}`).join('; ')}`);
|
|
825
|
+
if (s.services?.length) L.push(` It uses the services: ${s.services.join(', ')}`);
|
|
826
|
+
for (const e of s.early ?? []) { L.push(` When ${e.when}, it shows only:`); outlineLines(e.shows.length ? e.shows : [{ says: 'nothing' }], 2, L); }
|
|
827
|
+
if (s.shows.length) { L.push(' It shows:'); outlineLines(s.shows, 2, L); }
|
|
828
|
+
for (const e of s.effects) L.push(` ${e.when}: ${e.runs}${e.line ? ` (line ${e.line})` : ''}`);
|
|
829
|
+
if (s.outputs.length) L.push(` It sends: ${s.outputs.map((o) => `${o.label} (an event)`).join(', ')}`);
|
|
830
|
+
if (s.uses.length) L.push(` It shows these screens and components: ${s.uses.map((u) => u.label).join(', ')}`);
|
|
831
|
+
if (s.notRead.length) { L.push(' Not read:'); for (const n of s.notRead) L.push(` ${n.line ? `line ${n.line}: ` : ''}\`${n.code}\`: ${n.why}`); }
|
|
832
|
+
return `${L.join('\n')}\n`;
|
|
833
|
+
}
|