Skip to content

Commit 26a1604

Browse files
fix(mobile): the thread feed keeps its place when its width changes
Folding or unfolding the iPhone Duo, rotating, or resizing a split pane re-wraps every row at once. LegendList re-measures them over the next commits and judges the new geometry: the growth carried a following feed past its near-end threshold, so it showed earlier text and only jumped back later, and a reader's row kept its top while the text inside it moved by screens. The feed now records what the reader is looking at before any row is re-measured: on iOS from its own layout event, which arrives before the row measurements, and on Android from the commit that changes the width. A following feed pins the end once and lifts the end threshold until the rows settle. A reader returns, after the settle, to the same share of the row under the header. A drag, a send, a disclosure toggle, or a thread change cancels the restore, and the list's initial positioning is left alone until it loads. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 9450070 commit 26a1604

3 files changed

Lines changed: 246 additions & 19 deletions

File tree

‎apps/mobile/src/features/threads/ThreadFeed.tsx‎

Lines changed: 91 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ import {
9090
useCallback,
9191
useContext,
9292
useEffect,
93+
useEffectEvent,
9394
useLayoutEffect,
9495
useMemo,
9596
useRef,
@@ -202,7 +203,10 @@ import {
202203
import type { ThreadContentPresentation } from "./threadContentPresentation";
203204
import {
204205
resolveThreadFeedLiveFollow,
206+
resolveThreadFeedReflowAnchor,
207+
resolveThreadFeedReflowScroll,
205208
type ThreadFeedLiveFollowEvent,
209+
type ThreadFeedReflowAnchor,
206210
type ThreadWorkGroupScrollPosition,
207211
} from "./thread-feed-live-follow";
208212
import {
@@ -284,6 +288,11 @@ function formatMessageTime(input: string): string {
284288
}
285289

286290
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;
287296
const USER_BUBBLE_HORIZONTAL_PADDING = 3.5 * 3.5;
288297
const ASSISTANT_ROW_HORIZONTAL_PADDING = 3.5;
289298
const THREAD_FEED_DISCLOSURE_ENTER_TRANSITION = FadeIn.delay(
@@ -1972,6 +1981,20 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
19721981
const transitionEndFollow = (event: ThreadFeedLiveFollowEvent) => {
19731982
setEndFollow(resolveThreadFeedLiveFollow(endFollowEnabledRef.current, event));
19741983
};
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+
};
19751998
const [interactionState, setInteractionState] = useState<{
19761999
readonly copiedRowId: string | null;
19772000
readonly expandedWorkGroups: Record<string, boolean>;
@@ -2419,6 +2442,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
24192442
const handleScrollBeginDrag = () => {
24202443
clearUserScrollSettle();
24212444
userScrollSessionRef.current = true;
2445+
cancelReflow();
24222446
// Pause before the first scroll event. Otherwise a stream update can run
24232447
// maintainScrollAtEnd between touch-down and the drag leaving its threshold.
24242448
transitionEndFollow({ type: "user-scroll-begin" });
@@ -2461,22 +2485,17 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
24612485
useEffect(() => {
24622486
clearUserScrollSettle();
24632487
userScrollSessionRef.current = false;
2488+
cancelReflow();
24642489
transitionEndFollow({ type: "reset" });
2465-
}, [clearUserScrollSettle, feedThreadKey, transitionEndFollow]);
2490+
}, [cancelReflow, clearUserScrollSettle, feedThreadKey, transitionEndFollow]);
24662491
useEffect(() => {
24672492
if (props.submittedMessageId !== null) {
24682493
clearUserScrollSettle();
24692494
userScrollSessionRef.current = false;
2495+
cancelReflow();
24702496
transitionEndFollow({ type: "reset" });
24712497
}
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]);
24802499

24812500
useEffect(() => {
24822501
reportHeaderMaterialVisibility(false);
@@ -2498,6 +2517,54 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
24982517
}
24992518
}, [listMountKey, props.contentInsetEndAdjustment, listRef]);
25002519

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+
25012568
const anchoredEndSpace = resolveChatListAnchoredEndSpace(
25022569
presentedFeed,
25032570
props.anchorMessageId,
@@ -2580,6 +2647,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
25802647
};
25812648

25822649
const suspendEndScrollMaintenanceForDisclosure = (anchorKey: string | null) => {
2650+
cancelReflow();
25832651
disclosureAnchorKeyRef.current = anchorKey;
25842652
setDisclosureToggleSettling(true);
25852653
};
@@ -2724,16 +2792,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
27242792
useLayoutEffect(() => {
27252793
if (previousContentWidth.current === contentWidth) return;
27262794
previousContentWidth.current = contentWidth;
2795+
// Rows re-rendered at this width are measured in the next commit, after this effect.
2796+
beginReflow();
27272797
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]);
27372799

27382800
const renderItem = (info: { item: PendingThreadFeedEntry; index: number }) => (
27392801
<Animated.View
@@ -2881,6 +2943,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
28812943
},
28822944
}
28832945
}
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}
28842949
maintainVisibleContentPosition={
28852950
endFollowEnabled && !disclosureToggleSettling ? false : maintainVisibleContentPosition
28862951
}
@@ -2921,6 +2986,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
29212986
estimatedItemSize={180}
29222987
alignItemsAtEnd
29232988
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+
}}
29242996
onScroll={handleScroll}
29252997
onScrollBeginDrag={handleScrollBeginDrag}
29262998
onScrollEndDrag={handleScrollEndDrag}
@@ -2950,7 +3022,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
29503022
) : null
29513023
}
29523024
contentContainerStyle={{
2953-
paddingTop: 12,
3025+
paddingTop: FEED_PADDING_TOP,
29543026
paddingLeft: contentHorizontalPadding + contentLeftInset,
29553027
paddingRight: contentHorizontalPadding + contentRightInset,
29563028
}}

‎apps/mobile/src/features/threads/thread-feed-live-follow.test.ts‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import { describe, expect, it } from "vite-plus/test";
22

33
import {
44
resolveThreadFeedLiveFollow,
5+
resolveThreadFeedReflowAnchor,
6+
resolveThreadFeedReflowScroll,
57
resolveThreadFeedSubmissionAnchor,
68
resolveThreadWorkGroupInitialScroll,
79
shouldFollowThreadWorkGroupAppend,
@@ -178,3 +180,88 @@ describe("resolveThreadFeedLiveFollow", () => {
178180
).toBe(false);
179181
});
180182
});
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‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor";
2+
13
export type ThreadFeedLiveFollowEvent =
24
| { readonly type: "reset" }
35
| { readonly type: "user-scroll-begin" }
@@ -88,3 +90,69 @@ export function resolveThreadFeedLiveFollow(
8890
return current;
8991
}
9092
}
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+
}

0 commit comments

Comments
 (0)