Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

nativeReviewDiffAdapter.ts

579 lines18.4 KB

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