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

pullRequestList.ts

346 lines12.8 KB

1import { parsePullRequestQuery } from "@t3tools/client-runtime/pull-request-query";
2import {
3 ProjectId,
4 resolvePullRequestAuthorFilter,
5 type EnvironmentId,
6 type PullRequestListEntry,
7 type PullRequestListInput,
8 type PullRequestListResult,
9} from "@t3tools/contracts";
10import type { PullRequestListControls } from "../../persistence/mobile-preferences";
11​
12export const PR_LIST_PAGE_SIZE = 30;
13export type { PullRequestListControls } from "../../persistence/mobile-preferences";
14export const DEFAULT_PR_LIST_CONTROLS: PullRequestListControls = {
15 state: "open",
16 involvement: "all",
17 filters: {},
18 sort: "updated",
19};
20​
21export function withoutScratchProjectScope(
22 controls: PullRequestListControls,
23 projects: readonly { id: string; environmentId: string; isScratch?: true }[],
24): PullRequestListControls {
25 return projects.some(
26 (project) =>
27 project.isScratch &&
28 project.id === controls.projectId &&
29 project.environmentId === controls.projectEnvironmentId,
30 )
31 ? { ...controls, projectId: undefined, projectEnvironmentId: undefined }
32 : controls;
34​
35export function pullRequestListKey(
36 item: Pick<PullRequestListEntry, "host" | "repository" | "number">,
37) {
38 return `${item.host.toLowerCase()}:${item.repository.toLowerCase()}:${item.number}`;
40​
41export type EnvironmentPullRequestListEntry = PullRequestListEntry & {
42 readonly environmentId: EnvironmentId;
43};
44​
45export const scopedPullRequestListKey = (entry: EnvironmentPullRequestListEntry) =>
46 `${entry.environmentId}:${pullRequestListKey(entry)}`;
47​
48export function pullRequestListRowsAreEqual(
49 previous: EnvironmentPullRequestListEntry,
50 next: EnvironmentPullRequestListEntry,
51) {
52 return (
53 previous === next ||
54 (previous.environmentId === next.environmentId &&
55 previous.projectId === next.projectId &&
56 previous.host === next.host &&
57 previous.repository === next.repository &&
58 previous.number === next.number &&
59 previous.title === next.title &&
60 previous.url === next.url &&
61 previous.state === next.state &&
62 previous.isDraft === next.isDraft &&
63 previous.mergeability === next.mergeability &&
64 previous.baseBranch === next.baseBranch &&
65 previous.updatedAt === next.updatedAt &&
66 previous.additions === next.additions &&
67 previous.deletions === next.deletions &&
68 previous.checksState === next.checksState &&
69 previous.reviewDecision === next.reviewDecision &&
70 previous.viewerReviewRequested === next.viewerReviewRequested &&
71 previous.author?.login === next.author?.login &&
72 previous.author?.avatarUrl === next.author?.avatarUrl &&
73 previous.stack?.position === next.stack?.position &&
74 previous.stack?.size === next.stack?.size &&
75 previous.labels.length === next.labels.length &&
76 previous.labels.every(
77 (label, index) =>
78 label.name === next.labels[index]?.name && label.color === next.labels[index]?.color,
79 ))
80 );
82​
83export function mergeEnvironmentPullRequestPages(
84 sources: readonly { environmentId: EnvironmentId; pages: PullRequestListPages }[],
85) {
86 const viewers: Record<string, string> = {};
87 const localSearchHosts = new Set<string>();
88 const entries: EnvironmentPullRequestListEntry[] = [];
89 const errors = [];
90 for (const { environmentId, pages } of sources) {
91 entries.push(...pages.entries.map((entry) => ({ ...entry, environmentId })));
92 for (const [host, viewer] of Object.entries(pages.head.viewers))
93 viewers[`${environmentId} ${host}`] = viewer;
94 for (const provider of pages.head.providers)
95 if (!provider.searchesOnHost) localSearchHosts.add(`${environmentId} ${provider.host}`);
96 errors.push(...pages.head.errors.map((error) => ({ ...error, environmentId })));
97 }
98 return {
99 entries,
100 viewers,
101 localSearchHosts,
102 errors,
103 continued: sources.some(({ pages }) => pages.continued),
104 };
106​
107export function mergePullRequestListEntries(
108 previous: readonly PullRequestListEntry[],
109 incoming: readonly PullRequestListEntry[],
110) {
111 const entries = new Map(previous.map((entry) => [pullRequestListKey(entry), entry]));
112 for (const entry of incoming) {
113 const key = pullRequestListKey(entry);
114 const held = entries.get(key);
115 if (!held || (entry.observedAt ?? 0) >= (held.observedAt ?? 0)) entries.set(key, entry);
116 }
117 return [...entries.values()].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
119​
120export interface PullRequestListPages {
121 readonly head: PullRequestListResult;
122 readonly entries: readonly PullRequestListEntry[];
123 readonly nextCursors: PullRequestListResult["nextCursors"];
124 readonly truncated: boolean;
125 readonly limit: number;
126 readonly continued: boolean;
128​
129export function pullRequestListHead(
130 previous: PullRequestListPages | null,
131 head: PullRequestListResult,
132): PullRequestListPages {
133 if (previous?.head === head) return previous;
134 return previous?.continued
135 ? { ...previous, head, entries: mergePullRequestListEntries(previous.entries, head.entries) }
136 : {
137 head,
138 entries: head.entries,
139 nextCursors: head.nextCursors,
140 truncated: head.truncated,
141 limit: PR_LIST_PAGE_SIZE,
142 continued: false,
143 };
145​
146export function pullRequestListInput(
147 controls: PullRequestListControls,
148 query: string,
149): PullRequestListInput {
150 const parsed = parsePullRequestQuery(query);
151 return {
152 state: controls.state,
153 involvement: controls.involvement,
154 filters: { ...controls.filters, ...parsed.filters },
155 limit: PR_LIST_PAGE_SIZE,
156 ...(controls.projectId ? { projectId: ProjectId.make(controls.projectId) } : {}),
157 ...(parsed.text ? { query: parsed.text } : {}),
158 };
160​
161export function nextPullRequestListInput(
162 pages: PullRequestListPages,
163 input: PullRequestListInput,
164): PullRequestListInput | null {
165 if (Object.keys(pages.nextCursors).length)
166 return { ...input, limit: PR_LIST_PAGE_SIZE, cursors: pages.nextCursors };
167 return pages.truncated && pages.limit < 500
168 ? { ...input, limit: Math.min(pages.limit + PR_LIST_PAGE_SIZE, 500) }
169 : null;
171​
172export function appendPullRequestListPage(
173 previous: PullRequestListPages,
174 page: PullRequestListResult,
175 input: PullRequestListInput,
176): PullRequestListPages {
177 return {
178 ...previous,
179 entries: mergePullRequestListEntries(previous.entries, page.entries),
180 nextCursors: page.nextCursors,
181 truncated: page.truncated,
182 limit: input.limit ?? PR_LIST_PAGE_SIZE,
183 continued: true,
184 };
186​
187/**
188 * A filter picker's rows: what is picked stays in view, then the loaded rows' values that match,
189 * then the host's answers, each once. The host matched its own way (an author's display name, say),
190 * so its answers are not narrowed again here.
191 */
192const FILTER_CHOICE_LIMIT = 100;
193​
194export function pullRequestFilterChoices(input: {
195 readonly selected: readonly string[];
196 readonly suggestions: readonly string[];
197 readonly hosted: readonly string[];
198 readonly query: string;
199}): readonly string[] {
200 const needle = input.query.trim().toLowerCase();
201 const seen = new Set<string>();
202 const rows: string[] = [];
203 const add = (value: string) => {
204 const key = value.toLowerCase();
205 if (seen.has(key)) return;
206 seen.add(key);
207 rows.push(value);
208 };
209 const loaded = input.suggestions.filter((value) => value.toLowerCase().includes(needle));
210 for (const value of input.selected) add(value);
211 // Loaded matches alone could fill the list, so the host's answers get room after the first half.
212 for (const value of loaded.slice(0, FILTER_CHOICE_LIMIT / 2)) add(value);
213 for (const value of input.hosted) add(value);
214 for (const value of loaded.slice(FILTER_CHOICE_LIMIT / 2)) add(value);
215 return rows.slice(0, FILTER_CHOICE_LIMIT);
217​
218export function pullRequestListFacets(entries: readonly PullRequestListEntry[]) {
219 return {
220 authors: [
221 ...new Set(entries.flatMap((entry) => (entry.author ? [entry.author.login] : []))),
222 ].sort((a, b) => a.localeCompare(b)),
223 labels: [...new Set(entries.flatMap((entry) => entry.labels.map((label) => label.name)))].sort(
224 (a, b) => a.localeCompare(b),
225 ),
226 labelColors: pullRequestLabelColors(entries.flatMap((entry) => entry.labels)),
227 };
229​
230/** Each label's dot color by lowercased name; the first usable color a name carries wins. */
231export function pullRequestLabelColors(
232 labels: readonly { readonly name: string; readonly color: string | null }[],
233): Readonly<Record<string, string>> {
234 const colors: Record<string, string> = {};
235 for (const label of labels) {
236 const key = label.name.toLowerCase();
237 const color = pullRequestLabelColor(label.color);
238 if (color && !(key in colors)) colors[key] = color;
239 }
240 return colors;
242​
243export function filterPullRequestList<
244 Entry extends PullRequestListEntry & { environmentId?: string },
245>(
246 entries: readonly Entry[],
247 controls: PullRequestListControls,
248 viewers: PullRequestListResult["viewers"],
249 query: string,
250 localSearchHosts: ReadonlySet<string>,
251 connectedEnvironmentIds?: ReadonlySet<string>,
252) {
253 const normalize = (value: string) => value.toLowerCase();
254 const parsed = parsePullRequestQuery(query);
255 const words = parsed.text.toLowerCase().split(/\s+/).filter(Boolean);
256 const filters = { ...controls.filters, ...parsed.filters };
257 const filtered = entries.filter((entry) => {
258 if (controls.state !== "all" && entry.state !== controls.state) return false;
259 if (controls.projectId && entry.projectId !== controls.projectId) return false;
260 if (controls.projectEnvironmentId && entry.environmentId !== controls.projectEnvironmentId)
261 return false;
262 const viewerKey = entry.environmentId ? `${entry.environmentId} ${entry.host}` : entry.host;
263 const viewer = viewers[viewerKey];
264 if (controls.involvement === "reviewing" && !entry.viewerReviewRequested) return false;
265 if (
266 controls.involvement === "authored" &&
267 (!viewer || normalize(entry.author?.login ?? "") !== normalize(viewer))
268 )
269 return false;
270 if ((filters.draft === "only" && !entry.isDraft) || (filters.draft === "hide" && entry.isDraft))
271 return false;
272 if (filters.author) {
273 const author = resolvePullRequestAuthorFilter(filters.author, viewer);
274 if (normalize(entry.author?.login ?? "") !== normalize(author)) return false;
275 }
276 if (filters.review && entry.reviewDecision && entry.reviewDecision !== filters.review)
277 return false;
278 if (filters.review === "none" && entry.reviewDecision) return false;
279 if (filters.checks && entry.checksState && entry.checksState !== filters.checks) return false;
280 const labels = new Set(entry.labels.map((label) => normalize(label.name)));
281 if (filters.labels?.some((group) => !group.some((label) => labels.has(normalize(label)))))
282 return false;
283 if (filters.excludedLabels?.some((label) => labels.has(normalize(label)))) return false;
284 if (words.length && localSearchHosts.has(viewerKey)) {
285 const text =
286 `${entry.repository} #${entry.number} ${entry.title} ${entry.author?.login ?? ""} ${entry.headBranch} ${entry.baseBranch} ${entry.labels.map((label) => label.name).join(" ")}`.toLowerCase();
287 if (!words.every((word) => text.includes(word))) return false;
288 }
289 return true;
290 });
291 const reachable = (entry: Entry) =>
292 !connectedEnvironmentIds ||
293 (entry.environmentId !== undefined && connectedEnvironmentIds.has(entry.environmentId));
294 const unique = new Map<string, Entry>();
295 for (const entry of filtered) {
296 const key = pullRequestListKey(entry);
297 const held = unique.get(key);
298 if (!held || (!reachable(held) && reachable(entry))) unique.set(key, entry);
299 }
300 return [...unique.values()].sort((a, b) =>
301 controls.sort === "created"
302 ? b.createdAt.localeCompare(a.createdAt)
303 : controls.sort === "oldest"
304 ? a.updatedAt.localeCompare(b.updatedAt)
305 : b.updatedAt.localeCompare(a.updatedAt),
306 );
308​
309export function pullRequestListReviewStatus(
310 entry: Pick<PullRequestListEntry, "reviewDecision" | "viewerReviewRequested">,
311) {
312 if (entry.reviewDecision === "changes-requested")
313 return {
314 label: "Changes",
315 accessibleLabel: "Changes requested",
316 icon: "person.fill.xmark",
317 tint: "accent-danger-foreground",
318 } as const;
319 if (entry.reviewDecision === "approved")
320 return {
321 label: "Approved",
322 accessibleLabel: "Reviews approved",
323 icon: "person.fill.checkmark",
324 tint: "accent-adaptive-emerald-600-400",
325 } as const;
326 if (entry.viewerReviewRequested)
327 return {
328 label: "Your review",
329 accessibleLabel: "Your review requested",
330 icon: "person.badge.clock",
331 tint: "accent-warning-foreground",
332 } as const;
333 if (entry.reviewDecision === "review-required")
334 return {
335 label: "Review",
336 accessibleLabel: "Review required",
337 icon: "person.badge.clock",
338 tint: "accent-icon-muted",
339 } as const;
340 return null;
342​
343export function pullRequestLabelColor(color: string | null) {
344 const hex = color?.replace(/^#/, "");
345 return hex && /^[\da-f]{6}$/i.test(hex) ? `#${hex}` : null;