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

reviewCommentSelection.ts

443 lines13.5 KB

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