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

AnnotatableCodeView.tsx

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