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
31export function countViewedFiles(
32 states: FileViewedStates | null,
33 overlay: FileViewedOverlay,
34): number {
35 let count = 0;
36 for (const [path, state] of states ?? []) {
37 if (overlay.get(path) ?? isViewedState(state)) count++;
38 }
39 for (const [path, viewed] of overlay) {
40 if (viewed && !states?.has(path)) count++;
41 }
42 return count;
43}
44
45/** Retain presses until a read could have observed the write. */
46export function settleFileViewedOverlay(
47 overlay: FileViewedOverlay,
48 states: FileViewedStates | null,
49 pending: ReadonlySet<string>,
50 answered: ReadonlySet<string>,
51): FileViewedOverlay {
52 if (states === null || overlay.size === 0) return overlay;
53 const next = new Map(overlay);
54 for (const [path, pressed] of overlay) {
55 if (pending.has(path)) continue;
56 if (answered.has(path) || isViewedState(states.get(path)) === pressed) next.delete(path);
57 }
58 return next.size === overlay.size ? overlay : next;
59}
60
61/** Revert only owned paths; later presses belong to other requests. */
62export function revertFileViewedOverlay(
63 overlay: FileViewedOverlay,
64 batch: ReadonlyArray<{ readonly path: string; readonly viewed: boolean }>,
65 owned: ReadonlySet<string>,
66): FileViewedOverlay {
67 const next = new Map(overlay);
68 for (const { path, viewed } of batch) {
69 if (!owned.has(path)) continue;
70 if (next.get(path) === viewed) next.delete(path);
71 }
72 return next.size === overlay.size ? overlay : next;
73}
74
75export interface FileViewedPress {
76 readonly viewed: boolean;
77 readonly revision: string | undefined;
78}
79
80export function toFileViewedBatch(
81 presses: ReadonlyMap<string, FileViewedPress>,
82): ReadonlyArray<{ readonly path: string; readonly viewed: boolean; readonly revision?: string }> {
83 return [...presses].map(([path, { viewed, revision }]) =>
84 revision === undefined ? { path, viewed } : { path, viewed, revision },
85 );
86}