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

usePullRequestFilesViewed.ts

55 lines2.0 KB

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