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

reviewCommentSelection.ts

473 lines14.4 KB

1import { useSyncExternalStore } from "react";
2import type { OrchestrationMessageContext } from "@t3tools/contracts";
3import {
4 collectComposerContextReferences,
5 replaceComposerContextReferences,
6} from "@t3tools/shared/composerContextReferences";
7​
8import type { ReviewRenderableLineRow } from "./reviewModel";
9​
10export interface ReviewCommentTarget {
11 readonly sectionId: string;
12 readonly sectionTitle: string;
13 readonly filePath: string;
14 readonly lines: ReadonlyArray<ReviewRenderableLineRow>;
15 readonly startIndex: number;
16 readonly endIndex: number;
18​
19export interface ReviewInlineComment {
20 readonly id: string;
21 readonly sectionId: string;
22 readonly sectionTitle: string;
23 readonly filePath: string;
24 readonly startIndex: number;
25 readonly endIndex: number;
26 readonly rangeLabel: string;
27 readonly text: string;
28 readonly diff: string;
29 readonly fenceLanguage?: string;
31​
32export type ReviewCommentMessageSegment =
33 | {
34 readonly kind: "text";
35 readonly id: string;
36 readonly text: string;
37 }
38 | {
39 readonly kind: "review-comment";
40 readonly comment: ReviewInlineComment;
41 };
42​
43/** The first line of a range picked with a long press, waiting for its other end. */
44export interface PendingReviewCommentRange extends Pick<
45 ReviewCommentTarget,
46 "sectionId" | "sectionTitle" | "filePath" | "lines"
47> {
48 readonly lineIndex: number;
49 readonly rowId: string;
51​
52/** The sheet, thread and section a selection was made in, and the diff it was made over. */
53export interface ReviewCommentSelectionScope {
54 readonly key: string;
55 /** Compared by `===`: a git section's diff hash, or a turn's diff as answered. */
56 readonly content: string | null;
58​
59export interface ReviewCommentSelection {
60 readonly scope: ReviewCommentSelectionScope | null;
61 readonly target: ReviewCommentTarget | null;
62 readonly pending: PendingReviewCommentRange | null;
64​
65const EMPTY_SELECTION: ReviewCommentSelection = { scope: null, target: null, pending: null };
66let selection = EMPTY_SELECTION;
67const listeners = new Set<() => void>();
68const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b([^>]*)>\s*([\s\S]*?)<\/review_comment>/g;
69const REVIEW_COMMENT_ATTRIBUTE_PATTERN = /([a-zA-Z][a-zA-Z0-9_-]*)="([^"]*)"/g;
70const REVIEW_COMMENT_FENCE_PATTERN = /(`{3,})([^\s`]*)[^\n]*\n([\s\S]*?)\n\1/g;
71​
72function setSelection(next: ReviewCommentSelection) {
73 selection = next;
74 listeners.forEach((listener) => listener());
76​
77function subscribeReviewCommentSelection(listener: () => void): () => void {
78 listeners.add(listener);
79 return () => {
80 listeners.delete(listener);
81 };
83​
84export function getReviewCommentSelection(): ReviewCommentSelection {
85 return selection;
87​
88let lastReviewSheetId = 0;
89​
90/** A fresh id per mounted review sheet, so reopening the sheet starts without a selection. */
91export function nextReviewSheetId(): number {
92 lastReviewSheetId += 1;
93 return lastReviewSheetId;
95​
96export function reviewCommentSelectionScope(
97 sheetId: number,
98 threadKey: string | null,
99 section: { readonly id: string; readonly content: string | null } | null,
100): ReviewCommentSelectionScope | null {
101 return threadKey === null || section === null
102 ? null
103 : { key: JSON.stringify([sheetId, threadKey, section.id]), content: section.content };
105​
106function isSameScope(
107 a: ReviewCommentSelectionScope | null,
108 b: ReviewCommentSelectionScope | null,
109): boolean {
110 return a !== null && b !== null && a.key === b.key && a.content === b.content;
112​
113export function setReviewCommentTarget(
114 scope: ReviewCommentSelectionScope,
115 target: ReviewCommentTarget,
116) {
117 setSelection({ scope, target, pending: null });
119​
120/**
121 * Keeps the pending range: when both ends are the same line the target is a single line, and
122 * the range still waits for a different end.
123 */
124export function completeReviewCommentRange(
125 scope: ReviewCommentSelectionScope,
126 target: ReviewCommentTarget,
127) {
128 setSelection({
129 scope,
130 target,
131 pending: isSameScope(selection.scope, scope) ? selection.pending : null,
132 });
134​
135export function startReviewCommentRange(
136 scope: ReviewCommentSelectionScope,
137 pending: PendingReviewCommentRange,
138) {
139 setSelection({ scope, target: null, pending });
141​
142export function clearReviewCommentTarget() {
143 setSelection(EMPTY_SELECTION);
145​
146/** A selection made in another sheet, thread or section, or over another diff, reads as empty. */
147export function selectReviewCommentSelection(
148 current: ReviewCommentSelection,
149 scope: ReviewCommentSelectionScope | null,
150): ReviewCommentSelection {
151 return isSameScope(current.scope, scope) ? current : EMPTY_SELECTION;
153​
154export function useReviewCommentSelection(
155 scope: ReviewCommentSelectionScope | null,
156): ReviewCommentSelection {
157 return selectReviewCommentSelection(
158 useSyncExternalStore(
159 subscribeReviewCommentSelection,
160 getReviewCommentSelection,
161 getReviewCommentSelection,
162 ),
163 scope,
164 );
166​
167export function useReviewCommentTarget(): ReviewCommentTarget | null {
168 return useSyncExternalStore(
169 subscribeReviewCommentSelection,
170 getReviewCommentSelection,
171 getReviewCommentSelection,
172 ).target;
174​
175export function getSelectedReviewCommentLines(
176 target: ReviewCommentTarget,
177): ReadonlyArray<ReviewRenderableLineRow> {
178 return target.lines.slice(target.startIndex, target.endIndex + 1);
180​
181export function getReviewUnifiedLineNumber(line: ReviewRenderableLineRow): number | null {
182 return line.newLineNumber ?? line.oldLineNumber;
184​
185function getReviewChangeMarker(change: ReviewRenderableLineRow["change"]): string {
186 if (change === "add") return "+";
187 if (change === "delete") return "-";
188 return " ";
190​
191export function buildReviewCommentTarget(
192 target: Pick<ReviewCommentTarget, "sectionId" | "sectionTitle" | "filePath" | "lines">,
193 anchorIndex: number,
194 lineIndex: number,
195): ReviewCommentTarget {
196 return {
197 sectionId: target.sectionId,
198 sectionTitle: target.sectionTitle,
199 filePath: target.filePath,
200 lines: target.lines,
201 startIndex: Math.min(anchorIndex, lineIndex),
202 endIndex: Math.max(anchorIndex, lineIndex),
203 };
205​
206export function formatReviewSelectedRangeLabel(target: ReviewCommentTarget): string {
207 const lines = getSelectedReviewCommentLines(target);
208 const firstLine = lines[0]!;
209 const lastLine = lines[lines.length - 1]!;
210 const firstNumber = getReviewUnifiedLineNumber(firstLine);
211 const lastNumber = getReviewUnifiedLineNumber(lastLine);
212​
213 if (firstNumber === null || lastNumber === null) {
214 return lines.length === 1 ? "line" : `${lines.length} lines`;
215 }
216​
217 const firstMarker = getReviewChangeMarker(firstLine.change).trim();
218 const consistentMarker =
219 lines.every((line) => line.change === firstLine.change) && firstMarker.length > 0
220 ? getReviewChangeMarker(firstLine.change)
221 : "";
222​
223 if (firstNumber === lastNumber) {
224 return `${consistentMarker}${firstNumber}`;
225 }
226​
227 return `${consistentMarker}${firstNumber} to ${consistentMarker}${lastNumber}`;
229​
230function getDiffHunkRange(
231 selectedLines: ReadonlyArray<ReviewRenderableLineRow>,
232 key: "oldLineNumber" | "newLineNumber",
233): {
234 readonly start: number;
235 readonly count: number;
236} {
237 const numberedLines = selectedLines.filter((line) => line[key] !== null);
238 if (numberedLines.length === 0) {
239 return { start: 0, count: 0 };
240 }
241​
242 return {
243 start: numberedLines[0]![key] ?? 0,
244 count: numberedLines.length,
245 };
247​
248function formatReviewSelectedDiff(target: ReviewCommentTarget): string {
249 const selectedLines = getSelectedReviewCommentLines(target);
250 const oldRange = getDiffHunkRange(selectedLines, "oldLineNumber");
251 const newRange = getDiffHunkRange(selectedLines, "newLineNumber");
252 const diffBody = selectedLines
253 .map((line) => `${getReviewChangeMarker(line.change)}${line.content}`)
254 .join("\n");
255​
256 return [
257 `@@ -${oldRange.start},${oldRange.count} +${newRange.start},${newRange.count} @@`,
258 diffBody.length > 0 ? diffBody : " ",
259 ].join("\n");
261​
262function escapeReviewCommentAttribute(value: string): string {
263 return value
264 .replace(/&/g, "&amp;")
265 .replace(/"/g, "&quot;")
266 .replace(/</g, "&lt;")
267 .replace(/>/g, "&gt;");
269​
270function unescapeReviewCommentAttribute(value: string): string {
271 return value
272 .replace(/&lt;/g, "<")
273 .replace(/&gt;/g, ">")
274 .replace(/&quot;/g, '"')
275 .replace(/&amp;/g, "&");
277​
278function readReviewCommentAttributes(rawAttributes: string): Record<string, string> {
279 const attributes: Record<string, string> = {};
280 for (const match of rawAttributes.matchAll(REVIEW_COMMENT_ATTRIBUTE_PATTERN)) {
281 attributes[match[1]!] = unescapeReviewCommentAttribute(match[2] ?? "");
282 }
283 return attributes;
285​
286function readNonNegativeInteger(value: string | undefined): number | null {
287 if (value === undefined || !/^\d+$/.test(value)) {
288 return null;
289 }
290 return Number(value);
292​
293function extractReviewCommentBody(rawBody: string): {
294 text: string;
295 language: string;
296 contents: string;
297} {
298 const matches = Array.from(rawBody.matchAll(REVIEW_COMMENT_FENCE_PATTERN));
299 const match = matches.at(-1);
300 const fenceIndex = match?.index;
301 return {
302 text: rawBody.slice(0, fenceIndex ?? rawBody.length).trim(),
303 language: match?.[2]?.trim() || "diff",
304 contents: match?.[3] ?? "",
305 };
307​
308function parseReviewInlineComment(
309 rawAttributes: string,
310 rawBody: string,
311 index: number,
312): ReviewInlineComment | null {
313 const attributes = readReviewCommentAttributes(rawAttributes);
314 const startIndex = readNonNegativeInteger(attributes.startIndex);
315 const endIndex = readNonNegativeInteger(attributes.endIndex);
316 const filePath = attributes.filePath?.trim();
317 const sectionId = attributes.sectionId?.trim();
318 if (!filePath || !sectionId || startIndex === null || endIndex === null) {
319 return null;
320 }
321 const body = extractReviewCommentBody(rawBody);
322​
323 return {
324 id: `review-comment:${index}:${sectionId}:${filePath}:${startIndex}:${endIndex}`,
325 sectionId,
326 sectionTitle: attributes.sectionTitle?.trim() || "Review",
327 filePath,
328 startIndex: Math.min(startIndex, endIndex),
329 endIndex: Math.max(startIndex, endIndex),
330 rangeLabel: attributes.rangeLabel?.trim() || "line",
331 text: body.text,
332 diff: body.contents,
333 fenceLanguage: body.language,
334 };
336​
337export function formatReviewCommentContext(target: ReviewCommentTarget, comment: string): string {
338 const rangeLabel = formatReviewSelectedRangeLabel(target);
339 const diff = formatReviewSelectedDiff(target);
340 const longestBacktickRun = Math.max(
341 0,
342 ...Array.from(diff.matchAll(/`+/g), (match) => match[0].length),
343 );
344 const fence = "`".repeat(Math.max(3, longestBacktickRun + 1));
345 return [
346 [
347 "<review_comment",
348 ` sectionId="${escapeReviewCommentAttribute(target.sectionId)}"`,
349 ` sectionTitle="${escapeReviewCommentAttribute(target.sectionTitle)}"`,
350 ` filePath="${escapeReviewCommentAttribute(target.filePath)}"`,
351 ` startIndex="${target.startIndex}"`,
352 ` endIndex="${target.endIndex}"`,
353 ` rangeLabel="${escapeReviewCommentAttribute(rangeLabel)}"`,
354 ">",
355 ].join(""),
356 comment.trim(),
357 `${fence}diff`,
358 diff,
359 fence,
360 "</review_comment>",
361 ].join("\n");
363​
364export function parseReviewInlineComments(
365 value: string,
366 context?: OrchestrationMessageContext,
367): ReadonlyArray<ReviewInlineComment> {
368 const comments: ReviewInlineComment[] = [];
369 // Mask chip delimiters: labels containing </review_comment> would otherwise truncate the block.
370 const masked = replaceComposerContextReferences(value, (reference) =>
371 " ".repeat(reference.source.length),
372 );
373 for (const [index, match] of Array.from(
374 masked.matchAll(REVIEW_COMMENT_BLOCK_PATTERN),
375 ).entries()) {
376 const matchIndex = match.index;
377 const raw = value.slice(matchIndex, matchIndex + match[0].length);
378 const attributeStart = "<review_comment".length;
379 const attributeEnd = attributeStart + (match[1]?.length ?? 0);
380 const comment = parseReviewInlineComment(
381 raw.slice(attributeStart, attributeEnd),
382 raw.slice(attributeEnd + 1, -"</review_comment>".length),
383 index,
384 );
385 if (!comment) {
386 continue;
387 }
388​
389 comments.push(comment);
390 }
391 const referencedIds = new Set(
392 collectComposerContextReferences(value)
393 .filter((reference) => reference.kind === "review-comment")
394 .map((reference) => reference.contextId),
395 );
396 for (const record of context?.records ?? []) {
397 if (
398 record.kind !== "review-comment" ||
399 "payload" in record ||
400 record.sectionId.startsWith("pull-request:") ||
401 !referencedIds.has(record.contextId)
402 ) {
403 continue;
404 }
405 comments.push({
406 id: record.contextId,
407 sectionId: record.sectionId,
408 sectionTitle: record.sectionTitle,
409 filePath: record.filePath,
410 startIndex: record.startIndex,
411 endIndex: record.endIndex,
412 rangeLabel: record.rangeLabel,
413 text: record.text,
414 diff: record.diff,
415 ...(record.fenceLanguage !== undefined ? { fenceLanguage: record.fenceLanguage } : {}),
416 });
417 }
418 return comments;
420​
421export function parseReviewCommentMessageSegments(
422 value: string,
423): ReadonlyArray<ReviewCommentMessageSegment> {
424 const segments: ReviewCommentMessageSegment[] = [];
425 let cursor = 0;
426 let parsedCommentIndex = 0;
427 const masked = replaceComposerContextReferences(value, (reference) =>
428 " ".repeat(reference.source.length),
429 );
430 for (const match of masked.matchAll(REVIEW_COMMENT_BLOCK_PATTERN)) {
431 const matchIndex = match.index;
432 const beforeText = value.slice(cursor, matchIndex);
433 if (beforeText.length > 0) {
434 segments.push({
435 kind: "text",
436 id: `review-comment-text:${cursor}`,
437 text: beforeText,
438 });
439 }
440​
441 const raw = value.slice(matchIndex, matchIndex + match[0].length);
442 const attributeStart = "<review_comment".length;
443 const attributeEnd = attributeStart + (match[1]?.length ?? 0);
444 const comment = parseReviewInlineComment(
445 raw.slice(attributeStart, attributeEnd),
446 raw.slice(attributeEnd + 1, -"</review_comment>".length),
447 parsedCommentIndex,
448 );
449 if (comment) {
450 segments.push({ kind: "review-comment", comment });
451 parsedCommentIndex += 1;
452 } else {
453 segments.push({
454 kind: "text",
455 id: `review-comment-invalid:${matchIndex}`,
456 text: value.slice(matchIndex, matchIndex + match[0].length),
457 });
458 }
459​
460 cursor = matchIndex + match[0].length;
461 }
462​
463 const rest = value.slice(cursor);
464 if (rest.length > 0) {
465 segments.push({
466 kind: "text",
467 id: `review-comment-text:${cursor}`,
468 text: rest,
469 });
470 }
471​
472 return segments;