The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | EMPTY_PULL_REQUEST_DIFF_FOLDS, |
| 3 | foldAllPullRequestDiffs, |
| 4 | isFileDiffCollapsed, |
| 5 | withFileDiffFold, |
| 6 | withPullRequestDiffFold, |
| 7 | type FileDiffFoldChoices, |
| 8 | } from "@t3tools/client-runtime/pull-request-diff-fold"; |
| 9 | import { |
| 10 | parsePullRequestAnchor, |
| 11 | pullRequestDiffPathMatches, |
| 12 | pullRequestLinkCommit, |
| 13 | resolvePullRequestAnchorRange, |
| 14 | } from "@t3tools/shared/pullRequestAnchor"; |
| 15 | import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; |
| 16 | import type { |
| 17 | CodeViewItem, |
| 18 | DiffLineAnnotation, |
| 19 | FileDiffMetadata, |
| 20 | SelectedLineRange, |
| 21 | } from "@pierre/diffs"; |
| 22 | import type { CodeViewAnnotationArgs, CodeViewDiffItem } from "@pierre/diffs/react"; |
| 23 | import type { |
| 24 | EnvironmentId, |
| 25 | PullRequestDetailView, |
| 26 | PullRequestDiffSide, |
| 27 | PullRequestDiffResult, |
| 28 | PullRequestOmittedFileStat, |
| 29 | PullRequestRef, |
| 30 | PullRequestReviewPosition, |
| 31 | PullRequestReviewThread, |
| 32 | PullRequestThreadCommentsResult, |
| 33 | } from "@t3tools/contracts"; |
| 34 | import { SOURCE_CONTROL_MEDIA_ASSET } from "@t3tools/contracts"; |
| 35 | import { |
| 36 | ChevronDownIcon, |
| 37 | ChevronRightIcon, |
| 38 | Columns2Icon, |
| 39 | FlaskConicalOffIcon, |
| 40 | FolderTreeIcon, |
| 41 | InfoIcon, |
| 42 | MessageSquareOffIcon, |
| 43 | PilcrowIcon, |
| 44 | Rows3Icon, |
| 45 | Settings2Icon, |
| 46 | TextWrapIcon, |
| 47 | TriangleAlertIcon, |
| 48 | ChevronsDownUpIcon, |
| 49 | ChevronsUpDownIcon, |
| 50 | } from "lucide-react"; |
| 51 | import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-react"; |
| 52 | import { AsyncResult, Atom } from "effect/reactivity"; |
| 53 | import * as Schema from "effect/Schema"; |
| 54 | import { |
| 55 | createContext, |
| 56 | use, |
| 57 | useContext, |
| 58 | useEffect, |
| 59 | useEffectEvent, |
| 60 | useRef, |
| 61 | useState, |
| 62 | type ReactNode, |
| 63 | } from "react"; |
| 64 | import { msg, T, useGT, useMessages, Var } from "gt-react"; |
| 65 | |
| 66 | import { m, type MessageResolver } from "~/i18n/messages"; |
| 67 | |
| 68 | import { observeIntersection } from "~/lib/observeIntersection"; |
| 69 | import { useLocalStorage } from "~/hooks/useLocalStorage"; |
| 70 | import { useClientSettings, updateClientSettings } from "~/hooks/useSettings"; |
| 71 | import { useRenderedAppearance } from "~/hooks/useTheme"; |
| 72 | import { areAllDiffFilesCollapsed } from "~/lib/diffCollapse"; |
| 73 | import { |
| 74 | pullRequestFindingKey, |
| 75 | type PullRequestChatSubject, |
| 76 | type PullRequestFinding, |
| 77 | } from "./pullRequestDetail.logic"; |
| 78 | import { |
| 79 | canEditPullRequestComment, |
| 80 | canResolvePullRequestThread, |
| 81 | } from "@t3tools/client-runtime/pull-request-editing"; |
| 82 | import { fileDiffRows } from "@t3tools/client-runtime/review-guide-tour"; |
| 83 | import { isTestChangedFile } from "@t3tools/shared/changedFileKind"; |
| 84 | import { orderDiffFilesForReview } from "@t3tools/client-runtime/diff-file-order"; |
| 85 | import { isWorkspaceImagePreviewPath } from "@t3tools/shared/mediaPreview"; |
| 86 | import { |
| 87 | buildFileDiffIdentityKey, |
| 88 | buildFileDiffRenderKey, |
| 89 | fnv1a32, |
| 90 | getDiffLineStat, |
| 91 | getRenderablePatch, |
| 92 | resolveDiffThemeName, |
| 93 | resolveFileDiffPath, |
| 94 | resolveFileDiffPreviousPath, |
| 95 | type RenderablePatch, |
| 96 | } from "~/lib/diffRendering"; |
| 97 | import { APP_BASE_NAME } from "~/branding"; |
| 98 | import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting"; |
| 99 | import { cn } from "~/lib/utils"; |
| 100 | import { createPullRequestDiffFileContentsLoader } from "~/lib/diffFileContents"; |
| 101 | import { |
| 102 | buildDiffReviewComment, |
| 103 | diffReviewSelectionId, |
| 104 | resolveDiffReviewAnchor, |
| 105 | type ReviewCommentContext, |
| 106 | } from "~/reviewCommentContext"; |
| 107 | import { pullRequestEnvironment } from "~/state/pullRequests"; |
| 108 | import { useEnvironmentQuery } from "~/state/query"; |
| 109 | import { useAtomCommand } from "~/state/use-atom-command"; |
| 110 | |
| 111 | import { ChatMarkdownAssetImage } from "../chat/ChatMarkdownMedia"; |
| 112 | import { DiffPanelLoadingState } from "../DiffPanelShell"; |
| 113 | import { useDiffWorkerPool } from "../DiffWorkerPoolProvider"; |
| 114 | import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation"; |
| 115 | import { DiffFileTree } from "../diffs/DiffFileTree"; |
| 116 | import { FileExplorerPane } from "../files/FileExplorerPane"; |
| 117 | import { useCodeViewFileReveal } from "../diffs/useCodeViewFileReveal"; |
| 118 | import { useHideTestFiles } from "../diffs/useHideTestFiles"; |
| 119 | import { diffFileTreeEntries } from "../diffs/diffFileTree.logic"; |
| 120 | import { StyledDiffCodeView } from "../diffs/StyledDiffCodeView"; |
| 121 | import { Button } from "../ui/button"; |
| 122 | import { Checkbox } from "../ui/checkbox"; |
| 123 | import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; |
| 124 | import { |
| 125 | DropdownMenu, |
| 126 | DropdownMenuCheckboxItem, |
| 127 | DropdownMenuContent, |
| 128 | DropdownMenuItem, |
| 129 | DropdownMenuRadioGroup, |
| 130 | DropdownMenuRadioItem, |
| 131 | DropdownMenuSeparator, |
| 132 | DropdownMenuTrigger, |
| 133 | } from "../ui/menu"; |
| 134 | import { toastManager } from "../ui/toast"; |
| 135 | import { Toggle, ToggleGroup } from "../ui/toggle-group"; |
| 136 | import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; |
| 137 | import { |
| 138 | getReviewPositionAnchor, |
| 139 | InlineReviewThreads, |
| 140 | PendingReviewCommentCard, |
| 141 | ReviewThreadCard, |
| 142 | toViewerSide, |
| 143 | } from "./PullRequestReviewAnnotation"; |
| 144 | import { pullRequestCompletionScope } from "./PullRequestMarkdownTextarea"; |
| 145 | import { getFileViewedRange, isLineInFileDiff } from "./pullRequestDiff.logic"; |
| 146 | import { PullRequestDiffStat, PullRequestMetaLine } from "./pullRequestPresentation"; |
| 147 | import { PullRequestDiffUnavailableState } from "./PullRequestDiffUnavailableState"; |
| 148 | import { usePullRequestFilesViewed } from "./usePullRequestFilesViewed"; |
| 149 | import { hasCutLines } from "@t3tools/shared/diffCutLines"; |
| 150 | import { CUT_LINES_CSS, markCutLineNotes } from "./cutLineNotes"; |
| 151 | import { |
| 152 | nextPendingReviewCommentId, |
| 153 | pullRequestReviewKey, |
| 154 | usePendingReviewComments, |
| 155 | usePullRequestReviewStore, |
| 156 | type PendingReviewComment, |
| 157 | } from "./pullRequestReviewStore"; |
| 158 | |
| 159 | import { changeRequestTermKind } from "./changeRequestTerm"; |
| 160 | |
| 161 | interface ReviewAnnotationGroup { |
| 162 | readonly threads: ReadonlyArray<PullRequestReviewThread>; |
| 163 | readonly pending: ReadonlyArray<PendingReviewComment>; |
| 164 | readonly draft: boolean; |
| 165 | readonly image?: { readonly url: string; readonly path: string }; |
| 166 | readonly withheld?: { readonly path: string; readonly status: WithheldFileStatus }; |
| 167 | } |
| 168 | |
| 169 | type WithheldFileStatus = "idle" | "loading" | "error" | "empty"; |
| 170 | |
| 171 | type PullRequestDiffTarget = Parameters<typeof pullRequestEnvironment.diff>[0]; |
| 172 | |
| 173 | // One read per withheld file the reader asked for, so only that file's diff crosses the wire. |
| 174 | const withheldFileDiffsAtom = Atom.family((key: string) => { |
| 175 | const { environmentId, input, paths } = JSON.parse(key) as { |
| 176 | readonly environmentId: PullRequestDiffTarget["environmentId"]; |
| 177 | readonly input: PullRequestDiffTarget["input"]; |
| 178 | readonly paths: ReadonlyArray<string>; |
| 179 | }; |
| 180 | return Atom.make((get) => |
| 181 | paths.map((path) => |
| 182 | get(pullRequestEnvironment.diff({ environmentId, input: { ...input, path } })), |
| 183 | ), |
| 184 | ).pipe(Atom.withLabel(`pull-request-withheld-file-diffs:${key}`)); |
| 185 | }); |
| 186 | |
| 187 | const NO_PATHS: ReadonlyArray<string> = []; |
| 188 | |
| 189 | type ReviewAnnotation = DiffLineAnnotation<ReviewAnnotationGroup>; |
| 190 | |
| 191 | const COMMIT_PAGE_SIZE = 10; |
| 192 | |
| 193 | const PULL_REQUEST_FILE_TREE_STORAGE_KEY = "t3code.pullRequestFileTreeOpen"; |
| 194 | |
| 195 | interface DiffSlice { |
| 196 | readonly source: PullRequestDiffResult; |
| 197 | readonly cursor: string | null; |
| 198 | readonly patch: string; |
| 199 | readonly truncated: boolean; |
| 200 | readonly nextCursor: string | null; |
| 201 | readonly omittedFileStats: ReadonlyArray<PullRequestOmittedFileStat>; |
| 202 | } |
| 203 | |
| 204 | // Show host counts outside the shadow root; hunk totals are zero when hosts withhold hunks. |
| 205 | const REPLACE_FILE_COUNTS_CSS = ` |
| 206 | [data-diffs-header] [data-additions-count], |
| 207 | [data-diffs-header] [data-deletions-count] { |
| 208 | display: none !important; |
| 209 | }`; |
| 210 | |
| 211 | const NO_SLICES: ReadonlyArray<DiffSlice> = []; |
| 212 | |
| 213 | // Query results outlive the panel's slices, so their parses survive closing and reopening |
| 214 | // without retaining anything beyond the query cache's lifetime. |
| 215 | const sliceParses = new WeakMap<PullRequestDiffResult, Map<string, RenderablePatch | null>>(); |
| 216 | // Cached parses keep a raw patch's reason untranslated; the view resolves it in the UI language. |
| 217 | const keepMessage = ((message: string) => message) as MessageResolver; |
| 218 | |
| 219 | function parseSlice(slice: DiffSlice, cacheKey: string, ignoreWhitespace: boolean) { |
| 220 | let parses = sliceParses.get(slice.source); |
| 221 | if (parses === undefined) { |
| 222 | parses = new Map(); |
| 223 | sliceParses.set(slice.source, parses); |
| 224 | } |
| 225 | if (parses.has(cacheKey)) return parses.get(cacheKey) ?? null; |
| 226 | const parsed = getRenderablePatch( |
| 227 | slice.patch, |
| 228 | cacheKey, |
| 229 | { compactPartialHunkOffsets: true, ignoreWhitespace }, |
| 230 | keepMessage, |
| 231 | ); |
| 232 | parses.set(cacheKey, parsed); |
| 233 | return parsed; |
| 234 | } |
| 235 | |
| 236 | type DiffModel = { |
| 237 | readonly parsedSlices: ReadonlyArray<RenderablePatch | null>; |
| 238 | readonly loadedFiles: ReadonlyArray<Extract<RenderablePatch, { kind: "files" }>["files"][number]>; |
| 239 | readonly sourceFileStats: ReadonlyMap<string, ReturnType<typeof getDiffLineStat>>; |
| 240 | }; |
| 241 | const diffModels = new WeakMap<ReadonlyArray<DiffSlice>, Map<string, DiffModel>>(); |
| 242 | const patchHashes = new WeakMap<DiffSlice, number>(); |
| 243 | |
| 244 | // Hashing, ordering and counting every file of a huge pull request costs a second, and the tab |
| 245 | // renders far more often than its slices change, so the model is kept per slice list. |
| 246 | function diffModel( |
| 247 | slices: ReadonlyArray<DiffSlice>, |
| 248 | keyPrefix: string, |
| 249 | ignoreWhitespace: boolean, |
| 250 | ): DiffModel { |
| 251 | let models = diffModels.get(slices); |
| 252 | if (models === undefined) diffModels.set(slices, (models = new Map())); |
| 253 | const cached = models.get(keyPrefix); |
| 254 | if (cached !== undefined) return cached; |
| 255 | const parsedSlices = slices.map((slice) => { |
| 256 | let hash = patchHashes.get(slice); |
| 257 | if (hash === undefined) patchHashes.set(slice, (hash = fnv1a32(slice.patch))); |
| 258 | // The cache key carries the theme, which the tokenizer caches against, and the patch's |
| 259 | // hash: a refreshed page reuses its cursor, so position alone would return a stale parse. |
| 260 | return parseSlice(slice, `${keyPrefix}:${slice.cursor ?? "first"}:${hash}`, ignoreWhitespace); |
| 261 | }); |
| 262 | const model: DiffModel = { |
| 263 | parsedSlices, |
| 264 | loadedFiles: orderDiffFilesForReview( |
| 265 | parsedSlices.flatMap((parsed) => (parsed?.kind === "files" ? parsed.files : [])), |
| 266 | resolveFileDiffPath, |
| 267 | ), |
| 268 | sourceFileStats: new Map( |
| 269 | parsedSlices.flatMap((parsed) => |
| 270 | parsed?.kind === "files" |
| 271 | ? parsed.files.map( |
| 272 | (file, index) => |
| 273 | [ |
| 274 | buildFileDiffRenderKey(file), |
| 275 | getDiffLineStat([parsed.sourceFiles[index] ?? file]), |
| 276 | ] as const, |
| 277 | ) |
| 278 | : [], |
| 279 | ), |
| 280 | ), |
| 281 | }; |
| 282 | models.set(keyPrefix, model); |
| 283 | return model; |
| 284 | } |
| 285 | |
| 286 | const threadsByPathCache = new WeakMap< |
| 287 | ReadonlyArray<PullRequestReviewThread>, |
| 288 | ReadonlyMap<string, ReadonlyArray<PullRequestReviewThread>> |
| 289 | >(); |
| 290 | |
| 291 | function reviewThreadsByPath(threads: ReadonlyArray<PullRequestReviewThread>) { |
| 292 | let byPath = threadsByPathCache.get(threads); |
| 293 | if (byPath === undefined) { |
| 294 | const grouped = new Map<string, PullRequestReviewThread[]>(); |
| 295 | for (const thread of threads) { |
| 296 | const list = grouped.get(thread.path); |
| 297 | if (list) list.push(thread); |
| 298 | else grouped.set(thread.path, [thread]); |
| 299 | } |
| 300 | threadsByPathCache.set(threads, (byPath = grouped)); |
| 301 | } |
| 302 | return byPath; |
| 303 | } |
| 304 | |
| 305 | interface FileViewedToggleState { |
| 306 | readonly enabled: boolean; |
| 307 | readonly isViewed: (path: string) => boolean; |
| 308 | readonly isStale: (path: string) => boolean; |
| 309 | readonly setFileViewed: (fileKey: string, viewed: boolean, extendRange: boolean) => void; |
| 310 | } |
| 311 | |
| 312 | // Context updates viewed toggles without invalidating memoized header portals. |
| 313 | const FileViewedToggleContext = createContext<FileViewedToggleState | null>(null); |
| 314 | |
| 315 | function FileViewedToggle({ |
| 316 | fileKey, |
| 317 | path, |
| 318 | stat, |
| 319 | }: { |
| 320 | readonly fileKey: string; |
| 321 | readonly path: string; |
| 322 | readonly stat: ReactNode; |
| 323 | }) { |
| 324 | const gt = useGT(); |
| 325 | const viewedFiles = use(FileViewedToggleContext); |
| 326 | if (viewedFiles === null || !viewedFiles.enabled) return stat; |
| 327 | const viewed = viewedFiles.isViewed(path); |
| 328 | const stale = viewedFiles.isStale(path); |
| 329 | return ( |
| 330 | <span className="flex items-center gap-3"> |
| 331 | {stat} |
| 332 | <label |
| 333 | data-viewed-toggle="" |
| 334 | className="flex h-8 w-18 shrink-0 cursor-pointer select-none items-center gap-1.5 text-2xs text-muted-foreground" |
| 335 | onClick={(event) => event.stopPropagation()} |
| 336 | > |
| 337 | <Checkbox |
| 338 | aria-label={ |
| 339 | stale |
| 340 | ? gt("Changed", { $context: "file changed since viewed" }) |
| 341 | : gt("Viewed", { $context: "file marked as viewed" }) |
| 342 | } |
| 343 | checked={viewed} |
| 344 | onCheckedChange={(next, details) => |
| 345 | viewedFiles.setFileViewed( |
| 346 | fileKey, |
| 347 | next === true, |
| 348 | "shiftKey" in details.event && details.event.shiftKey === true, |
| 349 | ) |
| 350 | } |
| 351 | /> |
| 352 | {stale ? ( |
| 353 | <Tooltip> |
| 354 | <TooltipTrigger render={<span className="text-warning-foreground" />}> |
| 355 | <T context="file changed since viewed">Changed</T> |
| 356 | </TooltipTrigger> |
| 357 | <TooltipPopup side="bottom"> |
| 358 | <T>This file has been pushed to since you marked it viewed.</T> |
| 359 | </TooltipPopup> |
| 360 | </Tooltip> |
| 361 | ) : ( |
| 362 | <span className="@max-xs:hidden"> |
| 363 | <T context="file marked as viewed">Viewed</T> |
| 364 | </span> |
| 365 | )} |
| 366 | </label> |
| 367 | </span> |
| 368 | ); |
| 369 | } |
| 370 | |
| 371 | interface MutableAnnotationGroup { |
| 372 | readonly side: PullRequestDiffSide; |
| 373 | readonly line: number; |
| 374 | readonly threads: PullRequestReviewThread[]; |
| 375 | readonly pending: PendingReviewComment[]; |
| 376 | draft: boolean; |
| 377 | } |
| 378 | |
| 379 | interface DraftAnchor { |
| 380 | readonly fileKey: string; |
| 381 | readonly path: string; |
| 382 | readonly oldPath: string | null; |
| 383 | readonly position: PullRequestReviewPosition; |
| 384 | readonly startPosition?: PullRequestReviewPosition; |
| 385 | readonly range: SelectedLineRange; |
| 386 | } |
| 387 | |
| 388 | export interface PullRequestAgentSelectionInput { |
| 389 | readonly comment: ReviewCommentContext; |
| 390 | readonly request: string; |
| 391 | } |
| 392 | |
| 393 | // A test's fold belongs to the file even when filtering or a refresh replaces its viewer item. |
| 394 | function buildFileDiffFoldKey(fileDiff: FileDiffMetadata): string { |
| 395 | return isTestChangedFile(resolveFileDiffPath(fileDiff)) |
| 396 | ? buildFileDiffIdentityKey(fileDiff) |
| 397 | : buildFileDiffRenderKey(fileDiff); |
| 398 | } |
| 399 | |
| 400 | function isRemovedLine(fileDiff: FileDiffMetadata, oldLine: number): boolean { |
| 401 | return fileDiff.hunks.some((hunk) => { |
| 402 | let next = hunk.deletionStart; |
| 403 | return hunk.hunkContent.some((content) => { |
| 404 | const count = content.type === "context" ? content.lines : content.deletions; |
| 405 | const removed = content.type === "change" && oldLine >= next && oldLine < next + count; |
| 406 | next += count; |
| 407 | return removed; |
| 408 | }); |
| 409 | }); |
| 410 | } |
| 411 | |
| 412 | function PullRequestCodeTab({ |
| 413 | scrollerRef, |
| 414 | environmentId, |
| 415 | reference, |
| 416 | detail, |
| 417 | selectedCommitOid, |
| 418 | onSelectedCommitChange, |
| 419 | pendingFinding, |
| 420 | fixFindingLabel: requestedFixFindingLabel, |
| 421 | onFixFinding, |
| 422 | onAddToChat, |
| 423 | onAddToAgentSelection, |
| 424 | onRefresh, |
| 425 | refreshToken = 0, |
| 426 | backgroundRefreshToken = 0, |
| 427 | revealRequest = null, |
| 428 | revealUrl, |
| 429 | onRevealSettled, |
| 430 | }: { |
| 431 | scrollerRef: (node: HTMLDivElement | null) => void; |
| 432 | environmentId: EnvironmentId; |
| 433 | reference: PullRequestRef; |
| 434 | detail: PullRequestDetailView; |
| 435 | selectedCommitOid: string | null; |
| 436 | onSelectedCommitChange: (oid: string | null) => void; |
| 437 | pendingFinding?: string | null; |
| 438 | fixFindingLabel?: string; |
| 439 | onFixFinding?: (finding: PullRequestFinding) => void; |
| 440 | /** Absent where there is no composer beside the panel to add a conversation to. */ |
| 441 | onAddToChat?: (subject: PullRequestChatSubject) => void; |
| 442 | onAddToAgentSelection?: (input: PullRequestAgentSelectionInput) => void; |
| 443 | onRefresh: () => void; |
| 444 | refreshToken?: number; |
| 445 | backgroundRefreshToken?: number; |
| 446 | /** A clicked link to a file or line range, until onRevealSettled reports it shown. */ |
| 447 | revealUrl?: string | undefined; |
| 448 | onRevealSettled?: ((revealUrl: string) => void) | undefined; |
| 449 | revealRequest?: { readonly path: string; readonly nonce: number } | null; |
| 450 | }) { |
| 451 | const gt = useGT(); |
| 452 | const messages = useMessages(); |
| 453 | const fixFindingLabel = requestedFixFindingLabel ?? gt("Fix in a thread"); |
| 454 | const resolvedTheme = useRenderedAppearance(); |
| 455 | // Initialize the shared tokenizer and workers while the diff request is still pending. |
| 456 | useDiffWorkerPool(); |
| 457 | const settings = useClientSettings((settings) => ({ |
| 458 | diffFilesCollapsed: settings.diffFilesCollapsed, |
| 459 | diffIgnoreWhitespace: settings.diffIgnoreWhitespace, |
| 460 | diffLayout: settings.diffLayout, |
| 461 | wordWrap: settings.wordWrap, |
| 462 | })); |
| 463 | const [folds, setFolds] = useState(EMPTY_PULL_REQUEST_DIFF_FOLDS); |
| 464 | const foldGroup = (path: string) => { |
| 465 | const group = isTestChangedFile(path) ? folds.test : folds.source; |
| 466 | return group.override === null && settings.diffFilesCollapsed |
| 467 | ? { ...group, override: "folded" as const } |
| 468 | : group; |
| 469 | }; |
| 470 | const setFoldChoices = ( |
| 471 | path: string, |
| 472 | update: (choices: FileDiffFoldChoices) => FileDiffFoldChoices, |
| 473 | ) => setFolds((current) => withPullRequestDiffFold(current, isTestChangedFile(path), update)); |
| 474 | const [lastViewedFileKey, setLastViewedFileKey] = useState<string | null>(null); |
| 475 | const [visibleCommitCount, setVisibleCommitCount] = useState(COMMIT_PAGE_SIZE); |
| 476 | const diffLayout = settings.diffLayout; |
| 477 | const [wordWrapOverride, setWordWrapOverride] = useState<boolean | null>(null); |
| 478 | const wordWrap = wordWrapOverride ?? settings.wordWrap; |
| 479 | const [ignoreWhitespace, setIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace); |
| 480 | const [fileTreeOpen, setFileTreeOpen] = useLocalStorage( |
| 481 | PULL_REQUEST_FILE_TREE_STORAGE_KEY, |
| 482 | false, |
| 483 | Schema.Boolean, |
| 484 | ); |
| 485 | const [hideTestFiles, setHideTestFiles] = useHideTestFiles(); |
| 486 | const [selectedLines, setSelectedLines] = useState<{ |
| 487 | id: string; |
| 488 | range: SelectedLineRange; |
| 489 | } | null>(null); |
| 490 | const [draft, setDraft] = useState<DraftAnchor | null>(null); |
| 491 | const [threadPending, setThreadPending] = useState(false); |
| 492 | const [orphansOpen, setOrphansOpen] = useState(false); |
| 493 | // Scope slices before reset to prevent using a previous pull request's data or cursor. |
| 494 | const [sliceState, setSliceState] = useState<{ |
| 495 | readonly key: string; |
| 496 | readonly cursor: string | null; |
| 497 | readonly slices: ReadonlyArray<DiffSlice>; |
| 498 | }>({ key: "", cursor: null, slices: NO_SLICES }); |
| 499 | |
| 500 | const referenceKey = pullRequestReviewKey(reference); |
| 501 | // A commit opened from the timeline or left selected across a force-push may no longer be |
| 502 | // part of the pull request; read it as "All commits" instead of requesting its diff. |
| 503 | const commit = |
| 504 | selectedCommitOid !== null && detail.commits.some((entry) => entry.oid === selectedCommitOid) |
| 505 | ? selectedCommitOid |
| 506 | : null; |
| 507 | const scopeKey = JSON.stringify([environmentId, referenceKey, commit]); |
| 508 | // The panel keeps this mounted across pull requests, so an open composer would otherwise |
| 509 | // survive the switch and attach its comment to whichever one is on screen when it is sent. |
| 510 | const [stateScopeKey, setStateScopeKey] = useState(scopeKey); |
| 511 | if (stateScopeKey !== scopeKey) { |
| 512 | setStateScopeKey(scopeKey); |
| 513 | setLastViewedFileKey(null); |
| 514 | setDraft(null); |
| 515 | setSelectedLines(null); |
| 516 | setFolds(EMPTY_PULL_REQUEST_DIFF_FOLDS); |
| 517 | setVisibleCommitCount(COMMIT_PAGE_SIZE); |
| 518 | setOrphansOpen(false); |
| 519 | setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES }); |
| 520 | } |
| 521 | |
| 522 | const loadedSlices = sliceState.key === scopeKey ? sliceState.slices : NO_SLICES; |
| 523 | const cursor = sliceState.key === scopeKey ? sliceState.cursor : null; |
| 524 | const diffQuery = useEnvironmentQuery( |
| 525 | pullRequestEnvironment.diff({ |
| 526 | environmentId, |
| 527 | input: { |
| 528 | ...reference, |
| 529 | ...(cursor === null ? {} : { cursor }), |
| 530 | ...(commit === null ? {} : { commit }), |
| 531 | }, |
| 532 | }), |
| 533 | messages, |
| 534 | ); |
| 535 | const [appliedPage, setAppliedPage] = useState<{ |
| 536 | readonly data: typeof diffQuery.data; |
| 537 | readonly cursor: string | null; |
| 538 | readonly scopeKey: string; |
| 539 | } | null>(null); |
| 540 | const data = diffQuery.data; |
| 541 | if ( |
| 542 | data !== null && |
| 543 | (appliedPage?.data !== data || |
| 544 | appliedPage.cursor !== cursor || |
| 545 | appliedPage.scopeKey !== scopeKey) |
| 546 | ) { |
| 547 | setAppliedPage({ data, cursor, scopeKey }); |
| 548 | setSliceState((previous) => { |
| 549 | const slices = previous.key === scopeKey ? previous.slices : NO_SLICES; |
| 550 | const next = { |
| 551 | source: data, |
| 552 | cursor, |
| 553 | patch: data.patch, |
| 554 | truncated: data.truncated, |
| 555 | nextCursor: data.nextCursor, |
| 556 | omittedFileStats: data.omittedFileStats ?? [], |
| 557 | }; |
| 558 | const index = slices.findIndex((slice) => slice.cursor === cursor); |
| 559 | if (index === -1) { |
| 560 | return { key: scopeKey, cursor, slices: [...slices, next] }; |
| 561 | } |
| 562 | const existing = slices[index]; |
| 563 | if ( |
| 564 | existing !== undefined && |
| 565 | existing.patch === next.patch && |
| 566 | existing.truncated === next.truncated && |
| 567 | existing.nextCursor === next.nextCursor && |
| 568 | existing.source.withheldFilesReadable === next.source.withheldFilesReadable && |
| 569 | existing.omittedFileStats.length === next.omittedFileStats.length && |
| 570 | existing.omittedFileStats.every((file, index) => { |
| 571 | const refreshed = next.omittedFileStats[index]; |
| 572 | return ( |
| 573 | refreshed !== undefined && |
| 574 | refreshed.path === file.path && |
| 575 | refreshed.additions === file.additions && |
| 576 | refreshed.deletions === file.deletions |
| 577 | ); |
| 578 | }) |
| 579 | ) { |
| 580 | return previous; |
| 581 | } |
| 582 | // Drop later slices when replacing a changed page; their cursors target the old diff. |
| 583 | return { key: scopeKey, cursor, slices: [...slices.slice(0, index), next] }; |
| 584 | }); |
| 585 | } |
| 586 | const refreshFirstDiffPage = useAtomRefresh( |
| 587 | pullRequestEnvironment.diff({ |
| 588 | environmentId, |
| 589 | input: { ...reference, ...(commit === null ? {} : { commit }) }, |
| 590 | }), |
| 591 | ); |
| 592 | const reviewKey = referenceKey; |
| 593 | const pendingComments = usePendingReviewComments(reference); |
| 594 | const addComment = usePullRequestReviewStore((store) => store.addComment); |
| 595 | const removeComment = usePullRequestReviewStore((store) => store.removeComment); |
| 596 | const replyToThread = useAtomCommand(pullRequestEnvironment.replyToThread, { |
| 597 | reportFailure: false, |
| 598 | }); |
| 599 | const setThreadResolution = useAtomCommand(pullRequestEnvironment.setThreadResolution, { |
| 600 | reportFailure: false, |
| 601 | }); |
| 602 | const updateComment = useAtomCommand(pullRequestEnvironment.updateComment, { |
| 603 | reportFailure: false, |
| 604 | }); |
| 605 | const loadThreadComments = useAtomCommand(pullRequestEnvironment.threadComments, { |
| 606 | reportFailure: false, |
| 607 | }); |
| 608 | const getDiffFileContents = useAtomCommand(pullRequestEnvironment.diffFileContents); |
| 609 | |
| 610 | const viewedFilesStore = detail.capabilities.viewedFiles; |
| 611 | const filesViewed = usePullRequestFilesViewed({ |
| 612 | environmentId, |
| 613 | reference, |
| 614 | enabled: viewedFilesStore !== undefined, |
| 615 | }); |
| 616 | const { |
| 617 | setViewed, |
| 618 | refresh: refreshFilesViewed, |
| 619 | enabled: filesViewedEnabled, |
| 620 | isViewed: isFileViewed, |
| 621 | isStale: isFileViewedStale, |
| 622 | } = filesViewed; |
| 623 | const [withheldLoads, setWithheldLoads] = useState<{ |
| 624 | readonly scope: string; |
| 625 | readonly paths: ReadonlyArray<string>; |
| 626 | /** The render key each loaded file was last shown under; a changed patch gets a new one. */ |
| 627 | readonly shownKeys: ReadonlyMap<string, string>; |
| 628 | }>({ scope: "", paths: NO_PATHS, shownKeys: new Map() }); |
| 629 | const withheldPaths = withheldLoads.scope === scopeKey ? withheldLoads.paths : NO_PATHS; |
| 630 | const withheldInput = { ...reference, ...(commit === null ? {} : { commit }) }; |
| 631 | const atomRegistry = useContext(RegistryContext); |
| 632 | const withheldFileDiff = (path: string) => |
| 633 | pullRequestEnvironment.diff({ environmentId, input: { ...withheldInput, path } }); |
| 634 | const refreshWithheldFiles = useEffectEvent(() => { |
| 635 | for (const path of withheldPaths) atomRegistry.refresh(withheldFileDiff(path)); |
| 636 | }); |
| 637 | const appliedRefreshToken = useRef(refreshToken); |
| 638 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a new refresh token clears loaded slices and refetches the first diff page and viewed files |
| 639 | useEffect(() => { |
| 640 | if (appliedRefreshToken.current === refreshToken) return; |
| 641 | appliedRefreshToken.current = refreshToken; |
| 642 | setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES }); |
| 643 | // An equal refetch keeps the answer's identity, so the emptied slices refill only if the |
| 644 | // applied page is forgotten too. |
| 645 | setAppliedPage(null); |
| 646 | refreshFirstDiffPage(); |
| 647 | refreshWithheldFiles(); |
| 648 | refreshFilesViewed(); |
| 649 | }, [refreshToken, scopeKey, refreshFirstDiffPage, refreshFilesViewed]); |
| 650 | const appliedBackgroundRefreshToken = useRef(backgroundRefreshToken); |
| 651 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a background refresh token refetches the first diff page and viewed files while keeping slices |
| 652 | useEffect(() => { |
| 653 | if (appliedBackgroundRefreshToken.current === backgroundRefreshToken) return; |
| 654 | appliedBackgroundRefreshToken.current = backgroundRefreshToken; |
| 655 | // Keeping slices mounted preserves scroll; the page merge invalidates changed pages. |
| 656 | setSliceState((previous) => ({ ...previous, cursor: null })); |
| 657 | refreshFirstDiffPage(); |
| 658 | refreshWithheldFiles(); |
| 659 | refreshFilesViewed(); |
| 660 | }, [backgroundRefreshToken, refreshFirstDiffPage, refreshFilesViewed]); |
| 661 | |
| 662 | const codeViewReveal = useCodeViewFileReveal(); |
| 663 | const answeredRevealNonce = useRef<number | null>(null); |
| 664 | |
| 665 | const loadDiffFiles = createPullRequestDiffFileContentsLoader(getDiffFileContents, { |
| 666 | environmentId, |
| 667 | reference, |
| 668 | commit, |
| 669 | cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`, |
| 670 | }); |
| 671 | const completionScope = pullRequestCompletionScope(detail, environmentId, reference); |
| 672 | const hostReview = detail.capabilities.review; |
| 673 | const review = { |
| 674 | inlineComment: hostReview.inlineComment && detail.viewerPermissions.comment, |
| 675 | reply: hostReview.reply && detail.viewerPermissions.comment, |
| 676 | resolve: hostReview.resolve && detail.viewerPermissions.resolve, |
| 677 | }; |
| 678 | const canCommentOnLines = review.inlineComment && commit === null; |
| 679 | const rangeComments = hostReview.rangeComment === true; |
| 680 | // Agent context is local, so it does not require host comment permission. |
| 681 | const canSelectLines = |
| 682 | commit === null && (review.inlineComment || onAddToAgentSelection !== undefined); |
| 683 | const { |
| 684 | parsedSlices, |
| 685 | loadedFiles: pagedFiles, |
| 686 | sourceFileStats, |
| 687 | } = diffModel(loadedSlices, `pull-request:${scopeKey}:${ignoreWhitespace}`, ignoreWhitespace); |
| 688 | const withheldResults = useAtomValue( |
| 689 | withheldFileDiffsAtom( |
| 690 | JSON.stringify({ environmentId, input: withheldInput, paths: withheldPaths }), |
| 691 | ), |
| 692 | ); |
| 693 | // A refetch keeps showing the last patch, whose lines may not exist at the new head. |
| 694 | const withheldRefetching = withheldResults.some((result) => result.waiting); |
| 695 | const withheldStatuses = new Map<string, WithheldFileStatus>(); |
| 696 | const withheldFiles = new Map<string, (typeof pagedFiles)[number]>(); |
| 697 | const cutFiles = new Set<unknown>(); |
| 698 | withheldPaths.forEach((path, index) => { |
| 699 | const result = withheldResults[index]; |
| 700 | if (result === undefined) return; |
| 701 | // A failed refresh still carries the earlier patch; show the failure instead of stale code. |
| 702 | const data = result._tag === "Failure" ? null : AsyncResult.getOrElse(result, () => null); |
| 703 | if (data === null) { |
| 704 | withheldStatuses.set(path, result._tag === "Failure" ? "error" : "loading"); |
| 705 | return; |
| 706 | } |
| 707 | const parsed = parseSlice( |
| 708 | { |
| 709 | source: data, |
| 710 | cursor: null, |
| 711 | patch: data.patch, |
| 712 | truncated: false, |
| 713 | nextCursor: null, |
| 714 | omittedFileStats: [], |
| 715 | }, |
| 716 | `pull-request:${scopeKey}:withheld:${path}`, |
| 717 | // Cut lines can match up to the cut and differ after it; hiding them would drop changes. |
| 718 | false, |
| 719 | ); |
| 720 | const file = parsed?.kind === "files" ? parsed.files[0] : undefined; |
| 721 | if (file !== undefined && file.hunks.length > 0) { |
| 722 | withheldFiles.set(path, file); |
| 723 | if (hasCutLines(data.patch)) cutFiles.add(file); |
| 724 | } else withheldStatuses.set(path, "empty"); |
| 725 | }); |
| 726 | // A withheld patch opens on first load and keeps its choice when its fold key changes. |
| 727 | const rekeyed = [...withheldFiles].flatMap(([path, file]) => { |
| 728 | const key = buildFileDiffFoldKey(file); |
| 729 | return withheldLoads.shownKeys.get(path) === key ? [] : [[path, key] as const]; |
| 730 | }); |
| 731 | if (withheldLoads.scope === scopeKey && rekeyed.length > 0) { |
| 732 | setWithheldLoads({ |
| 733 | ...withheldLoads, |
| 734 | shownKeys: new Map([...withheldLoads.shownKeys, ...rekeyed]), |
| 735 | }); |
| 736 | for (const [path, key] of rekeyed) { |
| 737 | const shown = withheldLoads.shownKeys.get(path); |
| 738 | setFoldChoices(path, (current) => { |
| 739 | const collapsed = shown === undefined ? (current.get(key) ?? false) : current.get(shown); |
| 740 | return collapsed === undefined ? current : withFileDiffFold(current, key, collapsed); |
| 741 | }); |
| 742 | } |
| 743 | } |
| 744 | const loadedFiles = |
| 745 | withheldFiles.size === 0 |
| 746 | ? pagedFiles |
| 747 | : // A refreshed page may carry the file's patch itself now. |
| 748 | pagedFiles.map((file) => |
| 749 | file.hunks.length === 0 ? (withheldFiles.get(resolveFileDiffPath(file)) ?? file) : file, |
| 750 | ); |
| 751 | const loadWithheldFile = (path: string) => { |
| 752 | // The read is keyed without the head, so even a first load must not reuse an older one. |
| 753 | atomRegistry.refresh(withheldFileDiff(path)); |
| 754 | if (withheldPaths.includes(path)) return; |
| 755 | setWithheldLoads({ |
| 756 | scope: scopeKey, |
| 757 | paths: [...withheldPaths, path], |
| 758 | shownKeys: withheldLoads.scope === scopeKey ? withheldLoads.shownKeys : new Map(), |
| 759 | }); |
| 760 | }; |
| 761 | const linkAnchor = parsePullRequestAnchor(revealUrl); |
| 762 | const linkFile = |
| 763 | linkAnchor?.kind === "diff" |
| 764 | ? loadedFiles.find((file) => |
| 765 | pullRequestDiffPathMatches(linkAnchor.digest, resolveFileDiffPath(file)), |
| 766 | ) |
| 767 | : undefined; |
| 768 | const pendingLinkPath = linkFile ? resolveFileDiffPath(linkFile) : null; |
| 769 | // The linked file stays shown past the test-file filter after the link settles. |
| 770 | const [revealedLink, setRevealedLink] = useState<{ |
| 771 | readonly scope: string; |
| 772 | readonly path: string; |
| 773 | } | null>(null); |
| 774 | const linkPath = pendingLinkPath ?? (revealedLink?.scope === scopeKey ? revealedLink.path : null); |
| 775 | const testFileCount = loadedFiles.filter((file) => |
| 776 | isTestChangedFile(resolveFileDiffPath(file)), |
| 777 | ).length; |
| 778 | // A requested file stays visible so a jump to a hidden test still lands. |
| 779 | const files = hideTestFiles |
| 780 | ? loadedFiles.filter((file) => { |
| 781 | const path = resolveFileDiffPath(file); |
| 782 | return path === revealRequest?.path || path === linkPath || !isTestChangedFile(path); |
| 783 | }) |
| 784 | : loadedFiles; |
| 785 | const hiddenTestFileCount = loadedFiles.length - files.length; |
| 786 | const filePaths = files.map((file) => resolveFileDiffPath(file)); |
| 787 | const omittedFileStats = new Map( |
| 788 | loadedSlices.flatMap((slice) => |
| 789 | slice.omittedFileStats.map((file) => [file.path, file] as const), |
| 790 | ), |
| 791 | ); |
| 792 | const fileTreeEntries = diffFileTreeEntries(files); |
| 793 | const threadsByPath = reviewThreadsByPath(detail.reviewThreads); |
| 794 | // File membership does not guarantee a rendered hunk for the thread. |
| 795 | const placedThreadIds = (() => { |
| 796 | const placed = new Set<string>(); |
| 797 | // Commit diffs use different line coordinates; list conversations separately. |
| 798 | if (commit !== null) return placed; |
| 799 | for (const file of files) { |
| 800 | for (const thread of threadsByPath.get(resolveFileDiffPath(file)) ?? []) { |
| 801 | if (thread.line !== null && isLineInFileDiff(file, thread.side, thread.line)) { |
| 802 | placed.add(thread.id); |
| 803 | } |
| 804 | } |
| 805 | } |
| 806 | return placed; |
| 807 | })(); |
| 808 | |
| 809 | const imageRevision = commit ?? detail.headSha; |
| 810 | const rawFileUrl = sourceControlClients.find(detail.provider)?.rawFileUrl; |
| 811 | const repositoryUrl = sourceControlClients.parseChangeRequestUrl(detail.url)?.link.repositoryUrl; |
| 812 | // Hosts send no patch for an image, so its expanded row shows the file at this revision. |
| 813 | const imagePreviewUrl = (fileDiff: FileDiffMetadata, path: string) => |
| 814 | fileDiff.hunks.length === 0 && |
| 815 | fileDiff.type !== "deleted" && |
| 816 | isWorkspaceImagePreviewPath(path) && |
| 817 | imageRevision !== undefined && |
| 818 | rawFileUrl !== undefined && |
| 819 | repositoryUrl !== undefined |
| 820 | ? rawFileUrl({ repositoryUrl, sha: imageRevision, path }) |
| 821 | : null; |
| 822 | |
| 823 | const annotatedFiles = files.map((fileDiff) => { |
| 824 | const fileKey = buildFileDiffRenderKey(fileDiff); |
| 825 | const path = resolveFileDiffPath(fileDiff); |
| 826 | const groups = new Map<string, MutableAnnotationGroup>(); |
| 827 | // Stacked view draws a context row once, so its old side shares the new side's annotation. |
| 828 | const contextNewLines = new Map<number, number>(); |
| 829 | const groupAt = (anchorSide: PullRequestDiffSide, anchorLine: number) => { |
| 830 | if (anchorSide === "left" && diffLayout !== "split" && contextNewLines.size === 0) { |
| 831 | for (const row of fileDiffRows(fileDiff)) { |
| 832 | if (row.oldLine !== null && row.newLine !== null) { |
| 833 | contextNewLines.set(row.oldLine, row.newLine); |
| 834 | } |
| 835 | } |
| 836 | } |
| 837 | const contextLine = anchorSide === "left" ? contextNewLines.get(anchorLine) : undefined; |
| 838 | const side = contextLine === undefined ? anchorSide : "right"; |
| 839 | const line = contextLine ?? anchorLine; |
| 840 | const key = `${side}:${line}`; |
| 841 | const existing = groups.get(key); |
| 842 | if (existing) return existing; |
| 843 | const created: MutableAnnotationGroup = { |
| 844 | side, |
| 845 | line, |
| 846 | threads: [], |
| 847 | pending: [], |
| 848 | draft: false, |
| 849 | }; |
| 850 | groups.set(key, created); |
| 851 | return created; |
| 852 | }; |
| 853 | |
| 854 | for (const thread of threadsByPath.get(path) ?? []) { |
| 855 | if (thread.line === null || !placedThreadIds.has(thread.id)) continue; |
| 856 | groupAt(thread.side, thread.line).threads.push(thread); |
| 857 | } |
| 858 | if (commit === null) { |
| 859 | for (const comment of pendingComments) { |
| 860 | if (comment.path !== path) continue; |
| 861 | const anchor = getReviewPositionAnchor(comment.position); |
| 862 | groupAt(anchor.side, anchor.line).pending.push(comment); |
| 863 | } |
| 864 | } |
| 865 | if (draft?.fileKey === fileKey) { |
| 866 | const anchor = getReviewPositionAnchor(draft.position); |
| 867 | groupAt(anchor.side, anchor.line).draft = true; |
| 868 | } |
| 869 | |
| 870 | const annotations: ReviewAnnotation[] = [...groups.values()].map((group) => ({ |
| 871 | side: toViewerSide(group.side), |
| 872 | lineNumber: group.line, |
| 873 | metadata: { threads: group.threads, pending: group.pending, draft: group.draft }, |
| 874 | })); |
| 875 | const imageUrl = imagePreviewUrl(fileDiff, path); |
| 876 | if (imageUrl !== null) { |
| 877 | annotations.push({ |
| 878 | side: "additions", |
| 879 | lineNumber: 0, |
| 880 | metadata: { threads: [], pending: [], draft: false, image: { url: imageUrl, path } }, |
| 881 | }); |
| 882 | } else if (fileDiff.hunks.length === 0 && omittedFileStats.has(path)) { |
| 883 | annotations.push({ |
| 884 | side: "additions", |
| 885 | lineNumber: 0, |
| 886 | metadata: { |
| 887 | threads: [], |
| 888 | pending: [], |
| 889 | draft: false, |
| 890 | withheld: { path, status: withheldStatuses.get(path) ?? "idle" }, |
| 891 | }, |
| 892 | }); |
| 893 | } |
| 894 | return { |
| 895 | fileKey, |
| 896 | foldKey: buildFileDiffFoldKey(fileDiff), |
| 897 | path, |
| 898 | fileDiff, |
| 899 | annotations, |
| 900 | // The viewer redraws annotations only when their version changes. |
| 901 | annotationsVersion: fnv1a32( |
| 902 | annotations |
| 903 | .map( |
| 904 | ({ side, lineNumber, metadata }) => |
| 905 | `${side}:${lineNumber}:${metadata.image?.url ?? ""}:${metadata.withheld?.status ?? ""}:${metadata.draft ? "d" : ""}:${metadata.pending |
| 906 | .map((comment) => `${comment.id}:${comment.body}`) |
| 907 | .join(",")}:${metadata.threads |
| 908 | .map( |
| 909 | (thread) => |
| 910 | `${thread.id}:${thread.isResolved ? "r" : ""}:${ |
| 911 | thread.isOutdated ? "o" : "" |
| 912 | }:${thread.comments |
| 913 | .map( |
| 914 | (comment) => |
| 915 | `${comment.id}:${comment.author?.login ?? ""}:${comment.createdAt}:${comment.body}:${( |
| 916 | comment.reactions ?? [] |
| 917 | ) |
| 918 | .map((r) => `${r.content}:${r.count}:${r.viewerHasReacted ? "v" : ""}`) |
| 919 | .join(",")}`, |
| 920 | ) |
| 921 | .join(";")}`, |
| 922 | ) |
| 923 | .join(",")}`, |
| 924 | ) |
| 925 | .join("|"), |
| 926 | ), |
| 927 | }; |
| 928 | }); |
| 929 | |
| 930 | const nextCursor = loadedSlices.at(-1)?.nextCursor ?? null; |
| 931 | const withheldFilesReadable = loadedSlices[0]?.source.withheldFilesReadable === true; |
| 932 | const withheldContent = |
| 933 | loadedSlices.some((slice) => slice.truncated) || |
| 934 | parsedSlices.some((parsed) => parsed?.kind === "raw"); |
| 935 | // Keep the sentinel until all pages load; returning raw slices early would stop pagination. |
| 936 | const rawSlices = |
| 937 | nextCursor === null |
| 938 | ? parsedSlices.flatMap((parsed) => (parsed?.kind === "raw" ? [parsed] : [])) |
| 939 | : []; |
| 940 | const rawSlicesView = |
| 941 | files.length === 0 && rawSlices.length > 0 ? ( |
| 942 | <div className="space-y-4 px-4 py-5"> |
| 943 | {rawSlices.map((slice) => ( |
| 944 | <div key={`${slice.reason}:${slice.text.slice(0, 64)}`} className="space-y-2"> |
| 945 | <p className="text-xs text-muted-foreground">{messages(slice.reason)}</p> |
| 946 | <pre className="whitespace-pre-wrap break-words font-mono text-xs">{slice.text}</pre> |
| 947 | </div> |
| 948 | ))} |
| 949 | </div> |
| 950 | ) : null; |
| 951 | const unstructured = |
| 952 | rawSlices.length === 0 ? null : ( |
| 953 | <div className="space-y-4 border-t border-border/60 px-4 py-5"> |
| 954 | {rawSlices.map((slice) => ( |
| 955 | <div key={`${slice.reason}:${slice.text.slice(0, 64)}`} className="space-y-2"> |
| 956 | <p className="text-xs text-muted-foreground">{messages(slice.reason)}</p> |
| 957 | <pre className="whitespace-pre-wrap break-words font-mono text-xs">{slice.text}</pre> |
| 958 | </div> |
| 959 | ))} |
| 960 | </div> |
| 961 | ); |
| 962 | |
| 963 | const foldsAsViewed = (path: string) => |
| 964 | filesViewedEnabled && isFileViewed(path) && !isFileViewedStale(path); |
| 965 | const items: CodeViewDiffItem<ReviewAnnotationGroup>[] = annotatedFiles.map( |
| 966 | ({ fileKey, foldKey, path, fileDiff, annotations, annotationsVersion }) => { |
| 967 | const group = foldGroup(path); |
| 968 | const collapsed = isFileDiffCollapsed( |
| 969 | foldKey, |
| 970 | group.override, |
| 971 | group.choices, |
| 972 | foldsAsViewed(path), |
| 973 | ); |
| 974 | const viewedMark = filesViewedEnabled |
| 975 | ? `e${isFileViewed(path) ? "v" : ""}${isFileViewedStale(path) ? "s" : ""}` |
| 976 | : ""; |
| 977 | return { |
| 978 | id: fileKey, |
| 979 | type: "diff" as const, |
| 980 | fileDiff, |
| 981 | annotations, |
| 982 | collapsed, |
| 983 | version: fnv1a32(`${collapsed ? "1" : "0"}:${viewedMark}:${annotationsVersion}`), |
| 984 | }; |
| 985 | }, |
| 986 | ); |
| 987 | const fileKeys = items.map((item) => item.id); |
| 988 | const collapsedFileKeys = new Set( |
| 989 | items.filter((item) => item.collapsed === true).map((item) => item.id), |
| 990 | ); |
| 991 | const allFilesCollapsed = areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys); |
| 992 | |
| 993 | // Do not re-arm the visible sentinel after failure; it would retry indefinitely. |
| 994 | const canLoadNextSlice = |
| 995 | nextCursor !== null && |
| 996 | nextCursor !== cursor && |
| 997 | !diffQuery.isPending && |
| 998 | diffQuery.error === null; |
| 999 | const loadNextSlice = () => { |
| 1000 | if (nextCursor === null) return; |
| 1001 | setSliceState((previous) => ({ ...previous, cursor: nextCursor })); |
| 1002 | }; |
| 1003 | const sentinelRef = (node: HTMLDivElement | null) => { |
| 1004 | if (node === null || !canLoadNextSlice) return; |
| 1005 | return observeIntersection( |
| 1006 | node, |
| 1007 | (entry) => { |
| 1008 | if (entry.isIntersecting) loadNextSlice(); |
| 1009 | }, |
| 1010 | { rootMargin: "240px" }, |
| 1011 | ); |
| 1012 | }; |
| 1013 | |
| 1014 | const toggleFile = (fileKey: string) => { |
| 1015 | const file = annotatedFiles.find((file) => file.fileKey === fileKey); |
| 1016 | if (file === undefined) return; |
| 1017 | const { path, foldKey } = file; |
| 1018 | const { override } = foldGroup(path); |
| 1019 | const viewed = foldsAsViewed(path); |
| 1020 | setFoldChoices(path, (current) => |
| 1021 | withFileDiffFold(current, foldKey, !isFileDiffCollapsed(foldKey, override, current, viewed)), |
| 1022 | ); |
| 1023 | }; |
| 1024 | |
| 1025 | const setFileViewed = (fileKey: string, viewed: boolean, extendRange: boolean) => { |
| 1026 | const range = getFileViewedRange( |
| 1027 | annotatedFiles, |
| 1028 | fileKey, |
| 1029 | extendRange ? lastViewedFileKey : null, |
| 1030 | ); |
| 1031 | setLastViewedFileKey(fileKey); |
| 1032 | for (const file of range) { |
| 1033 | // A commit's diff names that commit's version of the file, not the head's. |
| 1034 | setViewed(file.path, viewed, commit === null ? file.fileDiff.newObjectId : undefined); |
| 1035 | } |
| 1036 | for (const file of range) { |
| 1037 | const collapsed = foldGroup(file.path).override === null ? undefined : viewed; |
| 1038 | setFoldChoices(file.path, (current) => withFileDiffFold(current, file.foldKey, collapsed)); |
| 1039 | } |
| 1040 | }; |
| 1041 | const fileViewedToggle = { |
| 1042 | enabled: filesViewedEnabled, |
| 1043 | isViewed: isFileViewed, |
| 1044 | isStale: isFileViewedStale, |
| 1045 | setFileViewed, |
| 1046 | }; |
| 1047 | |
| 1048 | const revealFile = (path: string, range?: SelectedLineRange) => { |
| 1049 | const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path); |
| 1050 | if (item === undefined) return; |
| 1051 | // Record the unfold even when already open, so a Viewed mark that loads later cannot fold it. |
| 1052 | setFoldChoices(path, (current) => |
| 1053 | withFileDiffFold(current, buildFileDiffFoldKey(item.fileDiff), false), |
| 1054 | ); |
| 1055 | if (range) setSelectedLines({ id: item.id, range }); |
| 1056 | codeViewReveal.request(item.id, range); |
| 1057 | }; |
| 1058 | |
| 1059 | const toggleAllFiles = () => { |
| 1060 | const shownTestKeys = annotatedFiles.flatMap((file) => |
| 1061 | isTestChangedFile(file.path) ? [file.foldKey] : [], |
| 1062 | ); |
| 1063 | setFolds((current) => |
| 1064 | foldAllPullRequestDiffs( |
| 1065 | current, |
| 1066 | allFilesCollapsed ? "expanded" : "folded", |
| 1067 | hideTestFiles ? { shownKeys: shownTestKeys } : null, |
| 1068 | ), |
| 1069 | ); |
| 1070 | }; |
| 1071 | |
| 1072 | const orderedCommits = // GitLab preserves UTC offsets, so compare instants. |
| 1073 | detail.commits.toSorted( |
| 1074 | (left, right) => Date.parse(right.committedDate) - Date.parse(left.committedDate), |
| 1075 | ); |
| 1076 | |
| 1077 | const beginComment = ( |
| 1078 | range: SelectedLineRange | null, |
| 1079 | context: { item: CodeViewItem<ReviewAnnotationGroup> }, |
| 1080 | ) => { |
| 1081 | if (!range || !canSelectLines || withheldRefetching) return; |
| 1082 | const item = context.item; |
| 1083 | if (item.type !== "diff") return; |
| 1084 | const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === item.id); |
| 1085 | if (!file) return; |
| 1086 | // On a host without ranged comments a range collapses to its last line: one that silently |
| 1087 | // lost its first line there would be worse than one line. |
| 1088 | const path = resolveFileDiffPath(file); |
| 1089 | const previousPath = resolveFileDiffPreviousPath(file); |
| 1090 | const sourceFile = parsedSlices |
| 1091 | .flatMap((slice) => (slice?.kind === "files" ? slice.sourceFiles : [])) |
| 1092 | .find((candidate) => resolveFileDiffPath(candidate) === path); |
| 1093 | const anchor = |
| 1094 | (sourceFile && resolveDiffReviewAnchor(sourceFile, range, rangeComments)) ?? |
| 1095 | resolveDiffReviewAnchor(file, range, rangeComments); |
| 1096 | if (anchor === null) return; |
| 1097 | setDraft({ |
| 1098 | fileKey: item.id, |
| 1099 | path, |
| 1100 | oldPath: previousPath === path ? null : previousPath, |
| 1101 | ...anchor, |
| 1102 | range, |
| 1103 | }); |
| 1104 | }; |
| 1105 | |
| 1106 | const finishSelection = ( |
| 1107 | anchor: DraftAnchor, |
| 1108 | text: string, |
| 1109 | onFinish: (comment: ReviewCommentContext) => void, |
| 1110 | ) => { |
| 1111 | const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === anchor.fileKey); |
| 1112 | const comment = |
| 1113 | file === undefined |
| 1114 | ? null |
| 1115 | : buildDiffReviewComment({ |
| 1116 | id: `pull-request-selection:${diffReviewSelectionId(anchor.fileKey, anchor.range)}`, |
| 1117 | sectionId: `pull-request:${detail.number}`, |
| 1118 | // oxlint-disable-next-line t3code/no-untranslated-copy -- context title sent to the agent |
| 1119 | sectionTitle: `PR #${detail.number} review`, |
| 1120 | filePath: anchor.path, |
| 1121 | fileDiff: file, |
| 1122 | range: anchor.range, |
| 1123 | text, |
| 1124 | }); |
| 1125 | setDraft(null); |
| 1126 | setSelectedLines(null); |
| 1127 | if (comment !== null) onFinish(comment); |
| 1128 | }; |
| 1129 | |
| 1130 | // Stable props preserve viewer portals during selection, typing, and review updates. |
| 1131 | const renderCodeViewFooter = () => |
| 1132 | nextCursor === null ? null : ( |
| 1133 | <div |
| 1134 | ref={sentinelRef} |
| 1135 | className="flex items-center justify-center gap-2 py-2 text-xs text-muted-foreground" |
| 1136 | > |
| 1137 | {diffQuery.error !== null ? ( |
| 1138 | <> |
| 1139 | <span> |
| 1140 | <T>The rest of this diff could not be loaded.</T> |
| 1141 | </span> |
| 1142 | <Button size="xs" variant="outline" onClick={() => diffQuery.refresh()}> |
| 1143 | <T>Retry</T> |
| 1144 | </Button> |
| 1145 | </> |
| 1146 | ) : diffQuery.isPending ? ( |
| 1147 | gt("Loading more files...") |
| 1148 | ) : null} |
| 1149 | </div> |
| 1150 | ); |
| 1151 | |
| 1152 | const renderHeaderPrefix = (item: CodeViewItem<ReviewAnnotationGroup>) => { |
| 1153 | const collapsed = item.collapsed === true; |
| 1154 | return ( |
| 1155 | <Button |
| 1156 | size="icon-micro" |
| 1157 | variant="ghost-muted" |
| 1158 | aria-expanded={!collapsed} |
| 1159 | aria-label={collapsed ? gt("Expand diff") : gt("Collapse diff")} |
| 1160 | className="mr-1" |
| 1161 | onClick={(event) => { |
| 1162 | event.stopPropagation(); |
| 1163 | toggleFile(item.id); |
| 1164 | }} |
| 1165 | > |
| 1166 | {collapsed ? ( |
| 1167 | <ChevronRightIcon className="size-4" /> |
| 1168 | ) : ( |
| 1169 | <ChevronDownIcon className="size-4" /> |
| 1170 | )} |
| 1171 | </Button> |
| 1172 | ); |
| 1173 | }; |
| 1174 | |
| 1175 | const renderHeaderMetadata = (item: CodeViewItem<ReviewAnnotationGroup>) => { |
| 1176 | if (item.type !== "diff") return null; |
| 1177 | let { additions, deletions } = sourceFileStats.get(item.id) ?? getDiffLineStat([item.fileDiff]); |
| 1178 | const path = resolveFileDiffPath(item.fileDiff); |
| 1179 | if (additions === 0 && deletions === 0) { |
| 1180 | const withheld = omittedFileStats.get(path); |
| 1181 | if (withheld) ({ additions, deletions } = withheld); |
| 1182 | } |
| 1183 | return ( |
| 1184 | <FileViewedToggle |
| 1185 | fileKey={item.id} |
| 1186 | path={path} |
| 1187 | stat={ |
| 1188 | <PullRequestDiffStat |
| 1189 | additions={additions} |
| 1190 | deletions={deletions} |
| 1191 | className="font-mono text-2xs" |
| 1192 | /> |
| 1193 | } |
| 1194 | /> |
| 1195 | ); |
| 1196 | }; |
| 1197 | |
| 1198 | const diffViewOptions = { |
| 1199 | diffStyle: diffLayout === "split" ? ("split" as const) : ("unified" as const), |
| 1200 | lineDiffType: "none" as const, |
| 1201 | overflow: wordWrap ? ("wrap" as const) : ("scroll" as const), |
| 1202 | theme: resolveDiffThemeName(resolvedTheme), |
| 1203 | preferredHighlighter: PREFERRED_HIGHLIGHTER, |
| 1204 | themeType: resolvedTheme, |
| 1205 | stickyHeaders: true, |
| 1206 | // Full contents would not match the cut lines, and would bring back the lines just cut. |
| 1207 | loadDiffFiles: (fileDiff: FileDiffMetadata) => |
| 1208 | cutFiles.has(fileDiff) |
| 1209 | ? Promise.reject( |
| 1210 | new Error(m(msg("Unchanged lines are unavailable in a file with cut lines."))), |
| 1211 | ) |
| 1212 | : loadDiffFiles(fileDiff), |
| 1213 | enableGutterUtility: canSelectLines && draft === null && !withheldRefetching, |
| 1214 | enableLineSelection: canSelectLines && draft === null && !withheldRefetching, |
| 1215 | onGutterUtilityClick: beginComment, |
| 1216 | onLineSelectionEnd: beginComment, |
| 1217 | onPostRender: (fileContainer: HTMLElement, instance: object) => { |
| 1218 | codeViewReveal.flush(); |
| 1219 | // Containers are reused across files, so the flag is set or cleared on every render. |
| 1220 | fileContainer.toggleAttribute( |
| 1221 | "data-cut-lines", |
| 1222 | "fileDiff" in instance && cutFiles.has(instance.fileDiff), |
| 1223 | ); |
| 1224 | if (withheldFiles.size > 0) markCutLineNotes(fileContainer); |
| 1225 | }, |
| 1226 | onItemCollapsedChange: ( |
| 1227 | _item: CodeViewItem<ReviewAnnotationGroup>, |
| 1228 | nextItem: CodeViewItem<ReviewAnnotationGroup>, |
| 1229 | ) => { |
| 1230 | if (nextItem.type !== "diff") return; |
| 1231 | setFoldChoices(resolveFileDiffPath(nextItem.fileDiff), (current) => |
| 1232 | withFileDiffFold( |
| 1233 | current, |
| 1234 | buildFileDiffFoldKey(nextItem.fileDiff), |
| 1235 | nextItem.collapsed === true, |
| 1236 | ), |
| 1237 | ); |
| 1238 | }, |
| 1239 | }; |
| 1240 | |
| 1241 | const runThreadCommand = async ( |
| 1242 | label: string, |
| 1243 | run: () => Promise<{ readonly _tag: string }>, |
| 1244 | ): Promise<boolean> => { |
| 1245 | if (threadPending) return false; |
| 1246 | setThreadPending(true); |
| 1247 | const result = await run(); |
| 1248 | setThreadPending(false); |
| 1249 | if (result._tag === "Failure") { |
| 1250 | toastManager.add({ type: "error", title: label }); |
| 1251 | return false; |
| 1252 | } |
| 1253 | onRefresh(); |
| 1254 | return true; |
| 1255 | }; |
| 1256 | |
| 1257 | const renderThreadCard = (thread: PullRequestReviewThread, hidden?: boolean) => ( |
| 1258 | <ReviewThreadCard |
| 1259 | // Host thread ids can collide across pull requests. |
| 1260 | key={`${reference.projectId}#${reference.number}:${thread.id}`} |
| 1261 | thread={thread} |
| 1262 | workspaceRoot={detail.workspaceRoot} |
| 1263 | canReply={review.reply} |
| 1264 | canResolve={review.resolve && canResolvePullRequestThread(detail, thread)} |
| 1265 | canReact={detail.capabilities.reactions === true} |
| 1266 | environmentId={environmentId} |
| 1267 | reference={reference} |
| 1268 | completionScope={completionScope} |
| 1269 | pending={threadPending} |
| 1270 | fixPending={pendingFinding === pullRequestFindingKey({ kind: "thread", thread })} |
| 1271 | fixLabel={fixFindingLabel} |
| 1272 | {...(onFixFinding ? { onFix: () => onFixFinding({ kind: "thread", thread }) } : {})} |
| 1273 | {...(onAddToChat |
| 1274 | ? { onAddToChat: (loaded) => onAddToChat({ kind: "thread", thread: loaded }) } |
| 1275 | : {})} |
| 1276 | onLoadMore={async (cursor): Promise<PullRequestThreadCommentsResult | null> => { |
| 1277 | const result = await loadThreadComments({ |
| 1278 | environmentId, |
| 1279 | input: { ...reference, threadId: thread.id, cursor }, |
| 1280 | }); |
| 1281 | if (result._tag === "Failure") { |
| 1282 | toastManager.add({ |
| 1283 | type: "error", |
| 1284 | title: m(msg("More comments could not be loaded")), |
| 1285 | }); |
| 1286 | return null; |
| 1287 | } |
| 1288 | return result.value; |
| 1289 | }} |
| 1290 | onReply={(body) => |
| 1291 | runThreadCommand(m(msg("Reply could not be posted")), () => |
| 1292 | replyToThread({ |
| 1293 | environmentId, |
| 1294 | input: { ...reference, threadId: thread.id, body }, |
| 1295 | }), |
| 1296 | ) |
| 1297 | } |
| 1298 | canEditComment={(comment) => |
| 1299 | canEditPullRequestComment(detail, { |
| 1300 | author: comment.author, |
| 1301 | kind: "review-comment", |
| 1302 | canEdit: comment.canEdit, |
| 1303 | }) |
| 1304 | } |
| 1305 | onEditComment={(commentId, body) => |
| 1306 | runThreadCommand(m(msg("The comment could not be saved")), () => |
| 1307 | updateComment({ |
| 1308 | environmentId, |
| 1309 | input: { ...reference, commentId, kind: "review-comment", body }, |
| 1310 | }), |
| 1311 | ) |
| 1312 | } |
| 1313 | onToggleResolved={() => |
| 1314 | void runThreadCommand(m(msg("The conversation could not be updated")), () => |
| 1315 | setThreadResolution({ |
| 1316 | environmentId, |
| 1317 | input: { ...reference, threadId: thread.id, resolved: !thread.isResolved }, |
| 1318 | }), |
| 1319 | ) |
| 1320 | } |
| 1321 | onReacted={onRefresh} |
| 1322 | {...(hidden === undefined ? {} : { hidden })} |
| 1323 | /> |
| 1324 | ); |
| 1325 | |
| 1326 | const renderAnnotation = (...[annotation]: CodeViewAnnotationArgs<ReviewAnnotationGroup>) => ( |
| 1327 | // Folded resolved conversations alone add no row, so the code reads straight through. |
| 1328 | <div className="relative font-sans text-foreground has-[>:not([data-resolved-threads])]:py-1"> |
| 1329 | {annotation.metadata.image ? ( |
| 1330 | <div className="flex justify-center p-3"> |
| 1331 | <ChatMarkdownAssetImage |
| 1332 | environmentId={environmentId} |
| 1333 | resource={{ |
| 1334 | _tag: SOURCE_CONTROL_MEDIA_ASSET, |
| 1335 | cwd: detail.workspaceRoot, |
| 1336 | url: annotation.metadata.image.url, |
| 1337 | repository: detail.repository, |
| 1338 | }} |
| 1339 | alt={annotation.metadata.image.path} |
| 1340 | /> |
| 1341 | </div> |
| 1342 | ) : null} |
| 1343 | {annotation.metadata.withheld ? ( |
| 1344 | <WithheldFileNotice |
| 1345 | {...annotation.metadata.withheld} |
| 1346 | onLoad={withheldFilesReadable ? loadWithheldFile : undefined} |
| 1347 | /> |
| 1348 | ) : null} |
| 1349 | <InlineReviewThreads threads={annotation.metadata.threads} renderThread={renderThreadCard} /> |
| 1350 | {annotation.metadata.pending.map((comment) => ( |
| 1351 | <PendingReviewCommentCard |
| 1352 | key={comment.id} |
| 1353 | comment={comment} |
| 1354 | onRemove={() => removeComment(reviewKey, comment.id)} |
| 1355 | /> |
| 1356 | ))} |
| 1357 | {annotation.metadata.draft && draft && canSelectLines ? ( |
| 1358 | <DiffCommentAnnotation |
| 1359 | environmentId={environmentId} |
| 1360 | projectId={reference.projectId} |
| 1361 | ownerKey={JSON.stringify([environmentId, reviewKey, draft])} |
| 1362 | kind="draft" |
| 1363 | rangeLabel={`${draft.path}:${getReviewPositionAnchor(draft.position).line}`} |
| 1364 | text="" |
| 1365 | completionScope={canCommentOnLines ? completionScope : null} |
| 1366 | submitLabel={canCommentOnLines ? gt("Add to review") : gt("Add to agent")} |
| 1367 | {...(canCommentOnLines && onAddToAgentSelection |
| 1368 | ? { |
| 1369 | secondaryAction: { |
| 1370 | label: gt("Add to agent"), |
| 1371 | onAction: (text: string) => |
| 1372 | finishSelection(draft, text, (comment) => |
| 1373 | onAddToAgentSelection({ comment, request: text }), |
| 1374 | ), |
| 1375 | }, |
| 1376 | } |
| 1377 | : {})} |
| 1378 | onCancel={() => { |
| 1379 | setDraft(null); |
| 1380 | setSelectedLines(null); |
| 1381 | }} |
| 1382 | onComment={(body) => { |
| 1383 | if (!canCommentOnLines) { |
| 1384 | if (onAddToAgentSelection) { |
| 1385 | finishSelection(draft, body, (comment) => |
| 1386 | onAddToAgentSelection({ comment, request: body }), |
| 1387 | ); |
| 1388 | } |
| 1389 | return; |
| 1390 | } |
| 1391 | addComment(reviewKey, { |
| 1392 | id: nextPendingReviewCommentId(), |
| 1393 | path: draft.path, |
| 1394 | ...(draft.oldPath === null ? {} : { oldPath: draft.oldPath }), |
| 1395 | ...(draft.startPosition === undefined ? {} : { startPosition: draft.startPosition }), |
| 1396 | position: draft.position, |
| 1397 | body, |
| 1398 | }); |
| 1399 | setDraft(null); |
| 1400 | setSelectedLines(null); |
| 1401 | }} |
| 1402 | /> |
| 1403 | ) : null} |
| 1404 | </div> |
| 1405 | ); |
| 1406 | |
| 1407 | const selectedCommit = orderedCommits.find((entry) => entry.oid === commit); |
| 1408 | const scopeLabel = selectedCommit ? selectedCommit.messageHeadline : gt("All commits"); |
| 1409 | const changeIgnoreWhitespace = (next: boolean) => { |
| 1410 | setIgnoreWhitespace(next); |
| 1411 | setDraft(null); |
| 1412 | setSelectedLines(null); |
| 1413 | }; |
| 1414 | const toolbar = ( |
| 1415 | <div className="@container flex h-10 min-h-10 shrink-0 items-center justify-between gap-2 border-b border-border/60 bg-background px-4 text-xs text-muted-foreground"> |
| 1416 | <div className="flex min-w-0 flex-1 items-center gap-3"> |
| 1417 | {orderedCommits.length > 0 ? ( |
| 1418 | <DropdownMenu> |
| 1419 | <DropdownMenuTrigger |
| 1420 | render={<Button size="xs" variant="secondary" />} |
| 1421 | className="min-w-0 max-w-64" |
| 1422 | aria-label={gt("Diff scope: {scope}", { scope: scopeLabel })} |
| 1423 | > |
| 1424 | <span className="truncate">{scopeLabel}</span> |
| 1425 | <ChevronDownIcon className="size-3.5 shrink-0 opacity-70" /> |
| 1426 | </DropdownMenuTrigger> |
| 1427 | <DropdownMenuContent align="start" className="max-w-[min(28rem,calc(100vw-2rem))]"> |
| 1428 | <DropdownMenuRadioGroup |
| 1429 | value={commit ?? "all"} |
| 1430 | onValueChange={(value) => onSelectedCommitChange(value === "all" ? null : value)} |
| 1431 | > |
| 1432 | <DropdownMenuRadioItem value="all" closeOnClick> |
| 1433 | <span> |
| 1434 | <T>All commits</T> |
| 1435 | </span> |
| 1436 | </DropdownMenuRadioItem> |
| 1437 | {orderedCommits.slice(0, visibleCommitCount).map((entry) => ( |
| 1438 | <DropdownMenuRadioItem key={entry.oid} value={entry.oid} closeOnClick> |
| 1439 | <span className="flex items-center gap-2"> |
| 1440 | <Tooltip> |
| 1441 | <TooltipTrigger |
| 1442 | render={<span className="min-w-0 truncate">{entry.messageHeadline}</span>} |
| 1443 | /> |
| 1444 | <TooltipPopup side="top">{entry.messageHeadline}</TooltipPopup> |
| 1445 | </Tooltip> |
| 1446 | <span className="ml-auto shrink-0 font-mono text-xs text-muted-foreground"> |
| 1447 | {entry.oid.slice(0, 7)} |
| 1448 | </span> |
| 1449 | </span> |
| 1450 | </DropdownMenuRadioItem> |
| 1451 | ))} |
| 1452 | </DropdownMenuRadioGroup> |
| 1453 | {orderedCommits.length > visibleCommitCount ? ( |
| 1454 | <DropdownMenuItem |
| 1455 | closeOnClick={false} |
| 1456 | onClick={() => setVisibleCommitCount((count) => count + COMMIT_PAGE_SIZE)} |
| 1457 | > |
| 1458 | <span className="text-muted-foreground"> |
| 1459 | {gt( |
| 1460 | "{count, plural, one {Show more ({count} left)} other {Show more ({count} left)}}", |
| 1461 | { count: orderedCommits.length - visibleCommitCount }, |
| 1462 | )} |
| 1463 | </span> |
| 1464 | </DropdownMenuItem> |
| 1465 | ) : null} |
| 1466 | </DropdownMenuContent> |
| 1467 | </DropdownMenu> |
| 1468 | ) : null} |
| 1469 | <PullRequestMetaLine> |
| 1470 | <span className="shrink-0 tabular-nums"> |
| 1471 | {gt("{count, plural, one {{count} file} other {{count} files}}", { |
| 1472 | count: files.length, |
| 1473 | })} |
| 1474 | {nextCursor === null ? "" : "+"} |
| 1475 | </span> |
| 1476 | {hiddenTestFileCount > 0 ? ( |
| 1477 | <Button type="button" size="xs" variant="link" onClick={() => setHideTestFiles(false)}> |
| 1478 | {gt( |
| 1479 | "{count, plural, one {{count} test file hidden} other {{count} test files hidden}}", |
| 1480 | { count: hiddenTestFileCount }, |
| 1481 | )} |
| 1482 | </Button> |
| 1483 | ) : null} |
| 1484 | {filesViewed.enabled && files.length > 0 ? ( |
| 1485 | <span className="flex min-w-0 items-center gap-1 tabular-nums"> |
| 1486 | <span className="shrink-0"> |
| 1487 | {filePaths.filter(isFileViewed).length} / {files.length} |
| 1488 | </span> |
| 1489 | <span className="truncate"> |
| 1490 | {viewedFilesStore === "environment" |
| 1491 | ? gt("viewed in {app}", { app: APP_BASE_NAME }) |
| 1492 | : gt("viewed", { $context: "files marked as viewed" })} |
| 1493 | </span> |
| 1494 | {viewedFilesStore === "environment" ? ( |
| 1495 | <Tooltip> |
| 1496 | <TooltipTrigger render={<span className="flex shrink-0 items-center" />}> |
| 1497 | <InfoIcon |
| 1498 | aria-label={gt("These ticks are kept here, not on the host")} |
| 1499 | className="text-muted-foreground size-3.5" |
| 1500 | /> |
| 1501 | </TooltipTrigger> |
| 1502 | <TooltipPopup side="bottom"> |
| 1503 | <T> |
| 1504 | This host keeps no shared record of which files you have read, so these ticks |
| 1505 | are kept by this environment. They follow you between the apps connected to |
| 1506 | it, but the host's own web UI will not show them. |
| 1507 | </T> |
| 1508 | </TooltipPopup> |
| 1509 | </Tooltip> |
| 1510 | ) : null} |
| 1511 | {filesViewed.error !== null ? ( |
| 1512 | <Tooltip> |
| 1513 | <TooltipTrigger render={<span className="flex shrink-0 items-center" />}> |
| 1514 | <TriangleAlertIcon |
| 1515 | aria-label={gt("Your ticks could not be read")} |
| 1516 | className="size-3.5 text-warning-foreground" |
| 1517 | /> |
| 1518 | </TooltipTrigger> |
| 1519 | <TooltipPopup side="bottom"> |
| 1520 | <T> |
| 1521 | The boxes below are whatever was last read, and empty if nothing has been read |
| 1522 | yet. <Var>{filesViewed.error}</Var> |
| 1523 | </T> |
| 1524 | </TooltipPopup> |
| 1525 | </Tooltip> |
| 1526 | ) : null} |
| 1527 | {filesViewed.truncated ? ( |
| 1528 | <Tooltip> |
| 1529 | <TooltipTrigger render={<span className="flex shrink-0 items-center" />}> |
| 1530 | <TriangleAlertIcon |
| 1531 | aria-label={gt("This count covers only part of the change")} |
| 1532 | className="size-3.5 text-warning-foreground" |
| 1533 | /> |
| 1534 | </TooltipTrigger> |
| 1535 | <TooltipPopup side="bottom"> |
| 1536 | <T> |
| 1537 | This change has more files than the host will report ticks for in one read, so |
| 1538 | the count is short and some boxes below start empty. |
| 1539 | </T> |
| 1540 | </TooltipPopup> |
| 1541 | </Tooltip> |
| 1542 | ) : null} |
| 1543 | </span> |
| 1544 | ) : null} |
| 1545 | {withheldContent ? ( |
| 1546 | <Tooltip> |
| 1547 | <TooltipTrigger render={<span className="flex shrink-0 items-center" />}> |
| 1548 | <TriangleAlertIcon |
| 1549 | aria-label={gt("Some of this diff was not shown")} |
| 1550 | className="size-3.5 text-warning-foreground" |
| 1551 | /> |
| 1552 | </TooltipTrigger> |
| 1553 | <TooltipPopup side="bottom"> |
| 1554 | <T> |
| 1555 | The host withheld part of this diff: a binary file, or a change too large to |
| 1556 | inline. |
| 1557 | </T> |
| 1558 | </TooltipPopup> |
| 1559 | </Tooltip> |
| 1560 | ) : null} |
| 1561 | {commit !== null && review.inlineComment ? ( |
| 1562 | <Tooltip> |
| 1563 | <TooltipTrigger render={<span className="flex shrink-0 items-center" />}> |
| 1564 | <MessageSquareOffIcon |
| 1565 | aria-label={gt("Line comments are written from the whole change")} |
| 1566 | className="size-3.5" |
| 1567 | /> |
| 1568 | </TooltipTrigger> |
| 1569 | <TooltipPopup side="bottom"> |
| 1570 | <T> |
| 1571 | A comment is anchored to the whole change, so switch to All commits to write one. |
| 1572 | </T> |
| 1573 | </TooltipPopup> |
| 1574 | </Tooltip> |
| 1575 | ) : null} |
| 1576 | </PullRequestMetaLine> |
| 1577 | </div> |
| 1578 | <div className="flex shrink-0 items-center gap-1"> |
| 1579 | <DropdownMenu> |
| 1580 | <Tooltip> |
| 1581 | <TooltipTrigger |
| 1582 | render={ |
| 1583 | <DropdownMenuTrigger |
| 1584 | render={<Button size="icon-sm" variant="ghost" />} |
| 1585 | className="@lg:hidden" |
| 1586 | aria-label={gt("Diff options")} |
| 1587 | /> |
| 1588 | } |
| 1589 | > |
| 1590 | <Settings2Icon className="size-3.5" /> |
| 1591 | </TooltipTrigger> |
| 1592 | <TooltipPopup side="top"> |
| 1593 | <T>Diff options</T> |
| 1594 | </TooltipPopup> |
| 1595 | </Tooltip> |
| 1596 | <DropdownMenuContent align="end"> |
| 1597 | <DropdownMenuCheckboxItem |
| 1598 | checked={ignoreWhitespace} |
| 1599 | onCheckedChange={(checked) => changeIgnoreWhitespace(checked)} |
| 1600 | > |
| 1601 | <T>Hide whitespace changes</T> |
| 1602 | </DropdownMenuCheckboxItem> |
| 1603 | <DropdownMenuCheckboxItem |
| 1604 | checked={wordWrap} |
| 1605 | onCheckedChange={(checked) => setWordWrapOverride(checked)} |
| 1606 | > |
| 1607 | <T>Wrap lines</T> |
| 1608 | </DropdownMenuCheckboxItem> |
| 1609 | <DropdownMenuSeparator /> |
| 1610 | <DropdownMenuRadioGroup |
| 1611 | value={diffLayout} |
| 1612 | onValueChange={(value) => { |
| 1613 | if (value === "stacked" || value === "split") { |
| 1614 | updateClientSettings({ diffLayout: value }); |
| 1615 | } |
| 1616 | }} |
| 1617 | > |
| 1618 | <DropdownMenuRadioItem value="stacked" closeOnClick> |
| 1619 | <T context="diff layout">Stacked</T> |
| 1620 | </DropdownMenuRadioItem> |
| 1621 | <DropdownMenuRadioItem value="split" closeOnClick> |
| 1622 | <T context="diff layout">Split</T> |
| 1623 | </DropdownMenuRadioItem> |
| 1624 | </DropdownMenuRadioGroup> |
| 1625 | </DropdownMenuContent> |
| 1626 | </DropdownMenu> |
| 1627 | <div className="hidden items-center gap-1 @lg:flex"> |
| 1628 | <Tooltip> |
| 1629 | <TooltipTrigger |
| 1630 | render={ |
| 1631 | <Toggle |
| 1632 | aria-label={ |
| 1633 | ignoreWhitespace ? gt("Show whitespace changes") : gt("Hide whitespace changes") |
| 1634 | } |
| 1635 | variant="ghost" |
| 1636 | size="sm" |
| 1637 | pressed={ignoreWhitespace} |
| 1638 | onPressedChange={(pressed) => changeIgnoreWhitespace(Boolean(pressed))} |
| 1639 | /> |
| 1640 | } |
| 1641 | > |
| 1642 | <PilcrowIcon className="size-3.5" /> |
| 1643 | </TooltipTrigger> |
| 1644 | <TooltipPopup side="top"> |
| 1645 | {ignoreWhitespace ? gt("Show whitespace changes") : gt("Hide whitespace changes")} |
| 1646 | </TooltipPopup> |
| 1647 | </Tooltip> |
| 1648 | <ToggleGroup |
| 1649 | aria-label={gt("Diff layout")} |
| 1650 | className="shrink-0" |
| 1651 | variant="segmented" |
| 1652 | value={[diffLayout]} |
| 1653 | onValueChange={(value) => { |
| 1654 | const next = value[0]; |
| 1655 | if (next === "stacked" || next === "split") { |
| 1656 | updateClientSettings({ diffLayout: next }); |
| 1657 | } |
| 1658 | }} |
| 1659 | > |
| 1660 | <Toggle aria-label={gt("Stacked diff view")} value="stacked"> |
| 1661 | <Rows3Icon className="size-3.5" /> |
| 1662 | </Toggle> |
| 1663 | <Toggle aria-label={gt("Split diff view")} value="split"> |
| 1664 | <Columns2Icon className="size-3.5" /> |
| 1665 | </Toggle> |
| 1666 | </ToggleGroup> |
| 1667 | <Tooltip> |
| 1668 | <TooltipTrigger |
| 1669 | render={ |
| 1670 | <Toggle |
| 1671 | aria-label={ |
| 1672 | wordWrap ? gt("Disable diff line wrapping") : gt("Enable diff line wrapping") |
| 1673 | } |
| 1674 | variant="ghost" |
| 1675 | size="sm" |
| 1676 | pressed={wordWrap} |
| 1677 | onPressedChange={(pressed) => { |
| 1678 | setWordWrapOverride(Boolean(pressed)); |
| 1679 | }} |
| 1680 | /> |
| 1681 | } |
| 1682 | > |
| 1683 | <TextWrapIcon className="size-3.5" /> |
| 1684 | </TooltipTrigger> |
| 1685 | <TooltipPopup side="top"> |
| 1686 | {wordWrap ? gt("Disable line wrapping") : gt("Enable line wrapping")} |
| 1687 | </TooltipPopup> |
| 1688 | </Tooltip> |
| 1689 | </div> |
| 1690 | {fileKeys.length > 0 ? ( |
| 1691 | <Tooltip> |
| 1692 | <TooltipTrigger |
| 1693 | render={ |
| 1694 | <Button |
| 1695 | type="button" |
| 1696 | size="icon-sm" |
| 1697 | variant="ghost" |
| 1698 | aria-label={allFilesCollapsed ? gt("Expand all files") : gt("Collapse all files")} |
| 1699 | onClick={toggleAllFiles} |
| 1700 | /> |
| 1701 | } |
| 1702 | > |
| 1703 | {allFilesCollapsed ? ( |
| 1704 | <ChevronsUpDownIcon className="size-3.5" /> |
| 1705 | ) : ( |
| 1706 | <ChevronsDownUpIcon className="size-3.5" /> |
| 1707 | )} |
| 1708 | </TooltipTrigger> |
| 1709 | <TooltipPopup side="top"> |
| 1710 | {allFilesCollapsed ? gt("Expand all files") : gt("Collapse all files")} |
| 1711 | </TooltipPopup> |
| 1712 | </Tooltip> |
| 1713 | ) : null} |
| 1714 | {testFileCount > 0 ? ( |
| 1715 | <Tooltip> |
| 1716 | <TooltipTrigger |
| 1717 | render={ |
| 1718 | <Toggle |
| 1719 | aria-label={gt("Hide test files")} |
| 1720 | variant="ghost" |
| 1721 | size="sm" |
| 1722 | pressed={hideTestFiles} |
| 1723 | onPressedChange={(pressed) => setHideTestFiles(Boolean(pressed))} |
| 1724 | /> |
| 1725 | } |
| 1726 | > |
| 1727 | <FlaskConicalOffIcon className="size-3.5" /> |
| 1728 | </TooltipTrigger> |
| 1729 | <TooltipPopup side="top"> |
| 1730 | {hideTestFiles ? gt("Show test files") : gt("Hide test files")} |
| 1731 | </TooltipPopup> |
| 1732 | </Tooltip> |
| 1733 | ) : null} |
| 1734 | {fileKeys.length > 0 ? ( |
| 1735 | <Tooltip> |
| 1736 | <TooltipTrigger |
| 1737 | render={ |
| 1738 | <Toggle |
| 1739 | aria-label={fileTreeOpen ? gt("Hide file tree") : gt("Show file tree")} |
| 1740 | variant="ghost" |
| 1741 | size="sm" |
| 1742 | pressed={fileTreeOpen} |
| 1743 | onPressedChange={(pressed) => setFileTreeOpen(Boolean(pressed))} |
| 1744 | /> |
| 1745 | } |
| 1746 | > |
| 1747 | <FolderTreeIcon className="size-3.5" /> |
| 1748 | </TooltipTrigger> |
| 1749 | <TooltipPopup side="top"> |
| 1750 | {fileTreeOpen ? gt("Hide file tree") : gt("Show file tree")} |
| 1751 | </TooltipPopup> |
| 1752 | </Tooltip> |
| 1753 | ) : null} |
| 1754 | </div> |
| 1755 | </div> |
| 1756 | ); |
| 1757 | // A file not loaded yet pages forward each time a slice arrives; once loaded, the viewer |
| 1758 | // positions it when it renders it. |
| 1759 | const answerReveal = useEffectEvent(() => { |
| 1760 | if (revealRequest === null || answeredRevealNonce.current === revealRequest.nonce) return; |
| 1761 | if (!items.some((item) => resolveFileDiffPath(item.fileDiff) === revealRequest.path)) { |
| 1762 | if (canLoadNextSlice) loadNextSlice(); |
| 1763 | return; |
| 1764 | } |
| 1765 | answeredRevealNonce.current = revealRequest.nonce; |
| 1766 | revealFile(revealRequest.path); |
| 1767 | }); |
| 1768 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the code view to a requested file once loaded, or pages forward until it arrives |
| 1769 | useEffect(() => { |
| 1770 | // oxlint-disable-next-line react/set-state-in-effect -- A reveal for a file not loaded yet pages forward, which sets the slice cursor. |
| 1771 | answerReveal(); |
| 1772 | // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-checked as pages load until the requested file arrives. |
| 1773 | }, [canLoadNextSlice, items, revealRequest]); |
| 1774 | // The store clears a settled link after this render, so one link must not reveal twice. |
| 1775 | const answeredLink = useRef<string | null>(null); |
| 1776 | const revealLink = useEffectEvent(() => { |
| 1777 | if (revealUrl === undefined) answeredLink.current = null; |
| 1778 | if (revealUrl === undefined || linkAnchor?.kind !== "diff") return; |
| 1779 | // The panel selects the link's commit after this tab's effects run, so the files on screen |
| 1780 | // can still be another commit's. |
| 1781 | const linkCommit = pullRequestLinkCommit(revealUrl); |
| 1782 | if ((detail.commits.some((entry) => entry.oid === linkCommit) ? linkCommit : null) !== commit) { |
| 1783 | return; |
| 1784 | } |
| 1785 | const key = `${scopeKey}:${revealUrl}`; |
| 1786 | if (answeredLink.current === key) return; |
| 1787 | if ( |
| 1788 | !pendingLinkPath || |
| 1789 | !items.some((item) => resolveFileDiffPath(item.fileDiff) === pendingLinkPath) |
| 1790 | ) { |
| 1791 | if (canLoadNextSlice) loadNextSlice(); |
| 1792 | // Every page is loaded and none has the file. |
| 1793 | else if (!pendingLinkPath && loadedSlices.length > 0 && nextCursor === null) { |
| 1794 | answeredLink.current = key; |
| 1795 | onRevealSettled?.(revealUrl); |
| 1796 | } |
| 1797 | return; |
| 1798 | } |
| 1799 | answeredLink.current = key; |
| 1800 | setRevealedLink({ scope: scopeKey, path: pendingLinkPath }); |
| 1801 | onRevealSettled?.(revealUrl); |
| 1802 | const range = |
| 1803 | linkAnchor.range && |
| 1804 | resolvePullRequestAnchorRange( |
| 1805 | linkAnchor.range, |
| 1806 | (line) => linkFile !== undefined && isRemovedLine(linkFile, line), |
| 1807 | ); |
| 1808 | revealFile( |
| 1809 | pendingLinkPath, |
| 1810 | range |
| 1811 | ? { |
| 1812 | start: range.start, |
| 1813 | end: range.end, |
| 1814 | side: toViewerSide(range.side), |
| 1815 | endSide: toViewerSide(range.endSide), |
| 1816 | } |
| 1817 | : undefined, |
| 1818 | ); |
| 1819 | }); |
| 1820 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- pages and scrolls the virtual diff to a clicked file or line range |
| 1821 | useEffect(() => { |
| 1822 | // oxlint-disable-next-line react/set-state-in-effect -- revealing unfolds the target and may request the next diff page |
| 1823 | revealLink(); |
| 1824 | // oxlint-disable-next-line react/exhaustive-effect-dependencies -- retries the reveal as diff pages and viewer items arrive |
| 1825 | }, [revealUrl, pendingLinkPath, canLoadNextSlice, items]); |
| 1826 | const withToolbar = (body: ReactNode) => ( |
| 1827 | <div className="flex h-full min-h-0 flex-col"> |
| 1828 | {toolbar} |
| 1829 | <div ref={scrollerRef} className="min-h-0 flex-1 overflow-auto"> |
| 1830 | {body} |
| 1831 | </div> |
| 1832 | </div> |
| 1833 | ); |
| 1834 | |
| 1835 | const term = changeRequestTermKind(sourceControlClients.get(detail.provider).changeRequest); |
| 1836 | if (diffQuery.isPending && loadedSlices.length === 0) { |
| 1837 | return withToolbar( |
| 1838 | <DiffPanelLoadingState |
| 1839 | label={gt( |
| 1840 | "Loading {term, select, mr {merge request} cr {change request} other {pull request}} diff...", |
| 1841 | { term }, |
| 1842 | )} |
| 1843 | />, |
| 1844 | ); |
| 1845 | } |
| 1846 | |
| 1847 | if (diffQuery.error && loadedSlices.length === 0) { |
| 1848 | return withToolbar( |
| 1849 | <PullRequestDiffUnavailableState |
| 1850 | error={diffQuery.error} |
| 1851 | provider={detail.provider} |
| 1852 | url={detail.url} |
| 1853 | onRetry={() => diffQuery.refresh()} |
| 1854 | />, |
| 1855 | ); |
| 1856 | } |
| 1857 | |
| 1858 | if (rawSlicesView !== null) { |
| 1859 | return withToolbar(rawSlicesView); |
| 1860 | } |
| 1861 | |
| 1862 | if (items.length === 0 && nextCursor === null) { |
| 1863 | return withToolbar( |
| 1864 | <p className="px-4 py-5 text-sm text-muted-foreground"> |
| 1865 | {commit === null |
| 1866 | ? gt( |
| 1867 | "This {term, select, mr {merge request} cr {change request} other {pull request}} has no file changes.", |
| 1868 | { term }, |
| 1869 | ) |
| 1870 | : gt("This commit has no file changes.")} |
| 1871 | </p>, |
| 1872 | ); |
| 1873 | } |
| 1874 | |
| 1875 | const orphanThreads = detail.reviewThreads.filter((thread) => !placedThreadIds.has(thread.id)); |
| 1876 | const orphanFiles = new Map<string, PullRequestReviewThread[]>(); |
| 1877 | for (const thread of orphanThreads) { |
| 1878 | const existing = orphanFiles.get(thread.path); |
| 1879 | if (existing) existing.push(thread); |
| 1880 | else orphanFiles.set(thread.path, [thread]); |
| 1881 | } |
| 1882 | |
| 1883 | return ( |
| 1884 | <div className="flex h-full min-h-0 flex-col"> |
| 1885 | {toolbar} |
| 1886 | {orphanFiles.size > 0 ? ( |
| 1887 | <div className="shrink-0 border-b border-border/60"> |
| 1888 | <Collapsible open={orphansOpen} onOpenChange={setOrphansOpen}> |
| 1889 | <h2> |
| 1890 | <CollapsibleTrigger className="flex w-full items-center gap-1.5 px-4 py-2 text-left text-xs text-muted-foreground"> |
| 1891 | <span> |
| 1892 | {nextCursor === null |
| 1893 | ? gt("Conversations not on the current diff") |
| 1894 | : gt("Conversations not on the diff loaded so far")} |
| 1895 | </span> |
| 1896 | <ChevronRightIcon |
| 1897 | aria-hidden |
| 1898 | className={cn("size-3.5 transition-transform", orphansOpen && "rotate-90")} |
| 1899 | /> |
| 1900 | <span aria-hidden className="tabular-nums"> |
| 1901 | {orphanThreads.length} |
| 1902 | </span> |
| 1903 | <span className="sr-only"> |
| 1904 | {gt("{count, plural, one {{count} conversation} other {{count} conversations}}", { |
| 1905 | count: orphanThreads.length, |
| 1906 | })} |
| 1907 | </span> |
| 1908 | </CollapsibleTrigger> |
| 1909 | </h2> |
| 1910 | <CollapsiblePanel> |
| 1911 | <div className="max-h-64 space-y-1 overflow-auto px-1 pb-1"> |
| 1912 | {[...orphanFiles].map(([path, threads]) => ( |
| 1913 | <div key={path}> |
| 1914 | <Tooltip> |
| 1915 | <TooltipTrigger |
| 1916 | render={ |
| 1917 | <p className="truncate px-3 text-xs text-muted-foreground">{path}</p> |
| 1918 | } |
| 1919 | /> |
| 1920 | <TooltipPopup side="top">{path}</TooltipPopup> |
| 1921 | </Tooltip> |
| 1922 | <div className="mt-1 space-y-2"> |
| 1923 | {threads.map((thread) => ( |
| 1924 | <div key={thread.id}> |
| 1925 | {thread.line === null ? null : ( |
| 1926 | <p className="px-3 text-xs text-muted-foreground"> |
| 1927 | <T> |
| 1928 | Line <Var>{thread.line}</Var> |
| 1929 | </T> |
| 1930 | </p> |
| 1931 | )} |
| 1932 | {renderThreadCard(thread)} |
| 1933 | </div> |
| 1934 | ))} |
| 1935 | </div> |
| 1936 | </div> |
| 1937 | ))} |
| 1938 | </div> |
| 1939 | </CollapsiblePanel> |
| 1940 | </Collapsible> |
| 1941 | </div> |
| 1942 | ) : null} |
| 1943 | <div className="flex min-h-0 flex-1 overflow-hidden"> |
| 1944 | <div |
| 1945 | className="relative min-h-0 min-w-0 flex-1" |
| 1946 | onWheelCapture={codeViewReveal.cancel} |
| 1947 | onTouchStartCapture={codeViewReveal.cancel} |
| 1948 | onPointerDownCapture={codeViewReveal.cancel} |
| 1949 | onKeyDownCapture={codeViewReveal.cancel} |
| 1950 | // Headers live in shadow DOM; composedPath crosses that boundary. |
| 1951 | onClickCapture={(event) => { |
| 1952 | const composedPath = event.nativeEvent.composedPath?.() ?? []; |
| 1953 | for (const node of composedPath) { |
| 1954 | if (!(node instanceof HTMLElement)) continue; |
| 1955 | if (node instanceof HTMLButtonElement || node instanceof HTMLAnchorElement) { |
| 1956 | return; |
| 1957 | } |
| 1958 | if (node.hasAttribute("data-viewed-toggle")) return; |
| 1959 | if (node.hasAttribute("data-diffs-header")) { |
| 1960 | const filePath = node.querySelector("[data-title]")?.textContent?.trim(); |
| 1961 | if (filePath === undefined || filePath === "") return; |
| 1962 | const item = items.find( |
| 1963 | (candidate) => resolveFileDiffPath(candidate.fileDiff) === filePath, |
| 1964 | ); |
| 1965 | if (item !== undefined) toggleFile(item.id); |
| 1966 | return; |
| 1967 | } |
| 1968 | } |
| 1969 | }} |
| 1970 | > |
| 1971 | {/* The viewer must own its scroll element to position virtual rows within it. */} |
| 1972 | <FileViewedToggleContext value={fileViewedToggle}> |
| 1973 | <StyledDiffCodeView<ReviewAnnotationGroup> |
| 1974 | className="@container h-full overflow-auto [scrollbar-gutter:stable]" |
| 1975 | containerRef={scrollerRef} |
| 1976 | viewerRef={codeViewReveal.attach} |
| 1977 | items={items} |
| 1978 | selectedLines={selectedLines} |
| 1979 | onSelectedLinesChange={setSelectedLines} |
| 1980 | options={diffViewOptions} |
| 1981 | renderCodeViewFooter={renderCodeViewFooter} |
| 1982 | renderHeaderPrefix={renderHeaderPrefix} |
| 1983 | renderHeaderMetadata={renderHeaderMetadata} |
| 1984 | renderAnnotation={renderAnnotation} |
| 1985 | unsafeCSSExtra={`${REPLACE_FILE_COUNTS_CSS}\n${CUT_LINES_CSS}`} |
| 1986 | /> |
| 1987 | </FileViewedToggleContext> |
| 1988 | </div> |
| 1989 | {fileTreeOpen ? ( |
| 1990 | <FileExplorerPane |
| 1991 | resizable |
| 1992 | storageKey="t3code:diff-file-tree-width" |
| 1993 | defaultWidth={320} |
| 1994 | defaultWidthFraction={0.4} |
| 1995 | minWidth={192} |
| 1996 | resizeLabel={gt("Resize PR Code files")} |
| 1997 | > |
| 1998 | <DiffFileTree |
| 1999 | ariaLabel={gt( |
| 2000 | "{term, select, mr {Merge request} cr {Change request} other {Pull request}} #{number} files", |
| 2001 | { |
| 2002 | term, |
| 2003 | number: detail.number, |
| 2004 | }, |
| 2005 | )} |
| 2006 | entries={fileTreeEntries} |
| 2007 | onSelectFile={revealFile} |
| 2008 | footer={ |
| 2009 | nextCursor === null ? null : ( |
| 2010 | <div className="shrink-0 border-t border-border/60 p-2"> |
| 2011 | <Button |
| 2012 | type="button" |
| 2013 | size="xs" |
| 2014 | variant="outline" |
| 2015 | className="w-full" |
| 2016 | disabled={diffQuery.isPending} |
| 2017 | onClick={diffQuery.error !== null ? () => diffQuery.refresh() : loadNextSlice} |
| 2018 | > |
| 2019 | {diffQuery.error !== null |
| 2020 | ? gt("Retry") |
| 2021 | : diffQuery.isPending |
| 2022 | ? gt("Loading more files...") |
| 2023 | : gt("Load more files")} |
| 2024 | </Button> |
| 2025 | </div> |
| 2026 | ) |
| 2027 | } |
| 2028 | /> |
| 2029 | </FileExplorerPane> |
| 2030 | ) : null} |
| 2031 | </div> |
| 2032 | {unstructured} |
| 2033 | </div> |
| 2034 | ); |
| 2035 | } |
| 2036 | |
| 2037 | function WithheldFileNotice({ |
| 2038 | path, |
| 2039 | status, |
| 2040 | onLoad, |
| 2041 | }: { |
| 2042 | readonly path: string; |
| 2043 | readonly status: WithheldFileStatus; |
| 2044 | readonly onLoad: ((path: string) => void) | undefined; |
| 2045 | }) { |
| 2046 | const gt = useGT(); |
| 2047 | return ( |
| 2048 | <div className="flex items-center gap-2 bg-warning/8 px-3 py-2 text-xs text-warning-foreground"> |
| 2049 | <TriangleAlertIcon aria-hidden className="size-3.5 shrink-0 text-warning" /> |
| 2050 | <span> |
| 2051 | {status === "error" |
| 2052 | ? gt("Couldn't load this diff.") |
| 2053 | : status === "empty" |
| 2054 | ? gt("No text diff for this file.") |
| 2055 | : gt("Diff too large to display.")} |
| 2056 | </span> |
| 2057 | {onLoad === undefined || status === "empty" ? null : ( |
| 2058 | <Button |
| 2059 | size="micro" |
| 2060 | variant="warning-outline" |
| 2061 | disabled={status === "loading"} |
| 2062 | onClick={() => onLoad(path)} |
| 2063 | > |
| 2064 | {status === "loading" |
| 2065 | ? gt("Loading...") |
| 2066 | : status === "error" |
| 2067 | ? gt("Retry") |
| 2068 | : gt("Load diff")} |
| 2069 | </Button> |
| 2070 | )} |
| 2071 | </div> |
| 2072 | ); |
| 2073 | } |
| 2074 | |
| 2075 | export default PullRequestCodeTab; |