The best way to control Claude Code, Codex and more from any computer or phone
refactor: upgrade Legend List to 3.7.2 and drop our list workarounds (#28125)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <51714798+juliusmarminge@users.noreply.github.com>
Jay Meistrich committed
Nov 9, 2026 at 09:54 UTC
4df0c1302a54805f821590e4eabe9e6ea4ab80fd
37 files changed
+657
-4060
apps/mobile/src/components/ui/useBarInset.ts
+7
@@ -48,6 +48,13 @@ export function useContentTopInset(): number {
48
return Platform.OS === "ios" ? (columnMetrics?.safeArea.top ?? insets.top) : 0;
49
}
50
51
+/** The content's bottom safe area on iOS, which a list with manual insets must add itself. */
52
+export function useContentBottomInset(): number {
53
+ const insets = useSafeAreaInsets();
54
+ const columnMetrics = useNativeColumnLayoutMetrics();
55
+ return Platform.OS === "ios" ? (columnMetrics?.safeArea.bottom ?? insets.bottom) : 0;
56
+}
57
+
58
/** How much of the screen's bottom edge an AppBar `search` covers: iOS's bottom search toolbar. */
59
export function useSearchToolbarInset(search: AppBarSearch | undefined): number {
60
const { layout } = useAdaptiveWorkspaceLayout();
apps/mobile/src/features/files/FileTreeBrowser.tsx
+4
-3
@@ -10,7 +10,7 @@ import { Pressable, RefreshControl, View } from "react-native";
10
import { AppText as Text } from "../../components/ui/AppText";
11
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
12
import { cn } from "../../lib/cn";
13
-import { useContentTopInset } from "../../components/ui/useBarInset";
13
+import { useContentBottomInset, useContentTopInset } from "../../components/ui/useBarInset";
14
import {
15
buildFileTree,
16
flattenFileTree,
@@ -122,6 +122,7 @@ export function FileTreeBrowser(props: {
122
readonly selectedPathAtPress: string | null;
123
} | null>(null);
124
const headerInset = useContentTopInset();
125
+ const bottomInset = useContentBottomInset();
126
const {
127
onLoadDirectory,
128
onPreviewFile,
@@ -214,12 +215,12 @@ export function FileTreeBrowser(props: {
215
return (
216
<LegendList
217
renderScrollComponent={NativeScrollView}
217
- contentInsetStartAdjustment={headerInset}
218
+ contentInset={{ top: headerInset, bottom: bottomInset }}
219
alwaysBounceVertical
220
className="flex-1"
221
data={visibleNodes}
222
keyExtractor={(item) => item.node.path}
222
- contentInsetAdjustmentBehavior="automatic"
223
+ contentInsetAdjustmentBehavior="never"
224
automaticallyAdjustsScrollIndicatorInsets
225
keyboardDismissMode="on-drag"
226
keyboardShouldPersistTaps="handled"
apps/mobile/src/features/files/ZipArchiveView.test.tsx
+4
-1
@@ -127,7 +127,10 @@ vi.mock("../../components/ui/AppBar", () => {
127
}) => <div>{props.menus?.map((menu) => renderItems(menu.items))}</div>,
128
};
129
});
130
-vi.mock("../../components/ui/useBarInset", () => ({ useContentTopInset: () => 0 }));
130
+vi.mock("../../components/ui/useBarInset", () => ({
131
+ useContentTopInset: () => 0,
132
+ useContentBottomInset: () => 0,
133
+}));
134
vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: () => null }));
135
vi.mock("../../components/ui/Progress", () => ({ Progress: () => null }));
136
vi.mock("../../components/PierreEntryIcon", () => ({ PierreEntryIcon: () => null }));
apps/mobile/src/features/files/ZipArchiveView.tsx
+4
-3
@@ -21,7 +21,7 @@ import { Keyboard, Pressable, ScrollView, TextInput, View } from "react-native";
21
22
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
23
import { AppBar } from "../../components/ui/AppBar";
24
-import { useContentTopInset } from "../../components/ui/useBarInset";
24
+import { useContentBottomInset, useContentTopInset } from "../../components/ui/useBarInset";
25
import { SymbolView } from "../../components/ui/AppSymbol";
26
import { AppText as Text } from "../../components/ui/AppText";
27
import { Button } from "../../components/ui/Button";
@@ -395,15 +395,16 @@ function ZipArchiveList(props: {
395
return next;
396
});
397
const fileCount = archive.fileCount;
398
+ const bottomInset = useContentBottomInset();
399
return (
400
<View className="flex-1 bg-sheet">
401
<LegendList
402
renderScrollComponent={NativeScrollView}
402
- contentInsetStartAdjustment={props.headerInset}
403
+ contentInset={{ top: props.headerInset, bottom: bottomInset }}
404
className="flex-1"
405
data={rows}
406
keyExtractor={(row) => `${row.node.entry ? "f" : "d"}:${row.node.path}`}
406
- contentInsetAdjustmentBehavior="automatic"
407
+ contentInsetAdjustmentBehavior="never"
408
automaticallyAdjustsScrollIndicatorInsets
409
estimatedItemSize={44}
410
recycleItems
apps/mobile/src/features/files/useFileTreeEntries.test.tsx
+4
-1
@@ -141,7 +141,10 @@ vi.mock("react-native", () => ({
141
vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ top: 0 }) }));
142
vi.mock("../../native/NativeScrollViewMarker", () => ({ NativeScrollView: Nothing }));
143
vi.mock("../../native/native-layout-metrics", () => ({ useNativeColumnLayoutMetrics: () => null }));
144
-vi.mock("../../components/ui/useBarInset", () => ({ useContentTopInset: () => 0 }));
144
+vi.mock("../../components/ui/useBarInset", () => ({
145
+ useContentTopInset: () => 0,
146
+ useContentBottomInset: () => 0,
147
+}));
148
vi.mock("@legendapp/list/react-native", () => ({
149
LegendList: <T,>(props: {
150
data: ReadonlyArray<T>;
apps/mobile/src/features/home/HomeScreen.tsx
+10
-14
@@ -1,3 +1,4 @@
1
+import { useContentTopInset } from "../../components/ui/useBarInset";
2
import { usePaneRole } from "../../components/ui/Pane";
3
import { ScreenContent } from "../../components/ui/ScreenContent";
4
import { useActiveNewTask } from "../../state/active-new-task";
@@ -262,6 +263,7 @@ export function HomeScreen(props: HomeScreenProps) {
263
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
264
const homeScrollGesture = useNativeGesture();
265
const insets = useSafeAreaInsets();
266
+ const contentTopInset = useContentTopInset();
267
const emptyTopInset = useWorkspaceListEmptyTopInset();
268
const { fabClearance } = useAndroidControlSizing();
269
const screenMetrics = useNativeLayoutMetrics();
@@ -326,7 +328,7 @@ export function HomeScreen(props: HomeScreenProps) {
328
useSearchScrollRestoration(searchMode, () => {
329
if (restoredOffset === undefined) return;
330
void listRef.current?.scrollToOffset({
329
- offset: restoredOffset - (Platform.OS === "ios" ? insets.top : 0),
331
+ offset: restoredOffset - contentTopInset,
332
animated: false,
333
});
334
});
@@ -347,7 +349,7 @@ export function HomeScreen(props: HomeScreenProps) {
349
if (workspace)
350
workspace.recordScrollOffset(
351
"threads",
350
- Math.max(0, event.nativeEvent.contentOffset.y + (Platform.OS === "ios" ? insets.top : 0)),
352
+ Math.max(0, event.nativeEvent.contentOffset.y + contentTopInset),
353
);
354
clearTimeout(activationTimerRef.current);
355
activationTimerRef.current = setTimeout(
@@ -798,7 +800,7 @@ export function HomeScreen(props: HomeScreenProps) {
800
onTouchStart={(event) => trackListTouches(event, true)}
801
onTouchEnd={(event) => trackListTouches(event, false)}
802
onTouchCancel={(event) => trackListTouches(event, false)}
801
- renderScrollComponent={renderHomeScrollView}
803
+ renderScrollComponent={Platform.OS === "ios" ? renderHomeScrollView : undefined}
804
data={threadListV2Items}
805
renderItem={renderV2Item}
806
keyExtractor={v2KeyExtractor}
@@ -829,17 +831,11 @@ export function HomeScreen(props: HomeScreenProps) {
831
}
832
ListEmptyComponent={v2ListEmpty}
833
style={{ flex: 1 }}
832
- automaticallyAdjustsScrollIndicatorInsets
833
- // UIKit owns the bar's inset, so a minimizing bar and a resized column move
834
- // the list in the same frame as the bar.
835
- contentInsetAdjustmentBehavior="automatic"
836
- contentInsetStartAdjustment={Platform.OS === "ios" ? insets.top : 0}
837
- // RN scrollTo clamps against raw insets and ignores the automatic bar inset.
838
- scrollToOverflowEnabled
834
+ automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
835
+ contentInsetAdjustmentBehavior="never"
836
+ contentInset={Platform.OS === "ios" ? { top: contentTopInset } : undefined}
837
initialScrollOffset={
840
- initialScrollOffset > 0
841
- ? initialScrollOffset - (Platform.OS === "ios" ? insets.top : 0)
842
- : undefined
838
+ initialScrollOffset > 0 ? initialScrollOffset - contentTopInset : undefined
839
}
840
showsVerticalScrollIndicator={false}
841
keyboardDismissMode="on-drag"
@@ -853,7 +849,7 @@ export function HomeScreen(props: HomeScreenProps) {
849
(contentSideInsets?.right ?? 0) + (sidebarSurface ? 8 : 0) + androidListGutter,
850
paddingBottom:
851
Platform.OS === "ios"
856
- ? iosBottomClearance - (columnMetrics?.safeArea.bottom ?? insets.bottom)
852
+ ? iosBottomClearance
853
: (workspace?.bottomClearance ??
854
Math.max(insets.bottom, 16) +
855
(Platform.OS === "android" ? fabClearance : 88)),
apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
+18
-15
@@ -383,8 +383,7 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
383
requestedSection.current = next;
384
scrollOffsets.current[next] = offset;
385
currentScrollOffset.current = { tab: next, offset };
386
- // LegendList clamps to its measured rows, which leave out the short-tab minHeight below.
387
- scrollViews.current[next]?.getNativeScrollRef().scrollTo({ y: offset, animated: false });
386
+ scrollViews.current[next]?.scrollToOffset({ offset, animated: false });
387
setSection(next);
388
};
389
const tabContent = activityContent;
@@ -444,8 +443,10 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
443
filesContent.refresh();
444
});
445
const jumpToFiles = () => {
447
- scrollViews.current.overview?.scrollToOffset({
448
- offset: bodyY.current + filesY.current - contentTopInset,
446
+ scrollViews.current.overview?.scrollToIndex({
447
+ index: 0,
448
+ viewPosition: 0,
449
+ viewOffset: -filesY.current,
450
animated: true,
451
});
452
pendingFilesJump.current = false;
@@ -602,13 +603,13 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
603
currentScrollOffset.current = { tab, offset };
604
}}
605
className="flex-1"
605
- renderScrollComponent={NativeScrollView}
606
- // UIKit owns the bar's inset, so a minimizing bar and a resized column
607
- // move the list in the same frame as the bar.
608
- contentInsetAdjustmentBehavior="automatic"
609
- contentInsetStartAdjustment={contentTopInset}
610
- // RN scrollTo clamps against raw insets and ignores the automatic bar inset.
611
- scrollToOverflowEnabled
606
+ renderScrollComponent={Platform.OS === "ios" ? NativeScrollView : undefined}
607
+ contentInsetAdjustmentBehavior="never"
608
+ contentInset={
609
+ Platform.OS === "ios"
610
+ ? { top: contentTopInset, bottom: contentBottomInset }
611
+ : undefined
612
+ }
613
refreshControl={
614
<RefreshControl
615
refreshing={section === tab && pullRefresh.refreshing}
@@ -617,17 +618,19 @@ export function PullRequestRouteScreen({ route }: StaticScreenProps<PullRequestP
618
}
619
alwaysBounceVertical
620
scrollsToTop={section === tab}
620
- onContentSizeChange={() => {
621
+ onItemSizeChanged={({ itemKey }) => {
622
if (
623
tab !== "overview" ||
624
section !== "overview" ||
625
+ itemKey !== "overview:body" ||
626
!pendingDescriptionJump.current
627
)
628
return;
629
pendingDescriptionJump.current = false;
628
- // Collapse changes the scroll range; restore the heading after that layout commits.
629
- scrollViews.current.overview?.scrollToOffset({
630
- offset: bodyY.current + descriptionY.current - contentTopInset,
630
+ scrollViews.current.overview?.scrollToIndex({
631
+ index: 0,
632
+ viewPosition: 0,
633
+ viewOffset: -descriptionY.current,
634
animated: false,
635
});
636
}}
apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx
+4
-8
@@ -294,20 +294,16 @@ export function PullRequestsScreen(
294
// to this tab. The thread list shows none either.
295
showsVerticalScrollIndicator={Platform.OS !== "android"}
296
recycleItems
297
- renderScrollComponent={NativeScrollView}
298
- // UIKit owns the bar's inset, so a minimizing bar and a resized column move
299
- // the list in the same frame as the bar.
300
- contentInsetAdjustmentBehavior="automatic"
297
+ renderScrollComponent={Platform.OS === "ios" ? NativeScrollView : undefined}
298
+ contentInsetAdjustmentBehavior="never"
299
+ contentInset={Platform.OS === "ios" ? { top: contentTopInset } : undefined}
300
// A plain offset: LegendList adds the list header to an index-based restore, which
301
// landed every return one header lower.
302
initialScrollOffset={
303
initialScrollOffset > 0 ? initialScrollOffset - contentTopInset : undefined
304
}
306
- contentInsetStartAdjustment={contentTopInset}
305
contentContainerStyle={{
308
- paddingBottom:
309
- Math.max(bottomSafeArea, workspace.bottomClearance) -
310
- (Platform.OS === "ios" ? bottomSafeArea : 0),
306
+ paddingBottom: Math.max(bottomSafeArea, workspace.bottomClearance),
307
}}
308
onScroll={(event) => {
309
workspace.recordScrollOffset(
apps/mobile/src/features/pull-requests/pullRequestTabScroll.test.ts
new
+19
@@ -0,0 +1,19 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+import { pullRequestTabOffset } from "./pullRequestTabScroll";
3
+
4
+describe("pull request tab scroll", () => {
5
+ it("keeps the header fixed while switching, even if the destination was scrolled deeply", () => {
6
+ expect(pullRequestTabOffset(-100, 900, 200)).toBe(-100);
7
+ expect(pullRequestTabOffset(75, 900, 200)).toBe(75);
8
+ });
9
+ it("resumes the destination body only when the shared header is already collapsed", () => {
10
+ expect(pullRequestTabOffset(600, 900, 200)).toBe(900);
11
+ expect(pullRequestTabOffset(600, 50, 200)).toBe(200);
12
+ expect(pullRequestTabOffset(600, undefined, 200)).toBe(200);
13
+ });
14
+ it("retains the saved body offset when native scrolling rounds the collapsed header", () => {
15
+ const headerEnd = 213.6666717529297 - 116;
16
+ expect(pullRequestTabOffset(97.66666666666667, 800, headerEnd)).toBe(800);
17
+ expect(pullRequestTabOffset(headerEnd - 1, 800, headerEnd)).toBe(headerEnd - 1);
18
+ });
19
+});
apps/mobile/src/features/pull-requests/pullRequestTabScroll.ts
+1
-1
@@ -3,5 +3,5 @@ export function pullRequestTabOffset(
3
saved: number | undefined,
4
headerEnd: number,
5
) {
6
- return current < headerEnd ? current : Math.max(headerEnd, saved ?? headerEnd);
6
+ return current < headerEnd - 0.5 ? current : Math.max(headerEnd, saved ?? headerEnd);
7
}
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+17
-72
@@ -33,7 +33,7 @@ import {
33
type CodexFeedbackSubmission,
34
type EnvironmentThreadStatus,
35
} from "@t3tools/client-runtime/state/threads";
36
-import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
36
+import { useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
37
import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills";
38
import type { LegendListRef } from "@legendapp/list/react-native";
39
import { NativeLayoutObserver } from "../../native/NativeLayoutObserver";
@@ -93,7 +93,6 @@ import {
93
View,
94
type GestureResponderEvent,
95
type LayoutChangeEvent,
96
- type ViewInstance,
96
} from "react-native";
97
import {
98
KeyboardController,
@@ -106,7 +105,6 @@ import Animated, {
105
FadeInDown,
106
FadeOut,
107
ReduceMotion,
109
- runOnJS,
108
useAnimatedReaction,
109
useAnimatedStyle,
110
useDerivedValue,
@@ -196,7 +194,7 @@ import {
194
ThreadComposer,
195
} from "./ThreadComposer";
196
import { ComposerPopoverHost } from "./ComposerPopoverHost";
199
-import { ThreadFeed, type ThreadFeedHandle, type ThreadFeedHistoryControls } from "./ThreadFeed";
197
+import { ThreadFeed, type ThreadFeedHistoryControls } from "./ThreadFeed";
198
import { WorkspaceMutationIdProvider } from "./WorkspaceMutationIdProvider";
199
import { useThreadTurnSubagents } from "./ThreadAgentsSheet";
200
import { ComposerQueuedEditBanner } from "./ComposerQueuedEdit";
@@ -204,7 +202,7 @@ import { useThreadQueuedCount } from "./ThreadQueueControl";
202
import { ThreadGuestShareBar } from "./ThreadGuestShareBar";
203
import { ThreadSideChatsRow } from "./ThreadSideChatsRow";
204
import type { ThreadContentPresentation } from "./threadContentPresentation";
207
-import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-live-follow";
205
+import { resolveThreadFeedSubmissionAnchor } from "./thread-feed-scroll-position";
206
import { useOpenLinkedThread } from "./useOpenLinkedThread";
207
import { useGlobalVoiceInput } from "../voice-input/VoiceInputProvider";
208
import type { OrchestrationV2ProviderSession } from "@t3tools/contracts";
@@ -498,7 +496,6 @@ function ThreadDetailBody(
496
const frame = requestAnimationFrame(() => composerEditorRef.current?.focus());
497
return () => cancelAnimationFrame(frame);
498
}, [editingRunId, composerEditorRef]);
501
- const composerOverlayRef = useRef<ViewInstance>(null);
499
const listRef = useRef<LegendListRef>(null);
500
const feedTouchStartRef = useRef<{ pageX: number; pageY: number } | null>(null);
501
// Aborted when this thread's body unmounts, so async work started for it
@@ -520,10 +517,9 @@ function ThreadDetailBody(
517
}, COMPOSER_HEIGHT_SETTLE_MS);
518
};
519
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
520
+ const [isAtEnd, setIsAtEnd] = useState(true);
521
const [sendingWithKeyboard, setSendingWithKeyboard] = useState(false);
522
if (sendingWithKeyboard && !isKeyboardVisible) setSendingWithKeyboard(false);
525
- const feedRef = useRef<ThreadFeedHandle>(null);
526
- const [endFollowEnabled, setEndFollowEnabled] = useState(true);
523
// Keep the bottom padding fixed while the keyboard animates. Changing it at
524
// keyboardDidHide makes the composer land low, then jump back above the safe area.
525
const bottomBarInset = useDuoBottomBarInset();
@@ -1014,17 +1010,13 @@ function ThreadDetailBody(
1010
? deviceType !== "duo-unfolded" || (composerOwnsKeyboard && !sidebarSearchActive)
1011
: !keyboardStateSuspect;
1012
const estimatedOverlayHeight = composerOverlapHeight;
1017
- // UIKit adds safe-area bottom to overlay insets; subtract here and include it in ThreadFeed scroll math.
1018
- const nativeInsetOvercount =
1019
- props.usesAutomaticContentInsets === true && Platform.OS === "ios" ? insets.bottom : 0;
1020
- const { contentInsetEndAdjustment, onComposerLayout } = useKeyboardChatComposerInset(
1021
- listRef,
1022
- composerOverlayRef,
1023
- Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
1024
- -nativeInsetOvercount,
1025
- // The composer already reports its animated height on each layout.
1026
- // Easing these samples again makes the feed trail behind it.
1027
- 0,
1013
+ const contentInsetEndAdjustment = useSharedValue(estimatedOverlayHeight);
1014
+ const onComposerLayout = useCallback(
1015
+ (event: LayoutChangeEvent) => {
1016
+ // The composer already animates its measured height on each layout.
1017
+ contentInsetEndAdjustment.set(event.nativeEvent.layout.height);
1018
+ },
1019
+ [contentInsetEndAdjustment],
1020
);
1021
// Android lays the screen out below its opaque header and reports a zero
1022
// header height, so the window height overstates the room by the header.
@@ -1116,47 +1108,14 @@ function ThreadDetailBody(
1108
const composerPopoverHeight = useSharedValue(0);
1109
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
1110
const reduceMotion = useReducedMotion();
1119
- // Repin timers fire after the render that scheduled them, so they read follow
1120
- // state from the ref the writers below keep in step with it.
1121
- const endFollowEnabledRef = useRef(true);
1122
- const overlayRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
1123
- const scheduleOverlayRepin = (delayMs: number) => {
1124
- if (overlayRepinTimerRef.current !== null) {
1125
- clearTimeout(overlayRepinTimerRef.current);
1126
- }
1127
- overlayRepinTimerRef.current = setTimeout(() => {
1128
- overlayRepinTimerRef.current = null;
1129
- const list = listRef.current;
1130
- if (!endFollowEnabledRef.current || !list || list.getState().isAtEnd) return;
1131
- void list.scrollToEnd({ animated: Platform.OS === "ios" && !reduceMotion });
1132
- }, delayMs);
1133
- };
1134
- // LegendList does not re-anchor short followed conversations when floating
1135
- // coverage changes after load. Re-pin each time it settles at a new value;
1136
- // the repin checks follow state so a user who scrolled up stays put.
1137
- const settledFloatingCoverageRef = useRef(0);
1138
- const repinAfterCoverageSettles = (coverage: number) => {
1139
- if (coverage === settledFloatingCoverageRef.current) return;
1140
- settledFloatingCoverageRef.current = coverage;
1141
- scheduleOverlayRepin(50);
1142
- };
1111
const floatingCoverageTarget = showFloatingStatus ? FLOATING_WORKING_CONTROL_COVERAGE : 0;
1112
const floatingControlCoverage = useDerivedValue(
1145
- () =>
1146
- withTiming(
1147
- floatingCoverageTarget,
1148
- { duration: 180, reduceMotion: ReduceMotion.System },
1149
- (finished) => {
1150
- if (finished) runOnJS(repinAfterCoverageSettles)(floatingCoverageTarget);
1151
- },
1152
- ),
1113
+ () => withTiming(floatingCoverageTarget, { duration: 180, reduceMotion: ReduceMotion.System }),
1114
[floatingCoverageTarget],
1115
);
1116
const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
1117
const questionStatusSpace = useAnimatedStyle(() => ({ height: floatingControlCoverage.value }));
1157
- const combinedContentInsetEndAdjustment = useSharedValue(
1158
- Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
1159
- );
1118
+ const combinedContentInsetEndAdjustment = useSharedValue(estimatedOverlayHeight);
1119
useAnimatedReaction(
1120
() =>
1121
questionInFlow
@@ -1185,10 +1144,6 @@ function ThreadDetailBody(
1144
),
1145
[userInputCoverageApplies],
1146
);
1188
- const handleEndFollowEnabledChange = (enabled: boolean) => {
1189
- endFollowEnabledRef.current = enabled;
1190
- setEndFollowEnabled(enabled);
1191
- };
1147
// A jump this thread never reached lets go when it closes.
1148
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- aborts the thread scope, clears its timers and ends a pending message jump when the thread changes
1149
useEffect(() => {
@@ -1196,7 +1151,6 @@ function ThreadDetailBody(
1151
const scope = threadScope.current;
1152
return () => {
1153
scope.abort();
1199
- if (overlayRepinTimerRef.current !== null) clearTimeout(overlayRepinTimerRef.current);
1154
if (composerHeightSettle.current !== null) clearTimeout(composerHeightSettle.current);
1155
finishThreadMessageJump(selectedThreadKey);
1156
};
@@ -1207,11 +1161,9 @@ function ThreadDetailBody(
1161
}
1162
if (userInputCollapsed) {
1163
setUserInputToggle({ requestId: activeUserInputRequestId, collapsed: false });
1210
- if (!questionInFlow) scheduleOverlayRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
1164
} else {
1165
Keyboard.dismiss();
1166
setUserInputToggle({ requestId: activeUserInputRequestId, collapsed: true });
1214
- if (!questionInFlow) scheduleOverlayRepin(60);
1167
}
1168
};
1169
const showContent = props.showContent ?? true;
@@ -1345,7 +1297,6 @@ function ThreadDetailBody(
1297
queuedMessageCount: props.selectedThreadQueueCount,
1298
deliveryDeferred: props.connectionStateLabel !== "connected",
1299
});
1348
- feedRef.current?.resetEndFollow();
1300
setAnchorMessageId(nextAnchorMessageId);
1301
if (!dismissingKeyboard) composerEditorRef.current?.blur();
1302
const followSubmission =
@@ -1358,7 +1309,7 @@ function ThreadDetailBody(
1309
// Scrolling freezes the keyboard inset, so wait until dismissal has removed it.
1310
void KeyboardController.dismiss()
1311
.then(() => {
1361
- if (!followSubmission || scope.aborted || !endFollowEnabledRef.current) return;
1312
+ if (!followSubmission || scope.aborted) return;
1313
return scrollMessageToEnd({ animated: !reduceMotion, closeKeyboard: false });
1314
})
1315
.catch(() => {
@@ -1412,8 +1363,7 @@ function ThreadDetailBody(
1363
});
1364
};
1365
1415
- const showScrollToEndButton =
1416
- !props.draftMode && contentPresentationKind === "ready" && !endFollowEnabled;
1366
+ const showScrollToEndButton = !props.draftMode && contentPresentationKind === "ready" && !isAtEnd;
1367
const { themeAppearance } = useAppearancePreferences();
1368
const isDarkMode = themeAppearance === "dark";
1369
@@ -1515,7 +1465,6 @@ function ThreadDetailBody(
1465
anchorMessageId={anchorMessageId}
1466
jumpToMessageId={jumpMessageLoaded ? jumpMessageId : null}
1467
onJumpedToMessage={() => finishThreadMessageJump(selectedThreadKey)}
1518
- ref={feedRef}
1468
contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
1469
keyboardOffset={composerKeyboardOffset}
1470
sendingWithKeyboard={sendingWithKeyboard}
@@ -1533,7 +1482,7 @@ function ThreadDetailBody(
1482
layoutVariant={layoutVariant}
1483
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
1484
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
1536
- onEndFollowEnabledChange={handleEndFollowEnabledChange}
1485
+ onIsAtEndChange={setIsAtEnd}
1486
skills={selectedProviderSkills}
1487
onUseArtifactTemplate={handleUseArtifactTemplate}
1488
/>
@@ -1603,11 +1552,7 @@ function ThreadDetailBody(
1552
{/* No paddingTop here: the overlay's measured height becomes the
1553
list's bottom inset, so any padding above the pill/composer
1554
pushes the resting content floor up by the same amount. */}
1606
- <View
1607
- ref={composerOverlayRef}
1608
- onLayout={handleComposerOverlayLayout}
1609
- className="w-full"
1610
- >
1555
+ <View onLayout={handleComposerOverlayLayout} className="w-full">
1556
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
1557
<FloatingWorkingControl
1558
colorScheme={isDarkMode ? "dark" : "light"}
apps/mobile/src/features/threads/ThreadFeed.tsx
+76
-323
@@ -105,7 +105,6 @@ import {
105
useCallback,
106
useEffect,
107
useEffectEvent,
108
- useImperativeHandle,
108
useLayoutEffect,
109
useMemo,
110
useRef,
@@ -113,9 +112,7 @@ import {
112
useSyncExternalStore,
113
useId,
114
type ComponentPropsWithRef,
116
- type ComponentRef,
115
type ReactNode,
118
- type Ref,
116
type RefObject,
117
} from "react";
118
import {
@@ -146,7 +143,6 @@ import { ThreadInlineFilePreview } from "./ThreadInlineFilePreview";
143
import { flattenThemeColor } from "../../lib/mobileTheme";
144
import { PresentationSource } from "../../components/ui/NativePresentation";
145
import { NativeScrollViewMarker } from "../../native/NativeScrollViewMarker";
149
-import { useSafeAreaInsets } from "react-native-safe-area-context";
146
import Animated, { FadeIn, FadeInDown, type SharedValue } from "react-native-reanimated";
147
import { useUniwindTheme } from "../../lib/useUniwindTheme";
148
import { FONT_FAMILIES } from "../../lib/fontFamilies";
@@ -212,15 +208,7 @@ import {
208
messageFoldRunId,
209
} from "../../lib/threadActivity";
210
import type { ThreadContentPresentation } from "./threadContentPresentation";
215
-import {
216
- resolveThreadFeedLiveFollow,
217
- resolveThreadFeedReflowAnchor,
218
- resolveThreadFeedReflowOffset,
219
- resolveThreadFeedReflowScroll,
220
- type ThreadFeedLiveFollowEvent,
221
- type ThreadFeedReflowAnchor,
222
- type ThreadWorkGroupScrollPosition,
223
-} from "./thread-feed-live-follow";
211
+import { type ThreadWorkGroupScrollPosition } from "./thread-feed-scroll-position";
212
import {
213
collapsedWorkLogHeight,
214
ThreadDisclosureChevron,
@@ -298,16 +286,8 @@ const WIDE_MARKDOWN_BLOCK_OPTIONS = {
286
287
const TURN_FOLD_HEIGHT = 42;
288
const FEED_PADDING_TOP = 12;
301
-// Rows re-measure within a commit or two of a width change. LegendList also defers imperative
302
-// scrolls for 100ms after it compensates a size change, and a deferred restore could land
303
-// under a drag that starts meanwhile.
304
-const FEED_REFLOW_SETTLE_MS = 200;
305
-// A fold resizes the feed in steps about 200ms apart. Holding the place taken at the first step
306
-// across all of them keeps a passing moment off the end from re-anchoring the rest to a row.
307
-const FEED_REFLOW_HOLD_MS = 600;
289
const USER_BUBBLE_HORIZONTAL_PADDING = 3.5 * 3.5;
290
const ASSISTANT_ROW_HORIZONTAL_PADDING = 3.5;
310
-
291
// Virtualization remounts old rows; only newly created content should replay an entrance.
292
const FRESH_ENTRY_WINDOW_MS = 3_000;
293
function isFreshTimestamp(input: string): boolean {
@@ -324,11 +304,6 @@ export interface ThreadFeedHistoryControls {
304
readonly onLoadThrough: (entryId: string) => void;
305
}
306
327
-export interface ThreadFeedHandle {
328
- /** A send re-arms following the end, whatever the reader had scrolled to. */
329
- readonly resetEndFollow: () => void;
330
-}
331
-
307
export interface ThreadFeedProps {
308
readonly toolCallVisibility?: ToolCallVisibility;
309
readonly worktreeSetup?: WorktreeSetupCardProps | null;
@@ -366,7 +341,7 @@ export interface ThreadFeedProps {
341
readonly layoutVariant?: LayoutVariant;
342
readonly usesAutomaticContentInsets?: boolean;
343
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
369
- readonly onEndFollowEnabledChange?: (enabled: boolean) => void;
344
+ readonly onIsAtEndChange?: (isAtEnd: boolean) => void;
345
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
346
readonly onUseArtifactTemplate?: (template: CodexArtifactTemplate) => void;
347
}
@@ -2303,7 +2278,6 @@ function renderFeedEntry(
2278
2279
return (
2280
<ThreadWorkLog
2306
- key={`${entry.id}:${props.workRowSizing.textSizeKey}`}
2281
activities={entry.activities}
2282
continuesWorkLog={entry.continuesWorkLog}
2283
environmentId={props.environmentId}
@@ -2651,11 +2625,13 @@ function DisclosureRow(props: {
2625
);
2626
}
2627
2654
-export const ThreadFeed = memo(function ThreadFeed({
2655
- ref,
2656
- ...props
2657
-}: ThreadFeedProps & { readonly ref?: Ref<ThreadFeedHandle> }) {
2658
- const { listRef, onEndFollowEnabledChange, onHeaderMaterialVisibilityChange } = props;
2628
+const THREAD_FEED_MAINTAIN_SCROLL_AT_END = {
2629
+ animated: false,
2630
+ on: { dataChange: true, itemLayout: true, layout: true },
2631
+} as const;
2632
+
2633
+export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2634
+ const { listRef, onIsAtEndChange, onHeaderMaterialVisibilityChange } = props;
2635
const workflowOpening = useWorkflowOpening(props.detailRef);
2636
const guestShare = useThreadGuestShare(props.detailRef);
2637
const deviceType = useDeviceType();
@@ -2678,10 +2654,6 @@ export const ThreadFeed = memo(function ThreadFeed({
2654
);
2655
const { themeAppearance } = useAppearancePreferences();
2656
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
2681
- const disclosureSettleFrameRef = useRef<number | null>(null);
2682
- const disclosureSettleSecondFrameRef = useRef<number | null>(null);
2683
- const disclosureAnchorKeyRef = useRef<string | null>(null);
2684
- const userScrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
2657
const headerMaterialVisibleRef = useRef(false);
2658
const { width: windowWidth, fontScale } = useWindowDimensions();
2659
const { appearance } = useAppearancePreferences();
@@ -2695,48 +2667,12 @@ export const ThreadFeed = memo(function ThreadFeed({
2667
const viewportWidth =
2668
settledPaneWidth !== null ? Math.round(settledPaneWidth) : measuredViewportWidth;
2669
const [viewportHeight, setViewportHeight] = useState(0);
2698
- const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
2670
const [disclosureLayout, setDisclosureLayout] = useState<DisclosureLayout | null>(null);
2671
const disclosureMotionRef = useRef<DisclosureLayout | null>(null);
2672
const disclosureMotionTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
2673
+ const disclosureSettleFrameRef = useRef<number | null>(null);
2674
+ const disclosureSettleSecondFrameRef = useRef<number | null>(null);
2675
const reduceMotion = useReduceMotionEnabled();
2703
- const headerEndRef = useRef<ComponentRef<typeof View>>(null);
2704
- const lastFeedId = props.feed.at(-1)?.id;
2705
- const [disclosureGap, setDisclosureGap] = useState<{
2706
- space: number;
2707
- tail: typeof lastFeedId;
2708
- } | null>(null);
2709
- const disclosureTopSpace = disclosureGap?.tail === lastFeedId ? (disclosureGap?.space ?? 0) : 0;
2710
- // LegendList's geometric follow threshold can reclaim users reading history when streamed rows grow.
2711
- const [endFollowEnabled, setEndFollowEnabled] = useState(true);
2712
- const endFollowEnabledRef = useRef(true);
2713
- // Only user scrolls from drag through momentum break follow; ignore MVCP and programmatic adjustments.
2714
- const userScrollSessionRef = useRef(false);
2715
- const setEndFollow = (enabled: boolean) => {
2716
- if (endFollowEnabledRef.current === enabled) {
2717
- return;
2718
- }
2719
- endFollowEnabledRef.current = enabled;
2720
- setEndFollowEnabled(enabled);
2721
- onEndFollowEnabledChange?.(enabled);
2722
- };
2723
- const transitionEndFollow = (event: ThreadFeedLiveFollowEvent) => {
2724
- setEndFollow(resolveThreadFeedLiveFollow(endFollowEnabledRef.current, event));
2725
- };
2726
- // Capture the reader's anchor before width reflow; LegendList thresholds see only new geometry.
2727
- // iOS preserves it during re-measures. Android restores after because following disables MVCP.
2728
- // undefined means no reflow; null means reflow with nothing to restore.
2729
- const reflowAnchorRef = useRef<ThreadFeedReflowAnchor | null | undefined>(undefined);
2730
- const reflowAnchorsSizeChanges = Platform.OS === "ios";
2731
- const [reflowFollowsEnd, setReflowFollowsEnd] = useState(false);
2732
- const reflowSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
2733
- const listHeaderSizeRef = useRef(0);
2734
- const loadedListKeyRef = useRef<string | null>(null);
2735
- const cancelReflow = () => {
2736
- if (reflowAnchorRef.current === undefined) return;
2737
- reflowAnchorRef.current = undefined;
2738
- setReflowFollowsEnd(false);
2739
- };
2676
const [interactionState, setInteractionState] = useState<{
2677
readonly copiedRowId: string | null;
2678
readonly expandedWorkGroups: Record<string, boolean>;
@@ -2809,7 +2745,6 @@ export const ThreadFeed = memo(function ThreadFeed({
2745
const userBubbleMaxWidth = contentWidth * 0.85;
2746
const markdownContentWidth = Math.max(0, contentWidth - ASSISTANT_ROW_HORIZONTAL_PADDING * 2);
2747
const reviewCommentBubbleWidth = Math.min(Math.max(280, contentWidth * 0.85), contentWidth);
2812
- const insets = useSafeAreaInsets();
2748
const barInset = useBarInset();
2749
const topContentInset = props.contentTopInset ?? barInset;
2750
const bottomContentInset = props.contentBottomInset ?? 18;
@@ -2820,7 +2755,6 @@ export const ThreadFeed = memo(function ThreadFeed({
2755
usesNativeAutomaticInsets,
2756
bottomContentInset,
2757
});
2823
- // LegendList cannot see UIKit's adjustedContentInset; include header height in anchor offsets.
2758
const anchorTopInset = usesNativeAutomaticInsets ? barInset : topContentInset;
2759
2760
const theme = useUniwindTheme();
@@ -3240,77 +3174,40 @@ export const ThreadFeed = memo(function ThreadFeed({
3174
headerMaterialVisibleRef.current = visible;
3175
onHeaderMaterialVisibilityChange?.(visible);
3176
};
3177
+ const handleMetricsChange = () => {
3178
+ const state = listRef.current?.getState();
3179
+ if (state) onIsAtEndChange?.(state.isAtEnd);
3180
+ };
3181
const handleScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
3182
reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6);
3245
- // Re-arm follow only at the actual end; the broader threshold can reclaim upward drags during streaming.
3246
- const listState = listRef.current?.getState();
3247
- if (listState) {
3248
- transitionEndFollow({
3249
- type: "scroll",
3250
- isAtEnd: listState.isAtEnd,
3251
- userScrollSessionActive: userScrollSessionRef.current,
3252
- });
3253
- }
3254
- };
3255
- const clearUserScrollSettle = () => {
3256
- if (userScrollSettleTimerRef.current !== null) {
3257
- clearTimeout(userScrollSettleTimerRef.current);
3258
- userScrollSettleTimerRef.current = null;
3259
- }
3260
- };
3261
- const handleScrollBeginDrag = () => {
3262
- clearUserScrollSettle();
3263
- userScrollSessionRef.current = true;
3264
- cancelReflow();
3265
- // Pause before the first scroll event. Otherwise a stream update can run
3266
- // maintainScrollAtEnd between touch-down and the drag leaving its threshold.
3267
- transitionEndFollow({ type: "user-scroll-begin" });
3268
- };
3269
- const finishUserScroll = (releaseIsAtEnd?: boolean) => {
3270
- clearUserScrollSettle();
3271
- const userScrollSessionActive = userScrollSessionRef.current;
3272
- userScrollSessionRef.current = false;
3273
- transitionEndFollow({
3274
- type: "user-scroll-end",
3275
- // Without momentum, retain release position; stream growth during detection must not disable follow.
3276
- isAtEnd: releaseIsAtEnd ?? listRef.current?.getState().isAtEnd ?? false,
3277
- userScrollSessionActive,
3278
- });
3279
- };
3280
- // Zero release velocity may still produce momentum; wait for native detection before ending the session.
3281
- const handleScrollEndDrag = () => {
3282
- clearUserScrollSettle();
3283
- const releaseIsAtEnd = listRef.current?.getState().isAtEnd ?? false;
3284
- userScrollSettleTimerRef.current = setTimeout(() => finishUserScroll(releaseIsAtEnd), 160);
3183
+ handleMetricsChange();
3184
};
3286
- const handleMomentumScrollBegin = () => {
3287
- if (userScrollSessionRef.current) {
3288
- clearUserScrollSettle();
3289
- }
3290
- };
3291
- const handleMomentumScrollEnd = () => {
3292
- finishUserScroll();
3293
- };
3294
-
3185
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the list's end state to report it to the parent
3186
+ useLayoutEffect(() => {
3187
+ const state = listRef.current?.getState();
3188
+ if (!state) return;
3189
+ handleMetricsChange();
3190
+ const stops = [
3191
+ state.listen("isAtEnd", handleMetricsChange),
3192
+ state.listen("totalSize", handleMetricsChange),
3193
+ state.listen("footerSize", handleMetricsChange),
3194
+ state.listen("headerSize", handleMetricsChange),
3195
+ ];
3196
+ return () => {
3197
+ for (const stop of stops) stop();
3198
+ };
3199
+ }, [listRef, handleMetricsChange]);
3200
const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId);
3296
- const workGroupScrollPositions = new Map<string, ThreadWorkGroupScrollPosition>();
3297
- // ThreadDetailScreen remounts the feed per thread, so only a send resets following.
3298
- useImperativeHandle(ref, () => ({
3299
- resetEndFollow: () => {
3300
- clearUserScrollSettle();
3301
- userScrollSessionRef.current = false;
3302
- setDisclosureGap(null);
3303
- cancelReflow();
3304
- transitionEndFollow({ type: "reset" });
3305
- },
3306
- }));
3201
+ const [workGroupScrollPositions] = useState(
3202
+ () => new Map<string, ThreadWorkGroupScrollPosition>(),
3203
+ );
3204
3205
// Opening at a message: once the filled list has loaded, the render that sees
3206
// the jump unfolds a run hiding the message and stops following the end, so
3207
// the committed list holds the target row with end maintenance off.
3208
const [loadedListKey, setLoadedListKey] = useState<string | null>(null);
3209
const { jumpToMessageId } = props;
3313
- const jumpReady = !!jumpToMessageId && loadedListKey === `${feedThreadKey}:filled`;
3210
+ const jumpReady = !!jumpToMessageId && loadedListKey === feedThreadKey;
3211
if (jumpReady && revealedMessageId !== jumpToMessageId) {
3212
setInteractionState((current) => ({ ...current, revealedMessageId: jumpToMessageId }));
3213
}
@@ -3338,11 +3235,6 @@ export const ThreadFeed = memo(function ThreadFeed({
3235
setupAnchorIndex:
3236
props.worktreeSetup || props.setupWorkingStartedAt ? setupAnchorIndex : undefined,
3237
});
3341
- // The empty↔filled key below remounts the list and resets its imperative
3342
- // content-inset override. Seed each fresh instance as it attaches with the
3343
- // current overlay height before the scroll integration's next reaction;
3344
- // on Android the declarative contentInset floor covers this same window.
3345
- const listMountKey = `${feedThreadKey}:${presentedFeed.some((entry) => entry.type !== "thinking") ? "filled" : "empty"}`;
3238
const { contentInsetEndAdjustment } = props;
3239
const attachList = (list: LegendListRef | null) => {
3240
listRef.current = list;
@@ -3352,84 +3244,29 @@ export const ThreadFeed = memo(function ThreadFeed({
3244
const jumpIndex = jumpReady
3245
? presentedFeed.findIndex((entry) => entry.type === "message" && entry.id === jumpToMessageId)
3246
: null;
3355
- const followsEnd = endFollowEnabled && !jumpReady;
3247
const landJump = useEffectEvent((index: number) => {
3357
- if (index !== -1) {
3358
- setEndFollow(false);
3359
- void listRef.current?.scrollToIndex({ index, viewPosition: 0.2, animated: false });
3360
- }
3361
- props.onJumpedToMessage?.();
3248
+ const list = listRef.current;
3249
+ if (!list) return;
3250
+ let cancelled = false;
3251
+ const positioning =
3252
+ index === -1 ? undefined : list.scrollToIndex({ index, viewPosition: 0.2, animated: false });
3253
+ void Promise.resolve(positioning).then(() => {
3254
+ if (!cancelled && listRef.current === list) props.onJumpedToMessage?.();
3255
+ });
3256
+ return () => {
3257
+ cancelled = true;
3258
+ };
3259
});
3363
- // Z: a native list scroll after the commit that rendered its target row. The
3364
- // row is often already measured, so no LegendList callback fires for that
3365
- // commit, and setEndFollow notifies the parent, so it can't run during render.
3260
+ // A jump can unfold a run; keep end maintenance off until its position settles.
3261
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the native list to the jump target after the commit that rendered its row
3262
useEffect(() => {
3368
- if (jumpIndex !== null) landJump(jumpIndex);
3263
+ if (jumpIndex !== null) return landJump(jumpIndex);
3264
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Jumping to a different message whose row index is unchanged must still land the jump.
3265
}, [jumpToMessageId, jumpIndex]);
3266
3372
- const reflowLayout = () => ({
3373
- rowsTop: FEED_PADDING_TOP + listHeaderSizeRef.current,
3374
- headerInset: anchorTopInset,
3375
- });
3376
- const settleReflow = () => {
3377
- reflowSettleTimerRef.current = null;
3378
- const anchor = reflowAnchorRef.current;
3379
- cancelReflow();
3380
- const list = listRef.current;
3381
- if (reflowAnchorsSizeChanges || !anchor || anchor === "end" || !list) return;
3382
- if (userScrollSessionRef.current) return;
3383
- if (loadedListKeyRef.current !== listMountKey) return;
3384
- const target = resolveThreadFeedReflowScroll(anchor, list.getState(), reflowLayout());
3385
- if (target) void list.scrollToIndex({ ...target, viewPosition: 0, animated: false });
3386
- };
3387
- const beginReflow = () => {
3388
- // Until the list loads, its own initial end positioning owns the offset.
3389
- if (loadedListKeyRef.current !== listMountKey) return;
3390
- if (reflowAnchorRef.current === undefined) {
3391
- const listState = listRef.current?.getState();
3392
- const anchor =
3393
- listState && !userScrollSessionRef.current
3394
- ? resolveThreadFeedReflowAnchor(listState, reflowLayout(), endFollowEnabledRef.current)
3395
- : null;
3396
- reflowAnchorRef.current = anchor;
3397
- if (anchor === "end" && !reflowAnchorsSizeChanges) {
3398
- // The list may already have judged the first new sizes against its own threshold, so
3399
- // pin the end once; the lifted threshold keeps it there as later rows re-measure.
3400
- setReflowFollowsEnd(true);
3401
- void listRef.current?.scrollToEnd({ animated: false });
3402
- }
3403
- }
3404
- // Every re-measure restarts the countdown.
3405
- if (reflowSettleTimerRef.current !== null) clearTimeout(reflowSettleTimerRef.current);
3406
- reflowSettleTimerRef.current = setTimeout(
3407
- settleReflow,
3408
- reflowAnchorsSizeChanges ? FEED_REFLOW_HOLD_MS : FEED_REFLOW_SETTLE_MS,
3409
- );
3410
- };
3411
-
3412
- const holdReflowAnchor = () => {
3413
- const anchor = reflowAnchorRef.current;
3414
- if (anchor === "end") return Number.POSITIVE_INFINITY;
3415
- const list = listRef.current;
3416
- return anchor && list
3417
- ? resolveThreadFeedReflowOffset(anchor, list.getState(), reflowLayout())
3418
- : undefined;
3419
- };
3420
-
3267
const handleViewportLayout = (event: LayoutChangeEvent) => {
3268
const nextWidth = Math.round(event.nativeEvent.layout.width);
3269
const nextHeight = Math.round(event.nativeEvent.layout.height);
3424
- // A native resize re-wraps the rows before JS hears of it. This event reaches JS ahead
3425
- // of the row measurements it caused, since layout events are sent parent first.
3426
- if (Math.abs(measuredViewportWidth - nextWidth) > 1) beginReflow();
3427
- if (
3428
- Math.abs(measuredViewportWidth - nextWidth) > 1 ||
3429
- Math.abs(viewportHeight - nextHeight) > 1
3430
- ) {
3431
- setDisclosureGap(null);
3432
- }
3270
setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current));
3271
setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
3272
};
@@ -3474,12 +3311,9 @@ export const ThreadFeed = memo(function ThreadFeed({
3311
}
3312
}
3313
3477
- // Timers and frames the feed schedules die with it.
3478
- // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the feed's scroll, reflow and copy timers and disclosure animation frames on unmount
3314
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears copy feedback and disclosure animation timers and frames on unmount
3315
useEffect(
3316
() => () => {
3481
- if (userScrollSettleTimerRef.current !== null) clearTimeout(userScrollSettleTimerRef.current);
3482
- if (reflowSettleTimerRef.current !== null) clearTimeout(reflowSettleTimerRef.current);
3317
if (copyFeedbackTimeoutRef.current) clearTimeout(copyFeedbackTimeoutRef.current);
3318
if (disclosureMotionTimer.current !== null) clearTimeout(disclosureMotionTimer.current);
3319
if (disclosureSettleFrameRef.current !== null) {
@@ -3501,16 +3335,6 @@ export const ThreadFeed = memo(function ThreadFeed({
3335
}
3336
disclosureSettleFrameRef.current = requestAnimationFrame(() => {
3337
disclosureSettleSecondFrameRef.current = requestAnimationFrame(() => {
3504
- const listState = listRef.current?.getState();
3505
- if (listState) {
3506
- transitionEndFollow({
3507
- type: "disclosure-settled",
3508
- isAtEnd: listState.isAtEnd,
3509
- userScrollSessionActive: userScrollSessionRef.current,
3510
- });
3511
- }
3512
- disclosureAnchorKeyRef.current = null;
3513
- setDisclosureToggleSettling(false);
3338
const motion = disclosureMotionRef.current;
3339
if (motion && !motion.playing) {
3340
const playing = { ...motion, playing: true };
@@ -3531,12 +3355,14 @@ export const ThreadFeed = memo(function ThreadFeed({
3355
});
3356
};
3357
3534
- // The quiet-frame countdown's first frame lands after the disclosure's commit.
3535
- // Every measured item-size change restarts it, so end maintenance cannot
3536
- // wake between the data mutation and LegendList's final layout correction.
3537
- const suspendEndScrollMaintenanceForDisclosure = (anchorKey: string | null) => {
3538
- cancelReflow();
3358
+ const preserveDisclosurePosition = (anchorKey: string | null) => {
3359
const list = listRef.current;
3360
+ const working = props.activeWorkStartedAt !== null || props.runlessWorkActive === true;
3361
+ // An anchor ends end-follow until the reader scrolls, so a streaming turn keeps the live end.
3362
+ if (anchorKey !== null && list && !(working && list.getState().isFollowingEnd)) {
3363
+ list.cancelScroll();
3364
+ list.anchorVisibleContent({ key: anchorKey });
3365
+ }
3366
if (list && anchorKey && !reduceMotion) {
3367
const state = list.getState();
3368
const anchorIndex = state.indexByKey(anchorKey);
@@ -3566,37 +3392,17 @@ export const ThreadFeed = memo(function ThreadFeed({
3392
if (disclosureMotionTimer.current !== null) clearTimeout(disclosureMotionTimer.current);
3393
disclosureMotionRef.current = motion;
3394
setDisclosureLayout(motion);
3395
+ settleDisclosureAfterLayout();
3396
}
3397
}
3571
- // Keep a short feed's bottom-alignment gap through collapse too; replacing it mid-frame moves the tap target.
3572
- const first = list?.getState().elementAtIndex(0);
3573
- if (first && headerEndRef.current) {
3574
- const gap =
3575
- first.getBoundingClientRect().top - headerEndRef.current.getBoundingClientRect().bottom;
3576
- if (gap > 1) setDisclosureGap({ space: disclosureTopSpace + gap, tail: lastFeedId });
3577
- }
3578
- disclosureAnchorKeyRef.current = anchorKey;
3579
- setDisclosureToggleSettling(true);
3580
- settleDisclosureAfterLayout();
3398
};
3399
3400
const handleItemSizeChanged = () => {
3584
- if (disclosureAnchorKeyRef.current !== null) {
3401
+ if (disclosureMotionRef.current && !disclosureMotionRef.current.playing) {
3402
settleDisclosureAfterLayout();
3403
}
3404
};
3405
3589
- const shouldRestoreVisibleContentPosition = (entry: ThreadFeedRow) => {
3590
- const disclosureAnchorKey = disclosureAnchorKeyRef.current;
3591
- return disclosureAnchorKey === null || entry.id === disclosureAnchorKey;
3592
- };
3593
-
3594
- const maintainVisibleContentPosition = {
3595
- data: true,
3596
- size: true,
3597
- shouldRestorePosition: shouldRestoreVisibleContentPosition,
3598
- };
3599
-
3406
const onCopyWorkRow = (rowId: string, value: string) => {
3407
copyTextWithHaptic(value, {
3408
target: "thread-work-row",
@@ -3615,7 +3421,7 @@ export const ThreadFeed = memo(function ThreadFeed({
3421
};
3422
3423
const onToggleWorkGroup = (groupId: string, anchorKey?: string) => {
3618
- suspendEndScrollMaintenanceForDisclosure(anchorKey ?? `work-toggle:${groupId}`);
3424
+ preserveDisclosurePosition(anchorKey ?? `work-toggle:${groupId}`);
3425
setInteractionState((current) => ({
3426
...current,
3427
expandedWorkGroups: {
@@ -3627,7 +3433,7 @@ export const ThreadFeed = memo(function ThreadFeed({
3433
3434
// Lone rows share their group's disclosure state so opened details survive a second call joining.
3435
const onToggleWorkRow = (rowId: string, anchorKey?: string, groupId?: string) => {
3630
- suspendEndScrollMaintenanceForDisclosure(anchorKey ?? null);
3436
+ preserveDisclosurePosition(anchorKey ?? null);
3437
setInteractionState((current) => {
3438
const expanded = !(current.expandedWorkRows[rowId] ?? false);
3439
return {
@@ -3641,7 +3447,7 @@ export const ThreadFeed = memo(function ThreadFeed({
3447
};
3448
3449
const onToggleTurnFold = (runId: RunId) => {
3644
- suspendEndScrollMaintenanceForDisclosure(`run-fold:${runId}`);
3450
+ preserveDisclosurePosition(`run-fold:${runId}`);
3451
setInteractionState((current) => {
3452
const next = new Set(current.expandedTurnIds);
3453
if (next.has(runId)) {
@@ -3705,17 +3511,15 @@ export const ThreadFeed = memo(function ThreadFeed({
3511
const { textSizeKey } = workRowSizing;
3512
const hasHtmlRenders = presentedFeed.some((entry) => entry.type === "html-render");
3513
const previousRowGeometry = useRef({ textSizeKey, contentWidth });
3708
- // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears LegendList size caches and starts a reflow after the commit that brings new row geometry
3514
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears LegendList size caches after the commit that brings new row geometry
3515
useLayoutEffect(() => {
3516
const previous = previousRowGeometry.current;
3517
if (previous.textSizeKey === textSizeKey && previous.contentWidth === contentWidth) return;
3518
previousRowGeometry.current = { textSizeKey, contentWidth };
3713
- // Rows re-rendered at this width are measured in the next commit, after this effect.
3714
- if (previous.contentWidth !== contentWidth) beginReflow();
3519
if (previous.textSizeKey !== textSizeKey || hasHtmlRenders) {
3520
listRef.current?.clearCaches({ mode: "sizes" });
3521
}
3718
- }, [textSizeKey, contentWidth, hasHtmlRenders, beginReflow, listRef]);
3522
+ }, [textSizeKey, contentWidth, hasHtmlRenders, listRef]);
3523
3524
const renderItem = (info: { item: GroupedThreadFeedRow; index: number }) => (
3525
<DisclosureRow
@@ -3827,62 +3631,21 @@ export const ThreadFeed = memo(function ThreadFeed({
3631
{/* oxlint-disable-next-line t3code/require-registered-list-scroll -- ThreadFeedScrollView is passed through the iOS-only spread below; the prop rejects undefined. */}
3632
<KeyboardAwareLegendList
3633
ref={attachList}
3830
- // LegendList cannot see adjustedContentInset; remount so initial positioning waits for UIKit attachment.
3831
- key={listMountKey}
3634
+ dataKey={feedThreadKey}
3635
style={{ flex: 1 }}
3636
// RN 0.81+ drops inset-area touches (facebook/react-native#54123), making blank post-send space unscrollable.
3637
applyWorkaroundForContentInsetHitTestBug
3638
{...(Platform.OS === "ios" ? { ScrollViewComponent: ThreadFeedScrollView } : {})}
3836
- // Horizontal Duo reservations are already included in the row padding.
3837
- contentInsetAdjustmentBehavior={
3838
- usesNativeAutomaticInsets
3839
- ? duoColumns && splitLayout
3840
- ? "scrollableAxes"
3841
- : "automatic"
3842
- : "never"
3843
- }
3639
+ contentInsetAdjustmentBehavior="never"
3640
automaticallyAdjustsScrollIndicatorInsets={usesNativeAutomaticInsets}
3845
- {...(usesNativeAutomaticInsets
3846
- ? {
3847
- // Manual contentInset zeroes UIKit's automatic header inset and scroll-edge region; derive it from the transparent header.
3848
- scrollIndicatorInsets: { top: 0, left: 0, right: 0, bottom: 0 },
3849
- }
3850
- : { scrollIndicatorInsets: { top: topContentInset, bottom: 0 } })}
3641
+ scrollIndicatorInsets={{ top: anchorTopInset, bottom: 0 }}
3642
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
3852
- // Patched LegendList math must allow -headerInset so short-content end scrolls rest below the header.
3853
- contentInsetStartAdjustment={usesNativeAutomaticInsets ? anchorTopInset : 0}
3643
contentInsetEndAdjustment={props.contentInsetEndAdjustment}
3644
keyboardOffset={props.keyboardOffset}
3856
- // UIKit adds the safe-area bottom to raw contentInset; ThreadDetailScreen under-reports it.
3857
- // Include that extra inset in LegendList's scroll math so end scrolls reach the resting offset.
3858
- contentInsetEndStaticAdjustment={usesNativeAutomaticInsets ? insets.bottom : 0}
3859
- // Seed composer height until keyboard integration reports it, or Android's initial end scroll runs too early.
3860
- {...(initialContentInset ? { contentInset: initialContentInset } : {})}
3861
- adjustedInsetCompensation={usesNativeAutomaticInsets ? insets.bottom : 0}
3645
+ contentInset={usesNativeAutomaticInsets ? { top: anchorTopInset } : initialContentInset}
3646
freeze={props.freeze}
3863
- // Follow the measured end immediately; animating estimates races row measurement on acknowledgement.
3864
- maintainScrollAtEnd={
3865
- disclosureToggleSettling || props.sendingWithKeyboard || !followsEnd
3866
- ? false
3867
- : {
3868
- animated: false,
3869
- on: {
3870
- dataChange: true,
3871
- itemLayout: true,
3872
- layout: true,
3873
- },
3874
- }
3875
- }
3876
- // A reflow grows every visible row at once, well past the near-end threshold
3877
- // that otherwise lets a status-bar tap leave the end.
3878
- maintainScrollAtEndThreshold={reflowFollowsEnd ? Number.POSITIVE_INFINITY : undefined}
3879
- sizeChangeAnchor={reflowAnchorsSizeChanges ? holdReflowAnchor : undefined}
3880
- maintainVisibleContentPosition={
3881
- (followsEnd && !disclosureToggleSettling) ||
3882
- (disclosureToggleSettling && disclosureTopSpace > 0)
3883
- ? false
3884
- : maintainVisibleContentPosition
3885
- }
3647
+ maintainScrollAtEnd={jumpReady ? false : THREAD_FEED_MAINTAIN_SCROLL_AT_END}
3648
+ maintainVisibleContentPosition
3649
data={groupedFeed}
3650
extraData={listAppearanceData}
3651
renderItem={renderItem}
@@ -3903,34 +3666,25 @@ export const ThreadFeed = memo(function ThreadFeed({
3666
: `message:${entry.message.role}`;
3667
}}
3668
getFixedItemSize={getFixedItemSize}
3906
- // Native layout transitions retain stale row positions during sync, even at duration zero.
3907
- onItemSizeChanged={handleItemSizeChanged}
3669
drawDistance={500}
3670
keyboardShouldPersistTaps="always"
3671
keyboardDismissMode="none"
3672
keyboardLiftBehavior={props.sendingWithKeyboard ? "persistent" : "whenAtEnd"}
3912
- // Seed viewport size to skip programmatic attach-time positioning, which races UIKit's adjustedContentInset.
3673
+ // Seed the initial viewport before native onLayout.
3674
{...(viewportHeight > 0 && viewportWidth > 0
3675
? { estimatedListSize: { height: viewportHeight, width: viewportWidth } }
3676
: {})}
3916
- // Enable overflow: RN scrollTo clamps against raw insets and ignores the automatic header inset.
3677
scrollToOverflowEnabled
3678
estimatedItemSize={180}
3679
alignItemsAtEnd
3680
initialScrollAtEnd
3921
- onLoad={() => {
3922
- loadedListKeyRef.current = listMountKey;
3923
- setLoadedListKey(listMountKey);
3924
- }}
3925
- // Row positions start below the header; the reflow anchor converts between them.
3926
- onMetricsChange={(metrics) => {
3927
- listHeaderSizeRef.current = metrics.headerSize;
3681
+ onReady={() => {
3682
+ setLoadedListKey(feedThreadKey);
3683
+ handleMetricsChange();
3684
}}
3685
+ onLayout={handleMetricsChange}
3686
+ onItemSizeChanged={handleItemSizeChanged}
3687
onScroll={handleScroll}
3930
- onScrollBeginDrag={handleScrollBeginDrag}
3931
- onScrollEndDrag={handleScrollEndDrag}
3932
- onMomentumScrollBegin={handleMomentumScrollBegin}
3933
- onMomentumScrollEnd={handleMomentumScrollEnd}
3688
scrollEventThrottle={16}
3689
ListHeaderComponent={
3690
<>
@@ -3941,7 +3695,6 @@ export const ThreadFeed = memo(function ThreadFeed({
3695
{props.historyControls ? (
3696
<ThreadFeedLoadEarlierControl {...props.historyControls} />
3697
) : null}
3944
- <View ref={headerEndRef} collapsable={false} />
3698
</>
3699
}
3700
ListFooterComponent={
@@ -3957,7 +3710,7 @@ export const ThreadFeed = memo(function ThreadFeed({
3710
}
3711
contentContainerStyle={{
3712
...(props.fitShortFeedToViewport ? { minHeight: "100%" } : {}),
3960
- paddingTop: FEED_PADDING_TOP + disclosureTopSpace,
3713
+ paddingTop: FEED_PADDING_TOP,
3714
paddingLeft: contentHorizontalPadding + contentLeftInset,
3715
paddingRight: contentHorizontalPadding + contentRightInset,
3716
}}
apps/mobile/src/features/threads/thread-feed-live-follow.test.ts
deleted
-312
@@ -1,312 +0,0 @@
1
-import { describe, expect, it } from "vite-plus/test";
2
-
3
-import {
4
- resolveThreadFeedLiveFollow,
5
- resolveThreadFeedReflowAnchor,
6
- resolveThreadFeedReflowOffset,
7
- resolveThreadFeedReflowScroll,
8
- resolveThreadFeedSubmissionAnchor,
9
- resolveThreadWorkGroupInitialScroll,
10
- shouldFollowThreadWorkGroupAppend,
11
-} from "./thread-feed-live-follow";
12
-
13
-describe("tool-group scroll restoration", () => {
14
- const position = {
15
- rowId: "read-output",
16
- offsetWithinRow: 80,
17
- scrollOffset: 600,
18
- contentHeight: 1_000,
19
- };
20
-
21
- it("restores the visible row and its detail offset rather than stale absolute pixels", () => {
22
- const before = [{ id: "first" }, { id: "read-output" }, { id: "last" }];
23
- const after = [{ id: "older" }, ...before];
24
- expect(resolveThreadWorkGroupInitialScroll(before, position)).toEqual({
25
- index: 1,
26
- viewOffset: -80,
27
- });
28
- expect(resolveThreadWorkGroupInitialScroll(after, position)).toEqual({
29
- index: 2,
30
- viewOffset: -80,
31
- });
32
- });
33
-});
34
-
35
-describe("tool-group append following", () => {
36
- const previousRows = Array.from({ length: 10 }, (_, index) => ({ id: `call-${index}` }));
37
- const appendedRows = [...previousRows, { id: "new-call" }];
38
- const atEnd = {
39
- previousRows,
40
- rows: appendedRows,
41
- previousContentHeight: 289,
42
- contentHeight: 318,
43
- viewportHeight: 256,
44
- scrollOffset: 33,
45
- detailsChanged: false,
46
- userScrolling: false,
47
- };
48
-
49
- it("follows a new call when the reader was at the end", () => {
50
- expect(shouldFollowThreadWorkGroupAppend(atEnd)).toBe(true);
51
- });
52
-
53
- it("follows the first overflowing append as a short group reaches its height cap", () => {
54
- expect(
55
- shouldFollowThreadWorkGroupAppend({
56
- ...atEnd,
57
- previousRows: previousRows.slice(0, 8),
58
- rows: previousRows.slice(0, 9),
59
- previousContentHeight: 231,
60
- contentHeight: 260,
61
- viewportHeight: 231,
62
- scrollOffset: 0,
63
- }),
64
- ).toBe(true);
65
- });
66
-
67
- it.each([
68
- { name: "reading earlier calls", changes: { scrollOffset: 20 } },
69
- { name: "streaming a result", changes: { rows: previousRows, contentHeight: 600 } },
70
- {
71
- name: "replacing a call while appending",
72
- changes: { rows: [{ id: "replacement" }, ...appendedRows.slice(1)] },
73
- },
74
- ])("does not steal the reader's position when $name", ({ changes }) => {
75
- expect(shouldFollowThreadWorkGroupAppend({ ...atEnd, ...changes })).toBe(false);
76
- });
77
-});
78
-
79
-describe("resolveThreadFeedSubmissionAnchor", () => {
80
- it("keeps an offline first message at the end", () => {
81
- expect(
82
- resolveThreadFeedSubmissionAnchor({
83
- currentAnchorMessageId: null,
84
- submittedMessageId: "offline-first",
85
- hasStartedTurn: false,
86
- hasUserMessage: false,
87
- queuedMessageCount: 0,
88
- deliveryDeferred: true,
89
- }),
90
- ).toBeNull();
91
- });
92
-
93
- it("anchors the first user message in a thread", () => {
94
- expect(
95
- resolveThreadFeedSubmissionAnchor({
96
- currentAnchorMessageId: null,
97
- submittedMessageId: "first-message",
98
- hasStartedTurn: false,
99
- hasUserMessage: false,
100
- deliveryDeferred: false,
101
- queuedMessageCount: 0,
102
- }),
103
- ).toBe("first-message");
104
- });
105
-
106
- it("preserves the first-message anchor when another message is queued", () => {
107
- expect(
108
- resolveThreadFeedSubmissionAnchor({
109
- currentAnchorMessageId: "first-message",
110
- submittedMessageId: "second-message",
111
- hasStartedTurn: false,
112
- hasUserMessage: false,
113
- deliveryDeferred: false,
114
- queuedMessageCount: 1,
115
- }),
116
- ).toBe("first-message");
117
- });
118
-
119
- it("does not anchor a follow-up after a user message appears", () => {
120
- expect(
121
- resolveThreadFeedSubmissionAnchor({
122
- currentAnchorMessageId: "first-message",
123
- submittedMessageId: "second-message",
124
- hasStartedTurn: false,
125
- hasUserMessage: true,
126
- deliveryDeferred: false,
127
- queuedMessageCount: 0,
128
- }),
129
- ).toBeNull();
130
- });
131
-
132
- // regression: #7897 stop pushing follow-up messages to the top
133
- it("does not anchor a thread that has already started a turn", () => {
134
- expect(
135
- resolveThreadFeedSubmissionAnchor({
136
- currentAnchorMessageId: null,
137
- submittedMessageId: "second-message",
138
- hasStartedTurn: true,
139
- hasUserMessage: false,
140
- deliveryDeferred: false,
141
- queuedMessageCount: 0,
142
- }),
143
- ).toBeNull();
144
- });
145
-});
146
-
147
-describe("resolveThreadFeedLiveFollow", () => {
148
- // regression: #5986 stabilize thread composer and interactions
149
- it("pauses immediately when the user starts scrolling", () => {
150
- expect(resolveThreadFeedLiveFollow(true, { type: "user-scroll-begin" })).toBe(false);
151
- });
152
-
153
- it("does not mistake programmatic layout compensation for a user scroll", () => {
154
- expect(
155
- resolveThreadFeedLiveFollow(true, {
156
- type: "scroll",
157
- isAtEnd: false,
158
- userScrollSessionActive: false,
159
- }),
160
- ).toBe(true);
161
- });
162
-
163
- it("does not re-arm at the end while a user scroll session is active", () => {
164
- expect(
165
- resolveThreadFeedLiveFollow(false, {
166
- type: "scroll",
167
- isAtEnd: true,
168
- userScrollSessionActive: true,
169
- }),
170
- ).toBe(false);
171
- });
172
-
173
- it.each([
174
- { isAtEnd: false, userScrollSessionActive: false, expected: false },
175
- { isAtEnd: true, userScrollSessionActive: false, expected: true },
176
- { isAtEnd: false, userScrollSessionActive: true, expected: false },
177
- { isAtEnd: true, userScrollSessionActive: true, expected: false },
178
- ])("reconciles follow after a disclosure settles: %j", ({ expected, ...state }) => {
179
- expect(resolveThreadFeedLiveFollow(!expected, { type: "disclosure-settled", ...state })).toBe(
180
- expected,
181
- );
182
- });
183
-
184
- it("re-arms at the actual end only after the user scroll session ends", () => {
185
- expect(
186
- resolveThreadFeedLiveFollow(false, {
187
- type: "user-scroll-end",
188
- isAtEnd: true,
189
- userScrollSessionActive: true,
190
- }),
191
- ).toBe(true);
192
- expect(
193
- resolveThreadFeedLiveFollow(false, {
194
- type: "user-scroll-end",
195
- isAtEnd: false,
196
- userScrollSessionActive: true,
197
- }),
198
- ).toBe(false);
199
- });
200
-});
201
-
202
-describe("width reflow anchors", () => {
203
- const layout = { rowsTop: 50, headerInset: 100 };
204
- const feedState = (
205
- rows: ReadonlyArray<{ readonly id: string; readonly size: number }>,
206
- scroll: number,
207
- isWithinMaintainScrollAtEndThreshold = false,
208
- ) => {
209
- const positions = rows.map((_, index) =>
210
- rows.slice(0, index).reduce((top, row) => top + row.size, 0),
211
- );
212
- return {
213
- data: rows,
214
- scroll,
215
- isWithinMaintainScrollAtEndThreshold,
216
- indexByKey: (key: string) => {
217
- const index = rows.findIndex((row) => row.id === key);
218
- return index < 0 ? undefined : index;
219
- },
220
- positionAtIndex: (index: number) => positions[index],
221
- sizes: new Map(rows.map((row) => [row.id, row.size])),
222
- };
223
- };
224
- const wide = [
225
- { id: "question", size: 400 },
226
- { id: "reply", size: 2_000 },
227
- { id: "follow-up", size: 300 },
228
- ];
229
- // The line under the header sits 1,200px, 60%, into the reply.
230
- const readingReply = feedState(wide, 1_550);
231
-
232
- it("keeps the end for a feed that is following it", () => {
233
- expect(resolveThreadFeedReflowAnchor(feedState(wide, 1_550, true), layout, true)).toBe("end");
234
- });
235
-
236
- it("keeps the reader's row after a status-bar scroll left follow on far from the end", () => {
237
- expect(resolveThreadFeedReflowAnchor(readingReply, layout, true)).toEqual({
238
- key: "reply",
239
- offsetWithinRow: 1_200,
240
- size: 2_000,
241
- });
242
- });
243
-
244
- it.each([
245
- { change: "narrows", replySize: 4_000 },
246
- { change: "widens", replySize: 1_000 },
247
- ])("keeps the reader 60% into a reply when the feed $change", ({ replySize }) => {
248
- const anchor = resolveThreadFeedReflowAnchor(readingReply, layout, false);
249
- if (anchor === null || anchor === "end") throw new Error("expected a row anchor");
250
- const reflowed = feedState(
251
- [
252
- { id: "question", size: 400 * (replySize / 2_000) },
253
- { id: "reply", size: replySize },
254
- { id: "follow-up", size: 300 },
255
- ],
256
- readingReply.scroll,
257
- );
258
- expect(resolveThreadFeedReflowScroll(anchor, reflowed, layout)).toEqual({
259
- index: 1,
260
- viewOffset: layout.headerInset - 0.6 * replySize,
261
- });
262
- });
263
-
264
- it.each([
265
- { change: "narrows", replySize: 4_000 },
266
- { change: "widens", replySize: 1_000 },
267
- ])(
268
- "holds the reader 60% into a reply on each re-measure as the feed $change",
269
- ({ replySize }) => {
270
- const anchor = resolveThreadFeedReflowAnchor(readingReply, layout, false);
271
- if (anchor === null || anchor === "end") throw new Error("expected a row anchor");
272
- const rows = [
273
- { id: "question", size: 400 * (replySize / 2_000) },
274
- { id: "reply", size: replySize },
275
- { id: "follow-up", size: 300 },
276
- ];
277
- const offset = resolveThreadFeedReflowOffset(
278
- anchor,
279
- feedState(rows, readingReply.scroll),
280
- layout,
281
- );
282
- if (offset === undefined) throw new Error("expected an offset");
283
- expect(resolveThreadFeedReflowAnchor(feedState(rows, offset), layout, false)).toEqual({
284
- key: "reply",
285
- offsetWithinRow: 0.6 * replySize,
286
- size: replySize,
287
- });
288
- },
289
- );
290
-
291
- it("leaves a reader at the top of the thread where they are", () => {
292
- expect(resolveThreadFeedReflowAnchor(feedState(wide, -layout.headerInset), layout, false)).toBe(
293
- null,
294
- );
295
- });
296
-
297
- it("does not scroll when the row did not change size", () => {
298
- const anchor = resolveThreadFeedReflowAnchor(readingReply, layout, false);
299
- if (anchor === null || anchor === "end") throw new Error("expected a row anchor");
300
- expect(resolveThreadFeedReflowScroll(anchor, readingReply, layout)).toBeNull();
301
- });
302
-
303
- it("does not restore a row that left the feed", () => {
304
- expect(
305
- resolveThreadFeedReflowScroll(
306
- { key: "reply", offsetWithinRow: 1_200, size: 2_000 },
307
- feedState([{ id: "question", size: 400 }], 0),
308
- layout,
309
- ),
310
- ).toBeNull();
311
- });
312
-});
apps/mobile/src/features/threads/thread-feed-live-follow.ts
deleted
-179
@@ -1,179 +0,0 @@
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" }
6
- | {
7
- readonly type: "user-scroll-end";
8
- readonly isAtEnd: boolean;
9
- readonly userScrollSessionActive: boolean;
10
- }
11
- | {
12
- readonly type: "scroll" | "disclosure-settled";
13
- readonly isAtEnd: boolean;
14
- readonly userScrollSessionActive: boolean;
15
- };
16
-
17
-export interface ThreadWorkGroupScrollPosition {
18
- readonly rowId: string;
19
- readonly offsetWithinRow: number;
20
- readonly scrollOffset: number;
21
- readonly contentHeight: number;
22
-}
23
-
24
-export function resolveThreadWorkGroupInitialScroll(
25
- rows: ReadonlyArray<{ readonly id: string }>,
26
- position: ThreadWorkGroupScrollPosition | undefined,
27
-) {
28
- const index = position ? rows.findIndex((row) => row.id === position.rowId) : -1;
29
- return index >= 0 && position ? { index, viewOffset: -position.offsetWithinRow } : undefined;
30
-}
31
-
32
-export function shouldFollowThreadWorkGroupAppend(input: {
33
- readonly previousRows: ReadonlyArray<{ readonly id: string }>;
34
- readonly rows: ReadonlyArray<{ readonly id: string }>;
35
- readonly previousContentHeight: number;
36
- readonly contentHeight: number;
37
- readonly viewportHeight: number;
38
- readonly scrollOffset: number;
39
- readonly detailsChanged: boolean;
40
- readonly userScrolling: boolean;
41
-}) {
42
- return (
43
- !input.detailsChanged &&
44
- !input.userScrolling &&
45
- input.contentHeight > input.previousContentHeight &&
46
- input.rows.length > input.previousRows.length &&
47
- input.previousRows.every((row, index) => row.id === input.rows[index]?.id) &&
48
- input.previousContentHeight - input.viewportHeight - input.scrollOffset <= 1
49
- );
50
-}
51
-
52
-export function resolveThreadFeedSubmissionAnchor<AnchorId>(input: {
53
- readonly currentAnchorMessageId: AnchorId | null;
54
- readonly submittedMessageId: AnchorId;
55
- readonly hasStartedTurn: boolean;
56
- readonly hasUserMessage: boolean;
57
- readonly queuedMessageCount: number;
58
- readonly deliveryDeferred: boolean;
59
-}): AnchorId | null {
60
- if (input.deliveryDeferred || input.hasStartedTurn || input.hasUserMessage) {
61
- return null;
62
- }
63
-
64
- if (input.currentAnchorMessageId !== null) {
65
- return input.currentAnchorMessageId;
66
- }
67
-
68
- return input.queuedMessageCount > 0 ? null : input.submittedMessageId;
69
-}
70
-
71
-export function resolveThreadFeedLiveFollow(
72
- current: boolean,
73
- event: ThreadFeedLiveFollowEvent,
74
-): boolean {
75
- switch (event.type) {
76
- case "reset":
77
- return true;
78
- case "user-scroll-begin":
79
- return false;
80
- case "user-scroll-end":
81
- return event.userScrollSessionActive ? event.isAtEnd : current;
82
- case "disclosure-settled":
83
- return !event.userScrollSessionActive && event.isAtEnd;
84
- case "scroll":
85
- if (event.userScrollSessionActive) {
86
- return false;
87
- }
88
- if (event.isAtEnd) {
89
- return true;
90
- }
91
- return current;
92
- }
93
-}
94
-
95
-/** The LegendList state a width reflow reads before rows re-measure and after they settle. */
96
-export interface ThreadFeedReflowListState {
97
- readonly data: ReadonlyArray<{ readonly id: string }>;
98
- readonly scroll: number;
99
- readonly isWithinMaintainScrollAtEndThreshold: boolean;
100
- readonly indexByKey: (key: string) => number | undefined;
101
- readonly positionAtIndex: (index: number) => number | undefined;
102
- readonly sizes: ReadonlyMap<string, number>;
103
-}
104
-
105
-export interface ThreadFeedReflowLayout {
106
- /** List padding and header; row positions start below them. */
107
- readonly rowsTop: number;
108
- /** The top of the viewport covered by the navigation header. */
109
- readonly headerInset: number;
110
-}
111
-
112
-export interface ThreadFeedReflowRowAnchor {
113
- readonly key: string;
114
- readonly offsetWithinRow: number;
115
- readonly size: number;
116
-}
117
-
118
-/** A feed that follows keeps the end through a reflow; a reader keeps the row they are in. */
119
-export type ThreadFeedReflowAnchor = "end" | ThreadFeedReflowRowAnchor;
120
-
121
-function readingLine(state: ThreadFeedReflowListState, layout: ThreadFeedReflowLayout) {
122
- return state.scroll + layout.headerInset - layout.rowsTop;
123
-}
124
-
125
-export function resolveThreadFeedReflowAnchor(
126
- state: ThreadFeedReflowListState,
127
- layout: ThreadFeedReflowLayout,
128
- following: boolean,
129
-): ThreadFeedReflowAnchor | null {
130
- // Follow alone is not enough: a status-bar tap scrolls to the top without a drag, so it
131
- // leaves follow on while the reader is far from the end.
132
- if (following && state.isWithinMaintainScrollAtEndThreshold) return "end";
133
- const line = readingLine(state, layout);
134
- // A reader at the top of the thread stays there without help.
135
- if (line <= 0) return null;
136
- const row = resolveWorkGroupScrollAnchor({
137
- data: state.data,
138
- scroll: line,
139
- positionAtIndex: state.positionAtIndex,
140
- });
141
- const size = row ? state.sizes.get(row.rowId) : undefined;
142
- return row && size ? { key: row.rowId, offsetWithinRow: row.offsetWithinRow, size } : null;
143
-}
144
-
145
-function resolveReflowAnchorPoint(
146
- anchor: ThreadFeedReflowRowAnchor,
147
- state: ThreadFeedReflowListState,
148
-) {
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
- return { index, top, offsetWithinRow: (anchor.offsetWithinRow * size) / anchor.size };
156
-}
157
-
158
-/** The scroll offset that puts the reader's line back under the header at the current sizes. */
159
-export function resolveThreadFeedReflowOffset(
160
- anchor: ThreadFeedReflowRowAnchor,
161
- state: ThreadFeedReflowListState,
162
- layout: ThreadFeedReflowLayout,
163
-): number | undefined {
164
- const point = resolveReflowAnchorPoint(anchor, state);
165
- return point
166
- ? point.top + point.offsetWithinRow - layout.headerInset + layout.rowsTop
167
- : undefined;
168
-}
169
-
170
-export function resolveThreadFeedReflowScroll(
171
- anchor: ThreadFeedReflowRowAnchor,
172
- state: ThreadFeedReflowListState,
173
- layout: ThreadFeedReflowLayout,
174
-): { readonly index: number; readonly viewOffset: number } | null {
175
- const point = resolveReflowAnchorPoint(anchor, state);
176
- if (!point) return null;
177
- if (Math.abs(readingLine(state, layout) - (point.top + point.offsetWithinRow)) < 1) return null;
178
- return { index: point.index, viewOffset: layout.headerInset - point.offsetWithinRow };
179
-}
apps/mobile/src/features/threads/thread-feed-scroll-position.test.ts
new
+94
@@ -0,0 +1,94 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+import {
3
+ resolveThreadFeedSubmissionAnchor,
4
+ resolveThreadWorkGroupInitialScroll,
5
+} from "./thread-feed-scroll-position";
6
+
7
+describe("tool-group scroll restoration", () => {
8
+ const position = {
9
+ rowId: "read-output",
10
+ offsetWithinRow: 80,
11
+ scrollOffset: 600,
12
+ };
13
+
14
+ it("restores the visible row and its detail offset rather than stale absolute pixels", () => {
15
+ const before = [{ id: "first" }, { id: "read-output" }, { id: "last" }];
16
+ const after = [{ id: "older" }, ...before];
17
+ expect(resolveThreadWorkGroupInitialScroll(before, position)).toEqual({
18
+ index: 1,
19
+ viewOffset: -80,
20
+ });
21
+ expect(resolveThreadWorkGroupInitialScroll(after, position)).toEqual({
22
+ index: 2,
23
+ viewOffset: -80,
24
+ });
25
+ });
26
+});
27
+
28
+describe("resolveThreadFeedSubmissionAnchor", () => {
29
+ it("keeps an offline first message at the end", () => {
30
+ expect(
31
+ resolveThreadFeedSubmissionAnchor({
32
+ currentAnchorMessageId: null,
33
+ submittedMessageId: "offline-first",
34
+ hasStartedTurn: false,
35
+ hasUserMessage: false,
36
+ queuedMessageCount: 0,
37
+ deliveryDeferred: true,
38
+ }),
39
+ ).toBeNull();
40
+ });
41
+
42
+ it("anchors the first user message in a thread", () => {
43
+ expect(
44
+ resolveThreadFeedSubmissionAnchor({
45
+ currentAnchorMessageId: null,
46
+ submittedMessageId: "first-message",
47
+ hasStartedTurn: false,
48
+ hasUserMessage: false,
49
+ deliveryDeferred: false,
50
+ queuedMessageCount: 0,
51
+ }),
52
+ ).toBe("first-message");
53
+ });
54
+
55
+ it("preserves the first-message anchor when another message is queued", () => {
56
+ expect(
57
+ resolveThreadFeedSubmissionAnchor({
58
+ currentAnchorMessageId: "first-message",
59
+ submittedMessageId: "second-message",
60
+ hasStartedTurn: false,
61
+ hasUserMessage: false,
62
+ deliveryDeferred: false,
63
+ queuedMessageCount: 1,
64
+ }),
65
+ ).toBe("first-message");
66
+ });
67
+
68
+ it("does not anchor a follow-up after a user message appears", () => {
69
+ expect(
70
+ resolveThreadFeedSubmissionAnchor({
71
+ currentAnchorMessageId: "first-message",
72
+ submittedMessageId: "second-message",
73
+ hasStartedTurn: false,
74
+ hasUserMessage: true,
75
+ deliveryDeferred: false,
76
+ queuedMessageCount: 0,
77
+ }),
78
+ ).toBeNull();
79
+ });
80
+
81
+ // regression: #7897 stop pushing follow-up messages to the top
82
+ it("does not anchor a thread that has already started a turn", () => {
83
+ expect(
84
+ resolveThreadFeedSubmissionAnchor({
85
+ currentAnchorMessageId: null,
86
+ submittedMessageId: "second-message",
87
+ hasStartedTurn: true,
88
+ hasUserMessage: false,
89
+ deliveryDeferred: false,
90
+ queuedMessageCount: 0,
91
+ }),
92
+ ).toBeNull();
93
+ });
94
+});
apps/mobile/src/features/threads/thread-feed-scroll-position.ts
new
+32
@@ -0,0 +1,32 @@
1
+export interface ThreadWorkGroupScrollPosition {
2
+ readonly rowId: string;
3
+ readonly offsetWithinRow: number;
4
+ readonly scrollOffset: number;
5
+}
6
+
7
+export function resolveThreadWorkGroupInitialScroll(
8
+ rows: ReadonlyArray<{ readonly id: string }>,
9
+ position: ThreadWorkGroupScrollPosition | undefined,
10
+) {
11
+ const index = position ? rows.findIndex((row) => row.id === position.rowId) : -1;
12
+ return index >= 0 && position ? { index, viewOffset: -position.offsetWithinRow } : undefined;
13
+}
14
+
15
+export function resolveThreadFeedSubmissionAnchor<AnchorId>(input: {
16
+ readonly currentAnchorMessageId: AnchorId | null;
17
+ readonly submittedMessageId: AnchorId;
18
+ readonly hasStartedTurn: boolean;
19
+ readonly hasUserMessage: boolean;
20
+ readonly queuedMessageCount: number;
21
+ readonly deliveryDeferred: boolean;
22
+}): AnchorId | null {
23
+ if (input.deliveryDeferred || input.hasStartedTurn || input.hasUserMessage) {
24
+ return null;
25
+ }
26
+
27
+ if (input.currentAnchorMessageId !== null) {
28
+ return input.currentAnchorMessageId;
29
+ }
30
+
31
+ return input.queuedMessageCount > 0 ? null : input.submittedMessageId;
32
+}
apps/mobile/src/features/threads/thread-work-log.tsx
+56
-124
@@ -23,7 +23,6 @@ import { AnimatedLegendList } from "@legendapp/list/reanimated";
23
import { useIsFocused } from "@react-navigation/native";
24
import {
25
useEffect,
26
- useEffectEvent,
26
useId,
27
useLayoutEffect,
28
useRef,
@@ -76,16 +75,14 @@ import {
75
import { useTurnItemDetail } from "../../state/queries";
76
import {
77
resolveThreadWorkGroupInitialScroll,
79
- shouldFollowThreadWorkGroupAppend,
78
type ThreadWorkGroupScrollPosition,
81
-} from "./thread-feed-live-follow";
79
+} from "./thread-feed-scroll-position";
80
import {
81
resolveWorkEntryToolPresentation,
82
toolGroupAction,
83
type ToolGroupSummaryKind,
84
workEntryViewedImagePath,
85
} from "@t3tools/client-runtime/work-log/presentation";
88
-import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor";
86
import { notificationChildThreadId } from "@t3tools/client-runtime/state/thread-execution";
87
import type { MarkdownImageRenderer } from "../../native/SelectableMarkdownText";
88
import type { FilePreviewSource } from "../../components/ui/FilePreviewModal";
@@ -597,6 +594,11 @@ function ThreadReasoningGroup(props: {
594
);
595
}
596
597
+const WORK_GROUP_MAINTAIN_SCROLL_AT_END = {
598
+ animated: false,
599
+ on: { dataAppend: true },
600
+} as const;
601
+
602
function ThreadWorkGroupList(props: {
603
readonly activities: ReadonlyArray<ThreadFeedActivity>;
604
readonly edgeFadeColor: string;
@@ -610,37 +612,27 @@ function ThreadWorkGroupList(props: {
612
props.activities,
613
props.rowSizing.estimatedRowHeight,
614
);
613
- const [initialPosition] = useState(() => {
614
- const position = props.scrollPositions.get(props.groupId);
615
- return props.activities.some((row) => row.id === position?.rowId) ? position : undefined;
616
- });
617
- const [initialScrollIndex] = useState(() =>
618
- resolveThreadWorkGroupInitialScroll(props.activities, initialPosition),
619
- );
620
- const [restoringPosition, setRestoringPosition] = useState(initialScrollIndex !== undefined);
615
+ const savedPosition = props.scrollPositions.get(props.groupId);
616
+ const initialPosition = props.activities.some((row) => row.id === savedPosition?.rowId)
617
+ ? savedPosition
618
+ : undefined;
619
+ const initialScrollIndex = resolveThreadWorkGroupInitialScroll(props.activities, initialPosition);
620
const listRef = useRef<LegendListRef>(null);
621
+ const previousTextSize = useRef(props.rowSizing.textSizeKey);
622
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the list's cached row sizes when the text size changes
623
+ useLayoutEffect(() => {
624
+ if (previousTextSize.current === props.rowSizing.textSizeKey) return;
625
+ previousTextSize.current = props.rowSizing.textSizeKey;
626
+ listRef.current?.clearCaches({ mode: "sizes" });
627
+ }, [props.rowSizing.textSizeKey]);
628
const loadedRef = useRef(false);
623
- const userScrollingRef = useRef(false);
624
- const pendingAppendHeightRef = useRef<number | null>(null);
625
- const previousContent = useRef({
626
- rows: props.activities,
627
- height: Math.max(estimatedRowsHeight, initialPosition?.contentHeight ?? 0),
628
- expandedRows: props.expandedRows,
629
- });
630
- const [measuredContent, setMeasuredContent] = useState(() => ({
631
- height: Math.max(estimatedRowsHeight, initialPosition?.contentHeight ?? 0),
632
- rowCount: props.activities.length,
633
- }));
634
- const contentHeight = Math.max(
635
- 1,
636
- measuredContent.height +
637
- Math.max(0, props.activities.length - measuredContent.rowCount) *
638
- (props.rowSizing.estimatedRowHeight + WORK_ROW_GAP),
639
- );
629
+ const [contentHeight, setContentHeight] = useState(estimatedRowsHeight);
630
const height = Math.min(contentHeight, WORK_GROUP_MAX_HEIGHT);
631
const scrollOffset = useSharedValue(initialPosition?.scrollOffset ?? 0);
632
const sharedValues = { scrollOffset };
633
634
+ // Each edge fades only while content continues past it. Scroll offset stays
635
+ // on the UI thread; only content-size changes update React state.
636
const topFadeStyle = useAnimatedStyle(() => ({
637
opacity: Math.min(1, Math.max(0, scrollOffset.value) / WORK_GROUP_EDGE_FADE_HEIGHT),
638
}));
@@ -650,78 +642,40 @@ function ThreadWorkGroupList(props: {
642
Math.max(0, contentHeight - height - scrollOffset.value) / WORK_GROUP_EDGE_FADE_HEIGHT,
643
),
644
}));
653
- const rememberPosition = () => {
645
+ const rememberPosition = (scroll: number) => {
646
if (!loadedRef.current) return;
655
- const state = listRef.current?.getState();
656
- const position = state && resolveWorkGroupScrollAnchor(state);
657
- if (!state || !position) return;
647
+ const position = listRef.current?.anchorVisibleContent({ hold: false });
648
+ if (!position) return;
649
props.scrollPositions.set(props.groupId, {
659
- ...position,
660
- contentHeight: state.contentLength,
650
+ rowId: position.key,
651
+ offsetWithinRow: position.offset,
652
+ scrollOffset: scroll,
653
});
654
};
663
- const finishPendingAppend = () => {
664
- const targetHeight = pendingAppendHeightRef.current;
665
- const state = listRef.current?.getState();
666
- if (
667
- targetHeight !== null &&
668
- state &&
669
- !userScrollingRef.current &&
670
- Math.abs(state.scrollLength - targetHeight) <= 1
671
- ) {
672
- pendingAppendHeightRef.current = null;
673
- void listRef.current?.scrollToEnd({ animated: false });
674
- }
655
+ const handleMetricsChange = () => {
656
+ const metrics = listRef.current?.getState();
657
+ if (!metrics) return;
658
+ setContentHeight(Math.max(1, metrics.contentLength));
659
+ rememberPosition(metrics.scroll);
660
+ };
661
+ const handleReady = () => {
662
+ loadedRef.current = true;
663
+ handleMetricsChange();
664
};
676
- // LegendList notifies from child layout effects. Effect Events see the
677
- // committed rows before those effects run, unlike a parent layout-effect ref.
678
- const onContentSizeChange = useEffectEvent((nextHeight: number) => {
679
- const previous = previousContent.current;
680
- const detailsChanged = previous.expandedRows !== props.expandedRows;
681
- const followAppend =
682
- loadedRef.current &&
683
- shouldFollowThreadWorkGroupAppend({
684
- previousRows: previous.rows,
685
- rows: props.activities,
686
- previousContentHeight: previous.height,
687
- contentHeight: nextHeight,
688
- viewportHeight: Math.min(previous.height, WORK_GROUP_MAX_HEIGHT),
689
- scrollOffset: scrollOffset.value,
690
- detailsChanged,
691
- userScrolling: userScrollingRef.current,
692
- });
693
- previousContent.current = {
694
- rows: props.activities,
695
- height: nextHeight,
696
- expandedRows: props.expandedRows,
697
- };
698
- setMeasuredContent((current) =>
699
- current.height === nextHeight && current.rowCount === props.activities.length
700
- ? current
701
- : { height: nextHeight, rowCount: props.activities.length },
702
- );
703
- if (followAppend) {
704
- pendingAppendHeightRef.current = Math.min(nextHeight, WORK_GROUP_MAX_HEIGHT);
705
- } else if (detailsChanged || userScrollingRef.current || previous.rows !== props.activities) {
706
- pendingAppendHeightRef.current = null;
707
- } else if (pendingAppendHeightRef.current !== null) {
708
- pendingAppendHeightRef.current = Math.min(nextHeight, WORK_GROUP_MAX_HEIGHT);
709
- }
710
- finishPendingAppend();
711
- rememberPosition();
712
- });
713
- // Native ScrollView reports size after LegendList lays out rows. Use LegendList's JS size
714
- // so group height and row measurements settle in the same commit.
665
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to LegendList's totalSize state to report content height in the same commit
666
useLayoutEffect(() => {
717
- const list = listRef.current;
718
- if (!list) return;
719
- const unsubscribe = list.getState().listen("totalSize", () => {
720
- onContentSizeChange(list.getState().contentLength);
721
- });
722
- onContentSizeChange(list.getState().contentLength);
723
- return unsubscribe;
724
- }, []);
667
+ const state = listRef.current?.getState();
668
+ if (!state) return;
669
+ handleMetricsChange();
670
+ const stops = [
671
+ state.listen("totalSize", handleMetricsChange),
672
+ state.listen("footerSize", handleMetricsChange),
673
+ state.listen("headerSize", handleMetricsChange),
674
+ ];
675
+ return () => {
676
+ for (const stop of stops) stop();
677
+ };
678
+ }, [handleMetricsChange]);
679
const getFixedItemSize = (row: ThreadFeedActivity, index: number) =>
680
props.expandedRows[row.id] || props.rowSizing.fixedRowHeight === undefined
681
? undefined
@@ -738,40 +692,20 @@ function ThreadWorkGroupList(props: {
692
<AnimatedLegendList
693
ref={listRef}
694
data={props.activities}
695
+ dataKey={props.groupId}
696
keyExtractor={workLogRowKey}
697
estimatedItemSize={props.rowSizing.estimatedRowHeight + WORK_ROW_GAP}
698
getFixedItemSize={getFixedItemSize}
699
initialScrollIndex={initialScrollIndex}
745
- // 50px bootstrap overscan may leave expanded details unmeasured until after scroll restoration.
746
- alwaysRender={
747
- restoringPosition && initialPosition ? { keys: [initialPosition.rowId] } : undefined
748
- }
700
recycleItems={false}
701
extraData={props.renderRow}
702
renderItem={renderItem}
703
sharedValues={sharedValues}
753
- onLayout={finishPendingAppend}
754
- onLoad={() => {
755
- loadedRef.current = true;
756
- setRestoringPosition(false);
757
- rememberPosition();
758
- }}
759
- onScroll={rememberPosition}
760
- onScrollBeginDrag={() => {
761
- userScrollingRef.current = true;
762
- pendingAppendHeightRef.current = null;
763
- }}
764
- onScrollEndDrag={() => {
765
- userScrollingRef.current = false;
766
- }}
767
- onMomentumScrollBegin={() => {
768
- userScrollingRef.current = true;
769
- pendingAppendHeightRef.current = null;
770
- }}
771
- onMomentumScrollEnd={() => {
772
- userScrollingRef.current = false;
773
- rememberPosition();
774
- }}
704
+ onReady={handleReady}
705
+ onScroll={handleMetricsChange}
706
+ onLayout={handleMetricsChange}
707
+ maintainScrollAtEnd={WORK_GROUP_MAINTAIN_SCROLL_AT_END}
708
+ maintainScrollAtEndThreshold={1 / Math.max(1, height)}
709
maintainVisibleContentPosition
710
nestedScrollEnabled
711
directionalLockEnabled
@@ -799,6 +733,7 @@ function ThreadWorkGroupList(props: {
733
);
734
}
735
736
+/** A screen-colored gradient painted over the list edge that still has content past it. */
737
function EdgeFade(props: { readonly color: string; readonly direction: "up" | "down" }) {
738
const gradientId = `work-group-fade-${useId().replaceAll(":", "")}`;
739
return (
@@ -1378,7 +1313,6 @@ export function ThreadWorkGroupToggle(props: {
1313
<WorkLogIcon icon="brain" color={props.iconSubtleColor} />
1314
</WorkLogIconSlot>
1315
<Text
1381
- key={props.rowSizing.textSizeKey}
1316
selectable={false}
1317
numberOfLines={4}
1318
ellipsizeMode="tail"
@@ -1403,7 +1337,6 @@ export function ThreadWorkGroupToggle(props: {
1337
>
1338
{props.shimmer ? (
1339
<ShimmeringWorkContent
1406
- key={props.rowSizing.textSizeKey}
1340
environmentId={props.environmentId}
1341
icon={icon}
1342
iconSubtleColor={props.iconSubtleColor}
@@ -1423,7 +1356,7 @@ export function ThreadWorkGroupToggle(props: {
1356
themeAppearance={props.themeAppearance}
1357
/>
1358
</WorkLogIconSlot>
1426
- <WorkLogLabel key={props.rowSizing.textSizeKey}>{props.summary}</WorkLogLabel>
1359
+ <WorkLogLabel>{props.summary}</WorkLogLabel>
1360
</>
1361
)}
1362
<ThreadDisclosureChevron
@@ -1454,7 +1387,6 @@ export function ThreadThinkingRow(props: {
1387
style={{ minHeight: props.rowSizing.estimatedRowHeight }}
1388
>
1389
<ShimmeringWorkContent
1457
- key={props.rowSizing.textSizeKey}
1390
icon="brain"
1391
iconSubtleColor={props.iconSubtleColor}
1392
label={label}
apps/web/src/components/BranchPicker.tsx
+13
-65
@@ -1,11 +1,10 @@
1
+import { useLegendListRef } from "~/hooks/useLegendListRef";
2
import type { VcsRef } from "@t3tools/contracts";
3
import { LegendList, type LegendListRef } from "@legendapp/list/react";
4
import { useId, useRef, useState, type ComponentProps, type ReactNode } from "react";
5
6
import { MiddleTruncate } from "./ui/middle-truncate";
6
-import { observeResize } from "../lib/observeResize";
7
import { cn } from "../lib/utils";
8
-import { shouldLoadNextBranchPageAfterScroll } from "../state/paginatedBranches";
8
import { RefreshIcon } from "./ui/refresh-icon";
9
import { Switch } from "./ui/switch";
10
import { getVirtualizedScrollFadeClassName } from "./ui/scroll-area";
@@ -59,10 +58,7 @@ export function BranchPicker({
58
}) {
59
const highlightedValueRef = useRef<string | null>(null);
60
const startFromOriginSwitchId = useId();
62
- const branchListScrollElementRef = useRef<HTMLElement | null>(null);
63
- const previousBranchListScrollTopRef = useRef<number | null>(null);
61
const handleOpenChange = (nextOpen: boolean) => {
65
- previousBranchListScrollTopRef.current = null;
62
if (!nextOpen) highlightedValueRef.current = null;
63
onOpenChange(nextOpen);
64
};
@@ -75,59 +71,14 @@ export function BranchPicker({
71
72
onLoadNext();
73
};
78
- const maybeFetchNextBranchPage = () => {
79
- const scrollElement = branchListScrollElementRef.current;
80
- if (!scrollElement) {
81
- return;
82
- }
83
-
84
- const previousScrollTop = previousBranchListScrollTopRef.current;
85
- previousBranchListScrollTopRef.current = scrollElement.scrollTop;
86
- if (
87
- !open ||
88
- !hasNextPage ||
89
- isFetchingNextPage ||
90
- !shouldLoadNextBranchPageAfterScroll({
91
- previousScrollTop,
92
- scrollTop: scrollElement.scrollTop,
93
- scrollHeight: scrollElement.scrollHeight,
94
- clientHeight: scrollElement.clientHeight,
95
- })
96
- ) {
97
- return;
98
- }
99
-
100
- fetchNextBranchPage();
101
- };
102
-
74
const branchListRef = useRef<LegendListRef | null>(null);
75
const updateBranchListScrollFades = () => {
105
- const scrollElement = branchListRef.current?.getScrollableNode?.();
106
- if (!(scrollElement instanceof HTMLElement)) {
107
- return;
108
- }
109
- branchListScrollElementRef.current = scrollElement;
110
- const maxScrollOffset = Math.max(0, scrollElement.scrollHeight - scrollElement.clientHeight);
111
- setShowTopBranchScrollFade(scrollElement.scrollTop > 1);
112
- setShowBottomBranchScrollFade(maxScrollOffset - scrollElement.scrollTop > 1);
113
- };
114
-
115
- // The popup mounts the list when it opens. Its content settles over a few
116
- // frames as rows measure, so the fades follow the scroller and its content.
117
- const attachBranchList = (list: LegendListRef | null) => {
118
- branchListRef.current = list;
119
- const scrollElement = list?.getScrollableNode?.();
120
- if (!(scrollElement instanceof HTMLElement)) return;
121
- const content = scrollElement.firstElementChild;
122
- const stopObserving = observeResize(
123
- content ? [scrollElement, content] : scrollElement,
124
- updateBranchListScrollFades,
125
- );
126
- return () => {
127
- stopObserving();
128
- branchListRef.current = null;
129
- };
76
+ const metrics = branchListRef.current?.getState();
77
+ if (!metrics) return;
78
+ setShowTopBranchScrollFade(!metrics.isAtStart);
79
+ setShowBottomBranchScrollFade(!metrics.isAtEnd);
80
};
81
+ const branchScrollRef = useLegendListRef(branchListRef, updateBranchListScrollFades);
82
83
return (
84
<Combobox
@@ -177,22 +128,19 @@ export function BranchPicker({
128
<div className="relative flex min-h-0 w-full max-h-56 flex-1 flex-col overflow-hidden">
129
<ComboboxListVirtualized className="flex size-full min-h-0 min-w-0 flex-col">
130
<LegendList<string>
180
- ref={attachBranchList}
131
+ ref={branchScrollRef}
132
data={filteredItems}
133
+ initialScrollOffset={0}
134
keyExtractor={(item) => item}
135
{...(getItemType ? { getItemType } : {})}
136
renderItem={({ item, index }) => renderItem(item, index)}
137
estimatedItemSize={28}
138
drawDistance={336}
187
- onLayout={() => {
188
- updateBranchListScrollFades();
189
- previousBranchListScrollTopRef.current =
190
- branchListScrollElementRef.current?.scrollTop ?? null;
191
- }}
192
- onScroll={() => {
193
- updateBranchListScrollFades();
194
- maybeFetchNextBranchPage();
195
- }}
139
+ onScroll={updateBranchListScrollFades}
140
+ onLayout={updateBranchListScrollFades}
141
+ onReady={updateBranchListScrollFades}
142
+ onEndReached={fetchNextBranchPage}
143
+ onEndReachedThreshold={0.5}
144
className={cn(
145
"min-h-0 max-h-56 scrollbar-gutter-stable overflow-x-hidden overscroll-y-contain ps-1 pe-0 py-2",
146
getVirtualizedScrollFadeClassName({
apps/web/src/components/CommandPalette.browser.test.tsx
+34
-1
@@ -1,6 +1,6 @@
1
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
2
import { describe, expect, it, vi } from "vite-plus/test";
3
-import { page } from "vite-plus/test/browser";
3
+import { page, userEvent } from "vite-plus/test/browser";
4
5
import { render } from "../../test/render";
6
import { openCommandPalette } from "../commandPaletteBus";
@@ -35,6 +35,39 @@ describe("CommandPalette open intents", () => {
35
await expect.element(page.getByPlaceholder("Search...")).toHaveFocus();
36
});
37
38
+ it("highlights the first project when New thread in... opens from the root list", async () => {
39
+ const environmentId = EnvironmentId.make("local");
40
+ const project = (id: string, title: string): Project => ({
41
+ id: ProjectId.make(id),
42
+ environmentId,
43
+ title,
44
+ workspaceRoot: `/work/${id}`,
45
+ repositoryIdentity: null,
46
+ defaultModelSelection: null,
47
+ createdAt: "2026-03-01T00:00:00.000Z",
48
+ updatedAt: "2026-03-01T00:00:00.000Z",
49
+ scripts: [],
50
+ });
51
+ setup({
52
+ projects: [project("acme", "Acme"), project("beta", "Beta"), project("gamma", "Gamma")],
53
+ });
54
+ await using _screen = await render(<CommandPalette>{null}</CommandPalette>);
55
+
56
+ openCommandPalette({});
57
+ await expect
58
+ .element(page.getByPlaceholder("Search commands, projects, and threads..."))
59
+ .toHaveFocus();
60
+ await userEvent.keyboard("{ArrowDown}");
61
+ await expect
62
+ .element(page.getByRole("option", { name: /^New thread in\.\.\./ }))
63
+ .toHaveAttribute("data-highlighted");
64
+ await userEvent.keyboard("{Enter}");
65
+
66
+ await expect.element(page.getByPlaceholder("Search...")).toHaveFocus();
67
+ await expect.element(page.getByRole("option").first()).toHaveAttribute("data-highlighted");
68
+ await expect.element(page.getByRole("option").nth(1)).not.toHaveAttribute("data-highlighted");
69
+ });
70
+
71
it("opens a search intent with its query in the focused input", async () => {
72
setup();
73
await using _screen = await render(<CommandPalette>{null}</CommandPalette>);
apps/web/src/components/CommandPaletteResults.tsx
+17
-13
@@ -1,3 +1,4 @@
1
+import { useLegendListRef } from "~/hooks/useLegendListRef";
2
import { type ResolvedKeybindingsConfig } from "@t3tools/contracts";
3
import { LegendList, type LegendListRef } from "@legendapp/list/react";
4
import { ChevronRightIcon } from "lucide-react";
@@ -77,12 +78,11 @@ export function CommandPaletteResults(props: CommandPaletteResultsProps) {
78
}
79
80
export function scrollCommandPaletteRowIntoView(list: LegendListRef | null, rowIndex: number) {
80
- const element = list?.getState?.().elementAtIndex(rowIndex);
81
- if (element instanceof HTMLElement) {
82
- element.scrollIntoView({ block: "nearest" });
83
- return;
84
- }
85
- void list?.scrollIndexIntoView?.({ index: rowIndex, animated: false });
81
+ void list?.scrollIndexIntoView({
82
+ index: rowIndex,
83
+ animated: false,
84
+ viewportMargin: { start: 24, end: 24 },
85
+ });
86
}
87
88
interface CommandPaletteVirtualizedResultsProps extends Omit<CommandPaletteResultsProps, "groups"> {
@@ -96,15 +96,15 @@ export function CommandPaletteVirtualizedResults(props: CommandPaletteVirtualize
96
const { listRef } = props;
97
const [scrollFade, setScrollFade] = useState({ top: false, bottom: false });
98
const updateScrollFade = () => {
99
- const scrollElement = listRef.current?.getScrollableNode?.();
100
- if (!(scrollElement instanceof HTMLElement)) return;
101
- const top = scrollElement.scrollTop > 1;
102
- const bottom =
103
- scrollElement.scrollHeight - scrollElement.clientHeight - scrollElement.scrollTop > 1;
99
+ const metrics = listRef.current?.getState();
100
+ if (!metrics) return;
101
+ const top = !metrics.isAtStart;
102
+ const bottom = !metrics.isAtEnd;
103
setScrollFade((current) =>
104
current.top === top && current.bottom === bottom ? current : { top, bottom },
105
);
106
};
107
+ const scrollRef = useLegendListRef(listRef, updateScrollFade);
108
109
if (props.rows.length === 0) {
110
return <CommandPaletteEmptyState {...props} />;
@@ -113,8 +113,9 @@ export function CommandPaletteVirtualizedResults(props: CommandPaletteVirtualize
113
return (
114
<CommandListVirtualized>
115
<LegendList<CommandPaletteRow>
116
- ref={listRef}
116
+ ref={scrollRef}
117
data={props.rows}
118
+ initialScrollOffset={0}
119
keyExtractor={(row) => row.key}
120
getItemType={(row) => row.kind}
121
extraData={props.highlightedItemValue}
@@ -139,9 +140,12 @@ export function CommandPaletteVirtualizedResults(props: CommandPaletteVirtualize
140
drawDistance={400}
141
onLayout={updateScrollFade}
142
onScroll={updateScrollFade}
143
+ onReady={updateScrollFade}
144
+ // Legend counts style padding (not class padding) in its size, end state and row positions.
145
+ style={{ paddingTop: 8, paddingBottom: 8 }}
146
contentContainerClassName="px-2"
147
className={cn(
144
- "min-h-0 scroll-py-6 overflow-x-hidden overscroll-y-contain py-2 [&::-webkit-scrollbar-track]:my-2",
148
+ "min-h-0 scroll-py-6 overflow-x-hidden overscroll-y-contain [&::-webkit-scrollbar-track]:my-2",
149
getVirtualizedScrollFadeClassName(scrollFade),
150
)}
151
/>
apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+35
@@ -262,6 +262,41 @@ describe("MessagesTimeline work rows", () => {
262
});
263
});
264
265
+ it("keeps following a streaming turn after a heading is expanded at the bottom", async () => {
266
+ const props = { ...baseProps(), isWorking: true };
267
+ const runId = RunId.make("live-run");
268
+ const container = document.createElement("div");
269
+ container.style.cssText =
270
+ "height: min(600px, 100vh); width: 900px; display: flex; flex-direction: column;";
271
+ const entries = [
272
+ ...Array.from({ length: 12 }, (_, index) =>
273
+ message(`Earlier context ${index}`, {}, `context-${index}`),
274
+ ),
275
+ message("Progress details\n\n".repeat(50), { role: "assistant", runId }, "progress"),
276
+ message("Done", { role: "assistant", runId }, "final"),
277
+ ];
278
+ await using screen = await render(<MessagesTimeline {...props} timelineEntries={entries} />, {
279
+ container,
280
+ });
281
+ const heading = screen.getByRole("button", { name: /^Worked for/ });
282
+ await expect.element(heading).toHaveStyle({ pointerEvents: "auto" });
283
+ const viewport = props.listRef.current!.getScrollableNode()!;
284
+ const distanceFromEnd = () =>
285
+ viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop;
286
+ await vi.waitFor(() => expect(distanceFromEnd()).toBeLessThan(2));
287
+ await heading.click();
288
+ await screen.rerender(
289
+ <MessagesTimeline
290
+ {...props}
291
+ timelineEntries={[
292
+ ...entries,
293
+ message("Streamed reply\n\n".repeat(40), { role: "assistant", runId }, "streamed"),
294
+ ]}
295
+ />,
296
+ );
297
+ await vi.waitFor(() => expect(distanceFromEnd()).toBeLessThan(2));
298
+ });
299
+
300
it.each(["delegated", "legacy", "missing"] as const)(
301
"uses the reported task for %s completion notifications",
302
async (source) => {
apps/web/src/components/chat/MessagesTimeline.tsx
+18
-50
@@ -465,43 +465,19 @@ const ConversationTimeline = memo(function ConversationTimeline({
465
const citationThreadRef = parseScopedThreadKey(routeThreadKey);
466
const openPullRequest = useOpenPrLink(citationThreadRef ?? undefined);
467
const [minimapStripMap] = useState(() => new Map<string, HTMLSpanElement>());
468
- const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
469
- const disclosureAnchorKeyRef = useRef<string | null>(null);
470
- const disclosureSettleFrameRef = useRef<number | null>(null);
471
- const disclosureSettleSecondFrameRef = useRef<number | null>(null);
468
const normalizedFindQuery = findQuery.trim();
469
const findActive = findExpanded;
470
475
- const scheduleDisclosureSettle = () => {
476
- if (disclosureSettleFrameRef.current !== null) {
477
- cancelAnimationFrame(disclosureSettleFrameRef.current);
478
- }
479
- if (disclosureSettleSecondFrameRef.current !== null) {
480
- cancelAnimationFrame(disclosureSettleSecondFrameRef.current);
481
- }
482
- disclosureSettleFrameRef.current = requestAnimationFrame(() => {
483
- disclosureSettleSecondFrameRef.current = requestAnimationFrame(() => {
484
- disclosureAnchorKeyRef.current = null;
485
- setDisclosureToggleSettling(false);
486
- disclosureSettleFrameRef.current = null;
487
- disclosureSettleSecondFrameRef.current = null;
488
- });
489
- });
490
- };
491
-
492
- const suspendEndScrollMaintenanceForDisclosure = (anchorKey: string) => {
493
- disclosureAnchorKeyRef.current = anchorKey;
494
- setDisclosureToggleSettling(true);
495
- scheduleDisclosureSettle();
496
- };
497
-
498
- const shouldRestoreVisibleContentPosition = (row: MessagesTimelineRow) => {
499
- const disclosureAnchorKey = disclosureAnchorKeyRef.current;
500
- return disclosureAnchorKey === null || row.id === disclosureAnchorKey;
471
+ const preserveDisclosurePosition = (anchorKey: string) => {
472
+ const list = listRef.current;
473
+ // An anchor ends end-follow until the reader scrolls, so a streaming turn keeps the live end.
474
+ if (!list || (isWorking && list.getState().isFollowingEnd)) return;
475
+ list.cancelScroll();
476
+ list.anchorVisibleContent({ key: anchorKey });
477
};
478
479
const onToggleTurnFold = (runId: RunId) => {
504
- suspendEndScrollMaintenanceForDisclosure(`turn-fold:${runId}`);
480
+ preserveDisclosurePosition(`turn-fold:${runId}`);
481
setExpandedRunIds((existing) => {
482
const next = new Set(existing);
483
if (next.has(runId)) {
@@ -513,7 +489,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
489
});
490
};
491
const onToggleWorkGroup = (groupId: string, anchorKey: string) => {
516
- suspendEndScrollMaintenanceForDisclosure(anchorKey);
492
+ preserveDisclosurePosition(anchorKey);
493
setExpandedWorkGroupIds((existing) => {
494
const next = new Set(existing);
495
if (next.has(groupId)) {
@@ -525,7 +501,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
501
});
502
};
503
const onToggleAttemptFold = (attemptId: RunAttemptId) => {
528
- suspendEndScrollMaintenanceForDisclosure(`attempt-fold:${attemptId}`);
504
+ preserveDisclosurePosition(`attempt-fold:${attemptId}`);
505
setExpandedAttemptIds((existing) => {
506
const next = new Set(existing);
507
if (next.has(attemptId)) {
@@ -844,7 +820,6 @@ const ConversationTimeline = memo(function ConversationTimeline({
820
const maintainVisibleContentPosition = {
821
data: true,
822
size: true,
847
- shouldRestorePosition: shouldRestoreVisibleContentPosition,
823
};
824
825
const refreshMinimap = useStableCallback(() => {
@@ -859,7 +834,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
834
firstBufferedIndex == null ? undefined : state.elementAtIndex(firstBufferedIndex);
835
const firstBufferedTop =
836
firstBufferedIndex == null ? undefined : state.positionAtIndex(firstBufferedIndex);
862
- const viewport: HTMLElement | undefined = listRef.current?.getScrollableNode();
837
+ const viewport = listRef.current?.getScrollableNode() ?? undefined;
838
// Cached row positions exclude the header and pending scroll adjustments.
839
const scroll =
840
firstBufferedRow && viewport && firstBufferedTop !== undefined
@@ -954,13 +929,6 @@ const ConversationTimeline = memo(function ConversationTimeline({
929
scheduleMinimapRefresh();
930
};
931
957
- const handleItemSizeChanged = () => {
958
- if (disclosureAnchorKeyRef.current !== null) {
959
- scheduleDisclosureSettle();
960
- }
961
- scheduleMinimapRefresh();
962
- };
963
-
932
const measureTimelineGutter = (viewportElement: HTMLElement) => {
933
const viewportWidth = viewportElement.getBoundingClientRect().width;
934
const contentWidth =
@@ -1054,7 +1022,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
1022
onToggleTurnFold,
1023
onToggleAttemptFold,
1024
onToggleWorkGroup,
1057
- onToggleWorkEntry: suspendEndScrollMaintenanceForDisclosure,
1025
+ onToggleWorkEntry: preserveDisclosurePosition,
1026
onCancelWorktreeSetup: onCancelWorktreeSetup ?? null,
1027
retryableWorkspacePreparationRunIds,
1028
onRetryWorkspacePreparation: onRetryWorkspacePreparation ?? null,
@@ -1170,8 +1138,6 @@ const ConversationTimeline = memo(function ConversationTimeline({
1138
detachViewport?.();
1139
viewport?.dispose();
1140
if (viewportRef.current === viewport) viewportRef.current = null;
1173
- // Refresh frames only read the list; disclosure frames still run so the
1174
- // settle flag clears.
1141
if (minimapRefreshFrameRef.current !== null) {
1142
cancelAnimationFrame(minimapRefreshFrameRef.current);
1143
minimapRefreshFrameRef.current = null;
@@ -1341,8 +1307,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
1307
(restoringThreadPosition && rememberedPosition?.atEnd === false) ||
1308
anchoredEndSpace ||
1309
!liveFollowEnabled ||
1344
- fullscreenAppRowId !== null ||
1345
- disclosureToggleSettling
1310
+ fullscreenAppRowId !== null
1311
? false
1312
: isWorking && !prefersReducedMotion && settlingListIdentity === null
1313
? TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH
@@ -1357,7 +1322,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
1322
}
1323
maintainScrollAtEndThreshold={1}
1324
onScroll={handleScroll}
1360
- onItemSizeChanged={handleItemSizeChanged}
1325
+ onItemSizeChanged={scheduleMinimapRefresh}
1326
className={cn(
1327
"messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain [overflow-anchor:none]",
1328
topFadeEnabled && "topbar-scroll-fade",
@@ -1428,11 +1393,14 @@ function keyExtractor(item: MessagesTimelineRow) {
1393
return item.id;
1394
}
1395
1431
-// LegendList averages by type; length buckets prevent inflated estimates and nested-update loops.
1396
+// LegendList estimates unmeasured rows from their type's average. Long messages of equal length
1397
+// can differ in height by orders of magnitude, so each gets its own type to avoid nested-update loops.
1398
function getItemType(item: MessagesTimelineRow) {
1399
if (item.kind !== "message") return item.kind;
1400
const lengthBucket = Math.max(0, Math.floor(Math.log2(item.message.text.length / 1000)));
1435
- return `message:${item.message.role}:${lengthBucket}`;
1401
+ return lengthBucket < 2
1402
+ ? `message:${item.message.role}:${lengthBucket}`
1403
+ : `message:${item.message.id}`;
1404
}
1405
1406
const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: TimelineRow }) {
apps/web/src/components/chat/ModelPickerContent.tsx
+8
-31
@@ -1,3 +1,4 @@
1
+import { useLegendListRef } from "~/hooks/useLegendListRef";
2
import {
3
ANTIGRAVITY_DEFAULT_MODEL,
4
type ProviderInstanceId,
@@ -264,37 +265,12 @@ function ModelPickerList({
265
const [showTopScrollFade, setShowTopScrollFade] = useState(false);
266
const [showBottomScrollFade, setShowBottomScrollFade] = useState(false);
267
const updateScrollFades = () => {
267
- const scrollElement = listRef.current?.getScrollableNode();
268
- if (!(scrollElement instanceof HTMLElement)) {
269
- return;
270
- }
271
- const maxScrollOffset = Math.max(0, scrollElement.scrollHeight - scrollElement.clientHeight);
272
- setShowTopScrollFade(scrollElement.scrollTop > 1);
273
- setShowBottomScrollFade(maxScrollOffset - scrollElement.scrollTop > 1);
268
+ const metrics = listRef.current?.getState();
269
+ if (!metrics) return;
270
+ setShowTopScrollFade(!metrics.isAtStart);
271
+ setShowBottomScrollFade(!metrics.isAtEnd);
272
};
275
-
276
- // Disabled-reason closures rebuild identical key arrays; compare contents.
277
- const itemListKey = JSON.stringify(itemKeys);
278
- const [fadesResetFor, setFadesResetFor] = useState(itemListKey);
279
- if (fadesResetFor !== itemListKey) {
280
- setFadesResetFor(itemListKey);
281
- setShowTopScrollFade(false);
282
- setShowBottomScrollFade(itemKeys.length > 5);
283
- }
284
- const measureScrollFades = useEffectEvent(updateScrollFades);
285
- // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the list scroller in animation frames after a new list lays out to set scroll fades
286
- useLayoutEffect(() => {
287
- let nestedFrame = 0;
288
- const frame = window.requestAnimationFrame(() => {
289
- measureScrollFades();
290
- nestedFrame = window.requestAnimationFrame(() => measureScrollFades());
291
- });
292
- return () => {
293
- window.cancelAnimationFrame(frame);
294
- window.cancelAnimationFrame(nestedFrame);
295
- };
296
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A new list re-measures its scroll fades once it has laid out.
297
- }, [itemListKey]);
273
+ const scrollRef = useLegendListRef(listRef, updateScrollFades);
274
275
return (
276
<div
@@ -305,7 +281,7 @@ function ModelPickerList({
281
>
282
<ComboboxListVirtualized>
283
<LegendList<string>
308
- ref={listRef}
284
+ ref={scrollRef}
285
data={itemKeys}
286
extraData={extraData}
287
keyExtractor={(modelKey) => modelKey}
@@ -317,6 +293,7 @@ function ModelPickerList({
293
ItemSeparatorComponent={ModelListSeparator}
294
onLayout={updateScrollFades}
295
onScroll={updateScrollFades}
296
+ onReady={updateScrollFades}
297
className={cn(
298
"scrollbar-gutter-stable h-full overflow-x-hidden overscroll-y-contain py-1.5 [&::-webkit-scrollbar-track]:my-2",
299
getVirtualizedScrollFadeClassName({
apps/web/src/components/chat/timelineViewport.browser.test.tsx
new
+61
@@ -0,0 +1,61 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+import { userEvent } from "vite-plus/test/browser";
3
+
4
+import { render } from "../../../test/render";
5
+import { attachTimelineViewport } from "./timelineViewport";
6
+
7
+describe("attachTimelineViewport", () => {
8
+ it("reports an upward scroll only while input is on an embedded frame", async () => {
9
+ // A plain scroller; the viewport needs no routes.
10
+ await using screen = await render(
11
+ <div>
12
+ <div data-testid="outside" style={{ height: 40 }} />
13
+ <div data-testid="timeline" style={{ height: 300, overflowY: "auto" }}>
14
+ <div style={{ height: 1200 }} />
15
+ <iframe
16
+ title="render"
17
+ sandbox=""
18
+ srcDoc="<p>frame</p>"
19
+ style={{ display: "block", height: 200 }}
20
+ />
21
+ <div data-testid="tail" style={{ height: 1200 }} />
22
+ </div>
23
+ </div>,
24
+ { router: false },
25
+ );
26
+ const timeline = screen.getByTestId("timeline").element() as HTMLElement;
27
+ const tail = screen.getByTestId("tail").element() as HTMLElement;
28
+ const scrolled = () =>
29
+ new Promise<void>((resolve) =>
30
+ timeline.addEventListener("scroll", () => resolve(), { once: true }),
31
+ );
32
+ let scroll = scrolled();
33
+ timeline.scrollTop = 1500;
34
+ await scroll;
35
+ const viewport = attachTimelineViewport(timeline);
36
+ const sources: string[] = [];
37
+ viewport.subscribe((navigation) => sources.push(navigation.source));
38
+
39
+ await userEvent.hover(screen.getByTestId("outside"));
40
+ scroll = scrolled();
41
+ timeline.scrollTop -= 100;
42
+ await scroll;
43
+ // Content that shrinks and grows back in one task clamps scrollTop with no input at all.
44
+ scroll = scrolled();
45
+ timeline.scrollTop = timeline.scrollHeight;
46
+ await scroll;
47
+ scroll = scrolled();
48
+ tail.style.height = "400px";
49
+ void timeline.scrollTop;
50
+ tail.style.height = "1200px";
51
+ await scroll;
52
+ expect(sources).toEqual([]);
53
+
54
+ await userEvent.hover(screen.getByTitle("render"));
55
+ scroll = scrolled();
56
+ timeline.scrollTop -= 100;
57
+ await scroll;
58
+ expect(sources).toEqual(["scroll"]);
59
+ viewport.dispose();
60
+ });
61
+});
apps/web/src/components/chat/timelineViewport.ts
+7
@@ -117,6 +117,12 @@ export function attachTimelineViewport(scrollNode: HTMLElement): TimelineViewpor
117
top: scrollNode.scrollTop,
118
height: scrollNode.scrollHeight,
119
});
120
+ // Only a frame's input reaches the timeline unseen. Any other unexplained upward move is not
121
+ // the reader's: the browser clamps scrollTop when content briefly shrinks.
122
+ const frameHasInput = () =>
123
+ scrollNode.querySelector("iframe:hover") !== null ||
124
+ (document.activeElement instanceof HTMLIFrameElement &&
125
+ scrollNode.contains(document.activeElement));
126
const handleScroll = () => {
127
if (
128
scrolledUp({
@@ -124,6 +130,7 @@ export function attachTimelineViewport(scrollNode: HTMLElement): TimelineViewpor
130
height: scrollNode.scrollHeight,
131
programmatic: programmaticHolds > 0,
132
}) &&
133
+ frameHasInput() &&
134
// LegendList updates its scroll state on the next animation frame.
135
resolveTimelineIsAtEnd({
136
contentLength: scrollNode.scrollHeight,
apps/web/src/components/chat/useTimelineFollow.ts
+1
-21
@@ -40,8 +40,6 @@ import type { deriveThreadActivityRun } from "@t3tools/client-runtime/state/thre
40
import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
41
import type { TimelineEntry } from "../../session-logic";
42
43
-const TIMELINE_SCROLL_CANCEL_SENTINEL = Object.freeze({});
44
-
43
interface TimelineAnchor {
44
readonly threadKey: string | null;
45
readonly messageId: MessageId | null;
@@ -247,25 +245,7 @@ export function useTimelineFollow(input: TimelineFollowInput) {
245
cancelAnimationFrame(scroll.anchorScrollRestoreFrame);
246
scroll.anchorScrollRestoreFrame = null;
247
}
250
- if (before.mode === "following") {
251
- // LegendList may run queued scrolls after user navigation. A new imperative
252
- // scroll cancels that queue; a missing item cancels without moving the view.
253
- void legendListRef.current?.scrollToItem({
254
- item: TIMELINE_SCROLL_CANCEL_SENTINEL,
255
- animated: false,
256
- });
257
- // An already-started animated scroll (behavior: smooth) keeps running in
258
- // the browser regardless of the queue; a same-position instant write is
259
- // the only way to halt it where it is.
260
- const scrollNode = legendListRef.current?.getScrollableNode() as
261
- | { scrollTop?: number }
262
- | null
263
- | undefined;
264
- const currentScrollTop = scrollNode?.scrollTop;
265
- if (scrollNode && typeof currentScrollTop === "number") {
266
- scrollNode.scrollTop = currentScrollTop;
267
- }
268
- }
248
+ if (before.mode === "following") legendListRef.current?.cancelScroll();
249
};
250
251
// A run that starts while the live end is followed anchors its user message
apps/web/src/components/guest/GuestPage.browser.test.tsx
+3
-1
@@ -341,13 +341,15 @@ describe("GuestPage", () => {
341
node.dispatchEvent(new Event("scroll"));
342
await expect.element(screen.getByRole("button", { name: /scroll to/i })).toBeVisible();
343
344
- // The guest's own message waits at the end for the owner.
344
+ // The guest sends; their message waits at the end for the owner.
345
const waiting = {
346
id: GuestMessageId.make("guest-1"),
347
text: "Can you also check the logout flow?",
348
status: "pending" as const,
349
submittedAt: "2026-10-23T10:01:00.000Z",
350
};
351
+ await userEvent.type(screen.getByRole("textbox", { name: "Message" }), waiting.text);
352
+ await userEvent.click(screen.getByRole("button", { name: "Send" }));
353
send({ type: "view", view: { ...view, messages: [waiting] } });
354
await expect.element(screen.getByText(waiting.text)).toBeInTheDocument();
355
await expectAtEnd();
apps/web/src/components/guest/GuestPage.tsx
+7
-28
@@ -39,7 +39,6 @@ import { useIncrementalTimelineEntries } from "~/hooks/useIncrementalTimelineEnt
39
import { useNowMinute } from "~/hooks/useNowMinute";
40
import { useStableCallback } from "~/hooks/useStableCallback";
41
import { useTheme } from "~/hooks/useTheme";
42
-import { observeResize } from "~/lib/observeResize";
42
import { cn } from "~/lib/utils";
43
import { deriveActiveWorkStartedAt, derivePhase } from "~/session-logic";
44
import { ComposerControl, ComposerControlIcon } from "../chat/ComposerControl";
@@ -472,31 +471,6 @@ function GuestThread({
471
),
472
);
473
const unplaced = unplacedGuestMessages(messages, items, awaitingRowIds);
475
- // The guest's waiting messages sit in the list footer, which the list does not follow on its
476
- // own (the owner's view does the same in ChatView). A new one is the guest's own send, so it
477
- // comes into view even if they had scrolled up, as the owner's send does. While following, the
478
- // footer stays in view as it grows, such as when its images load.
479
- const unplacedKey = unplaced.map((message) => message.id).join(",");
480
- const previousUnplacedKey = useRef(unplacedKey);
481
- const following = useRef(follow.timelineLiveFollowEnabled);
482
- const scrollToEnd = useStableCallback(follow.scrollToEnd);
483
- // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the timeline to the end after commit when new unplaced messages appear
484
- useEffect(() => {
485
- following.current = follow.timelineLiveFollowEnabled;
486
- const previous = new Set(previousUnplacedKey.current.split(","));
487
- previousUnplacedKey.current = unplacedKey;
488
- if (unplacedKey.split(",").some((id) => id !== "" && !previous.has(id))) scrollToEnd(true);
489
- }, [follow.timelineLiveFollowEnabled, unplacedKey, scrollToEnd, following, previousUnplacedKey]);
490
- const footerRef = useRef<HTMLOListElement>(null);
491
- const hasFooter = unplaced.length > 0;
492
- // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- ResizeObserver on the footer keeps it scrolled into view while following
493
- useEffect(() => {
494
- const footer = footerRef.current;
495
- if (!hasFooter || footer === null) return;
496
- return observeResize(footer, () => {
497
- if (following.current) scrollToEnd();
498
- });
499
- }, [hasFooter, scrollToEnd, following]);
474
return (
475
<>
476
<header className="flex shrink-0 items-center gap-3 border-b border-border px-4 py-2.5">
@@ -538,9 +512,10 @@ function GuestThread({
512
liveFollowEnabled={follow.timelineLiveFollowEnabled}
513
onIsAtEndChange={follow.onIsAtEndChangeStable}
514
onViewportAttach={follow.attachTimelineViewport}
515
+ onFooterGrow={follow.onTimelineFooterGrowStable}
516
footer={
517
unplaced.length === 0 ? null : (
543
- <ol ref={footerRef} className="chat-content-lane flex flex-col gap-4 pb-4">
518
+ <ol className="chat-content-lane flex flex-col gap-4 pb-4">
519
{unplaced.map((message) => (
520
<li key={message.id}>
521
<UnplacedGuestMessage shareId={shareId} message={message} />
@@ -560,7 +535,7 @@ function GuestThread({
535
) : null}
536
</div>
537
<div className={cn(LANE, "shrink-0 pb-4")}>
563
- <GuestComposer shareId={shareId} model={model} />
538
+ <GuestComposer shareId={shareId} model={model} onSent={() => follow.scrollToEnd(true)} />
539
</div>
540
</>
541
);
@@ -668,9 +643,12 @@ function StagedImage({ file }: { readonly file: File }) {
643
function GuestComposer({
644
shareId,
645
model,
646
+ onSent,
647
}: {
648
readonly shareId: GuestShareView["shareId"];
649
readonly model: GuestThreadModel;
650
+ /** The guest's own message comes into view even if they had scrolled up, as the owner's does. */
651
+ readonly onSent: () => void;
652
}) {
653
const [text, setText] = useState("");
654
const [files, setFiles] = useState<ReadonlyArray<StagedFile>>([]);
@@ -706,6 +684,7 @@ function GuestComposer({
684
setError(failure);
685
// Keep anything typed or attached while the request was in flight.
686
if (failure === null) {
687
+ onSent();
688
setText((current) => (current.trim() === trimmed ? "" : current));
689
setFiles((current) => current.filter((staged) => !sentFiles.includes(staged)));
690
}
apps/web/src/components/settings/FontFamilyPicker.tsx
+17
-3
@@ -1,3 +1,4 @@
1
+import { useLegendListRef } from "~/hooks/useLegendListRef";
2
import { LegendList, type LegendListRef } from "@legendapp/list/react";
3
import { CheckIcon } from "lucide-react";
4
import { useEffect, useRef, useState, useSyncExternalStore } from "react";
@@ -104,6 +105,12 @@ export function FontFamilyPicker({
105
if (openAfterMount) setOpen(true);
106
}, [openAfterMount]);
107
const listRef = useRef<LegendListRef | null>(null);
108
+ const [listHeight, setListHeight] = useState(288);
109
+ const handleMetricsChange = () => {
110
+ const metrics = listRef.current?.getState();
111
+ if (metrics) setListHeight(Math.min(metrics.contentLength, 288));
112
+ };
113
+ const scrollRef = useLegendListRef(listRef, handleMetricsChange);
114
const enumeration = useFontEnumeration();
115
116
const handleOpenChange = (nextOpen: boolean) => {
@@ -162,6 +169,8 @@ export function FontFamilyPicker({
169
);
170
};
171
172
+ const extraData = { items, selectedValue, defaultFamily };
173
+
174
return (
175
<Combobox
176
items={items}
@@ -193,16 +202,21 @@ export function FontFamilyPicker({
202
<div className="relative min-h-0 max-h-72 w-full flex-1 overflow-hidden">
203
<ComboboxListVirtualized>
204
<LegendList<string>
196
- ref={listRef}
205
+ ref={scrollRef}
206
data={items}
207
+ dataKey={query}
208
+ initialScrollOffset={0}
209
// Base UI selects virtualized rows by index; rerender surviving items when filtering changes
210
// their indices.
200
- extraData={items}
211
+ extraData={extraData}
212
keyExtractor={(item) => item}
213
renderItem={({ item, index }) => renderItem(item, index)}
214
estimatedItemSize={30}
215
drawDistance={360}
205
- style={{ height: Math.min(items.length * 30, 288) }}
216
+ onScroll={handleMetricsChange}
217
+ onLayout={handleMetricsChange}
218
+ onReady={handleMetricsChange}
219
+ style={{ height: listHeight }}
220
/>
221
</ComboboxListVirtualized>
222
</div>
apps/web/src/hooks/useLegendListRef.browser.test.tsx
new
+48
@@ -0,0 +1,48 @@
1
+import { LegendList, type LegendListRef } from "@legendapp/list/react";
2
+import { createRef, useState, type RefObject } from "react";
3
+import { expect, it } from "vite-plus/test";
4
+import { act, render } from "../../test/render";
5
+import { useLegendListRef } from "./useLegendListRef";
6
+
7
+function ListProbe({
8
+ items,
9
+ listRef,
10
+}: {
11
+ items: string[];
12
+ listRef: RefObject<LegendListRef | null>;
13
+}) {
14
+ const [edges, setEdges] = useState("");
15
+ const ref = useLegendListRef(listRef, () => {
16
+ const state = listRef.current?.getState();
17
+ if (state) setEdges(`${state.isAtStart}:${state.isAtEnd}`);
18
+ });
19
+ return (
20
+ <>
21
+ <output aria-label="List edges">{edges}</output>
22
+ <LegendList
23
+ ref={ref}
24
+ data={items}
25
+ keyExtractor={(item) => item}
26
+ renderItem={({ item }) => <div style={{ height: 40 }}>{item}</div>}
27
+ style={{ height: 120, width: 300 }}
28
+ />
29
+ </>
30
+ );
31
+}
32
+
33
+it("refreshes list edges after content shrinks without scrolling and after the list reopens", async () => {
34
+ const listRef = createRef<LegendListRef | null>();
35
+ const items = Array.from({ length: 20 }, (_, index) => `Row ${index}`);
36
+ await using screen = await render(<ListProbe items={items} listRef={listRef} />);
37
+ await expect.element(screen.getByLabelText("List edges")).toHaveTextContent("true:false");
38
+ await act(() => {
39
+ void listRef.current!.scrollToEnd({ animated: false });
40
+ });
41
+ await expect.element(screen.getByLabelText("List edges")).toHaveTextContent("false:true");
42
+ await screen.rerender(<ListProbe items={["Only row"]} listRef={listRef} />);
43
+ await expect.element(screen.getByLabelText("List edges")).toHaveTextContent("true:true");
44
+ await screen.rerender(<></>);
45
+ expect(listRef.current).toBeNull();
46
+ await screen.rerender(<ListProbe items={items} listRef={listRef} />);
47
+ await expect.element(screen.getByLabelText("List edges")).toHaveTextContent("true:false");
48
+});
apps/web/src/hooks/useLegendListRef.ts
new
+25
@@ -0,0 +1,25 @@
1
+import type { LegendListRef } from "@legendapp/list/react";
2
+import { type RefObject } from "react";
3
+import { useStableCallback } from "./useStableCallback";
4
+
5
+/** Refresh scroll-derived UI when layout changes without a scroll event. */
6
+export function useLegendListRef(listRef: RefObject<LegendListRef | null>, onChange: () => void) {
7
+ const notify = useStableCallback(onChange);
8
+ return (list: LegendListRef | null) => {
9
+ listRef.current = list;
10
+ if (!list) return;
11
+ const state = list.getState();
12
+ const stops = [
13
+ state.listen("totalSize", notify),
14
+ state.listen("headerSize", notify),
15
+ state.listen("footerSize", notify),
16
+ state.listen("isAtStart", notify),
17
+ state.listen("isAtEnd", notify),
18
+ ];
19
+ notify();
20
+ return () => {
21
+ for (const stop of stops) stop();
22
+ listRef.current = null;
23
+ };
24
+ };
25
+}
apps/web/src/state/paginatedBranches.test.ts
+1
-55
@@ -2,10 +2,7 @@ import type { VcsListRefsResult } from "@t3tools/contracts";
2
import { AsyncResult } from "effect/reactivity";
3
import { describe, expect, it } from "vite-plus/test";
4
5
-import {
6
- isPaginatedBranchesNextPagePending,
7
- shouldLoadNextBranchPageAfterScroll,
8
-} from "./paginatedBranches";
5
+import { isPaginatedBranchesNextPagePending } from "./paginatedBranches";
6
7
const FIRST_PAGE: VcsListRefsResult = {
8
refs: [],
@@ -47,54 +44,3 @@ describe("paginated branch loading state", () => {
44
).toBe(false);
45
});
46
});
50
-
51
-describe("paginated branch scroll trigger", () => {
52
- it("does not load from mount, layout, or an unchanged scroll position", () => {
53
- expect(
54
- shouldLoadNextBranchPageAfterScroll({
55
- previousScrollTop: null,
56
- scrollTop: 0,
57
- scrollHeight: 224,
58
- clientHeight: 224,
59
- }),
60
- ).toBe(false);
61
-
62
- expect(
63
- shouldLoadNextBranchPageAfterScroll({
64
- previousScrollTop: 120,
65
- scrollTop: 120,
66
- scrollHeight: 344,
67
- clientHeight: 224,
68
- }),
69
- ).toBe(false);
70
- });
71
-
72
- it("loads only after a downward scroll reaches the end threshold", () => {
73
- expect(
74
- shouldLoadNextBranchPageAfterScroll({
75
- previousScrollTop: 0,
76
- scrollTop: 100,
77
- scrollHeight: 800,
78
- clientHeight: 224,
79
- }),
80
- ).toBe(false);
81
-
82
- expect(
83
- shouldLoadNextBranchPageAfterScroll({
84
- previousScrollTop: 100,
85
- scrollTop: 500,
86
- scrollHeight: 800,
87
- clientHeight: 224,
88
- }),
89
- ).toBe(true);
90
-
91
- expect(
92
- shouldLoadNextBranchPageAfterScroll({
93
- previousScrollTop: 499.5,
94
- scrollTop: 500,
95
- scrollHeight: 800,
96
- clientHeight: 224,
97
- }),
98
- ).toBe(true);
99
- });
100
-});
apps/web/src/state/paginatedBranches.ts
-22
@@ -2,8 +2,6 @@ import type { VcsListRefsResult } from "@t3tools/contracts";
2
import * as Option from "effect/Option";
3
import { AsyncResult } from "effect/reactivity";
4
5
-const DEFAULT_NEXT_PAGE_DISTANCE_PX = 96;
6
-
5
export function isPaginatedBranchesNextPagePending<E>(
6
results: ReadonlyArray<AsyncResult.AsyncResult<VcsListRefsResult, E>>,
7
): boolean {
@@ -14,23 +12,3 @@ export function isPaginatedBranchesNextPagePending<E>(
12
Option.isNone(AsyncResult.value(lastResult))
13
);
14
}
17
-
18
-export function shouldLoadNextBranchPageAfterScroll({
19
- previousScrollTop,
20
- scrollTop,
21
- scrollHeight,
22
- clientHeight,
23
- distanceThreshold = DEFAULT_NEXT_PAGE_DISTANCE_PX,
24
-}: {
25
- previousScrollTop: number | null;
26
- scrollTop: number;
27
- scrollHeight: number;
28
- clientHeight: number;
29
- distanceThreshold?: number;
30
-}): boolean {
31
- if (previousScrollTop === null || scrollTop <= previousScrollTop) {
32
- return false;
33
- }
34
-
35
- return scrollHeight - scrollTop - clientHeight <= distanceThreshold;
36
-}
patches/@legendapp__list@3.3.5.patch
deleted
-2552
@@ -1,2552 +0,0 @@
1
-diff --git a/animated.d.ts b/animated.d.ts
2
-index 14beb98c0bfed9c60611b7d164670798011182ac..9fb0ca056d9dda4d4abeef2bb9bafcf70d0fa243 100644
3
---- a/animated.d.ts
4
-+++ b/animated.d.ts
5
-@@ -284,6 +284,11 @@ interface LegendListSpecificProps<ItemT, TItemType extends string | undefined> {
6
- * - true enables both behaviors; false disables both.
7
- */
8
- maintainVisibleContentPosition?: boolean | MaintainVisibleContentPositionConfig<ItemT>;
9
-+ /**
10
-+ * T3 patch: the scroll offset a change in item or list size should leave, read in the same pass
11
-+ * that repositions the items so the adjustment commits with them. `undefined` keeps the default.
12
-+ */
13
-+ sizeChangeAnchor?: () => number | undefined;
14
- /**
15
- * Keeps an item visually anchored to the start by adding trailing space when the content below it underflows.
16
- */
17
-diff --git a/keyboard.d.ts b/keyboard.d.ts
18
-index 367945cdfa8a8c260b7a127657a75c016c9ab46f..0ac7bf8b8e9c386058b2374199e58fe8c92d39b3 100644
19
---- a/keyboard.d.ts
20
-+++ b/keyboard.d.ts
21
-@@ -279,7 +279,7 @@ type KeyboardChatComposerInsetListRef = {
22
- type KeyboardChatComposerRef = {
23
- current: Pick<View, "measure"> | null;
24
- };
25
--declare function useKeyboardChatComposerInset(listRef: KeyboardChatComposerInsetListRef, composerRef: KeyboardChatComposerRef, initialHeight?: number): {
26
-+declare function useKeyboardChatComposerInset(listRef: KeyboardChatComposerInsetListRef, composerRef: KeyboardChatComposerRef, initialHeight?: number, heightAdjustment?: number, animationDuration?: number): {
27
- contentInsetEndAdjustment: SharedValue<number>;
28
- onComposerLayout: (event: LayoutChangeEvent) => void;
29
- };
30
-@@ -288,8 +288,10 @@ declare function useKeyboardScrollToEnd({ freeze: freezeProp, listRef }: UseKeyb
31
- scrollMessageToEnd: ({ animated, closeKeyboard }: ScrollMessageToEndOptions) => Promise<void>;
32
- };
33
- declare const KeyboardAwareLegendList: <ItemT>(props: Omit<AnimatedLegendListProps<ItemT>, "anchoredEndSpace" | "contentInsetEndAdjustment" | "renderScrollComponent"> & KeyboardChatScrollViewPropsUnique & {
34
-+ adjustedInsetCompensation?: number;
35
- anchoredEndSpace?: AnchoredEndSpaceConfig;
36
- contentInsetEndAdjustment?: SharedValue<number>;
37
-+ contentInsetEndStaticAdjustment?: number;
38
- keyboardOffset?: number;
39
- } & React.RefAttributes<LegendListRef>) => React.ReactElement | null;
40
-
41
-diff --git a/keyboard.js b/keyboard.js
42
-index 6645bcbb1f77c36c432035eaf8b2d6d924fc8bda..321c4c305129dd3ce3f06127c47d51720a73fb83 100644
43
---- a/keyboard.js
44
-+++ b/keyboard.js
45
-@@ -33,19 +33,22 @@ if (typeof __DEV__ !== "undefined" && __DEV__ && !reactNativeKeyboardController.
46
- "[legend-list] KeyboardAwareLegendList requires a recent react-native-keyboard-controller with KeyboardChatScrollView. Please upgrade react-native-keyboard-controller to at least 1.21.7."
47
- );
48
- }
49
--function useKeyboardChatComposerInset(listRef, composerRef, initialHeight = 0) {
50
-+function useKeyboardChatComposerInset(listRef, composerRef, initialHeight = 0, heightAdjustment = 0, animationDuration = 0) {
51
- const contentInsetEndAdjustment = reactNativeReanimated.useSharedValue(initialHeight);
52
- const lastHeightRef = React.useRef(void 0);
53
- const reportHeight = React.useCallback(
54
-- (height) => {
55
-+ (rawHeight) => {
56
-+ const height = Math.max(0, rawHeight + heightAdjustment);
57
- var _a;
58
- if (Number.isFinite(height) && height !== lastHeightRef.current) {
59
-+ const shouldAnimate = lastHeightRef.current !== void 0 && animationDuration > 0;
60
- lastHeightRef.current = height;
61
-- contentInsetEndAdjustment.value = height;
62
-- (_a = listRef.current) == null ? void 0 : _a.reportContentInset({ bottom: height });
63
-+ contentInsetEndAdjustment.value = shouldAnimate ? reactNativeReanimated.withTiming(height, {
64
-+ duration: animationDuration
65
-+ }) : height;
66
- }
67
- },
68
-- [contentInsetEndAdjustment, listRef]
69
-+ [animationDuration, contentInsetEndAdjustment, heightAdjustment, listRef]
70
- );
71
- React.useLayoutEffect(() => {
72
- var _a;
73
-@@ -84,9 +87,11 @@ function useKeyboardScrollToEnd({ freeze: freezeProp, listRef }) {
74
- }
75
- var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(props, forwardedRef) {
76
- const {
77
-+ adjustedInsetCompensation,
78
- anchoredEndSpace,
79
- applyWorkaroundForContentInsetHitTestBug,
80
- contentInsetEndAdjustment,
81
-+ contentInsetEndStaticAdjustment,
82
- freeze,
83
- keyboardLiftBehavior,
84
- keyboardOffset,
85
-@@ -94,6 +99,7 @@ var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(
86
- } = props;
87
- const refLegendList = React.useRef(null);
88
- const combinedRef = useCombinedRef(forwardedRef, refLegendList);
89
-+ const adjustedStartInsetCompensation = props.contentInsetStartAdjustment;
90
- const blankSpace = reactNativeReanimated.useSharedValue(0);
91
- React.useEffect(() => {
92
- if (!anchoredEndSpace) {
93
-@@ -108,11 +114,15 @@ var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(
94
- ...anchoredEndSpace,
95
- onSizeChanged: (size) => {
96
- var _a;
97
-- blankSpace.value = size;
98
-+ // The anchored blank is sized against the ADJUSTED viewport, but the
99
-+ // scroll component writes it as a raw contentInset that UIKit tops up
100
-+ // with the safe-area bottom — write it net of that or the end rest
101
-+ // (and the anchored message) sinks one safe-area under the header.
102
-+ blankSpace.value = size > 0 ? Math.max(0, size - (adjustedInsetCompensation || 0)) : 0;
103
- (_a = anchoredEndSpace.onSizeChanged) == null ? void 0 : _a.call(anchoredEndSpace, size);
104
- }
105
- };
106
-- }, [anchoredEndSpace, blankSpace]);
107
-+ }, [adjustedInsetCompensation, anchoredEndSpace, blankSpace]);
108
- const onContentInsetChange = React.useCallback((insets) => {
109
- var _a;
110
- (_a = refLegendList.current) == null ? void 0 : _a.reportContentInset(insets);
111
-@@ -123,6 +133,8 @@ var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(
112
- reactNativeKeyboardController.KeyboardChatScrollView,
113
- {
114
- ...scrollProps,
115
-+ adjustedInsetCompensation,
116
-+ adjustedStartInsetCompensation,
117
- applyWorkaroundForContentInsetHitTestBug,
118
- blankSpace,
119
- extraContentPadding: contentInsetEndAdjustment,
120
-@@ -134,6 +146,8 @@ var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(
121
- );
122
- },
123
- [
124
-+ adjustedInsetCompensation,
125
-+ adjustedStartInsetCompensation,
126
- applyWorkaroundForContentInsetHitTestBug,
127
- blankSpace,
128
- contentInsetEndAdjustment,
129
-@@ -149,6 +163,7 @@ var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(
130
- {
131
- anchoredEndSpace: anchoredEndSpaceWithBlankSpace,
132
- anchoredEndSpaceOwnerInternal: "scroll",
133
-+ contentInsetEndAdjustment: contentInsetEndStaticAdjustment,
134
- ref: combinedRef,
135
- renderScrollComponent: memoList,
136
- ...rest
137
-diff --git a/keyboard.mjs b/keyboard.mjs
138
-index 87b38b9607c2eba6b407c2acfd520633bdb0e7c2..111eb242ba9d9ade1cb912550f7df85cf4f361ee 100644
139
---- a/keyboard.mjs
140
-+++ b/keyboard.mjs
141
-@@ -1,7 +1,7 @@
142
- import * as React from 'react';
143
- import { useRef, useEffect, useMemo, useCallback, useLayoutEffect } from 'react';
144
- import { KeyboardChatScrollView, KeyboardController } from 'react-native-keyboard-controller';
145
--import { useSharedValue } from 'react-native-reanimated';
146
-+import { useSharedValue, withTiming } from 'react-native-reanimated';
147
- import { internal } from '@legendapp/list/react-native';
148
- import { AnimatedLegendList } from '@legendapp/list/reanimated';
149
-
150
-@@ -12,19 +12,22 @@ if (typeof __DEV__ !== "undefined" && __DEV__ && !KeyboardChatScrollView) {
151
- "[legend-list] KeyboardAwareLegendList requires a recent react-native-keyboard-controller with KeyboardChatScrollView. Please upgrade react-native-keyboard-controller to at least 1.21.7."
152
- );
153
- }
154
--function useKeyboardChatComposerInset(listRef, composerRef, initialHeight = 0) {
155
-+function useKeyboardChatComposerInset(listRef, composerRef, initialHeight = 0, heightAdjustment = 0, animationDuration = 0) {
156
- const contentInsetEndAdjustment = useSharedValue(initialHeight);
157
- const lastHeightRef = useRef(void 0);
158
- const reportHeight = useCallback(
159
-- (height) => {
160
-+ (rawHeight) => {
161
-+ const height = Math.max(0, rawHeight + heightAdjustment);
162
- var _a;
163
- if (Number.isFinite(height) && height !== lastHeightRef.current) {
164
-+ const shouldAnimate = lastHeightRef.current !== void 0 && animationDuration > 0;
165
- lastHeightRef.current = height;
166
-- contentInsetEndAdjustment.value = height;
167
-- (_a = listRef.current) == null ? void 0 : _a.reportContentInset({ bottom: height });
168
-+ contentInsetEndAdjustment.value = shouldAnimate ? withTiming(height, {
169
-+ duration: animationDuration
170
-+ }) : height;
171
- }
172
- },
173
-- [contentInsetEndAdjustment, listRef]
174
-+ [animationDuration, contentInsetEndAdjustment, heightAdjustment, listRef]
175
- );
176
- useLayoutEffect(() => {
177
- var _a;
178
-@@ -63,9 +66,11 @@ function useKeyboardScrollToEnd({ freeze: freezeProp, listRef }) {
179
- }
180
- var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(props, forwardedRef) {
181
- const {
182
-+ adjustedInsetCompensation,
183
- anchoredEndSpace,
184
- applyWorkaroundForContentInsetHitTestBug,
185
- contentInsetEndAdjustment,
186
-+ contentInsetEndStaticAdjustment,
187
- freeze,
188
- keyboardLiftBehavior,
189
- keyboardOffset,
190
-@@ -73,6 +78,7 @@ var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(
191
- } = props;
192
- const refLegendList = useRef(null);
193
- const combinedRef = useCombinedRef(forwardedRef, refLegendList);
194
-+ const adjustedStartInsetCompensation = props.contentInsetStartAdjustment;
195
- const blankSpace = useSharedValue(0);
196
- useEffect(() => {
197
- if (!anchoredEndSpace) {
198
-@@ -87,11 +93,15 @@ var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(
199
- ...anchoredEndSpace,
200
- onSizeChanged: (size) => {
201
- var _a;
202
-- blankSpace.value = size;
203
-+ // The anchored blank is sized against the ADJUSTED viewport, but the
204
-+ // scroll component writes it as a raw contentInset that UIKit tops up
205
-+ // with the safe-area bottom — write it net of that or the end rest
206
-+ // (and the anchored message) sinks one safe-area under the header.
207
-+ blankSpace.value = size > 0 ? Math.max(0, size - (adjustedInsetCompensation || 0)) : 0;
208
- (_a = anchoredEndSpace.onSizeChanged) == null ? void 0 : _a.call(anchoredEndSpace, size);
209
- }
210
- };
211
-- }, [anchoredEndSpace, blankSpace]);
212
-+ }, [adjustedInsetCompensation, anchoredEndSpace, blankSpace]);
213
- const onContentInsetChange = useCallback((insets) => {
214
- var _a;
215
- (_a = refLegendList.current) == null ? void 0 : _a.reportContentInset(insets);
216
-@@ -102,6 +112,8 @@ var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(
217
- KeyboardChatScrollView,
218
- {
219
- ...scrollProps,
220
-+ adjustedInsetCompensation,
221
-+ adjustedStartInsetCompensation,
222
- applyWorkaroundForContentInsetHitTestBug,
223
- blankSpace,
224
- extraContentPadding: contentInsetEndAdjustment,
225
-@@ -113,6 +125,8 @@ var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(
226
- );
227
- },
228
- [
229
-+ adjustedInsetCompensation,
230
-+ adjustedStartInsetCompensation,
231
- applyWorkaroundForContentInsetHitTestBug,
232
- blankSpace,
233
- contentInsetEndAdjustment,
234
-@@ -128,6 +142,7 @@ var KeyboardAwareLegendList = typedForwardRef(function KeyboardAwareLegendList2(
235
- {
236
- anchoredEndSpace: anchoredEndSpaceWithBlankSpace,
237
- anchoredEndSpaceOwnerInternal: "scroll",
238
-+ contentInsetEndAdjustment: contentInsetEndStaticAdjustment,
239
- ref: combinedRef,
240
- renderScrollComponent: memoList,
241
- ...rest
242
-diff --git a/react-native.d.ts b/react-native.d.ts
243
-index ce1fe00001c9e5aee6c6ea8bb2d4757d4586d002..ca6e596aa53327a097a388ffd545a4c6191f24e6 100644
244
---- a/react-native.d.ts
245
-+++ b/react-native.d.ts
246
-@@ -284,6 +284,11 @@ interface LegendListSpecificProps<ItemT, TItemType extends string | undefined> {
247
- * - true enables both behaviors; false disables both.
248
- */
249
- maintainVisibleContentPosition?: boolean | MaintainVisibleContentPositionConfig<ItemT>;
250
-+ /**
251
-+ * T3 patch: the scroll offset a change in item or list size should leave, read in the same pass
252
-+ * that repositions the items so the adjustment commits with them. `undefined` keeps the default.
253
-+ */
254
-+ sizeChangeAnchor?: () => number | undefined;
255
- /**
256
- * Keeps an item visually anchored to the start by adding trailing space when the content below it underflows.
257
- */
258
-@@ -293,6 +298,12 @@ interface LegendListSpecificProps<ItemT, TItemType extends string | undefined> {
259
- * The adjustment is also rendered as real content padding so the browser scroll range includes it.
260
- */
261
- contentInsetEndAdjustment?: number;
262
-+ /**
263
-+ * Width/height of a leading content inset applied natively outside the list's knowledge
264
-+ * (e.g. iOS contentInsetAdjustmentBehavior="automatic" under a transparent header).
265
-+ * Programmatic scrolls clamp to -adjustment instead of 0 so content can rest below the header.
266
-+ */
267
-+ contentInsetStartAdjustment?: number;
268
- /**
269
- * Number of columns to render items in.
270
- * @default 1
271
-diff --git a/react-native.js b/react-native.js
272
-index b3c5a306b293f797a8b338adfca3060c0f6db22b..d7f59b63cd4982dfc9c347732caa77e0974864df 100644
273
---- a/react-native.js
274
-+++ b/react-native.js
275
-@@ -717,6 +717,15 @@ function hasActiveInitialScroll(state) {
276
- return !!(state == null ? void 0 : state.initialScroll) && !state.didFinishInitialScroll;
277
- }
278
-
279
-+// Size-only changes may not emit a scroll event to refresh the edge signal.
280
-+function getIsAtEnd(ctx, contentSize = getContentSize(ctx)) {
281
-+ const { queuedInitialLayout, scroll, scrollLength } = ctx.state;
282
-+ if (!(contentSize > 0 && queuedInitialLayout)) {
283
-+ return peek$(ctx, "isAtEnd");
284
-+ }
285
-+ return contentSize < scrollLength || contentSize - scroll - scrollLength - getContentInsetEnd(ctx) <= EDGE_POSITION_EPSILON;
286
-+}
287
-+
288
- // src/utils/checkAtBottom.ts
289
- function checkAtBottom(ctx, allowedEdge, allowGateCreatedInCurrentCheck) {
290
- var _a3;
291
-@@ -737,7 +746,7 @@ function checkAtBottom(ctx, allowedEdge, allowGateCreatedInCurrentCheck) {
292
- const insetEnd = getContentInsetEnd(ctx);
293
- const distanceFromEnd = contentSize - scroll - scrollLength - insetEnd;
294
- const isContentLess = contentSize < scrollLength;
295
-- set$(ctx, "isAtEnd", isContentLess || distanceFromEnd <= EDGE_POSITION_EPSILON);
296
-+ set$(ctx, "isAtEnd", getIsAtEnd(ctx, contentSize));
297
- set$(ctx, "isNearEnd", isContentLess || distanceFromEnd <= onEndReachedThreshold * scrollLength);
298
- set$(
299
- ctx,
300
-@@ -954,7 +963,16 @@ function setInitialRenderState(ctx, {
301
- if (didInitialScroll) {
302
- state.didFinishInitialScroll = true;
303
- }
304
-- const isReadyToRender = Boolean(state.didContainersLayout && state.didFinishInitialScroll);
305
-+ // Native contentOffset can seed an end target without dispatchInitialScroll.
306
-+ // Both overflow completion paths must wait for the native end landing.
307
-+ // Underflow needs no scroll: preserve UIKit's untouched resting position.
308
-+ if (state.didContainersLayout && state.didFinishInitialScroll && state.initialScroll && state.initialScroll.viewPosition === 1 && state.initialScroll.index === state.props.data.length - 1 && state.props.data.length > 0) {
309
-+ const insetStartAdjustment = getContentInsetStartAdjustment(ctx);
310
-+ if (insetStartAdjustment > 0 && getContentSize(ctx) > state.scrollLength - insetStartAdjustment + 1) {
311
-+ startInsetEndSettleWatchdog(ctx);
312
-+ }
313
-+ }
314
-+ const isReadyToRender = Boolean(state.didContainersLayout && state.didFinishInitialScroll && !state.insetEndRevealHold);
315
- if (isReadyToRender && !peek$(ctx, "readyToRender")) {
316
- set$(ctx, "readyToRender", true);
317
- setAdaptiveRender(ctx, "normal", "ready");
318
-@@ -1090,7 +1108,7 @@ function getRawContentLength(ctx) {
319
- function getAlignItemsAtEndPadding(ctx) {
320
- const { state } = ctx;
321
- const shouldPad = !!state.props.alignItemsAtEndPaddingEnabled && !state.props.horizontal && state.props.data.length > 0 && state.scrollLength > 0;
322
-- return shouldPad ? Math.max(0, state.scrollLength - getRawContentLength(ctx) - getContentInsetEnd(ctx)) : 0;
323
-+ return shouldPad ? Math.max(0, state.scrollLength - getContentInsetStartAdjustment(ctx) - getRawContentLength(ctx) - getContentInsetEnd(ctx)) : 0;
324
- }
325
- function updateContentMetricsState(ctx) {
326
- const previousPadding = peek$(ctx, "alignItemsAtEndPadding") || 0;
327
-@@ -1115,6 +1133,10 @@ function addTotalSize(ctx, key, add, notifyTotalSize = true) {
328
- totalSize += add;
329
- }
330
- if (prevTotalSize !== totalSize) {
331
-+ const now = Date.now();
332
-+ const isContinuingContentSizeAnimation = state.contentSizeAnimationActiveEpoch !== void 0;
333
-+ state.contentSizeAnimationEpoch = (state.contentSizeAnimationEpoch || 0) + 1;
334
-+ state.contentSizeAnimationEligible = !!state.props.sizeComponentInternal && state.didContainersLayout && (isContinuingContentSizeAnimation || !state.props.maintainScrollAtEnd && !state.isUserDragging && !state.isMomentumScrolling && now - (state.lastMVCPAdjustTime || 0) >= 300);
335
- if (!IsNewArchitecture && state.initialScroll && totalSize < prevTotalSize) {
336
- state.pendingTotalSize = totalSize;
337
- } else {
338
-@@ -1304,18 +1326,23 @@ function calculateOffsetWithOffsetPosition(ctx, offsetParam, params) {
339
- }
340
-
341
- // src/core/clampScrollOffset.ts
342
-+function getContentInsetStartAdjustment(ctx) {
343
-+ const adjustment = ctx.state.props.contentInsetStartAdjustment;
344
-+ return typeof adjustment === "number" && Number.isFinite(adjustment) ? Math.max(0, adjustment) : 0;
345
-+}
346
- function clampScrollOffset(ctx, offset, scrollTarget) {
347
- const state = ctx.state;
348
- const contentSize = getContentSize(ctx);
349
-+ const minOffset = -getContentInsetStartAdjustment(ctx);
350
- let clampedOffset = offset;
351
- if (Number.isFinite(contentSize) && Number.isFinite(state.scrollLength) && (Platform.OS !== "android" || state.lastLayout)) {
352
-- const baseMaxOffset = Math.max(0, contentSize - state.scrollLength);
353
-+ const baseMaxOffset = Math.max(minOffset, contentSize - state.scrollLength);
354
- const viewOffset = scrollTarget == null ? void 0 : scrollTarget.viewOffset;
355
- const extraEndOffset = typeof viewOffset === "number" && viewOffset < 0 ? -viewOffset : 0;
356
- const maxOffset = baseMaxOffset + extraEndOffset;
357
- clampedOffset = Math.min(offset, maxOffset);
358
- }
359
-- clampedOffset = Math.max(0, clampedOffset);
360
-+ clampedOffset = Math.max(minOffset, clampedOffset);
361
- return clampedOffset;
362
- }
363
-
364
-@@ -1451,10 +1478,10 @@ function checkFinishedScrollFrame(ctx) {
365
- finishScrollTo(ctx);
366
- }
367
- }
368
--function scrollToFallbackOffset(ctx, offset) {
369
-+function scrollToFallbackOffset(ctx, offset, animated) {
370
- var _a3;
371
- (_a3 = ctx.state.refScroller.current) == null ? void 0 : _a3.scrollTo({
372
-- animated: false,
373
-+ animated: !!animated,
374
- x: ctx.state.props.horizontal ? offset : 0,
375
- y: ctx.state.props.horizontal ? 0 : offset
376
- });
377
-@@ -1503,7 +1530,10 @@ function checkFinishedScrollFallback(ctx) {
378
- );
379
- scheduleFallbackCheck(SILENT_INITIAL_SCROLL_RETRY_DELAY_MS);
380
- } else if (shouldRetryUnalignedEndScroll) {
381
-- scrollToFallbackOffset(ctx, completionState.clampedTargetOffset);
382
-+ const isActivelyAnimatingToEnd = !!isStillScrollingTo.animated && Date.now() - state.scrollTime < 100;
383
-+ if (!isActivelyAnimatingToEnd) {
384
-+ scrollToFallbackOffset(ctx, completionState.clampedTargetOffset, !!isStillScrollingTo.animated);
385
-+ }
386
- scheduleFallbackCheck(100);
387
- } else if (shouldFinishZeroTarget || shouldFinishAfterObservedScroll || canFinishInitialScrollWithoutNativeProgress || canFinishAfterSilentNativeDispatch || numChecks > maxChecks) {
388
- finishScrollTo(ctx);
389
-@@ -1560,15 +1590,33 @@ function doMaintainScrollAtEnd(ctx) {
390
- } = state;
391
- const isWithinMaintainScrollAtEndThreshold = peek$(ctx, "isWithinMaintainScrollAtEndThreshold");
392
- const shouldMaintainScrollAtEnd = !!(isWithinMaintainScrollAtEndThreshold && maintainScrollAtEnd && didContainersLayout);
393
-+ if (state.contentSizeAnimationActiveEpoch !== void 0) {
394
-+ state.pendingMaintainScrollAtEnd = false;
395
-+ return false;
396
-+ }
397
- if (pendingNativeMVCPAdjust) {
398
- state.pendingMaintainScrollAtEnd = shouldMaintainScrollAtEnd;
399
- return false;
400
- }
401
-+ // T3 patch: a caller anchor already placed this pass's offset; a later scroll would move it.
402
-+ if (state.props.sizeChangeAnchor && !state.mvcpDataChanged && state.props.sizeChangeAnchor() !== void 0) {
403
-+ state.pendingMaintainScrollAtEnd = false;
404
-+ return shouldMaintainScrollAtEnd;
405
-+ }
406
- if (shouldMaintainScrollAtEnd) {
407
- state.pendingMaintainScrollAtEnd = false;
408
-+ const maintainAnchoredEndSpace = state.props.anchoredEndSpace;
409
-+ const maintainAnchorIndex = maintainAnchoredEndSpace == null ? void 0 : maintainAnchoredEndSpace.anchorIndex;
410
-+ if (maintainAnchorIndex !== void 0 && maintainAnchorIndex >= 0 && maintainAnchorIndex < state.props.data.length && !areKnownOrFixedItemSizesAvailable(ctx, maintainAnchorIndex, state.props.data.length - 1)) {
411
-+ return false;
412
-+ }
413
- const contentSize = getContentSize(ctx);
414
-+ const maintainInsetStartAdjustment = getContentInsetStartAdjustment(ctx);
415
- if (contentSize < state.scrollLength) {
416
-- state.scroll = 0;
417
-+ state.scroll = -maintainInsetStartAdjustment;
418
-+ if (maintainInsetStartAdjustment > 0) {
419
-+ return true;
420
-+ }
421
- }
422
- if (!state.maintainingScrollAtEnd) {
423
- const pendingState = maintainScrollAtEnd.animated ? "pending-animated" : "pending-instant";
424
-@@ -1591,9 +1639,18 @@ function doMaintainScrollAtEnd(ctx) {
425
- y: 0
426
- });
427
- } else {
428
-- scroller == null ? void 0 : scroller.scrollToEnd({
429
-- animated: maintainScrollAtEnd.animated
430
-- });
431
-+ const insetStartAdjustment = getContentInsetStartAdjustment(ctx);
432
-+ if (insetStartAdjustment > 0) {
433
-+ scroller == null ? void 0 : scroller.scrollTo({
434
-+ animated: maintainScrollAtEnd.animated,
435
-+ x: 0,
436
-+ y: Math.max(-insetStartAdjustment, getContentSize(ctx) - state.scrollLength)
437
-+ });
438
-+ } else {
439
-+ scroller == null ? void 0 : scroller.scrollToEnd({
440
-+ animated: maintainScrollAtEnd.animated
441
-+ });
442
-+ }
443
- }
444
- setTimeout(
445
- () => {
446
-@@ -1624,6 +1681,10 @@ function doMaintainScrollAtEnd(ctx) {
447
- function requestAdjust(ctx, positionDiff, dataChanged) {
448
- const state = ctx.state;
449
- if (Math.abs(positionDiff) > 0.1) {
450
-+ // Timestamp for ReanimatedPositionView: repositions caused by an MVCP
451
-+ // size adjustment are already compensated by a contentOffset shift, so
452
-+ // animating them would make rows visibly lurch and slide back.
453
-+ state.lastMVCPAdjustTime = Date.now();
454
- const needsScrollWorkaround = Platform.OS === "android" && !IsNewArchitecture && dataChanged && state.scroll <= positionDiff;
455
- const doit = () => {
456
- if (needsScrollWorkaround) {
457
-@@ -1728,7 +1789,9 @@ function getPredictedNativeClamp(state, unresolvedAmount, totalSize) {
458
- if (Math.abs(unresolvedAmount) <= MVCP_POSITION_EPSILON) {
459
- return 0;
460
- }
461
-- const maxScroll = Math.max(0, totalSize - state.scrollLength);
462
-+ const insetStartAdjustment = state.props.contentInsetStartAdjustment;
463
-+ const minScroll = typeof insetStartAdjustment === "number" && Number.isFinite(insetStartAdjustment) ? -Math.max(0, insetStartAdjustment) : 0;
464
-+ const maxScroll = Math.max(minScroll, totalSize - state.scrollLength);
465
- const clampDelta = maxScroll - state.scroll;
466
- if (unresolvedAmount < 0) {
467
- return Math.max(unresolvedAmount, Math.min(0, clampDelta));
468
-@@ -1790,7 +1853,7 @@ function resolvePendingNativeMVCPAdjust(ctx, newScroll) {
469
- settlePendingNativeMVCPAdjust(ctx, remainingAfterManual, nativeDelta);
470
- return true;
471
- }
472
-- const expectedNativeClampScroll = Math.max(0, getContentSize(ctx) - state.scrollLength);
473
-+ const expectedNativeClampScroll = Math.max(-getContentInsetStartAdjustment(ctx), getContentSize(ctx) - state.scrollLength);
474
- const distanceToClamp = Math.abs(newScroll - expectedNativeClampScroll);
475
- const isAtExpectedNativeClamp = distanceToClamp <= NATIVE_END_CLAMP_EPSILON;
476
- if (isAtExpectedNativeClamp) {
477
-@@ -1811,7 +1874,35 @@ function resolvePendingNativeMVCPAdjust(ctx, newScroll) {
478
- }
479
- return false;
480
- }
481
-+// T3 patch: a caller anchor decides where a size change leaves the scroll position. It is read in
482
-+// the same pass that repositions the items, so the adjustment commits with the new positions.
483
- function prepareMVCP(ctx, dataChanged) {
484
-+ // T3 patch: a data change skips the caller anchor, so end maintenance must still run after it.
485
-+ ctx.state.mvcpDataChanged = !!dataChanged;
486
-+ const sizeChangeAnchor = dataChanged ? void 0 : ctx.state.props.sizeChangeAnchor;
487
-+ const restore = prepareDefaultMVCP(ctx, dataChanged);
488
-+ if (!sizeChangeAnchor || ctx.state.scrollingTo !== void 0) {
489
-+ return restore;
490
-+ }
491
-+ return () => {
492
-+ const target = sizeChangeAnchor();
493
-+ if (target === void 0) {
494
-+ restore == null ? void 0 : restore();
495
-+ return;
496
-+ }
497
-+ // Content that shrinks under an offset past its new end pulls the native offset back to
498
-+ // that end by itself; only the rest of the way to the target is adjusted.
499
-+ const endOffset = clampScrollOffset(ctx, Number.POSITIVE_INFINITY);
500
-+ if (ctx.state.scroll > endOffset) {
501
-+ ctx.state.scroll = endOffset;
502
-+ }
503
-+ const positionDiff = clampScrollOffset(ctx, target) - ctx.state.scroll;
504
-+ if (Math.abs(positionDiff) > MVCP_POSITION_EPSILON) {
505
-+ requestAdjust(ctx, positionDiff, false);
506
-+ }
507
-+ };
508
-+}
509
-+function prepareDefaultMVCP(ctx, dataChanged) {
510
- const state = ctx.state;
511
- const { idsInView, positions, props } = state;
512
- const {
513
-@@ -1923,7 +2014,7 @@ function prepareMVCP(ctx, dataChanged) {
514
- if (diff > 0) {
515
- diff = Math.max(0, totalSize - state.scroll - state.scrollLength);
516
- } else {
517
-- const maxScroll = Math.max(0, totalSize - state.scrollLength);
518
-+ const maxScroll = Math.max(-getContentInsetStartAdjustment(ctx), totalSize - state.scrollLength);
519
- state.scroll = maxScroll;
520
- state.scrollPending = maxScroll;
521
- diff = 0;
522
-@@ -2320,8 +2411,121 @@ function scrollToIndex(ctx, {
523
- }
524
-
525
- // src/core/initialScroll.ts
526
-+var INSET_END_SETTLE_WATCHDOG_FRAMES = 150;
527
-+var INSET_END_SETTLE_WATCHDOG_STABLE_FRAMES = 20;
528
-+var INSET_END_REVEAL_STABLE_FRAMES = 3;
529
-+var INSET_END_REVEAL_MAX_HOLD_FRAMES = 40;
530
-+function startInsetEndSettleWatchdog(ctx) {
531
-+ const state = ctx.state;
532
-+ if (state.insetEndSettleWatchdogStarted || state.didLoad) {
533
-+ return;
534
-+ }
535
-+ state.insetEndSettleWatchdogStarted = true;
536
-+ state.insetEndSettleWatchdogActive = true;
537
-+ // Hold the readyToRender opacity gate until the end landing is stable, so
538
-+ // the estimated-to-measured settle chase happens before first VISIBLE
539
-+ // paint instead of in front of the user. Capped so slow measurement can
540
-+ // never hide content for long.
541
-+ state.insetEndRevealHold = true;
542
-+ let frames = 0;
543
-+ let settledFrames = 0;
544
-+ let revealStableFrames = 0;
545
-+ let previousEndOffset;
546
-+ const releaseRevealHold = () => {
547
-+ if (state.insetEndRevealHold) {
548
-+ state.insetEndRevealHold = false;
549
-+ setInitialRenderState(ctx, {});
550
-+ }
551
-+ };
552
-+ // Revealing flips adaptive rendering to "normal", which re-renders rows and
553
-+ // can move the end target one more time — do that upgrade while still
554
-+ // hidden (phase 1), then require stability again before revealing (phase 2)
555
-+ // so the first visible frame is the settled one.
556
-+ let revealPhase = 1;
557
-+ const onRevealStability = () => {
558
-+ var _a3;
559
-+ if (!state.insetEndRevealHold) {
560
-+ return;
561
-+ }
562
-+ if (revealPhase === 1) {
563
-+ revealPhase = 2;
564
-+ revealStableFrames = 0;
565
-+ setAdaptiveRender(ctx, "normal");
566
-+ (_a3 = state.triggerCalculateItemsInView) == null ? void 0 : _a3.call(state);
567
-+ return;
568
-+ }
569
-+ releaseRevealHold();
570
-+ };
571
-+ const tick = () => {
572
-+ // The user owns the scroll from their first drag — a re-pin here would
573
-+ // pin the list under their finger.
574
-+ if (frames++ >= INSET_END_SETTLE_WATCHDOG_FRAMES || settledFrames >= INSET_END_SETTLE_WATCHDOG_STABLE_FRAMES || state.didUserDrag || !ctx.state || ctx.state !== state) {
575
-+ state.insetEndSettleWatchdogActive = false;
576
-+ releaseRevealHold();
577
-+ return;
578
-+ }
579
-+ if (frames >= INSET_END_REVEAL_MAX_HOLD_FRAMES) {
580
-+ releaseRevealHold();
581
-+ }
582
-+ const insetStartAdjustment = getContentInsetStartAdjustment(ctx);
583
-+ const contentSize = getContentSize(ctx);
584
-+ const scrollLength = state.scrollLength;
585
-+ const endOffset = Math.max(-insetStartAdjustment, contentSize - scrollLength);
586
-+ // state.scroll is optimistic: non-animated scrollTo writes it before UIKit
587
-+ // moves. Only a native scroll event proves that the requested offset landed.
588
-+ const nativeOffset = state.lastNativeScroll;
589
-+ const hasNativeOffset = typeof nativeOffset === "number" && Number.isFinite(nativeOffset);
590
-+ const distance = hasNativeOffset ? endOffset - nativeOffset : Infinity;
591
-+ const isIdle = !state.scrollingTo && !state.maintainingScrollAtEnd;
592
-+ const hasViewport = insetStartAdjustment > 0 && scrollLength > 0 && Number.isFinite(contentSize);
593
-+ const isStable = hasViewport && isIdle && Math.abs(distance) <= 2 && previousEndOffset !== void 0 && Math.abs(endOffset - previousEndOffset) <= 1;
594
-+ previousEndOffset = endOffset;
595
-+ if (isStable) {
596
-+ settledFrames++;
597
-+ revealStableFrames++;
598
-+ if (revealStableFrames >= INSET_END_REVEAL_STABLE_FRAMES) {
599
-+ onRevealStability();
600
-+ }
601
-+ } else {
602
-+ settledFrames = 0;
603
-+ revealStableFrames = 0;
604
-+ // Keep the existing near-end correction limit. In-flight scrolls and
605
-+ // unknown native offsets wait; neither counts as a settled frame.
606
-+ if (hasViewport && isIdle && Math.abs(distance) > 2 && Math.abs(distance) <= scrollLength * 0.5) {
607
-+ const scroller = state.refScroller.current;
608
-+ if (scroller) {
609
-+ scroller.scrollTo({ animated: false, x: 0, y: endOffset });
610
-+ }
611
-+ }
612
-+ }
613
-+ requestAnimationFrame(tick);
614
-+ };
615
-+ requestAnimationFrame(tick);
616
-+}
617
- function dispatchInitialScroll(ctx, params) {
618
- const { forceScroll, resolvedOffset, target, waitForCompletionFrame } = params;
619
-+ const insetStartAdjustment = getContentInsetStartAdjustment(ctx);
620
-+ if (insetStartAdjustment > 0 && ctx.state.props.data.length > 0) {
621
-+ if (ctx.state.scrollLength <= 0) {
622
-+ // The scroll length is unknown, so the resolved target is meaningless;
623
-+ // the initial-scroll machinery re-advances after layout.
624
-+ return;
625
-+ }
626
-+ if (resolvedOffset <= -insetStartAdjustment + 1 && !ctx.state.didDispatchInsetInitialScroll) {
627
-+ // Content underflows the viewport and nothing has scrolled yet: the
628
-+ // untouched native rest position (UIKit's adjustedContentInset) IS the
629
-+ // end position. Dispatching a negative scroll here would race UIKit's
630
-+ // inset application during screen attach, so just finish the session.
631
-+ finishInitialScroll(ctx, {
632
-+ resolvedOffset
633
-+ });
634
-+ return;
635
-+ }
636
-+ ctx.state.didDispatchInsetInitialScroll = true;
637
-+ if (target.viewPosition === 1) {
638
-+ startInsetEndSettleWatchdog(ctx);
639
-+ }
640
-+ }
641
- const requestedIndex = target.index;
642
- const index = requestedIndex !== void 0 ? clampScrollIndex(requestedIndex, ctx.state.props.data.length) : void 0;
643
- const itemSize = getItemSizeAtIndex(ctx, index);
644
-@@ -2747,7 +2951,9 @@ function clearFinishedBootstrapInitialScrollTargetIfMovedAway(ctx) {
645
- return;
646
- }
647
- if (didFinishedInitialScrollMoveAwayFromTarget(ctx, initialScroll)) {
648
-- const shouldKeepEndTargetAlive = isRetargetableBottomAlignedInitialScrollTarget(initialScroll) && peek$(ctx, "isAtEnd");
649
-+ const endTargetDistanceFromEnd = getContentSize(ctx) - state.scroll - state.scrollLength - getContentInsetEnd(ctx);
650
-+ const isNearEndForInsetList = getContentInsetStartAdjustment(ctx) > 0 && Number.isFinite(endTargetDistanceFromEnd) && endTargetDistanceFromEnd <= state.scrollLength * 0.5;
651
-+ const shouldKeepEndTargetAlive = isRetargetableBottomAlignedInitialScrollTarget(initialScroll) && (peek$(ctx, "isAtEnd") || !state.didUserDrag && isNearEndForInsetList);
652
- if (!shouldKeepEndTargetAlive) {
653
- if (shouldPreserveInitialScrollForFooterLayout(initialScroll)) {
654
- clearPendingInitialScrollFooterLayout(ctx, {
655
-@@ -4672,7 +4878,8 @@ function maybeUpdateAnchoredEndSpace(ctx) {
656
- contentBelowAnchor = Math.max(0, contentBelowAnchor - ctx.scrollAxisGap);
657
- contentBelowAnchor += (ctx.values.get("footerSize") || 0) + getStylePaddingEnd(state.props);
658
- isReady = !hasUnknownTailSize;
659
-- nextSize = hasUnknownTailSize ? previousSize || 0 : Math.max(0, state.scrollLength - contentBelowAnchor - anchorOffset);
660
-+ const knownSizeBound = Math.max(0, state.scrollLength - contentBelowAnchor - anchorOffset);
661
-+ nextSize = hasUnknownTailSize ? Math.min(previousSize || 0, knownSizeBound) : knownSizeBound;
662
- } else if (anchorIndex >= 0) {
663
- isReady = false;
664
- }
665
-@@ -4692,6 +4899,12 @@ function maybeUpdateAnchoredEndSpace(ctx) {
666
- updateScroll(ctx, state.scroll, true, { markHasScrolled: false });
667
- }
668
- (_b = anchoredEndSpace == null ? void 0 : anchoredEndSpace.onReady) == null ? void 0 : _b.call(anchoredEndSpace, { anchorIndex: nextAnchorIndex, anchorKey: nextAnchorKey, size: nextSize });
669
-+ } else if (!isReady && didSizeChange && nextSize < (previousSize || 0)) {
670
-+ set$(ctx, "anchoredEndSpaceSize", nextSize);
671
-+ (_a3 = anchoredEndSpace == null ? void 0 : anchoredEndSpace.onSizeChanged) == null ? void 0 : _a3.call(anchoredEndSpace, nextSize);
672
-+ if (anchoredEndSpace == null ? void 0 : anchoredEndSpace.includeInEndInset) {
673
-+ updateScroll(ctx, state.scroll, true, { markHasScrolled: false });
674
-+ }
675
- }
676
- return nextSize;
677
- }
678
-@@ -5715,8 +5928,11 @@ var ContainersLayer = typedMemo(function ContainersLayer2({
679
- horizontal
680
- }) {
681
- const ctx = useStateContext();
682
-+ const SizeComponent = ctx.state.props.sizeComponentInternal;
683
- const columnWrapperStyle = ctx.columnWrapperStyle;
684
-- const animSize = useValue$("totalSize");
685
-+ // T3 patch: on the new architecture an animated value commits on its own, ahead of the item
686
-+ // positions and their scroll compensation; a rendered size commits with them.
687
-+ const animSize = IsNewArchitecture ? useArr$(["totalSize"])[0] || 0 : useValue$("totalSize");
688
- const [readyToRender, numColumns, otherAxisSize = 0] = useArr$(["readyToRender", "numColumns", "otherAxisSize"]);
689
- const isVisible = useFreshDataTransitionVisibility(!!readyToRender, freshDataTransitionEpoch);
690
- const style = horizontal ? {
691
-@@ -5725,6 +5941,13 @@ var ContainersLayer = typedMemo(function ContainersLayer2({
692
- opacity: isVisible ? 1 : 0,
693
- width: animSize
694
- } : { height: animSize, minWidth: otherAxisSize, opacity: isVisible ? 1 : 0 };
695
-+ if (SizeComponent) {
696
-+ if (horizontal) {
697
-+ delete style.width;
698
-+ } else {
699
-+ delete style.height;
700
-+ }
701
-+ }
702
- if (columnWrapperStyle) {
703
- const { columnGap, rowGap, gap } = columnWrapperStyle;
704
- const gapX = columnGap || gap || 0;
705
-@@ -5745,7 +5968,8 @@ var ContainersLayer = typedMemo(function ContainersLayer2({
706
- }
707
- }
708
- }
709
-- return /* @__PURE__ */ React2__namespace.createElement(ReactNative.Animated.View, { pointerEvents: isVisible ? void 0 : "none", style }, /* @__PURE__ */ React2__namespace.createElement(ContainerLayoutCoordinator, null, children));
710
-+ const content = /* @__PURE__ */ React2__namespace.createElement(ContainerLayoutCoordinator, null, children);
711
-+ return SizeComponent ? /* @__PURE__ */ React2__namespace.createElement(SizeComponent, { horizontal, pointerEvents: isVisible ? void 0 : "none", signalName: "totalSize", style }, content) : /* @__PURE__ */ React2__namespace.createElement(ReactNative.Animated.View, { pointerEvents: isVisible ? void 0 : "none", style }, content);
712
- });
713
- var Containers = typedMemo(function Containers2({
714
- freshDataTransitionEpoch,
715
-@@ -5896,7 +6120,12 @@ var StyleSheet = ReactNative.StyleSheet;
716
-
717
- // src/components/ListComponent.tsx
718
- var AlignItemsAtEndSpacer = typedMemo(function AlignItemsAtEndSpacer2({ horizontal }) {
719
-+ const ctx = useStateContext();
720
- const [alignItemsAtEndPadding = 0] = useArr$(["alignItemsAtEndPadding"]);
721
-+ const SizeComponent = ctx.state.props.sizeComponentInternal;
722
-+ if (SizeComponent) {
723
-+ return /* @__PURE__ */ React2__namespace.createElement(SizeComponent, { horizontal, signalName: "alignItemsAtEndPadding", style: { flexShrink: 0 } });
724
-+ }
725
- if (alignItemsAtEndPadding <= 0) {
726
- return null;
727
- }
728
-@@ -5929,8 +6158,12 @@ var ListComponent = typedMemo(function ListComponent2({
729
- refScrollView,
730
- renderScrollComponent,
731
- onLayoutFooter,
732
-+ onInternalMomentumScrollBegin,
733
- onInternalScrollBeginDrag,
734
-+ onInternalScrollEndDrag,
735
- onInternalScrollEnd,
736
-+ onMomentumScrollBegin,
737
-+ onScrollEndDrag,
738
- scrollAdjustHandler,
739
- snapToIndices,
740
- stickyHeaderConfig,
741
-@@ -6001,7 +6234,17 @@ var ListComponent = typedMemo(function ListComponent2({
742
- SnapOrScroll,
743
- {
744
- ...rest,
745
-- ...Platform.OS === "web" ? ScrollComponent === ListComponentScrollView ? { onInternalScrollEnd, useWindowScroll } : {} : { onScrollBeginDrag: onInternalScrollBeginDrag },
746
-+ ...Platform.OS === "web" ? ScrollComponent === ListComponentScrollView ? { onInternalScrollEnd, useWindowScroll } : {} : {
747
-+ onMomentumScrollBegin: (event) => {
748
-+ onInternalMomentumScrollBegin == null ? void 0 : onInternalMomentumScrollBegin(event);
749
-+ onMomentumScrollBegin == null ? void 0 : onMomentumScrollBegin(event);
750
-+ },
751
-+ onScrollBeginDrag: onInternalScrollBeginDrag,
752
-+ onScrollEndDrag: (event) => {
753
-+ onInternalScrollEndDrag == null ? void 0 : onInternalScrollEndDrag(event);
754
-+ onScrollEndDrag == null ? void 0 : onScrollEndDrag(event);
755
-+ }
756
-+ },
757
- contentContainerStyle: [
758
- horizontal ? { height: "100%" } : {},
759
- contentContainerStyle,
760
-@@ -6010,7 +6253,10 @@ var ListComponent = typedMemo(function ListComponent2({
761
- ],
762
- contentOffset: initialContentOffset !== void 0 ? horizontal ? { x: initialContentOffset, y: 0 } : { x: 0, y: initialContentOffset } : void 0,
763
- horizontal,
764
-- maintainVisibleContentPosition: maintainVisibleContentPosition.size || maintainVisibleContentPosition.data ? { minIndexForVisible: 0 } : void 0,
765
-+ // Keep iOS anchored to ScrollAdjust even when JS position restoration is
766
-+ // disabled. Re-enabling native MVCP mid-drag can compare its stale anchor
767
-+ // with the 1e7 sentinel and scroll the entire list out of view.
768
-+ maintainVisibleContentPosition: Platform.OS === "ios" || maintainVisibleContentPosition.size || maintainVisibleContentPosition.data ? { minIndexForVisible: 0 } : void 0,
769
- onLayout,
770
- onScroll: onScroll2,
771
- ref: refScrollView,
772
-@@ -6267,7 +6513,8 @@ function handleLayout(ctx, layoutParam, setCanRender) {
773
- if (scrollLength > 0) {
774
- doInitialAllocateContainers(ctx);
775
- }
776
-- if (needsCalculate) {
777
-+ // T3 patch: a shorter list keeps a caller anchor too, such as the end.
778
-+ if (needsCalculate || state.props.sizeChangeAnchor) {
779
- calculateItemsInView(ctx, { doMVCP: true });
780
- }
781
- if (didChange || otherAxisSize !== prevOtherAxisSize) {
782
-@@ -6751,7 +6998,7 @@ function createImperativeHandle(ctx, scheduleImperativeScrollCommit) {
783
- endBuffered: state.endBuffered,
784
- getAverageItemSizes: () => getAverageItemSizes(state),
785
- indexByKey: (key) => state.indexByKey.get(key),
786
-- isAtEnd: peek$(ctx, "isAtEnd"),
787
-+ isAtEnd: getIsAtEnd(ctx),
788
- isAtStart: peek$(ctx, "isAtStart"),
789
- isEndReached: state.isEndReached,
790
- isNearEnd: peek$(ctx, "isNearEnd"),
791
-@@ -7075,6 +7322,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
792
- dataVersion,
793
- drawDistance = 250,
794
- contentInsetEndAdjustment,
795
-+ contentInsetStartAdjustment,
796
- estimatedItemSize = 100,
797
- estimatedListSize,
798
- extraData,
799
-@@ -7096,6 +7344,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
800
- maintainScrollAtEnd = false,
801
- maintainScrollAtEndThreshold = 0.1,
802
- maintainVisibleContentPosition: maintainVisibleContentPositionProp,
803
-+ sizeChangeAnchor,
804
- numColumns: numColumnsProp = 1,
805
- overrideItemLayout,
806
- onEndReached,
807
-@@ -7132,10 +7381,12 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
808
- const animatedPropsInternal = props.animatedPropsInternal;
809
- const anchoredEndSpaceOwner = (_a3 = props.anchoredEndSpaceOwnerInternal) != null ? _a3 : "list";
810
- const positionComponentInternal = props.positionComponentInternal;
811
-+ const sizeComponentInternal = props.sizeComponentInternal;
812
- const stickyPositionComponentInternal = props.stickyPositionComponentInternal;
813
- const {
814
- anchoredEndSpaceOwnerInternal: _anchoredEndSpaceOwnerInternal,
815
- positionComponentInternal: _positionComponentInternal,
816
-+ sizeComponentInternal: _sizeComponentInternal,
817
- stickyPositionComponentInternal: _stickyPositionComponentInternal,
818
- ...restProps
819
- } = rest;
820
-@@ -7200,7 +7451,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
821
- const combinedRef = useCombinedRef(refScroller, refScrollView);
822
- const keyExtractor = keyExtractorProp != null ? keyExtractorProp : ((_item, index) => index.toString());
823
- const stickyHeaderIndices = stickyHeaderIndicesProp;
824
-- const contentInsetEndAdjustmentResolved = Platform.OS === "web" ? contentInsetEndAdjustment : void 0;
825
-+ const contentInsetEndAdjustmentResolved = contentInsetEndAdjustment;
826
- const previousContentInsetEndAdjustmentRef = React2.useRef(contentInsetEndAdjustmentResolved);
827
- const alwaysRenderIndices = React2.useMemo(() => {
828
- const indices = getAlwaysRenderIndices(alwaysRender, dataProp, keyExtractor, anchoredEndSpace == null ? void 0 : anchoredEndSpace.anchorIndex);
829
-@@ -7341,6 +7592,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
830
- contentContainerAlignItems: contentContainerStyle.alignItems,
831
- contentInset,
832
- contentInsetEndAdjustment: contentInsetEndAdjustmentResolved,
833
-+ contentInsetStartAdjustment,
834
- data: dataProp,
835
- dataKey,
836
- dataVersion,
837
-@@ -7354,6 +7606,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
838
- maintainScrollAtEnd: maintainScrollAtEndConfig,
839
- maintainScrollAtEndThreshold,
840
- maintainVisibleContentPosition: maintainVisibleContentPositionConfig,
841
-+ sizeChangeAnchor,
842
- numColumns: numColumnsProp,
843
- onEndReached,
844
- onEndReachedThreshold,
845
-@@ -7372,6 +7625,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
846
- renderItem,
847
- rtl,
848
- snapToIndices,
849
-+ sizeComponentInternal,
850
- stickyHeaderIndicesArr: stickyHeaderIndices != null ? stickyHeaderIndices : [],
851
- stickyHeaderIndicesSet: React2.useMemo(() => new Set(stickyHeaderIndices != null ? stickyHeaderIndices : []), [stickyHeaderIndices == null ? void 0 : stickyHeaderIndices.join(",")]),
852
- stickyPositionComponentInternal,
853
-@@ -7423,6 +7677,13 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
854
- return void 0;
855
- }
856
- const resolvedOffset = (_a4 = initialScroll.contentOffset) != null ? _a4 : resolveInitialScrollOffset(ctx, initialScroll);
857
-+ if (getContentInsetStartAdjustment(ctx) > 0) {
858
-+ // With a native leading inset (transparent header + automatic insets),
859
-+ // any mount-time contentOffset races UIKit's adjustedContentInset
860
-+ // application. The gated initial-scroll dispatch positions the list once
861
-+ // real sizes are known instead.
862
-+ return void 0;
863
-+ }
864
- return usesBootstrapInitialScroll && ((_b2 = state.initialScrollSession) == null ? void 0 : _b2.kind) === "bootstrap" && Platform.OS === "web" ? void 0 : resolvedOffset;
865
- }, [usesBootstrapInitialScroll]);
866
- React2.useLayoutEffect(() => {
867
-@@ -7547,6 +7808,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
868
- [
869
- dataKey,
870
- dataVersion,
871
-+ contentInsetStartAdjustment,
872
- memoizedLastItemKeys.join(","),
873
- numColumnsProp,
874
- nextScrollAxisGap,
875
-@@ -7643,6 +7905,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
876
- () => ({
877
- getRenderedItem: (key) => getRenderedItem(ctx, key),
878
- onMomentumScrollEnd: (event) => {
879
-+ state.isMomentumScrolling = false;
880
- checkFinishedScrollFallback(ctx);
881
- if (state.props.onMomentumScrollEnd) {
882
- state.props.onMomentumScrollEnd(event);
883
-@@ -7651,6 +7914,8 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
884
- onScroll: (event) => onScroll(ctx, event),
885
- onScrollBeginDrag: (event) => {
886
- var _a4, _b2;
887
-+ ctx.state.didUserDrag = true;
888
-+ ctx.state.isUserDragging = true;
889
- prepareReachedEdgeForNextUserScroll(ctx);
890
- (_b2 = (_a4 = state.props).onScrollBeginDrag) == null ? void 0 : _b2.call(_a4, event);
891
- },
892
-@@ -7676,11 +7941,18 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
893
- ListFooterComponent,
894
- ListFooterComponentStyle,
895
- ListHeaderComponent,
896
-+ onInternalMomentumScrollBegin: () => {
897
-+ ctx.state.isMomentumScrolling = true;
898
-+ },
899
- onInternalScrollBeginDrag: fns.onScrollBeginDrag,
900
-+ onInternalScrollEndDrag: () => {
901
-+ ctx.state.isUserDragging = false;
902
-+ },
903
- onInternalScrollEnd: fns.onScrollEnd,
904
- onLayout,
905
- onLayoutFooter,
906
- onMomentumScrollEnd: fns.onMomentumScrollEnd,
907
-+ onScrollBeginDrag: fns.onScrollBeginDrag,
908
- onScroll: onScrollHandler,
909
- recycleItems,
910
- refreshControl: refreshControlElement ? stylePaddingTopState > 0 ? React2__namespace.cloneElement(refreshControlElement, {
911
-diff --git a/react-native.mjs b/react-native.mjs
912
-index 40e87cda8c9bc79a889e5542f29af429a24b24d4..c2ca39bab6ea1ebaaed25190a01e8cf2e395ece9 100644
913
---- a/react-native.mjs
914
-+++ b/react-native.mjs
915
-@@ -696,6 +696,15 @@ function hasActiveInitialScroll(state) {
916
- return !!(state == null ? void 0 : state.initialScroll) && !state.didFinishInitialScroll;
917
- }
918
-
919
-+// Size-only changes may not emit a scroll event to refresh the edge signal.
920
-+function getIsAtEnd(ctx, contentSize = getContentSize(ctx)) {
921
-+ const { queuedInitialLayout, scroll, scrollLength } = ctx.state;
922
-+ if (!(contentSize > 0 && queuedInitialLayout)) {
923
-+ return peek$(ctx, "isAtEnd");
924
-+ }
925
-+ return contentSize < scrollLength || contentSize - scroll - scrollLength - getContentInsetEnd(ctx) <= EDGE_POSITION_EPSILON;
926
-+}
927
-+
928
- // src/utils/checkAtBottom.ts
929
- function checkAtBottom(ctx, allowedEdge, allowGateCreatedInCurrentCheck) {
930
- var _a3;
931
-@@ -716,7 +725,7 @@ function checkAtBottom(ctx, allowedEdge, allowGateCreatedInCurrentCheck) {
932
- const insetEnd = getContentInsetEnd(ctx);
933
- const distanceFromEnd = contentSize - scroll - scrollLength - insetEnd;
934
- const isContentLess = contentSize < scrollLength;
935
-- set$(ctx, "isAtEnd", isContentLess || distanceFromEnd <= EDGE_POSITION_EPSILON);
936
-+ set$(ctx, "isAtEnd", getIsAtEnd(ctx, contentSize));
937
- set$(ctx, "isNearEnd", isContentLess || distanceFromEnd <= onEndReachedThreshold * scrollLength);
938
- set$(
939
- ctx,
940
-@@ -933,7 +942,16 @@ function setInitialRenderState(ctx, {
941
- if (didInitialScroll) {
942
- state.didFinishInitialScroll = true;
943
- }
944
-- const isReadyToRender = Boolean(state.didContainersLayout && state.didFinishInitialScroll);
945
-+ // Native contentOffset can seed an end target without dispatchInitialScroll.
946
-+ // Both overflow completion paths must wait for the native end landing.
947
-+ // Underflow needs no scroll: preserve UIKit's untouched resting position.
948
-+ if (state.didContainersLayout && state.didFinishInitialScroll && state.initialScroll && state.initialScroll.viewPosition === 1 && state.initialScroll.index === state.props.data.length - 1 && state.props.data.length > 0) {
949
-+ const insetStartAdjustment = getContentInsetStartAdjustment(ctx);
950
-+ if (insetStartAdjustment > 0 && getContentSize(ctx) > state.scrollLength - insetStartAdjustment + 1) {
951
-+ startInsetEndSettleWatchdog(ctx);
952
-+ }
953
-+ }
954
-+ const isReadyToRender = Boolean(state.didContainersLayout && state.didFinishInitialScroll && !state.insetEndRevealHold);
955
- if (isReadyToRender && !peek$(ctx, "readyToRender")) {
956
- set$(ctx, "readyToRender", true);
957
- setAdaptiveRender(ctx, "normal", "ready");
958
-@@ -1069,7 +1087,7 @@ function getRawContentLength(ctx) {
959
- function getAlignItemsAtEndPadding(ctx) {
960
- const { state } = ctx;
961
- const shouldPad = !!state.props.alignItemsAtEndPaddingEnabled && !state.props.horizontal && state.props.data.length > 0 && state.scrollLength > 0;
962
-- return shouldPad ? Math.max(0, state.scrollLength - getRawContentLength(ctx) - getContentInsetEnd(ctx)) : 0;
963
-+ return shouldPad ? Math.max(0, state.scrollLength - getContentInsetStartAdjustment(ctx) - getRawContentLength(ctx) - getContentInsetEnd(ctx)) : 0;
964
- }
965
- function updateContentMetricsState(ctx) {
966
- const previousPadding = peek$(ctx, "alignItemsAtEndPadding") || 0;
967
-@@ -1094,6 +1112,10 @@ function addTotalSize(ctx, key, add, notifyTotalSize = true) {
968
- totalSize += add;
969
- }
970
- if (prevTotalSize !== totalSize) {
971
-+ const now = Date.now();
972
-+ const isContinuingContentSizeAnimation = state.contentSizeAnimationActiveEpoch !== void 0;
973
-+ state.contentSizeAnimationEpoch = (state.contentSizeAnimationEpoch || 0) + 1;
974
-+ state.contentSizeAnimationEligible = !!state.props.sizeComponentInternal && state.didContainersLayout && (isContinuingContentSizeAnimation || !state.props.maintainScrollAtEnd && !state.isUserDragging && !state.isMomentumScrolling && now - (state.lastMVCPAdjustTime || 0) >= 300);
975
- if (!IsNewArchitecture && state.initialScroll && totalSize < prevTotalSize) {
976
- state.pendingTotalSize = totalSize;
977
- } else {
978
-@@ -1283,18 +1305,23 @@ function calculateOffsetWithOffsetPosition(ctx, offsetParam, params) {
979
- }
980
-
981
- // src/core/clampScrollOffset.ts
982
-+function getContentInsetStartAdjustment(ctx) {
983
-+ const adjustment = ctx.state.props.contentInsetStartAdjustment;
984
-+ return typeof adjustment === "number" && Number.isFinite(adjustment) ? Math.max(0, adjustment) : 0;
985
-+}
986
- function clampScrollOffset(ctx, offset, scrollTarget) {
987
- const state = ctx.state;
988
- const contentSize = getContentSize(ctx);
989
-+ const minOffset = -getContentInsetStartAdjustment(ctx);
990
- let clampedOffset = offset;
991
- if (Number.isFinite(contentSize) && Number.isFinite(state.scrollLength) && (Platform.OS !== "android" || state.lastLayout)) {
992
-- const baseMaxOffset = Math.max(0, contentSize - state.scrollLength);
993
-+ const baseMaxOffset = Math.max(minOffset, contentSize - state.scrollLength);
994
- const viewOffset = scrollTarget == null ? void 0 : scrollTarget.viewOffset;
995
- const extraEndOffset = typeof viewOffset === "number" && viewOffset < 0 ? -viewOffset : 0;
996
- const maxOffset = baseMaxOffset + extraEndOffset;
997
- clampedOffset = Math.min(offset, maxOffset);
998
- }
999
-- clampedOffset = Math.max(0, clampedOffset);
1000
-+ clampedOffset = Math.max(minOffset, clampedOffset);
1001
- return clampedOffset;
1002
- }
1003
-
1004
-@@ -1430,10 +1457,10 @@ function checkFinishedScrollFrame(ctx) {
1005
- finishScrollTo(ctx);
1006
- }
1007
- }
1008
--function scrollToFallbackOffset(ctx, offset) {
1009
-+function scrollToFallbackOffset(ctx, offset, animated) {
1010
- var _a3;
1011
- (_a3 = ctx.state.refScroller.current) == null ? void 0 : _a3.scrollTo({
1012
-- animated: false,
1013
-+ animated: !!animated,
1014
- x: ctx.state.props.horizontal ? offset : 0,
1015
- y: ctx.state.props.horizontal ? 0 : offset
1016
- });
1017
-@@ -1482,7 +1509,10 @@ function checkFinishedScrollFallback(ctx) {
1018
- );
1019
- scheduleFallbackCheck(SILENT_INITIAL_SCROLL_RETRY_DELAY_MS);
1020
- } else if (shouldRetryUnalignedEndScroll) {
1021
-- scrollToFallbackOffset(ctx, completionState.clampedTargetOffset);
1022
-+ const isActivelyAnimatingToEnd = !!isStillScrollingTo.animated && Date.now() - state.scrollTime < 100;
1023
-+ if (!isActivelyAnimatingToEnd) {
1024
-+ scrollToFallbackOffset(ctx, completionState.clampedTargetOffset, !!isStillScrollingTo.animated);
1025
-+ }
1026
- scheduleFallbackCheck(100);
1027
- } else if (shouldFinishZeroTarget || shouldFinishAfterObservedScroll || canFinishInitialScrollWithoutNativeProgress || canFinishAfterSilentNativeDispatch || numChecks > maxChecks) {
1028
- finishScrollTo(ctx);
1029
-@@ -1539,15 +1569,33 @@ function doMaintainScrollAtEnd(ctx) {
1030
- } = state;
1031
- const isWithinMaintainScrollAtEndThreshold = peek$(ctx, "isWithinMaintainScrollAtEndThreshold");
1032
- const shouldMaintainScrollAtEnd = !!(isWithinMaintainScrollAtEndThreshold && maintainScrollAtEnd && didContainersLayout);
1033
-+ if (state.contentSizeAnimationActiveEpoch !== void 0) {
1034
-+ state.pendingMaintainScrollAtEnd = false;
1035
-+ return false;
1036
-+ }
1037
- if (pendingNativeMVCPAdjust) {
1038
- state.pendingMaintainScrollAtEnd = shouldMaintainScrollAtEnd;
1039
- return false;
1040
- }
1041
-+ // T3 patch: a caller anchor already placed this pass's offset; a later scroll would move it.
1042
-+ if (state.props.sizeChangeAnchor && !state.mvcpDataChanged && state.props.sizeChangeAnchor() !== void 0) {
1043
-+ state.pendingMaintainScrollAtEnd = false;
1044
-+ return shouldMaintainScrollAtEnd;
1045
-+ }
1046
- if (shouldMaintainScrollAtEnd) {
1047
- state.pendingMaintainScrollAtEnd = false;
1048
-+ const maintainAnchoredEndSpace = state.props.anchoredEndSpace;
1049
-+ const maintainAnchorIndex = maintainAnchoredEndSpace == null ? void 0 : maintainAnchoredEndSpace.anchorIndex;
1050
-+ if (maintainAnchorIndex !== void 0 && maintainAnchorIndex >= 0 && maintainAnchorIndex < state.props.data.length && !areKnownOrFixedItemSizesAvailable(ctx, maintainAnchorIndex, state.props.data.length - 1)) {
1051
-+ return false;
1052
-+ }
1053
- const contentSize = getContentSize(ctx);
1054
-+ const maintainInsetStartAdjustment = getContentInsetStartAdjustment(ctx);
1055
- if (contentSize < state.scrollLength) {
1056
-- state.scroll = 0;
1057
-+ state.scroll = -maintainInsetStartAdjustment;
1058
-+ if (maintainInsetStartAdjustment > 0) {
1059
-+ return true;
1060
-+ }
1061
- }
1062
- if (!state.maintainingScrollAtEnd) {
1063
- const pendingState = maintainScrollAtEnd.animated ? "pending-animated" : "pending-instant";
1064
-@@ -1570,9 +1618,18 @@ function doMaintainScrollAtEnd(ctx) {
1065
- y: 0
1066
- });
1067
- } else {
1068
-- scroller == null ? void 0 : scroller.scrollToEnd({
1069
-- animated: maintainScrollAtEnd.animated
1070
-- });
1071
-+ const insetStartAdjustment = getContentInsetStartAdjustment(ctx);
1072
-+ if (insetStartAdjustment > 0) {
1073
-+ scroller == null ? void 0 : scroller.scrollTo({
1074
-+ animated: maintainScrollAtEnd.animated,
1075
-+ x: 0,
1076
-+ y: Math.max(-insetStartAdjustment, getContentSize(ctx) - state.scrollLength)
1077
-+ });
1078
-+ } else {
1079
-+ scroller == null ? void 0 : scroller.scrollToEnd({
1080
-+ animated: maintainScrollAtEnd.animated
1081
-+ });
1082
-+ }
1083
- }
1084
- setTimeout(
1085
- () => {
1086
-@@ -1603,6 +1660,10 @@ function doMaintainScrollAtEnd(ctx) {
1087
- function requestAdjust(ctx, positionDiff, dataChanged) {
1088
- const state = ctx.state;
1089
- if (Math.abs(positionDiff) > 0.1) {
1090
-+ // Timestamp for ReanimatedPositionView: repositions caused by an MVCP
1091
-+ // size adjustment are already compensated by a contentOffset shift, so
1092
-+ // animating them would make rows visibly lurch and slide back.
1093
-+ state.lastMVCPAdjustTime = Date.now();
1094
- const needsScrollWorkaround = Platform.OS === "android" && !IsNewArchitecture && dataChanged && state.scroll <= positionDiff;
1095
- const doit = () => {
1096
- if (needsScrollWorkaround) {
1097
-@@ -1707,7 +1768,9 @@ function getPredictedNativeClamp(state, unresolvedAmount, totalSize) {
1098
- if (Math.abs(unresolvedAmount) <= MVCP_POSITION_EPSILON) {
1099
- return 0;
1100
- }
1101
-- const maxScroll = Math.max(0, totalSize - state.scrollLength);
1102
-+ const insetStartAdjustment = state.props.contentInsetStartAdjustment;
1103
-+ const minScroll = typeof insetStartAdjustment === "number" && Number.isFinite(insetStartAdjustment) ? -Math.max(0, insetStartAdjustment) : 0;
1104
-+ const maxScroll = Math.max(minScroll, totalSize - state.scrollLength);
1105
- const clampDelta = maxScroll - state.scroll;
1106
- if (unresolvedAmount < 0) {
1107
- return Math.max(unresolvedAmount, Math.min(0, clampDelta));
1108
-@@ -1769,7 +1832,7 @@ function resolvePendingNativeMVCPAdjust(ctx, newScroll) {
1109
- settlePendingNativeMVCPAdjust(ctx, remainingAfterManual, nativeDelta);
1110
- return true;
1111
- }
1112
-- const expectedNativeClampScroll = Math.max(0, getContentSize(ctx) - state.scrollLength);
1113
-+ const expectedNativeClampScroll = Math.max(-getContentInsetStartAdjustment(ctx), getContentSize(ctx) - state.scrollLength);
1114
- const distanceToClamp = Math.abs(newScroll - expectedNativeClampScroll);
1115
- const isAtExpectedNativeClamp = distanceToClamp <= NATIVE_END_CLAMP_EPSILON;
1116
- if (isAtExpectedNativeClamp) {
1117
-@@ -1790,7 +1853,35 @@ function resolvePendingNativeMVCPAdjust(ctx, newScroll) {
1118
- }
1119
- return false;
1120
- }
1121
-+// T3 patch: a caller anchor decides where a size change leaves the scroll position. It is read in
1122
-+// the same pass that repositions the items, so the adjustment commits with the new positions.
1123
- function prepareMVCP(ctx, dataChanged) {
1124
-+ // T3 patch: a data change skips the caller anchor, so end maintenance must still run after it.
1125
-+ ctx.state.mvcpDataChanged = !!dataChanged;
1126
-+ const sizeChangeAnchor = dataChanged ? void 0 : ctx.state.props.sizeChangeAnchor;
1127
-+ const restore = prepareDefaultMVCP(ctx, dataChanged);
1128
-+ if (!sizeChangeAnchor || ctx.state.scrollingTo !== void 0) {
1129
-+ return restore;
1130
-+ }
1131
-+ return () => {
1132
-+ const target = sizeChangeAnchor();
1133
-+ if (target === void 0) {
1134
-+ restore == null ? void 0 : restore();
1135
-+ return;
1136
-+ }
1137
-+ // Content that shrinks under an offset past its new end pulls the native offset back to
1138
-+ // that end by itself; only the rest of the way to the target is adjusted.
1139
-+ const endOffset = clampScrollOffset(ctx, Number.POSITIVE_INFINITY);
1140
-+ if (ctx.state.scroll > endOffset) {
1141
-+ ctx.state.scroll = endOffset;
1142
-+ }
1143
-+ const positionDiff = clampScrollOffset(ctx, target) - ctx.state.scroll;
1144
-+ if (Math.abs(positionDiff) > MVCP_POSITION_EPSILON) {
1145
-+ requestAdjust(ctx, positionDiff, false);
1146
-+ }
1147
-+ };
1148
-+}
1149
-+function prepareDefaultMVCP(ctx, dataChanged) {
1150
- const state = ctx.state;
1151
- const { idsInView, positions, props } = state;
1152
- const {
1153
-@@ -1902,7 +1993,7 @@ function prepareMVCP(ctx, dataChanged) {
1154
- if (diff > 0) {
1155
- diff = Math.max(0, totalSize - state.scroll - state.scrollLength);
1156
- } else {
1157
-- const maxScroll = Math.max(0, totalSize - state.scrollLength);
1158
-+ const maxScroll = Math.max(-getContentInsetStartAdjustment(ctx), totalSize - state.scrollLength);
1159
- state.scroll = maxScroll;
1160
- state.scrollPending = maxScroll;
1161
- diff = 0;
1162
-@@ -2299,8 +2390,121 @@ function scrollToIndex(ctx, {
1163
- }
1164
-
1165
- // src/core/initialScroll.ts
1166
-+var INSET_END_SETTLE_WATCHDOG_FRAMES = 150;
1167
-+var INSET_END_SETTLE_WATCHDOG_STABLE_FRAMES = 20;
1168
-+var INSET_END_REVEAL_STABLE_FRAMES = 3;
1169
-+var INSET_END_REVEAL_MAX_HOLD_FRAMES = 40;
1170
-+function startInsetEndSettleWatchdog(ctx) {
1171
-+ const state = ctx.state;
1172
-+ if (state.insetEndSettleWatchdogStarted || state.didLoad) {
1173
-+ return;
1174
-+ }
1175
-+ state.insetEndSettleWatchdogStarted = true;
1176
-+ state.insetEndSettleWatchdogActive = true;
1177
-+ // Hold the readyToRender opacity gate until the end landing is stable, so
1178
-+ // the estimated-to-measured settle chase happens before first VISIBLE
1179
-+ // paint instead of in front of the user. Capped so slow measurement can
1180
-+ // never hide content for long.
1181
-+ state.insetEndRevealHold = true;
1182
-+ let frames = 0;
1183
-+ let settledFrames = 0;
1184
-+ let revealStableFrames = 0;
1185
-+ let previousEndOffset;
1186
-+ const releaseRevealHold = () => {
1187
-+ if (state.insetEndRevealHold) {
1188
-+ state.insetEndRevealHold = false;
1189
-+ setInitialRenderState(ctx, {});
1190
-+ }
1191
-+ };
1192
-+ // Revealing flips adaptive rendering to "normal", which re-renders rows and
1193
-+ // can move the end target one more time — do that upgrade while still
1194
-+ // hidden (phase 1), then require stability again before revealing (phase 2)
1195
-+ // so the first visible frame is the settled one.
1196
-+ let revealPhase = 1;
1197
-+ const onRevealStability = () => {
1198
-+ var _a3;
1199
-+ if (!state.insetEndRevealHold) {
1200
-+ return;
1201
-+ }
1202
-+ if (revealPhase === 1) {
1203
-+ revealPhase = 2;
1204
-+ revealStableFrames = 0;
1205
-+ setAdaptiveRender(ctx, "normal");
1206
-+ (_a3 = state.triggerCalculateItemsInView) == null ? void 0 : _a3.call(state);
1207
-+ return;
1208
-+ }
1209
-+ releaseRevealHold();
1210
-+ };
1211
-+ const tick = () => {
1212
-+ // The user owns the scroll from their first drag — a re-pin here would
1213
-+ // pin the list under their finger.
1214
-+ if (frames++ >= INSET_END_SETTLE_WATCHDOG_FRAMES || settledFrames >= INSET_END_SETTLE_WATCHDOG_STABLE_FRAMES || state.didUserDrag || !ctx.state || ctx.state !== state) {
1215
-+ state.insetEndSettleWatchdogActive = false;
1216
-+ releaseRevealHold();
1217
-+ return;
1218
-+ }
1219
-+ if (frames >= INSET_END_REVEAL_MAX_HOLD_FRAMES) {
1220
-+ releaseRevealHold();
1221
-+ }
1222
-+ const insetStartAdjustment = getContentInsetStartAdjustment(ctx);
1223
-+ const contentSize = getContentSize(ctx);
1224
-+ const scrollLength = state.scrollLength;
1225
-+ const endOffset = Math.max(-insetStartAdjustment, contentSize - scrollLength);
1226
-+ // state.scroll is optimistic: non-animated scrollTo writes it before UIKit
1227
-+ // moves. Only a native scroll event proves that the requested offset landed.
1228
-+ const nativeOffset = state.lastNativeScroll;
1229
-+ const hasNativeOffset = typeof nativeOffset === "number" && Number.isFinite(nativeOffset);
1230
-+ const distance = hasNativeOffset ? endOffset - nativeOffset : Infinity;
1231
-+ const isIdle = !state.scrollingTo && !state.maintainingScrollAtEnd;
1232
-+ const hasViewport = insetStartAdjustment > 0 && scrollLength > 0 && Number.isFinite(contentSize);
1233
-+ const isStable = hasViewport && isIdle && Math.abs(distance) <= 2 && previousEndOffset !== void 0 && Math.abs(endOffset - previousEndOffset) <= 1;
1234
-+ previousEndOffset = endOffset;
1235
-+ if (isStable) {
1236
-+ settledFrames++;
1237
-+ revealStableFrames++;
1238
-+ if (revealStableFrames >= INSET_END_REVEAL_STABLE_FRAMES) {
1239
-+ onRevealStability();
1240
-+ }
1241
-+ } else {
1242
-+ settledFrames = 0;
1243
-+ revealStableFrames = 0;
1244
-+ // Keep the existing near-end correction limit. In-flight scrolls and
1245
-+ // unknown native offsets wait; neither counts as a settled frame.
1246
-+ if (hasViewport && isIdle && Math.abs(distance) > 2 && Math.abs(distance) <= scrollLength * 0.5) {
1247
-+ const scroller = state.refScroller.current;
1248
-+ if (scroller) {
1249
-+ scroller.scrollTo({ animated: false, x: 0, y: endOffset });
1250
-+ }
1251
-+ }
1252
-+ }
1253
-+ requestAnimationFrame(tick);
1254
-+ };
1255
-+ requestAnimationFrame(tick);
1256
-+}
1257
- function dispatchInitialScroll(ctx, params) {
1258
- const { forceScroll, resolvedOffset, target, waitForCompletionFrame } = params;
1259
-+ const insetStartAdjustment = getContentInsetStartAdjustment(ctx);
1260
-+ if (insetStartAdjustment > 0 && ctx.state.props.data.length > 0) {
1261
-+ if (ctx.state.scrollLength <= 0) {
1262
-+ // The scroll length is unknown, so the resolved target is meaningless;
1263
-+ // the initial-scroll machinery re-advances after layout.
1264
-+ return;
1265
-+ }
1266
-+ if (resolvedOffset <= -insetStartAdjustment + 1 && !ctx.state.didDispatchInsetInitialScroll) {
1267
-+ // Content underflows the viewport and nothing has scrolled yet: the
1268
-+ // untouched native rest position (UIKit's adjustedContentInset) IS the
1269
-+ // end position. Dispatching a negative scroll here would race UIKit's
1270
-+ // inset application during screen attach, so just finish the session.
1271
-+ finishInitialScroll(ctx, {
1272
-+ resolvedOffset
1273
-+ });
1274
-+ return;
1275
-+ }
1276
-+ ctx.state.didDispatchInsetInitialScroll = true;
1277
-+ if (target.viewPosition === 1) {
1278
-+ startInsetEndSettleWatchdog(ctx);
1279
-+ }
1280
-+ }
1281
- const requestedIndex = target.index;
1282
- const index = requestedIndex !== void 0 ? clampScrollIndex(requestedIndex, ctx.state.props.data.length) : void 0;
1283
- const itemSize = getItemSizeAtIndex(ctx, index);
1284
-@@ -2726,7 +2930,9 @@ function clearFinishedBootstrapInitialScrollTargetIfMovedAway(ctx) {
1285
- return;
1286
- }
1287
- if (didFinishedInitialScrollMoveAwayFromTarget(ctx, initialScroll)) {
1288
-- const shouldKeepEndTargetAlive = isRetargetableBottomAlignedInitialScrollTarget(initialScroll) && peek$(ctx, "isAtEnd");
1289
-+ const endTargetDistanceFromEnd = getContentSize(ctx) - state.scroll - state.scrollLength - getContentInsetEnd(ctx);
1290
-+ const isNearEndForInsetList = getContentInsetStartAdjustment(ctx) > 0 && Number.isFinite(endTargetDistanceFromEnd) && endTargetDistanceFromEnd <= state.scrollLength * 0.5;
1291
-+ const shouldKeepEndTargetAlive = isRetargetableBottomAlignedInitialScrollTarget(initialScroll) && (peek$(ctx, "isAtEnd") || !state.didUserDrag && isNearEndForInsetList);
1292
- if (!shouldKeepEndTargetAlive) {
1293
- if (shouldPreserveInitialScrollForFooterLayout(initialScroll)) {
1294
- clearPendingInitialScrollFooterLayout(ctx, {
1295
-@@ -4651,7 +4857,8 @@ function maybeUpdateAnchoredEndSpace(ctx) {
1296
- contentBelowAnchor = Math.max(0, contentBelowAnchor - ctx.scrollAxisGap);
1297
- contentBelowAnchor += (ctx.values.get("footerSize") || 0) + getStylePaddingEnd(state.props);
1298
- isReady = !hasUnknownTailSize;
1299
-- nextSize = hasUnknownTailSize ? previousSize || 0 : Math.max(0, state.scrollLength - contentBelowAnchor - anchorOffset);
1300
-+ const knownSizeBound = Math.max(0, state.scrollLength - contentBelowAnchor - anchorOffset);
1301
-+ nextSize = hasUnknownTailSize ? Math.min(previousSize || 0, knownSizeBound) : knownSizeBound;
1302
- } else if (anchorIndex >= 0) {
1303
- isReady = false;
1304
- }
1305
-@@ -4671,6 +4878,12 @@ function maybeUpdateAnchoredEndSpace(ctx) {
1306
- updateScroll(ctx, state.scroll, true, { markHasScrolled: false });
1307
- }
1308
- (_b = anchoredEndSpace == null ? void 0 : anchoredEndSpace.onReady) == null ? void 0 : _b.call(anchoredEndSpace, { anchorIndex: nextAnchorIndex, anchorKey: nextAnchorKey, size: nextSize });
1309
-+ } else if (!isReady && didSizeChange && nextSize < (previousSize || 0)) {
1310
-+ set$(ctx, "anchoredEndSpaceSize", nextSize);
1311
-+ (_a3 = anchoredEndSpace == null ? void 0 : anchoredEndSpace.onSizeChanged) == null ? void 0 : _a3.call(anchoredEndSpace, nextSize);
1312
-+ if (anchoredEndSpace == null ? void 0 : anchoredEndSpace.includeInEndInset) {
1313
-+ updateScroll(ctx, state.scroll, true, { markHasScrolled: false });
1314
-+ }
1315
- }
1316
- return nextSize;
1317
- }
1318
-@@ -5694,8 +5907,11 @@ var ContainersLayer = typedMemo(function ContainersLayer2({
1319
- horizontal
1320
- }) {
1321
- const ctx = useStateContext();
1322
-+ const SizeComponent = ctx.state.props.sizeComponentInternal;
1323
- const columnWrapperStyle = ctx.columnWrapperStyle;
1324
-- const animSize = useValue$("totalSize");
1325
-+ // T3 patch: on the new architecture an animated value commits on its own, ahead of the item
1326
-+ // positions and their scroll compensation; a rendered size commits with them.
1327
-+ const animSize = IsNewArchitecture ? useArr$(["totalSize"])[0] || 0 : useValue$("totalSize");
1328
- const [readyToRender, numColumns, otherAxisSize = 0] = useArr$(["readyToRender", "numColumns", "otherAxisSize"]);
1329
- const isVisible = useFreshDataTransitionVisibility(!!readyToRender, freshDataTransitionEpoch);
1330
- const style = horizontal ? {
1331
-@@ -5704,6 +5920,13 @@ var ContainersLayer = typedMemo(function ContainersLayer2({
1332
- opacity: isVisible ? 1 : 0,
1333
- width: animSize
1334
- } : { height: animSize, minWidth: otherAxisSize, opacity: isVisible ? 1 : 0 };
1335
-+ if (SizeComponent) {
1336
-+ if (horizontal) {
1337
-+ delete style.width;
1338
-+ } else {
1339
-+ delete style.height;
1340
-+ }
1341
-+ }
1342
- if (columnWrapperStyle) {
1343
- const { columnGap, rowGap, gap } = columnWrapperStyle;
1344
- const gapX = columnGap || gap || 0;
1345
-@@ -5724,7 +5947,8 @@ var ContainersLayer = typedMemo(function ContainersLayer2({
1346
- }
1347
- }
1348
- }
1349
-- return /* @__PURE__ */ React2.createElement(Animated.View, { pointerEvents: isVisible ? void 0 : "none", style }, /* @__PURE__ */ React2.createElement(ContainerLayoutCoordinator, null, children));
1350
-+ const content = /* @__PURE__ */ React2.createElement(ContainerLayoutCoordinator, null, children);
1351
-+ return SizeComponent ? /* @__PURE__ */ React2.createElement(SizeComponent, { horizontal, pointerEvents: isVisible ? void 0 : "none", signalName: "totalSize", style }, content) : /* @__PURE__ */ React2.createElement(Animated.View, { pointerEvents: isVisible ? void 0 : "none", style }, content);
1352
- });
1353
- var Containers = typedMemo(function Containers2({
1354
- freshDataTransitionEpoch,
1355
-@@ -5875,7 +6099,12 @@ var StyleSheet = StyleSheet$1;
1356
-
1357
- // src/components/ListComponent.tsx
1358
- var AlignItemsAtEndSpacer = typedMemo(function AlignItemsAtEndSpacer2({ horizontal }) {
1359
-+ const ctx = useStateContext();
1360
- const [alignItemsAtEndPadding = 0] = useArr$(["alignItemsAtEndPadding"]);
1361
-+ const SizeComponent = ctx.state.props.sizeComponentInternal;
1362
-+ if (SizeComponent) {
1363
-+ return /* @__PURE__ */ React2.createElement(SizeComponent, { horizontal, signalName: "alignItemsAtEndPadding", style: { flexShrink: 0 } });
1364
-+ }
1365
- if (alignItemsAtEndPadding <= 0) {
1366
- return null;
1367
- }
1368
-@@ -5908,8 +6137,12 @@ var ListComponent = typedMemo(function ListComponent2({
1369
- refScrollView,
1370
- renderScrollComponent,
1371
- onLayoutFooter,
1372
-+ onInternalMomentumScrollBegin,
1373
- onInternalScrollBeginDrag,
1374
-+ onInternalScrollEndDrag,
1375
- onInternalScrollEnd,
1376
-+ onMomentumScrollBegin,
1377
-+ onScrollEndDrag,
1378
- scrollAdjustHandler,
1379
- snapToIndices,
1380
- stickyHeaderConfig,
1381
-@@ -5980,7 +6213,17 @@ var ListComponent = typedMemo(function ListComponent2({
1382
- SnapOrScroll,
1383
- {
1384
- ...rest,
1385
-- ...Platform.OS === "web" ? ScrollComponent === ListComponentScrollView ? { onInternalScrollEnd, useWindowScroll } : {} : { onScrollBeginDrag: onInternalScrollBeginDrag },
1386
-+ ...Platform.OS === "web" ? ScrollComponent === ListComponentScrollView ? { onInternalScrollEnd, useWindowScroll } : {} : {
1387
-+ onMomentumScrollBegin: (event) => {
1388
-+ onInternalMomentumScrollBegin == null ? void 0 : onInternalMomentumScrollBegin(event);
1389
-+ onMomentumScrollBegin == null ? void 0 : onMomentumScrollBegin(event);
1390
-+ },
1391
-+ onScrollBeginDrag: onInternalScrollBeginDrag,
1392
-+ onScrollEndDrag: (event) => {
1393
-+ onInternalScrollEndDrag == null ? void 0 : onInternalScrollEndDrag(event);
1394
-+ onScrollEndDrag == null ? void 0 : onScrollEndDrag(event);
1395
-+ }
1396
-+ },
1397
- contentContainerStyle: [
1398
- horizontal ? { height: "100%" } : {},
1399
- contentContainerStyle,
1400
-@@ -5989,7 +6232,10 @@ var ListComponent = typedMemo(function ListComponent2({
1401
- ],
1402
- contentOffset: initialContentOffset !== void 0 ? horizontal ? { x: initialContentOffset, y: 0 } : { x: 0, y: initialContentOffset } : void 0,
1403
- horizontal,
1404
-- maintainVisibleContentPosition: maintainVisibleContentPosition.size || maintainVisibleContentPosition.data ? { minIndexForVisible: 0 } : void 0,
1405
-+ // Keep iOS anchored to ScrollAdjust even when JS position restoration is
1406
-+ // disabled. Re-enabling native MVCP mid-drag can compare its stale anchor
1407
-+ // with the 1e7 sentinel and scroll the entire list out of view.
1408
-+ maintainVisibleContentPosition: Platform.OS === "ios" || maintainVisibleContentPosition.size || maintainVisibleContentPosition.data ? { minIndexForVisible: 0 } : void 0,
1409
- onLayout,
1410
- onScroll: onScroll2,
1411
- ref: refScrollView,
1412
-@@ -6246,7 +6492,8 @@ function handleLayout(ctx, layoutParam, setCanRender) {
1413
- if (scrollLength > 0) {
1414
- doInitialAllocateContainers(ctx);
1415
- }
1416
-- if (needsCalculate) {
1417
-+ // T3 patch: a shorter list keeps a caller anchor too, such as the end.
1418
-+ if (needsCalculate || state.props.sizeChangeAnchor) {
1419
- calculateItemsInView(ctx, { doMVCP: true });
1420
- }
1421
- if (didChange || otherAxisSize !== prevOtherAxisSize) {
1422
-@@ -6730,7 +6977,7 @@ function createImperativeHandle(ctx, scheduleImperativeScrollCommit) {
1423
- endBuffered: state.endBuffered,
1424
- getAverageItemSizes: () => getAverageItemSizes(state),
1425
- indexByKey: (key) => state.indexByKey.get(key),
1426
-- isAtEnd: peek$(ctx, "isAtEnd"),
1427
-+ isAtEnd: getIsAtEnd(ctx),
1428
- isAtStart: peek$(ctx, "isAtStart"),
1429
- isEndReached: state.isEndReached,
1430
- isNearEnd: peek$(ctx, "isNearEnd"),
1431
-@@ -7054,6 +7301,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
1432
- dataVersion,
1433
- drawDistance = 250,
1434
- contentInsetEndAdjustment,
1435
-+ contentInsetStartAdjustment,
1436
- estimatedItemSize = 100,
1437
- estimatedListSize,
1438
- extraData,
1439
-@@ -7075,6 +7323,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
1440
- maintainScrollAtEnd = false,
1441
- maintainScrollAtEndThreshold = 0.1,
1442
- maintainVisibleContentPosition: maintainVisibleContentPositionProp,
1443
-+ sizeChangeAnchor,
1444
- numColumns: numColumnsProp = 1,
1445
- overrideItemLayout,
1446
- onEndReached,
1447
-@@ -7111,10 +7360,12 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
1448
- const animatedPropsInternal = props.animatedPropsInternal;
1449
- const anchoredEndSpaceOwner = (_a3 = props.anchoredEndSpaceOwnerInternal) != null ? _a3 : "list";
1450
- const positionComponentInternal = props.positionComponentInternal;
1451
-+ const sizeComponentInternal = props.sizeComponentInternal;
1452
- const stickyPositionComponentInternal = props.stickyPositionComponentInternal;
1453
- const {
1454
- anchoredEndSpaceOwnerInternal: _anchoredEndSpaceOwnerInternal,
1455
- positionComponentInternal: _positionComponentInternal,
1456
-+ sizeComponentInternal: _sizeComponentInternal,
1457
- stickyPositionComponentInternal: _stickyPositionComponentInternal,
1458
- ...restProps
1459
- } = rest;
1460
-@@ -7179,7 +7430,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
1461
- const combinedRef = useCombinedRef(refScroller, refScrollView);
1462
- const keyExtractor = keyExtractorProp != null ? keyExtractorProp : ((_item, index) => index.toString());
1463
- const stickyHeaderIndices = stickyHeaderIndicesProp;
1464
-- const contentInsetEndAdjustmentResolved = Platform.OS === "web" ? contentInsetEndAdjustment : void 0;
1465
-+ const contentInsetEndAdjustmentResolved = contentInsetEndAdjustment;
1466
- const previousContentInsetEndAdjustmentRef = useRef(contentInsetEndAdjustmentResolved);
1467
- const alwaysRenderIndices = useMemo(() => {
1468
- const indices = getAlwaysRenderIndices(alwaysRender, dataProp, keyExtractor, anchoredEndSpace == null ? void 0 : anchoredEndSpace.anchorIndex);
1469
-@@ -7320,6 +7571,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
1470
- contentContainerAlignItems: contentContainerStyle.alignItems,
1471
- contentInset,
1472
- contentInsetEndAdjustment: contentInsetEndAdjustmentResolved,
1473
-+ contentInsetStartAdjustment,
1474
- data: dataProp,
1475
- dataKey,
1476
- dataVersion,
1477
-@@ -7333,6 +7585,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
1478
- maintainScrollAtEnd: maintainScrollAtEndConfig,
1479
- maintainScrollAtEndThreshold,
1480
- maintainVisibleContentPosition: maintainVisibleContentPositionConfig,
1481
-+ sizeChangeAnchor,
1482
- numColumns: numColumnsProp,
1483
- onEndReached,
1484
- onEndReachedThreshold,
1485
-@@ -7351,6 +7604,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
1486
- renderItem,
1487
- rtl,
1488
- snapToIndices,
1489
-+ sizeComponentInternal,
1490
- stickyHeaderIndicesArr: stickyHeaderIndices != null ? stickyHeaderIndices : [],
1491
- stickyHeaderIndicesSet: useMemo(() => new Set(stickyHeaderIndices != null ? stickyHeaderIndices : []), [stickyHeaderIndices == null ? void 0 : stickyHeaderIndices.join(",")]),
1492
- stickyPositionComponentInternal,
1493
-@@ -7402,6 +7656,13 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
1494
- return void 0;
1495
- }
1496
- const resolvedOffset = (_a4 = initialScroll.contentOffset) != null ? _a4 : resolveInitialScrollOffset(ctx, initialScroll);
1497
-+ if (getContentInsetStartAdjustment(ctx) > 0) {
1498
-+ // With a native leading inset (transparent header + automatic insets),
1499
-+ // any mount-time contentOffset races UIKit's adjustedContentInset
1500
-+ // application. The gated initial-scroll dispatch positions the list once
1501
-+ // real sizes are known instead.
1502
-+ return void 0;
1503
-+ }
1504
- return usesBootstrapInitialScroll && ((_b2 = state.initialScrollSession) == null ? void 0 : _b2.kind) === "bootstrap" && Platform.OS === "web" ? void 0 : resolvedOffset;
1505
- }, [usesBootstrapInitialScroll]);
1506
- useLayoutEffect(() => {
1507
-@@ -7526,6 +7787,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
1508
- [
1509
- dataKey,
1510
- dataVersion,
1511
-+ contentInsetStartAdjustment,
1512
- memoizedLastItemKeys.join(","),
1513
- numColumnsProp,
1514
- nextScrollAxisGap,
1515
-@@ -7622,6 +7884,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
1516
- () => ({
1517
- getRenderedItem: (key) => getRenderedItem(ctx, key),
1518
- onMomentumScrollEnd: (event) => {
1519
-+ state.isMomentumScrolling = false;
1520
- checkFinishedScrollFallback(ctx);
1521
- if (state.props.onMomentumScrollEnd) {
1522
- state.props.onMomentumScrollEnd(event);
1523
-@@ -7630,6 +7893,8 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
1524
- onScroll: (event) => onScroll(ctx, event),
1525
- onScrollBeginDrag: (event) => {
1526
- var _a4, _b2;
1527
-+ ctx.state.didUserDrag = true;
1528
-+ ctx.state.isUserDragging = true;
1529
- prepareReachedEdgeForNextUserScroll(ctx);
1530
- (_b2 = (_a4 = state.props).onScrollBeginDrag) == null ? void 0 : _b2.call(_a4, event);
1531
- },
1532
-@@ -7655,11 +7920,18 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
1533
- ListFooterComponent,
1534
- ListFooterComponentStyle,
1535
- ListHeaderComponent,
1536
-+ onInternalMomentumScrollBegin: () => {
1537
-+ ctx.state.isMomentumScrolling = true;
1538
-+ },
1539
- onInternalScrollBeginDrag: fns.onScrollBeginDrag,
1540
-+ onInternalScrollEndDrag: () => {
1541
-+ ctx.state.isUserDragging = false;
1542
-+ },
1543
- onInternalScrollEnd: fns.onScrollEnd,
1544
- onLayout,
1545
- onLayoutFooter,
1546
- onMomentumScrollEnd: fns.onMomentumScrollEnd,
1547
-+ onScrollBeginDrag: fns.onScrollBeginDrag,
1548
- onScroll: onScrollHandler,
1549
- recycleItems,
1550
- refreshControl: refreshControlElement ? stylePaddingTopState > 0 ? React2.cloneElement(refreshControlElement, {
1551
-diff --git a/react-native.web.js b/react-native.web.js
1552
-index 914d2dafaafa001c9ab6791a0a0581659295e333..8b88b09d1269acef77c6ce0f8aaa1049d4fa26e9 100644
1553
---- a/react-native.web.js
1554
-+++ b/react-native.web.js
1555
-@@ -5651,6 +5651,18 @@ var ContainerSlot = typedMemo(function ContainerSlot2(props) {
1556
- });
1557
-
1558
- // src/utils/reordering.ts
1559
-+// Element.moveBefore keeps the moved subtree's state and does not count as an
1560
-+// insertion, so CSS @starting-style transitions and iframes inside a row do not
1561
-+// restart when the list reorders its containers. insertBefore is the fallback.
1562
-+function moveChildBefore(container, element, reference) {
1563
-+ if (typeof container.moveBefore === "function") {
1564
-+ container.moveBefore(element, reference);
1565
-+ } else if (reference) {
1566
-+ container.insertBefore(element, reference);
1567
-+ } else {
1568
-+ container.appendChild(element);
1569
-+ }
1570
-+}
1571
- function sortDOMElements(container, indexByElement) {
1572
- const elements = Array.from(container.children);
1573
- if (elements.length <= 1) return elements;
1574
-@@ -5690,9 +5702,9 @@ function sortDOMElements(container, indexByElement) {
1575
- }
1576
- }
1577
- if (nextStableElement) {
1578
-- container.insertBefore(element, nextStableElement);
1579
-+ moveChildBefore(container, element, nextStableElement);
1580
- } else {
1581
-- container.appendChild(element);
1582
-+ moveChildBefore(container, element, null);
1583
- }
1584
- }
1585
- }
1586
-diff --git a/react-native.web.mjs b/react-native.web.mjs
1587
-index 95465f2ab89ce41a10553f58af83618f7310e83c..d7cbe1cb43449cc29822b2646deabbddd67f1e7d 100644
1588
---- a/react-native.web.mjs
1589
-+++ b/react-native.web.mjs
1590
-@@ -5630,6 +5630,18 @@ var ContainerSlot = typedMemo(function ContainerSlot2(props) {
1591
- });
1592
-
1593
- // src/utils/reordering.ts
1594
-+// Element.moveBefore keeps the moved subtree's state and does not count as an
1595
-+// insertion, so CSS @starting-style transitions and iframes inside a row do not
1596
-+// restart when the list reorders its containers. insertBefore is the fallback.
1597
-+function moveChildBefore(container, element, reference) {
1598
-+ if (typeof container.moveBefore === "function") {
1599
-+ container.moveBefore(element, reference);
1600
-+ } else if (reference) {
1601
-+ container.insertBefore(element, reference);
1602
-+ } else {
1603
-+ container.appendChild(element);
1604
-+ }
1605
-+}
1606
- function sortDOMElements(container, indexByElement) {
1607
- const elements = Array.from(container.children);
1608
- if (elements.length <= 1) return elements;
1609
-@@ -5669,9 +5681,9 @@ function sortDOMElements(container, indexByElement) {
1610
- }
1611
- }
1612
- if (nextStableElement) {
1613
-- container.insertBefore(element, nextStableElement);
1614
-+ moveChildBefore(container, element, nextStableElement);
1615
- } else {
1616
-- container.appendChild(element);
1617
-+ moveChildBefore(container, element, null);
1618
- }
1619
- }
1620
- }
1621
-diff --git a/react.js b/react.js
1622
-index 914d2dafaafa001c9ab6791a0a0581659295e333..8c320b0dfb3ea60ef145274b37b1297b7dee26dc 100644
1623
---- a/react.js
1624
-+++ b/react.js
1625
-@@ -1908,6 +1908,10 @@ function updateScroll(ctx, newScroll, forceUpdate, options) {
1626
- state.scrollTime = currentTime;
1627
- const scrollDelta = Math.abs(newScroll - prevScroll);
1628
- const isUserScrollEvent = !!(options == null ? void 0 : options.fromNativeScrollEvent) && scrollDelta > 0.1 && !adjustChanged && scrollingTo === void 0 && !state.pendingNativeMVCPAdjust;
1629
-+ if (isUserScrollEvent) {
1630
-+ state.userScrollPrevTime = state.userScrollTime;
1631
-+ state.userScrollTime = currentTime;
1632
-+ }
1633
- const allowedEdge = isUserScrollEvent ? beginReachedEdgeUserScroll(ctx, newScroll - prevScroll) : void 0;
1634
- const didResolvePendingNativeMVCPAdjust = resolvePendingNativeMVCPAdjust(ctx, newScroll);
1635
- const scrollLength = state.scrollLength;
1636
-@@ -3257,6 +3261,7 @@ function syncMountedContainer(ctx, containerIndex, itemIndex, options) {
1637
- const itemKey = (_a3 = state.idCache[itemIndex]) != null ? _a3 : getId(state, itemIndex);
1638
- const updateLayout = (_b = options == null ? void 0 : options.updateLayout) != null ? _b : true;
1639
- let didChangePosition = false;
1640
-+ let didChangeIndex = false;
1641
- let didRefreshData = false;
1642
- if (updateLayout) {
1643
- const positionValue = positions[itemIndex];
1644
-@@ -3286,6 +3291,7 @@ function syncMountedContainer(ctx, containerIndex, itemIndex, options) {
1645
- const prevIndex = peek$(ctx, `containerItemIndex${containerIndex}`);
1646
- if (prevIndex !== itemIndex) {
1647
- set$(ctx, `containerItemIndex${containerIndex}`, itemIndex);
1648
-+ didChangeIndex = true;
1649
- }
1650
- const prevData = peek$(ctx, `containerItemData${containerIndex}`);
1651
- const updateData = () => {
1652
-@@ -3324,7 +3330,7 @@ function syncMountedContainer(ctx, containerIndex, itemIndex, options) {
1653
- }
1654
- }
1655
- }
1656
-- return { didChangePosition, didRefreshData };
1657
-+ return { didChangeIndex, didChangePosition, didRefreshData };
1658
- }
1659
-
1660
- // src/core/prepareColumnStartState.ts
1661
-@@ -3542,7 +3548,11 @@ function updateItemPositions(ctx, dataChanged, {
1662
- }
1663
- if (shouldOptimize && breakAt === void 0 && !scrollingTo && !dataChanged && currentRowTop > maxVisibleArea) {
1664
- const itemsPerRow = hasColumns ? numColumns : 1;
1665
-- breakAt = i + itemsPerRow + 10;
1666
-+ // alwaysRender rows stay mounted outside the visible window, so keep their
1667
-+ // positions current instead of leaving them where they were last laid out.
1668
-+ const pinnedIndices = state.props.alwaysRenderIndicesArr;
1669
-+ const lastPinnedIndex = pinnedIndices && pinnedIndices.length > 0 ? pinnedIndices[pinnedIndices.length - 1] : -1;
1670
-+ breakAt = Math.max(i + itemsPerRow + 10, lastPinnedIndex);
1671
- }
1672
- const id = (_e = idCache[i]) != null ? _e : getId(state, i);
1673
- let span = 1;
1674
-@@ -4243,6 +4253,7 @@ function calculateItemsInView(ctx, params = {}) {
1675
- }
1676
- let totalSize = getContentSize(ctx);
1677
- let changedContainerIds;
1678
-+ let didChangeContainerOrder = false;
1679
- const topPad = peek$(ctx, "stylePaddingTop") + peek$(ctx, "alignItemsAtEndPadding") + peek$(ctx, "headerSize");
1680
- const numColumns = peek$(ctx, "numColumns");
1681
- const speed = (_b = params.scrollVelocity) != null ? _b : getScrollVelocity(state);
1682
-@@ -4545,6 +4556,9 @@ function calculateItemsInView(ctx, params = {}) {
1683
- const containerIndex = allocation.containerIndex;
1684
- const id = (_o = idCache[i]) != null ? _o : getId(state, i);
1685
- const oldKey = peek$(ctx, `containerItemKey${containerIndex}`);
1686
-+ if (oldKey !== id || peek$(ctx, `containerItemIndex${containerIndex}`) !== i) {
1687
-+ didChangeContainerOrder = true;
1688
-+ }
1689
- if (oldKey && oldKey !== id) {
1690
- containerItemKeys.delete(oldKey);
1691
- }
1692
-@@ -4629,10 +4643,12 @@ function calculateItemsInView(ctx, params = {}) {
1693
- } else {
1694
- const itemIndex = indexByKey.get(itemKey);
1695
- if (itemIndex !== void 0) {
1696
-- didChangePositions = syncMountedContainer(ctx, i, itemIndex, {
1697
-+ const synced = syncMountedContainer(ctx, i, itemIndex, {
1698
- scrollAdjustPending,
1699
- updateLayout: true
1700
-- }).didChangePosition || didChangePositions;
1701
-+ });
1702
-+ didChangePositions = synced.didChangePosition || didChangePositions;
1703
-+ didChangeContainerOrder = synced.didChangeIndex || didChangeContainerOrder;
1704
- }
1705
- }
1706
- }
1707
-@@ -4642,6 +4658,9 @@ function calculateItemsInView(ctx, params = {}) {
1708
- if (didChangePositions) {
1709
- set$(ctx, "lastPositionUpdate", Date.now());
1710
- }
1711
-+ if (didChangeContainerOrder) {
1712
-+ set$(ctx, "containerOrderUpdate", (peek$(ctx, "containerOrderUpdate") || 0) + 1);
1713
-+ }
1714
- if (suppressInitialScrollSideEffects) {
1715
- evaluateBootstrapInitialScroll(ctx);
1716
- return;
1717
-@@ -4702,7 +4721,8 @@ function maybeUpdateAnchoredEndSpace(ctx) {
1718
- contentBelowAnchor = Math.max(0, contentBelowAnchor - ctx.scrollAxisGap);
1719
- contentBelowAnchor += (ctx.values.get("footerSize") || 0) + getStylePaddingEnd(state.props);
1720
- isReady = !hasUnknownTailSize;
1721
-- nextSize = hasUnknownTailSize ? previousSize || 0 : Math.max(0, state.scrollLength - contentBelowAnchor - anchorOffset);
1722
-+ const knownSizeBound = Math.max(0, state.scrollLength - contentBelowAnchor - anchorOffset);
1723
-+ nextSize = hasUnknownTailSize ? Math.min(previousSize || 0, knownSizeBound) : knownSizeBound;
1724
- } else if (anchorIndex >= 0) {
1725
- isReady = false;
1726
- }
1727
-@@ -4722,6 +4742,12 @@ function maybeUpdateAnchoredEndSpace(ctx) {
1728
- updateScroll(ctx, state.scroll, true, { markHasScrolled: false });
1729
- }
1730
- (_b = anchoredEndSpace == null ? void 0 : anchoredEndSpace.onReady) == null ? void 0 : _b.call(anchoredEndSpace, { anchorIndex: nextAnchorIndex, anchorKey: nextAnchorKey, size: nextSize });
1731
-+ } else if (!isReady && didSizeChange && nextSize < (previousSize || 0)) {
1732
-+ set$(ctx, "anchoredEndSpaceSize", nextSize);
1733
-+ (_a3 = anchoredEndSpace == null ? void 0 : anchoredEndSpace.onSizeChanged) == null ? void 0 : _a3.call(anchoredEndSpace, nextSize);
1734
-+ if (anchoredEndSpace == null ? void 0 : anchoredEndSpace.includeInEndInset) {
1735
-+ updateScroll(ctx, state.scroll, true, { markHasScrolled: false });
1736
-+ }
1737
- }
1738
- return nextSize;
1739
- }
1740
-@@ -4956,7 +4982,8 @@ function measureContainersInLayoutEffect(ctx, targetContainerIds = null) {
1741
- const itemKey = peek$(ctx, `containerItemKey${containerId}`);
1742
- const element = viewRef == null ? void 0 : viewRef.current;
1743
- if (itemKey !== void 0 && element) {
1744
-- const rect = element.getBoundingClientRect();
1745
-+ // Unlike getBoundingClientRect, offset sizes ignore ancestor transforms (e.g. a popup's zoom-in), like ResizeObserver.
1746
-+ const rect = { height: element.offsetHeight, width: element.offsetWidth };
1747
- setContainerLayoutBaseline(element, rect);
1748
- measurements.push({
1749
- containerId,
1750
-@@ -4978,12 +5005,26 @@ var ContainerLayoutCoordinator = typedMemo(function ContainerLayoutCoordinatorCo
1751
- }) {
1752
- const ctx = useStateContext();
1753
- const [containerLayoutEpoch] = useArr$(["containerLayoutEpoch"]);
1754
-+ const layoutPasses = React3__namespace.useRef(0);
1755
- React3__namespace.useLayoutEffect(() => {
1756
-- {
1757
-- const targetContainerIds = getContainerLayoutEffectScope(ctx);
1758
-- if (targetContainerIds !== void 0) {
1759
-- measureContainersInLayoutEffect(ctx, targetContainerIds);
1760
-- }
1761
-+ const targetContainerIds = getContainerLayoutEffectScope(ctx);
1762
-+ if (targetContainerIds === void 0) return;
1763
-+ if (layoutPasses.current === 0) {
1764
-+ queueMicrotask(() => { layoutPasses.current = 0; });
1765
-+ }
1766
-+ // Correcting large estimates can mount one row per commit. Bound the
1767
-+ // synchronous chain below React's nested-update limit, then keep measuring
1768
-+ // the latest pending rows on the next frame. Idle lists schedule no work.
1769
-+ if (layoutPasses.current++ < 8) {
1770
-+ measureContainersInLayoutEffect(ctx, targetContainerIds);
1771
-+ } else {
1772
-+ ctx.pendingContainerIds = targetContainerIds;
1773
-+ ctx.state.scheduledWork.frame(() => {
1774
-+ const pendingIds = getContainerLayoutEffectScope(ctx);
1775
-+ if (pendingIds !== void 0) {
1776
-+ measureContainersInLayoutEffect(ctx, pendingIds);
1777
-+ }
1778
-+ }, "containerLayout");
1779
- }
1780
- }, [ctx, containerLayoutEpoch]);
1781
- return children;
1782
-@@ -5651,6 +5692,18 @@ var ContainerSlot = typedMemo(function ContainerSlot2(props) {
1783
- });
1784
-
1785
- // src/utils/reordering.ts
1786
-+// Element.moveBefore keeps the moved subtree's state and does not count as an
1787
-+// insertion, so CSS @starting-style transitions and iframes inside a row do not
1788
-+// restart when the list reorders its containers. insertBefore is the fallback.
1789
-+function moveChildBefore(container, element, reference) {
1790
-+ if (typeof container.moveBefore === "function") {
1791
-+ container.moveBefore(element, reference);
1792
-+ } else if (reference) {
1793
-+ container.insertBefore(element, reference);
1794
-+ } else {
1795
-+ container.appendChild(element);
1796
-+ }
1797
-+}
1798
- function sortDOMElements(container, indexByElement) {
1799
- const elements = Array.from(container.children);
1800
- if (elements.length <= 1) return elements;
1801
-@@ -5690,9 +5743,9 @@ function sortDOMElements(container, indexByElement) {
1802
- }
1803
- }
1804
- if (nextStableElement) {
1805
-- container.insertBefore(element, nextStableElement);
1806
-+ moveChildBefore(container, element, nextStableElement);
1807
- } else {
1808
-- container.appendChild(element);
1809
-+ moveChildBefore(container, element, null);
1810
- }
1811
- }
1812
- }
1813
-@@ -5734,37 +5787,55 @@ function findLIS(arr) {
1814
- }
1815
-
1816
- // src/hooks/useDOMOrder.ts
1817
-+var DOM_ORDER_SETTLE_MS = 150;
1818
-+function isUserScrolling(state) {
1819
-+ const { userScrollPrevTime, userScrollTime } = state;
1820
-+ return userScrollTime !== void 0 && userScrollPrevTime !== void 0 && userScrollTime - userScrollPrevTime < DOM_ORDER_SETTLE_MS && Date.now() - userScrollTime < DOM_ORDER_SETTLE_MS;
1821
-+}
1822
- function useDOMOrder(ref) {
1823
- const ctx = useStateContext();
1824
-- const debounceRef = React3.useRef(void 0);
1825
-- React3.useEffect(() => {
1826
-- const unsubscribe = listen$(ctx, "lastPositionUpdate", () => {
1827
-- if (debounceRef.current !== void 0) {
1828
-- clearTimeout(debounceRef.current);
1829
-- }
1830
-- debounceRef.current = setTimeout(() => {
1831
-- const parent = ref.current;
1832
-- if (parent) {
1833
-- const indexByElement = /* @__PURE__ */ new Map();
1834
-- for (const [containerId, viewRef] of ctx.viewRefs) {
1835
-- const element = viewRef.current;
1836
-- const index = peek$(ctx, `containerItemIndex${containerId}`);
1837
-- if (element && index !== void 0) {
1838
-- indexByElement.set(element, index);
1839
-- }
1840
-- }
1841
-- sortDOMElements(parent, indexByElement);
1842
-+ const [containerOrderUpdate] = useArr$(["containerOrderUpdate"]);
1843
-+ const settleRef = React3.useRef(void 0);
1844
-+ React3.useLayoutEffect(() => {
1845
-+ const sort = () => {
1846
-+ settleRef.current = void 0;
1847
-+ const parent = ref.current;
1848
-+ if (!parent) {
1849
-+ return;
1850
-+ }
1851
-+ const indexByElement = /* @__PURE__ */ new Map();
1852
-+ for (const [containerId, viewRef] of ctx.viewRefs) {
1853
-+ const element = viewRef.current;
1854
-+ const index = peek$(ctx, `containerItemIndex${containerId}`);
1855
-+ if (element && index !== void 0) {
1856
-+ indexByElement.set(element, index);
1857
- }
1858
-- debounceRef.current = void 0;
1859
-- }, 500);
1860
-- });
1861
-- return () => {
1862
-- unsubscribe();
1863
-- if (debounceRef.current !== void 0) {
1864
-- clearTimeout(debounceRef.current);
1865
- }
1866
-+ sortDOMElements(parent, indexByElement);
1867
- };
1868
-- }, [ctx]);
1869
-+ if (settleRef.current !== void 0) {
1870
-+ clearTimeout(settleRef.current);
1871
-+ }
1872
-+ // Before paint: NVDA's browse mode keeps the first DOM order it reads. Each move
1873
-+ // lays its row out again, so during a continuous scroll, sort once it settles.
1874
-+ if (!isUserScrolling(ctx.state)) {
1875
-+ sort();
1876
-+ return;
1877
-+ }
1878
-+ const settle = () => {
1879
-+ if (isUserScrolling(ctx.state)) {
1880
-+ settleRef.current = setTimeout(settle, DOM_ORDER_SETTLE_MS);
1881
-+ } else {
1882
-+ sort();
1883
-+ }
1884
-+ };
1885
-+ settleRef.current = setTimeout(settle, DOM_ORDER_SETTLE_MS);
1886
-+ }, [ctx, containerOrderUpdate]);
1887
-+ React3.useEffect(() => () => {
1888
-+ if (settleRef.current !== void 0) {
1889
-+ clearTimeout(settleRef.current);
1890
-+ }
1891
-+ }, []);
1892
- }
1893
- function useFreshDataTransitionVisibility(readyToRender, transitionEpoch) {
1894
- const [completedTransitionEpoch, setCompletedTransitionEpoch] = React3.useState(transitionEpoch);
1895
-@@ -6446,8 +6517,8 @@ function ScrollAdjust() {
1896
- window.getComputedStyle(contentNode)[axis.paddingEndProp]
1897
- );
1898
- const temporaryPaddingEnd = `${(currentPaddingEnd || 0) + pad}px`;
1899
-- temporaryPaddingRef.current = { baseline: baselinePaddingEnd, value: temporaryPaddingEnd };
1900
- contentNode.style[axis.paddingEndProp] = temporaryPaddingEnd;
1901
-+ temporaryPaddingRef.current = { baseline: baselinePaddingEnd, value: contentNode.style[axis.paddingEndProp] };
1902
- void contentNode.offsetHeight;
1903
- scrollBy();
1904
- if (resetPaddingRafRef.current !== void 0) {
1905
-diff --git a/react.mjs b/react.mjs
1906
-index 95465f2ab89ce41a10553f58af83618f7310e83c..252a9d5b23e271c089d30c357a78dff754f1c899 100644
1907
---- a/react.mjs
1908
-+++ b/react.mjs
1909
-@@ -1887,6 +1887,10 @@ function updateScroll(ctx, newScroll, forceUpdate, options) {
1910
- state.scrollTime = currentTime;
1911
- const scrollDelta = Math.abs(newScroll - prevScroll);
1912
- const isUserScrollEvent = !!(options == null ? void 0 : options.fromNativeScrollEvent) && scrollDelta > 0.1 && !adjustChanged && scrollingTo === void 0 && !state.pendingNativeMVCPAdjust;
1913
-+ if (isUserScrollEvent) {
1914
-+ state.userScrollPrevTime = state.userScrollTime;
1915
-+ state.userScrollTime = currentTime;
1916
-+ }
1917
- const allowedEdge = isUserScrollEvent ? beginReachedEdgeUserScroll(ctx, newScroll - prevScroll) : void 0;
1918
- const didResolvePendingNativeMVCPAdjust = resolvePendingNativeMVCPAdjust(ctx, newScroll);
1919
- const scrollLength = state.scrollLength;
1920
-@@ -3236,6 +3240,7 @@ function syncMountedContainer(ctx, containerIndex, itemIndex, options) {
1921
- const itemKey = (_a3 = state.idCache[itemIndex]) != null ? _a3 : getId(state, itemIndex);
1922
- const updateLayout = (_b = options == null ? void 0 : options.updateLayout) != null ? _b : true;
1923
- let didChangePosition = false;
1924
-+ let didChangeIndex = false;
1925
- let didRefreshData = false;
1926
- if (updateLayout) {
1927
- const positionValue = positions[itemIndex];
1928
-@@ -3265,6 +3270,7 @@ function syncMountedContainer(ctx, containerIndex, itemIndex, options) {
1929
- const prevIndex = peek$(ctx, `containerItemIndex${containerIndex}`);
1930
- if (prevIndex !== itemIndex) {
1931
- set$(ctx, `containerItemIndex${containerIndex}`, itemIndex);
1932
-+ didChangeIndex = true;
1933
- }
1934
- const prevData = peek$(ctx, `containerItemData${containerIndex}`);
1935
- const updateData = () => {
1936
-@@ -3303,7 +3309,7 @@ function syncMountedContainer(ctx, containerIndex, itemIndex, options) {
1937
- }
1938
- }
1939
- }
1940
-- return { didChangePosition, didRefreshData };
1941
-+ return { didChangeIndex, didChangePosition, didRefreshData };
1942
- }
1943
-
1944
- // src/core/prepareColumnStartState.ts
1945
-@@ -3521,7 +3527,11 @@ function updateItemPositions(ctx, dataChanged, {
1946
- }
1947
- if (shouldOptimize && breakAt === void 0 && !scrollingTo && !dataChanged && currentRowTop > maxVisibleArea) {
1948
- const itemsPerRow = hasColumns ? numColumns : 1;
1949
-- breakAt = i + itemsPerRow + 10;
1950
-+ // alwaysRender rows stay mounted outside the visible window, so keep their
1951
-+ // positions current instead of leaving them where they were last laid out.
1952
-+ const pinnedIndices = state.props.alwaysRenderIndicesArr;
1953
-+ const lastPinnedIndex = pinnedIndices && pinnedIndices.length > 0 ? pinnedIndices[pinnedIndices.length - 1] : -1;
1954
-+ breakAt = Math.max(i + itemsPerRow + 10, lastPinnedIndex);
1955
- }
1956
- const id = (_e = idCache[i]) != null ? _e : getId(state, i);
1957
- let span = 1;
1958
-@@ -4222,6 +4232,7 @@ function calculateItemsInView(ctx, params = {}) {
1959
- }
1960
- let totalSize = getContentSize(ctx);
1961
- let changedContainerIds;
1962
-+ let didChangeContainerOrder = false;
1963
- const topPad = peek$(ctx, "stylePaddingTop") + peek$(ctx, "alignItemsAtEndPadding") + peek$(ctx, "headerSize");
1964
- const numColumns = peek$(ctx, "numColumns");
1965
- const speed = (_b = params.scrollVelocity) != null ? _b : getScrollVelocity(state);
1966
-@@ -4524,6 +4535,9 @@ function calculateItemsInView(ctx, params = {}) {
1967
- const containerIndex = allocation.containerIndex;
1968
- const id = (_o = idCache[i]) != null ? _o : getId(state, i);
1969
- const oldKey = peek$(ctx, `containerItemKey${containerIndex}`);
1970
-+ if (oldKey !== id || peek$(ctx, `containerItemIndex${containerIndex}`) !== i) {
1971
-+ didChangeContainerOrder = true;
1972
-+ }
1973
- if (oldKey && oldKey !== id) {
1974
- containerItemKeys.delete(oldKey);
1975
- }
1976
-@@ -4608,10 +4622,12 @@ function calculateItemsInView(ctx, params = {}) {
1977
- } else {
1978
- const itemIndex = indexByKey.get(itemKey);
1979
- if (itemIndex !== void 0) {
1980
-- didChangePositions = syncMountedContainer(ctx, i, itemIndex, {
1981
-+ const synced = syncMountedContainer(ctx, i, itemIndex, {
1982
- scrollAdjustPending,
1983
- updateLayout: true
1984
-- }).didChangePosition || didChangePositions;
1985
-+ });
1986
-+ didChangePositions = synced.didChangePosition || didChangePositions;
1987
-+ didChangeContainerOrder = synced.didChangeIndex || didChangeContainerOrder;
1988
- }
1989
- }
1990
- }
1991
-@@ -4621,6 +4637,9 @@ function calculateItemsInView(ctx, params = {}) {
1992
- if (didChangePositions) {
1993
- set$(ctx, "lastPositionUpdate", Date.now());
1994
- }
1995
-+ if (didChangeContainerOrder) {
1996
-+ set$(ctx, "containerOrderUpdate", (peek$(ctx, "containerOrderUpdate") || 0) + 1);
1997
-+ }
1998
- if (suppressInitialScrollSideEffects) {
1999
- evaluateBootstrapInitialScroll(ctx);
2000
- return;
2001
-@@ -4681,7 +4700,8 @@ function maybeUpdateAnchoredEndSpace(ctx) {
2002
- contentBelowAnchor = Math.max(0, contentBelowAnchor - ctx.scrollAxisGap);
2003
- contentBelowAnchor += (ctx.values.get("footerSize") || 0) + getStylePaddingEnd(state.props);
2004
- isReady = !hasUnknownTailSize;
2005
-- nextSize = hasUnknownTailSize ? previousSize || 0 : Math.max(0, state.scrollLength - contentBelowAnchor - anchorOffset);
2006
-+ const knownSizeBound = Math.max(0, state.scrollLength - contentBelowAnchor - anchorOffset);
2007
-+ nextSize = hasUnknownTailSize ? Math.min(previousSize || 0, knownSizeBound) : knownSizeBound;
2008
- } else if (anchorIndex >= 0) {
2009
- isReady = false;
2010
- }
2011
-@@ -4701,6 +4721,12 @@ function maybeUpdateAnchoredEndSpace(ctx) {
2012
- updateScroll(ctx, state.scroll, true, { markHasScrolled: false });
2013
- }
2014
- (_b = anchoredEndSpace == null ? void 0 : anchoredEndSpace.onReady) == null ? void 0 : _b.call(anchoredEndSpace, { anchorIndex: nextAnchorIndex, anchorKey: nextAnchorKey, size: nextSize });
2015
-+ } else if (!isReady && didSizeChange && nextSize < (previousSize || 0)) {
2016
-+ set$(ctx, "anchoredEndSpaceSize", nextSize);
2017
-+ (_a3 = anchoredEndSpace == null ? void 0 : anchoredEndSpace.onSizeChanged) == null ? void 0 : _a3.call(anchoredEndSpace, nextSize);
2018
-+ if (anchoredEndSpace == null ? void 0 : anchoredEndSpace.includeInEndInset) {
2019
-+ updateScroll(ctx, state.scroll, true, { markHasScrolled: false });
2020
-+ }
2021
- }
2022
- return nextSize;
2023
- }
2024
-@@ -4935,7 +4961,8 @@ function measureContainersInLayoutEffect(ctx, targetContainerIds = null) {
2025
- const itemKey = peek$(ctx, `containerItemKey${containerId}`);
2026
- const element = viewRef == null ? void 0 : viewRef.current;
2027
- if (itemKey !== void 0 && element) {
2028
-- const rect = element.getBoundingClientRect();
2029
-+ // Unlike getBoundingClientRect, offset sizes ignore ancestor transforms (e.g. a popup's zoom-in), like ResizeObserver.
2030
-+ const rect = { height: element.offsetHeight, width: element.offsetWidth };
2031
- setContainerLayoutBaseline(element, rect);
2032
- measurements.push({
2033
- containerId,
2034
-@@ -4957,12 +4984,26 @@ var ContainerLayoutCoordinator = typedMemo(function ContainerLayoutCoordinatorCo
2035
- }) {
2036
- const ctx = useStateContext();
2037
- const [containerLayoutEpoch] = useArr$(["containerLayoutEpoch"]);
2038
-+ const layoutPasses = React3.useRef(0);
2039
- React3.useLayoutEffect(() => {
2040
-- {
2041
-- const targetContainerIds = getContainerLayoutEffectScope(ctx);
2042
-- if (targetContainerIds !== void 0) {
2043
-- measureContainersInLayoutEffect(ctx, targetContainerIds);
2044
-- }
2045
-+ const targetContainerIds = getContainerLayoutEffectScope(ctx);
2046
-+ if (targetContainerIds === void 0) return;
2047
-+ if (layoutPasses.current === 0) {
2048
-+ queueMicrotask(() => { layoutPasses.current = 0; });
2049
-+ }
2050
-+ // Correcting large estimates can mount one row per commit. Bound the
2051
-+ // synchronous chain below React's nested-update limit, then keep measuring
2052
-+ // the latest pending rows on the next frame. Idle lists schedule no work.
2053
-+ if (layoutPasses.current++ < 8) {
2054
-+ measureContainersInLayoutEffect(ctx, targetContainerIds);
2055
-+ } else {
2056
-+ ctx.pendingContainerIds = targetContainerIds;
2057
-+ ctx.state.scheduledWork.frame(() => {
2058
-+ const pendingIds = getContainerLayoutEffectScope(ctx);
2059
-+ if (pendingIds !== void 0) {
2060
-+ measureContainersInLayoutEffect(ctx, pendingIds);
2061
-+ }
2062
-+ }, "containerLayout");
2063
- }
2064
- }, [ctx, containerLayoutEpoch]);
2065
- return children;
2066
-@@ -5630,6 +5671,18 @@ var ContainerSlot = typedMemo(function ContainerSlot2(props) {
2067
- });
2068
-
2069
- // src/utils/reordering.ts
2070
-+// Element.moveBefore keeps the moved subtree's state and does not count as an
2071
-+// insertion, so CSS @starting-style transitions and iframes inside a row do not
2072
-+// restart when the list reorders its containers. insertBefore is the fallback.
2073
-+function moveChildBefore(container, element, reference) {
2074
-+ if (typeof container.moveBefore === "function") {
2075
-+ container.moveBefore(element, reference);
2076
-+ } else if (reference) {
2077
-+ container.insertBefore(element, reference);
2078
-+ } else {
2079
-+ container.appendChild(element);
2080
-+ }
2081
-+}
2082
- function sortDOMElements(container, indexByElement) {
2083
- const elements = Array.from(container.children);
2084
- if (elements.length <= 1) return elements;
2085
-@@ -5669,9 +5722,9 @@ function sortDOMElements(container, indexByElement) {
2086
- }
2087
- }
2088
- if (nextStableElement) {
2089
-- container.insertBefore(element, nextStableElement);
2090
-+ moveChildBefore(container, element, nextStableElement);
2091
- } else {
2092
-- container.appendChild(element);
2093
-+ moveChildBefore(container, element, null);
2094
- }
2095
- }
2096
- }
2097
-@@ -5713,37 +5766,55 @@ function findLIS(arr) {
2098
- }
2099
-
2100
- // src/hooks/useDOMOrder.ts
2101
-+var DOM_ORDER_SETTLE_MS = 150;
2102
-+function isUserScrolling(state) {
2103
-+ const { userScrollPrevTime, userScrollTime } = state;
2104
-+ return userScrollTime !== void 0 && userScrollPrevTime !== void 0 && userScrollTime - userScrollPrevTime < DOM_ORDER_SETTLE_MS && Date.now() - userScrollTime < DOM_ORDER_SETTLE_MS;
2105
-+}
2106
- function useDOMOrder(ref) {
2107
- const ctx = useStateContext();
2108
-- const debounceRef = useRef(void 0);
2109
-- useEffect(() => {
2110
-- const unsubscribe = listen$(ctx, "lastPositionUpdate", () => {
2111
-- if (debounceRef.current !== void 0) {
2112
-- clearTimeout(debounceRef.current);
2113
-- }
2114
-- debounceRef.current = setTimeout(() => {
2115
-- const parent = ref.current;
2116
-- if (parent) {
2117
-- const indexByElement = /* @__PURE__ */ new Map();
2118
-- for (const [containerId, viewRef] of ctx.viewRefs) {
2119
-- const element = viewRef.current;
2120
-- const index = peek$(ctx, `containerItemIndex${containerId}`);
2121
-- if (element && index !== void 0) {
2122
-- indexByElement.set(element, index);
2123
-- }
2124
-- }
2125
-- sortDOMElements(parent, indexByElement);
2126
-+ const [containerOrderUpdate] = useArr$(["containerOrderUpdate"]);
2127
-+ const settleRef = useRef(void 0);
2128
-+ useLayoutEffect(() => {
2129
-+ const sort = () => {
2130
-+ settleRef.current = void 0;
2131
-+ const parent = ref.current;
2132
-+ if (!parent) {
2133
-+ return;
2134
-+ }
2135
-+ const indexByElement = /* @__PURE__ */ new Map();
2136
-+ for (const [containerId, viewRef] of ctx.viewRefs) {
2137
-+ const element = viewRef.current;
2138
-+ const index = peek$(ctx, `containerItemIndex${containerId}`);
2139
-+ if (element && index !== void 0) {
2140
-+ indexByElement.set(element, index);
2141
- }
2142
-- debounceRef.current = void 0;
2143
-- }, 500);
2144
-- });
2145
-- return () => {
2146
-- unsubscribe();
2147
-- if (debounceRef.current !== void 0) {
2148
-- clearTimeout(debounceRef.current);
2149
- }
2150
-+ sortDOMElements(parent, indexByElement);
2151
- };
2152
-- }, [ctx]);
2153
-+ if (settleRef.current !== void 0) {
2154
-+ clearTimeout(settleRef.current);
2155
-+ }
2156
-+ // Before paint: NVDA's browse mode keeps the first DOM order it reads. Each move
2157
-+ // lays its row out again, so during a continuous scroll, sort once it settles.
2158
-+ if (!isUserScrolling(ctx.state)) {
2159
-+ sort();
2160
-+ return;
2161
-+ }
2162
-+ const settle = () => {
2163
-+ if (isUserScrolling(ctx.state)) {
2164
-+ settleRef.current = setTimeout(settle, DOM_ORDER_SETTLE_MS);
2165
-+ } else {
2166
-+ sort();
2167
-+ }
2168
-+ };
2169
-+ settleRef.current = setTimeout(settle, DOM_ORDER_SETTLE_MS);
2170
-+ }, [ctx, containerOrderUpdate]);
2171
-+ useEffect(() => () => {
2172
-+ if (settleRef.current !== void 0) {
2173
-+ clearTimeout(settleRef.current);
2174
-+ }
2175
-+ }, []);
2176
- }
2177
- function useFreshDataTransitionVisibility(readyToRender, transitionEpoch) {
2178
- const [completedTransitionEpoch, setCompletedTransitionEpoch] = useState(transitionEpoch);
2179
-@@ -6425,8 +6496,8 @@ function ScrollAdjust() {
2180
- window.getComputedStyle(contentNode)[axis.paddingEndProp]
2181
- );
2182
- const temporaryPaddingEnd = `${(currentPaddingEnd || 0) + pad}px`;
2183
-- temporaryPaddingRef.current = { baseline: baselinePaddingEnd, value: temporaryPaddingEnd };
2184
- contentNode.style[axis.paddingEndProp] = temporaryPaddingEnd;
2185
-+ temporaryPaddingRef.current = { baseline: baselinePaddingEnd, value: contentNode.style[axis.paddingEndProp] };
2186
- void contentNode.offsetHeight;
2187
- scrollBy();
2188
- if (resetPaddingRafRef.current !== void 0) {
2189
-diff --git a/reanimated.d.ts b/reanimated.d.ts
2190
-index e5043320700b12f34f4c0babbc341f85ca8135c1..e8cbd461325a2e2e9ffd61de26a85ae4d108555c 100644
2191
---- a/reanimated.d.ts
2192
-+++ b/reanimated.d.ts
2193
-@@ -285,6 +285,11 @@ interface LegendListSpecificProps<ItemT, TItemType extends string | undefined> {
2194
- * - true enables both behaviors; false disables both.
2195
- */
2196
- maintainVisibleContentPosition?: boolean | MaintainVisibleContentPositionConfig<ItemT>;
2197
-+ /**
2198
-+ * T3 patch: the scroll offset a change in item or list size should leave, read in the same pass
2199
-+ * that repositions the items so the adjustment commits with them. `undefined` keeps the default.
2200
-+ */
2201
-+ sizeChangeAnchor?: () => number | undefined;
2202
- /**
2203
- * Keeps an item visually anchored to the start by adding trailing space when the content below it underflows.
2204
- */
2205
-@@ -294,6 +299,12 @@ interface LegendListSpecificProps<ItemT, TItemType extends string | undefined> {
2206
- * The adjustment is also rendered as real content padding so the browser scroll range includes it.
2207
- */
2208
- contentInsetEndAdjustment?: number;
2209
-+ /**
2210
-+ * Width/height of a leading content inset applied natively outside the list's knowledge
2211
-+ * (e.g. iOS contentInsetAdjustmentBehavior="automatic" under a transparent header).
2212
-+ * Programmatic scrolls clamp to -adjustment instead of 0 so content can rest below the header.
2213
-+ */
2214
-+ contentInsetStartAdjustment?: number;
2215
- /**
2216
- * Number of columns to render items in.
2217
- * @default 1
2218
-diff --git a/reanimated.js b/reanimated.js
2219
-index f1265fad74189591b5aae86cf2e3a31f9c0fdb02..fc03be2190c046f743ffde45ed189ee7868d0cec 100644
2220
---- a/reanimated.js
2221
-+++ b/reanimated.js
2222
-@@ -115,8 +115,10 @@ var ReanimatedPositionView = typedMemo(function ReanimatedPositionViewComponent(
2223
- const { id, horizontal, style, refView, children, recycleItems, layoutTransition, ...rest } = props;
2224
- const [positionValue = POSITION_OUT_OF_VIEW] = useArr$([`containerPosition${id}`]);
2225
- const prevItemKeyRef = React__namespace.useRef(void 0);
2226
-+ const previousPositionRef = React__namespace.useRef(positionValue);
2227
-+ const lastContentSizeEpochRef = React__namespace.useRef(ctx.state.contentSizeAnimationEpoch || 0);
2228
- let shouldSkipTransitionForRecycleReuse = false;
2229
-- if (recycleItems && layoutTransition) {
2230
-+ if (layoutTransition) {
2231
- const itemKeySignal = `containerItemKey${id}`;
2232
- const itemKey = peek$(ctx, itemKeySignal);
2233
- shouldSkipTransitionForRecycleReuse = itemKey !== void 0 && prevItemKeyRef.current !== void 0 && prevItemKeyRef.current !== itemKey;
2234
-@@ -130,10 +132,29 @@ var ReanimatedPositionView = typedMemo(function ReanimatedPositionViewComponent(
2235
- () => [style, horizontal ? { left: positionValue } : { top: positionValue }],
2236
- [horizontal, positionValue, style]
2237
- );
2238
-+ // Two kinds of repositions must not animate: (1) MVCP size adjustments,
2239
-+ // which are compensated by an equal contentOffset shift so the row should
2240
-+ // not visibly move — animating turns the invisible correction into a
2241
-+ // lurch-and-settle; (2) any reposition while the user is actively
2242
-+ // scrolling, where rows shifting under the finger reads as jank. The
2243
-+ // transition exists to smooth at-rest shifts (streaming text, work-log
2244
-+ // folds), so gate it to at-rest moments.
2245
-+ const now = Date.now();
2246
-+ const contentSizeEpoch = ctx.state.contentSizeAnimationEpoch || 0;
2247
-+ const didPositionChange = positionValue !== previousPositionRef.current;
2248
-+ const isRawSizeReposition = didPositionChange && contentSizeEpoch !== lastContentSizeEpochRef.current && ctx.state.contentSizeAnimationEligible && !!layoutTransition && typeof layoutTransition.getAnimationAndConfig === "function";
2249
-+ React__namespace.useLayoutEffect(() => {
2250
-+ if (didPositionChange) {
2251
-+ previousPositionRef.current = positionValue;
2252
-+ lastContentSizeEpochRef.current = contentSizeEpoch;
2253
-+ }
2254
-+ }, [contentSizeEpoch, didPositionChange, positionValue]);
2255
-+ const isRecentNativeReposition = now - (ctx.state.lastNativeScrollTime || 0) < 300;
2256
-+ const shouldSkipLayoutTransition = now - (ctx.state.lastMVCPAdjustTime || 0) < 300 || ctx.state.isUserDragging || ctx.state.isMomentumScrolling || isRecentNativeReposition && !isRawSizeReposition;
2257
- return /* @__PURE__ */ React__namespace.createElement(
2258
- Reanimated__default.default.View,
2259
- {
2260
-- layout: shouldSkipTransitionForRecycleReuse ? void 0 : layoutTransition,
2261
-+ layout: shouldSkipTransitionForRecycleReuse || shouldSkipLayoutTransition ? void 0 : layoutTransition,
2262
- ref: refView,
2263
- style: viewStyle,
2264
- ...rest
2265
-@@ -141,6 +162,95 @@ var ReanimatedPositionView = typedMemo(function ReanimatedPositionViewComponent(
2266
- children
2267
- );
2268
- });
2269
-+var ReanimatedSizeView = typedMemo(function ReanimatedSizeViewComponent(props) {
2270
-+ const ctx = useStateContext();
2271
-+ const { horizontal, signalName, style, children, ...rest } = props;
2272
-+ const [logicalSize = 0] = useArr$(signalName === "totalSize" ? [signalName] : [signalName, "totalSize"]);
2273
-+ const baseSize = Reanimated.useSharedValue(logicalSize);
2274
-+ const animatedDelta = Reanimated.useSharedValue(0);
2275
-+ const previousLogicalSizeRef = React__namespace.useRef(logicalSize);
2276
-+ const previousEpochRef = React__namespace.useRef(ctx.state.contentSizeAnimationEpoch || 0);
2277
-+ const animationRunRef = React__namespace.useRef(0);
2278
-+ const isAnimatingRef = React__namespace.useRef(false);
2279
-+ const transition = props.layoutTransition;
2280
-+ const canAnimate = !!transition && typeof transition.getAnimationAndConfig === "function";
2281
-+ const renderEpoch = ctx.state.contentSizeAnimationEpoch || 0;
2282
-+ // Keep the animated size attached after transitions finish. Reanimated
2283
-+ // retains removed animated props, so switching to a static size leaves
2284
-+ // native scroll bounds stuck while logical measurements keep changing.
2285
-+ const animatedStyle = Reanimated.useAnimatedStyle(() => {
2286
-+ const size = Math.max(0, baseSize.value + animatedDelta.value);
2287
-+ return horizontal ? { width: size } : { height: size };
2288
-+ }, [horizontal]);
2289
-+ const completeAnimation = React__namespace.useCallback((run, epoch) => {
2290
-+ if (animationRunRef.current !== run) {
2291
-+ return;
2292
-+ }
2293
-+ isAnimatingRef.current = false;
2294
-+ const state = ctx.state;
2295
-+ if (state.contentSizeAnimationActiveEpoch !== epoch) {
2296
-+ return;
2297
-+ }
2298
-+ state.contentSizeAnimationActiveSignals.delete(signalName);
2299
-+ if (state.contentSizeAnimationActiveSignals.size === 0) {
2300
-+ state.contentSizeAnimationActiveEpoch = void 0;
2301
-+ state.contentSizeAnimationEligible = false;
2302
-+ }
2303
-+ }, [ctx.state, signalName]);
2304
-+ React__namespace.useLayoutEffect(() => {
2305
-+ const state = ctx.state;
2306
-+ const epoch = state.contentSizeAnimationEpoch || 0;
2307
-+ const previousLogicalSize = previousLogicalSizeRef.current;
2308
-+ const delta = logicalSize - previousLogicalSize;
2309
-+ const isNewEpoch = epoch !== previousEpochRef.current;
2310
-+ // Retarget measurements received mid-animation, even in the same epoch.
2311
-+ // Updating only the base keeps the old delta and can shrink scroll bounds.
2312
-+ const shouldAnimate = canAnimate && (isAnimatingRef.current || isNewEpoch && state.contentSizeAnimationEligible);
2313
-+ previousLogicalSizeRef.current = logicalSize;
2314
-+ previousEpochRef.current = epoch;
2315
-+ if (!delta) {
2316
-+ return;
2317
-+ }
2318
-+ if (!shouldAnimate) {
2319
-+ baseSize.value = logicalSize;
2320
-+ if (signalName === "totalSize" && isNewEpoch && state.contentSizeAnimationEligible && !canAnimate) {
2321
-+ state.contentSizeAnimationEligible = false;
2322
-+ }
2323
-+ return;
2324
-+ }
2325
-+ const [animation, config] = transition.getAnimationAndConfig();
2326
-+ const delayFunction = typeof transition.getDelayFunction === "function" ? transition.getDelayFunction() : (_, value) => value;
2327
-+ const delay = typeof transition.getDelay === "function" ? transition.getDelay() : 0;
2328
-+ if (typeof animation !== "function" || typeof delayFunction !== "function") {
2329
-+ baseSize.value = logicalSize;
2330
-+ if (signalName === "totalSize") {
2331
-+ state.contentSizeAnimationEligible = false;
2332
-+ }
2333
-+ return;
2334
-+ }
2335
-+ if (state.contentSizeAnimationActiveEpoch !== epoch) {
2336
-+ state.contentSizeAnimationActiveEpoch = epoch;
2337
-+ state.contentSizeAnimationActiveSignals = /* @__PURE__ */ new Set();
2338
-+ }
2339
-+ state.contentSizeAnimationActiveSignals.add(signalName);
2340
-+ const wasAnimating = isAnimatingRef.current;
2341
-+ isAnimatingRef.current = true;
2342
-+ const run = ++animationRunRef.current;
2343
-+ Reanimated.runOnUI((absoluteSize, previousSize, continuesAnimation, animationRun, animationEpoch) => {
2344
-+ "worklet";
2345
-+ const currentVisualSize = continuesAnimation ? baseSize.value + animatedDelta.value : previousSize;
2346
-+ baseSize.value = absoluteSize;
2347
-+ animatedDelta.value = currentVisualSize - absoluteSize;
2348
-+ animatedDelta.value = delayFunction(delay, animation(0, config, (finished) => {
2349
-+ "worklet";
2350
-+ if (finished) {
2351
-+ Reanimated.runOnJS(completeAnimation)(animationRun, animationEpoch);
2352
-+ }
2353
-+ }));
2354
-+ })(logicalSize, previousLogicalSize, wasAnimating, run, epoch);
2355
-+ }, [baseSize, animatedDelta, canAnimate, completeAnimation, ctx.state, logicalSize, renderEpoch, signalName, transition]);
2356
-+ return /* @__PURE__ */ React__namespace.createElement(Reanimated__default.default.View, { ...rest, style: [style, animatedStyle] }, children);
2357
-+});
2358
- function setSharedValueValue(sharedValue, value) {
2359
- if (!sharedValue) {
2360
- return;
2361
-@@ -245,10 +355,19 @@ var LegendListForwardedRef = typedMemo(
2362
- );
2363
- };
2364
- }, [hasItemLayoutAnimation, recycleItems]);
2365
-+ const sizeComponentInternal = React__namespace.useMemo(() => {
2366
-+ if (!hasItemLayoutAnimation) {
2367
-+ return void 0;
2368
-+ }
2369
-+ return function SizeComponent(sizeProps) {
2370
-+ return /* @__PURE__ */ React__namespace.createElement(ReanimatedSizeView, { ...sizeProps, layoutTransition: itemLayoutAnimationRef.current });
2371
-+ };
2372
-+ }, [hasItemLayoutAnimation]);
2373
- const legendListProps = {
2374
- ...rest,
2375
- positionComponentInternal,
2376
- recycleItems,
2377
-+ sizeComponentInternal,
2378
- ...{
2379
- renderScrollComponent: renderReanimatedScrollComponent,
2380
- ...IsNewArchitecture ? { stickyPositionComponentInternal } : {}
2381
-diff --git a/reanimated.mjs b/reanimated.mjs
2382
-index 29a00d5dc084fd408a0e0a0a4d64e856d0ed1525..6ab929250c8924e2d9919ee09a4f774238fbb90a 100644
2383
---- a/reanimated.mjs
2384
-+++ b/reanimated.mjs
2385
-@@ -1,7 +1,7 @@
2386
- import * as React from 'react';
2387
- import { useCallback } from 'react';
2388
- import { View } from 'react-native';
2389
--import Reanimated, { useAnimatedRef, useAnimatedStyle, useSharedValue, useScrollViewOffset } from 'react-native-reanimated';
2390
-+import Reanimated, { runOnJS, runOnUI, useAnimatedRef, useAnimatedStyle, useSharedValue, useScrollViewOffset } from 'react-native-reanimated';
2391
- import { internal, LegendList } from '@legendapp/list/react-native';
2392
-
2393
- // src/integrations/reanimated.tsx
2394
-@@ -91,8 +91,10 @@ var ReanimatedPositionView = typedMemo(function ReanimatedPositionViewComponent(
2395
- const { id, horizontal, style, refView, children, recycleItems, layoutTransition, ...rest } = props;
2396
- const [positionValue = POSITION_OUT_OF_VIEW] = useArr$([`containerPosition${id}`]);
2397
- const prevItemKeyRef = React.useRef(void 0);
2398
-+ const previousPositionRef = React.useRef(positionValue);
2399
-+ const lastContentSizeEpochRef = React.useRef(ctx.state.contentSizeAnimationEpoch || 0);
2400
- let shouldSkipTransitionForRecycleReuse = false;
2401
-- if (recycleItems && layoutTransition) {
2402
-+ if (layoutTransition) {
2403
- const itemKeySignal = `containerItemKey${id}`;
2404
- const itemKey = peek$(ctx, itemKeySignal);
2405
- shouldSkipTransitionForRecycleReuse = itemKey !== void 0 && prevItemKeyRef.current !== void 0 && prevItemKeyRef.current !== itemKey;
2406
-@@ -106,10 +108,29 @@ var ReanimatedPositionView = typedMemo(function ReanimatedPositionViewComponent(
2407
- () => [style, horizontal ? { left: positionValue } : { top: positionValue }],
2408
- [horizontal, positionValue, style]
2409
- );
2410
-+ // Two kinds of repositions must not animate: (1) MVCP size adjustments,
2411
-+ // which are compensated by an equal contentOffset shift so the row should
2412
-+ // not visibly move — animating turns the invisible correction into a
2413
-+ // lurch-and-settle; (2) any reposition while the user is actively
2414
-+ // scrolling, where rows shifting under the finger reads as jank. The
2415
-+ // transition exists to smooth at-rest shifts (streaming text, work-log
2416
-+ // folds), so gate it to at-rest moments.
2417
-+ const now = Date.now();
2418
-+ const contentSizeEpoch = ctx.state.contentSizeAnimationEpoch || 0;
2419
-+ const didPositionChange = positionValue !== previousPositionRef.current;
2420
-+ const isRawSizeReposition = didPositionChange && contentSizeEpoch !== lastContentSizeEpochRef.current && ctx.state.contentSizeAnimationEligible && !!layoutTransition && typeof layoutTransition.getAnimationAndConfig === "function";
2421
-+ React.useLayoutEffect(() => {
2422
-+ if (didPositionChange) {
2423
-+ previousPositionRef.current = positionValue;
2424
-+ lastContentSizeEpochRef.current = contentSizeEpoch;
2425
-+ }
2426
-+ }, [contentSizeEpoch, didPositionChange, positionValue]);
2427
-+ const isRecentNativeReposition = now - (ctx.state.lastNativeScrollTime || 0) < 300;
2428
-+ const shouldSkipLayoutTransition = now - (ctx.state.lastMVCPAdjustTime || 0) < 300 || ctx.state.isUserDragging || ctx.state.isMomentumScrolling || isRecentNativeReposition && !isRawSizeReposition;
2429
- return /* @__PURE__ */ React.createElement(
2430
- Reanimated.View,
2431
- {
2432
-- layout: shouldSkipTransitionForRecycleReuse ? void 0 : layoutTransition,
2433
-+ layout: shouldSkipTransitionForRecycleReuse || shouldSkipLayoutTransition ? void 0 : layoutTransition,
2434
- ref: refView,
2435
- style: viewStyle,
2436
- ...rest
2437
-@@ -117,6 +138,95 @@ var ReanimatedPositionView = typedMemo(function ReanimatedPositionViewComponent(
2438
- children
2439
- );
2440
- });
2441
-+var ReanimatedSizeView = typedMemo(function ReanimatedSizeViewComponent(props) {
2442
-+ const ctx = useStateContext();
2443
-+ const { horizontal, signalName, style, children, ...rest } = props;
2444
-+ const [logicalSize = 0] = useArr$(signalName === "totalSize" ? [signalName] : [signalName, "totalSize"]);
2445
-+ const baseSize = useSharedValue(logicalSize);
2446
-+ const animatedDelta = useSharedValue(0);
2447
-+ const previousLogicalSizeRef = React.useRef(logicalSize);
2448
-+ const previousEpochRef = React.useRef(ctx.state.contentSizeAnimationEpoch || 0);
2449
-+ const animationRunRef = React.useRef(0);
2450
-+ const isAnimatingRef = React.useRef(false);
2451
-+ const transition = props.layoutTransition;
2452
-+ const canAnimate = !!transition && typeof transition.getAnimationAndConfig === "function";
2453
-+ const renderEpoch = ctx.state.contentSizeAnimationEpoch || 0;
2454
-+ // Keep the animated size attached after transitions finish. Reanimated
2455
-+ // retains removed animated props, so switching to a static size leaves
2456
-+ // native scroll bounds stuck while logical measurements keep changing.
2457
-+ const animatedStyle = useAnimatedStyle(() => {
2458
-+ const size = Math.max(0, baseSize.value + animatedDelta.value);
2459
-+ return horizontal ? { width: size } : { height: size };
2460
-+ }, [horizontal]);
2461
-+ const completeAnimation = useCallback((run, epoch) => {
2462
-+ if (animationRunRef.current !== run) {
2463
-+ return;
2464
-+ }
2465
-+ isAnimatingRef.current = false;
2466
-+ const state = ctx.state;
2467
-+ if (state.contentSizeAnimationActiveEpoch !== epoch) {
2468
-+ return;
2469
-+ }
2470
-+ state.contentSizeAnimationActiveSignals.delete(signalName);
2471
-+ if (state.contentSizeAnimationActiveSignals.size === 0) {
2472
-+ state.contentSizeAnimationActiveEpoch = void 0;
2473
-+ state.contentSizeAnimationEligible = false;
2474
-+ }
2475
-+ }, [ctx.state, signalName]);
2476
-+ React.useLayoutEffect(() => {
2477
-+ const state = ctx.state;
2478
-+ const epoch = state.contentSizeAnimationEpoch || 0;
2479
-+ const previousLogicalSize = previousLogicalSizeRef.current;
2480
-+ const delta = logicalSize - previousLogicalSize;
2481
-+ const isNewEpoch = epoch !== previousEpochRef.current;
2482
-+ // Retarget measurements received mid-animation, even in the same epoch.
2483
-+ // Updating only the base keeps the old delta and can shrink scroll bounds.
2484
-+ const shouldAnimate = canAnimate && (isAnimatingRef.current || isNewEpoch && state.contentSizeAnimationEligible);
2485
-+ previousLogicalSizeRef.current = logicalSize;
2486
-+ previousEpochRef.current = epoch;
2487
-+ if (!delta) {
2488
-+ return;
2489
-+ }
2490
-+ if (!shouldAnimate) {
2491
-+ baseSize.value = logicalSize;
2492
-+ if (signalName === "totalSize" && isNewEpoch && state.contentSizeAnimationEligible && !canAnimate) {
2493
-+ state.contentSizeAnimationEligible = false;
2494
-+ }
2495
-+ return;
2496
-+ }
2497
-+ const [animation, config] = transition.getAnimationAndConfig();
2498
-+ const delayFunction = typeof transition.getDelayFunction === "function" ? transition.getDelayFunction() : (_, value) => value;
2499
-+ const delay = typeof transition.getDelay === "function" ? transition.getDelay() : 0;
2500
-+ if (typeof animation !== "function" || typeof delayFunction !== "function") {
2501
-+ baseSize.value = logicalSize;
2502
-+ if (signalName === "totalSize") {
2503
-+ state.contentSizeAnimationEligible = false;
2504
-+ }
2505
-+ return;
2506
-+ }
2507
-+ if (state.contentSizeAnimationActiveEpoch !== epoch) {
2508
-+ state.contentSizeAnimationActiveEpoch = epoch;
2509
-+ state.contentSizeAnimationActiveSignals = /* @__PURE__ */ new Set();
2510
-+ }
2511
-+ state.contentSizeAnimationActiveSignals.add(signalName);
2512
-+ const wasAnimating = isAnimatingRef.current;
2513
-+ isAnimatingRef.current = true;
2514
-+ const run = ++animationRunRef.current;
2515
-+ runOnUI((absoluteSize, previousSize, continuesAnimation, animationRun, animationEpoch) => {
2516
-+ "worklet";
2517
-+ const currentVisualSize = continuesAnimation ? baseSize.value + animatedDelta.value : previousSize;
2518
-+ baseSize.value = absoluteSize;
2519
-+ animatedDelta.value = currentVisualSize - absoluteSize;
2520
-+ animatedDelta.value = delayFunction(delay, animation(0, config, (finished) => {
2521
-+ "worklet";
2522
-+ if (finished) {
2523
-+ runOnJS(completeAnimation)(animationRun, animationEpoch);
2524
-+ }
2525
-+ }));
2526
-+ })(logicalSize, previousLogicalSize, wasAnimating, run, epoch);
2527
-+ }, [baseSize, animatedDelta, canAnimate, completeAnimation, ctx.state, logicalSize, renderEpoch, signalName, transition]);
2528
-+ return /* @__PURE__ */ React.createElement(Reanimated.View, { ...rest, style: [style, animatedStyle] }, children);
2529
-+});
2530
- function setSharedValueValue(sharedValue, value) {
2531
- if (!sharedValue) {
2532
- return;
2533
-@@ -221,10 +331,19 @@ var LegendListForwardedRef = typedMemo(
2534
- );
2535
- };
2536
- }, [hasItemLayoutAnimation, recycleItems]);
2537
-+ const sizeComponentInternal = React.useMemo(() => {
2538
-+ if (!hasItemLayoutAnimation) {
2539
-+ return void 0;
2540
-+ }
2541
-+ return function SizeComponent(sizeProps) {
2542
-+ return /* @__PURE__ */ React.createElement(ReanimatedSizeView, { ...sizeProps, layoutTransition: itemLayoutAnimationRef.current });
2543
-+ };
2544
-+ }, [hasItemLayoutAnimation]);
2545
- const legendListProps = {
2546
- ...rest,
2547
- positionComponentInternal,
2548
- recycleItems,
2549
-+ sizeComponentInternal,
2550
- ...{
2551
- renderScrollComponent: renderReanimatedScrollComponent,
2552
- ...IsNewArchitecture ? { stickyPositionComponentInternal } : {}
pnpm-lock.yaml
+9
-10
@@ -280,7 +280,7 @@ overrides:
280
expo-sharing: 58.0.19
281
expo-widgets: 58.0.20
282
'@ff-labs/fff-node': 0.11.0
283
- '@legendapp/list': 3.3.5
283
+ '@legendapp/list': 3.7.2
284
'@pierre/diffs': 1.6.1
285
'@react-native-ai/apple': 0.12.0
286
'@react-native-menu/menu': 2.0.0
@@ -365,7 +365,6 @@ patchedDependencies:
365
'@expo/metro-config@58.0.14': 90fa980e8b6480631fb2fbb04559834e3c612db40c550cd828f11be297d8d760
366
'@expo/ui@58.0.20': 64559cb60723e19a8a72256d4c78d1315d937a7af3b32d19860ea596f88736ce
367
'@ff-labs/fff-node@0.11.0': cc71fcec015f4d39bc96ae2e2bf6b0ca678124c722c66a7841efce9d34b5983c
368
- '@legendapp/list@3.3.5': 6cbdacd8c380d9a5afb9f73d4198dc2cc44be6ef28a955b1183c781469307896
368
'@muse-code/sdk@1.4.6': 7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101
369
'@pierre/diffs@1.6.1': 322ac5f5db8b5715189c010802047f8235c3a45d8ed5ca0ba60fac266e2eba34
370
'@react-native-ai/apple@0.12.0': 2d09870c2848d185cb05b53ed823a46e12dba519324d8dd8e584e28731990f9d
@@ -548,8 +547,8 @@ importers:
547
specifier: 58.0.20
548
version: 58.0.20(patch_hash=64559cb60723e19a8a72256d4c78d1315d937a7af3b32d19860ea596f88736ce)(@babel/core@7.29.7(supports-color@8.1.1))(expo@58.0.14)(react-dom@19.3.0(react@19.3.0))(react-native-worklets@0.13.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)(supports-color@8.1.1))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)
549
'@legendapp/list':
551
- specifier: 3.3.5
552
- version: 3.3.5(patch_hash=6cbdacd8c380d9a5afb9f73d4198dc2cc44be6ef28a955b1183c781469307896)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)
550
+ specifier: 3.7.2
551
+ version: 3.7.2(react-dom@19.3.0(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)
552
'@material/material-color-utilities':
553
specifier: 0.3.0
554
version: 0.3.0
@@ -1066,8 +1065,8 @@ importers:
1065
specifier: ^5.3.0
1066
version: 5.3.0
1067
'@legendapp/list':
1069
- specifier: 3.3.5
1070
- version: 3.3.5(patch_hash=6cbdacd8c380d9a5afb9f73d4198dc2cc44be6ef28a955b1183c781469307896)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)
1068
+ specifier: 3.7.2
1069
+ version: 3.7.2(react-dom@19.3.0(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)
1070
'@noble/hashes':
1071
specifier: 'catalog:'
1072
version: 1.8.0
@@ -4889,8 +4888,8 @@ packages:
4888
cpu: [x64]
4889
os: [win32]
4890
4892
- '@legendapp/list@3.3.5':
4893
- resolution: {integrity: sha512-XTsLYtpg41SVb5uLBYA+YcDSA3w0tgoPq/W8ZggQ2tx+3lrC/rf+ehTP9KYHea9oFaZIuePAgzACs5/auVMJlQ==}
4891
+ '@legendapp/list@3.7.2':
4892
+ resolution: {integrity: sha512-StFy5qjOHHuxHKjenwLq500S/z+zuF43hj8iqXhX9EMtzeOagPfsnMRWphvBG4CYBvMTX6VzgLjN5BzzwY1jDA==}
4893
peerDependencies:
4894
react: '*'
4895
react-dom: '*'
@@ -14941,10 +14940,10 @@ snapshots:
14940
'@koromix/koffi-win32-x64@3.3.6':
14941
optional: true
14942
14944
- '@legendapp/list@3.3.5(patch_hash=6cbdacd8c380d9a5afb9f73d4198dc2cc44be6ef28a955b1183c781469307896)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)':
14943
+ '@legendapp/list@3.7.2(react-dom@19.3.0(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)':
14944
dependencies:
14945
react: 19.3.0
14947
- use-sync-external-store: 1.6.0(react@19.3.0)
14946
+ use-sync-external-store: 1.7.0(react@19.3.0)
14947
optionalDependencies:
14948
react-dom: 19.3.0(react@19.3.0)
14949
react-native: 0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.0(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6)
pnpm-workspace.yaml
+3
-3
@@ -54,7 +54,7 @@ catalog:
54
"@effect/sql-sqlite-do": 4.1.2
55
"@effect/vitest": 4.1.2
56
"@electron-webauthn/macos": 1.3.1
57
- "@legendapp/list": 3.3.5
57
+ "@legendapp/list": 3.7.2
58
"@noble/curves": 1.9.1
59
"@noble/hashes": 1.8.0
60
"@pierre/diffs": 1.6.1
@@ -113,7 +113,7 @@ overrides:
113
expo-sharing: 58.0.19
114
expo-widgets: 58.0.20
115
"@ff-labs/fff-node": 0.11.0
116
- "@legendapp/list": 3.3.5
116
+ "@legendapp/list": 3.7.2
117
"@pierre/diffs": 1.6.1
118
"@react-native-ai/apple": 0.12.0
119
"@react-native-menu/menu": 2.0.0
@@ -237,7 +237,6 @@ patchedDependencies:
237
expo-sharing@58.0.19: patches/expo-sharing@58.0.19.patch
238
expo-widgets@58.0.20: patches/expo-widgets@58.0.20.patch
239
"@ff-labs/fff-node@0.11.0": patches/@ff-labs__fff-node@0.11.0.patch
240
- "@legendapp/list@3.3.5": patches/@legendapp__list@3.3.5.patch
240
# Exports the dependency-light subpaths mobile and the web diff parser import, and keeps
241
# measured wrapped-row heights above an edit (fileEditorVirtualization.test.ts).
242
"@pierre/diffs@1.6.1": patches/@pierre%2Fdiffs@1.6.1.patch
@@ -301,6 +300,7 @@ publicHoistPattern:
300
- "@cursor/sdk-*"
301
302
minimumReleaseAgeExclude:
303
+ - "@legendapp/list@3.7.2"
304
- "@effect/tsgo-darwin-arm64@0.67.1"
305
- "@effect/tsgo-darwin-x64@0.67.1"
306
- "@effect/tsgo-linux-arm64@0.67.1"
scripts/legend-list-initial-reveal.test.ts
deleted
-149
@@ -1,149 +0,0 @@
1
-// @effect-diagnostics nodeBuiltinImport:off - reads the installed native JS bundle for synchronous VM tests.
2
-import * as NodeFS from "node:fs";
3
-import * as NodeVM from "node:vm";
4
-import { describe, expect, it, vi } from "vite-plus/test";
5
-
6
-function createList(bundle: string) {
7
- const source = NodeFS.readFileSync(
8
- new URL(`../apps/mobile/node_modules/@legendapp/list/${bundle}`, import.meta.url),
9
- "utf8",
10
- );
11
- const renderState = source.slice(
12
- source.indexOf("function setInitialRenderState("),
13
- source.indexOf("// src/core/finishInitialScroll.ts"),
14
- );
15
- const watchdog = source.slice(
16
- source.indexOf("var INSET_END_SETTLE_WATCHDOG_FRAMES"),
17
- source.indexOf("function dispatchInitialScroll("),
18
- );
19
- const frames: Array<() => void> = [];
20
- const values = new Map<string, unknown>();
21
- const scrollTo = vi.fn();
22
- const onLoad = vi.fn();
23
- const state = {
24
- props: { data: ["message"], onLoad, drawDistance: 500 },
25
- initialScroll: { index: 0, viewPosition: 1 },
26
- loadStartTime: 0,
27
- didContainersLayout: true,
28
- didFinishInitialScroll: true,
29
- didLoad: false,
30
- didUserDrag: false,
31
- scrollLength: 800,
32
- scroll: 400,
33
- lastNativeScroll: 200 as number | undefined,
34
- scrollingTo: undefined as { offset: number } | undefined,
35
- maintainingScrollAtEnd: false,
36
- refScroller: { current: { scrollTo } },
37
- };
38
- const ctx = { state };
39
- let contentSize = 1200;
40
- let inset = 100;
41
- const api = NodeVM.runInNewContext(
42
- `${renderState}\n${watchdog}\n({ start: startInsetEndSettleWatchdog, complete: setInitialRenderState })`,
43
- {
44
- requestAnimationFrame: (callback: () => void) => frames.push(callback),
45
- getContentSize: () => contentSize,
46
- getContentInsetStartAdjustment: () => inset,
47
- peek$: (_ctx: unknown, key: string) => values.get(key),
48
- set$: (_ctx: unknown, key: string, value: unknown) => values.set(key, value),
49
- setAdaptiveRender: vi.fn(),
50
- scheduleFullDrawDistancePrewarm: vi.fn(),
51
- INITIAL_DRAW_DISTANCE: 250,
52
- },
53
- ) as {
54
- start: (context: typeof ctx) => void;
55
- complete: (context: typeof ctx, flags: Record<string, boolean>) => void;
56
- };
57
- return {
58
- state,
59
- scrollTo,
60
- onLoad,
61
- start: () => api.start(ctx),
62
- complete: () => api.complete(ctx, {}),
63
- ready: () => values.get("readyToRender") === true,
64
- resize: (size: number) => {
65
- contentSize = size;
66
- },
67
- setInset: (value: number) => {
68
- inset = value;
69
- },
70
- advance(count: number) {
71
- for (let index = 0; index < count; index++) {
72
- const batch = frames.splice(0);
73
- for (const frame of batch) frame();
74
- }
75
- },
76
- };
77
-}
78
-
79
-describe.each(["react-native.js", "react-native.mjs"])(
80
- "initial inset end reveal (%s)",
81
- (bundle) => {
82
- it("waits for the native offset instead of the optimistic scroll target", () => {
83
- const list = createList(bundle);
84
- list.start();
85
- list.advance(8);
86
- expect(list.ready()).toBe(false);
87
- expect(list.scrollTo).toHaveBeenCalledWith({ animated: false, x: 0, y: 400 });
88
- list.state.lastNativeScroll = 400;
89
- list.advance(7);
90
- expect(list.ready()).toBe(true);
91
- expect(list.onLoad).toHaveBeenCalledTimes(1);
92
- });
93
-
94
- it("does not count an in-flight scroll as stability", () => {
95
- const list = createList(bundle);
96
- list.state.lastNativeScroll = 400;
97
- list.state.scrollingTo = { offset: 400 };
98
- list.start();
99
- list.advance(8);
100
- expect(list.ready()).toBe(false);
101
- list.state.scrollingTo = undefined;
102
- list.state.maintainingScrollAtEnd = true;
103
- list.advance(8);
104
- expect(list.ready()).toBe(false);
105
- list.state.maintainingScrollAtEnd = false;
106
- list.advance(7);
107
- expect(list.ready()).toBe(true);
108
- });
109
-
110
- it("waits for a stable end target even when native scrolling follows each measurement", () => {
111
- const list = createList(bundle);
112
- list.start();
113
- for (let index = 0; index < 10; index++) {
114
- list.resize(1200 + index * 10);
115
- list.state.lastNativeScroll = 400 + index * 10;
116
- list.advance(1);
117
- }
118
- expect(list.ready()).toBe(false);
119
- list.advance(7);
120
- expect(list.ready()).toBe(true);
121
- });
122
-
123
- it("keeps the reveal bounded when native events never arrive", () => {
124
- const list = createList(bundle);
125
- list.state.lastNativeScroll = undefined;
126
- list.start();
127
- list.advance(8);
128
- expect(list.ready()).toBe(false);
129
- expect(list.scrollTo).not.toHaveBeenCalled();
130
- list.advance(32);
131
- expect(list.ready()).toBe(true);
132
- });
133
-
134
- it("releases control on drag and never starts another initial hold", () => {
135
- const list = createList(bundle);
136
- list.start();
137
- list.state.didUserDrag = true;
138
- list.advance(1);
139
- expect(list.ready()).toBe(true);
140
- expect(list.scrollTo).not.toHaveBeenCalled();
141
- list.complete();
142
- list.start();
143
- list.advance(20);
144
- expect(list.state.didUserDrag).toBe(true);
145
- expect(list.scrollTo).not.toHaveBeenCalled();
146
- expect(list.onLoad).toHaveBeenCalledTimes(1);
147
- });
148
- },
149
-);