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