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 const id = nextFileCommentId();
229 const filePath = resolveFileDiffPath(item.fileDiff);
230 const comment = buildDiffReviewComment({
231 id,
232 sectionId,
233 sectionTitle,
234 filePath,
235 fileDiff: item.fileDiff,
236 range,
237 text: "",
238 });
239 if (!comment) return;
240 setDraftText("");
241 setDraft({
242 fileKey: item.id,
243 filePath,
244 previousFilePath: resolveFileDiffPreviousPath(item.fileDiff),
245 annotation: {
246 side: annotationSide(range),
247 lineNumber: range.end,
248 metadata: {
249 entries: [{ id, kind: "draft", range, rangeLabel: comment.rangeLabel, text: "" }],
250 },
251 },
252 });
253 };
254
255 return (
256 <StyledDiffCodeView<DiffCommentAnnotationGroup>
257 key={codeViewKey}
258 {...(viewerRef ? { viewerRef } : {})}
259 {...(className ? { className } : {})}
260 {...(unsafeCSSExtra ? { unsafeCSSExtra } : {})}
261 {...(renderHeaderMetadata
262 ? {
263 renderHeaderMetadata: (item: CodeViewItem<DiffCommentAnnotationGroup>) =>
264 item.type === "diff" ? renderHeaderMetadata(item.fileDiff) : null,
265 }
266 : {})}
267 {...(renderCodeViewFooter ? { renderCodeViewFooter } : {})}
268 items={items}
269 selectedLines={selectedLines}
270 onSelectedLinesChange={setSelectedLines}
271 onRevealSearchMatch={(item) => onRevealSearchMatch(item.id)}
272 options={{
273 ...options,
274 enableGutterUtility: draft === null,
275 enableLineSelection: draft === null,
276 onGutterUtilityClick: beginComment,
277 }}
278 renderHeaderFilenameSuffix={(item) =>
279 item.type === "diff" ? renderHeaderFilenameSuffix(item.fileDiff) : null
280 }
281 renderHeaderPrefix={(item) =>
282 item.type === "diff"
283 ? renderHeaderPrefix(item.fileDiff, item.id, item.collapsed === true)
284 : null
285 }
286 renderAnnotation={(...[annotation]) => {
287 const hasDraft = annotation.metadata.entries.some((entry) => entry.kind === "draft");
288 return (
289 <div
290 className={hasDraft ? "py-1" : "divide-y divide-border/30 border-y border-border/30"}
291 >
292 {annotation.metadata.entries.map((entry) => (
293 <DiffCommentAnnotation
294 key={entry.id}
295 kind={entry.kind}
296 rangeLabel={entry.rangeLabel}
297 text={entry.kind === "draft" ? draftText : entry.text}
298 onTextChange={setDraftText}
299 onCancel={() => removeEntry(entry.id)}
300 onComment={(text) => submitEntry(entry.id, text)}
301 onDelete={() => removeEntry(entry.id)}
302 />
303 ))}
304 </div>
305 );
306 }}
307 />
308 );
309}