Open History to see the last commit
1import type { PullRequestFileViewedState, PullRequestFilesViewedResult } from "@t3tools/contracts";
2
3export type FileViewedStates = ReadonlyMap<string, PullRequestFileViewedState>;
4
5export type FileViewedOverlay = ReadonlyMap<string, boolean>;
6
7export function toFileViewedStates(
8 result: PullRequestFilesViewedResult | null,
9): FileViewedStates | null {
10 if (result === null) return null;
11 return new Map(result.files.map((file) => [file.path, file.state]));
12}
13
14function isViewedState(state: PullRequestFileViewedState | undefined): boolean {
15 return state === "viewed";
16}
17
18export function isStaleViewedState(state: PullRequestFileViewedState | undefined): boolean {
19 return state === "dismissed";
20}
21
22export function isFileViewed(
23 path: string,
24 states: FileViewedStates | null,
25 overlay: FileViewedOverlay,
26): boolean {
27 const pressed = overlay.get(path);
28 return pressed ?? isViewedState(states?.get(path));
29}
30
31/**
32 * A press is held until a read that could have seen it comes back, rather than cleared when the
33 * write succeeds: that read is a separate round trip, and dropping the press in between flashes
34 * the checkbox back.
35 */
36export function settleFileViewedOverlay(
37 overlay: FileViewedOverlay,
38 states: FileViewedStates | null,
39 pending: ReadonlySet<string>,
40 answered: ReadonlySet<string>,
41): FileViewedOverlay {
42 if (states === null || overlay.size === 0) return overlay;
43 const next = new Map(overlay);
44 for (const [path, pressed] of overlay) {
45 if (pending.has(path)) continue;
46 if (answered.has(path) || isViewedState(states.get(path)) === pressed) next.delete(path);
47 }
48 return next.size === overlay.size ? overlay : next;
49}
50
51/**
52 * `owned` are the paths that request still answers for, which keeps a failure from reaching past
53 * its own presses: a path pressed again since belongs to a later request or to the next flush,
54 * and putting that box back to the host's answer would take a press out from under the reader's
55 * hand.
56 */
57export function revertFileViewedOverlay(
58 overlay: FileViewedOverlay,
59 batch: ReadonlyArray<{ readonly path: string; readonly viewed: boolean }>,
60 owned: ReadonlySet<string>,
61): FileViewedOverlay {
62 const next = new Map(overlay);
63 for (const { path, viewed } of batch) {
64 if (!owned.has(path)) continue;
65 if (next.get(path) === viewed) next.delete(path);
66 }
67 return next.size === overlay.size ? overlay : next;
68}
69
70export function toFileViewedBatch(
71 overlay: FileViewedOverlay,
72): ReadonlyArray<{ readonly path: string; readonly viewed: boolean }> {
73 return [...overlay].map(([path, viewed]) => ({ path, viewed }));
74}