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

AnnotatableCodeView.tsx

281 lines8.6 KB

1import type {
2 AnnotationSide,
3 CodeViewDiffItem,
4 CodeViewItem,
5 DiffLineAnnotation,
6 FileDiffMetadata,
7 SelectedLineRange,
8} from "@pierre/diffs";
9import { CodeView, type CodeViewHandle, type CodeViewProps } 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 { LocalCommentAnnotation } from "../files/LocalCommentAnnotation";
22import { nextFileCommentId } from "../files/fileCommentAnnotations";
23​
24interface DiffCommentAnnotationEntry {
25 id: string;
26 kind: "draft" | "comment";
27 range: SelectedLineRange;
28 rangeLabel: string;
29 text: string;
31​
32interface DiffCommentAnnotationGroup {
33 entries: DiffCommentAnnotationEntry[];
35​
36type DiffCommentLineAnnotation = DiffLineAnnotation<DiffCommentAnnotationGroup>;
37export type AnnotatableCodeViewHandle = CodeViewHandle<DiffCommentAnnotationGroup>;
38const EMPTY_REVIEW_COMMENTS: ReadonlyArray<ReviewCommentContext> = [];
39​
40function annotationSide(range: SelectedLineRange): AnnotationSide {
41 return (range.endSide ?? range.side) === "deletions" ? "deletions" : "additions";
43​
44function appendAnnotationEntry(
45 annotations: ReadonlyArray<DiffCommentLineAnnotation>,
46 range: SelectedLineRange,
47 entry: DiffCommentAnnotationEntry,
48): DiffCommentLineAnnotation[] {
49 const side = annotationSide(range);
50 const annotationIndex = annotations.findIndex(
51 (annotation) => annotation.side === side && annotation.lineNumber === range.end,
52 );
53 if (annotationIndex < 0) {
54 return [
55 ...annotations,
56 {
57 side,
58 lineNumber: range.end,
59 metadata: { entries: [entry] },
60 },
61 ];
62 }
63 return annotations.map((annotation, index) =>
64 index === annotationIndex
65 ? {
66 ...annotation,
67 metadata: { entries: [...annotation.metadata.entries, entry] },
68 }
69 : annotation,
70 );
72​
73interface AnnotatableCodeViewProps {
74 codeViewKey: string;
75 files: ReadonlyArray<{
76 fileDiff: FileDiffMetadata;
77 filePath: string;
78 fileKey: string;
79 collapsed: boolean;
80 }>;
81 sectionId: string;
82 sectionTitle: string;
83 composerDraftTarget: ScopedThreadRef | DraftId;
84 options: NonNullable<CodeViewProps<DiffCommentAnnotationGroup>["options"]>;
85 viewerRef?: Ref<AnnotatableCodeViewHandle>;
86 className?: string;
87 renderHeaderPrefix: (
88 fileDiff: FileDiffMetadata,
89 fileKey: string,
90 collapsed: boolean,
91 ) => ReactNode;
93​
94interface DiffSelectionContext {
95 item: CodeViewItem<DiffCommentAnnotationGroup>;
97​
98export function AnnotatableCodeView({
99 codeViewKey,
100 files,
101 sectionId,
102 sectionTitle,
103 composerDraftTarget,
104 options,
105 viewerRef,
106 className,
107 renderHeaderPrefix,
108}: AnnotatableCodeViewProps) {
109 const addReviewComment = useComposerDraftStore((store) => store.addReviewComment);
110 const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment);
111 const reviewComments = useComposerDraftStore(
112 (store) => store.getComposerDraft(composerDraftTarget)?.reviewComments ?? EMPTY_REVIEW_COMMENTS,
113 );
114 const [selectedLines, setSelectedLines] = useState<{
115 id: string;
116 range: SelectedLineRange;
117 } | null>(null);
118 const [draft, setDraft] = useState<{
119 fileKey: string;
120 annotation: DiffCommentLineAnnotation;
121 } | null>(null);
122 const [draftText, setDraftText] = useState("");
123​
124 const filesByKey = useMemo(() => new Map(files.map((file) => [file.fileKey, file])), [files]);
125 const items = useMemo<CodeViewDiffItem<DiffCommentAnnotationGroup>[]>(
126 () =>
127 files.map(({ fileDiff, filePath, fileKey, collapsed }) => {
128 const persisted = reviewComments
129 .filter(
130 (comment) =>
131 comment.sectionId === sectionId &&
132 comment.filePath === filePath &&
133 (comment.fenceLanguage ?? "diff") === "diff",
134 )
135 .reduce<DiffCommentLineAnnotation[]>((annotations, comment) => {
136 const range = restoreDiffReviewCommentRange(fileDiff, comment);
137 if (!range) return annotations;
138 return appendAnnotationEntry(annotations, range, {
139 id: comment.id,
140 kind: "comment",
141 range,
142 rangeLabel: comment.rangeLabel,
143 text: comment.text,
144 });
145 }, []);
146 const annotations =
147 draft?.fileKey === fileKey ? [...persisted, draft.annotation] : persisted;
148 return {
149 id: fileKey,
150 type: "diff",
151 fileDiff,
152 annotations,
153 collapsed,
154 version: fnv1a32(
155 `${collapsed ? "1" : "0"}:${annotations
156 .flatMap((annotation) =>
157 annotation.metadata.entries.map(
158 (entry) => `${entry.id}:${entry.rangeLabel}:${entry.text}`,
159 ),
160 )
161 .join(":")}`,
162 ),
163 };
164 }),
165 [draft, files, reviewComments, sectionId],
166 );
167​
168 const removeEntry = useCallback(
169 (entryId: string) => {
170 setSelectedLines(null);
171 if (draft?.annotation.metadata.entries.some((entry) => entry.id === entryId)) {
172 setDraft(null);
173 setDraftText("");
174 } else {
175 removeReviewComment(composerDraftTarget, entryId);
176 }
177 },
178 [composerDraftTarget, draft, removeReviewComment],
179 );
180​
181 const submitEntry = useCallback(
182 (entryId: string, text: string) => {
183 const entry = draft?.annotation.metadata.entries.find(
184 (candidate) => candidate.id === entryId,
185 );
186 const file = draft ? filesByKey.get(draft.fileKey) : undefined;
187 if (!entry || !file) return;
188 const comment = buildDiffReviewComment({
189 id: entry.id,
190 sectionId,
191 sectionTitle,
192 filePath: file.filePath,
193 fileDiff: file.fileDiff,
194 range: entry.range,
195 text,
196 });
197 if (comment) addReviewComment(composerDraftTarget, comment);
198 setSelectedLines(null);
199 setDraft(null);
200 setDraftText("");
201 },
202 [addReviewComment, composerDraftTarget, draft, filesByKey, sectionId, sectionTitle],
203 );
204​
205 const beginComment = useCallback(
206 (range: SelectedLineRange | null, context: DiffSelectionContext) => {
207 if (!range) return;
208 const item = context.item;
209 if (item.type !== "diff") return;
210 const file = filesByKey.get(item.id);
211 if (!file) return;
212 const id = nextFileCommentId();
213 const comment = buildDiffReviewComment({
214 id,
215 sectionId,
216 sectionTitle,
217 filePath: file.filePath,
218 fileDiff: file.fileDiff,
219 range,
220 text: "",
221 });
222 if (!comment) return;
223 setDraftText("");
224 setDraft({
225 fileKey: item.id,
226 annotation: {
227 side: annotationSide(range),
228 lineNumber: range.end,
229 metadata: {
230 entries: [{ id, kind: "draft", range, rangeLabel: comment.rangeLabel, text: "" }],
231 },
232 },
233 });
234 },
235 [filesByKey, sectionId, sectionTitle],
236 );
237​
238 const hasOpenComment = draft !== null;
239 return (
240 <CodeView<DiffCommentAnnotationGroup>
241 key={codeViewKey}
242 {...(viewerRef ? { ref: viewerRef } : {})}
243 {...(className ? { className } : {})}
244 items={items}
245 selectedLines={selectedLines}
246 onSelectedLinesChange={setSelectedLines}
247 options={{
248 ...options,
249 enableGutterUtility: !hasOpenComment,
250 enableLineSelection: !hasOpenComment,
251 onGutterUtilityClick: beginComment,
252 }}
253 renderHeaderPrefix={(item) =>
254 item.type === "diff"
255 ? renderHeaderPrefix(item.fileDiff, item.id, item.collapsed === true)
256 : null
257 }
258 renderAnnotation={(annotation) => {
259 const hasDraft = annotation.metadata.entries.some((entry) => entry.kind === "draft");
260 return (
261 <div
262 className={hasDraft ? "py-1" : "divide-y divide-border/30 border-y border-border/30"}
263 >
264 {annotation.metadata.entries.map((entry) => (
265 <LocalCommentAnnotation
266 key={entry.id}
267 kind={entry.kind}
268 rangeLabel={entry.rangeLabel}
269 text={entry.kind === "draft" ? draftText : entry.text}
270 onTextChange={setDraftText}
271 onCancel={() => removeEntry(entry.id)}
272 onComment={(text) => submitEntry(entry.id, text)}
273 onDelete={() => removeEntry(entry.id)}
274 />
275 ))}
276 </div>
277 );
278 }}
279 />
280 );