@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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