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

nativeReviewDiffAdapter.ts

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