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

nativeReviewDiffAdapter.ts

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