Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usePullRequestFilesViewed.ts

174 lines6.7 KB

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​
22const FLUSH_DELAY_MS = 400;
23​
24const NO_OVERLAY: FileViewedOverlay = new Map();
25​
26export interface PullRequestFilesViewedView {
27 readonly enabled: boolean;
28 readonly isViewed: (path: string) => boolean;
29 readonly isStale: (path: string) => boolean;
30 readonly setViewed: (path: string, viewed: boolean) => void;
31 readonly viewedCount: number;
32 readonly truncated: boolean;
33 readonly error: string | null;
34 readonly refresh: () => void;
36​
37export function usePullRequestFilesViewed(options: {
38 readonly environmentId: EnvironmentId;
39 readonly reference: PullRequestRef;
40 readonly enabled: boolean;
41 readonly paths: ReadonlyArray<string>;
42}): PullRequestFilesViewedView {
43 const { environmentId, reference, enabled, paths } = options;
44 const query = useEnvironmentQuery(
45 enabled ? pullRequestEnvironment.filesViewed({ environmentId, input: reference }) : null,
46 );
47 const refresh = query.refresh;
48 const states = useMemo(() => toFileViewedStates(query.data), [query.data]);
49 const truncated = query.data?.truncated === true;
50 const error = query.error;
51 const [overlay, setOverlay] = useState<FileViewedOverlay>(NO_OVERLAY);
52 const setFilesViewed = useAtomCommand(pullRequestEnvironment.setFilesViewed, {
53 reportFailure: false,
54 });
55​
56 const queued = useRef<Map<string, boolean>>(new Map());
57 const sentBy = useRef<Map<string, number>>(new Map());
58 const requests = useRef(0);
59 const flushTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
60​
61 // Everything held here belongs to one change request on one environment. The environment is
62 // part of that: two of them can hand out the same project id, and a press made against one
63 // must never be answered for by the other.
64 const scopeKey = `${environmentId} ${reference.projectId} ${reference.repository} ${reference.number}`;
65 const scope = useRef(scopeKey);
66​
67 // The host's answer as it stood when a completed write was acknowledged, per path. The first
68 // answer that differs from it is the first read that could have seen the write, which is what
69 // retires the press rather than the host happening to agree with it.
70 const answeredFrom = useRef<Map<string, FileViewedStates | null>>(new Map());
71 const statesRef = useRef(states);
72 statesRef.current = states;
73​
74 useEffect(() => {
75 const pending = new Set([...queued.current.keys(), ...sentBy.current.keys()]);
76 const answered = new Set<string>();
77 for (const [path, from] of answeredFrom.current) {
78 if (pending.has(path) || from === states) continue;
79 answered.add(path);
80 answeredFrom.current.delete(path);
81 }
82 setOverlay((current) => settleFileViewedOverlay(current, states, pending, answered));
83 }, [states]);
84​
85 const flush = useCallback(() => {
86 flushTimer.current = null;
87 const batch = toFileViewedBatch(queued.current);
88 if (batch.length === 0) return;
89 queued.current = new Map();
90 const sentFrom = scope.current;
91 const request = ++requests.current;
92 for (const file of batch) sentBy.current.set(file.path, request);
93 void setFilesViewed({ environmentId, input: { ...reference, files: batch } }).then((result) => {
94 const mine = batch
95 .map((file) => file.path)
96 .filter((path) => sentBy.current.get(path) === request);
97 for (const path of mine) sentBy.current.delete(path);
98 if (scope.current !== sentFrom) return;
99 if (result._tag === "Failure") {
100 const owned = new Set(mine.filter((path) => !queued.current.has(path)));
101 setOverlay((current) => revertFileViewedOverlay(current, batch, owned));
102 if (owned.size > 0 && !isAtomCommandInterrupted(result)) {
103 toastManager.add({ type: "error", title: "Could not update viewed files" });
104 }
105 return;
106 }
107 // Answered for from the next read on, whatever it says. A push landing between the write
108 // and that read comes back as `dismissed`, and the press must not stand over it.
109 for (const path of mine) answeredFrom.current.set(path, statesRef.current);
110 refresh();
111 });
112 }, [environmentId, reference, refresh, setFilesViewed]);
113​
114 // Read through a ref rather than closed over: `setViewed` is handed to every file header the
115 // viewer draws, and a new identity per render would rebuild all of them.
116 const flushRef = useRef(flush);
117 flushRef.current = flush;
118​
119 // Leaving a change request, the environment it lives on, or the page itself records what was
120 // pressed and then drops the rest. The flush kept here is the one bound to the scope being
121 // left, which is what sends those last presses where they were meant to go.
122 useEffect(() => {
123 const flushScope = flushRef.current;
124 scope.current = scopeKey;
125 return () => {
126 if (flushTimer.current !== null) {
127 clearTimeout(flushTimer.current);
128 flushScope();
129 }
130 queued.current = new Map();
131 sentBy.current = new Map();
132 answeredFrom.current = new Map();
133 setOverlay(NO_OVERLAY);
134 };
135 }, [scopeKey]);
136​
137 const refreshRef = useRef(refresh);
138 refreshRef.current = refresh;
139 const refreshFromHost = useCallback(() => refreshRef.current(), []);
140​
141 const setViewed = useCallback((path: string, viewed: boolean) => {
142 setOverlay((current) => new Map(current).set(path, viewed));
143 queued.current.set(path, viewed);
144 if (flushTimer.current !== null) clearTimeout(flushTimer.current);
145 flushTimer.current = setTimeout(() => flushRef.current(), FLUSH_DELAY_MS);
146 }, []);
147​
148 const isViewed = useCallback(
149 (path: string) => isFileViewed(path, states, overlay),
150 [overlay, states],
151 );
152 const isStale = useCallback(
153 (path: string) => !overlay.has(path) && isStaleViewedState(states?.get(path)),
154 [overlay, states],
155 );
156 const viewedCount = useMemo(
157 () => countViewedFiles(paths, states, overlay),
158 [overlay, paths, states],
159 );
160​
161 return useMemo(
162 () => ({
163 enabled,
164 isViewed,
165 isStale,
166 setViewed,
167 viewedCount,
168 truncated,
169 error,
170 refresh: refreshFromHost,
171 }),
172 [enabled, error, isStale, isViewed, refreshFromHost, setViewed, truncated, viewedCount],
173 );