Improve mobile review diff rendering

- Switch review screen to a virtualized list layout
- Queue diff highlighting and default to the JS engine
- Add word-diff helpers and tests
This commit is contained in:
Julius Marminge committed 2026-05-20 10:40:27 +02:00
1 parent 43d534ad67
commit dcf4d6d38e
14 files changed
+1573 -323

No files matched your search

+8
View File
@@ -36,6 +36,14 @@ Build and run the local iOS preview app:
bun run ios:preview
```
Force the review diff highlighter engine:
```bash
EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE=javascript bun run ios:dev
```
`javascript` is the default and recommended setting for the review diff screen. Set `EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE=native` only when you explicitly want to test the native Shiki engine.
Inspect the resolved Expo config for a variant:
```bash
+1
View File
@@ -47,6 +47,7 @@
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"clsx": "^2.1.1",
"diff": "8.0.3",
"effect": "catalog:",
"expo": "~55.0.14",
"expo-camera": "~55.0.15",
@@ -27,12 +27,16 @@ import { appendReviewCommentToDraft } from "../use-thread-composer-state";
import {
clearReviewCommentTarget,
formatReviewCommentContext,
getReviewChangeMarker,
getReviewUnifiedLineNumber,
getSelectedReviewCommentLines,
useReviewCommentTarget,
} from "./reviewCommentSelection";
import { changeTone, DiffTokenText } from "./reviewDiffRendering";
import {
changeTone,
DiffTokenText,
REVIEW_MONO_FONT_FAMILY,
ReviewChangeBar,
} from "./reviewDiffRendering";
import {
highlightReviewSelectedLines,
type ReviewDiffTheme,
@@ -217,19 +221,18 @@ export function ReviewCommentComposerSheet() {
className={cn("flex-row items-start", changeTone(line.change))}
style={{ height: REVIEW_COMMENT_LINE_HEIGHT }}
>
<Text className="w-9 px-1 py-1 text-right text-[11px] font-t3-medium text-foreground-muted">
{lineNumber ?? ""}
</Text>
<ReviewChangeBar change={line.change} />
<Text
className="px-0.5 py-1 text-center font-mono text-[12px] text-foreground-muted"
style={{ width: 18 }}
className="w-9 py-1 pr-1 text-right text-[11px] font-t3-medium text-foreground-muted"
style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
>
{getReviewChangeMarker(line.change)}
{lineNumber ?? ""}
</Text>
<View className="min-w-0 flex-1 flex-shrink-0 px-1 py-1">
<DiffTokenText
fallback={line.content}
tokens={highlightedLinesById[line.id] ?? null}
change={line.change}
/>
</View>
</View>
File diff suppressed because it is too large. Load diff
@@ -1,4 +1,4 @@
import { Platform, Text as NativeText } from "react-native";
import { Platform, Text as NativeText, View } from "react-native";
import { cn } from "../../../lib/cn";
@@ -17,14 +17,47 @@ export function renderVisibleWhitespace(value: string): string {
}
export function changeTone(change: ReviewRenderableLineRow["change"]): string {
if (change === "add") return "bg-emerald-500/12";
if (change === "delete") return "bg-rose-500/12";
if (change === "add") return "bg-emerald-500/10";
if (change === "delete") return "bg-rose-500/10";
return "bg-card";
}
export function changeBarTone(change: ReviewRenderableLineRow["change"]): string {
if (change === "add") return "bg-emerald-400";
if (change === "delete") return "bg-rose-400";
return "bg-border/50";
}
function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string | undefined {
if (change === "add") return "rgba(16, 185, 129, 0.24)";
if (change === "delete") return "rgba(244, 63, 94, 0.24)";
return undefined;
}
export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) {
if (props.change === "delete") {
return (
<View className="w-[5px] self-stretch overflow-hidden">
<View className="flex-1 justify-between">
{Array.from({ length: 6 }, (_, index) => (
<View key={index} className="h-[2px] w-[5px] bg-rose-400" />
))}
</View>
</View>
);
}
return (
<View className="w-[5px] self-stretch overflow-hidden">
<View className={cn("h-full w-[5px] flex-1", changeBarTone(props.change))} />
</View>
);
}
export function DiffTokenText(props: {
readonly tokens: ReadonlyArray<ReviewHighlightedToken> | null;
readonly fallback: string;
readonly change?: ReviewRenderableLineRow["change"];
readonly className?: string;
}) {
if (!props.tokens || props.tokens.length === 0) {
@@ -70,6 +103,11 @@ export function DiffTokenText(props: {
fontFamily: REVIEW_MONO_FONT_FAMILY,
fontWeight,
fontStyle,
backgroundColor:
token.diffHighlight && props.change
? diffHighlightColor(props.change)
: undefined,
borderRadius: token.diffHighlight ? 4 : undefined,
}}
>
{token.content.length > 0 ? renderVisibleWhitespace(token.content) : " "}
@@ -13,6 +13,7 @@ describe("resolveReviewHighlighterEnginePreference", () => {
it("accepts supported values", () => {
expect(resolveReviewHighlighterEnginePreference("javascript")).toBe("javascript");
expect(resolveReviewHighlighterEnginePreference("js")).toBe("javascript");
expect(resolveReviewHighlighterEnginePreference("native")).toBe("native");
});
});
@@ -5,9 +5,11 @@ export function resolveReviewHighlighterEnginePreference(
value: string | undefined,
): ReviewHighlighterEnginePreference {
switch (value) {
case "js":
case "javascript":
return "javascript";
case "native":
return value;
return "native";
default:
return "javascript";
}
@@ -8,6 +8,7 @@ import {
} from "@t3tools/contracts";
import {
buildReviewListItems,
buildReviewParsedDiff,
buildReviewSectionItems,
getDefaultReviewSectionId,
@@ -138,6 +139,7 @@ describe("buildReviewParsedDiff", () => {
oldLineNumber: 1,
newLineNumber: null,
content: "const before = 1;",
comparison: { change: "add", tokenIndex: 0 },
}),
expect.objectContaining({
kind: "line",
@@ -145,6 +147,7 @@ describe("buildReviewParsedDiff", () => {
oldLineNumber: null,
newLineNumber: 1,
content: "const after = 2;",
comparison: { change: "delete", tokenIndex: 0 },
}),
expect.objectContaining({
kind: "line",
@@ -152,6 +155,7 @@ describe("buildReviewParsedDiff", () => {
oldLineNumber: null,
newLineNumber: 2,
content: "console.log(after);",
comparison: null,
}),
expect.objectContaining({
kind: "line",
@@ -159,6 +163,7 @@ describe("buildReviewParsedDiff", () => {
oldLineNumber: 2,
newLineNumber: 3,
content: "return true;",
comparison: null,
}),
]);
});
@@ -220,6 +225,7 @@ describe("buildReviewParsedDiff", () => {
content: `const line${index} = ${index};`,
additionTokenIndex: index,
deletionTokenIndex: null,
comparison: null,
})),
}),
);
@@ -231,4 +237,73 @@ describe("buildReviewParsedDiff", () => {
actionLabel: "Load diff",
});
});
it("flattens expanded files into virtualizable review items", () => {
const file = makeRenderableFile({
path: "apps/mobile/src/a.ts",
rows: [
{
kind: "hunk",
id: "hunk-1",
header: "@@ -1,1 +1,2 @@",
context: null,
},
{
kind: "line",
id: "line-1",
change: "add",
oldLineNumber: null,
newLineNumber: 1,
content: "const after = 2;",
additionTokenIndex: 0,
deletionTokenIndex: null,
comparison: null,
},
],
});
const items = buildReviewListItems({
files: [file],
expandedFileIds: [file.id],
revealedLargeFileIds: [],
});
expect(items).toEqual([
expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }),
expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }),
expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }),
]);
});
it("keeps large diffs collapsed into a placeholder item until revealed", () => {
const file = makeRenderableFile({
path: "apps/mobile/src/big.ts",
rows: Array.from({ length: 401 }, (_, index) => ({
kind: "line" as const,
id: `line-${index}`,
change: "add" as const,
oldLineNumber: null,
newLineNumber: index + 1,
content: `const line${index} = ${index};`,
additionTokenIndex: index,
deletionTokenIndex: null,
comparison: null,
})),
});
const items = buildReviewListItems({
files: [file],
expandedFileIds: [file.id],
revealedLargeFileIds: [],
});
expect(items).toEqual([
expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }),
expect.objectContaining({
kind: "file-suppressed",
fileId: file.id,
actionLabel: "Load diff",
}),
]);
});
});
@@ -30,6 +30,10 @@ export interface ReviewRenderableLineRow {
readonly content: string;
readonly additionTokenIndex: number | null;
readonly deletionTokenIndex: number | null;
readonly comparison: {
readonly change: "add" | "delete";
readonly tokenIndex: number;
} | null;
}
export type ReviewRenderableRow = ReviewRenderableHunkRow | ReviewRenderableLineRow;
@@ -48,6 +52,42 @@ export interface ReviewRenderableFile {
readonly rows: ReadonlyArray<ReviewRenderableRow>;
}
export interface ReviewFileHeaderListItem {
readonly kind: "file-header";
readonly id: string;
readonly fileId: string;
readonly file: ReviewRenderableFile;
readonly expanded: boolean;
}
export interface ReviewFileSuppressedListItem {
readonly kind: "file-suppressed";
readonly id: string;
readonly fileId: string;
readonly message: string;
readonly actionLabel: string | null;
}
export interface ReviewHunkListItem {
readonly kind: "hunk";
readonly id: string;
readonly fileId: string;
readonly row: ReviewRenderableHunkRow;
}
export interface ReviewLineListItem {
readonly kind: "line";
readonly id: string;
readonly fileId: string;
readonly row: ReviewRenderableLineRow;
}
export type ReviewListItem =
| ReviewFileHeaderListItem
| ReviewFileSuppressedListItem
| ReviewHunkListItem
| ReviewLineListItem;
export type ReviewFilePreviewState =
| {
readonly kind: "render";
@@ -267,6 +307,72 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil
return { kind: "render" };
}
// The flattened review list item model is inspired by pierre/diffs' iterator-first
// virtualization architecture, adapted here for React Native and LegendList.
// Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs
// Reference files:
// - src/utils/iterateOverDiff.ts
// - src/components/VirtualizedFileDiff.ts
export function buildReviewListItems(input: {
readonly files: ReadonlyArray<ReviewRenderableFile>;
readonly expandedFileIds: ReadonlyArray<string>;
readonly revealedLargeFileIds: ReadonlyArray<string>;
}): ReadonlyArray<ReviewListItem> {
const expandedFileIds = new Set(input.expandedFileIds);
const revealedLargeFileIds = new Set(input.revealedLargeFileIds);
const items: ReviewListItem[] = [];
input.files.forEach((file) => {
const expanded = expandedFileIds.has(file.id);
items.push({
kind: "file-header",
id: `${file.id}:header`,
fileId: file.id,
file,
expanded,
});
if (!expanded) {
return;
}
const previewState = getReviewFilePreviewState(file);
if (previewState.kind === "suppressed") {
if (previewState.reason !== "large" || !revealedLargeFileIds.has(file.id)) {
items.push({
kind: "file-suppressed",
id: `${file.id}:suppressed`,
fileId: file.id,
message: previewState.message,
actionLabel: previewState.actionLabel,
});
return;
}
}
file.rows.forEach((row) => {
if (row.kind === "hunk") {
items.push({
kind: "hunk",
id: row.id,
fileId: file.id,
row,
});
return;
}
items.push({
kind: "line",
id: row.id,
fileId: file.id,
row,
});
});
});
return items;
}
function fallbackHunkHeader(hunk: FileDiffMetadata["hunks"][number]): string {
return `@@ -${hunk.deletionStart},${hunk.deletionCount} +${hunk.additionStart},${hunk.additionCount} @@`;
}
@@ -304,6 +410,7 @@ function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray<ReviewRender
),
additionTokenIndex,
deletionTokenIndex,
comparison: null,
});
deletionLineNumber += 1;
additionLineNumber += 1;
@@ -313,6 +420,10 @@ function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray<ReviewRender
return;
}
const pairedLineCount = Math.min(segment.deletions, segment.additions);
const deletionTokenIndexStart = deletionTokenIndex;
const additionTokenIndexStart = additionTokenIndex;
for (let index = 0; index < segment.deletions; index += 1) {
rows.push({
kind: "line",
@@ -323,6 +434,13 @@ function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray<ReviewRender
content: stripTrailingNewline(file.deletionLines[deletionTokenIndex] ?? ""),
additionTokenIndex: null,
deletionTokenIndex,
comparison:
index < pairedLineCount
? {
change: "add",
tokenIndex: additionTokenIndexStart + index,
}
: null,
});
deletionLineNumber += 1;
deletionTokenIndex += 1;
@@ -338,6 +456,13 @@ function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray<ReviewRender
content: stripTrailingNewline(file.additionLines[additionTokenIndex] ?? ""),
additionTokenIndex,
deletionTokenIndex: null,
comparison:
index < pairedLineCount
? {
change: "delete",
tokenIndex: deletionTokenIndexStart + index,
}
: null,
});
additionLineNumber += 1;
additionTokenIndex += 1;
@@ -0,0 +1,62 @@
import { describe, expect, it } from "vitest";
import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs";
describe("computeWordAltDiffRanges", () => {
it("joins adjacent word replacements across a single shared separator", () => {
const ranges = computeWordAltDiffRanges({
deletionLine: "old old",
additionLine: "new new",
});
expect(ranges.deletion).toEqual([{ start: 0, end: "old old".length }]);
expect(ranges.addition).toEqual([{ start: 0, end: "new new".length }]);
});
it("skips inline word diffs for long lines", () => {
const longDeletion = `const before = "${"a".repeat(1_001)}";`;
const longAddition = `const after = "${"b".repeat(1_001)}";`;
const ranges = computeWordAltDiffRanges({
deletionLine: longDeletion,
additionLine: longAddition,
});
expect(ranges.deletion).toEqual([]);
expect(ranges.addition).toEqual([]);
});
});
describe("applyDiffRangesToTokens", () => {
it("splits highlighted fragments out of syntax tokens", () => {
const tokens = [
{
content: "const before = 1;",
color: "#fff",
fontStyle: null,
},
];
const nextTokens = applyDiffRangesToTokens(tokens, [{ start: 6, end: 12 }]);
expect(nextTokens).toEqual([
{
content: "const ",
color: "#fff",
fontStyle: null,
diffHighlight: false,
},
{
content: "before",
color: "#fff",
fontStyle: null,
diffHighlight: true,
},
{
content: " = 1;",
color: "#fff",
fontStyle: null,
diffHighlight: false,
},
]);
});
});
@@ -0,0 +1,266 @@
import { diffWordsWithSpace } from "diff";
import type { ReviewHighlightedToken } from "./shikiReviewHighlighter";
interface ReviewDiffOperation {
readonly value: string;
readonly added?: true;
readonly removed?: true;
}
interface ReviewDiffHighlightRange {
readonly start: number;
readonly end: number;
}
const REVIEW_MAX_WORD_ALT_LINE_LENGTH = 1_000;
function cleanLineEnding(value: string): string {
return value.endsWith("\n") ? value.slice(0, -1) : value;
}
function pushOrJoinSpan(input: {
readonly operation: ReviewDiffOperation;
readonly spans: Array<[0 | 1, string]>;
readonly enableJoin: boolean;
readonly isNeutral?: boolean;
readonly isLastOperation?: boolean;
}): void {
const { operation, spans, enableJoin, isNeutral = false, isLastOperation = false } = input;
const lastSpan = spans.at(-1);
if (!lastSpan || isLastOperation || !enableJoin) {
spans.push([isNeutral ? 0 : 1, operation.value]);
return;
}
const lastSpanIsNeutral = lastSpan[0] === 0;
if (
isNeutral === lastSpanIsNeutral ||
(isNeutral && operation.value.length === 1 && !lastSpanIsNeutral)
) {
lastSpan[1] += operation.value;
return;
}
spans.push([isNeutral ? 0 : 1, operation.value]);
}
function spansToRanges(
spans: ReadonlyArray<readonly [0 | 1, string]>,
): ReadonlyArray<ReviewDiffHighlightRange> {
const ranges: ReviewDiffHighlightRange[] = [];
let offset = 0;
spans.forEach(([kind, value]) => {
const nextOffset = offset + value.length;
if (kind === 1 && value.length > 0) {
ranges.push({ start: offset, end: nextOffset });
}
offset = nextOffset;
});
return ranges;
}
function mergeNearbyRanges(
ranges: ReadonlyArray<ReviewDiffHighlightRange>,
): ReadonlyArray<ReviewDiffHighlightRange> {
if (ranges.length <= 1) {
return ranges;
}
const merged: ReviewDiffHighlightRange[] = [];
ranges.forEach((range) => {
const previous = merged.at(-1);
if (previous && range.start - previous.end <= 1) {
merged[merged.length - 1] = { start: previous.start, end: range.end };
return;
}
merged.push({ ...range });
});
return merged;
}
function appendTokenSegment(
target: ReviewHighlightedToken[],
source: ReviewHighlightedToken,
content: string,
diffHighlight: boolean,
): void {
if (content.length === 0) {
return;
}
const previous = target.at(-1);
if (
previous &&
previous.color === source.color &&
previous.fontStyle === source.fontStyle &&
previous.diffHighlight === diffHighlight
) {
previous.content += content;
return;
}
target.push({
content,
color: source.color,
fontStyle: source.fontStyle,
diffHighlight,
});
}
export function computeWordAltDiffRanges(input: {
readonly deletionLine: string;
readonly additionLine: string;
}): {
readonly deletion: ReadonlyArray<ReviewDiffHighlightRange>;
readonly addition: ReadonlyArray<ReviewDiffHighlightRange>;
} {
const deletionLine = cleanLineEnding(input.deletionLine);
const additionLine = cleanLineEnding(input.additionLine);
if (deletionLine.length === 0 && additionLine.length === 0) {
return { deletion: [], addition: [] };
}
if (
deletionLine.length > REVIEW_MAX_WORD_ALT_LINE_LENGTH ||
additionLine.length > REVIEW_MAX_WORD_ALT_LINE_LENGTH
) {
return { deletion: [], addition: [] };
}
const operations = diffWordsWithSpace(
deletionLine,
additionLine,
) as ReadonlyArray<ReviewDiffOperation>;
const deletionSpans: Array<[0 | 1, string]> = [];
const additionSpans: Array<[0 | 1, string]> = [];
const lastOperation = operations.at(-1);
operations.forEach((operation) => {
const isLastOperation = operation === lastOperation;
if (!operation.added && !operation.removed) {
pushOrJoinSpan({
operation,
spans: deletionSpans,
enableJoin: true,
isNeutral: true,
isLastOperation,
});
pushOrJoinSpan({
operation,
spans: additionSpans,
enableJoin: true,
isNeutral: true,
isLastOperation,
});
return;
}
if (operation.removed) {
pushOrJoinSpan({
operation,
spans: deletionSpans,
enableJoin: true,
isLastOperation,
});
return;
}
pushOrJoinSpan({
operation,
spans: additionSpans,
enableJoin: true,
isLastOperation,
});
});
return {
deletion: mergeNearbyRanges(spansToRanges(deletionSpans)),
addition: mergeNearbyRanges(spansToRanges(additionSpans)),
};
}
export function applyDiffRangesToTokens(
tokens: ReadonlyArray<ReviewHighlightedToken>,
ranges: ReadonlyArray<ReviewDiffHighlightRange>,
): ReadonlyArray<ReviewHighlightedToken> {
if (tokens.length === 0 || ranges.length === 0) {
return tokens;
}
const nextTokens: ReviewHighlightedToken[] = [];
let tokenOffset = 0;
let rangeIndex = 0;
tokens.forEach((token) => {
const tokenStart = tokenOffset;
const tokenEnd = tokenStart + token.content.length;
tokenOffset = tokenEnd;
if (token.content.length === 0) {
nextTokens.push(token);
return;
}
while ((ranges[rangeIndex]?.end ?? 0) <= tokenStart) {
rangeIndex += 1;
}
if ((ranges[rangeIndex]?.start ?? Number.POSITIVE_INFINITY) >= tokenEnd) {
nextTokens.push(token.diffHighlight ? { ...token, diffHighlight: false } : token);
return;
}
let cursor = tokenStart;
let localRangeIndex = rangeIndex;
while ((ranges[localRangeIndex]?.start ?? Number.POSITIVE_INFINITY) < tokenEnd) {
const range = ranges[localRangeIndex];
if (!range) {
break;
}
if (range.start > cursor) {
appendTokenSegment(
nextTokens,
token,
token.content.slice(cursor - tokenStart, range.start - tokenStart),
false,
);
}
const highlightedStart = Math.max(cursor, range.start);
const highlightedEnd = Math.min(tokenEnd, range.end);
if (highlightedEnd > highlightedStart) {
appendTokenSegment(
nextTokens,
token,
token.content.slice(highlightedStart - tokenStart, highlightedEnd - tokenStart),
true,
);
}
cursor = highlightedEnd;
if (range.end <= tokenEnd) {
localRangeIndex += 1;
} else {
break;
}
}
if (cursor < tokenEnd) {
appendTokenSegment(nextTokens, token, token.content.slice(cursor - tokenStart), false);
}
rangeIndex = localRangeIndex;
});
return nextTokens;
}
@@ -41,4 +41,73 @@ describe("highlightReviewFile", () => {
expect(highlighted.additionLines[2]?.some((token) => token.content === "const")).toBe(true);
expect(highlighted.additionLines[3]?.some((token) => token.content === "expect")).toBe(true);
});
it("adds word-alt diff emphasis for paired deletion and addition lines", async () => {
const file = makeRenderableFile({
path: "apps/mobile/src/example-inline-diff.test.ts",
additionLines: ["const after = 2;"],
deletionLines: ["const before = 1;"],
rows: [
{
kind: "line",
id: "delete-1",
change: "delete",
oldLineNumber: 1,
newLineNumber: null,
content: "const before = 1;",
additionTokenIndex: null,
deletionTokenIndex: 0,
comparison: { change: "add", tokenIndex: 0 },
},
{
kind: "line",
id: "add-1",
change: "add",
oldLineNumber: null,
newLineNumber: 1,
content: "const after = 2;",
additionTokenIndex: 0,
deletionTokenIndex: null,
comparison: { change: "delete", tokenIndex: 0 },
},
],
});
const highlighted = await highlightReviewFile(file, "light");
expect(highlighted.deletionLines[0]?.some((token) => token.diffHighlight === true)).toBe(true);
expect(highlighted.additionLines[0]?.some((token) => token.diffHighlight === true)).toBe(true);
});
it("falls back to plain tokens for very long lines", async () => {
const longLine = `const value = "${"a".repeat(1_100)}";`;
const file = makeRenderableFile({
path: "apps/mobile/src/example-long-line.ts",
additionLines: [longLine],
rows: [
{
kind: "line",
id: "add-1",
change: "add",
oldLineNumber: null,
newLineNumber: 1,
content: longLine,
additionTokenIndex: 0,
deletionTokenIndex: null,
comparison: null,
},
],
});
const highlighted = await highlightReviewFile(file, "light");
expect(highlighted.additionLines).toHaveLength(1);
expect(highlighted.additionLines[0]).toEqual([
{
content: longLine,
color: null,
fontStyle: null,
},
]);
});
});
@@ -8,13 +8,15 @@ import {
type ReviewHighlighterEngine,
} from "./reviewHighlighterEngine";
import type { ReviewRenderableFile, ReviewRenderableLineRow } from "./reviewModel";
import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs";
export type ReviewDiffTheme = "light" | "dark";
export interface ReviewHighlightedToken {
readonly content: string;
content: string;
readonly color: string | null;
readonly fontStyle: number | null;
readonly diffHighlight?: boolean;
}
export interface ReviewHighlightedFile {
@@ -26,13 +28,19 @@ const SHIKI_THEME_NAME_BY_SCHEME = {
light: "github-light-default",
dark: "github-dark-default",
} as const;
const REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE =
process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? "javascript";
const REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE = resolveReviewHighlighterEnginePreference(
process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? "javascript",
REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE,
);
const REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE = resolveReviewHighlighterBooleanFlag(
process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_DISABLE_CACHE,
false,
);
const REVIEW_HIGHLIGHT_RESULT_CACHE_LIMIT = 8;
const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 40;
const REVIEW_HIGHLIGHT_CHUNK_SIZE = 20;
const REVIEW_TOKENIZE_MAX_LINE_LENGTH = 1_000;
const highlightCache = new Map<string, Promise<ReviewHighlightedFile>>();
const resolvedHighlightCache = new Map<string, ReviewHighlightedFile>();
const loadedLanguages = new Set<string>(["text"]);
@@ -205,6 +213,17 @@ function joinPatchLines(lines: ReadonlyArray<string>): string {
return lines.map(stripTrailingNewline).join("\n");
}
function waitForNextFrame(): Promise<void> {
return new Promise((resolve) => {
if (typeof requestAnimationFrame === "function") {
requestAnimationFrame(() => resolve());
return;
}
setTimeout(resolve, 0);
});
}
async function getHighlighter(): Promise<HighlighterCore> {
if (!highlighterPromise) {
const configuredHighlighterPromise = Promise.all([
@@ -214,6 +233,7 @@ async function getHighlighter(): Promise<HighlighterCore> {
let nativeEngineAvailable = false;
logReviewHighlighterDiagnostic("initializing", {
configuredPreference: REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE,
preference: REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE,
resultCacheDisabled: REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE,
});
@@ -379,6 +399,146 @@ function normalizeHighlightedLines(
);
}
function applyWordAltDiffHighlightsToFile(
file: ReviewRenderableFile,
highlighted: ReviewHighlightedFile,
): ReviewHighlightedFile {
const nextAdditionLines = [...highlighted.additionLines];
const nextDeletionLines = [...highlighted.deletionLines];
const processedPairs = new Set<string>();
let changed = false;
file.rows.forEach((row) => {
if (row.kind !== "line" || row.change === "context" || !row.comparison) {
return;
}
const deletionTokenIndex =
row.change === "delete"
? row.deletionTokenIndex
: row.comparison.change === "delete"
? row.comparison.tokenIndex
: null;
const additionTokenIndex =
row.change === "add"
? row.additionTokenIndex
: row.comparison.change === "add"
? row.comparison.tokenIndex
: null;
if (deletionTokenIndex === null || additionTokenIndex === null) {
return;
}
const pairKey = `${deletionTokenIndex}:${additionTokenIndex}`;
if (processedPairs.has(pairKey)) {
return;
}
processedPairs.add(pairKey);
const deletionLine = stripTrailingNewline(file.deletionLines[deletionTokenIndex] ?? "");
const additionLine = stripTrailingNewline(file.additionLines[additionTokenIndex] ?? "");
const ranges = computeWordAltDiffRanges({ deletionLine, additionLine });
if (ranges.deletion.length > 0) {
nextDeletionLines[deletionTokenIndex] = applyDiffRangesToTokens(
nextDeletionLines[deletionTokenIndex] ?? [],
ranges.deletion,
);
changed = true;
}
if (ranges.addition.length > 0) {
nextAdditionLines[additionTokenIndex] = applyDiffRangesToTokens(
nextAdditionLines[additionTokenIndex] ?? [],
ranges.addition,
);
changed = true;
}
});
return changed
? {
additionLines: nextAdditionLines,
deletionLines: nextDeletionLines,
}
: highlighted;
}
function applyWordAltDiffHighlightsToSelectedLines(input: {
readonly lines: ReadonlyArray<ReviewRenderableLineRow>;
readonly tokenMap: Record<string, ReadonlyArray<ReviewHighlightedToken>>;
}): Record<string, ReadonlyArray<ReviewHighlightedToken>> {
const additionLineByTokenIndex = new Map<number, ReviewRenderableLineRow>();
const deletionLineByTokenIndex = new Map<number, ReviewRenderableLineRow>();
input.lines.forEach((line) => {
if (line.change === "add" && line.additionTokenIndex !== null) {
additionLineByTokenIndex.set(line.additionTokenIndex, line);
}
if (line.change === "delete" && line.deletionTokenIndex !== null) {
deletionLineByTokenIndex.set(line.deletionTokenIndex, line);
}
});
const nextTokenMap = { ...input.tokenMap };
const processedPairs = new Set<string>();
input.lines.forEach((line) => {
if (line.change === "context" || !line.comparison) {
return;
}
const pairedDeletionLine =
line.change === "delete"
? line
: line.comparison.change === "delete"
? deletionLineByTokenIndex.get(line.comparison.tokenIndex)
: undefined;
const pairedAdditionLine =
line.change === "add"
? line
: line.comparison.change === "add"
? additionLineByTokenIndex.get(line.comparison.tokenIndex)
: undefined;
if (
!pairedDeletionLine ||
!pairedAdditionLine ||
pairedDeletionLine.deletionTokenIndex === null ||
pairedAdditionLine.additionTokenIndex === null
) {
return;
}
const pairKey = `${pairedDeletionLine.deletionTokenIndex}:${pairedAdditionLine.additionTokenIndex}`;
if (processedPairs.has(pairKey)) {
return;
}
processedPairs.add(pairKey);
const ranges = computeWordAltDiffRanges({
deletionLine: pairedDeletionLine.content,
additionLine: pairedAdditionLine.content,
});
if (ranges.deletion.length > 0) {
nextTokenMap[pairedDeletionLine.id] = applyDiffRangesToTokens(
nextTokenMap[pairedDeletionLine.id] ?? [],
ranges.deletion,
);
}
if (ranges.addition.length > 0) {
nextTokenMap[pairedAdditionLine.id] = applyDiffRangesToTokens(
nextTokenMap[pairedAdditionLine.id] ?? [],
ranges.addition,
);
}
});
return nextTokenMap;
}
async function highlightLines(
code: string,
language: string,
@@ -389,14 +549,76 @@ async function highlightLines(
}
const highlighter = await getHighlighter();
const tokenLines = highlighter.codeToTokensBase(code, { lang: language, theme });
return normalizeHighlightedLines(tokenLines);
const sourceLines = code.split("\n");
const highlightedLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
const shortLineBatch: string[] = [];
const flushShortLineBatch = async (): Promise<void> => {
if (shortLineBatch.length === 0) {
return;
}
const tokenLines = highlighter.codeToTokensBase(shortLineBatch.join("\n"), {
lang: language,
theme,
});
highlightedLines.push(...normalizeHighlightedLines(tokenLines));
shortLineBatch.length = 0;
};
for (let lineIndex = 0; lineIndex < sourceLines.length; lineIndex += 1) {
const line = sourceLines[lineIndex] ?? "";
if (line.length > REVIEW_TOKENIZE_MAX_LINE_LENGTH) {
await flushShortLineBatch();
highlightedLines.push([{ content: line, color: null, fontStyle: null }]);
} else {
shortLineBatch.push(line);
}
if (shortLineBatch.length >= REVIEW_HIGHLIGHT_CHUNK_SIZE) {
await flushShortLineBatch();
}
if (
sourceLines.length > REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD &&
lineIndex + 1 < sourceLines.length &&
(shortLineBatch.length === 0 || line.length > REVIEW_TOKENIZE_MAX_LINE_LENGTH)
) {
await waitForNextFrame();
}
}
await flushShortLineBatch();
return highlightedLines;
}
function getHighlightCacheKey(file: ReviewRenderableFile, theme: ReviewDiffTheme): string {
return `${SHIKI_THEME_NAME_BY_SCHEME[theme]}:${file.cacheKey}`;
}
function storeResolvedHighlightedFile(cacheKey: string, highlighted: ReviewHighlightedFile): void {
if (resolvedHighlightCache.has(cacheKey)) {
resolvedHighlightCache.delete(cacheKey);
}
resolvedHighlightCache.set(cacheKey, highlighted);
while (resolvedHighlightCache.size > REVIEW_HIGHLIGHT_RESULT_CACHE_LIMIT) {
const oldestKey = resolvedHighlightCache.keys().next().value;
if (oldestKey === undefined) {
break;
}
resolvedHighlightCache.delete(oldestKey);
}
}
export function clearReviewHighlightFileCache(): void {
highlightCache.clear();
resolvedHighlightCache.clear();
}
export function getCachedHighlightedReviewFile(
file: ReviewRenderableFile,
theme: ReviewDiffTheme,
@@ -417,32 +639,72 @@ export async function highlightReviewFile(
if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
const resolved = resolvedHighlightCache.get(cacheKey);
if (resolved) {
logReviewHighlighterDiagnostic("file highlight cache hit (resolved)", {
fileId: file.id,
filePath: file.path,
theme,
});
return resolved;
}
const cached = highlightCache.get(cacheKey);
if (cached) {
logReviewHighlighterDiagnostic("file highlight cache hit (pending)", {
fileId: file.id,
filePath: file.path,
theme,
});
return cached;
}
}
const promise = (async () => {
const startedAt = Date.now();
logReviewHighlighterDiagnostic("file highlight start", {
fileId: file.id,
filePath: file.path,
theme,
additionLineCount: file.additionLines.length,
deletionLineCount: file.deletionLines.length,
rowCount: file.rows.length,
});
const language = await resolveLanguage(file);
const [additionLines, deletionLines] = await Promise.all([
highlightLines(joinPatchLines(file.additionLines), language, shikiTheme),
highlightLines(joinPatchLines(file.deletionLines), language, shikiTheme),
]);
const additionLines = await highlightLines(
joinPatchLines(file.additionLines),
language,
shikiTheme,
);
await waitForNextFrame();
const deletionLines = await highlightLines(
joinPatchLines(file.deletionLines),
language,
shikiTheme,
);
await waitForNextFrame();
const highlighted = { additionLines, deletionLines };
const highlighted = applyWordAltDiffHighlightsToFile(file, { additionLines, deletionLines });
if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
resolvedHighlightCache.set(cacheKey, highlighted);
storeResolvedHighlightedFile(cacheKey, highlighted);
}
logReviewHighlighterDiagnostic("file highlight complete", {
fileId: file.id,
filePath: file.path,
theme,
language,
highlightedAdditionLineCount: highlighted.additionLines.length,
highlightedDeletionLineCount: highlighted.deletionLines.length,
durationMs: Date.now() - startedAt,
});
return highlighted;
})();
if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
highlightCache.set(cacheKey, promise);
}
return promise;
return promise.finally(() => {
if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
highlightCache.delete(cacheKey);
}
});
}
export async function highlightReviewSelectedLines(input: {
@@ -483,5 +745,8 @@ export async function highlightReviewSelectedLines(input: {
additionIndex += 1;
});
return tokenMap;
return applyWordAltDiffHighlightsToSelectedLines({
lines: input.lines,
tokenMap,
});
}
+1
View File
@@ -66,6 +66,7 @@
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"clsx": "^2.1.1",
"diff": "8.0.3",
"effect": "catalog:",
"expo": "~55.0.14",
"expo-camera": "~55.0.15",