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

usePullRequestListView.ts

332 lines11.8 KB

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