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

AnnotatableCodeView.tsx

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