Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

diffRendering.ts

353 lines11.6 KB

1import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
2import { parseDiffFromFile } from "@pierre/diffs";
3import type { FileDiffMetadata } from "@pierre/diffs/types";
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;
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;
33​
34function 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}`;
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;
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 );
75​
76interface RenderablePatchOptions {
77 ignoreWhitespace?: boolean;
78 /** Compact Pierre source offsets for partial-patch rows; retain collapsedBefore for separators. */
79 compactPartialHunkOffsets?: boolean;
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 };
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 };
159​
160export function getRenderablePatch(
161 patch: string | undefined,
162 cacheScope = "diff-panel",
163 options: RenderablePatchOptions = {},
164): RenderablePatch | null {
165 if (!patch) return null;
166 const normalizedPatch = patch.trim();
167 if (normalizedPatch.length === 0) return null;
168​
169 try {
170 const parsedPatches = parsePatchFiles(
171 normalizedPatch,
172 buildPatchCacheKey(normalizedPatch, cacheScope),
173 );
174 const sourceFiles = parsedPatches.flatMap((parsedPatch) => parsedPatch.files);
175 const files = sourceFiles.map((file) => {
176 const filtered = options.ignoreWhitespace ? hideWhitespaceChanges(file) : file;
177 return options.compactPartialHunkOffsets ? compactPartialHunkOffsets(filtered) : filtered;
178 });
179 if (files.length > 0) {
180 return { kind: "files", files, sourceFiles };
181 }
182​
183 return {
184 kind: "raw",
185 text: normalizedPatch,
186 reason: "Unsupported diff format. Showing raw patch.",
187 };
188 } catch {
189 return {
190 kind: "raw",
191 text: normalizedPatch,
192 reason: "Failed to parse patch. Showing raw patch.",
193 };
194 }
196​
197/** Uses the parser-decoded filename, including Git's quoted and escaped names. */
198export function resolveFileDiffPath(fileDiff: FileDiffMetadata): string {
199 return fileDiff.name ?? fileDiff.prevName ?? "";
201​
202export function resolveFileDiffPreviousPath(fileDiff: FileDiffMetadata): string {
203 return fileDiff.prevName ?? fileDiff.name ?? "";
205​
206/** Includes change type to distinguish deletion/addition pairs for file-to-symlink changes. */
207export function buildFileDiffIdentityKey(fileDiff: FileDiffMetadata): string {
208 return `${resolveFileDiffPreviousPath(fileDiff)}\u0000${resolveFileDiffPath(fileDiff)}\u0000${fileDiff.type}`;
210​
211export function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
212 const cacheKey = fileDiff.cacheKey;
213 if (!cacheKey) return `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
214​
215 return cacheKey.endsWith(":hydrated") ? cacheKey.slice(0, -":hydrated".length) : cacheKey;
217​
218function hashFileDiffPart(hash: number, value: string | number | boolean | undefined): number {
219 const serialized = value === undefined ? "undefined" : String(value);
220 const withLength = fnv1a32(`${typeof value}:${serialized.length}:`, hash);
221 return fnv1a32(serialized, withLength);
223​
224// Pierre's whole-patch cache key would repaint every file when one changes.
225export function buildFileDiffContentVersion(fileDiff: FileDiffMetadata): number {
226 let hash = FNV_OFFSET_BASIS_32;
227 const append = (value: string | number | boolean | undefined) => {
228 hash = hashFileDiffPart(hash, value);
229 };
230​
231 append(fileDiff.name);
232 append(fileDiff.prevName);
233 append(fileDiff.lang);
234 append(fileDiff.newObjectId);
235 append(fileDiff.prevObjectId);
236 append(fileDiff.mode);
237 append(fileDiff.prevMode);
238 append(fileDiff.type);
239 append(fileDiff.isPartial);
240 append(fileDiff.splitLineCount);
241 append(fileDiff.unifiedLineCount);
242​
243 for (const line of fileDiff.additionLines) append(line);
244 for (const line of fileDiff.deletionLines) append(line);
245 for (const hunk of fileDiff.hunks) {
246 append(hunk.collapsedBefore);
247 append(hunk.additionStart);
248 append(hunk.additionCount);
249 append(hunk.additionLines);
250 append(hunk.additionLineIndex);
251 append(hunk.deletionStart);
252 append(hunk.deletionCount);
253 append(hunk.deletionLines);
254 append(hunk.deletionLineIndex);
255 append(hunk.hunkContext);
256 append(hunk.hunkSpecs);
257 append(hunk.splitLineStart);
258 append(hunk.splitLineCount);
259 append(hunk.unifiedLineStart);
260 append(hunk.unifiedLineCount);
261 append(hunk.noEOFCRAdditions);
262 append(hunk.noEOFCRDeletions);
263 for (const content of hunk.hunkContent) {
264 append(content.type);
265 append(content.additionLineIndex);
266 append(content.deletionLineIndex);
267 append(content.type === "change" ? content.additions : content.lines);
268 append(content.type === "change" ? content.deletions : undefined);
269 }
270 }
271​
272 return hash;
274​
275export function getDiffCollapseIconClassName(fileDiff: FileDiffMetadata): string {
276 switch (fileDiff.type) {
277 case "new":
278 return "text-[var(--diffs-addition-base)]";
279 case "deleted":
280 return "text-[var(--diffs-deletion-base)]";
281 case "change":
282 case "rename-pure":
283 case "rename-changed":
284 return "text-[var(--diffs-modified-base)]";
285 default:
286 return "text-muted-foreground/80";
287 }
289​
290export const DIFF_SURFACE_THEME_UNSAFE_CSS = `
291[data-diffs-header],
292[data-diff],
293[data-file],
294[data-error-wrapper],
295[data-virtualizer-buffer] {
296 --diffs-header-font-family: var(--font-sans) !important;
297 --diffs-font-family: var(--font-mono) !important;
298 --diffs-bg: var(--code-background) !important;
299 --diffs-light-bg: var(--code-background) !important;
300 --diffs-dark-bg: var(--code-background) !important;
301 --diffs-token-light-bg: transparent;
302 --diffs-token-dark-bg: transparent;
303​
304 /* Gutter, context, and row tints all derive from the code surface the diff
305 body sits on. Mixing from the canvas leaves the gutter looking unthemed
306 when a palette separates the two. */
307 --diffs-bg-context-override: color-mix(in srgb, var(--code-background) 97%, var(--code-foreground));
308 --diffs-bg-hover-override: color-mix(in srgb, var(--code-background) 94%, var(--code-foreground));
309 --diffs-bg-separator-override: color-mix(
310 in srgb,
311 var(--code-background) 95%,
312 var(--code-foreground)
313 );
314 --diffs-bg-buffer-override: color-mix(in srgb, var(--code-background) 90%, var(--code-foreground));
315​
316 --diffs-bg-addition-override: light-dark(
317 color-mix(in srgb, var(--code-background) 50%, var(--diff-addition)),
318 color-mix(in srgb, var(--code-background) 70%, var(--diff-addition))
319 );
320 --diffs-bg-addition-number-override: light-dark(
321 color-mix(in srgb, var(--code-background) 35%, var(--diff-addition)),
322 color-mix(in srgb, var(--code-background) 60%, var(--diff-addition))
323 );
324 --diffs-bg-addition-hover-override: color-mix(in srgb, var(--code-background) 85%, var(--diff-addition));
325 --diffs-bg-addition-emphasis-override: color-mix(
326 in srgb,
327 var(--code-background) 80%,
328 var(--diff-addition)
329 );
330​
331 --diffs-bg-deletion-override: light-dark(
332 color-mix(in srgb, var(--code-background) 50%, var(--diff-deletion)),
333 color-mix(in srgb, var(--code-background) 70%, var(--diff-deletion))
334 );
335 --diffs-bg-deletion-number-override: light-dark(
336 color-mix(in srgb, var(--code-background) 35%, var(--diff-deletion)),
337 color-mix(in srgb, var(--code-background) 60%, var(--diff-deletion))
338 );
339 --diffs-bg-deletion-hover-override: color-mix(
340 in srgb,
341 var(--code-background) 85%,
342 var(--diff-deletion)
343 );
344 --diffs-bg-deletion-emphasis-override: color-mix(
345 in srgb,
346 var(--code-background) 80%,
347 var(--diff-deletion)
348 );
349​
350 background-color: var(--diffs-bg) !important;
351 color: var(--code-foreground) !important;
353`;