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): the pull requests page compiles with the React Compiler (#20539)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 16, 2026 at 21:02 UTC
5c5dcbc60b35aae59cbc554231afa9f2c04ad2ce
2 files changed
+832
-787
apps/web/reactCompiledFiles.ts
+1
@@ -96,4 +96,5 @@ export const REACT_COMPILED_FILES = [
96
"apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx",
97
"apps/web/src/components/ThreadTerminalDrawer.tsx",
98
"apps/web/src/components/settings/SettingsPanels.tsx",
99
+ "apps/web/src/routes/_chat.pull-requests.tsx",
100
] as const;
apps/web/src/routes/_chat.pull-requests.tsx
+831
-787
@@ -44,10 +44,8 @@ import {
44
type LucideIcon,
45
} from "lucide-react";
46
import {
47
- useCallback,
47
useEffect,
48
useEffectEvent,
50
- useMemo,
49
useRef,
50
useState,
51
type ComponentProps,
@@ -84,6 +82,7 @@ import {
82
type EnvironmentPullRequestEntry,
83
type MergedPullRequestList,
84
type PullRequestDiffStats,
85
+ type PullRequestGroup,
86
type PullRequestStatsBatch,
87
type PullRequestStatsPolicy,
88
type PullRequestStatsScope,
@@ -144,6 +143,7 @@ import { Menu, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "../
143
import { SidebarInset } from "../components/ui/sidebar";
144
import { Tooltip, TooltipPopup, TooltipTrigger } from "../components/ui/tooltip";
145
import { useLiveRefresh } from "../hooks/useLiveRefresh";
146
+import { useStableCallback } from "../hooks/useStableCallback";
147
import { useOpenPanelPullRequestUrl } from "../hooks/useOpenPanelPullRequestUrl";
148
import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
149
import { toastManager } from "../components/ui/toast";
@@ -254,6 +254,7 @@ const MATCHED_ELSEWHERE_SCORE = 10;
254
const PAGE_SIZE = 99;
255
const MAX_PAGE_SIZE = 500;
256
const EMPTY_VIEWERS: PullRequestListResult["viewers"] = {};
257
+const EMPTY_PARTITIONS: PullRequestPartitionsSnapshot = { authored: [], reviewing: [] };
258
const NO_LIST_TARGETS: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>> = [];
259
const EMPTY_PREVIEW_SESSIONS = {};
260
const EMPTY_PREVIEW_DESKTOP_STATE = {};
@@ -345,103 +346,26 @@ function PullRequestsRouteView() {
346
const navigate = useNavigate({ from: Route.fullPath });
347
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
348
const { environments } = useEnvironments();
348
- const capableEnvironments = useMemo(
349
- () =>
350
- environments
351
- .filter(
352
- (environment) => environment.serverConfig?.environment.capabilities.pullRequests === true,
353
- )
354
- .toSorted((left, right) => left.environmentId.localeCompare(right.environmentId)),
355
- [environments],
356
- );
357
- const scopedEnvironmentId =
358
- capableEnvironments.find((environment) => environment.environmentId === search.environmentId)
359
- ?.environmentId ?? null;
360
- const knownEnvironmentIds = useMemo(
361
- () => new Set(environments.map((environment) => environment.environmentId)),
362
- [environments],
363
- );
364
- const environmentIds = useMemo(
365
- () =>
366
- capableEnvironments
367
- .filter(
368
- (environment) =>
369
- scopedEnvironmentId === null || environment.environmentId === scopedEnvironmentId,
370
- )
371
- .map((environment) => environment.environmentId),
372
- [capableEnvironments, scopedEnvironmentId],
373
- );
374
- const environmentKey = useMemo(
375
- () => pullRequestEnvironmentSetKey(environmentIds),
376
- [environmentIds],
377
- );
378
- const capabilityKnown = environments.some((environment) => environment.serverConfig !== null);
379
- const pullRequestsSupported = environmentIds.length > 0;
349
const allProjects = useProjects();
350
const projectsKnown = useAllEnvironmentShellsBootstrapped();
382
- const projects = useMemo(
383
- () =>
384
- allProjects.filter(
385
- (project) => !project.isScratch && environmentIds.includes(project.environmentId),
386
- ),
387
- [allProjects, environmentIds],
388
- );
389
- const environmentLabels = useMemo(
390
- () =>
391
- new Map(
392
- environments.map((environment) => [environment.environmentId, environment.label] as const),
393
- ),
394
- [environments],
395
- );
396
- const scopedProjectId = useMemo(
397
- () => resolveProjectScope(search.projectId, projects, projectsKnown),
398
- [projects, projectsKnown, search.projectId],
399
- );
400
- const scopedProject = useMemo(
401
- () => findScopedProject(projects, scopedEnvironmentId, scopedProjectId),
402
- [projects, scopedEnvironmentId, scopedProjectId],
403
- );
404
- const scopedProjects = useMemo(
405
- () => pullRequestFilterProjects(projects, environmentLabels, scopedProject),
406
- [environmentLabels, projects, scopedProject],
407
- );
408
-
409
- const selectedHost = search.selectedHost ?? search.host;
410
- const projectIdForRepository = useMemo(() => {
411
- const repository = search.repository?.toLowerCase();
412
- if (repository === undefined) return undefined;
413
- const identity = projects.find(
414
- (project) =>
415
- project.repositoryIdentity?.owner &&
416
- project.repositoryIdentity.name &&
417
- `${project.repositoryIdentity.owner}/${project.repositoryIdentity.name}`.toLowerCase() ===
418
- repository &&
419
- (selectedHost === undefined ||
420
- pullRequestHostOf(
421
- project.repositoryIdentity,
422
- project.repositoryIdentity.provider as SourceControlProviderKind,
423
- ) === selectedHost.toLowerCase()),
424
- );
425
- return identity?.id;
426
- }, [projects, selectedHost, search.repository]);
427
-
428
- const linkedProjectId = useMemo(
429
- () => resolveProjectScope(search.selectedProjectId, projects, projectsKnown),
430
- [projects, projectsKnown, search.selectedProjectId],
431
- );
432
- const selectedProjectId = linkedProjectId ?? projectIdForRepository ?? scopedProjectId;
433
- // A named server still connecting is kept named rather than falling back: falling back while it
434
- // is merely not ready yet would resolve the project against whatever other server has answered,
435
- // which can be the wrong one where two servers share a project id.
436
- const selectedEnvironmentId = resolveSelectedEnvironmentId(
437
- search.selectedEnvironmentId,
438
- knownEnvironmentIds,
351
+ const {
352
+ capableEnvironments,
353
scopedEnvironmentId,
440
- );
441
- const selectedProject = useMemo(
442
- () => findScopedProject(projects, selectedEnvironmentId, selectedProjectId),
443
- [projects, selectedEnvironmentId, selectedProjectId],
444
- );
354
+ environmentKey,
355
+ capabilityKnown,
356
+ pullRequestsSupported,
357
+ projects,
358
+ environmentLabels,
359
+ scopedProjectId,
360
+ scopedProject,
361
+ scopedProjects,
362
+ selectedProject,
363
+ queryEnvironmentIds,
364
+ environmentQueries,
365
+ assignmentKey,
366
+ linkedSelection,
367
+ expectedHosts,
368
+ } = usePullRequestScope(environments, allProjects, projectsKnown, search);
369
const rightPanelRef = capableEnvironments.length === 0 ? null : PULL_REQUESTS_PANEL_REF;
370
const openPanelPullRequestUrl = useOpenPanelPullRequestUrl(rightPanelRef);
371
const rightPanelState = useRightPanelStore((state) =>
@@ -455,13 +379,10 @@ function PullRequestsRouteView() {
379
const activePullRequestSurface = rightPanelState.isOpen ? selectedPullRequestSurface : null;
380
const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
381
usePanelAnimationSettings();
458
- const rightPanelPresenceValue = useMemo(
459
- () => ({
460
- activeSurface: selectedPullRequestSurface,
461
- surfaces: rightPanelState.surfaces,
462
- }),
463
- [rightPanelState.surfaces, selectedPullRequestSurface],
464
- );
382
+ const rightPanelPresenceValue = {
383
+ activeSurface: selectedPullRequestSurface,
384
+ surfaces: rightPanelState.surfaces,
385
+ };
386
const rightPanelPresence = usePanelPresence(
387
rightPanelState.isOpen && selectedPullRequestSurface !== null,
388
rightPanelPresenceValue,
@@ -476,39 +397,36 @@ function PullRequestsRouteView() {
397
(renderedPullRequestSurface?.environmentId as EnvironmentId | undefined) ??
398
selectedProject?.environmentId ??
399
null;
479
- const updateSearch = useCallback(
480
- (patch: {
481
- [Key in keyof PullRequestsSearch]?: PullRequestsSearch[Key] | undefined;
482
- }) =>
483
- void navigate({
484
- search: (previous: PullRequestsSearch): PullRequestsSearch => {
485
- const next = { ...previous, ...patch };
486
- return {
487
- involvement: next.involvement ?? previous.involvement,
488
- state: next.state ?? previous.state,
489
- ...(next.sort && next.sort !== "ready" ? { sort: next.sort } : {}),
490
- ...(next.repository ? { repository: next.repository } : {}),
491
- ...(next.number ? { number: next.number } : {}),
492
- ...(next.projectId ? { projectId: next.projectId } : {}),
493
- ...(next.environmentId ? { environmentId: next.environmentId } : {}),
494
- ...(next.host ? { host: next.host } : {}),
495
- ...(next.selectedHost ? { selectedHost: next.selectedHost } : {}),
496
- ...(next.selectedProjectId ? { selectedProjectId: next.selectedProjectId } : {}),
497
- ...(next.selectedEnvironmentId
498
- ? { selectedEnvironmentId: next.selectedEnvironmentId }
499
- : {}),
500
- ...(next.q ? { q: next.q } : {}),
501
- ...(next.draft ? { draft: next.draft } : {}),
502
- ...(next.review ? { review: next.review } : {}),
503
- ...(next.checks ? { checks: next.checks } : {}),
504
- ...(next.author ? { author: next.author } : {}),
505
- ...(next.labels && next.labels.length > 0 ? { labels: next.labels } : {}),
506
- };
507
- },
508
- replace: true,
509
- }),
510
- [navigate],
511
- );
400
+ const updateSearch = (patch: {
401
+ [Key in keyof PullRequestsSearch]?: PullRequestsSearch[Key] | undefined;
402
+ }) =>
403
+ void navigate({
404
+ search: (previous: PullRequestsSearch): PullRequestsSearch => {
405
+ const next = { ...previous, ...patch };
406
+ return {
407
+ involvement: next.involvement ?? previous.involvement,
408
+ state: next.state ?? previous.state,
409
+ ...(next.sort && next.sort !== "ready" ? { sort: next.sort } : {}),
410
+ ...(next.repository ? { repository: next.repository } : {}),
411
+ ...(next.number ? { number: next.number } : {}),
412
+ ...(next.projectId ? { projectId: next.projectId } : {}),
413
+ ...(next.environmentId ? { environmentId: next.environmentId } : {}),
414
+ ...(next.host ? { host: next.host } : {}),
415
+ ...(next.selectedHost ? { selectedHost: next.selectedHost } : {}),
416
+ ...(next.selectedProjectId ? { selectedProjectId: next.selectedProjectId } : {}),
417
+ ...(next.selectedEnvironmentId
418
+ ? { selectedEnvironmentId: next.selectedEnvironmentId }
419
+ : {}),
420
+ ...(next.q ? { q: next.q } : {}),
421
+ ...(next.draft ? { draft: next.draft } : {}),
422
+ ...(next.review ? { review: next.review } : {}),
423
+ ...(next.checks ? { checks: next.checks } : {}),
424
+ ...(next.author ? { author: next.author } : {}),
425
+ ...(next.labels && next.labels.length > 0 ? { labels: next.labels } : {}),
426
+ };
427
+ },
428
+ replace: true,
429
+ });
430
431
const clearedSelection = {
432
repository: undefined,
@@ -532,70 +450,16 @@ function PullRequestsRouteView() {
450
const [filtersOpen, setFiltersOpen] = useState(false);
451
const sentQuery = useDebouncedValue(typedQuery, SEARCH_DEBOUNCE_MS);
452
const querySettled = typedQuery === sentQuery;
535
- const typedParsed = useMemo(() => parsePullRequestQuery(typedQuery), [typedQuery]);
536
- const sentParsed = useMemo(() => parsePullRequestQuery(sentQuery), [sentQuery]);
537
-
538
- const menuFilters = useMemo(
539
- (): PullRequestListFilters => ({
540
- ...(search.draft ? { draft: search.draft } : {}),
541
- ...(search.review ? { review: search.review } : {}),
542
- ...(search.checks ? { checks: search.checks } : {}),
543
- ...(search.author ? { author: search.author } : {}),
544
- ...(search.labels ? { labels: search.labels.map((label) => [label]) } : {}),
545
- }),
546
- [search.author, search.checks, search.draft, search.labels, search.review],
547
- );
548
- const menuFiltered = Object.keys(menuFilters).length > 0;
549
- const filters = useMemo(
550
- (): PullRequestListFilters => ({ ...menuFilters, ...sentParsed.filters }),
551
- [menuFilters, sentParsed.filters],
552
- );
553
- const hasFilters = Object.keys(filters).length > 0;
554
- const localFilters = useMemo(
555
- (): PullRequestListFilters => ({ ...menuFilters, ...typedParsed.filters }),
556
- [menuFilters, typedParsed.filters],
557
- );
558
- const hasLocalFilters = Object.keys(localFilters).length > 0;
559
- const queryEnvironmentIds = useMemo(
560
- () =>
561
- resolveQueryEnvironmentIds(
562
- environmentIds,
563
- projects,
564
- scopedProject,
565
- scopedProjectId,
566
- projectsKnown,
567
- ),
568
- [environmentIds, projects, projectsKnown, scopedProject, scopedProjectId],
569
- );
570
- const environmentQueries = useMemo((): ReadonlyArray<{
571
- readonly environmentId: EnvironmentId;
572
- readonly projectIds?: ReadonlyArray<ProjectId>;
573
- }> => {
574
- const plain = queryEnvironmentIds.map((environmentId) => ({ environmentId }));
575
- if (!projectsKnown || scopedProjectId !== undefined) return plain;
576
- const assignment = assignProjectsToEnvironments(
577
- projects,
578
- queryEnvironmentIds,
579
- queryEnvironmentIds[0],
580
- );
581
- const totals = new Map<EnvironmentId, number>();
582
- for (const project of projects) {
583
- totals.set(project.environmentId, (totals.get(project.environmentId) ?? 0) + 1);
584
- }
585
- return queryEnvironmentIds.flatMap((environmentId) => {
586
- const projectIds = assignment.get(environmentId);
587
- if (projectIds === undefined) return [];
588
- if (projectIds.length === (totals.get(environmentId) ?? 0)) return [{ environmentId }];
589
- return [{ environmentId, projectIds }];
590
- });
591
- }, [projects, projectsKnown, queryEnvironmentIds, scopedProjectId]);
592
- const assignmentKey = useMemo(
593
- () =>
594
- environmentQueries
595
- .map(({ environmentId, projectIds }) => `${environmentId}#${projectIds?.join("+") ?? "*"}`)
596
- .join("|"),
597
- [environmentQueries],
598
- );
453
+ const {
454
+ typedParsed,
455
+ sentParsed,
456
+ menuFilters,
457
+ menuFiltered,
458
+ filters,
459
+ hasFilters,
460
+ localFilters,
461
+ hasLocalFilters,
462
+ } = usePullRequestQueryFilters(search, typedQuery, sentQuery);
463
const turnRefreshes = usePullRequestTurnRefreshes(
464
environmentQueries.map(({ environmentId }) => environmentId),
465
);
@@ -604,8 +468,7 @@ function PullRequestsRouteView() {
468
.join("|");
469
const scopeKey = `${environmentKey}:${assignmentKey}:${search.state}:${search.involvement}:${scopedProjectId ?? ""}:${search.host ?? ""}:${search.draft ?? ""}:${search.review ?? ""}:${search.checks ?? ""}:${search.author ?? ""}:${search.labels?.join("\u0000") ?? ""}`;
470
const filterKey = `${scopeKey}:${sentQuery}`;
607
- const statsScopeRef = useRef<PullRequestStatsScope>({ key: filterKey, policy: statsPolicy });
608
- statsScopeRef.current = { key: filterKey, policy: statsPolicy };
471
+ const statsScope: PullRequestStatsScope = { key: filterKey, policy: statsPolicy };
472
const [page, setPage] = useState<{
473
key: string;
474
size: number;
@@ -621,86 +484,58 @@ function PullRequestsRouteView() {
484
const sentCursors = page.key === filterKey ? page.cursors : null;
485
const sentRegrown = page.key === filterKey ? page.regrown : [];
486
624
- useEffect(() => {
487
+ if (page.key !== filterKey) {
488
setPage({ key: filterKey, size: PAGE_SIZE, cursors: null, regrown: [] });
626
- }, [filterKey]);
627
-
628
- const listTargets = useMemo(
629
- () =>
630
- environmentQueries.flatMap(({ environmentId, projectIds }) => {
631
- const cursors = sentCursors?.[environmentId];
632
- if (sentCursors !== null && cursors === undefined && !sentRegrown.includes(environmentId)) {
633
- return [];
634
- }
635
- return [
636
- {
637
- environmentId,
638
- input: {
639
- state: search.state,
640
- involvement: search.involvement,
641
- limit: pageSize,
642
- ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
643
- ...(projectIds ? { projectIds } : {}),
644
- ...(search.host ? { host: search.host } : {}),
645
- ...(hasFilters ? { filters } : {}),
646
- ...(sentParsed.text ? { query: sentParsed.text } : {}),
647
- ...(cursors === undefined ? {} : { cursors }),
648
- } satisfies PullRequestListInput,
649
- },
650
- ];
651
- }),
652
- [
653
- filters,
654
- hasFilters,
655
- pageSize,
656
- environmentQueries,
657
- scopedProjectId,
658
- search.host,
659
- search.involvement,
660
- search.state,
661
- sentCursors,
662
- sentRegrown,
663
- sentParsed.text,
664
- ],
665
- );
666
- const listQuery = usePullRequestList(listTargets);
489
+ }
490
668
- /**
669
- * Kept as its own read rather than remembered from an earlier answer because an answer cannot
670
- * say which question it belongs to: mid-switch the text has already changed and the data has
671
- * not, and a search's answer would file itself under the workspace.
672
- */
673
- const baselineTargets = useMemo(
674
- () =>
675
- environmentQueries.map(({ environmentId, projectIds }) => ({
491
+ const listTargets = environmentQueries.flatMap(({ environmentId, projectIds }) => {
492
+ const cursors = sentCursors?.[environmentId];
493
+ if (sentCursors !== null && cursors === undefined && !sentRegrown.includes(environmentId)) {
494
+ return [];
495
+ }
496
+ return [
497
+ {
498
environmentId,
499
input: {
500
state: search.state,
501
involvement: search.involvement,
680
- limit: PAGE_SIZE,
502
+ limit: pageSize,
503
...(scopedProjectId ? { projectId: scopedProjectId } : {}),
504
...(projectIds ? { projectIds } : {}),
505
...(search.host ? { host: search.host } : {}),
684
- ...(menuFiltered ? { filters: menuFilters } : {}),
506
+ ...(hasFilters ? { filters } : {}),
507
+ ...(sentParsed.text ? { query: sentParsed.text } : {}),
508
+ ...(cursors === undefined ? {} : { cursors }),
509
} satisfies PullRequestListInput,
686
- })),
687
- [
688
- menuFiltered,
689
- menuFilters,
690
- environmentQueries,
691
- scopedProjectId,
692
- search.host,
693
- search.involvement,
694
- search.state,
695
- ],
696
- );
510
+ },
511
+ ];
512
+ });
513
+ const listQuery = usePullRequestList(listTargets);
514
+
515
+ /**
516
+ * Kept as its own read rather than remembered from an earlier answer because an answer cannot
517
+ * say which question it belongs to: mid-switch the text has already changed and the data has
518
+ * not, and a search's answer would file itself under the workspace.
519
+ */
520
+ const baselineTargets = environmentQueries.map(({ environmentId, projectIds }) => ({
521
+ environmentId,
522
+ input: {
523
+ state: search.state,
524
+ involvement: search.involvement,
525
+ limit: PAGE_SIZE,
526
+ ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
527
+ ...(projectIds ? { projectIds } : {}),
528
+ ...(search.host ? { host: search.host } : {}),
529
+ ...(menuFiltered ? { filters: menuFilters } : {}),
530
+ } satisfies PullRequestListInput,
531
+ }));
532
const baselineQuery = usePullRequestList(baselineTargets);
533
const baselineEmpty =
534
baselineQuery.data?.entries.length === 0 &&
535
baselineQuery.data.errors.length === 0 &&
536
!baselineQuery.isPending &&
537
baselineQuery.error === null;
703
- const facetTargets = useMemo(() => {
538
+ const facetTargets = (() => {
539
if (!filtersOpen) return NO_LIST_TARGETS;
540
return environmentQueries.map(({ environmentId, projectIds }) => ({
541
environmentId,
@@ -713,10 +548,10 @@ function PullRequestsRouteView() {
548
...(search.host ? { host: search.host } : {}),
549
} satisfies PullRequestListInput,
550
}));
716
- }, [environmentQueries, filtersOpen, scopedProjectId, search.host, search.involvement]);
551
+ })();
552
const facetQuery = usePullRequestList(facetTargets);
553
const partitionsWanted = search.involvement === "all" && typedQuery.length === 0;
719
- const partitionTargets = useMemo(() => {
554
+ const partitionTargets = (() => {
555
// The main list goes first. Besides putting the visible rows on screen sooner, it proves
556
// which repositories the host search indexes, so an empty partition does not trigger the
557
// expensive per-repository fallback.
@@ -741,69 +576,26 @@ function PullRequestsRouteView() {
576
} satisfies PullRequestListInput,
577
}));
578
return { authored: targetsFor("authored"), reviewing: targetsFor("reviewing") };
744
- }, [
745
- menuFiltered,
746
- menuFilters,
747
- partitionsWanted,
748
- baselineQuery.data,
749
- environmentQueries,
750
- scopedProjectId,
751
- search.host,
752
- search.state,
753
- ]);
579
+ })();
580
const authoredQuery = usePullRequestList(partitionTargets.authored);
581
const reviewingQuery = usePullRequestList(partitionTargets.reviewing);
582
const invalidate = useAtomCommand(pullRequestEnvironment.invalidate, { reportFailure: false });
583
const [detailRefreshToken, setDetailRefreshToken] = useState(0);
584
const [invalidating, setInvalidating] = useState(false);
759
- const refreshListAndStats = (
760
- requestedStatsScope = statsScopeRef.current,
761
- actedEnvironmentId?: EnvironmentId,
762
- ) => {
763
- refreshList(true, actedEnvironmentId);
764
- const visible = visibleStatsKeys.current;
765
- const batches = pullRequestStatsRefreshBatches({
766
- requestedScope: requestedStatsScope,
767
- currentScope: statsScopeRef.current,
768
- entriesByKey: entriesByStatsKey.current,
769
- candidateKeys: visible.key === requestedStatsScope.key ? visible.values : new Set(),
770
- statsByRow: statsByRowRef.current,
771
- });
772
- if (batches !== null) {
773
- setStatsTargetState({ key: requestedStatsScope.key, batches });
774
- statsQuery.refresh(
775
- batches
776
- .filter(({ environmentId }) =>
777
- actedEnvironmentId === undefined ? true : environmentId === actedEnvironmentId,
778
- )
779
- .map(({ environmentId, input }) => ({ environmentId, input })),
780
- );
781
- }
782
- };
783
- const refreshFromHost = async () => {
784
- const requestedStatsScope = statsScopeRef.current;
785
- setInvalidating(true);
786
- try {
787
- await Promise.all(
788
- queryEnvironmentIds.map((environmentId) => invalidate({ environmentId, input: {} })),
789
- );
790
- } finally {
791
- setInvalidating(false);
792
- }
793
- refreshListAndStats(requestedStatsScope);
794
- setDetailRefreshToken((token) => token + 1);
795
- };
585
const refreshing = invalidating || listQuery.isPending;
586
587
const [loaded, setLoaded] = useState<{
588
environmentKey: string;
589
scope: string;
590
query: string;
591
+ /** The answer this was built from, so a re-render with the same answer leaves it alone. */
592
+ source: MergedPullRequestList | null;
593
data: MergedPullRequestList;
594
partitions?: PullRequestPartitionsSnapshot;
595
} | null>(null);
596
const [ordered, setOrdered] = useState<{
597
key: string;
598
+ source: MergedPullRequestList;
599
entries: ReadonlyArray<EnvironmentPullRequestEntry>;
600
} | null>(null);
601
const [overrides, setOverrides] = useState<ReadonlyMap<string, PullRequestListOverride>>(
@@ -830,90 +622,103 @@ function PullRequestsRouteView() {
622
});
623
};
624
const detailOverrideTokens = useRef(new Map<string, number | null>());
833
- const speedActionRef = useRef<(result: PullRequestSpeedActionResult) => void>(() => {});
834
- speedActionRef.current = ({ entry, action }) => {
625
+ const onSpeedAction = useStableCallback(({ entry, action }: PullRequestSpeedActionResult) => {
626
// Some hosts accept a merge before it completes. Let the next host read declare it merged.
627
if (action !== "merge") overrideEntry(entry, action);
837
- };
838
- const onSpeedAction = useCallback((result: PullRequestSpeedActionResult) => {
839
- speedActionRef.current(result);
840
- }, []);
841
- const onBatchClosed = useCallback((entry: EnvironmentPullRequestEntry) => {
842
- speedActionRef.current({ entry, action: "close" });
843
- }, []);
628
+ });
629
+ const onBatchClosed = useStableCallback((entry: EnvironmentPullRequestEntry) => {
630
+ onSpeedAction({ entry, action: "close" });
631
+ });
632
const { close: closeBatch, closingKeys } = usePullRequestCloseBatch(onBatchClosed);
845
- useEffect(() => {
846
- if (environmentKey.length === 0) return;
847
- setLoaded((current) => {
848
- if (current !== null && current.environmentKey === environmentKey) return current;
633
+ const [snapshotEnvironmentKey, setSnapshotEnvironmentKey] = useState("");
634
+ if (environmentKey.length > 0 && snapshotEnvironmentKey !== environmentKey) {
635
+ setSnapshotEnvironmentKey(environmentKey);
636
+ if (loaded?.environmentKey !== environmentKey) {
637
const snapshot = readPullRequestListSnapshot(
638
typeof window === "undefined" ? undefined : window.localStorage,
639
environmentKey,
640
);
853
- if (snapshot === null) return null;
854
- return {
855
- environmentKey,
856
- scope: snapshot.scope,
857
- query: "",
858
- data: snapshot.data,
859
- ...(snapshot.partitions === undefined ? {} : { partitions: snapshot.partitions }),
860
- };
861
- });
862
- }, [environmentKey]);
863
- useEffect(() => {
864
- if (!listQuery.data || listQuery.isPending) return;
865
- const data = listQuery.data;
866
- setLoaded((current) => {
867
- const partitions =
868
- partitionsWanted && baselineEmpty
869
- ? { authored: [], reviewing: [] }
870
- : partitionsWanted && authoredQuery.data !== null && reviewingQuery.data !== null
871
- ? { authored: authoredQuery.data.entries, reviewing: reviewingQuery.data.entries }
872
- : current !== null &&
873
- current.environmentKey === environmentKey &&
874
- current.scope === scopeKey
875
- ? current.partitions
876
- : undefined;
877
- if (environmentKey.length > 0 && sentQuery.length === 0) {
878
- const accumulatedEntries = ordered?.key === filterKey ? ordered.entries : data.entries;
879
- writePullRequestListSnapshot(
880
- typeof window === "undefined" ? undefined : window.localStorage,
881
- environmentKey,
882
- {
883
- scope: scopeKey,
884
- data: {
885
- ...data,
886
- entries: accumulatedEntries,
887
- viewers: baselineQuery.data?.viewers ?? data.viewers,
888
- providers: baselineQuery.data?.providers ?? data.providers,
641
+ setLoaded(
642
+ snapshot === null
643
+ ? null
644
+ : {
645
+ environmentKey,
646
+ scope: snapshot.scope,
647
+ query: "",
648
+ source: null,
649
+ data: snapshot.data,
650
+ ...(snapshot.partitions === undefined ? {} : { partitions: snapshot.partitions }),
651
},
890
- ...(partitions === undefined ? {} : { partitions }),
891
- },
892
- );
893
- }
894
- return {
895
- environmentKey,
896
- scope: scopeKey,
897
- query: sentQuery,
898
- data: { ...data, entries: ordered?.key === filterKey ? ordered.entries : data.entries },
899
- ...(partitions === undefined ? {} : { partitions }),
900
- };
652
+ );
653
+ }
654
+ }
655
+ const settledList = listQuery.data !== null && !listQuery.isPending ? listQuery.data : null;
656
+ const answeredPartitions =
657
+ partitionsWanted && baselineEmpty
658
+ ? EMPTY_PARTITIONS
659
+ : partitionsWanted && authoredQuery.data !== null && reviewingQuery.data !== null
660
+ ? { authored: authoredQuery.data.entries, reviewing: reviewingQuery.data.entries }
661
+ : null;
662
+ const heldPartitions =
663
+ loaded !== null && loaded.environmentKey === environmentKey && loaded.scope === scopeKey
664
+ ? loaded.partitions
665
+ : undefined;
666
+ const nextPartitions = answeredPartitions ?? heldPartitions;
667
+ const loadedEntries =
668
+ settledList === null
669
+ ? null
670
+ : ordered?.key === filterKey
671
+ ? ordered.entries
672
+ : settledList.entries;
673
+ if (
674
+ settledList !== null &&
675
+ loadedEntries !== null &&
676
+ (loaded === null ||
677
+ loaded.source !== settledList ||
678
+ loaded.environmentKey !== environmentKey ||
679
+ loaded.scope !== scopeKey ||
680
+ loaded.query !== sentQuery ||
681
+ loaded.data.entries !== loadedEntries ||
682
+ loaded.partitions?.authored !== nextPartitions?.authored ||
683
+ loaded.partitions?.reviewing !== nextPartitions?.reviewing)
684
+ ) {
685
+ setLoaded({
686
+ environmentKey,
687
+ scope: scopeKey,
688
+ query: sentQuery,
689
+ source: settledList,
690
+ data: { ...settledList, entries: loadedEntries },
691
+ ...(nextPartitions === undefined ? {} : { partitions: nextPartitions }),
692
});
902
- }, [
903
- environmentKey,
904
- scopeKey,
905
- sentQuery,
906
- listQuery.data,
907
- listQuery.isPending,
908
- baselineEmpty,
909
- partitionsWanted,
910
- authoredQuery.data,
911
- reviewingQuery.data,
912
- ordered,
913
- filterKey,
914
- baselineQuery.data,
915
- ]);
916
- const narrowed = useMemo(() => {
693
+ }
694
+ const snapshotToWrite =
695
+ loaded !== null &&
696
+ loaded.source !== null &&
697
+ loaded.environmentKey.length > 0 &&
698
+ loaded.query.length === 0
699
+ ? loaded
700
+ : null;
701
+ const snapshotViewers = baselineQuery.data?.viewers;
702
+ const snapshotProviders = baselineQuery.data?.providers;
703
+ useEffect(() => {
704
+ if (snapshotToWrite === null) return;
705
+ writePullRequestListSnapshot(
706
+ typeof window === "undefined" ? undefined : window.localStorage,
707
+ snapshotToWrite.environmentKey,
708
+ {
709
+ scope: snapshotToWrite.scope,
710
+ data: {
711
+ ...snapshotToWrite.data,
712
+ viewers: snapshotViewers ?? snapshotToWrite.data.viewers,
713
+ providers: snapshotProviders ?? snapshotToWrite.data.providers,
714
+ },
715
+ ...(snapshotToWrite.partitions === undefined
716
+ ? {}
717
+ : { partitions: snapshotToWrite.partitions }),
718
+ },
719
+ );
720
+ }, [snapshotToWrite, snapshotViewers, snapshotProviders]);
721
+ const narrowed = (() => {
722
if (loaded === null || loaded.environmentKey !== environmentKey || loaded.scope === scopeKey) {
723
return null;
724
}
@@ -923,7 +728,7 @@ function PullRequestsRouteView() {
728
host: search.host,
729
});
730
return entries.length === 0 ? null : { ...loaded.data, entries };
926
- }, [environmentKey, loaded, scopeKey, scopedProjectId, search.host, search.state]);
731
+ })();
732
// A grown page is read by the list and nothing else: the baseline always asks for one page, so
733
// a host with no cursor to continue from — where "more" means asking for a longer page — would
734
// have its extra rows thrown away for the ninety-nine the baseline keeps answering with.
@@ -941,45 +746,42 @@ function PullRequestsRouteView() {
746
const loadingMore = listQuery.isPending && listData !== null;
747
const firstLoad = listQuery.isPending && listData === null;
748
944
- useEffect(() => {
945
- if (!answered || listQuery.isPending || (listQuery.error && listQuery.data === null)) return;
946
- setOrdered((previous) => {
947
- if (previous === null || previous.key !== filterKey) {
948
- return {
949
- key: filterKey,
950
- entries: rankPullRequestMatches(answered.entries, sentParsed.text),
951
- };
952
- }
953
- if (sentCursors !== null) {
954
- const held = new Set(previous.entries.map(pullRequestEntryKey));
955
- const arrived = answered.entries.filter((entry) => !held.has(pullRequestEntryKey(entry)));
956
- const appended = rankPullRequestMatches(
957
- arrived.toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)),
958
- sentParsed.text,
959
- );
960
- return { key: filterKey, entries: [...previous.entries, ...appended] };
961
- }
962
- return {
749
+ if (
750
+ answered !== null &&
751
+ !listQuery.isPending &&
752
+ !(listQuery.error && listQuery.data === null) &&
753
+ (ordered === null || ordered.key !== filterKey || ordered.source !== answered)
754
+ ) {
755
+ if (ordered === null || ordered.key !== filterKey) {
756
+ setOrdered({
757
key: filterKey,
758
+ source: answered,
759
+ entries: rankPullRequestMatches(answered.entries, sentParsed.text),
760
+ });
761
+ } else if (sentCursors !== null) {
762
+ const held = new Set(ordered.entries.map(pullRequestEntryKey));
763
+ const arrived = answered.entries.filter((entry) => !held.has(pullRequestEntryKey(entry)));
764
+ const appended = rankPullRequestMatches(
765
+ arrived.toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt)),
766
+ sentParsed.text,
767
+ );
768
+ setOrdered({ key: filterKey, source: answered, entries: [...ordered.entries, ...appended] });
769
+ } else {
770
+ setOrdered({
771
+ key: filterKey,
772
+ source: answered,
773
entries: reusePullRequestEntries(
965
- previous.entries,
774
+ ordered.entries,
775
rankPullRequestMatches(answered.entries, sentParsed.text),
776
pullRequestEntryKey,
777
),
969
- };
970
- });
778
+ });
779
+ }
780
+ const answeredEntries = answered.entries;
781
setOverrides((current) =>
972
- settlePullRequestOverrides(current, answered.entries, pullRequestEntryKey, Date.now()),
782
+ settlePullRequestOverrides(current, answeredEntries, pullRequestEntryKey, Date.now()),
783
);
974
- }, [
975
- answered,
976
- filterKey,
977
- sentCursors,
978
- sentParsed.text,
979
- listQuery.isPending,
980
- listQuery.error,
981
- listQuery.data,
982
- ]);
784
+ }
785
786
// From this question's own answer, never from the rows being held while it travels: a
787
// continuation is a boundary in one listing, and carrying one across a search would ask the new
@@ -1066,189 +868,106 @@ function PullRequestsRouteView() {
868
869
const viewers = baselineQuery.data?.viewers ?? listData?.viewers ?? EMPTY_VIEWERS;
870
const listErrors = baselineQuery.data?.errors ?? listData?.errors ?? [];
1069
- const facets = useMemo(
1070
- () =>
1071
- collectPullRequestListFacets(
1072
- [
1073
- ...(facetQuery.data?.entries ?? []),
1074
- ...(baselineQuery.data?.entries ?? listData?.entries ?? []),
1075
- ],
1076
- search.state,
1077
- ),
1078
- [baselineQuery.data?.entries, facetQuery.data?.entries, listData?.entries, search.state],
1079
- );
1080
-
1081
- const searchingHosts = useMemo(
1082
- () =>
1083
- new Set(
1084
- (baselineQuery.data?.providers ?? listData?.providers ?? []).flatMap((provider) =>
1085
- provider.searchesOnHost ? [provider.host] : [],
1086
- ),
1087
- ),
1088
- [baselineQuery.data?.providers, listData?.providers],
1089
- );
1090
-
1091
- const entries = useMemo(() => {
1092
- const known = ordered?.key === filterKey ? ordered.entries : (listData?.entries ?? []);
1093
- const involvementEntries = filterPullRequestsByInvolvement(known, viewers, search.involvement);
1094
- // The hosts search more than the row shows — a body, a review, a commit message — so once
1095
- // their answer is in, narrowing it again here would throw away matches the reader asked for.
1096
- // The local pass stands in for the answer that has not arrived yet, and for the hosts that
1097
- // answered without searching at all: Azure DevOps has no text filter, so its rows arrive
1098
- // whole and would otherwise sit under a search that never touched them.
1099
- const narrowedEntries = hasLocalFilters
1100
- ? involvementEntries.filter((entry) =>
1101
- matchesPullRequestFilters(entry, localFilters, pullRequestEntryViewer(entry, viewers)),
1102
- )
1103
- : involvementEntries;
1104
- if (typedParsed.text.length === 0) {
1105
- return narrowedEntries.toSorted((left, right) =>
1106
- right.updatedAt.localeCompare(left.updatedAt),
1107
- );
1108
- }
1109
- const answeredLocally = querySettled && !showingCarried;
1110
- return narrowedEntries.filter(
1111
- (entry) =>
1112
- (answeredLocally && searchingHosts.has(entry.host)) ||
1113
- matchesPullRequestQuery(entry, typedParsed.text),
1114
- );
1115
- }, [
1116
- filterKey,
1117
- hasLocalFilters,
1118
- localFilters,
1119
- listData,
1120
- ordered,
1121
- querySettled,
1122
- search.involvement,
1123
- searchingHosts,
1124
- showingCarried,
1125
- typedParsed.text,
1126
- viewers,
1127
- ]);
1128
-
1129
- const listedPullRequestTabStatuses = useMemo<Record<string, PullRequestTabStatusSeed>>(
1130
- () =>
1131
- Object.fromEntries(
1132
- entries.map((entry) => [
1133
- pullRequestSurfaceId(entry),
1134
- {
1135
- state: entry.state,
1136
- isDraft: entry.isDraft,
1137
- },
1138
- ]),
1139
- ),
1140
- [entries],
871
+ const facets = collectPullRequestListFacets(
872
+ [
873
+ ...(facetQuery.data?.entries ?? []),
874
+ ...(baselineQuery.data?.entries ?? listData?.entries ?? []),
875
+ ],
876
+ search.state,
877
);
878
879
const scrollRef = useRef<HTMLDivElement>(null);
1144
-
1145
- const groups = useMemo(() => {
1146
- if (search.involvement !== "all") return [{ key: "others" as const, label: "", entries }];
1147
- if (baselineEmpty) {
1148
- return groupPullRequestsByInvolvement(entries, viewers);
1149
- }
1150
- const held =
1151
- loaded !== null && loaded.environmentKey === environmentKey && loaded.scope === scopeKey
1152
- ? loaded.partitions
1153
- : undefined;
1154
- const narrow = (rows: ReadonlyArray<EnvironmentPullRequestEntry> | undefined) =>
1155
- rows === undefined || !hasLocalFilters
1156
- ? rows
1157
- : rows.filter((entry) =>
1158
- matchesPullRequestFilters(entry, localFilters, pullRequestEntryViewer(entry, viewers)),
1159
- );
1160
- const authored = narrow(
1161
- partitionsWanted ? (authoredQuery.data?.entries ?? held?.authored) : undefined,
1162
- );
1163
- const reviewing = narrow(
1164
- partitionsWanted ? (reviewingQuery.data?.entries ?? held?.reviewing) : undefined,
1165
- );
1166
- if (authored === undefined || reviewing === undefined) {
1167
- return groupPullRequestsByInvolvement(entries, viewers);
1168
- }
1169
- return partitionPullRequestsWithPriority(entries, authored, reviewing);
1170
- }, [
880
+ const {
881
+ entries,
882
+ listedPullRequestTabStatuses,
883
+ groups,
884
+ entriesByStatsKey,
885
+ heldPullRequestsBySurface,
886
+ } = usePullRequestGroups({
887
+ known: ordered?.key === filterKey ? ordered.entries : (listData?.entries ?? []),
888
+ providers: baselineQuery.data?.providers ?? listData?.providers ?? [],
889
+ viewers,
890
+ involvement: search.involvement,
891
+ localFilters,
892
hasLocalFilters,
893
+ text: typedParsed.text,
894
+ answeredLocally: querySettled && !showingCarried,
895
baselineEmpty,
1173
- localFilters,
1174
- authoredQuery.data?.entries,
1175
- entries,
1176
- environmentKey,
1177
- loaded,
896
+ held:
897
+ loaded !== null && loaded.environmentKey === environmentKey && loaded.scope === scopeKey
898
+ ? loaded.partitions
899
+ : undefined,
900
+ authored: partitionsWanted ? authoredQuery.data?.entries : undefined,
901
+ reviewing: partitionsWanted ? reviewingQuery.data?.entries : undefined,
902
partitionsWanted,
1179
- reviewingQuery.data?.entries,
1180
- scopeKey,
1181
- search.involvement,
1182
- viewers,
1183
- ]);
903
+ });
904
1185
- const entriesByStatsKey = useRef<ReadonlyMap<string, EnvironmentPullRequestEntry>>(new Map());
1186
- entriesByStatsKey.current = new Map(
1187
- groups.flatMap((group) =>
1188
- group.entries.map((entry) => [pullRequestEntryKey(entry), entry] as const),
1189
- ),
1190
- );
905
const visibleStatsKeys = useRef({ key: filterKey, values: new Set<string>() });
906
const [statsByRow, setStatsByRow] = useState<PullRequestDiffStats>(() => new Map());
1193
- const statsByRowRef = useRef(statsByRow);
1194
- statsByRowRef.current = statsByRow;
907
const [statsTargetState, setStatsTargetState] = useState<{
908
readonly key: string;
909
readonly batches: ReadonlyArray<PullRequestStatsBatch>;
910
}>({ key: filterKey, batches: [] });
911
const statsBatches = statsTargetState.key === filterKey ? statsTargetState.batches : [];
1200
- const statsTargets = useMemo(
1201
- () =>
1202
- statsBatches.map(({ environmentId, input }) => ({
1203
- environmentId,
1204
- input,
1205
- })),
1206
- [statsBatches],
1207
- );
912
+ const statsTargets = statsBatches.map(({ environmentId, input }) => ({
913
+ environmentId,
914
+ input,
915
+ }));
916
+ const statsQuery = usePullRequestListStats(statsTargets);
917
const statsObserver = useRef<IntersectionObserver | null>(null);
918
const statsRows = useRef(new Set<HTMLDivElement>());
1210
- const statsPending = useRef(true);
1211
- const statsPolicyRef = useRef(statsPolicy);
1212
- statsPolicyRef.current = statsPolicy;
1213
- const registerStatsRow = useCallback((node: HTMLDivElement | null) => {
919
+ // Called from a row's ref cleanup, which keeps the render it attached in; this reads the latest.
920
+ const releaseStatsRow = useStableCallback((key: string | undefined) => {
921
+ const visible = visibleStatsKeys.current;
922
+ if (
923
+ statsPolicy !== "visible" ||
924
+ key === undefined ||
925
+ !visible.values.delete(key) ||
926
+ statsQuery.isPending
927
+ ) {
928
+ return;
929
+ }
930
+ setStatsTargetState((current) => {
931
+ if (current.key !== visible.key) return current;
932
+ const batches = retainVisiblePullRequestStatsBatches(current.batches, visible.values);
933
+ return batches.length === current.batches.length ? current : { key: current.key, batches };
934
+ });
935
+ });
936
+ // Every row takes this as its ref, so a new identity would detach and reattach them all.
937
+ const registerStatsRow = useStableCallback((node: HTMLDivElement | null) => {
938
if (node === null || typeof IntersectionObserver === "undefined") return;
939
statsRows.current.add(node);
940
statsObserver.current?.observe(node);
941
return () => {
942
statsRows.current.delete(node);
943
statsObserver.current?.unobserve(node);
1220
- const key = node.dataset.pullRequestStatsKey;
1221
- const visible = visibleStatsKeys.current;
1222
- if (
1223
- statsPolicyRef.current !== "visible" ||
1224
- key === undefined ||
1225
- !visible.values.delete(key) ||
1226
- statsPending.current
1227
- ) {
1228
- return;
1229
- }
1230
- setStatsTargetState((current) => {
1231
- if (current.key !== visible.key) return current;
1232
- const batches = retainVisiblePullRequestStatsBatches(current.batches, visible.values);
1233
- return batches.length === current.batches.length ? current : { key: current.key, batches };
1234
- });
944
+ releaseStatsRow(node.dataset.pullRequestStatsKey);
945
};
1236
- }, []);
946
+ });
947
+ // Arriving stats must not re-run the effects that ask for them.
948
+ const readStatsProgress = useEffectEvent(() => ({
949
+ statsByRow,
950
+ pending: statsQuery.isPending,
951
+ }));
952
useEffect(() => {
953
if (statsPolicy !== "eager") return;
954
+ const { statsByRow: known } = readStatsProgress();
955
+ const candidateKeys = visibleStatsKeys.current.values;
956
setStatsTargetState((current) => {
957
const batches = current.key === filterKey ? current.batches : [];
958
const added = pullRequestStatsRequestBatches({
1242
- entriesByKey: entriesByStatsKey.current,
1243
- candidateKeys: visibleStatsKeys.current.values,
959
+ entriesByKey: entriesByStatsKey,
960
+ candidateKeys,
961
policy: statsPolicy,
962
activeBatches: batches,
1246
- statsByRow: statsByRowRef.current,
963
+ statsByRow: known,
964
});
965
if (added.length === 0 && current.key === filterKey) return current;
966
return { key: filterKey, batches: [...batches, ...added] };
967
});
1251
- }, [filterKey, groups, statsPolicy]);
968
+ }, [filterKey, entriesByStatsKey, statsPolicy]);
969
+ // The observer outlives the rows it watches, so it reads the rows held at the time it fires.
970
+ const readStatsRows = useEffectEvent(() => entriesByStatsKey);
971
useEffect(() => {
972
if (statsPolicy !== "visible" || typeof IntersectionObserver === "undefined") return;
973
visibleStatsKeys.current = { key: filterKey, values: new Set() };
@@ -1258,30 +977,32 @@ function PullRequestsRouteView() {
977
if (visible.key !== filterKey) return;
978
let changed = false;
979
const entered = new Set<string>();
980
+ const entriesByKey = readStatsRows();
981
for (const item of observed) {
982
const key = (item.target as HTMLElement).dataset.pullRequestStatsKey;
983
if (key === undefined) continue;
984
const wasVisible = visible.values.has(key);
1265
- if (item.isIntersecting && entriesByStatsKey.current.has(key)) {
985
+ if (item.isIntersecting && entriesByKey.has(key)) {
986
visible.values.add(key);
987
if (!wasVisible) entered.add(key);
988
} else {
989
visible.values.delete(key);
990
}
1271
- changed ||= wasVisible !== visible.values.has(key);
991
+ if (wasVisible !== visible.values.has(key)) changed = true;
992
}
993
if (!changed) return;
994
+ const progress = readStatsProgress();
995
setStatsTargetState((current) => {
996
const batches = current.key === filterKey ? current.batches : [];
1276
- const retained = statsPending.current
997
+ const retained = progress.pending
998
? batches
999
: retainVisiblePullRequestStatsBatches(batches, visible.values);
1000
const added = pullRequestStatsRequestBatches({
1280
- entriesByKey: entriesByStatsKey.current,
1001
+ entriesByKey,
1002
candidateKeys: entered,
1003
policy: statsPolicy,
1004
activeBatches: batches,
1284
- statsByRow: statsByRowRef.current,
1005
+ statsByRow: progress.statsByRow,
1006
});
1007
if (added.length === 0 && retained.length === batches.length) return current;
1008
return { key: filterKey, batches: [...retained, ...added] };
@@ -1296,8 +1017,6 @@ function PullRequestsRouteView() {
1017
if (statsObserver.current === observer) statsObserver.current = null;
1018
};
1019
}, [filterKey, statsPolicy]);
1299
- const statsQuery = usePullRequestListStats(statsTargets);
1300
- statsPending.current = statsQuery.isPending;
1020
useEffect(() => {
1021
if (statsPolicy !== "visible" || statsQuery.isPending) return;
1022
const visible = visibleStatsKeys.current;
@@ -1307,87 +1026,97 @@ function PullRequestsRouteView() {
1026
return batches.length === current.batches.length ? current : { key: current.key, batches };
1027
});
1028
}, [filterKey, statsPolicy, statsQuery.isPending]);
1310
- useEffect(() => {
1029
+ const [mergedStats, setMergedStats] = useState<typeof statsQuery.stats>(null);
1030
+ if (statsQuery.stats !== null && statsQuery.stats !== mergedStats) {
1031
const stats = statsQuery.stats;
1312
- if (stats === null) return;
1032
+ setMergedStats(stats);
1033
setStatsByRow((previous) => mergePullRequestDiffStats(previous, stats));
1314
- }, [statsQuery.stats]);
1315
- const displayGroups = useMemo(() => {
1316
- const enriched = groups.map((group) => {
1317
- const answered = applyPullRequestOverrides(
1318
- group.entries.map((entry) => withDiffStat(entry, statsByRow)),
1319
- overrides,
1320
- pullRequestEntryKey,
1321
- search.state,
1322
- );
1323
- return {
1324
- ...group,
1325
- entries:
1326
- hasLocalFilters && overrides.size > 0
1327
- ? answered.filter(
1328
- (entry) =>
1329
- !overrides.has(pullRequestEntryKey(entry)) ||
1330
- matchesPullRequestFilters(
1331
- entry,
1332
- localFilters,
1333
- pullRequestEntryViewer(entry, viewers),
1334
- ),
1335
- )
1336
- : answered,
1337
- };
1338
- });
1339
- return sortPullRequestGroups(
1340
- enriched,
1341
- sort,
1342
- typedParsed.text,
1343
- (entry) =>
1344
- entry.additions + entry.deletions > 0 || statsByRow.has(pullRequestDiffStatKey(entry)),
1345
- search.involvement,
1346
- );
1347
- }, [
1348
- groups,
1349
- hasLocalFilters,
1350
- localFilters,
1351
- overrides,
1352
- search.involvement,
1353
- search.state,
1354
- sort,
1355
- statsByRow,
1356
- typedParsed.text,
1357
- viewers,
1358
- ]);
1359
- const shownCount = displayGroups.reduce((count, group) => count + group.entries.length, 0);
1360
- const [hosts, setHosts] = useState<PullRequestListResult["providers"]>([]);
1361
- useEffect(() => {
1362
- if (answered === null) return;
1363
- setHosts((previous) =>
1364
- search.host === undefined || previous.length === 0 ? answered.providers : previous,
1034
+ }
1035
+ // Stable so a refresh that resumes after awaiting the host compares against the scope on screen
1036
+ // by then, not the one it started from.
1037
+ const refreshListAndStats = useStableCallback(
1038
+ (
1039
+ requestedStatsScope: PullRequestStatsScope = statsScope,
1040
+ actedEnvironmentId?: EnvironmentId,
1041
+ ) => {
1042
+ refreshList(true, actedEnvironmentId);
1043
+ const visible = visibleStatsKeys.current;
1044
+ const batches = pullRequestStatsRefreshBatches({
1045
+ requestedScope: requestedStatsScope,
1046
+ currentScope: statsScope,
1047
+ entriesByKey: entriesByStatsKey,
1048
+ candidateKeys: visible.key === requestedStatsScope.key ? visible.values : new Set(),
1049
+ statsByRow,
1050
+ });
1051
+ if (batches !== null) {
1052
+ setStatsTargetState({ key: requestedStatsScope.key, batches });
1053
+ statsQuery.refresh(
1054
+ batches
1055
+ .filter(({ environmentId }) =>
1056
+ actedEnvironmentId === undefined ? true : environmentId === actedEnvironmentId,
1057
+ )
1058
+ .map(({ environmentId, input }) => ({ environmentId, input })),
1059
+ );
1060
+ }
1061
+ },
1062
+ );
1063
+ const refreshFromHost = async () => {
1064
+ const requestedStatsScope = statsScope;
1065
+ setInvalidating(true);
1066
+ // Atom commands settle into results rather than throwing.
1067
+ await Promise.all(
1068
+ queryEnvironmentIds.map((environmentId) => invalidate({ environmentId, input: {} })),
1069
);
1366
- }, [answered, search.host]);
1070
+ setInvalidating(false);
1071
+ refreshListAndStats(requestedStatsScope);
1072
+ setDetailRefreshToken((token) => token + 1);
1073
+ };
1074
+ const [hostsState, setHostsState] = useState<{
1075
+ readonly source: MergedPullRequestList | null;
1076
+ readonly host: string | undefined;
1077
+ readonly hosts: PullRequestListResult["providers"];
1078
+ }>({ source: null, host: undefined, hosts: [] });
1079
+ if (answered !== null && (hostsState.source !== answered || hostsState.host !== search.host)) {
1080
+ setHostsState({
1081
+ source: answered,
1082
+ host: search.host,
1083
+ hosts:
1084
+ search.host === undefined || hostsState.hosts.length === 0
1085
+ ? answered.providers
1086
+ : hostsState.hosts,
1087
+ });
1088
+ }
1089
+ const hosts = hostsState.hosts;
1090
const showProvider = hosts.length > 1;
1368
- const hostActionsOf = useMemo(() => pullRequestHostActions(hosts), [hosts]);
1091
+ const { displayGroups, shownCount, hostActionsOf, closeSweepRows, listedPullRequestsBySurface } =
1092
+ usePullRequestDisplayGroups({
1093
+ groups,
1094
+ statsByRow,
1095
+ overrides,
1096
+ state: search.state,
1097
+ localFilters,
1098
+ hasLocalFilters,
1099
+ viewers,
1100
+ sort,
1101
+ text: typedParsed.text,
1102
+ involvement: search.involvement,
1103
+ hosts,
1104
+ });
1105
const [closeSweepKeys, setCloseSweepKeys] = useState<ReadonlySet<string>>(() => new Set());
1106
const closeSensorRef = useRef<SidebarPointerSensor | null>(null);
1371
- const closeSweepRows = useMemo(
1372
- () =>
1373
- new Map(
1374
- displayGroups.flatMap((group) =>
1375
- group.entries.map(
1376
- (entry) => [pullRequestEntryKey(entry), { entry, groupKey: group.key }] as const,
1377
- ),
1378
- ),
1379
- ),
1380
- [displayGroups],
1381
- );
1382
- const closeSweepRef = useRef({
1107
+ // A sweep spans many renders; each step reads the rows on screen at that moment.
1108
+ const readCloseSweep = useStableCallback(() => ({
1109
displayGroups,
1110
closeSweepRows,
1111
closingKeys,
1112
closeBatch,
1113
hostActionsOf,
1388
- });
1389
- closeSweepRef.current = { displayGroups, closeSweepRows, closingKeys, closeBatch, hostActionsOf };
1390
- useEffect(() => () => closeSensorRef.current?.cancel(), [filterKey, search.q, sort]);
1114
+ }));
1115
+ useEffect(
1116
+ () => () => closeSensorRef.current?.cancel(),
1117
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- The pointer sensor lives outside React; a new list under a sweep in progress must end it.
1118
+ [filterKey, search.q, sort],
1119
+ );
1120
useEffect(() => {
1121
const onKeyDown = (event: KeyboardEvent) => {
1122
if (event.key !== "Escape" || closeSensorRef.current === null) return;
@@ -1397,103 +1126,73 @@ function PullRequestsRouteView() {
1126
document.addEventListener("keydown", onKeyDown, true);
1127
return () => document.removeEventListener("keydown", onKeyDown, true);
1128
}, []);
1400
- const startCloseSweep = useCallback((entry: EnvironmentPullRequestEntry, event: PointerEvent) => {
1401
- closeSensorRef.current?.cancel();
1402
- const originKey = pullRequestEntryKey(entry);
1403
- const group = closeSweepRef.current.displayGroups.find((candidate) =>
1404
- candidate.entries.some((row) => pullRequestEntryKey(row) === originKey),
1405
- );
1406
- if (!group || closeSweepRef.current.closingKeys.has(originKey)) return;
1407
- const orderedKeys = closeSweepRef.current.displayGroups.flatMap((candidate) =>
1408
- candidate.entries.map(pullRequestEntryKey),
1409
- );
1410
- const canClose = (key: string) => {
1411
- const row = closeSweepRef.current.closeSweepRows.get(key);
1412
- return (
1413
- row?.groupKey === group.key &&
1414
- row.entry.state === "open" &&
1415
- closeSweepRef.current.hostActionsOf(row.entry).has("close") &&
1416
- !closeSweepRef.current.closingKeys.has(key) &&
1417
- !scrollRef.current?.querySelector(
1418
- `[data-pull-request-key="${CSS.escape(key)}"] [data-pull-request-action-pending="true"]`,
1419
- )
1129
+ const startCloseSweep = useStableCallback(
1130
+ (entry: EnvironmentPullRequestEntry, event: PointerEvent) => {
1131
+ closeSensorRef.current?.cancel();
1132
+ const originKey = pullRequestEntryKey(entry);
1133
+ const group = readCloseSweep().displayGroups.find((candidate) =>
1134
+ candidate.entries.some((row) => pullRequestEntryKey(row) === originKey),
1135
);
1421
- };
1422
- let sweptKeys: string[] = [];
1423
- let targetKey: string | null = null;
1424
- const sweepTo = (key: string) => {
1425
- if (key === targetKey) return;
1426
- targetKey = key;
1427
- sweptKeys = resolveSidebarSweepKeys(orderedKeys, originKey, key, canClose);
1428
- setCloseSweepKeys(new Set(sweptKeys));
1429
- };
1430
- closeSensorRef.current = new SidebarPointerSensor({
1431
- active: originKey,
1432
- event,
1433
- options: {
1434
- distance: 6,
1435
- onAttach: () => {},
1436
- onFinish: () => {
1437
- closeSensorRef.current = null;
1438
- setCloseSweepKeys(new Set());
1136
+ if (!group || readCloseSweep().closingKeys.has(originKey)) return;
1137
+ const orderedKeys = readCloseSweep().displayGroups.flatMap((candidate) =>
1138
+ candidate.entries.map(pullRequestEntryKey),
1139
+ );
1140
+ const canClose = (key: string) => {
1141
+ const row = readCloseSweep().closeSweepRows.get(key);
1142
+ return (
1143
+ row?.groupKey === group.key &&
1144
+ row.entry.state === "open" &&
1145
+ readCloseSweep().hostActionsOf(row.entry).has("close") &&
1146
+ !readCloseSweep().closingKeys.has(key) &&
1147
+ !scrollRef.current?.querySelector(
1148
+ `[data-pull-request-key="${CSS.escape(key)}"] [data-pull-request-action-pending="true"]`,
1149
+ )
1150
+ );
1151
+ };
1152
+ let sweptKeys: string[] = [];
1153
+ let targetKey: string | null = null;
1154
+ const sweepTo = (key: string) => {
1155
+ if (key === targetKey) return;
1156
+ targetKey = key;
1157
+ sweptKeys = resolveSidebarSweepKeys(orderedKeys, originKey, key, canClose);
1158
+ setCloseSweepKeys(new Set(sweptKeys));
1159
+ };
1160
+ closeSensorRef.current = new SidebarPointerSensor({
1161
+ active: originKey,
1162
+ event,
1163
+ options: {
1164
+ distance: 6,
1165
+ onAttach: () => {},
1166
+ onFinish: () => {
1167
+ closeSensorRef.current = null;
1168
+ setCloseSweepKeys(new Set());
1169
+ },
1170
},
1440
- },
1441
- onPending: () => {},
1442
- onStart: () => sweepTo(originKey),
1443
- onMove: ({ y }) => {
1444
- const viewport = scrollRef.current;
1445
- if (!viewport) return;
1446
- const bounds = viewport.getBoundingClientRect();
1447
- const visibleY = Math.min(Math.max(y, bounds.top), bounds.bottom - 1);
1448
- let key: string | null = null;
1449
- for (const row of viewport.querySelectorAll<HTMLElement>("[data-pull-request-key]")) {
1450
- if (key !== null && row.getBoundingClientRect().top > visibleY) break;
1451
- key = row.dataset.pullRequestKey ?? null;
1452
- }
1453
- if (key !== null) sweepTo(key);
1454
- },
1455
- onEnd: () => {
1456
- const batch = sweptKeys.filter(canClose).flatMap((key) => {
1457
- const row = closeSweepRef.current.closeSweepRows.get(key);
1458
- return row ? [row.entry] : [];
1459
- });
1460
- void closeSweepRef.current.closeBatch(batch);
1461
- },
1462
- onCancel: () => {},
1463
- onAbort: () => {},
1464
- });
1465
- }, []);
1466
- const heldPullRequestsBySurface = useMemo(
1467
- () =>
1468
- new Map(
1469
- groups.flatMap((group) =>
1470
- group.entries.map((entry) => [pullRequestListEntryId(entry), entry] as const),
1471
- ),
1472
- ),
1473
- [groups],
1474
- );
1475
- const listedPullRequestsBySurface = useMemo(
1476
- () =>
1477
- new Map(
1478
- displayGroups.flatMap((group) =>
1479
- group.entries.map((entry) => [pullRequestListEntryId(entry), entry] as const),
1480
- ),
1481
- ),
1482
- [displayGroups],
1483
- );
1484
-
1485
- const linkedSelection = useMemo(
1486
- () =>
1487
- search.repository && search.number && selectedProject
1488
- ? {
1489
- environmentId: selectedProject.environmentId,
1490
- repository: search.repository,
1491
- number: search.number,
1492
- projectId: selectedProject.id,
1493
- ...(selectedHost ? { host: selectedHost } : {}),
1171
+ onPending: () => {},
1172
+ onStart: () => sweepTo(originKey),
1173
+ onMove: ({ y }) => {
1174
+ const viewport = scrollRef.current;
1175
+ if (!viewport) return;
1176
+ const bounds = viewport.getBoundingClientRect();
1177
+ const visibleY = Math.min(Math.max(y, bounds.top), bounds.bottom - 1);
1178
+ let key: string | null = null;
1179
+ for (const row of viewport.querySelectorAll<HTMLElement>("[data-pull-request-key]")) {
1180
+ if (key !== null && row.getBoundingClientRect().top > visibleY) break;
1181
+ key = row.dataset.pullRequestKey ?? null;
1182
}
1495
- : null,
1496
- [search.number, search.repository, selectedProject, selectedHost],
1183
+ if (key !== null) sweepTo(key);
1184
+ },
1185
+ onEnd: () => {
1186
+ const batch = sweptKeys.filter(canClose).flatMap((key) => {
1187
+ const row = readCloseSweep().closeSweepRows.get(key);
1188
+ return row ? [row.entry] : [];
1189
+ });
1190
+ void readCloseSweep().closeBatch(batch);
1191
+ },
1192
+ onCancel: () => {},
1193
+ onAbort: () => {},
1194
+ });
1195
+ },
1196
);
1197
const rightPanelAvailable = selectedPullRequestSurface !== null;
1198
const [maximized, setMaximized] = useState(false);
@@ -1502,7 +1201,7 @@ function PullRequestsRouteView() {
1201
const toggleRightPanelMaximized = () => {
1202
if (rightPanelState.isOpen) setMaximized((value) => !value);
1203
};
1505
- const onGuideShown = useCallback(() => setMaximized(true), []);
1204
+ const onGuideShown = () => setMaximized(true);
1205
useEffect(() => {
1206
if (!pullRequestsSupported || rightPanelRef === null || linkedSelection === null) return;
1207
useRightPanelStore.getState().openPullRequest(rightPanelRef, linkedSelection);
@@ -1553,45 +1252,27 @@ function PullRequestsRouteView() {
1252
selectSurfaceInUrl(selectedPullRequestSurface);
1253
};
1254
1556
- const expectedHosts = useMemo(() => {
1557
- const byHost = new Map<string, PullRequestExpectedHost>();
1558
- for (const project of projects) {
1559
- const kind = project.repositoryIdentity?.provider as SourceControlProviderKind | undefined;
1560
- if (kind === undefined) continue;
1561
- const host = pullRequestHostOf(project.repositoryIdentity, kind);
1562
- if (!byHost.has(host)) byHost.set(host, { host, kind });
1563
- }
1564
- return [...byHost.values()];
1565
- }, [projects]);
1566
-
1567
- const unavailableProjects = useMemo(
1568
- () =>
1569
- new Map(
1570
- listErrors.map(
1571
- (error) =>
1572
- [
1573
- pullRequestProjectKey({ id: error.projectId, environmentId: error.environmentId }),
1574
- error.message,
1575
- ] as const,
1576
- ),
1577
- ),
1578
- [listErrors],
1255
+ const unavailableProjects = new Map(
1256
+ listErrors.map(
1257
+ (error) =>
1258
+ [
1259
+ pullRequestProjectKey({ id: error.projectId, environmentId: error.environmentId }),
1260
+ error.message,
1261
+ ] as const,
1262
+ ),
1263
);
1264
1581
- const selectEntry = useCallback(
1582
- (entry: PullRequestRowTarget) => {
1583
- if (rightPanelRef === null) return;
1584
- useRightPanelStore.getState().openPullRequest(rightPanelRef, entry);
1585
- updateSearch({
1586
- repository: entry.repository,
1587
- number: entry.number,
1588
- selectedProjectId: entry.projectId,
1589
- selectedEnvironmentId: entry.environmentId,
1590
- selectedHost: entry.host,
1591
- });
1592
- },
1593
- [rightPanelRef, updateSearch],
1594
- );
1265
+ const selectEntry = (entry: PullRequestRowTarget) => {
1266
+ if (rightPanelRef === null) return;
1267
+ useRightPanelStore.getState().openPullRequest(rightPanelRef, entry);
1268
+ updateSearch({
1269
+ repository: entry.repository,
1270
+ number: entry.number,
1271
+ selectedProjectId: entry.projectId,
1272
+ selectedEnvironmentId: entry.environmentId,
1273
+ selectedHost: entry.host,
1274
+ });
1275
+ };
1276
1277
const searchInput = (
1278
<PullRequestSearchInput
@@ -2095,14 +1776,377 @@ function PullRequestsRouteView() {
1776
);
1777
}
1778
1779
+/** Which servers and projects the page reads, from the URL and what this client knows. */
1780
+function usePullRequestScope(
1781
+ environments: ReturnType<typeof useEnvironments>["environments"],
1782
+ allProjects: ReturnType<typeof useProjects>,
1783
+ projectsKnown: boolean,
1784
+ search: PullRequestsSearch,
1785
+) {
1786
+ // Calls no hooks, so the compiler needs the directive to memoize it.
1787
+ "use memo";
1788
+ const capableEnvironments = environments
1789
+ .filter(
1790
+ (environment) => environment.serverConfig?.environment.capabilities.pullRequests === true,
1791
+ )
1792
+ .toSorted((left, right) => left.environmentId.localeCompare(right.environmentId));
1793
+ const scopedEnvironmentId =
1794
+ capableEnvironments.find((environment) => environment.environmentId === search.environmentId)
1795
+ ?.environmentId ?? null;
1796
+ const knownEnvironmentIds = new Set(environments.map((environment) => environment.environmentId));
1797
+ const environmentIds = capableEnvironments
1798
+ .filter(
1799
+ (environment) =>
1800
+ scopedEnvironmentId === null || environment.environmentId === scopedEnvironmentId,
1801
+ )
1802
+ .map((environment) => environment.environmentId);
1803
+ const environmentKey = pullRequestEnvironmentSetKey(environmentIds);
1804
+ const capabilityKnown = environments.some((environment) => environment.serverConfig !== null);
1805
+ const pullRequestsSupported = environmentIds.length > 0;
1806
+ const projects = allProjects.filter(
1807
+ (project) => !project.isScratch && environmentIds.includes(project.environmentId),
1808
+ );
1809
+ const environmentLabels = new Map(
1810
+ environments.map((environment) => [environment.environmentId, environment.label] as const),
1811
+ );
1812
+ const scopedProjectId = resolveProjectScope(search.projectId, projects, projectsKnown);
1813
+ const scopedProject = findScopedProject(projects, scopedEnvironmentId, scopedProjectId);
1814
+ const scopedProjects = pullRequestFilterProjects(projects, environmentLabels, scopedProject);
1815
+
1816
+ const selectedHost = search.selectedHost ?? search.host;
1817
+ const projectIdForRepository = (() => {
1818
+ const repository = search.repository?.toLowerCase();
1819
+ if (repository === undefined) return undefined;
1820
+ const identity = projects.find(
1821
+ (project) =>
1822
+ project.repositoryIdentity?.owner &&
1823
+ project.repositoryIdentity.name &&
1824
+ `${project.repositoryIdentity.owner}/${project.repositoryIdentity.name}`.toLowerCase() ===
1825
+ repository &&
1826
+ (selectedHost === undefined ||
1827
+ pullRequestHostOf(
1828
+ project.repositoryIdentity,
1829
+ project.repositoryIdentity.provider as SourceControlProviderKind,
1830
+ ) === selectedHost.toLowerCase()),
1831
+ );
1832
+ return identity?.id;
1833
+ })();
1834
+
1835
+ const linkedProjectId = resolveProjectScope(search.selectedProjectId, projects, projectsKnown);
1836
+ const selectedProjectId = linkedProjectId ?? projectIdForRepository ?? scopedProjectId;
1837
+ // A named server still connecting is kept named rather than falling back: falling back while it
1838
+ // is merely not ready yet would resolve the project against whatever other server has answered,
1839
+ // which can be the wrong one where two servers share a project id.
1840
+ const selectedEnvironmentId = resolveSelectedEnvironmentId(
1841
+ search.selectedEnvironmentId,
1842
+ knownEnvironmentIds,
1843
+ scopedEnvironmentId,
1844
+ );
1845
+ const selectedProject = findScopedProject(projects, selectedEnvironmentId, selectedProjectId);
1846
+ const queryEnvironmentIds = resolveQueryEnvironmentIds(
1847
+ environmentIds,
1848
+ projects,
1849
+ scopedProject,
1850
+ scopedProjectId,
1851
+ projectsKnown,
1852
+ );
1853
+ const environmentQueries = ((): ReadonlyArray<{
1854
+ readonly environmentId: EnvironmentId;
1855
+ readonly projectIds?: ReadonlyArray<ProjectId>;
1856
+ }> => {
1857
+ const plain = queryEnvironmentIds.map((environmentId) => ({ environmentId }));
1858
+ if (!projectsKnown || scopedProjectId !== undefined) return plain;
1859
+ const assignment = assignProjectsToEnvironments(
1860
+ projects,
1861
+ queryEnvironmentIds,
1862
+ queryEnvironmentIds[0],
1863
+ );
1864
+ const totals = new Map<EnvironmentId, number>();
1865
+ for (const project of projects) {
1866
+ totals.set(project.environmentId, (totals.get(project.environmentId) ?? 0) + 1);
1867
+ }
1868
+ return queryEnvironmentIds.flatMap((environmentId) => {
1869
+ const projectIds = assignment.get(environmentId);
1870
+ if (projectIds === undefined) return [];
1871
+ if (projectIds.length === (totals.get(environmentId) ?? 0)) return [{ environmentId }];
1872
+ return [{ environmentId, projectIds }];
1873
+ });
1874
+ })();
1875
+ const assignmentKey = environmentQueries
1876
+ .map(({ environmentId, projectIds }) => `${environmentId}#${projectIds?.join("+") ?? "*"}`)
1877
+ .join("|");
1878
+ const linkedSelection =
1879
+ search.repository && search.number && selectedProject
1880
+ ? {
1881
+ environmentId: selectedProject.environmentId,
1882
+ repository: search.repository,
1883
+ number: search.number,
1884
+ projectId: selectedProject.id,
1885
+ ...(selectedHost ? { host: selectedHost } : {}),
1886
+ }
1887
+ : null;
1888
+ const expectedHosts = (() => {
1889
+ const byHost = new Map<string, PullRequestExpectedHost>();
1890
+ for (const project of projects) {
1891
+ const kind = project.repositoryIdentity?.provider as SourceControlProviderKind | undefined;
1892
+ if (kind === undefined) continue;
1893
+ const host = pullRequestHostOf(project.repositoryIdentity, kind);
1894
+ if (!byHost.has(host)) byHost.set(host, { host, kind });
1895
+ }
1896
+ return [...byHost.values()];
1897
+ })();
1898
+
1899
+ return {
1900
+ capableEnvironments,
1901
+ scopedEnvironmentId,
1902
+ environmentKey,
1903
+ capabilityKnown,
1904
+ pullRequestsSupported,
1905
+ projects,
1906
+ environmentLabels,
1907
+ scopedProjectId,
1908
+ scopedProject,
1909
+ scopedProjects,
1910
+ selectedProject,
1911
+ queryEnvironmentIds,
1912
+ environmentQueries,
1913
+ assignmentKey,
1914
+ linkedSelection,
1915
+ expectedHosts,
1916
+ };
1917
+}
1918
+
1919
+function usePullRequestQueryFilters(
1920
+ search: PullRequestsSearch,
1921
+ typedQuery: string,
1922
+ sentQuery: string,
1923
+) {
1924
+ // Calls no hooks, so the compiler needs the directive to memoize it.
1925
+ "use memo";
1926
+ const typedParsed = parsePullRequestQuery(typedQuery);
1927
+ const sentParsed = parsePullRequestQuery(sentQuery);
1928
+
1929
+ const menuFilters = {
1930
+ ...(search.draft ? { draft: search.draft } : {}),
1931
+ ...(search.review ? { review: search.review } : {}),
1932
+ ...(search.checks ? { checks: search.checks } : {}),
1933
+ ...(search.author ? { author: search.author } : {}),
1934
+ ...(search.labels ? { labels: search.labels.map((label) => [label]) } : {}),
1935
+ };
1936
+ const menuFiltered = Object.keys(menuFilters).length > 0;
1937
+ const filters = { ...menuFilters, ...sentParsed.filters };
1938
+ const hasFilters = Object.keys(filters).length > 0;
1939
+ const localFilters = { ...menuFilters, ...typedParsed.filters };
1940
+ const hasLocalFilters = Object.keys(localFilters).length > 0;
1941
+ return {
1942
+ typedParsed,
1943
+ sentParsed,
1944
+ menuFilters,
1945
+ menuFiltered,
1946
+ filters,
1947
+ hasFilters,
1948
+ localFilters,
1949
+ hasLocalFilters,
1950
+ };
1951
+}
1952
+
1953
+/** The held rows narrowed to what the reader asked for, in the groups the list shows. */
1954
+function usePullRequestGroups({
1955
+ known,
1956
+ providers,
1957
+ viewers,
1958
+ involvement,
1959
+ localFilters,
1960
+ hasLocalFilters,
1961
+ text,
1962
+ answeredLocally,
1963
+ baselineEmpty,
1964
+ held,
1965
+ authored,
1966
+ reviewing,
1967
+ partitionsWanted,
1968
+}: {
1969
+ known: ReadonlyArray<EnvironmentPullRequestEntry>;
1970
+ providers: PullRequestListResult["providers"];
1971
+ viewers: PullRequestListResult["viewers"];
1972
+ involvement: PullRequestInvolvement;
1973
+ localFilters: PullRequestListFilters;
1974
+ hasLocalFilters: boolean;
1975
+ text: string;
1976
+ answeredLocally: boolean;
1977
+ baselineEmpty: boolean;
1978
+ held: PullRequestPartitionsSnapshot | undefined;
1979
+ authored: ReadonlyArray<EnvironmentPullRequestEntry> | undefined;
1980
+ reviewing: ReadonlyArray<EnvironmentPullRequestEntry> | undefined;
1981
+ partitionsWanted: boolean;
1982
+}) {
1983
+ // Calls no hooks, so the compiler needs the directive to memoize it.
1984
+ "use memo";
1985
+ const searchingHosts = new Set(
1986
+ providers.flatMap((provider) => (provider.searchesOnHost ? [provider.host] : [])),
1987
+ );
1988
+
1989
+ const entries = (() => {
1990
+ const involvementEntries = filterPullRequestsByInvolvement(known, viewers, involvement);
1991
+ // The hosts search more than the row shows — a body, a review, a commit message — so once
1992
+ // their answer is in, narrowing it again here would throw away matches the reader asked for.
1993
+ // The local pass stands in for the answer that has not arrived yet, and for the hosts that
1994
+ // answered without searching at all: Azure DevOps has no text filter, so its rows arrive
1995
+ // whole and would otherwise sit under a search that never touched them.
1996
+ const narrowedEntries = hasLocalFilters
1997
+ ? involvementEntries.filter((entry) =>
1998
+ matchesPullRequestFilters(entry, localFilters, pullRequestEntryViewer(entry, viewers)),
1999
+ )
2000
+ : involvementEntries;
2001
+ if (text.length === 0) {
2002
+ return narrowedEntries.toSorted((left, right) =>
2003
+ right.updatedAt.localeCompare(left.updatedAt),
2004
+ );
2005
+ }
2006
+ return narrowedEntries.filter(
2007
+ (entry) =>
2008
+ (answeredLocally && searchingHosts.has(entry.host)) || matchesPullRequestQuery(entry, text),
2009
+ );
2010
+ })();
2011
+
2012
+ const listedPullRequestTabStatuses: Record<string, PullRequestTabStatusSeed> = Object.fromEntries(
2013
+ entries.map((entry) => [
2014
+ pullRequestSurfaceId(entry),
2015
+ {
2016
+ state: entry.state,
2017
+ isDraft: entry.isDraft,
2018
+ },
2019
+ ]),
2020
+ );
2021
+
2022
+ const groups = (() => {
2023
+ if (involvement !== "all") return [{ key: "others" as const, label: "", entries }];
2024
+ if (baselineEmpty) {
2025
+ return groupPullRequestsByInvolvement(entries, viewers);
2026
+ }
2027
+ const narrow = (rows: ReadonlyArray<EnvironmentPullRequestEntry> | undefined) =>
2028
+ rows === undefined || !hasLocalFilters
2029
+ ? rows
2030
+ : rows.filter((entry) =>
2031
+ matchesPullRequestFilters(entry, localFilters, pullRequestEntryViewer(entry, viewers)),
2032
+ );
2033
+ const narrowedAuthored = narrow(partitionsWanted ? (authored ?? held?.authored) : undefined);
2034
+ const narrowedReviewing = narrow(partitionsWanted ? (reviewing ?? held?.reviewing) : undefined);
2035
+ if (narrowedAuthored === undefined || narrowedReviewing === undefined) {
2036
+ return groupPullRequestsByInvolvement(entries, viewers);
2037
+ }
2038
+ return partitionPullRequestsWithPriority(entries, narrowedAuthored, narrowedReviewing);
2039
+ })();
2040
+
2041
+ const entriesByStatsKey: ReadonlyMap<string, EnvironmentPullRequestEntry> = new Map(
2042
+ groups.flatMap((group) =>
2043
+ group.entries.map((entry) => [pullRequestEntryKey(entry), entry] as const),
2044
+ ),
2045
+ );
2046
+ const heldPullRequestsBySurface = new Map(
2047
+ groups.flatMap((group) =>
2048
+ group.entries.map((entry) => [pullRequestListEntryId(entry), entry] as const),
2049
+ ),
2050
+ );
2051
+ return {
2052
+ entries,
2053
+ listedPullRequestTabStatuses,
2054
+ groups,
2055
+ entriesByStatsKey,
2056
+ heldPullRequestsBySurface,
2057
+ };
2058
+}
2059
+
2060
+/** The groups as shown: with measured sizes, optimistic actions, and the reader's sort. */
2061
+function usePullRequestDisplayGroups({
2062
+ groups,
2063
+ statsByRow,
2064
+ overrides,
2065
+ state,
2066
+ localFilters,
2067
+ hasLocalFilters,
2068
+ viewers,
2069
+ sort,
2070
+ text,
2071
+ involvement,
2072
+ hosts,
2073
+}: {
2074
+ groups: ReadonlyArray<PullRequestGroup<EnvironmentPullRequestEntry>>;
2075
+ statsByRow: PullRequestDiffStats;
2076
+ overrides: ReadonlyMap<string, PullRequestListOverride>;
2077
+ state: PullRequestListState;
2078
+ localFilters: PullRequestListFilters;
2079
+ hasLocalFilters: boolean;
2080
+ viewers: PullRequestListResult["viewers"];
2081
+ sort: PullRequestListSort;
2082
+ text: string;
2083
+ involvement: PullRequestInvolvement;
2084
+ hosts: PullRequestListResult["providers"];
2085
+}) {
2086
+ // Calls no hooks, so the compiler needs the directive to memoize it.
2087
+ "use memo";
2088
+ const displayGroups = (() => {
2089
+ const enriched = groups.map((group) => {
2090
+ const answered = applyPullRequestOverrides(
2091
+ group.entries.map((entry) => withDiffStat(entry, statsByRow)),
2092
+ overrides,
2093
+ pullRequestEntryKey,
2094
+ state,
2095
+ );
2096
+ return {
2097
+ ...group,
2098
+ entries:
2099
+ hasLocalFilters && overrides.size > 0
2100
+ ? answered.filter(
2101
+ (entry) =>
2102
+ !overrides.has(pullRequestEntryKey(entry)) ||
2103
+ matchesPullRequestFilters(
2104
+ entry,
2105
+ localFilters,
2106
+ pullRequestEntryViewer(entry, viewers),
2107
+ ),
2108
+ )
2109
+ : answered,
2110
+ };
2111
+ });
2112
+ return sortPullRequestGroups(
2113
+ enriched,
2114
+ sort,
2115
+ text,
2116
+ (entry) =>
2117
+ entry.additions + entry.deletions > 0 || statsByRow.has(pullRequestDiffStatKey(entry)),
2118
+ involvement,
2119
+ );
2120
+ })();
2121
+ const shownCount = displayGroups.reduce((count, group) => count + group.entries.length, 0);
2122
+ const hostActionsOf = pullRequestHostActions(hosts);
2123
+ const closeSweepRows = new Map(
2124
+ displayGroups.flatMap((group) =>
2125
+ group.entries.map(
2126
+ (entry) => [pullRequestEntryKey(entry), { entry, groupKey: group.key }] as const,
2127
+ ),
2128
+ ),
2129
+ );
2130
+ const listedPullRequestsBySurface = new Map(
2131
+ displayGroups.flatMap((group) =>
2132
+ group.entries.map((entry) => [pullRequestListEntryId(entry), entry] as const),
2133
+ ),
2134
+ );
2135
+
2136
+ return {
2137
+ displayGroups,
2138
+ shownCount,
2139
+ hostActionsOf,
2140
+ closeSweepRows,
2141
+ listedPullRequestsBySurface,
2142
+ };
2143
+}
2144
+
2145
function PullRequestFiltersMenuInSidebarOrder(
2146
props: ComponentProps<typeof PullRequestFiltersMenu>,
2147
) {
2148
const sidebarProjectGroups = useSidebarProjectGroups();
2102
- const projects = useMemo(
2103
- () => sortProjectsByGroupOrder(props.projects, sidebarProjectGroups),
2104
- [props.projects, sidebarProjectGroups],
2105
- );
2149
+ const projects = sortProjectsByGroupOrder(props.projects, sidebarProjectGroups);
2150
return <PullRequestFiltersMenu {...props} projects={projects} />;
2151
}
2152
@@ -2299,7 +2343,7 @@ function PullRequestsColumn({
2343
);
2344
observer.observe(marker);
2345
return () => observer.disconnect();
2302
- }, []);
2346
+ }, [scrollRef]);
2347
// Typing into the topbar search narrows the list, and a short enough list un-scrolls the
2348
// page — which dissolves the condensed topbar and unmounts the very input being typed in.
2349
const topbarSearchFocusedRef = useRef(false);
@@ -2325,9 +2369,9 @@ function PullRequestsColumn({
2369
window.addEventListener("keydown", onKeyDown);
2370
return () => window.removeEventListener("keydown", onKeyDown);
2371
}, [condensed]);
2372
+ if (!condensed && searchOpen) setSearchOpen(false);
2373
useEffect(() => {
2374
if (condensed) return;
2330
- setSearchOpen(false);
2375
if (!topbarSearchFocusedRef.current) return;
2376
topbarSearchFocusedRef.current = false;
2377
const input = inFlowSearchRef.current?.querySelector("input");