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