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

usePullRequestFilesViewed.ts

158 lines6.3 KB

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