The best way to control Claude Code, Codex and more from any computer or phone

main
ts 380 lines 13.5 KB
Raw
1 import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
2 import { parseDiffFromFile } from "@pierre/diffs";
3 import type { FileDiffMetadata } from "@pierre/diffs/types";
4 import { msg } from "gt-react";
5
6 import { m, type MessageResolver } from "../i18n/messages";
7 import { READABLE_LIGHT_THEME_NAME } from "./readableSyntaxTheme";
8
9 // Light mode uses a darker pierre-light so syntax stays readable on every code surface.
10 export const DIFF_THEME_NAMES = {
11 light: READABLE_LIGHT_THEME_NAME,
12 dark: "pierre-dark",
13 } as const;
14
15 export type DiffThemeName = (typeof DIFF_THEME_NAMES)[keyof typeof DIFF_THEME_NAMES];
16
17 export function resolveDiffThemeName(theme: "light" | "dark"): DiffThemeName {
18 return DIFF_THEME_NAMES[theme];
19 }
20
21 const FNV_OFFSET_BASIS_32 = 0x811c9dc5;
22 const FNV_PRIME_32 = 0x01000193;
23 const SECONDARY_HASH_SEED = 0x9e3779b9;
24 const SECONDARY_HASH_MULTIPLIER = 0x85ebca6b;
25
26 export 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
39 function 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
45 export 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
57 export interface DiffLineStat {
58 additions: number;
59 deletions: number;
60 }
61
62 export 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
76 interface RenderablePatchOptions {
77 ignoreWhitespace?: boolean;
78 /** Compact Pierre source offsets for partial-patch rows; retain collapsedBefore for separators. */
79 compactPartialHunkOffsets?: boolean;
80 }
81
82 function 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
135 function 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
160 export 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 /** Uses the parser-decoded filename, including Git's quoted and escaped names. */
196 export function resolveFileDiffPath(fileDiff: FileDiffMetadata): string {
197 return fileDiff.name ?? fileDiff.prevName ?? "";
198 }
199
200 export function resolveFileDiffPreviousPath(fileDiff: FileDiffMetadata): string {
201 return fileDiff.prevName ?? fileDiff.name ?? "";
202 }
203
204 /** Includes change type to distinguish deletion/addition pairs for file-to-symlink changes. */
205 export function buildFileDiffIdentityKey(fileDiff: FileDiffMetadata): string {
206 return `${resolveFileDiffPreviousPath(fileDiff)}\u0000${resolveFileDiffPath(fileDiff)}\u0000${fileDiff.type}`;
207 }
208
209 export function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
210 const cacheKey = fileDiff.cacheKey;
211 if (!cacheKey) return `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
212
213 return cacheKey.endsWith(":hydrated") ? cacheKey.slice(0, -":hydrated".length) : cacheKey;
214 }
215
216 function hashFileDiffPart(hash: number, value: string | number | boolean | undefined): number {
217 const serialized = value === undefined ? "undefined" : String(value);
218 const withLength = fnv1a32(`${typeof value}:${serialized.length}:`, hash);
219 return fnv1a32(serialized, withLength);
220 }
221
222 // Pierre's whole-patch cache key would repaint every file when one changes.
223 export function buildFileDiffContentVersion(fileDiff: FileDiffMetadata): number {
224 let hash = FNV_OFFSET_BASIS_32;
225 const append = (value: string | number | boolean | undefined) => {
226 hash = hashFileDiffPart(hash, value);
227 };
228
229 append(fileDiff.name);
230 append(fileDiff.prevName);
231 append(fileDiff.lang);
232 append(fileDiff.newObjectId);
233 append(fileDiff.prevObjectId);
234 append(fileDiff.mode);
235 append(fileDiff.prevMode);
236 append(fileDiff.type);
237 append(fileDiff.isPartial);
238 append(fileDiff.splitLineCount);
239 append(fileDiff.unifiedLineCount);
240
241 for (const line of fileDiff.additionLines) append(line);
242 for (const line of fileDiff.deletionLines) append(line);
243 for (const hunk of fileDiff.hunks) {
244 append(hunk.collapsedBefore);
245 append(hunk.additionStart);
246 append(hunk.additionCount);
247 append(hunk.additionLines);
248 append(hunk.additionLineIndex);
249 append(hunk.deletionStart);
250 append(hunk.deletionCount);
251 append(hunk.deletionLines);
252 append(hunk.deletionLineIndex);
253 append(hunk.hunkContext);
254 append(hunk.hunkSpecs);
255 append(hunk.splitLineStart);
256 append(hunk.splitLineCount);
257 append(hunk.unifiedLineStart);
258 append(hunk.unifiedLineCount);
259 append(hunk.noEOFCRAdditions);
260 append(hunk.noEOFCRDeletions);
261 for (const content of hunk.hunkContent) {
262 append(content.type);
263 append(content.additionLineIndex);
264 append(content.deletionLineIndex);
265 append(content.type === "change" ? content.additions : content.lines);
266 append(content.type === "change" ? content.deletions : undefined);
267 }
268 }
269
270 return hash;
271 }
272
273 const fileEntryCache = new WeakMap<
274 FileDiffMetadata,
275 { fileDiff: FileDiffMetadata; fileKey: string; fileVersion: number }
276 >();
277
278 /** Give repeated blocks independent viewer state without tying identity to patch content. */
279 export function buildFileDiffEntries(files: ReadonlyArray<FileDiffMetadata>) {
280 const occurrences = new Map<string, number>();
281 return files.map((fileDiff) => {
282 let entry = fileEntryCache.get(fileDiff);
283 if (!entry) {
284 entry = {
285 fileDiff,
286 fileKey: buildFileDiffIdentityKey(fileDiff),
287 fileVersion: buildFileDiffContentVersion(fileDiff),
288 };
289 fileEntryCache.set(fileDiff, entry);
290 }
291 const occurrence = occurrences.get(entry.fileKey) ?? 0;
292 occurrences.set(entry.fileKey, occurrence + 1);
293 return occurrence === 0 ? entry : { ...entry, fileKey: `${entry.fileKey}\u0000${occurrence}` };
294 });
295 }
296
297 export const DIFF_SURFACE_THEME_UNSAFE_CSS = `
298 [data-diffs-header],
299 [data-diff],
300 [data-file],
301 [data-error-wrapper],
302 [data-virtualizer-buffer] {
303 --diffs-header-font-family: var(--font-sans) !important;
304 --diffs-font-family: var(--font-mono) !important;
305 --diffs-bg: var(--code-background) !important;
306 --diffs-light-bg: var(--code-background) !important;
307 --diffs-dark-bg: var(--code-background) !important;
308 --diffs-token-light-bg: transparent;
309 --diffs-token-dark-bg: transparent;
310
311 /* Gutter, context, and row tints all derive from the code surface the diff
312 body sits on. Mixing from the canvas leaves the gutter looking unthemed
313 when a palette separates the two. */
314 --diffs-bg-context-override: color-mix(in srgb, var(--code-background) 97%, var(--code-foreground));
315 --diffs-bg-hover-override: color-mix(in srgb, var(--code-background) 94%, var(--code-foreground));
316 --diffs-bg-separator-override: color-mix(
317 in srgb,
318 var(--code-background) 95%,
319 var(--code-foreground)
320 );
321 --diffs-bg-buffer-override: color-mix(in srgb, var(--code-background) 90%, var(--code-foreground));
322
323 --diffs-bg-addition-override: light-dark(
324 color-mix(in srgb, var(--code-background) calc(50% - var(--appearance-contrast-boost, 0%) / 4), var(--diff-addition)),
325 color-mix(in srgb, var(--code-background) calc(70% - var(--appearance-contrast-boost, 0%) / 4), var(--diff-addition))
326 );
327 --diffs-bg-addition-number-override: light-dark(
328 color-mix(in srgb, var(--code-background) calc(35% - var(--appearance-contrast-boost, 0%) / 4), var(--diff-addition)),
329 color-mix(in srgb, var(--code-background) calc(60% - var(--appearance-contrast-boost, 0%) / 4), var(--diff-addition))
330 );
331 --diffs-bg-addition-hover-override: color-mix(in srgb, var(--code-background) 85%, var(--diff-addition));
332 /* Pierre resolves emphasis on the host, before the diff's overrides can inherit. */
333 /* Light emphasis stays above t3-light's readable syntax luminance floor. */
334 --diffs-bg-addition-emphasis: light-dark(
335 rgb(from var(--diffs-addition-base) r g b / 15%),
336 rgb(from var(--diffs-addition-base) r g b / calc(20% + var(--appearance-contrast-boost, 0%) / 4))
337 );
338
339 --diffs-bg-deletion-override: light-dark(
340 color-mix(in srgb, var(--code-background) calc(50% - var(--appearance-contrast-boost, 0%) / 4), var(--diff-deletion)),
341 color-mix(in srgb, var(--code-background) calc(70% - var(--appearance-contrast-boost, 0%) / 4), var(--diff-deletion))
342 );
343 --diffs-bg-deletion-number-override: light-dark(
344 color-mix(in srgb, var(--code-background) calc(35% - var(--appearance-contrast-boost, 0%) / 4), var(--diff-deletion)),
345 color-mix(in srgb, var(--code-background) calc(60% - var(--appearance-contrast-boost, 0%) / 4), var(--diff-deletion))
346 );
347 --diffs-bg-deletion-hover-override: color-mix(
348 in srgb,
349 var(--code-background) 85%,
350 var(--diff-deletion)
351 );
352 --diffs-bg-deletion-emphasis: light-dark(
353 rgb(from var(--diffs-deletion-base) r g b / 15%),
354 rgb(from var(--diffs-deletion-base) r g b / calc(20% + var(--appearance-contrast-boost, 0%) / 4))
355 );
356
357 background-color: var(--diffs-bg) !important;
358 color: var(--code-foreground) !important;
359 }
360
361 /* The library's change-icon colors are tuned for dark canvases; light mode takes the app's darker tokens. */
362 [data-change-icon="new"] {
363 color: var(
364 --diff-added-icon,
365 light-dark(var(--diff-addition-foreground), var(--diffs-addition-base))
366 ) !important;
367 }
368 [data-change-icon="deleted"] {
369 color: light-dark(var(--diff-deletion-foreground), var(--diffs-deletion-base)) !important;
370 }
371 /* The page sets --diff-modified-icon to a muted T3 blue, so the common case stays quiet. */
372 [data-change-icon="change"],
373 [data-change-icon="rename-pure"],
374 [data-change-icon="rename-changed"] {
375 color: var(
376 --diff-modified-icon,
377 light-dark(var(--info-foreground), var(--diffs-modified-base))
378 ) !important;
379 }
380 `;