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

reviewCommentSelection.ts

326 lines9.6 KB

1import { useSyncExternalStore } from "react";
2​
3import type { ReviewRenderableLineRow } from "./reviewModel";
4​
5export interface ReviewCommentTarget {
6 readonly sectionId: string;
7 readonly sectionTitle: string;
8 readonly filePath: string;
9 readonly lines: ReadonlyArray<ReviewRenderableLineRow>;
10 readonly startIndex: number;
11 readonly endIndex: number;
13​
14export interface ReviewInlineComment {
15 readonly id: string;
16 readonly sectionId: string;
17 readonly sectionTitle: string;
18 readonly filePath: string;
19 readonly startIndex: number;
20 readonly endIndex: number;
21 readonly rangeLabel: string;
22 readonly text: string;
23 readonly diff: string;
24 readonly fenceLanguage?: string;
26​
27export type ReviewCommentMessageSegment =
28 | {
29 readonly kind: "text";
30 readonly id: string;
31 readonly text: string;
32 }
33 | {
34 readonly kind: "review-comment";
35 readonly comment: ReviewInlineComment;
36 };
37​
38let currentTarget: ReviewCommentTarget | null = null;
39const listeners = new Set<() => void>();
40const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b([^>]*)>\s*([\s\S]*?)<\/review_comment>/g;
41const REVIEW_COMMENT_ATTRIBUTE_PATTERN = /([a-zA-Z][a-zA-Z0-9_-]*)="([^"]*)"/g;
42const REVIEW_COMMENT_FENCE_PATTERN = /(`{3,})([^\s`]*)[^\n]*\n([\s\S]*?)\n\1/g;
43​
44function emitChange() {
45 listeners.forEach((listener) => listener());
47​
48export function subscribeReviewCommentTarget(listener: () => void): () => void {
49 listeners.add(listener);
50 return () => {
51 listeners.delete(listener);
52 };
54​
55export function getReviewCommentTarget(): ReviewCommentTarget | null {
56 return currentTarget;
58​
59export function setReviewCommentTarget(target: ReviewCommentTarget | null) {
60 currentTarget = target;
61 emitChange();
63​
64export function clearReviewCommentTarget() {
65 currentTarget = null;
66 emitChange();
68​
69export function useReviewCommentTarget(): ReviewCommentTarget | null {
70 return useSyncExternalStore(
71 subscribeReviewCommentTarget,
72 getReviewCommentTarget,
73 getReviewCommentTarget,
74 );
76​
77export function getSelectedReviewCommentLines(
78 target: ReviewCommentTarget,
79): ReadonlyArray<ReviewRenderableLineRow> {
80 return target.lines.slice(target.startIndex, target.endIndex + 1);
82​
83export function getReviewUnifiedLineNumber(line: ReviewRenderableLineRow): number | null {
84 return line.newLineNumber ?? line.oldLineNumber;
86​
87export function getReviewChangeMarker(change: ReviewRenderableLineRow["change"]): string {
88 if (change === "add") return "+";
89 if (change === "delete") return "-";
90 return " ";
92​
93export function buildReviewCommentTarget(
94 target: Pick<ReviewCommentTarget, "sectionId" | "sectionTitle" | "filePath" | "lines">,
95 anchorIndex: number,
96 lineIndex: number,
97): ReviewCommentTarget {
98 return {
99 sectionId: target.sectionId,
100 sectionTitle: target.sectionTitle,
101 filePath: target.filePath,
102 lines: target.lines,
103 startIndex: Math.min(anchorIndex, lineIndex),
104 endIndex: Math.max(anchorIndex, lineIndex),
105 };
107​
108export function formatReviewSelectedRangeLabel(target: ReviewCommentTarget): string {
109 const lines = getSelectedReviewCommentLines(target);
110 const firstLine = lines[0]!;
111 const lastLine = lines[lines.length - 1]!;
112 const firstNumber = getReviewUnifiedLineNumber(firstLine);
113 const lastNumber = getReviewUnifiedLineNumber(lastLine);
114​
115 if (firstNumber === null || lastNumber === null) {
116 return lines.length === 1 ? "line" : `${lines.length} lines`;
117 }
118​
119 const firstMarker = getReviewChangeMarker(firstLine.change).trim();
120 const consistentMarker =
121 lines.every((line) => line.change === firstLine.change) && firstMarker.length > 0
122 ? getReviewChangeMarker(firstLine.change)
123 : "";
124​
125 if (firstNumber === lastNumber) {
126 return `${consistentMarker}${firstNumber}`;
127 }
128​
129 return `${consistentMarker}${firstNumber} to ${consistentMarker}${lastNumber}`;
131​
132function getDiffHunkRange(
133 selectedLines: ReadonlyArray<ReviewRenderableLineRow>,
134 key: "oldLineNumber" | "newLineNumber",
135): {
136 readonly start: number;
137 readonly count: number;
138} {
139 const numberedLines = selectedLines.filter((line) => line[key] !== null);
140 if (numberedLines.length === 0) {
141 return { start: 0, count: 0 };
142 }
143​
144 return {
145 start: numberedLines[0]![key] ?? 0,
146 count: numberedLines.length,
147 };
149​
150function formatReviewSelectedDiff(target: ReviewCommentTarget): string {
151 const selectedLines = getSelectedReviewCommentLines(target);
152 const oldRange = getDiffHunkRange(selectedLines, "oldLineNumber");
153 const newRange = getDiffHunkRange(selectedLines, "newLineNumber");
154 const diffBody = selectedLines
155 .map((line) => `${getReviewChangeMarker(line.change)}${line.content}`)
156 .join("\n");
157​
158 return [
159 `@@ -${oldRange.start},${oldRange.count} +${newRange.start},${newRange.count} @@`,
160 diffBody.length > 0 ? diffBody : " ",
161 ].join("\n");
163​
164function escapeReviewCommentAttribute(value: string): string {
165 return value
166 .replace(/&/g, "&amp;")
167 .replace(/"/g, "&quot;")
168 .replace(/</g, "&lt;")
169 .replace(/>/g, "&gt;");
171​
172function unescapeReviewCommentAttribute(value: string): string {
173 return value
174 .replace(/&lt;/g, "<")
175 .replace(/&gt;/g, ">")
176 .replace(/&quot;/g, '"')
177 .replace(/&amp;/g, "&");
179​
180function readReviewCommentAttributes(rawAttributes: string): Record<string, string> {
181 const attributes: Record<string, string> = {};
182 for (const match of rawAttributes.matchAll(REVIEW_COMMENT_ATTRIBUTE_PATTERN)) {
183 attributes[match[1]!] = unescapeReviewCommentAttribute(match[2] ?? "");
184 }
185 return attributes;
187​
188function readNonNegativeInteger(value: string | undefined): number | null {
189 if (value === undefined || !/^\d+$/.test(value)) {
190 return null;
191 }
192 return Number(value);
194​
195function extractReviewCommentBody(rawBody: string): {
196 text: string;
197 language: string;
198 contents: string;
199} {
200 const matches = Array.from(rawBody.matchAll(REVIEW_COMMENT_FENCE_PATTERN));
201 const match = matches.at(-1);
202 const fenceIndex = match?.index;
203 return {
204 text: rawBody.slice(0, fenceIndex ?? rawBody.length).trim(),
205 language: match?.[2]?.trim() || "diff",
206 contents: match?.[3] ?? "",
207 };
209​
210function parseReviewInlineComment(
211 rawAttributes: string,
212 rawBody: string,
213 index: number,
214): ReviewInlineComment | null {
215 const attributes = readReviewCommentAttributes(rawAttributes);
216 const startIndex = readNonNegativeInteger(attributes.startIndex);
217 const endIndex = readNonNegativeInteger(attributes.endIndex);
218 const filePath = attributes.filePath?.trim();
219 const sectionId = attributes.sectionId?.trim();
220 if (!filePath || !sectionId || startIndex === null || endIndex === null) {
221 return null;
222 }
223 const body = extractReviewCommentBody(rawBody);
224​
225 return {
226 id: `review-comment:${index}:${sectionId}:${filePath}:${startIndex}:${endIndex}`,
227 sectionId,
228 sectionTitle: attributes.sectionTitle?.trim() || "Review",
229 filePath,
230 startIndex: Math.min(startIndex, endIndex),
231 endIndex: Math.max(startIndex, endIndex),
232 rangeLabel: attributes.rangeLabel?.trim() || "line",
233 text: body.text,
234 diff: body.contents,
235 fenceLanguage: body.language,
236 };
238​
239export function formatReviewCommentContext(target: ReviewCommentTarget, comment: string): string {
240 const rangeLabel = formatReviewSelectedRangeLabel(target);
241 const diff = formatReviewSelectedDiff(target);
242 const longestBacktickRun = Math.max(
243 0,
244 ...Array.from(diff.matchAll(/`+/g), (match) => match[0].length),
245 );
246 const fence = "`".repeat(Math.max(3, longestBacktickRun + 1));
247 return [
248 [
249 "<review_comment",
250 ` sectionId="${escapeReviewCommentAttribute(target.sectionId)}"`,
251 ` sectionTitle="${escapeReviewCommentAttribute(target.sectionTitle)}"`,
252 ` filePath="${escapeReviewCommentAttribute(target.filePath)}"`,
253 ` startIndex="${target.startIndex}"`,
254 ` endIndex="${target.endIndex}"`,
255 ` rangeLabel="${escapeReviewCommentAttribute(rangeLabel)}"`,
256 ">",
257 ].join(""),
258 comment.trim(),
259 `${fence}diff`,
260 diff,
261 fence,
262 "</review_comment>",
263 ].join("\n");
265​
266export function countReviewCommentContexts(value: string): number {
267 return Array.from(value.matchAll(/<review_comment\b/g)).length;
269​
270export function parseReviewInlineComments(value: string): ReadonlyArray<ReviewInlineComment> {
271 const comments: ReviewInlineComment[] = [];
272 for (const [index, match] of Array.from(value.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)).entries()) {
273 const comment = parseReviewInlineComment(match[1] ?? "", match[2] ?? "", index);
274 if (!comment) {
275 continue;
276 }
277​
278 comments.push(comment);
279 }
280 return comments;
282​
283export function parseReviewCommentMessageSegments(
284 value: string,
285): ReadonlyArray<ReviewCommentMessageSegment> {
286 const segments: ReviewCommentMessageSegment[] = [];
287 let cursor = 0;
288 let parsedCommentIndex = 0;
289​
290 for (const match of value.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)) {
291 const matchIndex = match.index ?? 0;
292 const beforeText = value.slice(cursor, matchIndex);
293 if (beforeText.length > 0) {
294 segments.push({
295 kind: "text",
296 id: `review-comment-text:${cursor}`,
297 text: beforeText,
298 });
299 }
300​
301 const comment = parseReviewInlineComment(match[1] ?? "", match[2] ?? "", parsedCommentIndex);
302 if (comment) {
303 segments.push({ kind: "review-comment", comment });
304 parsedCommentIndex += 1;
305 } else {
306 segments.push({
307 kind: "text",
308 id: `review-comment-invalid:${matchIndex}`,
309 text: match[0],
310 });
311 }
312​
313 cursor = matchIndex + match[0].length;
314 }
315​
316 const rest = value.slice(cursor);
317 if (rest.length > 0) {
318 segments.push({
319 kind: "text",
320 id: `review-comment-text:${cursor}`,
321 text: rest,
322 });
323 }
324​
325 return segments;