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

usePullRequestDetail.ts

245 lines9.2 KB

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 };
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;
67​
68export function pullRequestRefKey(reference: PullRequestRef) {
69 return `${reference.projectId}:${reference.host ?? ""}:${reference.repository}#${reference.number}`;
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 restoreDetail: true,
136 });
137 const pendingEdits = useAtomValue(pullRequestPendingEditsFor(environmentId, reference));
138 const activity = activityQuery.data;
139 const resolvedCoreDetail = resolveDisplayedPullRequestDetail({
140 live: liveDetail,
141 cached: cachedDetail,
142 reference,
143 });
144 // Every hook runs above this line: a hook between the merge and the panel's plain readers of
145 // `detail` would cost it its cache scope.
146 const listSummary = listEntry === null ? null : pullRequestListEntryToSummary(listEntry);
147 // The row can come from the page's stored snapshot, which no answer has published yet.
148 const sharedSummary = newestDisplayedPullRequestSummary(
149 resolvedCoreDetail,
150 liveDetail === null,
151 newestPullRequestSummary(listSummary, observedSummary),
152 reference,
153 pendingEdits,
154 );
155 const coreDetail =
156 resolvedCoreDetail === null || sharedSummary === null || sharedSummary === resolvedCoreDetail
157 ? resolvedCoreDetail
158 : {
159 ...resolvedCoreDetail,
160 title: sharedSummary.title,
161 state: sharedSummary.state,
162 headBranch: sharedSummary.headBranch,
163 baseBranch: sharedSummary.baseBranch,
164 updatedAt: sharedSummary.updatedAt,
165 author: sharedSummary.author ?? resolvedCoreDetail.author,
166 additions: sharedSummary.additions ?? resolvedCoreDetail.additions,
167 deletions: sharedSummary.deletions ?? resolvedCoreDetail.deletions,
168 changedFiles: sharedSummary.changedFiles ?? resolvedCoreDetail.changedFiles,
169 mergeability: sharedSummary.mergeability ?? resolvedCoreDetail.mergeability,
170 closedAt:
171 sharedSummary.closedAt === undefined
172 ? resolvedCoreDetail.closedAt
173 : sharedSummary.closedAt,
174 mergedAt:
175 sharedSummary.mergedAt === undefined
176 ? resolvedCoreDetail.mergedAt
177 : sharedSummary.mergedAt,
178 isDraft: sharedSummary.isDraft ?? resolvedCoreDetail.isDraft,
179 };
180 const detail =
181 coreDetail === null
182 ? null
183 : {
184 ...coreDetail,
185 capabilities: canWriteSourceControl
186 ? coreDetail.capabilities
187 : {
188 ...coreDetail.capabilities,
189 reactions: false,
190 edit: { changeRequest: false, comment: false },
191 },
192 viewerPermissions: canWriteSourceControl
193 ? coreDetail.viewerPermissions
194 : {
195 ...coreDetail.viewerPermissions,
196 actions: [],
197 comment: false,
198 resolve: false,
199 verdicts: [],
200 requestReviewers: false,
201 updateMethods: [],
202 labels: false,
203 },
204 author: activity?.author ?? coreDetail.author,
205 reviewers: activity?.reviewers ?? coreDetail.reviewers,
206 comments: activity?.comments ?? [],
207 commentCount: Math.max(
208 activity?.commentCount ?? 0,
209 new Set([
210 ...(activity?.comments.map((comment) => comment.id) ?? []),
211 ...(activity?.reviewThreads.flatMap((thread) =>
212 thread.comments.map((comment) => comment.id),
213 ) ?? []),
214 ]).size,
215 ),
216 commentsTruncated: activity?.commentsTruncated ?? false,
217 reviewThreads: activity?.reviewThreads ?? [],
218 ...(activity?.reviewThreadsTruncated === undefined
219 ? {}
220 : { reviewThreadsTruncated: activity.reviewThreadsTruncated }),
221 ...(activity?.overviewThreads === undefined
222 ? {}
223 : { overviewThreads: activity.overviewThreads }),
224 commits: activity?.commits ?? [],
225 reactions: activity?.reactions ?? [],
226 };
227 // Keep the shown detail through refreshes that only restamp it, so the panel's tree can skip
228 // re-rendering. Code that orders local edits against observations reads `observedAt` instead.
229 const [shownDetail, setShownDetail] = useState(detail);
230 const stableDetail =
231 detail !== shownDetail && samePullRequestReadExceptStamps(shownDetail, detail)
232 ? shownDetail
233 : detail;
234 if (stableDetail !== shownDetail) setShownDetail(stableDetail);
235 return {
236 canWriteSourceControl,
237 detailQuery,
238 activityQuery,
239 activity,
240 sharedSummary,
241 coreDetail,
242 detail: stableDetail,
243 observedAt: detail?.observedAt,
244 };