Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AnnotatableCodeView.tsx

306 lines9.8 KB

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