Open History to see the last commit
1import type { NativeReviewDiffRow, NativeReviewDiffTheme } from "../diffs/nativeReviewDiffSurface";
2import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes";
3import * as Arr from "effect/Array";
4import { pipe } from "effect/Function";
5import type { ResolvedMobileCodeSurface } from "../../lib/appearancePreferences";
6import { resolveHighlightLanguage } from "../../lib/highlightLanguage";
7import { type MobileThemeId, type MobileThemeVariables } from "../../lib/mobileTheme";
8import { getMobileTerminalTheme, type TerminalAppearanceScheme } from "../terminal/terminalTheme";
9import { computeWordAltDiffRanges } from "./reviewWordDiffs";
10import {
11 getReviewFilePreviewState,
12 type ReviewParsedDiff,
13 type ReviewRenderableFile,
14 type ReviewRenderableLineRow,
15} from "./reviewModel";
16import type { ReviewInlineComment } from "./reviewCommentSelection";
17
18const NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT = 4;
19const NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE = 0.45;
20// Keep eager word matching within the old 2,000-row budget while retaining more rendered rows.
21const NATIVE_REVIEW_MAX_WORD_DIFF_COMPARISONS = 1_000;
22// Bound the rows serialized to the native heap before mapping and word matching.
23const NATIVE_REVIEW_MAX_FILE_ROWS = 100_000;
24const TRUNCATED_FILE_NOTICE = "This diff is too large to show in full.";
25const NATIVE_HEX_COLOR = /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})([\da-f]{2})?$/i;
26const NATIVE_RGBA_COLOR =
27 /^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)(?:\s*,\s*([\d.]+))?\s*\)$/;
28
29export const NATIVE_REVIEW_DIFF_CONTENT_WIDTH = 2_800;
30
31export function buildNativeReviewSnippetRows(
32 comment: Pick<ReviewInlineComment, "id" | "diff" | "fenceLanguage">,
33): NativeReviewDiffRow[] {
34 if ((comment.fenceLanguage ?? "diff") !== "diff" || !comment.diff.trim()) return [];
35 const lines = comment.diff.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");
36 if (lines.some((line) => !/^[ +-]/.test(line) || /^(---|\+\+\+) /.test(line))) return [];
37 return lines.map((line, index) => ({
38 kind: "line",
39 id: `${comment.id}:snippet:${index}`,
40 content: line.slice(1),
41 change: line[0] === "+" ? "add" : line[0] === "-" ? "delete" : "context",
42 oldLineNumber: null,
43 newLineNumber: null,
44 }));
45}
46
47function opaqueNativeHexColor(color: string, background: string): string {
48 const hex = NATIVE_HEX_COLOR.exec(color);
49 if (hex && !hex[4]) return color;
50
51 const rgba = NATIVE_RGBA_COLOR.exec(color);
52 const backgroundHex = NATIVE_HEX_COLOR.exec(background);
53 if ((!hex && !rgba) || !backgroundHex) return background;
54
55 const alpha = hex
56 ? Number.parseInt(hex[4] ?? "ff", 16) / 255
57 : rgba?.[4] === undefined
58 ? 1
59 : Math.min(1, Math.max(0, Number(rgba[4])));
60 const channels = [1, 2, 3].map((index) => {
61 const foreground = hex ? Number.parseInt(hex[index] ?? "0", 16) : Number(rgba?.[index]);
62 const behind = Number.parseInt(backgroundHex[index] ?? "0", 16);
63 return Math.round(foreground * alpha + behind * (1 - alpha));
64 });
65 return `#${channels.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
66}
67
68export function createNativeReviewDiffStyle(
69 codeSurface: ResolvedMobileCodeSurface,
70 wordWrap: boolean,
71) {
72 return {
73 wordWrap,
74 rowHeight: codeSurface.rowHeight,
75 contentWidth: NATIVE_REVIEW_DIFF_CONTENT_WIDTH,
76 changeBarWidth: 4,
77 gutterWidth: codeSurface.gutterWidth,
78 codePadding: codeSurface.codePadding,
79 textVerticalInset: codeSurface.textVerticalInset,
80 fileHeaderHeight: 56,
81 fileHeaderHorizontalMargin: 8,
82 fileHeaderVerticalMargin: 6,
83 fileHeaderCornerRadius: 10,
84 fileHeaderHorizontalPadding: 10,
85 fileHeaderPathRightPadding: 118,
86 fileHeaderCountColumnWidth: 38,
87 fileHeaderCountGap: 5,
88 codeFontSize: codeSurface.fontSize,
89 codeFontWeight: "regular",
90 lineNumberFontSize: codeSurface.lineNumberFontSize,
91 lineNumberFontWeight: "regular",
92 hunkFontSize: 11,
93 hunkFontWeight: "medium",
94 fileHeaderFontSize: 11,
95 fileHeaderFontWeight: "semibold",
96 fileHeaderMetaFontSize: 10,
97 fileHeaderMetaFontWeight: "semibold",
98 fileHeaderSubtextFontSize: 11,
99 fileHeaderSubtextFontWeight: "medium",
100 fileHeaderStatusFontSize: 9,
101 fileHeaderStatusFontWeight: "bold",
102 emptyStateFontSize: 12,
103 emptyStateFontWeight: "medium",
104 } as const;
105}
106
107export interface NativeReviewDiffData {
108 readonly rows: ReadonlyArray<NativeReviewDiffRow>;
109 readonly files: ReadonlyArray<NativeReviewDiffFile>;
110 readonly commentTargetsByRowId: ReadonlyMap<string, NativeReviewDiffCommentTarget>;
111 readonly rowIdByCommentLineId: ReadonlyMap<string, string>;
112 readonly additions: number;
113 readonly deletions: number;
114}
115
116export interface NativeReviewDiffCommentTarget {
117 readonly filePath: string;
118 readonly lines: ReadonlyArray<ReviewRenderableLineRow>;
119 readonly lineIndex: number;
120}
121
122export interface BuildNativeReviewDiffDataInput {
123 readonly parsedDiff: ReviewParsedDiff;
124 readonly comments?: ReadonlyArray<ReviewInlineComment>;
125}
126
127interface CachedNativeReviewDiffData {
128 readonly prepared: PreparedNativeReviewDiffData;
129 readonly commentsKey: string;
130 readonly data: NativeReviewDiffData;
131}
132
133interface PreparedNativeReviewFileRows {
134 readonly fileId: string;
135 readonly filePath: string;
136 readonly lineCount: number;
137 readonly truncated: boolean;
138 readonly rows: ReadonlyArray<NativeReviewDiffRow>;
139 readonly commentTargetsByRowId: ReadonlyMap<string, NativeReviewDiffCommentTarget>;
140 readonly rowIdByCommentLineId: ReadonlyMap<string, string>;
141 commentedRows: {
142 readonly commentsKey: string;
143 readonly rows: ReadonlyArray<NativeReviewDiffRow>;
144 } | null;
145}
146
147interface PreparedNativeReviewDiffData extends Omit<NativeReviewDiffData, "rows"> {
148 readonly fileRows: ReadonlyArray<PreparedNativeReviewFileRows>;
149}
150
151const nativeReviewDiffDataCache = new WeakMap<ReviewParsedDiff, CachedNativeReviewDiffData>();
152const nativeReviewFileRowsCache = new WeakMap<ReviewRenderableFile, PreparedNativeReviewFileRows>();
153
154function buildReviewCommentsCacheKey(comments: ReadonlyArray<ReviewInlineComment>): string {
155 if (comments.length === 0) {
156 return "none";
157 }
158
159 return JSON.stringify(
160 comments.map((comment) => [
161 comment.id,
162 comment.sectionId,
163 comment.sectionTitle,
164 comment.filePath,
165 comment.startIndex,
166 comment.endIndex,
167 comment.rangeLabel,
168 comment.text,
169 ]),
170 );
171}
172
173export function createNativeReviewDiffTheme(
174 scheme: TerminalAppearanceScheme,
175 themeId: MobileThemeId,
176 appTheme: MobileThemeVariables,
177): NativeReviewDiffTheme {
178 const terminalTheme = getMobileTerminalTheme(themeId, scheme);
179 const [, terminalRed] = terminalTheme.palette;
180 // Swift and Android disagree on alpha-byte order; flatten to shared opaque #RRGGBB.
181 const screen = opaqueNativeHexColor(
182 appTheme["--color-screen"],
183 scheme === "dark" ? "#000000" : "#ffffff",
184 );
185 const background = opaqueNativeHexColor(appTheme["--color-md-code-bg"], screen);
186 const nativeColor = (color: string) => opaqueNativeHexColor(color, background);
187
188 if (scheme === "dark") {
189 return {
190 background,
191 text: nativeColor(appTheme["--color-md-code-text"]),
192 mutedText: nativeColor(appTheme["--color-foreground-muted"]),
193 headerBackground: background,
194 border: nativeColor(appTheme["--color-border"]),
195 hunkBackground: nativeColor(appTheme["--color-subtle-strong"]),
196 hunkText: nativeColor(appTheme["--color-foreground"]),
197 addBackground: "#0d2f28",
198 deleteBackground: "#391415",
199 addBar: "#00cab1",
200 deleteBar: terminalRed ?? "#ff2e3f",
201 addText: "#5ECC71",
202 deleteText: "#FF6762",
203 };
204 }
205
206 return {
207 background,
208 text: nativeColor(appTheme["--color-md-code-text"]),
209 mutedText: nativeColor(appTheme["--color-foreground-muted"]),
210 headerBackground: background,
211 border: nativeColor(appTheme["--color-border"]),
212 hunkBackground: nativeColor(appTheme["--color-subtle-strong"]),
213 hunkText: nativeColor(appTheme["--color-foreground"]),
214 addBackground: "#e5f8f5",
215 deleteBackground: "#ffe6e7",
216 addBar: "#00cab1",
217 deleteBar: terminalRed ?? "#ff2e3f",
218 addText: "#199F43",
219 deleteText: "#D52C36",
220 };
221}
222
223function mapChangeType(file: ReviewRenderableFile): NativeReviewDiffRow["changeType"] {
224 switch (file.changeType) {
225 case "change":
226 return "modified";
227 case "new":
228 case "deleted":
229 case "rename-pure":
230 case "rename-changed":
231 return file.changeType;
232 default:
233 return "modified";
234 }
235}
236
237function createNoticeRow(fileId: string, suffix: string, text: string): NativeReviewDiffRow {
238 return {
239 kind: "notice",
240 id: `${fileId}:notice:${suffix}`,
241 fileId,
242 text,
243 };
244}
245
246function noticeRowsForFile(file: ReviewRenderableFile): ReadonlyArray<NativeReviewDiffRow> {
247 if (file.notice) return [createNoticeRow(file.id, "loading", file.notice)];
248 if (file.rows.length > 0) {
249 return [];
250 }
251
252 const previewState = getReviewFilePreviewState(file);
253 if (previewState.kind === "suppressed" && previewState.reason === "non-text") {
254 return [
255 createNoticeRow(file.id, "non-text", "Unsupported format. Diff contents are not available."),
256 ];
257 }
258
259 if (file.changeType === "rename-pure") {
260 return [createNoticeRow(file.id, "rename", "This file was renamed without modifications.")];
261 }
262
263 return [];
264}
265
266function trimWordDiffRanges(
267 content: string,
268 ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
269): NonNullable<NativeReviewDiffRow["wordDiffRanges"]> {
270 return pipe(
271 ranges,
272 Arr.flatMap((range) => {
273 let start = Math.max(0, range.start);
274 let end = Math.min(content.length, range.end);
275
276 while (start < end && /\s/.test(content[start] ?? "")) {
277 start += 1;
278 }
279 while (end > start && /\s/.test(content[end - 1] ?? "")) {
280 end -= 1;
281 }
282
283 return end > start ? [{ start, end }] : [];
284 }),
285 );
286}
287
288function nonWhitespaceLength(value: string) {
289 return value.replace(/\s/g, "").length;
290}
291
292function shouldUseWordDiffRanges(
293 content: string,
294 ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
295) {
296 if (ranges.length === 0 || ranges.length > NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT) {
297 return false;
298 }
299
300 const meaningfulLength = nonWhitespaceLength(content);
301 if (meaningfulLength === 0) {
302 return false;
303 }
304
305 const highlightedLength = ranges.reduce(
306 (total, range) => total + nonWhitespaceLength(content.slice(range.start, range.end)),
307 0,
308 );
309 return highlightedLength / meaningfulLength <= NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE;
310}
311
312function addNativeWordDiffRanges(
313 rows: ReadonlyArray<NativeReviewDiffRow>,
314 lineRows: ReadonlyArray<ReviewRenderableLineRow>,
315): ReadonlyArray<NativeReviewDiffRow> {
316 const nextRows = [...rows];
317 const addedRowIndexes = new Map<number, number>();
318 const pairs: Array<{ deletionRowIndex: number; additionTokenIndex: number }> = [];
319 let lineIndex = 0;
320
321 // Pierre can split adjacent change blocks to align similar lines. Keep those pairings.
322 rows.forEach((row, rowIndex) => {
323 if (row.kind !== "line") return;
324 const source = lineRows[lineIndex++];
325 if (source?.change === "add" && source.additionTokenIndex !== null) {
326 addedRowIndexes.set(source.additionTokenIndex, rowIndex);
327 } else if (source?.change === "delete" && source.comparison?.change === "add") {
328 pairs.push({ deletionRowIndex: rowIndex, additionTokenIndex: source.comparison.tokenIndex });
329 }
330 });
331
332 let comparisonCount = 0;
333 for (const { deletionRowIndex, additionTokenIndex } of pairs) {
334 if (comparisonCount >= NATIVE_REVIEW_MAX_WORD_DIFF_COMPARISONS) break;
335 const addedRowIndex = addedRowIndexes.get(additionTokenIndex);
336 if (addedRowIndex === undefined) continue;
337 const deletedRow = nextRows[deletionRowIndex];
338 const addedRow = nextRows[addedRowIndex];
339 if (!deletedRow?.content || !addedRow?.content) continue;
340
341 comparisonCount += 1;
342 const ranges = computeWordAltDiffRanges({
343 deletionLine: deletedRow.content,
344 additionLine: addedRow.content,
345 });
346 const deletionRanges = trimWordDiffRanges(deletedRow.content, ranges.deletion);
347 const additionRanges = trimWordDiffRanges(addedRow.content, ranges.addition);
348
349 if (shouldUseWordDiffRanges(deletedRow.content, deletionRanges)) {
350 nextRows[deletionRowIndex] = { ...deletedRow, wordDiffRanges: deletionRanges };
351 }
352 if (shouldUseWordDiffRanges(addedRow.content, additionRanges)) {
353 nextRows[addedRowIndex] = { ...addedRow, wordDiffRanges: additionRanges };
354 }
355 }
356
357 return nextRows;
358}
359
360function mapLineRow(
361 file: ReviewRenderableFile,
362 row: ReviewRenderableLineRow,
363 rowIndex: number,
364): NativeReviewDiffRow {
365 return {
366 kind: "line",
367 id: `${file.id}:line:${rowIndex}:${row.id}`,
368 fileId: file.id,
369 content: row.content,
370 change: row.change,
371 oldLineNumber: row.oldLineNumber,
372 newLineNumber: row.newLineNumber,
373 };
374}
375
376function prepareFileRows(file: ReviewRenderableFile): PreparedNativeReviewFileRows {
377 const cached = nativeReviewFileRowsCache.get(file);
378 if (cached) return cached;
379 const commentTargetsByRowId = new Map<string, NativeReviewDiffCommentTarget>();
380 const rowIdByCommentLineId = new Map<string, string>();
381 const rows: NativeReviewDiffRow[] = [
382 {
383 kind: "file",
384 id: `${file.id}:header`,
385 fileId: file.id,
386 filePath: file.path,
387 previousPath: file.previousPath,
388 changeType: mapChangeType(file),
389 additions: file.additions,
390 deletions: file.deletions,
391 },
392 ];
393
394 const sourceRows =
395 file.rows.length > NATIVE_REVIEW_MAX_FILE_ROWS
396 ? file.rows.slice(0, NATIVE_REVIEW_MAX_FILE_ROWS)
397 : file.rows;
398 const lineRows = sourceRows.filter((row): row is ReviewRenderableLineRow => row.kind === "line");
399 let lineIndex = 0;
400 sourceRows.forEach((row, rowIndex) => {
401 if (row.kind === "hunk") {
402 rows.push({
403 kind: "hunk",
404 id: `${file.id}:hunk:${rowIndex}:${row.id}`,
405 fileId: file.id,
406 text: row.context ? `${row.header} ${row.context}` : row.header,
407 });
408 return;
409 }
410
411 const nativeRow = mapLineRow(file, row, rowIndex);
412 rows.push(nativeRow);
413 rowIdByCommentLineId.set(row.id, nativeRow.id);
414 commentTargetsByRowId.set(nativeRow.id, {
415 filePath: file.path,
416 lines: lineRows,
417 lineIndex,
418 });
419 lineIndex += 1;
420 });
421
422 if (sourceRows !== file.rows) {
423 rows.push(createNoticeRow(file.id, "truncated", TRUNCATED_FILE_NOTICE));
424 }
425 rows.push(...noticeRowsForFile(file));
426 if (file.noEOFCRAdditions || file.noEOFCRDeletions) {
427 const side = file.noEOFCRAdditions
428 ? file.noEOFCRDeletions
429 ? "Old and new files have"
430 : "New file has"
431 : "Old file has";
432 rows.push(createNoticeRow(file.id, "eof", `${side} no newline at end of file.`));
433 }
434 const prepared: PreparedNativeReviewFileRows = {
435 fileId: file.id,
436 filePath: file.path,
437 lineCount: lineRows.length,
438 truncated: sourceRows !== file.rows,
439 // Pair source lines before inserting comments so comment rows cannot affect matching.
440 rows: addNativeWordDiffRanges(rows, lineRows),
441 commentTargetsByRowId,
442 rowIdByCommentLineId,
443 commentedRows: null,
444 };
445 nativeReviewFileRowsCache.set(file, prepared);
446 return prepared;
447}
448
449function insertFileComments(
450 file: PreparedNativeReviewFileRows,
451 comments: ReadonlyArray<ReviewInlineComment>,
452): ReadonlyArray<NativeReviewDiffRow> {
453 if (comments.length === 0) {
454 file.commentedRows = null;
455 return file.rows;
456 }
457 const commentsKey = buildReviewCommentsCacheKey(comments);
458 if (file.commentedRows?.commentsKey === commentsKey) {
459 return file.commentedRows.rows;
460 }
461
462 const commentsByEndIndex = new Map<number, ReviewInlineComment[]>();
463 for (const comment of comments) {
464 if (file.truncated && comment.startIndex >= file.lineCount) continue;
465 const endIndex = Math.min(comment.endIndex, file.lineCount - 1);
466 if (endIndex < 0) continue;
467 const existing = commentsByEndIndex.get(endIndex);
468 if (existing) {
469 existing.push(comment);
470 } else {
471 commentsByEndIndex.set(endIndex, [comment]);
472 }
473 }
474 const rows: NativeReviewDiffRow[] = [];
475 let lineIndex = 0;
476 for (const row of file.rows) {
477 rows.push(row);
478 if (row.kind !== "line") continue;
479 for (const comment of commentsByEndIndex.get(lineIndex) ?? []) {
480 rows.push({
481 kind: "comment",
482 id: comment.id,
483 fileId: file.fileId,
484 filePath: file.filePath,
485 commentText: comment.text,
486 commentRangeLabel: comment.rangeLabel,
487 commentSectionTitle: comment.sectionTitle,
488 });
489 }
490 lineIndex += 1;
491 }
492 file.commentedRows = { commentsKey, rows };
493 return rows;
494}
495
496function prepareNativeReviewDiffData(parsedDiff: ReviewParsedDiff): PreparedNativeReviewDiffData {
497 if (parsedDiff.kind !== "files") {
498 return {
499 fileRows: [],
500 files: [],
501 commentTargetsByRowId: new Map(),
502 rowIdByCommentLineId: new Map(),
503 additions: 0,
504 deletions: 0,
505 };
506 }
507
508 const files = parsedDiff.files.map<NativeReviewDiffFile>((file) => ({
509 id: file.id,
510 path: file.path,
511 language: resolveHighlightLanguage({ language: file.languageHint, path: file.path }),
512 additions: file.additions,
513 deletions: file.deletions,
514 }));
515 const commentTargetsByRowId = new Map<string, NativeReviewDiffCommentTarget>();
516 const rowIdByCommentLineId = new Map<string, string>();
517 const fileRows = parsedDiff.files.map(prepareFileRows);
518 for (const file of fileRows) {
519 for (const [rowId, target] of file.commentTargetsByRowId) {
520 commentTargetsByRowId.set(rowId, target);
521 }
522 for (const [lineId, rowId] of file.rowIdByCommentLineId) {
523 rowIdByCommentLineId.set(lineId, rowId);
524 }
525 }
526
527 return {
528 fileRows,
529 files,
530 commentTargetsByRowId,
531 rowIdByCommentLineId,
532 additions: parsedDiff.additions,
533 deletions: parsedDiff.deletions,
534 };
535}
536
537function buildCommentedNativeReviewDiffData(
538 prepared: PreparedNativeReviewDiffData,
539 comments: ReadonlyArray<ReviewInlineComment>,
540): NativeReviewDiffData {
541 const commentsByFilePath = new Map<string, ReviewInlineComment[]>();
542 for (const comment of comments) {
543 const existing = commentsByFilePath.get(comment.filePath);
544 if (existing) {
545 existing.push(comment);
546 } else {
547 commentsByFilePath.set(comment.filePath, [comment]);
548 }
549 }
550 return {
551 rows: Arr.flatMap(prepared.fileRows, (file) =>
552 insertFileComments(file, commentsByFilePath.get(file.filePath) ?? []),
553 ),
554 files: prepared.files,
555 commentTargetsByRowId: prepared.commentTargetsByRowId,
556 rowIdByCommentLineId: prepared.rowIdByCommentLineId,
557 additions: prepared.additions,
558 deletions: prepared.deletions,
559 };
560}
561
562export function buildNativeReviewDiffData(
563 input: BuildNativeReviewDiffDataInput,
564): NativeReviewDiffData;
565export function buildNativeReviewDiffData(parsedDiff: ReviewParsedDiff): NativeReviewDiffData;
566export function buildNativeReviewDiffData(
567 input: ReviewParsedDiff | BuildNativeReviewDiffDataInput,
568): NativeReviewDiffData {
569 const parsedDiff = "parsedDiff" in input ? input.parsedDiff : input;
570 const comments = "parsedDiff" in input ? (input.comments ?? []) : [];
571 return buildCommentedNativeReviewDiffData(prepareNativeReviewDiffData(parsedDiff), comments);
572}
573
574export function getCachedNativeReviewDiffData(
575 input: BuildNativeReviewDiffDataInput,
576): NativeReviewDiffData {
577 const comments = input.comments ?? [];
578 const commentsKey = buildReviewCommentsCacheKey(comments);
579 const cached = nativeReviewDiffDataCache.get(input.parsedDiff);
580 if (cached?.commentsKey === commentsKey) {
581 return cached.data;
582 }
583
584 const prepared = cached?.prepared ?? prepareNativeReviewDiffData(input.parsedDiff);
585 const data = buildCommentedNativeReviewDiffData(prepared, comments);
586 nativeReviewDiffDataCache.set(input.parsedDiff, { prepared, commentsKey, data });
587 return data;
588}