Open History to see the last commit
1import { isAtomCommandInterrupted } from "@t3tools/client-runtime/state/runtime";
2import type { EnvironmentId, PullRequestRef } from "@t3tools/contracts";
3import { useEffect, useEffectEvent, useRef, useState } from "react";
4
5import { pullRequestEnvironment } from "~/state/pullRequests";
6import { useEnvironmentQuery } from "~/state/query";
7import { useAtomCommand } from "~/state/use-atom-command";
8import { useStableCallback } from "~/hooks/useStableCallback";
9
10import { toastManager } from "../ui/toast";
11import {
12 countViewedFiles,
13 isFileViewed,
14 isStaleViewedState,
15 revertFileViewedOverlay,
16 settleFileViewedOverlay,
17 toFileViewedBatch,
18 toFileViewedStates,
19 type FileViewedOverlay,
20 type FileViewedStates,
21} from "./pullRequestFilesViewed.logic";
22
23const FLUSH_DELAY_MS = 400;
24
25const NO_OVERLAY: FileViewedOverlay = new Map();
26
27export interface PullRequestFilesViewedView {
28 readonly enabled: boolean;
29 readonly isViewed: (path: string) => boolean;
30 readonly isStale: (path: string) => boolean;
31 readonly setViewed: (path: string, viewed: boolean) => void;
32 readonly viewedCount: number;
33 readonly truncated: boolean;
34 readonly error: string | null;
35 readonly refresh: () => void;
36}
37
38export function usePullRequestFilesViewed(options: {
39 readonly environmentId: EnvironmentId;
40 readonly reference: PullRequestRef;
41 readonly enabled: boolean;
42 readonly paths: ReadonlyArray<string>;
43}): PullRequestFilesViewedView {
44 const { environmentId, reference, enabled, paths } = options;
45 const query = useEnvironmentQuery(
46 enabled ? pullRequestEnvironment.filesViewed({ environmentId, input: reference }) : null,
47 );
48 const refresh = query.refresh;
49 const states = toFileViewedStates(query.data);
50 const truncated = query.data?.truncated === true;
51 const error = query.error;
52 const [overlay, setOverlay] = useState<FileViewedOverlay>(NO_OVERLAY);
53 const setFilesViewed = useAtomCommand(pullRequestEnvironment.setFilesViewed, {
54 reportFailure: false,
55 });
56
57 const queued = useRef<Map<string, boolean>>(new Map());
58 const sentBy = useRef<Map<string, number>>(new Map());
59 const requests = useRef(0);
60 const flushTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
61
62 // Everything held here belongs to one change request on one environment. The environment is
63 // part of that: two of them can hand out the same project id, and a press made against one
64 // must never be answered for by the other.
65 const scopeKey = `${environmentId} ${reference.projectId} ${reference.repository} ${reference.number}`;
66 const scope = useRef(scopeKey);
67
68 // The host's answer as it stood when a completed write was acknowledged, per path. The first
69 // answer that differs from it is the first read that could have seen the write, which is what
70 // retires the press rather than the host happening to agree with it.
71 const answeredFrom = useRef<Map<string, FileViewedStates | null>>(new Map());
72 // The committed answer, read when a write completes rather than when it was sent.
73 const committedStates = useRef(states);
74
75 useEffect(() => {
76 committedStates.current = states;
77 const pending = new Set([...queued.current.keys(), ...sentBy.current.keys()]);
78 const answered = new Set<string>();
79 for (const [path, from] of answeredFrom.current) {
80 if (pending.has(path) || from === states) continue;
81 answered.add(path);
82 answeredFrom.current.delete(path);
83 }
84 setOverlay((current) => settleFileViewedOverlay(current, states, pending, answered));
85 }, [states]);
86
87 // Takes the target explicitly so a scope being left still sends its last presses to itself.
88 const flush = (target: {
89 readonly environmentId: EnvironmentId;
90 readonly reference: PullRequestRef;
91 }) => {
92 flushTimer.current = null;
93 const batch = toFileViewedBatch(queued.current);
94 if (batch.length === 0) return;
95 queued.current = new Map();
96 const sentFrom = scope.current;
97 const request = ++requests.current;
98 for (const file of batch) sentBy.current.set(file.path, request);
99 void setFilesViewed({
100 environmentId: target.environmentId,
101 input: { ...target.reference, files: batch },
102 }).then((result) => {
103 const mine = batch
104 .map((file) => file.path)
105 .filter((path) => sentBy.current.get(path) === request);
106 for (const path of mine) sentBy.current.delete(path);
107 if (scope.current !== sentFrom) return;
108 if (result._tag === "Failure") {
109 const owned = new Set(mine.filter((path) => !queued.current.has(path)));
110 setOverlay((current) => revertFileViewedOverlay(current, batch, owned));
111 if (owned.size > 0 && !isAtomCommandInterrupted(result)) {
112 toastManager.add({ type: "error", title: "Could not update viewed files" });
113 }
114 return;
115 }
116 // Answered for from the next read on, whatever it says. A push landing between the write
117 // and that read comes back as `dismissed`, and the press must not stand over it.
118 for (const path of mine) answeredFrom.current.set(path, committedStates.current);
119 refresh();
120 });
121 };
122
123 const currentTarget = useEffectEvent(() => ({ environmentId, reference }));
124 const flushTarget = useEffectEvent(flush);
125
126 // Leaving a change request, the environment it lives on, or the page itself records what was
127 // pressed and then drops the rest, sending those last presses to the scope being left.
128 useEffect(() => {
129 const leaving = currentTarget();
130 scope.current = scopeKey;
131 return () => {
132 if (flushTimer.current !== null) {
133 clearTimeout(flushTimer.current);
134 flushTarget(leaving);
135 }
136 queued.current = new Map();
137 sentBy.current = new Map();
138 answeredFrom.current = new Map();
139 setOverlay(NO_OVERLAY);
140 };
141 }, [scopeKey]);
142
143 // Handed to every file header the viewer draws; a new identity would rebuild all of them.
144 const setViewed = useStableCallback((path: string, viewed: boolean) => {
145 setOverlay((current) => new Map(current).set(path, viewed));
146 queued.current.set(path, viewed);
147 if (flushTimer.current !== null) clearTimeout(flushTimer.current);
148 const target = { environmentId, reference };
149 flushTimer.current = setTimeout(() => flush(target), FLUSH_DELAY_MS);
150 });
151
152 return {
153 enabled,
154 isViewed: (path: string) => isFileViewed(path, states, overlay),
155 isStale: (path: string) => !overlay.has(path) && isStaleViewedState(states?.get(path)),
156 setViewed,
157 viewedCount: countViewedFiles(paths, states, overlay),
158 truncated,
159 error,
160 refresh,
161 };
162}