Skip to content

Commit 55afb76

Browse files
fix(mobile): keep word highlights during slow scrolls and in comment cards
Scroll distance was measured against the previous viewport event, so a one-row-at-a-time Android drag never crossed the 20 row threshold and stopped requesting word ranges past the initial overscan. Measure it against the last requested range instead. Review comment cards in the thread feed still sent only rows, so they lost word highlights once the adapter stopped embedding ranges. Compute their ranges with the same deferred path and deliver them as a keyed patch.
1 parent d6459f5 commit 55afb76

4 files changed

Lines changed: 220 additions & 8 deletions

File tree

‎apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.ts‎

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,146 @@ describe("resolveNativeReviewDiffView", () => {
256256
}
257257
expect(frames.size).toBe(0);
258258
});
259+
260+
it("requests new word ranges after many small scroll steps", async () => {
261+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
262+
const { useNativeReviewDiffHighlighting } =
263+
await import("../review/useNativeReviewDiffHighlighting");
264+
const rows: NativeReviewDiffRow[] = Array.from({ length: 2000 }, (_, index) => ({
265+
kind: "hunk" as const,
266+
id: `gap:${index}`,
267+
fileId: "gap",
268+
}));
269+
let changeRange:
270+
| ReturnType<typeof useNativeReviewDiffHighlighting>["updateVisibleRange"]
271+
| undefined;
272+
function Harness() {
273+
const result = useNativeReviewDiffHighlighting({
274+
files: [],
275+
rows,
276+
scheme: "dark",
277+
enabled: true,
278+
collapsedFileIds: [],
279+
resetKey: "source",
280+
contentResetKey: "view",
281+
});
282+
useLayoutEffect(() => {
283+
changeRange = result.updateVisibleRange;
284+
}, [result.updateVisibleRange]);
285+
return null;
286+
}
287+
let renderer: ReactTestRenderer | undefined;
288+
try {
289+
await act(async () => {
290+
renderer = create(createElement(Harness));
291+
});
292+
const mountJobCount = wordJobs.length;
293+
// Android reports the viewport one row at a time during a slow drag.
294+
for (let step = 1; step <= 500; step += 1) {
295+
await act(async () => {
296+
changeRange!({ firstRowIndex: step, lastRowIndex: step + 40 });
297+
});
298+
}
299+
const requestedStarts = wordJobs.slice(mountJobCount).map((job) => job.input.firstRowIndex);
300+
expect(requestedStarts.length).toBeGreaterThan(0);
301+
expect(requestedStarts.at(-1)).toBeGreaterThanOrEqual(490);
302+
// Each request waits for the viewport to move 20 rows past the previous request.
303+
expect(requestedStarts).toEqual(
304+
Array.from({ length: requestedStarts.length }, (_, index) => 1 + index * 10),
305+
);
306+
} finally {
307+
await act(async () => renderer?.unmount());
308+
}
309+
});
310+
311+
it("delivers word ranges for review comment cards as a keyed patch", async () => {
312+
setExpoViewConfigAvailable();
313+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
314+
const frames = new Map<number, (time: number) => void>();
315+
let frameId = 0;
316+
vi.stubGlobal("requestAnimationFrame", (callback: (time: number) => void) => {
317+
frames.set(++frameId, callback);
318+
return frameId;
319+
});
320+
vi.stubGlobal("cancelAnimationFrame", (id: number) => frames.delete(id));
321+
const sent: string[] = [];
322+
const nativeProps: Array<Record<string, unknown>> = [];
323+
const nativeHandle = {
324+
setRowsJson: async () => undefined,
325+
setTokensJson: async () => undefined,
326+
setTokensPatchJson: async (json: string) => {
327+
sent.push(json);
328+
},
329+
};
330+
const NativeMock = forwardRef<typeof nativeHandle, Record<string, unknown>>(
331+
function NativeMock(props, ref) {
332+
nativeProps.push(props);
333+
useImperativeHandle(ref, () => nativeHandle, []);
334+
return null;
335+
},
336+
);
337+
expoMocks.requireNativeView.mockReturnValue(NativeMock);
338+
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
339+
const { useNativeReviewCommentWordDiffs } =
340+
await import("../review/useNativeReviewCommentWordDiffs");
341+
const NativeView = resolveNativeReviewDiffView();
342+
if (!NativeView) throw new Error("Expected the native payload sender");
343+
const rows: NativeReviewDiffRow[] = [
344+
{
345+
kind: "line",
346+
id: "c:snippet:0",
347+
change: "delete",
348+
content: 'const item = renderPanel({ title: "before", active: true });',
349+
},
350+
{
351+
kind: "line",
352+
id: "c:snippet:1",
353+
change: "add",
354+
content: 'const item = renderPanel({ title: "after", active: true });',
355+
},
356+
];
357+
function Card() {
358+
const { tokensResetKey, wordDiffRangesPatchJson } = useNativeReviewCommentWordDiffs({
359+
rows,
360+
enabled: true,
361+
});
362+
return createElement(NativeView!, {
363+
appearanceScheme: "dark",
364+
themeJson: "{}",
365+
rowHeight: 20,
366+
contentWidth: 1000,
367+
rowsJson: "[]",
368+
tokensResetKey,
369+
wordDiffRangesPatchJson,
370+
});
371+
}
372+
let renderer: ReactTestRenderer | undefined;
373+
try {
374+
await act(async () => {
375+
renderer = create(createElement(Card));
376+
});
377+
await act(async () => {
378+
await wordJobs.at(-1)!.complete();
379+
});
380+
await act(async () => {
381+
const pending = [...frames.values()];
382+
frames.clear();
383+
for (const callback of pending) callback(performance.now());
384+
await Promise.resolve();
385+
});
386+
const patch = sent.map((json) => JSON.parse(json)).find((p) => "wordDiffRangesByRowId" in p);
387+
expect(patch).toBeDefined();
388+
expect(patch.resetKey).toBe(nativeProps.at(-1)!.tokensResetKey);
389+
expect(Object.keys(patch.wordDiffRangesByRowId).sort()).toEqual([
390+
"c:snippet:0",
391+
"c:snippet:1",
392+
]);
393+
expect(patch.wordDiffRangesByRowId["c:snippet:0"]).toEqual([{ start: 35, end: 41 }]);
394+
expect(patch.wordDiffRangesByRowId["c:snippet:1"]).toEqual([{ start: 35, end: 40 }]);
395+
} finally {
396+
await act(async () => renderer?.unmount());
397+
}
398+
});
259399
});
260400

261401
describe("isPendingNativeViewRegistration", () => {

‎apps/mobile/src/features/review/ReviewCommentCard.tsx‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { buildReviewParsedDiff } from "./reviewModel";
1717
import { REVIEW_MONO_FONT_FAMILY } from "./reviewDiffRendering";
1818
import type { ReviewInlineComment } from "./reviewCommentSelection";
1919
import { useMarkdownCodeHighlight } from "../threads/markdownCodeHighlightState";
20+
import { useNativeReviewCommentWordDiffs } from "./useNativeReviewCommentWordDiffs";
2021

2122
export interface ReviewCommentColors {
2223
readonly background: ColorValue;
@@ -127,6 +128,10 @@ export const ReviewCommentCard = memo(function ReviewCommentCard(props: {
127128
[compactNativeRows.length, nativeReviewDiffStyle],
128129
);
129130
const shouldRenderNativeDiff = NativeReviewDiffView != null && compactNativeRows.length > 0;
131+
const { tokensResetKey, wordDiffRangesPatchJson } = useNativeReviewCommentWordDiffs({
132+
rows: compactNativeRows,
133+
enabled: shouldRenderNativeDiff,
134+
});
130135

131136
return (
132137
<View
@@ -189,6 +194,8 @@ export const ReviewCommentCard = memo(function ReviewCommentCard(props: {
189194
rowHeight={nativeReviewDiffStyle.rowHeight}
190195
rowsJson={nativeRowsJson}
191196
tokensJson={nativeTokensJson}
197+
tokensResetKey={tokensResetKey}
198+
wordDiffRangesPatchJson={wordDiffRangesPatchJson}
192199
styleJson={nativeStyleJson}
193200
themeJson={nativeThemeJson}
194201
/>
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import { useEffect, useMemo, useState } from "react";
2+
3+
import type { NativeReviewDiffRow } from "../diffs/nativeReviewDiffSurface";
4+
import { computeVisibleNativeReviewWordDiffRanges } from "./nativeReviewWordDiffs";
5+
6+
interface NativeReviewCommentWordDiffPatch {
7+
readonly resetKey: string;
8+
readonly wordDiffRangesByRowId: Awaited<
9+
ReturnType<typeof computeVisibleNativeReviewWordDiffRanges>
10+
>["rangesByRowId"];
11+
}
12+
13+
// Line numbers stay out of the key: they change the rows JSON without changing
14+
// syntax tokens, and a reset would clear tokens native never gets resent.
15+
function buildCommentRowsResetKey(rows: ReadonlyArray<NativeReviewDiffRow>): string {
16+
let hash = 5381;
17+
for (const row of rows) {
18+
const text = `${row.id}\n${row.content ?? ""}\n`;
19+
for (let index = 0; index < text.length; index += 1) {
20+
hash = (hash * 33) ^ text.charCodeAt(index);
21+
}
22+
}
23+
return `${rows.length}:${(hash >>> 0).toString(36)}`;
24+
}
25+
26+
/** Word highlights for a comment card's rows, delivered as a patch like the review sheet. */
27+
export function useNativeReviewCommentWordDiffs(input: {
28+
readonly rows: ReadonlyArray<NativeReviewDiffRow>;
29+
readonly enabled: boolean;
30+
}) {
31+
const { enabled, rows } = input;
32+
const tokensResetKey = useMemo(() => buildCommentRowsResetKey(rows), [rows]);
33+
const [patch, setPatch] = useState<NativeReviewCommentWordDiffPatch>(() => ({
34+
resetKey: tokensResetKey,
35+
wordDiffRangesByRowId: {},
36+
}));
37+
const wordDiffRangesPatchJson = useMemo(() => JSON.stringify(patch), [patch]);
38+
39+
useEffect(() => {
40+
if (!enabled || rows.length === 0) return;
41+
const abortController = new AbortController();
42+
void computeVisibleNativeReviewWordDiffRanges({
43+
rows,
44+
firstRowIndex: 0,
45+
lastRowIndex: rows.length - 1,
46+
signal: abortController.signal,
47+
})
48+
.then((result) => {
49+
if (abortController.signal.aborted || result.pairCount === 0) return;
50+
setPatch({ resetKey: tokensResetKey, wordDiffRangesByRowId: result.rangesByRowId });
51+
})
52+
.catch((error: unknown) => {
53+
if (!abortController.signal.aborted && typeof __DEV__ !== "undefined" && __DEV__) {
54+
console.log("[review-comment] word diff failed", { error, resetKey: tokensResetKey });
55+
}
56+
});
57+
return () => abortController.abort();
58+
}, [enabled, rows, tokensResetKey]);
59+
60+
return { tokensResetKey, wordDiffRangesPatchJson };
61+
}

‎apps/mobile/src/features/review/useNativeReviewDiffHighlighting.ts‎

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ interface NativeReviewWordDiffPatch {
2121
>["rangesByRowId"];
2222
}
2323

24+
const INITIAL_VISIBLE_RANGE: NativeReviewVisibleRange = { firstRowIndex: 0, lastRowIndex: 80 };
25+
2426
function createEmptyTokenPatch(resetKey: string): string {
2527
return JSON.stringify({ resetKey, tokensByRowId: {} });
2628
}
@@ -55,10 +57,10 @@ export function useNativeReviewDiffHighlighting(input: {
5557
const highlightedRowIdsRef = useRef<Set<string>>(new Set());
5658
const wordHighlightedRowIdsRef = useRef<Set<string>>(new Set());
5759
const contentResetKeyRef = useRef(contentResetKey);
58-
const visibleRangeRef = useRef<NativeReviewVisibleRange>({
59-
firstRowIndex: 0,
60-
lastRowIndex: 80,
61-
});
60+
const visibleRangeRef = useRef<NativeReviewVisibleRange>(INITIAL_VISIBLE_RANGE);
61+
// The range the latest highlight request covered. Scroll distance is measured
62+
// from here, not from the previous viewport event, so a slow scroll still adds up.
63+
const requestedRangeRef = useRef<NativeReviewVisibleRange>(INITIAL_VISIBLE_RANGE);
6264
const visibleChunkIndexRef = useRef(0);
6365
const [tokensPatchJson, setTokensPatchJson] = useState(() => createEmptyTokenPatch(resetKey));
6466
const [wordDiffRangesPatch, setWordDiffRangesPatch] = useState<NativeReviewWordDiffPatch>(() => ({
@@ -77,11 +79,12 @@ export function useNativeReviewDiffHighlighting(input: {
7779
visibleChunkIndexRef.current = 0;
7880
if (contentResetKeyRef.current !== contentResetKey) {
7981
contentResetKeyRef.current = contentResetKey;
80-
visibleRangeRef.current = { firstRowIndex: 0, lastRowIndex: 80 };
82+
visibleRangeRef.current = INITIAL_VISIBLE_RANGE;
8183
}
8284
setTokensPatchJson(createEmptyTokenPatch(resetKey));
8385
setWordDiffRangesPatch({ resetKey, wordDiffRangesByRowId: {} });
8486
if (enabled && rows.length > 0) {
87+
requestedRangeRef.current = visibleRangeRef.current;
8588
setVisibleHighlightRequest((request) => request + 1);
8689
}
8790
}, [contentResetKey, enabled, resetKey, rows.length]);
@@ -180,13 +183,14 @@ export function useNativeReviewDiffHighlighting(input: {
180183
}, [resetKey, wordDiffRangesPatch]);
181184

182185
const updateVisibleRange = useCallback((nextRange: NativeReviewVisibleRange) => {
183-
const previousRange = visibleRangeRef.current;
186+
const requestedRange = requestedRangeRef.current;
184187
const movedRows =
185-
Math.abs(nextRange.firstRowIndex - previousRange.firstRowIndex) +
186-
Math.abs(nextRange.lastRowIndex - previousRange.lastRowIndex);
188+
Math.abs(nextRange.firstRowIndex - requestedRange.firstRowIndex) +
189+
Math.abs(nextRange.lastRowIndex - requestedRange.lastRowIndex);
187190

188191
visibleRangeRef.current = nextRange;
189192
if (movedRows >= 20) {
193+
requestedRangeRef.current = nextRange;
190194
setVisibleHighlightRequest((request) => request + 1);
191195
}
192196
}, []);

0 commit comments

Comments
 (0)