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