@scalebun/react-native 2.0.0 → 2.0.2

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 (70) hide show
  1. package/android/src/main/java/com/scalebun/rn/ota/BundleDownloader.kt +10 -0
  2. package/android/src/main/java/com/scalebun/rn/ota/DeviceIntegrity.kt +75 -0
  3. package/android/src/main/java/com/scalebun/rn/ota/ScaleBunOtaModule.kt +18 -3
  4. package/android/src/main/java/com/scalebun/rn/ota/SlotManager.kt +62 -1
  5. package/android/src/main/java/com/scalebun/rn/ota/TlsPinning.kt +118 -0
  6. package/android/src/oldarch/java/com/scalebun/rn/ota/ScaleBunOtaSpec.kt +2 -0
  7. package/dist/scalebun.full.js +840 -114
  8. package/dist/scalebun.slim.js +838 -112
  9. package/ios/ReplaySdk.swift +65 -2
  10. package/lib/commonjs/bootstrap/SDKBootstrapper.js +30 -0
  11. package/lib/commonjs/core/config/schema.js +16 -0
  12. package/lib/commonjs/core/constants/version.js +1 -1
  13. package/lib/commonjs/features/journey/ScaleBunDebugRoot.js +293 -5
  14. package/lib/commonjs/features/journey/ScaleBunScrollView.js +28 -0
  15. package/lib/commonjs/features/journey/autoInstrumentScroll.js +161 -0
  16. package/lib/commonjs/features/journey/interactionProtocol.js +131 -10
  17. package/lib/commonjs/features/journey/scrollContext.js +146 -0
  18. package/lib/commonjs/features/journey/targetGeometry.js +164 -0
  19. package/lib/commonjs/features/journey/touchTarget.js +152 -24
  20. package/lib/commonjs/features/journey/uiState.js +81 -1
  21. package/lib/commonjs/features/navigation/AutoScreenDetector.js +74 -5
  22. package/lib/commonjs/features/ota/OtaOrchestrator.js +69 -22
  23. package/lib/commonjs/features/session/SessionManager.js +63 -0
  24. package/lib/commonjs/public/ScaleBunFacade.js +18 -16
  25. package/lib/module/bootstrap/SDKBootstrapper.js +30 -0
  26. package/lib/module/core/config/schema.js +16 -0
  27. package/lib/module/core/constants/version.js +1 -1
  28. package/lib/module/features/journey/ScaleBunDebugRoot.js +295 -7
  29. package/lib/module/features/journey/ScaleBunScrollView.js +28 -0
  30. package/lib/module/features/journey/autoInstrumentScroll.js +155 -0
  31. package/lib/module/features/journey/interactionProtocol.js +128 -8
  32. package/lib/module/features/journey/scrollContext.js +135 -0
  33. package/lib/module/features/journey/targetGeometry.js +155 -0
  34. package/lib/module/features/journey/touchTarget.js +151 -24
  35. package/lib/module/features/journey/uiState.js +78 -1
  36. package/lib/module/features/navigation/AutoScreenDetector.js +74 -5
  37. package/lib/module/features/ota/OtaOrchestrator.js +69 -22
  38. package/lib/module/features/session/SessionManager.js +63 -0
  39. package/lib/module/public/ScaleBunFacade.js +18 -16
  40. package/lib/typescript/core/config/schema.d.ts +2 -0
  41. package/lib/typescript/core/constants/version.d.ts +1 -1
  42. package/lib/typescript/features/journey/autoInstrumentScroll.d.ts +46 -0
  43. package/lib/typescript/features/journey/interactionProtocol.d.ts +139 -1
  44. package/lib/typescript/features/journey/scrollContext.d.ts +85 -0
  45. package/lib/typescript/features/journey/targetGeometry.d.ts +114 -0
  46. package/lib/typescript/features/journey/touchTarget.d.ts +148 -15
  47. package/lib/typescript/features/journey/uiState.d.ts +39 -0
  48. package/lib/typescript/features/navigation/AutoScreenDetector.d.ts +48 -2
  49. package/lib/typescript/features/ota/OtaOrchestrator.d.ts +7 -0
  50. package/lib/typescript/features/session/SessionManager.d.ts +55 -0
  51. package/lib/typescript/public/types.d.ts +10 -0
  52. package/lib/typescript/specs/NativeScaleBunOta.d.ts +2 -0
  53. package/package.json +2 -2
  54. package/src/bootstrap/SDKBootstrapper.ts +40 -0
  55. package/src/core/config/schema.ts +18 -0
  56. package/src/core/constants/version.ts +1 -1
  57. package/src/features/journey/ScaleBunDebugRoot.tsx +288 -7
  58. package/src/features/journey/ScaleBunScrollView.tsx +29 -0
  59. package/src/features/journey/autoInstrumentScroll.ts +155 -0
  60. package/src/features/journey/interactionProtocol.ts +188 -10
  61. package/src/features/journey/scrollContext.ts +137 -0
  62. package/src/features/journey/targetGeometry.ts +176 -0
  63. package/src/features/journey/touchTarget.ts +237 -26
  64. package/src/features/journey/uiState.ts +80 -1
  65. package/src/features/navigation/AutoScreenDetector.ts +65 -5
  66. package/src/features/ota/OtaOrchestrator.ts +76 -22
  67. package/src/features/session/SessionManager.ts +113 -0
  68. package/src/public/ScaleBunFacade.ts +18 -16
  69. package/src/public/types.ts +10 -0
  70. package/src/specs/NativeScaleBunOta.ts +3 -0
@@ -14,7 +14,52 @@ export interface InteractionStartContext {
14
14
  y: number;
15
15
  target?: string;
16
16
  targetId?: string;
17
+ /**
18
+ * WHICH kind of identity `targetId` is: an authored `testID`, a structural component path, or
19
+ * a bare component name.
20
+ *
21
+ * Carried because they are not equally trustworthy — a testID is a promise from the app's
22
+ * authors, a path is an inference that breaks when the tree is refactored — and a consumer
23
+ * that cannot tell them apart renders a refactor-fragile guess as a confident target.
24
+ */
25
+ targetSource?: 'testID' | 'path' | 'component' | 'none';
17
26
  screenName?: string;
27
+ /** RN-8: where `screenName` came from, so low coverage is diagnosable rather than merely visible. */
28
+ screenSource?: 'manual' | 'navigation' | 'none';
29
+ /**
30
+ * RN-13: the target control's rectangle as fractions of the capture base, or undefined when it
31
+ * could not be measured synchronously. Comparable to the tap's own normalized point, which is
32
+ * what makes 'heat is on this control' checkable rather than assumed.
33
+ */
34
+ targetRect?: { x: number; y: number; width: number; height: number };
35
+ /**
36
+ * RN-3: the content offset of the nearest ancestor scroller at finger-down, so two taps at the
37
+ * same screen coordinate one viewport apart do not merge. Absent when no ancestor reported one
38
+ * — never defaulted to 0, which is a real scroll position (the top of a list).
39
+ */
40
+ scrollX?: number;
41
+ scrollY?: number;
42
+ /** Whether a scroll offset was available at all. 'none' means no wrapped scroller was an ancestor. */
43
+ scrollSource?: 'wrapper' | 'none';
44
+ /**
45
+ * RN-4: the list row's key, taken from the app's own `keyExtractor` via the cell's `cellKey`
46
+ * prop. Distinguishes two taps that share a RECYCLED native view — the same slot showing a
47
+ * different row after scrolling — which would otherwise merge into one hotspot.
48
+ */
49
+ itemKey?: string;
50
+ /** The row's index at render time. Same index + different key = a recycled slot. */
51
+ itemIndex?: number;
52
+ /**
53
+ * RN-15: the tap's position INSIDE the target control — (0,0) its top-left, (1,1) its
54
+ * bottom-right. Resolution-independent, so one control is one distribution across every device
55
+ * size rather than a separate cloud of heat per screen width.
56
+ *
57
+ * NOT clamped. A value outside 0..1 means the tap landed outside the control's visual box and
58
+ * was still attributed to it, which is what `hitSlop` does — and a control whose taps cluster
59
+ * outside its own bounds is drawn too small, which is a finding rather than noise.
60
+ */
61
+ localU?: number;
62
+ localV?: number;
18
63
  ui?: string;
19
64
  stateStatus: InteractionStateStatus;
20
65
  emitAutomaticAnalytics: boolean;
@@ -24,22 +69,155 @@ export function generateInteractionId(): string {
24
69
  return `ixj-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
25
70
  }
26
71
 
72
+ /**
73
+ * RN-6 — THE CORRELATION CONTRACT.
74
+ *
75
+ * WHAT IS BEING JOINED, AND WHY IT IS HARD. A physical tap is observed twice: natively, by
76
+ * a window callback that sees ACTION_DOWN/UP and produces the coordinates; and in JS, by a
77
+ * capture-phase touch handler that produces the IDENTITY — which control was hit, what UI
78
+ * state was declared, which screen. Both sides mint their own id and neither can derive
79
+ * the other's: native builds `ixn-a-<process nonce>-<MotionEvent ts>` from a clock JS
80
+ * cannot read, and JS builds `ixj-<Date.now()>-<random>`. So the two observations have to
81
+ * be JOINED, and the only shared quantity is time.
82
+ *
83
+ * WHY THE OLD JOIN WAS DANGEROUS RATHER THAN MERELY APPROXIMATE. It took whichever start
84
+ * was nearest in time within ±1500 ms and used it unconditionally. The fields it carries
85
+ * across are `target`, `targetId`, `ui`, `stateStatus` and `screenName`; the coordinates
86
+ * come from the native side and are always right. So a wrong pairing does not produce
87
+ * obviously broken data — it produces heat in the CORRECT position attributed to the
88
+ * WRONG control, in the wrong UI state, on the wrong screen. Nothing downstream can
89
+ * detect that, because every field is individually well-formed.
90
+ *
91
+ * 1500 ms is a very long time on a touch surface. A deliberate double-tap is 150–300 ms
92
+ * apart; an impatient tapper is faster. So "nearest within 1500 ms" routinely had more
93
+ * than one candidate, and picked one with no record that it had a choice.
94
+ *
95
+ * WHAT THIS REPLACES IT WITH — three outcomes instead of one, and a refusal:
96
+ *
97
+ * 'exact' one candidate is clearly closest: the runner-up is at least
98
+ * `marginMs` further away. The join is used.
99
+ * 'ambiguous' two candidates are within `marginMs` of each other, so choosing
100
+ * between them is a coin flip. The join is REFUSED and the caller must
101
+ * emit the interaction WITHOUT js-derived identity. A tap with no target
102
+ * is honest and visibly incomplete; a tap with the wrong target is
103
+ * indistinguishable from a correct one and corrupts every aggregate it
104
+ * enters.
105
+ * 'none' nothing within tolerance. Same refusal, different reason — worth
106
+ * separating because 'none' means the JS handler never fired (a real
107
+ * capture gap) while 'ambiguous' means it fired too often to attribute.
108
+ *
109
+ * It also reports `deltaMs` and `runnerUpDeltaMs` so the outcome is auditable after the
110
+ * fact rather than being a claim this comment makes.
111
+ *
112
+ * WHAT IT DELIBERATELY DOES NOT DO: use position to disambiguate. The native event carries
113
+ * raw px in the capture view and normalized 0..1 coordinates; the JS start carries its own
114
+ * x/y in a different space (dp in the root view). Comparing them needs a proven scale
115
+ * factor between the two, and getting it wrong would REJECT valid pairings — strictly
116
+ * worse than today. That calibration needs a device run, so it is a follow-up, not a
117
+ * guess made here.
118
+ */
119
+ export type CorrelationOutcome = 'exact' | 'ambiguous' | 'none';
120
+
121
+ export interface CorrelationResult<T> {
122
+ /** Present only when `outcome` is 'exact'. Never a best-guess. */
123
+ start?: T;
124
+ /** Index into the input array, so the caller can consume it. -1 unless 'exact'. */
125
+ index: number;
126
+ outcome: CorrelationOutcome;
127
+ /** Distance to the chosen (or best rejected) candidate; null when there was none. */
128
+ deltaMs: number | null;
129
+ /** Distance to the second candidate — what makes 'ambiguous' auditable. */
130
+ runnerUpDeltaMs: number | null;
131
+ }
132
+
133
+ /**
134
+ * How far apart a native event and a JS start may be and still be the same touch.
135
+ *
136
+ * Unchanged at 1500 ms from the previous implementation, deliberately: narrowing it is a
137
+ * separate, measurable decision about how late the JS handler can run on a slow device,
138
+ * and bundling it into this change would make any regression impossible to attribute.
139
+ */
140
+ export const CORRELATION_TOLERANCE_MS = 1500;
141
+
142
+ /**
143
+ * How much closer the winner must be than the runner-up to count as identified.
144
+ *
145
+ * 100 ms because that is comfortably below the fastest deliberate double-tap (~150 ms):
146
+ * when two candidate starts are within 100 ms of each other in distance, the native event
147
+ * sits effectively between them and the "nearest" one is a coin flip.
148
+ */
149
+ export const CORRELATION_MARGIN_MS = 100;
150
+
27
151
  /** Match a native bridge event to the JS evidence sampled at the same finger-down. */
28
- export function nearestInteractionStart<T extends InteractionStartContext>(
152
+ export function correlateInteraction<T extends InteractionStartContext>(
29
153
  starts: readonly T[],
30
154
  occurredAt: number,
31
- toleranceMs = 1500,
32
- ): T | undefined {
33
- let best: T | undefined;
34
- let bestDelta = toleranceMs + 1;
35
- for (const start of starts) {
155
+ toleranceMs = CORRELATION_TOLERANCE_MS,
156
+ marginMs = CORRELATION_MARGIN_MS,
157
+ ): CorrelationResult<T> {
158
+ const candidates: Array<{ index: number; delta: number }> = [];
159
+ for (let i = 0; i < starts.length; i++) {
160
+ const start = starts[i];
161
+ if (!start) continue;
36
162
  const delta = Math.abs(start.occurredAt - occurredAt);
37
- if (delta < bestDelta) {
38
- best = start;
39
- bestDelta = delta;
163
+ if (delta <= toleranceMs) candidates.push({ index: i, delta });
164
+ }
165
+
166
+ if (candidates.length === 0) {
167
+ return { index: -1, outcome: 'none', deltaMs: null, runnerUpDeltaMs: null };
168
+ }
169
+
170
+ /* Stable ordering: equal deltas resolve by index so a repeated run cannot produce a
171
+ different answer from the same inputs. A non-deterministic correlation would make
172
+ every downstream measurement unreproducible. */
173
+ candidates.sort((a, b) => (a.delta - b.delta) || (a.index - b.index));
174
+ const best = candidates[0]!;
175
+ const runnerUp = candidates[1];
176
+
177
+ if (runnerUp && runnerUp.delta - best.delta < marginMs) {
178
+ return {
179
+ index: -1,
180
+ outcome: 'ambiguous',
181
+ deltaMs: best.delta,
182
+ runnerUpDeltaMs: runnerUp.delta,
183
+ };
184
+ }
185
+
186
+ return {
187
+ start: starts[best.index],
188
+ index: best.index,
189
+ outcome: 'exact',
190
+ deltaMs: best.delta,
191
+ runnerUpDeltaMs: runnerUp ? runnerUp.delta : null,
192
+ };
193
+ }
194
+
195
+ /**
196
+ * Drop starts that can no longer match anything, in place.
197
+ *
198
+ * WHY IT MATTERS BEYOND MEMORY. A start older than the tolerance is unreachable, but while
199
+ * it sits in the list it is still a CANDIDATE for the ambiguity test — so a stale entry can
200
+ * turn a perfectly clear pairing into a refusal, and an accumulating list makes that more
201
+ * likely the longer a session runs. Pruning is therefore part of the correctness of the
202
+ * join, not housekeeping.
203
+ *
204
+ * Mutates rather than returning a copy because the caller holds it in a ref that the native
205
+ * listener and the touch handler both read.
206
+ */
207
+ export function pruneInteractionStarts<T extends InteractionStartContext>(
208
+ starts: T[],
209
+ now: number,
210
+ toleranceMs = CORRELATION_TOLERANCE_MS,
211
+ ): number {
212
+ let removed = 0;
213
+ for (let i = starts.length - 1; i >= 0; i--) {
214
+ const start = starts[i];
215
+ if (!start || now - start.occurredAt > toleranceMs) {
216
+ starts.splice(i, 1);
217
+ removed++;
40
218
  }
41
219
  }
42
- return bestDelta <= toleranceMs ? best : undefined;
220
+ return removed;
43
221
  }
44
222
 
45
223
  /** Analytics is a projection of the same evidence; no second click is invented. */
@@ -0,0 +1,137 @@
1
+ /**
2
+ * RN-3 — WHERE IN THE CONTENT A TAP HAPPENED, not just where on the glass.
3
+ *
4
+ * THE DEFECT. A tap carries screen coordinates. Two taps at the SAME screen coordinate, one
5
+ * viewport apart in a scrolling list, are two different controls — and with no scroll offset they
6
+ * are indistinguishable, so they merge into one hotspot. The heatmap then shows heavy engagement
7
+ * at a position where, in content terms, nothing in particular is.
8
+ *
9
+ * That is not a rendering nicety. Scroll offset is a PLACEMENT dimension (which content was under
10
+ * the finger) and a CACHE dimension (two states of one route that must not share a backdrop), so
11
+ * its absence corrupts both the aggregate and the picture drawn beneath it.
12
+ *
13
+ * WHY A REGISTRY RATHER THAN A SINGLE NUMBER. `ScrollTracker` already accumulates
14
+ * `previousOffsetX/Y`, but as ONE global pair with no idea which scroller moved. A screen with a
15
+ * vertical list containing a horizontal carousel has two scrollers, and whichever fired last
16
+ * overwrites the other — so the vertical position of a tap inside the carousel is whatever the
17
+ * carousel's horizontal offset happened to leave behind. A single global scrollY cannot express a
18
+ * nested scroller, and silently reports a wrong number rather than none.
19
+ *
20
+ * So offsets are keyed by the scroller's NATIVE TAG, which is the one identity both ends of this
21
+ * can see: the wrapper holds a ref to its own ScrollView, and the touch handler's fiber walk
22
+ * passes the same host instances on its way up. Matching on anything else — a name, an index, a
23
+ * generated id — would require the two sides to agree on a convention, and a convention that can
24
+ * drift is a join that can silently attach the wrong scroller's offset.
25
+ *
26
+ * WHAT THIS DELIBERATELY DOES NOT DO: guess. If no ancestor of the tapped node has a recorded
27
+ * offset, the answer is null, not zero. Zero is a real scroll position — the top of a list — and
28
+ * reporting it for "we do not know" would place every unmeasured tap at the top of its content,
29
+ * which is both wrong and indistinguishable from a genuine tap there.
30
+ *
31
+ * KNOWN LIMIT, stated because it bounds what this can deliver: offsets only arrive from
32
+ * `ScaleBunScrollView`, which an app has to opt into. A plain `<ScrollView>` reports nothing, so
33
+ * `scrollSource` is `'none'` and the tap has no content depth. Making it automatic means patching
34
+ * React Native's own exports — the SDK already does that for `@react-navigation/native` — and that
35
+ * is a decision with a much larger blast radius, not one to make silently inside a data fix.
36
+ */
37
+
38
+ export interface ScrollOffset {
39
+ x: number;
40
+ y: number;
41
+ /** When it was recorded; used only to expire entries, never reported. */
42
+ at: number;
43
+ }
44
+
45
+ /**
46
+ * How long a recorded offset stays usable.
47
+ *
48
+ * A scroller that has not moved in this long may well have been unmounted — a list on a screen the
49
+ * user left — and its stale offset must not be attached to a tap on a DIFFERENT screen that happens
50
+ * to reuse the same native tag. Tags are recycled by the platform, which makes this a correctness
51
+ * bound rather than a memory one.
52
+ *
53
+ * Five minutes is far longer than any plausible gap between scrolling a list and tapping in it,
54
+ * and far shorter than a session.
55
+ */
56
+ export const SCROLL_OFFSET_TTL_MS = 5 * 60_000;
57
+
58
+ /**
59
+ * Cap on tracked scrollers.
60
+ *
61
+ * Bounded because a long session on a virtualised screen can mount and unmount many scrollers, and
62
+ * an unbounded map is a leak that only shows up in the sessions that matter most — the long ones.
63
+ * Eviction is oldest-first, which is the entry least likely to be the one a tap needs.
64
+ */
65
+ const MAX_TRACKED_SCROLLERS = 32;
66
+
67
+ const offsets = new Map<number, ScrollOffset>();
68
+
69
+ /**
70
+ * The native tag of a host instance, across the shapes React Native has used.
71
+ *
72
+ * Fabric exposes `__nativeTag`; the old architecture used `_nativeTag`. Probing both means this
73
+ * keeps working on either architecture, and returns null rather than throwing on anything else —
74
+ * a scroll offset is never worth a crash.
75
+ */
76
+ export function nativeTagOf(node: unknown): number | null {
77
+ if (!node || typeof node !== 'object') return null;
78
+ const n = node as { __nativeTag?: unknown; _nativeTag?: unknown };
79
+ const tag = typeof n.__nativeTag === 'number' ? n.__nativeTag : n._nativeTag;
80
+ return typeof tag === 'number' && Number.isFinite(tag) ? tag : null;
81
+ }
82
+
83
+ /** Record where a scroller currently sits. Called on every scroll event of a wrapped scroller. */
84
+ export function recordScrollOffset(tag: number | null, x: number, y: number, now = Date.now()): void {
85
+ if (tag === null || !Number.isFinite(x) || !Number.isFinite(y)) return;
86
+ offsets.set(tag, { x, y, at: now });
87
+ if (offsets.size > MAX_TRACKED_SCROLLERS) {
88
+ let oldestTag: number | null = null;
89
+ let oldestAt = Infinity;
90
+ for (const [k, v] of offsets) {
91
+ if (v.at < oldestAt) {
92
+ oldestAt = v.at;
93
+ oldestTag = k;
94
+ }
95
+ }
96
+ if (oldestTag !== null) offsets.delete(oldestTag);
97
+ }
98
+ }
99
+
100
+ /**
101
+ * The offset of the NEAREST ancestor scroller that has one, given the tapped node's ancestor tags
102
+ * ordered innermost first.
103
+ *
104
+ * Nearest wins because that is the scroller the content under the finger actually moved with. A
105
+ * tap inside a horizontal carousel inside a vertical list belongs to the carousel's content
106
+ * position; attributing it to the outer list would place it by how far the PAGE had scrolled,
107
+ * which is the merge this whole module exists to prevent.
108
+ *
109
+ * Returns null when no ancestor has a recorded offset — never a zero.
110
+ */
111
+ export function nearestRecordedOffset(
112
+ ancestorTags: readonly (number | null)[],
113
+ now = Date.now(),
114
+ ): { x: number; y: number; tag: number } | null {
115
+ for (const tag of ancestorTags) {
116
+ if (tag === null) continue;
117
+ const hit = offsets.get(tag);
118
+ if (!hit) continue;
119
+ if (now - hit.at > SCROLL_OFFSET_TTL_MS) {
120
+ /* Expired: drop it so a recycled tag cannot serve a previous screen's offset. */
121
+ offsets.delete(tag);
122
+ continue;
123
+ }
124
+ return { x: hit.x, y: hit.y, tag };
125
+ }
126
+ return null;
127
+ }
128
+
129
+ /** Forget everything. Called between sessions so one recording cannot inherit another's scrollers. */
130
+ export function clearScrollOffsets(): void {
131
+ offsets.clear();
132
+ }
133
+
134
+ /** How many scrollers are currently tracked — for the leak assertion in tests. */
135
+ export function trackedScrollerCount(): number {
136
+ return offsets.size;
137
+ }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * RN-13 — THE TARGET'S RECTANGLE, without which "placed on Add to Cart" is unprovable.
3
+ *
4
+ * WHAT IS MISSING WITHOUT IT. A tap carries a point and an identity. That is enough to say "this
5
+ * tap resolved to the control named `checkout-cta`" and NOT enough to say the heat is actually ON
6
+ * that control — those are different claims, and only the second is what a heatmap draws. With no
7
+ * rect, an off-by-a-status-bar coordinate transform, a stale layout, or a mispaired identity all
8
+ * produce output that looks correct: a marker somewhere on the screen, labelled with a real
9
+ * control's name. The rect is what makes `heat ∈ target` decidable rather than assumed, which is
10
+ * why the plan moved this to P0 and ships it WITH semantic identity rather than after.
11
+ *
12
+ * WHY A SYNCHRONOUS MEASUREMENT IS THE WHOLE DESIGN CONSTRAINT. The tap handler runs synchronously
13
+ * and the interaction is emitted shortly after. React Native's classic measurement APIs
14
+ * (`measure`, `measureInWindow`) are CALLBACK-based, so a rect requested at finger-down arrives
15
+ * after the handler has returned and possibly after the event has been emitted. An implementation
16
+ * built on them would attach whichever rect happened to have resolved in time — sometimes the
17
+ * right one, sometimes the previous tap's, with no way to tell the two apart afterwards. That is
18
+ * the failure this module refuses to have.
19
+ *
20
+ * The New Architecture's host components expose `unstable_getBoundingClientRect()`, which returns
21
+ * a DOMRect SYNCHRONOUSLY. So the rect is either read in the same tick as the touch, or it is
22
+ * null. There is no third option and no best-effort.
23
+ *
24
+ * THE `unstable_` PREFIX IS LOAD-BEARING and is why every access here is a probe rather than a
25
+ * call. The method may be renamed when it stabilises, may be absent on the old architecture
26
+ * entirely, and may throw on a node that has been unmounted between the touch and the read. Each
27
+ * of those degrades to `null` — the SDK reports that it could not measure, which is a fact, rather
28
+ * than a rectangle it invented, which would be indistinguishable from a measured one.
29
+ */
30
+
31
+ /** A rectangle in the same coordinate space as `pageX`/`pageY`: the RN root view. */
32
+ export interface ElementRect {
33
+ x: number;
34
+ y: number;
35
+ width: number;
36
+ height: number;
37
+ }
38
+
39
+ /** A rectangle expressed as fractions of the capture base, directly comparable to a tap's normalized point. */
40
+ export interface NormalizedRect {
41
+ x: number;
42
+ y: number;
43
+ width: number;
44
+ height: number;
45
+ }
46
+
47
+ interface RectCapableNode {
48
+ unstable_getBoundingClientRect?: () => { x: number; y: number; width: number; height: number } | null;
49
+ getBoundingClientRect?: () => { x: number; y: number; width: number; height: number } | null;
50
+ }
51
+
52
+ /**
53
+ * Read a node's rectangle synchronously, or return null.
54
+ *
55
+ * Both spellings are probed: `unstable_getBoundingClientRect` is what React Native 0.81 ships, and
56
+ * the unprefixed name is what it becomes if the API stabilises. Probing for both means the day it
57
+ * is renamed the SDK keeps working instead of silently losing geometry — and silently is exactly
58
+ * how it would go, because a missing rect is a legitimate outcome that produces no error.
59
+ */
60
+ export function readRectSync(node: unknown): ElementRect | null {
61
+ if (!node || typeof node !== 'object') return null;
62
+ const n = node as RectCapableNode;
63
+ const fn =
64
+ typeof n.unstable_getBoundingClientRect === 'function'
65
+ ? n.unstable_getBoundingClientRect
66
+ : typeof n.getBoundingClientRect === 'function'
67
+ ? n.getBoundingClientRect
68
+ : null;
69
+ if (!fn) return null;
70
+ try {
71
+ const r = fn.call(n);
72
+ if (!r) return null;
73
+ const { x, y, width, height } = r;
74
+ /* A zero-area rect is not a measurement of a control, it is a control that is not laid out —
75
+ collapsed, unmounted mid-gesture, or measured before layout. Reporting it would put a
76
+ degenerate box into `heat ∈ target` and every containment test against it would fail in a
77
+ way that looks like a placement bug rather than a measurement gap. */
78
+ if (![x, y, width, height].every((v) => typeof v === 'number' && Number.isFinite(v))) return null;
79
+ if (width <= 0 || height <= 0) return null;
80
+ return { x, y, width, height };
81
+ } catch {
82
+ /* An unmounted node throws. Not measurable is not an error worth propagating. */
83
+ return null;
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Express a rect as fractions of the capture base, so it is comparable to the tap's normalized point.
89
+ *
90
+ * WHY THIS SHARES THE TAP'S BASE AND NOT A WINDOW SIZE. The tap is normalized against the measured
91
+ * ROOT VIEW — the exact view the screenshot captures — precisely because `Dimensions.get('window')`
92
+ * excludes system insets differently across devices and pushes markers about 10% off vertically.
93
+ * A rect normalized against a different base than the point it will be compared with produces a
94
+ * containment test that is wrong by that same offset, which would read as "the heat is just outside
95
+ * the button" on every device with a status bar. Same base, or no rect.
96
+ *
97
+ * Values are NOT clamped to 0..1. A control genuinely extending past the capture base (a row
98
+ * scrolled half off-screen) has a rect that runs past the edge, and clamping it would silently
99
+ * enlarge the containment test — turning a tap that missed the visible part of a control into a hit.
100
+ */
101
+ export function normalizeRect(rect: ElementRect | null, base: { w: number; h: number } | null): NormalizedRect | null {
102
+ if (!rect || !base || base.w <= 0 || base.h <= 0) return null;
103
+ const out = {
104
+ x: rect.x / base.w,
105
+ y: rect.y / base.h,
106
+ width: rect.width / base.w,
107
+ height: rect.height / base.h,
108
+ };
109
+ if (![out.x, out.y, out.width, out.height].every((v) => Number.isFinite(v))) return null;
110
+ return out;
111
+ }
112
+
113
+ /**
114
+ * WHERE IN THE CONTROL the tap landed — RN-15.
115
+ *
116
+ * `u` and `v` are the tap's position as fractions of the target's own box: (0,0) is its top-left,
117
+ * (1,1) its bottom-right, (0.5,0.5) dead centre. This is what turns "they tapped Add to Cart" into
118
+ * "they tapped the left edge of Add to Cart", which is the difference between knowing a control is
119
+ * used and knowing whether its hit area is right.
120
+ *
121
+ * RESOLUTION-INDEPENDENT BY CONSTRUCTION, which is the point on mobile. A screen-space heatmap
122
+ * aggregates a control differently on every device size, so a button that sits at 40% width on a
123
+ * phone and 25% on a tablet produces two clouds of heat that never combine. Local coordinates are
124
+ * the same numbers on both, so one control is one distribution regardless of what it is rendered on.
125
+ *
126
+ * DELIBERATELY NOT CLAMPED, and this is the interesting part rather than an oversight. A value
127
+ * outside 0..1 means the tap landed OUTSIDE the control's visual box and was still attributed to
128
+ * it — which is exactly what `hitSlop` does, and it is real: `hitSlop={24}` makes a control
129
+ * respond to touches two dozen points beyond its own edge. Clamping would erase the one signal
130
+ * that distinguishes "tapped the button" from "tapped near the button and the button took it",
131
+ * and that distinction is a design finding: a control whose taps cluster outside its own bounds is
132
+ * drawn too small.
133
+ *
134
+ * Returns null, not a centre, when either input is missing. A fabricated (0.5, 0.5) would sit in
135
+ * the middle of every distribution and look exactly like a deliberate central tap.
136
+ */
137
+ export function localPoint(
138
+ rect: NormalizedRect | null,
139
+ nx: number | null | undefined,
140
+ ny: number | null | undefined,
141
+ ): { u: number; v: number } | null {
142
+ if (!rect || rect.width <= 0 || rect.height <= 0) return null;
143
+ if (typeof nx !== 'number' || typeof ny !== 'number') return null;
144
+ if (!Number.isFinite(nx) || !Number.isFinite(ny)) return null;
145
+ return {
146
+ u: (nx - rect.x) / rect.width,
147
+ v: (ny - rect.y) / rect.height,
148
+ };
149
+ }
150
+
151
+ /**
152
+ * Is the tap's normalized point inside the target's normalized rect?
153
+ *
154
+ * THE PREDICATE THE WHOLE MODULE EXISTS FOR. A heatmap that draws a marker labelled with a
155
+ * control's name is asserting this, and until now nothing checked it.
156
+ *
157
+ * Edges are INCLUSIVE. A tap on a button's exact border is a tap on the button — exclusive edges
158
+ * would report a sliver of every control as a miss, and at the resolution these coordinates carry
159
+ * that sliver is not a real distinction.
160
+ *
161
+ * Returns null, not false, when either input is missing. "The point is outside the control" and
162
+ * "we could not measure the control" are different findings with different fixes, and collapsing
163
+ * them into `false` would make an unmeasurable control look like a placement failure.
164
+ */
165
+ export function containsNormalizedPoint(
166
+ rect: NormalizedRect | null,
167
+ nx: number | null | undefined,
168
+ ny: number | null | undefined,
169
+ ): boolean | null {
170
+ if (!rect) return null;
171
+ if (typeof nx !== 'number' || typeof ny !== 'number') return null;
172
+ if (!Number.isFinite(nx) || !Number.isFinite(ny)) return null;
173
+ return (
174
+ nx >= rect.x && nx <= rect.x + rect.width && ny >= rect.y && ny <= rect.y + rect.height
175
+ );
176
+ }