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