@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/README.md +253 -2
- package/bin/clarity-port.js +68 -0
- package/package.json +21 -4
- package/src/fiber.js +277 -0
- package/src/index.js +153 -0
- package/src/react.js +999 -0
- package/src/three.js +614 -0
package/README.md
CHANGED
|
@@ -1,3 +1,254 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @clarity-js/port
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Ports React components, React Three Fiber scenes and three.js scripts to
|
|
4
|
+
[Clarity.js](https://clarity-js.com), by rule.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
npx @clarity-js/port src/
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
Run it in the project you are porting. It reads every `.jsx` and `.tsx` file under the folder,
|
|
11
|
+
and every script there that builds a three.js scene, and writes a `.clarity` file beside each.
|
|
12
|
+
Your own files are not changed.
|
|
13
|
+
|
|
14
|
+
Every file it writes is compiled and linted, and the report says, per file, what is left for
|
|
15
|
+
you, with the line of the file it came from:
|
|
16
|
+
|
|
17
|
+
```
|
|
18
|
+
✓ src/Cart.jsx → src/Cart.clarity: compiles, nothing left to do
|
|
19
|
+
✓ src/Showcase.jsx → src/Showcase.clarity: compiles, nothing left to do
|
|
20
|
+
✓ src/Stepper.jsx → src/Stepper.clarity: compiles, nothing left to do
|
|
21
|
+
~ src/field.js → src/Field.clarity: compiles; 5 things left for you
|
|
22
|
+
line 30: `for (let i = 0; i < 40; i++) {…`: objects made in a loop: here that is a
|
|
23
|
+
<list> over data (an array of places), with one <Mesh> per row. The
|
|
24
|
+
statement is kept in the component as a comment
|
|
25
|
+
line 44: `const raycaster = new Raycaster();`: picking with a Raycaster: here a
|
|
26
|
+
<Mesh> hears `on:click` and the pointer events (the <Scene> already has
|
|
27
|
+
`events={ pointerEvents }`). The statement is kept in the component as a
|
|
28
|
+
comment
|
|
29
|
+
line 45: `const pointer = new Vector2();`: it uses three.js's `Vector2`, for which
|
|
30
|
+
there is no rule (the math and the helpers of @clarity-js/gl are in the
|
|
31
|
+
clarity-gl skill). The statement is kept in the component as a comment
|
|
32
|
+
line 46: `window.addEventListener('pointermove', (e) => {…`: it uses `pointer`,
|
|
33
|
+
which is not in the ported scene (made by a statement that is kept as a
|
|
34
|
+
comment, or not an object a rule could place). The statement is kept in the
|
|
35
|
+
component as a comment
|
|
36
|
+
line 54: `hub.material.emissiveIntensity = Math.sin(time * 0.002);`: it uses
|
|
37
|
+
`hub.material`: a node here is told its position, rotation, scale and
|
|
38
|
+
whether it is seen. A colour or a material's setting is a prop of the
|
|
39
|
+
<Mesh>, bound to a state. The statement is kept as a comment
|
|
40
|
+
lint src/Field.clarity:43:5 missing-cleanup: A listener on window is started here
|
|
41
|
+
and nothing in Field stops it (removeEventListener), so
|
|
42
|
+
it lives on after the component is gone. Stop it in
|
|
43
|
+
onCleanup { }, or return a function from onMount.
|
|
44
|
+
✓ src/spin-top.js → src/SpinTop.clarity: compiles, nothing left to do
|
|
45
|
+
|
|
46
|
+
5 files: 4 ported, 1 with things left for you.
|
|
47
|
+
A port is by rule: read each file once, and use the page.
|
|
48
|
+
The lines above say where a rule did not reach.
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
A port is by rule: a rule either applies or it does not, and where none does the tool says so
|
|
52
|
+
and leaves a `// TODO(port):` remark in the file. It does not guess. Read each file once and
|
|
53
|
+
use the page before you delete the original.
|
|
54
|
+
|
|
55
|
+
The whole of it, with a React component and a scene before and after: [clarity-js.com/docs/porting](https://clarity-js.com/docs/porting).
|
|
56
|
+
|
|
57
|
+
## Options
|
|
58
|
+
|
|
59
|
+
| | |
|
|
60
|
+
|---|---|
|
|
61
|
+
| `clarity-port <file or folder>…` | Port these. A script you name on its own is always tried; in a folder a `.js`, `.mjs` or `.ts` file is taken only when it imports `three` and makes a `Scene`. Tests and stories are left out. |
|
|
62
|
+
| `--out <folder>` | Write there instead of beside each source. The files keep their places under the folder you gave. |
|
|
63
|
+
| `--dry` | Write nothing: only the report. |
|
|
64
|
+
| `--verbose` | Also say which rules were applied (an early return became a `<when>`, a model loader became `<Model>`). |
|
|
65
|
+
| `--json` | The report as JSON. |
|
|
66
|
+
|
|
67
|
+
It reads the files with TypeScript's JavaScript API: your project's `typescript` when it has
|
|
68
|
+
one with that API (TypeScript 5 or 6, or the 6.0 API as `@typescript/typescript6` beside
|
|
69
|
+
TypeScript 7, which has none yet), otherwise the one it came with. It compiles and lints what it
|
|
70
|
+
writes with your project's `@ozsarman/clarityjs` when it has one, otherwise its own.
|
|
71
|
+
|
|
72
|
+
## A React component
|
|
73
|
+
|
|
74
|
+
| React | Clarity |
|
|
75
|
+
|---|---|
|
|
76
|
+
| `function Card({ title, tone = 'plain', ...rest })`, or `props` taken apart at the top of the body | `component Card(title, tone = 'plain', ...rest)`; with TypeScript the props interface becomes the parameters' types, and a generic component keeps its type parameters |
|
|
77
|
+
| `useState` | `state`; `setN(n + 1)` and `setN((n) => n + 1)` become `n = n + 1`; a setter handed on as a value (`onOpen={setOpen}`) is a function that sets |
|
|
78
|
+
| `useMemo`, and a `const` worked out from state or props in the body | `computed` |
|
|
79
|
+
| `useCallback`, `useEffectEvent`, a function in the body | `action`, or a `const` |
|
|
80
|
+
| `useRef` on an element | `ref` (`.current` goes); any other `useRef` is a plain `let` |
|
|
81
|
+
| `useEffect(…, [])` | `onMount`; what it returns still cleans up |
|
|
82
|
+
| `useEffect(…, [a, b])` | `effect on (a, b)`; with no plain list, `effect { }`, which follows what it reads |
|
|
83
|
+
| `useReducer` | a `state` and an `action dispatch` |
|
|
84
|
+
| `useContext`, `useId` | the same names from `@ozsarman/clarityjs` |
|
|
85
|
+
| an early `return <p>…</p>` | `<when>` around what follows |
|
|
86
|
+
| `className`, `htmlFor`, `onClick`, `style={{ width: 8 }}` | `class`, `for`, `on:click`, `style={ { width: '8px' } }` (React adds `px` to a bare number; here it is written out) |
|
|
87
|
+
| `value={v} onChange={(e) => setV(e.target.value)}` | `bind:value={ v }` |
|
|
88
|
+
| `{ ok && <A /> }`, `{ ok ? <A /> : <B /> }` | `<when test={ ok }>`, with `<else>` |
|
|
89
|
+
| `items.map((it) => <li key={it.id}>…</li>)` | `<list items={ items } as="it" key={ it.id }>` |
|
|
90
|
+
| `{children}`, a prop that takes markup | `<slot />`, a named slot |
|
|
91
|
+
| helpers and constants beside the component | a module of their own, `Card.shared.js`, that the component imports |
|
|
92
|
+
|
|
93
|
+
Three places where the same words mean something else, and what the tool does about them:
|
|
94
|
+
|
|
95
|
+
- **A function that reads a state after setting it.** In React that read gives the value from
|
|
96
|
+
before the change. Where a function does that, the port reads a `<name>Before` taken when the
|
|
97
|
+
function starts, and says so. If you meant the new value, read the state itself.
|
|
98
|
+
- **A prop with another name inside.** `{ rows: rawRows }`, in a component that has its own
|
|
99
|
+
`rows`. A Clarity parameter is called what the prop is called, so the component's own name
|
|
100
|
+
moves out of its way (`ownRows`), and the report says so.
|
|
101
|
+
- **Text.** In JSX a line break beside a piece of text is dropped; in Clarity, as in HTML, it
|
|
102
|
+
is a space. An element that holds text is written on one line so that nothing moves apart.
|
|
103
|
+
|
|
104
|
+
What has no rule, and is said: class components, your own hooks, render props,
|
|
105
|
+
`useImperativeHandle`, `forwardRef`, `dangerouslySetInnerHTML`, JSX kept in a variable or made
|
|
106
|
+
by a function, `flushSync` and `createPortal`, a props type that is imported (the parameters are
|
|
107
|
+
written without types), CSS-in-JS.
|
|
108
|
+
|
|
109
|
+
An import the port no longer uses is left out, name by name; one your file never used stays.
|
|
110
|
+
|
|
111
|
+
## A React Three Fiber scene
|
|
112
|
+
|
|
113
|
+
A file that imports from `@react-three/fiber` comes out as
|
|
114
|
+
[`@clarity-js/gl`](https://clarity-js.com/docs/graphics) markup.
|
|
115
|
+
|
|
116
|
+
| React Three Fiber | @clarity-js/gl |
|
|
117
|
+
|---|---|
|
|
118
|
+
| `<Canvas camera shadows>` | `<Scene camera shadows>`; `<color attach="background">` and `<fog>` become its `background` and `fog` |
|
|
119
|
+
| `<mesh>` with `<boxGeometry args={[1, 1, 1]} />` and `<meshStandardMaterial color="tomato" />` | one `<Mesh geometry="box" args={ [1, 1, 1] } color="#ff6347" />` |
|
|
120
|
+
| arguments that differ (a cylinder's, a torus's, a sphere's segments) | reordered, or left out and said |
|
|
121
|
+
| a colour name, `0xff6347` | `"#ff6347"` |
|
|
122
|
+
| `<ambientLight>`, `<directionalLight>`, `<pointLight>`, `<spotLight>`, `<hemisphereLight>` | the same with a capital; a spot light's angle in degrees |
|
|
123
|
+
| `<group>`, `<OrbitControls>` | `<Group>`, `<Orbit>` |
|
|
124
|
+
| `onClick`, `onPointerOver` on a mesh | `on:click`, `on:pointerover`; the scene gets `events={ pointerEvents }` |
|
|
125
|
+
| `useFrame((state, delta) => { ref.current.rotation.y += delta })` | `onMount { frame((delta) => { ref.rotation[1] += delta }) }` |
|
|
126
|
+
|
|
127
|
+
What has no rule, and is said: `useThree`, `useLoader` and `useTexture`, `<primitive>`, drei's
|
|
128
|
+
`<Html>`, `<Text>`, `<Environment>` and the like, a material of your own.
|
|
129
|
+
|
|
130
|
+
## A three.js script
|
|
131
|
+
|
|
132
|
+
A script is followed at its top level and through the function that builds its scene (the usual
|
|
133
|
+
`init()`, with the names declared above it). What it makes with `new` and adds to the scene becomes
|
|
134
|
+
markup; where each thing stands comes from `position.set(…)`, `rotation.y = …` and the like; the
|
|
135
|
+
camera, the background, the fog and the shadows go to `<Scene>`; `OrbitControls` is `<Orbit>`;
|
|
136
|
+
a model loaded with `GLTFLoader` and added to the scene is `<Model src>`. The function that ran
|
|
137
|
+
every frame becomes `frame()` with the same statements, and the renderer's housekeeping (its
|
|
138
|
+
size, the resize listener and its function, a `render()` that only draws, the frame-rate meter)
|
|
139
|
+
is gone, because `<Scene>` does that.
|
|
140
|
+
|
|
141
|
+
```js
|
|
142
|
+
// src/spin-top.js
|
|
143
|
+
import * as THREE from 'three';
|
|
144
|
+
|
|
145
|
+
const scene = new THREE.Scene();
|
|
146
|
+
scene.background = new THREE.Color('#202830');
|
|
147
|
+
const camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 50);
|
|
148
|
+
camera.position.set(0, 2, 5);
|
|
149
|
+
|
|
150
|
+
const renderer = new THREE.WebGLRenderer({ antialias: true });
|
|
151
|
+
renderer.setSize(innerWidth, innerHeight);
|
|
152
|
+
document.body.appendChild(renderer.domElement);
|
|
153
|
+
|
|
154
|
+
scene.add(new THREE.HemisphereLight('white', 'slategray', 1.5));
|
|
155
|
+
|
|
156
|
+
const top = new THREE.Mesh(
|
|
157
|
+
new THREE.ConeGeometry(1, 2, 24),
|
|
158
|
+
new THREE.MeshStandardMaterial({ color: 'gold', roughness: 0.3 }),
|
|
159
|
+
);
|
|
160
|
+
top.rotation.x = Math.PI;
|
|
161
|
+
scene.add(top);
|
|
162
|
+
|
|
163
|
+
const clock = new THREE.Clock();
|
|
164
|
+
function animate() {
|
|
165
|
+
requestAnimationFrame(animate);
|
|
166
|
+
top.rotation.y += clock.getDelta() * 3;
|
|
167
|
+
renderer.render(scene, camera);
|
|
168
|
+
}
|
|
169
|
+
animate();
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
```clarity
|
|
173
|
+
// src/SpinTop.clarity, as the tool wrote it
|
|
174
|
+
import { HemisphereLight, Mesh, Scene, pointerEvents } from '@clarity-js/gl'
|
|
175
|
+
import { frame } from '@ozsarman/clarityjs/game-loop'
|
|
176
|
+
|
|
177
|
+
component SpinTop() {
|
|
178
|
+
ref top
|
|
179
|
+
onMount {
|
|
180
|
+
frame((delta) => {
|
|
181
|
+
top.rotation[1] += delta * 3;
|
|
182
|
+
})
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
render {
|
|
186
|
+
<div style={ { height: '100vh' } }>
|
|
187
|
+
<Scene
|
|
188
|
+
camera={ { fov: 60, near: 0.1, far: 50, position: [0, 2, 5] } }
|
|
189
|
+
background="#202830"
|
|
190
|
+
events={ pointerEvents }
|
|
191
|
+
antialias
|
|
192
|
+
>
|
|
193
|
+
<HemisphereLight color="#ffffff" groundColor="#708090" intensity={ 1.5 } />
|
|
194
|
+
<Mesh
|
|
195
|
+
geometry="cone"
|
|
196
|
+
args={ [1, 2, 24] }
|
|
197
|
+
color="#ffd700"
|
|
198
|
+
roughness={ 0.3 }
|
|
199
|
+
ref={ top }
|
|
200
|
+
rotation-x={ Math.PI }
|
|
201
|
+
/>
|
|
202
|
+
</Scene>
|
|
203
|
+
</div>
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
What a rule cannot follow is kept in the component as a comment, with its line, and listed:
|
|
209
|
+
objects made in a loop or by a function of the script, a texture, a raycaster, post-processing,
|
|
210
|
+
and a statement that tells an object something a node here is not told (its material's colour,
|
|
211
|
+
say: that is a prop of the `<Mesh>`, bound to a state). The rest of the script is still ported.
|
|
212
|
+
|
|
213
|
+
Light strengths are not on the same scale in the two renderers. Look at the picture.
|
|
214
|
+
|
|
215
|
+
## How far it gets on real code
|
|
216
|
+
|
|
217
|
+
It was run over published code while it was written, and the rules above are what that taught it.
|
|
218
|
+
On 60 files of three React libraries (react-hot-toast, leva, react-data-grid): none stopped the
|
|
219
|
+
tool, every file it wrote compiles, 3 needed nothing more, 46 came out with a list (178 things in
|
|
220
|
+
all, most of them the library's own hooks and props types that live in another file), and 11 held
|
|
221
|
+
no function component. On the scripts of 15 of three.js's own examples: none stopped it, all
|
|
222
|
+
compile, and every one came out with a list (textures, helpers, instancing, a GUI), from 3 things
|
|
223
|
+
to 37. In no file did it write a name that is not there without saying so.
|
|
224
|
+
|
|
225
|
+
So: on a component or a scene that uses what the tables above name, it finishes the job. On a
|
|
226
|
+
large code base it does the mechanical part and hands you an exact list of the rest.
|
|
227
|
+
|
|
228
|
+
## From code
|
|
229
|
+
|
|
230
|
+
```js
|
|
231
|
+
import ts from 'typescript';
|
|
232
|
+
import { portReact, portThree, portFiles, formatReport } from '@clarity-js/port';
|
|
233
|
+
|
|
234
|
+
const { clarity, shared, components, notes } = portReact(source, { typescript: ts, filename: 'Card.tsx' });
|
|
235
|
+
const scene = portThree(script, { typescript: ts, filename: 'spin-top.js' });
|
|
236
|
+
|
|
237
|
+
// files and folders on disk, compiled and linted as the command does
|
|
238
|
+
import { compile } from '@ozsarman/clarityjs';
|
|
239
|
+
import { lintCode } from '@ozsarman/clarityjs/linter';
|
|
240
|
+
const results = portFiles(['src'], { typescript: ts, compile, lint: lintCode, write: false });
|
|
241
|
+
console.log(formatReport(results));
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
`notes` is a list of `{ line, level, text }`: `level` is `'done'` for a rule that was applied
|
|
245
|
+
and is worth knowing about, `'todo'` for what is left for a person.
|
|
246
|
+
|
|
247
|
+
## With an AI agent
|
|
248
|
+
|
|
249
|
+
What the tool leaves is the part that needs reading: a custom hook, a render prop, objects made
|
|
250
|
+
in a loop. The [Clarity skill](https://clarity-js.com/ai) has a porting reference
|
|
251
|
+
an agent follows for exactly those. Port by rule first, then hand the `TODO(port)` remarks to
|
|
252
|
+
the agent.
|
|
253
|
+
|
|
254
|
+
MIT © Özdemir Şarman
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* clarity-port: React components and three.js scenes → Clarity.js, by rule.
|
|
4
|
+
*
|
|
5
|
+
* npx @clarity-js/port src/ port every .jsx and .tsx under src/, each .clarity beside its source,
|
|
6
|
+
* and every script there that builds a three.js scene
|
|
7
|
+
* npx @clarity-js/port src/Card.tsx one file
|
|
8
|
+
* npx @clarity-js/port src/ --out clarity/ write into another folder
|
|
9
|
+
* npx @clarity-js/port src/ --dry write nothing: only the report
|
|
10
|
+
* --verbose also say which rules were applied --json the report as JSON
|
|
11
|
+
*
|
|
12
|
+
* Your own files are not changed. Every file written is compiled and linted; what a rule could
|
|
13
|
+
* not do is listed with its line.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import { createRequire } from 'node:module';
|
|
19
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
20
|
+
import { portFiles, formatReport } from '../src/index.js';
|
|
21
|
+
|
|
22
|
+
const args = process.argv.slice(2);
|
|
23
|
+
const flag = (name) => args.includes(name);
|
|
24
|
+
const value = (name) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : null; };
|
|
25
|
+
const paths = args.filter((a, i) => !a.startsWith('--') && args[i - 1] !== '--out');
|
|
26
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
27
|
+
|
|
28
|
+
if (flag('--version') || flag('-v')) { console.log(JSON.parse(fs.readFileSync(path.join(HERE, '../package.json'), 'utf8')).version); process.exit(0); }
|
|
29
|
+
if (flag('--help') || flag('-h') || !paths.length) {
|
|
30
|
+
console.log(`clarity-port: React components and three.js scenes → Clarity.js, by rule
|
|
31
|
+
|
|
32
|
+
Usage: clarity-port <file or folder>… [--out <folder>] [--dry] [--verbose] [--json]
|
|
33
|
+
|
|
34
|
+
Ports every .jsx and .tsx file (tests and stories are left out): React components, and React
|
|
35
|
+
Three Fiber scenes (to @clarity-js/gl). Also every .js, .mjs and .ts file that builds a
|
|
36
|
+
three.js scene (it imports three and makes a Scene); a single file you name is always tried.
|
|
37
|
+
Each .clarity file is written beside its source (or under --out), compiled and linted. Your
|
|
38
|
+
own files are not changed. The report lists, per file, what is left for you, with the line
|
|
39
|
+
of the file it came from.
|
|
40
|
+
|
|
41
|
+
--dry write nothing, only report --verbose also the rules that were applied
|
|
42
|
+
--json the report as JSON`);
|
|
43
|
+
process.exit(paths.length ? 0 : 1);
|
|
44
|
+
}
|
|
45
|
+
for (const p of paths) if (!fs.existsSync(p)) { console.error(`No such file or folder: ${p}`); process.exit(1); }
|
|
46
|
+
|
|
47
|
+
// TypeScript reads the files (it reads JSX and TSX), through its JavaScript API: TypeScript 5 or 6.
|
|
48
|
+
// (TypeScript 7.0, the native compiler, is published without one; its makers ship the 6.0 API as
|
|
49
|
+
// @typescript/typescript6.) The project's own when it has one with the API, else the one this tool came with.
|
|
50
|
+
let typescript = null;
|
|
51
|
+
for (const from of [path.join(process.cwd(), 'package.json'), import.meta.url]) {
|
|
52
|
+
for (const name of ['typescript', '@typescript/typescript6']) {
|
|
53
|
+
try { const found = createRequire(from)(name); if (typeof found?.createSourceFile === 'function') { typescript = found; break; } } catch { /* the next one */ }
|
|
54
|
+
}
|
|
55
|
+
if (typescript) break;
|
|
56
|
+
}
|
|
57
|
+
if (!typescript) { console.error('clarity-port reads your files with TypeScript\'s JavaScript API, and found no `typescript` that has one (TypeScript 7.0 does not): npm i -D typescript@6'); process.exit(1); }
|
|
58
|
+
|
|
59
|
+
// Clarity.js compiles and lints what is written: the project's own when it has one (the version it will be built with).
|
|
60
|
+
let clarity = null;
|
|
61
|
+
for (const from of [path.join(process.cwd(), 'package.json'), import.meta.url]) {
|
|
62
|
+
try { const r = createRequire(from); clarity = { compile: (await import(pathToFileURL(r.resolve('@ozsarman/clarityjs')).href)).compile, lint: (await import(pathToFileURL(r.resolve('@ozsarman/clarityjs/linter')).href)).lintCode }; break; } catch { /* the next one */ }
|
|
63
|
+
}
|
|
64
|
+
if (!clarity) console.error('(@ozsarman/clarityjs was not found: the files are written, and not compiled)');
|
|
65
|
+
|
|
66
|
+
const results = portFiles(paths, { typescript, compile: clarity?.compile, lint: clarity?.lint, out: value('--out') ?? undefined, write: !flag('--dry') });
|
|
67
|
+
if (flag('--json')) console.log(JSON.stringify(results, null, 2));
|
|
68
|
+
else console.log(formatReport(results, { verbose: flag('--verbose') }) + (flag('--dry') ? '\n(--dry: nothing was written)' : ''));
|
package/package.json
CHANGED
|
@@ -1,6 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@clarity-js/port",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.5.0",
|
|
4
|
+
"description": "Ports React components, React Three Fiber scenes and three.js scripts to Clarity.js by rule: props to parameters, hooks to state, computed, effects and actions, JSX to Clarity markup, a 3D scene to @clarity-js/gl. Every file it writes is compiled and linted, and what a rule could not do is listed with its line.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": { "import": "./src/index.js", "default": "./src/index.js" },
|
|
9
|
+
"./package.json": "./package.json"
|
|
10
|
+
},
|
|
11
|
+
"bin": { "clarity-port": "./bin/clarity-port.js" },
|
|
12
|
+
"files": ["src/", "bin/", "README.md"],
|
|
13
|
+
"keywords": ["clarity", "@ozsarman/clarityjs", "react", "migration", "codemod", "port", "jsx", "tsx", "react-three-fiber", "three.js"],
|
|
14
|
+
"author": "Özdemir Şarman",
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"@ozsarman/clarityjs": "^1.5.0",
|
|
18
|
+
"typescript": ">=5.0.0 <7"
|
|
19
|
+
},
|
|
20
|
+
"homepage": "https://clarity-js.com/docs/porting",
|
|
21
|
+
"repository": { "type": "git", "url": "git+https://gitlab.com/ozsarman/clarity.js.git", "directory": "packages/clarity-port" },
|
|
22
|
+
"engines": { "node": ">=18.0.0" }
|
|
23
|
+
}
|
package/src/fiber.js
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @clarity-js/port — a React Three Fiber scene, as @clarity-js/gl markup.
|
|
3
|
+
*
|
|
4
|
+
* R3F writes a three.js scene as JSX: `<mesh>` with a geometry and a material inside it, lights,
|
|
5
|
+
* groups, in a `<Canvas>`. @clarity-js/gl writes a scene as markup too, so most of it carries over
|
|
6
|
+
* by rule: `<Canvas>` is `<Scene>`, a mesh with `<boxGeometry args={[1, 1, 1]} />` and
|
|
7
|
+
* `<meshStandardMaterial color="hotpink" />` is `<Mesh geometry="box" args={ [1, 1, 1] } color="#ff69b4" />`.
|
|
8
|
+
* Where the two differ the rule converts (a spot light's angle is radians there and degrees here,
|
|
9
|
+
* a colour here is '#rrggbb'), and where there is no counterpart a note says so.
|
|
10
|
+
*
|
|
11
|
+
* Used by react.js, which hands over what it needs to write code and notes.
|
|
12
|
+
*
|
|
13
|
+
* Author: Özdemir Şarman
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** CSS colour names → hex (@clarity-js/gl takes '#rrggbb'). */
|
|
17
|
+
const NAMED = Object.fromEntries(('aliceblue:f0f8ff,antiquewhite:faebd7,aqua:00ffff,aquamarine:7fffd4,azure:f0ffff,beige:f5f5dc,bisque:ffe4c4,black:000000,blanchedalmond:ffebcd,blue:0000ff,blueviolet:8a2be2,brown:a52a2a,'
|
|
18
|
+
+ 'burlywood:deb887,cadetblue:5f9ea0,chartreuse:7fff00,chocolate:d2691e,coral:ff7f50,cornflowerblue:6495ed,cornsilk:fff8dc,crimson:dc143c,cyan:00ffff,darkblue:00008b,darkcyan:008b8b,darkgoldenrod:b8860b,'
|
|
19
|
+
+ 'darkgray:a9a9a9,darkgreen:006400,darkgrey:a9a9a9,darkkhaki:bdb76b,darkmagenta:8b008b,darkolivegreen:556b2f,darkorange:ff8c00,darkorchid:9932cc,darkred:8b0000,darksalmon:e9967a,darkseagreen:8fbc8f,'
|
|
20
|
+
+ 'darkslateblue:483d8b,darkslategray:2f4f4f,darkslategrey:2f4f4f,darkturquoise:00ced1,darkviolet:9400d3,deeppink:ff1493,deepskyblue:00bfff,dimgray:696969,dimgrey:696969,dodgerblue:1e90ff,firebrick:b22222,'
|
|
21
|
+
+ 'floralwhite:fffaf0,forestgreen:228b22,fuchsia:ff00ff,gainsboro:dcdcdc,ghostwhite:f8f8ff,gold:ffd700,goldenrod:daa520,gray:808080,green:008000,greenyellow:adff2f,grey:808080,honeydew:f0fff0,hotpink:ff69b4,'
|
|
22
|
+
+ 'indianred:cd5c5c,indigo:4b0082,ivory:fffff0,khaki:f0e68c,lavender:e6e6fa,lavenderblush:fff0f5,lawngreen:7cfc00,lemonchiffon:fffacd,lightblue:add8e6,lightcoral:f08080,lightcyan:e0ffff,'
|
|
23
|
+
+ 'lightgoldenrodyellow:fafad2,lightgray:d3d3d3,lightgreen:90ee90,lightgrey:d3d3d3,lightpink:ffb6c1,lightsalmon:ffa07a,lightseagreen:20b2aa,lightskyblue:87cefa,lightslategray:778899,lightslategrey:778899,'
|
|
24
|
+
+ 'lightsteelblue:b0c4de,lightyellow:ffffe0,lime:00ff00,limegreen:32cd32,linen:faf0e6,magenta:ff00ff,maroon:800000,mediumaquamarine:66cdaa,mediumblue:0000cd,mediumorchid:ba55d3,mediumpurple:9370db,'
|
|
25
|
+
+ 'mediumseagreen:3cb371,mediumslateblue:7b68ee,mediumspringgreen:00fa9a,mediumturquoise:48d1cc,mediumvioletred:c71585,midnightblue:191970,mintcream:f5fffa,mistyrose:ffe4e1,moccasin:ffe4b5,'
|
|
26
|
+
+ 'navajowhite:ffdead,navy:000080,oldlace:fdf5e6,olive:808000,olivedrab:6b8e23,orange:ffa500,orangered:ff4500,orchid:da70d6,palegoldenrod:eee8aa,palegreen:98fb98,paleturquoise:afeeee,palevioletred:db7093,'
|
|
27
|
+
+ 'papayawhip:ffefd5,peachpuff:ffdab9,peru:cd853f,pink:ffc0cb,plum:dda0dd,powderblue:b0e0e6,purple:800080,rebeccapurple:663399,red:ff0000,rosybrown:bc8f8f,royalblue:4169e1,saddlebrown:8b4513,salmon:fa8072,'
|
|
28
|
+
+ 'sandybrown:f4a460,seagreen:2e8b57,seashell:fff5ee,sienna:a0522d,silver:c0c0c0,skyblue:87ceeb,slateblue:6a5acd,slategray:708090,slategrey:708090,snow:fffafa,springgreen:00ff7f,steelblue:4682b4,tan:d2b48c,'
|
|
29
|
+
+ 'teal:008080,thistle:d8bfd8,tomato:ff6347,turquoise:40e0d0,violet:ee82ee,wheat:f5deb3,white:ffffff,whitesmoke:f5f5f5,yellow:ffff00,yellowgreen:9acd32').split(',').map((p) => p.split(':')));
|
|
30
|
+
|
|
31
|
+
/** The CSS colour names written as strings in a piece of code, as hex. */
|
|
32
|
+
export const namedToHex = (text) => text.replace(/(['"])([a-zA-Z]+)\1/g, (all, q, name) => (NAMED[name.toLowerCase()] ? `${q}#${NAMED[name.toLowerCase()]}${q}` : all));
|
|
33
|
+
|
|
34
|
+
/** three.js geometries → a named shape of @clarity-js/gl and how its arguments are ordered there, or a function that makes the shape. */
|
|
35
|
+
const GEOMETRY = {
|
|
36
|
+
boxGeometry: { shape: 'box', args: (a) => a.slice(0, 3) },
|
|
37
|
+
sphereGeometry: { shape: 'sphere', args: (a) => a.slice(0, 1), dropped: 'segments' },
|
|
38
|
+
planeGeometry: { shape: 'plane', args: (a) => a.slice(0, 2) },
|
|
39
|
+
coneGeometry: { shape: 'cone', args: (a) => a.slice(0, 3) },
|
|
40
|
+
icosahedronGeometry: { shape: 'icosahedron', args: (a) => a.slice(0, 2) },
|
|
41
|
+
octahedronGeometry: { shape: 'octahedron', args: (a) => a.slice(0, 1) },
|
|
42
|
+
// three: radius, tube, radialSegments (round the tube), tubularSegments (round the ring) → here: radius, tube, segments (round the ring), sides (round the tube).
|
|
43
|
+
// And three's ring stands up (round the z axis) where the one here lies down (round y): it is stood up, so that the mesh's own rotation means what it meant.
|
|
44
|
+
torusGeometry: { make: 'torus', args: (a) => [a[0] ?? '1', a[1] ?? '0.4', a[3] ?? '32', a[2] ?? '12'], wrap: (call) => `rotateX(${call}, Math.PI / 2)`, needs: ['rotateX'], more: 'crease={ 80 }' },
|
|
45
|
+
// three: radiusTop, radiusBottom, height, radialSegments → here: radius, height, segments
|
|
46
|
+
cylinderGeometry: { shape: 'cylinder', args: (a, say) => { if (a.length >= 2 && a[0] !== a[1]) say('a cylinder with two different radii: here `cylinder(radius, height, segments, { top })` from @clarity-js/gl makes one (the bottom radius was used)'); return [a[1] ?? a[0] ?? '1', a[2] ?? '1', ...(a[3] ? [a[3]] : [])]; } },
|
|
47
|
+
capsuleGeometry: { make: 'capsule', args: (a) => a.slice(0, 2) },
|
|
48
|
+
circleGeometry: { make: 'disc', args: (a) => a.slice(0, 2) },
|
|
49
|
+
ringGeometry: { make: 'ring', args: (a) => a.slice(0, 3) },
|
|
50
|
+
torusKnotGeometry: { make: 'torusKnot', args: (a) => a.slice(0, 6) },
|
|
51
|
+
tetrahedronGeometry: { make: 'tetrahedron', args: (a) => a.slice(0, 1) },
|
|
52
|
+
dodecahedronGeometry: { make: 'dodecahedron', args: (a) => a.slice(0, 1) },
|
|
53
|
+
};
|
|
54
|
+
/** three.js materials → `material` here (null: the default, 'standard'), and what else to say. */
|
|
55
|
+
const MATERIAL = {
|
|
56
|
+
meshStandardMaterial: { material: null },
|
|
57
|
+
meshBasicMaterial: { material: '"basic"' },
|
|
58
|
+
meshLambertMaterial: { material: null, note: 'meshLambertMaterial: drawn with the standard material (roughness 1 is close to it)' },
|
|
59
|
+
meshPhongMaterial: { material: null, note: 'meshPhongMaterial: drawn with the standard material; a shine is `roughness` here' },
|
|
60
|
+
meshPhysicalMaterial: { material: '{ physical }', gl: 'physical', params: ['clearcoat', 'clearcoatRoughness', 'sheen', 'sheenRoughness', 'iridescence', 'iridescenceIOR', 'anisotropy', 'anisotropyRotation'] },
|
|
61
|
+
meshToonMaterial: { material: '{ toon }', gl: 'toon' },
|
|
62
|
+
meshNormalMaterial: { material: '{ normalMaterial }', gl: 'normalMaterial' },
|
|
63
|
+
};
|
|
64
|
+
const SURFACE = new Set(['color', 'emissive', 'emissiveIntensity', 'roughness', 'metalness', 'flatShading', 'opacity', 'side']);
|
|
65
|
+
const LIGHT = { ambientLight: 'AmbientLight', hemisphereLight: 'HemisphereLight', directionalLight: 'DirectionalLight', pointLight: 'PointLight', spotLight: 'SpotLight' };
|
|
66
|
+
const NODE_PROPS = new Set(['position', 'rotation', 'scale', 'visible', 'castShadow', 'receiveShadow', 'name', 'renderOrder', 'ref', 'intensity', 'distance', 'decay', 'penumbra', 'groundColor', 'target']);
|
|
67
|
+
const POINTER = { onClick: 'click', onDoubleClick: 'dblclick', onContextMenu: 'contextmenu', onPointerDown: 'pointerdown', onPointerUp: 'pointerup', onPointerMove: 'pointermove', onPointerOver: 'pointerover', onPointerOut: 'pointerout', onPointerEnter: 'pointerover', onPointerLeave: 'pointerout' };
|
|
68
|
+
const DREI_WITHOUT_A_RULE = /^(Environment|Html|Text|Text3D|Stars|Sky|Cloud|ContactShadows|Float|Billboard|Line|Trail|Sparkles|Center|Bounds|Stage|PresentationControls|TransformControls|PerspectiveCamera|OrthographicCamera|Instances|Instance|Detailed|Preload|Loader|Stats|GizmoHelper|Grid|useGLTF|useTexture|useAnimations)$/;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* @param {object} tools from react.js: { ts, sf, code, raw, todo, done, handlerText, unparen, el, tree, gl (a Set: names to import from @clarity-js/gl) }
|
|
72
|
+
*/
|
|
73
|
+
export function createFiber(tools) {
|
|
74
|
+
const { ts, sf, code, raw, todo, done, handlerText, unparen, el, tree, gl } = tools;
|
|
75
|
+
/** A component of @clarity-js/gl, by the name it has in this file (another name when the file has one of its own called the same). */
|
|
76
|
+
const T = (name) => { gl.add(name); return tools.local ? tools.local(name) : name; };
|
|
77
|
+
const K = ts.SyntaxKind;
|
|
78
|
+
const nameOf = (a) => a.name.getText(sf);
|
|
79
|
+
const valueOf = (a) => (!a.initializer ? null : a.initializer.kind === K.StringLiteral ? a.initializer : a.initializer.expression ? unparen(a.initializer.expression) : null);
|
|
80
|
+
const tagOf = (n) => (n.kind === K.JsxElement ? n.openingElement : n).tagName.getText(sf);
|
|
81
|
+
const attrsOf = (n) => (n.kind === K.JsxElement ? n.openingElement : n).attributes.properties;
|
|
82
|
+
const childrenOf = (n) => (n.kind === K.JsxElement ? n.children.filter((c) => c.kind === K.JsxElement || c.kind === K.JsxSelfClosingElement) : []);
|
|
83
|
+
const isElement = (n) => n.kind === K.JsxElement || n.kind === K.JsxSelfClosingElement;
|
|
84
|
+
|
|
85
|
+
/** A colour as @clarity-js/gl takes one: `"#rrggbb"`, or `{ expression }`. */
|
|
86
|
+
function colour(v, at) {
|
|
87
|
+
if (!v) return null;
|
|
88
|
+
if (v.kind === K.StringLiteral || v.kind === K.NoSubstitutionTemplateLiteral) {
|
|
89
|
+
const text = v.text.trim().toLowerCase();
|
|
90
|
+
if (/^#[0-9a-f]{6}$/.test(text)) return `"${text}"`;
|
|
91
|
+
if (/^#[0-9a-f]{3}$/.test(text)) return `"#${[...text.slice(1)].map((c) => c + c).join('')}"`;
|
|
92
|
+
if (NAMED[text]) return `"#${NAMED[text]}"`;
|
|
93
|
+
todo(at, `the colour "${v.text}": @clarity-js/gl takes '#rrggbb' or [r, g, b]`);
|
|
94
|
+
return `"${v.text}"`;
|
|
95
|
+
}
|
|
96
|
+
if (v.kind === K.NumericLiteral) return `"#${Number(v.text).toString(16).padStart(6, '0')}"`;
|
|
97
|
+
// a colour that is worked out: the names inside it are said as hex too (`on ? 'orange' : color`)
|
|
98
|
+
return `{ ${namedToHex(code(v))} }`;
|
|
99
|
+
}
|
|
100
|
+
const isColourProp = (name) => /colou?r$/i.test(name) || name === 'emissive';
|
|
101
|
+
/** `name="text"` or `name={ code }` (a bare name for `true`). */
|
|
102
|
+
function prop(name, v, at) {
|
|
103
|
+
if (v === null) return name;
|
|
104
|
+
if (isColourProp(name)) return `${name}=${colour(v, at)}`;
|
|
105
|
+
if (v.kind === K.StringLiteral) return `${name}=${raw(v)}`;
|
|
106
|
+
return `${name}={ ${code(v)} }`;
|
|
107
|
+
}
|
|
108
|
+
const argsOf = (n) => { const a = attrsOf(n).find((x) => x.kind === K.JsxAttribute && nameOf(x) === 'args'); const v = a ? valueOf(a) : null; return { attr: a, list: v?.kind === K.ArrayLiteralExpression ? v.elements : null, value: v }; };
|
|
109
|
+
|
|
110
|
+
/** What every node takes: where it is, whether it is seen, what the pointer does on it. Returns the attribute texts; `skip` names are left to the caller. */
|
|
111
|
+
function common(n, skip = new Set()) {
|
|
112
|
+
const out = [];
|
|
113
|
+
for (const a of attrsOf(n)) {
|
|
114
|
+
if (a.kind === K.JsxSpreadAttribute) { out.push(`{...${code(a.expression)}}`); continue; }
|
|
115
|
+
const name = nameOf(a), v = valueOf(a);
|
|
116
|
+
if (skip.has(name) || name === 'args' || name === 'attach') continue;
|
|
117
|
+
if (name === 'key') continue;
|
|
118
|
+
if (POINTER[name]) { if (v) out.push(`on:${POINTER[name]}={ ${handlerText(v)} }`); if (/Enter|Leave/.test(name)) done(a, `${name}: written as on:${POINTER[name]} (a mesh hears over and out)`); continue; }
|
|
119
|
+
if (/^on[A-Z]/.test(name)) { todo(a, `${name} on a 3D object has no counterpart here (a mesh hears click, dblclick, contextmenu and the pointer events)`); continue; }
|
|
120
|
+
if (name === 'rotation' && v?.kind === K.ArrayLiteralExpression && v.elements.filter((e) => !(e.kind === K.NumericLiteral && Number(e.text) === 0)).length > 1) done(a, 'rotation on more than one axis: three.js turns x, then y, then z; here it is [pitch, heading, roll] with the heading (y) first. Look at the picture');
|
|
121
|
+
if (NODE_PROPS.has(name) || /^(position|rotation|scale)-[xyz]$/.test(name) || isColourProp(name)) { out.push(prop(name, v, a)); continue; }
|
|
122
|
+
if (/^shadow-/.test(name)) { if (name === 'shadow-mapSize' && v?.kind === K.ArrayLiteralExpression && v.elements[0]) out.push(`shadowMapSize={ ${code(v.elements[0])} }`); else done(a, `${name}: left out (a light's shadow here has shadowMapSize and shadowCameraSize)`); continue; }
|
|
123
|
+
done(a, `${name} on <${tagOf(n)}>: left out, there is no such prop here`);
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** <mesh> with its geometry and its material. */
|
|
129
|
+
function mesh(n) {
|
|
130
|
+
const attrs = [];
|
|
131
|
+
const kids = childrenOf(n), rest = [];
|
|
132
|
+
for (const k of kids) {
|
|
133
|
+
const tag = tagOf(k);
|
|
134
|
+
const g = GEOMETRY[tag], m = MATERIAL[tag];
|
|
135
|
+
if (g) {
|
|
136
|
+
const { list, value, attr } = argsOf(k);
|
|
137
|
+
const say = (text) => todo(k, text);
|
|
138
|
+
if (value && !list) { todo(attr, `the arguments of <${tag}> are worked out, not written: check their order against ${g.shape ?? g.make}() of @clarity-js/gl`); }
|
|
139
|
+
const a = list ? g.args(list.map((e) => code(e)), say) : null;
|
|
140
|
+
if (g.shape) { attrs.push(`geometry="${g.shape}"`); if (a?.length) attrs.push(`args={ [${a.join(', ')}] }`); else if (value && !list) attrs.push(`args={ ${code(value)} }`); }
|
|
141
|
+
else {
|
|
142
|
+
gl.add(g.make); for (const name of g.needs ?? []) gl.add(name);
|
|
143
|
+
const call = `${g.make}(${a ? a.join(', ') : value ? `...${code(value)}` : g.args([]).join(', ')})`;
|
|
144
|
+
attrs.push(`geometry={ ${g.wrap ? g.wrap(call) : call} }`);
|
|
145
|
+
if (g.more) attrs.push(g.more);
|
|
146
|
+
}
|
|
147
|
+
if (g.dropped && list && list.length > g.args(list.map(() => '')).length) done(k, `<${tag}>: its ${g.dropped} are left out (a sphere here has \`detail\`)`);
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
if (/Geometry$/.test(tag)) { todo(k, `<${tag}>: there is no rule for this geometry. A shape of your own is \`geometry={ positions }\` (a list of triangles), or a function of @clarity-js/gl (capsule, ring, torusKnot, …)`); continue; }
|
|
151
|
+
if (m || /Material$/.test(tag)) {
|
|
152
|
+
if (!m) { todo(k, `<${tag}>: there is no rule for this material (your own shader is \`material({ vertex, fragment, uniforms })\`; pictures on a surface are \`textured\`)`); continue; }
|
|
153
|
+
if (m.note) done(k, m.note);
|
|
154
|
+
if (m.material) attrs.push(`material=${m.material}`);
|
|
155
|
+
if (m.gl) gl.add(m.gl);
|
|
156
|
+
const params = [];
|
|
157
|
+
for (const a of attrsOf(k)) {
|
|
158
|
+
if (a.kind !== K.JsxAttribute) { todo(a, 'a material given its props by a spread: write them on the <Mesh>'); continue; }
|
|
159
|
+
const name = nameOf(a), v = valueOf(a);
|
|
160
|
+
if (name === 'side') { const text = v ? code(v) : ''; attrs.push(`side="${/Double/.test(text) ? 'double' : /Back/.test(text) ? 'back' : 'front'}"`); continue; }
|
|
161
|
+
if (name === 'transparent' || name === 'attach' || name === 'args') continue;
|
|
162
|
+
if (SURFACE.has(name)) { attrs.push(prop(name, v, a)); continue; }
|
|
163
|
+
if (m.params?.includes(name)) { params.push(`${name}: ${v ? code(v) : 'true'}`); continue; }
|
|
164
|
+
if (/[mM]ap$/.test(name)) { todo(a, `${name}: a picture on a surface is the \`textured\` material here (\`<Mesh material={ textured } params={ { map } } />\`, with a Texture loaded by \`loadTexture\`)`); continue; }
|
|
165
|
+
if (name === 'wireframe') { if (v?.kind !== K.FalseKeyword) todo(a, 'wireframe: draw the edges with `wires(geometry)` and a line material'); continue; }
|
|
166
|
+
done(a, `${name} on <${tag}>: left out, the material here has no such setting`);
|
|
167
|
+
}
|
|
168
|
+
if (params.length) attrs.push(`params={ { ${params.join(', ')} } }`);
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
rest.push(k);
|
|
172
|
+
}
|
|
173
|
+
const own = common(n);
|
|
174
|
+
const text = [...attrs, ...own].join(' ');
|
|
175
|
+
const Mesh = T('Mesh');
|
|
176
|
+
if (!rest.length) return [el(`<${Mesh}${text ? ' ' + text : ''} />`, null)];
|
|
177
|
+
// what stands inside a mesh moves with it: a group holds the mesh and what was inside
|
|
178
|
+
const Group = T('Group');
|
|
179
|
+
const moving = own.filter((a) => /^(position|rotation|scale)\b|^ref=|^name=|^visible/.test(a)), staying = own.filter((a) => !moving.includes(a));
|
|
180
|
+
return [el(`<${Group}${moving.length ? ' ' + moving.join(' ') : ''}>`, `</${Group}>`, [el(`<${Mesh} ${[...attrs, ...staying].join(' ')} />`, null), ...rest.flatMap(tree)])];
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function light(n, tag) {
|
|
184
|
+
const Light = T(LIGHT[tag]);
|
|
185
|
+
const attrs = [];
|
|
186
|
+
const { list } = argsOf(n);
|
|
187
|
+
const skip = new Set();
|
|
188
|
+
// <hemisphereLight args={[sky, ground, intensity]} />, <ambientLight args={[colour, intensity]} />
|
|
189
|
+
if (list) {
|
|
190
|
+
// (three.js: SpotLight(color, intensity, distance, angle, penumbra, decay), PointLight(color, intensity, distance, decay))
|
|
191
|
+
const names = tag === 'hemisphereLight' ? ['color', 'groundColor', 'intensity'] : tag === 'spotLight' ? ['color', 'intensity', 'distance', 'angle', 'penumbra', 'decay'] : tag === 'pointLight' ? ['color', 'intensity', 'distance', 'decay'] : ['color', 'intensity'];
|
|
192
|
+
list.forEach((e, i) => {
|
|
193
|
+
const v = unparen(e);
|
|
194
|
+
if (names[i] === 'angle') { attrs.push(v.kind === K.NumericLiteral ? `angle={ ${Math.round(Number(v.text) * 180 / Math.PI * 100) / 100} }` : `angle={ (${code(v)}) * 180 / Math.PI }`); done(n, 'a spot light\'s angle: radians in three.js, degrees here (converted)'); }
|
|
195
|
+
else if (names[i]) attrs.push(prop(names[i], v, n));
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
for (const a of attrsOf(n)) {
|
|
199
|
+
if (a.kind !== K.JsxAttribute) continue;
|
|
200
|
+
const name = nameOf(a), v = valueOf(a);
|
|
201
|
+
if (name === 'skyColor') { attrs.push(prop('color', v, a)); skip.add(name); }
|
|
202
|
+
// an angle is radians in three.js and degrees here
|
|
203
|
+
if (name === 'angle' && v) { attrs.push(v.kind === K.NumericLiteral ? `angle={ ${Math.round(Number(v.text) * 180 / Math.PI * 100) / 100} }` : `angle={ (${code(v)}) * 180 / Math.PI }`); skip.add(name); done(a, 'a spot light\'s angle: radians in three.js, degrees here (converted)'); }
|
|
204
|
+
}
|
|
205
|
+
attrs.push(...common(n, skip));
|
|
206
|
+
return [el(`<${Light}${attrs.length ? ' ' + attrs.join(' ') : ''} />`, null)];
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** <Canvas> … </Canvas> */
|
|
210
|
+
function canvas(n) {
|
|
211
|
+
const Scene = T('Scene');
|
|
212
|
+
const attrs = [], inside = [];
|
|
213
|
+
for (const a of attrsOf(n)) {
|
|
214
|
+
if (a.kind === K.JsxSpreadAttribute) { attrs.push(`{...${code(a.expression)}}`); continue; }
|
|
215
|
+
const name = nameOf(a), v = valueOf(a);
|
|
216
|
+
if (name === 'camera' || name === 'shadows' || name === 'frameloop') { attrs.push(v === null ? name : v.kind === K.StringLiteral ? `${name}=${raw(v)}` : `${name}={ ${code(v)} }`); continue; }
|
|
217
|
+
if (name === 'dpr') { attrs.push(v?.kind === K.ArrayLiteralExpression && v.elements.length ? `dpr={ ${code(v.elements[v.elements.length - 1])} }` : `dpr={ ${v ? code(v) : 2} }`); continue; }
|
|
218
|
+
if (name === 'className') { attrs.push(v?.kind === K.StringLiteral ? `class=${raw(v)}` : `class={ ${code(v)} }`); continue; }
|
|
219
|
+
if (name === 'onCreated') { todo(a, 'onCreated: <Scene onCreated={ (api) => … }> hands over { canvas, camera, scene, renderer, lights, invalidate, render }, not three.js\'s state'); continue; }
|
|
220
|
+
if (name === 'orthographic') { todo(a, 'an orthographic camera: use `orthographic()` from @clarity-js/gl'); continue; }
|
|
221
|
+
done(a, `${name} on <Canvas>: left out (<Scene> has camera, background, fog, shadows, antialias, dpr, frameloop, effects)`);
|
|
222
|
+
}
|
|
223
|
+
for (const k of n.kind === K.JsxElement ? n.children : []) {
|
|
224
|
+
if (isElement(k)) {
|
|
225
|
+
const tag = tagOf(k), attach = attrsOf(k).find((a) => a.kind === K.JsxAttribute && nameOf(a) === 'attach');
|
|
226
|
+
const where = attach ? valueOf(attach)?.text : null;
|
|
227
|
+
const { list } = argsOf(k);
|
|
228
|
+
// <color attach="background" args={['#000']} />, <fog attach="fog" args={[colour, near, far]} />
|
|
229
|
+
if (tag === 'color' && where === 'background' && list?.[0]) { attrs.push(`background=${colour(unparen(list[0]), k)}`); continue; }
|
|
230
|
+
if (tag === 'fogExp2' && list?.length) { attrs.push(`fog={ { color: ${colour(unparen(list[0]), k).replace(/^\{ | \}$/g, '')}${list[1] ? `, density: ${code(list[1])}` : ''} } }`); continue; }
|
|
231
|
+
if (tag === 'fog' && list?.length) { attrs.push(`fog={ { color: ${colour(unparen(list[0]), k).replace(/^\{ | \}$/g, '')}${list[1] ? `, near: ${code(list[1])}` : ''}${list[2] ? `, far: ${code(list[2])}` : ''} } }`); continue; }
|
|
232
|
+
}
|
|
233
|
+
inside.push(...tree(k));
|
|
234
|
+
}
|
|
235
|
+
// a mesh under a <Canvas> hears the pointer without being asked; here the scene is told to listen
|
|
236
|
+
gl.add('pointerEvents'); attrs.push('events={ pointerEvents }');
|
|
237
|
+
if (!attrs.includes('antialias')) attrs.push('antialias'); // (React Three Fiber smooths edges unless told not to)
|
|
238
|
+
done(n, '<Canvas> is <Scene>: it fills the element it is in, so that element needs a height. Light strengths are not on the same scale in the two renderers: look at the picture and adjust');
|
|
239
|
+
return [el(`<${Scene}${attrs.length ? ' ' + attrs.join(' ') : ''}>`, `</${Scene}>`, inside)];
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
return {
|
|
243
|
+
/** Is this tag one of React Three Fiber's (or drei's) that is handled here? */
|
|
244
|
+
handles(tag) { return tag === 'Canvas' || tag === 'mesh' || tag === 'group' || tag === 'primitive' || tag === 'OrbitControls' || !!LIGHT[tag] || /(Geometry|Material)$/.test(tag) || DREI_WITHOUT_A_RULE.test(tag) || tag === 'color' || tag === 'fog' || tag === 'fogExp2'; },
|
|
245
|
+
/** The tree of one R3F element. */
|
|
246
|
+
node(n) {
|
|
247
|
+
const tag = tagOf(n);
|
|
248
|
+
if (tag === 'Canvas') return canvas(n);
|
|
249
|
+
if (tag === 'mesh') return mesh(n);
|
|
250
|
+
if (LIGHT[tag]) return light(n, tag);
|
|
251
|
+
if (tag === 'group') {
|
|
252
|
+
const Group = T('Group');
|
|
253
|
+
const attrs = common(n);
|
|
254
|
+
const inside = n.kind === K.JsxElement ? n.children.flatMap(tree) : [];
|
|
255
|
+
return [inside.length ? el(`<${Group}${attrs.length ? ' ' + attrs.join(' ') : ''}>`, `</${Group}>`, inside) : el(`<${Group}${attrs.length ? ' ' + attrs.join(' ') : ''} />`, null)];
|
|
256
|
+
}
|
|
257
|
+
if (tag === 'OrbitControls') {
|
|
258
|
+
const Orbit = T('Orbit');
|
|
259
|
+
const attrs = [];
|
|
260
|
+
const SAME = new Set(['target', 'minDistance', 'maxDistance', 'rotateSpeed', 'zoomSpeed', 'enabled', 'ref']);
|
|
261
|
+
for (const a of attrsOf(n)) {
|
|
262
|
+
if (a.kind !== K.JsxAttribute) continue;
|
|
263
|
+
const name = nameOf(a), v = valueOf(a);
|
|
264
|
+
if (SAME.has(name)) attrs.push(prop(name, v, a));
|
|
265
|
+
else if (name === 'enablePan') attrs.push(prop('pan', v, a));
|
|
266
|
+
else if (name === 'minPolarAngle' || name === 'maxPolarAngle') { attrs.push(prop(name === 'minPolarAngle' ? 'minPolar' : 'maxPolar', v, a)); done(a, `${name}: written as ${name === 'minPolarAngle' ? 'minPolar' : 'maxPolar'}; check its unit against <Orbit>`); }
|
|
267
|
+
else if (name !== 'makeDefault' && name !== 'enableDamping') done(a, `${name} on <OrbitControls>: left out (<Orbit> has target, the distances, the polar limits, rotateSpeed, zoomSpeed, pan, keys, damping)`);
|
|
268
|
+
}
|
|
269
|
+
return [el(`<${Orbit}${attrs.length ? ' ' + attrs.join(' ') : ''} />`, null)];
|
|
270
|
+
}
|
|
271
|
+
if (tag === 'primitive') { todo(n, '<primitive object={ … }>: here <Primitive object={ node } /> takes a Node of @clarity-js/gl, not a three.js object. A loaded model comes from `loadGLTF` (the clarity-gl-models skill)'); return []; }
|
|
272
|
+
if (GEOMETRY[tag] || /(Material|Geometry)$/.test(tag) || tag === 'color' || tag === 'fog' || tag === 'fogExp2') { todo(n, `<${tag}> outside a <mesh> (or a <Canvas>): there is no rule for it there`); return []; }
|
|
273
|
+
todo(n, `<${tag}> (drei) has no counterpart that a rule can write: see the clarity-gl skills (models, vfx, polish) for what does the same`);
|
|
274
|
+
return [];
|
|
275
|
+
},
|
|
276
|
+
};
|
|
277
|
+
}
|