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