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

usePullRequestDetail.ts

200 lines7.4 KB

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