@devries-cameron20 / t3code-1 / commits / eec07b604d
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(mobile): retain resting scroll offsets through Duo inset changes (#22978)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 21, 2026 at 17:58 UTC eec07b604d96c902a3d945b6ddc16e95dc30860a
10 files changed +364 -24
apps/mobile/src/features/home/HomeScreen.tsx
+3 -1
@@ -42,6 +42,7 @@ import type { SavedRemoteConnection } from "../../lib/connection";
42 import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
43 import { NativePrimaryColumnContext } from "../../native/v5-workspace-context";
44 import { nativeHeaderScrollEdgeEffects } from "../../native/scrollEdgeEffects";
45 +import { useRestingTopOffset } from "../../native/useRestingTopOffset";
46 import {
47 useNativeColumnLayoutMetrics,
48 useNativeLayoutMetrics,
@@ -216,6 +217,7 @@ function HomeTopContentSpacer() {
217 function HomeScrollView(props: ComponentProps<typeof ScrollView>) {
218 const insets = useSafeAreaInsets();
219 const primaryColumn = use(NativePrimaryColumnContext);
220 + const restingOffset = useRestingTopOffset(insets.top, props);
221 if (Platform.OS !== "ios") return <ScrollView {...props} />;
222
223 // v5 needs the actual content scroll view registered with its screen controller.
@@ -230,6 +232,7 @@ function HomeScrollView(props: ComponentProps<typeof ScrollView>) {
232 >
233 <ScrollView
234 {...props}
235 + {...restingOffset}
236 // UIKit's scroll-edge material needs the scroll view's own surface color.
237 className={cn(props.className, primaryColumn ? "bg-drawer" : "bg-screen")}
238 // Use the column's measured inset so UIKit recognizes the resting top.
@@ -237,7 +240,6 @@ function HomeScrollView(props: ComponentProps<typeof ScrollView>) {
240 // past its edge, activating scroll-edge protection before any scroll.
241 automaticallyAdjustContentInsets={false}
242 contentInsetAdjustmentBehavior="never"
240 - contentOffset={props.contentOffset ?? { x: 0, y: -insets.top }}
243 />
244 </ScrollViewMarker>
245 );
apps/mobile/src/features/pull-requests/PullRequestReviewersScreen.tsx
+3 -1
@@ -20,6 +20,7 @@ import { ScrollViewMarker } from "react-native-screens";
20 import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
21 import { EmptyState } from "../../components/ui/EmptyState";
22 import { Button } from "../../components/ui/Button";
23 +import { useRestingTopOffset } from "../../native/useRestingTopOffset";
24 import { SymbolView } from "../../components/ui/AppSymbol";
25 import { NativeStackScreenOptions } from "../../native/StackHeader";
26 import { useNativeLayoutMetrics } from "../../native/native-layout-metrics";
@@ -35,14 +36,15 @@ import { pullRequestTarget, type PullRequestParams } from "./usePullRequestDiff"
36
37 function ReviewerScrollView(props: ScrollViewProps) {
38 const insets = useSafeAreaInsets();
39 + const restingOffset = useRestingTopOffset(insets.top, props);
40 return (
41 <ScrollViewMarker style={{ flex: 1 }}>
42 <ScrollView
43 {...props}
44 + {...restingOffset}
45 automaticallyAdjustContentInsets={false}
46 contentInsetAdjustmentBehavior="never"
47 contentInset={{ top: insets.top }}
45 - contentOffset={props.contentOffset ?? { x: 0, y: -insets.top }}
48 />
49 </ScrollViewMarker>
50 );
apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
+6 -2
@@ -56,6 +56,7 @@ import {
56 View,
57 } from "react-native";
58 import { NativeScrollViewMarker as ScrollViewMarker } from "../../native/NativeScrollViewMarker";
59 +import { useRestingTopOffset } from "../../native/useRestingTopOffset";
60 import { useSafeAreaInsets } from "react-native-safe-area-context";
61
62 import { AppText as Text } from "../../components/ui/AppText";
@@ -117,13 +118,14 @@ const EMPTY_IDS: readonly string[] = [];
118
119 function PullRequestTabScrollView(props: ScrollViewProps) {
120 const insets = useSafeAreaInsets();
121 + const restingOffset = useRestingTopOffset(insets.top, props);
122 return (
123 <ScrollViewMarker style={{ flex: 1 }}>
124 <ScrollView
125 {...props}
126 + {...restingOffset}
127 automaticallyAdjustContentInsets={false}
128 contentInsetAdjustmentBehavior="never"
126 - contentOffset={props.contentOffset ?? { x: 0, y: -insets.top }}
129 />
130 </ScrollViewMarker>
131 );
@@ -558,7 +560,9 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
560 >
561 <AnimatedLegendList
562 ref={listRefs[tab]}
561 - initialScrollOffset={-insets.top}
563 + // The scroll view owns its resting offset. LegendList keeps the first
564 + // initialScrollOffset it gets, and the first render has the window's top
565 + // inset (0 on the folded iPhone Duo), not the header's.
566 onScroll={(event) => {
567 const offset = event.nativeEvent.contentOffset.y;
568 scrollOffsets.current[tab] = offset;
apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx
+3 -1
@@ -21,6 +21,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
21
22 import { AppText as Text } from "../../components/ui/AppText";
23 import { EmptyState } from "../../components/ui/EmptyState";
24 +import { useRestingTopOffset } from "../../native/useRestingTopOffset";
25 import { NativePrimaryColumnContext } from "../../native/v5-workspace-context";
26 import { useWorkspaceState } from "../../state/workspace";
27 import { useProjects } from "../../state/entities";
@@ -46,13 +47,14 @@ import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSe
47
48 function PullRequestScrollView(props: ScrollViewProps) {
49 const insets = useSafeAreaInsets();
50 + const restingOffset = useRestingTopOffset(insets.top, props);
51 return (
52 <ScrollViewMarker style={{ flex: 1 }}>
53 <ScrollView
54 {...props}
55 + {...restingOffset}
56 automaticallyAdjustContentInsets={false}
57 contentInsetAdjustmentBehavior="never"
55 - contentOffset={props.contentOffset ?? { x: 0, y: -insets.top }}
58 />
59 </ScrollViewMarker>
60 );
apps/mobile/src/features/threads/ThreadFeed.tsx
+91 -19
@@ -90,6 +90,7 @@ import {
90 useCallback,
91 useContext,
92 useEffect,
93 + useEffectEvent,
94 useLayoutEffect,
95 useMemo,
96 useRef,
@@ -202,7 +203,10 @@ import {
203 import type { ThreadContentPresentation } from "./threadContentPresentation";
204 import {
205 resolveThreadFeedLiveFollow,
206 + resolveThreadFeedReflowAnchor,
207 + resolveThreadFeedReflowScroll,
208 type ThreadFeedLiveFollowEvent,
209 + type ThreadFeedReflowAnchor,
210 type ThreadWorkGroupScrollPosition,
211 } from "./thread-feed-live-follow";
212 import {
@@ -284,6 +288,11 @@ function formatMessageTime(input: string): string {
288 }
289
290 const TURN_FOLD_HEIGHT = 42;
291 +const FEED_PADDING_TOP = 12;
292 +// Rows re-measure within a commit or two of a width change. LegendList also defers imperative
293 +// scrolls for 100ms after it compensates a size change, and a deferred restore could land
294 +// under a drag that starts meanwhile.
295 +const FEED_REFLOW_SETTLE_MS = 200;
296 const USER_BUBBLE_HORIZONTAL_PADDING = 3.5 * 3.5;
297 const ASSISTANT_ROW_HORIZONTAL_PADDING = 3.5;
298 const THREAD_FEED_DISCLOSURE_ENTER_TRANSITION = FadeIn.delay(
@@ -1972,6 +1981,20 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
1981 const transitionEndFollow = (event: ThreadFeedLiveFollowEvent) => {
1982 setEndFollow(resolveThreadFeedLiveFollow(endFollowEnabledRef.current, event));
1983 };
1984 + // A width change re-wraps every row at once, and LegendList re-measures them over the next
1985 + // commits. Its end threshold and MVCP only see the new geometry, so the reader's place is
1986 + // taken before any row lands: the end while following, otherwise the row under the header.
1987 + // undefined: no reflow. null: a reflow with nothing to restore.
1988 + const reflowAnchorRef = useRef<ThreadFeedReflowAnchor | null | undefined>(undefined);
1989 + const [reflowFollowsEnd, setReflowFollowsEnd] = useState(false);
1990 + const [reflowSettleRevision, setReflowSettleRevision] = useState(0);
1991 + const listHeaderSizeRef = useRef(0);
1992 + const loadedListKeyRef = useRef<string | null>(null);
1993 + const cancelReflow = () => {
1994 + if (reflowAnchorRef.current === undefined) return;
1995 + reflowAnchorRef.current = undefined;
1996 + setReflowFollowsEnd(false);
1997 + };
1998 const [interactionState, setInteractionState] = useState<{
1999 readonly copiedRowId: string | null;
2000 readonly expandedWorkGroups: Record<string, boolean>;
@@ -2419,6 +2442,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2442 const handleScrollBeginDrag = () => {
2443 clearUserScrollSettle();
2444 userScrollSessionRef.current = true;
2445 + cancelReflow();
2446 // Pause before the first scroll event. Otherwise a stream update can run
2447 // maintainScrollAtEnd between touch-down and the drag leaving its threshold.
2448 transitionEndFollow({ type: "user-scroll-begin" });
@@ -2461,22 +2485,17 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2485 useEffect(() => {
2486 clearUserScrollSettle();
2487 userScrollSessionRef.current = false;
2488 + cancelReflow();
2489 transitionEndFollow({ type: "reset" });
2465 - }, [clearUserScrollSettle, feedThreadKey, transitionEndFollow]);
2490 + }, [cancelReflow, clearUserScrollSettle, feedThreadKey, transitionEndFollow]);
2491 useEffect(() => {
2492 if (props.submittedMessageId !== null) {
2493 clearUserScrollSettle();
2494 userScrollSessionRef.current = false;
2495 + cancelReflow();
2496 transitionEndFollow({ type: "reset" });
2497 }
2472 - }, [clearUserScrollSettle, props.submittedMessageId, transitionEndFollow]);
2473 -
2474 - const handleViewportLayout = (event: LayoutChangeEvent) => {
2475 - const nextWidth = Math.round(event.nativeEvent.layout.width);
2476 - const nextHeight = Math.round(event.nativeEvent.layout.height);
2477 - setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current));
2478 - setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
2479 - };
2498 + }, [cancelReflow, clearUserScrollSettle, props.submittedMessageId, transitionEndFollow]);
2499
2500 useEffect(() => {
2501 reportHeaderMaterialVisibility(false);
@@ -2498,6 +2517,54 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2517 }
2518 }, [listMountKey, props.contentInsetEndAdjustment, listRef]);
2519
2520 + const reflowLayout = () => ({
2521 + rowsTop: FEED_PADDING_TOP + listHeaderSizeRef.current,
2522 + headerInset: anchorTopInset,
2523 + });
2524 + const beginReflow = () => {
2525 + // Until the list loads, its own initial end positioning owns the offset.
2526 + if (loadedListKeyRef.current !== listMountKey) return;
2527 + if (reflowAnchorRef.current === undefined) {
2528 + const listState = listRef.current?.getState();
2529 + const anchor =
2530 + listState && !userScrollSessionRef.current
2531 + ? resolveThreadFeedReflowAnchor(listState, reflowLayout(), endFollowEnabledRef.current)
2532 + : null;
2533 + reflowAnchorRef.current = anchor;
2534 + if (anchor === "end") {
2535 + // The list may already have judged the first new sizes against its own threshold, so
2536 + // pin the end once; the lifted threshold keeps it there as later rows re-measure.
2537 + setReflowFollowsEnd(true);
2538 + void listRef.current?.scrollToEnd({ animated: false });
2539 + }
2540 + }
2541 + setReflowSettleRevision((revision) => revision + 1);
2542 + };
2543 + const settleReflow = useEffectEvent(() => {
2544 + const anchor = reflowAnchorRef.current;
2545 + cancelReflow();
2546 + const list = listRef.current;
2547 + if (!anchor || anchor === "end" || !list || userScrollSessionRef.current) return;
2548 + if (loadedListKeyRef.current !== listMountKey) return;
2549 + const target = resolveThreadFeedReflowScroll(anchor, list.getState(), reflowLayout());
2550 + if (target) void list.scrollToIndex({ ...target, viewPosition: 0, animated: false });
2551 + });
2552 + useEffect(() => {
2553 + if (reflowSettleRevision === 0) return;
2554 + const timeout = setTimeout(() => settleReflow(), FEED_REFLOW_SETTLE_MS);
2555 + return () => clearTimeout(timeout);
2556 + }, [reflowSettleRevision]);
2557 +
2558 + const handleViewportLayout = (event: LayoutChangeEvent) => {
2559 + const nextWidth = Math.round(event.nativeEvent.layout.width);
2560 + const nextHeight = Math.round(event.nativeEvent.layout.height);
2561 + // A native resize re-wraps the rows before JS hears of it. This event reaches JS ahead
2562 + // of the row measurements it caused, since layout events are sent parent first.
2563 + if (Math.abs(measuredViewportWidth - nextWidth) > 1) beginReflow();
2564 + setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current));
2565 + setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
2566 + };
2567 +
2568 const anchoredEndSpace = resolveChatListAnchoredEndSpace(
2569 presentedFeed,
2570 props.anchorMessageId,
@@ -2580,6 +2647,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2647 };
2648
2649 const suspendEndScrollMaintenanceForDisclosure = (anchorKey: string | null) => {
2650 + cancelReflow();
2651 disclosureAnchorKeyRef.current = anchorKey;
2652 setDisclosureToggleSettling(true);
2653 };
@@ -2724,16 +2792,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2792 useLayoutEffect(() => {
2793 if (previousContentWidth.current === contentWidth) return;
2794 previousContentWidth.current = contentWidth;
2795 + // Rows re-rendered at this width are measured in the next commit, after this effect.
2796 + beginReflow();
2797 if (hasHtmlRenders) listRef.current?.clearCaches({ mode: "sizes" });
2728 - // A reflow can grow the visible rows past LegendList's near-end threshold in one batch, and
2729 - // maintainScrollAtEnd then stops following. Pin the end the feed was following once the new
2730 - // sizes are in.
2731 - if (!endFollowEnabledRef.current || !listRef.current?.getState().isAtEnd) return;
2732 - const frame = requestAnimationFrame(() => {
2733 - if (endFollowEnabledRef.current) void listRef.current?.scrollToEnd({ animated: false });
2734 - });
2735 - return () => cancelAnimationFrame(frame);
2736 - }, [contentWidth, hasHtmlRenders, listRef]);
2798 + }, [beginReflow, contentWidth, hasHtmlRenders, listRef]);
2799
2800 const renderItem = (info: { item: PendingThreadFeedEntry; index: number }) => (
2801 <Animated.View
@@ -2881,6 +2943,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2943 },
2944 }
2945 }
2946 + // A reflow grows every visible row at once, well past the near-end threshold
2947 + // that otherwise lets a status-bar tap leave the end.
2948 + maintainScrollAtEndThreshold={reflowFollowsEnd ? Number.POSITIVE_INFINITY : undefined}
2949 maintainVisibleContentPosition={
2950 endFollowEnabled && !disclosureToggleSettling ? false : maintainVisibleContentPosition
2951 }
@@ -2921,6 +2986,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2986 estimatedItemSize={180}
2987 alignItemsAtEnd
2988 initialScrollAtEnd
2989 + onLoad={() => {
2990 + loadedListKeyRef.current = listMountKey;
2991 + }}
2992 + // Row positions start below the header; the reflow anchor converts between them.
2993 + onMetricsChange={(metrics) => {
2994 + listHeaderSizeRef.current = metrics.headerSize;
2995 + }}
2996 onScroll={handleScroll}
2997 onScrollBeginDrag={handleScrollBeginDrag}
2998 onScrollEndDrag={handleScrollEndDrag}
@@ -2950,7 +3022,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
3022 ) : null
3023 }
3024 contentContainerStyle={{
2953 - paddingTop: 12,
3025 + paddingTop: FEED_PADDING_TOP,
3026 paddingLeft: contentHorizontalPadding + contentLeftInset,
3027 paddingRight: contentHorizontalPadding + contentRightInset,
3028 }}
apps/mobile/src/features/threads/thread-feed-live-follow.test.ts
+87
@@ -2,6 +2,8 @@ import { describe, expect, it } from "vite-plus/test";
2
3 import {
4 resolveThreadFeedLiveFollow,
5 + resolveThreadFeedReflowAnchor,
6 + resolveThreadFeedReflowScroll,
7 resolveThreadFeedSubmissionAnchor,
8 resolveThreadWorkGroupInitialScroll,
9 shouldFollowThreadWorkGroupAppend,
@@ -178,3 +180,88 @@ describe("resolveThreadFeedLiveFollow", () => {
180 ).toBe(false);
181 });
182 });
183 +
184 +describe("width reflow anchors", () => {
185 + const layout = { rowsTop: 50, headerInset: 100 };
186 + const feedState = (
187 + rows: ReadonlyArray<{ readonly id: string; readonly size: number }>,
188 + scroll: number,
189 + isWithinMaintainScrollAtEndThreshold = false,
190 + ) => {
191 + const positions = rows.map((_, index) =>
192 + rows.slice(0, index).reduce((top, row) => top + row.size, 0),
193 + );
194 + return {
195 + data: rows,
196 + scroll,
197 + isWithinMaintainScrollAtEndThreshold,
198 + indexByKey: (key: string) => {
199 + const index = rows.findIndex((row) => row.id === key);
200 + return index < 0 ? undefined : index;
201 + },
202 + positionAtIndex: (index: number) => positions[index],
203 + sizes: new Map(rows.map((row) => [row.id, row.size])),
204 + };
205 + };
206 + const wide = [
207 + { id: "question", size: 400 },
208 + { id: "reply", size: 2_000 },
209 + { id: "follow-up", size: 300 },
210 + ];
211 + // The line under the header sits 1,200px, 60%, into the reply.
212 + const readingReply = feedState(wide, 1_550);
213 +
214 + it("keeps the end for a feed that is following it", () => {
215 + expect(resolveThreadFeedReflowAnchor(feedState(wide, 1_550, true), layout, true)).toBe("end");
216 + });
217 +
218 + it("keeps the reader's row after a status-bar scroll left follow on far from the end", () => {
219 + expect(resolveThreadFeedReflowAnchor(readingReply, layout, true)).toEqual({
220 + key: "reply",
221 + offsetWithinRow: 1_200,
222 + size: 2_000,
223 + });
224 + });
225 +
226 + it.each([
227 + { change: "narrows", replySize: 4_000 },
228 + { change: "widens", replySize: 1_000 },
229 + ])("keeps the reader 60% into a reply when the feed $change", ({ replySize }) => {
230 + const anchor = resolveThreadFeedReflowAnchor(readingReply, layout, false);
231 + if (anchor === null || anchor === "end") throw new Error("expected a row anchor");
232 + const reflowed = feedState(
233 + [
234 + { id: "question", size: 400 * (replySize / 2_000) },
235 + { id: "reply", size: replySize },
236 + { id: "follow-up", size: 300 },
237 + ],
238 + readingReply.scroll,
239 + );
240 + expect(resolveThreadFeedReflowScroll(anchor, reflowed, layout)).toEqual({
241 + index: 1,
242 + viewOffset: layout.headerInset - 0.6 * replySize,
243 + });
244 + });
245 +
246 + it("leaves a reader at the top of the thread where they are", () => {
247 + expect(resolveThreadFeedReflowAnchor(feedState(wide, -layout.headerInset), layout, false)).toBe(
248 + null,
249 + );
250 + });
251 +
252 + it("does not scroll when the row did not change size", () => {
253 + const anchor = resolveThreadFeedReflowAnchor(readingReply, layout, false);
254 + if (anchor === null || anchor === "end") throw new Error("expected a row anchor");
255 + expect(resolveThreadFeedReflowScroll(anchor, readingReply, layout)).toBeNull();
256 + });
257 +
258 + it("does not restore a row that left the feed", () => {
259 + expect(
260 + resolveThreadFeedReflowScroll(
261 + { key: "reply", offsetWithinRow: 1_200, size: 2_000 },
262 + feedState([{ id: "question", size: 400 }], 0),
263 + layout,
264 + ),
265 + ).toBeNull();
266 + });
267 +});
apps/mobile/src/features/threads/thread-feed-live-follow.ts
+68
@@ -1,3 +1,5 @@
1 +import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor";
2 +
3 export type ThreadFeedLiveFollowEvent =
4 | { readonly type: "reset" }
5 | { readonly type: "user-scroll-begin" }
@@ -88,3 +90,69 @@ export function resolveThreadFeedLiveFollow(
90 return current;
91 }
92 }
93 +
94 +/** The LegendList state a width reflow reads before rows re-measure and after they settle. */
95 +export interface ThreadFeedReflowListState {
96 + readonly data: ReadonlyArray<{ readonly id: string }>;
97 + readonly scroll: number;
98 + readonly isWithinMaintainScrollAtEndThreshold: boolean;
99 + readonly indexByKey: (key: string) => number | undefined;
100 + readonly positionAtIndex: (index: number) => number | undefined;
101 + readonly sizes: ReadonlyMap<string, number>;
102 +}
103 +
104 +export interface ThreadFeedReflowLayout {
105 + /** List padding and header; row positions start below them. */
106 + readonly rowsTop: number;
107 + /** The top of the viewport covered by the navigation header. */
108 + readonly headerInset: number;
109 +}
110 +
111 +export interface ThreadFeedReflowRowAnchor {
112 + readonly key: string;
113 + readonly offsetWithinRow: number;
114 + readonly size: number;
115 +}
116 +
117 +/** A feed that follows keeps the end through a reflow; a reader keeps the row they are in. */
118 +export type ThreadFeedReflowAnchor = "end" | ThreadFeedReflowRowAnchor;
119 +
120 +function readingLine(state: ThreadFeedReflowListState, layout: ThreadFeedReflowLayout) {
121 + return state.scroll + layout.headerInset - layout.rowsTop;
122 +}
123 +
124 +export function resolveThreadFeedReflowAnchor(
125 + state: ThreadFeedReflowListState,
126 + layout: ThreadFeedReflowLayout,
127 + following: boolean,
128 +): ThreadFeedReflowAnchor | null {
129 + // Follow alone is not enough: a status-bar tap scrolls to the top without a drag, so it
130 + // leaves follow on while the reader is far from the end.
131 + if (following && state.isWithinMaintainScrollAtEndThreshold) return "end";
132 + const line = readingLine(state, layout);
133 + // A reader at the top of the thread stays there without help.
134 + if (line <= 0) return null;
135 + const row = resolveWorkGroupScrollAnchor({
136 + data: state.data,
137 + scroll: line,
138 + positionAtIndex: state.positionAtIndex,
139 + });
140 + const size = row ? state.sizes.get(row.rowId) : undefined;
141 + return row && size ? { key: row.rowId, offsetWithinRow: row.offsetWithinRow, size } : null;
142 +}
143 +
144 +export function resolveThreadFeedReflowScroll(
145 + anchor: ThreadFeedReflowRowAnchor,
146 + state: ThreadFeedReflowListState,
147 + layout: ThreadFeedReflowLayout,
148 +): { readonly index: number; readonly viewOffset: number } | null {
149 + const index = state.indexByKey(anchor.key);
150 + const top = index === undefined ? undefined : state.positionAtIndex(index);
151 + const size = state.sizes.get(anchor.key);
152 + if (index === undefined || top === undefined || size === undefined) return null;
153 + // Rewrapped text grows with its row, so the reader's line sits at the same share of the
154 + // row rather than the same pixel offset into it.
155 + const offsetWithinRow = (anchor.offsetWithinRow * size) / anchor.size;
156 + if (Math.abs(readingLine(state, layout) - (top + offsetWithinRow)) < 1) return null;
157 + return { index, viewOffset: layout.headerInset - offsetWithinRow };
158 +}
apps/mobile/src/native/useRestingTopOffset.test.tsx new
+73
@@ -0,0 +1,73 @@
1 +import { act, useLayoutEffect } from "react";
2 +import { createRoot, type Root } from "react-dom/client";
3 +import { afterEach, describe, expect, it } from "vite-plus/test";
4 +
5 +import { useRestingTopOffset } from "./useRestingTopOffset";
6 +
7 +let root: Root | null = null;
8 +let latest: ReturnType<typeof useRestingTopOffset> | null = null;
9 +
10 +function Probe(props: { readonly topInset: number; readonly restoredOffset?: number }) {
11 + const restingOffset = useRestingTopOffset(
12 + props.topInset,
13 + props.restoredOffset === undefined ? {} : { contentOffset: { x: 0, y: props.restoredOffset } },
14 + );
15 + useLayoutEffect(() => {
16 + latest = restingOffset;
17 + });
18 + return null;
19 +}
20 +
21 +function render(topInset: number, restoredOffset?: number) {
22 + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
23 + root ??= createRoot(document.createElement("div"));
24 + act(() => root!.render(<Probe topInset={topInset} restoredOffset={restoredOffset} />));
25 +}
26 +
27 +function scrollTo(y: number) {
28 + const event = { nativeEvent: { contentOffset: { x: 0, y } } } as Parameters<
29 + ReturnType<typeof useRestingTopOffset>["onScroll"]
30 + >[0];
31 + act(() => latest!.onScroll(event));
32 +}
33 +
34 +function offset() {
35 + return latest!.contentOffset.y;
36 +}
37 +
38 +afterEach(() => {
39 + act(() => root?.unmount());
40 + root = null;
41 + latest = null;
42 +});
43 +
44 +describe("useRestingTopOffset", () => {
45 + it("keeps an untouched list below the header once the column's inset arrives", () => {
46 + // The folded iPhone Duo's window has no top inset; the header's arrives after mount.
47 + render(0);
48 + render(54);
49 + expect(offset()).toBe(-54);
50 + });
51 +
52 + it("does not move a list the reader scrolled when the inset changes", () => {
53 + render(54);
54 + scrollTo(300);
55 + render(90);
56 + expect(offset()).toBe(-54);
57 + });
58 +
59 + it("follows the inset again once the list is back at the top", () => {
60 + render(54);
61 + scrollTo(300);
62 + render(90);
63 + scrollTo(-90);
64 + render(54);
65 + expect(offset()).toBe(-54);
66 + });
67 +
68 + it("holds a restored position through an inset change", () => {
69 + render(0, 1_200);
70 + render(54);
71 + expect(offset()).toBe(1_200);
72 + });
73 +});
apps/mobile/src/native/useRestingTopOffset.ts new
+29
@@ -0,0 +1,29 @@
1 +import { useState } from "react";
2 +import 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 + */
11 +export function holdRestingTopOffset(held: number | null, scrollY: number, topInset: number) {
12 + return Math.abs(scrollY + topInset) <= 1 ? null : (held ?? -topInset);
13 +}
14 +
15 +export 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 + };
29 +}
apps/mobile/vite.config.ts
+1
@@ -6,6 +6,7 @@ const reactTests = [
6 "src/features/settings/SettingsServerControlsRouteScreen.test.tsx",
7 "src/features/settings/components/BranchNamingSettings.test.tsx",
8 "src/native/NativeHeaderToolbar.test.tsx",
9 + "src/native/useRestingTopOffset.test.tsx",
10 "src/state/use-selected-thread-git-actions.test.tsx",
11 ];
12