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