Add mobile review profiling and syntax highlight debug tools
- Add a debug diff scratch route with fixture-driven highlighting - Wrap review screen in a shared highlighter provider - Document profiling steps and add a Hermes profiling script
This commit is contained in:
1 parent
e27b561b84
commit
da56bd50d9
23 files changed
+10954
-532
No files matched your search
@@ -0,0 +1,80 @@
|
||||
# Review Screen Profiling
|
||||
|
||||
Use this when the mobile review screen is slow or crashes while opening large diffs.
|
||||
|
||||
## Preferred Capture: React Native DevTools Performance
|
||||
|
||||
This app is on Expo SDK 55 / React Native 0.83 with Hermes, so the best first trace is the React Native DevTools Performance recording. The review screen also emits `t3.review.*` user timing marks in development builds so the trace can show parse, list-building, row indexing, and syntax-highlighting work.
|
||||
|
||||
1. Start the development client:
|
||||
|
||||
```sh
|
||||
cd apps/mobile
|
||||
bun dev:client
|
||||
```
|
||||
|
||||
2. Open the app in the iOS Simulator or on the device using the development client.
|
||||
|
||||
3. In the terminal running Expo, press `j` to open React Native DevTools.
|
||||
|
||||
4. In DevTools, open the `Performance` panel.
|
||||
|
||||
5. Start recording.
|
||||
|
||||
6. In the app, reproduce the slow path:
|
||||
- Navigate to the thread.
|
||||
- Open `Files Changed`.
|
||||
- Select the largest review source.
|
||||
- Expand a few large files or tap `Load diff`.
|
||||
- Scroll until the app is clearly slow or until just before it crashes.
|
||||
|
||||
7. Stop recording.
|
||||
|
||||
8. Export or save the Performance recording as a JSON trace.
|
||||
|
||||
Send that exported trace file here. Also include the device/simulator model and whether it was iOS or Android.
|
||||
|
||||
## Android Fallback: Hermes Sampling Profile
|
||||
|
||||
Use this if the app crashes before DevTools can export a trace, or if we need deeper JavaScript stack samples.
|
||||
|
||||
1. Run Android dev client:
|
||||
|
||||
```sh
|
||||
cd apps/mobile
|
||||
bun android:dev
|
||||
bun dev:client
|
||||
```
|
||||
|
||||
2. Open the developer menu from the Expo terminal with `d`.
|
||||
|
||||
3. Select `Enable Sampling Profiler`.
|
||||
|
||||
4. Reproduce the review-screen slowdown.
|
||||
|
||||
5. Open the developer menu again with `d`.
|
||||
|
||||
6. Select `Disable Sampling Profiler`.
|
||||
|
||||
7. Pull and convert the Hermes profile:
|
||||
|
||||
```sh
|
||||
cd apps/mobile
|
||||
mkdir -p profiles/review
|
||||
bunx react-native profile-hermes profiles/review
|
||||
```
|
||||
|
||||
8. Send the generated Chrome trace/profile file from `apps/mobile/profiles/review`.
|
||||
|
||||
For the development app variant, the Android package is `com.t3tools.t3code.dev`.
|
||||
|
||||
## What To Capture
|
||||
|
||||
For the first trace, do not optimize the repro. We want the slowest realistic case:
|
||||
|
||||
- A diff with many files and large line counts.
|
||||
- At least one `Load diff` action for a suppressed large diff.
|
||||
- One vertical scroll pass after the content appears.
|
||||
- One horizontal scroll of a long file, if that is part of the slowdown.
|
||||
|
||||
If the app crashes, note the last visible action before the crash and attach device logs if available.
|
||||
@@ -30,6 +30,7 @@
|
||||
"config:dev": "APP_VARIANT=development expo config",
|
||||
"config:preview": "APP_VARIANT=preview expo config",
|
||||
"config:prod": "APP_VARIANT=production expo config",
|
||||
"profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",
|
||||
"test": "vitest run",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,964 @@
|
||||
import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";
|
||||
import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";
|
||||
import bashLanguage from "@shikijs/langs/bash";
|
||||
import diffLanguage from "@shikijs/langs/diff";
|
||||
import javascriptLanguage from "@shikijs/langs/javascript";
|
||||
import jsonLanguage from "@shikijs/langs/json";
|
||||
import jsxLanguage from "@shikijs/langs/jsx";
|
||||
import tsxLanguage from "@shikijs/langs/tsx";
|
||||
import typescriptLanguage from "@shikijs/langs/typescript";
|
||||
import yamlLanguage from "@shikijs/langs/yaml";
|
||||
import githubDarkDefault from "@shikijs/themes/github-dark-default";
|
||||
import githubLightDefault from "@shikijs/themes/github-light-default";
|
||||
import Stack from "expo-router/stack";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
useSyncExternalStore,
|
||||
} from "react";
|
||||
import {
|
||||
FlatList,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
Text as NativeText,
|
||||
type ListRenderItemInfo,
|
||||
useColorScheme,
|
||||
useWindowDimensions,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import {
|
||||
debugReviewDiffFixtures,
|
||||
type DebugReviewDiffFixture,
|
||||
type DebugReviewDiffFixtureId,
|
||||
} from "../../features/debug/fixtures/reviewDiffFixtures";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
type DebugHighlightEngine = "native" | "javascript";
|
||||
type DebugDiffChange = "context" | "add" | "delete";
|
||||
type DebugDiffLanguage =
|
||||
| "bash"
|
||||
| "diff"
|
||||
| "javascript"
|
||||
| "json"
|
||||
| "jsx"
|
||||
| "tsx"
|
||||
| "typescript"
|
||||
| "yaml";
|
||||
|
||||
type DebugToken = {
|
||||
readonly content: string;
|
||||
readonly color: string | null;
|
||||
readonly fontStyle: number | null;
|
||||
};
|
||||
|
||||
type DebugDiffFile = {
|
||||
readonly id: string;
|
||||
readonly path: string;
|
||||
readonly language: DebugDiffLanguage;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
};
|
||||
|
||||
type DebugDiffFileHeaderRow = {
|
||||
readonly kind: "file";
|
||||
readonly id: string;
|
||||
readonly fileId: string;
|
||||
readonly filePath: string;
|
||||
readonly language: DebugDiffLanguage;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
};
|
||||
|
||||
type DebugDiffHunkRow = {
|
||||
readonly kind: "hunk";
|
||||
readonly id: string;
|
||||
readonly fileId: string;
|
||||
readonly text: string;
|
||||
};
|
||||
|
||||
type DebugDiffCodeRow = {
|
||||
readonly kind: "line";
|
||||
readonly id: string;
|
||||
readonly fileId: string;
|
||||
readonly change: DebugDiffChange;
|
||||
readonly oldLineNumber: number | null;
|
||||
readonly newLineNumber: number | null;
|
||||
readonly content: string;
|
||||
readonly highlightChunkId: string;
|
||||
readonly indexInHighlightChunk: number;
|
||||
};
|
||||
|
||||
type DebugDiffRow = DebugDiffFileHeaderRow | DebugDiffHunkRow | DebugDiffCodeRow;
|
||||
|
||||
type DebugDiffFileBlock = {
|
||||
readonly file: DebugDiffFileHeaderRow;
|
||||
readonly rows: ReadonlyArray<DebugDiffHunkRow | DebugDiffCodeRow>;
|
||||
};
|
||||
|
||||
type DebugHighlightChunk = {
|
||||
readonly id: string;
|
||||
readonly fileId: string;
|
||||
readonly language: DebugDiffLanguage;
|
||||
readonly rows: ReadonlyArray<DebugDiffCodeRow>;
|
||||
};
|
||||
|
||||
type DebugParsedDiff = {
|
||||
readonly files: ReadonlyArray<DebugDiffFile>;
|
||||
readonly fileBlocks: ReadonlyArray<DebugDiffFileBlock>;
|
||||
readonly rows: ReadonlyArray<DebugDiffRow>;
|
||||
readonly highlightChunks: ReadonlyArray<DebugHighlightChunk>;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
};
|
||||
|
||||
type DebugHighlighterHandle = {
|
||||
readonly engine: DebugHighlightEngine;
|
||||
readonly tokenize: (
|
||||
code: string,
|
||||
options: { readonly lang: DebugDiffLanguage; readonly theme: string },
|
||||
) => ReadonlyArray<ReadonlyArray<DebugToken>>;
|
||||
};
|
||||
|
||||
const DEBUG_HIGHLIGHT_CHUNK_SIZE = 500;
|
||||
const DEBUG_DIFF_ROW_HEIGHT = 28;
|
||||
const DEBUG_CHANGE_BAR_WIDTH = 4;
|
||||
const DEBUG_GUTTER_WIDTH = 58;
|
||||
const DEBUG_STICKY_WIDTH = DEBUG_CHANGE_BAR_WIDTH + DEBUG_GUTTER_WIDTH;
|
||||
const DEBUG_CONTENT_WIDTH = 3_000;
|
||||
const DEBUG_DELETE_STRIPE_COUNT = DEBUG_DIFF_ROW_HEIGHT / 2;
|
||||
const DEBUG_MONO_FONT_FAMILY = "BerkeleyMono-Regular";
|
||||
const DEBUG_THEME_NAME_BY_SCHEME = {
|
||||
dark: "github-dark-default",
|
||||
light: "github-light-default",
|
||||
} as const;
|
||||
|
||||
const DEBUG_LANGUAGES = [
|
||||
bashLanguage,
|
||||
diffLanguage,
|
||||
javascriptLanguage,
|
||||
jsonLanguage,
|
||||
jsxLanguage,
|
||||
tsxLanguage,
|
||||
typescriptLanguage,
|
||||
yamlLanguage,
|
||||
] satisfies Parameters<typeof createHighlighterCore>[0]["langs"];
|
||||
|
||||
let nativeHighlighterPromise: Promise<DebugHighlighterHandle> | null = null;
|
||||
let javascriptHighlighterPromise: Promise<DebugHighlighterHandle> | null = null;
|
||||
|
||||
class DebugTokenStore {
|
||||
private readonly fileVersions = new Map<string, number>();
|
||||
private readonly listenersByFileId = new Map<string, Set<() => void>>();
|
||||
private resetVersion = 0;
|
||||
private readonly tokensByChunkId = new Map<string, ReadonlyArray<ReadonlyArray<DebugToken>>>();
|
||||
|
||||
getFileVersion(fileId: string): string {
|
||||
return `${this.resetVersion}:${this.fileVersions.get(fileId) ?? 0}`;
|
||||
}
|
||||
|
||||
getTokens(chunkId: string): ReadonlyArray<ReadonlyArray<DebugToken>> | null {
|
||||
return this.tokensByChunkId.get(chunkId) ?? null;
|
||||
}
|
||||
|
||||
reset(): void {
|
||||
this.tokensByChunkId.clear();
|
||||
this.fileVersions.clear();
|
||||
this.resetVersion += 1;
|
||||
this.listenersByFileId.forEach((listeners) => {
|
||||
listeners.forEach((listener) => listener());
|
||||
});
|
||||
}
|
||||
|
||||
setChunk(chunk: DebugHighlightChunk, tokens: ReadonlyArray<ReadonlyArray<DebugToken>>): void {
|
||||
this.tokensByChunkId.set(chunk.id, tokens);
|
||||
this.fileVersions.set(chunk.fileId, (this.fileVersions.get(chunk.fileId) ?? 0) + 1);
|
||||
this.listenersByFileId.get(chunk.fileId)?.forEach((listener) => listener());
|
||||
}
|
||||
|
||||
subscribeFile(fileId: string, listener: () => void): () => void {
|
||||
let listeners = this.listenersByFileId.get(fileId);
|
||||
if (!listeners) {
|
||||
listeners = new Set();
|
||||
this.listenersByFileId.set(fileId, listeners);
|
||||
}
|
||||
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners?.delete(listener);
|
||||
if (listeners?.size === 0) {
|
||||
this.listenersByFileId.delete(fileId);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function waitForNextFrame(): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
function normalizeTokens(
|
||||
tokenLines: ReadonlyArray<ReadonlyArray<{ content: string; color?: string; fontStyle?: number }>>,
|
||||
): ReadonlyArray<ReadonlyArray<DebugToken>> {
|
||||
return tokenLines.map((line) =>
|
||||
line.map((token) => ({
|
||||
content: token.content,
|
||||
color: token.color ?? null,
|
||||
fontStyle: token.fontStyle ?? null,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
async function createNativeDebugHighlighter(): Promise<DebugHighlighterHandle> {
|
||||
const nativeEngineModule = await import("react-native-shiki-engine");
|
||||
if (!nativeEngineModule.isNativeEngineAvailable()) {
|
||||
throw new Error("Native Shiki engine is not available in this build.");
|
||||
}
|
||||
|
||||
const highlighter = await createHighlighterCore({
|
||||
langs: DEBUG_LANGUAGES,
|
||||
themes: [githubLightDefault, githubDarkDefault],
|
||||
engine: nativeEngineModule.createNativeEngine(),
|
||||
});
|
||||
|
||||
return {
|
||||
engine: "native",
|
||||
tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),
|
||||
};
|
||||
}
|
||||
|
||||
async function createJavascriptDebugHighlighter(): Promise<DebugHighlighterHandle> {
|
||||
const highlighter: HighlighterCore = await createHighlighterCore({
|
||||
langs: DEBUG_LANGUAGES,
|
||||
themes: [githubLightDefault, githubDarkDefault],
|
||||
engine: createJavaScriptRegexEngine(),
|
||||
});
|
||||
|
||||
return {
|
||||
engine: "javascript",
|
||||
tokenize: (code, options) => normalizeTokens(highlighter.codeToTokensBase(code, options)),
|
||||
};
|
||||
}
|
||||
|
||||
async function getDebugHighlighter(engine: DebugHighlightEngine): Promise<DebugHighlighterHandle> {
|
||||
if (engine === "native") {
|
||||
nativeHighlighterPromise ??= createNativeDebugHighlighter();
|
||||
return nativeHighlighterPromise;
|
||||
}
|
||||
|
||||
javascriptHighlighterPromise ??= createJavascriptDebugHighlighter();
|
||||
return javascriptHighlighterPromise;
|
||||
}
|
||||
|
||||
function getDiffPathFromHeader(line: string): string {
|
||||
const match = line.match(/^diff --git a\/(.+) b\/(.+)$/);
|
||||
return match?.[2] ?? line.replace(/^diff --git /, "");
|
||||
}
|
||||
|
||||
function getLanguageForPath(filePath: string): DebugDiffLanguage {
|
||||
const normalizedPath = filePath.toLowerCase();
|
||||
if (normalizedPath.endsWith(".tsx")) return "tsx";
|
||||
if (normalizedPath.endsWith(".ts")) return "typescript";
|
||||
if (normalizedPath.endsWith(".jsx")) return "jsx";
|
||||
if (normalizedPath.endsWith(".js") || normalizedPath.endsWith(".cjs")) return "javascript";
|
||||
if (normalizedPath.endsWith(".json") || normalizedPath.endsWith(".jsonc")) return "json";
|
||||
if (normalizedPath.endsWith(".yml") || normalizedPath.endsWith(".yaml")) return "yaml";
|
||||
if (
|
||||
normalizedPath.endsWith(".sh") ||
|
||||
normalizedPath.includes("/bin/") ||
|
||||
normalizedPath.includes("shell")
|
||||
) {
|
||||
return "bash";
|
||||
}
|
||||
return "diff";
|
||||
}
|
||||
|
||||
function parseHunkLineNumbers(line: string): { oldLine: number; newLine: number } | null {
|
||||
const match = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
oldLine: Number(match[1]),
|
||||
newLine: Number(match[2]),
|
||||
};
|
||||
}
|
||||
|
||||
function makeChunkId(fileId: string, chunkIndex: number): string {
|
||||
return `${fileId}:chunk:${chunkIndex}`;
|
||||
}
|
||||
|
||||
function parseDebugDiffFixture(fixture: DebugReviewDiffFixture): DebugParsedDiff {
|
||||
const startedAt = performance.now();
|
||||
const rows: DebugDiffRow[] = [];
|
||||
const files = new Map<
|
||||
string,
|
||||
{ path: string; language: DebugDiffLanguage; additions: number; deletions: number }
|
||||
>();
|
||||
const fileLineRows = new Map<string, DebugDiffCodeRow[]>();
|
||||
const rawLines = fixture.diff.split(/\r?\n/);
|
||||
|
||||
let currentFileId: string | null = null;
|
||||
let currentOldLine: number | null = null;
|
||||
let currentNewLine: number | null = null;
|
||||
|
||||
function ensureCurrentFile(filePath: string): string {
|
||||
const fileId = `file:${files.size}:${filePath}`;
|
||||
files.set(fileId, {
|
||||
path: filePath,
|
||||
language: getLanguageForPath(filePath),
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
});
|
||||
fileLineRows.set(fileId, []);
|
||||
rows.push({
|
||||
kind: "file",
|
||||
id: `${fileId}:header`,
|
||||
fileId,
|
||||
filePath,
|
||||
language: getLanguageForPath(filePath),
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
});
|
||||
return fileId;
|
||||
}
|
||||
|
||||
for (let index = 0; index < rawLines.length; index += 1) {
|
||||
const rawLine = rawLines[index] ?? "";
|
||||
if (rawLine.startsWith("diff --git ")) {
|
||||
currentFileId = ensureCurrentFile(getDiffPathFromHeader(rawLine));
|
||||
currentOldLine = null;
|
||||
currentNewLine = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!currentFileId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (rawLine.startsWith("@@ ")) {
|
||||
const parsedLineNumbers = parseHunkLineNumbers(rawLine);
|
||||
currentOldLine = parsedLineNumbers?.oldLine ?? null;
|
||||
currentNewLine = parsedLineNumbers?.newLine ?? null;
|
||||
rows.push({
|
||||
kind: "hunk",
|
||||
id: `${currentFileId}:hunk:${index}`,
|
||||
fileId: currentFileId,
|
||||
text: rawLine,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (rawLine.startsWith("+++") || rawLine.startsWith("---")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const marker = rawLine[0];
|
||||
if (marker !== " " && marker !== "+" && marker !== "-") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const file = files.get(currentFileId);
|
||||
if (!file) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const change: DebugDiffChange = marker === "+" ? "add" : marker === "-" ? "delete" : "context";
|
||||
const oldLineNumber = change === "add" ? null : currentOldLine;
|
||||
const newLineNumber = change === "delete" ? null : currentNewLine;
|
||||
const lineRows = fileLineRows.get(currentFileId) ?? [];
|
||||
const chunkIndex = Math.floor(lineRows.length / DEBUG_HIGHLIGHT_CHUNK_SIZE);
|
||||
const codeRow: DebugDiffCodeRow = {
|
||||
kind: "line",
|
||||
id: `${currentFileId}:line:${index}`,
|
||||
fileId: currentFileId,
|
||||
change,
|
||||
oldLineNumber,
|
||||
newLineNumber,
|
||||
content: rawLine.slice(1),
|
||||
highlightChunkId: makeChunkId(currentFileId, chunkIndex),
|
||||
indexInHighlightChunk: lineRows.length % DEBUG_HIGHLIGHT_CHUNK_SIZE,
|
||||
};
|
||||
|
||||
rows.push(codeRow);
|
||||
lineRows.push(codeRow);
|
||||
fileLineRows.set(currentFileId, lineRows);
|
||||
|
||||
if (change === "add") {
|
||||
files.set(currentFileId, { ...file, additions: file.additions + 1 });
|
||||
currentNewLine = currentNewLine === null ? null : currentNewLine + 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (change === "delete") {
|
||||
files.set(currentFileId, { ...file, deletions: file.deletions + 1 });
|
||||
currentOldLine = currentOldLine === null ? null : currentOldLine + 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
currentOldLine = currentOldLine === null ? null : currentOldLine + 1;
|
||||
currentNewLine = currentNewLine === null ? null : currentNewLine + 1;
|
||||
}
|
||||
|
||||
const fileSummaries = Array.from(files, ([id, file]) => ({ id, ...file }));
|
||||
const fileSummaryById = new Map(fileSummaries.map((file) => [file.id, file]));
|
||||
const rowsWithFileStats = rows.map((row): DebugDiffRow => {
|
||||
if (row.kind !== "file") {
|
||||
return row;
|
||||
}
|
||||
const file = fileSummaryById.get(row.fileId);
|
||||
return {
|
||||
kind: row.kind,
|
||||
id: row.id,
|
||||
fileId: row.fileId,
|
||||
filePath: row.filePath,
|
||||
language: row.language,
|
||||
additions: file?.additions ?? row.additions,
|
||||
deletions: file?.deletions ?? row.deletions,
|
||||
};
|
||||
});
|
||||
const fileBlocksById = new Map<
|
||||
string,
|
||||
{ file: DebugDiffFileHeaderRow; rows: Array<DebugDiffHunkRow | DebugDiffCodeRow> }
|
||||
>();
|
||||
for (const row of rowsWithFileStats) {
|
||||
if (row.kind === "file") {
|
||||
fileBlocksById.set(row.fileId, { file: row, rows: [] });
|
||||
continue;
|
||||
}
|
||||
|
||||
fileBlocksById.get(row.fileId)?.rows.push(row);
|
||||
}
|
||||
const fileBlocks: DebugDiffFileBlock[] = Array.from(fileBlocksById.values());
|
||||
|
||||
const highlightChunks: DebugHighlightChunk[] = [];
|
||||
fileLineRows.forEach((lineRows, fileId) => {
|
||||
const file = fileSummaryById.get(fileId);
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
for (
|
||||
let startIndex = 0;
|
||||
startIndex < lineRows.length;
|
||||
startIndex += DEBUG_HIGHLIGHT_CHUNK_SIZE
|
||||
) {
|
||||
const chunkIndex = startIndex / DEBUG_HIGHLIGHT_CHUNK_SIZE;
|
||||
highlightChunks.push({
|
||||
id: makeChunkId(fileId, chunkIndex),
|
||||
fileId,
|
||||
language: file.language,
|
||||
rows: lineRows.slice(startIndex, startIndex + DEBUG_HIGHLIGHT_CHUNK_SIZE),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const parsed = {
|
||||
files: fileSummaries,
|
||||
fileBlocks,
|
||||
rows: rowsWithFileStats,
|
||||
highlightChunks,
|
||||
additions: fileSummaries.reduce((total, file) => total + file.additions, 0),
|
||||
deletions: fileSummaries.reduce((total, file) => total + file.deletions, 0),
|
||||
};
|
||||
|
||||
console.log("[debug-diff-scratch] parse", {
|
||||
durationMs: Math.round(performance.now() - startedAt),
|
||||
fixture: fixture.id,
|
||||
files: parsed.files.length,
|
||||
highlightChunks: parsed.highlightChunks.length,
|
||||
rows: parsed.rows.length,
|
||||
});
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
const TokenText = memo(function TokenText(props: {
|
||||
readonly content: string;
|
||||
readonly tokens: ReadonlyArray<DebugToken> | null;
|
||||
}) {
|
||||
if (!props.tokens) {
|
||||
return (
|
||||
<NativeText
|
||||
numberOfLines={1}
|
||||
className="text-[13px] font-medium leading-[18px] text-foreground"
|
||||
style={{ fontFamily: DEBUG_MONO_FONT_FAMILY }}
|
||||
>
|
||||
{props.content || " "}
|
||||
</NativeText>
|
||||
);
|
||||
}
|
||||
|
||||
let tokenOffset = 0;
|
||||
|
||||
return (
|
||||
<NativeText
|
||||
numberOfLines={1}
|
||||
className="text-[13px] font-medium leading-[18px] text-foreground"
|
||||
style={{ fontFamily: DEBUG_MONO_FONT_FAMILY }}
|
||||
>
|
||||
{props.tokens.map((token) => {
|
||||
const tokenKey = `${tokenOffset}:${token.content.length}:${token.color ?? ""}:${token.fontStyle ?? ""}`;
|
||||
tokenOffset += token.content.length;
|
||||
const fontWeight =
|
||||
token.fontStyle !== null && (token.fontStyle & 2) === 2
|
||||
? ("700" as const)
|
||||
: ("500" as const);
|
||||
const fontStyle =
|
||||
token.fontStyle !== null && (token.fontStyle & 1) === 1
|
||||
? ("italic" as const)
|
||||
: ("normal" as const);
|
||||
|
||||
return (
|
||||
<NativeText
|
||||
key={tokenKey}
|
||||
style={{
|
||||
color: token.color ?? undefined,
|
||||
fontFamily: DEBUG_MONO_FONT_FAMILY,
|
||||
fontStyle,
|
||||
fontWeight,
|
||||
}}
|
||||
>
|
||||
{token.content}
|
||||
</NativeText>
|
||||
);
|
||||
})}
|
||||
</NativeText>
|
||||
);
|
||||
});
|
||||
|
||||
function changeRowClassName(change: DebugDiffChange): string {
|
||||
if (change === "add") return "bg-emerald-500/10";
|
||||
if (change === "delete") return "bg-rose-500/10";
|
||||
return "bg-card";
|
||||
}
|
||||
|
||||
function DebugChangeBar(props: { readonly change: DebugDiffChange }) {
|
||||
if (props.change === "delete") {
|
||||
return (
|
||||
<View className="overflow-hidden" style={{ width: DEBUG_CHANGE_BAR_WIDTH }}>
|
||||
{Array.from({ length: DEBUG_DELETE_STRIPE_COUNT }, (_, index) => (
|
||||
<View key={index}>
|
||||
<View className="bg-rose-400" style={{ height: 1, width: DEBUG_CHANGE_BAR_WIDTH }} />
|
||||
<View style={{ height: 1, width: DEBUG_CHANGE_BAR_WIDTH }} />
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.change === "add") {
|
||||
return <View className="bg-emerald-400" style={{ width: DEBUG_CHANGE_BAR_WIDTH }} />;
|
||||
}
|
||||
|
||||
return <View style={{ width: DEBUG_CHANGE_BAR_WIDTH }} />;
|
||||
}
|
||||
|
||||
function DebugDiffFileHeader(props: {
|
||||
readonly header: DebugDiffFileHeaderRow;
|
||||
readonly width: number;
|
||||
}) {
|
||||
return (
|
||||
<View
|
||||
className="flex-row items-center border-b border-border bg-card px-3"
|
||||
style={{ height: DEBUG_DIFF_ROW_HEIGHT, width: props.width }}
|
||||
>
|
||||
<Text className="min-w-0 flex-1 text-[13px] font-t3-bold text-foreground" numberOfLines={1}>
|
||||
{props.header.filePath}
|
||||
</Text>
|
||||
<Text className="ml-2 text-[12px] font-t3-bold text-rose-500">-{props.header.deletions}</Text>
|
||||
<Text className="ml-2 text-[12px] font-t3-bold text-emerald-500">
|
||||
+{props.header.additions}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function DebugDiffStickyCell(props: { readonly item: DebugDiffHunkRow | DebugDiffCodeRow }) {
|
||||
if (props.item.kind === "hunk") {
|
||||
return (
|
||||
<View
|
||||
className="border-b border-sky-500/10 bg-sky-500/12"
|
||||
style={{ height: DEBUG_DIFF_ROW_HEIGHT, width: DEBUG_STICKY_WIDTH }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const displayLineNumber = props.item.newLineNumber ?? props.item.oldLineNumber ?? "";
|
||||
|
||||
return (
|
||||
<View
|
||||
className={cn("flex-row", changeRowClassName(props.item.change))}
|
||||
style={{ height: DEBUG_DIFF_ROW_HEIGHT, width: DEBUG_STICKY_WIDTH }}
|
||||
>
|
||||
<DebugChangeBar change={props.item.change} />
|
||||
<View className="items-end justify-center pr-2" style={{ width: DEBUG_GUTTER_WIDTH }}>
|
||||
<Text className="font-mono text-[11px] text-foreground-muted">{displayLineNumber}</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function DebugDiffCodeCell(props: {
|
||||
readonly item: DebugDiffHunkRow | DebugDiffCodeRow;
|
||||
readonly tokens: ReadonlyArray<DebugToken> | null;
|
||||
}) {
|
||||
const { item } = props;
|
||||
|
||||
if (item.kind === "hunk") {
|
||||
return (
|
||||
<View
|
||||
className="justify-center border-b border-sky-500/10 bg-sky-500/12 px-2"
|
||||
style={{ height: DEBUG_DIFF_ROW_HEIGHT, width: DEBUG_CONTENT_WIDTH }}
|
||||
>
|
||||
<NativeText
|
||||
numberOfLines={1}
|
||||
className="text-[13px] font-medium leading-[18px] text-sky-700 dark:text-sky-300"
|
||||
style={{ fontFamily: DEBUG_MONO_FONT_FAMILY }}
|
||||
>
|
||||
{item.text}
|
||||
</NativeText>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View
|
||||
className={cn("justify-center px-2", changeRowClassName(item.change))}
|
||||
style={{ height: DEBUG_DIFF_ROW_HEIGHT, width: DEBUG_CONTENT_WIDTH }}
|
||||
>
|
||||
<TokenText content={item.content} tokens={props.tokens} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const DebugDiffFileBlockView = memo(function DebugDiffFileBlockView(props: {
|
||||
readonly block: DebugDiffFileBlock;
|
||||
readonly tokenStore: DebugTokenStore;
|
||||
readonly width: number;
|
||||
}) {
|
||||
const viewportWidth = Math.max(0, props.width - DEBUG_STICKY_WIDTH);
|
||||
useSyncExternalStore(
|
||||
useCallback(
|
||||
(listener) => props.tokenStore.subscribeFile(props.block.file.fileId, listener),
|
||||
[props.block.file.fileId, props.tokenStore],
|
||||
),
|
||||
useCallback(
|
||||
() => props.tokenStore.getFileVersion(props.block.file.fileId),
|
||||
[props.block.file.fileId, props.tokenStore],
|
||||
),
|
||||
useCallback(
|
||||
() => props.tokenStore.getFileVersion(props.block.file.fileId),
|
||||
[props.block.file.fileId, props.tokenStore],
|
||||
),
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={{ width: props.width }}>
|
||||
<DebugDiffFileHeader header={props.block.file} width={props.width} />
|
||||
<View
|
||||
className="flex-row"
|
||||
style={{
|
||||
height: props.block.rows.length * DEBUG_DIFF_ROW_HEIGHT,
|
||||
width: props.width,
|
||||
}}
|
||||
>
|
||||
<View style={{ width: DEBUG_STICKY_WIDTH }}>
|
||||
{props.block.rows.map((row) => (
|
||||
<DebugDiffStickyCell key={row.id} item={row} />
|
||||
))}
|
||||
</View>
|
||||
<ScrollView
|
||||
horizontal
|
||||
bounces={false}
|
||||
directionalLockEnabled
|
||||
keyboardShouldPersistTaps="handled"
|
||||
showsHorizontalScrollIndicator
|
||||
style={{
|
||||
height: props.block.rows.length * DEBUG_DIFF_ROW_HEIGHT,
|
||||
width: viewportWidth,
|
||||
}}
|
||||
>
|
||||
<View style={{ width: DEBUG_CONTENT_WIDTH }}>
|
||||
{props.block.rows.map((row) => (
|
||||
<DebugDiffCodeCell
|
||||
key={row.id}
|
||||
item={row}
|
||||
tokens={
|
||||
row.kind === "line"
|
||||
? (props.tokenStore.getTokens(row.highlightChunkId)?.[
|
||||
row.indexInHighlightChunk
|
||||
] ?? null)
|
||||
: null
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</ScrollView>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
function EngineToggle(props: {
|
||||
readonly engine: DebugHighlightEngine;
|
||||
readonly onChangeEngine: (engine: DebugHighlightEngine) => void;
|
||||
}) {
|
||||
return (
|
||||
<View className="flex-row rounded-full bg-subtle p-1">
|
||||
{(["native", "javascript"] as const).map((engine) => {
|
||||
const selected = props.engine === engine;
|
||||
return (
|
||||
<Pressable
|
||||
key={engine}
|
||||
className={cn("rounded-full px-3 py-1.5", selected && "bg-card")}
|
||||
onPress={() => props.onChangeEngine(engine)}
|
||||
>
|
||||
<Text
|
||||
className={cn(
|
||||
"text-[12px] font-t3-bold",
|
||||
selected ? "text-foreground" : "text-foreground-muted",
|
||||
)}
|
||||
>
|
||||
{engine === "javascript" ? "JS" : "Native"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function FixtureToggle(props: {
|
||||
readonly fixtureId: DebugReviewDiffFixtureId;
|
||||
readonly onChangeFixture: (fixtureId: DebugReviewDiffFixtureId) => void;
|
||||
}) {
|
||||
return (
|
||||
<ScrollView horizontal showsHorizontalScrollIndicator={false}>
|
||||
<View className="flex-row gap-2">
|
||||
{debugReviewDiffFixtures.map((fixture) => {
|
||||
const selected = props.fixtureId === fixture.id;
|
||||
return (
|
||||
<Pressable
|
||||
key={fixture.id}
|
||||
className={cn(
|
||||
"rounded-full border border-border px-3 py-1.5",
|
||||
selected ? "bg-foreground" : "bg-card",
|
||||
)}
|
||||
onPress={() => props.onChangeFixture(fixture.id)}
|
||||
>
|
||||
<Text
|
||||
className={cn(
|
||||
"text-[12px] font-t3-bold",
|
||||
selected ? "text-sheet" : "text-foreground",
|
||||
)}
|
||||
>
|
||||
{fixture.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
export default function SyntaxHighlightDebugRoute() {
|
||||
const insets = useSafeAreaInsets();
|
||||
const { width } = useWindowDimensions();
|
||||
const colorScheme = useColorScheme();
|
||||
const headerIcon = String(useThemeColor("--color-icon"));
|
||||
const themeName = DEBUG_THEME_NAME_BY_SCHEME[colorScheme === "dark" ? "dark" : "light"];
|
||||
const [engine, setEngine] = useState<DebugHighlightEngine>("native");
|
||||
const [fixtureId, setFixtureId] = useState<DebugReviewDiffFixtureId>("small");
|
||||
const [status, setStatus] = useState("Idle");
|
||||
const renderStartRef = useRef<number | null>(null);
|
||||
const generationRef = useRef(0);
|
||||
const tokenStore = useMemo(() => new DebugTokenStore(), []);
|
||||
|
||||
const fixture = useMemo(
|
||||
() =>
|
||||
debugReviewDiffFixtures.find((candidate) => candidate.id === fixtureId) ??
|
||||
debugReviewDiffFixtures[0],
|
||||
[fixtureId],
|
||||
);
|
||||
const parsedDiff = useMemo(() => parseDebugDiffFixture(fixture), [fixture]);
|
||||
const fileBlockOffsets = useMemo(() => {
|
||||
let offset = 0;
|
||||
return parsedDiff.fileBlocks.map((block, index) => {
|
||||
const length = DEBUG_DIFF_ROW_HEIGHT * (block.rows.length + 1);
|
||||
const itemLayout = { index, length, offset };
|
||||
offset += length;
|
||||
return itemLayout;
|
||||
});
|
||||
}, [parsedDiff.fileBlocks]);
|
||||
|
||||
useEffect(() => {
|
||||
const generation = generationRef.current + 1;
|
||||
generationRef.current = generation;
|
||||
renderStartRef.current = performance.now();
|
||||
tokenStore.reset();
|
||||
setStatus("Initializing highlighter");
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const highlighterStartedAt = performance.now();
|
||||
const highlighter = await getDebugHighlighter(engine);
|
||||
if (generation !== generationRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("[debug-diff-scratch] initialize", {
|
||||
durationMs: Math.round(performance.now() - highlighterStartedAt),
|
||||
engine: highlighter.engine,
|
||||
});
|
||||
|
||||
let firstChunkMs: number | null = null;
|
||||
const totalStartedAt = performance.now();
|
||||
setStatus(`Streaming ${parsedDiff.highlightChunks.length.toLocaleString()} chunks`);
|
||||
|
||||
for (let chunkIndex = 0; chunkIndex < parsedDiff.highlightChunks.length; chunkIndex += 1) {
|
||||
if (generation !== generationRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const chunk = parsedDiff.highlightChunks[chunkIndex];
|
||||
if (!chunk) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const chunkCode = chunk.rows.map((line) => line.content).join("\n");
|
||||
const chunkStartedAt = performance.now();
|
||||
const chunkTokens = highlighter.tokenize(chunkCode, {
|
||||
lang: chunk.language,
|
||||
theme: themeName,
|
||||
});
|
||||
const chunkMs = performance.now() - chunkStartedAt;
|
||||
|
||||
if (firstChunkMs === null) {
|
||||
firstChunkMs = performance.now() - totalStartedAt;
|
||||
console.log("[debug-diff-scratch] first chunk", {
|
||||
durationMs: Math.round(firstChunkMs),
|
||||
engine,
|
||||
fixture: fixture.id,
|
||||
language: chunk.language,
|
||||
lineCount: chunkTokens.length,
|
||||
});
|
||||
}
|
||||
|
||||
tokenStore.setChunk(chunk, chunkTokens);
|
||||
|
||||
console.log("[debug-diff-scratch] chunk", {
|
||||
chunkIndex,
|
||||
chunkMs: Math.round(chunkMs),
|
||||
engine,
|
||||
fixture: fixture.id,
|
||||
language: chunk.language,
|
||||
lineCount: chunkTokens.length,
|
||||
});
|
||||
|
||||
await waitForNextFrame();
|
||||
}
|
||||
|
||||
console.log("[debug-diff-scratch] complete", {
|
||||
durationMs: Math.round(performance.now() - totalStartedAt),
|
||||
engine,
|
||||
fixture: fixture.id,
|
||||
rows: parsedDiff.rows.length,
|
||||
});
|
||||
setStatus(`Complete with ${engine}`);
|
||||
} catch (error) {
|
||||
console.error("[debug-diff-scratch] failed", {
|
||||
engine,
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
setStatus(error instanceof Error ? error.message : "Highlight failed");
|
||||
}
|
||||
})();
|
||||
}, [
|
||||
engine,
|
||||
fixture.id,
|
||||
parsedDiff.highlightChunks,
|
||||
parsedDiff.rows.length,
|
||||
themeName,
|
||||
tokenStore,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (renderStartRef.current === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const startedAt = renderStartRef.current;
|
||||
renderStartRef.current = null;
|
||||
const commitMs = performance.now() - startedAt;
|
||||
requestAnimationFrame(() => {
|
||||
console.log("[debug-diff-scratch] render", {
|
||||
commitMs: Math.round(commitMs),
|
||||
paintMs: Math.round(performance.now() - startedAt),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const renderItem = useCallback(
|
||||
({ item }: ListRenderItemInfo<DebugDiffFileBlock>) => (
|
||||
<DebugDiffFileBlockView block={item} tokenStore={tokenStore} width={width} />
|
||||
),
|
||||
[tokenStore, width],
|
||||
);
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
<Stack.Screen
|
||||
options={{
|
||||
headerShown: true,
|
||||
headerTitle: "Diff Scratch",
|
||||
headerTintColor: headerIcon,
|
||||
headerTransparent: true,
|
||||
headerShadowVisible: false,
|
||||
}}
|
||||
/>
|
||||
|
||||
<View
|
||||
className="gap-3 border-b border-border bg-sheet px-3 pb-3"
|
||||
style={{ paddingTop: insets.top + 56 }}
|
||||
>
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text className="text-[13px] font-t3-bold text-foreground">Diff streaming scratch</Text>
|
||||
<Text className="text-[11px] text-foreground-muted" numberOfLines={1}>
|
||||
{fixture.label} · {parsedDiff.files.length} files · {parsedDiff.rows.length} rows ·{" "}
|
||||
{status}
|
||||
</Text>
|
||||
</View>
|
||||
<EngineToggle engine={engine} onChangeEngine={setEngine} />
|
||||
</View>
|
||||
<FixtureToggle fixtureId={fixtureId} onChangeFixture={setFixtureId} />
|
||||
</View>
|
||||
|
||||
<FlatList
|
||||
style={{ flex: 1, width }}
|
||||
data={parsedDiff.fileBlocks}
|
||||
renderItem={renderItem}
|
||||
keyExtractor={(item) => item.file.id}
|
||||
getItemLayout={(_, index) => ({
|
||||
length: fileBlockOffsets[index]?.length ?? DEBUG_DIFF_ROW_HEIGHT,
|
||||
offset: fileBlockOffsets[index]?.offset ?? 0,
|
||||
index,
|
||||
})}
|
||||
initialNumToRender={2}
|
||||
maxToRenderPerBatch={3}
|
||||
updateCellsBatchingPeriod={32}
|
||||
windowSize={5}
|
||||
keyboardShouldPersistTaps="handled"
|
||||
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -43,28 +43,50 @@ export default function HomeRouteScreen() {
|
||||
headerTintColor: iconColor,
|
||||
headerTitle: "",
|
||||
headerRight: () => (
|
||||
<Pressable
|
||||
onPress={() => router.push("/connections")}
|
||||
hitSlop={8}
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 8,
|
||||
paddingHorizontal: 4,
|
||||
paddingVertical: 4,
|
||||
}}
|
||||
>
|
||||
<ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />
|
||||
<RNText
|
||||
<View style={{ flexDirection: "row", alignItems: "center", gap: 12 }}>
|
||||
<Pressable
|
||||
onPress={() => router.push("/debug/syntax-highlight")}
|
||||
hitSlop={8}
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 12,
|
||||
color: secondaryFg,
|
||||
borderRadius: 999,
|
||||
backgroundColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)",
|
||||
paddingHorizontal: 10,
|
||||
paddingVertical: 5,
|
||||
}}
|
||||
>
|
||||
{CONNECTION_LABEL[connectionState]}
|
||||
</RNText>
|
||||
</Pressable>
|
||||
<RNText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 12,
|
||||
color: secondaryFg,
|
||||
}}
|
||||
>
|
||||
Debug
|
||||
</RNText>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
onPress={() => router.push("/connections")}
|
||||
hitSlop={8}
|
||||
style={{
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 8,
|
||||
paddingHorizontal: 4,
|
||||
paddingVertical: 4,
|
||||
}}
|
||||
>
|
||||
<ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />
|
||||
<RNText
|
||||
style={{
|
||||
fontFamily: "DMSans_700Bold",
|
||||
fontSize: 12,
|
||||
color: secondaryFg,
|
||||
}}
|
||||
>
|
||||
{CONNECTION_LABEL[connectionState]}
|
||||
</RNText>
|
||||
</Pressable>
|
||||
</View>
|
||||
),
|
||||
headerSearchBarOptions: {
|
||||
placeholder: "Search threads",
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";
|
||||
import { ReviewSheet } from "../../../../features/review/ReviewSheet";
|
||||
|
||||
export default function ReviewRoute() {
|
||||
return <ReviewSheet />;
|
||||
return (
|
||||
<ReviewHighlighterProvider>
|
||||
<ReviewSheet />
|
||||
</ReviewHighlighterProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
# Debug Fixtures
|
||||
|
||||
These patch fixtures snapshot review-rendering worktree diffs used to develop
|
||||
the scratch review renderer. Keep them deterministic so the debug route can test
|
||||
parsing, chunked syntax highlighting, and virtualization without depending on
|
||||
the current repo state.
|
||||
|
||||
- `review-small.diff`: 155 lines, narrow model/rendering changes.
|
||||
- `review-medium.diff`: 1,955 lines, review screen and highlighter changes.
|
||||
- `review-large.diff`: 3,208 lines, broad current worktree snapshot excluding
|
||||
this fixture directory.
|
||||
- `current-working-review.diff`: alias of `review-large.diff` for quick loading
|
||||
while iterating.
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,155 @@
|
||||
diff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx
|
||||
index d61924a62..3f2ae0160 100644
|
||||
--- a/apps/mobile/src/features/review/reviewDiffRendering.tsx
|
||||
+++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx
|
||||
@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({
|
||||
default: "monospace",
|
||||
});
|
||||
|
||||
+export const REVIEW_DIFF_LINE_HEIGHT = 26;
|
||||
+const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2;
|
||||
+
|
||||
export function renderVisibleWhitespace(value: string): string {
|
||||
const expandedTabs = value.replace(/\t/g, " ");
|
||||
return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\u00A0"));
|
||||
@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string |
|
||||
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 className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>
|
||||
+ <View>
|
||||
+ {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => (
|
||||
+ <View key={index}>
|
||||
+ <View className="w-[5px] bg-rose-400" style={{ height: 1 }} />
|
||||
+ <View style={{ height: 1 }} />
|
||||
+ </View>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo
|
||||
}
|
||||
|
||||
return (
|
||||
- <View className="w-[5px] self-stretch overflow-hidden">
|
||||
+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>
|
||||
<View className={cn("h-full w-[5px] flex-1", changeBarTone(props.change))} />
|
||||
</View>
|
||||
);
|
||||
@@ -63,6 +69,7 @@ export function DiffTokenText(props: {
|
||||
if (!props.tokens || props.tokens.length === 0) {
|
||||
return (
|
||||
<NativeText
|
||||
+ numberOfLines={1}
|
||||
selectable
|
||||
className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}
|
||||
style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
|
||||
@@ -74,6 +81,7 @@ export function DiffTokenText(props: {
|
||||
|
||||
return (
|
||||
<NativeText
|
||||
+ numberOfLines={1}
|
||||
selectable
|
||||
className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}
|
||||
style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
|
||||
diff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts
|
||||
index a24a99ceb..69a6e7261 100644
|
||||
--- a/apps/mobile/src/features/review/reviewModel.test.ts
|
||||
+++ b/apps/mobile/src/features/review/reviewModel.test.ts
|
||||
@@ -238,7 +238,7 @@ describe("buildReviewParsedDiff", () => {
|
||||
});
|
||||
});
|
||||
|
||||
- it("flattens expanded files into virtualizable review items", () => {
|
||||
+ it("flattens expanded file rows into virtualized review items", () => {
|
||||
const file = makeRenderableFile({
|
||||
path: "apps/mobile/src/a.ts",
|
||||
rows: [
|
||||
@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => {
|
||||
|
||||
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] }),
|
||||
+ expect.objectContaining({
|
||||
+ kind: "hunk",
|
||||
+ fileId: file.id,
|
||||
+ file,
|
||||
+ row: file.rows[0],
|
||||
+ }),
|
||||
+ expect.objectContaining({
|
||||
+ kind: "line",
|
||||
+ fileId: file.id,
|
||||
+ file,
|
||||
+ row: file.rows[1],
|
||||
+ lineIndex: 0,
|
||||
+ }),
|
||||
]);
|
||||
});
|
||||
|
||||
diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts
|
||||
index 27e6d7ae4..1cfbf358c 100644
|
||||
--- a/apps/mobile/src/features/review/reviewModel.ts
|
||||
+++ b/apps/mobile/src/features/review/reviewModel.ts
|
||||
@@ -72,6 +72,7 @@ export interface ReviewHunkListItem {
|
||||
readonly kind: "hunk";
|
||||
readonly id: string;
|
||||
readonly fileId: string;
|
||||
+ readonly file: ReviewRenderableFile;
|
||||
readonly row: ReviewRenderableHunkRow;
|
||||
}
|
||||
|
||||
@@ -79,7 +80,9 @@ export interface ReviewLineListItem {
|
||||
readonly kind: "line";
|
||||
readonly id: string;
|
||||
readonly fileId: string;
|
||||
+ readonly file: ReviewRenderableFile;
|
||||
readonly row: ReviewRenderableLineRow;
|
||||
+ readonly lineIndex: number;
|
||||
}
|
||||
|
||||
export type ReviewListItem =
|
||||
@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil
|
||||
}
|
||||
|
||||
// The flattened review list item model is inspired by pierre/diffs' iterator-first
|
||||
-// virtualization architecture, adapted here for React Native and LegendList.
|
||||
+// virtualization architecture, adapted here for React Native virtualization.
|
||||
// Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs
|
||||
// Reference files:
|
||||
// - src/utils/iterateOverDiff.ts
|
||||
@@ -350,12 +353,14 @@ export function buildReviewListItems(input: {
|
||||
}
|
||||
}
|
||||
|
||||
- file.rows.forEach((row) => {
|
||||
+ let lineIndex = 0;
|
||||
+ file.rows.forEach((row, rowIndex) => {
|
||||
if (row.kind === "hunk") {
|
||||
items.push({
|
||||
kind: "hunk",
|
||||
- id: row.id,
|
||||
+ id: `${file.id}:row:${rowIndex}:${row.id}`,
|
||||
fileId: file.id,
|
||||
+ file,
|
||||
row,
|
||||
});
|
||||
return;
|
||||
@@ -363,10 +368,13 @@ export function buildReviewListItems(input: {
|
||||
|
||||
items.push({
|
||||
kind: "line",
|
||||
- id: row.id,
|
||||
+ id: `${file.id}:row:${rowIndex}:${row.id}`,
|
||||
fileId: file.id,
|
||||
+ file,
|
||||
row,
|
||||
+ lineIndex,
|
||||
});
|
||||
+ lineIndex += 1;
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
export type DebugReviewDiffFixtureId = "small" | "medium" | "large" | "current";
|
||||
|
||||
export interface DebugReviewDiffFixture {
|
||||
readonly id: DebugReviewDiffFixtureId;
|
||||
readonly label: string;
|
||||
readonly filename: string;
|
||||
readonly lineCount: number;
|
||||
readonly diff: string;
|
||||
}
|
||||
|
||||
export const debugReviewDiffFixtures: ReadonlyArray<DebugReviewDiffFixture> = [
|
||||
{
|
||||
id: "small",
|
||||
label: "Small",
|
||||
filename: "review-small.diff",
|
||||
lineCount: 155,
|
||||
diff: 'diff --git a/apps/mobile/src/features/review/reviewDiffRendering.tsx b/apps/mobile/src/features/review/reviewDiffRendering.tsx\nindex d61924a62..3f2ae0160 100644\n--- a/apps/mobile/src/features/review/reviewDiffRendering.tsx\n+++ b/apps/mobile/src/features/review/reviewDiffRendering.tsx\n@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({\n default: "monospace",\n });\n \n+export const REVIEW_DIFF_LINE_HEIGHT = 26;\n+const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2;\n+\n export function renderVisibleWhitespace(value: string): string {\n const expandedTabs = value.replace(/\\t/g, " ");\n return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\\u00A0"));\n@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string |\n export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) {\n if (props.change === "delete") {\n return (\n- <View className="w-[5px] self-stretch overflow-hidden">\n- <View className="flex-1 justify-between">\n- {Array.from({ length: 6 }, (_, index) => (\n- <View key={index} className="h-[2px] w-[5px] bg-rose-400" />\n+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>\n+ <View>\n+ {Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => (\n+ <View key={index}>\n+ <View className="w-[5px] bg-rose-400" style={{ height: 1 }} />\n+ <View style={{ height: 1 }} />\n+ </View>\n ))}\n </View>\n </View>\n@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo\n }\n \n return (\n- <View className="w-[5px] self-stretch overflow-hidden">\n+ <View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>\n <View className={cn("h-full w-[5px] flex-1", changeBarTone(props.change))} />\n </View>\n );\n@@ -63,6 +69,7 @@ export function DiffTokenText(props: {\n if (!props.tokens || props.tokens.length === 0) {\n return (\n <NativeText\n+ numberOfLines={1}\n selectable\n className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}\n style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}\n@@ -74,6 +81,7 @@ export function DiffTokenText(props: {\n \n return (\n <NativeText\n+ numberOfLines={1}\n selectable\n className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}\n style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}\ndiff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts\nindex a24a99ceb..69a6e7261 100644\n--- a/apps/mobile/src/features/review/reviewModel.test.ts\n+++ b/apps/mobile/src/features/review/reviewModel.test.ts\n@@ -238,7 +238,7 @@ describe("buildReviewParsedDiff", () => {\n });\n });\n \n- it("flattens expanded files into virtualizable review items", () => {\n+ it("flattens expanded file rows into virtualized review items", () => {\n const file = makeRenderableFile({\n path: "apps/mobile/src/a.ts",\n rows: [\n@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => {\n \n expect(items).toEqual([\n expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }),\n- expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }),\n- expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }),\n+ expect.objectContaining({\n+ kind: "hunk",\n+ fileId: file.id,\n+ file,\n+ row: file.rows[0],\n+ }),\n+ expect.objectContaining({\n+ kind: "line",\n+ fileId: file.id,\n+ file,\n+ row: file.rows[1],\n+ lineIndex: 0,\n+ }),\n ]);\n });\n \ndiff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts\nindex 27e6d7ae4..1cfbf358c 100644\n--- a/apps/mobile/src/features/review/reviewModel.ts\n+++ b/apps/mobile/src/features/review/reviewModel.ts\n@@ -72,6 +72,7 @@ export interface ReviewHunkListItem {\n readonly kind: "hunk";\n readonly id: string;\n readonly fileId: string;\n+ readonly file: ReviewRenderableFile;\n readonly row: ReviewRenderableHunkRow;\n }\n \n@@ -79,7 +80,9 @@ export interface ReviewLineListItem {\n readonly kind: "line";\n readonly id: string;\n readonly fileId: string;\n+ readonly file: ReviewRenderableFile;\n readonly row: ReviewRenderableLineRow;\n+ readonly lineIndex: number;\n }\n \n export type ReviewListItem =\n@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil\n }\n \n // The flattened review list item model is inspired by pierre/diffs\' iterator-first\n-// virtualization architecture, adapted here f
Line truncated
|
||||
},
|
||||
{
|
||||
id: "medium",
|
||||
label: "Medium",
|
||||
filename: "review-medium.diff",
|
||||
lineCount: 1955,
|
||||
diff: 'diff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\nindex 84c48c6ed..ee993ee7c 100644\n--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n@@ -1,5 +1,10 @@\n+import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";\n import { ReviewSheet } from "../../../../features/review/ReviewSheet";\n \n export default function ReviewRoute() {\n- return <ReviewSheet />;\n+ return (\n+ <ReviewHighlighterProvider>\n+ <ReviewSheet />\n+ </ReviewHighlighterProvider>\n+ );\n }\ndiff --git a/apps/mobile/src/features/review/ReviewSheet.tsx b/apps/mobile/src/features/review/ReviewSheet.tsx\nindex 82c28e81e..e148a8da2 100644\n--- a/apps/mobile/src/features/review/ReviewSheet.tsx\n+++ b/apps/mobile/src/features/review/ReviewSheet.tsx\n@@ -1,17 +1,31 @@\n import { EnvironmentId, ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts";\n+import { Gesture, GestureDetector } from "react-native-gesture-handler";\n+import Animated, {\n+ makeMutable,\n+ type SharedValue,\n+ useAnimatedStyle,\n+ useSharedValue,\n+} from "react-native-reanimated";\n import { useLocalSearchParams, useRouter } from "expo-router";\n import Stack from "expo-router/stack";\n import { SymbolView } from "expo-symbols";\n-import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react";\n+import {\n+ memo,\n+ type ReactElement,\n+ useCallback,\n+ useDeferredValue,\n+ useEffect,\n+ useMemo,\n+ useRef,\n+ useState,\n+} from "react";\n import {\n ActivityIndicator,\n FlatList,\n- InteractionManager,\n type ListRenderItemInfo,\n Pressable,\n ScrollView,\n Text as NativeText,\n- type ViewToken,\n useColorScheme,\n useWindowDimensions,\n View,\n@@ -32,6 +46,7 @@ import {\n setReviewTurnDiff,\n updateReviewExpandedFileIds,\n updateReviewRevealedLargeFileIds,\n+ updateReviewViewedFileIds,\n useReviewCacheForThread,\n } from "./reviewState";\n import {\n@@ -45,11 +60,12 @@ import {\n type ReviewParsedDiff,\n type ReviewRenderableFile,\n type ReviewRenderableLineRow,\n+ type ReviewRenderableRow,\n } from "./reviewModel";\n import {\n clearReviewHighlightFileCache,\n getCachedHighlightedReviewFile,\n- highlightReviewFile,\n+ streamHighlightReviewFile,\n type ReviewDiffTheme,\n type ReviewHighlightedFile,\n type ReviewHighlightedToken,\n@@ -67,9 +83,12 @@ import {\n import {\n changeTone,\n DiffTokenText,\n+ REVIEW_DIFF_LINE_HEIGHT,\n REVIEW_MONO_FONT_FAMILY,\n ReviewChangeBar,\n } from "./reviewDiffRendering";\n+import { markReviewEvent, measureReviewWork } from "./reviewPerf";\n+import { useReviewHighlighterStatus } from "./ReviewHighlighterProvider";\n \n interface PendingCommentSelection {\n readonly sectionTitle: string;\n@@ -87,14 +106,21 @@ interface ReviewLineActionInput {\n \n const IOS_NAV_BAR_HEIGHT = 44;\n const REVIEW_HEADER_SPACING = 0;\n-const REVIEW_LINE_GUTTER_WIDTH = 62;\n+const REVIEW_CHANGE_BAR_WIDTH = 5;\n+const REVIEW_MIN_LINE_NUMBER_WIDTH = 27;\n+const REVIEW_LINE_NUMBER_DIGIT_WIDTH_ESTIMATE = 8;\n+const REVIEW_LINE_NUMBER_HORIZONTAL_PADDING = 6;\n const REVIEW_CHARACTER_WIDTH_ESTIMATE = 8.4;\n const REVIEW_MAX_CONTENT_WIDTH = 4_800;\n-const REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT = 2;\n-const REVIEW_HIGHLIGHT_BACKTRACK_COUNT = 0;\n-const REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT = 1;\n+const REVIEW_HUNK_ROW_HEIGHT = 35;\n+const REVIEW_FILE_HEADER_HEIGHT = 43;\n+const REVIEW_SUPPRESSED_ROW_HEIGHT = 92;\n const loggedMissingReviewTokenKeys = new Set<string>();\n \n+function waitForReviewDelay(durationMs: number): Promise<void> {\n+ return new Promise((resolve) => setTimeout(resolve, durationMs));\n+}\n+\n function isReviewDiffDebugLoggingEnabled(): boolean {\n return typeof __DEV__ !== "undefined" ? __DEV__ : false;\n }\n@@ -113,33 +139,27 @@ function logReviewDiffDiagnostic(message: string, details?: Record<string, unkno\n }\n \n function getFileHeaderChrome(changeType: ReviewRenderableFile["changeType"]): {\n- readonly rail: string;\n readonly dot: string;\n } {\n switch (changeType) {\n case "new":\n return {\n- rail: "bg-emerald-400",\n dot: "bg-emerald-400",\n };\n case "deleted":\n return {\n- rail: "bg-rose-400",\n dot: "bg-rose-400",\n };\n case "rename-pure":\n return {\n- rail: "bg-amber-400",\n dot: "bg-amber-400",\n };\n case "rename-changed":\n return {\n- rail: "bg-sky-400",\n dot: "bg-sky-400",\n };\n default:\n return {\n- rail: "bg-sky-400",\n dot: "bg-sky-400",\n };\n }\n@@ -159,51 +179,72 @@ function formatHeaderDiffSummary(parsedDiff: ReviewParsedDiff): {\n };\n }\n \n-function computeReviewListContentWidth(\Line truncated
|
||||
},
|
||||
{
|
||||
id: "large",
|
||||
label: "Large",
|
||||
filename: "review-large.diff",
|
||||
lineCount: 3208,
|
||||
diff: 'diff --git a/apps/mobile/package.json b/apps/mobile/package.json\nindex 08329e1d4..36ac93a0f 100644\n--- a/apps/mobile/package.json\n+++ b/apps/mobile/package.json\n@@ -30,6 +30,7 @@\n "config:dev": "APP_VARIANT=development expo config",\n "config:preview": "APP_VARIANT=preview expo config",\n "config:prod": "APP_VARIANT=production expo config",\n+ "profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",\n "test": "vitest run",\n "typecheck": "tsc --noEmit"\n },\ndiff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx\nindex f153db701..f6095c051 100644\n--- a/apps/mobile/src/app/index.tsx\n+++ b/apps/mobile/src/app/index.tsx\n@@ -43,28 +43,50 @@ export default function HomeRouteScreen() {\n headerTintColor: iconColor,\n headerTitle: "",\n headerRight: () => (\n- <Pressable\n- onPress={() => router.push("/connections")}\n- hitSlop={8}\n- style={{\n- flexDirection: "row",\n- alignItems: "center",\n- gap: 8,\n- paddingHorizontal: 4,\n- paddingVertical: 4,\n- }}\n- >\n- <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />\n- <RNText\n+ <View style={{ flexDirection: "row", alignItems: "center", gap: 12 }}>\n+ <Pressable\n+ onPress={() => router.push("/debug/syntax-highlight")}\n+ hitSlop={8}\n style={{\n- fontFamily: "DMSans_700Bold",\n- fontSize: 12,\n- color: secondaryFg,\n+ borderRadius: 999,\n+ backgroundColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)",\n+ paddingHorizontal: 10,\n+ paddingVertical: 5,\n }}\n >\n- {CONNECTION_LABEL[connectionState]}\n- </RNText>\n- </Pressable>\n+ <RNText\n+ style={{\n+ fontFamily: "DMSans_700Bold",\n+ fontSize: 12,\n+ color: secondaryFg,\n+ }}\n+ >\n+ Debug\n+ </RNText>\n+ </Pressable>\n+ <Pressable\n+ onPress={() => router.push("/connections")}\n+ hitSlop={8}\n+ style={{\n+ flexDirection: "row",\n+ alignItems: "center",\n+ gap: 8,\n+ paddingHorizontal: 4,\n+ paddingVertical: 4,\n+ }}\n+ >\n+ <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />\n+ <RNText\n+ style={{\n+ fontFamily: "DMSans_700Bold",\n+ fontSize: 12,\n+ color: secondaryFg,\n+ }}\n+ >\n+ {CONNECTION_LABEL[connectionState]}\n+ </RNText>\n+ </Pressable>\n+ </View>\n ),\n headerSearchBarOptions: {\n placeholder: "Search threads",\ndiff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\nindex 84c48c6ed..ee993ee7c 100644\n--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n@@ -1,5 +1,10 @@\n+import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";\n import { ReviewSheet } from "../../../../features/review/ReviewSheet";\n \n export default function ReviewRoute() {\n- return <ReviewSheet />;\n+ return (\n+ <ReviewHighlighterProvider>\n+ <ReviewSheet />\n+ </ReviewHighlighterProvider>\n+ );\n }\ndiff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\nindex 076a2286d..9a173224a 100644\n--- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n+++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n@@ -2,15 +2,8 @@ import { useLocalSearchParams, useRouter } from "expo-router";\n import { SymbolView } from "expo-symbols";\n import { TextInputWrapper } from "expo-paste-input";\n import { useEffect, useMemo, useState } from "react";\n-import {\n- KeyboardAvoidingView,\n- Platform,\n- Pressable,\n- ScrollView,\n- View,\n- useColorScheme,\n- useWindowDimensions,\n-} from "react-native";\n+import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native";\n+import { KeyboardStickyView } from "react-native-keyboard-controller";\n import { useSafeAreaInsets } from "reactLine truncated
|
||||
},
|
||||
{
|
||||
id: "current",
|
||||
label: "Current Working",
|
||||
filename: "current-working-review.diff",
|
||||
lineCount: 3208,
|
||||
diff: 'diff --git a/apps/mobile/package.json b/apps/mobile/package.json\nindex 08329e1d4..36ac93a0f 100644\n--- a/apps/mobile/package.json\n+++ b/apps/mobile/package.json\n@@ -30,6 +30,7 @@\n "config:dev": "APP_VARIANT=development expo config",\n "config:preview": "APP_VARIANT=preview expo config",\n "config:prod": "APP_VARIANT=production expo config",\n+ "profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",\n "test": "vitest run",\n "typecheck": "tsc --noEmit"\n },\ndiff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx\nindex f153db701..f6095c051 100644\n--- a/apps/mobile/src/app/index.tsx\n+++ b/apps/mobile/src/app/index.tsx\n@@ -43,28 +43,50 @@ export default function HomeRouteScreen() {\n headerTintColor: iconColor,\n headerTitle: "",\n headerRight: () => (\n- <Pressable\n- onPress={() => router.push("/connections")}\n- hitSlop={8}\n- style={{\n- flexDirection: "row",\n- alignItems: "center",\n- gap: 8,\n- paddingHorizontal: 4,\n- paddingVertical: 4,\n- }}\n- >\n- <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />\n- <RNText\n+ <View style={{ flexDirection: "row", alignItems: "center", gap: 12 }}>\n+ <Pressable\n+ onPress={() => router.push("/debug/syntax-highlight")}\n+ hitSlop={8}\n style={{\n- fontFamily: "DMSans_700Bold",\n- fontSize: 12,\n- color: secondaryFg,\n+ borderRadius: 999,\n+ backgroundColor: isDark ? "rgba(255,255,255,0.06)" : "rgba(0,0,0,0.06)",\n+ paddingHorizontal: 10,\n+ paddingVertical: 5,\n }}\n >\n- {CONNECTION_LABEL[connectionState]}\n- </RNText>\n- </Pressable>\n+ <RNText\n+ style={{\n+ fontFamily: "DMSans_700Bold",\n+ fontSize: 12,\n+ color: secondaryFg,\n+ }}\n+ >\n+ Debug\n+ </RNText>\n+ </Pressable>\n+ <Pressable\n+ onPress={() => router.push("/connections")}\n+ hitSlop={8}\n+ style={{\n+ flexDirection: "row",\n+ alignItems: "center",\n+ gap: 8,\n+ paddingHorizontal: 4,\n+ paddingVertical: 4,\n+ }}\n+ >\n+ <ConnectionStatusDot state={connectionState} pulse={hasRemoteActivity} size={7} />\n+ <RNText\n+ style={{\n+ fontFamily: "DMSans_700Bold",\n+ fontSize: 12,\n+ color: secondaryFg,\n+ }}\n+ >\n+ {CONNECTION_LABEL[connectionState]}\n+ </RNText>\n+ </Pressable>\n+ </View>\n ),\n headerSearchBarOptions: {\n placeholder: "Search threads",\ndiff --git a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\nindex 84c48c6ed..ee993ee7c 100644\n--- a/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n+++ b/apps/mobile/src/app/threads/[environmentId]/[threadId]/review.tsx\n@@ -1,5 +1,10 @@\n+import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";\n import { ReviewSheet } from "../../../../features/review/ReviewSheet";\n \n export default function ReviewRoute() {\n- return <ReviewSheet />;\n+ return (\n+ <ReviewHighlighterProvider>\n+ <ReviewSheet />\n+ </ReviewHighlighterProvider>\n+ );\n }\ndiff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\nindex 076a2286d..9a173224a 100644\n--- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n+++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx\n@@ -2,15 +2,8 @@ import { useLocalSearchParams, useRouter } from "expo-router";\n import { SymbolView } from "expo-symbols";\n import { TextInputWrapper } from "expo-paste-input";\n import { useEffect, useMemo, useState } from "react";\n-import {\n- KeyboardAvoidingView,\n- Platform,\n- Pressable,\n- ScrollView,\n- View,\n- useColorScheme,\n- useWindowDimensions,\n-} from "react-native";\n+import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native";\n+import { KeyboardStickyView } from "react-native-keyboard-controller";\n import { useSafeAreaInsets } from "reactLine truncated
|
||||
},
|
||||
];
|
||||
@@ -2,15 +2,8 @@ import { useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { TextInputWrapper } from "expo-paste-input";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
KeyboardAvoidingView,
|
||||
Platform,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
View,
|
||||
useColorScheme,
|
||||
useWindowDimensions,
|
||||
} from "react-native";
|
||||
import { Pressable, ScrollView, View, useColorScheme, useWindowDimensions } from "react-native";
|
||||
import { KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
|
||||
@@ -34,6 +27,7 @@ import {
|
||||
import {
|
||||
changeTone,
|
||||
DiffTokenText,
|
||||
REVIEW_DIFF_LINE_HEIGHT,
|
||||
REVIEW_MONO_FONT_FAMILY,
|
||||
ReviewChangeBar,
|
||||
} from "./reviewDiffRendering";
|
||||
@@ -44,7 +38,6 @@ import {
|
||||
} from "./shikiReviewHighlighter";
|
||||
|
||||
const REVIEW_COMMENT_PREVIEW_MAX_LINES = 5;
|
||||
const REVIEW_COMMENT_LINE_HEIGHT = 26;
|
||||
|
||||
export function ReviewCommentComposerSheet() {
|
||||
const router = useRouter();
|
||||
@@ -84,8 +77,8 @@ export function ReviewCommentComposerSheet() {
|
||||
? `Lines ${firstNumber}-${lastNumber}`
|
||||
: `${selectedLines.length} lines selected`;
|
||||
const previewHeight = Math.max(
|
||||
Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_COMMENT_LINE_HEIGHT,
|
||||
REVIEW_COMMENT_LINE_HEIGHT,
|
||||
Math.min(selectedLines.length, REVIEW_COMMENT_PREVIEW_MAX_LINES) * REVIEW_DIFF_LINE_HEIGHT,
|
||||
REVIEW_DIFF_LINE_HEIGHT,
|
||||
);
|
||||
const previewViewportWidth = Math.max(width - 40, 280);
|
||||
const handleNativePaste = useNativePaste((uris) => {
|
||||
@@ -143,17 +136,13 @@ export function ReviewCommentComposerSheet() {
|
||||
}
|
||||
|
||||
return (
|
||||
<KeyboardAvoidingView
|
||||
behavior={Platform.OS === "ios" ? "padding" : "height"}
|
||||
keyboardVerticalOffset={Platform.OS === "ios" ? 12 : 0}
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
<View style={{ flex: 1 }}>
|
||||
<View
|
||||
style={{
|
||||
flex: 1,
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 8,
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 18,
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 82,
|
||||
}}
|
||||
>
|
||||
<View className="flex-row items-center justify-between py-2">
|
||||
@@ -219,7 +208,7 @@ export function ReviewCommentComposerSheet() {
|
||||
<View
|
||||
key={line.id}
|
||||
className={cn("flex-row items-start", changeTone(line.change))}
|
||||
style={{ height: REVIEW_COMMENT_LINE_HEIGHT }}
|
||||
style={{ height: REVIEW_DIFF_LINE_HEIGHT }}
|
||||
>
|
||||
<ReviewChangeBar change={line.change} />
|
||||
<Text
|
||||
@@ -280,35 +269,41 @@ export function ReviewCommentComposerSheet() {
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View className="flex-row items-center gap-3 pt-1">
|
||||
<ControlPill icon="plus" onPress={() => void handlePickImages()} />
|
||||
<View className="flex-1" />
|
||||
<ControlPill
|
||||
icon="arrow.up"
|
||||
label="Comment"
|
||||
variant="primary"
|
||||
disabled={!canSubmit}
|
||||
onPress={() => {
|
||||
if (!target || !environmentId || !threadId || commentText.trim().length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
appendReviewCommentToDraft({
|
||||
environmentId,
|
||||
threadId,
|
||||
text: formatReviewCommentContext(target, commentText),
|
||||
attachments,
|
||||
});
|
||||
setAttachments([]);
|
||||
clearReviewCommentTarget();
|
||||
router.dismiss();
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
{target ? (
|
||||
<KeyboardStickyView style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}>
|
||||
<View
|
||||
className="flex-row items-center gap-3 bg-sheet px-5 pt-3"
|
||||
style={{ paddingBottom: Math.max(insets.bottom, 18) }}
|
||||
>
|
||||
<ControlPill icon="plus" onPress={() => void handlePickImages()} />
|
||||
<View className="flex-1" />
|
||||
<ControlPill
|
||||
icon="arrow.up"
|
||||
label="Comment"
|
||||
variant="primary"
|
||||
disabled={!canSubmit}
|
||||
onPress={() => {
|
||||
if (!target || !environmentId || !threadId || commentText.trim().length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
appendReviewCommentToDraft({
|
||||
environmentId,
|
||||
threadId,
|
||||
text: formatReviewCommentContext(target, commentText),
|
||||
attachments,
|
||||
});
|
||||
setAttachments([]);
|
||||
clearReviewCommentTarget();
|
||||
router.dismiss();
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
</KeyboardStickyView>
|
||||
) : null}
|
||||
<ImageViewing
|
||||
images={previewImageUri ? [{ uri: previewImageUri }] : []}
|
||||
imageIndex={0}
|
||||
@@ -317,6 +312,6 @@ export function ReviewCommentComposerSheet() {
|
||||
swipeToCloseEnabled
|
||||
doubleTapToZoomEnabled
|
||||
/>
|
||||
</KeyboardAvoidingView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { createContext, type ReactNode, useContext, useEffect, useMemo, useState } from "react";
|
||||
|
||||
import {
|
||||
getActiveReviewHighlighterEngine,
|
||||
prepareReviewHighlighter,
|
||||
prepareReviewHighlighterLanguages,
|
||||
type ReviewHighlighterEngine,
|
||||
} from "./shikiReviewHighlighter";
|
||||
|
||||
type ReviewHighlighterStatus = "idle" | "initializing" | "ready" | "error";
|
||||
|
||||
interface ReviewHighlighterContextValue {
|
||||
readonly engine: ReviewHighlighterEngine | null;
|
||||
readonly error: string | null;
|
||||
readonly status: ReviewHighlighterStatus;
|
||||
}
|
||||
|
||||
const ReviewHighlighterContext = createContext<ReviewHighlighterContextValue>({
|
||||
engine: null,
|
||||
error: null,
|
||||
status: "idle",
|
||||
});
|
||||
|
||||
const REVIEW_INITIAL_LANGUAGES = [
|
||||
"typescript",
|
||||
"tsx",
|
||||
"javascript",
|
||||
"jsx",
|
||||
"json",
|
||||
"yaml",
|
||||
"bash",
|
||||
] as const;
|
||||
|
||||
function isReviewHighlighterProviderDebugLoggingEnabled(): boolean {
|
||||
return typeof __DEV__ !== "undefined" ? __DEV__ : false;
|
||||
}
|
||||
|
||||
function logReviewHighlighterProviderDiagnostic(
|
||||
message: string,
|
||||
details?: Record<string, unknown>,
|
||||
): void {
|
||||
if (!isReviewHighlighterProviderDebugLoggingEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (details) {
|
||||
console.log(`[review-highlighter-provider] ${message}`, details);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`[review-highlighter-provider] ${message}`);
|
||||
}
|
||||
|
||||
export function ReviewHighlighterProvider(props: { readonly children: ReactNode }) {
|
||||
const [value, setValue] = useState<ReviewHighlighterContextValue>({
|
||||
engine: null,
|
||||
error: null,
|
||||
status: "idle",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
setValue({ engine: null, error: null, status: "initializing" });
|
||||
|
||||
void (async () => {
|
||||
const startedAt = performance.now();
|
||||
try {
|
||||
await prepareReviewHighlighter();
|
||||
await prepareReviewHighlighterLanguages(REVIEW_INITIAL_LANGUAGES);
|
||||
const engine = await getActiveReviewHighlighterEngine();
|
||||
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const durationMs = Math.round(performance.now() - startedAt);
|
||||
logReviewHighlighterProviderDiagnostic("initialized", {
|
||||
durationMs,
|
||||
engine,
|
||||
});
|
||||
setValue({ engine, error: null, status: "ready" });
|
||||
} catch (error) {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
logReviewHighlighterProviderDiagnostic("initialization failed", { error: message });
|
||||
setValue({ engine: null, error: message, status: "error" });
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const contextValue = useMemo(() => value, [value]);
|
||||
|
||||
return (
|
||||
<ReviewHighlighterContext.Provider value={contextValue}>
|
||||
{props.children}
|
||||
</ReviewHighlighterContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useReviewHighlighterStatus(): ReviewHighlighterContextValue {
|
||||
return useContext(ReviewHighlighterContext);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -11,6 +11,9 @@ export const REVIEW_MONO_FONT_FAMILY = Platform.select({
|
||||
default: "monospace",
|
||||
});
|
||||
|
||||
export const REVIEW_DIFF_LINE_HEIGHT = 26;
|
||||
const REVIEW_DELETE_STRIPE_COUNT = REVIEW_DIFF_LINE_HEIGHT / 2;
|
||||
|
||||
export function renderVisibleWhitespace(value: string): string {
|
||||
const expandedTabs = value.replace(/\t/g, " ");
|
||||
return expandedTabs.replace(/^( +)/, (leading) => leading.replaceAll(" ", "\u00A0"));
|
||||
@@ -37,10 +40,13 @@ function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string |
|
||||
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 className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>
|
||||
<View>
|
||||
{Array.from({ length: REVIEW_DELETE_STRIPE_COUNT }, (_, index) => (
|
||||
<View key={index}>
|
||||
<View className="w-[5px] bg-rose-400" style={{ height: 1 }} />
|
||||
<View style={{ height: 1 }} />
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
@@ -48,7 +54,7 @@ export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRo
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="w-[5px] self-stretch overflow-hidden">
|
||||
<View className="w-[5px] overflow-hidden" style={{ height: REVIEW_DIFF_LINE_HEIGHT }}>
|
||||
<View className={cn("h-full w-[5px] flex-1", changeBarTone(props.change))} />
|
||||
</View>
|
||||
);
|
||||
@@ -63,6 +69,7 @@ export function DiffTokenText(props: {
|
||||
if (!props.tokens || props.tokens.length === 0) {
|
||||
return (
|
||||
<NativeText
|
||||
numberOfLines={1}
|
||||
selectable
|
||||
className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}
|
||||
style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
|
||||
@@ -74,6 +81,7 @@ export function DiffTokenText(props: {
|
||||
|
||||
return (
|
||||
<NativeText
|
||||
numberOfLines={1}
|
||||
selectable
|
||||
className={cn("text-[13px] leading-[17px] font-medium text-foreground", props.className)}
|
||||
style={{ fontFamily: REVIEW_MONO_FONT_FAMILY }}
|
||||
|
||||
@@ -6,9 +6,9 @@ import {
|
||||
} from "./reviewHighlighterEngine";
|
||||
|
||||
describe("resolveReviewHighlighterEnginePreference", () => {
|
||||
it("defaults invalid values to javascript", () => {
|
||||
expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("javascript");
|
||||
expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("javascript");
|
||||
it("defaults invalid values to native", () => {
|
||||
expect(resolveReviewHighlighterEnginePreference(undefined)).toBe("native");
|
||||
expect(resolveReviewHighlighterEnginePreference("bogus")).toBe("native");
|
||||
});
|
||||
|
||||
it("accepts supported values", () => {
|
||||
|
||||
@@ -11,7 +11,7 @@ export function resolveReviewHighlighterEnginePreference(
|
||||
case "native":
|
||||
return "native";
|
||||
default:
|
||||
return "javascript";
|
||||
return "native";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -238,7 +238,7 @@ describe("buildReviewParsedDiff", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("flattens expanded files into virtualizable review items", () => {
|
||||
it("flattens expanded file rows into virtualized review items", () => {
|
||||
const file = makeRenderableFile({
|
||||
path: "apps/mobile/src/a.ts",
|
||||
rows: [
|
||||
@@ -270,8 +270,19 @@ describe("buildReviewParsedDiff", () => {
|
||||
|
||||
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] }),
|
||||
expect.objectContaining({
|
||||
kind: "hunk",
|
||||
fileId: file.id,
|
||||
file,
|
||||
row: file.rows[0],
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "line",
|
||||
fileId: file.id,
|
||||
file,
|
||||
row: file.rows[1],
|
||||
lineIndex: 0,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
@@ -72,6 +72,7 @@ export interface ReviewHunkListItem {
|
||||
readonly kind: "hunk";
|
||||
readonly id: string;
|
||||
readonly fileId: string;
|
||||
readonly file: ReviewRenderableFile;
|
||||
readonly row: ReviewRenderableHunkRow;
|
||||
}
|
||||
|
||||
@@ -79,7 +80,9 @@ export interface ReviewLineListItem {
|
||||
readonly kind: "line";
|
||||
readonly id: string;
|
||||
readonly fileId: string;
|
||||
readonly file: ReviewRenderableFile;
|
||||
readonly row: ReviewRenderableLineRow;
|
||||
readonly lineIndex: number;
|
||||
}
|
||||
|
||||
export type ReviewListItem =
|
||||
@@ -308,7 +311,7 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil
|
||||
}
|
||||
|
||||
// The flattened review list item model is inspired by pierre/diffs' iterator-first
|
||||
// virtualization architecture, adapted here for React Native and LegendList.
|
||||
// virtualization architecture, adapted here for React Native virtualization.
|
||||
// Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs
|
||||
// Reference files:
|
||||
// - src/utils/iterateOverDiff.ts
|
||||
@@ -350,12 +353,14 @@ export function buildReviewListItems(input: {
|
||||
}
|
||||
}
|
||||
|
||||
file.rows.forEach((row) => {
|
||||
let lineIndex = 0;
|
||||
file.rows.forEach((row, rowIndex) => {
|
||||
if (row.kind === "hunk") {
|
||||
items.push({
|
||||
kind: "hunk",
|
||||
id: row.id,
|
||||
id: `${file.id}:row:${rowIndex}:${row.id}`,
|
||||
fileId: file.id,
|
||||
file,
|
||||
row,
|
||||
});
|
||||
return;
|
||||
@@ -363,10 +368,13 @@ export function buildReviewListItems(input: {
|
||||
|
||||
items.push({
|
||||
kind: "line",
|
||||
id: row.id,
|
||||
id: `${file.id}:row:${rowIndex}:${row.id}`,
|
||||
fileId: file.id,
|
||||
file,
|
||||
row,
|
||||
lineIndex,
|
||||
});
|
||||
lineIndex += 1;
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
interface ReviewPerformanceLike {
|
||||
readonly now?: () => number;
|
||||
readonly mark?: (name: string) => void;
|
||||
readonly measure?: (name: string, startMark: string, endMark: string) => void;
|
||||
readonly clearMarks?: (name?: string) => void;
|
||||
readonly clearMeasures?: (name?: string) => void;
|
||||
}
|
||||
|
||||
const REVIEW_PERF_PREFIX = "t3.review";
|
||||
let reviewPerfSequence = 0;
|
||||
|
||||
function getPerformance(): ReviewPerformanceLike | null {
|
||||
const candidate = (globalThis as { readonly performance?: ReviewPerformanceLike }).performance;
|
||||
return candidate ?? null;
|
||||
}
|
||||
|
||||
export function isReviewPerfEnabled(): boolean {
|
||||
return typeof __DEV__ !== "undefined" ? __DEV__ : false;
|
||||
}
|
||||
|
||||
export function measureReviewWork<T>(name: string, callback: () => T): T {
|
||||
if (!isReviewPerfEnabled()) {
|
||||
return callback();
|
||||
}
|
||||
|
||||
const perf = getPerformance();
|
||||
const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`;
|
||||
const startMark = `${marker}.start`;
|
||||
const endMark = `${marker}.end`;
|
||||
const startedAt = perf?.now?.() ?? Date.now();
|
||||
|
||||
perf?.mark?.(startMark);
|
||||
try {
|
||||
return callback();
|
||||
} finally {
|
||||
const durationMs = (perf?.now?.() ?? Date.now()) - startedAt;
|
||||
perf?.mark?.(endMark);
|
||||
perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark);
|
||||
perf?.clearMarks?.(startMark);
|
||||
perf?.clearMarks?.(endMark);
|
||||
console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) });
|
||||
}
|
||||
}
|
||||
|
||||
export async function measureReviewAsyncWork<T>(
|
||||
name: string,
|
||||
callback: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
if (!isReviewPerfEnabled()) {
|
||||
return callback();
|
||||
}
|
||||
|
||||
const perf = getPerformance();
|
||||
const marker = `${REVIEW_PERF_PREFIX}.${name}.${reviewPerfSequence++}`;
|
||||
const startMark = `${marker}.start`;
|
||||
const endMark = `${marker}.end`;
|
||||
const startedAt = perf?.now?.() ?? Date.now();
|
||||
|
||||
perf?.mark?.(startMark);
|
||||
try {
|
||||
return await callback();
|
||||
} finally {
|
||||
const durationMs = (perf?.now?.() ?? Date.now()) - startedAt;
|
||||
perf?.mark?.(endMark);
|
||||
perf?.measure?.(`${REVIEW_PERF_PREFIX}.${name}`, startMark, endMark);
|
||||
perf?.clearMarks?.(startMark);
|
||||
perf?.clearMarks?.(endMark);
|
||||
console.log(`[review-perf] ${name}`, { durationMs: Number(durationMs.toFixed(2)) });
|
||||
}
|
||||
}
|
||||
|
||||
export function markReviewEvent(name: string, details?: Record<string, unknown>): void {
|
||||
if (!isReviewPerfEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
getPerformance()?.mark?.(`${REVIEW_PERF_PREFIX}.${name}`);
|
||||
if (details) {
|
||||
console.log(`[review-perf] ${name}`, details);
|
||||
return;
|
||||
}
|
||||
console.log(`[review-perf] ${name}`);
|
||||
}
|
||||
@@ -64,6 +64,13 @@ const reviewRevealedLargeFileIdsByThreadKeyAtom = Atom.family((threadKey: string
|
||||
),
|
||||
);
|
||||
|
||||
const reviewViewedFileIdsByThreadKeyAtom = Atom.family((threadKey: string) =>
|
||||
Atom.make(EMPTY_REVIEW_SECTION_FILE_IDS).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel(`mobile:review:viewed-file-ids:${threadKey}`),
|
||||
),
|
||||
);
|
||||
|
||||
const reviewParsedDiffBySectionCacheKeyAtom = Atom.family((cacheKey: string) =>
|
||||
Atom.make<{ readonly diff: string | null; readonly parsed: ReviewParsedDiff } | null>(null).pipe(
|
||||
Atom.keepAlive,
|
||||
@@ -110,6 +117,9 @@ export function useReviewCacheForThread(input: {
|
||||
? reviewRevealedLargeFileIdsByThreadKeyAtom(threadKey)
|
||||
: EMPTY_REVIEW_SECTION_FILE_IDS_ATOM,
|
||||
);
|
||||
const viewedFileIdsBySection = useAtomValue(
|
||||
threadKey ? reviewViewedFileIdsByThreadKeyAtom(threadKey) : EMPTY_REVIEW_SECTION_FILE_IDS_ATOM,
|
||||
);
|
||||
|
||||
return {
|
||||
threadKey,
|
||||
@@ -118,6 +128,7 @@ export function useReviewCacheForThread(input: {
|
||||
selectedSectionId,
|
||||
expandedFileIdsBySection,
|
||||
revealedLargeFileIdsBySection,
|
||||
viewedFileIdsBySection,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -169,6 +180,20 @@ export function updateReviewRevealedLargeFileIds(
|
||||
});
|
||||
}
|
||||
|
||||
export function updateReviewViewedFileIds(
|
||||
threadKey: string,
|
||||
sectionId: string,
|
||||
update: (current: ReadonlyArray<string> | undefined) => ReadonlyArray<string> | undefined,
|
||||
): void {
|
||||
const atom = reviewViewedFileIdsByThreadKeyAtom(threadKey);
|
||||
const current = appAtomRegistry.get(atom);
|
||||
const nextValue = update(current[sectionId]);
|
||||
appAtomRegistry.set(atom, {
|
||||
...current,
|
||||
[sectionId]: nextValue,
|
||||
});
|
||||
}
|
||||
|
||||
export function getCachedReviewParsedDiff(input: {
|
||||
readonly threadKey: string | null;
|
||||
readonly sectionId: string | null;
|
||||
|
||||
@@ -24,7 +24,7 @@ function makeRenderableFile(
|
||||
describe("highlightReviewFile", () => {
|
||||
it("preserves one highlighted token row per diff line even without trailing newlines", async () => {
|
||||
const file = makeRenderableFile({
|
||||
path: "apps/mobile/src/example.test.ts",
|
||||
path: "apps/mobile/src/example.txt",
|
||||
additionLines: [
|
||||
'const items = ["a"];',
|
||||
'expect(items).toEqual(["a"]);',
|
||||
@@ -36,15 +36,23 @@ describe("highlightReviewFile", () => {
|
||||
const highlighted = await highlightReviewFile(file, "light");
|
||||
|
||||
expect(highlighted.additionLines).toHaveLength(file.additionLines.length);
|
||||
expect(highlighted.additionLines[0]?.some((token) => token.content === "const")).toBe(true);
|
||||
expect(highlighted.additionLines[1]?.some((token) => token.content === "expect")).toBe(true);
|
||||
expect(highlighted.additionLines[2]?.some((token) => token.content === "const")).toBe(true);
|
||||
expect(highlighted.additionLines[3]?.some((token) => token.content === "expect")).toBe(true);
|
||||
expect(highlighted.additionLines[0]?.map((token) => token.content).join("")).toBe(
|
||||
file.additionLines[0],
|
||||
);
|
||||
expect(highlighted.additionLines[1]?.map((token) => token.content).join("")).toBe(
|
||||
file.additionLines[1],
|
||||
);
|
||||
expect(highlighted.additionLines[2]?.map((token) => token.content).join("")).toBe(
|
||||
file.additionLines[2],
|
||||
);
|
||||
expect(highlighted.additionLines[3]?.map((token) => token.content).join("")).toBe(
|
||||
file.additionLines[3],
|
||||
);
|
||||
});
|
||||
|
||||
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",
|
||||
path: "apps/mobile/src/example-inline-diff.txt",
|
||||
additionLines: ["const after = 2;"],
|
||||
deletionLines: ["const before = 1;"],
|
||||
rows: [
|
||||
@@ -82,7 +90,7 @@ describe("highlightReviewFile", () => {
|
||||
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",
|
||||
path: "apps/mobile/src/example-long-line.txt",
|
||||
additionLines: [longLine],
|
||||
rows: [
|
||||
{
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
import { createHighlighterCore, type HighlighterCore } from "@shikijs/core";
|
||||
import { createJavaScriptRegexEngine } from "@shikijs/engine-javascript";
|
||||
import bashLanguage from "@shikijs/langs/bash";
|
||||
import javascriptLanguage from "@shikijs/langs/javascript";
|
||||
import jsonLanguage from "@shikijs/langs/json";
|
||||
import jsxLanguage from "@shikijs/langs/jsx";
|
||||
import tsxLanguage from "@shikijs/langs/tsx";
|
||||
import typescriptLanguage from "@shikijs/langs/typescript";
|
||||
import yamlLanguage from "@shikijs/langs/yaml";
|
||||
import githubDarkDefault from "@shikijs/themes/github-dark-default";
|
||||
import githubLightDefault from "@shikijs/themes/github-light-default";
|
||||
import { getFiletypeFromFileName } from "@pierre/diffs/utils";
|
||||
|
||||
import {
|
||||
@@ -11,6 +20,7 @@ import type { ReviewRenderableFile, ReviewRenderableLineRow } from "./reviewMode
|
||||
import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs";
|
||||
|
||||
export type ReviewDiffTheme = "light" | "dark";
|
||||
export type { ReviewHighlighterEngine };
|
||||
|
||||
export interface ReviewHighlightedToken {
|
||||
content: string;
|
||||
@@ -24,12 +34,19 @@ export interface ReviewHighlightedFile {
|
||||
readonly deletionLines: ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>;
|
||||
}
|
||||
|
||||
export interface ReviewHighlightFileProgress {
|
||||
readonly highlightedFile: ReviewHighlightedFile;
|
||||
readonly complete: boolean;
|
||||
readonly highlightedLineCount: number;
|
||||
}
|
||||
|
||||
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";
|
||||
process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ??
|
||||
(process.env.NODE_ENV === "test" ? "javascript" : "native");
|
||||
const REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE = resolveReviewHighlighterEnginePreference(
|
||||
REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE,
|
||||
);
|
||||
@@ -38,12 +55,30 @@ const REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE = resolveReviewHighlighterBooleanF
|
||||
false,
|
||||
);
|
||||
const REVIEW_HIGHLIGHT_RESULT_CACHE_LIMIT = 8;
|
||||
const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 40;
|
||||
const REVIEW_HIGHLIGHT_CHUNK_SIZE = 20;
|
||||
const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 8;
|
||||
const REVIEW_HIGHLIGHT_CHUNK_SIZE = 200;
|
||||
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"]);
|
||||
const REVIEW_INITIAL_LANGUAGE_MODULES = [
|
||||
bashLanguage,
|
||||
javascriptLanguage,
|
||||
jsonLanguage,
|
||||
jsxLanguage,
|
||||
tsxLanguage,
|
||||
typescriptLanguage,
|
||||
yamlLanguage,
|
||||
] satisfies Parameters<typeof createHighlighterCore>[0]["langs"];
|
||||
const loadedLanguages = new Set<string>([
|
||||
"text",
|
||||
"bash",
|
||||
"javascript",
|
||||
"json",
|
||||
"jsx",
|
||||
"tsx",
|
||||
"typescript",
|
||||
"yaml",
|
||||
]);
|
||||
const languageLoadingPromises = new Map<string, Promise<boolean>>();
|
||||
const languageImports: Partial<Record<string, () => Promise<unknown>>> = {
|
||||
javascript: () => import("@shikijs/langs/javascript"),
|
||||
@@ -215,21 +250,13 @@ function joinPatchLines(lines: ReadonlyArray<string>): string {
|
||||
|
||||
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([
|
||||
import("@shikijs/themes/github-light-default"),
|
||||
import("@shikijs/themes/github-dark-default"),
|
||||
]).then(async ([lightThemeModule, darkThemeModule]) => {
|
||||
const configuredHighlighterPromise = (async () => {
|
||||
let nativeEngineAvailable = false;
|
||||
|
||||
logReviewHighlighterDiagnostic("initializing", {
|
||||
@@ -238,12 +265,11 @@ async function getHighlighter(): Promise<HighlighterCore> {
|
||||
resultCacheDisabled: REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE,
|
||||
});
|
||||
|
||||
const themes = [lightThemeModule.default, darkThemeModule.default];
|
||||
const themes = [githubLightDefault, githubDarkDefault];
|
||||
|
||||
if (REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE !== "javascript") {
|
||||
try {
|
||||
const nativeEngineModule = await import("react-native-shiki-engine");
|
||||
logReviewHighlighterDiagnostic("imported react-native-shiki-engine");
|
||||
nativeEngineAvailable = nativeEngineModule.isNativeEngineAvailable();
|
||||
logReviewHighlighterDiagnostic("checked native engine availability", {
|
||||
nativeEngineAvailable,
|
||||
@@ -253,7 +279,7 @@ async function getHighlighter(): Promise<HighlighterCore> {
|
||||
logReviewHighlighterDiagnostic("creating native regex engine");
|
||||
const highlighter = await createHighlighterCore({
|
||||
themes,
|
||||
langs: [],
|
||||
langs: REVIEW_INITIAL_LANGUAGE_MODULES,
|
||||
engine: nativeEngineModule.createNativeEngine(),
|
||||
});
|
||||
logReviewHighlighterDiagnostic("using native engine");
|
||||
@@ -281,7 +307,7 @@ async function getHighlighter(): Promise<HighlighterCore> {
|
||||
);
|
||||
const highlighter = await createHighlighterCore({
|
||||
themes,
|
||||
langs: [],
|
||||
langs: REVIEW_INITIAL_LANGUAGE_MODULES,
|
||||
engine: createJavaScriptRegexEngine(),
|
||||
});
|
||||
logReviewHighlighterDiagnostic("using javascript engine", {
|
||||
@@ -291,7 +317,7 @@ async function getHighlighter(): Promise<HighlighterCore> {
|
||||
highlighter,
|
||||
engine,
|
||||
};
|
||||
});
|
||||
})();
|
||||
|
||||
highlighterPromise = configuredHighlighterPromise
|
||||
.then((result) => result.highlighter)
|
||||
@@ -316,11 +342,52 @@ export async function getActiveReviewHighlighterEngine(): Promise<ReviewHighligh
|
||||
return activeHighlighterEnginePromise ?? Promise.resolve("javascript");
|
||||
}
|
||||
|
||||
export async function prepareReviewHighlighter(): Promise<void> {
|
||||
await getHighlighter();
|
||||
}
|
||||
|
||||
export async function prepareReviewHighlighterLanguages(
|
||||
languages: ReadonlyArray<string>,
|
||||
): Promise<void> {
|
||||
const highlighter = await getHighlighter();
|
||||
await Promise.all(
|
||||
languages.map(async (language) => {
|
||||
const candidate = resolveLanguageAlias(language);
|
||||
if (candidate === "text" || !(candidate in languageImports)) {
|
||||
return;
|
||||
}
|
||||
|
||||
await loadSingleLanguage(highlighter, candidate);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function resolveLanguageAlias(language: string): string {
|
||||
const normalized = language.toLowerCase();
|
||||
return languageAliases[normalized] ?? normalized;
|
||||
}
|
||||
|
||||
function resolveLoadedLanguageFromPath(
|
||||
path: string,
|
||||
languageHint: string | null = null,
|
||||
): string | null {
|
||||
const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);
|
||||
if (!detectedLanguage) {
|
||||
return "text";
|
||||
}
|
||||
|
||||
const candidate = resolveLanguageAlias(detectedLanguage);
|
||||
if (candidate === "text" || candidate === "ansi") {
|
||||
return "text";
|
||||
}
|
||||
|
||||
if (!(candidate in languageImports)) {
|
||||
return "text";
|
||||
}
|
||||
|
||||
return loadedLanguages.has(candidate) ? candidate : null;
|
||||
}
|
||||
|
||||
async function loadSingleLanguage(
|
||||
highlighter: HighlighterCore,
|
||||
language: string,
|
||||
@@ -360,6 +427,11 @@ async function resolveLanguageFromPath(
|
||||
path: string,
|
||||
languageHint: string | null = null,
|
||||
): Promise<string> {
|
||||
const loadedLanguage = resolveLoadedLanguageFromPath(path, languageHint);
|
||||
if (loadedLanguage) {
|
||||
return loadedLanguage;
|
||||
}
|
||||
|
||||
const detectedLanguage = languageHint ?? getFiletypeFromFileName(path);
|
||||
if (!detectedLanguage) {
|
||||
return "text";
|
||||
@@ -374,8 +446,12 @@ async function resolveLanguageFromPath(
|
||||
return "text";
|
||||
}
|
||||
|
||||
if (loadedLanguages.has(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
|
||||
const highlighter = await getHighlighter();
|
||||
const loaded = await loadSingleLanguage(highlighter, resolveLanguageAlias(candidate));
|
||||
const loaded = await loadSingleLanguage(highlighter, candidate);
|
||||
if (!loaded) {
|
||||
return "text";
|
||||
}
|
||||
@@ -384,7 +460,10 @@ async function resolveLanguageFromPath(
|
||||
}
|
||||
|
||||
async function resolveLanguage(file: ReviewRenderableFile): Promise<string> {
|
||||
return resolveLanguageFromPath(file.path, file.languageHint);
|
||||
return (
|
||||
resolveLoadedLanguageFromPath(file.path, file.languageHint) ??
|
||||
(await resolveLanguageFromPath(file.path, file.languageHint))
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeHighlightedLines(
|
||||
@@ -399,6 +478,18 @@ function normalizeHighlightedLines(
|
||||
);
|
||||
}
|
||||
|
||||
function makePlainHighlightedLines(
|
||||
lines: ReadonlyArray<string>,
|
||||
): ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>> {
|
||||
return lines.map((line) => [
|
||||
{
|
||||
content: stripTrailingNewline(line),
|
||||
color: null,
|
||||
fontStyle: null,
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
function applyWordAltDiffHighlightsToFile(
|
||||
file: ReviewRenderableFile,
|
||||
highlighted: ReviewHighlightedFile,
|
||||
@@ -594,6 +685,67 @@ async function highlightLines(
|
||||
return highlightedLines;
|
||||
}
|
||||
|
||||
async function highlightPatchLinesInChunks(input: {
|
||||
readonly lines: ReadonlyArray<string>;
|
||||
readonly language: string;
|
||||
readonly theme: string;
|
||||
readonly onChunk: (
|
||||
startIndex: number,
|
||||
tokens: ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>,
|
||||
) => void;
|
||||
}): Promise<ReadonlyArray<ReadonlyArray<ReviewHighlightedToken>>> {
|
||||
if (input.lines.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const highlighter = await getHighlighter();
|
||||
const highlightedLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
|
||||
|
||||
for (
|
||||
let startIndex = 0;
|
||||
startIndex < input.lines.length;
|
||||
startIndex += REVIEW_HIGHLIGHT_CHUNK_SIZE
|
||||
) {
|
||||
const lineChunk = input.lines.slice(startIndex, startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE);
|
||||
const chunkTokens: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
|
||||
const tokenizableLines: string[] = [];
|
||||
const tokenizableIndexes: number[] = [];
|
||||
|
||||
lineChunk.forEach((line, index) => {
|
||||
const strippedLine = stripTrailingNewline(line);
|
||||
if (strippedLine.length > REVIEW_TOKENIZE_MAX_LINE_LENGTH) {
|
||||
chunkTokens[index] = [{ content: strippedLine, color: null, fontStyle: null }];
|
||||
return;
|
||||
}
|
||||
|
||||
tokenizableIndexes.push(index);
|
||||
tokenizableLines.push(strippedLine);
|
||||
});
|
||||
|
||||
if (tokenizableLines.length > 0) {
|
||||
const tokenLines = highlighter.codeToTokensBase(tokenizableLines.join("\n"), {
|
||||
lang: input.language,
|
||||
theme: input.theme,
|
||||
});
|
||||
const normalizedTokenLines = normalizeHighlightedLines(tokenLines);
|
||||
|
||||
tokenizableIndexes.forEach((chunkIndex, tokenIndex) => {
|
||||
chunkTokens[chunkIndex] = normalizedTokenLines[tokenIndex] ?? [];
|
||||
});
|
||||
}
|
||||
|
||||
const completedChunk = lineChunk.map((_, index) => chunkTokens[index] ?? []);
|
||||
highlightedLines.push(...completedChunk);
|
||||
input.onChunk(startIndex, completedChunk);
|
||||
|
||||
if (startIndex + REVIEW_HIGHLIGHT_CHUNK_SIZE < input.lines.length) {
|
||||
await waitForNextFrame();
|
||||
}
|
||||
}
|
||||
|
||||
return highlightedLines;
|
||||
}
|
||||
|
||||
function getHighlightCacheKey(file: ReviewRenderableFile, theme: ReviewDiffTheme): string {
|
||||
return `${SHIKI_THEME_NAME_BY_SCHEME[theme]}:${file.cacheKey}`;
|
||||
}
|
||||
@@ -667,7 +819,28 @@ export async function highlightReviewFile(
|
||||
deletionLineCount: file.deletionLines.length,
|
||||
rowCount: file.rows.length,
|
||||
});
|
||||
const language = await resolveLanguage(file);
|
||||
const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);
|
||||
const language = loadedLanguage ?? (await resolveLanguage(file));
|
||||
if (language === "text") {
|
||||
const highlighted = applyWordAltDiffHighlightsToFile(file, {
|
||||
additionLines: makePlainHighlightedLines(file.additionLines),
|
||||
deletionLines: makePlainHighlightedLines(file.deletionLines),
|
||||
});
|
||||
if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
|
||||
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;
|
||||
}
|
||||
|
||||
const additionLines = await highlightLines(
|
||||
joinPatchLines(file.additionLines),
|
||||
language,
|
||||
@@ -707,6 +880,113 @@ export async function highlightReviewFile(
|
||||
});
|
||||
}
|
||||
|
||||
export async function streamHighlightReviewFile(
|
||||
file: ReviewRenderableFile,
|
||||
theme: ReviewDiffTheme,
|
||||
onProgress: (progress: ReviewHighlightFileProgress) => void,
|
||||
): Promise<ReviewHighlightedFile> {
|
||||
const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[theme];
|
||||
const cacheKey = getHighlightCacheKey(file, theme);
|
||||
if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
|
||||
const resolved = resolvedHighlightCache.get(cacheKey);
|
||||
if (resolved) {
|
||||
onProgress({
|
||||
highlightedFile: resolved,
|
||||
complete: true,
|
||||
highlightedLineCount: resolved.additionLines.length + resolved.deletionLines.length,
|
||||
});
|
||||
return resolved;
|
||||
}
|
||||
}
|
||||
|
||||
const startedAt = Date.now();
|
||||
logReviewHighlighterDiagnostic("file stream highlight start", {
|
||||
fileId: file.id,
|
||||
filePath: file.path,
|
||||
theme,
|
||||
additionLineCount: file.additionLines.length,
|
||||
deletionLineCount: file.deletionLines.length,
|
||||
rowCount: file.rows.length,
|
||||
});
|
||||
|
||||
const loadedLanguage = resolveLoadedLanguageFromPath(file.path, file.languageHint);
|
||||
const language = loadedLanguage ?? (await resolveLanguage(file));
|
||||
if (language === "text") {
|
||||
const highlighted = applyWordAltDiffHighlightsToFile(file, {
|
||||
additionLines: makePlainHighlightedLines(file.additionLines),
|
||||
deletionLines: makePlainHighlightedLines(file.deletionLines),
|
||||
});
|
||||
if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
|
||||
storeResolvedHighlightedFile(cacheKey, highlighted);
|
||||
}
|
||||
onProgress({
|
||||
highlightedFile: highlighted,
|
||||
complete: true,
|
||||
highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,
|
||||
});
|
||||
logReviewHighlighterDiagnostic("file stream highlight complete", {
|
||||
fileId: file.id,
|
||||
filePath: file.path,
|
||||
theme,
|
||||
language,
|
||||
highlightedAdditionLineCount: highlighted.additionLines.length,
|
||||
highlightedDeletionLineCount: highlighted.deletionLines.length,
|
||||
highlightedLineCount: highlighted.additionLines.length + highlighted.deletionLines.length,
|
||||
durationMs: Date.now() - startedAt,
|
||||
});
|
||||
return highlighted;
|
||||
}
|
||||
|
||||
const additionLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
|
||||
const deletionLines: Array<ReadonlyArray<ReviewHighlightedToken>> = [];
|
||||
let highlightedLineCount = 0;
|
||||
|
||||
await highlightPatchLinesInChunks({
|
||||
lines: file.additionLines,
|
||||
language,
|
||||
theme: shikiTheme,
|
||||
onChunk: (startIndex, tokens) => {
|
||||
tokens.forEach((lineTokens, index) => {
|
||||
additionLines[startIndex + index] = lineTokens;
|
||||
});
|
||||
highlightedLineCount += tokens.length;
|
||||
},
|
||||
});
|
||||
await waitForNextFrame();
|
||||
await highlightPatchLinesInChunks({
|
||||
lines: file.deletionLines,
|
||||
language,
|
||||
theme: shikiTheme,
|
||||
onChunk: (startIndex, tokens) => {
|
||||
tokens.forEach((lineTokens, index) => {
|
||||
deletionLines[startIndex + index] = lineTokens;
|
||||
});
|
||||
highlightedLineCount += tokens.length;
|
||||
},
|
||||
});
|
||||
|
||||
const highlighted = applyWordAltDiffHighlightsToFile(file, { additionLines, deletionLines });
|
||||
if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {
|
||||
storeResolvedHighlightedFile(cacheKey, highlighted);
|
||||
}
|
||||
onProgress({
|
||||
highlightedFile: highlighted,
|
||||
complete: true,
|
||||
highlightedLineCount,
|
||||
});
|
||||
logReviewHighlighterDiagnostic("file stream highlight complete", {
|
||||
fileId: file.id,
|
||||
filePath: file.path,
|
||||
theme,
|
||||
language,
|
||||
highlightedAdditionLineCount: highlighted.additionLines.length,
|
||||
highlightedDeletionLineCount: highlighted.deletionLines.length,
|
||||
highlightedLineCount,
|
||||
durationMs: Date.now() - startedAt,
|
||||
});
|
||||
return highlighted;
|
||||
}
|
||||
|
||||
export async function highlightReviewSelectedLines(input: {
|
||||
readonly filePath: string;
|
||||
readonly lines: ReadonlyArray<ReviewRenderableLineRow>;
|
||||
@@ -717,7 +997,9 @@ export async function highlightReviewSelectedLines(input: {
|
||||
return {};
|
||||
}
|
||||
|
||||
const language = await resolveLanguageFromPath(input.filePath, input.languageHint ?? null);
|
||||
const loadedLanguage = resolveLoadedLanguageFromPath(input.filePath, input.languageHint ?? null);
|
||||
const language =
|
||||
loadedLanguage ?? (await resolveLanguageFromPath(input.filePath, input.languageHint ?? null));
|
||||
const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[input.theme];
|
||||
const additionLikeLines = input.lines
|
||||
.filter((line) => line.change !== "delete")
|
||||
|
||||
Reference in new issue
Block a user