Open History to see the last commit
1import * as Schema from "effect/Schema";
2
3import { PullRequestListEntry, PullRequestListResult } from "@t3tools/contracts";
4import type { PullRequestInvolvement, PullRequestListState } from "@t3tools/contracts";
5
6export type PullRequestGroupKey = "reviewRequested" | "authored" | "others";
7
8export interface PullRequestGroup {
9 readonly key: PullRequestGroupKey;
10 readonly label: string;
11 readonly entries: ReadonlyArray<PullRequestListEntry>;
12}
13
14/** The signed-in account per host, as the listing reports it. */
15export type PullRequestViewers = PullRequestListResult["viewers"];
16
17const GROUP_LABELS: Record<PullRequestGroupKey, string> = {
18 reviewRequested: "Review requested",
19 authored: "Authored",
20 others: "Others",
21};
22
23function normalize(value: string | null | undefined): string | null {
24 const trimmed = value?.trim().toLowerCase() ?? "";
25 return trimmed.length > 0 ? trimmed : null;
26}
27
28/**
29 * Authorship is per host, not per provider kind: the same list can hold change requests from
30 * GitHub, GitLab and a GitHub Enterprise install, and the account that owns one says nothing
31 * about the others.
32 */
33function isAuthoredByViewer(entry: PullRequestListEntry, viewers: PullRequestViewers): boolean {
34 const viewer = normalize(viewers[entry.host]);
35 return viewer !== null && normalize(entry.author?.login) === viewer;
36}
37
38/** Free-text filter over the fields a row actually shows, plus `#123` / `123`. */
39export function matchesPullRequestQuery(entry: PullRequestListEntry, query: string): boolean {
40 const normalizedQuery = query.trim().toLowerCase();
41 if (normalizedQuery.length === 0) return true;
42 return `#${entry.number} ${entry.title} ${entry.repository} ${entry.headBranch} ${entry.author?.login ?? ""}`
43 .toLowerCase()
44 .includes(normalizedQuery);
45}
46
47/**
48 * The server returns the involvement superset for a state, so switching between the Reviewing
49 * and Authored tabs never waits on the network.
50 */
51export function filterPullRequestsByInvolvement(
52 entries: ReadonlyArray<PullRequestListEntry>,
53 viewers: PullRequestViewers,
54 involvement: PullRequestInvolvement,
55): ReadonlyArray<PullRequestListEntry> {
56 if (involvement === "reviewing") {
57 return entries.filter((entry) => entry.viewerReviewRequested);
58 }
59 if (involvement === "authored") {
60 return entries.filter((entry) => isAuthoredByViewer(entry, viewers));
61 }
62 return entries;
63}
64
65/**
66 * The rows already read, kept only where the filters now being asked about would keep them.
67 *
68 * Every combination of filters is its own question to the hosts, and asking a new one is no
69 * reason to blank the page: what has been read is narrowed here and stays until the answer for
70 * the new question replaces it. So this may only ever drop rows — a merged pull request cannot
71 * sit under "Open" for the round trip — and what it leaves is a subset of the answer rather than
72 * the answer itself.
73 *
74 * Only the filters a row can be judged by from its own fields. Involvement is left out because
75 * it needs to know who is signed in on each host, and the search text because searching is the
76 * hosts' own answer; both are narrowed where that knowledge already lives.
77 */
78export function narrowPullRequestsToFilters(
79 entries: ReadonlyArray<PullRequestListEntry>,
80 filters: {
81 readonly state: PullRequestListState;
82 readonly projectId: string | undefined;
83 readonly host: string | undefined;
84 },
85): ReadonlyArray<PullRequestListEntry> {
86 return entries.filter(
87 (entry) =>
88 (filters.state === "all" || entry.state === filters.state) &&
89 (filters.projectId === undefined || entry.projectId === filters.projectId) &&
90 (filters.host === undefined || entry.host === filters.host),
91 );
92}
93
94/**
95 * Only relationships the list data actually carries: no "previously reviewed" bucket is
96 * inferred, because the listing has no review history.
97 */
98export function groupPullRequestsByInvolvement(
99 entries: ReadonlyArray<PullRequestListEntry>,
100 viewers: PullRequestViewers,
101): ReadonlyArray<PullRequestGroup> {
102 const buckets: Record<PullRequestGroupKey, PullRequestListEntry[]> = {
103 reviewRequested: [],
104 authored: [],
105 others: [],
106 };
107 for (const entry of entries) {
108 if (isAuthoredByViewer(entry, viewers)) {
109 buckets.authored.push(entry);
110 } else if (entry.viewerReviewRequested) {
111 buckets.reviewRequested.push(entry);
112 } else {
113 buckets.others.push(entry);
114 }
115 }
116 return (["reviewRequested", "authored", "others"] as const)
117 .filter((key) => buckets[key].length > 0)
118 .map((key) => ({ key, label: GROUP_LABELS[key], entries: buckets[key] }));
119}
120
121/** Repository plus number is unique on one host, so the host makes the key unique overall. */
122export function pullRequestEntryKey(entry: PullRequestListEntry): string {
123 return `${entry.host}:${entry.repository}#${entry.number}`;
124}
125
126/**
127 * The priority groups built from the hosts' own answers rather than re-partitioned from the
128 * paginated feed. The feed is sliced by recency, so an older authored or review-requested row
129 * can be missing from its first page and arrive with a later one; grouping the loaded pages
130 * would then move it above rows already read. Here the partitions come whole from their own
131 * server-filtered reads, the feed fills "Others" in its own order, and a continuation can only
132 * append — a row it carries that a partition already holds is dropped rather than moved.
133 */
134export function partitionPullRequestsWithPriority(
135 entries: ReadonlyArray<PullRequestListEntry>,
136 authored: ReadonlyArray<PullRequestListEntry>,
137 reviewRequested: ReadonlyArray<PullRequestListEntry>,
138): ReadonlyArray<PullRequestGroup> {
139 const authoredByKey = new Map(authored.map((entry) => [pullRequestEntryKey(entry), entry]));
140 // A row can be both authored and review-requested; authored wins, as the local grouping has it.
141 const reviewByKey = new Map(
142 reviewRequested.flatMap((entry) => {
143 const key = pullRequestEntryKey(entry);
144 return authoredByKey.has(key) ? [] : [[key, entry] as const];
145 }),
146 );
147 const others: PullRequestListEntry[] = [];
148 for (const entry of entries) {
149 const key = pullRequestEntryKey(entry);
150 // The feed's copy of a partitioned row is at least as fresh — it replaces in place.
151 if (authoredByKey.has(key)) {
152 authoredByKey.set(key, entry);
153 } else if (reviewByKey.has(key)) {
154 reviewByKey.set(key, entry);
155 } else {
156 others.push(entry);
157 }
158 }
159 const byRecency = (left: PullRequestListEntry, right: PullRequestListEntry) =>
160 right.updatedAt.localeCompare(left.updatedAt);
161 return (
162 [
163 { key: "reviewRequested", entries: [...reviewByKey.values()].toSorted(byRecency) },
164 { key: "authored", entries: [...authoredByKey.values()].toSorted(byRecency) },
165 { key: "others", entries: others },
166 ] as const
167 )
168 .filter((group) => group.entries.length > 0)
169 .map((group) => ({ ...group, label: GROUP_LABELS[group.key] }));
170}
171
172export type PullRequestDiffStats = ReadonlyMap<
173 string,
174 { readonly additions: number; readonly deletions: number }
175>;
176
177/**
178 * The line counts held so far, with a new batch merged on. The stats read is keyed by the rows
179 * on screen, so adding or removing one row is a fresh query with nothing in it yet; replacing
180 * the map would blank every count already showing for the round trip. Merging by row identity
181 * keeps them until their replacements arrive.
182 */
183export function mergePullRequestDiffStats(
184 previous: PullRequestDiffStats,
185 stats: ReadonlyArray<{
186 readonly projectId: string;
187 readonly number: number;
188 readonly additions: number;
189 readonly deletions: number;
190 }>,
191): PullRequestDiffStats {
192 if (stats.length === 0) return previous;
193 const next = new Map(previous);
194 for (const stat of stats) {
195 next.set(`${stat.projectId} ${stat.number}`, {
196 additions: stat.additions,
197 deletions: stat.deletions,
198 });
199 }
200 return next;
201}
202
203/** One page is what the list itself starts with, and all a cold start needs to look warm. */
204const SNAPSHOT_MAX_ENTRIES = 99;
205
206type SnapshotStorage = Pick<Storage, "getItem" | "setItem">;
207
208const snapshotStorageKey = (environmentId: string) => `t3.pullRequests.list:${environmentId}`;
209
210/**
211 * The priority groups' own server-filtered answers, carried with the feed. An authored pull
212 * request older than the feed's first page lives only in these, so a snapshot without them
213 * cold-starts into an Authored group missing exactly the rows that made it worth having.
214 */
215export interface PullRequestPartitionsSnapshot {
216 readonly authored: ReadonlyArray<PullRequestListEntry>;
217 readonly reviewing: ReadonlyArray<PullRequestListEntry>;
218}
219
220export interface PullRequestListSnapshot {
221 readonly scope: string;
222 readonly data: PullRequestListResult;
223 readonly partitions?: PullRequestPartitionsSnapshot | undefined;
224}
225
226/**
227 * Decoded with the contract's own schema rather than trusted from a cast: storage is writable
228 * by anything in the origin and by any past version of this app, and one malformed row would
229 * otherwise crash the list on every reload until the key is cleared. A snapshot from before a
230 * schema change is rejected the same way, which is exactly the cold start it would have broken.
231 */
232const decodeSnapshot = Schema.decodeUnknownOption(
233 Schema.Struct({
234 scope: Schema.String,
235 data: PullRequestListResult,
236 // Optional so a snapshot written before the partitions existed still hydrates the feed.
237 partitions: Schema.optional(
238 Schema.Struct({
239 authored: Schema.Array(PullRequestListEntry),
240 reviewing: Schema.Array(PullRequestListEntry),
241 }),
242 ),
243 }),
244);
245
246/**
247 * The last list answered for this environment, brought back across a reload. The registry the
248 * queries live in is recreated with the renderer, so without this a revisit cold-starts into
249 * skeletons even though almost every row is unchanged; hydrated, the stale rows render at once
250 * and the live read reconciles them in place by key. Errors are not carried — a failure is
251 * never cached, and yesterday's is not this morning's.
252 */
253export function readPullRequestListSnapshot(
254 storage: SnapshotStorage | undefined,
255 environmentId: string,
256): PullRequestListSnapshot | null {
257 try {
258 const raw = storage?.getItem(snapshotStorageKey(environmentId));
259 if (!raw) return null;
260 const decoded = decodeSnapshot(JSON.parse(raw));
261 return decoded._tag === "Some" ? decoded.value : null;
262 } catch {
263 return null;
264 }
265}
266
267export function writePullRequestListSnapshot(
268 storage: SnapshotStorage | undefined,
269 environmentId: string,
270 snapshot: PullRequestListSnapshot,
271): void {
272 try {
273 storage?.setItem(
274 snapshotStorageKey(environmentId),
275 JSON.stringify({
276 scope: snapshot.scope,
277 data: {
278 ...snapshot.data,
279 entries: snapshot.data.entries.slice(0, SNAPSHOT_MAX_ENTRIES),
280 // A failure is never cached and yesterday's is not this morning's; a cursor names a
281 // position in a listing the host has long since forgotten.
282 errors: [],
283 nextCursors: {},
284 },
285 ...(snapshot.partitions === undefined
286 ? {}
287 : {
288 partitions: {
289 authored: snapshot.partitions.authored.slice(0, SNAPSHOT_MAX_ENTRIES),
290 reviewing: snapshot.partitions.reviewing.slice(0, SNAPSHOT_MAX_ENTRIES),
291 },
292 }),
293 }),
294 );
295 } catch {
296 // Storage can be full or denied; the snapshot is a convenience, not a record.
297 }
298}
299
300/**
301 * The project scope to actually ask for. A `projectId` in the URL outlives the environment it
302 * came from, and one from elsewhere narrows the listing to nothing — an empty page with no
303 * visible filter explaining it, since the switcher has no such project to show as selected. So
304 * an id the environment does not have is dropped.
305 *
306 * Until `projectsKnown`, the id is kept rather than dropped: an environment that has not
307 * reported yet is not the same as one without the project, and dropping first would show every
308 * project's pull requests for a moment before narrowing back down.
309 */
310export function resolveProjectScope<Id extends string>(
311 projectId: Id | undefined,
312 projects: ReadonlyArray<{ readonly id: string }>,
313 projectsKnown: boolean,
314): Id | undefined {
315 if (projectId === undefined || !projectsKnown) return projectId;
316 return projects.some((project) => project.id === projectId) ? projectId : undefined;
317}
318
319/**
320 * How well a row answers the text that was searched for, as a number to order by.
321 *
322 * Every host searches more than a row shows — GitHub reads bodies and commit messages, GitLab
323 * and Bitbucket read descriptions — so a result can be a real match with nothing on the row to
324 * show for it. Ordering those by recency alone is what puts an apparently unrelated pull request
325 * between two obvious ones. They are still results, so they are still shown; they are shown last,
326 * under the rows whose own words matched.
327 *
328 * The scale is deliberately coarse. It sorts rows into "this is the one", "this mentions it" and
329 * "the host says so", which is as fine a judgement as the row's own fields support.
330 */
331export function scorePullRequestMatch(entry: PullRequestListEntry, query: string): number {
332 const needle = query.trim().toLowerCase();
333 if (needle.length === 0) return 0;
334 const number = needle.replace(/^#/u, "");
335 // Asking for a number is asking for one pull request, and it is the answer or it is not.
336 if (/^\d+$/u.test(number)) return String(entry.number) === number ? 100 : 0;
337
338 const title = entry.title.toLowerCase();
339 const terms = needle.split(/\s+/u).filter((term) => term.length > 0);
340 if (title === needle) return 90;
341 if (title.includes(needle)) return 80;
342 // Every word, in any order: "wizard welcome" is still about the welcome wizard.
343 if (terms.length > 1 && terms.every((term) => title.includes(term))) return 70;
344 if (entry.headBranch.toLowerCase().includes(needle)) return 60;
345 if ((entry.author?.login ?? "").toLowerCase().includes(needle)) return 50;
346 if (entry.repository.toLowerCase().includes(needle)) return 40;
347 if (terms.some((term) => title.includes(term))) return 30;
348 // The host matched something this row does not show — a description, a comment, a commit.
349 return 10;
350}
351
352/**
353 * Search results in the order they answer the question, most convincing first, and by recency
354 * among equals. Only for a search: without one, a listing is a timeline and recency is the order.
355 */
356export function rankPullRequestMatches(
357 entries: ReadonlyArray<PullRequestListEntry>,
358 query: string,
359): ReadonlyArray<PullRequestListEntry> {
360 if (query.trim().length === 0) return entries;
361 return entries.toSorted((left, right) => {
362 const byScore = scorePullRequestMatch(right, query) - scorePullRequestMatch(left, query);
363 return byScore !== 0 ? byScore : right.updatedAt.localeCompare(left.updatedAt);
364 });
365}
366
367/**
368 * A row with the line counts that arrived after it did. Only where the host left them out — a
369 * listing that carried them is not second-guessed — and only where they have arrived, since a row
370 * draws perfectly well without them in the meantime.
371 */
372export function withDiffStat(
373 entry: PullRequestListEntry,
374 statsByRow: ReadonlyMap<string, { readonly additions: number; readonly deletions: number }>,
375): PullRequestListEntry {
376 if (entry.additions !== 0 || entry.deletions !== 0) return entry;
377 const stat = statsByRow.get(`${entry.projectId} ${entry.number}`);
378 return stat === undefined ? entry : { ...entry, ...stat };
379}