Open History to see the last commit
1import { cutLineNoteStart } from "@t3tools/shared/diffCutLines";
2import type { NativeReviewDiffRow, NativeReviewDiffTheme } from "../diffs/nativeReviewDiffSurface";
3import type { NativeReviewDiffFile } from "../diffs/nativeReviewDiffTypes";
4import * as Arr from "effect/Array";
5import { pipe } from "effect/Function";
6import type { ResolvedMobileCodeSurface } from "../../lib/appearancePreferences";
7import { resolveHighlightLanguage } from "../../lib/highlightLanguage";
8import { type MobileThemeId, type MobileThemeVariables } from "../../lib/mobileTheme";
9import { getMobileTerminalTheme, type TerminalAppearanceScheme } from "../terminal/terminalTheme";
10import { computeWordAltDiffRanges } from "./reviewWordDiffs";
11import {
12 getReviewFilePreviewState,
13 type ReviewParsedDiff,
14 type ReviewRenderableFile,
15 type ReviewRenderableLineRow,
16} from "./reviewModel";
17import type { ReviewInlineComment } from "./reviewCommentSelection";
18import { msg } from "gt-react-native";
19import { m } from "../../i18n/messages";
20
21const NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT = 4;
22const NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE = 0.45;
23// Keep eager word matching within the old 2,000-row budget while retaining more rendered rows.
24const NATIVE_REVIEW_MAX_WORD_DIFF_COMPARISONS = 1_000;
25// Bound the rows serialized to the native heap before mapping and word matching.
26const NATIVE_REVIEW_MAX_FILE_ROWS = 100_000;
27const TRUNCATED_FILE_NOTICE = msg("This diff is too large to show in full.");
28const NATIVE_HEX_COLOR = /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})([\da-f]{2})?$/i;
29const NATIVE_RGBA_COLOR =
30 /^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)(?:\s*,\s*([\d.]+))?\s*\)$/;
31// Git's a/, b/ (maybe quoted) or /dev/null paths, or a `diff -u` timestamp after a tab.
32const LONE_FILE_HEADER =
33 /^(--- "?a\/|\+\+\+ "?b\/|(---|\+\+\+) (\/dev\/null(\t|$)|[^\t]+\t\d{4}-\d\d-\d\d \d\d:\d\d:\d\d))/;
34
35export const NATIVE_REVIEW_DIFF_CONTENT_WIDTH = 2_800;
36
37export function buildNativeReviewSnippetRows(
38 comment: Pick<ReviewInlineComment, "id" | "diff" | "fenceLanguage">,
39): NativeReviewDiffRow[] {
40 if ((comment.fenceLanguage ?? "diff") !== "diff" || !comment.diff.trim()) return [];
41 const lines = comment.diff.replace(/\r\n/g, "\n").replace(/\n$/, "").split("\n");
42 // A file header is a `--- ` line followed by `+++ `, or one shaped like a header on its own.
43 // Any other `--- ` or `+++ ` line is a changed `-- ` or `++ ` line.
44 const isFileHeader = (line: string, index: number) =>
45 LONE_FILE_HEADER.test(line) ||
46 (line.startsWith("--- ") && lines[index + 1]?.startsWith("+++ "));
47 if (lines.some((line, index) => !/^[ +-]/.test(line) || isFileHeader(line, index))) return [];
48 return lines.map((line, index) => ({
49 kind: "line",
50 id: `${comment.id}:snippet:${index}`,
51 content: line.slice(1),
52 change: line[0] === "+" ? "add" : line[0] === "-" ? "delete" : "context",
53 oldLineNumber: null,
54 newLineNumber: null,
55 }));
56}
57
58export function reviewCommentDiffText(diff: string): string {
59 return diff.trimStart().replace(/\n+$/, "");
60}
61
62export function buildReviewCommentPatch(comment: ReviewInlineComment): string {
63 if ((comment.fenceLanguage ?? "diff") !== "diff") {
64 return "";
65 }
66 if (!comment.diff.trim()) {
67 return "";
68 }
69 const diff = reviewCommentDiffText(comment.diff);
70
71 if (diff.startsWith("diff --git ")) {
72 return diff;
73 }
74
75 const normalizedPath = comment.filePath.replaceAll("\\", "/");
76 return [
77 `diff --git a/${normalizedPath} b/${normalizedPath}`,
78 `--- a/${normalizedPath}`,
79 `+++ b/${normalizedPath}`,
80 diff,
81 ].join("\n");
82}
83
84function opaqueNativeHexColor(color: string, background: string): string {
85 const hex = NATIVE_HEX_COLOR.exec(color);
86 if (hex && !hex[4]) return color;
87
88 const rgba = NATIVE_RGBA_COLOR.exec(color);
89 const backgroundHex = NATIVE_HEX_COLOR.exec(background);
90 if ((!hex && !rgba) || !backgroundHex) return background;
91
92 const alpha = hex
93 ? Number.parseInt(hex[4] ?? "ff", 16) / 255
94 : rgba?.[4] === undefined
95 ? 1
96 : Math.min(1, Math.max(0, Number(rgba[4])));
97 const channels = [1, 2, 3].map((index) => {
98 const foreground = hex ? Number.parseInt(hex[index] ?? "0", 16) : Number(rgba?.[index]);
99 const behind = Number.parseInt(backgroundHex[index] ?? "0", 16);
100 return Math.round(foreground * alpha + behind * (1 - alpha));
101 });
102 return `#${channels.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
103}
104
105export function createNativeReviewDiffStyle(
106 codeSurface: ResolvedMobileCodeSurface,
107 wordWrap: boolean,
108 fonts: { readonly code: string; readonly ui: string; readonly uiBold: string },
109) {
110 return {
111 wordWrap,
112 codeFontFamily: fonts.code,
113 uiFontFamily: fonts.ui,
114 uiBoldFontFamily: fonts.uiBold,
115 rowHeight: codeSurface.rowHeight,
116 contentWidth: NATIVE_REVIEW_DIFF_CONTENT_WIDTH,
117 changeBarWidth: 4,
118 gutterWidth: codeSurface.gutterWidth,
119 codePadding: codeSurface.codePadding,
120 textVerticalInset: codeSurface.textVerticalInset,
121 fileHeaderHeight: 56,
122 fileHeaderHorizontalMargin: 8,
123 fileHeaderVerticalMargin: 6,
124 fileHeaderCornerRadius: 10,
125 fileHeaderHorizontalPadding: 10,
126 fileHeaderPathRightPadding: 118,
127 fileHeaderCountColumnWidth: 38,
128 fileHeaderCountGap: 5,
129 codeFontSize: codeSurface.fontSize,
130 codeFontWeight: "regular",
131 lineNumberFontSize: codeSurface.lineNumberFontSize,
132 lineNumberFontWeight: "regular",
133 hunkFontSize: 11,
134 hunkFontWeight: "medium",
135 fileHeaderFontSize: 11,
136 fileHeaderFontWeight: "semibold",
137 fileHeaderMetaFontSize: 10,
138 fileHeaderMetaFontWeight: "semibold",
139 fileHeaderSubtextFontSize: 11,
140 fileHeaderSubtextFontWeight: "medium",
141 fileHeaderStatusFontSize: 9,
142 fileHeaderStatusFontWeight: "bold",
143 } as const;
144}
145
146export interface NativeReviewDiffData {
147 readonly rows: ReadonlyArray<NativeReviewDiffRow>;
148 readonly files: ReadonlyArray<NativeReviewDiffFile>;
149 readonly commentTargetsByRowId: ReadonlyMap<string, NativeReviewDiffCommentTarget>;
150 readonly rowIdByCommentLineId: ReadonlyMap<string, string>;
151 readonly additions: number;
152 readonly deletions: number;
153}
154
155export interface NativeReviewDiffCommentTarget {
156 readonly filePath: string;
157 readonly lines: ReadonlyArray<ReviewRenderableLineRow>;
158 readonly lineIndex: number;
159}
160
161export interface BuildNativeReviewDiffDataInput {
162 readonly parsedDiff: ReviewParsedDiff;
163 readonly comments?: ReadonlyArray<ReviewInlineComment>;
164}
165
166interface CachedNativeReviewDiffData {
167 readonly prepared: PreparedNativeReviewDiffData;
168 readonly commentsKey: string;
169 readonly data: NativeReviewDiffData;
170}
171
172interface PreparedNativeReviewFileRows {
173 readonly fileId: string;
174 readonly filePath: string;
175 readonly lineCount: number;
176 readonly rows: ReadonlyArray<NativeReviewDiffRow>;
177 readonly commentTargetsByRowId: ReadonlyMap<string, NativeReviewDiffCommentTarget>;
178 readonly rowIdByCommentLineId: ReadonlyMap<string, string>;
179 commentedRows: {
180 readonly commentsKey: string;
181 readonly rows: ReadonlyArray<NativeReviewDiffRow>;
182 } | null;
183}
184
185interface PreparedNativeReviewDiffData extends Omit<NativeReviewDiffData, "rows"> {
186 readonly fileRows: ReadonlyArray<PreparedNativeReviewFileRows>;
187}
188
189const nativeReviewDiffDataCache = new WeakMap<ReviewParsedDiff, CachedNativeReviewDiffData>();
190const nativeReviewFileRowsCache = new WeakMap<ReviewRenderableFile, PreparedNativeReviewFileRows>();
191
192function buildReviewCommentsCacheKey(comments: ReadonlyArray<ReviewInlineComment>): string {
193 if (comments.length === 0) {
194 return "none";
195 }
196
197 return JSON.stringify(
198 comments.map((comment) => [
199 comment.id,
200 comment.sectionId,
201 comment.sectionTitle,
202 comment.filePath,
203 comment.startIndex,
204 comment.endIndex,
205 comment.rangeLabel,
206 comment.text,
207 ]),
208 );
209}
210
211export function createNativeReviewDiffTheme(
212 scheme: TerminalAppearanceScheme,
213 themeId: MobileThemeId,
214 appTheme: MobileThemeVariables,
215): NativeReviewDiffTheme {
216 const terminalTheme = getMobileTerminalTheme(themeId, scheme);
217 const [, terminalRed] = terminalTheme.palette;
218 // Swift and Android disagree on alpha-byte order; flatten to shared opaque #RRGGBB.
219 const screen = opaqueNativeHexColor(
220 appTheme["--color-screen"],
221 scheme === "dark" ? "#000000" : "#ffffff",
222 );
223 const background = opaqueNativeHexColor(appTheme["--color-md-code-bg"], screen);
224 const nativeColor = (color: string) => opaqueNativeHexColor(color, background);
225
226 if (scheme === "dark") {
227 return {
228 background,
229 text: nativeColor(appTheme["--color-md-code-text"]),
230 mutedText: nativeColor(appTheme["--color-foreground-muted"]),
231 headerBackground: background,
232 border: nativeColor(appTheme["--color-border"]),
233 hunkBackground: nativeColor(appTheme["--color-subtle-strong"]),
234 hunkText: nativeColor(appTheme["--color-foreground"]),
235 addBackground: "#0d2f28",
236 deleteBackground: "#391415",
237 addBar: "#00cab1",
238 deleteBar: terminalRed ?? "#ff2e3f",
239 addText: "#5ECC71",
240 deleteText: "#FF6762",
241 warningText: nativeColor(appTheme["--color-warning-foreground"]),
242 warningBackground: nativeColor(appTheme["--color-warning"]),
243 };
244 }
245
246 return {
247 background,
248 text: nativeColor(appTheme["--color-md-code-text"]),
249 mutedText: nativeColor(appTheme["--color-foreground-muted"]),
250 headerBackground: background,
251 border: nativeColor(appTheme["--color-border"]),
252 hunkBackground: nativeColor(appTheme["--color-subtle-strong"]),
253 hunkText: nativeColor(appTheme["--color-foreground"]),
254 addBackground: "#e5f8f5",
255 deleteBackground: "#ffe6e7",
256 addBar: "#00cab1",
257 deleteBar: terminalRed ?? "#ff2e3f",
258 addText: "#199F43",
259 deleteText: "#D52C36",
260 warningText: nativeColor(appTheme["--color-warning-foreground"]),
261 warningBackground: nativeColor(appTheme["--color-warning"]),
262 };
263}
264
265function mapChangeType(file: ReviewRenderableFile): NativeReviewDiffRow["changeType"] {
266 switch (file.changeType) {
267 case "change":
268 return "modified";
269 case "new":
270 case "deleted":
271 case "rename-pure":
272 case "rename-changed":
273 return file.changeType;
274 default:
275 return "modified";
276 }
277}
278
279function createNoticeRow(fileId: string, suffix: string, text: string): NativeReviewDiffRow {
280 return {
281 kind: "notice",
282 id: `${fileId}:notice:${suffix}`,
283 fileId,
284 text,
285 };
286}
287
288function noticeRowsForFile(file: ReviewRenderableFile): ReadonlyArray<NativeReviewDiffRow> {
289 if (file.notice) {
290 return [
291 {
292 ...createNoticeRow(file.id, "loading", file.notice),
293 ...(file.noticeTone === undefined ? {} : { tone: file.noticeTone }),
294 ...(file.noticeActionable ? { actionable: true } : {}),
295 },
296 ];
297 }
298 if (file.rows.length > 0) {
299 return [];
300 }
301
302 const previewState = getReviewFilePreviewState(file);
303 if (previewState.kind === "suppressed" && previewState.reason === "non-text") {
304 return [
305 createNoticeRow(
306 file.id,
307 "non-text",
308 m(msg("Unsupported format. Diff contents are not available.")),
309 ),
310 ];
311 }
312
313 if (file.changeType === "rename-pure") {
314 return [
315 createNoticeRow(file.id, "rename", m(msg("This file was renamed without modifications."))),
316 ];
317 }
318
319 return [];
320}
321
322function trimWordDiffRanges(
323 content: string,
324 ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
325): NonNullable<NativeReviewDiffRow["wordDiffRanges"]> {
326 return pipe(
327 ranges,
328 Arr.flatMap((range) => {
329 let start = Math.max(0, range.start);
330 let end = Math.min(content.length, range.end);
331
332 while (start < end && /\s/.test(content[start] ?? "")) {
333 start += 1;
334 }
335 while (end > start && /\s/.test(content[end - 1] ?? "")) {
336 end -= 1;
337 }
338
339 return end > start ? [{ start, end }] : [];
340 }),
341 );
342}
343
344function nonWhitespaceLength(value: string) {
345 return value.replace(/\s/g, "").length;
346}
347
348function shouldUseWordDiffRanges(
349 content: string,
350 ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
351) {
352 if (ranges.length === 0 || ranges.length > NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT) {
353 return false;
354 }
355
356 const meaningfulLength = nonWhitespaceLength(content);
357 if (meaningfulLength === 0) {
358 return false;
359 }
360
361 const highlightedLength = ranges.reduce(
362 (total, range) => total + nonWhitespaceLength(content.slice(range.start, range.end)),
363 0,
364 );
365 return highlightedLength / meaningfulLength <= NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE;
366}
367
368function addNativeWordDiffRanges(
369 rows: ReadonlyArray<NativeReviewDiffRow>,
370 lineRows: ReadonlyArray<ReviewRenderableLineRow>,
371): ReadonlyArray<NativeReviewDiffRow> {
372 const nextRows = [...rows];
373 const addedRowIndexes = new Map<number, number>();
374 const pairs: Array<{ deletionRowIndex: number; additionTokenIndex: number }> = [];
375 let lineIndex = 0;
376
377 // Pierre can split adjacent change blocks to align similar lines. Keep those pairings.
378 rows.forEach((row, rowIndex) => {
379 if (row.kind !== "line") return;
380 const source = lineRows[lineIndex++];
381 if (source?.change === "add" && source.additionTokenIndex !== null) {
382 addedRowIndexes.set(source.additionTokenIndex, rowIndex);
383 } else if (source?.change === "delete" && source.comparison?.change === "add") {
384 pairs.push({ deletionRowIndex: rowIndex, additionTokenIndex: source.comparison.tokenIndex });
385 }
386 });
387
388 let comparisonCount = 0;
389 for (const { deletionRowIndex, additionTokenIndex } of pairs) {
390 if (comparisonCount >= NATIVE_REVIEW_MAX_WORD_DIFF_COMPARISONS) break;
391 const addedRowIndex = addedRowIndexes.get(additionTokenIndex);
392 if (addedRowIndex === undefined) continue;
393 const deletedRow = nextRows[deletionRowIndex];
394 const addedRow = nextRows[addedRowIndex];
395 if (!deletedRow?.content || !addedRow?.content) continue;
396
397 comparisonCount += 1;
398 const ranges = computeWordAltDiffRanges({
399 deletionLine: deletedRow.content,
400 additionLine: addedRow.content,
401 });
402 const deletionRanges = trimWordDiffRanges(deletedRow.content, ranges.deletion);
403 const additionRanges = trimWordDiffRanges(addedRow.content, ranges.addition);
404
405 if (shouldUseWordDiffRanges(deletedRow.content, deletionRanges)) {
406 nextRows[deletionRowIndex] = { ...deletedRow, wordDiffRanges: deletionRanges };
407 }
408 if (shouldUseWordDiffRanges(addedRow.content, additionRanges)) {
409 nextRows[addedRowIndex] = { ...addedRow, wordDiffRanges: additionRanges };
410 }
411 }
412
413 return nextRows;
414}
415
416function mapLineRow(
417 file: ReviewRenderableFile,
418 row: ReviewRenderableLineRow,
419 rowIndex: number,
420): NativeReviewDiffRow {
421 const noteStart = cutLineNoteStart(row.content);
422 return {
423 kind: "line",
424 id: `${file.id}:line:${rowIndex}:${row.id}`,
425 fileId: file.id,
426 content: row.content,
427 change: row.change,
428 oldLineNumber: row.oldLineNumber,
429 newLineNumber: row.newLineNumber,
430 ...(noteStart === null ? {} : { noteStart }),
431 };
432}
433
434function prepareFileRows(file: ReviewRenderableFile): PreparedNativeReviewFileRows {
435 const cached = nativeReviewFileRowsCache.get(file);
436 if (cached) return cached;
437 const commentTargetsByRowId = new Map<string, NativeReviewDiffCommentTarget>();
438 const rowIdByCommentLineId = new Map<string, string>();
439 const rows: NativeReviewDiffRow[] = [
440 {
441 kind: "file",
442 id: `${file.id}:header`,
443 fileId: file.id,
444 filePath: file.path,
445 previousPath: file.previousPath,
446 changeType: mapChangeType(file),
447 additions: file.additions,
448 deletions: file.deletions,
449 },
450 ];
451
452 const sourceRows =
453 file.rows.length > NATIVE_REVIEW_MAX_FILE_ROWS
454 ? file.rows.slice(0, NATIVE_REVIEW_MAX_FILE_ROWS)
455 : file.rows;
456 const lineRows = sourceRows.filter((row): row is ReviewRenderableLineRow => row.kind === "line");
457 let lineIndex = 0;
458 sourceRows.forEach((row, rowIndex) => {
459 if (row.kind === "hunk") {
460 rows.push({
461 kind: "hunk",
462 id: `${file.id}:hunk:${rowIndex}:${row.id}`,
463 fileId: file.id,
464 text: row.context ? `${row.header} ${row.context}` : row.header,
465 });
466 return;
467 }
468
469 const nativeRow = mapLineRow(file, row, rowIndex);
470 rows.push(nativeRow);
471 rowIdByCommentLineId.set(row.id, nativeRow.id);
472 commentTargetsByRowId.set(nativeRow.id, {
473 filePath: file.path,
474 lines: lineRows,
475 lineIndex,
476 });
477 lineIndex += 1;
478 });
479
480 if (sourceRows !== file.rows) {
481 rows.push(createNoticeRow(file.id, "truncated", m(TRUNCATED_FILE_NOTICE)));
482 }
483 rows.push(...noticeRowsForFile(file));
484 if (file.noEOFCRAdditions || file.noEOFCRDeletions) {
485 const text = file.noEOFCRAdditions
486 ? file.noEOFCRDeletions
487 ? m(msg("Old and new files have no newline at end of file."))
488 : m(msg("New file has no newline at end of file."))
489 : m(msg("Old file has no newline at end of file."));
490 rows.push(createNoticeRow(file.id, "eof", text));
491 }
492 const prepared: PreparedNativeReviewFileRows = {
493 fileId: file.id,
494 filePath: file.path,
495 lineCount: lineRows.length,
496 // Pair source lines before inserting comments so comment rows cannot affect matching.
497 rows: addNativeWordDiffRanges(rows, lineRows),
498 commentTargetsByRowId,
499 rowIdByCommentLineId,
500 commentedRows: null,
501 };
502 nativeReviewFileRowsCache.set(file, prepared);
503 return prepared;
504}
505
506function insertFileComments(
507 file: PreparedNativeReviewFileRows,
508 comments: ReadonlyArray<ReviewInlineComment>,
509): ReadonlyArray<NativeReviewDiffRow> {
510 if (comments.length === 0) {
511 file.commentedRows = null;
512 return file.rows;
513 }
514 const commentsKey = buildReviewCommentsCacheKey(comments);
515 if (file.commentedRows?.commentsKey === commentsKey) {
516 return file.commentedRows.rows;
517 }
518
519 const commentsByEndIndex = new Map<number, ReviewInlineComment[]>();
520 for (const comment of comments) {
521 if (comment.startIndex >= file.lineCount) continue;
522 const endIndex = Math.min(comment.endIndex, file.lineCount - 1);
523 if (endIndex < 0) continue;
524 const existing = commentsByEndIndex.get(endIndex);
525 if (existing) {
526 existing.push(comment);
527 } else {
528 commentsByEndIndex.set(endIndex, [comment]);
529 }
530 }
531 const rows: NativeReviewDiffRow[] = [];
532 let lineIndex = 0;
533 for (const row of file.rows) {
534 rows.push(row);
535 if (row.kind !== "line") continue;
536 for (const comment of commentsByEndIndex.get(lineIndex) ?? []) {
537 rows.push({
538 kind: "comment",
539 id: comment.id,
540 fileId: file.fileId,
541 filePath: file.filePath,
542 commentText: comment.text,
543 commentRangeLabel: comment.rangeLabel,
544 commentSectionTitle: comment.sectionTitle,
545 });
546 }
547 lineIndex += 1;
548 }
549 file.commentedRows = { commentsKey, rows };
550 return rows;
551}
552
553function prepareNativeReviewDiffData(parsedDiff: ReviewParsedDiff): PreparedNativeReviewDiffData {
554 if (parsedDiff.kind !== "files") {
555 return {
556 fileRows: [],
557 files: [],
558 commentTargetsByRowId: new Map(),
559 rowIdByCommentLineId: new Map(),
560 additions: 0,
561 deletions: 0,
562 };
563 }
564
565 const files = parsedDiff.files.map<NativeReviewDiffFile>((file) => ({
566 id: file.id,
567 path: file.path,
568 language: resolveHighlightLanguage({ language: file.languageHint, path: file.path }),
569 additions: file.additions,
570 deletions: file.deletions,
571 }));
572 const commentTargetsByRowId = new Map<string, NativeReviewDiffCommentTarget>();
573 const rowIdByCommentLineId = new Map<string, string>();
574 const fileRows = parsedDiff.files.map(prepareFileRows);
575 for (const file of fileRows) {
576 for (const [rowId, target] of file.commentTargetsByRowId) {
577 commentTargetsByRowId.set(rowId, target);
578 }
579 for (const [lineId, rowId] of file.rowIdByCommentLineId) {
580 rowIdByCommentLineId.set(lineId, rowId);
581 }
582 }
583
584 return {
585 fileRows,
586 files,
587 commentTargetsByRowId,
588 rowIdByCommentLineId,
589 additions: parsedDiff.additions,
590 deletions: parsedDiff.deletions,
591 };
592}
593
594function buildCommentedNativeReviewDiffData(
595 prepared: PreparedNativeReviewDiffData,
596 comments: ReadonlyArray<ReviewInlineComment>,
597): NativeReviewDiffData {
598 const commentsByFilePath = new Map<string, ReviewInlineComment[]>();
599 for (const comment of comments) {
600 const existing = commentsByFilePath.get(comment.filePath);
601 if (existing) {
602 existing.push(comment);
603 } else {
604 commentsByFilePath.set(comment.filePath, [comment]);
605 }
606 }
607 return {
608 rows: Arr.flatMap(prepared.fileRows, (file) =>
609 insertFileComments(file, commentsByFilePath.get(file.filePath) ?? []),
610 ),
611 files: prepared.files,
612 commentTargetsByRowId: prepared.commentTargetsByRowId,
613 rowIdByCommentLineId: prepared.rowIdByCommentLineId,
614 additions: prepared.additions,
615 deletions: prepared.deletions,
616 };
617}
618
619export function buildNativeReviewDiffData(
620 input: BuildNativeReviewDiffDataInput,
621): NativeReviewDiffData;
622export function buildNativeReviewDiffData(parsedDiff: ReviewParsedDiff): NativeReviewDiffData;
623export function buildNativeReviewDiffData(
624 input: ReviewParsedDiff | BuildNativeReviewDiffDataInput,
625): NativeReviewDiffData {
626 const parsedDiff = "parsedDiff" in input ? input.parsedDiff : input;
627 const comments = "parsedDiff" in input ? (input.comments ?? []) : [];
628 return buildCommentedNativeReviewDiffData(prepareNativeReviewDiffData(parsedDiff), comments);
629}
630
631export function getCachedNativeReviewDiffData(
632 input: BuildNativeReviewDiffDataInput,
633): NativeReviewDiffData {
634 const comments = input.comments ?? [];
635 const commentsKey = buildReviewCommentsCacheKey(comments);
636 const cached = nativeReviewDiffDataCache.get(input.parsedDiff);
637 if (cached?.commentsKey === commentsKey) {
638 return cached.data;
639 }
640
641 const prepared = cached?.prepared ?? prepareNativeReviewDiffData(input.parsedDiff);
642 const data = buildCommentedNativeReviewDiffData(prepared, comments);
643 nativeReviewDiffDataCache.set(input.parsedDiff, { prepared, commentsKey, data });
644 return data;
645}