Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useRestingTopOffset.ts

29 lines1.3 KB

1import { useState } from "react";
2import type { NativeScrollEvent, NativeSyntheticEvent, ScrollViewProps } from "react-native";
3​
4/**
5 * A scroll view with a manual top inset rests at `-topInset`, just below the header. The inset
6 * can change after mount: a column's safe area starts as the window's until UIKit measures it,
7 * and rotation or folding changes it again. While the view rests below the header it follows the
8 * inset; once scrolled away it holds the last resting offset, because RN re-applies a changed
9 * `contentOffset` prop and would move the reader.
10 */
11export function holdRestingTopOffset(held: number | null, scrollY: number, topInset: number) {
12 return Math.abs(scrollY + topInset) <= 1 ? null : (held ?? -topInset);
14​
15export function useRestingTopOffset(
16 topInset: number,
17 props: Pick<ScrollViewProps, "contentOffset" | "onScroll">,
18) {
19 // A list restoring a saved position mounts away from its resting offset.
20 const [held, setHeld] = useState(props.contentOffset?.y ?? null);
21 return {
22 contentOffset: { x: 0, y: held ?? -topInset },
23 onScroll: (event: NativeSyntheticEvent<NativeScrollEvent>) => {
24 const scrollY = event.nativeEvent.contentOffset.y;
25 setHeld((current) => holdRestingTopOffset(current, scrollY, topInset));
26 props.onScroll?.(event);
27 },
28 };