embedded-react 0.20.0 → 0.21.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.
Files changed (74) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +1 -0
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +16 -46
  5. package/aot/compiler/animations.mjs +299 -57
  6. package/aot/compiler/boot.mjs +27 -2
  7. package/aot/compiler/check.mjs +61 -9
  8. package/aot/compiler/collect.mjs +516 -136
  9. package/aot/compiler/contexts.mjs +391 -0
  10. package/aot/compiler/control-flow.mjs +276 -117
  11. package/aot/compiler/custom-hooks.mjs +686 -0
  12. package/aot/compiler/elements/button.mjs +182 -0
  13. package/aot/compiler/elements/image-background.mjs +76 -0
  14. package/aot/compiler/elements/image.mjs +2 -1
  15. package/aot/compiler/elements/props.mjs +38 -3
  16. package/aot/compiler/elements/rewrite.mjs +118 -0
  17. package/aot/compiler/elements/section-list.mjs +370 -0
  18. package/aot/compiler/expressions.mjs +1351 -97
  19. package/aot/compiler/handlers.mjs +1761 -365
  20. package/aot/compiler/helper-values.mjs +312 -0
  21. package/aot/compiler/ir/nodes.mjs +40 -1
  22. package/aot/compiler/ir/reads.mjs +206 -5
  23. package/aot/compiler/ir/text.mjs +5 -1
  24. package/aot/compiler/ir/types.mjs +12 -0
  25. package/aot/compiler/kept-states.mjs +177 -0
  26. package/aot/compiler/list-items.mjs +226 -0
  27. package/aot/compiler/list-order.mjs +586 -0
  28. package/aot/compiler/list-split.mjs +259 -0
  29. package/aot/compiler/loops.mjs +582 -0
  30. package/aot/compiler/lower.mjs +191 -53
  31. package/aot/compiler/native-files.mjs +439 -0
  32. package/aot/compiler/native-header.mjs +335 -0
  33. package/aot/compiler/native-modules.mjs +1173 -0
  34. package/aot/compiler/nodes.mjs +28 -22
  35. package/aot/compiler/options.mjs +3 -2
  36. package/aot/compiler/out.mjs +14 -1
  37. package/aot/compiler/package/animations.mjs +133 -23
  38. package/aot/compiler/package/assemble.mjs +2 -4
  39. package/aot/compiler/package/bytecode.mjs +37 -8
  40. package/aot/compiler/package/checks.mjs +4 -0
  41. package/aot/compiler/package/codegen.mjs +870 -31
  42. package/aot/compiler/package/enums.mjs +10 -0
  43. package/aot/compiler/package/format.mjs +12 -1
  44. package/aot/compiler/package/lower.mjs +658 -161
  45. package/aot/compiler/package/string-caps.mjs +515 -0
  46. package/aot/compiler/package/tables.mjs +24 -0
  47. package/aot/compiler/package/writer.mjs +22 -0
  48. package/aot/compiler/parse.mjs +3 -1
  49. package/aot/compiler/record-shapes.mjs +246 -0
  50. package/aot/compiler/records.mjs +654 -0
  51. package/aot/compiler/reducers.mjs +272 -0
  52. package/aot/compiler/static-eval.mjs +315 -7
  53. package/aot/compiler/style-text.mjs +18 -3
  54. package/aot/compiler/svg.mjs +7 -4
  55. package/aot/compiler/switch-cases.mjs +198 -0
  56. package/aot/compiler/tagged-records.mjs +450 -0
  57. package/aot/compiler/typing.mjs +307 -0
  58. package/aot/compiler/updaters.mjs +320 -0
  59. package/aot/compiler/window-dimensions.mjs +94 -0
  60. package/aot/compiler/worked-values.mjs +319 -0
  61. package/aot/demo-file.mjs +30 -0
  62. package/aot/style-map.mjs +50 -2
  63. package/build.mjs +9 -1
  64. package/cli.mjs +44 -1
  65. package/hotreload/pack-split.mjs +29 -40
  66. package/pack-container.mjs +9 -1
  67. package/package.json +1 -1
  68. package/sim/embedded-react.wasm +0 -0
  69. package/sim-server.mjs +22 -22
  70. package/src/embedded-react/Dimensions.js +37 -0
  71. package/src/embedded-react/SectionList.js +1 -3
  72. package/src/embedded-react/index.d.ts +83 -3
  73. package/src/embedded-react/index.js +2 -0
  74. package/src/embedded-react/nativeModule.js +462 -0
@@ -16,20 +16,27 @@
16
16
  /*----------------------------------------------------------------------------------------------------------------------
17
17
  - Imports
18
18
  ---------------------------------------------------------------------------------------------------------------------*/
19
- import { checkNumber, lowerWithChecks, runChecks } from './check.mjs';
20
- import { evalStatic, setBinding, withUndefined } from './static-eval.mjs';
19
+ import { checkNumber, lowerWithChecks, runChecks, whenTyped } from './check.mjs';
20
+ import { evalStatic, rethrowFoldLimit, setBinding, withUndefined, } from './static-eval.mjs';
21
21
  import { abandonBoot, beginBoot, endBoot, setBootLowering } from './boot.mjs';
22
- import { findShadowedClockCalls, lowerSourcedWide, lowerExpr, } from './expressions.mjs';
23
- import { findComponent, declaredNames, moduleScope, collectState, settleBootInitials, findReturnJSX, collectComponents, collectHelpers, collectImageImports, collectSvgImports, collectCallbacks, collectMemos, collectEffects, bindConst, } from './collect.mjs';
22
+ import { bindBuiltValues, findShadowedClockCalls, foldRuntime, inferWideSlots, lowerLocal, lowerExpr, } from './expressions.mjs';
23
+ import { findComponent, bindFoldedPattern, declaredNames, moduleScope, collectState, settleBootInitials, findReturnJSX, collectComponents, collectHelpers, collectImageImports, collectSvgImports, collectCallbacks, collectMemos, collectEffects, collectNativeEvents, bindConst, } from './collect.mjs';
24
24
  import { collectAnims, collectRefs } from './animations.mjs';
25
- import { lowerEffect } from './handlers.mjs';
25
+ import { lowerEffect, lowerNativeEvent } from './handlers.mjs';
26
26
  import { collectPanResponders } from './pan-responder.mjs';
27
27
  import { emitNode } from './nodes.mjs';
28
28
  import { lowerKeyboardConfig } from './keyboard.mjs';
29
+ import { itemValueAt } from './list-items.mjs';
29
30
  import { normalizeUndefined, parseApp } from './parse.mjs';
31
+ import { collectNativeModules, optionalModulesOf } from './native-modules.mjs';
32
+ import { inlineCustomHooks } from './custom-hooks.mjs';
33
+ import { rewriteWindowDimensions } from './window-dimensions.mjs';
30
34
  import { Out } from './out.mjs';
31
- import { isStateDriven, nodesOf, updatedVectorOf } from './ir/nodes.mjs';
32
- import { nodeReads, vectorReads } from './ir/reads.mjs';
35
+ import { conditionalsOf, isStateDriven, nodesOf, updatedVectorOf, } from './ir/nodes.mjs';
36
+ import { expressionReads, listStates, nodeReads, vectorReads, workedStates, } from './ir/reads.mjs';
37
+ import { wideSlotOf } from './ir/types.mjs';
38
+ import { bindDerivedList, renderBindings } from './list-order.mjs';
39
+ import { bindContextUses, contextsOf, refuseHiddenContexts, } from './contexts.mjs';
33
40
  /*----------------------------------------------------------------------------------------------------------------------
34
41
  - Implementation
35
42
  ---------------------------------------------------------------------------------------------------------------------*/
@@ -56,6 +63,9 @@ function settleFunctions(output, hasUpdate) {
56
63
  settleStmts(statement.consequent);
57
64
  settleStmts(statement.alternate ?? []);
58
65
  }
66
+ else if (statement.kind === 'block' || statement.kind === 'loop') {
67
+ settleStmts(statement.body);
68
+ }
59
69
  }
60
70
  };
61
71
  const settle = (callback) => {
@@ -77,6 +87,9 @@ function settleFunctions(output, hasUpdate) {
77
87
  for (const timer of output.timerFunctions) {
78
88
  settle(timer.callback);
79
89
  }
90
+ for (const handler of output.nativeEventHandlers) {
91
+ settle(handler.callback);
92
+ }
80
93
  for (const animationCallback of output.animationCallbacks) {
81
94
  if (animationCallback.kind === 'completion') {
82
95
  settle(animationCallback.completion);
@@ -103,19 +116,29 @@ function settleFunctions(output, hasUpdate) {
103
116
  }
104
117
  }
105
118
  /**
106
- * Flags each state a node or drawing reads, so a write to it marks it changed and the update sets them again.
107
- * A node that also reads something untracked is set on every update, so its reads need no flag.
119
+ * Flags each state a node, drawing, or conditional reads, so a write to it marks it changed and the update sets
120
+ * them again. One that also reads something untracked is set on every update, so its reads need no flag.
108
121
  *
109
- * @param nodes The app's nodes.
122
+ * @param root The app's tree.
123
+ * @param derivedLists The lists filtered, sorted or split in render.
124
+ * @param workedValues The values memos and helpers loop for in render.
110
125
  */
111
- function watchState(nodes) {
112
- for (const node of nodes) {
113
- const vector = updatedVectorOf(node);
114
- for (const reads of [nodeReads(node), vector && vectorReads(vector)]) {
115
- reads?.forEach(record => {
116
- record.isWatched = true;
117
- });
118
- }
126
+ function watchState(root, derivedLists, workedValues) {
127
+ const reads = [
128
+ ...nodesOf(root).flatMap(node => {
129
+ const vector = updatedVectorOf(node);
130
+ return [nodeReads(node), vector && vectorReads(vector)];
131
+ }),
132
+ ...conditionalsOf(root).map(conditional => expressionReads(conditional.test)),
133
+ // A handler can read a filtered or sorted list that nothing draws, which must still be rebuilt.
134
+ ...derivedLists.map(listStates),
135
+ // So can a value a memo or a helper loops for.
136
+ ...workedValues.map(workedStates),
137
+ ];
138
+ for (const read of reads) {
139
+ read?.forEach(record => {
140
+ record.isWatched = true;
141
+ });
119
142
  }
120
143
  }
121
144
  /**
@@ -130,9 +153,10 @@ function checkStateRecords(stateRecords) {
130
153
  continue;
131
154
  for (const item of record.items) {
132
155
  for (const field of record.struct.fields) {
133
- const value = item[field.key];
134
- if (field.kind === 'string' || value == null)
156
+ const { present, value } = itemValueAt(item, field);
157
+ if (field.kind === 'string' || field.kind === 'bool' || !present) {
135
158
  continue;
159
+ }
136
160
  const number = Number(value);
137
161
  if (field.kind === 'float' || !Number.isFinite(number)) {
138
162
  checkNumber(number);
@@ -142,20 +166,40 @@ function checkStateRecords(stateRecords) {
142
166
  }
143
167
  }
144
168
  /**
145
- * Lowers a Flow B app's JSX (or TSX) source, then runs the check pass over what lowering recorded. Pure (no
146
- * I/O); the package backend (package/) writes the result.
169
+ * Widens each int slot that has to hold 64 bits. A state or ref slot is typed from its initial value, so
170
+ * `useState(0)` is an int until a setter stores Date.now() in it; the values lowering stored into the int slots
171
+ * say which hold a timestamp or a number past the int range, following one through every slot it reaches.
172
+ *
173
+ * @param wide Takes the slots widened, and what each holds.
174
+ * @param stores Every value lowering stored into an int slot.
175
+ */
176
+ function widenSlots(wide, stores) {
177
+ for (const [slot, width] of inferWideSlots(stores, new Map())) {
178
+ wide.set(slot, width);
179
+ }
180
+ for (const { slot, target } of stores) {
181
+ const width = wideSlotOf(wide, slot);
182
+ if (target && width) {
183
+ target.slotKind = 'i64';
184
+ target.widened = width;
185
+ }
186
+ }
187
+ }
188
+ /**
189
+ * Lowers a Flow B app's JSX (or TSX) source, widens the slots that hold 64 bits, then runs the typing pass and
190
+ * the check pass over what lowering recorded. Pure (no I/O); the package backend (package/) writes the result.
147
191
  *
148
192
  * @param source The App.jsx/App.tsx source text.
149
193
  * @param options compilePackage's options, resolved (see resolveOptions).
150
- * @param wide State/ref slots to declare 64-bit (see compileWidened).
151
- * @param stores Collects every value stored into an int slot.
152
194
  *
153
195
  * @returns The lowered app.
154
196
  */
155
- export function lowerApp(source, options, wide, stores) {
197
+ export function lowerApp(source, options) {
156
198
  beginBoot(source);
157
199
  try {
158
- const { result, checks } = lowerWithChecks(() => lowerProgram(source, options, wide, stores));
200
+ const wide = new Map();
201
+ const stores = [];
202
+ const { result, checks } = lowerWithChecks(() => lowerProgram(source, options, wide, stores), () => widenSlots(wide, stores));
159
203
  const app = { ...result, boot: endBoot(), checks };
160
204
  runChecks(app.checks);
161
205
  return app;
@@ -170,15 +214,21 @@ export function lowerApp(source, options, wide, stores) {
170
214
  *
171
215
  * @param source The App.jsx/App.tsx source text.
172
216
  * @param options compilePackage's options, resolved (see resolveOptions).
173
- * @param wide State/ref slots to declare 64-bit (see compileWidened).
217
+ * @param wide Takes the slots the typing pass widens.
174
218
  * @param stores Collects every value stored into an int slot.
175
219
  *
176
220
  * @returns The lowered app, without its checks.
177
221
  */
178
222
  function lowerProgram(source, options, wide, stores) {
179
223
  // Parse the app and prepare the AST for the passes below.
180
- const ast = parseApp(source, options);
224
+ let nativeModules = new Map();
225
+ const ast = parseApp(source, options, typed => {
226
+ nativeModules = collectNativeModules(typed.program, options.nativeFiles);
227
+ });
181
228
  normalizeUndefined(ast);
229
+ rewriteWindowDimensions(ast);
230
+ inlineCustomHooks(ast);
231
+ refuseHiddenContexts(ast);
182
232
  const shadowedClock = findShadowedClockCalls(ast);
183
233
  // Seed the module scope with image imports (each is its baked-name string) so consts that use them can fold.
184
234
  const { screen } = options;
@@ -193,32 +243,87 @@ function lowerProgram(source, options, wide, stores) {
193
243
  for (const name of declaredNames(component.body.body)) {
194
244
  delete scope[name];
195
245
  }
246
+ // What the module itself can read, where a context's default is worked out.
247
+ const imageNames = new Map([...imageImports].map(([, imageImport]) => [
248
+ imageImport.name,
249
+ imageImport.importPath,
250
+ ])); // asset name → path
251
+ const moduleEnvironment = {
252
+ state: new Map(),
253
+ locals: new Map(),
254
+ constants: moduleConstants,
255
+ moduleConstants,
256
+ animations: new Map(),
257
+ refs: new Map(),
258
+ pans: new Map(),
259
+ callbacks: new Map(),
260
+ helpers: collectHelpers({ type: 'BlockStatement', body: [], directives: [] }, ast.program),
261
+ imageNames,
262
+ svgImports,
263
+ svgArtifacts: options.svgArtifacts || {},
264
+ caps: options.caps,
265
+ wide,
266
+ stores,
267
+ shadowedClock,
268
+ constantLists: new Map(),
269
+ derivedLists: new Map(),
270
+ workedValues: new Map(),
271
+ splitLists: new Map(),
272
+ functionProps: new Map(),
273
+ children: null,
274
+ nativeModules,
275
+ };
276
+ moduleEnvironment.contexts = {
277
+ records: contextsOf(ast.program),
278
+ defaults: moduleEnvironment,
279
+ };
280
+ // The App has no provider above it, so a context it reads is the default.
281
+ const appLocals = new Map();
282
+ const appFunctionProps = new Map();
283
+ const contextNames = bindContextUses(component.body, moduleEnvironment, {
284
+ scope,
285
+ locals: appLocals,
286
+ functionProps: appFunctionProps,
287
+ lists: new Map(),
288
+ });
196
289
  for (const statement of component.body.body) {
197
290
  if (statement.type !== 'VariableDeclaration' ||
198
291
  statement.kind !== 'const') {
199
292
  continue;
200
293
  }
201
294
  for (const declarator of statement.declarations) {
295
+ if (declarator.id.type === 'ObjectPattern' && declarator.init) {
296
+ try {
297
+ bindFoldedPattern(scope, declarator.id, declarator.init);
298
+ }
299
+ catch (error) {
300
+ rethrowFoldLimit(error); // not a fold, so bindBuiltValues binds it
301
+ }
302
+ continue;
303
+ }
202
304
  if (declarator.id.type !== 'Identifier' || !declarator.init)
203
305
  continue;
306
+ if (contextNames.has(declarator.id.name))
307
+ continue;
204
308
  try {
205
309
  setBinding(scope, declarator.id.name, bindConst(declarator.id.name, evalStatic(declarator.init, withUndefined(scope), 'boot')));
206
310
  }
207
- catch {
311
+ catch (error) {
312
+ rethrowFoldLimit(error);
208
313
  // A dynamic const must hide a same-named module const, or the JSX quietly renders the module value.
209
314
  delete scope[declarator.id.name];
210
315
  }
211
316
  }
212
317
  }
213
318
  // Collect the component's state; a state name hides any module const of the same name from the folds.
214
- const state = collectState(component.body, scope, options.caps, '', wide);
319
+ const state = collectState(component.body, scope, options.caps, '', ast.program);
215
320
  for (const name of state.byName.keys()) {
216
321
  delete scope[name];
217
322
  }
218
323
  // Collect the component's other hooks, plus the file's helpers and child components.
219
324
  const rootJSX = findReturnJSX(component.body, scope);
220
325
  const animations = collectAnims(component.body, scope);
221
- const refs = collectRefs(component.body, scope, '', wide);
326
+ const refs = collectRefs(component.body, scope);
222
327
  for (const name of [...animations.keys(), ...refs.keys()]) {
223
328
  delete scope[name];
224
329
  }
@@ -227,14 +332,10 @@ function lowerProgram(source, options, wide, stores) {
227
332
  const memos = collectMemos(component.body);
228
333
  const helpers = collectHelpers(component.body, ast.program);
229
334
  const components = collectComponents(ast.program);
230
- const imageNames = new Map([...imageImports].map(([, imageImport]) => [
231
- imageImport.name,
232
- imageImport.importPath,
233
- ])); // asset name → path
234
335
  // The expression environment every emitter compiles against.
235
336
  const environment = {
236
337
  state: state.byName,
237
- locals: new Map(),
338
+ locals: appLocals,
238
339
  constants: scope,
239
340
  moduleConstants, // what an inlined child component sees (see emitComponent)
240
341
  animations: animations,
@@ -249,30 +350,45 @@ function lowerProgram(source, options, wide, stores) {
249
350
  wide,
250
351
  stores,
251
352
  shadowedClock,
353
+ constantLists: moduleEnvironment.constantLists,
354
+ derivedLists: moduleEnvironment.derivedLists,
355
+ workedValues: moduleEnvironment.workedValues,
356
+ splitLists: moduleEnvironment.splitLists,
357
+ functionProps: appFunctionProps,
358
+ contexts: moduleEnvironment.contexts,
359
+ nativeModules,
252
360
  };
253
361
  // A value worked out at boot lowers its slot against the app's environment.
254
362
  setBootLowering(environment, lowerExpr);
255
363
  settleBootInitials(state.byName.values());
256
364
  // Before emit, fold each memo or inline its expression at each use (no cache needed: dep tracking re-applies).
257
- for (const [name, expression] of memos) {
365
+ for (const { name, expression, isMemo } of renderBindings(component.body, memos)) {
366
+ if (!isMemo) {
367
+ bindDerivedList(name, expression, environment);
368
+ continue;
369
+ }
258
370
  try {
259
371
  setBinding(scope, name, bindConst(name, evalStatic(expression, scope, 'boot')));
260
372
  }
261
- catch {
262
- const memo = lowerSourcedWide(expression, environment);
263
- environment.locals.set(name, {
264
- slotKind: memo.slotKind,
265
- isBoolean: memo.isBoolean,
266
- isLiteral: memo.isLiteral,
267
- wide: memo.wide,
268
- source: memo.source,
269
- expression: memo.expression,
270
- });
373
+ catch (error) {
374
+ rethrowFoldLimit(error);
375
+ if (bindDerivedList(name, expression, environment)) {
376
+ continue;
377
+ }
378
+ if (expression.type === 'ArrayExpression' ||
379
+ expression.type === 'ObjectExpression') {
380
+ setBinding(scope, name, foldRuntime(expression, environment));
381
+ continue;
382
+ }
383
+ environment.locals.set(name, lowerLocal(expression, environment));
271
384
  delete scope[name]; // a runtime binding beats a module const of its name in every fold
272
385
  }
273
386
  }
387
+ bindBuiltValues(component.body.body, environment);
274
388
  // Emit the scene graph from the root JSX; `output` collects everything else it lowers.
275
389
  const output = new Out(components, ast.program);
390
+ output.release = Boolean(options.release);
391
+ output.optionalModules = optionalModulesOf(nativeModules);
276
392
  const keyboard = lowerKeyboardConfig(ast.program); // a module-level setKeyboardConfig({...})
277
393
  const root = emitNode(rootJSX, scope, output, environment, state);
278
394
  // Emit registered only the images it reached; a dynamic source can't be enumerated, so bake every import.
@@ -285,13 +401,35 @@ function lowerProgram(source, options, wide, stores) {
285
401
  for (const effect of collectEffects(component.body)) {
286
402
  lowerEffect(effect, environment, state, output);
287
403
  }
288
- // An update exists only when something has to be re-applied after a state change.
289
- const hasUpdate = nodesOf(root).some(node => isStateDriven(node) || updatedVectorOf(node) !== null) || output.dependencyEffects.length > 0;
290
- settleFunctions(output, hasUpdate);
291
- if (hasUpdate) {
292
- watchState(nodesOf(root));
404
+ for (const call of collectNativeEvents(component.body)) {
405
+ lowerNativeEvent(call, environment, state, output);
293
406
  }
294
- const stateRecords = [...state.byName.values(), ...output.childStateRecords];
407
+ // An update exists only when something has to be re-applied after a state change, or a list filtered or sorted
408
+ // in render rebuilt.
409
+ const derivedLists = [...environment.derivedLists.values()].flatMap(lists => [...lists.values()]);
410
+ const workedValues = [...environment.workedValues.values()].flatMap(values => [...values.values()]);
411
+ // What the tree reads is known once it is typed.
412
+ whenTyped(() => {
413
+ const hasUpdate = nodesOf(root).some(node => isStateDriven(node) || updatedVectorOf(node) !== null) ||
414
+ conditionalsOf(root).some(conditional => !conditional.toggle) ||
415
+ output.dependencyEffects.length > 0 ||
416
+ derivedLists.length > 0 ||
417
+ workedValues.length > 0;
418
+ settleFunctions(output, hasUpdate);
419
+ if (hasUpdate) {
420
+ watchState(root, derivedLists, workedValues);
421
+ }
422
+ });
423
+ const stateRecords = [
424
+ ...state.byName.values(),
425
+ ...output.childStateRecords,
426
+ ...environment.constantLists.values(),
427
+ ...derivedLists,
428
+ ...workedValues,
429
+ ...[...environment.splitLists.values()].flatMap(lists => [
430
+ ...lists.values(),
431
+ ]),
432
+ ];
295
433
  checkStateRecords(stateRecords);
296
434
  return {
297
435
  state: stateRecords,