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 commentsKey: string;
109 readonly data: NativeReviewDiffData;
110}
111
112const nativeReviewDiffDataCache = new WeakMap<ReviewParsedDiff, CachedNativeReviewDiffData>();
113
114function buildReviewCommentsCacheKey(comments: ReadonlyArray<ReviewInlineComment>): string {
115 if (comments.length === 0) {
116 return "none";
117 }
118
119 return comments
120 .map((comment) =>
121 [
122 comment.id,
123 comment.sectionId,
124 comment.filePath,
125 comment.startIndex,
126 comment.endIndex,
127 comment.rangeLabel,
128 comment.text,
129 ].join("\u001f"),
130 )
131 .join("\u001e");
132}
133
134export function createNativeReviewDiffTheme(
135 scheme: TerminalAppearanceScheme,
136 themeId: MobileThemeId,
137 appTheme: MobileThemeVariables,
138): NativeReviewDiffTheme {
139 const terminalTheme = getMobileTerminalTheme(themeId, scheme);
140 const [, terminalRed] = terminalTheme.palette;
141 // Swift expects #RRGGBB/#RRGGBBAA while Android expects #RRGGBB/#AARRGGBB.
142 // Flatten translucent app tokens onto the code surface so both native
143 // implementations receive the one unambiguous shared format.
144 const background = opaqueNativeHexColor(appTheme["--color-sheet"], appTheme["--color-screen"]);
145 const nativeColor = (color: string) => opaqueNativeHexColor(color, background);
146
147 if (scheme === "dark") {
148 return {
149 // Match the app surface (--color-sheet) so code views blend with the rest of
150 // the app instead of using a distinct code-editor background.
151 background,
152 text: nativeColor(appTheme["--color-md-code-text"]),
153 mutedText: nativeColor(appTheme["--color-foreground-muted"]),
154 headerBackground: background,
155 border: nativeColor(appTheme["--color-border"]),
156 hunkBackground: nativeColor(appTheme["--color-subtle-strong"]),
157 hunkText: nativeColor(appTheme["--color-primary"]),
158 addBackground: "#0d2f28",
159 deleteBackground: "#391415",
160 addBar: "#00cab1",
161 deleteBar: terminalRed ?? "#ff2e3f",
162 addText: "#5ECC71",
163 deleteText: "#FF6762",
164 };
165 }
166
167 return {
168 // Match the app surface (--color-sheet) so code views blend with the rest of the
169 // app instead of using a distinct code-editor background.
170 background,
171 text: nativeColor(appTheme["--color-md-code-text"]),
172 mutedText: nativeColor(appTheme["--color-foreground-muted"]),
173 headerBackground: background,
174 border: nativeColor(appTheme["--color-border"]),
175 hunkBackground: nativeColor(appTheme["--color-subtle-strong"]),
176 hunkText: nativeColor(appTheme["--color-primary"]),
177 addBackground: "#e5f8f5",
178 deleteBackground: "#ffe6e7",
179 addBar: "#00cab1",
180 deleteBar: terminalRed ?? "#ff2e3f",
181 addText: "#199F43",
182 deleteText: "#D52C36",
183 };
184}
185
186function mapChangeType(file: ReviewRenderableFile): NativeReviewDiffRow["changeType"] {
187 switch (file.changeType) {
188 case "change":
189 return "modified";
190 case "new":
191 case "deleted":
192 case "rename-pure":
193 case "rename-changed":
194 return file.changeType;
195 default:
196 return "modified";
197 }
198}
199
200function getLanguageForPath(
201 filePath: string,
202 languageHint: string | null,
203): NativeReviewDiffLanguage {
204 const hinted = languageHint?.toLowerCase();
205 if (hinted === "typescript" || hinted === "tsx" || hinted === "javascript" || hinted === "jsx") {
206 return hinted;
207 }
208 if (hinted === "json" || hinted === "yaml" || hinted === "bash" || hinted === "diff") {
209 return hinted;
210 }
211
212 const normalizedPath = filePath.toLowerCase();
213 if (normalizedPath.endsWith(".tsx")) return "tsx";
214 if (normalizedPath.endsWith(".ts")) return "typescript";
215 if (normalizedPath.endsWith(".jsx")) return "jsx";
216 if (normalizedPath.endsWith(".js") || normalizedPath.endsWith(".cjs")) return "javascript";
217 if (normalizedPath.endsWith(".json") || normalizedPath.endsWith(".jsonc")) return "json";
218 if (normalizedPath.endsWith(".yml") || normalizedPath.endsWith(".yaml")) return "yaml";
219 if (
220 normalizedPath.endsWith(".sh") ||
221 normalizedPath.includes("/bin/") ||
222 normalizedPath.includes("shell")
223 ) {
224 return "bash";
225 }
226 return "diff";
227}
228
229function createNoticeRow(fileId: string, suffix: string, text: string): NativeReviewDiffRow {
230 return {
231 kind: "notice",
232 id: `${fileId}:notice:${suffix}`,
233 fileId,
234 text,
235 };
236}
237
238function noticeRowsForFile(file: ReviewRenderableFile): ReadonlyArray<NativeReviewDiffRow> {
239 if (file.rows.length > 0) {
240 return [];
241 }
242
243 const previewState = getReviewFilePreviewState(file);
244 if (previewState.kind === "suppressed" && previewState.reason === "non-text") {
245 return [
246 createNoticeRow(file.id, "non-text", "Unsupported format. Diff contents are not available."),
247 ];
248 }
249
250 if (file.changeType === "rename-pure") {
251 return [createNoticeRow(file.id, "rename", "This file was renamed without modifications.")];
252 }
253
254 return [];
255}
256
257function trimWordDiffRanges(
258 content: string,
259 ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
260): NonNullable<NativeReviewDiffRow["wordDiffRanges"]> {
261 return pipe(
262 ranges,
263 Arr.flatMap((range) => {
264 let start = Math.max(0, range.start);
265 let end = Math.min(content.length, range.end);
266
267 while (start < end && /\s/.test(content[start] ?? "")) {
268 start += 1;
269 }
270 while (end > start && /\s/.test(content[end - 1] ?? "")) {
271 end -= 1;
272 }
273
274 return end > start ? [{ start, end }] : [];
275 }),
276 );
277}
278
279function nonWhitespaceLength(value: string) {
280 return value.replace(/\s/g, "").length;
281}
282
283function shouldUseWordDiffRanges(
284 content: string,
285 ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
286) {
287 if (ranges.length === 0 || ranges.length > NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT) {
288 return false;
289 }
290
291 const meaningfulLength = nonWhitespaceLength(content);
292 if (meaningfulLength === 0) {
293 return false;
294 }
295
296 const highlightedLength = ranges.reduce(
297 (total, range) => total + nonWhitespaceLength(content.slice(range.start, range.end)),
298 0,
299 );
300 return highlightedLength / meaningfulLength <= NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE;
301}
302
303function addNativeWordDiffRanges(
304 rows: ReadonlyArray<NativeReviewDiffRow>,
305): ReadonlyArray<NativeReviewDiffRow> {
306 const nextRows = [...rows];
307 let index = 0;
308
309 while (index < nextRows.length) {
310 const deletedRowIndexes: number[] = [];
311 const addedRowIndexes: number[] = [];
312 const fileId = nextRows[index]?.fileId;
313
314 while (
315 nextRows[index]?.kind === "line" &&
316 nextRows[index]?.change === "delete" &&
317 nextRows[index]?.fileId === fileId
318 ) {
319 deletedRowIndexes.push(index);
320 index += 1;
321 }
322
323 while (
324 nextRows[index]?.kind === "line" &&
325 nextRows[index]?.change === "add" &&
326 nextRows[index]?.fileId === fileId
327 ) {
328 addedRowIndexes.push(index);
329 index += 1;
330 }
331
332 const pairedCount = Math.min(deletedRowIndexes.length, addedRowIndexes.length);
333 for (let pairIndex = 0; pairIndex < pairedCount; pairIndex += 1) {
334 const deletedRowIndex = deletedRowIndexes[pairIndex];
335 const addedRowIndex = addedRowIndexes[pairIndex];
336 const deletedRow = nextRows[deletedRowIndex];
337 const addedRow = nextRows[addedRowIndex];
338 if (!deletedRow?.content || !addedRow?.content) {
339 continue;
340 }
341
342 const ranges = computeWordAltDiffRanges({
343 deletionLine: deletedRow.content,
344 additionLine: addedRow.content,
345 });
346 const deletionRanges = trimWordDiffRanges(deletedRow.content, ranges.deletion);
347 const additionRanges = trimWordDiffRanges(addedRow.content, ranges.addition);
348
349 if (shouldUseWordDiffRanges(deletedRow.content, deletionRanges)) {
350 nextRows[deletedRowIndex] = { ...deletedRow, wordDiffRanges: deletionRanges };
351 }
352 if (shouldUseWordDiffRanges(addedRow.content, additionRanges)) {
353 nextRows[addedRowIndex] = { ...addedRow, wordDiffRanges: additionRanges };
354 }
355 }
356
357 if (deletedRowIndexes.length === 0 && addedRowIndexes.length === 0) {
358 index += 1;
359 }
360 }
361
362 return nextRows;
363}
364
365function mapLineRow(
366 file: ReviewRenderableFile,
367 row: ReviewRenderableLineRow,
368 rowIndex: number,
369): NativeReviewDiffRow {
370 return {
371 kind: "line",
372 id: `${file.id}:line:${rowIndex}:${row.id}`,
373 fileId: file.id,
374 content: row.content,
375 change: row.change,
376 oldLineNumber: row.oldLineNumber,
377 newLineNumber: row.newLineNumber,
378 };
379}
380
381function mapFileRows(
382 file: ReviewRenderableFile,
383 comments: ReadonlyArray<ReviewInlineComment>,
384 commentTargetsByRowId: Map<string, NativeReviewDiffCommentTarget>,
385 rowIdByCommentLineId: Map<string, string>,
386): ReadonlyArray<NativeReviewDiffRow> {
387 const rows: NativeReviewDiffRow[] = [
388 {
389 kind: "file",
390 id: `${file.id}:header`,
391 fileId: file.id,
392 filePath: file.path,
393 previousPath: file.previousPath,
394 changeType: mapChangeType(file),
395 additions: file.additions,
396 deletions: file.deletions,
397 },
398 ];
399
400 const lineRows = file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line");
401 const commentsByEndIndex = new Map<number, ReviewInlineComment[]>();
402 comments.forEach((comment) => {
403 if (comment.filePath !== file.path) {
404 return;
405 }
406 const endIndex = Math.min(comment.endIndex, lineRows.length - 1);
407 if (endIndex < 0) {
408 return;
409 }
410 const existing = commentsByEndIndex.get(endIndex);
411 if (existing) {
412 existing.push(comment);
413 return;
414 }
415 commentsByEndIndex.set(endIndex, [comment]);
416 });
417 let lineIndex = 0;
418 file.rows.forEach((row, rowIndex) => {
419 if (row.kind === "hunk") {
420 rows.push({
421 kind: "hunk",
422 id: `${file.id}:hunk:${rowIndex}:${row.id}`,
423 fileId: file.id,
424 text: row.context ? `${row.header} ${row.context}` : row.header,
425 });
426 return;
427 }
428
429 const nativeRow = mapLineRow(file, row, rowIndex);
430 rows.push(nativeRow);
431 rowIdByCommentLineId.set(row.id, nativeRow.id);
432 commentTargetsByRowId.set(nativeRow.id, {
433 filePath: file.path,
434 lines: lineRows,
435 lineIndex,
436 });
437 const commentsForLine = commentsByEndIndex.get(lineIndex) ?? [];
438 for (const comment of commentsForLine) {
439 rows.push({
440 kind: "comment",
441 id: comment.id,
442 fileId: file.id,
443 filePath: file.path,
444 commentText: comment.text,
445 commentRangeLabel: comment.rangeLabel,
446 commentSectionTitle: comment.sectionTitle,
447 });
448 }
449 lineIndex += 1;
450 });
451
452 rows.push(...noticeRowsForFile(file));
453 return rows;
454}
455
456export function buildNativeReviewDiffData(
457 input: BuildNativeReviewDiffDataInput,
458): NativeReviewDiffData;
459export function buildNativeReviewDiffData(parsedDiff: ReviewParsedDiff): NativeReviewDiffData;
460export function buildNativeReviewDiffData(
461 input: ReviewParsedDiff | BuildNativeReviewDiffDataInput,
462): NativeReviewDiffData {
463 const parsedDiff = "parsedDiff" in input ? input.parsedDiff : input;
464 const comments = "parsedDiff" in input ? (input.comments ?? []) : [];
465 if (parsedDiff.kind !== "files") {
466 return {
467 rows: [],
468 files: [],
469 commentTargetsByRowId: new Map(),
470 rowIdByCommentLineId: new Map(),
471 additions: 0,
472 deletions: 0,
473 };
474 }
475
476 const files = parsedDiff.files.map<NativeReviewDiffFile>((file) => ({
477 id: file.id,
478 path: file.path,
479 language: getLanguageForPath(file.path, file.languageHint),
480 additions: file.additions,
481 deletions: file.deletions,
482 }));
483 const commentTargetsByRowId = new Map<string, NativeReviewDiffCommentTarget>();
484 const rowIdByCommentLineId = new Map<string, string>();
485 const rows = addNativeWordDiffRanges(
486 Arr.flatMap(parsedDiff.files, (file) =>
487 mapFileRows(file, comments, commentTargetsByRowId, rowIdByCommentLineId),
488 ),
489 );
490
491 return {
492 rows,
493 files,
494 commentTargetsByRowId,
495 rowIdByCommentLineId,
496 additions: parsedDiff.additions,
497 deletions: parsedDiff.deletions,
498 };
499}
500
501/**
502 * Reuses the expensive flattened native row model across React development
503 * render probes and unrelated draft updates. Only the latest comment version
504 * is retained for each parsed diff so editing a comment cannot grow the cache.
505 */
506export function getCachedNativeReviewDiffData(
507 input: BuildNativeReviewDiffDataInput,
508): NativeReviewDiffData {
509 const comments = input.comments ?? [];
510 const commentsKey = buildReviewCommentsCacheKey(comments);
511 const cached = nativeReviewDiffDataCache.get(input.parsedDiff);
512 if (cached?.commentsKey === commentsKey) {
513 return cached.data;
514 }
515
516 const data = buildNativeReviewDiffData({
517 parsedDiff: input.parsedDiff,
518 comments,
519 });
520 nativeReviewDiffDataCache.set(input.parsedDiff, { commentsKey, data });
521 return data;
522}