The best way to control Claude Code, Codex and more from any computer or phone

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