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

reviewCommentSelection.ts

483 lines15.3 KB

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