Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3import {
4 comparePullRequestSummaries,
5 reconcileThreadPullRequestSnapshots,
6 type ObservedPullRequestStatus,
7} from "@t3tools/client-runtime/state/pull-requests";
8import { threadPullRequestKeyOf } from "@t3tools/client-runtime/thread-pull-requests";
9import type { EnvironmentId, PullRequestSummary, ThreadPullRequestLink } from "@t3tools/contracts";
10import { Atom, type AtomRegistry } from "effect/reactivity";
11
12import { rememberBounded } from "./thread-pr-presentation";
13
14const MAX_OBSERVATIONS = 500;
15
16// Keyed by the host's own URL, so checkout selectors and linked references meet on one entry.
17const pullRequestObservationsAtom = Atom.make<ReadonlyMap<string, ObservedPullRequestStatus>>(
18 new Map(),
19).pipe(Atom.keepAlive, Atom.withLabel("mobile:pull-request-observations"));
20
21const observationKey = (
22 environmentId: EnvironmentId,
23 link: Pick<ThreadPullRequestLink, "host" | "repository" | "number">,
24) => JSON.stringify([environmentId, threadPullRequestKeyOf(link)]);
25
26/** Records a host answer so linked rows, counts and badges show it over an older saved link. */
27export function observePullRequestSummary(
28 registry: AtomRegistry.AtomRegistry,
29 environmentId: EnvironmentId,
30 summary: PullRequestSummary,
31): void {
32 const link = sourceControlClients.parseChangeRequestUrl(summary.url)?.link;
33 if (link === undefined) return;
34 const key = observationKey(environmentId, link);
35 const { state, isDraft, title, updatedAt } = summary;
36 registry.update(pullRequestObservationsAtom, (current) => {
37 const previous = current.get(key);
38 // A late answer read before a merge must not reopen it.
39 return previous !== undefined && comparePullRequestSummaries(previous, summary) < 0
40 ? current
41 : rememberBounded(current, key, { state, isDraft, title, updatedAt }, MAX_OBSERVATIONS);
42 });
43}
44
45/** The thread's links with each saved snapshot overlaid by any newer host answer. */
46export function useReconciledThreadPullRequests(
47 environmentId: EnvironmentId | null,
48 links: ReadonlyArray<ThreadPullRequestLink>,
49): ReadonlyArray<ThreadPullRequestLink> {
50 // Returns `links` itself when nothing applies, so unrelated answers do not re-render rows.
51 return useAtomValue(pullRequestObservationsAtom, (observations) =>
52 environmentId === null || observations.size === 0
53 ? links
54 : reconcileThreadPullRequestSnapshots(links, (link) =>
55 observations.get(observationKey(environmentId, link)),
56 ),
57 );
58}