Open History to see the last commit
1import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
2import { parseDiffFromFile } from "@pierre/diffs";
3import type { FileDiffMetadata } from "@pierre/diffs/types";
4import { unquoteGitPatchPath } from "@t3tools/shared/gitPatchPath";
5
6const DIFF_THEME_NAMES = {
7 light: "pierre-light",
8 dark: "pierre-dark",
9} as const;
10
11export type DiffThemeName = (typeof DIFF_THEME_NAMES)[keyof typeof DIFF_THEME_NAMES];
12
13export function resolveDiffThemeName(theme: "light" | "dark"): DiffThemeName {
14 return theme === "dark" ? DIFF_THEME_NAMES.dark : DIFF_THEME_NAMES.light;
15}
16
17const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
18const FNV_PRIME_32 = 0x01000193;
19const SECONDARY_HASH_SEED = 0x9e3779b9;
20const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
21
22export function fnv1a32(
23 input: string,
24 seed = FNV_OFFSET_BASIS_32,
25 multiplier = FNV_PRIME_32,
26): number {
27 let hash = seed >>> 0;
28 for (let index = 0; index < input.length; index += 1) {
29 hash ^= input.charCodeAt(index);
30 hash = Math.imul(hash, multiplier) >>> 0;
31 }
32 return hash >>> 0;
33}
34
35export function buildPatchCacheKey(patch: string, scope = "diff-panel"): string {
36 const normalizedPatch = patch.trim();
37 const primary = fnv1a32(normalizedPatch, FNV_OFFSET_BASIS_32, FNV_PRIME_32).toString(36);
38 const secondary = fnv1a32(
39 normalizedPatch,
40 SECONDARY_HASH_SEED,
41 SECONDARY_HASH_MULTIPLIER,
42 ).toString(36);
43 return `${scope}:${normalizedPatch.length}:${primary}:${secondary}`;
44}
45
46export type RenderablePatch =
47 | {
48 kind: "files";
49 files: FileDiffMetadata[];
50 sourceFiles: FileDiffMetadata[];
51 }
52 | {
53 kind: "raw";
54 text: string;
55 reason: string;
56 };
57
58export interface DiffLineStat {
59 additions: number;
60 deletions: number;
61}
62
63export function getDiffLineStat(files: ReadonlyArray<FileDiffMetadata>): DiffLineStat {
64 return files.reduce<DiffLineStat>(
65 (total, file) => {
66 for (const hunk of file.hunks) {
67 total.additions += hunk.additionLines;
68 total.deletions += hunk.deletionLines;
69 }
70
71 return total;
72 },
73 { additions: 0, deletions: 0 },
74 );
75}
76
77interface RenderablePatchOptions {
78 ignoreWhitespace?: boolean;
79 /**
80 * Pierre's partial-patch parser keeps hunk render starts in source-file
81 * coordinates. Its virtualizer iterates partial patches as compact rows, so
82 * review diffs need compact render starts while retaining collapsedBefore
83 * for the "N unmodified lines" separator.
84 */
85 compactPartialHunkOffsets?: boolean;
86}
87
88function hideWhitespaceChanges(file: FileDiffMetadata): FileDiffMetadata {
89 let splitDelta = 0;
90 let unifiedDelta = 0;
91 const hunks = file.hunks.map((hunk) => {
92 const oldContents = file.deletionLines
93 .slice(hunk.deletionLineIndex, hunk.deletionLineIndex + hunk.deletionCount)
94 .map((line) => `${line.replace(/\s/g, "")}\n`)
95 .join("");
96 const newContents = file.additionLines
97 .slice(hunk.additionLineIndex, hunk.additionLineIndex + hunk.additionCount)
98 .map((line) => `${line.replace(/\s/g, "")}\n`)
99 .join("");
100 const filtered = parseDiffFromFile(
101 { name: file.name, contents: oldContents },
102 { name: file.name, contents: newContents },
103 { context: Infinity },
104 ).hunks[0];
105 const next = {
106 ...hunk,
107 additionLines: filtered?.additionLines ?? 0,
108 deletionLines: filtered?.deletionLines ?? 0,
109 hunkContent: filtered
110 ? filtered.hunkContent.map((content) => ({
111 ...content,
112 additionLineIndex: content.additionLineIndex + hunk.additionLineIndex,
113 deletionLineIndex: content.deletionLineIndex + hunk.deletionLineIndex,
114 }))
115 : [
116 {
117 type: "context" as const,
118 lines: hunk.additionCount,
119 additionLineIndex: hunk.additionLineIndex,
120 deletionLineIndex: hunk.deletionLineIndex,
121 },
122 ],
123 splitLineStart: hunk.splitLineStart + splitDelta,
124 unifiedLineStart: hunk.unifiedLineStart + unifiedDelta,
125 splitLineCount: filtered?.splitLineCount ?? hunk.additionCount,
126 unifiedLineCount: filtered?.unifiedLineCount ?? hunk.additionCount,
127 };
128 splitDelta += next.splitLineCount - hunk.splitLineCount;
129 unifiedDelta += next.unifiedLineCount - hunk.unifiedLineCount;
130 return next;
131 });
132 return {
133 ...file,
134 hunks,
135 splitLineCount: file.splitLineCount + splitDelta,
136 unifiedLineCount: file.unifiedLineCount + unifiedDelta,
137 ...(file.cacheKey ? { cacheKey: `${file.cacheKey}:ignore-whitespace` } : {}),
138 };
139}
140
141function compactPartialHunkOffsets(file: FileDiffMetadata): FileDiffMetadata {
142 if (!file.isPartial) return file;
143
144 let splitLineStart = 0;
145 let unifiedLineStart = 0;
146 const hunks = file.hunks.map((hunk) => {
147 const compactHunk = {
148 ...hunk,
149 splitLineStart,
150 unifiedLineStart,
151 };
152 splitLineStart += hunk.splitLineCount;
153 unifiedLineStart += hunk.unifiedLineCount;
154 return compactHunk;
155 });
156
157 return {
158 ...file,
159 hunks,
160 splitLineCount: splitLineStart,
161 unifiedLineCount: unifiedLineStart,
162 ...(file.cacheKey ? { cacheKey: `${file.cacheKey}:compact-partial` } : {}),
163 };
164}
165
166export function getRenderablePatch(
167 patch: string | undefined,
168 cacheScope = "diff-panel",
169 options: RenderablePatchOptions = {},
170): RenderablePatch | null {
171 if (!patch) return null;
172 const normalizedPatch = patch.trim();
173 if (normalizedPatch.length === 0) return null;
174
175 try {
176 const parsedPatches = parsePatchFiles(
177 normalizedPatch,
178 buildPatchCacheKey(normalizedPatch, cacheScope),
179 );
180 const sourceFiles = parsedPatches.flatMap((parsedPatch) => parsedPatch.files);
181 const files = sourceFiles.map((file) => {
182 const filtered = options.ignoreWhitespace ? hideWhitespaceChanges(file) : file;
183 return options.compactPartialHunkOffsets ? compactPartialHunkOffsets(filtered) : filtered;
184 });
185 if (files.length > 0) {
186 return { kind: "files", files, sourceFiles };
187 }
188
189 return {
190 kind: "raw",
191 text: normalizedPatch,
192 reason: "Unsupported diff format. Showing raw patch.",
193 };
194 } catch {
195 return {
196 kind: "raw",
197 text: normalizedPatch,
198 reason: "Failed to parse patch. Showing raw patch.",
199 };
200 }
201}
202
203/**
204 * What the patch called the file, as the file's own name. Git writes a name holding a tab, a
205 * newline, a quote or a backslash quoted and escaped, and the parser hands one of those back still
206 * escaped. A viewed mark, a review comment and a file's contents are all asked for by this path,
207 * and the host knows the file only under the name it really has.
208 */
209function fileDiffPath(raw: string): string {
210 return unquoteGitPatchPath(raw);
211}
212
213export function resolveFileDiffPath(fileDiff: FileDiffMetadata): string {
214 return fileDiffPath(fileDiff.name ?? fileDiff.prevName ?? "");
215}
216
217/**
218 * What the file was called before the change. Only a rename makes it differ from the current
219 * path, and the hosts that resolve a diff position against both sides need both names.
220 */
221export function resolveFileDiffPreviousPath(fileDiff: FileDiffMetadata): string {
222 return fileDiffPath(fileDiff.prevName ?? fileDiff.name ?? "");
223}
224
225/**
226 * Stable across re-renders of the same file, distinct for every block in a
227 * patch. A type change (regular file to symlink) arrives as a deletion and an
228 * addition of the same path, so the change type is part of the identity.
229 */
230export function buildFileDiffIdentityKey(fileDiff: FileDiffMetadata): string {
231 return `${resolveFileDiffPreviousPath(fileDiff)}\u0000${resolveFileDiffPath(fileDiff)}\u0000${fileDiff.type}`;
232}
233
234export function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
235 const cacheKey = fileDiff.cacheKey;
236 if (!cacheKey) return `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
237
238 return cacheKey.endsWith(":hydrated") ? cacheKey.slice(0, -":hydrated".length) : cacheKey;
239}
240
241function hashFileDiffPart(hash: number, value: string | number | boolean | undefined): number {
242 const serialized = value === undefined ? "undefined" : String(value);
243 const withLength = fnv1a32(`${typeof value}:${serialized.length}:`, hash);
244 return fnv1a32(serialized, withLength);
245}
246
247/**
248 * Content-only version for CodeView reconciliation. Pierre's cache key includes
249 * the whole patch, so using it here would repaint every file when one changes.
250 */
251export function buildFileDiffContentVersion(fileDiff: FileDiffMetadata): number {
252 let hash = FNV_OFFSET_BASIS_32;
253 const append = (value: string | number | boolean | undefined) => {
254 hash = hashFileDiffPart(hash, value);
255 };
256
257 append(fileDiff.name);
258 append(fileDiff.prevName);
259 append(fileDiff.lang);
260 append(fileDiff.newObjectId);
261 append(fileDiff.prevObjectId);
262 append(fileDiff.mode);
263 append(fileDiff.prevMode);
264 append(fileDiff.type);
265 append(fileDiff.isPartial);
266 append(fileDiff.splitLineCount);
267 append(fileDiff.unifiedLineCount);
268
269 for (const line of fileDiff.additionLines) append(line);
270 for (const line of fileDiff.deletionLines) append(line);
271 for (const hunk of fileDiff.hunks) {
272 append(hunk.collapsedBefore);
273 append(hunk.additionStart);
274 append(hunk.additionCount);
275 append(hunk.additionLines);
276 append(hunk.additionLineIndex);
277 append(hunk.deletionStart);
278 append(hunk.deletionCount);
279 append(hunk.deletionLines);
280 append(hunk.deletionLineIndex);
281 append(hunk.hunkContext);
282 append(hunk.hunkSpecs);
283 append(hunk.splitLineStart);
284 append(hunk.splitLineCount);
285 append(hunk.unifiedLineStart);
286 append(hunk.unifiedLineCount);
287 append(hunk.noEOFCRAdditions);
288 append(hunk.noEOFCRDeletions);
289 for (const content of hunk.hunkContent) {
290 append(content.type);
291 append(content.additionLineIndex);
292 append(content.deletionLineIndex);
293 append(content.type === "change" ? content.additions : content.lines);
294 append(content.type === "change" ? content.deletions : undefined);
295 }
296 }
297
298 return hash;
299}
300
301export function getDiffCollapseIconClassName(fileDiff: FileDiffMetadata): string {
302 switch (fileDiff.type) {
303 case "new":
304 return "text-[var(--diffs-addition-base)]";
305 case "deleted":
306 return "text-[var(--diffs-deletion-base)]";
307 case "change":
308 case "rename-pure":
309 case "rename-changed":
310 return "text-[var(--diffs-modified-base)]";
311 default:
312 return "text-muted-foreground/80";
313 }
314}
315
316/**
317 * Maps every diff/file surface the @pierre/diffs renderer paints onto the
318 * app's code tokens, so themed palettes reach the code body, gutter, and
319 * row tints instead of the renderer's bundled colors. Shared by the diff
320 * panel and the file preview.
321 */
322export const DIFF_SURFACE_THEME_UNSAFE_CSS = `
323[data-diffs-header],
324[data-diff],
325[data-file],
326[data-error-wrapper],
327[data-virtualizer-buffer] {
328 --diffs-header-font-family: var(--font-sans) !important;
329 --diffs-font-family: var(--font-mono) !important;
330 --diffs-bg: var(--code-background) !important;
331 --diffs-light-bg: var(--code-background) !important;
332 --diffs-dark-bg: var(--code-background) !important;
333 --diffs-token-light-bg: transparent;
334 --diffs-token-dark-bg: transparent;
335
336 /* Gutter, context, and row tints all derive from the code surface the diff
337 body sits on — mixing from the canvas leaves the gutter looking unthemed
338 when a palette separates the two. */
339 --diffs-bg-context-override: color-mix(in srgb, var(--code-background) 97%, var(--code-foreground));
340 --diffs-bg-hover-override: color-mix(in srgb, var(--code-background) 94%, var(--code-foreground));
341 --diffs-bg-separator-override: color-mix(
342 in srgb,
343 var(--code-background) 95%,
344 var(--code-foreground)
345 );
346 --diffs-bg-buffer-override: color-mix(in srgb, var(--code-background) 90%, var(--code-foreground));
347
348 --diffs-bg-addition-override: light-dark(
349 color-mix(in srgb, var(--code-background) 50%, var(--diff-addition)),
350 color-mix(in srgb, var(--code-background) 70%, var(--diff-addition))
351 );
352 --diffs-bg-addition-number-override: light-dark(
353 color-mix(in srgb, var(--code-background) 35%, var(--diff-addition)),
354 color-mix(in srgb, var(--code-background) 60%, var(--diff-addition))
355 );
356 --diffs-bg-addition-hover-override: color-mix(in srgb, var(--code-background) 85%, var(--diff-addition));
357 --diffs-bg-addition-emphasis-override: color-mix(
358 in srgb,
359 var(--code-background) 80%,
360 var(--diff-addition)
361 );
362
363 --diffs-bg-deletion-override: light-dark(
364 color-mix(in srgb, var(--code-background) 50%, var(--diff-deletion)),
365 color-mix(in srgb, var(--code-background) 70%, var(--diff-deletion))
366 );
367 --diffs-bg-deletion-number-override: light-dark(
368 color-mix(in srgb, var(--code-background) 35%, var(--diff-deletion)),
369 color-mix(in srgb, var(--code-background) 60%, var(--diff-deletion))
370 );
371 --diffs-bg-deletion-hover-override: color-mix(
372 in srgb,
373 var(--code-background) 85%,
374 var(--diff-deletion)
375 );
376 --diffs-bg-deletion-emphasis-override: color-mix(
377 in srgb,
378 var(--code-background) 80%,
379 var(--diff-deletion)
380 );
381
382 background-color: var(--diffs-bg) !important;
383 color: var(--code-foreground) !important;
384}
385`;