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

composerPullRequestMatches.ts

76 lines2.7 KB

1import type { ThreadPullRequestLink } from "@t3tools/contracts";
2​
3import { visibleThreadPullRequests } from "./threadPullRequests.ts";
4​
5export interface ComposerPullRequestMatch {
6 readonly number: number;
7 readonly projectId: string;
8 readonly repository: string;
9 readonly updatedAt: string;
11​
12export function composerPullRequestsFromLinks(
13 links: ReadonlyArray<ThreadPullRequestLink>,
14 projectId: string,
15) {
16 return visibleThreadPullRequests(links).flatMap((link) =>
17 link.snapshot === null
18 ? []
19 : [
20 {
21 projectId,
22 repository: link.repository,
23 number: link.number,
24 url: link.url,
25 title: link.snapshot.title,
26 headBranch: link.snapshot.headBranch,
27 baseBranch: link.snapshot.baseBranch,
28 state: link.snapshot.state,
29 isDraft: link.snapshot.isDraft,
30 updatedAt: link.snapshot.updatedAt ?? link.linkedAt,
31 },
32 ],
33 );
35​
36export function filterComposerPullRequestMatches<
37 Entry extends ComposerPullRequestMatch,
38 Linked extends ComposerPullRequestMatch = never,
39>(input: {
40 readonly entries: ReadonlyArray<Entry>;
41 readonly linked?: ReadonlyArray<Linked>;
42 readonly projectId: string;
43 readonly repository: string;
44 readonly query: string;
45 readonly limit: number;
46}): ReadonlyArray<Entry | Linked> {
47 const repository = input.repository.trim().toLowerCase();
48 const keyOf = (entry: ComposerPullRequestMatch) =>
49 `${entry.repository.trim().toLowerCase()}#${entry.number}`;
50 const linked = (input.linked ?? []).filter((entry) => String(entry.number).includes(input.query));
51 const linkedKeys = new Set(linked.map(keyOf));
52 const matchingEntries = input.entries.filter(
53 (entry) =>
54 entry.projectId === input.projectId &&
55 entry.repository.trim().toLowerCase() === repository &&
56 String(entry.number).includes(input.query),
57 );
58 const uniqueEntries = new Map<string, Entry | Linked>();
59 for (const entry of [...matchingEntries, ...linked]) {
60 if (!uniqueEntries.has(keyOf(entry))) {
61 uniqueEntries.set(keyOf(entry), entry);
62 }
63 }
64 const isExactMatch = (entry: ComposerPullRequestMatch) => String(entry.number) === input.query;
65 const isLinked = (entry: ComposerPullRequestMatch) => linkedKeys.has(keyOf(entry));
66 // `.sort()` on a copy, not `.toSorted()`: this runs on Hermes, which has no ES2023 array
67 // methods, and reaching for one here crashed the composer as the suggestions loaded.
68 return [...uniqueEntries.values()]
69 .sort(
70 (left, right) =>
71 Number(isExactMatch(right)) - Number(isExactMatch(left)) ||
72 Number(isLinked(right)) - Number(isLinked(left)) ||
73 right.updatedAt.localeCompare(left.updatedAt),
74 )
75 .slice(0, input.limit);