embedded-react 0.19.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 (148) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +8 -3
  3. package/aot/app-file-loader.mjs +116 -0
  4. package/aot/compile.mjs +180 -90
  5. package/aot/compiler/animations.mjs +568 -317
  6. package/aot/compiler/boot.mjs +97 -35
  7. package/aot/compiler/branch-merge.mjs +4 -3
  8. package/aot/compiler/check.mjs +70 -18
  9. package/aot/compiler/collect.mjs +787 -288
  10. package/aot/compiler/contexts.mjs +391 -0
  11. package/aot/compiler/control-flow.mjs +439 -268
  12. package/aot/compiler/custom-hooks.mjs +686 -0
  13. package/aot/compiler/diagnostics.mjs +22 -25
  14. package/aot/compiler/elements/activity-indicator.mjs +25 -24
  15. package/aot/compiler/elements/button.mjs +182 -0
  16. package/aot/compiler/elements/dial.mjs +91 -77
  17. package/aot/compiler/elements/flat-list.mjs +24 -22
  18. package/aot/compiler/elements/image-background.mjs +76 -0
  19. package/aot/compiler/elements/image.mjs +52 -50
  20. package/aot/compiler/elements/modal.mjs +31 -30
  21. package/aot/compiler/elements/props.mjs +61 -26
  22. package/aot/compiler/elements/rewrite.mjs +118 -0
  23. package/aot/compiler/elements/section-list.mjs +370 -0
  24. package/aot/compiler/elements/switch.mjs +42 -34
  25. package/aot/compiler/elements/text-input.mjs +34 -32
  26. package/aot/compiler/expressions.mjs +1685 -392
  27. package/aot/compiler/handlers.mjs +2029 -547
  28. package/aot/compiler/helper-values.mjs +312 -0
  29. package/aot/compiler/ir/functions.mjs +11 -1
  30. package/aot/compiler/ir/nodes.mjs +43 -4
  31. package/aot/compiler/ir/reads.mjs +223 -22
  32. package/aot/compiler/ir/text.mjs +5 -1
  33. package/aot/compiler/ir/types.mjs +26 -14
  34. package/aot/compiler/ir/vectors.mjs +5 -1
  35. package/aot/compiler/kept-states.mjs +177 -0
  36. package/aot/compiler/keyboard.mjs +17 -7
  37. package/aot/compiler/list-items.mjs +226 -0
  38. package/aot/compiler/list-order.mjs +586 -0
  39. package/aot/compiler/list-split.mjs +259 -0
  40. package/aot/compiler/loops.mjs +582 -0
  41. package/aot/compiler/lower.mjs +246 -111
  42. package/aot/compiler/native-files.mjs +439 -0
  43. package/aot/compiler/native-header.mjs +335 -0
  44. package/aot/compiler/native-modules.mjs +1173 -0
  45. package/aot/compiler/nodes.mjs +195 -172
  46. package/aot/compiler/options.mjs +37 -31
  47. package/aot/compiler/out.mjs +32 -23
  48. package/aot/compiler/package/animations.mjs +779 -0
  49. package/aot/compiler/package/arena.mjs +252 -0
  50. package/aot/compiler/package/assemble.mjs +175 -0
  51. package/aot/compiler/package/bytecode.mjs +315 -0
  52. package/aot/compiler/package/checks.mjs +1026 -0
  53. package/aot/compiler/package/codegen.mjs +2168 -0
  54. package/aot/compiler/package/enums.mjs +148 -0
  55. package/aot/compiler/package/format.mjs +771 -0
  56. package/aot/compiler/package/layouts.mjs +136 -0
  57. package/aot/compiler/package/lower.mjs +2103 -0
  58. package/aot/compiler/package/props.mjs +118 -0
  59. package/aot/compiler/package/string-caps.mjs +515 -0
  60. package/aot/compiler/package/tables.mjs +127 -0
  61. package/aot/compiler/package/vectors.mjs +502 -0
  62. package/aot/compiler/package/writer.mjs +686 -0
  63. package/aot/compiler/pan-responder.mjs +69 -61
  64. package/aot/compiler/parse.mjs +23 -21
  65. package/aot/compiler/record-shapes.mjs +246 -0
  66. package/aot/compiler/records.mjs +654 -0
  67. package/aot/compiler/reducers.mjs +272 -0
  68. package/aot/compiler/static-eval.mjs +340 -30
  69. package/aot/compiler/style-text.mjs +178 -174
  70. package/aot/compiler/svg.mjs +480 -251
  71. package/aot/compiler/switch-cases.mjs +198 -0
  72. package/aot/compiler/tagged-records.mjs +450 -0
  73. package/aot/compiler/typing.mjs +307 -0
  74. package/aot/compiler/updaters.mjs +320 -0
  75. package/aot/compiler/window-dimensions.mjs +94 -0
  76. package/aot/compiler/worked-values.mjs +319 -0
  77. package/aot/demo-file.mjs +30 -0
  78. package/aot/screenshot-smoke.mjs +54 -40
  79. package/aot/style-map.mjs +152 -92
  80. package/assets/bake-font.mjs +123 -77
  81. package/assets/bake-image.mjs +39 -22
  82. package/assets/bake-svg.mjs +361 -262
  83. package/assets/build-builtin-font.mjs +11 -7
  84. package/assets/emit-c.mjs +77 -58
  85. package/assets/emit-container.mjs +123 -37
  86. package/assets/emit-pack.mjs +77 -67
  87. package/assets/font-config.mjs +9 -6
  88. package/assets/font-sizes.mjs +163 -123
  89. package/assets/glyph-coverage.mjs +74 -54
  90. package/assets/index.mjs +31 -9
  91. package/assets/rasterize.mjs +126 -99
  92. package/assets/svg-loader.mjs +8 -8
  93. package/build.mjs +23 -13
  94. package/cli.mjs +402 -172
  95. package/compile-bin.mjs +3 -3
  96. package/flash.mjs +537 -0
  97. package/hotreload/dev-device.mjs +90 -33
  98. package/hotreload/pack-app.mjs +55 -43
  99. package/hotreload/pack-split.mjs +62 -64
  100. package/hotreload/package-transfer.mjs +175 -0
  101. package/hotreload/protocol.mjs +50 -37
  102. package/hotreload/uploader.mjs +38 -27
  103. package/hotreload/watch-tree.mjs +19 -19
  104. package/pack-container.mjs +37 -21
  105. package/package.json +7 -8
  106. package/persist-transform.mjs +34 -28
  107. package/qjsc-wasm.mjs +25 -14
  108. package/sim/embedded-react.cjs +1 -1
  109. package/sim/embedded-react.js +1 -1
  110. package/sim/embedded-react.wasm +0 -0
  111. package/sim/index.html +94 -85
  112. package/sim-server.mjs +113 -94
  113. package/src/embedded-react/Animated.js +24 -24
  114. package/src/embedded-react/Dimensions.js +37 -0
  115. package/src/embedded-react/Easing.js +1 -1
  116. package/src/embedded-react/FlatList.js +3 -3
  117. package/src/embedded-react/LayoutAnimation.js +8 -5
  118. package/src/embedded-react/PanResponder.js +75 -71
  119. package/src/embedded-react/Pressable.js +2 -8
  120. package/src/embedded-react/SectionList.js +7 -9
  121. package/src/embedded-react/StyleSheet.js +4 -3
  122. package/src/embedded-react/TouchableOpacity.js +13 -8
  123. package/src/embedded-react/index.d.ts +88 -8
  124. package/src/embedded-react/index.js +2 -0
  125. package/src/embedded-react/layout-anim-config.js +10 -4
  126. package/src/embedded-react/list-child.js +5 -5
  127. package/src/embedded-react/named-colors.js +1 -1
  128. package/src/embedded-react/nativeModule.js +462 -0
  129. package/src/embedded-react/split-style.js +11 -11
  130. package/src/embedded-react/svg-ops.js +760 -593
  131. package/src/embedded-react/useHostValue.js +3 -3
  132. package/src/embedded-react/usePersistentState.js +6 -6
  133. package/src/embedded-react/warn-props.js +1 -1
  134. package/src/host-config.js +60 -53
  135. package/src/props.js +49 -41
  136. package/src/renderer.js +7 -4
  137. package/aot/compiler/assemble.mjs +0 -944
  138. package/aot/compiler/c/animations.mjs +0 -436
  139. package/aot/compiler/c/boot.mjs +0 -127
  140. package/aot/compiler/c/expressions.mjs +0 -270
  141. package/aot/compiler/c/functions.mjs +0 -268
  142. package/aot/compiler/c/keyboard.mjs +0 -96
  143. package/aot/compiler/c/nodes.mjs +0 -303
  144. package/aot/compiler/c/pan-responder.mjs +0 -136
  145. package/aot/compiler/c/statements.mjs +0 -319
  146. package/aot/compiler/c/text.mjs +0 -83
  147. package/aot/compiler/c/vectors.mjs +0 -381
  148. package/aot/compiler/c-syntax.mjs +0 -127
@@ -0,0 +1,370 @@
1
+ /*
2
+ * Copyright 2026 Cory Lamming
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ /*----------------------------------------------------------------------------------------------------------------------
17
+ - Imports
18
+ ---------------------------------------------------------------------------------------------------------------------*/
19
+ import { aotError } from '../diagnostics.mjs';
20
+ import { componentReturnJSX, isFn } from '../collect.mjs';
21
+ import { emitChildren, rowEnv } from '../control-flow.mjs';
22
+ import { foldRuntime } from '../expressions.mjs';
23
+ import { emitNode } from '../nodes.mjs';
24
+ import { evalStatic, setBinding } from '../static-eval.mjs';
25
+ import { attrExpr } from '../style-text.mjs';
26
+ import { patternNames } from '../updaters.mjs';
27
+ import { at } from './props.mjs';
28
+ import { elementOf, expressionChild, refuseSpreads } from './rewrite.mjs';
29
+ /*----------------------------------------------------------------------------------------------------------------------
30
+ - Constants
31
+ ---------------------------------------------------------------------------------------------------------------------*/
32
+ /** A constant section's rows; `@` keeps it from meeting an app's name. */
33
+ const SECTION_DATA = 'data@section';
34
+ const SECTIONS_HINT = 'write sections={[{title: …, data: …}, …]} in place, where a data may be list state, or use a constant ' +
35
+ 'array. The number of sections is fixed at build time; a list of rows is not.';
36
+ /*----------------------------------------------------------------------------------------------------------------------
37
+ - Implementation
38
+ ---------------------------------------------------------------------------------------------------------------------*/
39
+ /**
40
+ * <SectionList sections renderItem renderSectionHeader renderSectionFooter style /> → a <ScrollView> holding each
41
+ * section's header, rows and footer as flat siblings, as SectionList.js renders it. The sections are unrolled at
42
+ * build time; each section's rows are a `.map` over its data, so a data that is list state is a pool of rows.
43
+ * keyExtractor is ignored (no reconciler).
44
+ *
45
+ * @param element The <SectionList>, its props already checked.
46
+ * @param scope Compile-time constants in reach.
47
+ * @param output Everything emitted so far.
48
+ * @param environment The expression environment.
49
+ * @param state The component's state table.
50
+ * @param options How the element is placed.
51
+ *
52
+ * @returns What the <ScrollView> lowers to.
53
+ */
54
+ export function emitSectionList(element, scope, output, environment, state, options) {
55
+ refuseSpreads(element, 'SectionList');
56
+ const attributes = new Map();
57
+ for (const attribute of element.openingElement
58
+ .attributes) {
59
+ attributes.set(attribute.name.name, attribute);
60
+ }
61
+ const sectionsAttribute = attributes.get('sections');
62
+ if (!sectionsAttribute) {
63
+ throw aotError('AOT: <SectionList> needs a sections prop', "sections={[{title: 'A', data: items}]}");
64
+ }
65
+ const renderItem = callbackOf(attributes.get('renderItem'), 'renderItem');
66
+ const header = callbackOf(attributes.get('renderSectionHeader'), 'renderSectionHeader');
67
+ const footer = callbackOf(attributes.get('renderSectionFooter'), 'renderSectionFooter');
68
+ const sections = sectionsOf(sectionsAttribute, scope, environment);
69
+ // The ScrollView first, so its node comes before the rows it holds.
70
+ const styleAttribute = attributes.get('style');
71
+ const scrollView = emitNode(elementOf('ScrollView', styleAttribute ? [styleAttribute] : [], [], element), scope, output, environment, state, options);
72
+ // Each callback sees its own name for the section.
73
+ const emitBound = (callback, allowed, section, child) => {
74
+ const names = destructured(callback, allowed);
75
+ const sectionName = names.get('section');
76
+ // A data that is list state has no value to bind, so `section.data` reads it where it is written.
77
+ const bound = sectionName && section.data && !Object.hasOwn(section.value, 'data')
78
+ ? {
79
+ ...callback,
80
+ body: withSectionData(callback.body, sectionName, section.data),
81
+ }
82
+ : callback;
83
+ const sectionScope = { ...scope };
84
+ if (sectionName) {
85
+ setBinding(sectionScope, sectionName, section.value);
86
+ }
87
+ if (section.constantData) {
88
+ setBinding(sectionScope, SECTION_DATA, section.constantData);
89
+ }
90
+ scrollView.node.children.push(...emitChildren([child(bound, names)], sectionScope, output, rowEnv(environment, [sectionName], sectionScope), state));
91
+ };
92
+ for (const section of sections) {
93
+ if (header) {
94
+ emitBound(header, ['section'], section, bound => bodyChild(bound));
95
+ }
96
+ const rowRenderer = section.renderItem ?? renderItem;
97
+ const rows = section.data ??
98
+ (section.constantData
99
+ ? { type: 'Identifier', name: SECTION_DATA }
100
+ : null);
101
+ if (rows) {
102
+ if (!rowRenderer) {
103
+ throw at(aotError('AOT: a <SectionList> section with data needs a renderItem', 'renderItem={({item}) => <Row item={item} />} on the list, or on the section.'), section.node);
104
+ }
105
+ emitBound(rowRenderer, ['item', 'index', 'section'], section, (bound, names) => rowsChild(bound, names, rows));
106
+ }
107
+ if (footer) {
108
+ emitBound(footer, ['section'], section, bound => bodyChild(bound));
109
+ }
110
+ }
111
+ return scrollView;
112
+ }
113
+ /**
114
+ * `node` with each `<sectionName>.data` read replaced by `data`, outside functions that bind the name again.
115
+ * The callback is shared by every section, so what changes is copied.
116
+ *
117
+ * @param node A node of the callback's body.
118
+ * @param sectionName The callback's name for the section.
119
+ * @param data The section's data, as written.
120
+ *
121
+ * @returns The node, or a copy with the reads replaced.
122
+ */
123
+ function withSectionData(node, sectionName, data) {
124
+ if (Array.isArray(node)) {
125
+ const replaced = node.map(entry => withSectionData(entry, sectionName, data));
126
+ return replaced.some((entry, index) => entry !== node[index])
127
+ ? replaced
128
+ : node;
129
+ }
130
+ if (!node || typeof node.type !== 'string')
131
+ return node;
132
+ const astNode = node;
133
+ if ((astNode.type === 'MemberExpression' ||
134
+ astNode.type === 'OptionalMemberExpression') &&
135
+ !astNode.computed &&
136
+ astNode.object.type === 'Identifier' &&
137
+ astNode.object.name === sectionName &&
138
+ astNode.property.type === 'Identifier' &&
139
+ astNode.property.name === 'data') {
140
+ return data;
141
+ }
142
+ if (isFn(astNode) &&
143
+ astNode.params.some(parameter => patternNames(parameter).includes(sectionName))) {
144
+ return node;
145
+ }
146
+ let copy = null;
147
+ for (const [key, value] of Object.entries(astNode)) {
148
+ if (key === 'loc' || key.endsWith('Comments'))
149
+ continue;
150
+ const replaced = withSectionData(value, sectionName, data);
151
+ if (replaced !== value) {
152
+ copy ??= { ...astNode };
153
+ copy[key] = replaced;
154
+ }
155
+ }
156
+ return copy ?? node;
157
+ }
158
+ /**
159
+ * A render callback prop, which must be an inline function.
160
+ *
161
+ * @param attribute The prop, if given.
162
+ * @param name Its name, for the error.
163
+ *
164
+ * @returns The function, or null without the prop.
165
+ */
166
+ function callbackOf(attribute, name) {
167
+ if (!attribute)
168
+ return null;
169
+ const callback = attrExpr(attribute);
170
+ if (!isFn(callback)) {
171
+ throw at(aotError(`AOT: <SectionList ${name}> must be an inline function`, `${name}={({section}) => <Text>{section.title}</Text>}`), attribute);
172
+ }
173
+ return callback;
174
+ }
175
+ /**
176
+ * The names a render callback destructures its one argument into.
177
+ *
178
+ * @param callback The callback.
179
+ * @param allowed The fields it may take.
180
+ *
181
+ * @returns Each field taken, to its local name.
182
+ */
183
+ function destructured(callback, allowed) {
184
+ const names = new Map();
185
+ const parameter = callback.params[0];
186
+ if (!parameter)
187
+ return names;
188
+ const refusal = () => at(aotError(`AOT: a <SectionList> callback may destructure only ${allowed.join(' / ')} (to plain names)`, `write it as ({${allowed.join(', ')}}) => …`), parameter);
189
+ if (parameter.type !== 'ObjectPattern' || callback.params.length > 1) {
190
+ throw refusal();
191
+ }
192
+ for (const property of parameter.properties) {
193
+ if (property.type !== 'ObjectProperty' ||
194
+ property.computed ||
195
+ property.key.type !== 'Identifier' ||
196
+ property.value.type !== 'Identifier' ||
197
+ !allowed.includes(property.key.name)) {
198
+ throw refusal();
199
+ }
200
+ names.set(property.key.name, property.value.name);
201
+ }
202
+ return names;
203
+ }
204
+ /**
205
+ * A header or footer callback's body as a child: the element a block body returns, or an expression body as is.
206
+ *
207
+ * @param callback The callback.
208
+ *
209
+ * @returns The child.
210
+ */
211
+ function bodyChild(callback) {
212
+ if (callback.body.type === 'BlockStatement') {
213
+ return componentReturnJSX(callback);
214
+ }
215
+ return callback.body.type === 'JSXElement'
216
+ ? callback.body
217
+ : expressionChild(callback.body);
218
+ }
219
+ /**
220
+ * A section's rows as a child: `{rows.map((item, index) => body)}`, the renderItem's body as a `.map` callback.
221
+ *
222
+ * @param renderItem The renderItem.
223
+ * @param names The fields it destructures, to their local names.
224
+ * @param rows What the rows map over.
225
+ *
226
+ * @returns The child.
227
+ */
228
+ function rowsChild(renderItem, names, rows) {
229
+ const itemName = names.get('item');
230
+ if (!itemName) {
231
+ throw at(aotError('AOT: a <SectionList> renderItem must destructure item', 'renderItem={({item}) => …}'), renderItem);
232
+ }
233
+ const parameters = [{ type: 'Identifier', name: itemName }];
234
+ const indexName = names.get('index');
235
+ if (indexName) {
236
+ parameters.push({ type: 'Identifier', name: indexName });
237
+ }
238
+ return expressionChild({
239
+ type: 'CallExpression',
240
+ callee: {
241
+ type: 'MemberExpression',
242
+ object: rows,
243
+ property: { type: 'Identifier', name: 'map' },
244
+ computed: false,
245
+ },
246
+ arguments: [
247
+ {
248
+ type: 'ArrowFunctionExpression',
249
+ params: parameters,
250
+ body: renderItem.body,
251
+ async: false,
252
+ expression: renderItem.body.type !== 'BlockStatement',
253
+ },
254
+ ],
255
+ });
256
+ }
257
+ /**
258
+ * The sections, unrolled at build time: written in place, where each field folds and a data may be anything a
259
+ * `.map` takes, or a constant array.
260
+ *
261
+ * @param attribute The sections prop.
262
+ * @param scope Compile-time constants in reach.
263
+ * @param environment The expression environment.
264
+ *
265
+ * @returns The sections.
266
+ */
267
+ function sectionsOf(attribute, scope, environment) {
268
+ const expression = attrExpr(attribute);
269
+ if (expression.type === 'ArrayExpression') {
270
+ return expression.elements.flatMap(entry => {
271
+ if (!entry || entry.type === 'SpreadElement') {
272
+ throw at(aotError('AOT: <SectionList sections> cannot have holes or spreads', 'write each section out.'), entry ?? expression);
273
+ }
274
+ return entry.type === 'ObjectExpression'
275
+ ? [writtenSection(entry, scope, environment)]
276
+ : foldedSection(foldRuntime(entry, environment, scope), entry);
277
+ });
278
+ }
279
+ let folded;
280
+ try {
281
+ folded = evalStatic(expression, scope);
282
+ }
283
+ catch {
284
+ throw at(aotError('AOT: <SectionList sections> must fold to an array at build time', SECTIONS_HINT), attribute);
285
+ }
286
+ if (!Array.isArray(folded)) {
287
+ throw at(aotError('AOT: <SectionList sections> must be an array', SECTIONS_HINT), attribute);
288
+ }
289
+ return folded.flatMap(value => foldedSection(value, attribute));
290
+ }
291
+ /**
292
+ * A section written in place. Its data and renderItem are kept as written; every other field folds.
293
+ *
294
+ * @param object The section.
295
+ * @param scope Compile-time constants in reach.
296
+ * @param environment The expression environment.
297
+ *
298
+ * @returns The section.
299
+ */
300
+ function writtenSection(object, scope, environment) {
301
+ const section = {
302
+ value: {},
303
+ data: null,
304
+ constantData: null,
305
+ renderItem: null,
306
+ node: object,
307
+ };
308
+ for (const property of object.properties) {
309
+ if (property.type !== 'ObjectProperty' ||
310
+ property.computed ||
311
+ (property.key.type !== 'Identifier' &&
312
+ property.key.type !== 'StringLiteral')) {
313
+ throw at(aotError('AOT: a <SectionList> section must be plain fields', "write each field out: {title: 'A', data: items}."), property);
314
+ }
315
+ const key = property.key.type === 'Identifier'
316
+ ? property.key.name
317
+ : property.key.value;
318
+ const value = property.value;
319
+ if (key === 'keyExtractor')
320
+ continue;
321
+ if (key === 'renderItem') {
322
+ if (!isFn(value)) {
323
+ throw at(aotError("AOT: a <SectionList> section's renderItem must be an inline function", 'renderItem: ({item}) => <Row item={item} />'), property);
324
+ }
325
+ section.renderItem = value;
326
+ continue;
327
+ }
328
+ if (key === 'data') {
329
+ section.data = value;
330
+ // A data that folds can be read through `section` too; list state is only mapped over.
331
+ try {
332
+ const rows = foldRuntime(value, environment, scope);
333
+ if (Array.isArray(rows)) {
334
+ section.value.data = rows;
335
+ }
336
+ }
337
+ catch {
338
+ // mapped over only
339
+ }
340
+ continue;
341
+ }
342
+ section.value[key] = foldRuntime(value, environment, scope);
343
+ }
344
+ return section;
345
+ }
346
+ /**
347
+ * A section that folded. One that is not an object is skipped, as Flow A skips it.
348
+ *
349
+ * @param value The folded section.
350
+ * @param node Where it is written, for errors.
351
+ *
352
+ * @returns The section, or nothing.
353
+ */
354
+ function foldedSection(value, node) {
355
+ if (value === null || typeof value !== 'object')
356
+ return [];
357
+ const fields = value;
358
+ if (fields.data != null && !Array.isArray(fields.data)) {
359
+ throw at(aotError("AOT: a <SectionList> section's data must be an array", SECTIONS_HINT), node);
360
+ }
361
+ return [
362
+ {
363
+ value: fields,
364
+ data: null,
365
+ constantData: fields.data ?? null,
366
+ renderItem: null,
367
+ node,
368
+ },
369
+ ];
370
+ }
@@ -16,15 +16,22 @@
16
16
  /*----------------------------------------------------------------------------------------------------------------------
17
17
  - Imports
18
18
  ---------------------------------------------------------------------------------------------------------------------*/
19
- import { colorLiteral } from '../../style-map.mjs';
20
- import { aotError } from '../diagnostics.mjs';
19
+ import { parseColorValue } from '../../style-map.mjs';
20
+ import { aotError, currentLoc } from '../diagnostics.mjs';
21
21
  import { evalStatic } from '../static-eval.mjs';
22
- import { asCond, emitExpr, lowerExpr } from '../expressions.mjs';
22
+ import { lowerExpr } from '../expressions.mjs';
23
+ import { BOOL } from '../ir/types.mjs';
23
24
  import { isFn } from '../collect.mjs';
24
25
  import { attrExpr, styleWrites, collectStyleAssigns } from '../style-text.mjs';
25
26
  import { lowerValueHandler } from '../handlers.mjs';
26
27
  import { checkInterpolations, lowerRefBinds } from '../nodes.mjs';
27
28
  import { at, elementSpec } from './props.mjs';
29
+ /*----------------------------------------------------------------------------------------------------------------------
30
+ - Constants
31
+ ---------------------------------------------------------------------------------------------------------------------*/
32
+ /** A <Switch>'s size when its style sets none, as iOS draws it. */
33
+ const DEFAULT_WIDTH = 51;
34
+ const DEFAULT_HEIGHT = 31;
28
35
  /*----------------------------------------------------------------------------------------------------------------------
29
36
  - Implementation
30
37
  ---------------------------------------------------------------------------------------------------------------------*/
@@ -36,49 +43,49 @@ import { at, elementSpec } from './props.mjs';
36
43
  *
37
44
  * @param element The <Switch>.
38
45
  * @param scope Compile-time constants in reach.
39
- * @param out Everything emitted so far.
40
- * @param env The expression environment.
46
+ * @param output Everything emitted so far.
47
+ * @param environment The expression environment.
41
48
  * @param state The component's state table.
42
49
  *
43
50
  * @returns The node's variable.
44
51
  */
45
- export function emitSwitch(element, scope, out, env, state) {
52
+ export function emitSwitch(element, scope, output, environment, state) {
46
53
  // get node id
47
- const nodeId = `n${out.allocateNodeId()}`;
54
+ const nodeId = `n${output.allocateNodeId()}`;
48
55
  // collect style assignments
49
- const { staticAssigns, dynAssigns, binds } = collectStyleAssigns(element.openingElement, scope, env, elementSpec('Switch'));
50
- const hasField = (f) => styleWrites(staticAssigns, dynAssigns, f);
56
+ const { staticAssigns, dynamicAssigns, binds } = collectStyleAssigns(element.openingElement, scope, environment, elementSpec('Switch'));
57
+ const hasField = (field) => styleWrites(staticAssigns, dynamicAssigns, field);
51
58
  if (!hasField('width')) {
52
- staticAssigns.push({ field: 'width', expr: '51' });
59
+ staticAssigns.push({ field: 'width', value: DEFAULT_WIDTH });
53
60
  }
54
61
  if (!hasField('height')) {
55
- staticAssigns.push({ field: 'height', expr: '31' });
62
+ staticAssigns.push({ field: 'height', value: DEFAULT_HEIGHT });
56
63
  }
57
64
  // process element attributes
58
65
  let valueNode = null;
59
- let onChangeFn = null;
60
- for (const attr of element.openingElement.attributes) {
66
+ let onChangeFunction = null;
67
+ for (const attribute of element.openingElement.attributes) {
61
68
  // Ensure all props are explicit named attributes.
62
69
  // Spread props cannot be analyzed statically
63
- if (attr.type !== 'JSXAttribute') {
70
+ if (attribute.type !== 'JSXAttribute') {
64
71
  throw aotError('AOT: spread props on <Switch> are not supported');
65
72
  }
66
73
  // skip non-props
67
- const name = attr.name.name;
74
+ const name = attribute.name.name;
68
75
  if (name === 'style' || name === 'ref' || name === 'key')
69
76
  continue;
70
77
  // process props
71
- const node = attrExpr(attr);
78
+ const node = attrExpr(attribute);
72
79
  if (name === 'value') {
73
80
  valueNode = node;
74
81
  }
75
82
  else if (name === 'onValueChange') {
76
- onChangeFn = node;
83
+ onChangeFunction = node;
77
84
  }
78
85
  else if (name === 'thumbColor') {
79
86
  staticAssigns.push({
80
87
  field: 'thumb_color',
81
- expr: colorLiteral(String(evalStatic(node, scope))),
88
+ value: parseColorValue(String(evalStatic(node, scope))),
82
89
  });
83
90
  }
84
91
  else if (name === 'trackColor') {
@@ -86,18 +93,18 @@ export function emitSwitch(element, scope, out, env, state) {
86
93
  if (trackColor == null ||
87
94
  typeof trackColor !== 'object' ||
88
95
  Object.keys(trackColor).some(key => key !== 'false' && key !== 'true')) {
89
- throw at(aotError('AOT: <Switch trackColor> must be an object of two colors', "trackColor={{false: '#767577', true: '#81b0ff'}}"), attr);
96
+ throw at(aotError('AOT: <Switch trackColor> must be an object of two colors', "trackColor={{false: '#767577', true: '#81b0ff'}}"), attribute);
90
97
  }
91
98
  if (trackColor.false != null) {
92
99
  staticAssigns.push({
93
100
  field: 'track_color_false',
94
- expr: colorLiteral(String(trackColor.false)),
101
+ value: parseColorValue(String(trackColor.false)),
95
102
  });
96
103
  }
97
104
  if (trackColor.true != null) {
98
105
  staticAssigns.push({
99
106
  field: 'track_color_true',
100
- expr: colorLiteral(String(trackColor.true)),
107
+ value: parseColorValue(String(trackColor.true)),
101
108
  });
102
109
  }
103
110
  }
@@ -112,27 +119,27 @@ export function emitSwitch(element, scope, out, env, state) {
112
119
  }
113
120
  if (disabled !== false) {
114
121
  throw at(aotError('AOT: a disabled <Switch> is not supported', 'the engine flips a Switch on every press and has no disabled state. Leave it enabled and ' +
115
- 'ignore the change in onValueChange while it should not move.'), attr);
122
+ 'ignore the change in onValueChange while it should not move.'), attribute);
116
123
  }
117
124
  }
118
125
  else {
119
126
  throw aotError(`AOT: <Switch> prop "${name}" is not supported`, 'supported props: value, onValueChange, trackColor, thumbColor, style.');
120
127
  }
121
128
  }
122
- // value → switch_value (static or, when state-driven, recomputed in app_update).
129
+ // value → switch_value (static or, when state-driven, recomputed in the update).
123
130
  if (valueNode) {
124
131
  try {
125
132
  staticAssigns.push({
126
133
  field: 'switch_value',
127
- expr: evalStatic(valueNode, scope) ? '1' : '0',
134
+ value: evalStatic(valueNode, scope) ? 1 : 0,
128
135
  });
129
136
  }
130
137
  catch {
131
- dynAssigns.push({
138
+ dynamicAssigns.push({
132
139
  field: 'switch_value',
133
140
  value: {
134
141
  kind: 'flag',
135
- test: lowerExpr(valueNode, env),
142
+ test: lowerExpr(valueNode, environment),
136
143
  truthiness: 'condition',
137
144
  negate: false,
138
145
  whenTrue: 1,
@@ -142,9 +149,10 @@ export function emitSwitch(element, scope, out, env, state) {
142
149
  }
143
150
  const node = {
144
151
  id: nodeId,
152
+ location: currentLoc(),
145
153
  type: 'ER_NODE_SWITCH',
146
154
  constantProps: staticAssigns,
147
- stateProps: dynAssigns,
155
+ stateProps: dynamicAssigns,
148
156
  placeholder: null,
149
157
  text: null,
150
158
  image: null,
@@ -153,21 +161,21 @@ export function emitSwitch(element, scope, out, env, state) {
153
161
  wiring: binds.map((bind, index) => ({ kind: 'bind', bind, index })),
154
162
  };
155
163
  // Compile onValueChange into a press handler that receives the toggled switch value.
156
- if (onChangeFn) {
164
+ if (onChangeFunction) {
157
165
  // Require a controlled switch so onValueChange can receive the next value.
158
- if (!isFn(onChangeFn)) {
166
+ if (!isFn(onChangeFunction)) {
159
167
  throw aotError('AOT: onValueChange must be an inline function', 'onValueChange={(v) => setX(v)}');
160
168
  }
161
169
  if (!valueNode) {
162
170
  throw aotError('AOT: a <Switch> with onValueChange needs a value prop', 'controlled switch: <Switch value={on} onValueChange={(v) => setOn(v)} />');
163
171
  }
164
172
  // Compile onValueChange into an ER_EVENT_PRESS handler, passing the next switch value.
165
- const handlerName = `er_handler_${out.handlers.length}`;
166
- const toggled = `(!(${asCond(emitExpr(valueNode, env))}))`; // the engine toggles on press → param is !value
167
- out.handlers.push({
173
+ const handlerName = `handler_${output.handlers.length}`;
174
+ const value = lowerExpr(valueNode, environment);
175
+ output.handlers.push({
168
176
  kind: 'callback',
169
177
  name: handlerName,
170
- callback: lowerValueHandler(onChangeFn, toggled, env, state, out, 'int', null, true),
178
+ callback: lowerValueHandler(onChangeFunction, environment, state, output, 'int', true, { kind: 'unary', operator: '!', operand: value, type: BOOL }),
171
179
  });
172
180
  node.wiring.push({
173
181
  kind: 'event',
@@ -175,7 +183,7 @@ export function emitSwitch(element, scope, out, env, state) {
175
183
  handler: handlerName,
176
184
  });
177
185
  }
178
- for (const slot of lowerRefBinds(element.openingElement, env)) {
186
+ for (const slot of lowerRefBinds(element.openingElement, environment)) {
179
187
  node.wiring.push({ kind: 'ref', slot });
180
188
  }
181
189
  checkInterpolations(node);