@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 344 lines 12.3 KB
Raw
1 import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
2 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
3 import { parsePullRequestQuery } from "@t3tools/client-runtime/pull-request-query";
4 import {
5 type EnvironmentId,
6 type ProjectId,
7 type PullRequestInvolvement,
8 type PullRequestListFilters,
9 type PullRequestListResult,
10 type PullRequestListState,
11 } from "@t3tools/contracts";
12 import { useEffect, useState } from "react";
13
14 import { useAllEnvironmentShellsBootstrapped, useProjects } from "~/state/entities";
15 import { useEnvironments } from "~/state/environments";
16 import {
17 applyPullRequestOverrides,
18 findProjectForRepository,
19 findScopedProject,
20 matchesPullRequestFilters,
21 pullRequestDiffStatKey,
22 pullRequestEntryKey,
23 pullRequestEntryViewer,
24 pullRequestEnvironmentSetKey,
25 pullRequestHostActions,
26 resolveProjectScope,
27 resolveQueryEnvironmentIds,
28 resolveSelectedEnvironmentId,
29 sortPullRequestGroups,
30 withDiffStat,
31 type EnvironmentPullRequestEntry,
32 type MergedPullRequestList,
33 type PullRequestDiffStats,
34 type PullRequestGroup,
35 type PullRequestListOverride,
36 } from "./pullRequestList.logic";
37 import type { PullRequestExpectedHost } from "./PullRequestListFilters";
38 import type { PullRequestListPreferences, PullRequestListSort } from "./pullRequestListPreferences";
39 import {
40 pullRequestProjectQueries,
41 type PullRequestHostAvailability,
42 } from "./pullRequestProjectAssignment.logic";
43 import { pullRequestFilterProjects } from "@t3tools/client-runtime/pull-request-project-filter";
44 import { pullRequestListEntryId } from "./pullRequestListGroups.logic";
45
46 export interface PullRequestsSearch extends PullRequestListPreferences {
47 readonly selectedUrl?: string;
48 readonly environmentId?: EnvironmentId;
49 readonly projectId?: ProjectId;
50 readonly host?: string | undefined;
51 readonly repository?: string;
52 readonly number?: number;
53 readonly selectedProjectId?: ProjectId | undefined;
54 readonly selectedHost?: string | undefined;
55 readonly selectedEnvironmentId?: EnvironmentId | undefined;
56 }
57
58 const SEARCH_DEBOUNCE_MS = 250;
59 const UNREACHABLE_PHASES: ReadonlySet<EnvironmentConnectionPhase> = new Set([
60 "offline",
61 "reconnecting",
62 "error",
63 "unsupported",
64 ]);
65
66 /** Which servers and projects the page reads, from the URL and what this client knows. */
67 export function usePullRequestScope(
68 search: PullRequestsSearch,
69 hostAvailability: PullRequestHostAvailability,
70 ) {
71 const { environments } = useEnvironments();
72 const allProjects = useProjects();
73 const projectsKnown = useAllEnvironmentShellsBootstrapped();
74 const capableEnvironments = environments
75 .filter((environment) => environment.serverConfig !== null)
76 .toSorted((left, right) => left.environmentId.localeCompare(right.environmentId));
77 const scopedEnvironmentId =
78 capableEnvironments.find((environment) => environment.environmentId === search.environmentId)
79 ?.environmentId ?? null;
80 const knownEnvironmentIds = new Set(environments.map((environment) => environment.environmentId));
81 const environmentIds = capableEnvironments
82 .filter(
83 (environment) =>
84 scopedEnvironmentId === null || environment.environmentId === scopedEnvironmentId,
85 )
86 .map((environment) => environment.environmentId);
87 const environmentKey = pullRequestEnvironmentSetKey(environmentIds);
88 const capabilityKnown = environments.some((environment) => environment.serverConfig !== null);
89 const pullRequestsSupported = environmentIds.length > 0;
90 const projects = allProjects.filter(
91 (project) => !project.isScratch && environmentIds.includes(project.environmentId),
92 );
93 const environmentLabels = new Map(
94 environments.map((environment) => [environment.environmentId, environment.label] as const),
95 );
96 const scopedProjectId = resolveProjectScope(search.projectId, projects, projectsKnown);
97 const scopedProject = findScopedProject(projects, scopedEnvironmentId, scopedProjectId);
98 const scopedProjects = pullRequestFilterProjects(projects, environmentLabels, scopedProject);
99
100 const selectedHost = search.selectedHost ?? search.host;
101 // A named server still connecting is kept named rather than falling back: falling back while it
102 // is merely not ready yet would resolve the project against whatever other server has answered,
103 // which can be the wrong one where two servers share a project id.
104 const selectedEnvironmentId = resolveSelectedEnvironmentId(
105 search.selectedEnvironmentId,
106 knownEnvironmentIds,
107 scopedEnvironmentId,
108 );
109 const projectForRepository =
110 search.repository === undefined
111 ? undefined
112 : findProjectForRepository(projects, {
113 repository: search.repository,
114 host: selectedHost,
115 selectedEnvironmentId,
116 scopedProjectId,
117 scopedEnvironmentId,
118 });
119 const linkedProjectId = resolveProjectScope(search.selectedProjectId, projects, projectsKnown);
120 const selectedProject =
121 linkedProjectId === undefined && search.repository !== undefined
122 ? projectForRepository
123 : findScopedProject(projects, selectedEnvironmentId, linkedProjectId ?? scopedProjectId);
124 const queryEnvironmentIds = resolveQueryEnvironmentIds(
125 environmentIds,
126 projects,
127 scopedProject,
128 scopedProjectId,
129 projectsKnown,
130 );
131 const unreachable = new Set(
132 environments.flatMap((environment) =>
133 UNREACHABLE_PHASES.has(environment.connection.phase) ? [environment.environmentId] : [],
134 ),
135 );
136 const queriesFor = (
137 availability?: PullRequestHostAvailability,
138 ): ReadonlyArray<{
139 readonly environmentId: EnvironmentId;
140 readonly projectIds?: ReadonlyArray<ProjectId>;
141 }> => {
142 const plain = queryEnvironmentIds.map((environmentId) => ({ environmentId }));
143 if (!projectsKnown || scopedProjectId !== undefined) return plain;
144 return pullRequestProjectQueries(projects, queryEnvironmentIds, availability, unreachable);
145 };
146 const environmentQueries = queriesFor(hostAvailability);
147 // What the page reads once a refresh forgets host reads; refresh must refetch these too.
148 const preferredEnvironmentQueries = queriesFor();
149 const assignmentKey = environmentQueries
150 .map(({ environmentId, projectIds }) => `${environmentId}#${projectIds?.join("+") ?? "*"}`)
151 .join("|");
152 // The URL is user-controlled and stands in for the PR link until detail loads.
153 const selectedLink = search.selectedUrl
154 ? sourceControlClients.parseChangeRequestUrl(search.selectedUrl)?.link
155 : undefined;
156 const selectedUrl =
157 selectedLink !== undefined &&
158 selectedLink.number === search.number &&
159 selectedLink.repository.toLowerCase() === search.repository?.toLowerCase()
160 ? search.selectedUrl
161 : undefined;
162 const linkedSelection =
163 search.repository && search.number && selectedProject
164 ? {
165 environmentId: selectedProject.environmentId,
166 repository: search.repository,
167 number: search.number,
168 projectId: selectedProject.id,
169 ...(selectedUrl ? { url: selectedUrl, revealUrl: selectedUrl } : {}),
170 ...(selectedHost ? { host: selectedHost } : {}),
171 }
172 : null;
173 const expectedHosts = (() => {
174 const byHost = new Map<string, PullRequestExpectedHost>();
175 for (const project of projects) {
176 const kind = project.repositoryIdentity?.provider;
177 if (kind === undefined) continue;
178 const host = sourceControlClients.changeRequestHost(project.repositoryIdentity, kind);
179 if (!byHost.has(host)) byHost.set(host, { host, kind });
180 }
181 return [...byHost.values()];
182 })();
183
184 return {
185 capableEnvironments,
186 scopedEnvironmentId,
187 environmentKey,
188 capabilityKnown,
189 pullRequestsSupported,
190 projects,
191 environmentLabels,
192 scopedProjectId,
193 scopedProject,
194 scopedProjects,
195 selectedProject,
196 queryEnvironmentIds,
197 environmentQueries,
198 preferredEnvironmentQueries,
199 assignmentKey,
200 linkedSelection,
201 expectedHosts,
202 projectsKnown,
203 };
204 }
205
206 export function usePullRequestQueryFilters(search: PullRequestsSearch, typedQuery: string) {
207 const [sentQuery, setSentQuery] = useState(typedQuery);
208 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- debounce timer that sends the typed query after SEARCH_DEBOUNCE_MS
209 useEffect(() => {
210 const timer = window.setTimeout(() => setSentQuery(typedQuery), SEARCH_DEBOUNCE_MS);
211 return () => window.clearTimeout(timer);
212 }, [typedQuery]);
213 const typedParsed = parsePullRequestQuery(typedQuery);
214 const sentParsed = parsePullRequestQuery(sentQuery);
215
216 const menuFilters = {
217 ...(search.draft ? { draft: search.draft } : {}),
218 ...(search.review ? { review: search.review } : {}),
219 ...(search.checks ? { checks: search.checks } : {}),
220 ...(search.author ? { author: search.author } : {}),
221 ...(search.labels ? { labels: search.labels.map((label) => [label]) } : {}),
222 };
223 const menuFiltered = Object.keys(menuFilters).length > 0;
224 const filters = { ...menuFilters, ...sentParsed.filters };
225 const hasFilters = Object.keys(filters).length > 0;
226 const localFilters = { ...menuFilters, ...typedParsed.filters };
227 const hasLocalFilters = Object.keys(localFilters).length > 0;
228 return {
229 sentQuery,
230 submitQuery: (query: string) => setSentQuery(query.trim()),
231 querySettled: typedQuery === sentQuery,
232 typedParsed,
233 sentParsed,
234 menuFilters,
235 menuFiltered,
236 filters,
237 hasFilters,
238 localFilters,
239 hasLocalFilters,
240 };
241 }
242
243 /**
244 * The hosts the list has answered for (kept while a host filter narrows the answer), and the
245 * groups as shown with measured sizes, optimistic actions, and the reader's sort.
246 */
247 export function usePullRequestDisplayGroups({
248 answered,
249 host,
250 groups,
251 statsByRow,
252 overrides,
253 state,
254 localFilters,
255 hasLocalFilters,
256 viewers,
257 sort,
258 text,
259 involvement,
260 }: {
261 answered: MergedPullRequestList | null;
262 host: string | undefined;
263 groups: ReadonlyArray<PullRequestGroup<EnvironmentPullRequestEntry>>;
264 statsByRow: PullRequestDiffStats;
265 overrides: ReadonlyMap<string, PullRequestListOverride>;
266 state: PullRequestListState;
267 localFilters: PullRequestListFilters;
268 hasLocalFilters: boolean;
269 viewers: PullRequestListResult["viewers"];
270 sort: PullRequestListSort;
271 text: string;
272 involvement: PullRequestInvolvement;
273 }) {
274 const [hostsState, setHostsState] = useState<{
275 readonly source: MergedPullRequestList | null;
276 readonly host: string | undefined;
277 readonly hosts: PullRequestListResult["providers"];
278 }>({ source: null, host: undefined, hosts: [] });
279 if (answered !== null && (hostsState.source !== answered || hostsState.host !== host)) {
280 setHostsState({
281 source: answered,
282 host,
283 hosts:
284 host === undefined || hostsState.hosts.length === 0 ? answered.providers : hostsState.hosts,
285 });
286 }
287 const hosts = hostsState.hosts;
288 const displayGroups = (() => {
289 const enriched = groups.map((group) => {
290 const overridden = applyPullRequestOverrides(
291 group.entries.map((entry) => withDiffStat(entry, statsByRow)),
292 overrides,
293 pullRequestEntryKey,
294 state,
295 );
296 return {
297 ...group,
298 entries:
299 hasLocalFilters && overrides.size > 0
300 ? overridden.filter(
301 (entry) =>
302 !overrides.has(pullRequestEntryKey(entry)) ||
303 matchesPullRequestFilters(
304 entry,
305 localFilters,
306 pullRequestEntryViewer(entry, viewers),
307 ),
308 )
309 : overridden,
310 };
311 });
312 return sortPullRequestGroups(
313 enriched,
314 sort,
315 text,
316 (entry) =>
317 entry.additions + entry.deletions > 0 || statsByRow.has(pullRequestDiffStatKey(entry)),
318 involvement,
319 );
320 })();
321 const shownCount = displayGroups.reduce((count, group) => count + group.entries.length, 0);
322 const hostActionsOf = pullRequestHostActions(hosts);
323 const closeSweepRows = new Map(
324 displayGroups.flatMap((group) =>
325 group.entries.map(
326 (entry) => [pullRequestEntryKey(entry), { entry, groupKey: group.key }] as const,
327 ),
328 ),
329 );
330 const listedPullRequestsBySurface = new Map(
331 displayGroups.flatMap((group) =>
332 group.entries.map((entry) => [pullRequestListEntryId(entry), entry] as const),
333 ),
334 );
335
336 return {
337 hosts,
338 displayGroups,
339 shownCount,
340 hostActionsOf,
341 closeSweepRows,
342 listedPullRequestsBySurface,
343 };
344 }