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