The best way to control Claude Code, Codex and more from any computer or phone

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