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