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