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], 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 const deletedRow = nextRows[deletedRowIndex];
362 const addedRow = nextRows[addedRowIndex];
363 if (!deletedRow?.content || !addedRow?.content) {
364 continue;
365 }
366
367 const ranges = computeWordAltDiffRanges({
368 deletionLine: deletedRow.content,
369 additionLine: addedRow.content,
370 });
371 const deletionRanges = trimWordDiffRanges(deletedRow.content, ranges.deletion);
372 const additionRanges = trimWordDiffRanges(addedRow.content, ranges.addition);
373
374 if (shouldUseWordDiffRanges(deletedRow.content, deletionRanges)) {
375 nextRows[deletedRowIndex] = { ...deletedRow, wordDiffRanges: deletionRanges };
376 }
377 if (shouldUseWordDiffRanges(addedRow.content, additionRanges)) {
378 nextRows[addedRowIndex] = { ...addedRow, wordDiffRanges: additionRanges };
379 }
380 }
381
382 if (deletedRowIndexes.length === 0 && addedRowIndexes.length === 0) {
383 index += 1;
384 }
385 }
386
387 return nextRows;
388}
389
390function mapLineRow(
391 file: ReviewRenderableFile,
392 row: ReviewRenderableLineRow,
393 rowIndex: number,
394): NativeReviewDiffRow {
395 return {
396 kind: "line",
397 id: `${file.id}:line:${rowIndex}:${row.id}`,
398 fileId: file.id,
399 content: row.content,
400 change: row.change,
401 oldLineNumber: row.oldLineNumber,
402 newLineNumber: row.newLineNumber,
403 };
404}
405
406function prepareFileRows(
407 file: ReviewRenderableFile,
408 commentTargetsByRowId: Map<string, NativeReviewDiffCommentTarget>,
409 rowIdByCommentLineId: Map<string, string>,
410): PreparedNativeReviewFileRows {
411 const rows: NativeReviewDiffRow[] = [
412 {
413 kind: "file",
414 id: `${file.id}:header`,
415 fileId: file.id,
416 filePath: file.path,
417 previousPath: file.previousPath,
418 changeType: mapChangeType(file),
419 additions: file.additions,
420 deletions: file.deletions,
421 },
422 ];
423
424 const lineRows = file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line");
425 let lineIndex = 0;
426 file.rows.forEach((row, rowIndex) => {
427 if (row.kind === "hunk") {
428 rows.push({
429 kind: "hunk",
430 id: `${file.id}:hunk:${rowIndex}:${row.id}`,
431 fileId: file.id,
432 text: row.context ? `${row.header} ${row.context}` : row.header,
433 });
434 return;
435 }
436
437 const nativeRow = mapLineRow(file, row, rowIndex);
438 rows.push(nativeRow);
439 rowIdByCommentLineId.set(row.id, nativeRow.id);
440 commentTargetsByRowId.set(nativeRow.id, {
441 filePath: file.path,
442 lines: lineRows,
443 lineIndex,
444 });
445 lineIndex += 1;
446 });
447
448 rows.push(...noticeRowsForFile(file));
449 return {
450 fileId: file.id,
451 filePath: file.path,
452 lineCount: lineRows.length,
453 // Comments must not split the source deletion/addition runs used for word matching.
454 rows: addNativeWordDiffRanges(rows),
455 commentedRows: null,
456 };
457}
458
459function insertFileComments(
460 file: PreparedNativeReviewFileRows,
461 comments: ReadonlyArray<ReviewInlineComment>,
462): ReadonlyArray<NativeReviewDiffRow> {
463 if (comments.length === 0) {
464 file.commentedRows = null;
465 return file.rows;
466 }
467 const commentsKey = buildReviewCommentsCacheKey(comments);
468 if (file.commentedRows?.commentsKey === commentsKey) {
469 return file.commentedRows.rows;
470 }
471
472 const commentsByEndIndex = new Map<number, ReviewInlineComment[]>();
473 for (const comment of comments) {
474 const endIndex = Math.min(comment.endIndex, file.lineCount - 1);
475 if (endIndex < 0) continue;
476 const existing = commentsByEndIndex.get(endIndex);
477 if (existing) {
478 existing.push(comment);
479 } else {
480 commentsByEndIndex.set(endIndex, [comment]);
481 }
482 }
483 const rows: NativeReviewDiffRow[] = [];
484 let lineIndex = 0;
485 for (const row of file.rows) {
486 rows.push(row);
487 if (row.kind !== "line") continue;
488 for (const comment of commentsByEndIndex.get(lineIndex) ?? []) {
489 rows.push({
490 kind: "comment",
491 id: comment.id,
492 fileId: file.fileId,
493 filePath: file.filePath,
494 commentText: comment.text,
495 commentRangeLabel: comment.rangeLabel,
496 commentSectionTitle: comment.sectionTitle,
497 });
498 }
499 lineIndex += 1;
500 }
501 file.commentedRows = { commentsKey, rows };
502 return rows;
503}
504
505function prepareNativeReviewDiffData(parsedDiff: ReviewParsedDiff): PreparedNativeReviewDiffData {
506 if (parsedDiff.kind !== "files") {
507 return {
508 fileRows: [],
509 files: [],
510 commentTargetsByRowId: new Map(),
511 rowIdByCommentLineId: new Map(),
512 additions: 0,
513 deletions: 0,
514 };
515 }
516
517 const files = parsedDiff.files.map<NativeReviewDiffFile>((file) => ({
518 id: file.id,
519 path: file.path,
520 language: getLanguageForPath(file.path, file.languageHint),
521 additions: file.additions,
522 deletions: file.deletions,
523 }));
524 const commentTargetsByRowId = new Map<string, NativeReviewDiffCommentTarget>();
525 const rowIdByCommentLineId = new Map<string, string>();
526 const fileRows = parsedDiff.files.map((file) =>
527 prepareFileRows(file, commentTargetsByRowId, rowIdByCommentLineId),
528 );
529
530 return {
531 fileRows,
532 files,
533 commentTargetsByRowId,
534 rowIdByCommentLineId,
535 additions: parsedDiff.additions,
536 deletions: parsedDiff.deletions,
537 };
538}
539
540function buildCommentedNativeReviewDiffData(
541 prepared: PreparedNativeReviewDiffData,
542 comments: ReadonlyArray<ReviewInlineComment>,
543): NativeReviewDiffData {
544 const commentsByFilePath = new Map<string, ReviewInlineComment[]>();
545 for (const comment of comments) {
546 const existing = commentsByFilePath.get(comment.filePath);
547 if (existing) {
548 existing.push(comment);
549 } else {
550 commentsByFilePath.set(comment.filePath, [comment]);
551 }
552 }
553 return {
554 rows: Arr.flatMap(prepared.fileRows, (file) =>
555 insertFileComments(file, commentsByFilePath.get(file.filePath) ?? []),
556 ),
557 files: prepared.files,
558 commentTargetsByRowId: prepared.commentTargetsByRowId,
559 rowIdByCommentLineId: prepared.rowIdByCommentLineId,
560 additions: prepared.additions,
561 deletions: prepared.deletions,
562 };
563}
564
565export function buildNativeReviewDiffData(
566 input: BuildNativeReviewDiffDataInput,
567): NativeReviewDiffData;
568export function buildNativeReviewDiffData(parsedDiff: ReviewParsedDiff): NativeReviewDiffData;
569export function buildNativeReviewDiffData(
570 input: ReviewParsedDiff | BuildNativeReviewDiffDataInput,
571): NativeReviewDiffData {
572 const parsedDiff = "parsedDiff" in input ? input.parsedDiff : input;
573 const comments = "parsedDiff" in input ? (input.comments ?? []) : [];
574 return buildCommentedNativeReviewDiffData(prepareNativeReviewDiffData(parsedDiff), comments);
575}
576
577/**
578 * Prepares source rows once per parsed diff, including its section-specific IDs.
579 * Comment edits reuse those rows, word ranges, and targets. Each file retains
580 * only its latest comment overlay, and the weak key releases old parsed diffs.
581 */
582export function getCachedNativeReviewDiffData(
583 input: BuildNativeReviewDiffDataInput,
584): NativeReviewDiffData {
585 const comments = input.comments ?? [];
586 const commentsKey = buildReviewCommentsCacheKey(comments);
587 const cached = nativeReviewDiffDataCache.get(input.parsedDiff);
588 if (cached?.commentsKey === commentsKey) {
589 return cached.data;
590 }
591
592 const prepared = cached?.prepared ?? prepareNativeReviewDiffData(input.parsedDiff);
593 const data = buildCommentedNativeReviewDiffData(prepared, comments);
594 nativeReviewDiffDataCache.set(input.parsedDiff, { prepared, commentsKey, data });
595 return data;
596}