Open History to see the last commit
1import type {
2 AnnotationSide,
3 CodeViewDiffItem,
4 CodeViewItem,
5 DiffLineAnnotation,
6 FileDiffMetadata,
7 SelectedLineRange,
8} from "@pierre/diffs";
9import type { CodeViewHandle, CodeViewProps } from "@pierre/diffs/react";
10import type { EnvironmentId, ProjectId, ScopedThreadRef } from "@t3tools/contracts";
11import { useState, type ReactNode, type Ref } from "react";
12
13import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
14import { fnv1a32, resolveFileDiffPath, resolveFileDiffPreviousPath } from "~/lib/diffRendering";
15import {
16 buildDiffReviewComment,
17 restoreDiffReviewCommentRange,
18 type ReviewCommentContext,
19} from "~/reviewCommentContext";
20
21import { nextFileCommentId } from "../files/fileCommentAnnotations";
22import { DiffCommentAnnotation } from "./DiffCommentAnnotation";
23import { StyledDiffCodeView, type StyledDiffCodeViewOptions } from "./StyledDiffCodeView";
24
25interface DiffCommentAnnotationEntry {
26 id: string;
27 kind: "draft" | "comment";
28 range: SelectedLineRange;
29 rangeLabel: string;
30 text: string;
31}
32
33interface DiffCommentAnnotationGroup {
34 entries: DiffCommentAnnotationEntry[];
35 imagePath?: string;
36}
37
38type DiffCommentLineAnnotation = DiffLineAnnotation<DiffCommentAnnotationGroup>;
39export type AnnotatableCodeViewHandle = CodeViewHandle<DiffCommentAnnotationGroup, undefined>;
40const EMPTY_REVIEW_COMMENTS: ReadonlyArray<ReviewCommentContext> = [];
41
42function annotationSide(range: SelectedLineRange): AnnotationSide {
43 return (range.endSide ?? range.side) === "deletions" ? "deletions" : "additions";
44}
45
46function appendAnnotationEntry(
47 annotations: ReadonlyArray<DiffCommentLineAnnotation>,
48 range: SelectedLineRange,
49 entry: DiffCommentAnnotationEntry,
50): DiffCommentLineAnnotation[] {
51 const side = annotationSide(range);
52 const annotationIndex = annotations.findIndex(
53 (annotation) => annotation.side === side && annotation.lineNumber === range.end,
54 );
55 if (annotationIndex < 0) {
56 return [
57 ...annotations,
58 {
59 side,
60 lineNumber: range.end,
61 metadata: { entries: [entry] },
62 },
63 ];
64 }
65 return annotations.map((annotation, index) =>
66 index === annotationIndex
67 ? {
68 ...annotation,
69 metadata: { entries: [...annotation.metadata.entries, entry] },
70 }
71 : annotation,
72 );
73}
74
75interface AnnotatableCodeViewProps {
76 environmentId?: EnvironmentId | undefined;
77 projectId?: ProjectId | null | undefined;
78 codeViewKey: string;
79 files: ReadonlyArray<{
80 fileDiff: FileDiffMetadata;
81 filePath: string;
82 fileKey: string;
83 fileVersion: number;
84 collapsed: boolean;
85 }>;
86 pendingFiles: ReadonlyArray<FileDiffMetadata>;
87 sectionId: string;
88 sectionTitle: string;
89 composerDraftTarget: ScopedThreadRef | DraftId;
90 options: StyledDiffCodeViewOptions<DiffCommentAnnotationGroup>;
91 viewerRef?: Ref<AnnotatableCodeViewHandle>;
92 onScroll?: CodeViewProps<DiffCommentAnnotationGroup, undefined>["onScroll"];
93 className?: string;
94 renderCodeViewFooter?: () => ReactNode;
95 unsafeCSSExtra?: string;
96 renderHeaderMetadata?: (fileDiff: FileDiffMetadata) => ReactNode;
97 renderHeaderFilenameSuffix: (fileDiff: FileDiffMetadata) => ReactNode;
98 renderHeaderPrefix: (
99 fileDiff: FileDiffMetadata,
100 fileKey: string,
101 collapsed: boolean,
102 ) => ReactNode;
103 onFileCollapsedChange: (fileKey: string, collapsed: boolean) => void;
104 /** Git sends no patch for an image, so its row can show the file at this path instead. */
105 imagePreviewPath?: (fileDiff: FileDiffMetadata) => string | null;
106 renderImagePreview?: (path: string) => ReactNode;
107}
108
109interface DiffSelectionContext {
110 item: CodeViewItem<DiffCommentAnnotationGroup>;
111}
112
113export function AnnotatableCodeView({
114 environmentId,
115 projectId,
116 codeViewKey,
117 files,
118 pendingFiles,
119 sectionId,
120 sectionTitle,
121 composerDraftTarget,
122 options,
123 viewerRef,
124 onScroll,
125 className,
126 renderCodeViewFooter,
127 unsafeCSSExtra,
128 renderHeaderMetadata,
129 renderHeaderFilenameSuffix,
130 renderHeaderPrefix,
131 onFileCollapsedChange,
132 imagePreviewPath,
133 renderImagePreview,
134}: AnnotatableCodeViewProps) {
135 const addReviewComment = useComposerDraftStore((store) => store.addReviewComment);
136 const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment);
137 const reviewComments = useComposerDraftStore(
138 (store) => store.getComposerDraft(composerDraftTarget)?.reviewComments ?? EMPTY_REVIEW_COMMENTS,
139 );
140 const [selectedLines, setSelectedLines] = useState<{
141 id: string;
142 range: SelectedLineRange;
143 } | null>(null);
144 const [draft, setDraft] = useState<{
145 fileKey: string;
146 filePath: string;
147 previousFilePath: string;
148 annotation: DiffCommentLineAnnotation;
149 } | null>(null);
150 const [draftText, setDraftText] = useState("");
151
152 const filesByKey = new Map(files.map((file) => [file.fileKey, file]));
153 if (
154 draft !== null &&
155 !filesByKey.has(draft.fileKey) &&
156 // Lazy placeholders have provisional change types, so match both paths instead.
157 !pendingFiles.some(
158 (file) =>
159 resolveFileDiffPath(file) === draft.filePath &&
160 resolveFileDiffPreviousPath(file) === draft.previousFilePath,
161 )
162 ) {
163 setDraft(null);
164 setDraftText("");
165 setSelectedLines(null);
166 }
167 const items: CodeViewDiffItem<DiffCommentAnnotationGroup>[] = files.map(
168 ({ fileDiff, filePath, fileKey, fileVersion, collapsed }) => {
169 const persisted = reviewComments
170 .filter(
171 (comment) =>
172 comment.sectionId === sectionId &&
173 comment.filePath === filePath &&
174 (comment.fenceLanguage ?? "diff") === "diff",
175 )
176 .reduce<DiffCommentLineAnnotation[]>((annotations, comment) => {
177 const range = restoreDiffReviewCommentRange(fileDiff, comment);
178 if (!range) return annotations;
179 return appendAnnotationEntry(annotations, range, {
180 id: comment.id,
181 kind: "comment",
182 range,
183 rangeLabel: comment.rangeLabel,
184 text: comment.text,
185 });
186 }, []);
187 const imagePath = imagePreviewPath?.(fileDiff) ?? null;
188 const annotations = [
189 ...persisted,
190 ...(draft?.fileKey === fileKey ? [draft.annotation] : []),
191 ...(imagePath === null
192 ? []
193 : [{ side: "additions" as const, lineNumber: 0, metadata: { entries: [], imagePath } }]),
194 ];
195 return {
196 id: fileKey,
197 type: "diff",
198 fileDiff,
199 annotations,
200 collapsed,
201 version: fnv1a32(
202 `${fileVersion}:${collapsed ? "1" : "0"}:${imagePath ?? ""}:${annotations
203 .flatMap((annotation) =>
204 annotation.metadata.entries.map(
205 (entry) => `${entry.id}:${entry.rangeLabel}:${entry.text}`,
206 ),
207 )
208 .join(":")}`,
209 ),
210 };
211 },
212 );
213
214 const removeEntry = (entryId: string) => {
215 setSelectedLines(null);
216 if (draft?.annotation.metadata.entries.some((entry) => entry.id === entryId)) {
217 setDraft(null);
218 setDraftText("");
219 } else {
220 removeReviewComment(composerDraftTarget, entryId);
221 }
222 };
223
224 const submitEntry = (entryId: string, text: string) => {
225 const entry = draft?.annotation.metadata.entries.find((candidate) => candidate.id === entryId);
226 const file = draft ? filesByKey.get(draft.fileKey) : undefined;
227 if (!entry || !file) return;
228 const comment = buildDiffReviewComment({
229 id: entry.id,
230 sectionId,
231 sectionTitle,
232 filePath: file.filePath,
233 fileDiff: file.fileDiff,
234 range: entry.range,
235 text,
236 });
237 if (comment) addReviewComment(composerDraftTarget, comment);
238 setSelectedLines(null);
239 setDraft(null);
240 setDraftText("");
241 };
242
243 const beginComment = (range: SelectedLineRange | null, context: DiffSelectionContext) => {
244 if (!range) return;
245 const item = context.item;
246 if (item.type !== "diff") return;
247 const id = nextFileCommentId();
248 const filePath = resolveFileDiffPath(item.fileDiff);
249 const comment = buildDiffReviewComment({
250 id,
251 sectionId,
252 sectionTitle,
253 filePath,
254 fileDiff: item.fileDiff,
255 range,
256 text: "",
257 });
258 if (!comment) return;
259 setDraftText("");
260 setDraft({
261 fileKey: item.id,
262 filePath,
263 previousFilePath: resolveFileDiffPreviousPath(item.fileDiff),
264 annotation: {
265 side: annotationSide(range),
266 lineNumber: range.end,
267 metadata: {
268 entries: [{ id, kind: "draft", range, rangeLabel: comment.rangeLabel, text: "" }],
269 },
270 },
271 });
272 };
273
274 return (
275 <StyledDiffCodeView<DiffCommentAnnotationGroup>
276 key={codeViewKey}
277 {...(viewerRef ? { viewerRef } : {})}
278 {...(onScroll ? { onScroll } : {})}
279 {...(className ? { className } : {})}
280 {...(unsafeCSSExtra ? { unsafeCSSExtra } : {})}
281 {...(renderHeaderMetadata
282 ? {
283 renderHeaderMetadata: (item: CodeViewItem<DiffCommentAnnotationGroup>) =>
284 item.type === "diff" ? renderHeaderMetadata(item.fileDiff) : null,
285 }
286 : {})}
287 {...(renderCodeViewFooter ? { renderCodeViewFooter } : {})}
288 items={items}
289 selectedLines={selectedLines}
290 onSelectedLinesChange={setSelectedLines}
291 options={{
292 ...options,
293 enableGutterUtility: draft === null,
294 enableLineSelection: draft === null,
295 onGutterUtilityClick: beginComment,
296 onItemCollapsedChange: (_item, nextItem) =>
297 onFileCollapsedChange(nextItem.id, nextItem.collapsed === true),
298 }}
299 renderHeaderFilenameSuffix={(item) =>
300 item.type === "diff" ? renderHeaderFilenameSuffix(item.fileDiff) : null
301 }
302 renderHeaderPrefix={(item) =>
303 item.type === "diff"
304 ? renderHeaderPrefix(item.fileDiff, item.id, item.collapsed === true)
305 : null
306 }
307 renderAnnotation={(...[annotation]) => {
308 if (annotation.metadata.imagePath !== undefined) {
309 return renderImagePreview?.(annotation.metadata.imagePath) ?? null;
310 }
311 const hasDraft = annotation.metadata.entries.some((entry) => entry.kind === "draft");
312 return (
313 <div
314 className={hasDraft ? "py-1" : "divide-y divide-border/30 border-y border-border/30"}
315 >
316 {annotation.metadata.entries.map((entry) => (
317 <DiffCommentAnnotation
318 key={entry.id}
319 environmentId={environmentId}
320 projectId={projectId}
321 ownerKey={JSON.stringify([
322 environmentId,
323 composerDraftTarget,
324 codeViewKey,
325 entry.id,
326 ])}
327 kind={entry.kind}
328 rangeLabel={entry.rangeLabel}
329 text={entry.kind === "draft" ? draftText : entry.text}
330 onTextChange={setDraftText}
331 onCancel={() => removeEntry(entry.id)}
332 onComment={(text) => submitEntry(entry.id, text)}
333 onDelete={() => removeEntry(entry.id)}
334 />
335 ))}
336 </div>
337 );
338 }}
339 />
340 );
341}