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

AnnotatableCodeView.tsx

291 lines9.2 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 { 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 onRevealSearchMatch: (fileKey: string) => void;
100​
101interface DiffSelectionContext {
102 item: CodeViewItem<DiffCommentAnnotationGroup>;
104​
105export function AnnotatableCodeView({
106 codeViewKey,
107 files,
108 sectionId,
109 sectionTitle,
110 composerDraftTarget,
111 options,
112 viewerRef,
113 className,
114 renderCodeViewFooter,
115 unsafeCSSExtra,
116 renderHeaderMetadata,
117 renderHeaderFilenameSuffix,
118 renderHeaderPrefix,
119 onRevealSearchMatch,
120}: AnnotatableCodeViewProps) {
121 const addReviewComment = useComposerDraftStore((store) => store.addReviewComment);
122 const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment);
123 const reviewComments = useComposerDraftStore(
124 (store) => store.getComposerDraft(composerDraftTarget)?.reviewComments ?? EMPTY_REVIEW_COMMENTS,
125 );
126 const [selectedLines, setSelectedLines] = useState<{
127 id: string;
128 range: SelectedLineRange;
129 } | null>(null);
130 const [draft, setDraft] = useState<{
131 fileKey: string;
132 annotation: DiffCommentLineAnnotation;
133 } | null>(null);
134 const [draftText, setDraftText] = useState("");
135​
136 const filesByKey = new Map(files.map((file) => [file.fileKey, file]));
137 const items: CodeViewDiffItem<DiffCommentAnnotationGroup>[] = files.map(
138 ({ fileDiff, filePath, fileKey, fileVersion, collapsed }) => {
139 const persisted = reviewComments
140 .filter(
141 (comment) =>
142 comment.sectionId === sectionId &&
143 comment.filePath === filePath &&
144 (comment.fenceLanguage ?? "diff") === "diff",
145 )
146 .reduce<DiffCommentLineAnnotation[]>((annotations, comment) => {
147 const range = restoreDiffReviewCommentRange(fileDiff, comment);
148 if (!range) return annotations;
149 return appendAnnotationEntry(annotations, range, {
150 id: comment.id,
151 kind: "comment",
152 range,
153 rangeLabel: comment.rangeLabel,
154 text: comment.text,
155 });
156 }, []);
157 const annotations = 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 );
176​
177 const removeEntry = (entryId: string) => {
178 setSelectedLines(null);
179 if (draft?.annotation.metadata.entries.some((entry) => entry.id === entryId)) {
180 setDraft(null);
181 setDraftText("");
182 } else {
183 removeReviewComment(composerDraftTarget, entryId);
184 }
185 };
186​
187 const submitEntry = (entryId: string, text: string) => {
188 const entry = draft?.annotation.metadata.entries.find((candidate) => candidate.id === entryId);
189 const file = draft ? filesByKey.get(draft.fileKey) : undefined;
190 if (!entry || !file) return;
191 const comment = buildDiffReviewComment({
192 id: entry.id,
193 sectionId,
194 sectionTitle,
195 filePath: file.filePath,
196 fileDiff: file.fileDiff,
197 range: entry.range,
198 text,
199 });
200 if (comment) addReviewComment(composerDraftTarget, comment);
201 setSelectedLines(null);
202 setDraft(null);
203 setDraftText("");
204 };
205​
206 const beginComment = (range: SelectedLineRange | null, context: DiffSelectionContext) => {
207 if (!range) return;
208 const item = context.item;
209 if (item.type !== "diff") return;
210 // Read from the item, not the file list, so the compiled callback keeps its identity
211 // as patches arrive; the viewer re-applies its options whenever it changes.
212 const id = nextFileCommentId();
213 const comment = buildDiffReviewComment({
214 id,
215 sectionId,
216 sectionTitle,
217 filePath: resolveFileDiffPath(item.fileDiff),
218 fileDiff: item.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​
236 const hasOpenComment = draft !== null;
237 return (
238 <StyledDiffCodeView<DiffCommentAnnotationGroup>
239 key={codeViewKey}
240 {...(viewerRef ? { viewerRef } : {})}
241 {...(className ? { className } : {})}
242 {...(unsafeCSSExtra ? { unsafeCSSExtra } : {})}
243 {...(renderHeaderMetadata
244 ? {
245 renderHeaderMetadata: (item: CodeViewItem<DiffCommentAnnotationGroup>) =>
246 item.type === "diff" ? renderHeaderMetadata(item.fileDiff) : null,
247 }
248 : {})}
249 {...(renderCodeViewFooter ? { renderCodeViewFooter } : {})}
250 items={items}
251 selectedLines={selectedLines}
252 onSelectedLinesChange={setSelectedLines}
253 onRevealSearchMatch={(item) => onRevealSearchMatch(item.id)}
254 options={{
255 ...options,
256 enableGutterUtility: !hasOpenComment,
257 enableLineSelection: !hasOpenComment,
258 onGutterUtilityClick: beginComment,
259 }}
260 renderHeaderFilenameSuffix={(item) =>
261 item.type === "diff" ? renderHeaderFilenameSuffix(item.fileDiff) : null
262 }
263 renderHeaderPrefix={(item) =>
264 item.type === "diff"
265 ? renderHeaderPrefix(item.fileDiff, item.id, item.collapsed === true)
266 : null
267 }
268 renderAnnotation={(annotation) => {
269 const hasDraft = annotation.metadata.entries.some((entry) => entry.kind === "draft");
270 return (
271 <div
272 className={hasDraft ? "py-1" : "divide-y divide-border/30 border-y border-border/30"}
273 >
274 {annotation.metadata.entries.map((entry) => (
275 <DiffCommentAnnotation
276 key={entry.id}
277 kind={entry.kind}
278 rangeLabel={entry.rangeLabel}
279 text={entry.kind === "draft" ? draftText : entry.text}
280 onTextChange={setDraftText}
281 onCancel={() => removeEntry(entry.id)}
282 onComment={(text) => submitEntry(entry.id, text)}
283 onDelete={() => removeEntry(entry.id)}
284 />
285 ))}
286 </div>
287 );
288 }}
289 />
290 );