@nstudio/nativescript-compiler-react 0.0.0-stage → 9.2.0-alpha.9
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/LICENSE +19 -0
- package/README.md +27 -2
- package/dist/core-api.js +8 -0
- package/dist/index.js +46 -0
- package/dist/react.js +526 -0
- package/package.json +52 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Copyright OpenJS Foundation and other contributors, https://openjsf.org
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
in the Software without restriction, including without limitation the rights
|
|
6
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in
|
|
11
|
+
all copies or substantial portions of the Software.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
|
19
|
+
THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,28 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @nstudio/nativescript-compiler-react
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
React adapter for [`@nstudio/nativescript-compiler`](https://www.npmjs.com/package/@nstudio/nativescript-compiler), enabling NativeScript React apps (`react-nativescript`) to compile directly to Swift (iOS) and Kotlin (Android) with no JavaScript runtime.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
ns extension install @nstudio/nativescript-compiler
|
|
9
|
+
npm install --save-dev @nstudio/nativescript-compiler-react
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Install the adapter at the same version as `@nstudio/nativescript-compiler`.
|
|
13
|
+
|
|
14
|
+
## Usage
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
ns compile ios
|
|
18
|
+
ns compile android
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Supported Versions
|
|
22
|
+
|
|
23
|
+
- `react-nativescript`: `>=5.0.0 <6.0.0`
|
|
24
|
+
- `react`: `>=18.2.0 <19.0.0`
|
|
25
|
+
|
|
26
|
+
## License
|
|
27
|
+
|
|
28
|
+
MIT
|
package/dist/core-api.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** The compiler's own functions and state, from the compiler that loaded the adapter: set by its entry before any front end runs. */
|
|
2
|
+
export let core;
|
|
3
|
+
/** The compiler's TypeScript (`core.ts`), set with `core`: the adapter reads and makes the compiler's syntax trees with it, never with a TypeScript of its own. */
|
|
4
|
+
export let ts;
|
|
5
|
+
export function useCore(api) {
|
|
6
|
+
core = api;
|
|
7
|
+
ts = api.ts;
|
|
8
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { useCore, ts } from "./core-api.js";
|
|
4
|
+
import { reactComponent, reactScreens, zustandStore } from "./react.js";
|
|
5
|
+
export default function adapter(core) {
|
|
6
|
+
useCore(core);
|
|
7
|
+
return {
|
|
8
|
+
apiVersion: 1,
|
|
9
|
+
name: 'react',
|
|
10
|
+
packages: ['react-nativescript', 'react'],
|
|
11
|
+
behaviour: {
|
|
12
|
+
schedule: 'now', eventScope: 'event', propsOrder: 'post', deferBindings: false, insertion: 'built', listenersAfterBindings: false, effectScope: null, checkEveryBinding: 'off', slots: false, rowSignals: 'off', fragments: false,
|
|
13
|
+
// The flexbox react-nativescript-navigation's FrameNavigatorView renders a screen into.
|
|
14
|
+
pageContentAttrs: { flexGrow: '1', flexDirection: 'column', width: '100%', height: '100%' },
|
|
15
|
+
},
|
|
16
|
+
reach: 'project',
|
|
17
|
+
frontEnd(app) {
|
|
18
|
+
const tsx = app.files.filter((f) => f.endsWith('.tsx'));
|
|
19
|
+
const texts = new Map([...app.sources, ...tsx].map((f) => [f, readFileSync(f, 'utf8')]));
|
|
20
|
+
const navigatorFile = tsx.find((f) => /\.Navigator\b/.test(texts.get(f)));
|
|
21
|
+
const { screens, initial, container } = navigatorFile ? reactScreens(texts.get(navigatorFile)) : { screens: [], initial: '', container: null };
|
|
22
|
+
const fns = [];
|
|
23
|
+
for (const f of tsx) {
|
|
24
|
+
if (f === navigatorFile)
|
|
25
|
+
continue;
|
|
26
|
+
const sf = ts.createSourceFile(f, texts.get(f), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
|
|
27
|
+
for (const st of sf.statements)
|
|
28
|
+
if (ts.isFunctionDeclaration(st) && st.name && /^[A-Z]/.test(st.name.text))
|
|
29
|
+
fns.push({ file: f, fn: st });
|
|
30
|
+
}
|
|
31
|
+
const names = new Map(fns.map(({ file, fn }) => [fn.name.text, file]));
|
|
32
|
+
const components = fns.map(({ file, fn }) => reactComponent(file, texts.get(file), fn, screens, texts, names));
|
|
33
|
+
const overrides = new Map();
|
|
34
|
+
for (const f of app.sources) {
|
|
35
|
+
const store = zustandStore(texts.get(f));
|
|
36
|
+
if (store)
|
|
37
|
+
overrides.set(f, store);
|
|
38
|
+
}
|
|
39
|
+
// The navigator is the app's frame, starting at the initial screen.
|
|
40
|
+
const start = screens.find((s) => s.name === initial);
|
|
41
|
+
const frameName = container ?? 'Navigator';
|
|
42
|
+
components.push({ name: frameName, file: join(dirname(navigatorFile), frameName + '.react.ts'), source: `import ${start.component} from './${start.component}.react';\nexport default class ${frameName} {}\n`, props: [], template: [{ kind: 'element', tag: 'Frame', attrs: [], events: [], children: [{ kind: 'component', name: start.component, props: [], events: [] }] }] });
|
|
43
|
+
return { components, modules: app.sources, overrides, root: frameName };
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}
|
package/dist/react.js
ADDED
|
@@ -0,0 +1,526 @@
|
|
|
1
|
+
import { dirname, relative } from 'node:path';
|
|
2
|
+
import { core, ts } from "./core-api.js";
|
|
3
|
+
/**
|
|
4
|
+
* A React NativeScript function component as a virtual class. React runs the
|
|
5
|
+
* whole body on every render; the release build gets the same results by
|
|
6
|
+
* making `useState` a signal and every other body `const` a derived value
|
|
7
|
+
* read where it is used, so each binding updates on its own.
|
|
8
|
+
*/
|
|
9
|
+
export function reactComponent(path, text, fn, screens, files, components) {
|
|
10
|
+
const name = fn.name.text;
|
|
11
|
+
const sf = fn.getSourceFile();
|
|
12
|
+
const screen = screens.find((s) => s.component === name);
|
|
13
|
+
const scope = { names: new Map() };
|
|
14
|
+
const fields = [];
|
|
15
|
+
const props = [];
|
|
16
|
+
const arity = new Map();
|
|
17
|
+
// Components are imported as their virtual classes; React's own modules have no part in a release build.
|
|
18
|
+
const imports = [];
|
|
19
|
+
// react-nativescript's `<ListView>`, under the name the file imports it as.
|
|
20
|
+
let listTag = '';
|
|
21
|
+
for (const i of sf.statements.filter(ts.isImportDeclaration)) {
|
|
22
|
+
if (/^['"](react|react-nativescript-navigation|@react-navigation\/core)['"]$/.test(i.moduleSpecifier.getText()))
|
|
23
|
+
continue;
|
|
24
|
+
const named = i.importClause?.namedBindings;
|
|
25
|
+
if (i.moduleSpecifier.text === 'react-nativescript' && named && ts.isNamedImports(named)) {
|
|
26
|
+
const list = named.elements.find((e) => (e.propertyName ?? e.name).text === 'ListView');
|
|
27
|
+
if (list && named.elements.length === 1) {
|
|
28
|
+
listTag = list.name.text;
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const names = named && ts.isNamedImports(named) ? named.elements.map((e) => e.name.text) : [];
|
|
33
|
+
const own = names.filter((n) => components.has(n));
|
|
34
|
+
for (const n of own)
|
|
35
|
+
imports.push(`import ${n} from './${n}.react';`);
|
|
36
|
+
if (own.length && own.length === names.length)
|
|
37
|
+
continue;
|
|
38
|
+
imports.push(i.getText());
|
|
39
|
+
}
|
|
40
|
+
// A screen navigates to other screens by component.
|
|
41
|
+
for (const s of screens)
|
|
42
|
+
if (s.component !== name && new RegExp(`navigate\\(\\s*['"]${s.name}['"]`).test(text) && !imports.some((i) => i.startsWith(`import ${s.component} `)))
|
|
43
|
+
imports.push(`import ${s.component} from './${s.component}.react';`);
|
|
44
|
+
// Props: `{ recipe, favorite, onTap }: { recipe: Recipe; ... }`; a screen's `{ navigation, route }`.
|
|
45
|
+
const param = fn.parameters[0];
|
|
46
|
+
let routeName = '';
|
|
47
|
+
let navigationName = '';
|
|
48
|
+
if (param && ts.isObjectBindingPattern(param.name) && param.type && ts.isTypeLiteralNode(param.type)) {
|
|
49
|
+
for (const m of param.type.members) {
|
|
50
|
+
if (!ts.isPropertySignature(m) || !m.type)
|
|
51
|
+
continue;
|
|
52
|
+
const p = m.name.text;
|
|
53
|
+
const t = m.type.getText();
|
|
54
|
+
if (/^RouteProp\b/.test(t)) {
|
|
55
|
+
routeName = p;
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (/^\w*NavigationProp\b/.test(t)) {
|
|
59
|
+
navigationName = p;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
props.push(p);
|
|
63
|
+
fields.push(` ${p}!: ${t};`);
|
|
64
|
+
scope.names.set(p, `this.${p}`);
|
|
65
|
+
if (ts.isFunctionTypeNode(m.type))
|
|
66
|
+
arity.set(p, m.type.parameters.length);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
// A screen's route params are its props.
|
|
70
|
+
const route = screen ? routeParams(files, screen.name) : null;
|
|
71
|
+
if (route) {
|
|
72
|
+
if (!imports.some((i) => new RegExp(`\\b${route.alias}\\b`).test(i)))
|
|
73
|
+
imports.push(`import type { ${route.alias} } from '${relativeModule(path, route.file)}';`);
|
|
74
|
+
for (const p of route.params) {
|
|
75
|
+
props.push(p);
|
|
76
|
+
fields.push(` ${p}!: ${route.alias}['${screen.name}']['${p}'];`);
|
|
77
|
+
scope.names.set(p, `this.${p}`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const routeScope = (s) => ({ names: new Map(s.names), members: routeName ? { object: `${routeName}.params`, replacement: 'this' } : undefined });
|
|
81
|
+
const body = fn.body.statements;
|
|
82
|
+
const ret = body.find(ts.isReturnStatement);
|
|
83
|
+
for (const st of body) {
|
|
84
|
+
if (st === ret)
|
|
85
|
+
continue;
|
|
86
|
+
if (ts.isFunctionDeclaration(st) && st.name) {
|
|
87
|
+
const f = st.name.text;
|
|
88
|
+
arity.set(f, st.parameters.length);
|
|
89
|
+
scope.names.set(f, `this.${f}`);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (!ts.isVariableStatement(st))
|
|
93
|
+
throw new Error(`${path}: unsupported statement in ${name}: ${st.getText().slice(0, 60)}`);
|
|
94
|
+
for (const d of st.declarationList.declarations) {
|
|
95
|
+
const init = d.initializer;
|
|
96
|
+
if (ts.isArrayBindingPattern(d.name) && ts.isCallExpression(init) && /(^|\.)useState$/.test(init.expression.getText())) {
|
|
97
|
+
const [value, setter] = d.name.elements.map((e) => (ts.isBindingElement(e) ? e.name.text : ''));
|
|
98
|
+
scope.names.set(value, `this.${value}()`);
|
|
99
|
+
if (setter)
|
|
100
|
+
scope.names.set(setter, `this.${value}.$write`);
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (ts.isObjectBindingPattern(d.name) && routeName && init.getText() === `${routeName}.params`)
|
|
104
|
+
continue; // the params are props already
|
|
105
|
+
if (ts.isIdentifier(d.name)) {
|
|
106
|
+
const id = d.name.text;
|
|
107
|
+
if (ts.isArrowFunction(init) || ts.isFunctionExpression(init))
|
|
108
|
+
arity.set(id, init.parameters.length);
|
|
109
|
+
scope.names.set(id, `this.${id}`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
// Store selectors: `useRecipes((s) => s.favoriteIds)` reads the store directly.
|
|
114
|
+
const selector = (init) => {
|
|
115
|
+
if (!ts.isCallExpression(init) || !ts.isIdentifier(init.expression) || !/^use[A-Z]/.test(init.expression.text) || init.expression.text === 'useState')
|
|
116
|
+
return null;
|
|
117
|
+
const sel = init.arguments[0];
|
|
118
|
+
if (!sel || !(ts.isArrowFunction(sel) && !ts.isBlock(sel.body)))
|
|
119
|
+
return null;
|
|
120
|
+
const s = sel.parameters[0].name.text;
|
|
121
|
+
return core.rewrite(sel.body.getText(), routeScope({ names: new Map([...scope.names, [s, init.expression.text]]) }));
|
|
122
|
+
};
|
|
123
|
+
for (const st of body) {
|
|
124
|
+
if (st === ret)
|
|
125
|
+
continue;
|
|
126
|
+
if (ts.isFunctionDeclaration(st) && st.name) {
|
|
127
|
+
fields.push(` ${(ts.getModifiers(st)?.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword) ? 'async ' : '')}${st.name.text}(${st.parameters.map((p) => p.getText()).join(', ')})${st.type ? `: ${st.type.getText()}` : ''} ${core.rewrite(navigate(st.body.getText(), navigationName, screens), routeScope(scope), 'statements')}`);
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
for (const d of st.declarationList.declarations) {
|
|
131
|
+
const init = d.initializer;
|
|
132
|
+
if (ts.isArrayBindingPattern(d.name)) {
|
|
133
|
+
const value = d.name.elements[0].name.text;
|
|
134
|
+
const arg = init.arguments[0];
|
|
135
|
+
fields.push(` ${value} = $state($writable(${arg ? core.rewrite(arg.getText(), routeScope(scope)) : 'undefined'}));`);
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
if (!ts.isIdentifier(d.name))
|
|
139
|
+
continue;
|
|
140
|
+
const id = d.name.text;
|
|
141
|
+
const read = selector(init);
|
|
142
|
+
if (read) {
|
|
143
|
+
fields.push(` get ${id}() { return ${read}; }`);
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (ts.isArrowFunction(init) || ts.isFunctionExpression(init)) {
|
|
147
|
+
const b = ts.isBlock(init.body) ? init.body.getText() : `{ return ${init.body.getText()}; }`;
|
|
148
|
+
fields.push(` ${(ts.getModifiers(init)?.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword) ? 'async ' : '')}${id}(${init.parameters.map((p) => p.getText()).join(', ')}) ${core.rewrite(navigate(b, navigationName, screens), routeScope(scope), 'statements')}`);
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
// React recomputes a body const on every render: a derived value.
|
|
152
|
+
fields.push(` get ${id}() { return ${core.rewrite(init.getText(), routeScope(scope))}; }`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
// The template.
|
|
156
|
+
const methods = [];
|
|
157
|
+
let next = 0;
|
|
158
|
+
const params = (loops) => loops.map((l) => l.param).join(', ');
|
|
159
|
+
const args = (loops) => loops.flatMap((l) => [l.item, l.index]).join(', ');
|
|
160
|
+
const local = (loops, extra = {}) => {
|
|
161
|
+
const names = new Map(scope.names);
|
|
162
|
+
for (const l of loops) {
|
|
163
|
+
names.delete(l.item);
|
|
164
|
+
names.delete(l.index);
|
|
165
|
+
}
|
|
166
|
+
for (const [k, v] of Object.entries(extra))
|
|
167
|
+
names.set(k, v);
|
|
168
|
+
return routeScope({ names });
|
|
169
|
+
};
|
|
170
|
+
const expr = (code, loops) => {
|
|
171
|
+
const m = `$b${next++}`;
|
|
172
|
+
methods.push(` ${m}(${params(loops)}) { return ${core.rewrite(code, local(loops))}; }`);
|
|
173
|
+
return m;
|
|
174
|
+
};
|
|
175
|
+
const handler = (e, loops) => {
|
|
176
|
+
const m = `$e${next++}`;
|
|
177
|
+
let code;
|
|
178
|
+
if (ts.isArrowFunction(e) || ts.isFunctionExpression(e)) {
|
|
179
|
+
const p = e.parameters[0] ? e.parameters[0].name.text : null;
|
|
180
|
+
const extra = p ? { [p]: '$event' } : {};
|
|
181
|
+
code = ts.isBlock(e.body) ? core.rewrite(e.body.getText(), local(loops, extra), 'statements') : `${core.rewrite(e.body.getText(), local(loops, extra)).slice(1, -1)};`;
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
const t = e.getText();
|
|
185
|
+
code = `${core.rewrite(t, local(loops)).slice(1, -1)}(${arity.get(t) === 0 ? '' : '$event'});`;
|
|
186
|
+
}
|
|
187
|
+
methods.push(` ${m}(${[params(loops), '$event: $EventData'].filter(Boolean).join(', ')}) { ${code} }`);
|
|
188
|
+
return m;
|
|
189
|
+
};
|
|
190
|
+
const element = (n, loops) => {
|
|
191
|
+
const open = ts.isJsxElement(n) ? n.openingElement : n;
|
|
192
|
+
const tag = open.tagName.getText();
|
|
193
|
+
if (listTag && tag === listTag)
|
|
194
|
+
return list(open, loops);
|
|
195
|
+
const attrs = [];
|
|
196
|
+
const events = [];
|
|
197
|
+
const isComponent = /^[A-Z]/.test(tag);
|
|
198
|
+
for (const a of open.attributes.properties) {
|
|
199
|
+
if (!ts.isJsxAttribute(a))
|
|
200
|
+
throw new Error(`${path}: spread attributes are not supported in a release build yet`);
|
|
201
|
+
const attr = a.name.getText();
|
|
202
|
+
if (attr === 'key')
|
|
203
|
+
continue;
|
|
204
|
+
const name = attr === 'className' ? 'class' : attr;
|
|
205
|
+
const init = a.initializer;
|
|
206
|
+
if (!isComponent && /^on[A-Z]/.test(attr) && init && ts.isJsxExpression(init) && init.expression) {
|
|
207
|
+
events.push({ name: attr[2].toLowerCase() + attr.slice(3), method: handler(init.expression, loops) });
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
if (!init)
|
|
211
|
+
attrs.push({ name, value: 'true' });
|
|
212
|
+
else if (ts.isStringLiteral(init))
|
|
213
|
+
attrs.push({ name, value: init.text });
|
|
214
|
+
else if (ts.isJsxExpression(init) && init.expression)
|
|
215
|
+
attrs.push({ name, method: expr(init.expression.getText(), loops) });
|
|
216
|
+
}
|
|
217
|
+
if (isComponent)
|
|
218
|
+
return { kind: 'component', name: tag, props: attrs, events };
|
|
219
|
+
const element = core.canonical(tag);
|
|
220
|
+
if (!element)
|
|
221
|
+
throw new Error(`${path}: <${tag}> is not a @nativescript/core element the release build knows`);
|
|
222
|
+
return { kind: 'element', tag: element, attrs, events, children: ts.isJsxElement(n) ? children(n.children, loops) : [] };
|
|
223
|
+
};
|
|
224
|
+
/**
|
|
225
|
+
* react-nativescript's `<ListView items cellFactory>`, or `cellFactories` (a `new Map` of key →
|
|
226
|
+
* `{ placeholderItem, cellFactory }`) chosen by `itemTemplateSelector(item, index, items)`. A cell
|
|
227
|
+
* factory is called with the item only.
|
|
228
|
+
*/
|
|
229
|
+
const list = (open, loops) => {
|
|
230
|
+
const attrs = [];
|
|
231
|
+
const events = [];
|
|
232
|
+
const factories = [];
|
|
233
|
+
let single = null;
|
|
234
|
+
let selector = null;
|
|
235
|
+
for (const a of open.attributes.properties) {
|
|
236
|
+
if (!ts.isJsxAttribute(a))
|
|
237
|
+
throw new Error(`${path}: spread attributes are not supported in a release build yet`);
|
|
238
|
+
const attr = a.name.getText();
|
|
239
|
+
const init = a.initializer;
|
|
240
|
+
const e = init && ts.isJsxExpression(init) ? init.expression : undefined;
|
|
241
|
+
if (attr === 'key')
|
|
242
|
+
continue;
|
|
243
|
+
if (attr === 'cellFactory' && e) {
|
|
244
|
+
single = e;
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
if (attr === 'itemTemplateSelector' && e) {
|
|
248
|
+
selector = e;
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
if (attr === 'cellFactories' && e) {
|
|
252
|
+
factories.push(...cellFactories(e));
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
if (/^on[A-Z]/.test(attr) && e) {
|
|
256
|
+
events.push({ name: attr[2].toLowerCase() + attr.slice(3), method: handler(e, loops) });
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
if (!init)
|
|
260
|
+
attrs.push({ name: attr, value: 'true' });
|
|
261
|
+
else if (ts.isStringLiteral(init))
|
|
262
|
+
attrs.push({ name: attr, value: init.text });
|
|
263
|
+
else if (e)
|
|
264
|
+
attrs.push({ name: attr, method: expr(e.getText(), loops) });
|
|
265
|
+
}
|
|
266
|
+
const items = attrs.find((a) => a.name === 'items');
|
|
267
|
+
if (!items || !('method' in items))
|
|
268
|
+
throw new Error(`${path}: <${listTag}> needs items={…}`);
|
|
269
|
+
const rows = `this.${items.method}(${args(loops)})`;
|
|
270
|
+
const row = (fn) => {
|
|
271
|
+
while (ts.isParenthesizedExpression(fn))
|
|
272
|
+
fn = fn.expression;
|
|
273
|
+
if (!(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) || fn.parameters.length > 1)
|
|
274
|
+
throw new Error(`${path}: a cell factory is a function of the item`);
|
|
275
|
+
if (ts.isBlock(fn.body))
|
|
276
|
+
throw new Error(`${path}: a cell factory with a block body is not supported in a release build yet`);
|
|
277
|
+
const item = fn.parameters[0] ? fn.parameters[0].name.text : `$item${loops.length}`;
|
|
278
|
+
const index = `$i${loops.length}`;
|
|
279
|
+
const inner = [...loops, { item, index, param: `${item} = ${rows}[0], ${index} = 0` }];
|
|
280
|
+
return { item, index, inner, body: jsx(fn.body, inner) };
|
|
281
|
+
};
|
|
282
|
+
const selectorMethod = (inner, code) => {
|
|
283
|
+
const m = `$b${next++}`;
|
|
284
|
+
methods.push(` ${m}(${params(inner)}): string { return ${code}; }`);
|
|
285
|
+
attrs.push({ name: 'itemTemplateSelector', method: m });
|
|
286
|
+
};
|
|
287
|
+
let children;
|
|
288
|
+
if (selector && factories.length) {
|
|
289
|
+
selectorMethod([...loops, { item: '$item', index: '$index', param: `$item = ${rows}[0], $index = 0` }], `${core.rewrite(selector.getText(), local(loops))}($item, $index, ${rows})`);
|
|
290
|
+
children = factories.map(({ key, fn }) => {
|
|
291
|
+
const r = row(fn);
|
|
292
|
+
return { kind: 'template', key, item: r.item, index: r.index, body: r.body };
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
else {
|
|
296
|
+
// Without a selector, or without factories to select from, every row is `cellFactory`'s.
|
|
297
|
+
if (!single)
|
|
298
|
+
throw new Error(`${path}: <${listTag}> needs a cellFactory`);
|
|
299
|
+
const r = row(single);
|
|
300
|
+
const { templates, selector: choose } = core.rowTemplates(r.body, r.item, r.index);
|
|
301
|
+
if (choose)
|
|
302
|
+
selectorMethod(r.inner, choose((m) => `this.${m}(${args(r.inner)})`));
|
|
303
|
+
children = templates;
|
|
304
|
+
}
|
|
305
|
+
return { kind: 'element', tag: 'ListView', attrs, events, children };
|
|
306
|
+
};
|
|
307
|
+
/** `new Map([['header', { placeholderItem, cellFactory: (item) => <…/> }], …])`. */
|
|
308
|
+
const cellFactories = (e) => {
|
|
309
|
+
const entries = ts.isNewExpression(e) && e.expression.getText() === 'Map' ? e.arguments?.[0] : undefined;
|
|
310
|
+
if (!entries || !ts.isArrayLiteralExpression(entries))
|
|
311
|
+
throw new Error(`${path}: cellFactories={…} needs an inline new Map([...]) in a release build`);
|
|
312
|
+
return entries.elements.map((entry) => {
|
|
313
|
+
const [k, v] = ts.isArrayLiteralExpression(entry) ? entry.elements : [];
|
|
314
|
+
const fn = v && ts.isObjectLiteralExpression(v) ? v.properties.find((p) => ts.isPropertyAssignment(p) && p.name.getText() === 'cellFactory')?.initializer : undefined;
|
|
315
|
+
if (!k || !ts.isStringLiteral(k) || !fn)
|
|
316
|
+
throw new Error(`${path}: a cellFactories entry is ['key', { placeholderItem, cellFactory }]`);
|
|
317
|
+
return { key: k.text, fn };
|
|
318
|
+
});
|
|
319
|
+
};
|
|
320
|
+
const jsx = (e, loops) => {
|
|
321
|
+
while (ts.isParenthesizedExpression(e))
|
|
322
|
+
e = e.expression;
|
|
323
|
+
if (ts.isJsxElement(e) || ts.isJsxSelfClosingElement(e))
|
|
324
|
+
return [element(e, loops)];
|
|
325
|
+
if (ts.isJsxFragment(e))
|
|
326
|
+
return children(e.children, loops);
|
|
327
|
+
// `cond && <X/>`
|
|
328
|
+
if (ts.isBinaryExpression(e) && e.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken)
|
|
329
|
+
return [{ kind: 'if', branches: [{ cond: expr(e.left.getText(), loops), body: jsx(e.right, loops) }] }];
|
|
330
|
+
// `cond ? <A/> : <B/>`
|
|
331
|
+
if (ts.isConditionalExpression(e))
|
|
332
|
+
return [{ kind: 'if', branches: [{ cond: expr(e.condition.getText(), loops), body: jsx(e.whenTrue, loops) }, { cond: null, body: jsx(e.whenFalse, loops) }] }];
|
|
333
|
+
// `list.map((item, i) => <X key={…}/>)`
|
|
334
|
+
if (ts.isCallExpression(e) && ts.isPropertyAccessExpression(e.expression) && e.expression.name.text === 'map') {
|
|
335
|
+
const cb = e.arguments[0];
|
|
336
|
+
const item = cb.parameters[0].name.text;
|
|
337
|
+
const index = cb.parameters[1] ? cb.parameters[1].name.text : `$i${loops.length}`;
|
|
338
|
+
const items = expr(e.expression.expression.getText(), loops);
|
|
339
|
+
const inner = [...loops, { item, index, param: `${item} = this.${items}(${args(loops)})[0], ${index} = 0` }];
|
|
340
|
+
let body = cb.body;
|
|
341
|
+
while (ts.isParenthesizedExpression(body))
|
|
342
|
+
body = body.expression;
|
|
343
|
+
const open = ts.isJsxElement(body) ? body.openingElement : ts.isJsxSelfClosingElement(body) ? body : null;
|
|
344
|
+
const keyAttr = open?.attributes.properties.find((a) => ts.isJsxAttribute(a) && a.name.getText() === 'key');
|
|
345
|
+
const key = keyAttr?.initializer && ts.isJsxExpression(keyAttr.initializer) ? expr(keyAttr.initializer.expression.getText(), inner) : keyAttr?.initializer && ts.isStringLiteral(keyAttr.initializer) ? expr(keyAttr.initializer.getText(), inner) : null;
|
|
346
|
+
return [{ kind: 'for', items, key, item, index, body: jsx(body, inner) }];
|
|
347
|
+
}
|
|
348
|
+
throw new Error(`${path}: {${e.getText().slice(0, 50)}} in JSX is not supported in a release build yet`);
|
|
349
|
+
};
|
|
350
|
+
const children = (list, loops) => list.flatMap((c) => {
|
|
351
|
+
if (ts.isJsxText(c))
|
|
352
|
+
return [];
|
|
353
|
+
if (ts.isJsxExpression(c))
|
|
354
|
+
return c.expression ? jsx(c.expression, loops) : [];
|
|
355
|
+
return jsx(c, loops);
|
|
356
|
+
});
|
|
357
|
+
let template = jsx(ret.expression, []);
|
|
358
|
+
if (screen?.title) {
|
|
359
|
+
// The navigator's header for this screen is the page's action bar.
|
|
360
|
+
const title = 'value' in screen.title ? { name: 'title', value: screen.title.value } : { name: 'title', method: expr(screen.title.code, []) };
|
|
361
|
+
template = [{ kind: 'element', tag: 'ActionBar', attrs: [title], events: [], children: [] }, ...template];
|
|
362
|
+
}
|
|
363
|
+
const source = [`import { $writable, $state, $navigateTo, type EventData as $EventData } from '@nativescript/release';`, ...imports, '', `export default class ${name} {`, ...fields, ...methods, '}', ''].join('\n');
|
|
364
|
+
return { name, file: `${dirname(path)}/${name}.react.ts`, source, props, template, page: !!screen };
|
|
365
|
+
}
|
|
366
|
+
/** `navigation.navigate('Detail', { recipe })` → push the Detail screen's page with those props. */
|
|
367
|
+
function navigate(code, navigation, screens) {
|
|
368
|
+
if (!navigation)
|
|
369
|
+
return code;
|
|
370
|
+
return code.replace(new RegExp(`\\b${navigation}\\.navigate\\(\\s*['"](\\w+)['"]\\s*,\\s*`, 'g'), (_, route) => {
|
|
371
|
+
const screen = screens.find((s) => s.name === route);
|
|
372
|
+
if (!screen)
|
|
373
|
+
throw new Error(`navigate('${route}'): no such screen`);
|
|
374
|
+
return `$navigateTo(${screen.component}, `;
|
|
375
|
+
}).replace(new RegExp(`\\$navigateTo\\((\\w+), (\\{[^}]*\\})\\)`, 'g'), (_, c, p) => `$navigateTo(${c}, { props: ${p} })`);
|
|
376
|
+
}
|
|
377
|
+
/** The params a screen's route takes, from the navigator's param list type (`Routes`). */
|
|
378
|
+
function routeParams(files, route) {
|
|
379
|
+
for (const [file, text] of files) {
|
|
380
|
+
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
|
|
381
|
+
for (const st of sf.statements) {
|
|
382
|
+
if (!ts.isTypeAliasDeclaration(st) || !ts.isTypeLiteralNode(st.type))
|
|
383
|
+
continue;
|
|
384
|
+
const member = st.type.members.find((m) => ts.isPropertySignature(m) && m.name.text === route);
|
|
385
|
+
if (!member?.type)
|
|
386
|
+
continue;
|
|
387
|
+
const params = ts.isTypeLiteralNode(member.type) ? member.type.members.filter(ts.isPropertySignature).map((m) => m.name.text) : [];
|
|
388
|
+
return { alias: st.name.text, file, params };
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
return null;
|
|
392
|
+
}
|
|
393
|
+
function relativeModule(from, to) {
|
|
394
|
+
const r = relative(dirname(from), to).replace(/\.tsx?$/, '');
|
|
395
|
+
return r.startsWith('.') ? r : './' + r;
|
|
396
|
+
}
|
|
397
|
+
/** The stack navigator's screens and the initial route, from the `<Stack.Navigator>` JSX. */
|
|
398
|
+
export function reactScreens(text) {
|
|
399
|
+
const sf = ts.createSourceFile('nav.tsx', text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
|
|
400
|
+
const screens = [];
|
|
401
|
+
let initial = '';
|
|
402
|
+
let container = null;
|
|
403
|
+
const visit = (n) => {
|
|
404
|
+
if (ts.isVariableDeclaration(n) && n.initializer && ts.isArrowFunction(n.initializer) && /Navigator|NavigationContainer/.test(n.initializer.getText()))
|
|
405
|
+
container = n.name.text;
|
|
406
|
+
if (ts.isJsxOpeningElement(n) || ts.isJsxSelfClosingElement(n)) {
|
|
407
|
+
const tag = n.tagName.getText();
|
|
408
|
+
const attr = (k) => n.attributes.properties.find((a) => ts.isJsxAttribute(a) && a.name.getText() === k)?.initializer;
|
|
409
|
+
if (tag.endsWith('.Navigator')) {
|
|
410
|
+
const i = attr('initialRouteName');
|
|
411
|
+
if (i && ts.isStringLiteral(i))
|
|
412
|
+
initial = i.text;
|
|
413
|
+
}
|
|
414
|
+
if (tag.endsWith('.Screen')) {
|
|
415
|
+
const nameInit = attr('name');
|
|
416
|
+
const comp = attr('component').expression.getText();
|
|
417
|
+
const opts = attr('options');
|
|
418
|
+
let title = null;
|
|
419
|
+
if (opts && ts.isJsxExpression(opts) && opts.expression) {
|
|
420
|
+
let o = opts.expression;
|
|
421
|
+
let routeVar = '';
|
|
422
|
+
if (ts.isArrowFunction(o)) {
|
|
423
|
+
const p = o.parameters[0]?.name;
|
|
424
|
+
if (p && ts.isObjectBindingPattern(p))
|
|
425
|
+
routeVar = p.elements[0].name.text;
|
|
426
|
+
o = o.body;
|
|
427
|
+
while (ts.isParenthesizedExpression(o))
|
|
428
|
+
o = o.expression;
|
|
429
|
+
}
|
|
430
|
+
if (ts.isObjectLiteralExpression(o)) {
|
|
431
|
+
const t = o.properties.find((p) => ts.isPropertyAssignment(p) && p.name.text === 'title');
|
|
432
|
+
if (t && ts.isStringLiteral(t.initializer))
|
|
433
|
+
title = { value: t.initializer.text };
|
|
434
|
+
else if (t)
|
|
435
|
+
title = { code: routeVar ? t.initializer.getText().replace(new RegExp(`\\b${routeVar}\\.params\\.`, 'g'), '') : t.initializer.getText() };
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
screens.push({ name: nameInit.text, component: comp, title });
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
ts.forEachChild(n, visit);
|
|
442
|
+
};
|
|
443
|
+
visit(sf);
|
|
444
|
+
return { screens, initial: initial || screens[0]?.name || '', container };
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* A zustand store (`create<State>()((set) => ({ ...state, ...actions }))`) as a
|
|
448
|
+
* virtual class: a signal per state field read through a getter, a method per
|
|
449
|
+
* action, and `set((s) => ({ field: value }))` as writes of those signals.
|
|
450
|
+
*/
|
|
451
|
+
export function zustandStore(text) {
|
|
452
|
+
const sf = ts.createSourceFile('store.ts', text, ts.ScriptTarget.Latest, true);
|
|
453
|
+
let out = '';
|
|
454
|
+
for (const st of sf.statements) {
|
|
455
|
+
if (!ts.isVariableStatement(st))
|
|
456
|
+
continue;
|
|
457
|
+
for (const d of st.declarationList.declarations) {
|
|
458
|
+
const init = d.initializer;
|
|
459
|
+
if (!init || !ts.isCallExpression(init) || !ts.isCallExpression(init.expression) || init.expression.expression.getText() !== 'create')
|
|
460
|
+
continue;
|
|
461
|
+
const stateType = init.expression.typeArguments?.[0]?.getText() ?? 'any';
|
|
462
|
+
const factory = init.arguments[0];
|
|
463
|
+
const setName = factory.parameters[0]?.name?.text ?? 'set';
|
|
464
|
+
let obj = factory.body;
|
|
465
|
+
while (ts.isParenthesizedExpression(obj))
|
|
466
|
+
obj = obj.expression;
|
|
467
|
+
if (!ts.isObjectLiteralExpression(obj))
|
|
468
|
+
return null;
|
|
469
|
+
const name = d.name.text;
|
|
470
|
+
const cls = name.replace(/^use/, '') + 'Store';
|
|
471
|
+
const members = [];
|
|
472
|
+
const fields = new Set();
|
|
473
|
+
for (const p of obj.properties) {
|
|
474
|
+
if (ts.isPropertyAssignment(p) && !(ts.isArrowFunction(p.initializer) || ts.isFunctionExpression(p.initializer)))
|
|
475
|
+
fields.add(p.name.text);
|
|
476
|
+
}
|
|
477
|
+
for (const p of obj.properties) {
|
|
478
|
+
if (!ts.isPropertyAssignment(p))
|
|
479
|
+
continue;
|
|
480
|
+
const key = p.name.text;
|
|
481
|
+
const v = p.initializer;
|
|
482
|
+
if (fields.has(key)) {
|
|
483
|
+
members.push(` $${key} = $writable<${stateType}['${key}']>(${v.getText()});`);
|
|
484
|
+
members.push(` get ${key}(): ${stateType}['${key}'] { return this.$${key}(); }`);
|
|
485
|
+
continue;
|
|
486
|
+
}
|
|
487
|
+
const fn = v;
|
|
488
|
+
const params = fn.parameters.map((x) => x.getText()).join(', ');
|
|
489
|
+
// `set((s) => ({ a: x }))` and `set({ a: x })`: write each named field.
|
|
490
|
+
const body = fn.body.getText().replace(new RegExp(`\\b${setName}\\(\\s*(?:\\(?\\s*(\\w+)\\s*\\)?\\s*=>\\s*)?\\(?\\{([^]*)\\}\\)?\\s*\\)\\s*$`), (_, s, inner) => {
|
|
491
|
+
const assigns = splitTopLevel(inner).map((part) => {
|
|
492
|
+
const at = part.indexOf(':');
|
|
493
|
+
const field = part.slice(0, at).trim();
|
|
494
|
+
const value = part.slice(at + 1).trim();
|
|
495
|
+
return `this.$${field}.set(${s ? core.rewrite(value, { names: new Map([[s, 'this']]) }) : value})`;
|
|
496
|
+
});
|
|
497
|
+
return `{ ${assigns.join('; ')}; }`;
|
|
498
|
+
});
|
|
499
|
+
members.push(` ${key}(${params}) ${body.startsWith('{') ? body : `{ ${body}; }`}`);
|
|
500
|
+
}
|
|
501
|
+
out += `class ${cls} {\n${members.join('\n')}\n}\nexport const ${name} = new ${cls}();\n`;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
if (!out)
|
|
505
|
+
return null;
|
|
506
|
+
const rest = sf.statements.filter((s) => !ts.isVariableStatement(s) || !s.getText().includes('create<')).filter((s) => !ts.isImportDeclaration(s)).map((s) => s.getText()).join('\n\n');
|
|
507
|
+
return `import { $writable } from '@nativescript/release';\n${rest}\n\n${out}`;
|
|
508
|
+
}
|
|
509
|
+
function splitTopLevel(text) {
|
|
510
|
+
const parts = [];
|
|
511
|
+
let depth = 0, start = 0;
|
|
512
|
+
for (let i = 0; i < text.length; i++) {
|
|
513
|
+
const c = text[i];
|
|
514
|
+
if ('([{'.includes(c))
|
|
515
|
+
depth++;
|
|
516
|
+
else if (')]}'.includes(c))
|
|
517
|
+
depth--;
|
|
518
|
+
else if (c === ',' && depth === 0) {
|
|
519
|
+
parts.push(text.slice(start, i));
|
|
520
|
+
start = i + 1;
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
if (text.slice(start).trim())
|
|
524
|
+
parts.push(text.slice(start));
|
|
525
|
+
return parts.map((p) => p.trim()).filter(Boolean);
|
|
526
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nstudio/nativescript-compiler-react",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "9.2.0-alpha.9",
|
|
4
|
+
"description": "The React adapter of @nstudio/nativescript-compiler: compiles a NativeScript app written with React into a native iOS or Android app with no JavaScript runtime.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"source": "./index.ts",
|
|
9
|
+
"default": "./dist/index.js"
|
|
10
|
+
},
|
|
11
|
+
"./package.json": "./package.json"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"dist/"
|
|
15
|
+
],
|
|
16
|
+
"scripts": {
|
|
17
|
+
"build": "ns-compiled-adapter build .",
|
|
18
|
+
"prepack": "npm run build"
|
|
19
|
+
},
|
|
20
|
+
"license": "MIT",
|
|
21
|
+
"repository": {
|
|
22
|
+
"type": "git",
|
|
23
|
+
"url": "https://github.com/nstudio/nativescript-compiler.git",
|
|
24
|
+
"directory": "packages/react"
|
|
25
|
+
},
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"@nstudio/nativescript-compiler": "9.2.0-alpha.9"
|
|
28
|
+
},
|
|
29
|
+
"nativescript": {
|
|
30
|
+
"compilerAdapter": {
|
|
31
|
+
"apiVersion": 1,
|
|
32
|
+
"detect": {
|
|
33
|
+
"priority": 30,
|
|
34
|
+
"dependencies": [
|
|
35
|
+
"react-nativescript",
|
|
36
|
+
"react"
|
|
37
|
+
],
|
|
38
|
+
"entryMentions": [
|
|
39
|
+
"react-nativescript"
|
|
40
|
+
],
|
|
41
|
+
"entryImports": [
|
|
42
|
+
"react"
|
|
43
|
+
]
|
|
44
|
+
},
|
|
45
|
+
"testedVersions": {
|
|
46
|
+
"react-nativescript": ">=5.0.0 <6.0.0",
|
|
47
|
+
"react": ">=18.2.0 <19.0.0"
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
"publishConfig": {
|
|
52
|
+
"access": "public"
|
|
53
|
+
}
|
|
54
|
+
}
|