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
6export const DIFF_THEME_NAMES = {
7 light: "pierre-light",
8 dark: "pierre-dark",
9 readableLight: READABLE_LIGHT_THEME_NAME,
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 if (theme === "dark") return DIFF_THEME_NAMES.dark;
16 // The New design (data-redesign on <html>) keeps light syntax readable on every code surface.
17 return typeof document !== "undefined" && document.documentElement.hasAttribute("data-redesign")
18 ? DIFF_THEME_NAMES.readableLight
19 : DIFF_THEME_NAMES.light;
20}
21
22const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
23const FNV_PRIME_32 = 0x01000193;
24const SECONDARY_HASH_SEED = 0x9e3779b9;
25const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
26
27export function fnv1a32(
28 input: string,
29 seed = FNV_OFFSET_BASIS_32,
30 multiplier = FNV_PRIME_32,
31): number {
32 let hash = seed >>> 0;
33 for (let index = 0; index < input.length; index += 1) {
34 hash ^= input.charCodeAt(index);
35 hash = Math.imul(hash, multiplier) >>> 0;
36 }
37 return hash >>> 0;
38}
39
40function buildPatchCacheKey(patch: string, scope = "diff-panel"): string {
41 const normalizedPatch = patch.trim();
42 const primary = fnv1a32(normalizedPatch, FNV_OFFSET_BASIS_32, FNV_PRIME_32).toString(36);
43 const secondary = fnv1a32(
44 normalizedPatch,
45 SECONDARY_HASH_SEED,
46 SECONDARY_HASH_MULTIPLIER,
47 ).toString(36);
48 return `${scope}:${normalizedPatch.length}:${primary}:${secondary}`;
49}
50
51export type RenderablePatch =
52 | {
53 kind: "files";
54 files: FileDiffMetadata[];
55 sourceFiles: FileDiffMetadata[];
56 }
57 | {
58 kind: "raw";
59 text: string;
60 reason: string;
61 };
62
63export interface DiffLineStat {
64 additions: number;
65 deletions: number;
66}
67
68export function getDiffLineStat(files: ReadonlyArray<FileDiffMetadata>): DiffLineStat {
69 return files.reduce<DiffLineStat>(
70 (total, file) => {
71 for (const hunk of file.hunks) {
72 total.additions += hunk.additionLines;
73 total.deletions += hunk.deletionLines;
74 }
75
76 return total;
77 },
78 { additions: 0, deletions: 0 },
79 );
80}
81
82interface RenderablePatchOptions {
83 ignoreWhitespace?: boolean;
84 /** Compact Pierre source offsets for partial-patch rows; retain collapsedBefore for separators. */
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/** Uses the parser-decoded filename, including Git's quoted and escaped names. */
204export function resolveFileDiffPath(fileDiff: FileDiffMetadata): string {
205 return fileDiff.name ?? fileDiff.prevName ?? "";
206}
207
208export function resolveFileDiffPreviousPath(fileDiff: FileDiffMetadata): string {
209 return fileDiff.prevName ?? fileDiff.name ?? "";
210}
211
212/** Includes change type to distinguish deletion/addition pairs for file-to-symlink changes. */
213export function buildFileDiffIdentityKey(fileDiff: FileDiffMetadata): string {
214 return `${resolveFileDiffPreviousPath(fileDiff)}\u0000${resolveFileDiffPath(fileDiff)}\u0000${fileDiff.type}`;
215}
216
217export function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
218 const cacheKey = fileDiff.cacheKey;
219 if (!cacheKey) return `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
220
221 return cacheKey.endsWith(":hydrated") ? cacheKey.slice(0, -":hydrated".length) : cacheKey;
222}
223
224function hashFileDiffPart(hash: number, value: string | number | boolean | undefined): number {
225 const serialized = value === undefined ? "undefined" : String(value);
226 const withLength = fnv1a32(`${typeof value}:${serialized.length}:`, hash);
227 return fnv1a32(serialized, withLength);
228}
229
230// Pierre's whole-patch cache key would repaint every file when one changes.
231export function buildFileDiffContentVersion(fileDiff: FileDiffMetadata): number {
232 let hash = FNV_OFFSET_BASIS_32;
233 const append = (value: string | number | boolean | undefined) => {
234 hash = hashFileDiffPart(hash, value);
235 };
236
237 append(fileDiff.name);
238 append(fileDiff.prevName);
239 append(fileDiff.lang);
240 append(fileDiff.newObjectId);
241 append(fileDiff.prevObjectId);
242 append(fileDiff.mode);
243 append(fileDiff.prevMode);
244 append(fileDiff.type);
245 append(fileDiff.isPartial);
246 append(fileDiff.splitLineCount);
247 append(fileDiff.unifiedLineCount);
248
249 for (const line of fileDiff.additionLines) append(line);
250 for (const line of fileDiff.deletionLines) append(line);
251 for (const hunk of fileDiff.hunks) {
252 append(hunk.collapsedBefore);
253 append(hunk.additionStart);
254 append(hunk.additionCount);
255 append(hunk.additionLines);
256 append(hunk.additionLineIndex);
257 append(hunk.deletionStart);
258 append(hunk.deletionCount);
259 append(hunk.deletionLines);
260 append(hunk.deletionLineIndex);
261 append(hunk.hunkContext);
262 append(hunk.hunkSpecs);
263 append(hunk.splitLineStart);
264 append(hunk.splitLineCount);
265 append(hunk.unifiedLineStart);
266 append(hunk.unifiedLineCount);
267 append(hunk.noEOFCRAdditions);
268 append(hunk.noEOFCRDeletions);
269 for (const content of hunk.hunkContent) {
270 append(content.type);
271 append(content.additionLineIndex);
272 append(content.deletionLineIndex);
273 append(content.type === "change" ? content.additions : content.lines);
274 append(content.type === "change" ? content.deletions : undefined);
275 }
276 }
277
278 return hash;
279}
280
281export function getDiffCollapseIconClassName(fileDiff: FileDiffMetadata): string {
282 switch (fileDiff.type) {
283 case "new":
284 return "text-[var(--diffs-addition-base)] redesign:text-muted-foreground/80";
285 case "deleted":
286 return "text-[var(--diffs-deletion-base)] redesign:text-muted-foreground/80";
287 case "change":
288 case "rename-pure":
289 case "rename-changed":
290 return "text-[var(--diffs-modified-base)] redesign:text-muted-foreground/80";
291 default:
292 return "text-muted-foreground/80";
293 }
294}
295
296export const DIFF_SURFACE_THEME_UNSAFE_CSS = `
297[data-diffs-header],
298[data-diff],
299[data-file],
300[data-error-wrapper],
301[data-virtualizer-buffer] {
302 --diffs-header-font-family: var(--font-sans) !important;
303 --diffs-font-family: var(--font-mono) !important;
304 --diffs-bg: var(--code-background) !important;
305 --diffs-light-bg: var(--code-background) !important;
306 --diffs-dark-bg: var(--code-background) !important;
307 --diffs-token-light-bg: transparent;
308 --diffs-token-dark-bg: transparent;
309
310 /* Gutter, context, and row tints all derive from the code surface the diff
311 body sits on. Mixing from the canvas leaves the gutter looking unthemed
312 when a palette separates the two. */
313 --diffs-bg-context-override: color-mix(in srgb, var(--code-background) 97%, var(--code-foreground));
314 --diffs-bg-hover-override: color-mix(in srgb, var(--code-background) 94%, var(--code-foreground));
315 --diffs-bg-separator-override: color-mix(
316 in srgb,
317 var(--code-background) 95%,
318 var(--code-foreground)
319 );
320 --diffs-bg-buffer-override: color-mix(in srgb, var(--code-background) 90%, var(--code-foreground));
321
322 --diffs-bg-addition-override: light-dark(
323 color-mix(in srgb, var(--code-background) 50%, var(--diff-addition)),
324 color-mix(in srgb, var(--code-background) 70%, var(--diff-addition))
325 );
326 --diffs-bg-addition-number-override: light-dark(
327 color-mix(in srgb, var(--code-background) 35%, var(--diff-addition)),
328 color-mix(in srgb, var(--code-background) 60%, var(--diff-addition))
329 );
330 --diffs-bg-addition-hover-override: color-mix(in srgb, var(--code-background) 85%, var(--diff-addition));
331 --diffs-bg-addition-emphasis-override: color-mix(
332 in srgb,
333 var(--code-background) 80%,
334 var(--diff-addition)
335 );
336
337 --diffs-bg-deletion-override: light-dark(
338 color-mix(in srgb, var(--code-background) 50%, var(--diff-deletion)),
339 color-mix(in srgb, var(--code-background) 70%, var(--diff-deletion))
340 );
341 --diffs-bg-deletion-number-override: light-dark(
342 color-mix(in srgb, var(--code-background) 35%, var(--diff-deletion)),
343 color-mix(in srgb, var(--code-background) 60%, var(--diff-deletion))
344 );
345 --diffs-bg-deletion-hover-override: color-mix(
346 in srgb,
347 var(--code-background) 85%,
348 var(--diff-deletion)
349 );
350 --diffs-bg-deletion-emphasis-override: color-mix(
351 in srgb,
352 var(--code-background) 80%,
353 var(--diff-deletion)
354 );
355
356 background-color: var(--diffs-bg) !important;
357 color: var(--code-foreground) !important;
358}
359
360/* The library's change-icon colors are tuned for dark canvases; light mode takes the app's darker tokens. */
361[data-change-icon="new"] {
362 color: var(
363 --diff-added-icon,
364 light-dark(var(--diff-addition-foreground), var(--diffs-addition-base))
365 ) !important;
366}
367[data-change-icon="deleted"] {
368 color: light-dark(var(--diff-deletion-foreground), var(--diffs-deletion-base)) !important;
369}
370/* The page sets --diff-modified-icon under the New design: a muted T3 blue, so the common case stays quiet. */
371[data-change-icon="change"],
372[data-change-icon="rename-pure"],
373[data-change-icon="rename-changed"] {
374 color: var(
375 --diff-modified-icon,
376 light-dark(var(--info-foreground), var(--diffs-modified-base))
377 ) !important;
378}
379`;