@oxyhq/bloom 0.78.0 → 0.79.1

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 (105) hide show
  1. package/README.md +3 -3
  2. package/lib/commonjs/provider/index.js +11 -7
  3. package/lib/commonjs/provider/index.js.map +1 -1
  4. package/lib/commonjs/scroll/context.js +96 -0
  5. package/lib/commonjs/scroll/context.js.map +1 -0
  6. package/lib/commonjs/scroll/expo-router/index.js +133 -0
  7. package/lib/commonjs/scroll/expo-router/index.js.map +1 -0
  8. package/lib/commonjs/scroll/index.js +85 -21
  9. package/lib/commonjs/scroll/index.js.map +1 -1
  10. package/lib/commonjs/scroll/index.web.js +184 -118
  11. package/lib/commonjs/scroll/index.web.js.map +1 -1
  12. package/lib/commonjs/scroll/scrollable.native.js +58 -0
  13. package/lib/commonjs/scroll/scrollable.native.js.map +1 -0
  14. package/lib/commonjs/scroll/store.js +47 -25
  15. package/lib/commonjs/scroll/store.js.map +1 -1
  16. package/lib/commonjs/theme/color-policy.js +11 -9
  17. package/lib/commonjs/theme/color-policy.js.map +1 -1
  18. package/lib/module/provider/index.js +10 -6
  19. package/lib/module/provider/index.js.map +1 -1
  20. package/lib/module/scroll/context.js +90 -0
  21. package/lib/module/scroll/context.js.map +1 -0
  22. package/lib/module/scroll/expo-router/index.js +128 -0
  23. package/lib/module/scroll/expo-router/index.js.map +1 -0
  24. package/lib/module/scroll/index.js +80 -21
  25. package/lib/module/scroll/index.js.map +1 -1
  26. package/lib/module/scroll/index.web.js +181 -119
  27. package/lib/module/scroll/index.web.js.map +1 -1
  28. package/lib/module/scroll/scrollable.native.js +54 -0
  29. package/lib/module/scroll/scrollable.native.js.map +1 -0
  30. package/lib/module/scroll/store.js +47 -25
  31. package/lib/module/scroll/store.js.map +1 -1
  32. package/lib/module/theme/color-policy.js +11 -9
  33. package/lib/module/theme/color-policy.js.map +1 -1
  34. package/lib/typescript/commonjs/provider/index.d.ts +7 -5
  35. package/lib/typescript/commonjs/provider/index.d.ts.map +1 -1
  36. package/lib/typescript/commonjs/scroll/context.d.ts +14 -0
  37. package/lib/typescript/commonjs/scroll/context.d.ts.map +1 -0
  38. package/lib/typescript/commonjs/scroll/expo-router/index.d.ts +7 -0
  39. package/lib/typescript/commonjs/scroll/expo-router/index.d.ts.map +1 -0
  40. package/lib/typescript/commonjs/scroll/index.d.ts +14 -23
  41. package/lib/typescript/commonjs/scroll/index.d.ts.map +1 -1
  42. package/lib/typescript/commonjs/scroll/index.web.d.ts +17 -19
  43. package/lib/typescript/commonjs/scroll/index.web.d.ts.map +1 -1
  44. package/lib/typescript/commonjs/scroll/scrollable.native.d.ts +23 -0
  45. package/lib/typescript/commonjs/scroll/scrollable.native.d.ts.map +1 -0
  46. package/lib/typescript/commonjs/scroll/store.d.ts +41 -22
  47. package/lib/typescript/commonjs/scroll/store.d.ts.map +1 -1
  48. package/lib/typescript/commonjs/scroll/types.d.ts +82 -12
  49. package/lib/typescript/commonjs/scroll/types.d.ts.map +1 -1
  50. package/lib/typescript/commonjs/theme/color-policy.d.ts.map +1 -1
  51. package/lib/typescript/module/provider/index.d.ts +7 -5
  52. package/lib/typescript/module/provider/index.d.ts.map +1 -1
  53. package/lib/typescript/module/scroll/context.d.ts +14 -0
  54. package/lib/typescript/module/scroll/context.d.ts.map +1 -0
  55. package/lib/typescript/module/scroll/expo-router/index.d.ts +7 -0
  56. package/lib/typescript/module/scroll/expo-router/index.d.ts.map +1 -0
  57. package/lib/typescript/module/scroll/index.d.ts +14 -23
  58. package/lib/typescript/module/scroll/index.d.ts.map +1 -1
  59. package/lib/typescript/module/scroll/index.web.d.ts +17 -19
  60. package/lib/typescript/module/scroll/index.web.d.ts.map +1 -1
  61. package/lib/typescript/module/scroll/scrollable.native.d.ts +23 -0
  62. package/lib/typescript/module/scroll/scrollable.native.d.ts.map +1 -0
  63. package/lib/typescript/module/scroll/store.d.ts +41 -22
  64. package/lib/typescript/module/scroll/store.d.ts.map +1 -1
  65. package/lib/typescript/module/scroll/types.d.ts +82 -12
  66. package/lib/typescript/module/scroll/types.d.ts.map +1 -1
  67. package/lib/typescript/module/theme/color-policy.d.ts.map +1 -1
  68. package/package.json +15 -1
  69. package/src/__tests__/BloomProvider.web.test.tsx +8 -15
  70. package/src/__tests__/optional-peer-imports.test.ts +2 -2
  71. package/src/__tests__/scroll-expo-router-adapter.test.tsx +164 -0
  72. package/src/__tests__/scroll-native.test.tsx +465 -0
  73. package/src/__tests__/scroll-store.test.ts +41 -17
  74. package/src/__tests__/scroll-web.test.tsx +547 -111
  75. package/src/provider/index.tsx +10 -7
  76. package/src/scroll/context.tsx +107 -0
  77. package/src/scroll/expo-router/index.ts +140 -0
  78. package/src/scroll/index.ts +92 -25
  79. package/src/scroll/index.web.tsx +219 -162
  80. package/src/scroll/scrollable.native.ts +64 -0
  81. package/src/scroll/store.ts +47 -25
  82. package/src/scroll/types.ts +82 -12
  83. package/src/theme/__tests__/__fixtures__/golden-resolved-tokens.json +27 -27
  84. package/src/theme/__tests__/__snapshots__/visual-gallery.test.tsx.snap +55 -55
  85. package/src/theme/__tests__/policy-legibility.test.ts +21 -1
  86. package/src/theme/color-policy.ts +13 -9
  87. package/lib/commonjs/provider/scroll-provider.js +0 -13
  88. package/lib/commonjs/provider/scroll-provider.js.map +0 -1
  89. package/lib/commonjs/provider/scroll-provider.web.js +0 -13
  90. package/lib/commonjs/provider/scroll-provider.web.js.map +0 -1
  91. package/lib/module/provider/scroll-provider.js +0 -16
  92. package/lib/module/provider/scroll-provider.js.map +0 -1
  93. package/lib/module/provider/scroll-provider.web.js +0 -5
  94. package/lib/module/provider/scroll-provider.web.js.map +0 -1
  95. package/lib/typescript/commonjs/provider/scroll-provider.d.ts +0 -14
  96. package/lib/typescript/commonjs/provider/scroll-provider.d.ts.map +0 -1
  97. package/lib/typescript/commonjs/provider/scroll-provider.web.d.ts +0 -3
  98. package/lib/typescript/commonjs/provider/scroll-provider.web.d.ts.map +0 -1
  99. package/lib/typescript/module/provider/scroll-provider.d.ts +0 -14
  100. package/lib/typescript/module/provider/scroll-provider.d.ts.map +0 -1
  101. package/lib/typescript/module/provider/scroll-provider.web.d.ts +0 -3
  102. package/lib/typescript/module/provider/scroll-provider.web.d.ts.map +0 -1
  103. package/src/__tests__/scroll-native.test.ts +0 -25
  104. package/src/provider/scroll-provider.ts +0 -13
  105. package/src/provider/scroll-provider.web.ts +0 -2
@@ -1,22 +1,22 @@
1
1
  /**
2
2
  * Web variant of the scroll-restoration primitive.
3
3
  *
4
- * Mirrors the proven Bluesky pattern (`history.scrollRestoration = 'manual'`
5
- * plus an in-memory `Map<routeKey, offset>`) with two deliberate differences
6
- * forced by Oxy's layouts and the behaviour of the (expo-router-wrapped)
7
- * React Navigation web stack:
4
+ * Mirrors the proven Bluesky pattern (manual `history.scrollRestoration` plus
5
+ * an in-memory `Map<key, offset>`) with three deliberate differences forced by
6
+ * Oxy's layouts and by the behaviour of the (expo-router-wrapped) React
7
+ * Navigation web stack:
8
8
  *
9
9
  * 1. Bluesky restores the WINDOW scroller, whereas Oxy apps keep multi-column
10
10
  * layouts whose feed scrolls an INNER container. So we restore the offset
11
11
  * of a caller-registered scrollable (a ref to an element / RN scroll
12
- * component, or the `'window'` sentinel), keyed by the active route.
12
+ * component, or the `'window'` sentinel).
13
13
  *
14
- * 2. The web stack HIDES the background screen on push. While
15
- * hidden, the previous screen's scroll container collapses
16
- * (`scrollHeight === clientHeight`) and the navigator forces its
17
- * `scrollTop` to 0. The screen is NOT unmounted, so a virtualized list
18
- * (e.g. FlashList) keeps its rows but re-lays them out over SEVERAL frames
19
- * once the screen is re-shown. Two problems follow, both handled here:
14
+ * 2. The web stack HIDES the background screen on push. While hidden, the
15
+ * previous screen's scroll container collapses (`scrollHeight ===
16
+ * clientHeight`) and the navigator forces its `scrollTop` to 0. The screen
17
+ * is NOT unmounted, so a virtualized list (e.g. FlashList) keeps its rows
18
+ * but re-lays them out over SEVERAL frames once the screen is re-shown. Two
19
+ * problems follow, both handled here:
20
20
  *
21
21
  * (a) A blur-time read of `scrollTop` returns the navigator's forced 0,
22
22
  * not the user's real offset — saving it would clobber the good
@@ -30,45 +30,44 @@
30
30
  * sticks (the content has grown tall enough) or a small frame cap is
31
31
  * reached.
32
32
  *
33
- * Native bundlers use `./index.ts` (a no-op); web bundlers select this file via
34
- * the `"browser"` export condition in `package.json`.
33
+ * 3. A document-scrolled app (one window scroller shared by every route) has
34
+ * no per-screen container to reset, so an unrecognised key MUST be written
35
+ * to 0 explicitly. Doing nothing leaves the previous screen's offset in
36
+ * place and the new screen opens mid-page.
35
37
  *
36
- * The navigation hooks are imported from `expo-router` (which re-exports
37
- * `useFocusEffect` and `useRoute` from its bundled React Navigation core) rather
38
- * than from `@react-navigation/native` directly. Every Oxy app uses expo-router
39
- * as its router, so it is always a DIRECT, top-level dependency that resolves
40
- * cleanly under Bun's isolated linker — whereas `@react-navigation/native` is
41
- * only a nested/transitive dependency of expo-router and would fail to resolve
42
- * when bundling those apps.
38
+ * Native bundlers use `./index.ts`; web bundlers select this file via the
39
+ * `"browser"` export condition in `package.json`.
43
40
  */
44
- import { createContext, useCallback, useContext, useMemo, useRef } from 'react';
45
- import { useFocusEffect, useRoute } from 'expo-router';
41
+ import { useCallback, useRef } from 'react';
46
42
 
43
+ import { useScrollRestorationContext } from './context';
47
44
  import { createScroller } from './scrollable.web';
48
- import { ScrollOffsetStore, deriveScrollKey } from './store';
45
+ import { deriveScrollKey } from './store';
49
46
  import type {
50
- ScrollRestorationProviderProps,
47
+ ScrollRestorationBinding,
51
48
  ScrollRestorationTarget,
52
49
  UseScrollRestorationOptions,
53
50
  } from './types';
54
51
 
52
+ export { ScrollRestorationProvider } from './context';
53
+
55
54
  export type {
55
+ ScreenFocusEffect,
56
56
  ScrollableHandle,
57
+ ScrollRestorationBinding,
57
58
  ScrollRestorationProviderProps,
58
59
  ScrollRestorationTarget,
60
+ ScrollRouterAdapter,
59
61
  UseScrollRestorationOptions,
60
62
  } from './types';
61
63
 
62
- const ScrollOffsetContext = createContext<ScrollOffsetStore | null>(null);
63
- ScrollOffsetContext.displayName = 'BloomScrollOffsetContext';
64
-
65
64
  /**
66
- * Maximum number of animation frames the focus restore will re-apply the saved
67
- * offset before giving up. A virtualized list re-lays out its rows over a
68
- * handful of frames after its screen is re-shown; ~30 frames (≈0.5s at 60fps)
69
- * is comfortably longer than any observed relayout while staying short enough
70
- * that the loop never lingers as a perceptible cost. The loop normally exits
71
- * far earlier — as soon as the write sticks.
65
+ * Maximum number of animation frames the restore will re-apply the saved offset
66
+ * before giving up. A virtualized list re-lays out its rows over a handful of
67
+ * frames after its screen is re-shown; ~30 frames (≈0.5s at 60fps) is
68
+ * comfortably longer than any observed relayout while staying short enough that
69
+ * the loop never lingers as a perceptible cost. The loop normally exits far
70
+ * earlier — as soon as the write sticks.
72
71
  */
73
72
  const RESTORE_FRAME_CAP = 30;
74
73
 
@@ -82,162 +81,220 @@ const RESTORE_FRAME_CAP = 30;
82
81
  const RESTORE_STICK_TOLERANCE_PX = 2;
83
82
 
84
83
  /**
85
- * Switch the browser to manual scroll restoration exactly once per document.
86
- *
87
- * The browser's default `'auto'` restoration fights our manual restore on
88
- * Back/Forward navigations. Doing this at module scope (guarded for SSR) means
89
- * it is set before any provider mounts, matching Bluesky's module-level call.
84
+ * The web binding is a constant: this platform observes offsets by subscribing
85
+ * to the resolved DOM node's own `scroll` event, so it needs nothing from the
86
+ * caller. It is still returned and still safe to spread onto a list — so a
87
+ * call site is written once and runs on both platforms.
90
88
  */
91
- if (typeof history !== 'undefined' && 'scrollRestoration' in history) {
92
- history.scrollRestoration = 'manual';
93
- }
89
+ const WEB_BINDING: ScrollRestorationBinding = { onScroll: () => undefined };
94
90
 
95
91
  /**
96
- * Holds the per-route offset map for the subtree. One provider near the app
97
- * root is enough; the store lives for the document's lifetime so offsets
98
- * survive navigating away and back (including browser Back/Forward).
92
+ * Events that mean the USER has taken over the scroller, and the restore must
93
+ * stop trying to put them back.
94
+ *
95
+ * The browser's own restoration is specified the same way: HTML §7.4.6.5 has
96
+ * the UA re-attempt the saved position and "may continue to attempt to do so
97
+ * periodically, until document's has been scrolled by the user becomes true".
98
+ * Without this the loop fights anyone who starts scrolling inside the frame
99
+ * budget, yanking them back once per frame for up to {@link RESTORE_FRAME_CAP}
100
+ * frames.
101
+ *
102
+ * Two designs were rejected, and the reasons are the point:
103
+ *
104
+ * - **"Any `scroll` event aborts"** — the obvious version, and it aborts on the
105
+ * FIRST frame every time: `setOffset` is itself a scroll, so the loop would
106
+ * cancel on the event its own write produced and no restore would ever
107
+ * complete.
108
+ * - **"Abort on an offset we did not write"** — tempting because it needs no
109
+ * listeners, but a virtualized list inserting rows ABOVE the viewport makes
110
+ * the browser's scroll anchoring move `scrollTop` on its own. That is
111
+ * precisely the situation the loop exists for, so the unexplained-delta test
112
+ * would abort exactly when it must not.
113
+ *
114
+ * What is being detected is user INPUT, so this detects user input. `pointerdown`
115
+ * covers a scrollbar drag and a touch-less press; `keydown` covers arrow/page
116
+ * keys, and reaches us whenever focus is inside the scroller it would scroll.
99
117
  */
100
- export function ScrollRestorationProvider({
101
- children,
102
- }: ScrollRestorationProviderProps) {
103
- const store = useMemo(() => new ScrollOffsetStore(), []);
104
- return (
105
- <ScrollOffsetContext.Provider value={store}>
106
- {children}
107
- </ScrollOffsetContext.Provider>
108
- );
109
- }
110
-
111
- function useScrollOffsetStore(): ScrollOffsetStore {
112
- const store = useContext(ScrollOffsetContext);
113
- if (store === null) {
114
- throw new Error(
115
- 'useScrollRestoration must be used within a <ScrollRestorationProvider>.',
116
- );
117
- }
118
- return store;
119
- }
118
+ const USER_TAKEOVER_EVENTS = ['wheel', 'touchstart', 'pointerdown', 'keydown'];
120
119
 
121
120
  /**
122
121
  * Preserve and restore the scroll offset of `target` across navigation, keyed
123
- * by the active route (plus an optional `options.key` for routes that host
124
- * multiple scrollables).
122
+ * by the content its screen is showing plus an optional `options.key`.
125
123
  *
126
124
  * Behaviour (web):
127
125
  * - On every scroll while the screen is focused, the current offset is recorded
128
- * in memory and persisted. This live stream of saves is the source of truth.
129
- * - On focus, the saved offset is re-applied across a bounded run of animation
130
- * frames, stopping as soon as the write sticks (the list has re-rendered its
131
- * rows and grown tall enough) or {@link RESTORE_FRAME_CAP} is reached. A
132
- * saved offset of 0 is a no-op (nothing to restore).
133
- * - On blur, the LAST OBSERVED offset is persisted as a final safety net — not
134
- * a fresh `scrollTop` read, which the navigator may already have forced to 0
135
- * while collapsing the hidden screen.
126
+ * under the key that was live when the listener was attached. This stream of
127
+ * saves is the source of truth.
128
+ * - On focus and again whenever the key changes while the screen STAYS
129
+ * focused, which is how an in-screen tab or folder swap is seen at all — the
130
+ * offset saved for the new key is re-applied across a bounded run of
131
+ * animation frames, stopping as soon as the write sticks or
132
+ * {@link RESTORE_FRAME_CAP} is reached. Content never seen this session is
133
+ * written to 0 once instead; a write to 0 always sticks, so it needs no loop.
134
+ * - On blur (and on a key change), the LAST OBSERVED offset is persisted under
135
+ * the OUTGOING key as a final safety net — not a fresh `scrollTop` read,
136
+ * which the navigator may already have forced to 0 while collapsing the
137
+ * hidden screen.
136
138
  */
137
139
  export function useScrollRestoration(
138
140
  target: ScrollRestorationTarget,
139
141
  options?: UseScrollRestorationOptions,
140
- ): void {
141
- const store = useScrollOffsetStore();
142
- const route = useRoute();
143
- const subKey = options?.key;
142
+ ): ScrollRestorationBinding {
143
+ const { store, adapter } = useScrollRestorationContext();
144
+ const contentId = adapter.useScreenContentId();
144
145
  const enabled = options?.enabled ?? true;
146
+ const scrollKey = deriveScrollKey(contentId, options?.key);
145
147
 
146
- const scrollKey = deriveScrollKey(route.key, subKey);
148
+ // The key this hook instance has already sent to the top. Writing 0 is a
149
+ // one-time ARRIVAL action: a later re-run for the SAME key (`enabled` turning
150
+ // on once the rows exist, a screen regaining focus) must not repeat it,
151
+ // because by then the user may have scrolled somewhere the hook never got to
152
+ // record. Restoring twice is harmless; resetting twice is data loss.
153
+ const resetKeyRef = useRef<string | null>(null);
147
154
 
148
- // Keep the latest target/enabled/key in refs so the focus effect can read
149
- // them without being re-subscribed on every render.
150
- const targetRef = useRef(target);
151
- targetRef.current = target;
152
- const enabledRef = useRef(enabled);
153
- enabledRef.current = enabled;
154
- const scrollKeyRef = useRef(scrollKey);
155
- scrollKeyRef.current = scrollKey;
155
+ adapter.useScreenFocusEffect(
156
+ // Every varying input is a dependency rather than a ref read, so the
157
+ // session below CLOSES OVER the key it belongs to. That is what makes a
158
+ // key change mid-focus correct in both directions: the outgoing session's
159
+ // cleanup persists to the old key, and the incoming one restores the new.
160
+ useCallback(() => {
161
+ if (!enabled || scrollKey === null) return undefined;
156
162
 
157
- useFocusEffect(
158
- // The effect identity is intentionally stable across renders: it reads all
159
- // varying inputs from refs. expo-router's `useFocusEffect` re-runs it on
160
- // each focus.
161
- useCallback(
162
- () => {
163
- const key = scrollKeyRef.current;
164
- if (!enabledRef.current || key === null) return undefined;
163
+ const scroller = createScroller(target);
164
+ const element =
165
+ target === 'window'
166
+ ? typeof window === 'undefined'
167
+ ? null
168
+ : window
169
+ : resolveScrollEventTarget(target);
165
170
 
166
- const scroller = createScroller(targetRef.current);
167
- const element =
168
- targetRef.current === 'window'
169
- ? (typeof window !== 'undefined' ? window : null)
170
- : resolveScrollEventTarget(targetRef.current);
171
+ // The last offset the live scroll listener observed for this session.
172
+ // This — not a cleanup-time `getOffset()` — is what we persist at the
173
+ // end, because by then the navigator may have collapsed the hidden
174
+ // screen and forced its `scrollTop` to 0 (problem A). `null` means the
175
+ // user never scrolled this session, so there is nothing newer to persist
176
+ // than what the scroll listener already saved live.
177
+ let lastObservedOffset: number | null = null;
171
178
 
172
- // The last offset the live scroll listener observed for this focus
173
- // session. This not a blur-time `getOffset()` is what we persist on
174
- // blur, because by blur time the navigator may have collapsed the
175
- // hidden screen and forced its `scrollTop` to 0 (bug A). `null` means
176
- // the user never scrolled this session, so there is nothing newer to
177
- // persist than what the scroll listener already saved live.
178
- let lastObservedOffset: number | null = null;
179
+ // The 0 WE wrote, which a real browser dispatches back as a `scroll`
180
+ // event (jsdom does not, so the test for this emits it explicitly).
181
+ // Persisting it would record an offset the user never chose, under a key
182
+ // another LIVE screen may share the two-live-entries trade content
183
+ // keying makes (see `deriveScrollKey`) means a sibling showing the same
184
+ // content can save a real offset between our write and its echo, and the
185
+ // echo would clobber it.
186
+ let echoOffset: number | null = null;
179
187
 
180
- const save = () => {
181
- const currentKey = scrollKeyRef.current;
182
- if (!enabledRef.current || currentKey === null) return;
183
- const offset = scroller.getOffset();
184
- // Ignore a spurious 0 produced by the navigator collapsing a hidden
185
- // background screen: while collapsed the container cannot scroll, so
186
- // its `scrollTop` is forced to 0. Persisting it would clobber the
187
- // good offset recorded by earlier live saves (bug A). A genuine
188
- // scroll-to-top keeps the container scrollable and is saved normally.
189
- if (offset === 0 && !scroller.canScroll()) return;
190
- lastObservedOffset = offset;
191
- store.save(currentKey, offset);
192
- };
188
+ const save = () => {
189
+ const offset = scroller.getOffset();
190
+ // Ignore a spurious 0 produced by the navigator collapsing a hidden
191
+ // background screen: while collapsed the container cannot scroll, so
192
+ // its `scrollTop` is forced to 0. Persisting it would clobber the good
193
+ // offset recorded by earlier live saves (problem A). A genuine
194
+ // scroll-to-top keeps the container scrollable and is saved normally.
195
+ if (offset === 0 && !scroller.canScroll()) return;
196
+ if (offset === echoOffset) {
197
+ // Our own write coming back. Consume the arming so a real scroll to
198
+ // the same offset later is saved normally.
199
+ echoOffset = null;
200
+ return;
201
+ }
202
+ echoOffset = null;
203
+ lastObservedOffset = offset;
204
+ store.save(scrollKey, offset);
205
+ };
193
206
 
194
- // Restore across a bounded run of frames. A freshly re-shown
195
- // virtualized list re-lays out its rows over several frames, so a
196
- // single write while it is still collapsed would be clamped to 0 and
197
- // never re-applied (bug B). We re-apply each frame until the write
198
- // sticks or the frame cap is hit.
199
- const targetOffset = store.read(key);
200
- let rafId: number | null = null;
207
+ // Restore and reset are ONE write. A miss reads 0, and 0 is exactly what
208
+ // an unseen screen must be written to left alone it would show the
209
+ // previous screen's offset, since a document-scrolled app shares one
210
+ // scroller across every route.
211
+ const targetOffset = store.read(scrollKey);
201
212
 
202
- if (targetOffset > 0 && typeof requestAnimationFrame !== 'undefined') {
203
- let framesLeft = RESTORE_FRAME_CAP;
204
- const applyOffset = () => {
205
- rafId = null;
206
- scroller.setOffset(targetOffset);
207
- framesLeft -= 1;
208
- // Stop once the write took effect (content grew tall enough) or we
209
- // exhaust the frame budget. `getOffset` re-reads the clamped value.
210
- const reached =
211
- Math.abs(scroller.getOffset() - targetOffset) <=
212
- RESTORE_STICK_TOLERANCE_PX;
213
- if (!reached && framesLeft > 0) {
214
- rafId = requestAnimationFrame(applyOffset);
215
- }
216
- };
217
- rafId = requestAnimationFrame(applyOffset);
218
- }
213
+ // They remain two DECISIONS, though, and `read` cannot tell them apart:
214
+ // a key never seen and a key deliberately saved at the top both read 0.
215
+ // Only the first is a RESET, and a reset is a one-time ARRIVAL action
216
+ // gated on `resetKeyRef` — repeating it on a later re-run for the same
217
+ // key would send a user who has since scrolled back to the top, and the
218
+ // hook was inert while they did it so there is nothing to restore them
219
+ // to afterwards. A 0 the user deliberately saved is theirs, and always
220
+ // re-applies. `has` is the only thing that answers this.
221
+ const isReset = !store.has(scrollKey);
222
+ const alreadyReset = isReset && resetKeyRef.current === scrollKey;
223
+ if (isReset) resetKeyRef.current = scrollKey;
224
+
225
+ let rafId: number | null = null;
219
226
 
220
- element?.addEventListener('scroll', save, { passive: true });
227
+ const stopRestore = () => {
228
+ if (rafId === null) return;
229
+ cancelAnimationFrame(rafId);
230
+ rafId = null;
231
+ };
221
232
 
222
- return () => {
223
- if (rafId !== null) cancelAnimationFrame(rafId);
224
- element?.removeEventListener('scroll', save);
225
- // Final capture on blur: persist the last offset the scroll listener
226
- // OBSERVED, never a fresh read (which the navigator may have forced
227
- // to 0 while collapsing the hidden screen). When the user never
228
- // scrolled this session there is nothing newer to persist than the
229
- // live saves already recorded.
230
- if (lastObservedOffset !== null) {
231
- const currentKey = scrollKeyRef.current;
232
- if (enabledRef.current && currentKey !== null) {
233
- store.save(currentKey, lastObservedOffset);
234
- }
233
+ if (alreadyReset) {
234
+ // Nothing to write: this content has already been sent to the top once
235
+ // and the user is wherever they have moved to since.
236
+ } else if (targetOffset === 0) {
237
+ // A write to 0 is never clamped away, so it needs no re-apply loop.
238
+ echoOffset = 0;
239
+ scroller.setOffset(0);
240
+ } else if (typeof requestAnimationFrame !== 'undefined') {
241
+ // Re-apply across a bounded run of frames. A freshly re-shown
242
+ // virtualized list re-lays out its rows over several frames, so a
243
+ // single write while it is still collapsed would be clamped to 0 and
244
+ // never re-applied (problem B).
245
+ //
246
+ // KNOWN PROPERTY, not a bug: each of these writes echoes back as a
247
+ // `scroll` event and IS persisted (only the reset arms `echoOffset`,
248
+ // and `canScroll()` is always true for the `'window'` sentinel so the
249
+ // collapsed-container guard never fires there). A loop that reaches
250
+ // the target self-heals on its last echo. A loop that exhausts the cap
251
+ // leaves the CLAMPED offset stored — which is the right thing to
252
+ // remember when the content genuinely shrank, since that is as far as
253
+ // the user can now scroll.
254
+ let framesLeft = RESTORE_FRAME_CAP;
255
+ const applyOffset = () => {
256
+ rafId = null;
257
+ scroller.setOffset(targetOffset);
258
+ framesLeft -= 1;
259
+ // Stop once the write took effect (content grew tall enough) or we
260
+ // exhaust the frame budget. `getOffset` re-reads the clamped value.
261
+ const reached =
262
+ Math.abs(scroller.getOffset() - targetOffset) <=
263
+ RESTORE_STICK_TOLERANCE_PX;
264
+ if (!reached && framesLeft > 0) {
265
+ rafId = requestAnimationFrame(applyOffset);
235
266
  }
236
267
  };
237
- },
238
- [store],
239
- ),
268
+ rafId = requestAnimationFrame(applyOffset);
269
+ // Only while a loop is actually in flight — the reset path has nothing
270
+ // to abort, and the listeners would be idle on every screen.
271
+ for (const type of USER_TAKEOVER_EVENTS) {
272
+ element?.addEventListener(type, stopRestore, { passive: true });
273
+ }
274
+ }
275
+
276
+ element?.addEventListener('scroll', save, { passive: true });
277
+
278
+ return () => {
279
+ stopRestore();
280
+ element?.removeEventListener('scroll', save);
281
+ // Removing a listener that was never added is a no-op, so this needs no
282
+ // flag tracking whether the loop branch ran.
283
+ for (const type of USER_TAKEOVER_EVENTS) {
284
+ element?.removeEventListener(type, stopRestore);
285
+ }
286
+ // Final capture: persist the last offset the scroll listener OBSERVED,
287
+ // never a fresh read (which the navigator may have forced to 0 while
288
+ // collapsing the hidden screen). When the user never scrolled this
289
+ // session there is nothing newer than the live saves already recorded.
290
+ if (lastObservedOffset !== null) {
291
+ store.save(scrollKey, lastObservedOffset);
292
+ }
293
+ };
294
+ }, [store, scrollKey, enabled, target]),
240
295
  );
296
+
297
+ return WEB_BINDING;
241
298
  }
242
299
 
243
300
  /**
@@ -247,7 +304,7 @@ export function useScrollRestoration(
247
304
  function resolveScrollEventTarget(
248
305
  target: Exclude<ScrollRestorationTarget, 'window'>,
249
306
  ): EventTarget | null {
250
- const current = (target as { current: unknown }).current;
307
+ const current = target.current;
251
308
  if (current == null) return null;
252
309
  if (typeof EventTarget !== 'undefined' && current instanceof EventTarget) {
253
310
  return current;
@@ -0,0 +1,64 @@
1
+ import type { ScrollableHandle, ScrollRestorationTarget } from './types';
2
+
3
+ /**
4
+ * The write half of a scrollable, on native. There is no read half: native
5
+ * offers no way to sample a list's offset from outside it, so offsets arrive
6
+ * through the `onScroll` binding the hook returns instead.
7
+ */
8
+ export interface NativeScroller {
9
+ setOffset: (offset: number) => void;
10
+ }
11
+
12
+ function hasScrollToOffset(
13
+ value: unknown,
14
+ ): value is Required<Pick<ScrollableHandle, 'scrollToOffset'>> {
15
+ return (
16
+ typeof value === 'object' &&
17
+ value !== null &&
18
+ typeof (value as ScrollableHandle).scrollToOffset === 'function'
19
+ );
20
+ }
21
+
22
+ function hasScrollTo(
23
+ value: unknown,
24
+ ): value is Required<Pick<ScrollableHandle, 'scrollTo'>> {
25
+ return (
26
+ typeof value === 'object' &&
27
+ value !== null &&
28
+ typeof (value as ScrollableHandle).scrollTo === 'function'
29
+ );
30
+ }
31
+
32
+ /**
33
+ * Build a {@link NativeScroller} for a target.
34
+ *
35
+ * `scrollToOffset` (`FlatList`, `FlashList`) is preferred over `scrollTo`
36
+ * (`ScrollView`) because a list exposes both shapes on some versions and only
37
+ * the former accounts for the list's own header. The `'window'` sentinel has no
38
+ * native meaning — there is no document scroller — so it resolves to a no-op
39
+ * rather than an error: a call site shared with web legitimately passes it.
40
+ *
41
+ * The handle is re-resolved on every write; it is never cached, because a ref
42
+ * can be swapped or detached between the schedule and the write.
43
+ */
44
+ export function createScroller(
45
+ target: ScrollRestorationTarget,
46
+ ): NativeScroller {
47
+ if (target === 'window') {
48
+ return { setOffset: () => undefined };
49
+ }
50
+
51
+ return {
52
+ setOffset: (offset) => {
53
+ const current = target.current;
54
+ if (current == null) return;
55
+ if (hasScrollToOffset(current)) {
56
+ current.scrollToOffset({ offset, animated: false });
57
+ return;
58
+ }
59
+ if (hasScrollTo(current)) {
60
+ current.scrollTo({ y: offset, animated: false });
61
+ }
62
+ },
63
+ };
64
+ }