Open History to see the last commit
1import type { EnvironmentId, PullRequestRef } from "@t3tools/contracts";
2import { create } from "zustand";
3
4import type { PullRequestDetailTab } from "~/rightPanelStore";
5
6import { pullRequestReviewKey } from "../pullRequestReviewStore";
7
8export interface GuideRunWatch {
9 readonly environmentId: EnvironmentId;
10 readonly reference: PullRequestRef;
11 readonly title: string | null;
12 readonly previousGuideAt: string | null;
13 readonly previousFailedAt: string | null;
14 readonly since: number;
15 /**
16 * Registered from a server answer that reports the run as Running. The guide atom still holds
17 * the previous answer then, and its outcome belongs to an earlier run.
18 */
19 readonly answeredRunning?: boolean;
20}
21
22export interface GuideProgress {
23 readonly position: number;
24 readonly seen: ReadonlySet<number>;
25}
26
27const NO_PROGRESS: GuideProgress = { position: 0, seen: new Set() };
28
29interface GuideRunStoreState {
30 readonly watches: Readonly<Record<string, GuideRunWatch>>;
31 /** The tab the pull requests page shows, for the pull request (run key) it was chosen on. */
32 readonly pageDetailTab: { readonly key: string; readonly tab: PullRequestDetailTab } | null;
33 readonly progress: Readonly<Record<string, GuideProgress>>;
34 readonly setProgress: (key: string, change: (current: GuideProgress) => GuideProgress) => void;
35 readonly watch: (watch: GuideRunWatch) => void;
36 readonly settle: (key: string) => void;
37 readonly showPageDetailTab: (key: string, tab: PullRequestDetailTab) => void;
38}
39
40export function guideRunKey(environmentId: EnvironmentId, reference: PullRequestRef): string {
41 return `${environmentId}:${pullRequestReviewKey(reference)}`;
42}
43
44export const useGuideRunStore = create<GuideRunStoreState>()((set) => ({
45 watches: {},
46 pageDetailTab: null,
47 progress: {},
48 setProgress: (key, change) =>
49 set((state) => ({
50 progress: { ...state.progress, [key]: change(state.progress[key] ?? NO_PROGRESS) },
51 })),
52 watch: (watch) =>
53 set((state) => {
54 const key = guideRunKey(watch.environmentId, watch.reference);
55 if (state.watches[key] !== undefined) return state;
56 return { watches: { ...state.watches, [key]: watch } };
57 }),
58 settle: (key) =>
59 set((state) => {
60 if (state.watches[key] === undefined) return state;
61 const { [key]: _settled, ...watches } = state.watches;
62 return { watches };
63 }),
64 showPageDetailTab: (key, tab) => set({ pageDetailTab: { key, tab } }),
65}));
66
67export function guideProgressKey(runKey: string, headSha: string): string {
68 return `${runKey}:${headSha}`;
69}
70
71export function useGuideProgress(key: string): GuideProgress {
72 return useGuideRunStore((state) => state.progress[key] ?? NO_PROGRESS);
73}