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

diffRendering.ts

484 lines17.2 KB

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