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 { CodeView, type CodeViewHandle, type CodeViewProps } from "@pierre/diffs/react";
10import type { ScopedThreadRef } from "@v12/contracts";
11import { useCallback, useMemo, useState, type ReactNode, type Ref } from "react";
12
13import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
14import { fnv1a32 } from "~/lib/diffRendering";
15import {
16 buildDiffReviewComment,
17 restoreDiffReviewCommentRange,
18 type ReviewCommentContext,
19} from "~/reviewCommentContext";
20
21import { LocalCommentAnnotation } from "../files/LocalCommentAnnotation";
22import { nextFileCommentId } from "../files/fileCommentAnnotations";
23
24interface DiffCommentAnnotationEntry {
25 id: string;
26 kind: "draft" | "comment";
27 range: SelectedLineRange;
28 rangeLabel: string;
29 text: string;
30}
31
32interface DiffCommentAnnotationGroup {
33 entries: DiffCommentAnnotationEntry[];
34}
35
36type DiffCommentLineAnnotation = DiffLineAnnotation<DiffCommentAnnotationGroup>;
37export type AnnotatableCodeViewHandle = CodeViewHandle<DiffCommentAnnotationGroup>;
38const EMPTY_REVIEW_COMMENTS: ReadonlyArray<ReviewCommentContext> = [];
39
40function annotationSide(range: SelectedLineRange): AnnotationSide {
41 return (range.endSide ?? range.side) === "deletions" ? "deletions" : "additions";
42}
43
44function appendAnnotationEntry(
45 annotations: ReadonlyArray<DiffCommentLineAnnotation>,
46 range: SelectedLineRange,
47 entry: DiffCommentAnnotationEntry,
48): DiffCommentLineAnnotation[] {
49 const side = annotationSide(range);
50 const annotationIndex = annotations.findIndex(
51 (annotation) => annotation.side === side && annotation.lineNumber === range.end,
52 );
53 if (annotationIndex < 0) {
54 return [
55 ...annotations,
56 {
57 side,
58 lineNumber: range.end,
59 metadata: { entries: [entry] },
60 },
61 ];
62 }
63 return annotations.map((annotation, index) =>
64 index === annotationIndex
65 ? {
66 ...annotation,
67 metadata: { entries: [...annotation.metadata.entries, entry] },
68 }
69 : annotation,
70 );
71}
72
73interface AnnotatableCodeViewProps {
74 files: ReadonlyArray<{
75 fileDiff: FileDiffMetadata;
76 filePath: string;
77 fileKey: string;
78 collapsed: boolean;
79 }>;
80 sectionId: string;
81 sectionTitle: string;
82 composerDraftTarget: ScopedThreadRef | DraftId;
83 options: NonNullable<CodeViewProps<DiffCommentAnnotationGroup>["options"]>;
84 viewerRef?: Ref<AnnotatableCodeViewHandle>;
85 className?: string;
86 renderHeaderPrefix: (
87 fileDiff: FileDiffMetadata,
88 fileKey: string,
89 collapsed: boolean,
90 ) => ReactNode;
91}
92
93interface DiffSelectionContext {
94 item: CodeViewItem<DiffCommentAnnotationGroup>;
95}
96
97export function AnnotatableCodeView({
98 files,
99 sectionId,
100 sectionTitle,
101 composerDraftTarget,
102 options,
103 viewerRef,
104 className,
105 renderHeaderPrefix,
106}: AnnotatableCodeViewProps) {
107 const addReviewComment = useComposerDraftStore((store) => store.addReviewComment);
108 const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment);
109 const reviewComments = useComposerDraftStore(
110 (store) => store.getComposerDraft(composerDraftTarget)?.reviewComments ?? EMPTY_REVIEW_COMMENTS,
111 );
112 const [selectedLines, setSelectedLines] = useState<{
113 id: string;
114 range: SelectedLineRange;
115 } | null>(null);
116 const [draft, setDraft] = useState<{
117 fileKey: string;
118 annotation: DiffCommentLineAnnotation;
119 } | null>(null);
120
121 const filesByKey = useMemo(() => new Map(files.map((file) => [file.fileKey, file])), [files]);
122 const items = useMemo<CodeViewDiffItem<DiffCommentAnnotationGroup>[]>(
123 () =>
124 files.map(({ fileDiff, filePath, fileKey, collapsed }) => {
125 const persisted = reviewComments
126 .filter(
127 (comment) =>
128 comment.sectionId === sectionId &&
129 comment.filePath === filePath &&
130 (comment.fenceLanguage ?? "diff") === "diff",
131 )
132 .reduce<DiffCommentLineAnnotation[]>((annotations, comment) => {
133 const range = restoreDiffReviewCommentRange(fileDiff, comment);
134 if (!range) return annotations;
135 return appendAnnotationEntry(annotations, range, {
136 id: comment.id,
137 kind: "comment",
138 range,
139 rangeLabel: comment.rangeLabel,
140 text: comment.text,
141 });
142 }, []);
143 const annotations =
144 draft?.fileKey === fileKey ? [...persisted, draft.annotation] : persisted;
145 return {
146 id: fileKey,
147 type: "diff",
148 fileDiff,
149 annotations,
150 collapsed,
151 version: fnv1a32(
152 `${collapsed ? "1" : "0"}:${annotations
153 .flatMap((annotation) =>
154 annotation.metadata.entries.map(
155 (entry) => `${entry.id}:${entry.rangeLabel}:${entry.text}`,
156 ),
157 )
158 .join(":")}`,
159 ),
160 };
161 }),
162 [draft, files, reviewComments, sectionId],
163 );
164
165 const removeEntry = useCallback(
166 (entryId: string) => {
167 setSelectedLines(null);
168 if (draft?.annotation.metadata.entries.some((entry) => entry.id === entryId)) {
169 setDraft(null);
170 } else {
171 removeReviewComment(composerDraftTarget, entryId);
172 }
173 },
174 [composerDraftTarget, draft, removeReviewComment],
175 );
176
177 const submitEntry = useCallback(
178 (entryId: string, text: string) => {
179 const entry = draft?.annotation.metadata.entries.find(
180 (candidate) => candidate.id === entryId,
181 );
182 const file = draft ? filesByKey.get(draft.fileKey) : undefined;
183 if (!entry || !file) return;
184 const comment = buildDiffReviewComment({
185 id: entry.id,
186 sectionId,
187 sectionTitle,
188 filePath: file.filePath,
189 fileDiff: file.fileDiff,
190 range: entry.range,
191 text,
192 });
193 if (comment) addReviewComment(composerDraftTarget, comment);
194 setSelectedLines(null);
195 setDraft(null);
196 },
197 [addReviewComment, composerDraftTarget, draft, filesByKey, sectionId, sectionTitle],
198 );
199
200 const beginComment = useCallback(
201 (range: SelectedLineRange | null, context: DiffSelectionContext) => {
202 if (!range) return;
203 const item = context.item;
204 if (item.type !== "diff") return;
205 const file = filesByKey.get(item.id);
206 if (!file) return;
207 const id = nextFileCommentId();
208 const comment = buildDiffReviewComment({
209 id,
210 sectionId,
211 sectionTitle,
212 filePath: file.filePath,
213 fileDiff: file.fileDiff,
214 range,
215 text: "",
216 });
217 if (!comment) return;
218 setDraft({
219 fileKey: item.id,
220 annotation: {
221 side: annotationSide(range),
222 lineNumber: range.end,
223 metadata: {
224 entries: [{ id, kind: "draft", range, rangeLabel: comment.rangeLabel, text: "" }],
225 },
226 },
227 });
228 },
229 [filesByKey, sectionId, sectionTitle],
230 );
231
232 const hasOpenComment = draft !== null;
233 return (
234 <CodeView<DiffCommentAnnotationGroup>
235 {...(viewerRef ? { ref: viewerRef } : {})}
236 {...(className ? { className } : {})}
237 items={items}
238 selectedLines={selectedLines}
239 onSelectedLinesChange={setSelectedLines}
240 options={{
241 ...options,
242 enableGutterUtility: !hasOpenComment,
243 enableLineSelection: !hasOpenComment,
244 onLineSelectionEnd: beginComment,
245 }}
246 renderHeaderPrefix={(item) =>
247 item.type === "diff"
248 ? renderHeaderPrefix(item.fileDiff, item.id, item.collapsed === true)
249 : null
250 }
251 renderAnnotation={(annotation) => (
252 <div className="py-1">
253 {annotation.metadata.entries.map((entry) => (
254 <LocalCommentAnnotation
255 key={entry.id}
256 kind={entry.kind}
257 rangeLabel={entry.rangeLabel}
258 text={entry.text}
259 onCancel={() => removeEntry(entry.id)}
260 onComment={(text) => submitEntry(entry.id, text)}
261 onDelete={() => removeEntry(entry.id)}
262 />
263 ))}
264 </div>
265 )}
266 />
267 );
268}