@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
@@ -18,11 +18,13 @@
18
18
  * Nesting extra contexts costs nothing at runtime — the win is that scope is no
19
19
  * longer a per-app decision.
20
20
  *
21
- * EXPO/EXPO-ROUTER APPS ONLY. The scroll-restoration provider it mounts imports
22
- * `expo-router` (its web implementation keys offsets on the focused route), so
23
- * a Vite/SPA consumer that has no expo-router cannot resolve this module. Those
24
- * apps keep mounting `BloomThemeProvider` (and any other piece they need)
25
- * directly that is not a lesser path, just the one without a router.
21
+ * EXPO/EXPO-ROUTER APPS ONLY, and now for one narrow reason: it binds the
22
+ * scroll store to the expo-router ADAPTER, which is the only module in the
23
+ * scroll primitive that imports `expo-router`. The scroll core itself is
24
+ * router-agnostic, so a Vite/SPA consumer can mount
25
+ * `<ScrollRestorationProvider adapter={...}>` from `@oxyhq/bloom/scroll` with
26
+ * an adapter for its own router — alongside `BloomThemeProvider` and whatever
27
+ * else it needs — rather than going without.
26
28
  *
27
29
  * NOT included, on purpose — these are OUTLETS, not state, and their placement
28
30
  * in the tree is a real app decision (z-order, safe areas, and mounting a
@@ -36,7 +38,8 @@ import { ImageResolverProvider, type ImageResolver } from '../image-resolver';
36
38
  import { BloomHapticsProvider } from '../hooks/useHaptics';
37
39
  import { TabBarMinimizeProvider } from '../tab-bar/minimize-context';
38
40
  import { BloomThemeProvider, type BloomThemeProviderProps } from '../theme';
39
- import { ScrollRestorationProvider } from './scroll-provider';
41
+ import { ScrollRestorationProvider } from '../scroll/context';
42
+ import { expoRouterScrollAdapter } from '../scroll/expo-router';
40
43
 
41
44
  export interface BloomProviderProps extends Omit<BloomThemeProviderProps, 'children'> {
42
45
  children: ReactNode;
@@ -61,7 +64,7 @@ export function BloomProvider({
61
64
  // never changes the tree shape and remounts everything below it.
62
65
  <ImageResolverProvider value={imageResolver ?? null}>
63
66
  <BloomThemeProvider {...themeProps}>
64
- <ScrollRestorationProvider>
67
+ <ScrollRestorationProvider adapter={expoRouterScrollAdapter}>
65
68
  <BloomHapticsProvider enabled={haptics}>
66
69
  <TabBarMinimizeProvider>{children}</TabBarMinimizeProvider>
67
70
  </BloomHapticsProvider>
@@ -0,0 +1,107 @@
1
+ /**
2
+ * The provider and context both platform barrels share.
3
+ *
4
+ * Nothing here is platform-specific: the provider holds an offset store and the
5
+ * router adapter, and that composition is identical on web and native. Keeping
6
+ * it in one module also guarantees ONE context identity — a provider mounted
7
+ * from the native barrel and a hook imported from the web barrel would
8
+ * otherwise read two different contexts and the hook would throw.
9
+ */
10
+ import { createContext, useContext, useEffect, useMemo } from 'react';
11
+
12
+ import { ScrollOffsetStore } from './store';
13
+ import type {
14
+ ScrollRestorationProviderProps,
15
+ ScrollRouterAdapter,
16
+ } from './types';
17
+
18
+ export interface ScrollRestorationContextValue {
19
+ store: ScrollOffsetStore;
20
+ adapter: ScrollRouterAdapter;
21
+ }
22
+
23
+ const ScrollRestorationContext =
24
+ createContext<ScrollRestorationContextValue | null>(null);
25
+ ScrollRestorationContext.displayName = 'BloomScrollRestorationContext';
26
+
27
+ /**
28
+ * Holds the offset map and the router binding for the subtree. One provider
29
+ * near the app root is enough; the store lives as long as the provider, so
30
+ * offsets survive navigating away and back (including browser Back/Forward).
31
+ */
32
+ export function ScrollRestorationProvider({
33
+ children,
34
+ adapter,
35
+ }: ScrollRestorationProviderProps) {
36
+ const store = useMemo(() => new ScrollOffsetStore(), []);
37
+ const value = useMemo(() => ({ store, adapter }), [store, adapter]);
38
+
39
+ useManualBrowserScrollRestoration();
40
+
41
+ return (
42
+ <ScrollRestorationContext.Provider value={value}>
43
+ {children}
44
+ </ScrollRestorationContext.Provider>
45
+ );
46
+ }
47
+
48
+ export function useScrollRestorationContext(): ScrollRestorationContextValue {
49
+ const value = useContext(ScrollRestorationContext);
50
+ if (value === null) {
51
+ throw new Error(
52
+ 'useScrollRestoration must be used within a <ScrollRestorationProvider>.',
53
+ );
54
+ }
55
+ return value;
56
+ }
57
+
58
+ /**
59
+ * Take over scroll restoration from the browser for as long as this provider is
60
+ * mounted, and hand it back both on unmount and on `pagehide`.
61
+ *
62
+ * The browser's default `'auto'` restoration fights our restore on
63
+ * Back/Forward, so it has to be turned off — but only while something is
64
+ * actually going to restore instead. Two moments where that stops being true:
65
+ *
66
+ * - **Unmount.** This used to run at MODULE scope, which meant merely
67
+ * importing the module disabled the browser's own restoration. Now that the
68
+ * core is importable by apps that mount no provider (and by SSR and Node
69
+ * tooling), that would have left those apps with neither restoration. Tying
70
+ * the switch to the provider's lifetime makes it describe exactly the period
71
+ * during which a replacement exists. The provider mounts at the app root on
72
+ * the first commit, which is before any navigation can create a history
73
+ * entry, so nothing is lost by not doing it at module scope.
74
+ * - **`pagehide`.** The offset map lives in memory only. A reload starts with
75
+ * an empty one, and a bfcache restore resumes a document whose provider is
76
+ * already mounted and whose focus effects therefore never re-run — so in
77
+ * both cases `'manual'` means NOBODY restores. Handing the mode back to the
78
+ * browser on the way out lets it do the job we are no longer able to.
79
+ * (react-router does exactly this, for the same reason.)
80
+ *
81
+ * The feature detect is also the platform test — `history` exists on web and
82
+ * nowhere else — so this stays one implementation rather than a fork. On React
83
+ * Native and during SSR it is a no-op.
84
+ */
85
+ function useManualBrowserScrollRestoration(): void {
86
+ useEffect(() => {
87
+ if (
88
+ typeof window === 'undefined' ||
89
+ typeof history === 'undefined' ||
90
+ !('scrollRestoration' in history)
91
+ ) {
92
+ return undefined;
93
+ }
94
+ const previous = history.scrollRestoration;
95
+ history.scrollRestoration = 'manual';
96
+
97
+ const handBackToBrowser = () => {
98
+ history.scrollRestoration = 'auto';
99
+ };
100
+ window.addEventListener('pagehide', handBackToBrowser);
101
+
102
+ return () => {
103
+ window.removeEventListener('pagehide', handBackToBrowser);
104
+ history.scrollRestoration = previous;
105
+ };
106
+ }, []);
107
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * The expo-router binding for `@oxyhq/bloom/scroll`.
3
+ *
4
+ * This is the only file in the scroll primitive that knows a router exists. It
5
+ * is separate from the core so a consumer with a different router — or none —
6
+ * can still use the core with its own adapter; before the split, a module-scope
7
+ * `expo-router` import made the whole subpath unresolvable for them.
8
+ *
9
+ * The navigation hooks come from `expo-router` (which re-exports React
10
+ * Navigation's) rather than from `@react-navigation/native` directly. Every Oxy
11
+ * app uses expo-router as its router, so it is always a DIRECT, top-level
12
+ * dependency that resolves cleanly under Bun's isolated linker — whereas
13
+ * `@react-navigation/native` is only a nested/transitive dependency of
14
+ * expo-router and would fail to resolve when bundling those apps.
15
+ */
16
+ import { useMemo } from 'react';
17
+ import { useFocusEffect, useRoute } from 'expo-router';
18
+
19
+ import type { ScreenFocusEffect, ScrollRouterAdapter } from '../types';
20
+
21
+ /**
22
+ * Params that describe how a screen was REACHED rather than what it shows, and
23
+ * so must not contribute to a content id — the same screen showing the same
24
+ * thing would otherwise get two ids depending on how the user got there.
25
+ *
26
+ * - `screen` / `params` are React Navigation's nested-navigator plumbing.
27
+ * expo-router strips both wherever it derives a URL from state
28
+ * (`global-state/getRouteInfoFromState.js` deletes them before building the
29
+ * pathname; `global-state/stateUtils.js` deletes `screen` from a payload;
30
+ * `hooks/useSearchParams.js` skips both).
31
+ * - `initial` is React Navigation's reserved anchor flag, set by expo-router's
32
+ * `withAnchor` handling in `global-state/getNavigationAction.js` — which also
33
+ * warns if an app supplies it as a real param.
34
+ */
35
+ const NON_CONTENT_PARAM_KEYS = new Set(['screen', 'params', 'initial']);
36
+
37
+ /**
38
+ * expo-router's own internal params all carry this prefix
39
+ * (`build/navigationParams.js` — `__internal_expo_router_no_animation`,
40
+ * `__internal__expo_router_is_preview_navigation`, and the two zoom-transition
41
+ * ids, verified identical in expo-router 56.2.10 and 57.0.9). They are appended
42
+ * to the params of an ordinary navigation, so matching the prefix rather than
43
+ * the four literals means a fifth one added upstream cannot silently split one
44
+ * screen's content id in two.
45
+ */
46
+ const INTERNAL_PARAM_PREFIX = '__internal';
47
+
48
+ /**
49
+ * Depth at which nested param objects stop being described. React Navigation
50
+ * expects params to be serializable, but nothing enforces it, and a serializer
51
+ * that a cyclic value can hang is not one to put on a render path. Four levels
52
+ * is far past anything a URL produces.
53
+ */
54
+ const MAX_PARAM_DEPTH = 4;
55
+
56
+ function serializeValue(value: unknown, depth: number): string {
57
+ if (value === undefined) return '~undefined';
58
+ if (value === null) return '~null';
59
+ // JSON.stringify quotes and escapes, so a string can never be confused with
60
+ // a marker above or with the punctuation of a nested structure below.
61
+ if (typeof value === 'string') return JSON.stringify(value);
62
+ if (typeof value === 'number' || typeof value === 'boolean') {
63
+ return String(value);
64
+ }
65
+ if (depth >= MAX_PARAM_DEPTH) return '~deep';
66
+ if (Array.isArray(value)) {
67
+ return `[${value.map((entry) => serializeValue(entry, depth + 1)).join(',')}]`;
68
+ }
69
+ if (typeof value === 'object') {
70
+ const source = value as Record<string, unknown>;
71
+ return `{${Object.keys(source)
72
+ .sort()
73
+ .map((key) => `${JSON.stringify(key)}:${serializeValue(source[key], depth + 1)}`)
74
+ .join(',')}}`;
75
+ }
76
+ // A function, symbol or bigint reached a screen's params. Nothing about it
77
+ // identifies content, and it cannot be compared across renders anyway.
78
+ return '~opaque';
79
+ }
80
+
81
+ /**
82
+ * Render a screen's params as a stable string. Keys are SORTED so params that
83
+ * differ only in insertion order — routinely, since expo-router rebuilds the
84
+ * object on every navigation — can never produce two ids for one screen.
85
+ *
86
+ * The exclusions apply at the top level only, because that is where React
87
+ * Navigation and expo-router inject theirs; a nested user object keeps every
88
+ * key it has.
89
+ */
90
+ function serializeContentParams(params: object | undefined): string {
91
+ if (params === undefined) return '';
92
+ const source = params as Record<string, unknown>;
93
+ return Object.keys(source)
94
+ .filter(
95
+ (key) =>
96
+ !NON_CONTENT_PARAM_KEYS.has(key) && !key.startsWith(INTERNAL_PARAM_PREFIX),
97
+ )
98
+ .sort()
99
+ .map((key) => `${JSON.stringify(key)}:${serializeValue(source[key], 1)}`)
100
+ .join(',');
101
+ }
102
+
103
+ /**
104
+ * Identify WHAT the calling screen is showing: its route name plus its params.
105
+ *
106
+ * `useRoute()` is the source, and it has to be: it reads the route object of
107
+ * the nearest screen, so a background screen keeps reporting its own content.
108
+ * `usePathname()` would not do — it reads the globally focused route, so a
109
+ * background screen would adopt the foreground one's pathname and save its
110
+ * offset under a key that is not its own.
111
+ *
112
+ * `route.key` is deliberately NOT part of this. An offset belongs to what the
113
+ * user was looking at, not to the history slot it occupied — see
114
+ * `deriveScrollKey` for the full reasoning and the trade it makes.
115
+ *
116
+ * Params are what separate two screens sharing a route name. That matters most
117
+ * where expo-router RECYCLES a route object: `layouts/StackClient.js` reuses
118
+ * the current route — key included — when `NAVIGATE` targets the current route
119
+ * name and `getSingularId` matches, i.e. when only the query changed. Measured
120
+ * on 56.2.10 and 57.0.9: `search?q=cats` -> `search?q=dogs` keeps one key and
121
+ * swaps `params`, so without the params the two searches would share an offset.
122
+ */
123
+ function useScreenContentId(): string | null {
124
+ const route = useRoute();
125
+ const contentId = `${route.name}?${serializeContentParams(route.params)}`;
126
+ return useMemo(() => contentId, [contentId]);
127
+ }
128
+
129
+ function useScreenFocusEffect(effect: ScreenFocusEffect): void {
130
+ useFocusEffect(effect);
131
+ }
132
+
133
+ /**
134
+ * The adapter to hand `<ScrollRestorationProvider adapter={...}>` in an
135
+ * expo-router app. A module-level constant, as the adapter contract requires.
136
+ */
137
+ export const expoRouterScrollAdapter: ScrollRouterAdapter = {
138
+ useScreenContentId,
139
+ useScreenFocusEffect,
140
+ };
@@ -1,47 +1,114 @@
1
1
  /**
2
- * Native variant of the scroll-restoration primitive — a deliberate no-op.
2
+ * Native variant of the scroll-restoration primitive.
3
3
  *
4
- * React Navigation's native-stack keeps every screen mounted while it is in the
5
- * stack, so a list's scroll position survives a push/pop for free. There is
6
- * nothing to save or restore. We still ship the full API surface (provider +
7
- * hook) so consumers write one set of call sites that compile and run on every
8
- * platform; on native the provider just renders its children and the hook does
9
- * nothing.
4
+ * React Navigation's native-stack keeps every screen MOUNTED while it is in the
5
+ * stack, so a list's scroll position survives a push/pop for free this file
6
+ * must not interfere with that, and does not: nothing here runs on focus.
7
+ *
8
+ * What native does not survive is a KEY CHANGE: an in-screen tab or folder swap
9
+ * that re-keys a list, and a screen that genuinely unmounts and remounts. The
10
+ * effect below is therefore keyed on the storage key (plus `enabled`) rather
11
+ * than on focus, which draws exactly that line with no bookkeeping: React
12
+ * re-runs it when the key changes and leaves it alone when a push/pop merely
13
+ * re-focuses the same screen showing the same content.
10
14
  *
11
15
  * Web bundlers select `./index.web` via the `"browser"` export condition in
12
16
  * `package.json`; native bundlers fall through to this file.
13
17
  */
14
- import type { ReactElement } from 'react';
18
+ import { useCallback, useEffect, useMemo, useRef } from 'react';
19
+
20
+ import { useScrollRestorationContext } from './context';
21
+ import { createScroller } from './scrollable.native';
22
+ import { deriveScrollKey } from './store';
15
23
  import type {
16
- ScrollRestorationProviderProps,
24
+ ScrollRestorationBinding,
17
25
  ScrollRestorationTarget,
18
26
  UseScrollRestorationOptions,
19
27
  } from './types';
20
28
 
29
+ export { ScrollRestorationProvider } from './context';
30
+
21
31
  export type {
32
+ ScreenFocusEffect,
22
33
  ScrollableHandle,
34
+ ScrollRestorationBinding,
23
35
  ScrollRestorationProviderProps,
24
36
  ScrollRestorationTarget,
37
+ ScrollRouterAdapter,
25
38
  UseScrollRestorationOptions,
26
39
  } from './types';
27
40
 
28
41
  /**
29
- * No-op provider. Renders children unchanged native scroll persistence is
30
- * handled by the navigator, so no per-route state is kept.
31
- */
32
- export function ScrollRestorationProvider({
33
- children,
34
- }: ScrollRestorationProviderProps): ReactElement {
35
- return children as ReactElement;
36
- }
37
-
38
- /**
39
- * No-op hook. Accepts the same arguments as the web implementation so call
40
- * sites are identical across platforms.
42
+ * Preserve and restore the scroll offset of `target` across content changes,
43
+ * keyed by the content its screen is showing plus an optional `options.key`.
44
+ *
45
+ * Behaviour (native):
46
+ * - Offsets are recorded from the returned `onScroll` binding, which the caller
47
+ * wires onto the list. There is no other way to observe a list's offset.
48
+ * - When the storage key changes — a re-keyed list, a remount, or `enabled`
49
+ * turning on — the saved offset is applied, or 0 when the key was never seen.
50
+ * - A push/pop that re-focuses the same screen scrolls nothing. The navigator
51
+ * already preserved the position, and re-applying it would at best be a
52
+ * no-op and at worst fight a list that has legitimately moved on.
41
53
  */
42
54
  export function useScrollRestoration(
43
- _target: ScrollRestorationTarget,
44
- _options?: UseScrollRestorationOptions,
45
- ): void {
46
- // Intentionally empty: native-stack already preserves scroll position.
55
+ target: ScrollRestorationTarget,
56
+ options?: UseScrollRestorationOptions,
57
+ ): ScrollRestorationBinding {
58
+ const { store, adapter } = useScrollRestorationContext();
59
+ const contentId = adapter.useScreenContentId();
60
+ const enabled = options?.enabled ?? true;
61
+ const scrollKey = deriveScrollKey(contentId, options?.key);
62
+
63
+ // The key the live `onScroll` binding is allowed to record against. It is
64
+ // assigned by the effect below only AFTER that effect's own write has landed,
65
+ // and cleared by its cleanup — so the relayout the outgoing content emits
66
+ // while a new key is already rendered is never attributed to the new key.
67
+ const recordingKeyRef = useRef<string | null>(null);
68
+
69
+ useEffect(() => {
70
+ if (!enabled || scrollKey === null) return undefined;
71
+
72
+ const scroller = createScroller(target);
73
+ let frame: number | null = null;
74
+
75
+ // Restore and reset are ONE write: a miss reads 0, and 0 is exactly what a
76
+ // list showing content never seen this session must be sent to rather than
77
+ // left at the offset its predecessor had.
78
+ const apply = (): void => {
79
+ frame = null;
80
+ scroller.setOffset(store.read(scrollKey));
81
+ recordingKeyRef.current = scrollKey;
82
+ };
83
+
84
+ // Defer one frame. This effect fires in the same commit that rendered the
85
+ // incoming rows, and a list cannot honour an offset before it has laid them
86
+ // out — the write would be clamped to whatever height it has reached so
87
+ // far, with no second chance (unlike web, native gets no scroll event to
88
+ // re-apply from). One frame is all that is needed because `enabled` has
89
+ // already guaranteed the rows are there; what remains is the layout pass.
90
+ if (typeof requestAnimationFrame === 'function') {
91
+ frame = requestAnimationFrame(apply);
92
+ } else {
93
+ // No frame scheduler (SSR, or a bare Node import of this barrel).
94
+ // Applying immediately is still the correct write; only the wait is lost.
95
+ apply();
96
+ }
97
+
98
+ return () => {
99
+ if (frame !== null) cancelAnimationFrame(frame);
100
+ recordingKeyRef.current = null;
101
+ };
102
+ }, [store, scrollKey, enabled, target]);
103
+
104
+ const onScroll = useCallback<ScrollRestorationBinding['onScroll']>(
105
+ (event) => {
106
+ const key = recordingKeyRef.current;
107
+ if (key === null) return;
108
+ store.save(key, event.nativeEvent.contentOffset.y);
109
+ },
110
+ [store],
111
+ );
112
+
113
+ return useMemo(() => ({ onScroll }), [onScroll]);
47
114
  }