The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { useSyncExternalStore } from "react"; |
| 2 | import type { OrchestrationMessageContext } from "@t3tools/contracts"; |
| 3 | import { |
| 4 | collectComposerContextReferences, |
| 5 | replaceComposerContextReferences, |
| 6 | } from "@t3tools/shared/composerContextReferences"; |
| 7 | |
| 8 | import type { ReviewRenderableLineRow } from "./reviewModel"; |
| 9 | import { msg } from "gt-react-native"; |
| 10 | import { m, type MessageResolver } from "../../i18n/messages"; |
| 11 | |
| 12 | export interface ReviewCommentTarget { |
| 13 | readonly sectionId: string; |
| 14 | readonly sectionTitle: string; |
| 15 | readonly filePath: string; |
| 16 | readonly lines: ReadonlyArray<ReviewRenderableLineRow>; |
| 17 | readonly startIndex: number; |
| 18 | readonly endIndex: number; |
| 19 | } |
| 20 | |
| 21 | export interface ReviewInlineComment { |
| 22 | readonly id: string; |
| 23 | readonly sectionId: string; |
| 24 | readonly sectionTitle: string; |
| 25 | readonly filePath: string; |
| 26 | readonly startIndex: number; |
| 27 | readonly endIndex: number; |
| 28 | readonly rangeLabel: string; |
| 29 | readonly text: string; |
| 30 | readonly diff: string; |
| 31 | readonly fenceLanguage?: string; |
| 32 | } |
| 33 | |
| 34 | export type ReviewCommentMessageSegment = |
| 35 | | { |
| 36 | readonly kind: "text"; |
| 37 | readonly id: string; |
| 38 | readonly text: string; |
| 39 | } |
| 40 | | { |
| 41 | readonly kind: "review-comment"; |
| 42 | readonly comment: ReviewInlineComment; |
| 43 | }; |
| 44 | |
| 45 | /** The first line of a range picked with a long press, waiting for its other end. */ |
| 46 | export interface PendingReviewCommentRange extends Pick< |
| 47 | ReviewCommentTarget, |
| 48 | "sectionId" | "sectionTitle" | "filePath" | "lines" |
| 49 | > { |
| 50 | readonly lineIndex: number; |
| 51 | readonly rowId: string; |
| 52 | } |
| 53 | |
| 54 | /** The sheet, thread and section a selection was made in, and the diff it was made over. */ |
| 55 | export interface ReviewCommentSelectionScope { |
| 56 | readonly key: string; |
| 57 | /** Compared by `===`: a git section's diff hash, or a turn's diff as answered. */ |
| 58 | readonly content: string | null; |
| 59 | } |
| 60 | |
| 61 | export interface ReviewCommentSelection { |
| 62 | readonly scope: ReviewCommentSelectionScope | null; |
| 63 | readonly target: ReviewCommentTarget | null; |
| 64 | readonly pending: PendingReviewCommentRange | null; |
| 65 | } |
| 66 | |
| 67 | const EMPTY_SELECTION: ReviewCommentSelection = { scope: null, target: null, pending: null }; |
| 68 | let selection = EMPTY_SELECTION; |
| 69 | const listeners = new Set<() => void>(); |
| 70 | const REVIEW_COMMENT_BLOCK_PATTERN = /<review_comment\b([^>]*)>\s*([\s\S]*?)<\/review_comment>/g; |
| 71 | const REVIEW_COMMENT_ATTRIBUTE_PATTERN = /([a-zA-Z][a-zA-Z0-9_-]*)="([^"]*)"/g; |
| 72 | const REVIEW_COMMENT_FENCE_PATTERN = /(`{3,})([^\s`]*)[^\n]*\n([\s\S]*?)\n\1/g; |
| 73 | |
| 74 | function setSelection(next: ReviewCommentSelection) { |
| 75 | selection = next; |
| 76 | listeners.forEach((listener) => listener()); |
| 77 | } |
| 78 | |
| 79 | function subscribeReviewCommentSelection(listener: () => void): () => void { |
| 80 | listeners.add(listener); |
| 81 | return () => { |
| 82 | listeners.delete(listener); |
| 83 | }; |
| 84 | } |
| 85 | |
| 86 | export function getReviewCommentSelection(): ReviewCommentSelection { |
| 87 | return selection; |
| 88 | } |
| 89 | |
| 90 | let lastReviewSheetId = 0; |
| 91 | |
| 92 | /** A fresh id per mounted review sheet, so reopening the sheet starts without a selection. */ |
| 93 | export function nextReviewSheetId(): number { |
| 94 | lastReviewSheetId += 1; |
| 95 | return lastReviewSheetId; |
| 96 | } |
| 97 | |
| 98 | export function reviewCommentSelectionScope( |
| 99 | sheetId: number, |
| 100 | threadKey: string | null, |
| 101 | section: { readonly id: string; readonly content: string | null } | null, |
| 102 | ): ReviewCommentSelectionScope | null { |
| 103 | return threadKey === null || section === null |
| 104 | ? null |
| 105 | : { key: JSON.stringify([sheetId, threadKey, section.id]), content: section.content }; |
| 106 | } |
| 107 | |
| 108 | function isSameScope( |
| 109 | a: ReviewCommentSelectionScope | null, |
| 110 | b: ReviewCommentSelectionScope | null, |
| 111 | ): boolean { |
| 112 | return a !== null && b !== null && a.key === b.key && a.content === b.content; |
| 113 | } |
| 114 | |
| 115 | export function setReviewCommentTarget( |
| 116 | scope: ReviewCommentSelectionScope, |
| 117 | target: ReviewCommentTarget, |
| 118 | ) { |
| 119 | setSelection({ scope, target, pending: null }); |
| 120 | } |
| 121 | |
| 122 | /** |
| 123 | * Keeps the pending range: when both ends are the same line the target is a single line, and |
| 124 | * the range still waits for a different end. |
| 125 | */ |
| 126 | export function completeReviewCommentRange( |
| 127 | scope: ReviewCommentSelectionScope, |
| 128 | target: ReviewCommentTarget, |
| 129 | ) { |
| 130 | setSelection({ |
| 131 | scope, |
| 132 | target, |
| 133 | pending: isSameScope(selection.scope, scope) ? selection.pending : null, |
| 134 | }); |
| 135 | } |
| 136 | |
| 137 | export function startReviewCommentRange( |
| 138 | scope: ReviewCommentSelectionScope, |
| 139 | pending: PendingReviewCommentRange, |
| 140 | ) { |
| 141 | setSelection({ scope, target: null, pending }); |
| 142 | } |
| 143 | |
| 144 | export function clearReviewCommentTarget() { |
| 145 | setSelection(EMPTY_SELECTION); |
| 146 | } |
| 147 | |
| 148 | /** A selection made in another sheet, thread or section, or over another diff, reads as empty. */ |
| 149 | export function selectReviewCommentSelection( |
| 150 | current: ReviewCommentSelection, |
| 151 | scope: ReviewCommentSelectionScope | null, |
| 152 | ): ReviewCommentSelection { |
| 153 | return isSameScope(current.scope, scope) ? current : EMPTY_SELECTION; |
| 154 | } |
| 155 | |
| 156 | export function useReviewCommentSelection( |
| 157 | scope: ReviewCommentSelectionScope | null, |
| 158 | ): ReviewCommentSelection { |
| 159 | return selectReviewCommentSelection( |
| 160 | useSyncExternalStore( |
| 161 | subscribeReviewCommentSelection, |
| 162 | getReviewCommentSelection, |
| 163 | getReviewCommentSelection, |
| 164 | ), |
| 165 | scope, |
| 166 | ); |
| 167 | } |
| 168 | |
| 169 | export function useReviewCommentTarget(): ReviewCommentTarget | null { |
| 170 | return useSyncExternalStore( |
| 171 | subscribeReviewCommentSelection, |
| 172 | getReviewCommentSelection, |
| 173 | getReviewCommentSelection, |
| 174 | ).target; |
| 175 | } |
| 176 | |
| 177 | export function getSelectedReviewCommentLines( |
| 178 | target: ReviewCommentTarget, |
| 179 | ): ReadonlyArray<ReviewRenderableLineRow> { |
| 180 | return target.lines.slice(target.startIndex, target.endIndex + 1); |
| 181 | } |
| 182 | |
| 183 | export function getReviewUnifiedLineNumber(line: ReviewRenderableLineRow): number | null { |
| 184 | return line.newLineNumber ?? line.oldLineNumber; |
| 185 | } |
| 186 | |
| 187 | function getReviewChangeMarker(change: ReviewRenderableLineRow["change"]): string { |
| 188 | if (change === "add") return "+"; |
| 189 | if (change === "delete") return "-"; |
| 190 | return " "; |
| 191 | } |
| 192 | |
| 193 | export function buildReviewCommentTarget( |
| 194 | target: Pick<ReviewCommentTarget, "sectionId" | "sectionTitle" | "filePath" | "lines">, |
| 195 | anchorIndex: number, |
| 196 | lineIndex: number, |
| 197 | ): ReviewCommentTarget { |
| 198 | return { |
| 199 | sectionId: target.sectionId, |
| 200 | sectionTitle: target.sectionTitle, |
| 201 | filePath: target.filePath, |
| 202 | lines: target.lines, |
| 203 | startIndex: Math.min(anchorIndex, lineIndex), |
| 204 | endIndex: Math.max(anchorIndex, lineIndex), |
| 205 | }; |
| 206 | } |
| 207 | |
| 208 | export function formatReviewSelectedRangeLabel(target: ReviewCommentTarget): string { |
| 209 | const lines = getSelectedReviewCommentLines(target); |
| 210 | const firstLine = lines[0]!; |
| 211 | const lastLine = lines[lines.length - 1]!; |
| 212 | const firstNumber = getReviewUnifiedLineNumber(firstLine); |
| 213 | const lastNumber = getReviewUnifiedLineNumber(lastLine); |
| 214 | |
| 215 | if (firstNumber === null || lastNumber === null) { |
| 216 | return lines.length === 1 ? "line" : `${lines.length} lines`; |
| 217 | } |
| 218 | |
| 219 | const firstMarker = getReviewChangeMarker(firstLine.change).trim(); |
| 220 | const consistentMarker = |
| 221 | lines.every((line) => line.change === firstLine.change) && firstMarker.length > 0 |
| 222 | ? getReviewChangeMarker(firstLine.change) |
| 223 | : ""; |
| 224 | |
| 225 | if (firstNumber === lastNumber) { |
| 226 | return `${consistentMarker}${firstNumber}`; |
| 227 | } |
| 228 | |
| 229 | return `${consistentMarker}${firstNumber} to ${consistentMarker}${lastNumber}`; |
| 230 | } |
| 231 | |
| 232 | function getDiffHunkRange( |
| 233 | selectedLines: ReadonlyArray<ReviewRenderableLineRow>, |
| 234 | key: "oldLineNumber" | "newLineNumber", |
| 235 | ): { |
| 236 | readonly start: number; |
| 237 | readonly count: number; |
| 238 | } { |
| 239 | const numberedLines = selectedLines.filter((line) => line[key] !== null); |
| 240 | if (numberedLines.length === 0) { |
| 241 | return { start: 0, count: 0 }; |
| 242 | } |
| 243 | |
| 244 | return { |
| 245 | start: numberedLines[0]![key] ?? 0, |
| 246 | count: numberedLines.length, |
| 247 | }; |
| 248 | } |
| 249 | |
| 250 | function formatReviewSelectedDiff(target: ReviewCommentTarget): string { |
| 251 | const selectedLines = getSelectedReviewCommentLines(target); |
| 252 | const oldRange = getDiffHunkRange(selectedLines, "oldLineNumber"); |
| 253 | const newRange = getDiffHunkRange(selectedLines, "newLineNumber"); |
| 254 | const diffBody = selectedLines |
| 255 | .map((line) => `${getReviewChangeMarker(line.change)}${line.content}`) |
| 256 | .join("\n"); |
| 257 | |
| 258 | return [ |
| 259 | `@@ -${oldRange.start},${oldRange.count} +${newRange.start},${newRange.count} @@`, |
| 260 | diffBody.length > 0 ? diffBody : " ", |
| 261 | ].join("\n"); |
| 262 | } |
| 263 | |
| 264 | function escapeReviewCommentAttribute(value: string): string { |
| 265 | return value |
| 266 | .replace(/&/g, "&") |
| 267 | .replace(/"/g, """) |
| 268 | .replace(/</g, "<") |
| 269 | .replace(/>/g, ">"); |
| 270 | } |
| 271 | |
| 272 | function unescapeReviewCommentAttribute(value: string): string { |
| 273 | return value |
| 274 | .replace(/</g, "<") |
| 275 | .replace(/>/g, ">") |
| 276 | .replace(/"/g, '"') |
| 277 | .replace(/&/g, "&"); |
| 278 | } |
| 279 | |
| 280 | function readReviewCommentAttributes(rawAttributes: string): Record<string, string> { |
| 281 | const attributes: Record<string, string> = {}; |
| 282 | for (const match of rawAttributes.matchAll(REVIEW_COMMENT_ATTRIBUTE_PATTERN)) { |
| 283 | attributes[match[1]!] = unescapeReviewCommentAttribute(match[2] ?? ""); |
| 284 | } |
| 285 | return attributes; |
| 286 | } |
| 287 | |
| 288 | function readNonNegativeInteger(value: string | undefined): number | null { |
| 289 | if (value === undefined || !/^\d+$/.test(value)) { |
| 290 | return null; |
| 291 | } |
| 292 | return Number(value); |
| 293 | } |
| 294 | |
| 295 | function extractReviewCommentBody(rawBody: string): { |
| 296 | text: string; |
| 297 | language: string; |
| 298 | contents: string; |
| 299 | } { |
| 300 | const matches = Array.from(rawBody.matchAll(REVIEW_COMMENT_FENCE_PATTERN)); |
| 301 | const match = matches.at(-1); |
| 302 | const fenceIndex = match?.index; |
| 303 | return { |
| 304 | text: rawBody.slice(0, fenceIndex ?? rawBody.length).trim(), |
| 305 | language: match?.[2]?.trim() || "diff", |
| 306 | contents: match?.[3] ?? "", |
| 307 | }; |
| 308 | } |
| 309 | |
| 310 | function parseReviewInlineComment( |
| 311 | rawAttributes: string, |
| 312 | rawBody: string, |
| 313 | index: number, |
| 314 | resolve: MessageResolver, |
| 315 | ): ReviewInlineComment | null { |
| 316 | const attributes = readReviewCommentAttributes(rawAttributes); |
| 317 | const startIndex = readNonNegativeInteger(attributes.startIndex); |
| 318 | const endIndex = readNonNegativeInteger(attributes.endIndex); |
| 319 | const filePath = attributes.filePath?.trim(); |
| 320 | const sectionId = attributes.sectionId?.trim(); |
| 321 | if (!filePath || !sectionId || startIndex === null || endIndex === null) { |
| 322 | return null; |
| 323 | } |
| 324 | const body = extractReviewCommentBody(rawBody); |
| 325 | |
| 326 | return { |
| 327 | id: `review-comment:${index}:${sectionId}:${filePath}:${startIndex}:${endIndex}`, |
| 328 | sectionId, |
| 329 | sectionTitle: |
| 330 | attributes.sectionTitle?.trim() || |
| 331 | resolve(msg("Review", { $context: "review comment section" })), |
| 332 | filePath, |
| 333 | startIndex: Math.min(startIndex, endIndex), |
| 334 | endIndex: Math.max(startIndex, endIndex), |
| 335 | rangeLabel: |
| 336 | attributes.rangeLabel?.trim() || resolve(msg("line", { $context: "review comment range" })), |
| 337 | text: body.text, |
| 338 | diff: body.contents, |
| 339 | fenceLanguage: body.language, |
| 340 | }; |
| 341 | } |
| 342 | |
| 343 | export function formatReviewCommentContext(target: ReviewCommentTarget, comment: string): string { |
| 344 | const rangeLabel = formatReviewSelectedRangeLabel(target); |
| 345 | const diff = formatReviewSelectedDiff(target); |
| 346 | const longestBacktickRun = Math.max( |
| 347 | 0, |
| 348 | ...Array.from(diff.matchAll(/`+/g), (match) => match[0].length), |
| 349 | ); |
| 350 | const fence = "`".repeat(Math.max(3, longestBacktickRun + 1)); |
| 351 | return [ |
| 352 | [ |
| 353 | "<review_comment", |
| 354 | ` sectionId="${escapeReviewCommentAttribute(target.sectionId)}"`, |
| 355 | ` sectionTitle="${escapeReviewCommentAttribute(target.sectionTitle)}"`, |
| 356 | ` filePath="${escapeReviewCommentAttribute(target.filePath)}"`, |
| 357 | ` startIndex="${target.startIndex}"`, |
| 358 | ` endIndex="${target.endIndex}"`, |
| 359 | ` rangeLabel="${escapeReviewCommentAttribute(rangeLabel)}"`, |
| 360 | ">", |
| 361 | ].join(""), |
| 362 | comment.trim(), |
| 363 | `${fence}diff`, |
| 364 | diff, |
| 365 | fence, |
| 366 | "</review_comment>", |
| 367 | ].join("\n"); |
| 368 | } |
| 369 | |
| 370 | export 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: record.rangeLabel, |
| 421 | text: record.text, |
| 422 | diff: record.diff, |
| 423 | ...(record.fenceLanguage !== undefined ? { fenceLanguage: record.fenceLanguage } : {}), |
| 424 | }); |
| 425 | } |
| 426 | return comments; |
| 427 | } |
| 428 | |
| 429 | export 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; |
| 483 | } |