TypeScript
fix(mobile): avoid crashes opening wrapped source links (#25156)
Julius Marminge1ecb1a0f9346
diff --git a/apps/mobile/src/features/files/SourceFileSurface.tsx b/apps/mobile/src/features/files/SourceFileSurface.tsxindex 3799554ae32..bf691fa4bef 100644--- a/apps/mobile/src/features/files/SourceFileSurface.tsx+++ b/apps/mobile/src/features/files/SourceFileSurface.tsx@@ -2,7 +2,7 @@ import { settlePromise } from "@t3tools/client-runtime/state/runtime";import { useAtomValue } from "@effect/atom-react";import { AsyncResult } from "effect/reactivity";import type { ComponentType } from "react";-import { useEffect, useRef, useState } from "react";+import { useLayoutEffect, useRef, useState } from "react";import {FlatList,Platform,@@ -37,6 +37,7 @@ import { SourceText } from "@t3tools/mobile-source-text";import { boundedSelectableSourceTokens, prepareSourceFileDocument } from "./source-file-document";import { sourceHighlightAtom } from "./sourceHighlightingState";+import { createSourceLineScroll } from "./source-file-scroll";interface SourceFileSurfaceProps {readonly contents: string;@@ -241,21 +242,21 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {const { normalizedContents, lines, status, targetIndex, tokens } = useSourceFileModel(props);const selectableTokens = props.selectable ? boundedSelectableSourceTokens(tokens) : null;const listRef = useRef<FlatList<string>>(null);+ const [lineScroll] = useState(createSourceLineScroll);const { isPullRefreshing, handlePullToRefresh } = useSourceFileRefresh(props.onRefresh);const refreshControl = props.onRefresh ? (<RefreshControl refreshing={isPullRefreshing} onRefresh={() => void handlePullToRefresh()} />) : undefined;- useEffect(() => {+ // Layout effect so a pending jump is cancelled in the commit that swaps the file.+ useLayoutEffect(() => {if (targetIndex === null) {return;}- const frame = requestAnimationFrame(() => {- listRef.current?.scrollToIndex({ index: targetIndex, animated: false, viewPosition: 0.3 });- });- return () => cancelAnimationFrame(frame);+ lineScroll.scrollToLine(listRef.current, targetIndex);+ return lineScroll.cancel;// oxlint-disable-next-line react/exhaustive-effect-dependencies -- Opening another file at the same line index scrolls the new file to it.- }, [props.path, targetIndex]);+ }, [lineScroll, props.path, targetIndex]);const renderLine = ({ item, index }: { item: string; index: number }) => (<HighlightedSourceLine@@ -346,6 +347,8 @@ function JavaScriptSourceFileSurface(props: SourceFileSurfaceProps) {paddingTop: 8,}}renderItem={renderLine}+ onScrollToIndexFailed={lineScroll.onScrollToIndexFailed}+ onScrollBeginDrag={lineScroll.cancel}/>);diff --git a/apps/mobile/src/features/files/source-file-scroll.test.ts b/apps/mobile/src/features/files/source-file-scroll.test.tsnew file mode 100644index 00000000000..98fc4b6a2ad--- /dev/null+++ b/apps/mobile/src/features/files/source-file-scroll.test.ts@@ -0,0 +1,156 @@+import { expect, it, vi } from "vite-plus/test";++import { createSourceLineScroll } from "./source-file-scroll";++const ROW_HEIGHT = 24;++// Mirrors VirtualizedList.scrollToIndex without getItemLayout: indices past the highest+// measured cell fail, and unmeasured indices below it scroll to an averaged estimate.+function setup({+ lineCount = 1_203,+ measuredThrough = 79,+ rowHeight = (_index: number): number => ROW_HEIGHT,+} = {}) {+ vi.useFakeTimers();+ vi.stubGlobal("requestAnimationFrame", (callback: () => void) => setTimeout(callback, 16));+ vi.stubGlobal("cancelAnimationFrame", (frame: ReturnType<typeof setTimeout>) =>+ clearTimeout(frame),+ );+ const measured = new Set<number>();+ const state = {+ lineCount,+ offset: 0,+ measure(from: number, to: number) {+ for (let index = from; index <= to; index += 1) measured.add(index);+ },+ };+ state.measure(0, measuredThrough);+ const offsetOf = (index: number) => {+ let offset = 0;+ for (let row = 0; row < index; row += 1) offset += rowHeight(row);+ return offset;+ };+ const averageItemLength = () => {+ let total = 0;+ for (const index of measured) total += rowHeight(index);+ return total / measured.size;+ };+ const scrollToIndex = vi.fn((params: { index: number }) => {+ if (params.index < 0 || params.index >= state.lineCount) {+ throw new Error(`scrollToIndex out of range: requested index ${params.index}`);+ }+ const highestMeasuredFrameIndex = Math.max(...measured);+ if (params.index > highestMeasuredFrameIndex) {+ scroll.onScrollToIndexFailed({+ index: params.index,+ averageItemLength: averageItemLength(),+ highestMeasuredFrameIndex,+ });+ return;+ }+ state.offset = measured.has(params.index)+ ? offsetOf(params.index)+ : averageItemLength() * params.index;+ });+ const scrollToOffset = vi.fn((params: { offset: number }) => {+ state.offset = params.offset;+ });+ const list = {+ get props() {+ return { data: { length: state.lineCount } };+ },+ scrollToIndex,+ scrollToOffset,+ };+ const scroll = createSourceLineScroll();+ return {+ scroll,+ list,+ state,+ offsetOf,+ scrollToIndex,+ scrollToOffset,+ [Symbol.dispose]: () => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+ },+ };+}++it("lands on an already measured line", () => {+ using t = setup();++ t.scroll.scrollToLine(t.list, 40);+ vi.runAllTimers();++ expect(t.state.offset).toBe(t.offsetOf(40));+ expect(t.scrollToOffset).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+});++it("jumps near an unmeasured wrapped line, then lands on it once rows measure", () => {+ using t = setup({ rowHeight: (index) => (index >= 80 ? ROW_HEIGHT * 3 : ROW_HEIGHT) });++ t.scroll.scrollToLine(t.list, 899);+ expect(() => vi.advanceTimersToNextTimer()).not.toThrow();+ expect(t.state.offset).toBeGreaterThan(0);++ // The render batch after the estimated jump measures rows past the target first, so+ // the next scrollToIndex is accepted against an averaged estimate.+ t.state.measure(900, 979);+ vi.advanceTimersToNextTimer();+ expect(t.state.offset).not.toBe(t.offsetOf(899));++ t.state.measure(820, 899);+ vi.runAllTimers();++ expect(t.state.offset).toBe(t.offsetOf(899));+ expect(vi.getTimerCount()).toBe(0);+});++it("stops retrying when the target never measures", () => {+ using t = setup({ rowHeight: (index) => (index === 899 ? ROW_HEIGHT * 400 : ROW_HEIGHT) });++ t.scroll.scrollToLine(t.list, 899);+ expect(() => vi.runAllTimers()).not.toThrow();++ expect(t.scrollToIndex.mock.calls.length).toBeLessThanOrEqual(10);+ expect(vi.getTimerCount()).toBe(0);+});++it("ignores a line outside the document", () => {+ using t = setup({ lineCount: 12 });++ expect(() => t.scroll.scrollToLine(t.list, 899)).not.toThrow();+ vi.runAllTimers();+ expect(t.scrollToIndex).not.toHaveBeenCalled();+ expect(t.scrollToOffset).not.toHaveBeenCalled();+});++it("drops a pending jump when the document shrinks or the jump is cancelled", () => {+ using t = setup();++ t.scroll.scrollToLine(t.list, 899);+ vi.advanceTimersToNextTimer();+ t.state.lineCount = 12;+ expect(() => vi.runAllTimers()).not.toThrow();++ t.state.lineCount = 1_203;+ t.scroll.scrollToLine(t.list, 899);+ vi.advanceTimersToNextTimer();+ const calls = t.scrollToIndex.mock.calls.length;+ t.scroll.cancel();+ t.state.measure(80, 999);+ vi.runAllTimers();+ expect(t.scrollToIndex).toHaveBeenCalledTimes(calls);+});++it("a drag before the first frame cancels the jump", () => {+ using t = setup();++ t.scroll.scrollToLine(t.list, 40);+ t.scroll.cancel();+ vi.runAllTimers();++ expect(t.scrollToIndex).not.toHaveBeenCalled();+});diff --git a/apps/mobile/src/features/files/source-file-scroll.ts b/apps/mobile/src/features/files/source-file-scroll.tsnew file mode 100644index 00000000000..eb0f3dbd63f--- /dev/null+++ b/apps/mobile/src/features/files/source-file-scroll.ts@@ -0,0 +1,66 @@+interface SourceLineList {+ readonly props: { readonly data?: { readonly length: number } | null };+ scrollToIndex(params: { index: number; animated: boolean; viewPosition: number }): void;+ scrollToOffset(params: { offset: number; animated: boolean }): void;+}++const RETRY_DELAY_MS = 100;+const MAX_RETRIES = 5;++// Wrapped rows have no getItemLayout. VirtualizedList fails a jump past its highest measured+// row and silently estimates an unmeasured row below it, so re-aim until the budget runs out.+export function createSourceLineScroll() {+ let list: SourceLineList | null = null;+ let target: number | null = null;+ let retries = 0;+ let cancelPending: (() => void) | null = null;++ const cancel = () => {+ cancelPending?.();+ cancelPending = null;+ target = null;+ };++ const retry = () => {+ if (retries >= MAX_RETRIES) {+ target = null;+ return;+ }+ retries += 1;+ const timer = setTimeout(attempt, RETRY_DELAY_MS);+ cancelPending = () => clearTimeout(timer);+ };++ const attempt = () => {+ cancelPending = null;+ if (target === null || !list || target >= (list.props.data?.length ?? 0)) {+ target = null;+ return;+ }+ list.scrollToIndex({ index: target, animated: false, viewPosition: 0.3 });+ // A failed jump has already scheduled its retry.+ if (cancelPending === null) retry();+ };++ return {+ scrollToLine(nextList: SourceLineList | null, index: number) {+ cancel();+ list = nextList;+ if (!Number.isInteger(index) || index < 0) return;+ target = index;+ retries = 0;+ const frame = requestAnimationFrame(attempt);+ cancelPending = () => cancelAnimationFrame(frame);+ },+ onScrollToIndexFailed(info: {+ index: number;+ averageItemLength: number;+ highestMeasuredFrameIndex: number;+ }) {+ if (info.index !== target || !list) return;+ list.scrollToOffset({ offset: info.averageItemLength * info.index, animated: false });+ retry();+ },+ cancel,+ };+}