Skip to content

Commit 1ecb1a0

Browse files
fix(mobile): avoid crashes opening wrapped source links (#25156)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 572cf74 commit 1ecb1a0

3 files changed

Lines changed: 232 additions & 7 deletions

File tree

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

Lines changed: 10 additions & 7 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 { useEffect, useRef, useState } from "react";
5+
import { useLayoutEffect, useRef, useState } from "react";
66
import {
77
FlatList,
88
Platform,
@@ -37,6 +37,7 @@ import { SourceText } from "@t3tools/mobile-source-text";
3737

3838
import { boundedSelectableSourceTokens, prepareSourceFileDocument } from "./source-file-document";
3939
import { sourceHighlightAtom } from "./sourceHighlightingState";
40+
import { createSourceLineScroll } from "./source-file-scroll";
4041

4142
interface SourceFileSurfaceProps {
4243
readonly contents: string;
@@ -241,21 +242,21 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
241242
const { normalizedContents, lines, status, targetIndex, tokens } = useSourceFileModel(props);
242243
const selectableTokens = props.selectable ? boundedSelectableSourceTokens(tokens) : null;
243244
const listRef = useRef<FlatList<string>>(null);
245+
const [lineScroll] = useState(createSourceLineScroll);
244246
const { isPullRefreshing, handlePullToRefresh } = useSourceFileRefresh(props.onRefresh);
245247
const refreshControl = props.onRefresh ? (
246248
<RefreshControl refreshing={isPullRefreshing} onRefresh={() => void handlePullToRefresh()} />
247249
) : undefined;
248250

249-
useEffect(() => {
251+
// Layout effect so a pending jump is cancelled in the commit that swaps the file.
252+
useLayoutEffect(() => {
250253
if (targetIndex === null) {
251254
return;
252255
}
253-
const frame = requestAnimationFrame(() => {
254-
listRef.current?.scrollToIndex({ index: targetIndex, animated: false, viewPosition: 0.3 });
255-
});
256-
return () => cancelAnimationFrame(frame);
256+
lineScroll.scrollToLine(listRef.current, targetIndex);
257+
return lineScroll.cancel;
257258
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Opening another file at the same line index scrolls the new file to it.
258-
}, [props.path, targetIndex]);
259+
}, [lineScroll, props.path, targetIndex]);
259260

260261
const renderLine = ({ item, index }: { item: string; index: number }) => (
261262
<HighlightedSourceLine
@@ -346,6 +347,8 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {
346347
paddingTop: 8,
347348
}}
348349
renderItem={renderLine}
350+
onScrollToIndexFailed={lineScroll.onScrollToIndexFailed}
351+
onScrollBeginDrag={lineScroll.cancel}
349352
/>
350353
);
351354

Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
import { expect, it, vi } from "vite-plus/test";
2+
3+
import { createSourceLineScroll } from "./source-file-scroll";
4+
5+
const ROW_HEIGHT = 24;
6+
7+
// Mirrors VirtualizedList.scrollToIndex without getItemLayout: indices past the highest
8+
// measured cell fail, and unmeasured indices below it scroll to an averaged estimate.
9+
function setup({
10+
lineCount = 1_203,
11+
measuredThrough = 79,
12+
rowHeight = (_index: number): number => ROW_HEIGHT,
13+
} = {}) {
14+
vi.useFakeTimers();
15+
vi.stubGlobal("requestAnimationFrame", (callback: () => void) => setTimeout(callback, 16));
16+
vi.stubGlobal("cancelAnimationFrame", (frame: ReturnType<typeof setTimeout>) =>
17+
clearTimeout(frame),
18+
);
19+
const measured = new Set<number>();
20+
const state = {
21+
lineCount,
22+
offset: 0,
23+
measure(from: number, to: number) {
24+
for (let index = from; index <= to; index += 1) measured.add(index);
25+
},
26+
};
27+
state.measure(0, measuredThrough);
28+
const offsetOf = (index: number) => {
29+
let offset = 0;
30+
for (let row = 0; row < index; row += 1) offset += rowHeight(row);
31+
return offset;
32+
};
33+
const averageItemLength = () => {
34+
let total = 0;
35+
for (const index of measured) total += rowHeight(index);
36+
return total / measured.size;
37+
};
38+
const scrollToIndex = vi.fn((params: { index: number }) => {
39+
if (params.index < 0 || params.index >= state.lineCount) {
40+
throw new Error(`scrollToIndex out of range: requested index ${params.index}`);
41+
}
42+
const highestMeasuredFrameIndex = Math.max(...measured);
43+
if (params.index > highestMeasuredFrameIndex) {
44+
scroll.onScrollToIndexFailed({
45+
index: params.index,
46+
averageItemLength: averageItemLength(),
47+
highestMeasuredFrameIndex,
48+
});
49+
return;
50+
}
51+
state.offset = measured.has(params.index)
52+
? offsetOf(params.index)
53+
: averageItemLength() * params.index;
54+
});
55+
const scrollToOffset = vi.fn((params: { offset: number }) => {
56+
state.offset = params.offset;
57+
});
58+
const list = {
59+
get props() {
60+
return { data: { length: state.lineCount } };
61+
},
62+
scrollToIndex,
63+
scrollToOffset,
64+
};
65+
const scroll = createSourceLineScroll();
66+
return {
67+
scroll,
68+
list,
69+
state,
70+
offsetOf,
71+
scrollToIndex,
72+
scrollToOffset,
73+
[Symbol.dispose]: () => {
74+
vi.unstubAllGlobals();
75+
vi.useRealTimers();
76+
},
77+
};
78+
}
79+
80+
it("lands on an already measured line", () => {
81+
using t = setup();
82+
83+
t.scroll.scrollToLine(t.list, 40);
84+
vi.runAllTimers();
85+
86+
expect(t.state.offset).toBe(t.offsetOf(40));
87+
expect(t.scrollToOffset).not.toHaveBeenCalled();
88+
expect(vi.getTimerCount()).toBe(0);
89+
});
90+
91+
it("jumps near an unmeasured wrapped line, then lands on it once rows measure", () => {
92+
using t = setup({ rowHeight: (index) => (index >= 80 ? ROW_HEIGHT * 3 : ROW_HEIGHT) });
93+
94+
t.scroll.scrollToLine(t.list, 899);
95+
expect(() => vi.advanceTimersToNextTimer()).not.toThrow();
96+
expect(t.state.offset).toBeGreaterThan(0);
97+
98+
// The render batch after the estimated jump measures rows past the target first, so
99+
// the next scrollToIndex is accepted against an averaged estimate.
100+
t.state.measure(900, 979);
101+
vi.advanceTimersToNextTimer();
102+
expect(t.state.offset).not.toBe(t.offsetOf(899));
103+
104+
t.state.measure(820, 899);
105+
vi.runAllTimers();
106+
107+
expect(t.state.offset).toBe(t.offsetOf(899));
108+
expect(vi.getTimerCount()).toBe(0);
109+
});
110+
111+
it("stops retrying when the target never measures", () => {
112+
using t = setup({ rowHeight: (index) => (index === 899 ? ROW_HEIGHT * 400 : ROW_HEIGHT) });
113+
114+
t.scroll.scrollToLine(t.list, 899);
115+
expect(() => vi.runAllTimers()).not.toThrow();
116+
117+
expect(t.scrollToIndex.mock.calls.length).toBeLessThanOrEqual(10);
118+
expect(vi.getTimerCount()).toBe(0);
119+
});
120+
121+
it("ignores a line outside the document", () => {
122+
using t = setup({ lineCount: 12 });
123+
124+
expect(() => t.scroll.scrollToLine(t.list, 899)).not.toThrow();
125+
vi.runAllTimers();
126+
expect(t.scrollToIndex).not.toHaveBeenCalled();
127+
expect(t.scrollToOffset).not.toHaveBeenCalled();
128+
});
129+
130+
it("drops a pending jump when the document shrinks or the jump is cancelled", () => {
131+
using t = setup();
132+
133+
t.scroll.scrollToLine(t.list, 899);
134+
vi.advanceTimersToNextTimer();
135+
t.state.lineCount = 12;
136+
expect(() => vi.runAllTimers()).not.toThrow();
137+
138+
t.state.lineCount = 1_203;
139+
t.scroll.scrollToLine(t.list, 899);
140+
vi.advanceTimersToNextTimer();
141+
const calls = t.scrollToIndex.mock.calls.length;
142+
t.scroll.cancel();
143+
t.state.measure(80, 999);
144+
vi.runAllTimers();
145+
expect(t.scrollToIndex).toHaveBeenCalledTimes(calls);
146+
});
147+
148+
it("a drag before the first frame cancels the jump", () => {
149+
using t = setup();
150+
151+
t.scroll.scrollToLine(t.list, 40);
152+
t.scroll.cancel();
153+
vi.runAllTimers();
154+
155+
expect(t.scrollToIndex).not.toHaveBeenCalled();
156+
});
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
interface SourceLineList {
2+
readonly props: { readonly data?: { readonly length: number } | null };
3+
scrollToIndex(params: { index: number; animated: boolean; viewPosition: number }): void;
4+
scrollToOffset(params: { offset: number; animated: boolean }): void;
5+
}
6+
7+
const RETRY_DELAY_MS = 100;
8+
const MAX_RETRIES = 5;
9+
10+
// Wrapped rows have no getItemLayout. VirtualizedList fails a jump past its highest measured
11+
// row and silently estimates an unmeasured row below it, so re-aim until the budget runs out.
12+
export function createSourceLineScroll() {
13+
let list: SourceLineList | null = null;
14+
let target: number | null = null;
15+
let retries = 0;
16+
let cancelPending: (() => void) | null = null;
17+
18+
const cancel = () => {
19+
cancelPending?.();
20+
cancelPending = null;
21+
target = null;
22+
};
23+
24+
const retry = () => {
25+
if (retries >= MAX_RETRIES) {
26+
target = null;
27+
return;
28+
}
29+
retries += 1;
30+
const timer = setTimeout(attempt, RETRY_DELAY_MS);
31+
cancelPending = () => clearTimeout(timer);
32+
};
33+
34+
const attempt = () => {
35+
cancelPending = null;
36+
if (target === null || !list || target >= (list.props.data?.length ?? 0)) {
37+
target = null;
38+
return;
39+
}
40+
list.scrollToIndex({ index: target, animated: false, viewPosition: 0.3 });
41+
// A failed jump has already scheduled its retry.
42+
if (cancelPending === null) retry();
43+
};
44+
45+
return {
46+
scrollToLine(nextList: SourceLineList | null, index: number) {
47+
cancel();
48+
list = nextList;
49+
if (!Number.isInteger(index) || index < 0) return;
50+
target = index;
51+
retries = 0;
52+
const frame = requestAnimationFrame(attempt);
53+
cancelPending = () => cancelAnimationFrame(frame);
54+
},
55+
onScrollToIndexFailed(info: {
56+
index: number;
57+
averageItemLength: number;
58+
highestMeasuredFrameIndex: number;
59+
}) {
60+
if (info.index !== target || !list) return;
61+
list.scrollToOffset({ offset: info.averageItemLength * info.index, animated: false });
62+
retry();
63+
},
64+
cancel,
65+
};
66+
}

0 commit comments

Comments
 (0)