Open History to see the last commit
1import { useAtomValue } from "@effect/atom-react";
2import { resolvePullRequestDetailChecks } from "@t3tools/client-runtime/pull-request-checks";
3import { pullRequestPendingEditsFor } from "@t3tools/client-runtime/state/pull-requests";
4import {
5 AuthSourceControlWriteScope,
6 type EnvironmentId,
7 type PullRequestListEntry,
8 type PullRequestRef,
9 type ProjectId,
10} from "@t3tools/contracts";
11import { useState } from "react";
12
13import { usePullRequestChecksRefresh } from "~/hooks/usePullRequestChecksRefresh";
14import { useServerConfigs } from "~/state/entities";
15import { useEnvironmentQuery } from "~/state/query";
16import { useEnvironmentScope } from "~/state/session";
17import {
18 newestDisplayedPullRequestSummary,
19 newestPullRequestSummary,
20 pullRequestEnvironment,
21 pullRequestListEntryToSummary,
22 useSharedPullRequestSummary,
23} from "~/state/pullRequests";
24import {
25 readPullRequestDetailSnapshot,
26 resolveDisplayedPullRequestDetail,
27 samePullRequestReadExceptStamps,
28} from "./pullRequestDetail.logic";
29
30// Query atoms key on JSON order, so the panel and the row prefetch must build the ref here.
31export function pullRequestPanelReference(target: {
32 readonly projectId: ProjectId;
33 readonly repository: string;
34 readonly number: number;
35 readonly host?: string | undefined;
36}): PullRequestRef {
37 return {
38 projectId: target.projectId,
39 repository: target.repository,
40 number: target.number,
41 ...(target.host ? { host: target.host } : {}),
42 };
43}
44
45const internedReferences = new Map<string, PullRequestRef>();
46
47/**
48 * One object per pull request reference. Parents rebuild the reference on unrelated updates, and
49 * every comment's reaction bar, form and resolve button closes over it.
50 */
51export function internPullRequestReference(reference: PullRequestRef): PullRequestRef {
52 const key = JSON.stringify([
53 reference.projectId,
54 reference.host ?? null,
55 reference.repository,
56 reference.number,
57 reference.expectedAccountId ?? null,
58 reference.allowStale ?? null,
59 ]);
60 const interned = internedReferences.get(key);
61 if (interned !== undefined) return interned;
62 // Losing old entries only costs those pull requests one extra render.
63 if (internedReferences.size >= 500) internedReferences.clear();
64 internedReferences.set(key, reference);
65 return reference;
66}
67
68export function pullRequestRefKey(reference: PullRequestRef) {
69 return `${reference.projectId}:${reference.host ?? ""}:${reference.repository}#${reference.number}`;
70}
71
72/**
73 * Loads a pull request's detail and activity and merges them, with the snapshot cache, the shared
74 * summary and the list row, into the detail the panel shows.
75 */
76export function usePullRequestDetail(
77 environmentId: EnvironmentId,
78 reference: PullRequestRef,
79 listEntry: PullRequestListEntry | null,
80) {
81 const scopeKey = `${environmentId}:${pullRequestRefKey(reference)}`;
82 const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope);
83 const detailQuery = useEnvironmentQuery(
84 pullRequestEnvironment.detail({ environmentId, input: { ...reference, allowStale: false } }),
85 );
86 const activityQuery = useEnvironmentQuery(
87 pullRequestEnvironment.activity({ environmentId, input: reference }),
88 );
89 const serverConfigs = useServerConfigs();
90 const supportsChecks =
91 serverConfigs.get(environmentId)?.environment.capabilities.pullRequestChecks === true;
92 const checksQuery = useEnvironmentQuery(
93 supportsChecks && detailQuery.data !== null
94 ? pullRequestEnvironment.checks({ environmentId, input: reference })
95 : null,
96 );
97 const liveDetail = resolvePullRequestDetailChecks(
98 detailQuery.data,
99 checksQuery.data,
100 checksQuery.dataUpdatedAt >= detailQuery.dataUpdatedAt,
101 );
102 usePullRequestChecksRefresh({
103 refresh: () => {
104 if (!checksQuery.isPending && !detailQuery.isPending) checksQuery.refresh();
105 },
106 enabled:
107 liveDetail?.state === "open" &&
108 supportsChecks &&
109 !(checksQuery.isSuccess && checksQuery.data === null),
110 key: `workspace-pr-checks:${environmentId}:${reference.projectId}:${reference.host}:${reference.repository}:${reference.number}`,
111 checks: liveDetail?.checks ?? [],
112 });
113 const [cachedDetail, setCachedDetail] = useState(() =>
114 readPullRequestDetailSnapshot(
115 typeof window === "undefined" ? undefined : window.localStorage,
116 environmentId,
117 reference,
118 ),
119 );
120 const [cachedDetailKey, setCachedDetailKey] = useState(scopeKey);
121 if (cachedDetailKey !== scopeKey) {
122 setCachedDetailKey(scopeKey);
123 setCachedDetail(
124 detailQuery.data ??
125 readPullRequestDetailSnapshot(
126 typeof window === "undefined" ? undefined : window.localStorage,
127 environmentId,
128 reference,
129 ),
130 );
131 } else if (detailQuery.data !== null && detailQuery.data !== cachedDetail) {
132 setCachedDetail(detailQuery.data);
133 }
134 const observedSummary = useSharedPullRequestSummary(environmentId, reference);
135 const pendingEdits = useAtomValue(pullRequestPendingEditsFor(environmentId, reference));
136 const activity = activityQuery.data;
137 const resolvedCoreDetail = resolveDisplayedPullRequestDetail({
138 live: liveDetail,
139 cached: cachedDetail,
140 reference,
141 });
142 // Every hook runs above this line: a hook between the merge and the panel's plain readers of
143 // `detail` would cost it its cache scope.
144 const listSummary = listEntry === null ? null : pullRequestListEntryToSummary(listEntry);
145 // The row can come from the page's stored snapshot, which no answer has published yet.
146 const sharedSummary = newestDisplayedPullRequestSummary(
147 resolvedCoreDetail,
148 liveDetail === null,
149 newestPullRequestSummary(listSummary, observedSummary),
150 reference,
151 pendingEdits,
152 );
153 const coreDetail =
154 resolvedCoreDetail === null || sharedSummary === null || sharedSummary === resolvedCoreDetail
155 ? resolvedCoreDetail
156 : {
157 ...resolvedCoreDetail,
158 title: sharedSummary.title,
159 state: sharedSummary.state,
160 headBranch: sharedSummary.headBranch,
161 baseBranch: sharedSummary.baseBranch,
162 updatedAt: sharedSummary.updatedAt,
163 author: sharedSummary.author ?? resolvedCoreDetail.author,
164 additions: sharedSummary.additions ?? resolvedCoreDetail.additions,
165 deletions: sharedSummary.deletions ?? resolvedCoreDetail.deletions,
166 changedFiles: sharedSummary.changedFiles ?? resolvedCoreDetail.changedFiles,
167 mergeability: sharedSummary.mergeability ?? resolvedCoreDetail.mergeability,
168 closedAt:
169 sharedSummary.closedAt === undefined
170 ? resolvedCoreDetail.closedAt
171 : sharedSummary.closedAt,
172 mergedAt:
173 sharedSummary.mergedAt === undefined
174 ? resolvedCoreDetail.mergedAt
175 : sharedSummary.mergedAt,
176 isDraft: sharedSummary.isDraft ?? resolvedCoreDetail.isDraft,
177 };
178 const detail =
179 coreDetail === null
180 ? null
181 : {
182 ...coreDetail,
183 capabilities: canWriteSourceControl
184 ? coreDetail.capabilities
185 : {
186 ...coreDetail.capabilities,
187 reactions: false,
188 edit: { changeRequest: false, comment: false },
189 },
190 viewerPermissions: canWriteSourceControl
191 ? coreDetail.viewerPermissions
192 : {
193 ...coreDetail.viewerPermissions,
194 actions: [],
195 comment: false,
196 resolve: false,
197 verdicts: [],
198 requestReviewers: false,
199 updateMethods: [],
200 labels: false,
201 },
202 author: activity?.author ?? coreDetail.author,
203 reviewers: activity?.reviewers ?? coreDetail.reviewers,
204 comments: activity?.comments ?? [],
205 commentCount: Math.max(
206 activity?.commentCount ?? 0,
207 new Set([
208 ...(activity?.comments.map((comment) => comment.id) ?? []),
209 ...(activity?.reviewThreads.flatMap((thread) =>
210 thread.comments.map((comment) => comment.id),
211 ) ?? []),
212 ]).size,
213 ),
214 commentsTruncated: activity?.commentsTruncated ?? false,
215 reviewThreads: activity?.reviewThreads ?? [],
216 ...(activity?.reviewThreadsTruncated === undefined
217 ? {}
218 : { reviewThreadsTruncated: activity.reviewThreadsTruncated }),
219 ...(activity?.overviewThreads === undefined
220 ? {}
221 : { overviewThreads: activity.overviewThreads }),
222 commits: activity?.commits ?? [],
223 reactions: activity?.reactions ?? [],
224 };
225 // Keep the shown detail through refreshes that only restamp it, so the panel's tree can skip
226 // re-rendering. Code that orders local edits against observations reads `observedAt` instead.
227 const [shownDetail, setShownDetail] = useState(detail);
228 const stableDetail =
229 detail !== shownDetail && samePullRequestReadExceptStamps(shownDetail, detail)
230 ? shownDetail
231 : detail;
232 if (stableDetail !== shownDetail) setShownDetail(stableDetail);
233 return {
234 canWriteSourceControl,
235 detailQuery,
236 activityQuery,
237 activity,
238 sharedSummary,
239 coreDetail,
240 detail: stableDetail,
241 observedAt: detail?.observedAt,
242 };
243}