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

pullRequestList.ts

473 lines17.2 KB

1import { parsePullRequestQuery } from "@t3tools/client-runtime/pull-request-query";
2import {
3 ProjectId,
4 resolvePullRequestAuthorFilter,
5 type EnvironmentId,
6 type PullRequestDiffStat,
7 type PullRequestListEntry,
8 type PullRequestListInput,
9 type PullRequestListResult,
10 type PullRequestListStatsInput,
11} from "@t3tools/contracts";
12import type { PullRequestListControls } from "../../persistence/mobile-preferences";
13​
14export const PR_LIST_PAGE_SIZE = 30;
15export type { PullRequestListControls } from "../../persistence/mobile-preferences";
16export const DEFAULT_PR_LIST_CONTROLS: PullRequestListControls = {
17 state: "open",
18 involvement: "all",
19 filters: {},
20 sort: "updated",
21};
22​
23export function withoutScratchProjectScope(
24 controls: PullRequestListControls,
25 projects: readonly { id: string; environmentId: string; isScratch?: true }[],
26): PullRequestListControls {
27 return projects.some(
28 (project) =>
29 project.isScratch &&
30 project.id === controls.projectId &&
31 project.environmentId === controls.projectEnvironmentId,
32 )
33 ? { ...controls, projectId: undefined, projectEnvironmentId: undefined }
34 : controls;
36​
37export function pullRequestListKey(
38 item: Pick<PullRequestListEntry, "host" | "repository" | "number">,
39) {
40 return `${item.host.toLowerCase()}:${item.repository.toLowerCase()}:${item.number}`;
42​
43export type EnvironmentPullRequestListEntry = PullRequestListEntry & {
44 readonly environmentId: EnvironmentId;
45};
46​
47export const scopedPullRequestListKey = (entry: EnvironmentPullRequestListEntry) =>
48 `${entry.environmentId}:${pullRequestListKey(entry)}`;
49​
50export const pullRequestStatKey = (
51 row: Pick<PullRequestDiffStat, "projectId" | "repository" | "number">,
52) => `${row.projectId}:${row.repository}:${row.number}`;
53​
54/**
55 * Diff stats an environment has answered, the stats query that answered each, and each row's
56 * `updatedAt` as its list last answered it.
57 */
58export interface PullRequestStatsCache {
59 readonly stats: ReadonlyMap<string, PullRequestDiffStat>;
60 readonly answeredBy: ReadonlyMap<string, PullRequestListStatsInput>;
61 readonly updatedAt: ReadonlyMap<string, string>;
63​
64export const EMPTY_PULL_REQUEST_STATS_CACHE: PullRequestStatsCache = {
65 stats: new Map(),
66 answeredBy: new Map(),
67 updatedAt: new Map(),
68};
69​
70/**
71 * Records the rows a list answered. Stats carry no head, so a row whose `updatedAt` moved (a push,
72 * among other changes) drops its cached stat, and the stats queries that answered it are returned
73 * to refresh: one can still be fresh and would otherwise answer the row's next read with the old
74 * counts.
75 */
76export function withListedPullRequests(
77 cache: PullRequestStatsCache,
78 entries: readonly Pick<
79 PullRequestListEntry,
80 "projectId" | "repository" | "number" | "updatedAt"
81 >[],
82): {
83 readonly cache: PullRequestStatsCache;
84 readonly refresh: readonly PullRequestListStatsInput[];
85} {
86 const moved = entries.filter(
87 (entry) => cache.updatedAt.get(pullRequestStatKey(entry)) !== entry.updatedAt,
88 );
89 if (!moved.length) return { cache, refresh: [] };
90 const stats = new Map(cache.stats);
91 const answeredBy = new Map(cache.answeredBy);
92 const updatedAt = new Map(cache.updatedAt);
93 const refresh = new Set<PullRequestListStatsInput>();
94 for (const entry of moved) {
95 const key = pullRequestStatKey(entry);
96 const query = answeredBy.get(key);
97 if (query) refresh.add(query);
98 stats.delete(key);
99 answeredBy.delete(key);
100 updatedAt.set(key, entry.updatedAt);
101 }
102 return { cache: { stats, answeredBy, updatedAt }, refresh: [...refresh] };
104​
105export function withAnsweredPullRequestStats(
106 cache: PullRequestStatsCache,
107 input: PullRequestListStatsInput,
108 answered: readonly PullRequestDiffStat[],
109): PullRequestStatsCache {
110 const stats = new Map(cache.stats);
111 const answeredBy = new Map(cache.answeredBy);
112 for (const row of answered) {
113 stats.set(pullRequestStatKey(row), row);
114 answeredBy.set(pullRequestStatKey(row), input);
115 }
116 return { ...cache, stats, answeredBy };
118​
119/**
120 * Fills rows that have no diff stat yet from the stats answers on screen. Returns `entries`
121 * itself when no row changes, so the list keeps its identity across renders.
122 */
123export function withShownPullRequestStats(
124 entries: readonly EnvironmentPullRequestListEntry[],
125 answers: readonly {
126 readonly environmentId: EnvironmentId;
127 readonly stats: readonly PullRequestDiffStat[];
128 }[],
129): readonly EnvironmentPullRequestListEntry[] {
130 const shown = new Map(
131 answers.flatMap(({ environmentId, stats }) =>
132 stats.map((row) => [`${environmentId}:${pullRequestStatKey(row)}`, row] as const),
133 ),
134 );
135 if (!shown.size) return entries;
136 let changed = false;
137 const next = entries.map((entry) => {
138 const stat = shown.get(`${entry.environmentId}:${pullRequestStatKey(entry)}`);
139 if (!stat || entry.additions + entry.deletions !== 0) return entry;
140 if (stat.additions + stat.deletions === 0) return entry;
141 changed = true;
142 return { ...entry, additions: stat.additions, deletions: stat.deletions };
143 });
144 return changed ? next : entries;
146​
147export function pullRequestListRowsAreEqual(
148 previous: EnvironmentPullRequestListEntry,
149 next: EnvironmentPullRequestListEntry,
150) {
151 return (
152 previous === next ||
153 (previous.environmentId === next.environmentId &&
154 previous.projectId === next.projectId &&
155 previous.host === next.host &&
156 previous.repository === next.repository &&
157 previous.number === next.number &&
158 previous.title === next.title &&
159 previous.url === next.url &&
160 previous.state === next.state &&
161 previous.isDraft === next.isDraft &&
162 previous.mergeability === next.mergeability &&
163 previous.baseBranch === next.baseBranch &&
164 previous.updatedAt === next.updatedAt &&
165 previous.additions === next.additions &&
166 previous.deletions === next.deletions &&
167 previous.checksState === next.checksState &&
168 previous.reviewDecision === next.reviewDecision &&
169 previous.viewerReviewRequested === next.viewerReviewRequested &&
170 previous.author?.login === next.author?.login &&
171 previous.author?.avatarUrl === next.author?.avatarUrl &&
172 previous.stack?.position === next.stack?.position &&
173 previous.stack?.size === next.stack?.size &&
174 previous.labels.length === next.labels.length &&
175 previous.labels.every(
176 (label, index) =>
177 label.name === next.labels[index]?.name && label.color === next.labels[index]?.color,
178 ))
179 );
181​
182export function mergeEnvironmentPullRequestPages(
183 sources: readonly { environmentId: EnvironmentId; pages: PullRequestListPages }[],
184) {
185 const viewers: Record<string, string> = {};
186 const localSearchHosts = new Set<string>();
187 const entries: EnvironmentPullRequestListEntry[] = [];
188 const errors = [];
189 for (const { environmentId, pages } of sources) {
190 entries.push(...pages.entries.map((entry) => ({ ...entry, environmentId })));
191 for (const [host, viewer] of Object.entries(pages.head.viewers))
192 viewers[`${environmentId} ${host}`] = viewer;
193 for (const provider of pages.head.providers)
194 if (!provider.searchesOnHost) localSearchHosts.add(`${environmentId} ${provider.host}`);
195 errors.push(...pages.head.errors.map((error) => ({ ...error, environmentId })));
196 }
197 return {
198 entries,
199 viewers,
200 localSearchHosts,
201 errors,
202 continued: sources.some(({ pages }) => pages.continued),
203 };
205​
206export function mergePullRequestListEntries(
207 previous: readonly PullRequestListEntry[],
208 incoming: readonly PullRequestListEntry[],
209) {
210 const entries = new Map(previous.map((entry) => [pullRequestListKey(entry), entry]));
211 for (const entry of incoming) {
212 const key = pullRequestListKey(entry);
213 const held = entries.get(key);
214 if (!held || (entry.observedAt ?? 0) >= (held.observedAt ?? 0)) entries.set(key, entry);
215 }
216 return [...entries.values()].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
218​
219export interface PullRequestListPages {
220 readonly head: PullRequestListResult;
221 readonly entries: readonly PullRequestListEntry[];
222 readonly nextCursors: PullRequestListResult["nextCursors"];
223 readonly truncated: boolean;
224 readonly limit: number;
225 readonly continued: boolean;
227​
228export function pullRequestListHead(
229 previous: PullRequestListPages | null,
230 head: PullRequestListResult,
231): PullRequestListPages {
232 if (previous?.head === head) return previous;
233 return previous?.continued
234 ? { ...previous, head, entries: mergePullRequestListEntries(previous.entries, head.entries) }
235 : {
236 head,
237 entries: head.entries,
238 nextCursors: head.nextCursors,
239 truncated: head.truncated,
240 limit: PR_LIST_PAGE_SIZE,
241 continued: false,
242 };
244​
245/** The recorded pages with the current list head on top; before any answer is recorded, the head alone. */
246export function shownPullRequestListPages(
247 recorded: PullRequestListPages | null,
248 head: PullRequestListResult | null,
249): PullRequestListPages | null {
250 return head ? pullRequestListHead(recorded, head) : recorded;
252​
253export function patchPullRequestListEntry(
254 recorded: PullRequestListPages | null,
255 head: PullRequestListResult | null,
256 entry: PullRequestListEntry,
257 patch: Partial<PullRequestListEntry>,
258 observedAt: number,
259): PullRequestListPages | null {
260 const pages = shownPullRequestListPages(recorded, head);
261 return (
262 pages && {
263 ...pages,
264 entries: pages.entries.map((row) =>
265 pullRequestListKey(row) === pullRequestListKey(entry)
266 ? { ...row, ...patch, observedAt }
267 : row,
268 ),
269 }
270 );
272​
273export function pullRequestListInput(
274 controls: PullRequestListControls,
275 query: string,
276): PullRequestListInput {
277 const parsed = parsePullRequestQuery(query);
278 return {
279 state: controls.state,
280 involvement: controls.involvement,
281 filters: { ...controls.filters, ...parsed.filters },
282 limit: PR_LIST_PAGE_SIZE,
283 ...(controls.projectId ? { projectId: ProjectId.make(controls.projectId) } : {}),
284 ...(parsed.text ? { query: parsed.text } : {}),
285 };
287​
288export function nextPullRequestListInput(
289 pages: PullRequestListPages,
290 input: PullRequestListInput,
291): PullRequestListInput | null {
292 if (Object.keys(pages.nextCursors).length)
293 return { ...input, limit: PR_LIST_PAGE_SIZE, cursors: pages.nextCursors };
294 return pages.truncated && pages.limit < 500
295 ? { ...input, limit: Math.min(pages.limit + PR_LIST_PAGE_SIZE, 500) }
296 : null;
298​
299export function appendPullRequestListPage(
300 previous: PullRequestListPages,
301 page: PullRequestListResult,
302 input: PullRequestListInput,
303): PullRequestListPages {
304 return {
305 ...previous,
306 entries: mergePullRequestListEntries(previous.entries, page.entries),
307 nextCursors: page.nextCursors,
308 truncated: page.truncated,
309 limit: input.limit ?? PR_LIST_PAGE_SIZE,
310 continued: true,
311 };
313​
314/**
315 * A filter picker's rows: what is picked stays in view, then the loaded rows' values that match,
316 * then the host's answers, each once. The host matched its own way (an author's display name, say),
317 * so its answers are not narrowed again here.
318 */
319const FILTER_CHOICE_LIMIT = 100;
320​
321export function pullRequestFilterChoices(input: {
322 readonly selected: readonly string[];
323 readonly suggestions: readonly string[];
324 readonly hosted: readonly string[];
325 readonly query: string;
326}): readonly string[] {
327 const needle = input.query.trim().toLowerCase();
328 const seen = new Set<string>();
329 const rows: string[] = [];
330 const add = (value: string) => {
331 const key = value.toLowerCase();
332 if (seen.has(key)) return;
333 seen.add(key);
334 rows.push(value);
335 };
336 const loaded = input.suggestions.filter((value) => value.toLowerCase().includes(needle));
337 for (const value of input.selected) add(value);
338 // Loaded matches alone could fill the list, so the host's answers get room after the first half.
339 for (const value of loaded.slice(0, FILTER_CHOICE_LIMIT / 2)) add(value);
340 for (const value of input.hosted) add(value);
341 for (const value of loaded.slice(FILTER_CHOICE_LIMIT / 2)) add(value);
342 return rows.slice(0, FILTER_CHOICE_LIMIT);
344​
345export function pullRequestListFacets(entries: readonly PullRequestListEntry[]) {
346 return {
347 authors: [
348 ...new Set(entries.flatMap((entry) => (entry.author ? [entry.author.login] : []))),
349 ].sort((a, b) => a.localeCompare(b)),
350 labels: [...new Set(entries.flatMap((entry) => entry.labels.map((label) => label.name)))].sort(
351 (a, b) => a.localeCompare(b),
352 ),
353 labelColors: pullRequestLabelColors(entries.flatMap((entry) => entry.labels)),
354 };
356​
357/** Each label's dot color by lowercased name; the first usable color a name carries wins. */
358export function pullRequestLabelColors(
359 labels: readonly { readonly name: string; readonly color: string | null }[],
360): Readonly<Record<string, string>> {
361 const colors: Record<string, string> = {};
362 for (const label of labels) {
363 const key = label.name.toLowerCase();
364 const color = pullRequestLabelColor(label.color);
365 if (color && !(key in colors)) colors[key] = color;
366 }
367 return colors;
369​
370export function filterPullRequestList<
371 Entry extends PullRequestListEntry & { environmentId?: string },
372>(
373 entries: readonly Entry[],
374 controls: PullRequestListControls,
375 viewers: PullRequestListResult["viewers"],
376 query: string,
377 localSearchHosts: ReadonlySet<string>,
378 connectedEnvironmentIds?: ReadonlySet<string>,
379) {
380 const normalize = (value: string) => value.toLowerCase();
381 const parsed = parsePullRequestQuery(query);
382 const words = parsed.text.toLowerCase().split(/\s+/).filter(Boolean);
383 const filters = { ...controls.filters, ...parsed.filters };
384 const filtered = entries.filter((entry) => {
385 if (controls.state !== "all" && entry.state !== controls.state) return false;
386 if (controls.projectId && entry.projectId !== controls.projectId) return false;
387 if (controls.projectEnvironmentId && entry.environmentId !== controls.projectEnvironmentId)
388 return false;
389 const viewerKey = entry.environmentId ? `${entry.environmentId} ${entry.host}` : entry.host;
390 const viewer = viewers[viewerKey];
391 if (controls.involvement === "reviewing" && !entry.viewerReviewRequested) return false;
392 if (
393 controls.involvement === "authored" &&
394 (!viewer || normalize(entry.author?.login ?? "") !== normalize(viewer))
395 )
396 return false;
397 if ((filters.draft === "only" && !entry.isDraft) || (filters.draft === "hide" && entry.isDraft))
398 return false;
399 if (filters.author) {
400 const author = resolvePullRequestAuthorFilter(filters.author, viewer);
401 if (normalize(entry.author?.login ?? "") !== normalize(author)) return false;
402 }
403 if (filters.review && entry.reviewDecision && entry.reviewDecision !== filters.review)
404 return false;
405 if (filters.review === "none" && entry.reviewDecision) return false;
406 if (filters.checks && entry.checksState && entry.checksState !== filters.checks) return false;
407 const labels = new Set(entry.labels.map((label) => normalize(label.name)));
408 if (filters.labels?.some((group) => !group.some((label) => labels.has(normalize(label)))))
409 return false;
410 if (filters.excludedLabels?.some((label) => labels.has(normalize(label)))) return false;
411 if (words.length && localSearchHosts.has(viewerKey)) {
412 const text =
413 `${entry.repository} #${entry.number} ${entry.title} ${entry.author?.login ?? ""} ${entry.headBranch} ${entry.baseBranch} ${entry.labels.map((label) => label.name).join(" ")}`.toLowerCase();
414 if (!words.every((word) => text.includes(word))) return false;
415 }
416 return true;
417 });
418 const reachable = (entry: Entry) =>
419 !connectedEnvironmentIds ||
420 (entry.environmentId !== undefined && connectedEnvironmentIds.has(entry.environmentId));
421 const unique = new Map<string, Entry>();
422 for (const entry of filtered) {
423 const key = pullRequestListKey(entry);
424 const held = unique.get(key);
425 if (!held || (!reachable(held) && reachable(entry))) unique.set(key, entry);
426 }
427 return [...unique.values()].sort((a, b) =>
428 controls.sort === "created"
429 ? b.createdAt.localeCompare(a.createdAt)
430 : controls.sort === "oldest"
431 ? a.updatedAt.localeCompare(b.updatedAt)
432 : b.updatedAt.localeCompare(a.updatedAt),
433 );
435​
436export function pullRequestListReviewStatus(
437 entry: Pick<PullRequestListEntry, "reviewDecision" | "viewerReviewRequested">,
438) {
439 if (entry.reviewDecision === "changes-requested")
440 return {
441 label: "Changes",
442 accessibleLabel: "Changes requested",
443 icon: "person.fill.xmark",
444 tint: "accent-danger-foreground",
445 } as const;
446 if (entry.reviewDecision === "approved")
447 return {
448 label: "Approved",
449 accessibleLabel: "Reviews approved",
450 icon: "person.fill.checkmark",
451 tint: "accent-adaptive-emerald-600-400",
452 } as const;
453 if (entry.viewerReviewRequested)
454 return {
455 label: "Your review",
456 accessibleLabel: "Your review requested",
457 icon: "person.badge.clock",
458 tint: "accent-warning-foreground",
459 } as const;
460 if (entry.reviewDecision === "review-required")
461 return {
462 label: "Review",
463 accessibleLabel: "Review required",
464 icon: "person.badge.clock",
465 tint: "accent-icon-muted",
466 } as const;
467 return null;
469​
470export function pullRequestLabelColor(color: string | null) {
471 const hex = color?.replace(/^#/, "");
472 return hex && /^[\da-f]{6}$/i.test(hex) ? `#${hex}` : null;