embedded-react 0.12.0 → 0.14.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 (38) hide show
  1. package/README.md +222 -6
  2. package/aot/compile.mjs +3316 -364
  3. package/aot/style-map.mjs +30 -6
  4. package/assets/bake-font.mjs +104 -12
  5. package/assets/bake-svg.mjs +11 -1
  6. package/assets/build-builtin-font.mjs +6 -12
  7. package/assets/emit-c.mjs +10 -2
  8. package/assets/emit-container.mjs +4 -2
  9. package/assets/font-config.mjs +49 -0
  10. package/assets/font-sizes.mjs +652 -0
  11. package/assets/glyph-coverage.mjs +281 -0
  12. package/assets/index.mjs +29 -5
  13. package/build.mjs +11 -21
  14. package/cli.mjs +41 -3
  15. package/compile-bin.mjs +71 -0
  16. package/hotreload/pack-app.mjs +8 -21
  17. package/hotreload/pack-split.mjs +12 -27
  18. package/pack-container.mjs +10 -47
  19. package/package.json +2 -1
  20. package/sim/embedded-react.wasm +0 -0
  21. package/sim/index.html +32 -3
  22. package/sim-server.mjs +33 -27
  23. package/src/embedded-react/Animated.js +23 -9
  24. package/src/embedded-react/Button.js +98 -0
  25. package/src/embedded-react/FlatList.js +88 -0
  26. package/src/embedded-react/ImageBackground.js +67 -0
  27. package/src/embedded-react/PanResponder.js +326 -0
  28. package/src/embedded-react/SectionList.js +148 -0
  29. package/src/embedded-react/TouchableOpacity.js +152 -0
  30. package/src/embedded-react/components.js +4 -3
  31. package/src/embedded-react/index.d.ts +867 -60
  32. package/src/embedded-react/index.js +7 -2
  33. package/src/embedded-react/list-child.js +54 -0
  34. package/src/embedded-react/svg-ops.js +309 -77
  35. package/src/embedded-react/warn-props.js +80 -0
  36. package/src/host-config.js +103 -3
  37. package/src/props.js +40 -0
  38. package/src/renderer.js +31 -0
@@ -0,0 +1,326 @@
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
+ // PanResponder — the React Native analog for drags, swipes and flings.
18
+ //
19
+ // A raw `onTouchMove` carries an absolute point and nothing else, so every drag ends up re-deriving the
20
+ // same three things by hand: where the finger started, how far it has travelled, and how fast it is
21
+ // going. This module does that once. `create(config)` returns an object whose `panHandlers` you spread
22
+ // onto any component; each callback receives `(event, gestureState)` exactly as in RN:
23
+ //
24
+ // const pan = useRef(PanResponder.create({
25
+ // onStartShouldSetPanResponder: () => true,
26
+ // onPanResponderMove: (e, g) => setX(g.dx),
27
+ // onPanResponderRelease: (e, g) => (g.vx > 0.5 ? next() : settle()),
28
+ // })).current;
29
+ //
30
+ // <View {...pan.panHandlers} />
31
+ //
32
+ // The gesture rides the ENGINE's responder system (issue #115 shipped a JS-only precursor over the raw
33
+ // onTouch* events; this is the rebase). `panHandlers` is a bag of RN View responder props — the
34
+ // should-set predicates become native negotiation QUERIES (the engine calls them synchronously during
35
+ // hit-testing and the boolean answer decides who owns the gesture), and grant/move/release/terminate
36
+ // arrive as native responder events. That buys real arbitration:
37
+ //
38
+ // • A granted PanResponder OWNS the gesture: a ScrollView ancestor no longer auto-scrolls under the
39
+ // pan (auto-scroll only claims a gesture nobody owns), and it takes a slop-claimed scroll BACK the
40
+ // moment `onMoveShouldSetPanResponder` answers true.
41
+ // • Negotiation covers the subtree: the engine asks every node on the hit chain, capture phase
42
+ // root→leaf first (`*Capture` config keys), then bubble leaf→root — so a responder on a wrapper
43
+ // claims touches that land on its children, and an outer responder can pre-empt an inner one.
44
+ // • Losing a negotiation is reported (`onPanResponderReject`), and a challenger asking for the
45
+ // gesture is refusable (`onPanResponderTerminationRequest` — return false to keep it).
46
+ // • `onPanResponderTerminate` is the undo hook for whatever `onPanResponderGrant` began: the engine
47
+ // fires it when the touch sequence is cancelled, when a fresh touch-down arrives on a finger whose
48
+ // previous sequence never ended, or when this responder yields to a challenger.
49
+ //
50
+ // Remaining limits: `onShouldBlockNativeResponder` is Android-specific and stays unsupported (holding
51
+ // the responder already blocks the ScrollView; the built-in adjustable-Arc drag deliberately wins over
52
+ // JS claimants). And the engine events carry no finger id, so multiple fingers fold into ONE gesture —
53
+ // `numberActiveTouches` counts them, extra fingers fire `onPanResponderStart`/`End` (Flow A only; see
54
+ // below), and the last one to lift releases; two independent single-finger gestures need two
55
+ // responders on disjoint subtrees.
56
+ //
57
+ // Flow B compiles the same code: the AOT recognises `useRef(PanResponder.create({…})).current`
58
+ // and the `{...pan.panHandlers}` spread as a special form and lowers them onto the SAME C responder
59
+ // system this module rides — so no part of this file ships to a device that has no JS. Only
60
+ // `onPanResponderStart`/`End`, which exist here to fold extra fingers into one gesture, are Flow A only;
61
+ // the AOT names them rather than dropping them.
62
+
63
+ /** Per-instance gesture id, so two responders on screen at once are told apart. */
64
+ let s_nextStateID = 1;
65
+
66
+ /** Unsupported config keys already warned about (each unique key warns once per process). */
67
+ const s_warnedKeys = new Set();
68
+
69
+ /** Config keys this module acts on. Everything else is either RN-Android-specific or a typo. */
70
+ const SUPPORTED = [
71
+ 'onStartShouldSetPanResponder',
72
+ 'onStartShouldSetPanResponderCapture',
73
+ 'onMoveShouldSetPanResponder',
74
+ 'onMoveShouldSetPanResponderCapture',
75
+ 'onPanResponderGrant',
76
+ 'onPanResponderMove',
77
+ 'onPanResponderRelease',
78
+ 'onPanResponderTerminate',
79
+ 'onPanResponderTerminationRequest',
80
+ 'onPanResponderReject',
81
+ 'onPanResponderStart',
82
+ 'onPanResponderEnd',
83
+ ];
84
+
85
+ /**
86
+ * The engine's monotonic millisecond clock, used for velocity. `performance.now()` is installed by the
87
+ * QuickJS runtime on every context (it is React's scheduler clock) and exists in the simulator and in
88
+ * Node; `Date.now()` jumps whenever the host sets the wall clock, so it is never used here.
89
+ * The clock only advances when the host ticks, so a dt of 0 is normal and leaves velocity untouched.
90
+ */
91
+ const now = () =>
92
+ typeof performance !== 'undefined' && typeof performance.now === 'function'
93
+ ? performance.now()
94
+ : 0;
95
+
96
+ /**
97
+ * Coerces whatever was passed to a usable config object. A default parameter only covers `undefined`,
98
+ * so `create(null)` would throw on Object.keys, and a primitive would enumerate its INDICES as unknown
99
+ * keys ("ignores 0, 1, 2, 3"). Neither is a useful failure for a public API on a device.
100
+ *
101
+ * @param {*} config Whatever the caller passed.
102
+ * @returns {object} The config when it is a usable object; an empty one otherwise.
103
+ */
104
+ function asConfig(config) {
105
+ return config !== null && typeof config === 'object' ? config : {};
106
+ }
107
+
108
+ /** Warns ONCE PER KEY about config keys this module does not act on. */
109
+ function warnUnsupportedConfig(config) {
110
+ const names = Object.keys(config).filter(
111
+ k => !SUPPORTED.includes(k) && !s_warnedKeys.has(k),
112
+ );
113
+ if (names.length === 0) return;
114
+ for (const k of names) s_warnedKeys.add(k);
115
+ console.warn(
116
+ `embedded-react: PanResponder ignores ${names.join(', ')} — ` +
117
+ `supported: ${SUPPORTED.join(', ')}.`,
118
+ );
119
+ }
120
+
121
+ /**
122
+ * Clears the travel/velocity fields between gestures. `numberActiveTouches` is deliberately left alone:
123
+ * it counts fingers on the panel, which outlives the gesture when a second finger is still down.
124
+ *
125
+ * @param {object} g The gesture state to reset in place.
126
+ */
127
+ function resetGestureState(g) {
128
+ g.moveX = 0;
129
+ g.moveY = 0;
130
+ g.x0 = 0;
131
+ g.y0 = 0;
132
+ g.dx = 0;
133
+ g.dy = 0;
134
+ g.vx = 0;
135
+ g.vy = 0;
136
+ }
137
+
138
+ /**
139
+ * Builds a gesture recogniser. Call it ONCE per component and keep the result in a ref — the returned
140
+ * handlers close over one mutable gestureState, so re-creating it per render throws the drag away.
141
+ *
142
+ * @param {object} [userConfig] RN-shaped callbacks; see SUPPORTED. Every one is optional, and a
143
+ * non-object (null, a primitive) is treated as an empty config.
144
+ * @returns {{panHandlers: object}} `panHandlers` to spread onto a component.
145
+ */
146
+ export function create(userConfig = {}) {
147
+ const config = asConfig(userConfig);
148
+ warnUnsupportedConfig(config);
149
+
150
+ // The single mutable object handed to every callback — same identity for the responder's lifetime,
151
+ // as in RN, so a handler may stash it but must not expect a snapshot.
152
+ const gestureState = {
153
+ /** Identifies this responder; stable for its lifetime. */
154
+ stateID: s_nextStateID++,
155
+ /** Latest touch point. */
156
+ moveX: 0,
157
+ moveY: 0,
158
+ /** Where the gesture was granted — the anchor dx/dy are measured from. */
159
+ x0: 0,
160
+ y0: 0,
161
+ /** Travel since the grant, in pixels. */
162
+ dx: 0,
163
+ dy: 0,
164
+ /** Velocity in pixels per millisecond. */
165
+ vx: 0,
166
+ vy: 0,
167
+ /** Fingers currently on the panel (within this responder's subtree). */
168
+ numberActiveTouches: 0,
169
+ };
170
+
171
+ let granted = false;
172
+ let lastMoveTime = 0;
173
+ // The engine measures e.dx/e.dy from TOUCH-DOWN; RN (and this module) measure g.dx/g.dy from the
174
+ // GRANT — a responder that needed 10px of slop to claim starts its own travel at zero, so the slop
175
+ // never shows up as a jump. The base is what e.dx read at the moment of the grant.
176
+ let baseDx = 0;
177
+ let baseDy = 0;
178
+
179
+ const fire = (name, e) => {
180
+ if (typeof config[name] === 'function') config[name](e, gestureState);
181
+ };
182
+
183
+ /** Folds one engine payload (e.x/e.y absolute, e.dx/e.dy from touch-down) into the travel fields. */
184
+ const advance = e => {
185
+ gestureState.moveX = e.x;
186
+ gestureState.moveY = e.y;
187
+ gestureState.dx = e.dx - baseDx;
188
+ gestureState.dy = e.dy - baseDy;
189
+ };
190
+
191
+ /** A move: travel, plus a fresh velocity reading over the time since the last one. */
192
+ const track = e => {
193
+ const t = now();
194
+ const dt = t - lastMoveTime;
195
+ const prevDx = gestureState.dx;
196
+ const prevDy = gestureState.dy;
197
+
198
+ advance(e);
199
+
200
+ // dt is 0 whenever two touches land inside one host frame (the clock only moves on er_tick), and
201
+ // the division would be Infinity. Keeping the previous velocity is the honest answer: nothing new
202
+ // has been measured yet.
203
+ if (dt > 0) {
204
+ gestureState.vx = (gestureState.dx - prevDx) / dt;
205
+ gestureState.vy = (gestureState.dy - prevDy) / dt;
206
+ }
207
+ lastMoveTime = t;
208
+ };
209
+
210
+ /** Wraps a should-set predicate as an engine query: track the point, ask, absent means "no" (as in RN). */
211
+ const query = name =>
212
+ typeof config[name] === 'function'
213
+ ? e => {
214
+ if (!granted) advance(e);
215
+ return config[name](e, gestureState) === true;
216
+ }
217
+ : undefined;
218
+
219
+ /** Ends the gesture: reports it if this responder owned it, then clears the state for the next one. */
220
+ const finish = (e, callback) => {
221
+ const wasGranted = granted;
222
+ granted = false;
223
+ // Fold the final point into the travel so `dx` is the gesture's true total even when the finger
224
+ // lifted without a final move — but leave vx/vy at the last MOVE's reading. A fling ends with the
225
+ // finger resting for a frame or two, and re-measuring across that would report zero and throw the
226
+ // throw away.
227
+ advance(e);
228
+ if (wasGranted) fire(callback, e);
229
+ resetGestureState(gestureState);
230
+ baseDx = 0;
231
+ baseDy = 0;
232
+ };
233
+
234
+ const panHandlers = {
235
+ // --- Raw touch bookkeeping (bubbles per finger): finger count + Start/End for extra fingers ---
236
+ onTouchStart(e) {
237
+ gestureState.numberActiveTouches += 1;
238
+ // A later finger joins the gesture in flight (the engine events carry no finger id, so
239
+ // independent tracking is impossible). Its own touch slot re-negotiates and re-grants this
240
+ // node, and THAT grant fires onPanResponderStart — not this raw handler, which runs first.
241
+ if (gestureState.numberActiveTouches > 1) return;
242
+ resetGestureState(gestureState);
243
+ baseDx = 0;
244
+ baseDy = 0;
245
+ gestureState.x0 = e.x;
246
+ gestureState.y0 = e.y;
247
+ gestureState.moveX = e.x;
248
+ gestureState.moveY = e.y;
249
+ lastMoveTime = now();
250
+ },
251
+ onTouchEnd(e) {
252
+ if (gestureState.numberActiveTouches > 0)
253
+ gestureState.numberActiveTouches -= 1;
254
+ // A finger lifted but the gesture continues; the RELEASE for the last one arrives as a
255
+ // responder event below.
256
+ if (granted && gestureState.numberActiveTouches > 0)
257
+ fire('onPanResponderEnd', e);
258
+ },
259
+ onTouchCancel() {
260
+ gestureState.numberActiveTouches = 0;
261
+ },
262
+
263
+ // --- Negotiation queries (the engine calls these; returning true claims the gesture) ---
264
+ onStartShouldSetResponder: query('onStartShouldSetPanResponder'),
265
+ onStartShouldSetResponderCapture: query(
266
+ 'onStartShouldSetPanResponderCapture',
267
+ ),
268
+ onMoveShouldSetResponder: query('onMoveShouldSetPanResponder'),
269
+ onMoveShouldSetResponderCapture: query(
270
+ 'onMoveShouldSetPanResponderCapture',
271
+ ),
272
+ onResponderTerminationRequest:
273
+ typeof config.onPanResponderTerminationRequest === 'function'
274
+ ? e => config.onPanResponderTerminationRequest(e, gestureState) === true
275
+ : undefined, // absent → the engine's default: yield (RN's default too)
276
+
277
+ // --- Responder lifecycle (native events; fire only on the node that owns the gesture) ---
278
+ onResponderGrant(e) {
279
+ if (granted) {
280
+ // A second finger's touch slot granted the same node: one gesture, not two. RN calls this a
281
+ // responder "start" for the extra touch.
282
+ fire('onPanResponderStart', e);
283
+ return;
284
+ }
285
+ granted = true;
286
+ baseDx = e.dx;
287
+ baseDy = e.dy;
288
+ gestureState.x0 = e.x;
289
+ gestureState.y0 = e.y;
290
+ gestureState.dx = 0;
291
+ gestureState.dy = 0;
292
+ lastMoveTime = now();
293
+ fire('onPanResponderGrant', e);
294
+ },
295
+ onResponderMove(e) {
296
+ if (!granted) return;
297
+ track(e);
298
+ fire('onPanResponderMove', e);
299
+ },
300
+ onResponderRelease(e) {
301
+ if (!granted) return;
302
+ // Another finger still down: its touch slot keeps the responder, so the gesture continues (the
303
+ // raw onTouchEnd above already reported the End).
304
+ if (gestureState.numberActiveTouches > 0) return;
305
+ finish(e, 'onPanResponderRelease');
306
+ },
307
+ onResponderTerminate(e) {
308
+ if (!granted) return;
309
+ gestureState.numberActiveTouches = 0;
310
+ finish(e, 'onPanResponderTerminate');
311
+ },
312
+ onResponderReject(e) {
313
+ fire('onPanResponderReject', e);
314
+ },
315
+ };
316
+
317
+ // Absent queries must not appear as props at all (an undefined on* prop is skipped by the host
318
+ // config anyway, but a clean bag is easier to reason about and to spread).
319
+ for (const k of Object.keys(panHandlers)) {
320
+ if (panHandlers[k] === undefined) delete panHandlers[k];
321
+ }
322
+
323
+ return {panHandlers};
324
+ }
325
+
326
+ export const PanResponder = {create};
@@ -0,0 +1,148 @@
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
+ // SectionList — a thin API-compat wrapper over <ScrollView>, NOT a virtualized list. It is <FlatList>
18
+ // with a header and a footer around each group:
19
+ //
20
+ // <SectionList sections={[{title: 'A', data: ['ant']}]}
21
+ // renderSectionHeader={({section}) => <Header title={section.title} />}
22
+ // renderItem={({item}) => <Row item={item} />} />
23
+ // renders the same tree as
24
+ // <ScrollView><Header title="A" /><Row item="ant" /></ScrollView>
25
+ //
26
+ // Header, rows and footer are FLAT SIBLINGS, as in RN — no wrapper node per section — so a section
27
+ // costs exactly the nodes it draws. Nothing sticks: `stickySectionHeadersEnabled` needs a scroll
28
+ // listener re-laying the header out every frame, which is the per-event JS cost Flow A can least
29
+ // afford.
30
+ //
31
+ // Everything the FlatList section of the README says about the node budget applies here and then
32
+ // some: a section adds its header and footer on top of its rows, and every one of them mounts and
33
+ // stays mounted. Size `sections x (1 + rows) x nodes-per-row` against ERUI_MAX_NODES before writing
34
+ // the screen.
35
+ //
36
+ // Unlike <FlatList>, this has no Flow B counterpart yet — the AOT unrolls one `.map` per container
37
+ // and a section expands to a header AND a variable number of rows. It is a Flow A / simulator
38
+ // component until that lands; the AOT says so by name rather than "unknown element".
39
+ import {createElement} from 'react';
40
+ import {ScrollView} from './components.js';
41
+ import {pushKeyedChild} from './list-child.js';
42
+ import {createPropWarner, RN_PLATFORM_NO_OPS} from './warn-props.js';
43
+
44
+ /** The props this honours. The rest are virtualization / platform knobs with no meaning on a panel. */
45
+ const SUPPORTED = [
46
+ 'sections',
47
+ 'renderItem',
48
+ 'renderSectionHeader',
49
+ 'renderSectionFooter',
50
+ 'keyExtractor',
51
+ 'style',
52
+ ];
53
+
54
+ const warnUnsupportedProps = createPropWarner(
55
+ 'SectionList',
56
+ SUPPORTED,
57
+ 'it is a thin <ScrollView> alias with no virtualization and no sticky headers. For separators, ' +
58
+ 'list headers/footers or onEndReached, use <ScrollView> + .map directly.',
59
+ RN_PLATFORM_NO_OPS,
60
+ );
61
+
62
+ /**
63
+ * Renders `sections` into a <ScrollView>, each as an optional header, its rows, and an optional footer.
64
+ *
65
+ * Row keys are namespaced by section (`<section>:<row>`), because the rows of every section end up as
66
+ * siblings of one another — an index or an id that is only unique WITHIN a section would collide.
67
+ *
68
+ * @param {object} [props] Missing / empty renders an empty scroller, like a missing `sections`.
69
+ * @param {Array} [props.sections] Sections, each `{data, key?, renderItem?, keyExtractor?, ...}`.
70
+ * Anything else on a section (RN's convention is `title`) is yours, and reaches the render callbacks.
71
+ * @param {(info: {item: *, index: number, section: object}) => *} [props.renderItem] Row renderer.
72
+ * A section's own `renderItem` wins for that section, as in RN.
73
+ * @param {(info: {section: object}) => *} [props.renderSectionHeader] Rendered before a section's rows.
74
+ * @param {(info: {section: object}) => *} [props.renderSectionFooter] Rendered after a section's rows.
75
+ * @param {(item: *, index: number) => string|number} [props.keyExtractor] React key per row (a
76
+ * section's own `keyExtractor` wins); defaults to the key `renderItem` already set, else the index.
77
+ * @param {object} [props.style] Forwarded to the ScrollView untouched.
78
+ * @returns {*} A <ScrollView> holding every section's header, rows and footer as flat children.
79
+ */
80
+ export function SectionList(props = {}) {
81
+ const {
82
+ sections,
83
+ renderItem,
84
+ renderSectionHeader,
85
+ renderSectionFooter,
86
+ keyExtractor,
87
+ style,
88
+ } = props;
89
+
90
+ warnUnsupportedProps(props);
91
+
92
+ const children = [];
93
+ if (Array.isArray(sections)) {
94
+ for (let s = 0; s < sections.length; s++) {
95
+ const section = sections[s];
96
+ if (section === null || typeof section !== 'object') continue;
97
+ const sectionKey =
98
+ section.key === null || section.key === undefined
99
+ ? String(s)
100
+ : String(section.key);
101
+
102
+ if (typeof renderSectionHeader === 'function')
103
+ pushKeyedChild(
104
+ children,
105
+ renderSectionHeader({section}),
106
+ () => `${sectionKey}:$header`,
107
+ );
108
+
109
+ const rowRenderer =
110
+ typeof section.renderItem === 'function'
111
+ ? section.renderItem
112
+ : renderItem;
113
+ const rowKey =
114
+ typeof section.keyExtractor === 'function'
115
+ ? section.keyExtractor
116
+ : keyExtractor;
117
+ if (Array.isArray(section.data) && typeof rowRenderer === 'function') {
118
+ for (let index = 0; index < section.data.length; index++) {
119
+ const item = section.data[index];
120
+ const row = rowRenderer({item, index, section});
121
+ // Built lazily, so keyExtractor never runs for a row that rendered nothing or for a raw
122
+ // string — see pushKeyedChild.
123
+ pushKeyedChild(children, row, el => {
124
+ const key = rowKey
125
+ ? String(rowKey(item, index))
126
+ : el.key !== null && el.key !== undefined
127
+ ? el.key
128
+ : String(index);
129
+ return `${sectionKey}:${key}`;
130
+ });
131
+ }
132
+ }
133
+
134
+ if (typeof renderSectionFooter === 'function')
135
+ pushKeyedChild(
136
+ children,
137
+ renderSectionFooter({section}),
138
+ () => `${sectionKey}:$footer`,
139
+ );
140
+ }
141
+ }
142
+
143
+ return createElement(
144
+ ScrollView,
145
+ style === undefined ? null : {style},
146
+ children,
147
+ );
148
+ }
@@ -0,0 +1,152 @@
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
+ // TouchableOpacity — RN's press-to-dim wrapper, as a plain component over <Pressable>. No engine node
18
+ // of its own:
19
+ //
20
+ // <TouchableOpacity style={styles.tile} onPress={open}>…</TouchableOpacity>
21
+ // renders the same tree as
22
+ // <Pressable style={[styles.tile, {opacity: dim}]} onPressIn={…} onPressOut={…}>…</Pressable>
23
+ //
24
+ // The fade is a native-driver animation, not a re-render: the two press handlers hand the engine a
25
+ // target opacity and a duration, and it runs the ramp in C (er_anim_value_*). Nothing re-enters JS per
26
+ // frame, and the subtree React just built is not touched at all.
27
+ //
28
+ // Worth knowing before wrapping a whole screen in one: an opacity below 1 makes the Pressable an
29
+ // OPACITY GROUP, so the engine composites its entire subtree through an off-screen strip for as long
30
+ // as the fade lasts. That is exactly what makes the label dim with its button — but it costs in
31
+ // proportion to the dimmed area, so dim the box that reads as the button, not the page around it.
32
+ import {
33
+ createElement,
34
+ forwardRef,
35
+ useCallback,
36
+ useEffect,
37
+ useMemo,
38
+ useRef,
39
+ } from 'react';
40
+ import {Pressable} from './components.js';
41
+ import {timing, useAnimatedValue} from './Animated.js';
42
+ import {Easing} from './Easing.js';
43
+ import {flattenStyleObj} from '../props.js';
44
+
45
+ // RN's own numbers (Libraries/Components/Touchable/TouchableOpacity.js): the dim lands on touch-down
46
+ // with no ramp at all, and fades back over a quarter second once the finger lifts.
47
+ const DEFAULT_ACTIVE_OPACITY = 0.2;
48
+ const DIM_MS = 0;
49
+ const RESTORE_MS = 250;
50
+
51
+ let warnedAnimatedOpacity = false;
52
+
53
+ /** The opacity the touchable rests at — whatever its style asks for, fully opaque if it asks nothing. */
54
+ function restingOpacity(style) {
55
+ const o = flattenStyleObj(style).opacity;
56
+ if (o && o.__animated) {
57
+ if (!warnedAnimatedOpacity) {
58
+ warnedAnimatedOpacity = true;
59
+ console.warn(
60
+ 'embedded-react: <TouchableOpacity> ignores an animated `opacity` in its style — the press ' +
61
+ 'feedback owns that property. To animate opacity yourself, use <Pressable>: the dim is just ' +
62
+ 'onPressIn/onPressOut driving an Animated.Value.',
63
+ );
64
+ }
65
+ return 1;
66
+ }
67
+ return typeof o === 'number' ? o : 1;
68
+ }
69
+
70
+ /** Runs `value` to `to` over `ms` on the native driver (a 0 ms ramp snaps, without taking a slot). */
71
+ function fadeTo(value, to, ms) {
72
+ timing(value, {toValue: to, duration: ms, easing: Easing.quadInOut}).start();
73
+ }
74
+
75
+ /**
76
+ * A press target that dims while it is held.
77
+ *
78
+ * Every <Pressable> prop works here unchanged — this IS a Pressable, plus the feedback — so the two are
79
+ * interchangeable and the choice is only whether you want the dim.
80
+ *
81
+ * @param {object} props Pressable props, plus the two below.
82
+ * @param {number} [props.activeOpacity] Opacity to dim to while held. Defaults to RN's 0.2.
83
+ * @param {boolean} [props.disabled] Stops it responding to presses, and stops it dimming with them.
84
+ * @returns {*} A <Pressable> whose opacity is bound to the press animation.
85
+ */
86
+ export const TouchableOpacity = forwardRef(
87
+ function TouchableOpacity(props, ref) {
88
+ const {
89
+ activeOpacity = DEFAULT_ACTIVE_OPACITY,
90
+ disabled,
91
+ style,
92
+ onPress,
93
+ onLongPress,
94
+ onPressIn,
95
+ onPressOut,
96
+ ...rest
97
+ } = props;
98
+
99
+ // Both of these walk the style, so they are keyed to its identity rather than redone every render —
100
+ // a StyleSheet entry (or any hoisted object) makes that a pointer compare. Memoizing the composed
101
+ // array also keeps the reconciler's style diff a pointer compare instead of a deep walk.
102
+ const resting = useMemo(() => restingOpacity(style), [style]);
103
+ const opacity = useAnimatedValue(resting);
104
+ const composedStyle = useMemo(() => [style, {opacity}], [style, opacity]);
105
+
106
+ // Only read by the resting-opacity sync below: a press whose node unmounts mid-touch never sees its
107
+ // press-out, but the animated value goes with the node, so nothing has to unwind.
108
+ const pressed = useRef(false);
109
+
110
+ const handlePressIn = useCallback(
111
+ event => {
112
+ pressed.current = true;
113
+ fadeTo(opacity, activeOpacity, DIM_MS);
114
+ if (onPressIn) onPressIn(event);
115
+ },
116
+ [opacity, activeOpacity, onPressIn],
117
+ );
118
+
119
+ const handlePressOut = useCallback(
120
+ event => {
121
+ pressed.current = false;
122
+ fadeTo(opacity, resting, RESTORE_MS);
123
+ if (onPressOut) onPressOut(event);
124
+ },
125
+ [opacity, resting, onPressOut],
126
+ );
127
+
128
+ // The binding owns the node's opacity from the first commit — buildProps no longer carries it — so a
129
+ // style that CHANGES its opacity would otherwise never reach the node. Skipped while the finger is
130
+ // down: the dim owns the value until the press-out, which already restores to the latest resting one.
131
+ const synced = useRef(resting);
132
+ useEffect(() => {
133
+ if (synced.current === resting) return;
134
+ synced.current = resting;
135
+ if (!pressed.current) opacity.setValue(resting);
136
+ }, [opacity, resting]);
137
+
138
+ return createElement(Pressable, {
139
+ ...rest,
140
+ ref,
141
+ style: composedStyle,
142
+ disabled,
143
+ // `disabled` here is RN's: no press, and no feedback with it. Withholding the handlers is what
144
+ // actually does that — the engine has no such node flag, so a Pressable left holding onPress still
145
+ // fires (the same reason <Button> withholds its own).
146
+ onPress: disabled ? undefined : onPress,
147
+ onLongPress: disabled ? undefined : onLongPress,
148
+ onPressIn: disabled ? undefined : handlePressIn,
149
+ onPressOut: disabled ? undefined : handlePressOut,
150
+ });
151
+ },
152
+ );
@@ -20,14 +20,15 @@ export const View = 'View';
20
20
  export const Text = 'Text';
21
21
  export const Image = 'Image';
22
22
  export const ScrollView = 'ScrollView';
23
- export const FlatList = 'FlatList';
23
+ // FlatList is NOT a host tag — it is a component that renders a <ScrollView> with `data` mapped
24
+ // through `renderItem` (see FlatList.js). ER_NODE_FLAT_LIST exists in the engine but is byte-for-byte
25
+ // a ScrollView, so both flows emit the ScrollView node instead.
24
26
  export const Pressable = 'Pressable';
25
- // TouchableOpacity is RN's press-with-opacity wrapper; for now it maps to the same Pressable node.
26
- export const TouchableOpacity = 'Pressable';
27
27
  export const TextInput = 'TextInput';
28
28
  export const Switch = 'Switch';
29
29
  export const ActivityIndicator = 'ActivityIndicator';
30
30
  export const Modal = 'Modal';
31
+ export const Dial = 'Dial';
31
32
 
32
33
  // SVG surface. <Svg> is the only host node (→ ER_NODE_VECTOR); the shape tags below are descriptive
33
34
  // children that the host config flattens into the Svg node's op-tape (they are never mounted on their