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