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

nativeReviewDiffAdapter.ts

494 lines14.9 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 { resolveMobileCodeSurface } from "../../lib/appearancePreferences";
10import { MOBILE_CODE_SURFACE } from "../../lib/typography";
11import { getPierreTerminalTheme, type TerminalAppearanceScheme } from "../terminal/terminalTheme";
12import { computeWordAltDiffRanges } from "./reviewWordDiffs";
13import {
14 getReviewFilePreviewState,
15 type ReviewParsedDiff,
16 type ReviewRenderableFile,
17 type ReviewRenderableLineRow,
18} from "./reviewModel";
19import type { ReviewInlineComment } from "./reviewCommentSelection";
20​
21const NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT = 4;
22const NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE = 0.45;
23​
24export const NATIVE_REVIEW_DIFF_ROW_HEIGHT = MOBILE_CODE_SURFACE.rowHeight;
25export const NATIVE_REVIEW_DIFF_CONTENT_WIDTH = 2_800;
26​
27export const NATIVE_REVIEW_DIFF_STYLE = createNativeReviewDiffStyle(
28 resolveMobileCodeSurface(MOBILE_CODE_SURFACE.fontSize),
29);
30​
31export function createNativeReviewDiffStyle(codeSurface: ResolvedMobileCodeSurface) {
32 return {
33 rowHeight: codeSurface.rowHeight,
34 contentWidth: NATIVE_REVIEW_DIFF_CONTENT_WIDTH,
35 changeBarWidth: 4,
36 gutterWidth: codeSurface.gutterWidth,
37 codePadding: codeSurface.codePadding,
38 textVerticalInset: codeSurface.textVerticalInset,
39 fileHeaderHeight: 56,
40 fileHeaderHorizontalMargin: 8,
41 fileHeaderVerticalMargin: 6,
42 fileHeaderCornerRadius: 10,
43 fileHeaderHorizontalPadding: 10,
44 fileHeaderPathRightPadding: 118,
45 fileHeaderCountColumnWidth: 38,
46 fileHeaderCountGap: 5,
47 codeFontSize: codeSurface.fontSize,
48 codeFontWeight: "regular",
49 lineNumberFontSize: codeSurface.lineNumberFontSize,
50 lineNumberFontWeight: "regular",
51 hunkFontSize: 11,
52 hunkFontWeight: "medium",
53 fileHeaderFontSize: 11,
54 fileHeaderFontWeight: "semibold",
55 fileHeaderMetaFontSize: 10,
56 fileHeaderMetaFontWeight: "semibold",
57 fileHeaderSubtextFontSize: 11,
58 fileHeaderSubtextFontWeight: "medium",
59 fileHeaderStatusFontSize: 9,
60 fileHeaderStatusFontWeight: "bold",
61 emptyStateFontSize: 12,
62 emptyStateFontWeight: "medium",
63 } as const;
65​
66export interface NativeReviewDiffData {
67 readonly rows: ReadonlyArray<NativeReviewDiffRow>;
68 readonly files: ReadonlyArray<NativeReviewDiffFile>;
69 readonly commentTargetsByRowId: ReadonlyMap<string, NativeReviewDiffCommentTarget>;
70 readonly rowIdByCommentLineId: ReadonlyMap<string, string>;
71 readonly additions: number;
72 readonly deletions: number;
74​
75export interface NativeReviewDiffCommentTarget {
76 readonly filePath: string;
77 readonly lines: ReadonlyArray<ReviewRenderableLineRow>;
78 readonly lineIndex: number;
80​
81export interface BuildNativeReviewDiffDataInput {
82 readonly parsedDiff: ReviewParsedDiff;
83 readonly comments?: ReadonlyArray<ReviewInlineComment>;
85​
86interface CachedNativeReviewDiffData {
87 readonly commentsKey: string;
88 readonly data: NativeReviewDiffData;
90​
91const nativeReviewDiffDataCache = new WeakMap<ReviewParsedDiff, CachedNativeReviewDiffData>();
92​
93function buildReviewCommentsCacheKey(comments: ReadonlyArray<ReviewInlineComment>): string {
94 if (comments.length === 0) {
95 return "none";
96 }
97​
98 return comments
99 .map((comment) =>
100 [
101 comment.id,
102 comment.sectionId,
103 comment.filePath,
104 comment.startIndex,
105 comment.endIndex,
106 comment.rangeLabel,
107 comment.text,
108 ].join("\u001f"),
109 )
110 .join("\u001e");
112​
113export function createNativeReviewDiffTheme(
114 scheme: TerminalAppearanceScheme,
115): NativeReviewDiffTheme {
116 const terminalTheme = getPierreTerminalTheme(scheme);
117 const [, terminalRed, , , terminalBlue] = terminalTheme.palette;
118​
119 if (scheme === "dark") {
120 return {
121 // Match the app surface (--color-sheet) so code views blend with the rest of
122 // the app instead of using a distinct code-editor background.
123 background: "#0e0e0e",
124 text: terminalTheme.foreground,
125 mutedText: terminalTheme.mutedForeground,
126 headerBackground: "#0e0e0e",
127 border: terminalTheme.border,
128 hunkBackground: "#071f28",
129 hunkText: terminalBlue ?? "#009fff",
130 addBackground: "#0d2f28",
131 deleteBackground: "#391415",
132 addBar: "#00cab1",
133 deleteBar: terminalRed ?? "#ff2e3f",
134 addText: "#5ECC71",
135 deleteText: "#FF6762",
136 };
137 }
138​
139 return {
140 // Match the app surface (--color-sheet) so code views blend with the rest of the
141 // app instead of using a distinct code-editor background.
142 background: "#f2f2f7",
143 text: "#070707",
144 mutedText: terminalTheme.mutedForeground,
145 headerBackground: "#f2f2f7",
146 border: terminalTheme.border,
147 hunkBackground: "#e0f2ff",
148 hunkText: terminalBlue ?? "#009fff",
149 addBackground: "#e5f8f5",
150 deleteBackground: "#ffe6e7",
151 addBar: "#00cab1",
152 deleteBar: terminalRed ?? "#ff2e3f",
153 addText: "#199F43",
154 deleteText: "#D52C36",
155 };
157​
158function mapChangeType(file: ReviewRenderableFile): NativeReviewDiffRow["changeType"] {
159 switch (file.changeType) {
160 case "change":
161 return "modified";
162 case "new":
163 case "deleted":
164 case "rename-pure":
165 case "rename-changed":
166 return file.changeType;
167 default:
168 return "modified";
169 }
171​
172function getLanguageForPath(
173 filePath: string,
174 languageHint: string | null,
175): NativeReviewDiffLanguage {
176 const hinted = languageHint?.toLowerCase();
177 if (hinted === "typescript" || hinted === "tsx" || hinted === "javascript" || hinted === "jsx") {
178 return hinted;
179 }
180 if (hinted === "json" || hinted === "yaml" || hinted === "bash" || hinted === "diff") {
181 return hinted;
182 }
183​
184 const normalizedPath = filePath.toLowerCase();
185 if (normalizedPath.endsWith(".tsx")) return "tsx";
186 if (normalizedPath.endsWith(".ts")) return "typescript";
187 if (normalizedPath.endsWith(".jsx")) return "jsx";
188 if (normalizedPath.endsWith(".js") || normalizedPath.endsWith(".cjs")) return "javascript";
189 if (normalizedPath.endsWith(".json") || normalizedPath.endsWith(".jsonc")) return "json";
190 if (normalizedPath.endsWith(".yml") || normalizedPath.endsWith(".yaml")) return "yaml";
191 if (
192 normalizedPath.endsWith(".sh") ||
193 normalizedPath.includes("/bin/") ||
194 normalizedPath.includes("shell")
195 ) {
196 return "bash";
197 }
198 return "diff";
200​
201function createNoticeRow(fileId: string, suffix: string, text: string): NativeReviewDiffRow {
202 return {
203 kind: "notice",
204 id: `${fileId}:notice:${suffix}`,
205 fileId,
206 text,
207 };
209​
210function noticeRowsForFile(file: ReviewRenderableFile): ReadonlyArray<NativeReviewDiffRow> {
211 if (file.rows.length > 0) {
212 return [];
213 }
214​
215 const previewState = getReviewFilePreviewState(file);
216 if (previewState.kind === "suppressed" && previewState.reason === "non-text") {
217 return [
218 createNoticeRow(file.id, "non-text", "Unsupported format. Diff contents are not available."),
219 ];
220 }
221​
222 if (file.changeType === "rename-pure") {
223 return [createNoticeRow(file.id, "rename", "This file was renamed without modifications.")];
224 }
225​
226 return [];
228​
229function trimWordDiffRanges(
230 content: string,
231 ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
232): NonNullable<NativeReviewDiffRow["wordDiffRanges"]> {
233 return pipe(
234 ranges,
235 Arr.flatMap((range) => {
236 let start = Math.max(0, range.start);
237 let end = Math.min(content.length, range.end);
238​
239 while (start < end && /\s/.test(content[start] ?? "")) {
240 start += 1;
241 }
242 while (end > start && /\s/.test(content[end - 1] ?? "")) {
243 end -= 1;
244 }
245​
246 return end > start ? [{ start, end }] : [];
247 }),
248 );
250​
251function nonWhitespaceLength(value: string) {
252 return value.replace(/\s/g, "").length;
254​
255function shouldUseWordDiffRanges(
256 content: string,
257 ranges: NonNullable<NativeReviewDiffRow["wordDiffRanges"]>,
258) {
259 if (ranges.length === 0 || ranges.length > NATIVE_REVIEW_MAX_WORD_DIFF_RANGE_COUNT) {
260 return false;
261 }
262​
263 const meaningfulLength = nonWhitespaceLength(content);
264 if (meaningfulLength === 0) {
265 return false;
266 }
267​
268 const highlightedLength = ranges.reduce(
269 (total, range) => total + nonWhitespaceLength(content.slice(range.start, range.end)),
270 0,
271 );
272 return highlightedLength / meaningfulLength <= NATIVE_REVIEW_MAX_WORD_DIFF_COVERAGE;
274​
275function addNativeWordDiffRanges(
276 rows: ReadonlyArray<NativeReviewDiffRow>,
277): ReadonlyArray<NativeReviewDiffRow> {
278 const nextRows = [...rows];
279 let index = 0;
280​
281 while (index < nextRows.length) {
282 const deletedRowIndexes: number[] = [];
283 const addedRowIndexes: number[] = [];
284 const fileId = nextRows[index]?.fileId;
285​
286 while (
287 nextRows[index]?.kind === "line" &&
288 nextRows[index]?.change === "delete" &&
289 nextRows[index]?.fileId === fileId
290 ) {
291 deletedRowIndexes.push(index);
292 index += 1;
293 }
294​
295 while (
296 nextRows[index]?.kind === "line" &&
297 nextRows[index]?.change === "add" &&
298 nextRows[index]?.fileId === fileId
299 ) {
300 addedRowIndexes.push(index);
301 index += 1;
302 }
303​
304 const pairedCount = Math.min(deletedRowIndexes.length, addedRowIndexes.length);
305 for (let pairIndex = 0; pairIndex < pairedCount; pairIndex += 1) {
306 const deletedRowIndex = deletedRowIndexes[pairIndex];
307 const addedRowIndex = addedRowIndexes[pairIndex];
308 const deletedRow = nextRows[deletedRowIndex];
309 const addedRow = nextRows[addedRowIndex];
310 if (!deletedRow?.content || !addedRow?.content) {
311 continue;
312 }
313​
314 const ranges = computeWordAltDiffRanges({
315 deletionLine: deletedRow.content,
316 additionLine: addedRow.content,
317 });
318 const deletionRanges = trimWordDiffRanges(deletedRow.content, ranges.deletion);
319 const additionRanges = trimWordDiffRanges(addedRow.content, ranges.addition);
320​
321 if (shouldUseWordDiffRanges(deletedRow.content, deletionRanges)) {
322 nextRows[deletedRowIndex] = { ...deletedRow, wordDiffRanges: deletionRanges };
323 }
324 if (shouldUseWordDiffRanges(addedRow.content, additionRanges)) {
325 nextRows[addedRowIndex] = { ...addedRow, wordDiffRanges: additionRanges };
326 }
327 }
328​
329 if (deletedRowIndexes.length === 0 && addedRowIndexes.length === 0) {
330 index += 1;
331 }
332 }
333​
334 return nextRows;
336​
337function mapLineRow(
338 file: ReviewRenderableFile,
339 row: ReviewRenderableLineRow,
340 rowIndex: number,
341): NativeReviewDiffRow {
342 return {
343 kind: "line",
344 id: `${file.id}:line:${rowIndex}:${row.id}`,
345 fileId: file.id,
346 content: row.content,
347 change: row.change,
348 oldLineNumber: row.oldLineNumber,
349 newLineNumber: row.newLineNumber,
350 };
352​
353function mapFileRows(
354 file: ReviewRenderableFile,
355 comments: ReadonlyArray<ReviewInlineComment>,
356 commentTargetsByRowId: Map<string, NativeReviewDiffCommentTarget>,
357 rowIdByCommentLineId: Map<string, string>,
358): ReadonlyArray<NativeReviewDiffRow> {
359 const rows: NativeReviewDiffRow[] = [
360 {
361 kind: "file",
362 id: `${file.id}:header`,
363 fileId: file.id,
364 filePath: file.path,
365 previousPath: file.previousPath,
366 changeType: mapChangeType(file),
367 additions: file.additions,
368 deletions: file.deletions,
369 },
370 ];
371​
372 const lineRows = file.rows.filter((row): row is ReviewRenderableLineRow => row.kind === "line");
373 const commentsByEndIndex = new Map<number, ReviewInlineComment[]>();
374 comments.forEach((comment) => {
375 if (comment.filePath !== file.path) {
376 return;
377 }
378 const endIndex = Math.min(comment.endIndex, lineRows.length - 1);
379 if (endIndex < 0) {
380 return;
381 }
382 const existing = commentsByEndIndex.get(endIndex);
383 if (existing) {
384 existing.push(comment);
385 return;
386 }
387 commentsByEndIndex.set(endIndex, [comment]);
388 });
389 let lineIndex = 0;
390 file.rows.forEach((row, rowIndex) => {
391 if (row.kind === "hunk") {
392 rows.push({
393 kind: "hunk",
394 id: `${file.id}:hunk:${rowIndex}:${row.id}`,
395 fileId: file.id,
396 text: row.context ? `${row.header} ${row.context}` : row.header,
397 });
398 return;
399 }
400​
401 const nativeRow = mapLineRow(file, row, rowIndex);
402 rows.push(nativeRow);
403 rowIdByCommentLineId.set(row.id, nativeRow.id);
404 commentTargetsByRowId.set(nativeRow.id, {
405 filePath: file.path,
406 lines: lineRows,
407 lineIndex,
408 });
409 const commentsForLine = commentsByEndIndex.get(lineIndex) ?? [];
410 for (const comment of commentsForLine) {
411 rows.push({
412 kind: "comment",
413 id: comment.id,
414 fileId: file.id,
415 filePath: file.path,
416 commentText: comment.text,
417 commentRangeLabel: comment.rangeLabel,
418 commentSectionTitle: comment.sectionTitle,
419 });
420 }
421 lineIndex += 1;
422 });
423​
424 rows.push(...noticeRowsForFile(file));
425 return rows;
427​
428export function buildNativeReviewDiffData(
429 input: BuildNativeReviewDiffDataInput,
430): NativeReviewDiffData;
431export function buildNativeReviewDiffData(parsedDiff: ReviewParsedDiff): NativeReviewDiffData;
432export function buildNativeReviewDiffData(
433 input: ReviewParsedDiff | BuildNativeReviewDiffDataInput,
434): NativeReviewDiffData {
435 const parsedDiff = "parsedDiff" in input ? input.parsedDiff : input;
436 const comments = "parsedDiff" in input ? (input.comments ?? []) : [];
437 if (parsedDiff.kind !== "files") {
438 return {
439 rows: [],
440 files: [],
441 commentTargetsByRowId: new Map(),
442 rowIdByCommentLineId: new Map(),
443 additions: 0,
444 deletions: 0,
445 };
446 }
447​
448 const files = parsedDiff.files.map<NativeReviewDiffFile>((file) => ({
449 id: file.id,
450 path: file.path,
451 language: getLanguageForPath(file.path, file.languageHint),
452 additions: file.additions,
453 deletions: file.deletions,
454 }));
455 const commentTargetsByRowId = new Map<string, NativeReviewDiffCommentTarget>();
456 const rowIdByCommentLineId = new Map<string, string>();
457 const rows = addNativeWordDiffRanges(
458 Arr.flatMap(parsedDiff.files, (file) =>
459 mapFileRows(file, comments, commentTargetsByRowId, rowIdByCommentLineId),
460 ),
461 );
462​
463 return {
464 rows,
465 files,
466 commentTargetsByRowId,
467 rowIdByCommentLineId,
468 additions: parsedDiff.additions,
469 deletions: parsedDiff.deletions,
470 };
472​
473/**
474 * Reuses the expensive flattened native row model across React development
475 * render probes and unrelated draft updates. Only the latest comment version
476 * is retained for each parsed diff so editing a comment cannot grow the cache.
477 */
478export function getCachedNativeReviewDiffData(
479 input: BuildNativeReviewDiffDataInput,
480): NativeReviewDiffData {
481 const comments = input.comments ?? [];
482 const commentsKey = buildReviewCommentsCacheKey(comments);
483 const cached = nativeReviewDiffDataCache.get(input.parsedDiff);
484 if (cached?.commentsKey === commentsKey) {
485 return cached.data;
486 }
487​
488 const data = buildNativeReviewDiffData({
489 parsedDiff: input.parsedDiff,
490 comments,
491 });
492 nativeReviewDiffDataCache.set(input.parsedDiff, { commentsKey, data });
493 return data;