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 { READABLE_LIGHT_THEME_NAME } from "./readableSyntaxTheme";
5
6// Light mode uses a darker pierre-light so syntax stays readable on every code surface.
7export const DIFF_THEME_NAMES = {
8 light: READABLE_LIGHT_THEME_NAME,
9 dark: "pierre-dark",
10} as const;
11
12export type DiffThemeName = (typeof DIFF_THEME_NAMES)[keyof typeof DIFF_THEME_NAMES];
13
14export function resolveDiffThemeName(theme: "light" | "dark"): DiffThemeName {
15 return DIFF_THEME_NAMES[theme];
16}
17
18const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
19const FNV_PRIME_32 = 0x01000193;
20const SECONDARY_HASH_SEED = 0x9e3779b9;
21const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
22
23export function fnv1a32(
24 input: string,
25 seed = FNV_OFFSET_BASIS_32,
26 multiplier = FNV_PRIME_32,
27): number {
28 let hash = seed >>> 0;
29 for (let index = 0; index < input.length; index += 1) {
30 hash ^= input.charCodeAt(index);
31 hash = Math.imul(hash, multiplier) >>> 0;
32 }
33 return hash >>> 0;
34}
35
36function buildPatchCacheKey(patch: string, scope = "diff-panel"): string {
37 const normalizedPatch = patch.trim();
38 const primary = fnv1a32(normalizedPatch, FNV_OFFSET_BASIS_32, FNV_PRIME_32).toString(36);
39 const secondary = fnv1a32(
40 normalizedPatch,
41 SECONDARY_HASH_SEED,
42 SECONDARY_HASH_MULTIPLIER,
43 ).toString(36);
44 return `${scope}:${normalizedPatch.length}:${primary}:${secondary}`;
45}
46
47export type RenderablePatch =
48 | {
49 kind: "files";
50 files: FileDiffMetadata[];
51 sourceFiles: FileDiffMetadata[];
52 }
53 | {
54 kind: "raw";
55 text: string;
56 reason: string;
57 };
58
59export interface DiffLineStat {
60 additions: number;
61 deletions: number;
62}
63
64export function getDiffLineStat(files: ReadonlyArray<FileDiffMetadata>): DiffLineStat {
65 return files.reduce<DiffLineStat>(
66 (total, file) => {
67 for (const hunk of file.hunks) {
68 total.additions += hunk.additionLines;
69 total.deletions += hunk.deletionLines;
70 }
71
72 return total;
73 },
74 { additions: 0, deletions: 0 },
75 );
76}
77
78interface RenderablePatchOptions {
79 ignoreWhitespace?: boolean;
80 /** Compact Pierre source offsets for partial-patch rows; retain collapsedBefore for separators. */
81 compactPartialHunkOffsets?: boolean;
82}
83
84function hideWhitespaceChanges(file: FileDiffMetadata): FileDiffMetadata {
85 let splitDelta = 0;
86 let unifiedDelta = 0;
87 const hunks = file.hunks.map((hunk) => {
88 const oldContents = file.deletionLines
89 .slice(hunk.deletionLineIndex, hunk.deletionLineIndex + hunk.deletionCount)
90 .map((line) => `${line.replace(/\s/g, "")}\n`)
91 .join("");
92 const newContents = file.additionLines
93 .slice(hunk.additionLineIndex, hunk.additionLineIndex + hunk.additionCount)
94 .map((line) => `${line.replace(/\s/g, "")}\n`)
95 .join("");
96 const filtered = parseDiffFromFile(
97 { name: file.name, contents: oldContents },
98 { name: file.name, contents: newContents },
99 { context: Infinity },
100 ).hunks[0];
101 const next = {
102 ...hunk,
103 additionLines: filtered?.additionLines ?? 0,
104 deletionLines: filtered?.deletionLines ?? 0,
105 hunkContent: filtered
106 ? filtered.hunkContent.map((content) => ({
107 ...content,
108 additionLineIndex: content.additionLineIndex + hunk.additionLineIndex,
109 deletionLineIndex: content.deletionLineIndex + hunk.deletionLineIndex,
110 }))
111 : [
112 {
113 type: "context" as const,
114 lines: hunk.additionCount,
115 additionLineIndex: hunk.additionLineIndex,
116 deletionLineIndex: hunk.deletionLineIndex,
117 },
118 ],
119 splitLineStart: hunk.splitLineStart + splitDelta,
120 unifiedLineStart: hunk.unifiedLineStart + unifiedDelta,
121 splitLineCount: filtered?.splitLineCount ?? hunk.additionCount,
122 unifiedLineCount: filtered?.unifiedLineCount ?? hunk.additionCount,
123 };
124 splitDelta += next.splitLineCount - hunk.splitLineCount;
125 unifiedDelta += next.unifiedLineCount - hunk.unifiedLineCount;
126 return next;
127 });
128 return {
129 ...file,
130 hunks,
131 splitLineCount: file.splitLineCount + splitDelta,
132 unifiedLineCount: file.unifiedLineCount + unifiedDelta,
133 ...(file.cacheKey ? { cacheKey: `${file.cacheKey}:ignore-whitespace` } : {}),
134 };
135}
136
137function compactPartialHunkOffsets(file: FileDiffMetadata): FileDiffMetadata {
138 if (!file.isPartial) return file;
139
140 let splitLineStart = 0;
141 let unifiedLineStart = 0;
142 const hunks = file.hunks.map((hunk) => {
143 const compactHunk = {
144 ...hunk,
145 splitLineStart,
146 unifiedLineStart,
147 };
148 splitLineStart += hunk.splitLineCount;
149 unifiedLineStart += hunk.unifiedLineCount;
150 return compactHunk;
151 });
152
153 return {
154 ...file,
155 hunks,
156 splitLineCount: splitLineStart,
157 unifiedLineCount: unifiedLineStart,
158 ...(file.cacheKey ? { cacheKey: `${file.cacheKey}:compact-partial` } : {}),
159 };
160}
161
162export function getRenderablePatch(
163 patch: string | undefined,
164 cacheScope = "diff-panel",
165 options: RenderablePatchOptions = {},
166): RenderablePatch | null {
167 if (!patch) return null;
168 const normalizedPatch = patch.trim();
169 if (normalizedPatch.length === 0) return null;
170
171 try {
172 const parsedPatches = parsePatchFiles(
173 normalizedPatch,
174 buildPatchCacheKey(normalizedPatch, cacheScope),
175 );
176 const sourceFiles = parsedPatches.flatMap((parsedPatch) => parsedPatch.files);
177 const files = sourceFiles.map((file) => {
178 const filtered = options.ignoreWhitespace ? hideWhitespaceChanges(file) : file;
179 return options.compactPartialHunkOffsets ? compactPartialHunkOffsets(filtered) : filtered;
180 });
181 if (files.length > 0) {
182 return { kind: "files", files, sourceFiles };
183 }
184
185 return {
186 kind: "raw",
187 text: normalizedPatch,
188 reason: "Unsupported diff format. Showing raw patch.",
189 };
190 } catch {
191 return {
192 kind: "raw",
193 text: normalizedPatch,
194 reason: "Failed to parse patch. Showing raw patch.",
195 };
196 }
197}
198
199/** Uses the parser-decoded filename, including Git's quoted and escaped names. */
200export function resolveFileDiffPath(fileDiff: FileDiffMetadata): string {
201 return fileDiff.name ?? fileDiff.prevName ?? "";
202}
203
204export function resolveFileDiffPreviousPath(fileDiff: FileDiffMetadata): string {
205 return fileDiff.prevName ?? fileDiff.name ?? "";
206}
207
208/** Includes change type to distinguish deletion/addition pairs for file-to-symlink changes. */
209export function buildFileDiffIdentityKey(fileDiff: FileDiffMetadata): string {
210 return `${resolveFileDiffPreviousPath(fileDiff)}\u0000${resolveFileDiffPath(fileDiff)}\u0000${fileDiff.type}`;
211}
212
213export function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
214 const cacheKey = fileDiff.cacheKey;
215 if (!cacheKey) return `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
216
217 return cacheKey.endsWith(":hydrated") ? cacheKey.slice(0, -":hydrated".length) : cacheKey;
218}
219
220function hashFileDiffPart(hash: number, value: string | number | boolean | undefined): number {
221 const serialized = value === undefined ? "undefined" : String(value);
222 const withLength = fnv1a32(`${typeof value}:${serialized.length}:`, hash);
223 return fnv1a32(serialized, withLength);
224}
225
226// Pierre's whole-patch cache key would repaint every file when one changes.
227export function buildFileDiffContentVersion(fileDiff: FileDiffMetadata): number {
228 let hash = FNV_OFFSET_BASIS_32;
229 const append = (value: string | number | boolean | undefined) => {
230 hash = hashFileDiffPart(hash, value);
231 };
232
233 append(fileDiff.name);
234 append(fileDiff.prevName);
235 append(fileDiff.lang);
236 append(fileDiff.newObjectId);
237 append(fileDiff.prevObjectId);
238 append(fileDiff.mode);
239 append(fileDiff.prevMode);
240 append(fileDiff.type);
241 append(fileDiff.isPartial);
242 append(fileDiff.splitLineCount);
243 append(fileDiff.unifiedLineCount);
244
245 for (const line of fileDiff.additionLines) append(line);
246 for (const line of fileDiff.deletionLines) append(line);
247 for (const hunk of fileDiff.hunks) {
248 append(hunk.collapsedBefore);
249 append(hunk.additionStart);
250 append(hunk.additionCount);
251 append(hunk.additionLines);
252 append(hunk.additionLineIndex);
253 append(hunk.deletionStart);
254 append(hunk.deletionCount);
255 append(hunk.deletionLines);
256 append(hunk.deletionLineIndex);
257 append(hunk.hunkContext);
258 append(hunk.hunkSpecs);
259 append(hunk.splitLineStart);
260 append(hunk.splitLineCount);
261 append(hunk.unifiedLineStart);
262 append(hunk.unifiedLineCount);
263 append(hunk.noEOFCRAdditions);
264 append(hunk.noEOFCRDeletions);
265 for (const content of hunk.hunkContent) {
266 append(content.type);
267 append(content.additionLineIndex);
268 append(content.deletionLineIndex);
269 append(content.type === "change" ? content.additions : content.lines);
270 append(content.type === "change" ? content.deletions : undefined);
271 }
272 }
273
274 return hash;
275}
276
277export const DIFF_SURFACE_THEME_UNSAFE_CSS = `
278[data-diffs-header],
279[data-diff],
280[data-file],
281[data-error-wrapper],
282[data-virtualizer-buffer] {
283 --diffs-header-font-family: var(--font-sans) !important;
284 --diffs-font-family: var(--font-mono) !important;
285 --diffs-bg: var(--code-background) !important;
286 --diffs-light-bg: var(--code-background) !important;
287 --diffs-dark-bg: var(--code-background) !important;
288 --diffs-token-light-bg: transparent;
289 --diffs-token-dark-bg: transparent;
290
291 /* Gutter, context, and row tints all derive from the code surface the diff
292 body sits on. Mixing from the canvas leaves the gutter looking unthemed
293 when a palette separates the two. */
294 --diffs-bg-context-override: color-mix(in srgb, var(--code-background) 97%, var(--code-foreground));
295 --diffs-bg-hover-override: color-mix(in srgb, var(--code-background) 94%, var(--code-foreground));
296 --diffs-bg-separator-override: color-mix(
297 in srgb,
298 var(--code-background) 95%,
299 var(--code-foreground)
300 );
301 --diffs-bg-buffer-override: color-mix(in srgb, var(--code-background) 90%, var(--code-foreground));
302
303 --diffs-bg-addition-override: light-dark(
304 color-mix(in srgb, var(--code-background) 50%, var(--diff-addition)),
305 color-mix(in srgb, var(--code-background) 70%, var(--diff-addition))
306 );
307 --diffs-bg-addition-number-override: light-dark(
308 color-mix(in srgb, var(--code-background) 35%, var(--diff-addition)),
309 color-mix(in srgb, var(--code-background) 60%, var(--diff-addition))
310 );
311 --diffs-bg-addition-hover-override: color-mix(in srgb, var(--code-background) 85%, var(--diff-addition));
312 --diffs-bg-addition-emphasis-override: color-mix(
313 in srgb,
314 var(--code-background) 80%,
315 var(--diff-addition)
316 );
317
318 --diffs-bg-deletion-override: light-dark(
319 color-mix(in srgb, var(--code-background) 50%, var(--diff-deletion)),
320 color-mix(in srgb, var(--code-background) 70%, var(--diff-deletion))
321 );
322 --diffs-bg-deletion-number-override: light-dark(
323 color-mix(in srgb, var(--code-background) 35%, var(--diff-deletion)),
324 color-mix(in srgb, var(--code-background) 60%, var(--diff-deletion))
325 );
326 --diffs-bg-deletion-hover-override: color-mix(
327 in srgb,
328 var(--code-background) 85%,
329 var(--diff-deletion)
330 );
331 --diffs-bg-deletion-emphasis-override: color-mix(
332 in srgb,
333 var(--code-background) 80%,
334 var(--diff-deletion)
335 );
336
337 background-color: var(--diffs-bg) !important;
338 color: var(--code-foreground) !important;
339}
340
341/* The library's change-icon colors are tuned for dark canvases; light mode takes the app's darker tokens. */
342[data-change-icon="new"] {
343 color: var(
344 --diff-added-icon,
345 light-dark(var(--diff-addition-foreground), var(--diffs-addition-base))
346 ) !important;
347}
348[data-change-icon="deleted"] {
349 color: light-dark(var(--diff-deletion-foreground), var(--diffs-deletion-base)) !important;
350}
351/* The page sets --diff-modified-icon to a muted T3 blue, so the common case stays quiet. */
352[data-change-icon="change"],
353[data-change-icon="rename-pure"],
354[data-change-icon="rename-changed"] {
355 color: var(
356 --diff-modified-icon,
357 light-dark(var(--info-foreground), var(--diffs-modified-base))
358 ) !important;
359}
360`;