Skip to content
TypeScript

perf(web): defer pull request line stats until visible (#6471)

Adamulek1233c73fa7ce02b
diff --git a/apps/web/src/components/pullRequest/PullRequestRow.tsx b/apps/web/src/components/pullRequest/PullRequestRow.tsx
index b6b96ab7f55..2284144d7fd 100644
--- a/apps/web/src/components/pullRequest/PullRequestRow.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestRow.tsx
@@ -1,5 +1,5 @@
import { SearchIcon } from "lucide-react";
-import { memo } from "react";
+import { memo, type RefCallback } from "react";
import { cn } from "~/lib/utils";
import { getSourceControlPresentationForKind } from "~/sourceControlPresentation";
@@ -40,6 +40,8 @@ function PullRequestRowImpl({
showProvider,
environmentLabel,
matchedElsewhere,
+ statsKey,
+ statsRef,
onSelect,
}: {
entry: EnvironmentPullRequestEntry;
@@ -54,11 +56,16 @@ function PullRequestRowImpl({
* commit message. Saying so is the difference between a result and an apparently random row.
*/
matchedElsewhere?: boolean;
+ /** Used by the list's shared visibility observer to defer optional line-count reads. */
+ statsKey?: string;
+ statsRef?: RefCallback<HTMLButtonElement>;
onSelect: (entry: EnvironmentPullRequestEntry) => void;
}) {
const { Icon, providerName } = getSourceControlPresentationForKind(entry.provider);
return (
<button
+ ref={statsRef}
+ data-pull-request-stats-key={statsKey}
type="button"
aria-current={selected ? "true" : undefined}
onClick={() => onSelect(entry)}
diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
index 0145e618033..c8110d9ec7a 100644
--- a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
@@ -11,6 +11,10 @@ import {
matchesPullRequestFilters,
matchesPullRequestQuery,
parsePullRequestQuery,
+ pullRequestStatsBatches,
+ pullRequestStatsKeysToRequest,
+ pullRequestStatsRefreshBatches,
+ pullRequestStatsRequestBatches,
mergePullRequestDiffStats,
narrowPullRequestsToFilters,
partitionPullRequestsWithPriority,
@@ -18,6 +22,7 @@ import {
writePullRequestListSnapshot,
rankPullRequestMatches,
scorePullRequestMatch,
+ retainVisiblePullRequestStatsBatches,
withDiffStat,
resolveProjectScope,
resolveQueryEnvironmentIds,
@@ -56,6 +61,197 @@ function entry(
} as EnvironmentPullRequestEntry;
}
+describe("visible pull request line-count targets", () => {
+ it("does not request a row again after its received batch is pruned", () => {
+ const entries = [entry({ number: 1 }), entry({ number: 2 })];
+ const entriesByKey = new Map(entries.map((item) => [pullRequestEntryKey(item), item]));
+ const firstKey = pullRequestEntryKey(entries[0]!);
+ const secondKey = pullRequestEntryKey(entries[1]!);
+ const completedStats = mergePullRequestDiffStats(new Map(), [
+ {
+ environmentId: ENV_1,
+ projectId: "project-1",
+ number: 1,
+ additions: 1,
+ deletions: 1,
+ },
+ ]);
+
+ const keys = pullRequestStatsKeysToRequest(
+ entriesByKey,
+ new Set([firstKey, secondKey]),
+ [],
+ completedStats,
+ );
+ expect([...keys]).toEqual([secondKey]);
+ expect(pullRequestStatsBatches(entriesByKey, keys)[0]?.input.refs).toEqual([
+ { projectId: "project-1", repository: "pingdotgg/t3code", number: 2 },
+ ]);
+ });
+
+ it("drops historical rows after a long scroll so refresh stays bounded to the viewport", () => {
+ const entries = Array.from({ length: 500 }, (_, index) => entry({ number: index + 1 }));
+ const entriesByKey = new Map(entries.map((item) => [pullRequestEntryKey(item), item]));
+ const batches = entries.map(
+ (item) => pullRequestStatsBatches(entriesByKey, new Set([pullRequestEntryKey(item)]))[0]!,
+ );
+ const visibleKeys = new Set(entries.slice(-12).map(pullRequestEntryKey));
+
+ const retained = retainVisiblePullRequestStatsBatches(batches, visibleKeys);
+ expect(retained).toHaveLength(12);
+ expect(retained.flatMap((batch) => batch.input.refs.map((ref) => ref.number))).toEqual(
+ entries.slice(-12).map((item) => item.number),
+ );
+ });
+
+ it("keeps every per-environment batch within the stats contract limit", () => {
+ const entries = Array.from({ length: 501 }, (_, index) => entry({ number: index + 1 }));
+ const entriesByKey = new Map(entries.map((item) => [pullRequestEntryKey(item), item]));
+ const batches = pullRequestStatsBatches(
+ entriesByKey,
+ new Set(entries.map(pullRequestEntryKey)),
+ );
+
+ expect(batches.map((batch) => batch.input.refs.length)).toEqual([500, 1]);
+ expect(batches.flatMap((batch) => [...batch.keys])).toEqual(entries.map(pullRequestEntryKey));
+ });
+
+ it("selects visible rows for date modes and every uncached row for size modes", () => {
+ const entries = [
+ entry({ number: 1 }),
+ entry({ number: 2 }),
+ entry({ number: 3, environmentId: "env-2" as EnvironmentId }),
+ ];
+ const entriesByKey = new Map(entries.map((item) => [pullRequestEntryKey(item), item]));
+ const [firstKey, secondKey] = entries.map(pullRequestEntryKey);
+ const cachedStats = mergePullRequestDiffStats(new Map(), [
+ {
+ environmentId: ENV_1,
+ projectId: "project-1",
+ number: 1,
+ additions: 1,
+ deletions: 1,
+ },
+ ]);
+
+ const visible = pullRequestStatsRequestBatches({
+ entriesByKey,
+ candidateKeys: new Set([firstKey!, secondKey!]),
+ policy: "visible",
+ activeBatches: [],
+ statsByRow: cachedStats,
+ });
+ expect(visible.flatMap((batch) => batch.input.refs.map((ref) => ref.number))).toEqual([2]);
+
+ const eager = pullRequestStatsRequestBatches({
+ entriesByKey,
+ candidateKeys: new Set([firstKey!]),
+ policy: "eager",
+ activeBatches: [],
+ statsByRow: cachedStats,
+ });
+ expect(eager.map((batch) => batch.environmentId)).toEqual([ENV_1, "env-2"]);
+ expect(eager.flatMap((batch) => batch.input.refs.map((ref) => ref.number))).toEqual([2, 3]);
+ });
+
+ it("refreshes only visible rows unless size sorting needs every loaded row", () => {
+ const entries = [entry({ number: 1 }), entry({ number: 2 }), entry({ number: 3 })];
+ const entriesByKey = new Map(entries.map((item) => [pullRequestEntryKey(item), item]));
+ const visibleKeys = new Set([pullRequestEntryKey(entries[1]!)]);
+ const cachedStats = mergePullRequestDiffStats(
+ new Map(),
+ entries.map((item) => ({
+ environmentId: ENV_1,
+ projectId: item.projectId,
+ number: item.number,
+ additions: item.additions,
+ deletions: item.deletions,
+ })),
+ );
+
+ const visible = pullRequestStatsRequestBatches({
+ entriesByKey,
+ candidateKeys: visibleKeys,
+ policy: "visible",
+ activeBatches: [],
+ statsByRow: cachedStats,
+ refresh: true,
+ });
+ expect(visible[0]?.input.refs.map((ref) => ref.number)).toEqual([2]);
+
+ const eager = pullRequestStatsRequestBatches({
+ entriesByKey,
+ candidateKeys: visibleKeys,
+ policy: "eager",
+ activeBatches: [],
+ statsByRow: cachedStats,
+ refresh: true,
+ });
+ expect(eager[0]?.input.refs.map((ref) => ref.number)).toEqual([1, 2, 3]);
+ });
+
+ it("ignores a late refresh after the filter or stats policy changes", () => {
+ const entries = [entry({ number: 1 }), entry({ number: 2 })];
+ const entriesByKey = new Map(entries.map((item) => [pullRequestEntryKey(item), item]));
+ const visibleKeys = new Set([pullRequestEntryKey(entries[1]!)]);
+ const requestedScope = { key: "open", policy: "visible" } as const;
+ const refresh = (currentScope: { key: string; policy: "visible" | "eager" }) =>
+ pullRequestStatsRefreshBatches({
+ requestedScope,
+ currentScope,
+ entriesByKey,
+ candidateKeys: visibleKeys,
+ statsByRow: new Map(),
+ });
+
+ expect(refresh(requestedScope)?.[0]?.input.refs.map((ref) => ref.number)).toEqual([2]);
+ expect(refresh({ key: "closed", policy: "visible" })).toBeNull();
+ expect(refresh({ key: "open", policy: "eager" })).toBeNull();
+ });
+
+ it("does not add request batches again while rows are active or cached", () => {
+ const entries = [entry({ number: 1 }), entry({ number: 2 })];
+ const entriesByKey = new Map(entries.map((item) => [pullRequestEntryKey(item), item]));
+ const first = pullRequestStatsRequestBatches({
+ entriesByKey,
+ candidateKeys: new Set(),
+ policy: "eager",
+ activeBatches: [],
+ statsByRow: new Map(),
+ });
+
+ expect(
+ pullRequestStatsRequestBatches({
+ entriesByKey,
+ candidateKeys: new Set(),
+ policy: "eager",
+ activeBatches: first,
+ statsByRow: new Map(),
+ }),
+ ).toEqual([]);
+
+ const cachedStats = mergePullRequestDiffStats(
+ new Map(),
+ entries.map((item) => ({
+ environmentId: ENV_1,
+ projectId: item.projectId,
+ number: item.number,
+ additions: item.additions,
+ deletions: item.deletions,
+ })),
+ );
+ expect(
+ pullRequestStatsRequestBatches({
+ entriesByKey,
+ candidateKeys: new Set(entries.map(pullRequestEntryKey)),
+ policy: "visible",
+ activeBatches: [],
+ statsByRow: cachedStats,
+ }),
+ ).toEqual([]);
+ });
+});
+
describe("pull request involvement filtering", () => {
const entries = [
entry({ number: 1, author: { login: "Bilal", name: null, avatarUrl: null } }),
diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.ts
index 85cf9520dc9..e18fbe4ae5c 100644
--- a/apps/web/src/components/pullRequest/pullRequestList.logic.ts
+++ b/apps/web/src/components/pullRequest/pullRequestList.logic.ts
@@ -8,6 +8,7 @@ import {
resolvePullRequestAuthorFilter,
} from "@t3tools/contracts";
import type {
+ ProjectId,
PullRequestActor,
PullRequestDiffStat,
PullRequestInvolvement,
@@ -429,6 +430,155 @@ export function pullRequestEntryKey(entry: ScopedEntry): string {
return `${scope}${entry.host}:${entry.repository}#${entry.number}`;
}
+export interface PullRequestStatsTarget {
+ readonly environmentId: EnvironmentId;
+ readonly input: {
+ readonly refs: ReadonlyArray<{
+ readonly projectId: ProjectId;
+ readonly repository: string;
+ readonly number: number;
+ }>;
+ };
+}
+
+export interface PullRequestStatsBatch extends PullRequestStatsTarget {
+ readonly keys: ReadonlySet<string>;
+}
+
+export type PullRequestStatsPolicy = "visible" | "eager";
+
+export interface PullRequestStatsScope {
+ readonly key: string;
+ readonly policy: PullRequestStatsPolicy;
+}
+
+const MAX_PULL_REQUEST_STATS_REFS = 500;
+
+/** Excludes rows already covered by an active batch or the received-count cache. */
+export function pullRequestStatsKeysToRequest(
+ entriesByKey: ReadonlyMap<string, EnvironmentPullRequestEntry>,
+ enteredKeys: ReadonlySet<string>,
+ batches: ReadonlyArray<PullRequestStatsBatch>,
+ statsByRow: ReadonlyMap<string, unknown>,
+): ReadonlySet<string> {
+ const requested = new Set(batches.flatMap((batch) => [...batch.keys]));
+ return new Set(
+ [...enteredKeys].filter((key) => {
+ const entry = entriesByKey.get(key);
+ return (
+ entry !== undefined && !requested.has(key) && !statsByRow.has(pullRequestDiffStatKey(entry))
+ );
+ }),
+ );
+}
+
+/** Groups selected rows into bounded, immutable line-count reads per environment. */
+export function pullRequestStatsBatches(
+ entriesByKey: ReadonlyMap<string, EnvironmentPullRequestEntry>,
+ keys: ReadonlySet<string>,
+): ReadonlyArray<PullRequestStatsBatch> {
+ const byEnvironment = new Map<
+ EnvironmentId,
+ Array<{
+ readonly key: string;
+ readonly ref: PullRequestStatsTarget["input"]["refs"][number];
+ }>
+ >();
+ for (const key of keys) {
+ const entry = entriesByKey.get(key);
+ if (entry === undefined) continue;
+ const rows = byEnvironment.get(entry.environmentId) ?? [];
+ rows.push({
+ key,
+ ref: {
+ projectId: entry.projectId,
+ repository: entry.repository,
+ number: entry.number,
+ },
+ });
+ byEnvironment.set(entry.environmentId, rows);
+ }
+ return [...byEnvironment].flatMap(([environmentId, rows]) => {
+ const batches: PullRequestStatsBatch[] = [];
+ for (let index = 0; index < rows.length; index += MAX_PULL_REQUEST_STATS_REFS) {
+ const batch = rows.slice(index, index + MAX_PULL_REQUEST_STATS_REFS);
+ batches.push({
+ environmentId,
+ input: { refs: batch.map((row) => row.ref) },
+ keys: new Set(batch.map((row) => row.key)),
+ });
+ }
+ return batches;
+ });
+}
+
+/**
+ * Selects the next immutable stats batches. Size sorting needs every loaded row, while the other
+ * modes only need rows near the viewport. Normal reads skip active and cached rows; an explicit
+ * refresh asks for the selected rows again.
+ */
+export function pullRequestStatsRequestBatches({
+ entriesByKey,
+ candidateKeys,
+ policy,
+ activeBatches,
+ statsByRow,
+ refresh = false,
+}: {
+ readonly entriesByKey: ReadonlyMap<string, EnvironmentPullRequestEntry>;
+ readonly candidateKeys: ReadonlySet<string>;
+ readonly policy: PullRequestStatsPolicy;
+ readonly activeBatches: ReadonlyArray<PullRequestStatsBatch>;
+ readonly statsByRow: ReadonlyMap<string, unknown>;
+ readonly refresh?: boolean;
+}): ReadonlyArray<PullRequestStatsBatch> {
+ const requestedKeys = policy === "eager" ? new Set(entriesByKey.keys()) : candidateKeys;
+ const keys = refresh
+ ? requestedKeys
+ : pullRequestStatsKeysToRequest(entriesByKey, requestedKeys, activeBatches, statsByRow);
+ return pullRequestStatsBatches(entriesByKey, keys);
+}
+
+/** Ignores a refresh that finished after the list moved to another filter or stats policy. */
+export function pullRequestStatsRefreshBatches({
+ requestedScope,
+ currentScope,
+ entriesByKey,
+ candidateKeys,
+ statsByRow,
+}: {
+ readonly requestedScope: PullRequestStatsScope;
+ readonly currentScope: PullRequestStatsScope;
+ readonly entriesByKey: ReadonlyMap<string, EnvironmentPullRequestEntry>;
+ readonly candidateKeys: ReadonlySet<string>;
+ readonly statsByRow: ReadonlyMap<string, unknown>;
+}): ReadonlyArray<PullRequestStatsBatch> | null {
+ if (requestedScope.key !== currentScope.key || requestedScope.policy !== currentScope.policy) {
+ return null;
+ }
+ return pullRequestStatsRequestBatches({
+ entriesByKey,
+ candidateKeys,
+ policy: requestedScope.policy,
+ activeBatches: [],
+ statsByRow,
+ refresh: true,
+ });
+}
+
+/** Drops completed batches once every row in them has left the observer window. */
+export function retainVisiblePullRequestStatsBatches(
+ batches: ReadonlyArray<PullRequestStatsBatch>,
+ visibleKeys: ReadonlySet<string>,
+): ReadonlyArray<PullRequestStatsBatch> {
+ return batches.filter((batch) => {
+ for (const key of batch.keys) {
+ if (visibleKeys.has(key)) return true;
+ }
+ return false;
+ });
+}
+
/**
* The priority groups built from the hosts' own answers rather than re-partitioned from the
* paginated feed. The feed is sliced by recency, so an older authored or review-requested row
diff --git a/apps/web/src/routes/_chat.pull-requests.tsx b/apps/web/src/routes/_chat.pull-requests.tsx
index fcd17dbb7b8..abe76a65394 100644
--- a/apps/web/src/routes/_chat.pull-requests.tsx
+++ b/apps/web/src/routes/_chat.pull-requests.tsx
@@ -32,7 +32,15 @@ import {
RefreshCwIcon,
SearchIcon,
} from "lucide-react";
-import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+ type RefObject,
+} from "react";
import {
filterPullRequestsByInvolvement,
@@ -57,9 +65,15 @@ import {
withDiffStat,
writePullRequestListSnapshot,
scorePullRequestMatch,
+ pullRequestStatsRefreshBatches,
+ pullRequestStatsRequestBatches,
+ retainVisiblePullRequestStatsBatches,
type EnvironmentPullRequestEntry,
type MergedPullRequestList,
type PullRequestDiffStats,
+ type PullRequestStatsBatch,
+ type PullRequestStatsPolicy,
+ type PullRequestStatsScope,
type PullRequestPartitionsSnapshot,
} from "../components/pullRequest/pullRequestList.logic";
import { assignProjectsToEnvironments } from "../components/pullRequest/pullRequestProjectAssignment.logic";
@@ -273,6 +287,8 @@ export const Route = createFileRoute("/_chat/pull-requests")({
function PullRequestsRouteView() {
const search = Route.useSearch();
const sort = search.sort ?? "updated";
+ const statsPolicy: PullRequestStatsPolicy =
+ sort === "largest" || sort === "smallest" ? "eager" : "visible";
const navigate = useNavigate({ from: Route.fullPath });
const { environments } = useEnvironments();
// Every connected environment that has said it can list pull requests. Sorted, so the query
@@ -607,6 +623,8 @@ function PullRequestsRouteView() {
// Page size is view state, not a URL concern: a shared link should open the first page.
const scopeKey = `${environmentKey}:${assignmentKey}:${search.state}:${search.involvement}:${scopedProjectId ?? ""}:${search.host ?? ""}:${search.draft ?? ""}:${search.review ?? ""}:${search.checks ?? ""}:${search.author ?? ""}:${search.labels?.join("\u0000") ?? ""}`;
const filterKey = `${scopeKey}:${sentQuery}`;
+ const statsScopeRef = useRef<PullRequestStatsScope>({ key: filterKey, policy: statsPolicy });
+ statsScopeRef.current = { key: filterKey, policy: statsPolicy };
// Where the next slice carries on from, per repository within each environment, as that
// environment handed it back. Sending it is what makes a second page cost a second page rather
// than the whole list again — and a repository it does not name has run out and is not read a
@@ -780,6 +798,7 @@ function PullRequestsRouteView() {
// of its own work is a button that gets pressed again, and buys the whole cascade twice.
const [invalidating, setInvalidating] = useState(false);
const refreshFromHost = async () => {
+ const requestedStatsScope = statsScopeRef.current;
setInvalidating(true);
try {
// Every environment the page is reading, since what the reader pressed refresh for is the
@@ -795,7 +814,18 @@ function PullRequestsRouteView() {
facetQuery.refresh();
authoredQuery.refresh();
reviewingQuery.refresh();
- statsQuery.refresh();
+ const visible = visibleStatsKeys.current;
+ const batches = pullRequestStatsRefreshBatches({
+ requestedScope: requestedStatsScope,
+ currentScope: statsScopeRef.current,
+ entriesByKey: entriesByStatsKey.current,
+ candidateKeys: visible.key === requestedStatsScope.key ? visible.values : new Set(),
+ statsByRow: statsByRowRef.current,
+ });
+ if (batches !== null) {
+ setStatsTargetState({ key: requestedStatsScope.key, batches });
+ statsQuery.refresh(batches.map(({ environmentId, input }) => ({ environmentId, input })));
+ }
setDetailRefreshToken((token) => token + 1);
};
const refreshing = invalidating || listQuery.isPending;
@@ -1122,6 +1152,7 @@ function PullRequestsRouteView() {
viewers,
]);
+ const scrollRef = useRef<HTMLDivElement>(null);
const sentinelRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const sentinel = sentinelRef.current;
@@ -1156,7 +1187,7 @@ function PullRequestsRouteView() {
}
},
// Start the next page slightly before the sentinel is on screen.
- { rootMargin: "240px" },
+ { root: scrollRef.current, rootMargin: "240px" },
);
observer.observe(sentinel);
return () => observer.disconnect();
@@ -1220,35 +1251,136 @@ function PullRequestsRouteView() {
viewers,
]);
- // Keyed by every row being shown — the partitions can hold rows the feed has not paged to —
- // so scrolling further asks only about what is new. One read per environment, each asking only
- // about its own rows: a reference names a project, and a project belongs to one machine.
- const statsTargets = useMemo(() => {
- const refsByEnvironment = new Map<
- EnvironmentId,
- Array<{ projectId: ProjectId; repository: string; number: number }>
- >();
- for (const group of groups) {
- for (const entry of group.entries) {
- const refs = refsByEnvironment.get(entry.environmentId) ?? [];
- refs.push({
- projectId: entry.projectId,
- repository: entry.repository,
- number: entry.number,
- });
- refsByEnvironment.set(entry.environmentId, refs);
+ // Date sorts keep optional line-count reads near the viewport. Size sorts need every loaded
+ // count before their order is final. Received counts stay cached across both policies.
+ const entriesByStatsKey = useRef<ReadonlyMap<string, EnvironmentPullRequestEntry>>(new Map());
+ entriesByStatsKey.current = new Map(
+ groups.flatMap((group) =>
+ group.entries.map((entry) => [pullRequestEntryKey(entry), entry] as const),
+ ),
+ );
+ const visibleStatsKeys = useRef({ key: filterKey, values: new Set<string>() });
+ const [statsByRow, setStatsByRow] = useState<PullRequestDiffStats>(() => new Map());
+ const statsByRowRef = useRef(statsByRow);
+ statsByRowRef.current = statsByRow;
+ const [statsTargetState, setStatsTargetState] = useState<{
+ readonly key: string;
+ readonly batches: ReadonlyArray<PullRequestStatsBatch>;
+ }>({ key: filterKey, batches: [] });
+ const statsBatches = statsTargetState.key === filterKey ? statsTargetState.batches : [];
+ const statsTargets = useMemo(
+ () =>
+ statsBatches.map(({ environmentId, input }) => ({
+ environmentId,
+ input,
+ })),
+ [statsBatches],
+ );
+ const statsObserver = useRef<IntersectionObserver | null>(null);
+ const statsRows = useRef(new Set<HTMLButtonElement>());
+ const statsPending = useRef(true);
+ const statsPolicyRef = useRef(statsPolicy);
+ statsPolicyRef.current = statsPolicy;
+ const registerStatsRow = useCallback((node: HTMLButtonElement | null) => {
+ if (node === null || typeof IntersectionObserver === "undefined") return;
+ statsRows.current.add(node);
+ statsObserver.current?.observe(node);
+ return () => {
+ statsRows.current.delete(node);
+ statsObserver.current?.unobserve(node);
+ const key = node.dataset.pullRequestStatsKey;
+ const visible = visibleStatsKeys.current;
+ if (
+ statsPolicyRef.current !== "visible" ||
+ key === undefined ||
+ !visible.values.delete(key) ||
+ statsPending.current
+ ) {
+ return;
}
- }
- return [...refsByEnvironment].map(([environmentId, refs]) => ({
- environmentId,
- input: { refs },
- }));
- }, [groups]);
+ setStatsTargetState((current) => {
+ if (current.key !== visible.key) return current;
+ const batches = retainVisiblePullRequestStatsBatches(current.batches, visible.values);
+ return batches.length === current.batches.length ? current : { key: current.key, batches };
+ });
+ };
+ }, []);
+ useEffect(() => {
+ if (statsPolicy !== "eager") return;
+ setStatsTargetState((current) => {
+ const batches = current.key === filterKey ? current.batches : [];
+ const added = pullRequestStatsRequestBatches({
+ entriesByKey: entriesByStatsKey.current,
+ candidateKeys: visibleStatsKeys.current.values,
+ policy: statsPolicy,
+ activeBatches: batches,
+ statsByRow: statsByRowRef.current,
+ });
+ if (added.length === 0 && current.key === filterKey) return current;
+ return { key: filterKey, batches: [...batches, ...added] };
+ });
+ }, [filterKey, groups, statsPolicy]);
+ useEffect(() => {
+ if (statsPolicy !== "visible" || typeof IntersectionObserver === "undefined") return;
+ visibleStatsKeys.current = { key: filterKey, values: new Set() };
+ const observer = new IntersectionObserver(
+ (observed) => {
+ const visible = visibleStatsKeys.current;
+ if (visible.key !== filterKey) return;
+ let changed = false;
+ const entered = new Set<string>();
+ for (const item of observed) {
+ const key = (item.target as HTMLElement).dataset.pullRequestStatsKey;
+ if (key === undefined) continue;
+ const wasVisible = visible.values.has(key);
+ if (item.isIntersecting && entriesByStatsKey.current.has(key)) {
+ visible.values.add(key);
+ if (!wasVisible) entered.add(key);
+ } else {
+ visible.values.delete(key);
+ }
+ changed ||= wasVisible !== visible.values.has(key);
+ }
+ if (!changed) return;
+ setStatsTargetState((current) => {
+ const batches = current.key === filterKey ? current.batches : [];
+ const retained = statsPending.current
+ ? batches
+ : retainVisiblePullRequestStatsBatches(batches, visible.values);
+ const added = pullRequestStatsRequestBatches({
+ entriesByKey: entriesByStatsKey.current,
+ candidateKeys: entered,
+ policy: statsPolicy,
+ activeBatches: batches,
+ statsByRow: statsByRowRef.current,
+ });
+ if (added.length === 0 && retained.length === batches.length) return current;
+ return { key: filterKey, batches: [...retained, ...added] };
+ });
+ },
+ { root: scrollRef.current, rootMargin: "480px" },
+ );
+ statsObserver.current = observer;
+ for (const row of statsRows.current) observer.observe(row);
+ return () => {
+ observer.disconnect();
+ if (statsObserver.current === observer) statsObserver.current = null;
+ };
+ }, [filterKey, statsPolicy]);
const statsQuery = usePullRequestListStats(statsTargets);
+ statsPending.current = statsQuery.isPending;
+ useEffect(() => {
+ if (statsPolicy !== "visible" || statsQuery.isPending) return;
+ const visible = visibleStatsKeys.current;
+ setStatsTargetState((current) => {
+ if (current.key !== filterKey || visible.key !== filterKey) return current;
+ const batches = retainVisiblePullRequestStatsBatches(current.batches, visible.values);
+ return batches.length === current.batches.length ? current : { key: current.key, batches };
+ });
+ }, [filterKey, statsPolicy, statsQuery.isPending]);
// Adding or removing one row keys a fresh stats query with nothing in it yet, so the counts
// are merged into what is already held rather than rebuilt: every count on screen stays until
// its replacement arrives.
- const [statsByRow, setStatsByRow] = useState<PullRequestDiffStats>(() => new Map());
useEffect(() => {
const stats = statsQuery.stats;
if (stats === null) return;
@@ -1486,30 +1618,35 @@ function PullRequestsRouteView() {
{group.label}
</h2>
) : null}
- {group.entries.map((entry) => (
- <PullRequestRow
- key={pullRequestEntryKey(entry)}
- entry={entry}
- showProjectTitle
- showProvider={showProvider}
- {...(capableEnvironments.length > 1 &&
- environmentLabels.get(entry.environmentId) !== undefined
- ? { environmentLabel: environmentLabels.get(entry.environmentId)! }
- : {})}
- // Ten is the floor the ranking gives a row whose own fields say nothing
- // about the search: the host matched something this row cannot show.
- matchedElsewhere={
- typedParsed.text.length > 0 &&
- scorePullRequestMatch(entry, typedParsed.text) <= MATCHED_ELSEWHERE_SCORE
- }
- selected={
- selected?.environmentId === entry.environmentId &&
- selected.repository === entry.repository &&
- selected.number === entry.number
- }
- onSelect={selectEntry}
- />
- ))}
+ {group.entries.map((entry) => {
+ const entryKey = pullRequestEntryKey(entry);
+ return (
+ <PullRequestRow
+ key={entryKey}
+ statsKey={entryKey}
+ statsRef={registerStatsRow}
+ entry={entry}
+ showProjectTitle
+ showProvider={showProvider}
+ {...(capableEnvironments.length > 1 &&
+ environmentLabels.get(entry.environmentId) !== undefined
+ ? { environmentLabel: environmentLabels.get(entry.environmentId)! }
+ : {})}
+ // Ten is the floor the ranking gives a row whose own fields say nothing
+ // about the search: the host matched something this row cannot show.
+ matchedElsewhere={
+ typedParsed.text.length > 0 &&
+ scorePullRequestMatch(entry, typedParsed.text) <= MATCHED_ELSEWHERE_SCORE
+ }
+ selected={
+ selected?.environmentId === entry.environmentId &&
+ selected.repository === entry.repository &&
+ selected.number === entry.number
+ }
+ onSelect={selectEntry}
+ />
+ );
+ })}
</div>
))}
</div>
@@ -1648,6 +1785,7 @@ function PullRequestsRouteView() {
pullRequestsSupported && !rightPanelState.isOpen ? openPanelControls : null,
rightPanelOpen: rightPanelState.isOpen,
listBody,
+ scrollRef,
};
const activateSurface = (surface: PullRequestSurface) => {
@@ -1932,6 +2070,7 @@ function PullRequestsColumn({
titlebarControls,
rightPanelOpen,
listBody,
+ scrollRef,
}: {
refreshing: boolean;
onRefresh: () => void;
@@ -1950,8 +2089,8 @@ function PullRequestsColumn({
titlebarControls: ReactNode;
rightPanelOpen: boolean;
listBody: ReactNode;
+ scrollRef: RefObject<HTMLDivElement | null>;
}) {
- const scrollRef = useRef<HTMLDivElement | null>(null);
const markerRef = useRef<HTMLDivElement | null>(null);
const [condensed, setCondensed] = useState(false);
useEffect(() => {
diff --git a/apps/web/src/state/pullRequests.ts b/apps/web/src/state/pullRequests.ts
index 99bbddd6e38..939c4f3aea2 100644
--- a/apps/web/src/state/pullRequests.ts
+++ b/apps/web/src/state/pullRequests.ts
@@ -31,7 +31,7 @@ export interface EnvironmentQueryTarget<Input> {
}
interface MergedEnvironmentQueryView<A> {
- /** One entry per environment that has answered, in the order the targets were given. */
+ /** One entry per query target that has answered, in the order the targets were given. */
readonly values: ReadonlyArray<readonly [EnvironmentId, A]>;
/** The first environment that failed. Others may still have answered — this is not fatal. */
readonly error: string | null;
@@ -78,11 +78,16 @@ function createMergedEnvironmentQuery<Input, A>(
return function useMergedQuery(targets: ReadonlyArray<EnvironmentQueryTarget<Input>>) {
const key = JSON.stringify(targets);
const view = useAtomValue(targets.length === 0 ? empty : family(key));
- const refresh = useCallback(() => {
- for (const target of JSON.parse(key) as ReadonlyArray<EnvironmentQueryTarget<Input>>) {
- appAtomRegistry.refresh(atomFor(target));
- }
- }, [key]);
+ const refresh = useCallback(
+ (override?: ReadonlyArray<EnvironmentQueryTarget<Input>>) => {
+ const refreshTargets =
+ override ?? (JSON.parse(key) as ReadonlyArray<EnvironmentQueryTarget<Input>>);
+ for (const target of refreshTargets) {
+ appAtomRegistry.refresh(atomFor(target));
+ }
+ },
+ [key],
+ );
return { ...view, refresh };
};
}
@@ -118,7 +123,10 @@ export function usePullRequestListStats(
targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListStatsInput>>,
): {
readonly stats: ReadonlyArray<EnvironmentPullRequestStat> | null;
- readonly refresh: () => void;
+ readonly isPending: boolean;
+ readonly refresh: (
+ targets?: ReadonlyArray<EnvironmentQueryTarget<PullRequestListStatsInput>>,
+ ) => void;
} {
const query = usePullRequestStatsQuery(targets);
const stats = useMemo(
@@ -130,5 +138,5 @@ export function usePullRequestListStats(
),
[query.values],
);
- return { stats, refresh: query.refresh };
+ return { stats, isPending: query.isPending, refresh: query.refresh };
}