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

main
tsx 1,728 lines 68 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import { heldPullRequestListEntriesAtom } from "@t3tools/client-runtime/state/pull-requests";
3 import { AsyncResult, Atom } from "effect/reactivity";
4 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
5 import { applyPullRequestDraftFilterChange } from "@t3tools/client-runtime/pull-request-query";
6 import { Spinner } from "~/components/ui/spinner";
7 import type { PullRequestSpeedActionResult } from "~/components/pullRequest/PullRequestSpeedActions";
8 import { usePullRequestCloseBatch } from "~/components/pullRequest/usePullRequestActions";
9 import { SidebarPointerSensor } from "~/components/Sidebar.pointer";
10 import { resolveSidebarSweepKeys } from "~/components/Sidebar.logic";
11 import { sortProjectsByGroupOrder } from "@t3tools/client-runtime/state/project-grouping";
12 import { resolveEnvironmentMachineKind } from "@t3tools/contracts";
13 import type {
14 EnvironmentId,
15 ProjectId,
16 PullRequestAction,
17 PullRequestInvolvement,
18 PullRequestListCursors,
19 PullRequestListInput,
20 PullRequestListResult,
21 PullRequestListState,
22 PullRequestSummary,
23 } from "@t3tools/contracts";
24 import { useAtomValue } from "@effect/atom-react";
25 import { useNavigate, useSearch } from "@tanstack/react-router";
26 import { ArrowDownUpIcon, LayersIcon, Plug2Icon } from "lucide-react";
27 import { msg, T, useGT, useMessages } from "gt-react";
28
29 import { m } from "~/i18n/messages";
30 import { useEffect, useEffectEvent, useRef, useState, type ComponentProps } from "react";
31
32 import {
33 collectPullRequestListFacets,
34 narrowPullRequestsToFilters,
35 mergePullRequestDiffStats,
36 pullRequestDiffStatKey,
37 pullRequestEntryKey,
38 rankPullRequestMatches,
39 pullRequestStatsRefreshBatches,
40 pullRequestStatsRequestBatches,
41 retainVisiblePullRequestStatsBatches,
42 type EnvironmentPullRequestEntry,
43 type MergedPullRequestList,
44 type PullRequestDiffStats,
45 type PullRequestStatsBatch,
46 type PullRequestStatsPolicy,
47 type PullRequestStatsScope,
48 type PullRequestPartitionsSnapshot,
49 type PullRequestListOverride,
50 pullRequestOverrideAfterAction,
51 reusePullRequestEntries,
52 settlePullRequestOverrides,
53 comparePullRequestsByRecency,
54 largestPullRequestReadCount,
55 } from "./pullRequestList.logic";
56 import {
57 pullRequestListPreferences,
58 type PullRequestListPreferencePatch,
59 writePullRequestListPreferences,
60 } from "./pullRequestListPreferences";
61 import { SavedViewsMenu } from "../SavedViewsMenu";
62 import { PULL_REQUEST_SAVED_VIEWS, pullRequestSavedViewPatch } from "./pullRequestSavedViews";
63 import { environmentMachineIcon } from "../EnvironmentMachineIcon";
64 import { PullRequestDetailPanel } from "./PullRequestDetailPanel";
65 import {
66 PullRequestFiltersMenu,
67 PullRequestSearchInput,
68 pullRequestHostLabel,
69 pullRequestProjectKey,
70 type PullRequestFilterOption,
71 } from "./PullRequestListFilters";
72 import { PullRequestCompactFilterMenu } from "./PullRequestCompactFilterMenu";
73 import {
74 INVOLVEMENT_TABS,
75 resolveFilterOptions,
76 SORT_OPTIONS,
77 STATE_TABS,
78 } from "./pullRequestListOptions";
79 import { PullRequestsColumn } from "./PullRequestsColumn";
80 import { PullRequestListGroups } from "./PullRequestListGroups";
81 import { pullRequestPanelReference } from "./usePullRequestDetail";
82 import { usePullRequestIntentPrefetch } from "./usePullRequestIntentPrefetch";
83 import {
84 usePullRequestDisplayGroups,
85 usePullRequestQueryFilters,
86 usePullRequestScope,
87 type PullRequestsSearch,
88 } from "./usePullRequestListView";
89 import { pullRequestGroups, pullRequestListEntryId } from "./pullRequestListGroups.logic";
90 import { PullRequestListEmptyState } from "./PullRequestListEmptyState";
91 import { PullRequestListGhost } from "./PullRequestGhosts";
92 import { type PullRequestRowTarget } from "./PullRequestRow";
93 import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState";
94 import { RightPanelTabs } from "../RightPanelTabs";
95 import { isCommandPaletteOpen } from "~/commandPaletteBus";
96 import { isElectron } from "~/env";
97 import { resolveShortcutCommand, shortcutLabelForCommand } from "~/keybindings";
98 import { registerCommands } from "~/shortcuts/dispatcher";
99 import { isTerminalFocused } from "~/lib/terminalFocus";
100 import { PanelLayoutControls, RightPanelMaximizeControl } from "../chat/PanelLayoutControls";
101 import { Button } from "../ui/button";
102 import { SidebarInset, useMobileSidebarSheetMounted } from "../ui/sidebar";
103 import { useLiveRefresh } from "~/hooks/useLiveRefresh";
104 import { useStableCallback } from "~/hooks/useStableCallback";
105 import { useOpenPanelPullRequestUrl } from "~/hooks/useOpenPanelPullRequestUrl";
106 import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
107 import { toastManager } from "../ui/toast";
108 import { usePanelAnimationSettings, usePanelPresence } from "~/panelAnimations";
109 import {
110 PULL_REQUESTS_PANEL_REF,
111 selectActiveRightPanelSurface,
112 selectSelectedRightPanelSurface,
113 selectThreadRightPanelState,
114 useRightPanelStore,
115 type PullRequestSurface,
116 } from "~/rightPanelStore";
117 import { useSidebarProjectGroups } from "~/hooks/useSidebarProjectGroups";
118 import {
119 pullRequestEnvironment,
120 usePullRequestHostList,
121 usePullRequestListStats,
122 restoredPullRequestList,
123 usePullRequestTurnRefreshes,
124 useSharedPullRequestSummary,
125 type EnvironmentQueryTarget,
126 } from "~/state/pullRequests";
127 import { useAtomCommand } from "~/state/use-atom-command";
128 import { cn } from "~/lib/utils";
129 import { primaryServerKeybindingsAtom } from "~/state/server";
130 import { getSourceControlPresentationForKind } from "~/sourceControlPresentation";
131 import {
132 rememberPullRequestHosts,
133 resetPullRequestHosts,
134 type PullRequestHostRead,
135 } from "./pullRequestProjectAssignment.logic";
136
137 import { changeRequestTermKind } from "./changeRequestTerm";
138
139 function getShortcutContext() {
140 return {
141 terminalFocus: isTerminalFocused(),
142 terminalOpen: false,
143 previewFocus: false,
144 previewOpen: false,
145 modelPickerOpen: false,
146 isWeb: !isElectron,
147 isDesktop: isElectron,
148 };
149 }
150
151 /**
152 * One whole page from the host and no more: every provider asks for one row beyond the page as
153 * its "is there more" probe, and GitHub serves a hundred per request — so asking for ninety-nine
154 * costs one round trip where a hundred costs two.
155 */
156 const PAGE_SIZE = 99;
157 const MAX_PAGE_SIZE = 500;
158 const EMPTY_VIEWERS: PullRequestListResult["viewers"] = {};
159 const EMPTY_PARTITIONS: PullRequestPartitionsSnapshot = { authored: [], reviewing: [] };
160 const NO_LIST_TARGETS: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>> = [];
161 const EMPTY_PREVIEW_SESSIONS = {};
162 const EMPTY_PREVIEW_DESKTOP_STATE = {};
163 const EMPTY_TERMINAL_LABELS = new Map<string, string>();
164 const EMPTY_PENDING_SURFACES = new Set<string>();
165 const heldRowReaders = new WeakMap<
166 EnvironmentPullRequestEntry,
167 Map<string, ReturnType<typeof heldPullRequestListEntriesAtom<EnvironmentPullRequestEntry>>>
168 >();
169
170 function usePendingListEntries(
171 input: PullRequestListInput,
172 entries: ReadonlyArray<EnvironmentPullRequestEntry> | undefined,
173 ) {
174 const key = JSON.stringify(input);
175 return useAtomValue(
176 Atom.make((get) =>
177 (entries ?? []).flatMap((entry) => {
178 let readers = heldRowReaders.get(entry);
179 if (readers === undefined) {
180 readers = new Map();
181 heldRowReaders.set(entry, readers);
182 }
183 let reader = readers.get(key);
184 if (reader === undefined) {
185 reader = heldPullRequestListEntriesAtom(entry.environmentId, input, [entry]);
186 readers.set(key, reader);
187 }
188 return AsyncResult.getOrElse(get(reader), () => []);
189 }),
190 ),
191 );
192 }
193
194 export function PullRequestsPage() {
195 const gt = useGT();
196 const resolve = useMessages();
197 const search = useSearch({ from: "/_chat/pull-requests" });
198 const sort = search.sort ?? "ready";
199 const statsPolicy: PullRequestStatsPolicy =
200 sort === "ready" || sort === "largest" || sort === "smallest" ? "eager" : "visible";
201 const navigate = useNavigate({ from: "/pull-requests" });
202 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
203 const [hostReads, setHostReads] = useState<ReadonlyMap<EnvironmentId, PullRequestHostRead>>(
204 () => new Map(),
205 );
206 const {
207 capableEnvironments,
208 scopedEnvironmentId,
209 environmentKey,
210 capabilityKnown,
211 pullRequestsSupported,
212 projects,
213 environmentLabels,
214 scopedProjectId,
215 scopedProject,
216 scopedProjects,
217 selectedProject,
218 queryEnvironmentIds,
219 environmentQueries,
220 preferredEnvironmentQueries,
221 assignmentKey,
222 linkedSelection,
223 expectedHosts,
224 projectsKnown,
225 } = usePullRequestScope(search, hostReads);
226 const rightPanelRef = capableEnvironments.length === 0 ? null : PULL_REQUESTS_PANEL_REF;
227 const openPanelPullRequestUrl = useOpenPanelPullRequestUrl(rightPanelRef);
228 const rightPanelState = useRightPanelStore((state) =>
229 selectThreadRightPanelState(state.byThreadKey, rightPanelRef),
230 );
231 const selectedRightPanelSurface = useRightPanelStore((state) =>
232 selectSelectedRightPanelSurface(state.byThreadKey, rightPanelRef),
233 );
234 const selectedPullRequestSurface =
235 selectedRightPanelSurface?.kind === "pull-request" ? selectedRightPanelSurface : null;
236 const activePullRequestSurface = rightPanelState.isOpen ? selectedPullRequestSurface : null;
237 const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
238 usePanelAnimationSettings();
239 const rightPanelPresenceValue = {
240 activeSurface: selectedPullRequestSurface,
241 surfaces: rightPanelState.surfaces,
242 };
243 const rightPanelPresence = usePanelPresence(
244 rightPanelState.isOpen && selectedPullRequestSurface !== null,
245 rightPanelPresenceValue,
246 panelAnimationsActive,
247 rightPanelRef?.threadId ?? null,
248 panelAnimationDurationMs,
249 );
250 const rightPanelPresent = rightPanelPresence.present;
251 const renderedPullRequestSurface = rightPanelPresence.value?.activeSurface ?? null;
252 const renderedRightPanelSurfaces = rightPanelPresence.value?.surfaces ?? [];
253 const panelEnvironmentId =
254 (renderedPullRequestSurface?.environmentId as EnvironmentId | undefined) ??
255 selectedProject?.environmentId ??
256 null;
257 const panelSummary = useSharedPullRequestSummary(
258 panelEnvironmentId,
259 renderedPullRequestSurface === null
260 ? null
261 : {
262 ...renderedPullRequestSurface,
263 projectId: renderedPullRequestSurface.projectId as ProjectId,
264 },
265 );
266 const updateSearch = (patch: {
267 [Key in keyof PullRequestsSearch]?: PullRequestsSearch[Key] | undefined;
268 }) =>
269 void navigate({
270 search: (previous: PullRequestsSearch): PullRequestsSearch => {
271 const next = { ...previous, ...patch };
272 return {
273 involvement: next.involvement ?? previous.involvement,
274 state: next.state ?? previous.state,
275 ...(next.sort && next.sort !== "ready" ? { sort: next.sort } : {}),
276 ...(next.repository ? { repository: next.repository } : {}),
277 ...(next.number ? { number: next.number } : {}),
278 ...(next.projectId ? { projectId: next.projectId } : {}),
279 ...(next.environmentId ? { environmentId: next.environmentId } : {}),
280 ...(next.host ? { host: next.host } : {}),
281 ...(next.selectedHost ? { selectedHost: next.selectedHost } : {}),
282 ...(next.selectedProjectId ? { selectedProjectId: next.selectedProjectId } : {}),
283 ...(next.selectedEnvironmentId
284 ? { selectedEnvironmentId: next.selectedEnvironmentId }
285 : {}),
286 ...(next.q ? { q: next.q } : {}),
287 ...(next.draft ? { draft: next.draft } : {}),
288 ...(next.review ? { review: next.review } : {}),
289 ...(next.checks ? { checks: next.checks } : {}),
290 ...(next.author ? { author: next.author } : {}),
291 ...(next.labels && next.labels.length > 0 ? { labels: next.labels } : {}),
292 };
293 },
294 replace: true,
295 });
296
297 const clearedSelection = {
298 repository: undefined,
299 number: undefined,
300 selectedProjectId: undefined,
301 selectedEnvironmentId: undefined,
302 selectedHost: undefined,
303 };
304 const updateListScope = (patch: PullRequestListPreferencePatch) => {
305 const currentPreferences = pullRequestListPreferences({
306 ...search,
307 ...patch,
308 involvement: patch.involvement ?? search.involvement,
309 state: patch.state ?? search.state,
310 });
311 writePullRequestListPreferences(currentPreferences);
312 updateSearch(patch);
313 };
314
315 const typedQuery = (search.q ?? "").trim();
316 const [filtersOpen, setFiltersOpen] = useState(false);
317 const {
318 sentQuery,
319 submitQuery,
320 querySettled,
321 typedParsed,
322 sentParsed,
323 menuFilters,
324 menuFiltered,
325 filters,
326 hasFilters,
327 localFilters,
328 hasLocalFilters,
329 } = usePullRequestQueryFilters(search, typedQuery);
330 const turnRefreshes = usePullRequestTurnRefreshes([
331 ...new Set(environmentQueries.map(({ environmentId }) => environmentId)),
332 ]);
333 const turnRefreshToken = turnRefreshes
334 .map(([environmentId, revision]) => `${environmentId}:${revision}`)
335 .join("|");
336 const scopeKey = `${environmentKey}:${assignmentKey}:${search.state}:${search.involvement}:${scopedProjectId ?? ""}:${search.host ?? ""}:${search.draft ?? ""}:${search.review ?? ""}:${search.checks ?? ""}:${search.author ?? ""}:${search.labels?.join("\u0000") ?? ""}`;
337 const filterKey = `${scopeKey}:${sentQuery}`;
338 const statsScope: PullRequestStatsScope = { key: filterKey, policy: statsPolicy };
339 const [page, setPage] = useState<{
340 key: string;
341 size: number;
342 cursors: Readonly<Record<string, PullRequestListCursors>> | null;
343 /**
344 * An environment can say it has more without saying where to carry on from — its provider has
345 * no cursor to give — and a continuation naming only the others would strand its rows on the
346 * host forever.
347 */
348 regrown: ReadonlyArray<string>;
349 /** The turn refreshes a continuation was read under; a later turn makes its cursors stale. */
350 turn: string;
351 }>({ key: filterKey, size: PAGE_SIZE, cursors: null, regrown: [], turn: turnRefreshToken });
352 const pageSize = page.key === filterKey ? page.size : PAGE_SIZE;
353 const sentCursors = page.key === filterKey ? page.cursors : null;
354 const sentRegrown = page.key === filterKey ? page.regrown : [];
355
356 if (page.key !== filterKey) {
357 setPage({
358 key: filterKey,
359 size: PAGE_SIZE,
360 cursors: null,
361 regrown: [],
362 turn: turnRefreshToken,
363 });
364 }
365
366 const listTargetsFor = (queries: typeof environmentQueries) =>
367 queries.flatMap(({ environmentId, projectIds }) => {
368 const cursors = sentCursors?.[environmentId];
369 if (sentCursors !== null && cursors === undefined && !sentRegrown.includes(environmentId)) {
370 return [];
371 }
372 return [
373 {
374 environmentId,
375 input: {
376 state: search.state,
377 involvement: search.involvement,
378 limit: pageSize,
379 ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
380 ...(projectIds ? { projectIds } : {}),
381 ...(search.host ? { host: search.host } : {}),
382 ...(hasFilters ? { filters } : {}),
383 ...(sentParsed.text ? { query: sentParsed.text } : {}),
384 ...(cursors === undefined ? {} : { cursors }),
385 } satisfies PullRequestListInput,
386 },
387 ];
388 });
389 const listTargets = listTargetsFor(environmentQueries);
390 const listQuery = usePullRequestHostList(listTargets);
391
392 /**
393 * Kept as its own read rather than remembered from an earlier answer because an answer cannot
394 * say which question it belongs to: mid-switch the text has already changed and the data has
395 * not, and a search's answer would file itself under the workspace.
396 */
397 const baselineTargetsFor = (queries: typeof environmentQueries) =>
398 queries.map(({ environmentId, projectIds }) => ({
399 environmentId,
400 input: {
401 state: search.state,
402 involvement: search.involvement,
403 limit: PAGE_SIZE,
404 ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
405 ...(projectIds ? { projectIds } : {}),
406 ...(search.host ? { host: search.host } : {}),
407 ...(menuFiltered ? { filters: menuFilters } : {}),
408 } satisfies PullRequestListInput,
409 }));
410 const baselineTargets = baselineTargetsFor(environmentQueries);
411 const baselineQuery = usePullRequestHostList(baselineTargets);
412 const observedHosts = rememberPullRequestHosts(
413 rememberPullRequestHosts(hostReads, baselineQuery.observations),
414 listQuery.observations,
415 );
416 if (observedHosts !== hostReads) setHostReads(observedHosts);
417 const baselineEmpty =
418 baselineQuery.data?.entries.length === 0 &&
419 baselineQuery.data.errors.length === 0 &&
420 !baselineQuery.isPending &&
421 baselineQuery.error === null;
422 const facetTargets = (() => {
423 if (!filtersOpen) return NO_LIST_TARGETS;
424 return environmentQueries.map(({ environmentId, projectIds }) => ({
425 environmentId,
426 input: {
427 state: "all",
428 involvement: search.involvement,
429 limit: PAGE_SIZE,
430 ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
431 ...(projectIds ? { projectIds } : {}),
432 ...(search.host ? { host: search.host } : {}),
433 } satisfies PullRequestListInput,
434 }));
435 })();
436 const facetQuery = usePullRequestHostList(facetTargets);
437 const filterOptionScope = environmentQueries.map(({ environmentId, projectIds }) => ({
438 environmentId,
439 input: {
440 ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
441 ...(projectIds ? { projectIds } : {}),
442 ...(search.host ? { host: search.host } : {}),
443 },
444 }));
445 const partitionsWanted = search.involvement === "all" && typedQuery.length === 0;
446 const partitionTargets = (() => {
447 // The main list goes first. Besides putting the visible rows on screen sooner, it proves
448 // which repositories the host search indexes, so an empty partition does not trigger the
449 // expensive per-repository fallback.
450 if (
451 !partitionsWanted ||
452 baselineQuery.data === null ||
453 baselineQuery.data.entries.length === 0
454 ) {
455 return { authored: NO_LIST_TARGETS, reviewing: NO_LIST_TARGETS };
456 }
457 const targetsFor = (involvement: PullRequestInvolvement) =>
458 environmentQueries.map(({ environmentId, projectIds }) => ({
459 environmentId,
460 input: {
461 state: search.state,
462 involvement,
463 limit: PAGE_SIZE,
464 ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
465 ...(projectIds ? { projectIds } : {}),
466 ...(search.host ? { host: search.host } : {}),
467 ...(menuFiltered ? { filters: menuFilters } : {}),
468 } satisfies PullRequestListInput,
469 }));
470 return { authored: targetsFor("authored"), reviewing: targetsFor("reviewing") };
471 })();
472 const authoredQuery = usePullRequestHostList(partitionTargets.authored);
473 const reviewingQuery = usePullRequestHostList(partitionTargets.reviewing);
474 const invalidate = useAtomCommand(pullRequestEnvironment.invalidate, { reportFailure: false });
475 const [detailRefreshToken, setDetailRefreshToken] = useState(0);
476 const [invalidating, setInvalidating] = useState(false);
477 const refreshing = invalidating || listQuery.isPending;
478
479 const [loaded, setLoaded] = useState<{
480 environmentKey: string;
481 scope: string;
482 query: string;
483 /** The answer this was built from, so a re-render with the same answer leaves it alone. */
484 source: MergedPullRequestList | null;
485 data: MergedPullRequestList;
486 partitions?: PullRequestPartitionsSnapshot;
487 } | null>(null);
488 const [ordered, setOrdered] = useState<{
489 key: string;
490 source: MergedPullRequestList;
491 entries: ReadonlyArray<EnvironmentPullRequestEntry>;
492 } | null>(null);
493 const [overrides, setOverrides] = useState<ReadonlyMap<string, PullRequestListOverride>>(
494 () => new Map(),
495 );
496 const overrideToken = useRef(0);
497 const overrideEntry = (
498 entry: EnvironmentPullRequestEntry,
499 action: PullRequestAction,
500 reply?: PullRequestSummary,
501 ): number | null => {
502 const token = ++overrideToken.current;
503 const override = pullRequestOverrideAfterAction(entry, action, new Date(), token, reply);
504 if (override === null) return null;
505 setOverrides((current) => new Map(current).set(pullRequestEntryKey(entry), override));
506 return token;
507 };
508 const revertOverride = (key: string, token: number | null) => {
509 if (token === null) return;
510 setOverrides((current) => {
511 if (current.get(key)?.token !== token) return current;
512 const next = new Map(current);
513 next.delete(key);
514 return next;
515 });
516 };
517 const detailOverrideTokens = useRef(new Map<string, number | null>());
518 const onSpeedAction = useStableCallback(
519 ({ entry, action, reply }: PullRequestSpeedActionResult) => {
520 // Some hosts accept a merge before it completes. Without a reply, let the next read say so.
521 if (reply !== undefined || action !== "merge") overrideEntry(entry, action, reply);
522 },
523 );
524 const onBatchClosed = useStableCallback(
525 (entry: EnvironmentPullRequestEntry, reply: PullRequestSummary | undefined) => {
526 onSpeedAction({ entry, action: "close", reply });
527 },
528 );
529 const { close: closeBatch, closingKeys } = usePullRequestCloseBatch(onBatchClosed);
530 const [snapshotEnvironmentKey, setSnapshotEnvironmentKey] = useState("");
531 if (environmentKey.length > 0 && snapshotEnvironmentKey !== environmentKey) {
532 setSnapshotEnvironmentKey(environmentKey);
533 if (loaded?.environmentKey !== environmentKey) {
534 const restored = restoredPullRequestList(baselineTargets);
535 const restoredPartition = (involvement: PullRequestInvolvement) =>
536 restoredPullRequestList(
537 baselineTargets.map((target) => ({ ...target, input: { ...target.input, involvement } })),
538 )?.entries;
539 const authored = partitionsWanted ? restoredPartition("authored") : undefined;
540 const reviewing = partitionsWanted ? restoredPartition("reviewing") : undefined;
541 setLoaded(
542 restored === null
543 ? null
544 : {
545 environmentKey,
546 scope: scopeKey,
547 query: "",
548 source: null,
549 data: restored,
550 ...(authored === undefined || reviewing === undefined
551 ? {}
552 : { partitions: { authored, reviewing } }),
553 },
554 );
555 }
556 }
557 const settledList = listQuery.data !== null && !listQuery.isPending ? listQuery.data : null;
558 const answeredPartitions =
559 partitionsWanted && baselineEmpty
560 ? EMPTY_PARTITIONS
561 : partitionsWanted && authoredQuery.data !== null && reviewingQuery.data !== null
562 ? { authored: authoredQuery.data.entries, reviewing: reviewingQuery.data.entries }
563 : null;
564 const heldPartitions =
565 loaded !== null && loaded.environmentKey === environmentKey && loaded.scope === scopeKey
566 ? loaded.partitions
567 : undefined;
568 const nextPartitions = answeredPartitions ?? heldPartitions;
569 const loadedEntries =
570 settledList === null
571 ? null
572 : ordered?.key === filterKey
573 ? ordered.entries
574 : settledList.entries;
575 if (
576 settledList !== null &&
577 loadedEntries !== null &&
578 (loaded === null ||
579 loaded.source !== settledList ||
580 loaded.environmentKey !== environmentKey ||
581 loaded.scope !== scopeKey ||
582 loaded.query !== sentQuery ||
583 loaded.data.entries !== loadedEntries ||
584 loaded.partitions?.authored !== nextPartitions?.authored ||
585 loaded.partitions?.reviewing !== nextPartitions?.reviewing)
586 ) {
587 setLoaded({
588 environmentKey,
589 scope: scopeKey,
590 query: sentQuery,
591 source: settledList,
592 data: { ...settledList, entries: loadedEntries },
593 ...(nextPartitions === undefined ? {} : { partitions: nextPartitions }),
594 });
595 }
596 const narrowed = (() => {
597 if (loaded === null || loaded.environmentKey !== environmentKey || loaded.scope === scopeKey) {
598 return null;
599 }
600 const entries = narrowPullRequestsToFilters(loaded.data.entries, {
601 state: search.state,
602 projectId: scopedProjectId,
603 host: search.host,
604 });
605 return entries.length === 0 ? null : { ...loaded.data, entries };
606 })();
607 // A grown page is read by the list and nothing else: the baseline always asks for one page, so
608 // a host with no cursor to continue from — where "more" means asking for a longer page — would
609 // have its extra rows thrown away for the ninety-nine the baseline keeps answering with.
610 const answered =
611 (sentQuery.length === 0 && sentCursors === null && pageSize === PAGE_SIZE
612 ? baselineQuery.data
613 : listQuery.data) ??
614 (loaded?.scope === scopeKey && loaded.query === sentQuery ? loaded.data : null);
615 const carried =
616 (sentQuery.length === 0 ? baselineQuery.data : undefined) ??
617 (loaded?.scope === scopeKey ? loaded.data : null) ??
618 narrowed;
619 const listData = answered ?? carried;
620 const showingCarried = answered === null && carried !== null;
621 const loadingMore = listQuery.isPending && listData !== null;
622 const firstLoad = listQuery.isPending && listData === null;
623
624 if (
625 answered !== null &&
626 !listQuery.isPending &&
627 !(listQuery.error && listQuery.data === null) &&
628 (ordered === null || ordered.key !== filterKey || ordered.source !== answered)
629 ) {
630 if (ordered === null || ordered.key !== filterKey) {
631 setOrdered({
632 key: filterKey,
633 source: answered,
634 entries: rankPullRequestMatches(answered.entries, sentParsed.text),
635 });
636 } else if (sentCursors !== null) {
637 const held = new Set(ordered.entries.map(pullRequestEntryKey));
638 const arrived = answered.entries.filter((entry) => !held.has(pullRequestEntryKey(entry)));
639 const appended = rankPullRequestMatches(
640 arrived.toSorted(comparePullRequestsByRecency),
641 sentParsed.text,
642 );
643 setOrdered({ key: filterKey, source: answered, entries: [...ordered.entries, ...appended] });
644 } else {
645 setOrdered({
646 key: filterKey,
647 source: answered,
648 entries: reusePullRequestEntries(
649 ordered.entries,
650 rankPullRequestMatches(answered.entries, sentParsed.text),
651 pullRequestEntryKey,
652 ),
653 });
654 }
655 const answeredEntries = answered.entries;
656 setOverrides((current) =>
657 settlePullRequestOverrides(current, answeredEntries, pullRequestEntryKey, Date.now()),
658 );
659 }
660
661 // From this question's own answer, never from the rows being held while it travels: a
662 // continuation is a boundary in one listing, and carrying one across a search would ask the new
663 // question to start where the old one stopped — skipping its newest matches entirely.
664 const nextCursors = answered?.nextCursors ?? {};
665 const regrown = (answered?.truncatedEnvironments ?? []).filter(
666 (environmentId) => nextCursors[environmentId] === undefined,
667 );
668 const canContinue = !showingCarried && Object.keys(nextCursors).length > 0;
669 const loadMore = () => {
670 if (canContinue) {
671 setPage({
672 key: filterKey,
673 size: regrown.length === 0 ? pageSize : Math.min(pageSize + PAGE_SIZE, MAX_PAGE_SIZE),
674 cursors: nextCursors,
675 regrown,
676 turn: turnRefreshToken,
677 });
678 return;
679 }
680 setPage({
681 key: filterKey,
682 size: Math.min(pageSize + PAGE_SIZE, MAX_PAGE_SIZE),
683 cursors: null,
684 regrown: [],
685 turn: turnRefreshToken,
686 });
687 };
688
689 const collapsedPage = () => {
690 const loadedCount =
691 ordered?.key === filterKey ? largestPullRequestReadCount(ordered.entries) : pageSize;
692 return {
693 key: filterKey,
694 regrown: [],
695 size: Math.min(
696 Math.max(pageSize, Math.ceil(loadedCount / PAGE_SIZE) * PAGE_SIZE),
697 MAX_PAGE_SIZE,
698 ),
699 cursors: null,
700 turn: turnRefreshToken,
701 };
702 };
703 // Every list read refetches itself when a turn completes, but a continuation would refetch only
704 // its later page and strand the rows before it, so the whole loaded list is asked for again.
705 if (sentCursors !== null && page.turn !== turnRefreshToken) setPage(collapsedPage());
706
707 const refreshList = (includeRelated = false, actedEnvironmentId?: EnvironmentId) => {
708 const related = (
709 includeRelated
710 ? [
711 ...baselineTargets,
712 ...facetTargets,
713 ...partitionTargets.authored,
714 ...partitionTargets.reviewing,
715 ]
716 : []
717 ).filter(
718 ({ environmentId }) =>
719 actedEnvironmentId === undefined || environmentId === actedEnvironmentId,
720 );
721 if (sentCursors === null) {
722 listQuery.refresh([
723 ...listTargets.filter(
724 ({ environmentId }) =>
725 actedEnvironmentId === undefined || environmentId === actedEnvironmentId,
726 ),
727 ...related,
728 ]);
729 return;
730 }
731 if (related.length > 0) listQuery.refresh(related);
732 setPage(collapsedPage());
733 };
734
735 useLiveRefresh(
736 () => {
737 refreshList(true);
738 },
739 { enabled: pullRequestsSupported },
740 );
741
742 const viewers = baselineQuery.data?.viewers ?? listData?.viewers ?? EMPTY_VIEWERS;
743 const listErrors = baselineQuery.data?.errors ?? listData?.errors ?? [];
744 const facets = collectPullRequestListFacets(
745 [
746 ...(facetQuery.data?.entries ?? []),
747 ...(baselineQuery.data?.entries ?? listData?.entries ?? []),
748 ],
749 search.state,
750 );
751
752 const heldEntries = ordered?.key === filterKey ? ordered.entries : (listData?.entries ?? []);
753 const overlayInput = { state: search.state, filters };
754 const shownEntries = usePendingListEntries(overlayInput, heldEntries);
755 const shownBaseline = usePendingListEntries(
756 overlayInput,
757 typedParsed.filters.checks === undefined ? baselineQuery.data?.entries : undefined,
758 );
759 const shownAuthored = usePendingListEntries(
760 overlayInput,
761 partitionsWanted ? authoredQuery.data?.entries : undefined,
762 );
763 const shownReviewing = usePendingListEntries(
764 overlayInput,
765 partitionsWanted ? reviewingQuery.data?.entries : undefined,
766 );
767 const shownHeldAuthored = usePendingListEntries(overlayInput, heldPartitions?.authored);
768 const shownHeldReviewing = usePendingListEntries(overlayInput, heldPartitions?.reviewing);
769 const scrollRef = useRef<HTMLDivElement>(null);
770 const {
771 entries,
772 listedPullRequestTabStatuses,
773 groups,
774 entriesByStatsKey,
775 heldPullRequestsBySurface,
776 } = pullRequestGroups({
777 known: shownEntries,
778 // The baseline was read without typed qualifiers, and rows cannot be checked for `checks:`.
779 baseline:
780 typedParsed.filters.checks === undefined && baselineQuery.data !== null
781 ? shownBaseline
782 : undefined,
783 providers: baselineQuery.data?.providers ?? listData?.providers ?? [],
784 viewers,
785 involvement: search.involvement,
786 localFilters,
787 hasLocalFilters,
788 text: typedParsed.text,
789 answeredLocally: querySettled && !showingCarried,
790 baselineEmpty,
791 held:
792 heldPartitions === undefined
793 ? undefined
794 : {
795 authored: shownHeldAuthored,
796 reviewing: shownHeldReviewing,
797 },
798 authored: partitionsWanted && authoredQuery.data !== null ? shownAuthored : undefined,
799 reviewing: partitionsWanted && reviewingQuery.data !== null ? shownReviewing : undefined,
800 partitionsWanted,
801 });
802
803 const visibleStatsKeys = useRef({ key: filterKey, values: new Set<string>() });
804 const [statsByRow, setStatsByRow] = useState<PullRequestDiffStats>(() => new Map());
805 if (
806 panelEnvironmentId !== null &&
807 panelSummary?.additions !== undefined &&
808 panelSummary.deletions !== undefined
809 ) {
810 const stat = {
811 ...panelSummary,
812 environmentId: panelEnvironmentId,
813 additions: panelSummary.additions,
814 deletions: panelSummary.deletions,
815 };
816 const previous = statsByRow.get(pullRequestDiffStatKey(stat));
817 if (previous?.additions !== stat.additions || previous.deletions !== stat.deletions) {
818 setStatsByRow(mergePullRequestDiffStats(statsByRow, [stat]));
819 }
820 }
821 const [statsTargetState, setStatsTargetState] = useState<{
822 readonly key: string;
823 readonly batches: ReadonlyArray<PullRequestStatsBatch>;
824 }>({ key: filterKey, batches: [] });
825 const statsBatches = statsTargetState.key === filterKey ? statsTargetState.batches : [];
826 const statsTargets = statsBatches.map(({ environmentId, input }) => ({
827 environmentId,
828 input,
829 }));
830 const statsQuery = usePullRequestListStats(statsTargets);
831 const statsObserver = useRef<IntersectionObserver | null>(null);
832 const statsRows = useRef(new Set<HTMLDivElement>());
833 // Called from a row's ref cleanup, which keeps the render it attached in; this reads the latest.
834 const releaseStatsRow = useStableCallback((key: string | undefined) => {
835 const visible = visibleStatsKeys.current;
836 if (
837 statsPolicy !== "visible" ||
838 key === undefined ||
839 !visible.values.delete(key) ||
840 statsQuery.isPending
841 ) {
842 return;
843 }
844 setStatsTargetState((current) => {
845 if (current.key !== visible.key) return current;
846 const batches = retainVisiblePullRequestStatsBatches(current.batches, visible.values);
847 return batches.length === current.batches.length ? current : { key: current.key, batches };
848 });
849 });
850 // Every row takes this as its ref, so a new identity would detach and reattach them all.
851 const registerStatsRow = useStableCallback((node: HTMLDivElement | null) => {
852 if (node === null || typeof IntersectionObserver === "undefined") return;
853 statsRows.current.add(node);
854 statsObserver.current?.observe(node);
855 return () => {
856 statsRows.current.delete(node);
857 statsObserver.current?.unobserve(node);
858 releaseStatsRow(node.dataset.pullRequestStatsKey);
859 };
860 });
861 // Arriving stats must not re-run the effects that ask for them.
862 const readStatsProgress = useEffectEvent(() => ({
863 statsByRow,
864 pending: statsQuery.isPending,
865 }));
866 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- queues eager stats batches for the rows, reading known stats and visible keys held outside render
867 useEffect(() => {
868 if (statsPolicy !== "eager") return;
869 const { statsByRow: known } = readStatsProgress();
870 const candidateKeys = visibleStatsKeys.current.values;
871 setStatsTargetState((current) => {
872 const batches = current.key === filterKey ? current.batches : [];
873 const added = pullRequestStatsRequestBatches({
874 entriesByKey: entriesByStatsKey,
875 candidateKeys,
876 policy: statsPolicy,
877 activeBatches: batches,
878 statsByRow: known,
879 });
880 if (added.length === 0 && current.key === filterKey) return current;
881 return { key: filterKey, batches: [...batches, ...added] };
882 });
883 }, [filterKey, entriesByStatsKey, statsPolicy]);
884 // The observer outlives the rows it watches, so it reads the rows held at the time it fires.
885 const readStatsRows = useEffectEvent(() => entriesByStatsKey);
886 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- IntersectionObserver on rows requests stats for rows that scroll into view
887 useEffect(() => {
888 if (statsPolicy !== "visible" || typeof IntersectionObserver === "undefined") return;
889 visibleStatsKeys.current = { key: filterKey, values: new Set() };
890 const observer = new IntersectionObserver(
891 (observed) => {
892 const visible = visibleStatsKeys.current;
893 if (visible.key !== filterKey) return;
894 let changed = false;
895 const entered = new Set<string>();
896 const entriesByKey = readStatsRows();
897 for (const item of observed) {
898 const key = (item.target as HTMLElement).dataset.pullRequestStatsKey;
899 if (key === undefined) continue;
900 const wasVisible = visible.values.has(key);
901 if (item.isIntersecting && entriesByKey.has(key)) {
902 visible.values.add(key);
903 if (!wasVisible) entered.add(key);
904 } else {
905 visible.values.delete(key);
906 }
907 if (wasVisible !== visible.values.has(key)) changed = true;
908 }
909 if (!changed) return;
910 const progress = readStatsProgress();
911 setStatsTargetState((current) => {
912 const batches = current.key === filterKey ? current.batches : [];
913 const retained = progress.pending
914 ? batches
915 : retainVisiblePullRequestStatsBatches(batches, visible.values);
916 const added = pullRequestStatsRequestBatches({
917 entriesByKey,
918 candidateKeys: entered,
919 policy: statsPolicy,
920 activeBatches: batches,
921 statsByRow: progress.statsByRow,
922 });
923 if (added.length === 0 && retained.length === batches.length) return current;
924 return { key: filterKey, batches: [...retained, ...added] };
925 });
926 },
927 { root: scrollRef.current, rootMargin: "480px" },
928 );
929 statsObserver.current = observer;
930 for (const row of statsRows.current) observer.observe(row);
931 return () => {
932 observer.disconnect();
933 if (statsObserver.current === observer) statsObserver.current = null;
934 };
935 }, [filterKey, statsPolicy]);
936 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- prunes stats batches to the observer's visible rows once a stats request settles
937 useEffect(() => {
938 if (statsPolicy !== "visible" || statsQuery.isPending) return;
939 const visible = visibleStatsKeys.current;
940 setStatsTargetState((current) => {
941 if (current.key !== filterKey || visible.key !== filterKey) return current;
942 const batches = retainVisiblePullRequestStatsBatches(current.batches, visible.values);
943 return batches.length === current.batches.length ? current : { key: current.key, batches };
944 });
945 }, [filterKey, statsPolicy, statsQuery.isPending]);
946 const [mergedStats, setMergedStats] = useState<typeof statsQuery.stats>(null);
947 if (statsQuery.stats !== null && statsQuery.stats !== mergedStats) {
948 const stats = statsQuery.stats;
949 setMergedStats(stats);
950 setStatsByRow((previous) => mergePullRequestDiffStats(previous, stats));
951 }
952 // Stable so a refresh that resumes after awaiting the host compares against the scope on screen
953 // by then, not the one it started from.
954 const refreshListAndStats = useStableCallback(
955 (
956 requestedStatsScope: PullRequestStatsScope = statsScope,
957 actedEnvironmentId?: EnvironmentId,
958 ) => {
959 refreshList(true, actedEnvironmentId);
960 const visible = visibleStatsKeys.current;
961 const batches = pullRequestStatsRefreshBatches({
962 requestedScope: requestedStatsScope,
963 currentScope: statsScope,
964 entriesByKey: entriesByStatsKey,
965 candidateKeys: visible.key === requestedStatsScope.key ? visible.values : new Set(),
966 statsByRow,
967 });
968 if (batches !== null) {
969 setStatsTargetState({ key: requestedStatsScope.key, batches });
970 statsQuery.refresh(
971 batches
972 .filter(({ environmentId }) =>
973 actedEnvironmentId === undefined ? true : environmentId === actedEnvironmentId,
974 )
975 .map(({ environmentId, input }) => ({ environmentId, input })),
976 );
977 }
978 },
979 );
980 const refreshFromHost = async () => {
981 const requestedStatsScope = statsScope;
982 setInvalidating(true);
983 // Atom commands settle into results rather than throwing.
984 await Promise.all(
985 queryEnvironmentIds.map((environmentId) => invalidate({ environmentId, input: {} })),
986 );
987 listQuery.refresh([
988 ...listTargetsFor(preferredEnvironmentQueries),
989 ...baselineTargetsFor(preferredEnvironmentQueries),
990 ]);
991 setHostReads(resetPullRequestHosts);
992 setInvalidating(false);
993 refreshListAndStats(requestedStatsScope);
994 setDetailRefreshToken((token) => token + 1);
995 };
996 const {
997 hosts,
998 displayGroups,
999 shownCount,
1000 hostActionsOf,
1001 closeSweepRows,
1002 listedPullRequestsBySurface,
1003 } = usePullRequestDisplayGroups({
1004 answered,
1005 host: search.host,
1006 groups,
1007 statsByRow,
1008 overrides,
1009 state: search.state,
1010 localFilters,
1011 hasLocalFilters,
1012 viewers,
1013 sort,
1014 text: typedParsed.text,
1015 involvement: search.involvement,
1016 });
1017 const showProvider = hosts.length > 1;
1018 const [closeSweepKeys, setCloseSweepKeys] = useState<ReadonlySet<string>>(() => new Set());
1019 const closeSensorRef = useRef<SidebarPointerSensor | null>(null);
1020 // A sweep spans many renders; each step reads the rows on screen at that moment.
1021 const readCloseSweep = useStableCallback(() => ({
1022 displayGroups,
1023 closeSweepRows,
1024 closingKeys,
1025 closeBatch,
1026 hostActionsOf,
1027 }));
1028 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels the pointer close-sweep sensor when the list changes or on unmount
1029 useEffect(
1030 () => () => closeSensorRef.current?.cancel(),
1031 // 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.
1032 [filterKey, search.q, sort],
1033 );
1034 const startCloseSweep = useStableCallback(
1035 (entry: EnvironmentPullRequestEntry, event: PointerEvent) => {
1036 closeSensorRef.current?.cancel();
1037 const originKey = pullRequestEntryKey(entry);
1038 const group = readCloseSweep().displayGroups.find((candidate) =>
1039 candidate.entries.some((row) => pullRequestEntryKey(row) === originKey),
1040 );
1041 if (!group || readCloseSweep().closingKeys.has(originKey)) return;
1042 const orderedKeys = readCloseSweep().displayGroups.flatMap((candidate) =>
1043 candidate.entries.map(pullRequestEntryKey),
1044 );
1045 const canClose = (key: string) => {
1046 const row = readCloseSweep().closeSweepRows.get(key);
1047 return (
1048 row?.groupKey === group.key &&
1049 row.entry.state === "open" &&
1050 readCloseSweep().hostActionsOf(row.entry).has("close") &&
1051 !readCloseSweep().closingKeys.has(key) &&
1052 !scrollRef.current?.querySelector(
1053 `[data-pull-request-key="${CSS.escape(key)}"] [data-pull-request-action-pending="true"]`,
1054 )
1055 );
1056 };
1057 let sweptKeys: string[] = [];
1058 let targetKey: string | null = null;
1059 const sweepTo = (key: string) => {
1060 if (key === targetKey) return;
1061 targetKey = key;
1062 sweptKeys = resolveSidebarSweepKeys(orderedKeys, originKey, key, canClose);
1063 setCloseSweepKeys(new Set(sweptKeys));
1064 };
1065 // Only while a sweep runs: Escape ends it, ahead of any other scope that would also take it.
1066 const releaseEscape = registerCommands(
1067 {},
1068 {
1069 capture: true,
1070 onKeyDown: (keyEvent) => {
1071 if (keyEvent.key !== "Escape") return false;
1072 keyEvent.preventDefault();
1073 sensor.cancel();
1074 },
1075 },
1076 );
1077 const sensor = new SidebarPointerSensor({
1078 active: originKey,
1079 event,
1080 options: {
1081 distance: 6,
1082 onAttach: () => {},
1083 onFinish: () => {
1084 releaseEscape();
1085 if (closeSensorRef.current === sensor) closeSensorRef.current = null;
1086 setCloseSweepKeys(new Set());
1087 },
1088 },
1089 onPending: () => {},
1090 onStart: () => sweepTo(originKey),
1091 onMove: ({ y }) => {
1092 const viewport = scrollRef.current;
1093 if (!viewport) return;
1094 const bounds = viewport.getBoundingClientRect();
1095 const visibleY = Math.min(Math.max(y, bounds.top), bounds.bottom - 1);
1096 let key: string | null = null;
1097 for (const row of viewport.querySelectorAll<HTMLElement>("[data-pull-request-key]")) {
1098 if (key !== null && row.getBoundingClientRect().top > visibleY) break;
1099 key = row.dataset.pullRequestKey ?? null;
1100 }
1101 if (key !== null) sweepTo(key);
1102 },
1103 onEnd: () => {
1104 const batch = sweptKeys.filter(canClose).flatMap((key) => {
1105 const row = readCloseSweep().closeSweepRows.get(key);
1106 return row ? [row.entry] : [];
1107 });
1108 void readCloseSweep().closeBatch(batch);
1109 },
1110 onCancel: () => {},
1111 onAbort: () => {},
1112 });
1113 closeSensorRef.current = sensor;
1114 },
1115 );
1116 const rightPanelAvailable = selectedPullRequestSurface !== null;
1117 const mobileSidebarSheetMounted = useMobileSidebarSheetMounted();
1118 const [maximized, setMaximized] = useState(false);
1119 const rightPanelMaximized = rightPanelState.isOpen && maximized;
1120 if (!rightPanelState.isOpen && maximized) setMaximized(false);
1121 const toggleRightPanelMaximized = () => {
1122 if (rightPanelState.isOpen) setMaximized((value) => !value);
1123 };
1124 const onGuideShown = () => setMaximized(true);
1125 // updateSearch leaves selectedUrl out, so a reload does not reveal the link again.
1126 const consumeLinkedUrl = useEffectEvent(() => updateSearch({}));
1127 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens the URL-linked pull request in the right panel store
1128 useEffect(() => {
1129 if (!pullRequestsSupported || rightPanelRef === null || linkedSelection === null) return;
1130 useRightPanelStore.getState().openPullRequest(rightPanelRef, linkedSelection);
1131 if (linkedSelection.revealUrl !== undefined) consumeLinkedUrl();
1132 }, [linkedSelection, pullRequestsSupported, rightPanelRef]);
1133
1134 const selected =
1135 rightPanelState.isOpen && activePullRequestSurface !== null
1136 ? {
1137 environmentId: activePullRequestSurface.environmentId,
1138 repository: activePullRequestSurface.repository,
1139 number: activePullRequestSurface.number,
1140 projectId: activePullRequestSurface.projectId as ProjectId,
1141 host:
1142 activePullRequestSurface.host ??
1143 (selectedProject?.repositoryIdentity
1144 ? sourceControlClients.changeRequestHost(
1145 selectedProject.repositoryIdentity,
1146 selectedProject.repositoryIdentity.provider,
1147 )
1148 : undefined),
1149 }
1150 : null;
1151
1152 const selectSurfaceInUrl = (surface: PullRequestSurface | null) =>
1153 updateSearch(
1154 surface === null
1155 ? clearedSelection
1156 : {
1157 repository: surface.repository,
1158 number: surface.number,
1159 selectedProjectId: surface.projectId as ProjectId,
1160 selectedHost: surface.host,
1161 ...(surface.environmentId === undefined
1162 ? {}
1163 : { selectedEnvironmentId: surface.environmentId as EnvironmentId }),
1164 },
1165 );
1166
1167 const toggleRightPanel = () => {
1168 if (rightPanelRef === null) return;
1169 if (rightPanelState.isOpen) {
1170 useRightPanelStore.getState().close(rightPanelRef);
1171 updateSearch(clearedSelection);
1172 return;
1173 }
1174 if (selectedPullRequestSurface === null) return;
1175 useRightPanelStore.getState().show(rightPanelRef);
1176 selectSurfaceInUrl(selectedPullRequestSurface);
1177 };
1178
1179 const unavailableProjects = new Map(
1180 listErrors.map(
1181 (error) =>
1182 [
1183 pullRequestProjectKey({ id: error.projectId, environmentId: error.environmentId }),
1184 error.message,
1185 ] as const,
1186 ),
1187 );
1188
1189 const prefetchEntry = usePullRequestIntentPrefetch((entry) =>
1190 listedPullRequestsBySurface.has(pullRequestListEntryId(entry)),
1191 );
1192 const selectEntry = (entry: PullRequestRowTarget) => {
1193 if (rightPanelRef === null) return;
1194 useRightPanelStore.getState().openPullRequest(rightPanelRef, entry);
1195 updateSearch({
1196 repository: entry.repository,
1197 number: entry.number,
1198 selectedProjectId: entry.projectId,
1199 selectedEnvironmentId: entry.environmentId,
1200 selectedHost: entry.host,
1201 });
1202 };
1203
1204 const searchInput = (
1205 <PullRequestSearchInput
1206 value={search.q ?? ""}
1207 label={gt("Search pull requests")}
1208 placeholder={gt("Search pull requests, or label:bug")}
1209 busy={typedQuery.length > 0 && (!querySettled || showingCarried)}
1210 onChange={(query) => updateListScope({ q: query || undefined })}
1211 onSubmit={submitQuery}
1212 />
1213 );
1214 const panelToggleControls = (
1215 <PanelLayoutControls
1216 showTerminalControl={false}
1217 showThreadPanelControl={false}
1218 terminalAvailable={false}
1219 terminalOpen={false}
1220 terminalShortcutLabel={null}
1221 threadPanelOpen={false}
1222 threadPanelPresentation="inline"
1223 threadPanelShortcutLabel={null}
1224 onToggleThreadPanel={() => undefined}
1225 rightPanelAvailable={rightPanelAvailable}
1226 rightPanelOpen={rightPanelState.isOpen}
1227 rightPanelShortcutLabel={shortcutLabelForCommand(keybindings, "rightPanel.toggle")}
1228 rightPanelUnavailableLabel={gt("Select a pull request first")}
1229 onToggleTerminal={() => undefined}
1230 onToggleRightPanel={toggleRightPanel}
1231 />
1232 );
1233 const openPanelControls = (
1234 <div
1235 className={cn(
1236 "absolute top-[var(--workspace-controls-top)] right-[var(--workspace-controls-right)] z-50 mr-px flex h-[var(--workspace-topbar-height)] items-center gap-1 [-webkit-app-region:no-drag]",
1237 mobileSidebarSheetMounted && "hidden",
1238 )}
1239 data-workspace-titlebar-controls
1240 >
1241 {rightPanelState.isOpen ? (
1242 <RightPanelMaximizeControl
1243 maximized={rightPanelMaximized}
1244 onToggle={toggleRightPanelMaximized}
1245 />
1246 ) : null}
1247 {panelToggleControls}
1248 </div>
1249 );
1250 const listError = listQuery.error
1251 ? `${environmentLabels.get(listQuery.error.environmentId) || gt("Environment")}: ${listQuery.error.message}`
1252 : null;
1253 const carriedToNothing =
1254 shownCount === 0 &&
1255 typedQuery.length === 0 &&
1256 (!querySettled || (showingCarried && listQuery.isPending));
1257 const listBody = (
1258 <>
1259 {!capabilityKnown ? (
1260 <PullRequestListGhost rows={7} caption={gt("Loading pull requests…")} />
1261 ) : !pullRequestsSupported ? (
1262 <PullRequestsUnavailableState
1263 title={gt("Pull requests unavailable")}
1264 error={gt("Update your T3 Code servers to browse pull requests.")}
1265 />
1266 ) : firstLoad ? (
1267 <PullRequestListGhost rows={7} caption={gt("Loading pull requests…")} />
1268 ) : listError && shownCount === 0 ? (
1269 <PullRequestsUnavailableState
1270 error={listError}
1271 refreshing={listQuery.isPending}
1272 onRetry={listQuery.retry}
1273 />
1274 ) : carriedToNothing ? (
1275 <PullRequestListGhost rows={7} />
1276 ) : shownCount === 0 ? (
1277 <PullRequestListEmptyState
1278 hasProjects={!projectsKnown || projects.length > 0}
1279 refreshing={refreshing}
1280 onRefresh={() => void refreshFromHost()}
1281 query={typedQuery}
1282 filtered={
1283 menuFiltered ||
1284 search.state !== "open" ||
1285 search.involvement !== "all" ||
1286 scopedProjectId !== undefined ||
1287 search.host !== undefined
1288 }
1289 searching={typedQuery.length > 0 && (!querySettled || showingCarried)}
1290 canLoadMore={listData?.truncated === true && (canContinue || pageSize < MAX_PAGE_SIZE)}
1291 loadingMore={loadingMore}
1292 onClearQuery={() => updateListScope({ q: undefined })}
1293 onLoadMore={loadMore}
1294 />
1295 ) : (
1296 <PullRequestListGroups
1297 groups={displayGroups}
1298 environmentLabels={capableEnvironments.length > 1 ? environmentLabels : null}
1299 query={typedParsed.text}
1300 selected={selected}
1301 showProvider={showProvider}
1302 statsRef={registerStatsRow}
1303 onSelect={selectEntry}
1304 onIntent={prefetchEntry}
1305 hostActionsOf={hostActionsOf}
1306 onActed={onSpeedAction}
1307 closingKeys={closingKeys}
1308 sweepingKeys={closeSweepKeys}
1309 onCloseSweepStart={startCloseSweep}
1310 />
1311 )}
1312
1313 {listError && shownCount > 0 ? (
1314 <div className="flex items-center justify-between gap-3 rounded-lg border border-warning/30 bg-warning-surface px-3 py-2 text-xs">
1315 <span>{gt("{error} Showing the last pull requests loaded.", { error: listError })}</span>
1316 <Button size="xs" variant="outline" onClick={listQuery.retry}>
1317 <T>Retry</T>
1318 </Button>
1319 </div>
1320 ) : null}
1321 {listData?.truncated && entries.length > 0 ? (
1322 <div className="flex justify-center py-3 text-xs text-muted-foreground">
1323 {loadingMore ? (
1324 <span className="flex items-center gap-2">
1325 <Spinner aria-hidden size="sm" />
1326 {sentCursors === null ? gt("Updating pull requests") : gt("Loading more")}
1327 </span>
1328 ) : canContinue || pageSize < MAX_PAGE_SIZE ? (
1329 <Button
1330 size="sm"
1331 variant="outline"
1332 onClick={loadMore}
1333 disabled={listQuery.isPending || showingCarried}
1334 >
1335 <T>Load more pull requests</T>
1336 </Button>
1337 ) : (
1338 <span>
1339 <T>Narrow your search to find more pull requests.</T>
1340 </span>
1341 )}
1342 </div>
1343 ) : null}
1344 </>
1345 );
1346 const hostEntries = hosts.length > 0 ? hosts : expectedHosts;
1347 const hostMenuOptions: ReadonlyArray<PullRequestFilterOption<string>> = [
1348 { value: "", label: gt("All", { $context: "all hosts" }), Icon: Plug2Icon },
1349 ...hostEntries.map((entry) => {
1350 const summary = hosts.find((host) => host.host === entry.host);
1351 return {
1352 value: entry.host,
1353 label: pullRequestHostLabel(hostEntries, entry),
1354 Icon: getSourceControlPresentationForKind(entry.kind).Icon,
1355 ...(summary === undefined || summary.configured
1356 ? {}
1357 : { unavailable: summary.detail ?? gt("This host could not be read.") }),
1358 };
1359 }),
1360 ];
1361 const serverMenuOptions: ReadonlyArray<PullRequestFilterOption<string>> = [
1362 { value: "", label: gt("All servers"), Icon: LayersIcon },
1363 ...capableEnvironments.map((environment) => ({
1364 value: environment.environmentId,
1365 label: environment.label,
1366 Icon: environmentMachineIcon(resolveEnvironmentMachineKind(environment.serverConfig)),
1367 })),
1368 ];
1369 const sortMenu = (
1370 <PullRequestCompactFilterMenu
1371 label={gt("Sort pull requests")}
1372 triggerIcon={<ArrowDownUpIcon aria-hidden className="size-4" />}
1373 triggerLabel={gt("Sort", { $context: "verb, sort a list" })}
1374 outlined
1375 value={sort}
1376 options={resolveFilterOptions(SORT_OPTIONS, resolve)}
1377 onChange={(next) => updateListScope({ sort: next })}
1378 />
1379 );
1380 const filtersMenu = (
1381 <PullRequestFiltersMenuInSidebarOrder
1382 onOpenChange={setFiltersOpen}
1383 state={search.state}
1384 stateOptions={resolveFilterOptions(STATE_TABS, resolve)}
1385 onState={(state) => updateListScope({ state })}
1386 involvement={search.involvement}
1387 involvementOptions={resolveFilterOptions(INVOLVEMENT_TABS, resolve)}
1388 onInvolvement={(involvement) => updateListScope({ involvement })}
1389 filters={
1390 typedParsed.filters.draft
1391 ? { ...menuFilters, draft: typedParsed.filters.draft }
1392 : menuFilters
1393 }
1394 onFilters={(value) => {
1395 const { query, filters: next } = applyPullRequestDraftFilterChange(
1396 typedQuery,
1397 menuFilters,
1398 value,
1399 );
1400 updateListScope({
1401 ...(query === typedQuery ? {} : { q: query || undefined }),
1402 draft: next.draft,
1403 review: next.review,
1404 checks: next.checks,
1405 author: next.author,
1406 labels: next.labels?.flatMap((group) => group),
1407 });
1408 }}
1409 authorOptions={facets.authors}
1410 labelOptions={facets.labels}
1411 optionScope={filterOptionScope}
1412 host={search.host}
1413 hostOptions={hostMenuOptions}
1414 onHost={(host) => updateListScope({ host })}
1415 server={scopedEnvironmentId ?? undefined}
1416 serverOptions={serverMenuOptions}
1417 onServer={(server) => updateListScope({ environmentId: server, projectId: undefined })}
1418 projects={scopedProjects}
1419 projectId={scopedProjectId}
1420 projectEnvironmentId={scopedProject?.environmentId}
1421 unavailable={unavailableProjects}
1422 onProject={(projectId, environmentId) =>
1423 updateListScope(environmentId === undefined ? { projectId } : { projectId, environmentId })
1424 }
1425 />
1426 );
1427 const columnProps = {
1428 refreshing,
1429 onRefresh: () => void refreshFromHost(),
1430 searchValue: search.q ?? "",
1431 involvement: search.involvement,
1432 state: search.state,
1433 host: search.host,
1434 hostMenuOptions,
1435 onInvolvement: (involvement: PullRequestInvolvement) => updateListScope({ involvement }),
1436 onState: (state: PullRequestListState) => updateListScope({ state }),
1437 onHost: (host: string | undefined) => updateListScope({ host }),
1438 searchInput,
1439 sortMenu,
1440 filtersMenu,
1441 savedViewsMenu: (
1442 <SavedViewsMenu
1443 kind={PULL_REQUEST_SAVED_VIEWS}
1444 preferences={search}
1445 onApply={(preferences) => updateListScope(pullRequestSavedViewPatch(preferences))}
1446 />
1447 ),
1448 rightPanelControl: !pullRequestsSupported ? null : (
1449 <span
1450 aria-hidden
1451 className={cn(
1452 "shrink-0",
1453 rightPanelState.isOpen ? "-ml-3 w-0" : "w-7 sm:w-5",
1454 panelAnimationsActive && "transition-[width,margin] ease-out",
1455 )}
1456 style={
1457 panelAnimationsActive
1458 ? { transitionDuration: `${panelAnimationDurationMs}ms` }
1459 : undefined
1460 }
1461 />
1462 ),
1463 titlebarControls:
1464 // While the panel is closed the strip lives inside the header: a no-drag
1465 // descendant beats the header's desktop drag-region, where a floating
1466 // sibling loses (app-region hit-testing ignores z-index).
1467 pullRequestsSupported ? (
1468 rightPanelPresent ? (
1469 <span
1470 aria-hidden
1471 className="pointer-events-none absolute inset-y-0 left-full w-7 [-webkit-app-region:no-drag]"
1472 />
1473 ) : (
1474 openPanelControls
1475 )
1476 ) : null,
1477 rightPanelOpen: rightPanelState.isOpen,
1478 maximizedAway: rightPanelMaximized,
1479 listBody,
1480 scrollRef,
1481 };
1482
1483 const activateSurface = (surface: PullRequestSurface) => {
1484 if (rightPanelRef === null) return;
1485 useRightPanelStore.getState().activateSurface(rightPanelRef, surface.id);
1486 selectSurfaceInUrl(surface);
1487 };
1488 const closeSurface = (surface: PullRequestSurface) => {
1489 if (rightPanelRef === null) return;
1490 useRightPanelStore.getState().closeSurface(rightPanelRef, surface.id);
1491 const next = selectActiveRightPanelSurface(
1492 useRightPanelStore.getState().byThreadKey,
1493 rightPanelRef,
1494 );
1495 selectSurfaceInUrl(next?.kind === "pull-request" ? next : null);
1496 };
1497 const closeOtherSurfaces = (surface: PullRequestSurface) => {
1498 if (rightPanelRef === null) return;
1499 useRightPanelStore.getState().closeOtherSurfaces(rightPanelRef, surface.id);
1500 selectSurfaceInUrl(surface);
1501 };
1502 const closeSurfacesToRight = (surface: PullRequestSurface) => {
1503 if (rightPanelRef === null) return;
1504 useRightPanelStore.getState().closeSurfacesToRight(rightPanelRef, surface.id);
1505 const next = selectActiveRightPanelSurface(
1506 useRightPanelStore.getState().byThreadKey,
1507 rightPanelRef,
1508 );
1509 selectSurfaceInUrl(next?.kind === "pull-request" ? next : null);
1510 };
1511 const closeAllSurfaces = () => {
1512 if (rightPanelRef === null) return;
1513 useRightPanelStore.getState().closeAllSurfaces(rightPanelRef);
1514 selectSurfaceInUrl(null);
1515 };
1516
1517 const copyPullRequestFromShortcut = useEffectEvent((event: KeyboardEvent) => {
1518 if (!openPanelPullRequestUrl) return;
1519 event.preventDefault();
1520 event.stopPropagation();
1521 if (event.repeat) return;
1522 const url = openPanelPullRequestUrl;
1523 const terminology = (
1524 sourceControlClients.findByChangeRequestUrl(url) ?? sourceControlClients.get(undefined)
1525 ).changeRequest;
1526 void writeTextToClipboard(url, {
1527 target: `${terminology.singular} link`,
1528 unavailableMessage: msg(
1529 "Clipboard API is unavailable while copying {term, select, mr {merge request} cr {change request} other {pull request}} link.",
1530 { term: changeRequestTermKind(terminology) },
1531 ),
1532 failureMessage: msg(
1533 "Failed to copy {term, select, mr {merge request} cr {change request} other {pull request}} link to the clipboard.",
1534 { term: changeRequestTermKind(terminology) },
1535 ),
1536 }).then(undefined, (error) => {
1537 toastManager.add({
1538 type: "error",
1539 title: m(
1540 msg("Failed to copy {term, select, mr {MR} cr {change request} other {PR}} link", {
1541 term: changeRequestTermKind(terminology),
1542 }),
1543 ),
1544 description: thrownErrorMessage(error, m) ?? m(msg("An error occurred.")),
1545 });
1546 });
1547 });
1548 const closeActiveSurfaceFromShortcut = useEffectEvent((event: KeyboardEvent) => {
1549 if (activePullRequestSurface === null) return;
1550 event.preventDefault();
1551 event.stopPropagation();
1552 if (!event.repeat) closeSurface(activePullRequestSurface);
1553 });
1554 const toggleRightPanelFromShortcut = useEffectEvent((event: KeyboardEvent) => {
1555 if (!rightPanelAvailable) return;
1556 event.preventDefault();
1557 event.stopPropagation();
1558 if (!event.repeat) toggleRightPanel();
1559 });
1560 const toggleRightPanelMaximizedFromShortcut = useEffectEvent((event: KeyboardEvent) => {
1561 if (!rightPanelState.isOpen) return;
1562 event.preventDefault();
1563 event.stopPropagation();
1564 if (!event.repeat) toggleRightPanelMaximized();
1565 });
1566 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- document keydown listener for the right panel and copy-reference shortcuts
1567 useEffect(() => {
1568 const onKeyDown = (event: KeyboardEvent) => {
1569 if (event.defaultPrevented || isCommandPaletteOpen()) return;
1570 const command = resolveShortcutCommand(event, keybindings, {
1571 context: getShortcutContext(),
1572 });
1573 if (command === "rightPanel.close") closeActiveSurfaceFromShortcut(event);
1574 if (command === "rightPanel.toggle") toggleRightPanelFromShortcut(event);
1575 if (command === "rightPanel.toggleMaximized") toggleRightPanelMaximizedFromShortcut(event);
1576 if (command === "thread.copyReference") copyPullRequestFromShortcut(event);
1577 };
1578 document.addEventListener("keydown", onKeyDown);
1579 return () => document.removeEventListener("keydown", onKeyDown);
1580 }, [keybindings]);
1581
1582 return (
1583 <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none">
1584 <div className="relative flex min-h-0 flex-1">
1585 {pullRequestsSupported && rightPanelPresent ? openPanelControls : null}
1586 <PullRequestsColumn {...columnProps} />
1587
1588 {rightPanelPresent && renderedPullRequestSurface && panelEnvironmentId !== null ? (
1589 <RightPanelTabs
1590 mode="inline"
1591 open={rightPanelState.isOpen}
1592 maximized={rightPanelMaximized}
1593 keybindings={keybindings}
1594 getShortcutContext={getShortcutContext}
1595 widthStorageKey="t3code:pull-request-panel-width"
1596 defaultWidth={typeof window === "undefined" ? 640 : Math.floor(window.innerWidth / 2)}
1597 surfaces={renderedRightPanelSurfaces}
1598 environmentId={panelEnvironmentId}
1599 activeSurfaceId={renderedPullRequestSurface.id}
1600 pendingSurfaceIds={EMPTY_PENDING_SURFACES}
1601 previewSessions={EMPTY_PREVIEW_SESSIONS}
1602 desktopByTabId={EMPTY_PREVIEW_DESKTOP_STATE}
1603 terminalLabelsById={EMPTY_TERMINAL_LABELS}
1604 onActivate={(surface) => {
1605 if (surface.kind === "pull-request") activateSurface(surface);
1606 }}
1607 onCloseSurface={(surface) => {
1608 if (surface.kind === "pull-request") closeSurface(surface);
1609 }}
1610 onCloseOtherSurfaces={(surface) => {
1611 if (surface.kind === "pull-request") closeOtherSurfaces(surface);
1612 }}
1613 onCloseSurfacesToRight={(surface) => {
1614 if (surface.kind === "pull-request") closeSurfacesToRight(surface);
1615 }}
1616 onCloseAllSurfaces={closeAllSurfaces}
1617 onMoveSurface={(surfaceId, toIndex) => {
1618 if (rightPanelRef !== null)
1619 useRightPanelStore.getState().moveSurface(rightPanelRef, surfaceId, toIndex);
1620 }}
1621 onCopyFilePath={() => undefined}
1622 onAddBrowser={() => undefined}
1623 onAddBrowserInProfile={() => undefined}
1624 onAddTerminal={() => undefined}
1625 onAddDiff={() => undefined}
1626 onAddFiles={() => undefined}
1627 onAddPullRequest={() => undefined}
1628 onAddPullRequests={() => undefined}
1629 onAddDevice={() => undefined}
1630 browserAvailable={false}
1631 terminalAvailable={false}
1632 diffAvailable={false}
1633 filesAvailable={false}
1634 pullRequestAvailable={false}
1635 pullRequestsAvailable={false}
1636 deviceAvailable={false}
1637 pullRequestStatusSeeds={listedPullRequestTabStatuses}
1638 >
1639 <PullRequestDetailPanel
1640 getShortcutContext={getShortcutContext}
1641 shortcutsEnabled={activePullRequestSurface?.id === renderedPullRequestSurface.id}
1642 key={renderedPullRequestSurface.id}
1643 revealUrl={renderedPullRequestSurface.revealUrl}
1644 onRevealSettled={(revealUrl) => {
1645 if (rightPanelRef === null) return;
1646 useRightPanelStore
1647 .getState()
1648 .settlePullRequestReveal(rightPanelRef, renderedPullRequestSurface.id, revealUrl);
1649 }}
1650 environmentId={panelEnvironmentId}
1651 onGuideShown={onGuideShown}
1652 onSelectPullRequest={(reference) => {
1653 if (rightPanelRef === null) return;
1654 useRightPanelStore.getState().openPullRequest(rightPanelRef, {
1655 projectId: reference.projectId,
1656 repository: reference.repository,
1657 number: reference.number,
1658 ...(reference.host ? { host: reference.host } : {}),
1659 environmentId: panelEnvironmentId,
1660 });
1661 updateSearch({
1662 repository: reference.repository,
1663 number: reference.number,
1664 selectedHost: reference.host,
1665 selectedProjectId: reference.projectId,
1666 selectedEnvironmentId: panelEnvironmentId,
1667 });
1668 }}
1669 reference={pullRequestPanelReference({
1670 ...renderedPullRequestSurface,
1671 projectId: renderedPullRequestSurface.projectId as ProjectId,
1672 })}
1673 listEntry={
1674 listedPullRequestsBySurface.get(
1675 pullRequestListEntryId(renderedPullRequestSurface),
1676 ) ?? null
1677 }
1678 refreshToken={detailRefreshToken}
1679 tabOnPage
1680 onActed={(action, phase = "done", reply) => {
1681 // From every row held, not the ones on screen: a pull request closed from an open
1682 // list has left the screen, and reopening it has to find it anyway.
1683 const acted = heldPullRequestsBySurface.get(
1684 pullRequestListEntryId(renderedPullRequestSurface),
1685 );
1686 if (reply !== undefined) {
1687 if (acted !== undefined) {
1688 if (action !== undefined) overrideEntry(acted, action, reply);
1689 detailOverrideTokens.current.delete(pullRequestEntryKey(acted));
1690 }
1691 return;
1692 }
1693 const stateOnly =
1694 action !== undefined &&
1695 acted !== undefined &&
1696 pullRequestOverrideAfterAction(acted, action, new Date(), 0) !== null;
1697 if (stateOnly) {
1698 const key = pullRequestEntryKey(acted);
1699 if (phase === "sent" && action !== "merge") {
1700 detailOverrideTokens.current.set(key, overrideEntry(acted, action));
1701 }
1702 if (phase === "failed" && action !== "merge") {
1703 revertOverride(key, detailOverrideTokens.current.get(key) ?? null);
1704 }
1705 if (phase !== "sent") detailOverrideTokens.current.delete(key);
1706 if (phase === "done" && action === "merge") {
1707 overrideEntry(acted, action);
1708 refreshListAndStats(undefined, panelEnvironmentId);
1709 }
1710 return;
1711 }
1712 if (phase === "done") refreshListAndStats(undefined, panelEnvironmentId);
1713 }}
1714 />
1715 </RightPanelTabs>
1716 ) : null}
1717 </div>
1718 </SidebarInset>
1719 );
1720 }
1721
1722 function PullRequestFiltersMenuInSidebarOrder(
1723 props: ComponentProps<typeof PullRequestFiltersMenu>,
1724 ) {
1725 const sidebarProjectGroups = useSidebarProjectGroups();
1726 const projects = sortProjectsByGroupOrder(props.projects, sidebarProjectGroups);
1727 return <PullRequestFiltersMenu {...props} projects={projects} />;
1728 }