@devries-cameron20 / t3code Mirror · read-only / commits / bb30390933
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 08:00 UTC

perf(web): pull request code tab compiles, with viewed toggles read through context (#20471)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 16, 2026 at 18:46 UTC bb30390933ebcc6a2f50bb153ffc155e76d655fa
2 files changed +634 -598
apps/web/reactCompiledFiles.ts
+1
@@ -46,4 +46,5 @@ export const REACT_COMPILED_FILES = [
46 "apps/web/src/components/DiffPanel.tsx",
47 "apps/web/src/components/onboarding/WelcomeWizard.tsx",
48 "apps/web/src/hooks/useThreadActions.ts",
49 + "apps/web/src/components/pullRequest/PullRequestCodeTab.tsx",
50 ] as const;
apps/web/src/components/pullRequest/PullRequestCodeTab.tsx
+633 -598
@@ -1,4 +1,9 @@
1 -import type { CodeViewItem, DiffLineAnnotation, SelectedLineRange } from "@pierre/diffs";
1 +import type {
2 + CodeViewItem,
3 + DiffLineAnnotation,
4 + FileDiffMetadata,
5 + SelectedLineRange,
6 +} from "@pierre/diffs";
7 import type { CodeViewDiffItem, CodeViewHandle } from "@pierre/diffs/react";
8 import type {
9 EnvironmentId,
@@ -26,7 +31,15 @@ import {
31 import { ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown } from "lucide";
32 import { useAtomRefresh } from "@effect/atom-react";
33 import * as Schema from "effect/Schema";
29 -import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
34 +import {
35 + createContext,
36 + use,
37 + useEffect,
38 + useEffectEvent,
39 + useRef,
40 + useState,
41 + type ReactNode,
42 +} from "react";
43
44 import { useLocalStorage } from "~/hooks/useLocalStorage";
45 import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
@@ -136,6 +149,79 @@ const REPLACE_FILE_COUNTS_CSS = `
149
150 const NO_SLICES: ReadonlyArray<DiffSlice> = [];
151
152 +// Each slice is parsed once per cache key and the parse lives as long as the slice does, so a
153 +// slice arriving costs one parse rather than one per slice already on screen.
154 +const sliceParses = new WeakMap<DiffSlice, Map<string, RenderablePatch | null>>();
155 +
156 +function parseSlice(slice: DiffSlice, cacheKey: string, ignoreWhitespace: boolean) {
157 + let parses = sliceParses.get(slice);
158 + if (parses === undefined) {
159 + parses = new Map();
160 + sliceParses.set(slice, parses);
161 + }
162 + if (parses.has(cacheKey)) return parses.get(cacheKey) ?? null;
163 + const parsed = getRenderablePatch(slice.patch, cacheKey, {
164 + compactPartialHunkOffsets: true,
165 + ignoreWhitespace,
166 + });
167 + parses.set(cacheKey, parsed);
168 + return parsed;
169 +}
170 +
171 +interface FileViewedToggleState {
172 + readonly enabled: boolean;
173 + readonly isViewed: (path: string) => boolean;
174 + readonly isStale: (path: string) => boolean;
175 + readonly setFileViewed: (fileKey: string, path: string, viewed: boolean) => void;
176 +}
177 +
178 +// Header portals are memoized on the render props; the viewed toggle reads its state through
179 +// context so a press redraws the toggles, not every header on screen.
180 +const FileViewedToggleContext = createContext<FileViewedToggleState | null>(null);
181 +
182 +function FileViewedToggle({
183 + fileKey,
184 + path,
185 + stat,
186 +}: {
187 + readonly fileKey: string;
188 + readonly path: string;
189 + readonly stat: ReactNode;
190 +}) {
191 + const viewedFiles = use(FileViewedToggleContext);
192 + if (viewedFiles === null || !viewedFiles.enabled) return stat;
193 + const viewed = viewedFiles.isViewed(path);
194 + const stale = viewedFiles.isStale(path);
195 + return (
196 + <span className="flex items-center gap-3">
197 + {stat}
198 + <label
199 + data-viewed-toggle=""
200 + className="flex cursor-pointer select-none items-center gap-1.5 text-2xs text-muted-foreground"
201 + onClick={(event) => event.stopPropagation()}
202 + >
203 + <Checkbox
204 + aria-label={stale ? "Changed" : "Viewed"}
205 + checked={viewed}
206 + onCheckedChange={(next) => viewedFiles.setFileViewed(fileKey, path, next === true)}
207 + />
208 + {stale ? (
209 + <Tooltip>
210 + <TooltipTrigger render={<span className="text-warning-foreground" />}>
211 + Changed
212 + </TooltipTrigger>
213 + <TooltipPopup side="bottom">
214 + This file has been pushed to since you marked it viewed.
215 + </TooltipPopup>
216 + </Tooltip>
217 + ) : (
218 + <span className="@max-xs:hidden">Viewed</span>
219 + )}
220 + </label>
221 + </span>
222 + );
223 +}
224 +
225 interface MutableAnnotationGroup {
226 readonly side: PullRequestDiffSide;
227 readonly line: number;
@@ -157,6 +243,201 @@ export interface PullRequestAgentSelectionInput {
243 readonly request: string;
244 }
245
246 +// These hooks call no hooks, so the compiler needs the directive to memoize them. The viewer
247 +// and the viewed-file tracker key on the identity of what they return.
248 +function usePullRequestDiffFileContentsLoader<E>(
249 + getDiffFileContents: Parameters<typeof createPullRequestDiffFileContentsLoader<E>>[0],
250 + source: Parameters<typeof createPullRequestDiffFileContentsLoader<E>>[1],
251 +) {
252 + "use memo";
253 + return createPullRequestDiffFileContentsLoader(getDiffFileContents, source);
254 +}
255 +
256 +function useParsedDiffSlices(
257 + loadedSlices: ReadonlyArray<DiffSlice>,
258 + scopeKey: string,
259 + resolvedTheme: string,
260 + ignoreWhitespace: boolean,
261 +) {
262 + "use memo";
263 + // The cache key carries the theme, which is what the tokenizer caches against, so a theme
264 + // change is still a fresh parse. The patch's own hash is part of it too: a refreshed page
265 + // reuses its cursor, and a key of position alone would hand back the parse it replaced.
266 + const parsedSlices = loadedSlices.map((slice) =>
267 + parseSlice(
268 + slice,
269 + `pull-request:${scopeKey}:${resolvedTheme}:${ignoreWhitespace}:${slice.cursor ?? "first"}:${fnv1a32(slice.patch)}`,
270 + ignoreWhitespace,
271 + ),
272 + );
273 + const files = parsedSlices.flatMap((parsed) =>
274 + parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [],
275 + );
276 + const filePaths = files.map((file) => resolveFileDiffPath(file));
277 + const omittedFileStats = new Map(
278 + loadedSlices.flatMap((slice) =>
279 + slice.omittedFileStats.map((file) => [file.path, file] as const),
280 + ),
281 + );
282 + const sourceFileStats = new Map(
283 + parsedSlices.flatMap((parsed) =>
284 + parsed?.kind === "files"
285 + ? parsed.files.map(
286 + (file, index) =>
287 + [
288 + buildFileDiffRenderKey(file),
289 + getDiffLineStat([parsed.sourceFiles[index] ?? file]),
290 + ] as const,
291 + )
292 + : [],
293 + ),
294 + );
295 + const fileTreeEntries = diffFileTreeEntries(files);
296 + return { parsedSlices, files, filePaths, sourceFileStats, omittedFileStats, fileTreeEntries };
297 +}
298 +
299 +function useAnnotatedDiffFiles(
300 + files: ReadonlyArray<FileDiffMetadata>,
301 + reviewThreads: ReadonlyArray<PullRequestReviewThread>,
302 + pendingComments: ReadonlyArray<PendingReviewComment>,
303 + draft: DraftAnchor | null,
304 + scopedToCommit: boolean,
305 +) {
306 + "use memo";
307 + // Placing a conversation takes more than its file being in the diff: its line has to fall
308 + // inside a hunk that was rendered. One that does not is drawn nowhere, so it belongs in the
309 + // off-diff list rather than disappearing between the two.
310 + const placedThreadIds = (() => {
311 + const placed = new Set<string>();
312 + // A commit's diff counts lines within that commit; a review comment is anchored to the
313 + // pull request's head diff. Pinning one onto the other would put the remark against
314 + // whichever code happens to hold that line number in this commit, so while a commit is on
315 + // screen every conversation is listed rather than placed.
316 + if (scopedToCommit) return placed;
317 + for (const file of files) {
318 + const path = resolveFileDiffPath(file);
319 + for (const thread of reviewThreads) {
320 + if (
321 + thread.path === path &&
322 + thread.line !== null &&
323 + isLineInFileDiff(file, thread.side, thread.line)
324 + ) {
325 + placed.add(thread.id);
326 + }
327 + }
328 + }
329 + return placed;
330 + })();
331 +
332 + const annotatedFiles = files.map((fileDiff) => {
333 + const fileKey = buildFileDiffRenderKey(fileDiff);
334 + const path = resolveFileDiffPath(fileDiff);
335 + const groups = new Map<string, MutableAnnotationGroup>();
336 + const groupAt = (side: PullRequestDiffSide, line: number) => {
337 + const key = `${side}:${line}`;
338 + const existing = groups.get(key);
339 + if (existing) return existing;
340 + const created: MutableAnnotationGroup = {
341 + side,
342 + line,
343 + threads: [],
344 + pending: [],
345 + draft: false,
346 + };
347 + groups.set(key, created);
348 + return created;
349 + };
350 +
351 + for (const thread of reviewThreads) {
352 + if (thread.path !== path || thread.line === null) continue;
353 + if (!placedThreadIds.has(thread.id)) continue;
354 + groupAt(thread.side, thread.line).threads.push(thread);
355 + }
356 + if (!scopedToCommit) {
357 + for (const comment of pendingComments) {
358 + if (comment.path !== path) continue;
359 + const anchor = getReviewPositionAnchor(comment.position);
360 + groupAt(anchor.side, anchor.line).pending.push(comment);
361 + }
362 + }
363 + if (draft?.fileKey === fileKey) {
364 + const anchor = getReviewPositionAnchor(draft.position);
365 + groupAt(anchor.side, anchor.line).draft = true;
366 + }
367 +
368 + const annotations: ReviewAnnotation[] = [...groups.values()].map((group) => ({
369 + side: toViewerSide(group.side),
370 + lineNumber: group.line,
371 + metadata: { threads: group.threads, pending: group.pending, draft: group.draft },
372 + }));
373 + return {
374 + fileKey,
375 + path,
376 + fileDiff,
377 + annotations,
378 + // The viewer re-renders an item only when its version changes, so everything the
379 + // annotations show has to be part of it.
380 + annotationsVersion: fnv1a32(
381 + annotations
382 + .map(
383 + ({ side, lineNumber, metadata }) =>
384 + `${side}:${lineNumber}:${metadata.draft ? "d" : ""}:${metadata.pending
385 + .map((comment) => `${comment.id}:${comment.body}`)
386 + .join(",")}:${metadata.threads
387 + .map(
388 + (thread) =>
389 + `${thread.id}:${thread.isResolved ? "r" : ""}:${
390 + thread.isOutdated ? "o" : ""
391 + }:${thread.comments
392 + .map(
393 + (comment) =>
394 + `${comment.id}:${comment.author?.login ?? ""}:${comment.createdAt}:${comment.body}:${(
395 + comment.reactions ?? []
396 + )
397 + .map((r) => `${r.content}:${r.count}:${r.viewerHasReacted ? "v" : ""}`)
398 + .join(",")}`,
399 + )
400 + .join(";")}`,
401 + )
402 + .join(",")}`,
403 + )
404 + .join("|"),
405 + ),
406 + };
407 + });
408 + return { annotatedFiles, placedThreadIds };
409 +}
410 +
411 +function useDiffItems(
412 + annotatedFiles: ReturnType<typeof useAnnotatedDiffFiles>["annotatedFiles"],
413 + foldOverride: Exclude<DiffFoldOverride, null>,
414 + toggledFiles: ReadonlySet<string>,
415 + viewedFiles: {
416 + readonly enabled: boolean;
417 + readonly isViewed: (path: string) => boolean;
418 + readonly isStale: (path: string) => boolean;
419 + },
420 +) {
421 + "use memo";
422 + const items: CodeViewDiffItem<ReviewAnnotationGroup>[] = annotatedFiles.map(
423 + ({ fileKey, path, fileDiff, annotations, annotationsVersion }) => {
424 + const collapsed = isFileDiffCollapsed(fileKey, foldOverride, toggledFiles);
425 + const viewedMark = viewedFiles.enabled
426 + ? `e${viewedFiles.isViewed(path) ? "v" : ""}${viewedFiles.isStale(path) ? "s" : ""}`
427 + : "";
428 + return {
429 + id: fileKey,
430 + type: "diff" as const,
431 + fileDiff,
432 + annotations,
433 + collapsed,
434 + version: fnv1a32(`${collapsed ? "1" : "0"}:${viewedMark}:${annotationsVersion}`),
435 + };
436 + },
437 + );
438 + return items;
439 +}
440 +
441 function PullRequestCodeTab({
442 scrollerRef,
443 environmentId,
@@ -216,7 +497,6 @@ function PullRequestCodeTab({
497 readonly cursor: string | null;
498 readonly slices: ReadonlyArray<DiffSlice>;
499 }>({ key: "", cursor: null, slices: NO_SLICES });
219 - const parseCache = useRef(new Map<string, RenderablePatch>());
500 const [viewer, setViewer] = useState<CodeViewHandle<ReviewAnnotationGroup, undefined> | null>(
501 null,
502 );
@@ -226,7 +506,9 @@ function PullRequestCodeTab({
506 const scopeKey = commit === null ? referenceKey : `${referenceKey}@${commit}`;
507 // The panel keeps this mounted across pull requests, so an open composer would otherwise
508 // survive the switch and attach its comment to whichever one is on screen when it is sent.
229 - useEffect(() => {
509 + const [stateScopeKey, setStateScopeKey] = useState(scopeKey);
510 + if (stateScopeKey !== scopeKey) {
511 + setStateScopeKey(scopeKey);
512 setDraft(null);
513 setSelectedLines(null);
514 setToggledFiles(new Set());
@@ -234,8 +516,7 @@ function PullRequestCodeTab({
516 setVisibleCommitCount(COMMIT_PAGE_SIZE);
517 setOrphansOpen(false);
518 setSliceState({ key: scopeKey, cursor: null, slices: NO_SLICES });
237 - parseCache.current.clear();
238 - }, [scopeKey]);
519 + }
520
521 const loadedSlices = sliceState.key === scopeKey ? sliceState.slices : NO_SLICES;
522 const cursor = sliceState.key === scopeKey ? sliceState.cursor : null;
@@ -249,9 +530,21 @@ function PullRequestCodeTab({
530 },
531 }),
532 );
252 - useEffect(() => {
253 - const data = diffQuery.data;
254 - if (data === null) return;
533 + // Pages accumulate into slices as each answer arrives, so the slice list is adjusted while
534 + // rendering the answer rather than one commit later.
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 = {
@@ -288,7 +581,7 @@ function PullRequestCodeTab({
581 // after it go with the replacement: their cursors were positions in the old diff.
582 return { key: scopeKey, cursor, slices: [...slices.slice(0, index), next] };
583 });
291 - }, [cursor, diffQuery.data, scopeKey]);
584 + }
585 const refreshFirstDiffPage = useAtomRefresh(
586 pullRequestEnvironment.diff({
587 environmentId,
@@ -312,55 +605,22 @@ function PullRequestCodeTab({
605 reportFailure: false,
606 });
607 const getDiffFileContents = useAtomCommand(pullRequestEnvironment.diffFileContents);
315 - const loadDiffFiles = useMemo(
316 - () =>
317 - createPullRequestDiffFileContentsLoader(getDiffFileContents, {
318 - environmentId,
319 - reference,
320 - commit,
321 - cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`,
322 - }),
323 - [commit, detail.updatedAt, environmentId, getDiffFileContents, reference, referenceKey],
324 - );
608 + const loadDiffFiles = usePullRequestDiffFileContentsLoader(getDiffFileContents, {
609 + environmentId,
610 + reference,
611 + commit,
612 + cacheKey: `pull-request:${referenceKey}:${detail.updatedAt}:${commit ?? "all"}`,
613 + });
614
326 - const review = useMemo(() => {
327 - const hostReview = detail.capabilities.review;
328 - const viewer = detail.viewerPermissions;
329 - return {
330 - inlineComment: hostReview.inlineComment && viewer.comment,
331 - reply: hostReview.reply && viewer.comment,
332 - resolve: hostReview.resolve && viewer.resolve,
333 - };
334 - }, [detail.capabilities.review, detail.viewerPermissions]);
615 + const hostReview = detail.capabilities.review;
616 + const review = {
617 + inlineComment: hostReview.inlineComment && detail.viewerPermissions.comment,
618 + reply: hostReview.reply && detail.viewerPermissions.comment,
619 + resolve: hostReview.resolve && detail.viewerPermissions.resolve,
620 + };
621 const canCommentOnLines = review.inlineComment && commit === null;
336 - // Every slice is parsed on its own and the result held, so a slice arriving costs one parse
337 - // rather than one per slice already on screen. Its cache key carries the theme, which is what
338 - // the tokenizer caches against, so a theme change is still a fresh parse.
339 - const parsedSlices = useMemo(
340 - () =>
341 - loadedSlices.map((slice) => {
342 - // The patch's own hash is part of the key: a refreshed page reuses its cursor, and a
343 - // key of position alone would keep handing back the parse of the patch it replaced.
344 - const cacheKey = `pull-request:${scopeKey}:${resolvedTheme}:${ignoreWhitespace}:${slice.cursor ?? "first"}:${fnv1a32(slice.patch)}`;
345 - const cached = parseCache.current.get(cacheKey);
346 - if (cached) return cached;
347 - const parsed = getRenderablePatch(slice.patch, cacheKey, {
348 - compactPartialHunkOffsets: true,
349 - ignoreWhitespace,
350 - });
351 - if (parsed) parseCache.current.set(cacheKey, parsed);
352 - return parsed;
353 - }),
354 - [loadedSlices, resolvedTheme, scopeKey, ignoreWhitespace],
355 - );
356 - const files = useMemo(
357 - () =>
358 - parsedSlices.flatMap((parsed) =>
359 - parsed?.kind === "files" ? orderDiffFiles(parsed.files) : [],
360 - ),
361 - [parsedSlices],
362 - );
363 - const filePaths = useMemo(() => files.map((file) => resolveFileDiffPath(file)), [files]);
622 + const { parsedSlices, files, filePaths, sourceFileStats, omittedFileStats, fileTreeEntries } =
623 + useParsedDiffSlices(loadedSlices, scopeKey, resolvedTheme, ignoreWhitespace);
624 const viewedFilesStore = detail.capabilities.viewedFiles;
625 const filesViewed = usePullRequestFilesViewed({
626 environmentId,
@@ -388,172 +648,20 @@ function PullRequestCodeTab({
648 loadedSlices.some((slice) => slice.truncated) ||
649 parsedSlices.some((parsed) => parsed?.kind === "raw");
650
391 - // Placing a conversation takes more than its file being in the diff: its line has to fall
392 - // inside a hunk that was rendered. One that does not is drawn nowhere, so it belongs in the
393 - // off-diff list rather than disappearing between the two.
394 - const placedThreadIds = useMemo(() => {
395 - const placed = new Set<string>();
396 - // A commit's diff counts lines within that commit; a review comment is anchored to the
397 - // pull request's head diff. Pinning one onto the other would put the remark against
398 - // whichever code happens to hold that line number in this commit, so while a commit is on
399 - // screen every conversation is listed rather than placed.
400 - if (commit !== null) return placed;
401 - for (const file of files) {
402 - const path = resolveFileDiffPath(file);
403 - for (const thread of detail.reviewThreads) {
404 - if (
405 - thread.path === path &&
406 - thread.line !== null &&
407 - isLineInFileDiff(file, thread.side, thread.line)
408 - ) {
409 - placed.add(thread.id);
410 - }
411 - }
412 - }
413 - return placed;
414 - }, [commit, detail.reviewThreads, files]);
415 -
416 - const annotatedFiles = useMemo(
417 - () =>
418 - files.map((fileDiff) => {
419 - const fileKey = buildFileDiffRenderKey(fileDiff);
420 - const path = resolveFileDiffPath(fileDiff);
421 - const groups = new Map<string, MutableAnnotationGroup>();
422 - const groupAt = (side: PullRequestDiffSide, line: number) => {
423 - const key = `${side}:${line}`;
424 - const existing = groups.get(key);
425 - if (existing) return existing;
426 - const created: MutableAnnotationGroup = {
427 - side,
428 - line,
429 - threads: [],
430 - pending: [],
431 - draft: false,
432 - };
433 - groups.set(key, created);
434 - return created;
435 - };
436 -
437 - for (const thread of detail.reviewThreads) {
438 - if (thread.path !== path || thread.line === null) continue;
439 - if (!placedThreadIds.has(thread.id)) continue;
440 - groupAt(thread.side, thread.line).threads.push(thread);
441 - }
442 - if (commit === null) {
443 - for (const comment of pendingComments) {
444 - if (comment.path !== path) continue;
445 - const anchor = getReviewPositionAnchor(comment.position);
446 - groupAt(anchor.side, anchor.line).pending.push(comment);
447 - }
448 - }
449 - if (draft?.fileKey === fileKey) {
450 - const anchor = getReviewPositionAnchor(draft.position);
451 - groupAt(anchor.side, anchor.line).draft = true;
452 - }
453 -
454 - const annotations: ReviewAnnotation[] = [...groups.values()].map((group) => ({
455 - side: toViewerSide(group.side),
456 - lineNumber: group.line,
457 - metadata: { threads: group.threads, pending: group.pending, draft: group.draft },
458 - }));
459 - return {
460 - fileKey,
461 - path,
462 - fileDiff,
463 - annotations,
464 - // The viewer re-renders an item only when its version changes, so everything the
465 - // annotations show has to be part of it.
466 - annotationsVersion: fnv1a32(
467 - annotations
468 - .map(
469 - ({ side, lineNumber, metadata }) =>
470 - `${side}:${lineNumber}:${metadata.draft ? "d" : ""}:${metadata.pending
471 - .map((comment) => `${comment.id}:${comment.body}`)
472 - .join(",")}:${metadata.threads
473 - .map(
474 - (thread) =>
475 - `${thread.id}:${thread.isResolved ? "r" : ""}:${
476 - thread.isOutdated ? "o" : ""
477 - }:${thread.comments
478 - .map(
479 - (comment) =>
480 - `${comment.id}:${comment.author?.login ?? ""}:${comment.createdAt}:${comment.body}:${(
481 - comment.reactions ?? []
482 - )
483 - .map(
484 - (r) => `${r.content}:${r.count}:${r.viewerHasReacted ? "v" : ""}`,
485 - )
486 - .join(",")}`,
487 - )
488 - .join(";")}`,
489 - )
490 - .join(",")}`,
491 - )
492 - .join("|"),
493 - ),
494 - };
495 - }),
496 - [commit, detail.reviewThreads, draft, files, pendingComments, placedThreadIds],
651 + const { annotatedFiles, placedThreadIds } = useAnnotatedDiffFiles(
652 + files,
653 + detail.reviewThreads,
654 + pendingComments,
655 + draft,
656 + commit !== null,
657 );
658
499 - const items = useMemo<CodeViewDiffItem<ReviewAnnotationGroup>[]>(
500 - () =>
501 - annotatedFiles.map(({ fileKey, path, fileDiff, annotations, annotationsVersion }) => {
502 - const collapsed = isFileDiffCollapsed(fileKey, effectiveFoldOverride, toggledFiles);
503 - const viewedMark = filesViewedEnabled
504 - ? `e${isFileViewed(path) ? "v" : ""}${isFileViewedStale(path) ? "s" : ""}`
505 - : "";
506 - return {
507 - id: fileKey,
508 - type: "diff" as const,
509 - fileDiff,
510 - annotations,
511 - collapsed,
512 - version: fnv1a32(`${collapsed ? "1" : "0"}:${viewedMark}:${annotationsVersion}`),
513 - };
514 - }),
515 - [
516 - annotatedFiles,
517 - filesViewedEnabled,
518 - effectiveFoldOverride,
519 - isFileViewed,
520 - isFileViewedStale,
521 - toggledFiles,
522 - ],
523 - );
524 - const omittedFileStats = useMemo(
525 - () =>
526 - new Map(
527 - loadedSlices.flatMap((slice) =>
528 - slice.omittedFileStats.map((file) => [file.path, file] as const),
529 - ),
530 - ),
531 - [loadedSlices],
532 - );
533 - const sourceFileStats = useMemo(
534 - () =>
535 - new Map(
536 - parsedSlices.flatMap((parsed) =>
537 - parsed?.kind === "files"
538 - ? parsed.files.map(
539 - (file, index) =>
540 - [
541 - buildFileDiffRenderKey(file),
542 - getDiffLineStat([parsed.sourceFiles[index] ?? file]),
543 - ] as const,
544 - )
545 - : [],
546 - ),
547 - ),
548 - [parsedSlices],
549 - );
550 - const fileKeys = useMemo(() => items.map((item) => item.id), [items]);
551 - const collapsedFileKeys = useMemo(
552 - () => new Set(items.filter((item) => item.collapsed === true).map((item) => item.id)),
553 - [items],
659 + const items = useDiffItems(annotatedFiles, effectiveFoldOverride, toggledFiles, filesViewed);
660 + const fileKeys = items.map((item) => item.id);
661 + const collapsedFileKeys = new Set(
662 + items.filter((item) => item.collapsed === true).map((item) => item.id),
663 );
664 const allFilesCollapsed = areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys);
556 - const fileTreeEntries = useMemo(() => diffFileTreeEntries(files), [files]);
665
666 // A failed slice must not be asked for again on its own. The files already loaded keep the
667 // sentinel on screen, so re-arming it after a failure would request the same slice forever.
@@ -562,10 +670,10 @@ function PullRequestCodeTab({
670 nextCursor !== cursor &&
671 !diffQuery.isPending &&
672 diffQuery.error === null;
565 - const loadNextSlice = useCallback(() => {
673 + const loadNextSlice = () => {
674 if (nextCursor === null) return;
675 setSliceState((previous) => ({ ...previous, cursor: nextCursor }));
568 - }, [nextCursor]);
676 + };
677
678 // The sentinel is held as state rather than a ref because the viewer mounts its own footer:
679 // an effect reading a ref could run before that node exists and would never arm the observer.
@@ -582,39 +690,36 @@ function PullRequestCodeTab({
690 return () => observer.disconnect();
691 }, [canLoadNextSlice, loadNextSlice, sentinel]);
692
585 - const toggleFile = useCallback(
586 - (fileKey: string) =>
587 - setToggledFiles((current) => {
588 - const next = new Set(current);
589 - if (next.has(fileKey)) next.delete(fileKey);
590 - else next.add(fileKey);
591 - return next;
592 - }),
593 - [],
594 - );
693 + const toggleFile = (fileKey: string) =>
694 + setToggledFiles((current) => {
695 + const next = new Set(current);
696 + if (next.has(fileKey)) next.delete(fileKey);
697 + else next.add(fileKey);
698 + return next;
699 + });
700
596 - const setFileViewed = useCallback(
597 - (fileKey: string, path: string, viewed: boolean) => {
598 - setViewed(path, viewed);
599 - setToggledFiles((current) =>
600 - toggleFileDiffFoldForViewed(fileKey, viewed, effectiveFoldOverride, current),
601 - );
602 - },
603 - [effectiveFoldOverride, setViewed],
604 - );
701 + const setFileViewed = (fileKey: string, path: string, viewed: boolean) => {
702 + setViewed(path, viewed);
703 + setToggledFiles((current) =>
704 + toggleFileDiffFoldForViewed(fileKey, viewed, effectiveFoldOverride, current),
705 + );
706 + };
707 + const fileViewedToggle = {
708 + enabled: filesViewedEnabled,
709 + isViewed: isFileViewed,
710 + isStale: isFileViewedStale,
711 + setFileViewed,
712 + };
713
714 const requestTreeReveal = useCodeViewFileReveal(viewer, scopeKey);
607 - const revealFile = useCallback(
608 - (path: string) => {
609 - const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path);
610 - if (item === undefined) return;
611 - if (item.collapsed === true) toggleFile(item.id);
612 - requestTreeReveal(item.id);
613 - },
614 - [items, requestTreeReveal, toggleFile],
615 - );
715 + const revealFile = (path: string) => {
716 + const item = items.find((candidate) => resolveFileDiffPath(candidate.fileDiff) === path);
717 + if (item === undefined) return;
718 + if (item.collapsed === true) toggleFile(item.id);
719 + requestTreeReveal(item.id);
720 + };
721 const answeredReveal = useRef<number | null>(null);
617 - useEffect(() => {
722 + const answerReveal = useEffectEvent(() => {
723 if (revealRequest === null || answeredReveal.current === revealRequest.nonce) return;
724 if (!items.some((item) => resolveFileDiffPath(item.fileDiff) === revealRequest.path)) {
725 if (canLoadNextSlice) loadNextSlice();
@@ -622,357 +727,285 @@ function PullRequestCodeTab({
727 }
728 answeredReveal.current = revealRequest.nonce;
729 revealFile(revealRequest.path);
625 - }, [canLoadNextSlice, items, loadNextSlice, revealFile, revealRequest]);
730 + });
731 + useEffect(() => {
732 + // oxlint-disable-next-line react/set-state-in-effect -- A reveal for a file not loaded yet pages forward, which sets the slice cursor.
733 + answerReveal();
734 + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Re-checked as pages load until the requested file arrives.
735 + }, [canLoadNextSlice, items, revealRequest]);
736
737 const toggleAllFiles = () => {
738 setFoldOverride(areAllDiffFilesCollapsed(fileKeys, collapsedFileKeys) ? "expanded" : "folded");
739 setToggledFiles(new Set());
740 };
741
632 - const orderedCommits = useMemo(
633 - () =>
634 - // By instant, not by the text: GitLab keeps a commit's own UTC offset, so two commits
635 - // from different zones would sort by how they were written rather than when they landed.
636 - detail.commits.toSorted(
637 - (left, right) => Date.parse(right.committedDate) - Date.parse(left.committedDate),
638 - ),
639 - [detail.commits],
640 - );
742 + const orderedCommits = // By instant, not by the text: GitLab keeps a commit's own UTC offset, so two commits
743 + // from different zones would sort by how they were written rather than when they landed.
744 + detail.commits.toSorted(
745 + (left, right) => Date.parse(right.committedDate) - Date.parse(left.committedDate),
746 + );
747
642 - const beginComment = useCallback(
643 - (range: SelectedLineRange | null, context: { item: CodeViewItem<ReviewAnnotationGroup> }) => {
644 - if (!range || !canCommentOnLines) return;
645 - const item = context.item;
646 - if (item.type !== "diff") return;
647 - const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === item.id);
648 - if (!file) return;
649 - // A range collapses to its last line: only GitHub carries a multi-line comment, and one
650 - // that silently lost its first line on the other hosts would be worse than one line.
651 - const path = resolveFileDiffPath(file);
652 - const previousPath = resolveFileDiffPreviousPath(file);
653 - const sourceFile = parsedSlices
654 - .flatMap((slice) => (slice?.kind === "files" ? slice.sourceFiles : []))
655 - .find((candidate) => resolveFileDiffPath(candidate) === path);
656 - const side = range.endSide ?? range.side;
657 - const position =
658 - (sourceFile && resolveDiffReviewPosition(sourceFile, range.end, side)) ??
659 - resolveDiffReviewPosition(file, range.end, side);
660 - if (position === null) return;
661 - setDraft({
662 - fileKey: item.id,
663 - path,
664 - oldPath: previousPath === path ? null : previousPath,
665 - position,
666 - range,
667 - });
668 - },
669 - [canCommentOnLines, files, parsedSlices],
670 - );
748 + const beginComment = (
749 + range: SelectedLineRange | null,
750 + context: { item: CodeViewItem<ReviewAnnotationGroup> },
751 + ) => {
752 + if (!range || !canCommentOnLines) return;
753 + const item = context.item;
754 + if (item.type !== "diff") return;
755 + const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === item.id);
756 + if (!file) return;
757 + // A range collapses to its last line: only GitHub carries a multi-line comment, and one
758 + // that silently lost its first line on the other hosts would be worse than one line.
759 + const path = resolveFileDiffPath(file);
760 + const previousPath = resolveFileDiffPreviousPath(file);
761 + const sourceFile = parsedSlices
762 + .flatMap((slice) => (slice?.kind === "files" ? slice.sourceFiles : []))
763 + .find((candidate) => resolveFileDiffPath(candidate) === path);
764 + const side = range.endSide ?? range.side;
765 + const position =
766 + (sourceFile && resolveDiffReviewPosition(sourceFile, range.end, side)) ??
767 + resolveDiffReviewPosition(file, range.end, side);
768 + if (position === null) return;
769 + setDraft({
770 + fileKey: item.id,
771 + path,
772 + oldPath: previousPath === path ? null : previousPath,
773 + position,
774 + range,
775 + });
776 + };
777
672 - const finishSelection = useCallback(
673 - (anchor: DraftAnchor, text: string, onFinish: (comment: ReviewCommentContext) => void) => {
674 - const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === anchor.fileKey);
675 - const comment =
676 - file === undefined
677 - ? null
678 - : buildDiffReviewComment({
679 - id: `pull-request-selection:${anchor.fileKey}:${anchor.range.start}:${anchor.range.end}`,
680 - sectionId: `pull-request:${detail.number}`,
681 - sectionTitle: `PR #${detail.number} review`,
682 - filePath: anchor.path,
683 - fileDiff: file,
684 - range: anchor.range,
685 - text,
686 - });
687 - setDraft(null);
688 - setSelectedLines(null);
689 - if (comment !== null) onFinish(comment);
690 - },
691 - [detail.number, files],
692 - );
778 + const finishSelection = (
779 + anchor: DraftAnchor,
780 + text: string,
781 + onFinish: (comment: ReviewCommentContext) => void,
782 + ) => {
783 + const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === anchor.fileKey);
784 + const comment =
785 + file === undefined
786 + ? null
787 + : buildDiffReviewComment({
788 + id: `pull-request-selection:${anchor.fileKey}:${anchor.range.start}:${anchor.range.end}`,
789 + sectionId: `pull-request:${detail.number}`,
790 + sectionTitle: `PR #${detail.number} review`,
791 + filePath: anchor.path,
792 + fileDiff: file,
793 + range: anchor.range,
794 + text,
795 + });
796 + setDraft(null);
797 + setSelectedLines(null);
798 + if (comment !== null) onFinish(comment);
799 + };
800
801 // The viewer's SlotPortals memoizes each visible file's header/annotation portal on these
802 // render props and on `options` below; a fresh identity on any of them — as a plain inline
803 // function or object literal would be — invalidates that memo and recreates every portal on
804 // screen on any tab re-render (a drag-selection, a keystroke in the draft, a review-store
805 // update), which is the jank this file is otherwise clean of.
699 - const renderCodeViewFooter = useCallback(
700 - () =>
701 - nextCursor === null ? null : (
702 - <div
703 - ref={setSentinel}
704 - className="flex items-center justify-center gap-2 py-2 text-xs text-muted-foreground"
705 - >
706 - {diffQuery.error !== null ? (
707 - <>
708 - <span>The rest of this diff could not be loaded.</span>
709 - <Button size="xs" variant="outline" onClick={() => diffQuery.refresh()}>
710 - Retry
711 - </Button>
712 - </>
713 - ) : diffQuery.isPending ? (
714 - "Loading more files..."
715 - ) : null}
716 - </div>
717 - ),
718 - [nextCursor, diffQuery.error, diffQuery.isPending, diffQuery.refresh],
719 - );
720 -
721 - const renderHeaderPrefix = useCallback(
722 - (item: CodeViewItem<ReviewAnnotationGroup>) => {
723 - const collapsed = item.collapsed === true;
724 - return (
725 - <Button
726 - size="icon-micro"
727 - variant="ghost-muted"
728 - aria-expanded={!collapsed}
729 - aria-label={collapsed ? "Expand diff" : "Collapse diff"}
730 - className="mr-1"
731 - onClick={(event) => {
732 - event.stopPropagation();
733 - toggleFile(item.id);
734 - }}
735 - >
736 - <MorphIcon className="size-4" icon={collapsed ? ChevronRight : ChevronDown} />
737 - </Button>
738 - );
739 - },
740 - [toggleFile],
741 - );
806 + const renderCodeViewFooter = () =>
807 + nextCursor === null ? null : (
808 + <div
809 + ref={setSentinel}
810 + className="flex items-center justify-center gap-2 py-2 text-xs text-muted-foreground"
811 + >
812 + {diffQuery.error !== null ? (
813 + <>
814 + <span>The rest of this diff could not be loaded.</span>
815 + <Button size="xs" variant="outline" onClick={() => diffQuery.refresh()}>
816 + Retry
817 + </Button>
818 + </>
819 + ) : diffQuery.isPending ? (
820 + "Loading more files..."
821 + ) : null}
822 + </div>
823 + );
824
743 - const filesViewedRef = useRef(filesViewed);
744 - filesViewedRef.current = filesViewed;
745 - const setFileViewedRef = useRef(setFileViewed);
746 - setFileViewedRef.current = setFileViewed;
825 + const renderHeaderPrefix = (item: CodeViewItem<ReviewAnnotationGroup>) => {
826 + const collapsed = item.collapsed === true;
827 + return (
828 + <Button
829 + size="icon-micro"
830 + variant="ghost-muted"
831 + aria-expanded={!collapsed}
832 + aria-label={collapsed ? "Expand diff" : "Collapse diff"}
833 + className="mr-1"
834 + onClick={(event) => {
835 + event.stopPropagation();
836 + toggleFile(item.id);
837 + }}
838 + >
839 + <MorphIcon className="size-4" icon={collapsed ? ChevronRight : ChevronDown} />
840 + </Button>
841 + );
842 + };
843
748 - const renderHeaderMetadata = useCallback(
749 - (item: CodeViewItem<ReviewAnnotationGroup>) => {
750 - if (item.type !== "diff") return null;
751 - let { additions, deletions } =
752 - sourceFileStats.get(item.id) ?? getDiffLineStat([item.fileDiff]);
753 - const path = resolveFileDiffPath(item.fileDiff);
754 - if (additions === 0 && deletions === 0) {
755 - const withheld = omittedFileStats.get(path);
756 - if (withheld) ({ additions, deletions } = withheld);
757 - }
758 - const stat = (
759 - <PullRequestDiffStat
760 - additions={additions}
761 - deletions={deletions}
762 - className="font-mono text-2xs"
763 - />
764 - );
765 - const viewedFiles = filesViewedRef.current;
766 - if (!viewedFiles.enabled) return stat;
767 - const viewed = viewedFiles.isViewed(path);
768 - const stale = viewedFiles.isStale(path);
769 - return (
770 - <span className="flex items-center gap-3">
771 - {stat}
772 - <label
773 - data-viewed-toggle=""
774 - className="flex cursor-pointer select-none items-center gap-1.5 text-2xs text-muted-foreground"
775 - onClick={(event) => event.stopPropagation()}
776 - >
777 - <Checkbox
778 - aria-label={stale ? "Changed" : "Viewed"}
779 - checked={viewed}
780 - onCheckedChange={(next) => setFileViewedRef.current(item.id, path, next === true)}
781 - />
782 - {stale ? (
783 - <Tooltip>
784 - <TooltipTrigger render={<span className="text-warning-foreground" />}>
785 - Changed
786 - </TooltipTrigger>
787 - <TooltipPopup side="bottom">
788 - This file has been pushed to since you marked it viewed.
789 - </TooltipPopup>
790 - </Tooltip>
791 - ) : (
792 - <span className="@max-xs:hidden">Viewed</span>
793 - )}
794 - </label>
795 - </span>
796 - );
797 - },
798 - [omittedFileStats, sourceFileStats],
799 - );
844 + const renderHeaderMetadata = (item: CodeViewItem<ReviewAnnotationGroup>) => {
845 + if (item.type !== "diff") return null;
846 + let { additions, deletions } = sourceFileStats.get(item.id) ?? getDiffLineStat([item.fileDiff]);
847 + const path = resolveFileDiffPath(item.fileDiff);
848 + if (additions === 0 && deletions === 0) {
849 + const withheld = omittedFileStats.get(path);
850 + if (withheld) ({ additions, deletions } = withheld);
851 + }
852 + return (
853 + <FileViewedToggle
854 + fileKey={item.id}
855 + path={path}
856 + stat={
857 + <PullRequestDiffStat
858 + additions={additions}
859 + deletions={deletions}
860 + className="font-mono text-2xs"
861 + />
862 + }
863 + />
864 + );
865 + };
866
801 - const diffViewOptions = useMemo(
802 - () => ({
803 - diffStyle: diffLayout === "split" ? ("split" as const) : ("unified" as const),
804 - lineDiffType: "none" as const,
805 - overflow: wordWrap ? ("wrap" as const) : ("scroll" as const),
806 - theme: resolveDiffThemeName(resolvedTheme),
807 - preferredHighlighter: PREFERRED_HIGHLIGHTER,
808 - themeType: resolvedTheme,
809 - stickyHeaders: true,
810 - loadDiffFiles,
811 - enableGutterUtility: canCommentOnLines && draft === null,
812 - enableLineSelection: canCommentOnLines && draft === null,
813 - onGutterUtilityClick: beginComment,
814 - onLineSelectionEnd: beginComment,
815 - }),
816 - [diffLayout, wordWrap, resolvedTheme, loadDiffFiles, canCommentOnLines, draft, beginComment],
817 - );
867 + const diffViewOptions = {
868 + diffStyle: diffLayout === "split" ? ("split" as const) : ("unified" as const),
869 + lineDiffType: "none" as const,
870 + overflow: wordWrap ? ("wrap" as const) : ("scroll" as const),
871 + theme: resolveDiffThemeName(resolvedTheme),
872 + preferredHighlighter: PREFERRED_HIGHLIGHTER,
873 + themeType: resolvedTheme,
874 + stickyHeaders: true,
875 + loadDiffFiles,
876 + enableGutterUtility: canCommentOnLines && draft === null,
877 + enableLineSelection: canCommentOnLines && draft === null,
878 + onGutterUtilityClick: beginComment,
879 + onLineSelectionEnd: beginComment,
880 + };
881
819 - const runThreadCommand = useCallback(
820 - async (label: string, run: () => Promise<{ readonly _tag: string }>): Promise<boolean> => {
821 - if (threadPending) return false;
822 - setThreadPending(true);
823 - const result = await run();
824 - setThreadPending(false);
825 - if (result._tag === "Failure") {
826 - toastManager.add({ type: "error", title: label });
827 - return false;
828 - }
829 - onRefresh();
830 - return true;
831 - },
832 - [onRefresh, threadPending],
833 - );
882 + const runThreadCommand = async (
883 + label: string,
884 + run: () => Promise<{ readonly _tag: string }>,
885 + ): Promise<boolean> => {
886 + if (threadPending) return false;
887 + setThreadPending(true);
888 + const result = await run();
889 + setThreadPending(false);
890 + if (result._tag === "Failure") {
891 + toastManager.add({ type: "error", title: label });
892 + return false;
893 + }
894 + onRefresh();
895 + return true;
896 + };
897
835 - const renderThreadCard = useCallback(
836 - (thread: PullRequestReviewThread) => (
837 - <ReviewThreadCard
838 - // Named with the pull request too: a thread's id is the host's own, and two pull requests
839 - // can hand out the same one — which would leave one card's open editor standing over the
840 - // other's conversation.
841 - key={`${reference.projectId}#${reference.number}:${thread.id}`}
842 - thread={thread}
843 - workspaceRoot={detail.workspaceRoot}
844 - canReply={review.reply}
845 - canResolve={review.resolve && canResolvePullRequestThread(detail, thread)}
846 - canReact={detail.capabilities.reactions === true}
847 - environmentId={environmentId}
848 - reference={reference}
849 - pending={threadPending}
850 - fixPending={pendingFinding === pullRequestFindingKey({ kind: "thread", thread })}
851 - fixLabel={fixFindingLabel}
852 - {...(onFixFinding ? { onFix: () => onFixFinding({ kind: "thread", thread }) } : {})}
853 - onLoadMore={async (cursor): Promise<PullRequestThreadCommentsResult | null> => {
854 - const result = await loadThreadComments({
855 - environmentId,
856 - input: { ...reference, threadId: thread.id, cursor },
898 + const renderThreadCard = (thread: PullRequestReviewThread) => (
899 + <ReviewThreadCard
900 + // Named with the pull request too: a thread's id is the host's own, and two pull requests
901 + // can hand out the same one — which would leave one card's open editor standing over the
902 + // other's conversation.
903 + key={`${reference.projectId}#${reference.number}:${thread.id}`}
904 + thread={thread}
905 + workspaceRoot={detail.workspaceRoot}
906 + canReply={review.reply}
907 + canResolve={review.resolve && canResolvePullRequestThread(detail, thread)}
908 + canReact={detail.capabilities.reactions === true}
909 + environmentId={environmentId}
910 + reference={reference}
911 + pending={threadPending}
912 + fixPending={pendingFinding === pullRequestFindingKey({ kind: "thread", thread })}
913 + fixLabel={fixFindingLabel}
914 + {...(onFixFinding ? { onFix: () => onFixFinding({ kind: "thread", thread }) } : {})}
915 + onLoadMore={async (cursor): Promise<PullRequestThreadCommentsResult | null> => {
916 + const result = await loadThreadComments({
917 + environmentId,
918 + input: { ...reference, threadId: thread.id, cursor },
919 + });
920 + if (result._tag === "Failure") {
921 + toastManager.add({
922 + type: "error",
923 + title: "More comments could not be loaded",
924 });
858 - if (result._tag === "Failure") {
859 - toastManager.add({
860 - type: "error",
861 - title: "More comments could not be loaded",
862 - });
863 - return null;
864 - }
865 - return result.value;
866 - }}
867 - onReply={(body) =>
868 - runThreadCommand("Reply could not be posted", () =>
869 - replyToThread({
870 - environmentId,
871 - input: { ...reference, threadId: thread.id, body },
872 - }),
873 - )
925 + return null;
926 }
875 - canEditComment={(comment) =>
876 - canEditPullRequestComment(detail, {
877 - author: comment.author,
878 - kind: "review-comment",
879 - canEdit: comment.canEdit,
880 - })
881 - }
882 - onEditComment={(commentId, body) =>
883 - runThreadCommand("The comment could not be saved", () =>
884 - updateComment({
885 - environmentId,
886 - input: { ...reference, commentId, kind: "review-comment", body },
887 - }),
888 - )
889 - }
890 - onToggleResolved={() =>
891 - void runThreadCommand("The conversation could not be updated", () =>
892 - setThreadResolution({
893 - environmentId,
894 - input: { ...reference, threadId: thread.id, resolved: !thread.isResolved },
895 - }),
896 - )
897 - }
898 - onReacted={onRefresh}
899 - />
900 - ),
901 - [
902 - detail,
903 - environmentId,
904 - fixFindingLabel,
905 - loadThreadComments,
906 - onRefresh,
907 - onFixFinding,
908 - pendingFinding,
909 - reference,
910 - replyToThread,
911 - review.reply,
912 - review.resolve,
913 - runThreadCommand,
914 - setThreadResolution,
915 - threadPending,
916 - updateComment,
917 - ],
927 + return result.value;
928 + }}
929 + onReply={(body) =>
930 + runThreadCommand("Reply could not be posted", () =>
931 + replyToThread({
932 + environmentId,
933 + input: { ...reference, threadId: thread.id, body },
934 + }),
935 + )
936 + }
937 + canEditComment={(comment) =>
938 + canEditPullRequestComment(detail, {
939 + author: comment.author,
940 + kind: "review-comment",
941 + canEdit: comment.canEdit,
942 + })
943 + }
944 + onEditComment={(commentId, body) =>
945 + runThreadCommand("The comment could not be saved", () =>
946 + updateComment({
947 + environmentId,
948 + input: { ...reference, commentId, kind: "review-comment", body },
949 + }),
950 + )
951 + }
952 + onToggleResolved={() =>
953 + void runThreadCommand("The conversation could not be updated", () =>
954 + setThreadResolution({
955 + environmentId,
956 + input: { ...reference, threadId: thread.id, resolved: !thread.isResolved },
957 + }),
958 + )
959 + }
960 + onReacted={onRefresh}
961 + />
962 );
963
920 - const renderAnnotation = useCallback(
921 - (annotation: ReviewAnnotation) => (
922 - <div className="py-1 font-sans text-foreground">
923 - {annotation.metadata.threads.map(renderThreadCard)}
924 - {annotation.metadata.pending.map((comment) => (
925 - <PendingReviewCommentCard
926 - key={comment.id}
927 - comment={comment}
928 - onRemove={() => removeComment(reviewKey, comment.id)}
929 - />
930 - ))}
931 - {annotation.metadata.draft && draft ? (
932 - <DiffCommentAnnotation
933 - kind="draft"
934 - rangeLabel={`${draft.path}:${getReviewPositionAnchor(draft.position).line}`}
935 - text=""
936 - submitLabel="Add to review"
937 - {...(onAddToAgentSelection
938 - ? {
939 - secondaryAction: {
940 - label: "Add to agent",
941 - onAction: (text: string) =>
942 - finishSelection(draft, text, (comment) =>
943 - onAddToAgentSelection({ comment, request: text }),
944 - ),
945 - },
946 - }
947 - : {})}
948 - onCancel={() => {
949 - setDraft(null);
950 - setSelectedLines(null);
951 - }}
952 - onComment={(body) => {
953 - addComment(reviewKey, {
954 - id: nextPendingReviewCommentId(),
955 - path: draft.path,
956 - ...(draft.oldPath === null ? {} : { oldPath: draft.oldPath }),
957 - position: draft.position,
958 - body,
959 - });
960 - setDraft(null);
961 - setSelectedLines(null);
962 - }}
963 - />
964 - ) : null}
965 - </div>
966 - ),
967 - [
968 - addComment,
969 - draft,
970 - finishSelection,
971 - onAddToAgentSelection,
972 - removeComment,
973 - renderThreadCard,
974 - reviewKey,
975 - ],
964 + const renderAnnotation = (annotation: ReviewAnnotation) => (
965 + <div className="py-1 font-sans text-foreground">
966 + {annotation.metadata.threads.map(renderThreadCard)}
967 + {annotation.metadata.pending.map((comment) => (
968 + <PendingReviewCommentCard
969 + key={comment.id}
970 + comment={comment}
971 + onRemove={() => removeComment(reviewKey, comment.id)}
972 + />
973 + ))}
974 + {annotation.metadata.draft && draft ? (
975 + <DiffCommentAnnotation
976 + kind="draft"
977 + rangeLabel={`${draft.path}:${getReviewPositionAnchor(draft.position).line}`}
978 + text=""
979 + submitLabel="Add to review"
980 + {...(onAddToAgentSelection
981 + ? {
982 + secondaryAction: {
983 + label: "Add to agent",
984 + onAction: (text: string) =>
985 + finishSelection(draft, text, (comment) =>
986 + onAddToAgentSelection({ comment, request: text }),
987 + ),
988 + },
989 + }
990 + : {})}
991 + onCancel={() => {
992 + setDraft(null);
993 + setSelectedLines(null);
994 + }}
995 + onComment={(body) => {
996 + addComment(reviewKey, {
997 + id: nextPendingReviewCommentId(),
998 + path: draft.path,
999 + ...(draft.oldPath === null ? {} : { oldPath: draft.oldPath }),
1000 + position: draft.position,
1001 + body,
1002 + });
1003 + setDraft(null);
1004 + setSelectedLines(null);
1005 + }}
1006 + />
1007 + ) : null}
1008 + </div>
1009 );
1010
1011 // A rebase or a force-push can take the scoped commit out of the change. Its diff may still
@@ -1439,26 +1472,28 @@ function PullRequestCodeTab({
1472 {/* The viewer virtualizes against the element it is told is scrolling and places its
1473 rows absolutely, so it has to own that element — the thread diff panel hands it the
1474 same one. Scrolling from a parent instead leaves it painting over its neighbours. */}
1442 - <StyledDiffCodeView<ReviewAnnotationGroup>
1443 - className="@container h-full overflow-auto [scrollbar-gutter:stable]"
1444 - containerRef={scrollerRef}
1445 - viewerRef={setViewer}
1446 - items={items}
1447 - selectedLines={selectedLines}
1448 - onSelectedLinesChange={setSelectedLines}
1449 - options={diffViewOptions}
1450 - renderCodeViewFooter={renderCodeViewFooter}
1451 - renderHeaderPrefix={renderHeaderPrefix}
1452 - renderHeaderMetadata={renderHeaderMetadata}
1453 - renderAnnotation={renderAnnotation}
1454 - // Find can ask again before the unfolded file arrives, so this unfolds and never folds.
1455 - onRevealSearchMatch={(item) =>
1456 - setToggledFiles((current) =>
1457 - toggleFileDiffFoldForViewed(item.id, false, effectiveFoldOverride, current),
1458 - )
1459 - }
1460 - unsafeCSSExtra={REPLACE_FILE_COUNTS_CSS}
1461 - />
1475 + <FileViewedToggleContext value={fileViewedToggle}>
1476 + <StyledDiffCodeView<ReviewAnnotationGroup>
1477 + className="@container h-full overflow-auto [scrollbar-gutter:stable]"
1478 + containerRef={scrollerRef}
1479 + viewerRef={setViewer}
1480 + items={items}
1481 + selectedLines={selectedLines}
1482 + onSelectedLinesChange={setSelectedLines}
1483 + options={diffViewOptions}
1484 + renderCodeViewFooter={renderCodeViewFooter}
1485 + renderHeaderPrefix={renderHeaderPrefix}
1486 + renderHeaderMetadata={renderHeaderMetadata}
1487 + renderAnnotation={renderAnnotation}
1488 + // Find can ask again before the unfolded file arrives, so this unfolds and never folds.
1489 + onRevealSearchMatch={(item) =>
1490 + setToggledFiles((current) =>
1491 + toggleFileDiffFoldForViewed(item.id, false, effectiveFoldOverride, current),
1492 + )
1493 + }
1494 + unsafeCSSExtra={REPLACE_FILE_COUNTS_CSS}
1495 + />
1496 + </FileViewedToggleContext>
1497 </div>
1498 {fileTreeOpen ? (
1499 <aside className="flex w-[min(20rem,40%)] min-w-48 shrink-0 border-l border-border/60">