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 } from "@pierre/diffs/react";
10import type { 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}
36
37type DiffCommentLineAnnotation = DiffLineAnnotation<DiffCommentAnnotationGroup>;
38export type AnnotatableCodeViewHandle = CodeViewHandle<DiffCommentAnnotationGroup, undefined>;
39const EMPTY_REVIEW_COMMENTS: ReadonlyArray<ReviewCommentContext> = [];
40
41function annotationSide(range: SelectedLineRange): AnnotationSide {
42 return (range.endSide ?? range.side) === "deletions" ? "deletions" : "additions";
43}
44
45function appendAnnotationEntry(
46 annotations: ReadonlyArray<DiffCommentLineAnnotation>,
47 range: SelectedLineRange,
48 entry: DiffCommentAnnotationEntry,
49): DiffCommentLineAnnotation[] {
50 const side = annotationSide(range);
51 const annotationIndex = annotations.findIndex(
52 (annotation) => annotation.side === side && annotation.lineNumber === range.end,
53 );
54 if (annotationIndex < 0) {
55 return [
56 ...annotations,
57 {
58 side,
59 lineNumber: range.end,
60 metadata: { entries: [entry] },
61 },
62 ];
63 }
64 return annotations.map((annotation, index) =>
65 index === annotationIndex
66 ? {
67 ...annotation,
68 metadata: { entries: [...annotation.metadata.entries, entry] },
69 }
70 : annotation,
71 );
72}
73
74interface AnnotatableCodeViewProps {
75 codeViewKey: string;
76 files: ReadonlyArray<{
77 fileDiff: FileDiffMetadata;
78 filePath: string;
79 fileKey: string;
80 fileVersion: number;
81 collapsed: boolean;
82 }>;
83 pendingFiles: ReadonlyArray<FileDiffMetadata>;
84 sectionId: string;
85 sectionTitle: string;
86 composerDraftTarget: ScopedThreadRef | DraftId;
87 options: StyledDiffCodeViewOptions<DiffCommentAnnotationGroup>;
88 viewerRef?: Ref<AnnotatableCodeViewHandle>;
89 className?: string;
90 renderCodeViewFooter?: () => ReactNode;
91 unsafeCSSExtra?: string;
92 renderHeaderMetadata?: (fileDiff: FileDiffMetadata) => ReactNode;
93 renderHeaderFilenameSuffix: (fileDiff: FileDiffMetadata) => ReactNode;
94 renderHeaderPrefix: (
95 fileDiff: FileDiffMetadata,
96 fileKey: string,
97 collapsed: boolean,
98 ) => ReactNode;
99 onRevealSearchMatch: (fileKey: string) => void;
100}
101
102interface DiffSelectionContext {
103 item: CodeViewItem<DiffCommentAnnotationGroup>;
104}
105
106export function AnnotatableCodeView({
107 codeViewKey,
108 files,
109 pendingFiles,
110 sectionId,
111 sectionTitle,
112 composerDraftTarget,
113 options,
114 viewerRef,
115 className,
116 renderCodeViewFooter,
117 unsafeCSSExtra,
118 renderHeaderMetadata,
119 renderHeaderFilenameSuffix,
120 renderHeaderPrefix,
121 onRevealSearchMatch,
122}: AnnotatableCodeViewProps) {
123 const addReviewComment = useComposerDraftStore((store) => store.addReviewComment);
124 const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment);
125 const reviewComments = useComposerDraftStore(
126 (store) => store.getComposerDraft(composerDraftTarget)?.reviewComments ?? EMPTY_REVIEW_COMMENTS,
127 );
128 const [selectedLines, setSelectedLines] = useState<{
129 id: string;
130 range: SelectedLineRange;
131 } | null>(null);
132 const [draft, setDraft] = useState<{
133 fileKey: string;
134 filePath: string;
135 previousFilePath: string;
136 annotation: DiffCommentLineAnnotation;
137 } | null>(null);
138 const [draftText, setDraftText] = useState("");
139
140 const filesByKey = new Map(files.map((file) => [file.fileKey, file]));
141 if (
142 draft !== null &&
143 !filesByKey.has(draft.fileKey) &&
144 // Lazy placeholders have provisional change types, so match both paths instead.
145 !pendingFiles.some(
146 (file) =>
147 resolveFileDiffPath(file) === draft.filePath &&
148 resolveFileDiffPreviousPath(file) === draft.previousFilePath,
149 )
150 ) {
151 setDraft(null);
152 setDraftText("");
153 setSelectedLines(null);
154 }
155 const items: CodeViewDiffItem<DiffCommentAnnotationGroup>[] = files.map(
156 ({ fileDiff, filePath, fileKey, fileVersion, collapsed }) => {
157 const persisted = reviewComments
158 .filter(
159 (comment) =>
160 comment.sectionId === sectionId &&
161 comment.filePath === filePath &&
162 (comment.fenceLanguage ?? "diff") === "diff",
163 )
164 .reduce<DiffCommentLineAnnotation[]>((annotations, comment) => {
165 const range = restoreDiffReviewCommentRange(fileDiff, comment);
166 if (!range) return annotations;
167 return appendAnnotationEntry(annotations, range, {
168 id: comment.id,
169 kind: "comment",
170 range,
171 rangeLabel: comment.rangeLabel,
172 text: comment.text,
173 });
174 }, []);
175 const annotations = draft?.fileKey === fileKey ? [...persisted, draft.annotation] : persisted;
176 return {
177 id: fileKey,
178 type: "diff",
179 fileDiff,
180 annotations,
181 collapsed,
182 version: fnv1a32(
183 `${fileVersion}:${collapsed ? "1" : "0"}:${annotations
184 .flatMap((annotation) =>
185 annotation.metadata.entries.map(
186 (entry) => `${entry.id}:${entry.rangeLabel}:${entry.text}`,
187 ),
188 )
189 .join(":")}`,
190 ),
191 };
192 },
193 );
194
195 const removeEntry = (entryId: string) => {
196 setSelectedLines(null);
197 if (draft?.annotation.metadata.entries.some((entry) => entry.id === entryId)) {
198 setDraft(null);
199 setDraftText("");
200 } else {
201 removeReviewComment(composerDraftTarget, entryId);
202 }
203 };
204
205 const submitEntry = (entryId: string, text: string) => {
206 const entry = draft?.annotation.metadata.entries.find((candidate) => candidate.id === entryId);
207 const file = draft ? filesByKey.get(draft.fileKey) : undefined;
208 if (!entry || !file) return;
209 const comment = buildDiffReviewComment({
210 id: entry.id,
211 sectionId,
212 sectionTitle,
213 filePath: file.filePath,
214 fileDiff: file.fileDiff,
215 range: entry.range,
216 text,
217 });
218 if (comment) addReviewComment(composerDraftTarget, comment);
219 setSelectedLines(null);
220 setDraft(null);
221 setDraftText("");
222 };
223
224 const beginComment = (range: SelectedLineRange | null, context: DiffSelectionContext) => {
225 if (!range) return;
226 const item = context.item;
227 if (item.type !== "diff") return;
228 // Read from the item, not the file list, so the compiled callback keeps its identity
229 // as patches arrive; the viewer re-applies its options whenever it changes.
230 const id = nextFileCommentId();
231 const filePath = resolveFileDiffPath(item.fileDiff);
232 const comment = buildDiffReviewComment({
233 id,
234 sectionId,
235 sectionTitle,
236 filePath,
237 fileDiff: item.fileDiff,
238 range,
239 text: "",
240 });
241 if (!comment) return;
242 setDraftText("");
243 setDraft({
244 fileKey: item.id,
245 filePath,
246 previousFilePath: resolveFileDiffPreviousPath(item.fileDiff),
247 annotation: {
248 side: annotationSide(range),
249 lineNumber: range.end,
250 metadata: {
251 entries: [{ id, kind: "draft", range, rangeLabel: comment.rangeLabel, text: "" }],
252 },
253 },
254 });
255 };
256
257 return (
258 <StyledDiffCodeView<DiffCommentAnnotationGroup>
259 key={codeViewKey}
260 {...(viewerRef ? { viewerRef } : {})}
261 {...(className ? { className } : {})}
262 {...(unsafeCSSExtra ? { unsafeCSSExtra } : {})}
263 {...(renderHeaderMetadata
264 ? {
265 renderHeaderMetadata: (item: CodeViewItem<DiffCommentAnnotationGroup>) =>
266 item.type === "diff" ? renderHeaderMetadata(item.fileDiff) : null,
267 }
268 : {})}
269 {...(renderCodeViewFooter ? { renderCodeViewFooter } : {})}
270 items={items}
271 selectedLines={selectedLines}
272 onSelectedLinesChange={setSelectedLines}
273 onRevealSearchMatch={(item) => onRevealSearchMatch(item.id)}
274 options={{
275 ...options,
276 enableGutterUtility: draft === null,
277 enableLineSelection: draft === null,
278 onGutterUtilityClick: beginComment,
279 }}
280 renderHeaderFilenameSuffix={(item) =>
281 item.type === "diff" ? renderHeaderFilenameSuffix(item.fileDiff) : null
282 }
283 renderHeaderPrefix={(item) =>
284 item.type === "diff"
285 ? renderHeaderPrefix(item.fileDiff, item.id, item.collapsed === true)
286 : null
287 }
288 renderAnnotation={(annotation) => {
289 const hasDraft = annotation.metadata.entries.some((entry) => entry.kind === "draft");
290 return (
291 <div
292 className={hasDraft ? "py-1" : "divide-y divide-border/30 border-y border-border/30"}
293 >
294 {annotation.metadata.entries.map((entry) => (
295 <DiffCommentAnnotation
296 key={entry.id}
297 kind={entry.kind}
298 rangeLabel={entry.rangeLabel}
299 text={entry.kind === "draft" ? draftText : entry.text}
300 onTextChange={setDraftText}
301 onCancel={() => removeEntry(entry.id)}
302 onComment={(text) => submitEntry(entry.id, text)}
303 onDelete={() => removeEntry(entry.id)}
304 />
305 ))}
306 </div>
307 );
308 }}
309 />
310 );
311}