@clarity-js/port 0.0.0-stage → 1.5.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/src/react.js ADDED
@@ -0,0 +1,999 @@
1
+ /**
2
+ * @clarity-js/port — a React component, as a Clarity component.
3
+ *
4
+ * What a function component says can mostly be said again by rule: its props are parameters, a
5
+ * `useState` is a `state`, a `useMemo` a `computed`, `{ ok && <p/> }` a `<when>`, a `.map()` a
6
+ * `<list>`. This reads the component with TypeScript's parser (which reads JSX and TSX), writes the
7
+ * `.clarity` file those rules give, and keeps a list of what it did and of what it could not do by
8
+ * rule, each with its line. It does not guess: where a rule does not apply, the original code stays
9
+ * in the output with a TODO, and the list says so.
10
+ *
11
+ * `typescript` is handed in. Nothing here touches the disk.
12
+ *
13
+ * Author: Özdemir Şarman
14
+ */
15
+
16
+ import { createFiber, namedToHex } from './fiber.js';
17
+
18
+ /** React's names for attributes of plain elements → the DOM's. (What is not here is lower-cased when it starts a known pattern, else kept.) */
19
+ const ATTRIBUTE = {
20
+ className: 'class', htmlFor: 'for', tabIndex: 'tabindex', autoFocus: 'autofocus', readOnly: 'readonly', maxLength: 'maxlength', minLength: 'minlength',
21
+ colSpan: 'colspan', rowSpan: 'rowspan', srcSet: 'srcset', crossOrigin: 'crossorigin', autoComplete: 'autocomplete', spellCheck: 'spellcheck',
22
+ autoCapitalize: 'autocapitalize', contentEditable: 'contenteditable', inputMode: 'inputmode', enterKeyHint: 'enterkeyhint', noValidate: 'novalidate',
23
+ formAction: 'formaction', acceptCharset: 'accept-charset', httpEquiv: 'http-equiv', useMap: 'usemap', frameBorder: 'frameborder', allowFullScreen: 'allowfullscreen',
24
+ cellPadding: 'cellpadding', cellSpacing: 'cellspacing', dateTime: 'datetime', encType: 'enctype', hrefLang: 'hreflang', playsInline: 'playsinline', autoPlay: 'autoplay',
25
+ referrerPolicy: 'referrerpolicy', defaultValue: 'value', defaultChecked: 'checked',
26
+ // SVG's presentation attributes (viewBox, gradientUnits and the like are camel-cased in SVG itself, and stay)
27
+ strokeWidth: 'stroke-width', strokeLinecap: 'stroke-linecap', strokeLinejoin: 'stroke-linejoin', strokeDasharray: 'stroke-dasharray', strokeDashoffset: 'stroke-dashoffset',
28
+ strokeMiterlimit: 'stroke-miterlimit', strokeOpacity: 'stroke-opacity', fillOpacity: 'fill-opacity', fillRule: 'fill-rule', clipPath: 'clip-path', clipRule: 'clip-rule',
29
+ fontFamily: 'font-family', fontSize: 'font-size', fontWeight: 'font-weight', fontStyle: 'font-style', textAnchor: 'text-anchor', textDecoration: 'text-decoration',
30
+ dominantBaseline: 'dominant-baseline', alignmentBaseline: 'alignment-baseline', stopColor: 'stop-color', stopOpacity: 'stop-opacity', markerEnd: 'marker-end',
31
+ markerStart: 'marker-start', markerMid: 'marker-mid', pointerEvents: 'pointer-events', shapeRendering: 'shape-rendering', vectorEffect: 'vector-effect',
32
+ letterSpacing: 'letter-spacing', wordSpacing: 'word-spacing', floodColor: 'flood-color', floodOpacity: 'flood-opacity', lightingColor: 'lighting-color',
33
+ imageRendering: 'image-rendering', paintOrder: 'paint-order', colorInterpolationFilters: 'color-interpolation-filters', xlinkHref: 'xlink:href', xmlSpace: 'xml:space', xmlnsXlink: 'xmlns:xlink',
34
+ };
35
+ /** Style properties React leaves a bare number on; to every other one it adds `px`. */
36
+ const UNITLESS = new Set(['animationIterationCount', 'aspectRatio', 'borderImageOutset', 'borderImageSlice', 'borderImageWidth', 'boxFlex', 'boxFlexGroup', 'boxOrdinalGroup', 'columnCount', 'columns',
37
+ 'flex', 'flexGrow', 'flexPositive', 'flexShrink', 'flexNegative', 'flexOrder', 'gridArea', 'gridRow', 'gridRowEnd', 'gridRowSpan', 'gridRowStart', 'gridColumn', 'gridColumnEnd', 'gridColumnSpan',
38
+ 'gridColumnStart', 'fontWeight', 'lineClamp', 'lineHeight', 'opacity', 'order', 'orphans', 'scale', 'tabSize', 'widows', 'zIndex', 'zoom', 'fillOpacity', 'floodOpacity', 'stopOpacity',
39
+ 'strokeDasharray', 'strokeDashoffset', 'strokeMiterlimit', 'strokeOpacity', 'strokeWidth']);
40
+ /** React's event names that are not simply the DOM's with a capital. */
41
+ const EVENT = { doubleclick: 'dblclick' };
42
+ /** React's own types → what the DOM (or plain TypeScript) calls the same thing. `$1` is the first type argument. */
43
+ const REACT_TYPE = {
44
+ MouseEvent: 'MouseEvent', KeyboardEvent: 'KeyboardEvent', FocusEvent: 'FocusEvent', DragEvent: 'DragEvent', PointerEvent: 'PointerEvent', TouchEvent: 'TouchEvent',
45
+ WheelEvent: 'WheelEvent', ClipboardEvent: 'ClipboardEvent', AnimationEvent: 'AnimationEvent', TransitionEvent: 'TransitionEvent', UIEvent: 'UIEvent',
46
+ SyntheticEvent: 'Event', FormEvent: 'SubmitEvent', ChangeEvent: 'Event & { target: $1; currentTarget: $1 }', InputEvent: 'InputEvent',
47
+ CSSProperties: 'Partial<CSSStyleDeclaration>', ReactNode: 'unknown', ReactElement: 'Node', JSX: 'Node', Key: 'string | number',
48
+ Dispatch: '(value: $1) => void', SetStateAction: '$1', RefObject: '$1 | null', MutableRefObject: '$1',
49
+ MouseEventHandler: '(e: MouseEvent) => void', ChangeEventHandler: '(e: Event & { target: $1; currentTarget: $1 }) => void', KeyboardEventHandler: '(e: KeyboardEvent) => void',
50
+ FormEventHandler: '(e: SubmitEvent) => void', FocusEventHandler: '(e: FocusEvent) => void',
51
+ };
52
+ const HOOKS_WITHOUT_A_RULE = new Set(['useThree', 'useLoader', 'useGLTF', 'useTexture', 'useAnimations', 'useImperativeHandle', 'useSyncExternalStore', 'useTransition', 'useDeferredValue', 'useInsertionEffect', 'useOptimistic', 'useActionState', 'useFormStatus', 'use']);
53
+
54
+ /**
55
+ * @typedef {object} PortNote
56
+ * @property {number} line the line of the React file it is about
57
+ * @property {'done' | 'todo'} level done: a rule was applied; todo: this needs a person (or an AI) to finish
58
+ * @property {string} text
59
+ */
60
+
61
+ /**
62
+ * @typedef {object} PortResult
63
+ * @property {string | null} clarity the `.clarity` file; null when the file holds no component
64
+ * @property {{ name: string, code: string } | null} shared what stood beside the components (constants, helpers): a module of its own, for the `.clarity` file to import
65
+ * @property {string[]} components the components found, in order
66
+ * @property {PortNote[]} notes
67
+ */
68
+
69
+ /**
70
+ * Ports the function components of one React file.
71
+ *
72
+ * @param {string} source
73
+ * @param {object} options
74
+ * @param {object} options.typescript the `typescript` module
75
+ * @param {string} [options.filename] 'Card.tsx': its ending says whether types are kept (.tsx) or there are none (.jsx)
76
+ * @param {(specifier: string) => boolean} [options.isComponentFile] is the file an import names being ported too? (then the import gets `.clarity`). Default: a relative import whose default name starts with a capital.
77
+ * @returns {PortResult}
78
+ */
79
+ export function portReact(source, options = {}) {
80
+ const ts = options.typescript;
81
+ if (typeof ts?.createSourceFile !== 'function') throw new Error('portReact needs the `typescript` module with its JavaScript API (TypeScript 5 or 6; TypeScript 7.0 has none): portReact(source, { typescript })');
82
+ const filename = options.filename ?? 'Component.jsx';
83
+ const typed = /\.tsx?$/.test(filename);
84
+ const K = ts.SyntaxKind;
85
+ const sf = ts.createSourceFile(filename, source, ts.ScriptTarget.Latest, true, typed ? ts.ScriptKind.TSX : ts.ScriptKind.JSX);
86
+
87
+ const notes = [];
88
+ const lineOf = (node) => sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;
89
+ const note = (node, level, text) => { const line = lineOf(node); if (!notes.some((n) => n.line === line && n.level === level && n.text === text)) notes.push({ line, level, text }); };
90
+ const done = (node, text) => note(node, 'done', text);
91
+ const todo = (node, text) => note(node, 'todo', text);
92
+ const raw = (node) => source.slice(node.getStart(sf), node.end);
93
+ const isJsx = (n) => n && (n.kind === K.JsxElement || n.kind === K.JsxSelfClosingElement || n.kind === K.JsxFragment);
94
+ const unparen = (n) => { while (n && n.kind === K.ParenthesizedExpression) n = n.expression; return n; };
95
+ const holdsJsx = (n) => { let found = false; const walk = (x) => { if (found) return; if (isJsx(x)) { found = true; return; } ts.forEachChild(x, walk); }; walk(n); return found; };
96
+ const calleeName = (call) => (call.expression.kind === K.Identifier ? call.expression.text : call.expression.kind === K.PropertyAccessExpression && call.expression.expression.kind === K.Identifier && call.expression.expression.text === 'React' ? call.expression.name.text : null);
97
+
98
+ // ── which top-level things are components ──
99
+ /** The function of a component declaration, and its name: `function X() {}`, `const X = () => {}`, `const X = memo(() => {})`, `forwardRef`. */
100
+ function componentOf(statement) {
101
+ const named = (name, fn, wrapper) => (fn && /^[A-Z]/.test(name) && (fn.kind === K.FunctionDeclaration || fn.kind === K.ArrowFunction || fn.kind === K.FunctionExpression) && holdsJsx(fn) ? { name, fn, wrapper, statement } : null);
102
+ if (statement.kind === K.FunctionDeclaration && statement.name && statement.body) return named(statement.name.text, statement, null);
103
+ if (statement.kind === K.VariableStatement && statement.declarationList.declarations.length === 1) {
104
+ const d = statement.declarationList.declarations[0];
105
+ if (d.name.kind !== K.Identifier || !d.initializer) return null;
106
+ let init = unparen(d.initializer), wrapper = null;
107
+ while (init.kind === K.CallExpression && ['memo', 'forwardRef', 'observer'].includes(calleeName(init) ?? '') && init.arguments[0]) { wrapper = calleeName(init); init = unparen(init.arguments[0]); }
108
+ const got = named(d.name.text, init, wrapper);
109
+ if (got) got.annotation = d.type ?? null;
110
+ return got;
111
+ }
112
+ return null;
113
+ }
114
+
115
+ const fromReact = new Set(); // names this file imports from 'react' (ChangeEvent, FC, …)
116
+ const keptForTypes = new Set(); // names of a props type that could not be read: their imports stay
117
+ const ofReact = new Set(); // … `React` itself, and what it imports from react-dom (flushSync, createPortal)
118
+ let isFiber = false; // the file draws with React Three Fiber
119
+ const gl = new Set(); // what the ported code needs from @clarity-js/gl
120
+ let usesFrame = false; // … and `frame` from the game loop
121
+ const components = [], imports = [], types = [], others = [];
122
+ for (const s of sf.statements) {
123
+ if (s.kind === K.ImportDeclaration) {
124
+ if (s.moduleSpecifier.text === 'react') for (const e of s.importClause?.namedBindings?.elements ?? []) fromReact.add(e.name.text);
125
+ if (/^react(-dom)?(\/client)?$/.test(s.moduleSpecifier.text)) { const c = s.importClause; for (const n of [c?.name?.text, c?.namedBindings?.name?.text, ...(s.moduleSpecifier.text === 'react' ? [] : c?.namedBindings?.elements?.map((e) => e.name.text) ?? [])]) if (n) ofReact.add(n); }
126
+ if (/^@react-three\//.test(s.moduleSpecifier.text)) isFiber = true;
127
+ imports.push(s); continue;
128
+ }
129
+ if (s.kind === K.InterfaceDeclaration || s.kind === K.TypeAliasDeclaration) { types.push(s); continue; }
130
+ if (s.kind === K.ExportAssignment || s.kind === K.ExportDeclaration) continue; // `export default X`, `export { X }`: a .clarity file exports its components by itself
131
+ if (s.kind === K.ClassDeclaration && s.heritageClauses?.some((h) => /Component\b/.test(raw(h)))) { todo(s, `class ${s.name?.text ?? ''} is a class component: there is no rule for one (its state, its lifecycle methods and \`this\` have to be read and written again as state, onMount and actions)`); continue; }
132
+ const c = componentOf(s);
133
+ if (c) components.push(c); else others.push(s);
134
+ }
135
+
136
+ if (!components.length) return { clarity: null, shared: null, components: [], notes };
137
+
138
+ // A prop given another name inside the component (`{ rows: rawRows }`), while the component has a
139
+ // `rows` of its own. A Clarity parameter is called what the prop is called, so the component's
140
+ // own name moves out of its way: it is written again as `ownRows` in the source, everywhere in
141
+ // that component (inside it `rows` never meant the prop), and the file is read anew.
142
+ //
143
+ // Two smaller things are said again in the source first, each in a round of its own:
144
+ // `function Card(props) { const { title, tone = 'plain' } = props; … }` is `function Card({ title, tone = 'plain' })`
145
+ // (the props taken apart in the body are the parameters), and `const a = 1, b = 2;` is two statements.
146
+ const round = options.round ?? 0;
147
+ const again = (edits, more = () => {}) => {
148
+ let text = '', at = 0;
149
+ for (const e of edits.sort((x, y) => x.from - y.from)) { text += source.slice(at, e.from) + e.text; at = e.to; }
150
+ const r = portReact(text + source.slice(at), { ...options, round: round + 1 });
151
+ more(r);
152
+ r.notes.sort((x, y) => x.line - y.line);
153
+ return r;
154
+ };
155
+ if (round < 6) {
156
+ const moved = [], movedNotes = [];
157
+ for (const c of components) {
158
+ const first = c.fn.parameters[0];
159
+ if (first?.name.kind !== K.Identifier || c.fn.body?.kind !== K.Block) continue;
160
+ const name = first.name.text;
161
+ const st = c.fn.body.statements.find((x) => x.kind === K.VariableStatement && x.declarationList.declarations.length === 1 && x.declarationList.declarations[0].name.kind === K.ObjectBindingPattern && x.declarationList.declarations[0].initializer?.kind === K.Identifier && x.declarationList.declarations[0].initializer.text === name);
162
+ if (!st) continue;
163
+ const pattern = st.declarationList.declarations[0].name;
164
+ const reads = [];
165
+ let whole = 0;
166
+ (function find(n) {
167
+ if (n === st) return;
168
+ if (n.kind === K.Identifier && n.text === name) { const p = n.parent; if (p.kind === K.PropertyAccessExpression && p.expression === n) reads.push(p); else if (!(p.kind === K.PropertyAccessExpression && p.name === n) && !(p.kind === K.PropertyAssignment && p.name === n) && p.kind !== K.JsxAttribute) whole++; return; }
169
+ ts.forEachChild(n, find);
170
+ })(c.fn.body);
171
+ if (whole) continue; // handed on whole somewhere: it is left as it is, and said below
172
+ const keys = new Map(); // a prop's name → the name it has inside
173
+ for (const e of pattern.elements) if (!e.dotDotDotToken) keys.set(e.propertyName ? (e.propertyName.kind === K.StringLiteral ? e.propertyName.text : e.propertyName.getText(sf)) : e.name.getText(sf), e.name.kind === K.Identifier ? e.name.text : null);
174
+ const declared = new Set();
175
+ (function find(n) { if ((n.kind === K.VariableDeclaration || n.kind === K.Parameter || n.kind === K.BindingElement) && n.name.kind === K.Identifier) declared.add(n.name.text); if (n.kind === K.FunctionDeclaration && n.name) declared.add(n.name.text); ts.forEachChild(n, find); })(c.fn.body);
176
+ const extra = [], local = [];
177
+ let ok = true;
178
+ for (const r of reads) {
179
+ const key = r.name.text;
180
+ if (keys.has(key)) { if (keys.get(key)) local.push({ from: r.getStart(sf), to: r.end, text: keys.get(key) }); else ok = false; }
181
+ else if (declared.has(key)) ok = false; // `props.rows` beside a `rows` of the component's own: left for the rule that says it
182
+ else { if (!extra.includes(key)) extra.push(key); local.push({ from: r.getStart(sf), to: r.end, text: key }); }
183
+ }
184
+ if (!ok) continue;
185
+ // (written from its parts, on one line: a remark between two of them would swallow the rest of the line)
186
+ const parts = pattern.elements.map((e) => ({ rest: !!e.dotDotDotToken, text: raw(e).replace(/\s*\n\s*/g, ' ') }));
187
+ if (parts.some((x) => /\/\/|\/\*/.test(x.text))) continue;
188
+ const text = `{ ${[...parts.filter((x) => !x.rest).map((x) => x.text), ...extra, ...parts.filter((x) => x.rest).map((x) => x.text)].join(', ')} }`;
189
+ moved.push({ from: first.name.getStart(sf), to: first.name.end, text }, { from: st.getStart(sf), to: st.end, text: '\n'.repeat(raw(st).split('\n').length - 1) }, ...local);
190
+ movedNotes.push({ line: lineOf(st), level: 'done', text: `\`${name}\` taken apart at the top of ${c.name}: its parts are the parameters` });
191
+ }
192
+ if (moved.length) return again(moved, (r) => r.notes.push(...movedNotes));
193
+
194
+ const split = [];
195
+ for (const c of components) for (const st of c.fn.body?.kind === K.Block ? c.fn.body.statements : []) {
196
+ if (st.kind !== K.VariableStatement || st.declarationList.declarations.length < 2) continue;
197
+ const ds = st.declarationList.declarations, word = st.declarationList.flags & ts.NodeFlags.Const ? 'const' : st.declarationList.flags & ts.NodeFlags.Let ? 'let' : 'var';
198
+ for (let i = 1; i < ds.length; i++) split.push({ from: ds[i - 1].end, to: ds[i].getStart(sf), text: `; ${word} ` });
199
+ }
200
+ if (split.length) return again(split);
201
+
202
+ const edits = [], renamed = [];
203
+ for (const c of components) {
204
+ const first = c.fn.parameters[0];
205
+ if (first?.name.kind !== K.ObjectBindingPattern || !c.fn.body) continue;
206
+ const given = new Map(); // the prop's name → the name it has inside
207
+ for (const e of first.name.elements) if (e.propertyName?.kind === K.Identifier && e.name.kind === K.Identifier && e.propertyName.text !== e.name.text) given.set(e.propertyName.text, e.name.text);
208
+ if (!given.size) continue;
209
+ const declared = new Set();
210
+ (function find(n) {
211
+ if ((n.kind === K.VariableDeclaration || n.kind === K.Parameter || n.kind === K.BindingElement) && n.name.kind === K.Identifier) declared.add(n.name.text);
212
+ if ((n.kind === K.FunctionDeclaration || n.kind === K.ClassDeclaration) && n.name) declared.add(n.name.text);
213
+ ts.forEachChild(n, find);
214
+ })(c.fn.body);
215
+ const taken = new Set([...declared, ...first.name.elements.map((e) => (e.name.kind === K.Identifier ? e.name.text : ''))]);
216
+ for (const [prop, inside] of given) {
217
+ if (!declared.has(prop)) continue;
218
+ let own = `own${prop[0].toUpperCase()}${prop.slice(1)}`;
219
+ while (taken.has(own)) own += '_';
220
+ taken.add(own);
221
+ renamed.push({ line: lineOf(first), prop, inside, own, component: c.name });
222
+ (function find(n) {
223
+ if (n.kind === K.Identifier && n.text === prop) {
224
+ const p = n.parent;
225
+ const isKey = (p.kind === K.PropertyAccessExpression && p.name === n) || (p.kind === K.PropertyAssignment && p.name === n) || (p.kind === K.BindingElement && p.propertyName === n) || p.kind === K.JsxAttribute || (p.kind === K.MethodDeclaration && p.name === n) || (p.kind === K.PropertySignature && p.name === n) || (p.kind === K.QualifiedName && p.right === n);
226
+ if (!isKey) edits.push({ from: n.getStart(sf), to: n.end, text: p.kind === K.ShorthandPropertyAssignment || (p.kind === K.BindingElement && !p.propertyName && p.parent.kind === K.ObjectBindingPattern) ? `${prop}: ${own}` : own });
227
+ return;
228
+ }
229
+ ts.forEachChild(n, find);
230
+ })(c.fn.body);
231
+ }
232
+ }
233
+ if (edits.length) return again(edits, (r) => { for (const x of renamed) r.notes.push({ line: x.line, level: 'done', text: `the prop \`${x.prop}\` was called \`${x.inside}\` inside ${x.component}, which has its own \`${x.prop}\`: a parameter keeps the prop's name, so the component's own is \`${x.own}\` now. Give it a better name` }); });
234
+ }
235
+
236
+ // A name this file has of its own (a component called Scene, a helper called Mesh) keeps it: what
237
+ // @clarity-js/gl calls the same is imported under another name (`Scene as GlScene`).
238
+ const taken = new Set(components.map((c) => c.name));
239
+ for (const s of others) { if (s.kind === K.VariableStatement) for (const d of s.declarationList.declarations) { if (d.name.kind === K.Identifier) taken.add(d.name.text); } else if (s.name?.text) taken.add(s.name.text); }
240
+ for (const s of imports) { if (/^@react-three\/|^three$|^react(-dom)?(\/|$)/.test(s.moduleSpecifier.text)) continue; const c = s.importClause; if (c?.name) taken.add(c.name.text); for (const e of c?.namedBindings?.elements ?? []) taken.add(e.name.text); }
241
+ const local = (name) => (taken.has(name) ? `Gl${name}` : name);
242
+ for (const name of options.gl ?? []) gl.add(name);
243
+
244
+ // ── what stood beside the components goes to a module of its own ──
245
+ const base = filename.replace(/^.*[\\/]/, '').replace(/\.[jt]sx?$/, '');
246
+ const namesOf = (pattern, out = []) => {
247
+ if (pattern.kind === K.Identifier) out.push(pattern.text);
248
+ else for (const e of pattern.elements ?? []) if (e.name) namesOf(e.name, out);
249
+ return out;
250
+ };
251
+ const sharedNames = [];
252
+ let sharedCode = '';
253
+ for (const s of others) {
254
+ const text = raw(s);
255
+ let declared = [];
256
+ if (s.kind === K.VariableStatement) declared = s.declarationList.declarations.flatMap((d) => namesOf(d.name));
257
+ else if ((s.kind === K.FunctionDeclaration || s.kind === K.ClassDeclaration || s.kind === K.EnumDeclaration) && s.name) declared = [s.name.text];
258
+ sharedNames.push(...declared);
259
+ sharedCode += (declared.length && !/^export\b/.test(text) ? 'export ' : '') + text.replace(/^export\s+default\s+/, 'export ') + '\n\n';
260
+ }
261
+ const sharedName = `${base}.shared.${typed ? 'ts' : 'js'}`;
262
+
263
+ // ── imports ──
264
+ const coreNames = new Set(); // what the ported code needs from Clarity.js
265
+ const out = [];
266
+ const usedInShared = (name) => new RegExp(`\\b${name}\\b`).test(sharedCode);
267
+ let sharedImports = '';
268
+ for (const imp of imports) {
269
+ const spec = imp.moduleSpecifier.text;
270
+ if (spec === 'react' || spec === 'react-dom' || spec === 'react-dom/client' || spec === 'react/jsx-runtime') continue;
271
+ if (/^@react-three\/(fiber|drei)$/.test(spec) || (isFiber && spec === 'three')) continue; // what they gave is @clarity-js/gl's now
272
+ let text = raw(imp);
273
+ const clause = imp.importClause;
274
+ const relative = spec.startsWith('.');
275
+ const isComponent = options.isComponentFile ? options.isComponentFile(spec) : relative && !/\.(css|scss|sass|less|svg|png|jpe?g|gif|webp|json)$/.test(spec) && !!clause?.name && /^[A-Z]/.test(clause.name.text) && !/\.(js|ts)$/.test(spec);
276
+ if (isComponent) {
277
+ text = text.replace(/(['"])([^'"]+?)(?:\.[jt]sx?)?\1\s*;?\s*$/, (all, q, p) => `${q}${p}.clarity${q}`);
278
+ done(imp, `import of ${spec}: taken to be a component that is ported too, so it now names ${spec.replace(/\.[jt]sx?$/, '')}.clarity`);
279
+ }
280
+ out.push({ imp, text: text.replace(/;\s*$/, '') });
281
+ const locals = [clause?.name?.text, ...(clause?.namedBindings?.elements?.map((e) => e.name.text) ?? []), clause?.namedBindings?.name?.text].filter(Boolean);
282
+ if (locals.some(usedInShared)) sharedImports += raw(imp) + '\n';
283
+ }
284
+
285
+ // ── a component ──
286
+ function component(c) {
287
+ const fn = c.fn;
288
+ const lines = [];
289
+ const state = new Map(); // setter → state name
290
+ const writers = new Map(); // a call that writes a state (its setter, a reducer's dispatch) → that state
291
+ const follows = new Map(); // a computed → the states it is worked out from
292
+ const snaps = []; // the functions being written that read a state after setting it
293
+ const kept = new Map(); // a const that holds markup → the markup (written where it is shown)
294
+ const slots = new Set(); // props whose type says they are markup: named slots
295
+ const reactive = new Set(); // names whose reading follows a change: params, state, computed
296
+ const elementRefs = new Set(), boxes = new Set();
297
+ let propsName = null; // `props`, when the parameter is one name
298
+ let restProps = false; // … and it is handed on whole: it stays, as the rest parameter
299
+ const subst = new Map(); // an identifier → what to write for it (the parts of a destructured list row)
300
+
301
+ // refs put on an element are element refs; the others are boxes for a value
302
+ const onElement = new Set();
303
+ (function find(n) { if (n.kind === K.JsxAttribute && n.name.getText(sf) === 'ref' && n.initializer?.kind === K.JsxExpression && n.initializer.expression?.kind === K.Identifier) onElement.add(n.initializer.expression.text); ts.forEachChild(n, find); })(fn);
304
+
305
+ // ── code, said again: setters are assignments, a ref is its element, props are names ──
306
+ function code(node, inside = false) {
307
+ const start = node.getStart(sf);
308
+ const edits = [];
309
+ const visit = (n) => {
310
+ const e = edit(n);
311
+ if (e !== null) { edits.push({ from: n.getStart(sf), to: n.end, text: e }); return; }
312
+ ts.forEachChild(n, visit);
313
+ };
314
+ const whole = inside ? null : edit(node);
315
+ if (whole !== null) return whole;
316
+ ts.forEachChild(node, visit);
317
+ let text = '', at = start;
318
+ for (const e of edits.sort((a, b) => a.from - b.from)) { text += source.slice(at, e.from) + e.text; at = e.to; }
319
+ return text + source.slice(at, node.end);
320
+ }
321
+
322
+ const isFunction = (n) => n.kind === K.ArrowFunction || n.kind === K.FunctionExpression || n.kind === K.FunctionDeclaration || n.kind === K.MethodDeclaration;
323
+ const functionOf = (n) => { for (let p = n.parent; p; p = p.parent) if (isFunction(p)) return p; return null; };
324
+ const isRead = (n) => { const p = n.parent; return !((p.kind === K.PropertyAccessExpression && p.name === n) || (p.kind === K.PropertyAssignment && p.name === n) || (p.kind === K.Parameter && p.name === n) || (p.kind === K.VariableDeclaration && p.name === n) || p.kind === K.BindingElement || p.kind === K.JsxAttribute || (p.kind === K.CallExpression && p.expression === n)); };
325
+ /**
326
+ * In React a function sees the values of the render it was made in: after `setCount(count + 1)`,
327
+ * `count` is still the old value until the next render. Here an assignment is seen at once. So a
328
+ * function that reads a state (or something worked out from it) after setting it keeps the value
329
+ * from before: `{ name → { alias, after } }` for the names it has to read that way.
330
+ */
331
+ function staleReads(f) {
332
+ const firstWrite = new Map(); // state → where its first write ends
333
+ (function walk(n) {
334
+ if (n !== f && isFunction(n)) return; // what a function inside does, it does later
335
+ if (n.kind === K.CallExpression && n.expression.kind === K.Identifier && writers.has(n.expression.text)) { const st = writers.get(n.expression.text); if (!firstWrite.has(st)) firstWrite.set(st, n.end); }
336
+ ts.forEachChild(n, walk);
337
+ })(f.body);
338
+ const alias = new Map();
339
+ if (!firstWrite.size) return alias;
340
+ (function walk(n) {
341
+ if (n !== f && isFunction(n)) return;
342
+ if (n.kind === K.Identifier && isRead(n)) {
343
+ const states = firstWrite.has(n.text) ? [n.text] : [...(follows.get(n.text) ?? [])].filter((st) => firstWrite.has(st));
344
+ const after = Math.min(...states.map((st) => firstWrite.get(st)));
345
+ if (states.length && n.getStart(sf) >= after && !alias.has(n.text)) alias.set(n.text, { alias: `${n.text}Before`, after });
346
+ }
347
+ ts.forEachChild(n, walk);
348
+ })(f.body);
349
+ return alias;
350
+ }
351
+ /** A function's block, with the values it must read as they were taken at its top. */
352
+ function bodyOf(f) {
353
+ const alias = staleReads(f);
354
+ if (!alias.size) return block(f.body);
355
+ snaps.push({ fn: f, alias });
356
+ const text = block(f.body);
357
+ snaps.pop();
358
+ const names = [...alias.keys()];
359
+ done(f, `this function reads ${names.map((n) => `\`${n}\``).join(', ')} after setting ${names.length === 1 ? 'it' : 'state'}: in React that read gave the value from before the change, so the port reads ${names.map((n) => `\`${alias.get(n).alias}\``).join(', ')}, taken when the function starts. If the new value was meant, read \`${names[0]}\``);
360
+ return text.replace(/^\{/, `{\n ${names.map((n) => `const ${alias.get(n).alias} = ${n}`).join('; ')}`);
361
+ }
362
+
363
+ /** What to write instead of a node, or null to keep it (and look inside it). */
364
+ function edit(n) {
365
+ if (n.kind === K.CallExpression && n.expression.kind === K.Identifier && state.has(n.expression.text)) {
366
+ const name = state.get(n.expression.text), arg = n.arguments[0] ? unparen(n.arguments[0]) : null;
367
+ let value;
368
+ if (!arg) value = 'undefined';
369
+ else if ((arg.kind === K.ArrowFunction || arg.kind === K.FunctionExpression) && arg.parameters.length <= 1) {
370
+ const param = arg.parameters[0]?.name;
371
+ if (arg.kind === K.ArrowFunction && arg.body.kind !== K.Block && (!param || param.kind === K.Identifier)) {
372
+ // setN((n) => n + 1): the value it gives, with the old value read by its name
373
+ if (param && param.text !== name) subst.set(param.text, name);
374
+ value = code(unparen(arg.body));
375
+ if (param && param.text !== name) subst.delete(param.text);
376
+ if (unparen(arg.body).kind === K.ObjectLiteralExpression) value = `(${value})`.replace(/^\(\((.*)\)\)$/s, '($1)');
377
+ } else value = `(${code(arg)})(${name})`;
378
+ } else value = code(arg);
379
+ const statementLike = n.parent.kind === K.ExpressionStatement || (n.parent.kind === K.ArrowFunction && n.parent.body === n);
380
+ return statementLike ? `${name} = ${value}` : `(${name} = ${value})`;
381
+ }
382
+ // a setter handed on as a value (`onOpen={setOpen}`): a function that sets, as React's did (a function it is given works the new value out from the old)
383
+ if (n.kind === K.Identifier && state.has(n.text) && isRead(n) && n.parent.kind !== K.ShorthandPropertyAssignment) {
384
+ const name = state.get(n.text);
385
+ done(n, `${n.text} is handed on as a value: written as a function that sets \`${name}\``);
386
+ return `((next) => { ${name} = typeof next === 'function' ? next(${name}) : next })`;
387
+ }
388
+ if (n.kind === K.PropertyAccessExpression && n.name.text === 'current' && n.expression.kind === K.Identifier && (elementRefs.has(n.expression.text) || boxes.has(n.expression.text))) return n.expression.text;
389
+ if (n.kind === K.PropertyAccessExpression && propsName && !restProps && n.expression.kind === K.Identifier && n.expression.text === propsName) return n.name.text === 'children' ? 'children' : n.name.text;
390
+ // a 3D node's place: `.rotation.y` there is `.rotation[1]` here (a node's position, rotation and scale are arrays)
391
+ if (isFiber && n.kind === K.PropertyAccessExpression && /^[xyz]$/.test(n.name.text) && n.expression.kind === K.PropertyAccessExpression && /^(position|rotation|scale)$/.test(n.expression.name.text)) return `${code(n.expression)}[${'xyz'.indexOf(n.name.text)}]`;
392
+ if (isFiber && n.kind === K.CallExpression && n.expression.kind === K.PropertyAccessExpression && /^set(Scalar)?$/.test(n.expression.name.text) && n.expression.expression.kind === K.PropertyAccessExpression && /^(position|rotation|scale)$/.test(n.expression.expression.name.text)) {
393
+ const args = n.arguments.map((a) => code(a));
394
+ return n.expression.name.text === 'setScalar' ? `${code(n.expression.expression)}.fill(${args[0]})` : `Object.assign(${code(n.expression.expression)}, [${args.join(', ')}])`;
395
+ }
396
+ if (isFiber && n.kind === K.CallExpression && /^THREE\.MathUtils\.degToRad$/.test(raw(n.expression)) && n.arguments[0]) return `((${code(n.arguments[0])}) * Math.PI / 180)`;
397
+ if (n.kind === K.Identifier && snaps.length) {
398
+ const snap = snaps[snaps.length - 1], hit = snap.alias.get(n.text);
399
+ if (hit && n.getStart(sf) >= hit.after && functionOf(n) === snap.fn && isRead(n)) return n.parent.kind === K.ShorthandPropertyAssignment ? `${n.text}: ${hit.alias}` : hit.alias;
400
+ }
401
+ if ((n.kind === K.ArrowFunction || n.kind === K.FunctionExpression) && n.body.kind === K.Block && !snaps.some((x) => x.fn === n)) {
402
+ const alias = staleReads(n);
403
+ if (alias.size) {
404
+ snaps.push({ fn: n, alias });
405
+ const text = code(n, true);
406
+ snaps.pop();
407
+ const names = [...alias.keys()];
408
+ done(n, `this function reads ${names.map((x) => `\`${x}\``).join(', ')} after setting state: the port reads the value from before the change (${names.map((x) => alias.get(x).alias).join(', ')}), as React did`);
409
+ const at = n.body.getStart(sf) - n.getStart(sf);
410
+ return text.slice(0, at + 1) + ` ${names.map((x) => `const ${alias.get(x).alias} = ${x}`).join('; ')};` + text.slice(at + 1);
411
+ }
412
+ }
413
+ if (n.kind === K.Identifier && subst.has(n.text)) {
414
+ const p = n.parent;
415
+ const isName = (p.kind === K.PropertyAccessExpression && p.name === n) || (p.kind === K.PropertyAssignment && p.name === n) || (p.kind === K.Parameter && p.name === n) || (p.kind === K.VariableDeclaration && p.name === n) || p.kind === K.BindingElement || p.kind === K.JsxAttribute;
416
+ if (p.kind === K.ShorthandPropertyAssignment) return `${n.text}: ${subst.get(n.text)}`;
417
+ if (!isName) return subst.get(n.text);
418
+ }
419
+ if (n.kind === K.PropertyAssignment && n.parent.kind === K.ObjectLiteralExpression && n.parent.parent?.kind === K.JsxExpression && n.parent.parent.parent?.kind === K.JsxAttribute && n.parent.parent.parent.name.getText(sf) === 'style') {
420
+ const key = n.name.kind === K.Identifier ? n.name.text : n.name.kind === K.StringLiteral ? n.name.text : null;
421
+ const v = n.initializer.kind === K.PrefixUnaryExpression ? n.initializer.operand : n.initializer;
422
+ if (key && !key.startsWith('--') && !UNITLESS.has(key)) {
423
+ if (v.kind === K.NumericLiteral) { if (Number(v.text) !== 0) return `${raw(n.name)}: '${raw(n.initializer)}px'`; }
424
+ else if (v.kind !== K.StringLiteral && v.kind !== K.NoSubstitutionTemplateLiteral && v.kind !== K.TemplateExpression) done(n, `style: React adds \`px\` to a bare number; here a value is written as it is. If \`${key}\` is a number, add the unit`);
425
+ }
426
+ }
427
+ if (n.kind === K.TypeReference) {
428
+ const name = n.typeName.kind === K.QualifiedName && n.typeName.left.kind === K.Identifier && n.typeName.left.text === 'React' ? n.typeName.right.text
429
+ : n.typeName.kind === K.Identifier && fromReact.has(n.typeName.text) ? n.typeName.text : null;
430
+ if (name) {
431
+ const to = REACT_TYPE[name];
432
+ if (to) return to.replace(/\$1/g, n.typeArguments?.[0] ? code(n.typeArguments[0]) : 'HTMLElement');
433
+ todo(n, `the React type ${name} has no counterpart here: say what it is in the DOM's own terms`);
434
+ return 'unknown';
435
+ }
436
+ }
437
+ if (isJsx(n)) { todo(n, 'JSX kept in a value (a variable, an argument, a function\'s result): in Clarity markup lives in `render { }`. Make it a component, or a <when> where it is shown'); return `/* TODO(port): markup in a value */ null`; }
438
+ return null;
439
+ }
440
+ /** The states a piece of code is worked out from (through other computeds too). */
441
+ const statesIn = (node) => { const found = new Set(); (function walk(n) { if (n.kind === K.Identifier && isRead(n)) { if ([...writers.values()].includes(n.text)) found.add(n.text); for (const st of follows.get(n.text) ?? []) found.add(st); } ts.forEachChild(n, walk); })(node); return found; };
442
+ const reads = (node) => { let hit = false; (function walk(n) { if (hit) return; if (n.kind === K.Identifier && (reactive.has(n.text) || reactive.has(subst.get(n.text)) || (propsName && n.text === propsName)) && !(n.parent.kind === K.PropertyAccessExpression && n.parent.name === n) && !(n.parent.kind === K.PropertyAssignment && n.parent.name === n)) { hit = true; return; } ts.forEachChild(n, walk); })(node); return hit; };
443
+ /** How a part of a pattern is read from the whole: `.name`, or `['aria-label']` for a key that is not a name. */
444
+ const memberOf = (e) => { const key = e.propertyName ?? e.name; const text = key.kind === K.StringLiteral ? key.text : key.getText(sf); return /^[A-Za-z_$][\w$]*$/.test(text) ? `.${text}` : key.kind === K.ComputedPropertyName ? `[${code(key.expression)}]` : `[${JSON.stringify(text)}]`; };
445
+ const typeText = (t) => (typed && t ? `: ${code(t)}` : '');
446
+ const indent = (text, by) => text.split('\n').map((l, i) => (i === 0 || !l.trim() ? l : by + l)).join('\n');
447
+ /** A block's text, its lines moved left so that its closing brace is under its first line. (Whoever uses it indents it.) */
448
+ const block = (node) => {
449
+ const text = code(node);
450
+ const lineStart = source.lastIndexOf('\n', node.getStart(sf)) + 1;
451
+ const own = /^[ \t]*/.exec(source.slice(lineStart))[0].length;
452
+ return text.split('\n').map((l, i) => (i === 0 ? l : l.slice(Math.min(own, /^[ \t]*/.exec(l)[0].length)))).join('\n');
453
+ };
454
+
455
+ // ── parameters ──
456
+ const params = [];
457
+ const propTypes = new Map(); // a prop's name → { type, optional }
458
+ let propsInterface = null;
459
+ const readPropTypes = (typeNode) => {
460
+ if (!typeNode) return;
461
+ let members = typeNode.kind === K.TypeLiteral ? typeNode.members : null;
462
+ if (!members && typeNode.kind === K.TypeReference && typeNode.typeName.kind === K.Identifier) {
463
+ const name = typeNode.typeName.text;
464
+ if ((name === 'FC' || name === 'FunctionComponent' || name === 'PropsWithChildren') && typeNode.typeArguments?.[0]) return readPropTypes(typeNode.typeArguments[0]);
465
+ const decl = types.find((t) => t.name.text === name);
466
+ if (decl) { propsInterface = decl; members = decl.kind === K.InterfaceDeclaration ? decl.members : decl.type.kind === K.TypeLiteral ? decl.type.members : null; }
467
+ }
468
+ if (typeNode.kind === K.TypeReference && typeNode.typeName.kind === K.QualifiedName && /^(FC|FunctionComponent|PropsWithChildren)$/.test(typeNode.typeName.right.text) && typeNode.typeArguments?.[0]) return readPropTypes(typeNode.typeArguments[0]);
469
+ for (const m of members ?? []) if (m.kind === K.PropertySignature && m.name && m.type) propTypes.set(m.name.getText(sf), { type: code(m.type), optional: !!m.questionToken, markup: /\b(ReactNode|ReactElement|JSX\.Element)\b/.test(raw(m.type)) && !/=>/.test(raw(m.type)) });
470
+ };
471
+ const first = fn.parameters[0];
472
+ readPropTypes(first?.type ?? c.annotation);
473
+ // types that could not be read from this file: the parameters are written without them, and it is said
474
+ if (typed && (first?.type ?? c.annotation) && !propTypes.size && first) (function find(n) { if (n.kind === K.Identifier) keptForTypes.add(n.text); ts.forEachChild(n, find); })(first.type ?? c.annotation); // (its import stays, for whoever writes them)
475
+ if (typed && (first?.type ?? c.annotation) && !propTypes.size && first) todo(first, `the props' type (\`${raw(first.type ?? c.annotation).replace(/\s+/g, ' ').slice(0, 60)}\`) is not written out in this file (it is imported, or built from other types): the parameters have no types yet. Write them on the parameters`);
476
+ const typedParam = (name) => { const t = propTypes.get(name); return typed && t ? `${name}${t.optional ? '?' : ''}: ${t.type}` : name; };
477
+ let takesChildren = false;
478
+ if (first?.name.kind === K.ObjectBindingPattern) {
479
+ for (const e of first.name.elements) {
480
+ const name = e.name.kind === K.Identifier ? e.name.text : null;
481
+ if (!name) { todo(e, 'a prop taken apart in the parameter list: take the whole prop and read its parts in the component'); continue; }
482
+ const prop = e.propertyName ? (e.propertyName.kind === K.StringLiteral ? e.propertyName.text : e.propertyName.getText(sf)) : name;
483
+ if (e.dotDotDotToken) { params.push(`...${name}`); continue; }
484
+ if (!/^[A-Za-z_$][\w$]*$/.test(prop)) { todo(e, `the prop '${prop}' is not a name a parameter can have: here it arrives with what is left (\`...rest\`), so \`${name}\` is \`rest['${prop}']\``); continue; }
485
+ if (prop === 'children') { takesChildren = true; continue; }
486
+ if (propTypes.get(prop)?.markup) { slots.add(name); done(e, `the prop ${prop} is markup (by its type): it is the named slot "${prop}", which a caller fills with <template slot="${prop}">…</template>`); continue; }
487
+ if (prop !== name) subst.set(name, prop); // { title: heading } → the parameter is `title`
488
+ const t = propTypes.get(prop);
489
+ const initial = e.initializer ? (isFiber && /colou?r$/i.test(prop) ? namedToHex(code(e.initializer)) : code(e.initializer)) : null; // (a 3D colour here is '#rrggbb')
490
+ params.push(e.initializer ? `${prop}${typed && t ? `: ${t.type}` : ''} = ${initial}` : typedParam(prop));
491
+ reactive.add(prop);
492
+ }
493
+ } else if (first?.name.kind === K.Identifier) {
494
+ propsName = first.name.text;
495
+ // `props` handed on whole to one element (`<mesh {...props}>`): it is the rest parameter, and `props.x` reads from it
496
+ let whole = 0, spread = 0;
497
+ (function find(n) { if (n.kind === K.Identifier && n.text === propsName && n.parent !== first && !(n.parent.kind === K.PropertyAccessExpression && n.parent.expression === n)) { whole++; if (n.parent.kind === K.JsxSpreadAttribute) spread++; } ts.forEachChild(n, find); })(fn.body);
498
+ if (whole && whole === spread) { restProps = true; params.push(`...${propsName}`); done(first, `\`${propsName}\` is handed on whole: it is the rest parameter \`...${propsName}\``); }
499
+ }
500
+ if (restProps) {
501
+ /* nothing more to name */
502
+ } else if (first?.name.kind === K.Identifier) {
503
+ const used = new Set();
504
+ (function find(n) { if (n.kind === K.PropertyAccessExpression && n.expression.kind === K.Identifier && n.expression.text === propsName) used.add(n.name.text); ts.forEachChild(n, find); })(fn.body);
505
+ const names = propTypes.size ? [...propTypes.keys()] : [...used];
506
+ for (const name of names) {
507
+ if (name === 'children') { takesChildren = true; continue; }
508
+ if (!/^[A-Za-z_$][\w$]*$/.test(name)) continue; // 'aria-label', 'data-testid': not a name a parameter can have (they arrive with `...rest`)
509
+ if (propTypes.get(name)?.markup) { slots.add(name); done(first, `the prop ${name} is markup (by its type): it is the named slot "${name}"`); continue; }
510
+ params.push(typedParam(name)); reactive.add(name);
511
+ }
512
+ // `props` handed on whole (`{...props}`, `fn(props)`) has no name to become
513
+ (function find(n) { if (n.kind === K.Identifier && n.text === propsName && !(n.parent.kind === K.PropertyAccessExpression && n.parent.expression === n) && n.parent !== first) todo(n, `\`${propsName}\` is used whole here: a Clarity component names its parameters (\`...rest\` takes what is left)`); ts.forEachChild(n, find); })(fn.body);
514
+ }
515
+ if (c.wrapper === 'forwardRef') todo(fn, 'forwardRef: in Clarity a `ref` written on a component reaches the element that spreads `...rest`, so the second parameter is not needed; check where it was used');
516
+ if (c.wrapper === 'memo') done(fn, 'memo(): dropped. A Clarity component runs once; only what reads a changed value is updated');
517
+
518
+ // ── the body ──
519
+ const body = fn.body.kind === K.Block ? [...fn.body.statements] : [];
520
+ const returns = []; // [{ test: node | null, jsx: node }]
521
+ const decl = []; // lines of declarations, in order
522
+ const say = (text) => decl.push(text);
523
+
524
+ /** The hook a value comes from, seen through `(…)`, `!`, `as T` and `satisfies T`. */
525
+ const hookOf = (init) => { let e = init ? unparen(init) : null; while (e && (e.kind === K.NonNullExpression || e.kind === K.AsExpression || e.kind === K.SatisfiesExpression)) e = unparen(e.expression); return e?.kind === K.CallExpression ? { call: e, name: calleeName(e) } : null; };
526
+ const fnBodyAsBlock = (f) => (f.body.kind === K.Block ? bodyOf(f) : `{ return ${code(f.body)} }`);
527
+
528
+ for (const s of body) {
529
+ // return <jsx>, and the early ones
530
+ if (s.kind === K.ReturnStatement) { returns.push({ test: null, node: s.expression ? unparen(s.expression) : null, at: s }); continue; }
531
+ if (s.kind === K.IfStatement && !s.elseStatement) {
532
+ const inner = s.thenStatement.kind === K.Block ? (s.thenStatement.statements.length === 1 ? s.thenStatement.statements[0] : null) : s.thenStatement;
533
+ if (inner?.kind === K.ReturnStatement) { returns.push({ test: s.expression, node: inner.expression ? unparen(inner.expression) : null, at: s }); continue; }
534
+ }
535
+
536
+ if (s.kind === K.VariableStatement && s.declarationList.declarations.length === 1) {
537
+ const d = s.declarationList.declarations[0];
538
+ const hook = hookOf(d.initializer);
539
+ const args = hook?.call.arguments ?? [];
540
+
541
+ if (hook?.name === 'useState' && d.name.kind === K.ArrayBindingPattern) {
542
+ const [value, setter] = d.name.elements;
543
+ const name = value?.name?.text;
544
+ if (name) {
545
+ if (setter?.name) { state.set(setter.name.text, name); writers.set(setter.name.text, name); }
546
+ const init = args[0] ? unparen(args[0]) : null;
547
+ const lazy = init && init.kind === K.ArrowFunction && !init.parameters.length;
548
+ const first = !init ? 'undefined' : lazy ? (init.body.kind === K.Block ? `(${code(init)})()` : code(init.body)) : code(init);
549
+ say(`state ${name}${typeText(hook.call.typeArguments?.[0])} = ${first}`);
550
+ reactive.add(name);
551
+ continue;
552
+ }
553
+ }
554
+ if (hook?.name === 'useReducer' && d.name.kind === K.ArrayBindingPattern && args.length >= 2) {
555
+ const [value, dispatch] = d.name.elements;
556
+ if (value?.name && dispatch?.name) {
557
+ const name = value.name.text;
558
+ say(`state ${name} = ${args[2] ? `(${code(args[2])})(${code(args[1])})` : code(args[1])}`);
559
+ const reducerText = args[0].kind === K.Identifier ? code(args[0]) : `(${code(args[0])})`;
560
+ say(`action ${dispatch.name.text}(action${typed && args[0].kind === K.Identifier ? `: Parameters<typeof ${reducerText}>[1]` : ''}) { ${name} = ${reducerText}(${name}, action) }`);
561
+ reactive.add(name); writers.set(dispatch.name.text, name);
562
+ done(s, `useReducer: ${name} is a state, and ${dispatch.name.text}(action) an action that runs the reducer`);
563
+ continue;
564
+ }
565
+ }
566
+ if (hook?.name === 'useMemo' && d.name.kind === K.Identifier && args[0]) {
567
+ const f = unparen(args[0]);
568
+ const value = (f.kind === K.ArrowFunction || f.kind === K.FunctionExpression) ? (f.body.kind === K.Block ? `(${code(f)})()` : code(unparen(f.body))) : `(${code(f)})()`;
569
+ say(`computed ${d.name.text}${typeText(d.type ?? hook.call.typeArguments?.[0])} = ${/^\{/.test(value) ? `(${value})` : value}`);
570
+ reactive.add(d.name.text); follows.set(d.name.text, statesIn(f));
571
+ continue;
572
+ }
573
+ // const { rows, count } = useMemo(…), const [a, b] = useMemo(…): worked out once, and each part read from it
574
+ if (hook?.name === 'useMemo' && args[0] && (d.name.kind === K.ObjectBindingPattern || d.name.kind === K.ArrayBindingPattern) && d.name.elements.every((e) => e.kind === K.BindingElement && e.name.kind === K.Identifier && !e.dotDotDotToken && !e.initializer)) {
575
+ const f = unparen(args[0]);
576
+ const value = (f.kind === K.ArrowFunction || f.kind === K.FunctionExpression) ? (f.body.kind === K.Block ? `(${code(f)})()` : code(unparen(f.body))) : `(${code(f)})()`;
577
+ const names = d.name.elements.map((e) => e.name.text);
578
+ let whole = names.length <= 2 ? names.map((n, i) => (i ? n[0].toUpperCase() + n.slice(1) : n)).join('And') : `${names[0]}AndOthers`;
579
+ while (reactive.has(whole) || names.includes(whole)) whole += '_';
580
+ say(`computed ${whole} = ${/^\{/.test(value) ? `(${value})` : value}`);
581
+ reactive.add(whole); follows.set(whole, statesIn(f));
582
+ d.name.elements.forEach((e, i) => { say(`computed ${e.name.text} = ${whole}${d.name.kind === K.ArrayBindingPattern ? `[${i}]` : `${memberOf(e)}`}`); reactive.add(e.name.text); follows.set(e.name.text, statesIn(f)); });
583
+ done(s, `useMemo taken apart: the value is \`${whole}\`, and ${names.map((n) => `\`${n}\``).join(', ')} are read from it`);
584
+ continue;
585
+ }
586
+ // useEffectEvent(fn): a function that always sees the latest values. Every function does, here
587
+ if (hook?.name === 'useEffectEvent' && d.name.kind === K.Identifier && args[0]) {
588
+ const f = unparen(args[0]);
589
+ if (f.kind === K.ArrowFunction || f.kind === K.FunctionExpression) { say(functionAsAction(d.name.text, f)); continue; }
590
+ if (f.kind === K.Identifier) { say(`const ${d.name.text} = ${code(f)}`); continue; } // a function that has a name already
591
+ }
592
+ if (hook?.name === 'useCallback' && d.name.kind === K.Identifier && args[0]) {
593
+ const f = unparen(args[0]);
594
+ if (f.kind === K.ArrowFunction || f.kind === K.FunctionExpression) { say(functionAsAction(d.name.text, f)); continue; }
595
+ }
596
+ if (hook?.name === 'useRef' && d.name.kind === K.Identifier) {
597
+ const name = d.name.text, t = hook.call.typeArguments?.[0];
598
+ if (onElement.has(name)) { elementRefs.add(name); say(`ref ${name}${typeText(t)}`); }
599
+ else { boxes.add(name); say(`let ${name}${typed && t ? `: ${code(t)}${args[0] ? '' : ' | undefined'}` : ''} = ${args[0] ? code(args[0]) : 'undefined'}`); done(s, `useRef: ${name} is not put on an element, so it is a plain variable (\`${name}.current\` is \`${name}\`)`); }
600
+ continue;
601
+ }
602
+ if ((hook?.name === 'useContext' || hook?.name === 'useId') && (d.name.kind === K.Identifier || d.name.kind === K.ObjectBindingPattern || d.name.kind === K.ArrayBindingPattern)) {
603
+ coreNames.add(hook.name);
604
+ say(`const ${code(d.name)} = ${hook.name}(${args.map(code).join(', ')})`);
605
+ continue;
606
+ }
607
+ if (hook?.name && HOOKS_WITHOUT_A_RULE.has(hook.name)) {
608
+ todo(s, `${hook.name}: there is no rule for it`);
609
+ say(`// TODO(port): ${raw(s).split('\n')[0]}`);
610
+ continue;
611
+ }
612
+ if (hook?.name && /^use[A-Z]/.test(hook.name)) {
613
+ if (fromReact.has(hook.name) || (hook.call.expression.kind === K.PropertyAccessExpression && /^React\./.test(raw(hook.call.expression)))) todo(s, `${hook.name} is React's, and ${d.name.kind === K.Identifier ? 'there is no rule for it' : 'what it gives is taken apart here in a way there is no rule for'}. The call is kept as it is, and will not run`);
614
+ else todo(s, `${hook.name}() is a hook of this project: if it keeps state or runs effects it has to become a store, a plain function, or be written into the component. The call is kept as it is`);
615
+ say(`const ${code(d.name)} = ${code(d.initializer)} // TODO(port): a custom hook`);
616
+ for (const n of namesOf(d.name)) reactive.add(n);
617
+ continue;
618
+ }
619
+
620
+ // a function kept in a const
621
+ const init = d.initializer ? unparen(d.initializer) : null;
622
+ if (d.name.kind === K.Identifier && init && (isJsx(init) || ((init.kind === K.ConditionalExpression || init.kind === K.BinaryExpression) && holdsJsx(init)))) {
623
+ kept.set(d.name.text, init);
624
+ done(s, `${d.name.text} held markup: it is written where it is shown`);
625
+ continue;
626
+ }
627
+ if (d.name.kind === K.Identifier && init && (init.kind === K.ArrowFunction || init.kind === K.FunctionExpression)) { say(functionAsAction(d.name.text, init)); continue; }
628
+
629
+ // a value worked out while rendering: React works it out again on every render
630
+ if (init && reads(init)) {
631
+ if (d.name.kind === K.Identifier) { const value = code(init); say(`computed ${d.name.text}${typeText(d.type)} = ${/^\s*\{/.test(value) ? `(${value})` : value}`); reactive.add(d.name.text); follows.set(d.name.text, statesIn(init)); continue; }
632
+ if (d.name.kind === K.ObjectBindingPattern && d.name.elements.every((e) => e.name.kind === K.Identifier && !e.dotDotDotToken && !e.initializer)) {
633
+ const from = init.kind === K.Identifier ? code(init) : `(${code(init)})`;
634
+ for (const e of d.name.elements) { say(`computed ${e.name.text} = ${from}${memberOf(e)}`); reactive.add(e.name.text); follows.set(e.name.text, statesIn(init)); }
635
+ continue;
636
+ }
637
+ todo(s, 'a value taken apart from something that changes: it would be read once. Make each part a `computed`');
638
+ }
639
+ say(code(s).replace(/;\s*$/, ''));
640
+ continue;
641
+ }
642
+
643
+ // useEffect(…) and its kin, as statements
644
+ if (s.kind === K.ExpressionStatement) {
645
+ const hook = hookOf(s.expression);
646
+ if (hook && (hook.name === 'useEffect' || hook.name === 'useLayoutEffect') && hook.call.arguments[0]) {
647
+ const f = unparen(hook.call.arguments[0]), deps = hook.call.arguments[1] ? unparen(hook.call.arguments[1]) : null;
648
+ if (f.kind === K.ArrowFunction || f.kind === K.FunctionExpression) {
649
+ let bodyText = fnBodyAsBlock(f);
650
+ const touched = [...elementRefs].filter((r) => new RegExp(`\\b${r}\\b`).test(bodyText));
651
+ if (deps?.kind === K.ArrayLiteralExpression && deps.elements.length === 0) say(`onMount ${bodyText}`);
652
+ else {
653
+ const plain = deps?.kind === K.ArrayLiteralExpression && deps.elements.every((e) => e.kind === K.Identifier && reactive.has(e.text));
654
+ // An element is not there yet when an effect first runs: it waits for it.
655
+ if (touched.length) { bodyText = bodyText.replace(/^\{/, `{\n if (${touched.map((r) => `!${r}`).join(' || ')}) return`); done(s, `this effect reads the element ${touched.join(', ')}: it now waits until the element is there`); }
656
+ if (plain && !touched.length) say(`effect on (${deps.elements.map((e) => e.text).join(', ')}) ${bodyText}`);
657
+ else {
658
+ say(`effect ${bodyText}`);
659
+ if (deps && !plain) done(s, `useEffect with the dependencies ${raw(deps)}: written as \`effect { }\`, which follows whatever it reads. Check that it reads nothing it should not follow`);
660
+ }
661
+ }
662
+ continue;
663
+ }
664
+ }
665
+ if (hook?.name === 'useFrame' && hook.call.arguments[0]) {
666
+ const f = unparen(hook.call.arguments[0]);
667
+ if ((f.kind === K.ArrowFunction || f.kind === K.FunctionExpression) && f.parameters.every((p) => p.name.kind === K.Identifier)) {
668
+ const st = f.parameters[0]?.name.text ?? null, dt = f.parameters[1]?.name.text ?? 'dt';
669
+ let text = f.body.kind === K.Block ? bodyOf(f) : `{ ${code(f.body)} }`;
670
+ // the time since the start: three's clock there, the second argument here
671
+ let elapsed = false;
672
+ if (st) { text = text.replace(new RegExp(`\\b${st}\\.clock\\.(?:elapsedTime|getElapsedTime\\(\\))`, 'g'), () => { elapsed = true; return 'elapsed'; }); if (new RegExp(`\\b${st}\\b`).test(text)) todo(s, `useFrame's first argument (\`${st}\`: three.js's state) is used for more than the clock: the camera, the pointer and the renderer come from <Scene onCreated={ (api) => … }> here`); }
673
+ usesFrame = true;
674
+ say(`onMount {\n frame((${dt}${elapsed ? ', elapsed' : ''}) => ${text.split('\n').map((l, i) => (i ? ' ' + l : l)).join('\n')})\n}`);
675
+ done(s, 'useFrame: `frame((dt, elapsed) => …)` in onMount. A node\'s position, rotation and scale are arrays here, and a rotation is [pitch, heading, roll]');
676
+ continue;
677
+ }
678
+ }
679
+ if (hook?.name && (HOOKS_WITHOUT_A_RULE.has(hook.name) || /^use[A-Z]/.test(hook.name))) { todo(s, `${hook.name}: there is no rule for it`); say(`// TODO(port): ${raw(s).split('\n')[0]}`); continue; }
680
+ todo(s, 'a statement that ran on every render: in Clarity a component\'s body runs once. If it must follow a change, it is an `effect { }`');
681
+ say(`onMount { ${code(s).replace(/;\s*$/, '')} } // TODO(port): this ran on every render`);
682
+ continue;
683
+ }
684
+
685
+ if (s.kind === K.FunctionDeclaration && s.name) { say(functionAsAction(s.name.text, s)); continue; }
686
+ if (s.kind === K.InterfaceDeclaration || s.kind === K.TypeAliasDeclaration) { if (typed) say(raw(s)); continue; }
687
+
688
+ todo(s, 'this statement has no rule: it is kept as a comment');
689
+ say(raw(s).split('\n').map((l) => `// TODO(port): ${l}`).join('\n'));
690
+ }
691
+ if (fn.body.kind !== K.Block) returns.push({ test: null, node: unparen(fn.body), at: fn.body });
692
+
693
+ /** A function of the component: an action when it is statements, a const when it is one expression. */
694
+ function functionAsAction(name, f) {
695
+ const isAsync = !!f.modifiers?.some((m) => m.kind === K.AsyncKeyword);
696
+ const paramsText = f.parameters.map((p) => code(p)).join(', ');
697
+ const ret = typed && f.type ? `: ${code(f.type)}` : '';
698
+ if (f.body.kind === K.Block) return `action ${isAsync ? 'async ' : ''}${name}(${paramsText})${ret} ${bodyOf(f)}`;
699
+ return `const ${name} = ${isAsync ? 'async ' : ''}(${paramsText})${ret} => ${code(f.body)}`;
700
+ }
701
+
702
+ // ── the markup ──
703
+ const PAD = ' ';
704
+
705
+ /** A handler: `() => setN(n + 1)` is the statement itself; anything else is the function. */
706
+ function handlerText(e) {
707
+ const f = unparen(e);
708
+ if (f.kind === K.ArrowFunction && f.body.kind !== K.Block && !f.modifiers?.length) {
709
+ const param = f.parameters[0]?.name;
710
+ if (f.parameters.length === 0 || (f.parameters.length === 1 && param.kind === K.Identifier && param.text === 'e')) {
711
+ const text = code(unparen(f.body));
712
+ // (a statement in a handler is not parenthesised, and an object literal there would be a block)
713
+ if (unparen(f.body).kind !== K.ObjectLiteralExpression) return text;
714
+ }
715
+ }
716
+ return code(f);
717
+ }
718
+
719
+ function attributes(el, tag, isComponent) {
720
+ const list = el.attributes.properties;
721
+ const outAttrs = [];
722
+ const get = (name) => list.find((a) => a.kind === K.JsxAttribute && a.name.getText(sf) === name);
723
+ const exprOf = (a) => (a?.initializer?.kind === K.JsxExpression ? a.initializer.expression : null);
724
+
725
+ // value + onChange that writes it back: two-way
726
+ const skip = new Set();
727
+ if (!isComponent && (tag === 'input' || tag === 'textarea' || tag === 'select')) {
728
+ for (const [prop, field] of [['value', 'value'], ['checked', 'checked']]) {
729
+ const v = exprOf(get(prop)), h = exprOf(get('onChange'));
730
+ const f = h ? unparen(h) : null;
731
+ if (v?.kind !== K.Identifier || !f || f.kind !== K.ArrowFunction || f.parameters.length !== 1 || f.parameters[0].name.kind !== K.Identifier) continue;
732
+ const param = f.parameters[0].name.text;
733
+ const call = unparen(f.body.kind === K.Block && f.body.statements.length === 1 && f.body.statements[0].kind === K.ExpressionStatement ? f.body.statements[0].expression : f.body);
734
+ const written = (x) => { while (x && (x.kind === K.AsExpression || x.kind === K.NonNullExpression || x.kind === K.ParenthesizedExpression || x.kind === K.SatisfiesExpression)) x = x.expression; return x; };
735
+ const writes = call.kind === K.CallExpression && call.expression.kind === K.Identifier && state.get(call.expression.text) === v.text && call.arguments.length === 1
736
+ && new RegExp(`^${param}\\.(?:target|currentTarget)\\.${field}$`).test(raw(written(call.arguments[0])).replace(/\s+/g, ''));
737
+ if (writes) { outAttrs.push(`bind:${prop}={ ${v.text} }`); skip.add(get(prop)); skip.add(get('onChange')); done(el, `<${tag}> value and onChange that writes it back: \`bind:${prop}\``); }
738
+ }
739
+ }
740
+
741
+ for (const a of list) {
742
+ if (skip.has(a)) continue;
743
+ if (a.kind === K.JsxSpreadAttribute) { outAttrs.push(`{...${code(a.expression)}}`); continue; }
744
+ const name = a.name.getText(sf), init = a.initializer;
745
+ const value = !init ? null : init.kind === K.StringLiteral ? raw(init) : init.expression ? init.expression : null;
746
+ if (name === 'key') { if (!el.__listKey) done(a, 'key on an element outside a list: dropped (only a <list> has a key)'); continue; }
747
+ if (name === 'children') { todo(a, 'children handed over as a prop: write them inside the tag'); continue; }
748
+ if (name === 'dangerouslySetInnerHTML') { todo(a, 'dangerouslySetInnerHTML: set it yourself in onMount (`ref el`, then `el.innerHTML = …`), after making sure the text is safe'); continue; }
749
+ const event = /^on([A-Z]\w*)$/.exec(name);
750
+ if (event && typeof value !== 'string' && value) {
751
+ let type = event[1].toLowerCase();
752
+ type = EVENT[type] ?? type;
753
+ // React's onChange on a text field is the DOM's `input`
754
+ if (!isComponent && type === 'change' && (tag === 'textarea' || (tag === 'input' && !/^["'](checkbox|radio|file|range|color)["']$/.test(get('type')?.initializer ? raw(get('type').initializer) : '')))) type = 'input';
755
+ const written = isComponent ? event[1][0].toLowerCase() + event[1].slice(1) : type;
756
+ outAttrs.push(`on:${written}={ ${handlerText(value)} }`);
757
+ continue;
758
+ }
759
+ const attr = isComponent ? name : ATTRIBUTE[name] ?? name;
760
+ if (value === null) outAttrs.push(attr);
761
+ else if (typeof value === 'string') outAttrs.push(`${attr}=${value}`);
762
+ else {
763
+ if (holdsJsx(value) && isComponent) { todo(a, `the prop ${name} is handed markup: in Clarity that is a named slot (<template slot="${name}">…</template> inside the tag, <slot name="${name}" /> in the component)`); continue; }
764
+ outAttrs.push(`${attr}={ ${code(value)} }`);
765
+ }
766
+ }
767
+ return outAttrs.length ? ' ' + outAttrs.join(' ') : '';
768
+ }
769
+
770
+ // Markup is first a small tree: { text } | { code } | { open, close, children }. How it is laid
771
+ // out on the page is decided when it is printed, because in Clarity (as in HTML) a line break
772
+ // beside a piece of text is a space: an element that holds text is written on one line, so
773
+ // that "{ n }. { name }" does not become "1 . Ada".
774
+ const el = (open, close, children = []) => ({ open, close, children });
775
+
776
+ const fiber = isFiber ? createFiber({ ts, sf, code, raw, todo, done, handlerText, unparen, el, tree: (x) => tree(x), gl, local }) : null;
777
+
778
+ /** JSX text as React reads it: lines trimmed and joined by one space, blank lines gone. */
779
+ function jsxText(textNode) {
780
+ const lines = source.slice(textNode.pos, textNode.end).split(/\r\n|\n|\r/); // (from `pos`: the node's own start skips the white space that matters here)
781
+ const kept = [];
782
+ lines.forEach((line, i) => {
783
+ let l = line.replace(/\t/g, ' ');
784
+ if (i !== 0) l = l.replace(/^ +/, '');
785
+ if (i !== lines.length - 1) l = l.replace(/ +$/, '');
786
+ if (l) kept.push(l);
787
+ });
788
+ return kept.join(' ');
789
+ }
790
+
791
+ /** The tree of a piece of markup: a list of nodes. */
792
+ function tree(n) {
793
+ n = unparen(n);
794
+ if (!n || n.kind === K.NullKeyword || (n.kind === K.Identifier && n.text === 'undefined') || n.kind === K.FalseKeyword) return [];
795
+ if (n.kind === K.JsxText) { const text = jsxText(n); return text ? [{ text }] : []; }
796
+ if (n.kind === K.JsxExpression) return n.expression ? child(unparen(n.expression)) : [];
797
+ if (n.kind === K.JsxFragment) return [el('<>', '</>', n.children.flatMap(tree))];
798
+ if (n.kind === K.JsxSelfClosingElement || n.kind === K.JsxElement) {
799
+ const open = n.kind === K.JsxElement ? n.openingElement : n;
800
+ const tag = open.tagName.getText(sf);
801
+ const isComponent = /^[A-Z]/.test(tag) || tag.includes('.');
802
+ if (tag === 'React.Fragment' || tag === 'Fragment') return n.kind === K.JsxElement ? [el('<>', '</>', n.children.flatMap(tree))] : [];
803
+ if (fiber?.handles(tag)) return fiber.node(n);
804
+ const attrs = attributes(open, tag, isComponent);
805
+ if (n.kind === K.JsxSelfClosingElement) return [el(`<${tag}${attrs} />`, null)];
806
+ return [el(`<${tag}${attrs}>`, `</${tag}>`, n.children.flatMap(tree))];
807
+ }
808
+ return child(n);
809
+ }
810
+
811
+ /** What stands in `{ }` among children. */
812
+ function child(e) {
813
+ if (!e) return [];
814
+ if (isJsx(e)) return tree(e);
815
+ if (e.kind === K.JsxExpression) return child(unparen(e.expression));
816
+ if (e.kind === K.NullKeyword || e.kind === K.FalseKeyword || e.kind === K.TrueKeyword || (e.kind === K.Identifier && e.text === 'undefined')) return [];
817
+ if (e.kind === K.Identifier && e.text === 'children' && takesChildren) return [el('<slot />', null)];
818
+ if (e.kind === K.Identifier && kept.has(e.text)) return child(kept.get(e.text));
819
+ if (e.kind === K.Identifier && slots.has(e.text)) return [el(`<slot name="${e.text}" />`, null)];
820
+ const slotProp = e.kind === K.PropertyAccessExpression && propsName && e.expression.kind === K.Identifier && e.expression.text === propsName ? e.name.text : null;
821
+ if (slotProp && slots.has(slotProp)) return [el(`<slot name="${slotProp}" />`, null)];
822
+ // renderFooter(user), children(user): a function handed over that gives markup
823
+ if (e.kind === K.CallExpression) {
824
+ const called = e.expression.kind === K.Identifier ? e.expression.text : e.expression.kind === K.PropertyAccessExpression && propsName && e.expression.expression.kind === K.Identifier && e.expression.expression.text === propsName ? e.expression.name.text : null;
825
+ if (called && (/^render[A-Z]/.test(called) || called === 'children') && (reactive.has(called) || called === 'children')) {
826
+ const slot = called === 'children' ? null : called.replace(/^render/, '').replace(/^./, (c) => c.toLowerCase());
827
+ todo(e, `${called}(…) is a function that gives markup (a render prop): in Clarity that is a slot that hands values over: <slot${slot ? ` name="${slot}"` : ''} :value={ … } /> here, and <template${slot ? ` slot="${slot}"` : ''} let:value>…</template> where the component is used`);
828
+ }
829
+ }
830
+ if (e.kind === K.PropertyAccessExpression && propsName && e.expression.kind === K.Identifier && e.expression.text === propsName && e.name.text === 'children') return [el('<slot />', null)];
831
+ // a && <b/>
832
+ if (e.kind === K.BinaryExpression && e.operatorToken.kind === K.AmpersandAmpersandToken && holdsJsx(e.right)) return [el(`<when test={ ${code(e.left)} }>`, '</when>', child(unparen(e.right)))];
833
+ // a ? <b/> : <c/>
834
+ if (e.kind === K.ConditionalExpression && (holdsJsx(e.whenTrue) || holdsJsx(e.whenFalse))) {
835
+ const yes = child(unparen(e.whenTrue)), no = child(unparen(e.whenFalse));
836
+ if (!yes.length) return no.length ? [el(`<when test={ !(${code(e.condition)}) }>`, '</when>', no)] : [];
837
+ return [el(`<when test={ ${code(e.condition)} }>`, '</when>', no.length ? [...yes, el('<else>', '</else>', no)] : yes)];
838
+ }
839
+ // items.map((item, i) => <li key={item.id}>…</li>)
840
+ if (e.kind === K.CallExpression && e.expression.kind === K.PropertyAccessExpression && e.expression.name.text === 'map' && e.arguments.length >= 1) {
841
+ const f = unparen(e.arguments[0]);
842
+ if ((f.kind === K.ArrowFunction || f.kind === K.FunctionExpression) && f.parameters.length >= 1 && f.parameters.length <= 2) {
843
+ let row = f.body.kind === K.Block ? (f.body.statements.length === 1 && f.body.statements[0].kind === K.ReturnStatement ? f.body.statements[0].expression : null) : f.body;
844
+ row = row ? unparen(row) : null;
845
+ if (row && holdsJsx(row) && (isJsx(row) || row.kind === K.ConditionalExpression || row.kind === K.BinaryExpression)) {
846
+ const p0 = f.parameters[0].name, p1 = f.parameters[1]?.name;
847
+ let as = 'item';
848
+ const added = [];
849
+ if (p0.kind === K.Identifier) as = p0.text;
850
+ else if (p0.kind === K.ObjectBindingPattern && p0.elements.every((x) => x.name.kind === K.Identifier && !x.dotDotDotToken && !x.initializer)) {
851
+ for (const x of p0.elements) { subst.set(x.name.text, `${as}${memberOf(x)}`); added.push(x.name.text); }
852
+ done(f.parameters[0], `a list row taken apart (${raw(p0)}): the row is \`${as}\`, and its parts are read from it`);
853
+ } else todo(f.parameters[0], 'a list row taken apart in a way there is no rule for: the row is `item`, read its parts from it');
854
+ const index = p1?.kind === K.Identifier ? p1.text : null;
855
+ // the key comes off the row's first element and onto the list
856
+ let keyText = '';
857
+ const top = isJsx(row) ? (row.kind === K.JsxElement ? row.openingElement : row.kind === K.JsxSelfClosingElement ? row : null) : null;
858
+ const keyAttr = top?.attributes.properties.find((a) => a.kind === K.JsxAttribute && a.name.getText(sf) === 'key');
859
+ if (keyAttr?.initializer?.kind === K.JsxExpression && keyAttr.initializer.expression) {
860
+ const k = keyAttr.initializer.expression;
861
+ keyText = k.kind === K.Identifier && k.text === index ? '' : ` key={ ${code(k)} }`;
862
+ top.__listKey = true;
863
+ }
864
+ const made = el(`<list items={ ${code(e.expression.expression)} } as="${as}"${index ? ` index="${index}"` : ''}${keyText}>`, '</list>', child(row));
865
+ for (const name of added) subst.delete(name);
866
+ return [made];
867
+ }
868
+ }
869
+ }
870
+ if (holdsJsx(e)) { todo(e, 'markup inside an expression there is no rule for (a function that returns JSX, a switch, an object of elements): write it with <when>, <list> or a component'); return [{ code: '/* TODO(port) */ null' }]; }
871
+ return [{ code: code(e) }];
872
+ }
873
+
874
+ /** A node on one line. */
875
+ const inline = (n) => (n.text !== undefined ? n.text.replace(/[{}]/g, (c) => `{ "${c}" }`) : n.code !== undefined ? `{ ${n.code} }` : n.close === null ? n.open : n.open + n.children.map(inline).join('') + n.close);
876
+ /** The pieces of an opening tag: ['<Mesh', 'geometry="box"', 'args={ [1, 1, 1] }', '/>']. A space inside braces or quotes does not part two attributes. */
877
+ function pieces(open) {
878
+ const end = open.endsWith('/>') ? '/>' : '>';
879
+ const text = open.slice(0, -end.length).trimEnd(), out = [];
880
+ let depth = 0, quote = null, from = 0;
881
+ for (let i = 0; i < text.length; i++) {
882
+ const ch = text[i];
883
+ if (quote) { if (ch === '\\') i++; else if (ch === quote) quote = null; continue; }
884
+ if (ch === '"' || ch === "'" || ch === '`') quote = ch;
885
+ else if (ch === '{') depth++;
886
+ else if (ch === '}') depth--;
887
+ else if (ch === ' ' && depth === 0) { if (i > from) out.push(text.slice(from, i)); from = i + 1; }
888
+ }
889
+ if (from < text.length) out.push(text.slice(from));
890
+ return [...out, end];
891
+ }
892
+ /** An opening tag as lines: on one line when it fits in 100 columns, else one attribute to a line. */
893
+ function opening(open, pad, after = '') {
894
+ if ((pad + open + after).length <= 100 || open.includes('\n')) return [pad + open];
895
+ const parts = pieces(open);
896
+ if (parts.length < 4) return [pad + open]; // a name and one attribute: there is nothing to part
897
+ return [pad + parts[0], ...parts.slice(1, -1).map((a) => pad + PAD + a), pad + parts[parts.length - 1]];
898
+ }
899
+ /** Nodes as lines at `pad`. */
900
+ function print(nodes, pad) {
901
+ return nodes.flatMap((n) => {
902
+ if (n.text !== undefined || n.code !== undefined) return [pad + inline(n)];
903
+ if (n.close === null) return opening(n.open, pad);
904
+ if (!n.children.length) { const lines = opening(n.open, pad, n.close); lines[lines.length - 1] += n.close; return lines; }
905
+ // text among the children: on one line with the tag's end, as written (a line break beside text would be a space)
906
+ if (n.children.some((c) => c.text !== undefined)) { const rest = n.children.map(inline).join('') + n.close, lines = opening(n.open, pad, rest); lines[lines.length - 1] += rest; return lines; }
907
+ const one = inline(n);
908
+ if (n.children.length === 1 && n.children[0].code !== undefined && (pad + one).length <= 100) return [pad + one];
909
+ return [...opening(n.open, pad), ...print(n.children, pad + PAD), pad + n.close];
910
+ });
911
+ }
912
+
913
+ // the returns: the early ones are tests around what follows
914
+ const finalReturn = returns.find((r) => !r.test) ?? null;
915
+ const early = returns.filter((r) => r.test && returns.indexOf(r) < (finalReturn ? returns.indexOf(finalReturn) : returns.length));
916
+ function rendered(i) {
917
+ if (i >= early.length) return finalReturn?.node ? tree(finalReturn.node) : [];
918
+ const r = early[i];
919
+ const yes = r.node ? tree(r.node) : [], rest = rendered(i + 1);
920
+ if (!yes.length) return rest.length ? [el(`<when test={ !(${code(r.test)}) }>`, '</when>', rest)] : [];
921
+ return [el(`<when test={ ${code(r.test)} }>`, '</when>', rest.length ? [...yes, el('<else>', '</else>', rest)] : yes)];
922
+ }
923
+ if (early.length) done(early[0].at, `${early.length === 1 ? 'an early return' : `${early.length} early returns`}: written as <when> around what follows`);
924
+ const view = print(rendered(0), PAD + PAD);
925
+
926
+ lines.push(`component ${c.name}${typed && fn.typeParameters?.length ? `<${fn.typeParameters.map((t) => code(t)).join(', ')}>` : ''}(${params.join(', ')}) {`);
927
+ for (const d of decl) lines.push(PAD + indent(d, PAD));
928
+ if (decl.length) lines.push('');
929
+ lines.push(`${PAD}render {`);
930
+ lines.push(...(view.length ? view : [`${PAD + PAD}<></>`]));
931
+ lines.push(`${PAD}}`);
932
+ lines.push('}');
933
+ return { text: lines.join('\n'), propsInterface };
934
+ }
935
+
936
+ const made = components.map(component);
937
+
938
+ // ── the file ──
939
+ const body = made.map((m) => m.text).join('\n\n');
940
+ const mentions = (name, text) => new RegExp(`\\b${name}\\b`).test(text);
941
+ const isProps = (t) => made.some((m) => m.propsInterface === t) && !mentions(t.name.text, body + sharedCode);
942
+ const kept = typed ? types.filter((t) => !isProps(t)) : [];
943
+ // a type the module beside needs lives there (said once), and the component imports it when it uses it too
944
+ const inShared = sharedCode.trim() ? kept.filter((t) => mentions(t.name.text, sharedCode) || kept.some((u) => u !== t && mentions(u.name.text, sharedCode) && mentions(t.name.text, raw(u)))) : [];
945
+ const here = kept.filter((t) => !inShared.includes(t));
946
+
947
+ const top = [];
948
+ if (coreNames.size) top.push(`import { ${[...coreNames].sort().join(', ')} } from '@ozsarman/clarityjs'`);
949
+ if (gl.size) top.push(`import { ${[...gl].sort().map((n) => (local(n) === n ? n : `${n} as ${local(n)}`)).join(', ')} } from '@clarity-js/gl'`);
950
+ if (usesFrame) top.push(`import { frame } from '@ozsarman/clarityjs/game-loop'`);
951
+ // An import the React file used and the port no longer does (a hook that became a rule, a type that
952
+ // went with the props, a helper that moved to the module beside) is left out, name by name. One the
953
+ // React file never used is none of the port's business: it stays.
954
+ const usedBefore = new Set();
955
+ for (const st of sf.statements) if (st.kind !== K.ImportDeclaration) (function find(n) { if (n.kind === K.Identifier) usedBefore.add(n.text); ts.forEachChild(n, find); })(st);
956
+ const after = body + '\n' + here.map(raw).join('\n');
957
+ const stays = (name) => mentions(name, after) || !usedBefore.has(name) || keptForTypes.has(name);
958
+ for (const { imp, text } of out) {
959
+ const clause = imp.importClause;
960
+ if (!clause) { top.push(text); continue; } // imported for what it does (a stylesheet)
961
+ const def = clause.name && stays(clause.name.text) ? clause.name.text : null;
962
+ const nb = clause.namedBindings;
963
+ const names = nb?.kind === K.NamespaceImport ? (stays(nb.name.text) ? `* as ${nb.name.text}` : null) : nb ? (nb.elements.some((e) => stays(e.name.text)) ? `{ ${nb.elements.filter((e) => stays(e.name.text)).map(raw).join(', ')} }` : null) : null;
964
+ const all = (!clause.name || def) && (!nb || (nb.kind === K.NamespaceImport ? names : nb.elements.every((e) => stays(e.name.text))));
965
+ if (all) { top.push(text); continue; }
966
+ if (!def && !names) continue;
967
+ top.push(`import ${clause.isTypeOnly ? 'type ' : ''}${[def, names].filter(Boolean).join(', ')} from ${/from\s*(['"][^'"]+['"])\s*$/.exec(text)?.[1] ?? raw(imp.moduleSpecifier)}`);
968
+ }
969
+ // What is React's own and is still used after the rules (flushSync, createPortal, a hook called in
970
+ // a way no rule reads) would not run: it is said, at the line it is used.
971
+ const plain = body.replace(/\/\/.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '');
972
+ for (const name of new Set([...fromReact, ...ofReact])) {
973
+ if (coreNames.has(name) || !new RegExp(`(?<![.\\w$])${name.replace(/\$/g, '\\$')}(?![\\w$])`).test(plain) || notes.some((n) => n.level === 'todo' && n.text.includes(name))) continue;
974
+ let at = null;
975
+ for (const c of components) (function find(n) { if (at) return; if (n.kind === K.Identifier && n.text === name) { at = n; return; } ts.forEachChild(n, find); })(c.fn);
976
+ notes.push({ line: at ? lineOf(at) : 1, level: 'todo', text: `\`${name}\` is React's and is still used in the ported code: there is no rule for it here, and it is not imported any more` });
977
+ }
978
+ const sharedFrom = `./${typed ? sharedName.replace(/\.ts$/, '') : sharedName}`;
979
+ const fromShared = sharedNames.filter((n) => mentions(n, body));
980
+ const typesFromShared = inShared.map((t) => t.name.text).filter((n) => mentions(n, body + here.map(raw).join('\n')));
981
+ if (fromShared.length) top.push(`import { ${fromShared.join(', ')} } from '${sharedFrom}'`);
982
+ if (typesFromShared.length) top.push(`import type { ${typesFromShared.join(', ')} } from '${sharedFrom}'`);
983
+ const typeText = here.length ? here.map(raw).join('\n\n') + '\n\n' : '';
984
+ const clarity = (top.length ? top.join('\n') + '\n\n' : '') + typeText + body + '\n';
985
+
986
+ let shared = null;
987
+ if (sharedCode.trim()) {
988
+ const sharedPlain = sharedCode.replace(/\/\/.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '');
989
+ const inCore = [], lost = [];
990
+ for (const name of new Set([...fromReact, ...ofReact])) if (new RegExp(`(?<![.\\w$])${name.replace(/\$/g, '\\$')}(?![\\w$])`).test(sharedPlain)) (/^(createContext|useContext|useId)$/.test(name) ? inCore : lost).push(name);
991
+ if (inCore.length) sharedImports = `import { ${inCore.sort().join(', ')} } from '@ozsarman/clarityjs'\n` + sharedImports;
992
+ if (lost.length) notes.push({ line: lineOf(others[0]), level: 'todo', text: `${lost.map((n) => `\`${n}\``).join(', ')} (React's) ${lost.length === 1 ? 'is' : 'are'} used in what stood beside the component, now in ${sharedName}: there is no rule for ${lost.length === 1 ? 'it' : 'them'} there` });
993
+ const exported = (t) => (/^export\b/.test(raw(t)) ? raw(t) : 'export ' + raw(t));
994
+ shared = { name: sharedName, code: sharedImports + (sharedImports ? '\n' : '') + (inShared.length ? inShared.map(exported).join('\n') + '\n\n' : '') + sharedCode.trimEnd() + '\n' };
995
+ notes.push({ line: lineOf(others[0]), level: 'done', text: `what stood beside the component${components.length > 1 ? 's' : ''} (${sharedNames.join(', ') || 'statements'}) is in ${sharedName}: a .clarity file holds imports, types, stores and components` });
996
+ }
997
+ notes.sort((a, b) => a.line - b.line);
998
+ return { clarity, shared, components: components.map((c) => c.name), notes };
999
+ }