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