Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

source-file-scroll.ts

66 lines2.0 KB

1interface 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​
7const RETRY_DELAY_MS = 100;
8const 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.
12export 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 };