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