diff --git a/apps/mobile/README.md b/apps/mobile/README.md index c1bf5b4064..597cb4a339 100644 --- a/apps/mobile/README.md +++ b/apps/mobile/README.md @@ -36,6 +36,14 @@ Build and run the local iOS preview app: bun run ios:preview ``` +Force the review diff highlighter engine: + +```bash +EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE=javascript bun run ios:dev +``` + +`javascript` is the default and recommended setting for the review diff screen. Set `EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE=native` only when you explicitly want to test the native Shiki engine. + Inspect the resolved Expo config for a variant: ```bash diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 41fd2afc49..526fc62210 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -47,6 +47,7 @@ "@t3tools/contracts": "workspace:*", "@t3tools/shared": "workspace:*", "clsx": "^2.1.1", + "diff": "8.0.3", "effect": "catalog:", "expo": "~55.0.14", "expo-camera": "~55.0.15", diff --git a/apps/mobile/src/features/threads/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/threads/review/ReviewCommentComposerSheet.tsx index 0f19059c97..9d4c56dac1 100644 --- a/apps/mobile/src/features/threads/review/ReviewCommentComposerSheet.tsx +++ b/apps/mobile/src/features/threads/review/ReviewCommentComposerSheet.tsx @@ -27,12 +27,16 @@ import { appendReviewCommentToDraft } from "../use-thread-composer-state"; import { clearReviewCommentTarget, formatReviewCommentContext, - getReviewChangeMarker, getReviewUnifiedLineNumber, getSelectedReviewCommentLines, useReviewCommentTarget, } from "./reviewCommentSelection"; -import { changeTone, DiffTokenText } from "./reviewDiffRendering"; +import { + changeTone, + DiffTokenText, + REVIEW_MONO_FONT_FAMILY, + ReviewChangeBar, +} from "./reviewDiffRendering"; import { highlightReviewSelectedLines, type ReviewDiffTheme, @@ -217,19 +221,18 @@ export function ReviewCommentComposerSheet() { className={cn("flex-row items-start", changeTone(line.change))} style={{ height: REVIEW_COMMENT_LINE_HEIGHT }} > - - {lineNumber ?? ""} - + - {getReviewChangeMarker(line.change)} + {lineNumber ?? ""} diff --git a/apps/mobile/src/features/threads/review/ReviewSheet.tsx b/apps/mobile/src/features/threads/review/ReviewSheet.tsx index 29af80c832..858b0832b9 100644 --- a/apps/mobile/src/features/threads/review/ReviewSheet.tsx +++ b/apps/mobile/src/features/threads/review/ReviewSheet.tsx @@ -1,14 +1,17 @@ import { ThreadId, type OrchestrationCheckpointSummary } from "@t3tools/contracts"; -import { LegendList } from "@legendapp/list/react-native"; import { useLocalSearchParams, useRouter } from "expo-router"; import Stack from "expo-router/stack"; import { SymbolView } from "expo-symbols"; -import { memo, type ReactElement, useCallback, useEffect, useMemo, useState } from "react"; +import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { ActivityIndicator, + FlatList, + InteractionManager, + type ListRenderItemInfo, Pressable, ScrollView, Text as NativeText, + type ViewToken, useColorScheme, useWindowDimensions, View, @@ -32,16 +35,19 @@ import { useReviewCacheForThread, } from "./reviewState"; import { + buildReviewListItems, getReadyReviewCheckpoints, buildReviewSectionItems, getDefaultReviewSectionId, getReviewFilePreviewState, getReviewSectionIdForCheckpoint, + type ReviewListItem, type ReviewParsedDiff, type ReviewRenderableFile, type ReviewRenderableLineRow, } from "./reviewModel"; import { + clearReviewHighlightFileCache, getCachedHighlightedReviewFile, highlightReviewFile, type ReviewDiffTheme, @@ -53,14 +59,17 @@ import { clearReviewCommentTarget, countReviewCommentContexts, formatReviewSelectedRangeLabel, - getReviewChangeMarker, getReviewUnifiedLineNumber, - getSelectedReviewCommentLines, setReviewCommentTarget, type ReviewCommentTarget, useReviewCommentTarget, } from "./reviewCommentSelection"; -import { changeTone, DiffTokenText } from "./reviewDiffRendering"; +import { + changeTone, + DiffTokenText, + REVIEW_MONO_FONT_FAMILY, + ReviewChangeBar, +} from "./reviewDiffRendering"; interface PendingCommentSelection { readonly sectionTitle: string; @@ -77,20 +86,62 @@ interface ReviewLineActionInput { } const IOS_NAV_BAR_HEIGHT = 44; -const REVIEW_HEADER_SPACING = 32; +const REVIEW_HEADER_SPACING = 0; +const REVIEW_LINE_GUTTER_WIDTH = 62; +const REVIEW_CHARACTER_WIDTH_ESTIMATE = 8.4; +const REVIEW_MAX_CONTENT_WIDTH = 4_800; +const REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT = 2; +const REVIEW_HIGHLIGHT_BACKTRACK_COUNT = 0; +const REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT = 1; +const loggedMissingReviewTokenKeys = new Set(); -function changeTypeLabel(type: ReviewRenderableFile["changeType"]): string { - switch (type) { +function isReviewDiffDebugLoggingEnabled(): boolean { + return typeof __DEV__ !== "undefined" ? __DEV__ : false; +} + +function logReviewDiffDiagnostic(message: string, details?: Record): void { + if (!isReviewDiffDebugLoggingEnabled()) { + return; + } + + if (details) { + console.log(`[review-sheet] ${message}`, details); + return; + } + + console.log(`[review-sheet] ${message}`); +} + +function getFileHeaderChrome(changeType: ReviewRenderableFile["changeType"]): { + readonly rail: string; + readonly dot: string; +} { + switch (changeType) { case "new": - return "Added"; + return { + rail: "bg-emerald-400", + dot: "bg-emerald-400", + }; case "deleted": - return "Deleted"; + return { + rail: "bg-rose-400", + dot: "bg-rose-400", + }; case "rename-pure": - return "Renamed"; + return { + rail: "bg-amber-400", + dot: "bg-amber-400", + }; case "rename-changed": - return "Renamed + edited"; + return { + rail: "bg-sky-400", + dot: "bg-sky-400", + }; default: - return "Edited"; + return { + rail: "bg-sky-400", + dot: "bg-sky-400", + }; } } @@ -108,12 +159,70 @@ function formatHeaderDiffSummary(parsedDiff: ReviewParsedDiff): { }; } +function computeReviewListContentWidth( + items: ReadonlyArray, + viewportWidth: number, +): number { + let maxTextLength = 0; + + items.forEach((item) => { + switch (item.kind) { + case "file-header": + maxTextLength = Math.max( + maxTextLength, + item.file.path.length, + item.file.previousPath?.length ?? 0, + ); + break; + case "file-suppressed": + maxTextLength = Math.max(maxTextLength, item.message.length, item.actionLabel?.length ?? 0); + break; + case "hunk": + maxTextLength = Math.max( + maxTextLength, + item.row.header.length + (item.row.context ? item.row.context.length + 1 : 0), + ); + break; + case "line": + maxTextLength = Math.max(maxTextLength, item.row.content.length); + break; + } + }); + + return Math.max( + viewportWidth, + Math.min( + REVIEW_MAX_CONTENT_WIDTH, + Math.ceil(REVIEW_LINE_GUTTER_WIDTH + 48 + maxTextLength * REVIEW_CHARACTER_WIDTH_ESTIMATE), + ), + ); +} + function getDefaultExpandedFileIds( files: ReadonlyArray, ): ReadonlyArray { return files.map((file) => file.id); } +function getHighlightedTokensForLine( + line: ReviewRenderableLineRow, + highlightedFile: ReviewHighlightedFile | null, +): ReadonlyArray | null { + if (!highlightedFile) { + return null; + } + + if (line.additionTokenIndex !== null) { + return highlightedFile.additionLines[line.additionTokenIndex] ?? null; + } + + if (line.deletionTokenIndex !== null) { + return highlightedFile.deletionLines[line.deletionTokenIndex] ?? null; + } + + return null; +} + const ReviewLineRow = memo(function ReviewLineRow(props: { readonly line: ReviewRenderableLineRow; readonly tokens: ReadonlyArray | null; @@ -145,17 +254,19 @@ const ReviewLineRow = memo(function ReviewLineRow(props: { onPress={props.onComment} style={{ minWidth: props.viewportWidth }} > - + + {lineNumber ?? ""} - - {getReviewChangeMarker(props.line.change)} - - + ); @@ -165,41 +276,55 @@ const ReviewFileCard = memo(function ReviewFileCard(props: { readonly file: ReviewRenderableFile; readonly fileId: string; readonly expanded: boolean; + readonly viewportWidth: number; readonly onToggleFile: (fileId: string) => void; }) { + const chrome = getFileHeaderChrome(props.file.changeType); + return ( - - props.onToggleFile(props.fileId)} - > - - - - - - {props.file.path} - - {props.file.previousPath && props.file.previousPath !== props.file.path ? ( - - {props.file.previousPath} - - ) : null} - - - - {changeTypeLabel(props.file.changeType)} - - - + + props.onToggleFile(props.fileId)}> + + + + + + + + + + {props.file.path} + + {props.file.previousPath && props.file.previousPath !== props.file.path ? ( + + {props.file.previousPath} + + ) : null} + + + + +{props.file.additions} - -{props.file.deletions} + + -{props.file.deletions} + @@ -207,117 +332,18 @@ const ReviewFileCard = memo(function ReviewFileCard(props: { ); }); -const ReviewFileBody = memo(function ReviewFileBody(props: { - readonly file: ReviewRenderableFile; - readonly sectionTitle: string; - readonly highlightedFile: ReviewHighlightedFile | null; - readonly viewportWidth: number; - readonly pendingSelection: PendingCommentSelection | null; - readonly selectedTarget: ReviewCommentTarget | null; - readonly onPressLine: (input: ReviewLineActionInput) => void; - readonly onStartRangeSelection: (input: ReviewLineActionInput) => void; -}) { - const commentableLines = useMemo( - () => props.file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"), - [props.file.rows], - ); - const lineIndexById = useMemo( - () => new Map(commentableLines.map((line, index) => [line.id, index])), - [commentableLines], - ); - const anchorLineId = useMemo( - () => - props.pendingSelection && - props.pendingSelection.sectionTitle === props.sectionTitle && - props.pendingSelection.filePath === props.file.path - ? (props.pendingSelection.lines[props.pendingSelection.anchorIndex]?.id ?? null) - : null, - [props.file.path, props.pendingSelection, props.sectionTitle], - ); - const selectedLineIds = useMemo( - () => - props.selectedTarget && - props.selectedTarget.sectionTitle === props.sectionTitle && - props.selectedTarget.filePath === props.file.path - ? new Set(getSelectedReviewCommentLines(props.selectedTarget).map((line) => line.id)) - : null, - [props.file.path, props.sectionTitle, props.selectedTarget], - ); - - return ( - - - {props.file.rows.map((row) => { - if (row.kind === "hunk") { - return ( - - - {row.header} - {row.context ? ` ${row.context}` : ""} - - - ); - } - - const tokens = - row.change === "delete" - ? (props.highlightedFile?.deletionLines[row.deletionTokenIndex ?? -1] ?? null) - : (props.highlightedFile?.additionLines[row.additionTokenIndex ?? -1] ?? null); - - return ( - { - props.onPressLine({ - sectionTitle: props.sectionTitle, - filePath: props.file.path, - lines: commentableLines, - lineIndex: lineIndexById.get(row.id) ?? 0, - }); - }} - onStartRangeSelection={() => { - props.onStartRangeSelection({ - sectionTitle: props.sectionTitle, - filePath: props.file.path, - lines: commentableLines, - lineIndex: lineIndexById.get(row.id) ?? 0, - }); - }} - /> - ); - })} - - - ); -}); - const ReviewFileSuppressedBody = memo(function ReviewFileSuppressedBody(props: { readonly message: string; readonly actionLabel?: string | null; readonly fileId: string; + readonly viewportWidth: number; readonly onLoadDiffFile?: (fileId: string) => void; }) { return ( - + {props.message} {props.actionLabel && props.onLoadDiffFile ? ( void; - readonly onLoadDiffFile: (fileId: string) => void; - readonly onPressLine: (input: ReviewLineActionInput) => void; - readonly onStartRangeSelection: (input: ReviewLineActionInput) => void; }) { - const previewState = useMemo(() => getReviewFilePreviewState(props.file), [props.file]); - const shouldRenderBody = - previewState.kind === "render" || (previewState.reason === "large" && props.revealedLarge); - const highlightCacheKey = `${props.selectedTheme}:${props.file.cacheKey}`; - const [highlightedFile, setHighlightedFile] = useState(() => - getCachedHighlightedReviewFile(props.file, props.selectedTheme), - ); - - useEffect(() => { - setHighlightedFile(getCachedHighlightedReviewFile(props.file, props.selectedTheme)); - }, [highlightCacheKey, props.file, props.selectedTheme]); - - useEffect(() => { - if (!props.expanded || !shouldRenderBody) { - return; - } - - const cached = getCachedHighlightedReviewFile(props.file, props.selectedTheme); - if (cached) { - setHighlightedFile(cached); - return; - } - - let cancelled = false; - void highlightReviewFile(props.file, props.selectedTheme) - .then((result) => { - if (!cancelled) { - setHighlightedFile(result); - } - }) - .catch(() => { - if (cancelled) { - return; - } - }); - - return () => { - cancelled = true; - }; - }, [highlightCacheKey, props.expanded, props.file, props.selectedTheme, shouldRenderBody]); - return ( - <> - - {props.expanded ? ( - shouldRenderBody ? ( - - ) : ( - - ) - ) : null} - + + + {props.header} + {props.context ? ` ${props.context}` : ""} + + ); }); @@ -496,7 +452,18 @@ export function ReviewSheet() { const [error, setError] = useState(null); const [pendingCommentSelection, setPendingCommentSelection] = useState(null); + const [highlightedFilesById, setHighlightedFilesById] = useState< + Record + >({}); + const [visibleFileIds, setVisibleFileIds] = useState>([]); const activeCommentTarget = useReviewCommentTarget(); + const selectedTheme = (colorScheme === "dark" ? "dark" : "light") satisfies ReviewDiffTheme; + const highlightQueueRef = useRef([]); + const highlightRequestedFileIdsRef = useRef>(new Set()); + const highlightQueueGenerationRef = useRef(0); + const highlightQueueActiveRef = useRef(false); + const highlightableFilesByIdRef = useRef>(new Map()); + const selectedThemeRef = useRef(selectedTheme); const cwd = selectedThread?.worktreePath ?? selectedThreadProject?.workspaceRoot ?? null; const readyCheckpoints = useMemo( @@ -544,7 +511,6 @@ export function ReviewSheet() { [draftMessage], ); - const selectedTheme = (colorScheme === "dark" ? "dark" : "light") satisfies ReviewDiffTheme; const expandedFileIds = useMemo( () => selectedSection?.id && parsedDiff.kind === "files" @@ -560,6 +526,120 @@ export function ReviewSheet() { : [], [reviewCache.revealedLargeFileIdsBySection, selectedSection?.id], ); + const reviewListItems = useMemo( + () => + selectedSection && parsedDiff.kind === "files" + ? buildReviewListItems({ + files: parsedDiff.files, + expandedFileIds, + revealedLargeFileIds, + }) + : [], + [expandedFileIds, parsedDiff, revealedLargeFileIds, selectedSection], + ); + const reviewFileById = useMemo(() => { + if (parsedDiff.kind !== "files") { + return new Map(); + } + + return new Map(parsedDiff.files.map((file) => [file.id, file] as const)); + }, [parsedDiff]); + const reviewLineRowsByFileId = useMemo(() => { + if (parsedDiff.kind !== "files") { + return new Map>(); + } + + return new Map( + parsedDiff.files.map((file) => [ + file.id, + file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line"), + ]), + ); + }, [parsedDiff]); + const reviewLineIndexByRowId = useMemo(() => { + const map = new Map(); + + reviewLineRowsByFileId.forEach((rows) => { + rows.forEach((row, index) => { + map.set(row.id, index); + }); + }); + + return map; + }, [reviewLineRowsByFileId]); + const highlightableFiles = useMemo(() => { + if (parsedDiff.kind !== "files") { + return [] as ReadonlyArray; + } + + const expandedFileIdSet = new Set(expandedFileIds); + const revealedLargeFileIdSet = new Set(revealedLargeFileIds); + + return parsedDiff.files.filter((file) => { + if (!expandedFileIdSet.has(file.id)) { + return false; + } + + const previewState = getReviewFilePreviewState(file); + return ( + previewState.kind === "render" || + (previewState.reason === "large" && revealedLargeFileIdSet.has(file.id)) + ); + }); + }, [expandedFileIds, parsedDiff, revealedLargeFileIds]); + const highlightableFileIds = useMemo( + () => new Set(highlightableFiles.map((file) => file.id)), + [highlightableFiles], + ); + const priorityHighlightFileIds = useMemo(() => { + if (parsedDiff.kind !== "files" || highlightableFiles.length === 0) { + return [] as ReadonlyArray; + } + + const fileIdsInPriorityOrder = + visibleFileIds.length > 0 + ? visibleFileIds.filter((fileId) => highlightableFileIds.has(fileId)) + : parsedDiff.files + .slice(0, REVIEW_INITIAL_HIGHLIGHT_FILE_COUNT) + .map((file) => file.id) + .filter((fileId) => highlightableFileIds.has(fileId)); + + if (fileIdsInPriorityOrder.length === 0) { + return [] as ReadonlyArray; + } + + const firstVisibleIndex = parsedDiff.files.findIndex( + (file) => file.id === fileIdsInPriorityOrder[0], + ); + const lastVisibleIndex = parsedDiff.files.findIndex( + (file) => file.id === fileIdsInPriorityOrder[fileIdsInPriorityOrder.length - 1], + ); + + if (firstVisibleIndex < 0 || lastVisibleIndex < 0) { + return fileIdsInPriorityOrder; + } + + const startIndex = Math.max(0, firstVisibleIndex - REVIEW_HIGHLIGHT_BACKTRACK_COUNT); + const endIndex = Math.min( + parsedDiff.files.length - 1, + lastVisibleIndex + REVIEW_HIGHLIGHT_LOOKAHEAD_COUNT, + ); + + const queuedIds: string[] = []; + for (let index = startIndex; index <= endIndex; index += 1) { + const fileId = parsedDiff.files[index]?.id; + if (fileId && highlightableFileIds.has(fileId)) { + queuedIds.push(fileId); + } + } + + return queuedIds; + }, [highlightableFileIds, highlightableFiles.length, parsedDiff, visibleFileIds]); + const viewportWidth = Math.max(width, 280); + const reviewListContentWidth = useMemo( + () => computeReviewListContentWidth(reviewListItems, viewportWidth), + [reviewListItems, viewportWidth], + ); const loadGitDiffs = useCallback(async () => { if (!environmentId || !cwd) { return; @@ -634,6 +714,100 @@ export function ReviewSheet() { void loadGitDiffs(); }, [loadGitDiffs]); + useEffect(() => { + selectedThemeRef.current = selectedTheme; + }, [selectedTheme]); + + useEffect(() => { + highlightableFilesByIdRef.current = new Map(highlightableFiles.map((file) => [file.id, file])); + }, [highlightableFiles]); + + const startHighlightQueueRunner = useCallback(function startHighlightQueueRunner() { + if (highlightQueueActiveRef.current) { + return; + } + + const generation = highlightQueueGenerationRef.current; + highlightQueueActiveRef.current = true; + + void (async () => { + try { + while (generation === highlightQueueGenerationRef.current) { + const nextFileId = highlightQueueRef.current.shift(); + if (!nextFileId) { + break; + } + + const file = highlightableFilesByIdRef.current.get(nextFileId); + if (!file) { + continue; + } + + const theme = selectedThemeRef.current; + const cached = getCachedHighlightedReviewFile(file, theme); + if (cached) { + logReviewDiffDiagnostic("using cached highlighted file", { + fileId: file.id, + filePath: file.path, + theme, + }); + setHighlightedFilesById((current) => + current[file.id] === cached ? current : { ...current, [file.id]: cached }, + ); + continue; + } + + logReviewDiffDiagnostic("requesting highlighted file", { + fileId: file.id, + filePath: file.path, + theme, + }); + + try { + await new Promise((resolve) => { + InteractionManager.runAfterInteractions(() => resolve()); + }); + const result = await highlightReviewFile(file, theme); + if (generation !== highlightQueueGenerationRef.current) { + logReviewDiffDiagnostic("discarding highlighted file after cancellation", { + fileId: file.id, + filePath: file.path, + }); + return; + } + + logReviewDiffDiagnostic("received highlighted file", { + fileId: file.id, + filePath: file.path, + additionLines: result.additionLines.length, + deletionLines: result.deletionLines.length, + }); + setHighlightedFilesById((current) => { + if (current[file.id] === result) { + return current; + } + return { ...current, [file.id]: result }; + }); + } catch (error) { + logReviewDiffDiagnostic("highlight request failed", { + fileId: file.id, + filePath: file.path, + error: error instanceof Error ? error.message : String(error), + }); + } + } + } finally { + highlightQueueActiveRef.current = false; + if ( + generation === highlightQueueGenerationRef.current && + highlightQueueRef.current.length > 0 + ) { + startHighlightQueueRunner(); + } + } + })(); + }, []); + useEffect(() => { if (reviewSections.length === 0) { return; @@ -711,6 +885,71 @@ export function ReviewSheet() { }); }, [parsedDiff, reviewCache.threadKey, selectedSection?.id]); + useEffect(() => { + setHighlightedFilesById({}); + setVisibleFileIds([]); + highlightQueueGenerationRef.current += 1; + highlightQueueRef.current = []; + highlightRequestedFileIdsRef.current = new Set(); + highlightQueueActiveRef.current = false; + clearReviewHighlightFileCache(); + loggedMissingReviewTokenKeys.clear(); + logReviewDiffDiagnostic("reset highlighted files", { + selectedSectionId: selectedSection?.id ?? null, + selectedTheme, + }); + }, [selectedSection?.id, selectedTheme]); + + useEffect(() => { + if (parsedDiff.kind !== "files") { + return; + } + + logReviewDiffDiagnostic("parsed diff files", { + selectedSectionId: selectedSection?.id ?? null, + fileCount: parsedDiff.fileCount, + renderableFileCount: parsedDiff.files.length, + }); + }, [parsedDiff, selectedSection?.id]); + + useEffect(() => { + if (priorityHighlightFileIds.length === 0) { + logReviewDiffDiagnostic("no highlightable files", { + selectedSectionId: selectedSection?.id ?? null, + parsedDiffKind: parsedDiff.kind, + requestedFileCount: 0, + }); + return; + } + + const queuedFileIds: string[] = []; + priorityHighlightFileIds.forEach((fileId) => { + if (highlightRequestedFileIdsRef.current.has(fileId)) { + return; + } + + const file = highlightableFilesByIdRef.current.get(fileId); + if (!file) { + return; + } + + highlightRequestedFileIdsRef.current.add(fileId); + highlightQueueRef.current.push(fileId); + queuedFileIds.push(fileId); + }); + + if (queuedFileIds.length === 0) { + return; + } + + logReviewDiffDiagnostic("scheduling file highlights", { + selectedSectionId: selectedSection?.id ?? null, + fileCount: queuedFileIds.length, + fileIds: queuedFileIds, + }); + startHighlightQueueRunner(); + }, [parsedDiff.kind, priorityHighlightFileIds, selectedSection?.id, startHighlightQueueRunner]); + const refreshSelectedSection = useCallback(async () => { if (!selectedSection) { return; @@ -841,77 +1080,166 @@ export function ReviewSheet() { return <>{children}; }, [error, parsedDiffNotice]); + const stickyHeaderIndices = useMemo(() => { + const itemOffset = listHeader ? 1 : 0; - const renderFileItem = useCallback( - ({ item }: { item: ReviewRenderableFile; index: number }) => { + return reviewListItems.flatMap((item, index) => + item.kind === "file-header" ? [index + itemOffset] : [], + ); + }, [listHeader, reviewListItems]); + + const viewabilityConfigRef = useRef({ + itemVisiblePercentThreshold: 10, + }); + const onViewableItemsChangedRef = useRef( + ({ + viewableItems, + }: { + readonly viewableItems: Array>; + readonly changed: Array>; + }) => { + const nextVisibleFileIds = Array.from( + new Set( + viewableItems + .filter((token) => token.isViewable && token.item !== undefined) + .map((token) => token.item.fileId), + ), + ); + + setVisibleFileIds(nextVisibleFileIds); + }, + ); + + const renderReviewListItem = useCallback( + ({ item }: ListRenderItemInfo) => { if (!selectedSection) { return null; } - const pendingSelectionForFile = - pendingCommentSelection && - pendingCommentSelection.sectionTitle === selectedSection.title && - pendingCommentSelection.filePath === item.path - ? pendingCommentSelection - : null; - const selectedTargetForFile = - activeCommentTarget && - activeCommentTarget.sectionTitle === selectedSection.title && - activeCommentTarget.filePath === item.path - ? activeCommentTarget - : null; - return ( - - ); + switch (item.kind) { + case "file-header": + return ( + + ); + case "file-suppressed": + return ( + + ); + case "hunk": + return ( + + ); + case "line": { + const file = reviewFileById.get(item.fileId); + if (!file) { + return null; + } + + const fileLineRows = reviewLineRowsByFileId.get(file.id) ?? []; + const lineIndex = reviewLineIndexByRowId.get(item.row.id); + if (lineIndex === undefined) { + return null; + } + + const pendingSelectionForFile = + pendingCommentSelection && + pendingCommentSelection.sectionTitle === selectedSection.title && + pendingCommentSelection.filePath === file.path + ? pendingCommentSelection + : null; + const selectedTargetForFile = + activeCommentTarget && + activeCommentTarget.sectionTitle === selectedSection.title && + activeCommentTarget.filePath === file.path + ? activeCommentTarget + : null; + const highlightedFile = + highlightedFilesById[file.id] ?? + getCachedHighlightedReviewFile(file, selectedTheme) ?? + null; + + if (highlightedFile === null) { + const missingTokenKey = `${selectedSection.id}:${file.id}`; + if (!loggedMissingReviewTokenKeys.has(missingTokenKey)) { + loggedMissingReviewTokenKeys.add(missingTokenKey); + logReviewDiffDiagnostic("rendering file without tokens", { + sectionId: selectedSection.id, + fileId: file.id, + filePath: file.path, + highlightedFileKnownInState: highlightedFilesById[file.id] !== undefined, + }); + } + } + + const selectionState = + pendingSelectionForFile?.anchorIndex === lineIndex + ? ("anchor" as const) + : selectedTargetForFile && + lineIndex >= selectedTargetForFile.startIndex && + lineIndex <= selectedTargetForFile.endIndex + ? ("selected" as const) + : null; + + return ( + + handlePressLine({ + sectionTitle: selectedSection.title, + filePath: file.path, + lines: fileLineRows, + lineIndex, + }) + } + onStartRangeSelection={() => + handleStartRangeSelection({ + sectionTitle: selectedSection.title, + filePath: file.path, + lines: fileLineRows, + lineIndex, + }) + } + /> + ); + } + } }, [ activeCommentTarget, - expandedFileIds, handlePressLine, handleRevealLargeDiff, handleStartRangeSelection, handleToggleExpandedFile, + highlightedFilesById, pendingCommentSelection, - revealedLargeFileIds, + reviewFileById, + reviewLineIndexByRowId, + reviewLineRowsByFileId, + reviewListContentWidth, selectedSection, selectedTheme, - width, ], ); - const visibleListExtraData = useMemo(() => { - return { - selectedSectionId: selectedSection?.id ?? null, - selectedTheme, - expandedFileIds, - revealedLargeFileIds, - pendingSelection: pendingCommentSelection, - selectedTarget: activeCommentTarget, - viewportWidth: Math.max(width, 280), - }; - }, [ - activeCommentTarget, - expandedFileIds, - pendingCommentSelection, - revealedLargeFileIds, - selectedSection, - selectedTheme, - width, - ]); - return ( <> {selectedSection && parsedDiff.kind === "files" ? ( - file.id} - extraData={visibleListExtraData} + data={reviewListItems} + renderItem={renderReviewListItem} + keyExtractor={(item) => item.id} keyboardShouldPersistTaps="handled" - estimatedItemSize={220} - drawDistance={900} - recycleItems ListHeaderComponent={listHeader} + stickyHeaderIndices={stickyHeaderIndices} + removeClippedSubviews={false} + initialNumToRender={24} + maxToRenderPerBatch={16} + updateCellsBatchingPeriod={16} + windowSize={10} + scrollEventThrottle={16} + onViewableItemsChanged={onViewableItemsChangedRef.current} + viewabilityConfig={viewabilityConfigRef.current} contentContainerStyle={{ paddingTop: REVIEW_HEADER_SPACING, paddingBottom: Math.max(insets.bottom, 18) + 18, diff --git a/apps/mobile/src/features/threads/review/reviewDiffRendering.tsx b/apps/mobile/src/features/threads/review/reviewDiffRendering.tsx index 6f63993e4f..20199adf6a 100644 --- a/apps/mobile/src/features/threads/review/reviewDiffRendering.tsx +++ b/apps/mobile/src/features/threads/review/reviewDiffRendering.tsx @@ -1,4 +1,4 @@ -import { Platform, Text as NativeText } from "react-native"; +import { Platform, Text as NativeText, View } from "react-native"; import { cn } from "../../../lib/cn"; @@ -17,14 +17,47 @@ export function renderVisibleWhitespace(value: string): string { } export function changeTone(change: ReviewRenderableLineRow["change"]): string { - if (change === "add") return "bg-emerald-500/12"; - if (change === "delete") return "bg-rose-500/12"; + if (change === "add") return "bg-emerald-500/10"; + if (change === "delete") return "bg-rose-500/10"; return "bg-card"; } +export function changeBarTone(change: ReviewRenderableLineRow["change"]): string { + if (change === "add") return "bg-emerald-400"; + if (change === "delete") return "bg-rose-400"; + return "bg-border/50"; +} + +function diffHighlightColor(change: ReviewRenderableLineRow["change"]): string | undefined { + if (change === "add") return "rgba(16, 185, 129, 0.24)"; + if (change === "delete") return "rgba(244, 63, 94, 0.24)"; + return undefined; +} + +export function ReviewChangeBar(props: { readonly change: ReviewRenderableLineRow["change"] }) { + if (props.change === "delete") { + return ( + + + {Array.from({ length: 6 }, (_, index) => ( + + ))} + + + ); + } + + return ( + + + + ); +} + export function DiffTokenText(props: { readonly tokens: ReadonlyArray | null; readonly fallback: string; + readonly change?: ReviewRenderableLineRow["change"]; readonly className?: string; }) { if (!props.tokens || props.tokens.length === 0) { @@ -70,6 +103,11 @@ export function DiffTokenText(props: { fontFamily: REVIEW_MONO_FONT_FAMILY, fontWeight, fontStyle, + backgroundColor: + token.diffHighlight && props.change + ? diffHighlightColor(props.change) + : undefined, + borderRadius: token.diffHighlight ? 4 : undefined, }} > {token.content.length > 0 ? renderVisibleWhitespace(token.content) : " "} diff --git a/apps/mobile/src/features/threads/review/reviewHighlighterEngine.test.ts b/apps/mobile/src/features/threads/review/reviewHighlighterEngine.test.ts index 257c134f1a..d63a7a67c6 100644 --- a/apps/mobile/src/features/threads/review/reviewHighlighterEngine.test.ts +++ b/apps/mobile/src/features/threads/review/reviewHighlighterEngine.test.ts @@ -13,6 +13,7 @@ describe("resolveReviewHighlighterEnginePreference", () => { it("accepts supported values", () => { expect(resolveReviewHighlighterEnginePreference("javascript")).toBe("javascript"); + expect(resolveReviewHighlighterEnginePreference("js")).toBe("javascript"); expect(resolveReviewHighlighterEnginePreference("native")).toBe("native"); }); }); diff --git a/apps/mobile/src/features/threads/review/reviewHighlighterEngine.ts b/apps/mobile/src/features/threads/review/reviewHighlighterEngine.ts index 918e1192d8..5ef9f055a6 100644 --- a/apps/mobile/src/features/threads/review/reviewHighlighterEngine.ts +++ b/apps/mobile/src/features/threads/review/reviewHighlighterEngine.ts @@ -5,9 +5,11 @@ export function resolveReviewHighlighterEnginePreference( value: string | undefined, ): ReviewHighlighterEnginePreference { switch (value) { + case "js": case "javascript": + return "javascript"; case "native": - return value; + return "native"; default: return "javascript"; } diff --git a/apps/mobile/src/features/threads/review/reviewModel.test.ts b/apps/mobile/src/features/threads/review/reviewModel.test.ts index 8a0331c8c5..a24a99ceb4 100644 --- a/apps/mobile/src/features/threads/review/reviewModel.test.ts +++ b/apps/mobile/src/features/threads/review/reviewModel.test.ts @@ -8,6 +8,7 @@ import { } from "@t3tools/contracts"; import { + buildReviewListItems, buildReviewParsedDiff, buildReviewSectionItems, getDefaultReviewSectionId, @@ -138,6 +139,7 @@ describe("buildReviewParsedDiff", () => { oldLineNumber: 1, newLineNumber: null, content: "const before = 1;", + comparison: { change: "add", tokenIndex: 0 }, }), expect.objectContaining({ kind: "line", @@ -145,6 +147,7 @@ describe("buildReviewParsedDiff", () => { oldLineNumber: null, newLineNumber: 1, content: "const after = 2;", + comparison: { change: "delete", tokenIndex: 0 }, }), expect.objectContaining({ kind: "line", @@ -152,6 +155,7 @@ describe("buildReviewParsedDiff", () => { oldLineNumber: null, newLineNumber: 2, content: "console.log(after);", + comparison: null, }), expect.objectContaining({ kind: "line", @@ -159,6 +163,7 @@ describe("buildReviewParsedDiff", () => { oldLineNumber: 2, newLineNumber: 3, content: "return true;", + comparison: null, }), ]); }); @@ -220,6 +225,7 @@ describe("buildReviewParsedDiff", () => { content: `const line${index} = ${index};`, additionTokenIndex: index, deletionTokenIndex: null, + comparison: null, })), }), ); @@ -231,4 +237,73 @@ describe("buildReviewParsedDiff", () => { actionLabel: "Load diff", }); }); + + it("flattens expanded files into virtualizable review items", () => { + const file = makeRenderableFile({ + path: "apps/mobile/src/a.ts", + rows: [ + { + kind: "hunk", + id: "hunk-1", + header: "@@ -1,1 +1,2 @@", + context: null, + }, + { + kind: "line", + id: "line-1", + change: "add", + oldLineNumber: null, + newLineNumber: 1, + content: "const after = 2;", + additionTokenIndex: 0, + deletionTokenIndex: null, + comparison: null, + }, + ], + }); + + const items = buildReviewListItems({ + files: [file], + expandedFileIds: [file.id], + revealedLargeFileIds: [], + }); + + expect(items).toEqual([ + expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }), + expect.objectContaining({ kind: "hunk", fileId: file.id, row: file.rows[0] }), + expect.objectContaining({ kind: "line", fileId: file.id, row: file.rows[1] }), + ]); + }); + + it("keeps large diffs collapsed into a placeholder item until revealed", () => { + const file = makeRenderableFile({ + path: "apps/mobile/src/big.ts", + rows: Array.from({ length: 401 }, (_, index) => ({ + kind: "line" as const, + id: `line-${index}`, + change: "add" as const, + oldLineNumber: null, + newLineNumber: index + 1, + content: `const line${index} = ${index};`, + additionTokenIndex: index, + deletionTokenIndex: null, + comparison: null, + })), + }); + + const items = buildReviewListItems({ + files: [file], + expandedFileIds: [file.id], + revealedLargeFileIds: [], + }); + + expect(items).toEqual([ + expect.objectContaining({ kind: "file-header", fileId: file.id, expanded: true }), + expect.objectContaining({ + kind: "file-suppressed", + fileId: file.id, + actionLabel: "Load diff", + }), + ]); + }); }); diff --git a/apps/mobile/src/features/threads/review/reviewModel.ts b/apps/mobile/src/features/threads/review/reviewModel.ts index 6762999748..27e6d7ae40 100644 --- a/apps/mobile/src/features/threads/review/reviewModel.ts +++ b/apps/mobile/src/features/threads/review/reviewModel.ts @@ -30,6 +30,10 @@ export interface ReviewRenderableLineRow { readonly content: string; readonly additionTokenIndex: number | null; readonly deletionTokenIndex: number | null; + readonly comparison: { + readonly change: "add" | "delete"; + readonly tokenIndex: number; + } | null; } export type ReviewRenderableRow = ReviewRenderableHunkRow | ReviewRenderableLineRow; @@ -48,6 +52,42 @@ export interface ReviewRenderableFile { readonly rows: ReadonlyArray; } +export interface ReviewFileHeaderListItem { + readonly kind: "file-header"; + readonly id: string; + readonly fileId: string; + readonly file: ReviewRenderableFile; + readonly expanded: boolean; +} + +export interface ReviewFileSuppressedListItem { + readonly kind: "file-suppressed"; + readonly id: string; + readonly fileId: string; + readonly message: string; + readonly actionLabel: string | null; +} + +export interface ReviewHunkListItem { + readonly kind: "hunk"; + readonly id: string; + readonly fileId: string; + readonly row: ReviewRenderableHunkRow; +} + +export interface ReviewLineListItem { + readonly kind: "line"; + readonly id: string; + readonly fileId: string; + readonly row: ReviewRenderableLineRow; +} + +export type ReviewListItem = + | ReviewFileHeaderListItem + | ReviewFileSuppressedListItem + | ReviewHunkListItem + | ReviewLineListItem; + export type ReviewFilePreviewState = | { readonly kind: "render"; @@ -267,6 +307,72 @@ export function getReviewFilePreviewState(file: ReviewRenderableFile): ReviewFil return { kind: "render" }; } +// The flattened review list item model is inspired by pierre/diffs' iterator-first +// virtualization architecture, adapted here for React Native and LegendList. +// Original project: https://github.com/pingdotgg/pierre/tree/main/packages/diffs +// Reference files: +// - src/utils/iterateOverDiff.ts +// - src/components/VirtualizedFileDiff.ts +export function buildReviewListItems(input: { + readonly files: ReadonlyArray; + readonly expandedFileIds: ReadonlyArray; + readonly revealedLargeFileIds: ReadonlyArray; +}): ReadonlyArray { + const expandedFileIds = new Set(input.expandedFileIds); + const revealedLargeFileIds = new Set(input.revealedLargeFileIds); + const items: ReviewListItem[] = []; + + input.files.forEach((file) => { + const expanded = expandedFileIds.has(file.id); + items.push({ + kind: "file-header", + id: `${file.id}:header`, + fileId: file.id, + file, + expanded, + }); + + if (!expanded) { + return; + } + + const previewState = getReviewFilePreviewState(file); + if (previewState.kind === "suppressed") { + if (previewState.reason !== "large" || !revealedLargeFileIds.has(file.id)) { + items.push({ + kind: "file-suppressed", + id: `${file.id}:suppressed`, + fileId: file.id, + message: previewState.message, + actionLabel: previewState.actionLabel, + }); + return; + } + } + + file.rows.forEach((row) => { + if (row.kind === "hunk") { + items.push({ + kind: "hunk", + id: row.id, + fileId: file.id, + row, + }); + return; + } + + items.push({ + kind: "line", + id: row.id, + fileId: file.id, + row, + }); + }); + }); + + return items; +} + function fallbackHunkHeader(hunk: FileDiffMetadata["hunks"][number]): string { return `@@ -${hunk.deletionStart},${hunk.deletionCount} +${hunk.additionStart},${hunk.additionCount} @@`; } @@ -304,6 +410,7 @@ function buildRenderableRows(file: FileDiffMetadata): ReadonlyArray { + it("joins adjacent word replacements across a single shared separator", () => { + const ranges = computeWordAltDiffRanges({ + deletionLine: "old old", + additionLine: "new new", + }); + + expect(ranges.deletion).toEqual([{ start: 0, end: "old old".length }]); + expect(ranges.addition).toEqual([{ start: 0, end: "new new".length }]); + }); + + it("skips inline word diffs for long lines", () => { + const longDeletion = `const before = "${"a".repeat(1_001)}";`; + const longAddition = `const after = "${"b".repeat(1_001)}";`; + + const ranges = computeWordAltDiffRanges({ + deletionLine: longDeletion, + additionLine: longAddition, + }); + + expect(ranges.deletion).toEqual([]); + expect(ranges.addition).toEqual([]); + }); +}); + +describe("applyDiffRangesToTokens", () => { + it("splits highlighted fragments out of syntax tokens", () => { + const tokens = [ + { + content: "const before = 1;", + color: "#fff", + fontStyle: null, + }, + ]; + const nextTokens = applyDiffRangesToTokens(tokens, [{ start: 6, end: 12 }]); + + expect(nextTokens).toEqual([ + { + content: "const ", + color: "#fff", + fontStyle: null, + diffHighlight: false, + }, + { + content: "before", + color: "#fff", + fontStyle: null, + diffHighlight: true, + }, + { + content: " = 1;", + color: "#fff", + fontStyle: null, + diffHighlight: false, + }, + ]); + }); +}); diff --git a/apps/mobile/src/features/threads/review/reviewWordDiffs.ts b/apps/mobile/src/features/threads/review/reviewWordDiffs.ts new file mode 100644 index 0000000000..2dbca88fd4 --- /dev/null +++ b/apps/mobile/src/features/threads/review/reviewWordDiffs.ts @@ -0,0 +1,266 @@ +import { diffWordsWithSpace } from "diff"; + +import type { ReviewHighlightedToken } from "./shikiReviewHighlighter"; + +interface ReviewDiffOperation { + readonly value: string; + readonly added?: true; + readonly removed?: true; +} + +interface ReviewDiffHighlightRange { + readonly start: number; + readonly end: number; +} + +const REVIEW_MAX_WORD_ALT_LINE_LENGTH = 1_000; + +function cleanLineEnding(value: string): string { + return value.endsWith("\n") ? value.slice(0, -1) : value; +} + +function pushOrJoinSpan(input: { + readonly operation: ReviewDiffOperation; + readonly spans: Array<[0 | 1, string]>; + readonly enableJoin: boolean; + readonly isNeutral?: boolean; + readonly isLastOperation?: boolean; +}): void { + const { operation, spans, enableJoin, isNeutral = false, isLastOperation = false } = input; + const lastSpan = spans.at(-1); + + if (!lastSpan || isLastOperation || !enableJoin) { + spans.push([isNeutral ? 0 : 1, operation.value]); + return; + } + + const lastSpanIsNeutral = lastSpan[0] === 0; + if ( + isNeutral === lastSpanIsNeutral || + (isNeutral && operation.value.length === 1 && !lastSpanIsNeutral) + ) { + lastSpan[1] += operation.value; + return; + } + + spans.push([isNeutral ? 0 : 1, operation.value]); +} + +function spansToRanges( + spans: ReadonlyArray, +): ReadonlyArray { + const ranges: ReviewDiffHighlightRange[] = []; + let offset = 0; + + spans.forEach(([kind, value]) => { + const nextOffset = offset + value.length; + if (kind === 1 && value.length > 0) { + ranges.push({ start: offset, end: nextOffset }); + } + offset = nextOffset; + }); + + return ranges; +} + +function mergeNearbyRanges( + ranges: ReadonlyArray, +): ReadonlyArray { + if (ranges.length <= 1) { + return ranges; + } + + const merged: ReviewDiffHighlightRange[] = []; + + ranges.forEach((range) => { + const previous = merged.at(-1); + if (previous && range.start - previous.end <= 1) { + merged[merged.length - 1] = { start: previous.start, end: range.end }; + return; + } + merged.push({ ...range }); + }); + + return merged; +} + +function appendTokenSegment( + target: ReviewHighlightedToken[], + source: ReviewHighlightedToken, + content: string, + diffHighlight: boolean, +): void { + if (content.length === 0) { + return; + } + + const previous = target.at(-1); + if ( + previous && + previous.color === source.color && + previous.fontStyle === source.fontStyle && + previous.diffHighlight === diffHighlight + ) { + previous.content += content; + return; + } + + target.push({ + content, + color: source.color, + fontStyle: source.fontStyle, + diffHighlight, + }); +} + +export function computeWordAltDiffRanges(input: { + readonly deletionLine: string; + readonly additionLine: string; +}): { + readonly deletion: ReadonlyArray; + readonly addition: ReadonlyArray; +} { + const deletionLine = cleanLineEnding(input.deletionLine); + const additionLine = cleanLineEnding(input.additionLine); + + if (deletionLine.length === 0 && additionLine.length === 0) { + return { deletion: [], addition: [] }; + } + + if ( + deletionLine.length > REVIEW_MAX_WORD_ALT_LINE_LENGTH || + additionLine.length > REVIEW_MAX_WORD_ALT_LINE_LENGTH + ) { + return { deletion: [], addition: [] }; + } + + const operations = diffWordsWithSpace( + deletionLine, + additionLine, + ) as ReadonlyArray; + const deletionSpans: Array<[0 | 1, string]> = []; + const additionSpans: Array<[0 | 1, string]> = []; + const lastOperation = operations.at(-1); + + operations.forEach((operation) => { + const isLastOperation = operation === lastOperation; + if (!operation.added && !operation.removed) { + pushOrJoinSpan({ + operation, + spans: deletionSpans, + enableJoin: true, + isNeutral: true, + isLastOperation, + }); + pushOrJoinSpan({ + operation, + spans: additionSpans, + enableJoin: true, + isNeutral: true, + isLastOperation, + }); + return; + } + + if (operation.removed) { + pushOrJoinSpan({ + operation, + spans: deletionSpans, + enableJoin: true, + isLastOperation, + }); + return; + } + + pushOrJoinSpan({ + operation, + spans: additionSpans, + enableJoin: true, + isLastOperation, + }); + }); + + return { + deletion: mergeNearbyRanges(spansToRanges(deletionSpans)), + addition: mergeNearbyRanges(spansToRanges(additionSpans)), + }; +} + +export function applyDiffRangesToTokens( + tokens: ReadonlyArray, + ranges: ReadonlyArray, +): ReadonlyArray { + if (tokens.length === 0 || ranges.length === 0) { + return tokens; + } + + const nextTokens: ReviewHighlightedToken[] = []; + let tokenOffset = 0; + let rangeIndex = 0; + + tokens.forEach((token) => { + const tokenStart = tokenOffset; + const tokenEnd = tokenStart + token.content.length; + tokenOffset = tokenEnd; + + if (token.content.length === 0) { + nextTokens.push(token); + return; + } + + while ((ranges[rangeIndex]?.end ?? 0) <= tokenStart) { + rangeIndex += 1; + } + + if ((ranges[rangeIndex]?.start ?? Number.POSITIVE_INFINITY) >= tokenEnd) { + nextTokens.push(token.diffHighlight ? { ...token, diffHighlight: false } : token); + return; + } + + let cursor = tokenStart; + let localRangeIndex = rangeIndex; + + while ((ranges[localRangeIndex]?.start ?? Number.POSITIVE_INFINITY) < tokenEnd) { + const range = ranges[localRangeIndex]; + if (!range) { + break; + } + + if (range.start > cursor) { + appendTokenSegment( + nextTokens, + token, + token.content.slice(cursor - tokenStart, range.start - tokenStart), + false, + ); + } + + const highlightedStart = Math.max(cursor, range.start); + const highlightedEnd = Math.min(tokenEnd, range.end); + + if (highlightedEnd > highlightedStart) { + appendTokenSegment( + nextTokens, + token, + token.content.slice(highlightedStart - tokenStart, highlightedEnd - tokenStart), + true, + ); + } + + cursor = highlightedEnd; + if (range.end <= tokenEnd) { + localRangeIndex += 1; + } else { + break; + } + } + + if (cursor < tokenEnd) { + appendTokenSegment(nextTokens, token, token.content.slice(cursor - tokenStart), false); + } + + rangeIndex = localRangeIndex; + }); + + return nextTokens; +} diff --git a/apps/mobile/src/features/threads/review/shikiReviewHighlighter.test.ts b/apps/mobile/src/features/threads/review/shikiReviewHighlighter.test.ts index 35a4de32d5..05b5c9213c 100644 --- a/apps/mobile/src/features/threads/review/shikiReviewHighlighter.test.ts +++ b/apps/mobile/src/features/threads/review/shikiReviewHighlighter.test.ts @@ -41,4 +41,73 @@ describe("highlightReviewFile", () => { expect(highlighted.additionLines[2]?.some((token) => token.content === "const")).toBe(true); expect(highlighted.additionLines[3]?.some((token) => token.content === "expect")).toBe(true); }); + + it("adds word-alt diff emphasis for paired deletion and addition lines", async () => { + const file = makeRenderableFile({ + path: "apps/mobile/src/example-inline-diff.test.ts", + additionLines: ["const after = 2;"], + deletionLines: ["const before = 1;"], + rows: [ + { + kind: "line", + id: "delete-1", + change: "delete", + oldLineNumber: 1, + newLineNumber: null, + content: "const before = 1;", + additionTokenIndex: null, + deletionTokenIndex: 0, + comparison: { change: "add", tokenIndex: 0 }, + }, + { + kind: "line", + id: "add-1", + change: "add", + oldLineNumber: null, + newLineNumber: 1, + content: "const after = 2;", + additionTokenIndex: 0, + deletionTokenIndex: null, + comparison: { change: "delete", tokenIndex: 0 }, + }, + ], + }); + + const highlighted = await highlightReviewFile(file, "light"); + + expect(highlighted.deletionLines[0]?.some((token) => token.diffHighlight === true)).toBe(true); + expect(highlighted.additionLines[0]?.some((token) => token.diffHighlight === true)).toBe(true); + }); + + it("falls back to plain tokens for very long lines", async () => { + const longLine = `const value = "${"a".repeat(1_100)}";`; + const file = makeRenderableFile({ + path: "apps/mobile/src/example-long-line.ts", + additionLines: [longLine], + rows: [ + { + kind: "line", + id: "add-1", + change: "add", + oldLineNumber: null, + newLineNumber: 1, + content: longLine, + additionTokenIndex: 0, + deletionTokenIndex: null, + comparison: null, + }, + ], + }); + + const highlighted = await highlightReviewFile(file, "light"); + + expect(highlighted.additionLines).toHaveLength(1); + expect(highlighted.additionLines[0]).toEqual([ + { + content: longLine, + color: null, + fontStyle: null, + }, + ]); + }); }); diff --git a/apps/mobile/src/features/threads/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/threads/review/shikiReviewHighlighter.ts index c8afd7e767..f7a5c4125f 100644 --- a/apps/mobile/src/features/threads/review/shikiReviewHighlighter.ts +++ b/apps/mobile/src/features/threads/review/shikiReviewHighlighter.ts @@ -8,13 +8,15 @@ import { type ReviewHighlighterEngine, } from "./reviewHighlighterEngine"; import type { ReviewRenderableFile, ReviewRenderableLineRow } from "./reviewModel"; +import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs"; export type ReviewDiffTheme = "light" | "dark"; export interface ReviewHighlightedToken { - readonly content: string; + content: string; readonly color: string | null; readonly fontStyle: number | null; + readonly diffHighlight?: boolean; } export interface ReviewHighlightedFile { @@ -26,13 +28,19 @@ const SHIKI_THEME_NAME_BY_SCHEME = { light: "github-light-default", dark: "github-dark-default", } as const; +const REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE = + process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? "javascript"; const REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE = resolveReviewHighlighterEnginePreference( - process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE ?? "javascript", + REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE, ); const REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE = resolveReviewHighlighterBooleanFlag( process.env.EXPO_PUBLIC_REVIEW_HIGHLIGHTER_DISABLE_CACHE, false, ); +const REVIEW_HIGHLIGHT_RESULT_CACHE_LIMIT = 8; +const REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD = 40; +const REVIEW_HIGHLIGHT_CHUNK_SIZE = 20; +const REVIEW_TOKENIZE_MAX_LINE_LENGTH = 1_000; const highlightCache = new Map>(); const resolvedHighlightCache = new Map(); const loadedLanguages = new Set(["text"]); @@ -205,6 +213,17 @@ function joinPatchLines(lines: ReadonlyArray): string { return lines.map(stripTrailingNewline).join("\n"); } +function waitForNextFrame(): Promise { + return new Promise((resolve) => { + if (typeof requestAnimationFrame === "function") { + requestAnimationFrame(() => resolve()); + return; + } + + setTimeout(resolve, 0); + }); +} + async function getHighlighter(): Promise { if (!highlighterPromise) { const configuredHighlighterPromise = Promise.all([ @@ -214,6 +233,7 @@ async function getHighlighter(): Promise { let nativeEngineAvailable = false; logReviewHighlighterDiagnostic("initializing", { + configuredPreference: REVIEW_HIGHLIGHTER_ENGINE_ENV_VALUE, preference: REVIEW_HIGHLIGHTER_ENGINE_PREFERENCE, resultCacheDisabled: REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE, }); @@ -379,6 +399,146 @@ function normalizeHighlightedLines( ); } +function applyWordAltDiffHighlightsToFile( + file: ReviewRenderableFile, + highlighted: ReviewHighlightedFile, +): ReviewHighlightedFile { + const nextAdditionLines = [...highlighted.additionLines]; + const nextDeletionLines = [...highlighted.deletionLines]; + const processedPairs = new Set(); + let changed = false; + + file.rows.forEach((row) => { + if (row.kind !== "line" || row.change === "context" || !row.comparison) { + return; + } + + const deletionTokenIndex = + row.change === "delete" + ? row.deletionTokenIndex + : row.comparison.change === "delete" + ? row.comparison.tokenIndex + : null; + const additionTokenIndex = + row.change === "add" + ? row.additionTokenIndex + : row.comparison.change === "add" + ? row.comparison.tokenIndex + : null; + + if (deletionTokenIndex === null || additionTokenIndex === null) { + return; + } + + const pairKey = `${deletionTokenIndex}:${additionTokenIndex}`; + if (processedPairs.has(pairKey)) { + return; + } + processedPairs.add(pairKey); + + const deletionLine = stripTrailingNewline(file.deletionLines[deletionTokenIndex] ?? ""); + const additionLine = stripTrailingNewline(file.additionLines[additionTokenIndex] ?? ""); + const ranges = computeWordAltDiffRanges({ deletionLine, additionLine }); + + if (ranges.deletion.length > 0) { + nextDeletionLines[deletionTokenIndex] = applyDiffRangesToTokens( + nextDeletionLines[deletionTokenIndex] ?? [], + ranges.deletion, + ); + changed = true; + } + + if (ranges.addition.length > 0) { + nextAdditionLines[additionTokenIndex] = applyDiffRangesToTokens( + nextAdditionLines[additionTokenIndex] ?? [], + ranges.addition, + ); + changed = true; + } + }); + + return changed + ? { + additionLines: nextAdditionLines, + deletionLines: nextDeletionLines, + } + : highlighted; +} + +function applyWordAltDiffHighlightsToSelectedLines(input: { + readonly lines: ReadonlyArray; + readonly tokenMap: Record>; +}): Record> { + const additionLineByTokenIndex = new Map(); + const deletionLineByTokenIndex = new Map(); + + input.lines.forEach((line) => { + if (line.change === "add" && line.additionTokenIndex !== null) { + additionLineByTokenIndex.set(line.additionTokenIndex, line); + } + if (line.change === "delete" && line.deletionTokenIndex !== null) { + deletionLineByTokenIndex.set(line.deletionTokenIndex, line); + } + }); + + const nextTokenMap = { ...input.tokenMap }; + const processedPairs = new Set(); + + input.lines.forEach((line) => { + if (line.change === "context" || !line.comparison) { + return; + } + + const pairedDeletionLine = + line.change === "delete" + ? line + : line.comparison.change === "delete" + ? deletionLineByTokenIndex.get(line.comparison.tokenIndex) + : undefined; + const pairedAdditionLine = + line.change === "add" + ? line + : line.comparison.change === "add" + ? additionLineByTokenIndex.get(line.comparison.tokenIndex) + : undefined; + + if ( + !pairedDeletionLine || + !pairedAdditionLine || + pairedDeletionLine.deletionTokenIndex === null || + pairedAdditionLine.additionTokenIndex === null + ) { + return; + } + + const pairKey = `${pairedDeletionLine.deletionTokenIndex}:${pairedAdditionLine.additionTokenIndex}`; + if (processedPairs.has(pairKey)) { + return; + } + processedPairs.add(pairKey); + + const ranges = computeWordAltDiffRanges({ + deletionLine: pairedDeletionLine.content, + additionLine: pairedAdditionLine.content, + }); + + if (ranges.deletion.length > 0) { + nextTokenMap[pairedDeletionLine.id] = applyDiffRangesToTokens( + nextTokenMap[pairedDeletionLine.id] ?? [], + ranges.deletion, + ); + } + if (ranges.addition.length > 0) { + nextTokenMap[pairedAdditionLine.id] = applyDiffRangesToTokens( + nextTokenMap[pairedAdditionLine.id] ?? [], + ranges.addition, + ); + } + }); + + return nextTokenMap; +} + async function highlightLines( code: string, language: string, @@ -389,14 +549,76 @@ async function highlightLines( } const highlighter = await getHighlighter(); - const tokenLines = highlighter.codeToTokensBase(code, { lang: language, theme }); - return normalizeHighlightedLines(tokenLines); + const sourceLines = code.split("\n"); + const highlightedLines: Array> = []; + const shortLineBatch: string[] = []; + + const flushShortLineBatch = async (): Promise => { + if (shortLineBatch.length === 0) { + return; + } + + const tokenLines = highlighter.codeToTokensBase(shortLineBatch.join("\n"), { + lang: language, + theme, + }); + highlightedLines.push(...normalizeHighlightedLines(tokenLines)); + shortLineBatch.length = 0; + }; + + for (let lineIndex = 0; lineIndex < sourceLines.length; lineIndex += 1) { + const line = sourceLines[lineIndex] ?? ""; + + if (line.length > REVIEW_TOKENIZE_MAX_LINE_LENGTH) { + await flushShortLineBatch(); + highlightedLines.push([{ content: line, color: null, fontStyle: null }]); + } else { + shortLineBatch.push(line); + } + + if (shortLineBatch.length >= REVIEW_HIGHLIGHT_CHUNK_SIZE) { + await flushShortLineBatch(); + } + + if ( + sourceLines.length > REVIEW_HIGHLIGHT_CHUNK_LINE_THRESHOLD && + lineIndex + 1 < sourceLines.length && + (shortLineBatch.length === 0 || line.length > REVIEW_TOKENIZE_MAX_LINE_LENGTH) + ) { + await waitForNextFrame(); + } + } + + await flushShortLineBatch(); + + return highlightedLines; } function getHighlightCacheKey(file: ReviewRenderableFile, theme: ReviewDiffTheme): string { return `${SHIKI_THEME_NAME_BY_SCHEME[theme]}:${file.cacheKey}`; } +function storeResolvedHighlightedFile(cacheKey: string, highlighted: ReviewHighlightedFile): void { + if (resolvedHighlightCache.has(cacheKey)) { + resolvedHighlightCache.delete(cacheKey); + } + + resolvedHighlightCache.set(cacheKey, highlighted); + + while (resolvedHighlightCache.size > REVIEW_HIGHLIGHT_RESULT_CACHE_LIMIT) { + const oldestKey = resolvedHighlightCache.keys().next().value; + if (oldestKey === undefined) { + break; + } + resolvedHighlightCache.delete(oldestKey); + } +} + +export function clearReviewHighlightFileCache(): void { + highlightCache.clear(); + resolvedHighlightCache.clear(); +} + export function getCachedHighlightedReviewFile( file: ReviewRenderableFile, theme: ReviewDiffTheme, @@ -417,32 +639,72 @@ export async function highlightReviewFile( if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { const resolved = resolvedHighlightCache.get(cacheKey); if (resolved) { + logReviewHighlighterDiagnostic("file highlight cache hit (resolved)", { + fileId: file.id, + filePath: file.path, + theme, + }); return resolved; } const cached = highlightCache.get(cacheKey); if (cached) { + logReviewHighlighterDiagnostic("file highlight cache hit (pending)", { + fileId: file.id, + filePath: file.path, + theme, + }); return cached; } } const promise = (async () => { + const startedAt = Date.now(); + logReviewHighlighterDiagnostic("file highlight start", { + fileId: file.id, + filePath: file.path, + theme, + additionLineCount: file.additionLines.length, + deletionLineCount: file.deletionLines.length, + rowCount: file.rows.length, + }); const language = await resolveLanguage(file); - const [additionLines, deletionLines] = await Promise.all([ - highlightLines(joinPatchLines(file.additionLines), language, shikiTheme), - highlightLines(joinPatchLines(file.deletionLines), language, shikiTheme), - ]); + const additionLines = await highlightLines( + joinPatchLines(file.additionLines), + language, + shikiTheme, + ); + await waitForNextFrame(); + const deletionLines = await highlightLines( + joinPatchLines(file.deletionLines), + language, + shikiTheme, + ); + await waitForNextFrame(); - const highlighted = { additionLines, deletionLines }; + const highlighted = applyWordAltDiffHighlightsToFile(file, { additionLines, deletionLines }); if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { - resolvedHighlightCache.set(cacheKey, highlighted); + storeResolvedHighlightedFile(cacheKey, highlighted); } + logReviewHighlighterDiagnostic("file highlight complete", { + fileId: file.id, + filePath: file.path, + theme, + language, + highlightedAdditionLineCount: highlighted.additionLines.length, + highlightedDeletionLineCount: highlighted.deletionLines.length, + durationMs: Date.now() - startedAt, + }); return highlighted; })(); if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { highlightCache.set(cacheKey, promise); } - return promise; + return promise.finally(() => { + if (!REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) { + highlightCache.delete(cacheKey); + } + }); } export async function highlightReviewSelectedLines(input: { @@ -483,5 +745,8 @@ export async function highlightReviewSelectedLines(input: { additionIndex += 1; }); - return tokenMap; + return applyWordAltDiffHighlightsToSelectedLines({ + lines: input.lines, + tokenMap, + }); } diff --git a/bun.lock b/bun.lock index 8f58b52d54..11768b2f64 100644 --- a/bun.lock +++ b/bun.lock @@ -66,6 +66,7 @@ "@t3tools/contracts": "workspace:*", "@t3tools/shared": "workspace:*", "clsx": "^2.1.1", + "diff": "8.0.3", "effect": "catalog:", "expo": "~55.0.14", "expo-camera": "~55.0.15",