@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 194 lines 7.64 KB
Raw
1 /**
2 * Shared changed-file renderer used by the commit view (`Commit.tsx`)
3 * and the pull-request view (`Pull.tsx`): one card per `DiffEntry` with
4 * a status badge header and a `@pierre/diffs` `<FileDiff>` body, plus
5 * "Show more files" pagination.
6 *
7 * IMPORTANT: this module imports the diffs+shiki runtime (via
8 * `../diff.tsx`). Only `React.lazy` chunks may import it — never
9 * `main.tsx`/`Repo.tsx` statically — so the library stays out of the
10 * initial bundle.
11 *
12 * Each card fetches its own old/new blob contents by oid (shared
13 * 4-concurrent limiter) and diffs locally. Gitlinks, mode-only changes,
14 * oversize and binary blobs render placeholder rows and never
15 * fetch/parse.
16 */
17 import { parseDiffFromFile, type FileContents, type FileDiffMetadata } from "@pierre/diffs";
18 import { FileDiff } from "@pierre/diffs/react";
19 import { useEffect, useState, type ReactNode } from "react";
20 import { getBlob, type DiffEntry, type FileStatus } from "../client.ts";
21 import { Button, ErrorBox } from "../components.tsx";
22 import { blobLimiter, MAX_RENDER_BYTES, useFileDiffOptions } from "../diff.tsx";
23 import { decodeText, formatBytes } from "../format.ts";
24 import type { RepoContext } from "./Repo.tsx";
25
26 // ── per-file diff card ──────────────────────────────────────────────────────
27
28 type FileState =
29 | { kind: "loading" }
30 | { kind: "text"; fileDiff: FileDiffMetadata }
31 | { kind: "binary" }
32 | { kind: "error"; error: unknown };
33
34 const StatusBadge = ({ status }: { status: FileStatus }) => (
35 <span
36 className={`shrink-0 rounded-full border px-2 py-0.5 font-medium ${
37 status === "added"
38 ? "border-success/40 text-success"
39 : status === "removed"
40 ? "border-danger/40 text-danger"
41 : "border-attention/40 text-attention"
42 }`}
43 >
44 {status}
45 </span>
46 );
47
48 /** Placeholder body for files we deliberately don't render as a diff. */
49 const NoteRow = ({ children }: { children: ReactNode }) => (
50 <div className="px-4 py-6 text-center text-sm text-fg-muted">{children}</div>
51 );
52
53 const sizeLabel = (entry: DiffEntry): string | null => {
54 const size = entry.newSize ?? entry.oldSize;
55 return size == null ? null : formatBytes(size);
56 };
57
58 export const FileDiffCard = ({ context, entry }: { context: RepoContext; entry: DiffEntry }) => {
59 const options = useFileDiffOptions();
60 const { connection, repo } = context;
61
62 // Cases that never fetch contents.
63 const gitlink = entry.oldMode === "160000" || entry.newMode === "160000";
64 const modeOnly =
65 entry.status === "modified" && entry.oldOid != null && entry.oldOid === entry.newOid;
66 const oversize =
67 (entry.oldSize ?? 0) > MAX_RENDER_BYTES || (entry.newSize ?? 0) > MAX_RENDER_BYTES;
68 const skip = gitlink || modeOnly || oversize;
69
70 const [state, setState] = useState<FileState>({ kind: "loading" });
71
72 useEffect(() => {
73 if (skip) return;
74 let cancelled = false;
75 setState({ kind: "loading" });
76 void blobLimiter(async () => {
77 // Absent sides arrive as null over JSON (added/removed files) —
78 // treat null and undefined alike or we fetch "blobs/null".
79 const side = (oid: string | null | undefined, size: number | null | undefined) =>
80 oid == null
81 ? Promise.resolve(null)
82 : getBlob(connection, repo.owner, repo.name, oid, {
83 size: size ?? undefined,
84 });
85 const [oldBytes, newBytes] = await Promise.all([
86 side(entry.oldOid, entry.oldSize),
87 side(entry.newOid, entry.newSize),
88 ]);
89 if (cancelled) return;
90 const oldText = oldBytes === null ? null : decodeText(oldBytes);
91 const newText = newBytes === null ? null : decodeText(newBytes);
92 // A side that exists but doesn't decode as UTF-8 is binary.
93 if ((oldBytes !== null && oldText === null) || (newBytes !== null && newText === null)) {
94 setState({ kind: "binary" });
95 return;
96 }
97 // The blob oid is a perfect cacheKey: content-addressed identity.
98 const contents = (
99 text: string | null,
100 oid: string | null | undefined,
101 ): FileContents | null =>
102 text === null ? null : { name: entry.path, contents: text, cacheKey: oid ?? undefined };
103 // The server guarantees ≥ 1 side, so this never sees (null, null).
104 const fileDiff = parseDiffFromFile(
105 contents(oldText, entry.oldOid),
106 contents(newText, entry.newOid),
107 );
108 setState({ kind: "text", fileDiff });
109 }).catch((error: unknown) => {
110 if (!cancelled) setState({ kind: "error", error });
111 });
112 return () => {
113 cancelled = true;
114 };
115 // eslint-disable-next-line react-hooks/exhaustive-deps
116 }, [entry.oldOid, entry.newOid, skip, repo.repoId]);
117
118 const size = sizeLabel(entry);
119 const modeChanged =
120 entry.oldMode !== undefined && entry.newMode !== undefined && entry.oldMode !== entry.newMode;
121
122 return (
123 <div className="overflow-hidden rounded-md border border-border-muted">
124 <div className="flex items-center justify-between gap-3 border-b border-border-muted bg-canvas-subtle px-3 py-2 text-xs">
125 <div className="flex min-w-0 items-center gap-2">
126 <StatusBadge status={entry.status} />
127 <span className="truncate font-mono">{entry.path}</span>
128 {modeChanged && (
129 <span className="shrink-0 text-fg-muted">
130 {entry.oldMode} → {entry.newMode}
131 </span>
132 )}
133 </div>
134 {size !== null && <span className="shrink-0 text-fg-muted">{size}</span>}
135 </div>
136 {gitlink ? (
137 <NoteRow>
138 Subproject commit <code className="font-mono">{entry.newOid ?? entry.oldOid}</code>
139 </NoteRow>
140 ) : modeOnly ? (
141 <NoteRow>File mode changed — contents unchanged</NoteRow>
142 ) : oversize ? (
143 <NoteRow>Large file not rendered ({size})</NoteRow>
144 ) : state.kind === "loading" ? (
145 <div className="flex justify-center py-6">
146 <div className="size-5 animate-spin rounded-full border-2 border-border-muted border-t-accent" />
147 </div>
148 ) : state.kind === "binary" ? (
149 <NoteRow>Binary file not shown{size !== null && ` (${size})`}</NoteRow>
150 ) : state.kind === "error" ? (
151 <ErrorBox error={state.error} />
152 ) : (
153 <FileDiff fileDiff={state.fileDiff} options={options} />
154 )}
155 </div>
156 );
157 };
158
159 // ── the paged list ──────────────────────────────────────────────────────────
160
161 /** Files rendered before the "Show more" affordance kicks in. */
162 const PAGE_SIZE = 25;
163
164 /** Paged list of file-diff cards (resets paging when `files` changes). */
165 const FileDiffList = ({ context, files }: { context: RepoContext; files: DiffEntry[] }) => {
166 const [visible, setVisible] = useState(PAGE_SIZE);
167 useEffect(() => {
168 setVisible(PAGE_SIZE);
169 }, [files]);
170
171 return (
172 <div>
173 <div className="flex flex-col gap-4">
174 {files.slice(0, visible).map((entry) => (
175 <FileDiffCard key={`${entry.status}:${entry.path}`} context={context} entry={entry} />
176 ))}
177 {files.length === 0 && (
178 <div className="rounded-md border border-border-muted px-4 py-8 text-center text-sm text-fg-muted">
179 No changes
180 </div>
181 )}
182 </div>
183 {visible < files.length && (
184 <div className="mt-4 flex justify-center">
185 <Button onClick={() => setVisible((count) => count + PAGE_SIZE)}>
186 Show more files ({files.length - visible} remaining)
187 </Button>
188 </div>
189 )}
190 </div>
191 );
192 };
193
194 export default FileDiffList;