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

usePullRequestListView.ts

320 lines11.2 KB

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