embedded-react 0.20.0 → 0.22.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 (140) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +3 -2
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +17 -47
  5. package/aot/compiler/alerts.mjs +604 -0
  6. package/aot/compiler/animations.mjs +299 -57
  7. package/aot/compiler/boot.mjs +27 -2
  8. package/aot/compiler/check.mjs +62 -10
  9. package/aot/compiler/collect.mjs +517 -137
  10. package/aot/compiler/contexts.mjs +391 -0
  11. package/aot/compiler/control-flow.mjs +276 -117
  12. package/aot/compiler/custom-hooks.mjs +686 -0
  13. package/aot/compiler/elements/button.mjs +182 -0
  14. package/aot/compiler/elements/image-background.mjs +76 -0
  15. package/aot/compiler/elements/image.mjs +2 -1
  16. package/aot/compiler/elements/props.mjs +47 -8
  17. package/aot/compiler/elements/rewrite.mjs +118 -0
  18. package/aot/compiler/elements/section-list.mjs +370 -0
  19. package/aot/compiler/expressions.mjs +1378 -97
  20. package/aot/compiler/handlers.mjs +1807 -354
  21. package/aot/compiler/helper-values.mjs +312 -0
  22. package/aot/compiler/ir/nodes.mjs +40 -1
  23. package/aot/compiler/ir/reads.mjs +206 -5
  24. package/aot/compiler/ir/text.mjs +5 -1
  25. package/aot/compiler/ir/types.mjs +12 -0
  26. package/aot/compiler/kept-states.mjs +177 -0
  27. package/aot/compiler/keyboard-dismiss.mjs +99 -0
  28. package/aot/compiler/keyboard.mjs +1 -1
  29. package/aot/compiler/list-items.mjs +226 -0
  30. package/aot/compiler/list-order.mjs +586 -0
  31. package/aot/compiler/list-split.mjs +259 -0
  32. package/aot/compiler/loops.mjs +582 -0
  33. package/aot/compiler/lower.mjs +203 -53
  34. package/aot/compiler/native-files.mjs +439 -0
  35. package/aot/compiler/native-header.mjs +335 -0
  36. package/aot/compiler/native-modules.mjs +1173 -0
  37. package/aot/compiler/nodes.mjs +45 -31
  38. package/aot/compiler/options.mjs +3 -2
  39. package/aot/compiler/out.mjs +18 -1
  40. package/aot/compiler/package/animations.mjs +133 -23
  41. package/aot/compiler/package/assemble.mjs +2 -4
  42. package/aot/compiler/package/bytecode.mjs +37 -8
  43. package/aot/compiler/package/checks.mjs +4 -0
  44. package/aot/compiler/package/codegen.mjs +906 -33
  45. package/aot/compiler/package/enums.mjs +10 -0
  46. package/aot/compiler/package/format.mjs +16 -3
  47. package/aot/compiler/package/lower.mjs +707 -176
  48. package/aot/compiler/package/string-caps.mjs +515 -0
  49. package/aot/compiler/package/tables.mjs +24 -0
  50. package/aot/compiler/package/writer.mjs +22 -0
  51. package/aot/compiler/parse.mjs +3 -1
  52. package/aot/compiler/record-shapes.mjs +246 -0
  53. package/aot/compiler/records.mjs +654 -0
  54. package/aot/compiler/reducers.mjs +272 -0
  55. package/aot/compiler/scroll-to.mjs +112 -0
  56. package/aot/compiler/static-eval.mjs +315 -7
  57. package/aot/compiler/style-text.mjs +20 -5
  58. package/aot/compiler/svg.mjs +13 -7
  59. package/aot/compiler/switch-cases.mjs +198 -0
  60. package/aot/compiler/tagged-records.mjs +450 -0
  61. package/aot/compiler/typing.mjs +307 -0
  62. package/aot/compiler/updaters.mjs +321 -0
  63. package/aot/compiler/window-dimensions.mjs +94 -0
  64. package/aot/compiler/worked-values.mjs +319 -0
  65. package/aot/demo-file.mjs +30 -0
  66. package/aot/style-map.mjs +94 -3
  67. package/assets/bake-font.mjs +187 -244
  68. package/assets/bake-image.mjs +47 -71
  69. package/assets/bake-svg.mjs +465 -533
  70. package/assets/build-builtin-font.mjs +14 -27
  71. package/assets/emit-c.mjs +124 -204
  72. package/assets/emit-container.mjs +129 -197
  73. package/assets/emit-pack.mjs +92 -136
  74. package/assets/font-config.mjs +19 -27
  75. package/assets/font-sizes.mjs +432 -507
  76. package/assets/glyph-coverage.mjs +170 -214
  77. package/assets/index.mjs +52 -97
  78. package/assets/rasterize.mjs +173 -194
  79. package/assets/svg-loader.mjs +42 -48
  80. package/build.mjs +85 -94
  81. package/cli.mjs +490 -586
  82. package/compile-bin.mjs +24 -36
  83. package/flash.mjs +297 -401
  84. package/hotreload/dev-device.mjs +229 -270
  85. package/hotreload/pack-app.mjs +118 -159
  86. package/hotreload/pack-split.mjs +146 -213
  87. package/hotreload/package-transfer.mjs +128 -131
  88. package/hotreload/protocol.mjs +118 -118
  89. package/hotreload/uploader.mjs +132 -159
  90. package/hotreload/watch-tree.mjs +56 -65
  91. package/pack-container.mjs +94 -116
  92. package/package.json +19 -16
  93. package/persist-transform.mjs +89 -105
  94. package/qjsc-wasm.mjs +47 -72
  95. package/sim/embedded-react.wasm +0 -0
  96. package/sim/index.html +1 -1
  97. package/sim-server.mjs +260 -354
  98. package/src/embedded-react/Alert.mjs +112 -0
  99. package/src/embedded-react/Animated.mjs +412 -0
  100. package/src/embedded-react/{AppRegistry.js → AppRegistry.mjs} +26 -25
  101. package/src/embedded-react/{Button.js → Button.mjs} +29 -53
  102. package/src/embedded-react/Dimensions.mjs +32 -0
  103. package/src/embedded-react/Easing.mjs +34 -0
  104. package/src/embedded-react/{FlatList.js → FlatList.mjs} +25 -42
  105. package/src/embedded-react/{ImageBackground.js → ImageBackground.mjs} +11 -22
  106. package/src/embedded-react/Keyboard.mjs +82 -0
  107. package/src/embedded-react/{LayoutAnimation.js → LayoutAnimation.mjs} +17 -28
  108. package/src/embedded-react/PanResponder.mjs +256 -0
  109. package/src/embedded-react/{Platform.js → Platform.mjs} +8 -9
  110. package/src/embedded-react/{Pressable.js → Pressable.mjs} +12 -25
  111. package/src/embedded-react/SectionList.mjs +103 -0
  112. package/src/embedded-react/{StyleSheet.js → StyleSheet.mjs} +16 -20
  113. package/src/embedded-react/{TouchableOpacity.js → TouchableOpacity.mjs} +47 -83
  114. package/src/embedded-react/background-image.mjs +321 -0
  115. package/src/embedded-react/{components.js → components.mjs} +1 -3
  116. package/src/embedded-react/{imperative.js → imperative.mjs} +27 -38
  117. package/src/embedded-react/index.d.ts +238 -5
  118. package/src/embedded-react/index.js +26 -17
  119. package/src/embedded-react/layout-anim-config.mjs +85 -0
  120. package/src/embedded-react/{list-child.js → list-child.mjs} +11 -20
  121. package/src/embedded-react/{named-colors.js → named-colors.mjs} +2 -6
  122. package/src/embedded-react/nativeModule.mjs +371 -0
  123. package/src/embedded-react/split-style.mjs +57 -0
  124. package/src/embedded-react/svg-ops.mjs +1075 -0
  125. package/src/embedded-react/{useHostValue.js → useHostValue.mjs} +2 -4
  126. package/src/embedded-react/{usePersistentState.js → usePersistentState.mjs} +34 -38
  127. package/src/embedded-react/{warn-props.js → warn-props.mjs} +32 -39
  128. package/src/host-config.mjs +512 -0
  129. package/src/{native-ui.js → native-ui.mjs} +1 -8
  130. package/src/props.mjs +341 -0
  131. package/src/{renderer.js → renderer.mjs} +30 -44
  132. package/src/embedded-react/Animated.js +0 -440
  133. package/src/embedded-react/Easing.js +0 -39
  134. package/src/embedded-react/PanResponder.js +0 -330
  135. package/src/embedded-react/SectionList.js +0 -148
  136. package/src/embedded-react/layout-anim-config.js +0 -101
  137. package/src/embedded-react/split-style.js +0 -58
  138. package/src/embedded-react/svg-ops.js +0 -1295
  139. package/src/host-config.js +0 -548
  140. package/src/props.js +0 -306
@@ -32,14 +32,17 @@
32
32
  * pass; a row shows while the list holds it. Rows whose nodes and handlers
33
33
  * are the same share a template, and a row handler reads its item through the row it was built for.
34
34
  *
35
+ * A conditional on state is a branch template for each branch that has an element. The update destroys a branch
36
+ * once its test picks another, then builds the one picked, before the first sibling after it that is built. All
37
+ * the destroys of a pass come before its builds, so the panel's nodes are the most any one state of the app shows
38
+ * at once. A conditional in a list row builds every branch with the row instead, and shows the one picked.
39
+ *
35
40
  * A PanResponder is a handler for each responder event and a query function for each should-set predicate,
36
41
  * bound on each node that spreads it. Its gesture state is slots, kept by its grant, release and terminate
37
42
  * handlers, and a callback reads the gesture through them and EVT.
38
43
  *
39
- * An effect runs inside an update pass, so the state it sets shows at the next pass that isn't its own, not at
40
- * once. The VM runs a pass whenever state changed, so a pass that only an
41
- * effect's write started keeps what changed in a pending flag, and the next pass a handler, a timer or the
42
- * load started sets it. A dep-driven effect checks its deps itself, when it runs,
44
+ * An effect runs after an update pass, and one that set state asks for another, which shows what it set, as
45
+ * React renders again after an effect sets state. A dep-driven effect checks its deps itself, when it runs,
43
46
  * each in turn. The mount effects run one after another, after the first pass; one that set state has the
44
47
  * pass after it queue the next.
45
48
  */
@@ -48,23 +51,28 @@
48
51
  ---------------------------------------------------------------------------------------------------------------------*/
49
52
  import { aotError, constantText, ENGINE_STRING_MAX, locateError, } from '../diagnostics.mjs';
50
53
  import { hasRuntimeProps, isStateDriven, nodesOf, branchElements, stateDrivenVectorOf, updatedVectorOf, } from '../ir/nodes.mjs';
51
- import { nodeReads, vectorReads } from '../ir/reads.mjs';
54
+ import { expressionReads, listReads, nodeReads, vectorReads, workedReads, } from '../ir/reads.mjs';
52
55
  import { armedFlag } from '../ir/functions.mjs';
53
56
  import { AnimationPlan, doneFunctions, startPressFade } from './animations.mjs';
54
57
  import { Arena } from './arena.mjs';
55
58
  import { FunctionBuilder, OP } from './bytecode.mjs';
56
59
  import { internedStates } from './enums.mjs';
60
+ import { longestLiteral, stringCaps } from './string-caps.mjs';
57
61
  import { Codegen, notYet } from './codegen.mjs';
58
62
  import { BindingKind, ENGINE_VALUES, EventField, FLAG_DEBUG, FRAME_CELLS, FunctionKind, MAX_SPANS, NONE, Resource, SlotFlag, TemplateKind, ValueType, } from './format.mjs';
59
63
  import { abiProp, constantPropEntry, floatBits, stringPropEntry, } from './props.mjs';
60
64
  import { ProgramTables } from './tables.mjs';
65
+ import { itemValueAt, rowEntries } from '../list-items.mjs';
61
66
  import { commitDrawing, VectorPlan } from './vectors.mjs';
62
67
  import { lowerCheck } from './checks.mjs';
68
+ import { MAX_NATIVE_EVENTS } from '../native-modules.mjs';
63
69
  /*----------------------------------------------------------------------------------------------------------------------
64
70
  - Constants
65
71
  ---------------------------------------------------------------------------------------------------------------------*/
66
72
  /** The most a u16 count or size in the format holds: a row's bytes, a panel's nodes, the row fields. */
67
73
  const MAX_U16 = 0xffff;
74
+ /** BUILD's instance operand when the template is no list row's. */
75
+ const NO_REGISTER = 0xff;
68
76
  /** The most fields a row has: ROWGET names one in a byte. */
69
77
  const MAX_ROW_FIELDS = 255;
70
78
  /** Key kind → its ERKeyboardKey type. */
@@ -109,60 +117,80 @@ const isSetOnce = (node) => !isStateDriven(node) && (hasRuntimeProps(node) || no
109
117
  - Slots
110
118
  ---------------------------------------------------------------------------------------------------------------------*/
111
119
  /**
112
- * The most bytes a boot value's string can be: its longest literal, since nothing else reaches it at boot.
113
- *
114
- * @param expression The value.
115
- *
116
- * @returns The bytes.
117
- */
118
- function longestLiteral(expression) {
119
- let longest = 0;
120
- const walk = (value) => {
121
- if (!value || typeof value !== 'object') {
122
- return;
123
- }
124
- const node = value;
125
- if (node.kind === 'string' && typeof node.value === 'string') {
126
- longest = Math.max(longest, Buffer.byteLength(node.value, 'utf8'));
127
- return;
128
- }
129
- Object.values(node).forEach(walk);
130
- };
131
- walk(expression);
132
- return Math.max(longest, 1);
133
- }
134
- /**
135
- * Every string local a statement list declares, with its cap.
120
+ * Every string local a statement list declares.
136
121
  *
137
122
  * @param statements The statements.
138
- * @param found Collects each local's name and cap.
123
+ * @param found Collects each local's name.
139
124
  */
140
125
  function stringLocals(statements, found) {
141
126
  for (const statement of statements) {
142
127
  if (statement.kind === 'declareLocal' &&
143
128
  statement.initializer.type.kind === 'string') {
144
- found.set(statement.name, Math.max(found.get(statement.name) ?? 0, statement.stringCapacity - 1));
129
+ found.add(statement.name);
145
130
  }
146
131
  else if (statement.kind === 'if') {
147
132
  stringLocals(statement.consequent, found);
148
133
  stringLocals(statement.alternate ?? [], found);
149
134
  }
135
+ else if (statement.kind === 'block') {
136
+ stringLocals(statement.body, found);
137
+ }
138
+ else if (statement.kind === 'loop') {
139
+ stringLocals(statement.body, found);
140
+ stringLocals(statement.step, found);
141
+ }
150
142
  }
151
143
  }
152
144
  /**
153
- * Every updateVector call a statement list makes.
145
+ * Every native call in a value that returns strings, at any depth: each copies them into buffers of its own.
146
+ *
147
+ * @param value The statements, or any part of them.
148
+ * @param found Collects the calls.
149
+ * @param seen What has been walked, so a value reached twice is walked once.
150
+ */
151
+ function stringNativeCalls(value, found, seen = new Set()) {
152
+ if (!value || typeof value !== 'object' || seen.has(value))
153
+ return;
154
+ seen.add(value);
155
+ if (Array.isArray(value)) {
156
+ value.forEach(child => stringNativeCalls(child, found, seen));
157
+ return;
158
+ }
159
+ const record = value;
160
+ const call = record;
161
+ if (call.import &&
162
+ call.callArguments &&
163
+ call.import.results.includes('string')) {
164
+ found.add(call);
165
+ }
166
+ for (const [key, child] of Object.entries(record)) {
167
+ // Where a value came from repeats its reads, and a location holds none.
168
+ if (key !== 'source' && key !== 'location') {
169
+ stringNativeCalls(child, found, seen);
170
+ }
171
+ }
172
+ }
173
+ /**
174
+ * Every updateVector and scrollTo call a statement list makes.
154
175
  *
155
176
  * @param statements The statements.
156
177
  * @param found Collects the calls.
157
178
  */
158
- function updateVectors(statements, found) {
179
+ function nodeCalls(statements, found) {
159
180
  for (const statement of statements) {
160
- if (statement.kind === 'updateVector') {
181
+ if (statement.kind === 'updateVector' || statement.kind === 'scrollTo') {
161
182
  found.push(statement);
162
183
  }
163
184
  else if (statement.kind === 'if') {
164
- updateVectors(statement.consequent, found);
165
- updateVectors(statement.alternate ?? [], found);
185
+ nodeCalls(statement.consequent, found);
186
+ nodeCalls(statement.alternate ?? [], found);
187
+ }
188
+ else if (statement.kind === 'block') {
189
+ nodeCalls(statement.body, found);
190
+ }
191
+ else if (statement.kind === 'loop') {
192
+ nodeCalls(statement.body, found);
193
+ nodeCalls(statement.step, found);
166
194
  }
167
195
  }
168
196
  }
@@ -184,6 +212,13 @@ function statesSet(statements, found) {
184
212
  statesSet(statement.consequent, found);
185
213
  statesSet(statement.alternate ?? [], found);
186
214
  }
215
+ else if (statement.kind === 'block') {
216
+ statesSet(statement.body, found);
217
+ }
218
+ else if (statement.kind === 'loop') {
219
+ statesSet(statement.body, found);
220
+ statesSet(statement.step, found);
221
+ }
187
222
  }
188
223
  }
189
224
  /**
@@ -204,6 +239,19 @@ function depType(dependency) {
204
239
  return 'int';
205
240
  }
206
241
  }
242
+ /**
243
+ * Whether a dep-driven effect or its cleanup sets state, so an update runs after it.
244
+ *
245
+ * @param effect The effect.
246
+ *
247
+ * @returns Whether it does.
248
+ */
249
+ const setsState = (effect) => {
250
+ const states = new Set();
251
+ statesSet(effect.body, states);
252
+ statesSet(effect.cleanup ?? [], states);
253
+ return states.size > 0;
254
+ };
207
255
  /**
208
256
  * Whether a mount effect sets state, so an update runs after it.
209
257
  *
@@ -230,6 +278,7 @@ function bodies(app) {
230
278
  ? [handler.event.callback.body]
231
279
  : []),
232
280
  ...output.timerFunctions.map(timer => timer.callback.body),
281
+ ...output.nativeEventHandlers.map(handler => handler.callback.body),
233
282
  ...output.effectFunctions.map(effectFunction => effectFunction.kind === 'mount'
234
283
  ? effectFunction.body
235
284
  : effectFunction.kind === 'cleanup'
@@ -267,24 +316,49 @@ const stateSlotOf = (state, slots) => state.kind === 'list'
267
316
  */
268
317
  const firstNode = (element) => element.kind === 'component' ? firstNode(element.root) : element.node;
269
318
  /**
270
- * Every `.map` over a list under an element, in tree order, with the node its rows go under and the one they go
271
- * before. A list inside a list's row is refused.
319
+ * Walks a tree for its pools and the conditionals that build their branches, and the branch each node sits in.
320
+ * A list inside a list's row is refused.
272
321
  *
273
322
  * @param element The element.
274
- * @param found Collects the pools.
323
+ * @param within The branch it sits in, or null.
324
+ * @param plan Collects what the walk finds.
325
+ * @param arena Lays out each conditional's slots.
275
326
  */
276
- function poolsOf(element, found) {
327
+ function planTree(element, within, plan, arena) {
277
328
  if (element.kind === 'component') {
278
- poolsOf(element.root, found);
329
+ planTree(element.root, within, plan, arena);
279
330
  return;
280
331
  }
281
332
  const { node } = element;
333
+ if (within) {
334
+ plan.places.set(node, within);
335
+ }
282
336
  node.children.forEach((child, index) => {
337
+ const after = node.children.slice(index + 1);
283
338
  if (child.kind === 'element') {
284
- poolsOf(child.element, found);
339
+ planTree(child.element, within, plan, arena);
340
+ }
341
+ else if (child.kind === 'conditional' && child.toggle) {
342
+ branchElements(child).forEach(branch => planTree(branch, within, plan, arena));
285
343
  }
286
344
  else if (child.kind === 'conditional') {
287
- branchElements(child).forEach(branch => poolsOf(branch, found));
345
+ const branching = {
346
+ conditional: child,
347
+ alternatives: branchElements(child),
348
+ templates: [],
349
+ parent: node,
350
+ after,
351
+ anchors: [],
352
+ within,
353
+ built: arena.slot(ValueType.int, 0),
354
+ root: arena.slot(ValueType.node),
355
+ nested: [],
356
+ };
357
+ plan.branchings.push(branching);
358
+ for (let outer = within; outer; outer = outer.branching.within) {
359
+ outer.branching.nested.push(branching);
360
+ }
361
+ branching.alternatives.forEach((alternative, place) => planTree(alternative, { branching, alternative: place + 1 }, plan, arena));
288
362
  }
289
363
  else {
290
364
  for (const row of child.rows) {
@@ -292,25 +366,54 @@ function poolsOf(element, found) {
292
366
  if (nested) {
293
367
  notYetAt('a list inside a list row', nested.location);
294
368
  }
369
+ if (within) {
370
+ nodesOf(row).forEach(rowNode => plan.places.set(rowNode, within));
371
+ }
295
372
  }
296
- // The rows go before the next node the parent builds itself.
297
- const after = node.children
298
- .slice(index + 1)
299
- .flatMap(sibling => sibling.kind === 'element'
300
- ? [sibling.element]
301
- : sibling.kind === 'conditional'
302
- ? branchElements(sibling)
303
- : []);
304
- found.push({
373
+ plan.pools.push({
305
374
  list: child.list,
306
375
  rows: child.rows,
307
376
  parent: node,
308
- anchor: after.length ? firstNode(after[0]) : null,
377
+ after,
378
+ anchors: [],
379
+ within,
309
380
  templates: [],
310
381
  });
311
382
  }
312
383
  });
313
384
  }
385
+ /**
386
+ * The siblings something goes before, in order: each branch until one that is always built when they are.
387
+ *
388
+ * @param after The siblings after it.
389
+ * @param pools The tree's pools.
390
+ * @param branchings The tree's conditionals that build their branches.
391
+ *
392
+ * @returns The anchors; none when it goes last.
393
+ */
394
+ function anchorsOf(after, pools, branchings) {
395
+ const anchors = [];
396
+ for (const child of after) {
397
+ const first = child.kind === 'element'
398
+ ? child.element
399
+ : child.kind === 'pool'
400
+ ? (pools.find(pool => pool.rows === child.rows)?.rows[0] ?? null)
401
+ : child.toggle
402
+ ? (branchElements(child)[0] ?? null)
403
+ : null;
404
+ if (first) {
405
+ anchors.push({ kind: 'node', node: firstNode(first) });
406
+ return anchors;
407
+ }
408
+ if (child.kind === 'conditional' && !child.toggle) {
409
+ anchors.push({
410
+ kind: 'branching',
411
+ branching: branchings.find(branching => branching.conditional === child),
412
+ });
413
+ }
414
+ }
415
+ return anchors;
416
+ }
314
417
  /**
315
418
  * Plans every slot the program uses, then lays the arena out.
316
419
  *
@@ -321,7 +424,6 @@ function poolsOf(element, found) {
321
424
  * @returns The slots, the node handles, and the bookkeeping bits.
322
425
  */
323
426
  function planSlots(app, tables, caps) {
324
- const { listStrCap: listStringCapacity } = caps;
325
427
  const { output } = app;
326
428
  const arena = new Arena();
327
429
  const animations = new AnimationPlan(app, arena);
@@ -333,7 +435,9 @@ function planSlots(app, tables, caps) {
333
435
  refs: new Map(),
334
436
  boot: new Map(),
335
437
  stringLocals: new Map(),
438
+ nativeStrings: new Map(),
336
439
  enums: new Map(),
440
+ kept: new Map(),
337
441
  hoisted: new Map(),
338
442
  armed: new Map(),
339
443
  timerFunctions: new Map(),
@@ -348,6 +452,8 @@ function planSlots(app, tables, caps) {
348
452
  values,
349
453
  });
350
454
  }
455
+ // Each string buffer is sized from the values that reach it.
456
+ const stringCap = stringCaps(app, new Map([...slots.enums].map(([state, { values }]) => [state, values])), caps.listStrCap - 1);
351
457
  // State, each with a dirty bit when a node reads it.
352
458
  for (const state of app.state) {
353
459
  if (state.kind === 'list') {
@@ -359,7 +465,7 @@ function planSlots(app, tables, caps) {
359
465
  const slot = interned
360
466
  ? Object.assign(arena.slot(ValueType.enum, 0), { aux: interned.set })
361
467
  : state.slotKind === 'string'
362
- ? arena.slot(ValueType.string, tables.string(String(initial)), listStringCapacity - 1)
468
+ ? arena.slot(ValueType.string, tables.string(String(initial)), stringCap.state(state))
363
469
  : state.slotKind === 'i64'
364
470
  ? arena.slot(ValueType.int64, tables.constant64(BigInt(Math.trunc(Number(initial)))))
365
471
  : state.slotKind === 'float'
@@ -371,6 +477,19 @@ function planSlots(app, tables, caps) {
371
477
  }
372
478
  slots.states.set(state, slot);
373
479
  }
480
+ // The copy a body keeps of a state it sets and then reads: a slot like the state's, which nothing watches.
481
+ for (const state of output.keptStates) {
482
+ const interned = slots.enums.get(state);
483
+ slots.kept.set(state, interned
484
+ ? Object.assign(arena.slot(ValueType.enum, 0), { aux: interned.set })
485
+ : state.slotKind === 'string'
486
+ ? arena.slot(ValueType.string, tables.string(''), stringCap.state(state))
487
+ : state.slotKind === 'i64'
488
+ ? arena.slot(ValueType.int64, tables.constant64(0n))
489
+ : state.slotKind === 'float'
490
+ ? arena.slot(ValueType.float, 0)
491
+ : arena.slot(state.isBoolean ? ValueType.bool : ValueType.int, 0));
492
+ }
374
493
  // A list is a pool of rows, empty at load; the boot function appends its first items. Each row field is
375
494
  // 4-aligned, and a string field holds its cap and a terminator.
376
495
  const rows = [];
@@ -381,18 +500,24 @@ function planSlots(app, tables, caps) {
381
500
  if (!state.struct.fields.length) {
382
501
  notYet(`list state "${state.name}", whose items have no fields`);
383
502
  }
384
- if (state.struct.fields.length > MAX_ROW_FIELDS) {
385
- throw aotError(`AOT: list state "${state.name}" has ${state.struct.fields.length} fields, but a package row holds ${MAX_ROW_FIELDS}`, 'give the items fewer fields.');
503
+ const entries = rowEntries(state.struct);
504
+ if (entries.length > MAX_ROW_FIELDS) {
505
+ throw aotError(`AOT: list state "${state.name}" has ${entries.length} fields, but a package row holds ${MAX_ROW_FIELDS}`, 'give the items fewer fields, or fewer that some items leave out (each of those takes two).');
386
506
  }
387
507
  let size = 0;
388
- const fields = state.struct.fields.map(field => {
389
- const capacity = field.kind === 'string' ? listStringCapacity - 1 : 0;
390
- const entry = { type: ValueType[field.kind], cap: capacity, offset: size };
391
- size += field.kind === 'string' ? (capacity + 1 + 3) & ~3 : 4;
508
+ const fields = entries.map(({ field, presence }) => {
509
+ const isString = !presence && field.kind === 'string';
510
+ const capacity = isString ? stringCap.field(state, field.key) : 0;
511
+ const entry = {
512
+ type: presence ? ValueType.bool : ValueType[field.kind],
513
+ cap: capacity,
514
+ offset: size,
515
+ };
516
+ size += isString ? (capacity + 1 + 3) & ~3 : 4;
392
517
  return entry;
393
518
  });
394
519
  if (size > MAX_U16) {
395
- throw aotError(`AOT: a row of list state "${state.name}" takes ${size} bytes, but a package row holds ${MAX_U16 - 3}`, 'lower ER_AOT_LIST_STR_CAP (the listStrCap option), or give the items fewer text fields.');
520
+ throw aotError(`AOT: a row of list state "${state.name}" takes ${size} bytes, but a package row holds ${MAX_U16 - 3}`, 'shorten its strings, or give the items fewer text fields.');
396
521
  }
397
522
  const slot = arena.list(rows.length, size, state.capacity);
398
523
  rows.push({ size, fields });
@@ -404,7 +529,7 @@ function planSlots(app, tables, caps) {
404
529
  .filter(field => field.kind === 'string')
405
530
  .map(field => [
406
531
  field.key,
407
- arena.slot(ValueType.string, undefined, listStringCapacity - 1),
532
+ arena.slot(ValueType.string, undefined, stringCap.field(state, field.key)),
408
533
  ]));
409
534
  slots.lists.set(state, { slot, buffers });
410
535
  }
@@ -438,7 +563,7 @@ function planSlots(app, tables, caps) {
438
563
  for (const declaration of output.effectDeclarations) {
439
564
  if (declaration.kind === 'local') {
440
565
  slots.hoisted.set(declaration.name, declaration.slotKind === 'string'
441
- ? arena.slot(ValueType.string, undefined, listStringCapacity - 1)
566
+ ? arena.slot(ValueType.string, undefined, stringCap.local(declaration.name))
442
567
  : arena.slot(declaration.slotKind === 'i64'
443
568
  ? ValueType.int64
444
569
  : declaration.slotKind === 'float'
@@ -456,66 +581,122 @@ function planSlots(app, tables, caps) {
456
581
  return {
457
582
  type,
458
583
  slot: type === 'string'
459
- ? arena.slot(ValueType.string, undefined, listStringCapacity - 1)
584
+ ? arena.slot(ValueType.string, undefined, stringCap.value(dependency))
460
585
  : arena.slot(ValueType[type]),
461
586
  };
462
587
  }));
463
588
  }
464
- const locals = new Map();
589
+ const locals = new Set();
465
590
  for (const body of bodies(app)) {
466
591
  stringLocals(body, locals);
467
592
  }
468
- for (const [name, capacity] of locals) {
593
+ for (const state of app.state) {
594
+ if (state.kind === 'scalar' && state.worked) {
595
+ stringLocals(state.worked.rebuild, locals);
596
+ }
597
+ }
598
+ for (const name of locals) {
469
599
  if (!slots.hoisted.has(name)) {
470
- slots.stringLocals.set(name, arena.slot(ValueType.string, undefined, capacity));
600
+ slots.stringLocals.set(name, arena.slot(ValueType.string, undefined, stringCap.local(name)));
471
601
  }
472
602
  }
603
+ // A native call's string result can be anything a write holds. A record's strings take a buffer each, one after
604
+ // another, as CALLNS names the first.
605
+ const nativeCalls = new Set();
606
+ stringNativeCalls(bodies(app), nativeCalls);
607
+ for (const call of nativeCalls) {
608
+ const buffers = call.import.results
609
+ .filter(type => type === 'string')
610
+ .map(() => arena.slot(ValueType.string, undefined, ENGINE_STRING_MAX.ER_TEXT_MAX));
611
+ slots.nativeStrings.set(call, buffers[0]);
612
+ }
473
613
  const nodes = nodesOf(app.root);
474
614
  // A <TextInput>'s onChangeText reads the input's text, through its handle.
475
615
  const handles = new Map();
476
616
  const readsInput = (node) => node.wiring.some(wire => wire.kind === 'event' && wire.event === 'ER_EVENT_CHANGE_TEXT');
477
- // An updateVector call draws on the node its ref holds: the last one built with it.
617
+ // An updateVector call draws on the node its ref holds, and a scrollTo call scrolls it: the last one built with
618
+ // the ref.
478
619
  const calls = [];
479
620
  for (const body of bodies(app)) {
480
- updateVectors(body, calls);
621
+ nodeCalls(body, calls);
481
622
  }
482
- const drawnRefs = new Set(calls.map(call => call.node));
623
+ const callOf = new Map(calls.map(call => [call.node, call]));
483
624
  const refNodes = new Map();
484
625
  for (const node of nodes) {
485
626
  for (const wire of node.wiring) {
486
- if (wire.kind === 'ref' && drawnRefs.has(wire.slot)) {
627
+ if (wire.kind === 'ref' && callOf.has(wire.slot)) {
487
628
  refNodes.set(wire.slot, node);
488
629
  }
489
630
  }
490
631
  }
491
- const drawnOn = new Set(refNodes.values());
632
+ const drawnOn = new Map([...refNodes].map(([ref, node]) => [
633
+ node,
634
+ callOf.get(ref).kind === 'scrollTo' ? 'scrollTo' : 'updateVector',
635
+ ]));
636
+ for (const call of calls) {
637
+ if (call.kind !== 'scrollTo')
638
+ continue;
639
+ const node = refNodes.get(call.node);
640
+ if (node?.type !== 'ER_NODE_SCROLL_VIEW' &&
641
+ node?.type !== 'ER_NODE_FLAT_LIST') {
642
+ const error = aotError('AOT: scrollTo() takes a ref that is on a <ScrollView>', 'put ref={…} on the <ScrollView> to scroll, and pass its `.current`.');
643
+ locateError(error, node?.location ?? call.location);
644
+ throw error;
645
+ }
646
+ }
492
647
  const reached = (node) => isStateDriven(node) ||
493
648
  isSetOnce(node) ||
494
649
  readsInput(node) ||
495
650
  stateDrivenVectorOf(node) !== null;
651
+ const { pools, branchings, places } = {
652
+ pools: [],
653
+ branchings: [],
654
+ places: new Map(),
655
+ };
656
+ planTree(app.root, null, { pools, branchings, places }, arena);
657
+ for (const placed of [...pools, ...branchings]) {
658
+ placed.anchors = anchorsOf(placed.after, pools, branchings);
659
+ }
660
+ // Rows and branches are built under their parent, before an anchor.
661
+ const builtUnder = new Set([...pools, ...branchings].flatMap(placed => [
662
+ placed.parent,
663
+ ...placed.anchors.flatMap(anchor => anchor.kind === 'node' ? [anchor.node] : []),
664
+ ]));
496
665
  // A row's node keeps its handle in an array by the row, one array for each place in the row that needs one.
497
- const pools = [];
498
- poolsOf(app.root, pools);
499
666
  const rowHandles = new Map();
500
667
  for (const pool of pools) {
501
668
  const arrays = [];
669
+ const anchoring = pool.rows.length > 0 && builtUnder.has(firstNode(pool.rows[0]));
502
670
  pool.rows.forEach((rowElement, row) => nodesOf(rowElement).forEach((node, place) => {
503
671
  if (readsInput(node)) {
504
672
  notYetAt('onChangeText in a list row', node.location);
505
673
  }
506
674
  if (drawnOn.has(node)) {
507
- notYetAt('updateVector on a node in a list row', node.location);
675
+ notYetAt(`${drawnOn.get(node)} on a node in a list row`, node.location);
508
676
  }
509
- if (reached(node)) {
677
+ // Every row's first node, when the first row's is an anchor, so the rows can still share a template.
678
+ if (reached(node) || (anchoring && place === 0)) {
510
679
  arrays[place] ??= arena.slot(ValueType.node, 0, pool.list.capacity);
511
680
  rowHandles.set(node, { array: arrays[place], row });
512
681
  }
513
682
  }));
514
683
  }
515
- // The rows are built under their parent, before the node after them.
516
- const builtUnder = new Set(pools.flatMap(pool => pool.anchor ? [pool.parent, pool.anchor] : [pool.parent]));
684
+ // A branch's first node keeps its handle in its conditional's slot, which every branch of it shares.
685
+ for (const branching of branchings) {
686
+ for (const alternative of branching.alternatives) {
687
+ handles.set(firstNode(alternative), branching.root);
688
+ }
689
+ }
517
690
  for (const node of nodes) {
691
+ if (drawnOn.has(node) && places.has(node)) {
692
+ const error = aotError(drawnOn.get(node) === 'scrollTo'
693
+ ? 'AOT: scrollTo scrolls a node a conditional builds and destroys'
694
+ : 'AOT: updateVector draws on a node a conditional builds and destroys', 'keep the node built and show it with visible={…} instead.');
695
+ locateError(error, node.location);
696
+ throw error;
697
+ }
518
698
  if (!rowHandles.has(node) &&
699
+ !handles.has(node) &&
519
700
  (reached(node) || builtUnder.has(node) || drawnOn.has(node))) {
520
701
  handles.set(node, arena.slot(ValueType.node));
521
702
  }
@@ -540,7 +721,9 @@ function planSlots(app, tables, caps) {
540
721
  ? handler.callback.updatesState
541
722
  : handler.kind === 'panEvent' && !!handler.event.callback?.updatesState) ||
542
723
  output.timerFunctions.some(timer => timer.callback.updatesState) ||
724
+ output.nativeEventHandlers.some(handler => handler.callback.updatesState) ||
543
725
  output.mountEffects.some(mountUpdates) ||
726
+ output.dependencyEffects.some(setsState) ||
544
727
  completionsOf(app).some(completion => completion.updatesState);
545
728
  const requested = requestsUpdate
546
729
  ? arena.track(arena.slot(ValueType.bool))
@@ -551,25 +734,10 @@ function planSlots(app, tables, caps) {
551
734
  nodes.some(node => isStateDriven(node) || isSetOnce(node) || stateDrivenVectorOf(node))
552
735
  ? arena.track(arena.slot(ValueType.bool))
553
736
  : null;
554
- // A state an effect sets that a node reads waits for the next update in a pending flag.
555
- const effectWrites = new Set();
556
- for (const effect of output.dependencyEffects) {
557
- statesSet(effect.body, effectWrites);
558
- statesSet(effect.cleanup ?? [], effectWrites);
559
- }
560
- const pending = new Map();
561
- for (const state of effectWrites) {
562
- const slot = stateSlotOf(state, slots);
563
- if (slot.flags & SlotFlag.tracked) {
564
- pending.set(slot, arena.slot(ValueType.bool));
565
- }
566
- }
567
- const realBits = [requested, once].filter(slot => slot !== null);
568
- for (const [state, slot] of slots.states) {
569
- if (state.host && slot.flags & SlotFlag.tracked) {
570
- realBits.push(slot);
571
- }
572
- }
737
+ // The mount effects run each dep-driven effect first, so its checks wait for the last of them.
738
+ const checksQueued = output.dependencyEffects.length
739
+ ? arena.slot(ValueType.bool, 1)
740
+ : null;
573
741
  // The first mount effect is queued by the first pass.
574
742
  const mountNext = output.mountEffects.length
575
743
  ? arena.slot(ValueType.int, 1)
@@ -577,9 +745,10 @@ function planSlots(app, tables, caps) {
577
745
  if (output.timerFunctions.length) {
578
746
  arena.timerTable(caps.maxTimers);
579
747
  }
580
- // A pass queues each dep-driven effect and the next mount effect, and a mount effect the one after it.
748
+ // A pass queues each dep-driven effect's check unless a batch is waiting to start, so the queue holds one waiting
749
+ // batch, the rest of the one running, and the next mount effect.
581
750
  if (hasEffects) {
582
- arena.eventQueue(output.dependencyEffects.length + 1);
751
+ arena.eventQueue(2 * output.dependencyEffects.length + 1);
583
752
  }
584
753
  arena.layOut();
585
754
  return {
@@ -588,10 +757,12 @@ function planSlots(app, tables, caps) {
588
757
  rowHandles,
589
758
  rows,
590
759
  pools,
760
+ branchings,
761
+ places,
591
762
  inputText,
592
763
  requested,
593
764
  once,
594
- effects: { copies, pending, realBits, mountNext },
765
+ effects: { copies, checksQueued, mountNext },
595
766
  };
596
767
  }
597
768
  /*----------------------------------------------------------------------------------------------------------------------
@@ -627,8 +798,8 @@ function constantProps(node, lowering) {
627
798
  }
628
799
  /**
629
800
  * The handler function an event on a node runs, made the first time. A handler bound to two events is one
630
- * function per event, since a function's kind is the event it is entered with, and an onChangeText one per
631
- * input, since it reads its own. Each row has its own handler; rows whose handlers have the same
801
+ * function per event, since a function's kind is the event it is entered with, an onChangeText one per
802
+ * input, since it reads its own, and an onScroll one per ScrollView. Each row has its own handler; rows whose handlers have the same
632
803
  * code share one function, so they can share a template.
633
804
  *
634
805
  * @param name The handler.
@@ -655,6 +826,8 @@ function handlerFunction(name, eventName, node, lowering, inRow) {
655
826
  throw new Error(`AOT internal: no handler for "${name}"`);
656
827
  }
657
828
  const readsInput = eventName === 'ER_EVENT_CHANGE_TEXT';
829
+ // One per ScrollView, in a row too, so the runtime can tell whose scroll is waiting.
830
+ const scrolls = eventName === 'ER_EVENT_SCROLL';
658
831
  const made = {
659
832
  callback: then?.callback ?? { body: [], updatesState: false },
660
833
  fade: handler.kind === 'pressFade' ? handler.fade : null,
@@ -667,8 +840,8 @@ function handlerFunction(name, eventName, node, lowering, inRow) {
667
840
  };
668
841
  // Compared by code alone, so where each handler is in the source doesn't keep two apart.
669
842
  const key = inRow
670
- ? `row ${JSON.stringify({ ...handlerBody({ ...made, index: NONE }, lowering), debug: undefined })}`
671
- : `${name} ${eventName}${readsInput ? ` ${node.id}` : ''}`;
843
+ ? `row ${scrolls ? `${node.id} ` : ''}${JSON.stringify({ ...handlerBody({ ...made, index: NONE }, lowering), debug: undefined })}`
844
+ : `${name} ${eventName}${readsInput || scrolls ? ` ${node.id}` : ''}`;
672
845
  const existing = lowering.handlers.get(key);
673
846
  if (existing) {
674
847
  return existing.index;
@@ -729,9 +902,10 @@ function responderBindings(pan, lowering) {
729
902
  ];
730
903
  }
731
904
  /**
732
- * An element and everything under it as template nodes, each before its children. A conditional's branches
733
- * are all built, and the update shows the chosen one. A list's rows are row templates of their own. What a node
734
- * needs that a package can't lower yet is refused at the node's element.
905
+ * An element and everything under it as template nodes, each before its children. A conditional's branches are
906
+ * branch templates of their own, except in a list row, where all of them are built and the update shows the
907
+ * chosen one. A list's rows are row templates of their own. What a node needs that a package can't lower yet is
908
+ * refused at the node's element.
735
909
  *
736
910
  * @param element The element.
737
911
  * @param lowering The program being lowered.
@@ -771,7 +945,7 @@ function templateNodes(element, lowering, nodes, inRow = false) {
771
945
  }
772
946
  children = node.children.flatMap(child => child.kind === 'element'
773
947
  ? [child.element]
774
- : child.kind === 'conditional'
948
+ : child.kind === 'conditional' && child.toggle
775
949
  ? branchElements(child)
776
950
  : []);
777
951
  // A node the update sets starts with no props.
@@ -829,6 +1003,52 @@ function rowTemplates(lowering) {
829
1003
  });
830
1004
  }
831
1005
  }
1006
+ /**
1007
+ * Each branch's template, for every conditional that builds its branches.
1008
+ *
1009
+ * @param lowering The program being lowered.
1010
+ */
1011
+ function branchTemplates(lowering) {
1012
+ for (const branching of lowering.branchings) {
1013
+ branching.templates = branching.alternatives.map(alternative => {
1014
+ const nodes = [];
1015
+ templateNodes(alternative, lowering, nodes);
1016
+ // The root template is first, so a branch template's index is its place after it.
1017
+ return lowering.templates.push({ kind: TemplateKind.branch, nodes });
1018
+ });
1019
+ }
1020
+ }
1021
+ /**
1022
+ * The most nodes an element and everything under it hold at once: every row of a list, and the largest branch
1023
+ * of a conditional, or all of them in a list row.
1024
+ *
1025
+ * @param element The element.
1026
+ * @param counts How many a node counts for.
1027
+ *
1028
+ * @returns The nodes.
1029
+ */
1030
+ function mostBuilt(element, counts) {
1031
+ if (element.kind === 'component') {
1032
+ return mostBuilt(element.root, counts);
1033
+ }
1034
+ const sum = (elements) => elements.reduce((total, each) => total + mostBuilt(each, counts), 0);
1035
+ let total = counts(element.node);
1036
+ for (const child of element.node.children) {
1037
+ if (child.kind === 'element') {
1038
+ total += mostBuilt(child.element, counts);
1039
+ }
1040
+ else if (child.kind === 'pool') {
1041
+ total += sum(child.rows);
1042
+ }
1043
+ else if (child.toggle) {
1044
+ total += sum(branchElements(child));
1045
+ }
1046
+ else {
1047
+ total += Math.max(0, ...branchElements(child).map(branch => mostBuilt(branch, counts)));
1048
+ }
1049
+ }
1050
+ return total;
1051
+ }
832
1052
  /*----------------------------------------------------------------------------------------------------------------------
833
1053
  - Functions
834
1054
  ---------------------------------------------------------------------------------------------------------------------*/
@@ -896,23 +1116,132 @@ function nodeHandle(codegen, node, lowering) {
896
1116
  return handle;
897
1117
  }
898
1118
  /**
899
- * Builds every list row, in order, under its parent and before the node after it.
1119
+ * Builds under a parent, before the first anchor that is built: emits the BUILD for each node it may go before.
900
1120
  *
901
1121
  * @param codegen The update function's codegen.
1122
+ * @param parent The parent's handle.
1123
+ * @param anchors What it goes before.
902
1124
  * @param lowering The program being lowered.
1125
+ * @param build Emits the BUILD, before a node.
903
1126
  */
904
- function buildRows(codegen, lowering) {
1127
+ function buildBefore(codegen, parent, anchors, lowering, build) {
905
1128
  const { builder } = codegen;
906
- for (const pool of lowering.pools) {
1129
+ const done = builder.label();
1130
+ for (const anchor of anchors) {
1131
+ if (anchor.kind === 'node') {
1132
+ codegen.scoped(() => build(nodeHandle(codegen, anchor.node, lowering)));
1133
+ builder.place(done);
1134
+ return;
1135
+ }
1136
+ const absent = builder.label();
907
1137
  codegen.scoped(() => {
908
- const parent = nodeHandle(codegen, pool.parent, lowering);
909
- // BUILD before the parent itself puts the row last.
910
- const before = pool.anchor
911
- ? nodeHandle(codegen, pool.anchor, lowering)
912
- : parent;
913
- pool.templates.forEach((template, row) => codegen.scoped(() => builder.abc('BUILD', builder.register('node').index, parent.index, before.index, template | (codegen.load('int', row).index << 16))));
1138
+ const { branching } = anchor;
1139
+ builder.branch('JF', absent, codegen.truthy(codegen.get(branching.built)));
1140
+ const before = builder.register('node');
1141
+ builder.abx('GET64', before.index, branching.root.index);
1142
+ build(before);
1143
+ builder.branch('JMP', done);
914
1144
  });
1145
+ builder.place(absent);
1146
+ }
1147
+ // BUILD before the parent itself puts it last.
1148
+ build(parent);
1149
+ builder.place(done);
1150
+ }
1151
+ /**
1152
+ * Builds every row of a list under its parent, last row first, each before the row after it.
1153
+ *
1154
+ * @param codegen The update function's codegen.
1155
+ * @param pool The list's pool.
1156
+ * @param lowering The program being lowered.
1157
+ */
1158
+ function buildPool(codegen, pool, lowering) {
1159
+ const { builder } = codegen;
1160
+ codegen.scoped(() => {
1161
+ const parent = nodeHandle(codegen, pool.parent, lowering);
1162
+ const row = builder.register('int');
1163
+ const built = [builder.register('node'), builder.register('node')];
1164
+ const last = pool.templates.length - 1;
1165
+ for (let index = last; index >= 0; index--) {
1166
+ builder.abx('LOADI', row.index, index);
1167
+ const build = (before) => builder.abc('BUILD', built[index % 2].index, parent.index, before.index, pool.templates[index] | (row.index << 16));
1168
+ if (index === last) {
1169
+ buildBefore(codegen, parent, pool.anchors, lowering, build);
1170
+ }
1171
+ else {
1172
+ build(built[(index + 1) % 2]);
1173
+ }
1174
+ }
1175
+ });
1176
+ }
1177
+ /**
1178
+ * Runs `body` only while a branch is built; at the root, always.
1179
+ *
1180
+ * @param codegen The update function's codegen.
1181
+ * @param within The branch, or null.
1182
+ * @param body Emits what it guards.
1183
+ */
1184
+ function whileBuilt(codegen, within, body) {
1185
+ if (!within) {
1186
+ body();
1187
+ return;
1188
+ }
1189
+ const { builder } = codegen;
1190
+ const skip = builder.label();
1191
+ codegen.scoped(() => {
1192
+ builder.branch('JF', skip, codegen.same(codegen.get(within.branching.built), codegen.load('int', within.alternative)));
1193
+ body();
1194
+ });
1195
+ builder.place(skip);
1196
+ }
1197
+ /**
1198
+ * The branch a conditional's tests pick: its number, or 0 for one that builds nothing.
1199
+ *
1200
+ * @param codegen The function's codegen.
1201
+ * @param branching The conditional.
1202
+ *
1203
+ * @returns An int register.
1204
+ */
1205
+ function picked(codegen, branching) {
1206
+ const { builder } = codegen;
1207
+ const choice = builder.register('int');
1208
+ const pick = (branch) => {
1209
+ if (branch?.kind !== 'conditional') {
1210
+ builder.abx('LOADI', choice.index, branch ? branching.alternatives.indexOf(branch) + 1 : 0);
1211
+ return;
1212
+ }
1213
+ const otherwise = builder.label();
1214
+ const end = builder.label();
1215
+ codegen.scoped(() => builder.branch('JF', otherwise, codegen.condition(branch.test)));
1216
+ pick(branch.whenTrue);
1217
+ builder.branch('JMP', end);
1218
+ builder.place(otherwise);
1219
+ pick(branch.whenFalse);
1220
+ builder.place(end);
1221
+ };
1222
+ pick(branching.conditional);
1223
+ return choice;
1224
+ }
1225
+ /**
1226
+ * The state a conditional's tests read, those of the conditionals that are its branches included.
1227
+ *
1228
+ * @param conditional The conditional.
1229
+ *
1230
+ * @returns Its reads.
1231
+ */
1232
+ function conditionalReads(conditional) {
1233
+ const reads = new Set();
1234
+ const tests = [
1235
+ expressionReads(conditional.test),
1236
+ ...[conditional.whenTrue, conditional.whenFalse].map(branch => branch?.kind === 'conditional' ? conditionalReads(branch) : new Set()),
1237
+ ];
1238
+ for (const found of tests) {
1239
+ if (!found) {
1240
+ return null;
1241
+ }
1242
+ found.forEach(state => reads.add(state));
915
1243
  }
1244
+ return reads;
916
1245
  }
917
1246
  /**
918
1247
  * The dirty bits of a set of slots, as a mask per dirty word.
@@ -930,26 +1259,18 @@ function dirtyMasks(slots) {
930
1259
  return words;
931
1260
  }
932
1261
  /**
933
- * Runs `body` only when one of a set of dirty bits is set in this update pass, or one of a set of pending flags.
1262
+ * Runs `body` only when one of a set of dirty bits is set in this update pass.
934
1263
  *
935
1264
  * @param builder The update function.
936
1265
  * @param slots The slots whose bits guard it.
937
1266
  * @param body Emits what it guards.
938
- * @param pending The pending flags that guard it too.
939
1267
  */
940
- function whenDirty(builder, slots, body, pending = []) {
1268
+ function whenDirty(builder, slots, body) {
941
1269
  const run = builder.label();
942
1270
  const skip = builder.label();
943
1271
  for (const [word, mask] of dirtyMasks(slots)) {
944
1272
  builder.branchIfDirty(word, mask, run);
945
1273
  }
946
- for (const flag of pending) {
947
- const checkpoint = builder.checkpoint();
948
- const set = builder.register('bool');
949
- builder.abx('GET32', set.index, flag.index);
950
- builder.branch('JT', run, set);
951
- builder.release(checkpoint);
952
- }
953
1274
  builder.branch('JMP', skip);
954
1275
  builder.place(run);
955
1276
  body();
@@ -966,8 +1287,9 @@ function setConstant(codegen, slot, value) {
966
1287
  codegen.scoped(() => codegen.builder.abx('SET32', codegen.load(slot.type === ValueType.bool ? 'bool' : 'int', value).index, slot.index));
967
1288
  }
968
1289
  /**
969
- * The update function: what a state change sets again, each node when a state it reads changed, and the nodes set
970
- * once in the first pass; then the effects it runs, queued.
1290
+ * The update function: the branches a state change no longer picks destroyed, what it sets again, each node when
1291
+ * a state it reads changed, and the nodes set once in the first pass; then the branches picked built, each with
1292
+ * all of its props; then the effects it runs, queued.
971
1293
  *
972
1294
  * @param lowering The program being lowered.
973
1295
  *
@@ -982,16 +1304,21 @@ function updateFunction(lowering) {
982
1304
  const vector = stateDrivenVectorOf(node);
983
1305
  return vector ? [{ node, vector }] : [];
984
1306
  });
985
- if (!updated.length &&
1307
+ const derivedLists = lowering.app.state.flatMap(state => state.kind === 'list' && state.derived ? [state] : []);
1308
+ const workedValues = lowering.app.state.flatMap(state => state.kind === 'scalar' && state.worked ? [state] : []);
1309
+ if (!derivedLists.length &&
1310
+ !workedValues.length &&
1311
+ !updated.length &&
986
1312
  !setOnce.length &&
987
1313
  !drawings.length &&
1314
+ !lowering.branchings.length &&
988
1315
  !output.dependencyEffects.length &&
989
1316
  !output.mountEffects.length) {
990
1317
  return null;
991
1318
  }
992
1319
  const builder = new FunctionBuilder(FunctionKind.update, 'the update');
993
1320
  const codegen = new Codegen(builder, lowering.slots);
994
- const { pending, realBits, mountNext } = lowering.effects;
1321
+ const { mountNext } = lowering.effects;
995
1322
  const located = (node, lower) => {
996
1323
  builder.at(node.location);
997
1324
  try {
@@ -1010,49 +1337,121 @@ function updateFunction(lowering) {
1010
1337
  ? [...reads].map(state => stateSlotOf(state, lowering.slots))
1011
1338
  : [];
1012
1339
  if (bits.length && bits.every(slot => slot.flags & SlotFlag.tracked)) {
1013
- whenDirty(builder, bits, lower, bits.flatMap(slot => pending.get(slot) ?? []));
1340
+ whenDirty(builder, bits, lower);
1014
1341
  }
1015
1342
  else {
1016
1343
  lower();
1017
1344
  }
1018
1345
  };
1019
- // A pass only an effect's writes started keeps what they changed for the next one.
1020
1346
  const end = builder.label();
1021
- if (pending.size) {
1022
- const real = builder.label();
1023
- for (const [word, mask] of dirtyMasks(realBits)) {
1024
- builder.branchIfDirty(word, mask, real);
1025
- }
1026
- for (const [state, flag] of pending) {
1027
- whenDirty(builder, [state], () => setConstant(codegen, flag, 1));
1028
- }
1029
- builder.branch('JMP', end);
1030
- builder.place(real);
1347
+ // The lists filtered or sorted in render, and the values memos and helpers loop for, worked out first, each after
1348
+ // what it reads, as what reads them counts what they read.
1349
+ const rebuilds = [
1350
+ ...derivedLists.map(list => ({
1351
+ order: list.derived.order ?? 0,
1352
+ reads: () => listReads(list),
1353
+ statements: list.derived.rebuild,
1354
+ })),
1355
+ ...workedValues.map(value => ({
1356
+ order: value.worked.order,
1357
+ reads: () => workedReads(value),
1358
+ statements: value.worked.rebuild,
1359
+ })),
1360
+ ];
1361
+ if (workedValues.length)
1362
+ rebuilds.sort((a, b) => a.order - b.order);
1363
+ for (const { reads, statements } of rebuilds) {
1364
+ whenRead(reads(), () => codegen.scoped(() => codegen.statements(statements)));
1365
+ }
1366
+ // The branches a test no longer picks, destroyed before anything is built, with the conditionals in them.
1367
+ const { branchings, places } = lowering;
1368
+ for (const branching of branchings) {
1369
+ codegen.scoped(() => {
1370
+ const kept = builder.label();
1371
+ const built = codegen.get(branching.built);
1372
+ builder.branch('JF', kept, codegen.truthy(built));
1373
+ whenRead(conditionalReads(branching.conditional), () => codegen.scoped(() => {
1374
+ builder.branch('JT', kept, codegen.same(picked(codegen, branching), built));
1375
+ const root = builder.register('node');
1376
+ builder.abx('GET64', root.index, branching.root.index);
1377
+ builder.abc('DESTROY', root.index);
1378
+ for (const each of [branching, ...branching.nested]) {
1379
+ setConstant(codegen, each.built, 0);
1380
+ }
1381
+ }));
1382
+ builder.place(kept);
1383
+ });
1031
1384
  }
1032
- // The rows, the props that read only boot values, and the drawings that do, built once.
1033
- const builtOnce = drawings.filter(({ node }) => !updatedVectorOf(node));
1034
- if (setOnce.length || lowering.pools.length || builtOnce.length) {
1385
+ // The rows, the props that read only boot values, and the drawings that do, built once, outside the branches.
1386
+ const atRoot = (node) => !places.has(node);
1387
+ const rootPools = lowering.pools.filter(pool => !pool.within);
1388
+ const rootSetOnce = setOnce.filter(atRoot);
1389
+ const builtOnce = drawings.filter(({ node }) => !updatedVectorOf(node) && atRoot(node));
1390
+ if (rootSetOnce.length || rootPools.length || builtOnce.length) {
1035
1391
  whenDirty(builder, [lowering.once], () => {
1036
- buildRows(codegen, lowering);
1037
- setOnce.forEach(node => located(node, () => setNode(codegen, node, lowering)));
1392
+ rootPools.forEach(pool => buildPool(codegen, pool, lowering));
1393
+ rootSetOnce.forEach(node => located(node, () => setNode(codegen, node, lowering)));
1038
1394
  builtOnce.forEach(({ node, vector }) => draw(node, vector));
1039
1395
  });
1040
1396
  }
1041
- // The nodes, then the drawings.
1397
+ // The nodes, then the drawings, each only while its branch is built.
1042
1398
  for (const node of updated) {
1043
- located(node, () => whenRead(nodeReads(node), () => setNode(codegen, node, lowering)));
1399
+ located(node, () => whenRead(nodeReads(node), () => whileBuilt(codegen, places.get(node), () => setNode(codegen, node, lowering))));
1044
1400
  }
1045
1401
  for (const { node, vector } of drawings) {
1046
1402
  if (updatedVectorOf(node)) {
1047
- whenRead(vectorReads(vector), () => draw(node, vector));
1403
+ whenRead(vectorReads(vector), () => whileBuilt(codegen, places.get(node), () => draw(node, vector)));
1048
1404
  }
1049
1405
  }
1050
- for (const flag of pending.values()) {
1051
- setConstant(codegen, flag, 0);
1406
+ // The branches picked that aren't built, outer ones first: each built with its rows, then all of its props.
1407
+ for (const branching of branchings) {
1408
+ const skip = builder.label();
1409
+ whileBuilt(codegen, branching.within, () => codegen.scoped(() => {
1410
+ builder.branch('JT', skip, codegen.truthy(codegen.get(branching.built)));
1411
+ const choice = picked(codegen, branching);
1412
+ branching.alternatives.forEach((_, place) => {
1413
+ const alternative = place + 1;
1414
+ const other = builder.label();
1415
+ codegen.scoped(() => {
1416
+ builder.branch('JF', other, codegen.same(choice, codegen.load('int', alternative)));
1417
+ const parent = nodeHandle(codegen, branching.parent, lowering);
1418
+ const root = builder.register('node');
1419
+ buildBefore(codegen, parent, branching.anchors, lowering, before => builder.abc('BUILD', root.index, parent.index, before.index, branching.templates[place] | (NO_REGISTER << 16)));
1420
+ setConstant(codegen, branching.built, alternative);
1421
+ const inside = (within) => within?.branching === branching &&
1422
+ within.alternative === alternative;
1423
+ lowering.pools
1424
+ .filter(pool => inside(pool.within))
1425
+ .forEach(pool => buildPool(codegen, pool, lowering));
1426
+ nodes
1427
+ .filter(node => inside(places.get(node)) &&
1428
+ (isStateDriven(node) || isSetOnce(node)))
1429
+ .forEach(node => located(node, () => setNode(codegen, node, lowering)));
1430
+ drawings
1431
+ .filter(({ node }) => inside(places.get(node)))
1432
+ .forEach(({ node, vector }) => draw(node, vector));
1433
+ builder.branch('JMP', skip);
1434
+ });
1435
+ builder.place(other);
1436
+ });
1437
+ }));
1438
+ builder.place(skip);
1052
1439
  }
1053
- // Each dep-driven effect checks its deps when it runs, each in turn.
1054
- for (const check of lowering.effectFunctions.checks) {
1055
- builder.abx('EFFECT', 0, check);
1440
+ // Each dep-driven effect checks its deps when it runs, each in turn. A batch already waiting sees what this pass
1441
+ // shows, so another isn't queued.
1442
+ const { checksQueued } = lowering.effects;
1443
+ if (checksQueued) {
1444
+ codegen.scoped(() => {
1445
+ const skip = builder.label();
1446
+ const waiting = builder.register('bool');
1447
+ builder.abx('GET32', waiting.index, checksQueued.index);
1448
+ builder.branch('JT', skip, waiting);
1449
+ setConstant(codegen, checksQueued, 1);
1450
+ for (const check of lowering.effectFunctions.checks) {
1451
+ builder.abx('EFFECT', 0, check);
1452
+ }
1453
+ builder.place(skip);
1454
+ });
1056
1455
  }
1057
1456
  // The first mount effect, then each one after a mount effect that set state.
1058
1457
  if (mountNext) {
@@ -1192,6 +1591,66 @@ function timerBody(name, callback, lowering) {
1192
1591
  }
1193
1592
  return builder.finish();
1194
1593
  }
1594
+ /**
1595
+ * The handlers of each native event the app subscribes to, in the order they lowered.
1596
+ *
1597
+ * @param handlers Every useNativeEvent's handler.
1598
+ *
1599
+ * @returns Them, grouped by event.
1600
+ */
1601
+ function byEvent(handlers) {
1602
+ const groups = new Map();
1603
+ for (const handler of handlers) {
1604
+ const { name, version, signature } = handler.event;
1605
+ const key = `${name} ${version} ${signature}`;
1606
+ groups.set(key, [...(groups.get(key) ?? []), handler]);
1607
+ }
1608
+ return [...groups.values()];
1609
+ }
1610
+ /**
1611
+ * A native event's function: entered with its values, it runs each subscriber whose component is mounted. Whether
1612
+ * each one is mounted is read before any of them runs, as Flow A calls the subscribers it had when the event came.
1613
+ *
1614
+ * @param handlers The event's subscribers.
1615
+ * @param lowering The program being lowered.
1616
+ *
1617
+ * @returns The function.
1618
+ */
1619
+ function nativeEventBody(handlers, lowering) {
1620
+ const { event } = handlers[0];
1621
+ const builder = new FunctionBuilder(FunctionKind.nativeEvent, `native event ${event.name}`);
1622
+ // The event's values from register 0, laid out as the runtime enters the function: an int64 on an even register.
1623
+ const values = event.params.map(type => builder.reserved(type));
1624
+ const last = values.at(-1);
1625
+ const parameterCells = last
1626
+ ? last.index + (last.type === 'int64' ? 2 : 1)
1627
+ : 0;
1628
+ const codegenOf = (handler) => new Codegen(builder, lowering.slots, {
1629
+ values: new Map(handler.values.map((name, position) => [name, values[position]])),
1630
+ });
1631
+ const mounted = handlers.map(handler => {
1632
+ if (!handler.mounted) {
1633
+ return null;
1634
+ }
1635
+ const test = handler.mounted;
1636
+ const kept = builder.reserved('bool');
1637
+ const codegen = codegenOf(handler);
1638
+ codegen.scoped(() => builder.abc('MOVE', kept.index, codegen.condition(test).index));
1639
+ return kept;
1640
+ });
1641
+ handlers.forEach((handler, index) => {
1642
+ const skip = builder.label();
1643
+ if (mounted[index]) {
1644
+ builder.branch('JF', skip, mounted[index]);
1645
+ }
1646
+ codegenOf(handler).statements(handler.callback.body);
1647
+ builder.place(skip);
1648
+ });
1649
+ if (handlers.some(handler => handler.callback.updatesState)) {
1650
+ requestUpdate(codegenOf(handlers[0]), lowering);
1651
+ }
1652
+ return builder.finish(parameterCells);
1653
+ }
1195
1654
  /**
1196
1655
  * An animation completion's helper: entered with what it was passed, which the body reads as `finished`.
1197
1656
  *
@@ -1274,10 +1733,10 @@ function runEffect(effect, codegen, lowering) {
1274
1733
  builder.branch('JF', skip, flag);
1275
1734
  });
1276
1735
  setConstant(codegen, armed, 0);
1277
- codegen.statements(effect.cleanup ?? []);
1736
+ codegen.body(effect.cleanup ?? []);
1278
1737
  builder.place(skip);
1279
1738
  }
1280
- codegen.statements(effect.body);
1739
+ codegen.body(effect.body);
1281
1740
  }
1282
1741
  /**
1283
1742
  * The function a dep-driven effect runs in after an update pass: it copies each dep that changed,
@@ -1291,8 +1750,14 @@ function runEffect(effect, codegen, lowering) {
1291
1750
  function checkedEffect(effect, lowering) {
1292
1751
  const builder = new FunctionBuilder(FunctionKind.effect, `effect ${effect.id}`);
1293
1752
  const end = builder.label();
1294
- const codegen = new Codegen(builder, lowering.slots, { onReturn: end });
1753
+ // An early `return` still ends at the request.
1754
+ const ran = builder.label();
1755
+ const codegen = new Codegen(builder, lowering.slots, { onReturn: ran });
1295
1756
  const copies = lowering.effects.copies.get(effect);
1757
+ // The batch has started, so a write from here on needs one of its own.
1758
+ if (effect === lowering.app.output.dependencyEffects[0]) {
1759
+ setConstant(codegen, lowering.effects.checksQueued, 0);
1760
+ }
1296
1761
  const changed = builder.register('bool');
1297
1762
  builder.abx('LOADI', changed.index, 0);
1298
1763
  effect.dependencies.forEach((dependency, index) => {
@@ -1308,6 +1773,10 @@ function checkedEffect(effect, lowering) {
1308
1773
  });
1309
1774
  builder.branch('JF', end, changed);
1310
1775
  runEffect(effect, codegen, lowering);
1776
+ builder.place(ran);
1777
+ if (setsState(effect)) {
1778
+ requestUpdate(codegen, lowering);
1779
+ }
1311
1780
  builder.place(end);
1312
1781
  return builder.finish();
1313
1782
  }
@@ -1355,6 +1824,12 @@ function mountEffect(index, lowering) {
1355
1824
  else if (hasNext) {
1356
1825
  builder.abx('EFFECT', 0, lowering.effectFunctions.mounts[index + 1]);
1357
1826
  }
1827
+ // After the last, the dep-driven effects check what the mount effects changed.
1828
+ if (!hasNext) {
1829
+ for (const check of lowering.effectFunctions.checks) {
1830
+ builder.abx('EFFECT', 0, check);
1831
+ }
1832
+ }
1358
1833
  return builder.finish();
1359
1834
  }
1360
1835
  /**
@@ -1367,18 +1842,24 @@ function mountEffect(index, lowering) {
1367
1842
  */
1368
1843
  function appendInitialItems(list, codegen, lowering) {
1369
1844
  const { builder } = codegen;
1370
- const { fields } = list.struct;
1845
+ const entries = rowEntries(list.struct);
1371
1846
  for (const item of list.items) {
1372
1847
  codegen.scoped(() => {
1373
- const row = builder.consecutive(fields.map(field => (field.kind === 'string' ? 'string' : field.kind)));
1374
- fields.forEach((field, index) => {
1375
- const value = item[field.key];
1376
- if (field.kind === 'string') {
1377
- builder.abx('LOADS', row[index].index, lowering.slots.tables.string(String(value ?? '')));
1848
+ const row = builder.consecutive(entries.map(({ field, presence }) => presence ? 'bool' : field.kind === 'string' ? 'string' : field.kind));
1849
+ entries.forEach(({ field, presence }, index) => {
1850
+ const { present, value } = itemValueAt(item, field);
1851
+ if (field.kind === 'string' && !presence) {
1852
+ builder.abx('LOADS', row[index].index, lowering.slots.tables.string(present ? String(value) : ''));
1378
1853
  return;
1379
1854
  }
1380
- const number = Number(value) || 0;
1381
- codegen.scoped(() => builder.abc('MOVE', row[index].index, codegen.load(field.kind, field.kind === 'float' ? number : Math.round(number)).index));
1855
+ const number = presence || field.kind === 'bool'
1856
+ ? Number(presence ? present : !!value)
1857
+ : Number(value) || 0;
1858
+ const kind = presence
1859
+ ? 'bool'
1860
+ : field.kind;
1861
+ codegen.scoped(() => builder.abc('MOVE', row[index].index, codegen.load(kind, kind === 'float' ? number : Math.round(number))
1862
+ .index));
1382
1863
  });
1383
1864
  builder.abx('APPEND', row[0].index, lowering.slots.lists.get(list).slot.index);
1384
1865
  });
@@ -1413,6 +1894,11 @@ function bootFunction(bootSlots, lowering) {
1413
1894
  builder.abx('SCREEN', size.index, initializer.dimension === 'width' ? 0 : 1);
1414
1895
  codegen.set(slot, size);
1415
1896
  }
1897
+ else if (initializer.kind === 'native') {
1898
+ const available = builder.register('bool');
1899
+ builder.abx('AVAIL', available.index, initializer.module);
1900
+ codegen.set(slot, available);
1901
+ }
1416
1902
  else {
1417
1903
  codegen.set(slot, codegen.value(initializer.expression));
1418
1904
  }
@@ -1502,15 +1988,12 @@ export function lowerPackage(app, options) {
1502
1988
  },
1503
1989
  ];
1504
1990
  templateNodes(app.root, lowering, nodes);
1991
+ branchTemplates(lowering);
1505
1992
  rowTemplates(lowering);
1506
- // Every row is built, whether the list holds it or not.
1507
- const built = [
1508
- ...nodes,
1509
- ...lowering.pools.flatMap(pool => pool.templates.flatMap(template => lowering.templates[template - 1].nodes)),
1510
- ];
1511
- const nodeCount = built.length;
1512
- const vectorType = ENGINE_VALUES.get('ER_NODE_VECTOR');
1513
- const vectorNodes = built.filter(node => node.type === vectorType).length;
1993
+ // Every row is built, whether the list holds it or not, and the largest branch of each conditional; the root
1994
+ // template's own node too.
1995
+ const nodeCount = 1 + mostBuilt(app.root, () => 1);
1996
+ const vectorNodes = mostBuilt(app.root, node => node.type === 'ER_NODE_VECTOR' ? 1 : 0);
1514
1997
  if (nodeCount > MAX_U16) {
1515
1998
  throw aotError(`AOT: the app needs ${nodeCount} nodes, but a package holds ${MAX_U16}`, 'lower ER_AOT_LIST_CAP (the listCap option), or give the list rows fewer nodes.');
1516
1999
  }
@@ -1520,6 +2003,36 @@ export function lowerPackage(app, options) {
1520
2003
  for (const timer of output.timerFunctions) {
1521
2004
  lowering.slots.timerFunctions.set(timer.name, next++);
1522
2005
  }
2006
+ if (output.nativeEventHandlers.length > MAX_NATIVE_EVENTS) {
2007
+ throw aotError(`AOT: the app subscribes to native events ${output.nativeEventHandlers.length} times, but a package holds ` +
2008
+ `${MAX_NATIVE_EVENTS}`, 'each useNativeEvent counts once, and once for each row of a list it is in: subscribe in the component ' +
2009
+ 'that holds the list instead.');
2010
+ }
2011
+ // An optional module's methods and events are all listed, used or not, so that whether it is there agrees with
2012
+ // Flow A, which looks for them all. An event nothing subscribes to has no function.
2013
+ for (const module of output.optionalModules) {
2014
+ module.methods.forEach(method => tables.nativeImport(method));
2015
+ }
2016
+ const subscribed = byEvent(output.nativeEventHandlers);
2017
+ const nativeEvent = (event, handler) => ({
2018
+ name: tables.string(event.name),
2019
+ version: event.version,
2020
+ signature: tables.string(event.signature),
2021
+ function: handler,
2022
+ module: event.module ?? NONE,
2023
+ });
2024
+ const nativeEvents = subscribed.map(([{ event }]) => nativeEvent(event, next++));
2025
+ const subscribedNames = new Set(subscribed.map(([{ event }]) => event.name));
2026
+ for (const module of output.optionalModules) {
2027
+ for (const event of module.events) {
2028
+ if (!subscribedNames.has(event.name)) {
2029
+ nativeEvents.push(nativeEvent(event, NONE));
2030
+ }
2031
+ }
2032
+ }
2033
+ if (nativeEvents.length > MAX_NATIVE_EVENTS) {
2034
+ throw aotError(`AOT: the app lists ${nativeEvents.length} native events, but a package holds ${MAX_NATIVE_EVENTS}`, 'an optional module counts every event its interface declares; declare fewer events.');
2035
+ }
1523
2036
  lowering.effectFunctions = {
1524
2037
  checks: output.dependencyEffects.map(() => next++),
1525
2038
  mounts: output.mountEffects.map(() => next++),
@@ -1530,6 +2043,7 @@ export function lowerPackage(app, options) {
1530
2043
  const functions = [
1531
2044
  ...[...lowering.handlers.values()].map(handler => handlerBody(handler, lowering)),
1532
2045
  ...output.timerFunctions.map(timer => timerBody(timer.name, timer.callback, lowering)),
2046
+ ...subscribed.map(handlers => nativeEventBody(handlers, lowering)),
1533
2047
  ...output.dependencyEffects.map(effect => checkedEffect(effect, lowering)),
1534
2048
  ...output.mountEffects.map((_, index) => mountEffect(index, lowering)),
1535
2049
  ...doneFunctions(animations, builder => new Codegen(builder, lowering.slots)),
@@ -1545,6 +2059,21 @@ export function lowerPackage(app, options) {
1545
2059
  const ends = Math.max(0, ...functions.map(programFunction => countOps(programFunction, ['ASTART', 'AVSET', 'ASTOP'])));
1546
2060
  lowering.slots.arena.eventQueue(animations.entries + 2 * ends);
1547
2061
  }
2062
+ // A scrollTo in a function fires onScroll, which waits in the queue until the function ends. The runtime keeps
2063
+ // one waiting event per ScrollView, and each scrollTo scrolls one, so a loop needs no more room.
2064
+ if (functions.some(programFunction => programFunction.kind === ENGINE_VALUES.get('ER_EVENT_SCROLL'))) {
2065
+ let scrolls = 0;
2066
+ for (const programFunction of functions) {
2067
+ scrolls += countOps(programFunction, ['SCROLL']);
2068
+ }
2069
+ lowering.slots.arena.eventQueue(scrolls);
2070
+ }
2071
+ // A Keyboard.dismiss() in a function fires onBlur, which waits in the queue until the function ends. One input
2072
+ // has the focus, so one blur waits at a time.
2073
+ if (functions.some(programFunction => programFunction.kind === ENGINE_VALUES.get('ER_EVENT_BLUR')) &&
2074
+ functions.some(programFunction => countOps(programFunction, ['BLUR']))) {
2075
+ lowering.slots.arena.eventQueue(1);
2076
+ }
1548
2077
  const { regions, bytes } = lowering.slots.arena.regions(stackCells(functions));
1549
2078
  // Host values, by name, for erb_input_find().
1550
2079
  const inputs = app.state
@@ -1598,6 +2127,8 @@ export function lowerPackage(app, options) {
1598
2127
  bindings: lowering.bindings,
1599
2128
  functions,
1600
2129
  animations: animations.animations,
2130
+ imports: tables.imports,
2131
+ nativeEvents,
1601
2132
  inputs,
1602
2133
  interpolations: animations.interpolations,
1603
2134
  tapes: lowering.slots.vectors.tapes,