Open History to see the last commit
1import { useMessages } from "gt-react";
2import type { EnvironmentId, PullRequestRef } from "@t3tools/contracts";
3import { useSyncExternalStore } from "react";
4
5import { pullRequestEnvironment } from "~/state/pullRequests";
6import { useEnvironmentQuery } from "~/state/query";
7
8import { filesViewedScope } from "./filesViewedStore";
9import {
10 countViewedFiles,
11 isFileViewed,
12 isStaleViewedState,
13 toFileViewedStates,
14} from "./pullRequestFilesViewed.logic";
15
16export interface PullRequestFilesViewedView {
17 readonly enabled: boolean;
18 readonly viewedCount: number;
19 readonly isViewed: (path: string) => boolean;
20 readonly isStale: (path: string) => boolean;
21 readonly setViewed: (path: string, viewed: boolean, revision?: string) => void;
22 readonly truncated: boolean;
23 readonly error: string | null;
24 readonly refresh: () => void;
25}
26
27const NO_OVERLAY = new Map<string, boolean>();
28// Without this a change request that cannot record views would still be handed a scope handle.
29const DISABLED_SCOPE = {
30 subscribe: () => () => {},
31 getSnapshot: () => NO_OVERLAY,
32 setViewed: () => {},
33};
34
35export function usePullRequestFilesViewed(options: {
36 readonly environmentId: EnvironmentId;
37 readonly reference: PullRequestRef;
38 readonly enabled: boolean;
39}): PullRequestFilesViewedView {
40 const { environmentId, reference, enabled } = options;
41 const query = useEnvironmentQuery(
42 enabled ? pullRequestEnvironment.filesViewed({ environmentId, input: reference }) : null,
43 useMessages(),
44 );
45 const states = toFileViewedStates(query.data);
46 // Stable per scope: `setViewed` is handed to every file header the viewer draws.
47 const scope = enabled ? filesViewedScope({ environmentId, reference }) : DISABLED_SCOPE;
48 const overlay = useSyncExternalStore(scope.subscribe, scope.getSnapshot);
49
50 return {
51 enabled,
52 viewedCount: countViewedFiles(states, overlay),
53 isViewed: (path: string) => isFileViewed(path, states, overlay),
54 isStale: (path: string) => !overlay.has(path) && isStaleViewedState(states?.get(path)),
55 setViewed: scope.setViewed,
56 truncated: query.data?.truncated === true,
57 error: query.error,
58 refresh: query.refresh,
59 };
60}