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

usePullRequestDetail.ts

206 lines7.6 KB

1import {
2 AuthSourceControlWriteScope,
3 type EnvironmentId,
4 type PullRequestDetail,
5 type PullRequestListEntry,
6 type PullRequestRef,
7} from "@t3tools/contracts";
8import { useEffect, useEffectEvent, useState } from "react";
9​
10import { usePullRequestChecksRefresh } from "~/hooks/usePullRequestChecksRefresh";
11import { useServerConfigs } from "~/state/entities";
12import { useEnvironmentQuery } from "~/state/query";
13import { useEnvironmentScope } from "~/state/session";
14import {
15 newestPullRequestSummary,
16 pullRequestEnvironment,
17 pullRequestListEntryToSummary,
18 useSharedPullRequestSummary,
19} from "~/state/pullRequests";
20import {
21 readPullRequestDetailSnapshot,
22 resolveDisplayedPullRequestDetail,
23 resolvePullRequestDetailChecks,
24 writePullRequestDetailSnapshot,
25} from "./pullRequestDetail.logic";
26import { pullRequestChecksState } from "./pullRequestPresentation";
27​
28export function pullRequestRefKey(reference: PullRequestRef) {
29 return `${reference.projectId}:${reference.host ?? ""}:${reference.repository}#${reference.number}`;
31​
32function pullRequestDetailSummary(data: PullRequestDetail | null) {
33 return data === null ? null : { ...data, checksState: pullRequestChecksState(data.checks) };
35​
36/**
37 * Loads a pull request's detail and activity and merges them, with the snapshot cache, the shared
38 * summary and the list row, into the detail the panel shows.
39 */
40export function usePullRequestDetail(
41 environmentId: EnvironmentId,
42 reference: PullRequestRef,
43 listEntry: PullRequestListEntry | null,
44) {
45 const scopeKey = `${environmentId}:${pullRequestRefKey(reference)}`;
46 const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope);
47 const detailQuery = useEnvironmentQuery(
48 pullRequestEnvironment.detail({ environmentId, input: { ...reference, allowStale: false } }),
49 );
50 const activityQuery = useEnvironmentQuery(
51 pullRequestEnvironment.activity({ environmentId, input: reference }),
52 );
53 const serverConfigs = useServerConfigs();
54 const supportsChecks =
55 serverConfigs.get(environmentId)?.environment.capabilities.pullRequestChecks === true;
56 const checksQuery = useEnvironmentQuery(
57 supportsChecks && detailQuery.data !== null
58 ? pullRequestEnvironment.checks({ environmentId, input: reference })
59 : null,
60 );
61 const liveDetail = resolvePullRequestDetailChecks(
62 detailQuery.data,
63 checksQuery.data,
64 checksQuery.dataUpdatedAt >= detailQuery.dataUpdatedAt,
65 );
66 usePullRequestChecksRefresh({
67 refresh: () => {
68 if (!checksQuery.isPending && !detailQuery.isPending) checksQuery.refresh();
69 },
70 enabled:
71 liveDetail?.state === "open" &&
72 supportsChecks &&
73 !(checksQuery.isSuccess && checksQuery.data === null),
74 key: `workspace-pr-checks:${environmentId}:${reference.projectId}:${reference.host}:${reference.repository}:${reference.number}`,
75 checks: liveDetail?.checks ?? [],
76 });
77 const [cachedDetail, setCachedDetail] = useState(() =>
78 readPullRequestDetailSnapshot(
79 typeof window === "undefined" ? undefined : window.localStorage,
80 environmentId,
81 reference,
82 ),
83 );
84 const [cachedDetailKey, setCachedDetailKey] = useState(scopeKey);
85 if (cachedDetailKey !== scopeKey) {
86 setCachedDetailKey(scopeKey);
87 setCachedDetail(
88 detailQuery.data ??
89 readPullRequestDetailSnapshot(
90 typeof window === "undefined" ? undefined : window.localStorage,
91 environmentId,
92 reference,
93 ),
94 );
95 } else if (detailQuery.data !== null && detailQuery.data !== cachedDetail) {
96 setCachedDetail(detailQuery.data);
97 }
98 const saveDetailSnapshot = useEffectEvent((data: PullRequestDetail) => {
99 writePullRequestDetailSnapshot(
100 typeof window === "undefined" ? undefined : window.localStorage,
101 environmentId,
102 reference,
103 data,
104 );
105 });
106 useEffect(() => {
107 if (detailQuery.data !== null) saveDetailSnapshot(detailQuery.data);
108 }, [detailQuery.data]);
109 const detailSummary = pullRequestDetailSummary(liveDetail);
110 const observedSummary = useSharedPullRequestSummary(
111 environmentId,
112 reference,
113 detailSummary,
114 Math.max(detailQuery.dataUpdatedAt, checksQuery.dataUpdatedAt),
115 );
116 const activity = activityQuery.data;
117 const resolvedCoreDetail = resolveDisplayedPullRequestDetail({
118 live: liveDetail,
119 cached: cachedDetail,
120 reference,
121 });
122 // Every hook runs above this line: a hook between the merge and the panel's plain readers of
123 // `detail` would cost it its cache scope.
124 const listSummary = listEntry === null ? null : pullRequestListEntryToSummary(listEntry);
125 // The list row is also published to the shared cache, but only after this commit's layout
126 // effects run, so it is compared directly rather than trusted to be there already.
127 const sharedSummary = newestPullRequestSummary(
128 resolvedCoreDetail,
129 newestPullRequestSummary(observedSummary, listSummary),
130 );
131 const coreDetail =
132 resolvedCoreDetail === null || sharedSummary === null || sharedSummary === resolvedCoreDetail
133 ? resolvedCoreDetail
134 : {
135 ...resolvedCoreDetail,
136 title: sharedSummary.title,
137 state: sharedSummary.state,
138 headBranch: sharedSummary.headBranch,
139 baseBranch: sharedSummary.baseBranch,
140 updatedAt: sharedSummary.updatedAt,
141 author: sharedSummary.author ?? resolvedCoreDetail.author,
142 additions: sharedSummary.additions ?? resolvedCoreDetail.additions,
143 deletions: sharedSummary.deletions ?? resolvedCoreDetail.deletions,
144 changedFiles: sharedSummary.changedFiles ?? resolvedCoreDetail.changedFiles,
145 mergeability: sharedSummary.mergeability ?? resolvedCoreDetail.mergeability,
146 closedAt:
147 sharedSummary.closedAt === undefined
148 ? resolvedCoreDetail.closedAt
149 : sharedSummary.closedAt,
150 mergedAt:
151 sharedSummary.mergedAt === undefined
152 ? resolvedCoreDetail.mergedAt
153 : sharedSummary.mergedAt,
154 isDraft: sharedSummary.isDraft ?? resolvedCoreDetail.isDraft,
155 };
156 const detail =
157 coreDetail === null
158 ? null
159 : {
160 ...coreDetail,
161 capabilities: canWriteSourceControl
162 ? coreDetail.capabilities
163 : {
164 ...coreDetail.capabilities,
165 reactions: false,
166 edit: { changeRequest: false, comment: false },
167 },
168 viewerPermissions: canWriteSourceControl
169 ? coreDetail.viewerPermissions
170 : {
171 ...coreDetail.viewerPermissions,
172 actions: [],
173 comment: false,
174 resolve: false,
175 verdicts: [],
176 requestReviewers: false,
177 updateMethods: [],
178 labels: false,
179 },
180 author: activity?.author ?? coreDetail.author,
181 reviewers: activity?.reviewers ?? coreDetail.reviewers,
182 comments: activity?.comments ?? [],
183 commentCount: Math.max(
184 activity?.commentCount ?? 0,
185 new Set([
186 ...(activity?.comments.map((comment) => comment.id) ?? []),
187 ...(activity?.reviewThreads.flatMap((thread) =>
188 thread.comments.map((comment) => comment.id),
189 ) ?? []),
190 ]).size,
191 ),
192 commentsTruncated: activity?.commentsTruncated ?? false,
193 reviewThreads: activity?.reviewThreads ?? [],
194 commits: activity?.commits ?? [],
195 reactions: activity?.reactions ?? [],
196 };
197 return {
198 canWriteSourceControl,
199 detailQuery,
200 activityQuery,
201 activity,
202 sharedSummary,
203 coreDetail,
204 detail,
205 };