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 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;
34}
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 // Project ids can repeat across environments.
60 const scopeKey = `${environmentId} ${reference.projectId} ${reference.repository} ${reference.number}`;
61 const scope = useRef(scopeKey);
62
63 // Retire presses only after a post-write read, even if an older response agrees.
64 const answeredFrom = useRef<Map<string, FileViewedStates | null>>(new Map());
65 const committedStates = useRef(states);
66
67 useEffect(() => {
68 committedStates.current = states;
69 const pending = new Set([...queued.current.keys(), ...sentBy.current.keys()]);
70 const answered = new Set<string>();
71 for (const [path, from] of answeredFrom.current) {
72 if (pending.has(path) || from === states) continue;
73 answered.add(path);
74 answeredFrom.current.delete(path);
75 }
76 setOverlay((current) => settleFileViewedOverlay(current, states, pending, answered));
77 }, [states]);
78
79 // Explicit targets keep departing scopes' presses in their original scope.
80 const flush = (target: {
81 readonly environmentId: EnvironmentId;
82 readonly reference: PullRequestRef;
83 }) => {
84 flushTimer.current = null;
85 const batch = toFileViewedBatch(queued.current);
86 if (batch.length === 0) return;
87 queued.current = new Map();
88 const sentFrom = scope.current;
89 const request = ++requests.current;
90 for (const file of batch) sentBy.current.set(file.path, request);
91 void setFilesViewed({
92 environmentId: target.environmentId,
93 input: { ...target.reference, files: batch },
94 }).then((result) => {
95 const mine = batch
96 .map((file) => file.path)
97 .filter((path) => sentBy.current.get(path) === request);
98 for (const path of mine) sentBy.current.delete(path);
99 if (scope.current !== sentFrom) return;
100 if (result._tag === "Failure") {
101 const owned = new Set(mine.filter((path) => !queued.current.has(path)));
102 setOverlay((current) => revertFileViewedOverlay(current, batch, owned));
103 if (owned.size > 0 && !isAtomCommandInterrupted(result)) {
104 toastManager.add({ type: "error", title: "Could not update viewed files" });
105 refresh();
106 }
107 return;
108 }
109 // The next read can report dismissed after a push; retire presses regardless of its value.
110 for (const path of mine) answeredFrom.current.set(path, committedStates.current);
111 refresh();
112 });
113 };
114
115 const currentTarget = useEffectEvent(() => ({ environmentId, reference }));
116 const flushTarget = useEffectEvent(flush);
117
118 useEffect(() => {
119 const leaving = currentTarget();
120 scope.current = scopeKey;
121 return () => {
122 if (flushTimer.current !== null) {
123 clearTimeout(flushTimer.current);
124 flushTarget(leaving);
125 }
126 queued.current = new Map();
127 sentBy.current = new Map();
128 answeredFrom.current = new Map();
129 setOverlay(NO_OVERLAY);
130 };
131 }, [scopeKey]);
132
133 const setViewed = useStableCallback((path: string, viewed: boolean) => {
134 setOverlay((current) => new Map(current).set(path, viewed));
135 queued.current.set(path, viewed);
136 if (flushTimer.current !== null) clearTimeout(flushTimer.current);
137 const target = { environmentId, reference };
138 flushTimer.current = setTimeout(() => flush(target), FLUSH_DELAY_MS);
139 });
140
141 return {
142 enabled,
143 isViewed: (path: string) => isFileViewed(path, states, overlay),
144 isStale: (path: string) => !overlay.has(path) && isStaleViewedState(states?.get(path)),
145 setViewed,
146 truncated,
147 error,
148 refresh,
149 };
150}