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