Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

pullRequests.ts

653 lines24.0 KB

1import { useAtomValue } from "@effect/atom-react";
2import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3import {
4 createLinkedPullRequestSummaryAtomFamily,
5 createPullRequestEnvironmentAtoms,
6 createPullRequestStackAtomFamily,
7} from "@t3tools/client-runtime/state/pull-requests";
8import {
9 PullRequestListResult,
10 type EnvironmentId,
11 type ProjectId,
12 type PullRequestChecksState,
13 type PullRequestListInput,
14 type PullRequestFilterOptionsInput,
15 type PullRequestListStatsInput,
16 type PullRequestListEntry,
17 type PullRequestRef,
18 type PullRequestSummary,
19 type ThreadPullRequestLink,
20} from "@t3tools/contracts";
21import {
22 threadPullRequestKeyOf,
23 visibleThreadPullRequests,
24} from "@t3tools/client-runtime/thread-pull-requests";
25import * as Clock from "effect/Clock";
26import * as Effect from "effect/Effect";
27import * as Option from "effect/Option";
28import * as Schema from "effect/Schema";
29import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
30​
31import { connectionAtomRuntime } from "../connection/runtime";
32import { appAtomRegistry } from "../rpc/atomRegistry";
33import {
34 mergePullRequestLists,
35 type EnvironmentPullRequestStat,
36 type MergedPullRequestList,
37} from "../components/pullRequest/pullRequestList.logic";
38import { writePullRequestDetailSnapshot } from "../components/pullRequest/pullRequestDetail.logic";
39import { pullRequestChecksState } from "../components/pullRequest/pullRequestPresentation";
40import { useGuideRunStore } from "../components/pullRequest/guide/guideRunStore";
41import { formatEnvironmentQueryError } from "./query";
42import { environmentThreadShells } from "./threads";
43​
44export interface ObservedPullRequestSummary {
45 readonly summary: PullRequestSummary;
46 /** Client arrival time, the only ordering older servers leave us for same-dated snapshots. */
47 readonly observedAt: number;
49​
50function compareSummaries(current: PullRequestSummary, incoming: PullRequestSummary): number {
51 const merged = Number(incoming.state === "merged") - Number(current.state === "merged");
52 if (merged !== 0) return merged;
53 const updated = Date.parse(incoming.updatedAt) - Date.parse(current.updatedAt);
54 if (updated !== 0) return updated;
55 if (current.observedAt === undefined && incoming.observedAt === undefined) return 0;
56 return (incoming.observedAt ?? -Infinity) - (current.observedAt ?? -Infinity);
58​
59export function newestPullRequestSummary(
60 current: PullRequestSummary | null,
61 observed: PullRequestSummary | null,
62): PullRequestSummary | null {
63 if (current === null) return observed;
64 if (observed === null) return current;
65 return compareSummaries(current, observed) >= 0 ? observed : current;
67​
68export function pullRequestListEntryToSummary(entry: PullRequestListEntry): PullRequestSummary {
69 return {
70 provider: entry.provider,
71 projectId: entry.projectId,
72 repository: entry.repository,
73 number: entry.number,
74 title: entry.title,
75 url: entry.url,
76 state: entry.state,
77 isDraft: entry.isDraft,
78 headBranch: entry.headBranch,
79 baseBranch: entry.baseBranch,
80 updatedAt: entry.updatedAt,
81 ...(entry.observedAt === undefined ? {} : { observedAt: entry.observedAt }),
82 author: entry.author,
83 ...(entry.reviewDecision === undefined ? {} : { reviewDecision: entry.reviewDecision }),
84 ...(entry.checksState === undefined ? {} : { checksState: entry.checksState }),
85 mergeability: entry.mergeability,
86 };
88​
89// Project ids pin the remote host; omit host so legacy, URL, and list references share entries.
90function pullRequestSummaryKey(environmentId: EnvironmentId, reference: PullRequestRef): string {
91 return JSON.stringify([
92 environmentId,
93 reference.projectId,
94 reference.repository.toLowerCase(),
95 reference.number,
96 ]);
98​
99export function newestPullRequestObservation(
100 current: ObservedPullRequestSummary | null,
101 incoming: ObservedPullRequestSummary | null,
102): ObservedPullRequestSummary | null {
103 if (current === null) return incoming;
104 if (incoming === null) return current;
105 let order = compareSummaries(current.summary, incoming.summary);
106 if (
107 order === 0 &&
108 current.summary.observedAt === undefined &&
109 incoming.summary.observedAt === undefined
110 ) {
111 order = incoming.observedAt - current.observedAt;
112 }
113 if (!(order > 0)) return current;
114 // A sparse summary must not erase known status, or carry old detail stats into a new list read.
115 return {
116 ...incoming,
117 summary: {
118 ...incoming.summary,
119 isDraft: incoming.summary.isDraft ?? current.summary.isDraft,
120 mergeability: incoming.summary.mergeability ?? current.summary.mergeability,
121 reviewDecision:
122 incoming.summary.reviewDecision === undefined
123 ? current.summary.reviewDecision
124 : incoming.summary.reviewDecision,
125 checksState:
126 incoming.summary.checksState === undefined
127 ? current.summary.checksState
128 : incoming.summary.checksState,
129 },
130 };
132​
133export interface ObservedPullRequestChecks {
134 readonly checksState: PullRequestChecksState | null;
135 /** Server read time, when the server reports one. */
136 readonly readAt: number | undefined;
137 /** Client arrival time. */
138 readonly observedAt: number;
140​
141/**
142 * Checks are reread far more often than the rest of a pull request, so they keep their own
143 * freshness: a checks read must not carry old metadata forward, and a list read must not take
144 * back newer checks.
145 */
146export interface PullRequestObservations {
147 readonly metadata: ObservedPullRequestSummary | null;
148 readonly checks: ObservedPullRequestChecks | null;
150​
151const noObservations: PullRequestObservations = { metadata: null, checks: null };
152​
153const pullRequestObservationsAtom = Atom.family((key: string) =>
154 Atom.make<PullRequestObservations>(noObservations).pipe(
155 Atom.setIdleTTL(5 * 60_000),
156 Atom.withLabel(`web-pull-requests:observations:${key}`),
157 ),
158);
159​
160export function observePullRequestChecks(
161 current: PullRequestObservations,
162 incoming: ObservedPullRequestChecks,
163): PullRequestObservations {
164 const previous = current.checks;
165 const newer =
166 previous === null ||
167 (previous.readAt !== undefined && incoming.readAt !== undefined
168 ? incoming.readAt >= previous.readAt
169 : incoming.observedAt >= previous.observedAt);
170 return newer ? { ...current, checks: incoming } : current;
172​
173export function observePullRequestMetadata(
174 current: PullRequestObservations,
175 incoming: ObservedPullRequestSummary,
176): PullRequestObservations {
177 const metadata = newestPullRequestObservation(current.metadata, incoming);
178 const next = metadata === current.metadata ? current : { ...current, metadata };
179 const { checksState } = incoming.summary;
180 return checksState === undefined
181 ? next
182 : observePullRequestChecks(next, {
183 checksState,
184 readAt: incoming.summary.observedAt,
185 observedAt: incoming.observedAt,
186 });
188​
189export function observedPullRequestSummary(
190 observations: PullRequestObservations,
191): PullRequestSummary | null {
192 const { metadata, checks } = observations;
193 if (metadata === null) return null;
194 return checks === null
195 ? metadata.summary
196 : { ...metadata.summary, checksState: checks.checksState };
198​
199function recordObservation(
200 registry: AtomRegistry.AtomRegistry,
201 key: string,
202 observe: (current: PullRequestObservations) => PullRequestObservations,
203): void {
204 registry.modify(pullRequestObservationsAtom(key), (previous) => {
205 const next = observe(previous);
206 return next === previous ? [false, previous] : [true, next];
207 });
209​
210function observePullRequestSummary(
211 registry: AtomRegistry.AtomRegistry,
212 key: string,
213 summary: PullRequestSummary,
214 observedAt: number,
215): void {
216 recordObservation(registry, key, (current) =>
217 observePullRequestMetadata(current, { summary, observedAt }),
218 );
220​
221// Reading localStorage throws where the browser blocks storage; that must not break the page.
222function snapshotStorage(): Storage | undefined {
223 if (typeof window === "undefined") return undefined;
224 try {
225 return window.localStorage;
226 } catch {
227 return undefined;
228 }
230​
231type ListAnswerStorage = Pick<Storage, "getItem" | "setItem" | "removeItem" | "key" | "length">;
232​
233const LIST_SCOPE_INDEX_KEY = "t3.pullRequests.listScopes";
234const LIST_SCOPE_KEY_PREFIX = "t3.pullRequests.listScope:";
235const LEGACY_SNAPSHOT_KEY_PREFIX = "t3.pullRequests.list:";
236const LIST_ANSWER_MAX_ENTRIES = 99;
237/**
238 * A scope holds a page of rows per environment, so only the scopes visited most recently are
239 * kept. Eviction drops a whole scope, never one environment's answer, so a restored list is never
240 * missing environments that did answer.
241 */
242const LIST_SCOPE_MAX_KEPT = 8;
243const listScopeCodec = Schema.fromJsonString(
244 Schema.Record(Schema.String, Schema.toCodecJson(PullRequestListResult)),
245);
246const decodeListScope = Schema.decodeUnknownOption(listScopeCodec);
247const encodeListScope = Schema.encodeOption(listScopeCodec);
248const decodeListScopeIndex = Schema.decodeUnknownOption(
249 Schema.fromJsonString(Schema.Array(Schema.String)),
250);
251const sweptStorages = new WeakSet<ListAnswerStorage>();
252​
253/**
254 * The project assignment is left out: a cold start asks before the project shells load, when
255 * every environment is asked for all of its projects, while the answers were remembered after
256 * overlapping projects were split between environments. Each environment's answer covers only
257 * its assigned projects, so the scope's answers together still cover the whole scope.
258 */
259const listScopeKey = ({ projectIds: _projectIds, ...scope }: PullRequestListInput) =>
260 `${LIST_SCOPE_KEY_PREFIX}${JSON.stringify(scope)}`;
261​
262function readListScope(storage: ListAnswerStorage | undefined, key: string) {
263 let raw: string | null = null;
264 try {
265 raw = storage?.getItem(key) ?? null;
266 } catch {}
267 return Option.getOrElse(decodeListScope(raw), (): Record<string, PullRequestListResult> => ({}));
269​
270/** The single composite snapshot this replaced is never read again. */
271function sweepLegacySnapshots(storage: ListAnswerStorage): void {
272 if (sweptStorages.has(storage)) return;
273 sweptStorages.add(storage);
274 const legacy: string[] = [];
275 for (let index = 0; index < storage.length; index++) {
276 const key = storage.key(index);
277 if (key?.startsWith(LEGACY_SNAPSHOT_KEY_PREFIX)) legacy.push(key);
278 }
279 for (const key of legacy) storage.removeItem(key);
281​
282/**
283 * Keeps what a cold start can show before the host answers again. Searches, continuation pages
284 * and grown pages are never shown that way, so only first-page reads are kept. Failures and
285 * cursors are dropped: they describe the moment of the read, and a restored list must not
286 * continue from it.
287 */
288export function rememberPullRequestListAnswer(
289 storage: ListAnswerStorage | undefined,
290 target: EnvironmentQueryTarget<PullRequestListInput>,
291 answer: PullRequestListResult,
292): void {
293 const { input } = target;
294 if (storage === undefined || input.query !== undefined || input.cursors !== undefined) return;
295 if (input.limit !== undefined && input.limit > LIST_ANSWER_MAX_ENTRIES) return;
296 const key = listScopeKey(input);
297 try {
298 sweepLegacySnapshots(storage);
299 const scope = readListScope(storage, key);
300 // An answer for some projects replaces only their rows. A repository this environment no
301 // longer owns stays covered until the environment that took it over answers; the next answer
302 // for all of the environment's projects, which every cold start asks for, drops them.
303 const assigned = input.projectIds === undefined ? undefined : new Set(input.projectIds);
304 const retained =
305 assigned === undefined
306 ? []
307 : (scope[target.environmentId]?.entries ?? []).filter(
308 (entry) => !assigned.has(entry.projectId),
309 );
310 const encoded = encodeListScope({
311 ...scope,
312 [target.environmentId]: {
313 ...answer,
314 // The fresh rows come first, so retained rows only fill what is left of the page.
315 entries: [...answer.entries, ...retained].slice(0, LIST_ANSWER_MAX_ENTRIES),
316 errors: [],
317 nextCursors: {},
318 },
319 });
320 if (Option.isNone(encoded)) return;
321 const index = Option.getOrElse(
322 decodeListScopeIndex(storage.getItem(LIST_SCOPE_INDEX_KEY)),
323 () => [],
324 );
325 const kept = [key, ...index.filter((held) => held !== key)];
326 for (const evicted of kept.slice(LIST_SCOPE_MAX_KEPT)) storage.removeItem(evicted);
327 storage.setItem(key, encoded.value);
328 storage.setItem(LIST_SCOPE_INDEX_KEY, JSON.stringify(kept.slice(0, LIST_SCOPE_MAX_KEPT)));
329 } catch {}
331​
332/**
333 * The kept answers for these reads, merged the way live answers are. An environment without a
334 * kept answer is left out rather than failing the restore: one whose projects were all assigned
335 * to another environment was never asked, and its pull requests are in that environment's answer.
336 */
337export function restorePullRequestList(
338 storage: ListAnswerStorage | undefined,
339 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
340): MergedPullRequestList | null {
341 const scopes = new Map<string, Record<string, PullRequestListResult>>();
342 const answers: Array<readonly [EnvironmentId, PullRequestListResult]> = [];
343 for (const target of targets) {
344 const key = listScopeKey(target.input);
345 const scope = scopes.get(key) ?? readListScope(storage, key);
346 scopes.set(key, scope);
347 const answer = scope[target.environmentId];
348 if (answer !== undefined) answers.push([target.environmentId, answer]);
349 }
350 const merged = mergePullRequestLists(answers);
351 if (merged === null) return null;
352 // Answers kept before the projects were reassigned between environments can overlap.
353 const seen = new Set<string>();
354 const entries = merged.entries.filter((entry) => {
355 const key = `${entry.host}:${entry.repository}#${entry.number}`;
356 if (seen.has(key)) return false;
357 seen.add(key);
358 return true;
359 });
360 return { ...merged, entries };
362​
363export function restoredPullRequestList(
364 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
365): MergedPullRequestList | null {
366 return restorePullRequestList(snapshotStorage(), targets);
368​
369// Answers are stamped on arrival: older servers leave no other ordering for same-dated reads.
370export const pullRequestEnvironment = createPullRequestEnvironmentAtoms(connectionAtomRuntime, {
371 list: ({ environmentId, input }, answer, registry) =>
372 Effect.map(Clock.currentTimeMillis, (observedAt) => {
373 rememberPullRequestListAnswer(snapshotStorage(), { environmentId, input }, answer);
374 for (const entry of answer.entries) {
375 observePullRequestSummary(
376 registry,
377 pullRequestSummaryKey(environmentId, entry),
378 pullRequestListEntryToSummary(entry),
379 observedAt,
380 );
381 }
382 }),
383 detail: ({ environmentId, input }, detail, registry) =>
384 Effect.map(Clock.currentTimeMillis, (at) => {
385 // Only fresh reads seed the cold-start snapshot; a stale one could replace a newer record.
386 if (input.allowStale === false) {
387 writePullRequestDetailSnapshot(snapshotStorage(), environmentId, input, detail);
388 }
389 observePullRequestSummary(
390 registry,
391 pullRequestSummaryKey(environmentId, input),
392 { ...detail, checksState: pullRequestChecksState(detail.checks) },
393 at,
394 );
395 }),
396 checks: ({ environmentId, input }, checks, registry) =>
397 Effect.map(Clock.currentTimeMillis, (observedAt) => {
398 if (checks === null) return;
399 recordObservation(registry, pullRequestSummaryKey(environmentId, input), (current) =>
400 observePullRequestChecks(current, {
401 checksState: pullRequestChecksState(checks.checks),
402 readAt: checks.observedAt,
403 observedAt,
404 }),
405 );
406 }),
407 // Covers runs started elsewhere (another client, an agent) as well as this client's own.
408 reviewGuide: ({ environmentId, input }, guide) =>
409 Effect.map(Clock.currentTimeMillis, (since) => {
410 if (guide.run?._tag !== "Running") return;
411 useGuideRunStore.getState().watch({
412 environmentId,
413 reference: input,
414 title: null,
415 previousGuideAt: guide.guide?.generatedAt ?? null,
416 previousFailedAt: null,
417 since,
418 answeredRunning: true,
419 });
420 }),
421});
422​
423export const linkedPullRequestDetailAtom = createLinkedPullRequestSummaryAtomFamily(
424 connectionAtomRuntime,
425 pullRequestEnvironment.refreshes,
426 ({ environmentId, input }, summary, registry) =>
427 Effect.map(Clock.currentTimeMillis, (observedAt) =>
428 observePullRequestSummary(
429 registry,
430 pullRequestSummaryKey(environmentId, input),
431 summary,
432 observedAt,
433 ),
434 ),
435);
436​
437export function threadPullRequestLinkToSummary(
438 link: ThreadPullRequestLink,
439 projectId: ProjectId,
440): PullRequestSummary | null {
441 const updatedAt = link.snapshot?.updatedAt;
442 if (link.snapshot === null || updatedAt == null) return null;
443 return {
444 ...link.snapshot,
445 provider: (
446 sourceControlClients.findByChangeRequestUrl(link.url) ?? sourceControlClients.get(undefined)
447 ).kind,
448 projectId,
449 repository: link.repository,
450 number: link.number,
451 url: link.url,
452 updatedAt,
453 };
455​
456function savedPullRequestKey(
457 environmentId: EnvironmentId,
458 reference: Pick<PullRequestRef, "host" | "repository" | "number">,
459): string {
460 return reference.host === undefined
461 ? ""
462 : `${environmentId}:${threadPullRequestKeyOf({ ...reference, host: reference.host })}`;
464​
465const savedPullRequestSummariesAtom = Atom.make((get) => {
466 const summaries = new Map<string, PullRequestSummary>();
467 for (const thread of get(environmentThreadShells.threadShellsAtom)) {
468 for (const link of visibleThreadPullRequests(thread.pullRequests)) {
469 const summary = threadPullRequestLinkToSummary(link, thread.projectId);
470 if (summary === null) continue;
471 const key = savedPullRequestKey(thread.environmentId, link);
472 summaries.set(key, newestPullRequestSummary(summaries.get(key) ?? null, summary) ?? summary);
473 }
474 }
475 return summaries;
476});
477​
478const savedPullRequestSummaryAtom = Atom.family((key: string) =>
479 Atom.make((get) => get(savedPullRequestSummariesAtom).get(key) ?? null).pipe(
480 Atom.withEquality((previous, next) => JSON.stringify(previous) === JSON.stringify(next)),
481 Atom.setIdleTTL(5 * 60_000),
482 ),
483);
484​
485export function observedPullRequestTitle(
486 registry: AtomRegistry.AtomRegistry,
487 environmentId: EnvironmentId,
488 reference: PullRequestRef,
489): string | null {
490 return (
491 registry.get(pullRequestObservationsAtom(pullRequestSummaryKey(environmentId, reference)))
492 .metadata?.summary.title ?? null
493 );
495​
496/** The newest of every list, detail, checks and linked-summary answer and the thread's saved link. */
497export function useSharedPullRequestSummary(
498 environmentId: EnvironmentId | null,
499 reference: PullRequestRef | null,
500): PullRequestSummary | null {
501 const key =
502 environmentId === null || reference === null
503 ? "none"
504 : pullRequestSummaryKey(environmentId, reference);
505 const observations = useAtomValue(pullRequestObservationsAtom(key));
506 const saved = useAtomValue(
507 savedPullRequestSummaryAtom(
508 environmentId === null || reference === null
509 ? ""
510 : savedPullRequestKey(environmentId, reference),
511 ),
512 );
513 return newestPullRequestSummary(observedPullRequestSummary(observations), saved);
515export const pullRequestStackAtom = createPullRequestStackAtomFamily(
516 connectionAtomRuntime,
517 pullRequestEnvironment.refreshes,
518);
519​
520export interface EnvironmentQueryTarget<Input> {
521 readonly environmentId: EnvironmentId;
522 readonly input: Input;
524​
525interface MergedEnvironmentQueryView<A> {
526 readonly values: ReadonlyArray<readonly [EnvironmentId, A]>;
527 readonly error: string | null;
528 readonly isPending: boolean;
530​
531// Use one derived atom for variable fan-out; unreachable environments must not hide other rows.
532function createMergedEnvironmentQuery<Input, A>(
533 label: string,
534 atomFor: (
535 target: EnvironmentQueryTarget<Input>,
536 ) => Atom.Atom<AsyncResult.AsyncResult<A, unknown>>,
537) {
538 const family = Atom.family((key: string) =>
539 Atom.make((get): MergedEnvironmentQueryView<A> => {
540 const targets = JSON.parse(key) as ReadonlyArray<EnvironmentQueryTarget<Input>>;
541 const values: Array<readonly [EnvironmentId, A]> = [];
542 let error: string | null = null;
543 let isPending = false;
544 for (const target of targets) {
545 const result = get(atomFor(target));
546 isPending ||= result.waiting;
547 if (result._tag === "Failure" && error === null) {
548 error = formatEnvironmentQueryError(result.cause);
549 }
550 const value = Option.getOrNull(AsyncResult.value(result));
551 if (value !== null) values.push([target.environmentId, value]);
552 }
553 return { values, error, isPending };
554 }).pipe(Atom.withLabel(`${label}:${key}`)),
555 );
556 const empty = Atom.make<MergedEnvironmentQueryView<A>>({
557 values: [],
558 error: null,
559 isPending: false,
560 }).pipe(Atom.withLabel(`${label}:empty`));
561 return function useMergedQuery(targets: ReadonlyArray<EnvironmentQueryTarget<Input>>) {
562 const key = JSON.stringify(targets);
563 const view = useAtomValue(targets.length === 0 ? empty : family(key));
564 const refresh = (override?: ReadonlyArray<EnvironmentQueryTarget<Input>>) => {
565 const refreshTargets =
566 override ?? (JSON.parse(key) as ReadonlyArray<EnvironmentQueryTarget<Input>>);
567 for (const atom of new Set(refreshTargets.map(atomFor))) {
568 appAtomRegistry.refresh(atom);
569 }
570 };
571 return { ...view, refresh };
572 };
574​
575const usePullRequestListsQuery = createMergedEnvironmentQuery(
576 "web-pull-requests:list",
577 pullRequestEnvironment.list,
578);
579​
580const usePullRequestStatsQuery = createMergedEnvironmentQuery(
581 "web-pull-requests:list-stats",
582 pullRequestEnvironment.listStats,
583);
584​
585const usePullRequestFilterOptionsQuery = createMergedEnvironmentQuery(
586 "web-pull-requests:filter-options",
587 pullRequestEnvironment.filterOptions,
588);
589​
590const usePullRequestTurnRefreshQuery = createMergedEnvironmentQuery(
591 "web-pull-requests:turn-refreshes",
592 ({ environmentId }: EnvironmentQueryTarget<Readonly<Record<string, never>>>) =>
593 pullRequestEnvironment.refreshes({ environmentId, input: {} }),
594);
595​
596export function usePullRequestTurnRefreshes(
597 environmentIds: ReadonlyArray<EnvironmentId>,
598): ReadonlyArray<readonly [EnvironmentId, number]> {
599 return usePullRequestTurnRefreshQuery(
600 environmentIds.map((environmentId) => ({ environmentId, input: {} })),
601 ).values;
603​
604export function usePullRequestTurnRefresh(environmentId: EnvironmentId): number | null {
605 const result = useAtomValue(pullRequestEnvironment.refreshes({ environmentId, input: {} }));
606 return Option.getOrNull(AsyncResult.value(result));
608​
609export interface MergedPullRequestListView {
610 readonly data: MergedPullRequestList | null;
611 readonly error: string | null;
612 readonly isPending: boolean;
613 readonly refresh: (targets?: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>) => void;
615​
616export function usePullRequestList(
617 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>,
618): MergedPullRequestListView {
619 const query = usePullRequestListsQuery(targets);
620 const data = mergePullRequestLists(query.values);
621 return { data, error: query.error, isPending: query.isPending, refresh: query.refresh };
623​
624export function usePullRequestListStats(
625 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestListStatsInput>>,
626): {
627 readonly stats: ReadonlyArray<EnvironmentPullRequestStat> | null;
628 readonly isPending: boolean;
629 readonly refresh: (
630 targets?: ReadonlyArray<EnvironmentQueryTarget<PullRequestListStatsInput>>,
631 ) => void;
632} {
633 const query = usePullRequestStatsQuery(targets);
634 const stats =
635 query.values.length === 0
636 ? null
637 : query.values.flatMap(([environmentId, result]) =>
638 result.stats.map((stat) => ({ ...stat, environmentId })),
639 );
640 return { stats, isPending: query.isPending, refresh: query.refresh };
642​
643export function usePullRequestFilterOptions(
644 targets: ReadonlyArray<EnvironmentQueryTarget<PullRequestFilterOptionsInput>>,
645) {
646 const query = usePullRequestFilterOptionsQuery(targets);
647 return {
648 labels: query.values.flatMap(([, options]) => options.labels),
649 authors: query.values.flatMap(([, options]) => options.authors),
650 error: query.error,
651 isPending: query.isPending,
652 };