Skip to content

Commit bc3067d

Browse files
committed
fix(mobile): finish source jumps and cancel stale recovery
1 parent 44b2e83 commit bc3067d

3 files changed

Lines changed: 157 additions & 8 deletions

File tree

‎apps/mobile/src/features/files/SourceFileSurface.tsx‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { settlePromise } from "@t3tools/client-runtime/state/runtime";
22
import { useAtomValue } from "@effect/atom-react";
33
import { AsyncResult } from "effect/reactivity";
44
import type { ComponentType } from "react";
5-
import { useCallback, useEffect, useRef, useState } from "react";
5+
import { useCallback, useLayoutEffect, useRef, useState } from "react";
66
import {
77
FlatList,
88
Platform,
@@ -244,12 +244,17 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
244244
const listRef = useRef<FlatList<string>>(null);
245245
const [lineScroll] = useState(createSourceLineScroll);
246246
const retryLineScroll = useCallback(() => lineScroll.retry(listRef.current), [lineScroll]);
247+
const handleViewableLines = useCallback(
248+
({ viewableItems }: { viewableItems: ReadonlyArray<{ readonly index?: number | null }> }) =>
249+
lineScroll.onViewableItemsChanged(listRef.current, viewableItems),
250+
[lineScroll],
251+
);
247252
const { isPullRefreshing, handlePullToRefresh } = useSourceFileRefresh(props.onRefresh);
248253
const refreshControl = props.onRefresh ? (
249254
<RefreshControl refreshing={isPullRefreshing} onRefresh={() => void handlePullToRefresh()} />
250255
) : undefined;
251256

252-
useEffect(() => {
257+
useLayoutEffect(() => {
253258
if (targetIndex === null) {
254259
return;
255260
}
@@ -349,8 +354,15 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
349354
}}
350355
renderItem={renderLine}
351356
onScrollToIndexFailed={(info) => lineScroll.onScrollToIndexFailed(listRef.current, info)}
352-
onViewableItemsChanged={retryLineScroll}
357+
onViewableItemsChanged={handleViewableLines}
353358
onContentSizeChange={retryLineScroll}
359+
onScroll={(event) =>
360+
lineScroll.onScroll(
361+
event.nativeEvent.contentOffset.y,
362+
event.nativeEvent.layoutMeasurement.height,
363+
)
364+
}
365+
onScrollBeginDrag={lineScroll.cancel}
354366
/>
355367
);
356368

‎apps/mobile/src/features/files/source-file-scroll.test.ts‎

Lines changed: 88 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,14 @@ function setup() {
77
let visibleIndex = 0;
88
let requestedOffset: number | null = null;
99
let mounted = true;
10+
let lineCount = 1_203;
11+
let unmeasuredIndex: number | null = null;
1012
const list = {
13+
get props() {
14+
return { data: { length: lineCount } };
15+
},
1116
scrollToIndex({ index }: { index: number }) {
17+
if (index >= lineCount) throw new Error("scrollToIndex out of range");
1218
if (index > highestMeasuredIndex) {
1319
// VirtualizedList requires this recovery path for unmeasured variable-height rows.
1420
if (!scroll.onScrollToIndexFailed) {
@@ -17,7 +23,7 @@ function setup() {
1723
scroll.onScrollToIndexFailed(list, { index, averageItemLength: 24 });
1824
return;
1925
}
20-
visibleIndex = index;
26+
visibleIndex = index === unmeasuredIndex ? 100 : index;
2127
},
2228
scrollToOffset({ offset }: { offset: number }) {
2329
requestedOffset = offset;
@@ -36,9 +42,27 @@ function setup() {
3642
return requestedOffset;
3743
},
3844
measureThrough(index: number) {
39-
highestMeasuredIndex = index;
45+
highestMeasuredIndex = Math.max(highestMeasuredIndex, index);
46+
if (unmeasuredIndex !== null && index >= unmeasuredIndex) unmeasuredIndex = null;
4047
scroll.retry(mounted ? list : null);
4148
},
49+
acceptApproximationFor(index: number) {
50+
highestMeasuredIndex = index + 100;
51+
unmeasuredIndex = index;
52+
},
53+
replaceDocument(count: number) {
54+
lineCount = count;
55+
},
56+
reportViewable(offset: number, height: number, indices: readonly number[]) {
57+
visibleIndex = indices[0] ?? visibleIndex;
58+
highestMeasuredIndex = Math.max(highestMeasuredIndex, ...indices);
59+
if (unmeasuredIndex !== null && indices.includes(unmeasuredIndex)) unmeasuredIndex = null;
60+
scroll.onScroll(offset, height);
61+
scroll.onViewableItemsChanged(
62+
mounted ? list : null,
63+
indices.map((index) => ({ index })),
64+
);
65+
},
4266
unmount() {
4367
mounted = false;
4468
scroll.cancel();
@@ -86,3 +110,65 @@ it("does not scroll after the source list unmounts", () => {
86110
expect(() => state.measureThrough(950)).not.toThrow();
87111
expect(state.visibleIndex).toBe(0);
88112
});
113+
114+
it("keeps an accepted approximate jump pending until the target is reached", () => {
115+
const state = setup();
116+
state.acceptApproximationFor(899);
117+
118+
state.scroll.scrollToLine(899);
119+
expect(state.visibleIndex).toBe(100);
120+
state.measureThrough(950);
121+
expect(state.visibleIndex).toBe(899);
122+
});
123+
124+
it("rejects a stale jump when replacement data arrives before cleanup", () => {
125+
const state = setup();
126+
127+
state.scroll.scrollToLine(899);
128+
state.replaceDocument(12);
129+
expect(() => state.measureThrough(950)).not.toThrow();
130+
expect(state.visibleIndex).toBe(0);
131+
});
132+
133+
it.each([
134+
{ first: 100, offset: 2_400, direction: "before" },
135+
{ first: 1_000, offset: 24_000, direction: "after" },
136+
])("corrects an approximate jump that lands $direction the target", ({ first, offset }) => {
137+
const state = setup();
138+
state.acceptApproximationFor(899);
139+
state.scroll.scrollToLine(899);
140+
141+
state.reportViewable(
142+
offset,
143+
240,
144+
Array.from({ length: 10 }, (_, index) => first + index),
145+
);
146+
if (first < 899) expect(state.requestedOffset).toBeGreaterThan(offset);
147+
else expect(state.requestedOffset).toBeLessThan(offset);
148+
149+
state.measureThrough(950);
150+
expect(state.visibleIndex).toBe(899);
151+
});
152+
153+
it("stops recovering after the target becomes visible", () => {
154+
const state = setup();
155+
state.acceptApproximationFor(899);
156+
state.scroll.scrollToLine(899);
157+
158+
state.reportViewable(21_576, 240, [899, 900, 901]);
159+
expect(state.visibleIndex).toBe(899);
160+
161+
state.reportViewable(480, 240, [20, 21, 22]);
162+
state.measureThrough(1_100);
163+
expect(state.visibleIndex).toBe(20);
164+
});
165+
166+
it("finishes an already visible target without waiting for another viewability event", () => {
167+
const state = setup();
168+
state.reportViewable(0, 240, [0, 1, 2, 3, 4]);
169+
170+
state.scroll.scrollToLine(4);
171+
state.reportViewable(480, 240, [20, 21, 22]);
172+
state.measureThrough(100);
173+
expect(state.visibleIndex).toBe(20);
174+
});
Lines changed: 54 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,29 @@
11
interface SourceLineList {
2+
readonly props: { readonly data?: { readonly length: number } | null };
23
scrollToIndex(options: { index: number; animated: boolean; viewPosition: number }): void;
34
scrollToOffset(options: { offset: number; animated: boolean }): void;
45
}
56

67
export function createSourceLineScroll() {
78
let pendingIndex: number | null = null;
9+
let visibleItems: ReadonlyArray<{ readonly index?: number | null }> = [];
10+
let scrollOffset = 0;
11+
let viewportHeight = 0;
12+
let averageItemLength = 0;
13+
const target = (list: SourceLineList | null) => {
14+
if (
15+
pendingIndex !== null &&
16+
(pendingIndex < 0 || pendingIndex >= (list?.props.data?.length ?? 0))
17+
) {
18+
pendingIndex = null;
19+
}
20+
return pendingIndex;
21+
};
822
const scrollToLine = (list: SourceLineList | null, index: number) => {
9-
pendingIndex = null;
23+
pendingIndex = index;
24+
if (target(list) === null) return;
1025
list?.scrollToIndex({ index, animated: false, viewPosition: 0.3 });
26+
if (visibleItems.some((item) => item.index === index)) pendingIndex = null;
1127
};
1228

1329
return {
@@ -16,7 +32,8 @@ export function createSourceLineScroll() {
1632
list: SourceLineList | null,
1733
info: { index: number; averageItemLength: number },
1834
) {
19-
pendingIndex = info.index;
35+
if (target(list) !== info.index) return;
36+
averageItemLength = info.averageItemLength;
2037
// Wrapped rows have no fixed layout. Move their render window near the line,
2138
// then finish the jump when native measurements update the list.
2239
list?.scrollToOffset({
@@ -25,10 +42,44 @@ export function createSourceLineScroll() {
2542
});
2643
},
2744
retry(list: SourceLineList | null) {
28-
if (pendingIndex !== null) scrollToLine(list, pendingIndex);
45+
const index = target(list);
46+
if (index !== null) scrollToLine(list, index);
47+
},
48+
onScroll(offset: number, height: number) {
49+
scrollOffset = offset;
50+
viewportHeight = height;
51+
},
52+
onViewableItemsChanged(
53+
list: SourceLineList | null,
54+
items: ReadonlyArray<{ readonly index?: number | null }>,
55+
) {
56+
visibleItems = items;
57+
const index = target(list);
58+
if (index === null) return;
59+
if (items.some((item) => item.index === index)) {
60+
pendingIndex = null;
61+
list?.scrollToIndex({ index, animated: false, viewPosition: 0.3 });
62+
return;
63+
}
64+
const first = items[0]?.index;
65+
const last = items.at(-1)?.index;
66+
if (first == null || last == null || last < first) return;
67+
// An accepted scroll can still use an estimate for an unmeasured row.
68+
// Correct from the actual viewport rather than repeating that same estimate.
69+
const rowHeight =
70+
viewportHeight > 0 ? viewportHeight / (last - first + 1) : averageItemLength;
71+
if (rowHeight <= 0) return;
72+
list?.scrollToOffset({
73+
offset: Math.max(0, scrollOffset + (index - first) * rowHeight),
74+
animated: false,
75+
});
2976
},
3077
cancel() {
3178
pendingIndex = null;
79+
visibleItems = [];
80+
scrollOffset = 0;
81+
viewportHeight = 0;
82+
averageItemLength = 0;
3283
},
3384
};
3485
}

0 commit comments

Comments
 (0)