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 const selection = comment.selection ?? range;
260 setDraftText("");
261 setDraft({
262 fileKey: item.id,
263 filePath,
264 previousFilePath: resolveFileDiffPreviousPath(item.fileDiff),
265 annotation: {
266 side: annotationSide(selection),
267 lineNumber: selection.end,
268 metadata: {
269 entries: [
270 { id, kind: "draft", range: selection, rangeLabel: comment.rangeLabel, text: "" },
271 ],
272 },
273 },
274 });
275 };
276
277 return (
278 <StyledDiffCodeView<DiffCommentAnnotationGroup>
279 key={codeViewKey}
280 {...(viewerRef ? { viewerRef } : {})}
281 {...(onScroll ? { onScroll } : {})}
282 {...(className ? { className } : {})}
283 {...(unsafeCSSExtra ? { unsafeCSSExtra } : {})}
284 {...(renderHeaderMetadata
285 ? {
286 renderHeaderMetadata: (item: CodeViewItem<DiffCommentAnnotationGroup>) =>
287 item.type === "diff" ? renderHeaderMetadata(item.fileDiff) : null,
288 }
289 : {})}
290 {...(renderCodeViewFooter ? { renderCodeViewFooter } : {})}
291 items={items}
292 selectedLines={selectedLines}
293 onSelectedLinesChange={setSelectedLines}
294 options={{
295 ...options,
296 enableGutterUtility: draft === null,
297 enableLineSelection: draft === null,
298 onGutterUtilityClick: beginComment,
299 onItemCollapsedChange: (_item, nextItem) =>
300 onFileCollapsedChange(nextItem.id, nextItem.collapsed === true),
301 }}
302 renderHeaderFilenameSuffix={(item) =>
303 item.type === "diff" ? renderHeaderFilenameSuffix(item.fileDiff) : null
304 }
305 renderHeaderPrefix={(item) =>
306 item.type === "diff"
307 ? renderHeaderPrefix(item.fileDiff, item.id, item.collapsed === true)
308 : null
309 }
310 renderAnnotation={(...[annotation]) => {
311 if (annotation.metadata.imagePath !== undefined) {
312 return renderImagePreview?.(annotation.metadata.imagePath) ?? null;
313 }
314 const hasDraft = annotation.metadata.entries.some((entry) => entry.kind === "draft");
315 return (
316 <div
317 className={hasDraft ? "py-1" : "divide-y divide-border/30 border-y border-border/30"}
318 >
319 {annotation.metadata.entries.map((entry) => (
320 <DiffCommentAnnotation
321 key={entry.id}
322 environmentId={environmentId}
323 projectId={projectId}
324 ownerKey={JSON.stringify([
325 environmentId,
326 composerDraftTarget,
327 codeViewKey,
328 entry.id,
329 ])}
330 kind={entry.kind}
331 rangeLabel={entry.rangeLabel}
332 text={entry.kind === "draft" ? draftText : entry.text}
333 onTextChange={setDraftText}
334 onCancel={() => removeEntry(entry.id)}
335 onComment={(text) => submitEntry(entry.id, text)}
336 onDelete={() => removeEntry(entry.id)}
337 />
338 ))}
339 </div>
340 );
341 }}
342 />
343 );
344}