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

AnnotatableCodeView.tsx

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