Open History to see the last commit
1import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
2import type { EnvironmentId, PullRequestRef } from "@t3tools/contracts";
3import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4
5import { pullRequestEnvironment } from "~/state/pullRequests";
6import { useEnvironmentQuery } from "~/state/query";
7import { useAtomCommand } from "~/state/use-atom-command";
8
9import { toastManager } from "../ui/toast";
10import {
11 countViewedFiles,
12 isFileViewed,
13 isStaleViewedState,
14 revertFileViewedOverlay,
15 settleFileViewedOverlay,
16 toFileViewedBatch,
17 toFileViewedStates,
18 type FileViewedOverlay,
19 type FileViewedStates,
20} from "./pullRequestFilesViewed.logic";
21
22/**
23 * How long presses gather before the host is told. Long enough that ticking down a file list
24 * costs one request rather than one per file, short enough that a reader who ticks one file and
25 * closes the tab has already been recorded.
26 */
27const FLUSH_DELAY_MS = 400;
28
29const NO_OVERLAY: FileViewedOverlay = new Map();
30
31export interface PullRequestFilesViewedView {
32 /** Whether anything remembers this at all, which is what hides the whole control. */
33 readonly enabled: boolean;
34 readonly isViewed: (path: string) => boolean;
35 /** This file has been pushed to since it was cleared. */
36 readonly isStale: (path: string) => boolean;
37 readonly setViewed: (path: string, viewed: boolean) => void;
38 /** How many of the files on screen are ticked off. */
39 readonly viewedCount: number;
40 /** The host had more files than the read covered, so the count above may be short. */
41 readonly truncated: boolean;
42 /** The host has answered at least once, so `isViewed` reflects its marks and not their absence. */
43 readonly ready: boolean;
44 /**
45 * Why the marks could not be read, when they could not. The boxes fall back to the last answer
46 * there was, or to empty when there has not been one, and neither of those says so on its own:
47 * a reader who sees every box unticked has no way to tell a fresh review from a failed read.
48 */
49 readonly error: string | null;
50 /** Re-ask the host, for the page's refresh button, which goes around the host's cache. */
51 readonly refresh: () => void;
52}
53
54/**
55 * Which files this reader has already cleared. The marks live on the server rather than in this
56 * tab, so a review carried on from another machine picks up where it was left. Presses show
57 * immediately and are held over the server's answer until a read that could have seen them comes
58 * back, so the checkbox never waits on a round trip and never outlasts the record behind it.
59 */
60export function usePullRequestFilesViewed(options: {
61 readonly environmentId: EnvironmentId;
62 readonly reference: PullRequestRef;
63 readonly enabled: boolean;
64 /** The paths on screen, which is what the counter counts. */
65 readonly paths: ReadonlyArray<string>;
66}): PullRequestFilesViewedView {
67 const { environmentId, reference, enabled, paths } = options;
68 const query = useEnvironmentQuery(
69 enabled ? pullRequestEnvironment.filesViewed({ environmentId, input: reference }) : null,
70 );
71 const refresh = query.refresh;
72 // `query.data` holds the last answer through a failure, so the boxes stay where the host last
73 // put them rather than emptying under the reader; the error travels with them, because ticks
74 // that stopped being refreshed look exactly like ticks that are current.
75 const states = useMemo(() => toFileViewedStates(query.data), [query.data]);
76 const truncated = query.data?.truncated === true;
77 const error = query.error;
78 const [overlay, setOverlay] = useState<FileViewedOverlay>(NO_OVERLAY);
79 const setFilesViewed = useAtomCommand(pullRequestEnvironment.setFilesViewed, {
80 reportFailure: false,
81 });
82
83 // Presses waiting for the next flush, and, for every path a request is already carrying, which
84 // request that is. A path pressed again while its request is out belongs to the later request
85 // from then on, and the earlier one stops answering for it. Both are refs rather than state:
86 // nothing on screen reads them, and the flush must see the latest.
87 const queued = useRef<Map<string, boolean>>(new Map());
88 const sentBy = useRef<Map<string, number>>(new Map());
89 const requests = useRef(0);
90 const flushTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
91
92 // Everything held here belongs to one change request on one environment. The environment is
93 // part of that: two of them can hand out the same project id, and a press made against one
94 // must never be answered for by the other.
95 const scopeKey = `${environmentId} ${reference.projectId} ${reference.repository} ${reference.number}`;
96 const scope = useRef(scopeKey);
97
98 // The host's answer as it stood when a completed write was acknowledged, per path. The first
99 // answer that differs from it is the first read that could have seen the write, which is what
100 // retires the press rather than the host happening to agree with it.
101 const answeredFrom = useRef<Map<string, FileViewedStates | null>>(new Map());
102 const statesRef = useRef(states);
103 statesRef.current = states;
104
105 useEffect(() => {
106 const pending = new Set([...queued.current.keys(), ...sentBy.current.keys()]);
107 const answered = new Set<string>();
108 for (const [path, from] of answeredFrom.current) {
109 if (pending.has(path) || from === states) continue;
110 answered.add(path);
111 answeredFrom.current.delete(path);
112 }
113 setOverlay((current) => settleFileViewedOverlay(current, states, pending, answered));
114 }, [states]);
115
116 const flush = useCallback(() => {
117 flushTimer.current = null;
118 const batch = toFileViewedBatch(queued.current);
119 if (batch.length === 0) return;
120 queued.current = new Map();
121 const sentFrom = scope.current;
122 const request = ++requests.current;
123 for (const file of batch) sentBy.current.set(file.path, request);
124 void setFilesViewed({ environmentId, input: { ...reference, files: batch } }).then((result) => {
125 const mine = batch
126 .map((file) => file.path)
127 .filter((path) => sentBy.current.get(path) === request);
128 for (const path of mine) sentBy.current.delete(path);
129 // The reader has moved on, and what is on screen now has nothing to do with this answer.
130 if (scope.current !== sentFrom) return;
131 if (result._tag === "Failure") {
132 // The host never heard these, so the ticks go back to whatever it last said. Only the
133 // paths this request still answers for: one pressed again since is waiting on a request
134 // of its own, or on the next flush, and that press is the one on screen.
135 const owned = new Set(mine.filter((path) => !queued.current.has(path)));
136 setOverlay((current) => revertFileViewedOverlay(current, batch, owned));
137 // Silent when nothing was still this request's to answer for, so nothing on screen went
138 // back, and when the connection went away mid-flight, which the reader is already being
139 // told about and which the host never refused.
140 if (owned.size > 0 && !isAtomCommandInterrupted(result)) {
141 toastManager.add({ type: "error", title: "Could not update viewed files" });
142 }
143 return;
144 }
145 // Answered for from the next read on, whatever it says. A push landing between the write
146 // and that read comes back as `dismissed`, and the press must not stand over it.
147 for (const path of mine) answeredFrom.current.set(path, statesRef.current);
148 refresh();
149 });
150 }, [environmentId, reference, refresh, setFilesViewed]);
151
152 // Read through a ref rather than closed over: `setViewed` is handed to every file header the
153 // viewer draws, and a new identity per render would rebuild all of them.
154 const flushRef = useRef(flush);
155 flushRef.current = flush;
156
157 // Leaving a change request, the environment it lives on, or the page itself records what was
158 // pressed and then drops the rest. The flush kept here is the one bound to the scope being
159 // left, which is what sends those last presses where they were meant to go.
160 useEffect(() => {
161 const flushScope = flushRef.current;
162 scope.current = scopeKey;
163 return () => {
164 if (flushTimer.current !== null) {
165 clearTimeout(flushTimer.current);
166 flushScope();
167 }
168 queued.current = new Map();
169 sentBy.current = new Map();
170 answeredFrom.current = new Map();
171 setOverlay(NO_OVERLAY);
172 };
173 }, [scopeKey]);
174
175 const refreshRef = useRef(refresh);
176 refreshRef.current = refresh;
177 const refreshFromHost = useCallback(() => refreshRef.current(), []);
178
179 const setViewed = useCallback((path: string, viewed: boolean) => {
180 setOverlay((current) => new Map(current).set(path, viewed));
181 queued.current.set(path, viewed);
182 if (flushTimer.current !== null) clearTimeout(flushTimer.current);
183 flushTimer.current = setTimeout(() => flushRef.current(), FLUSH_DELAY_MS);
184 }, []);
185
186 const isViewed = useCallback(
187 (path: string) => isFileViewed(path, states, overlay),
188 [overlay, states],
189 );
190 const isStale = useCallback(
191 (path: string) => !overlay.has(path) && isStaleViewedState(states?.get(path)),
192 [overlay, states],
193 );
194 const viewedCount = useMemo(
195 () => countViewedFiles(paths, states, overlay),
196 [overlay, paths, states],
197 );
198
199 // One identity per change of what it says: the viewer keys every file it draws off this.
200 return useMemo(
201 () => ({
202 enabled,
203 isViewed,
204 isStale,
205 setViewed,
206 viewedCount,
207 truncated,
208 ready: states !== null,
209 error,
210 refresh: refreshFromHost,
211 }),
212 [enabled, error, isStale, isViewed, refreshFromHost, setViewed, truncated, viewedCount],
213 );
214}