Open History to see the last commit
1import type { EnvironmentId, PullRequestRef } from "@t3tools/contracts";
2import { create } from "zustand";
3
4import { pullRequestReviewKey } from "../pullRequestReviewStore";
5
6export interface GuideRunWatch {
7 readonly environmentId: EnvironmentId;
8 readonly reference: PullRequestRef;
9 readonly title: string | null;
10 readonly previousGuideAt: string | null;
11 readonly previousFailedAt: string | null;
12 readonly since: number;
13}
14
15export interface GuideProgress {
16 readonly position: number;
17 readonly seen: ReadonlySet<number>;
18}
19
20const NO_PROGRESS: GuideProgress = { position: 0, seen: new Set() };
21
22interface GuideRunStoreState {
23 readonly watches: Readonly<Record<string, GuideRunWatch>>;
24 readonly shownKey: string | null;
25 readonly openRequestKey: string | null;
26 readonly progress: Readonly<Record<string, GuideProgress>>;
27 readonly setProgress: (key: string, change: (current: GuideProgress) => GuideProgress) => void;
28 readonly watch: (watch: GuideRunWatch) => void;
29 readonly settle: (key: string) => void;
30 readonly setShown: (key: string | null) => void;
31 readonly requestOpen: (key: string | null) => void;
32}
33
34export function guideRunKey(environmentId: EnvironmentId, reference: PullRequestRef): string {
35 return `${environmentId}:${pullRequestReviewKey(reference)}`;
36}
37
38export const useGuideRunStore = create<GuideRunStoreState>()((set) => ({
39 watches: {},
40 shownKey: null,
41 openRequestKey: null,
42 progress: {},
43 setProgress: (key, change) =>
44 set((state) => ({
45 progress: { ...state.progress, [key]: change(state.progress[key] ?? NO_PROGRESS) },
46 })),
47 watch: (watch) =>
48 set((state) => {
49 const key = guideRunKey(watch.environmentId, watch.reference);
50 if (state.watches[key] !== undefined) return state;
51 return { watches: { ...state.watches, [key]: watch } };
52 }),
53 settle: (key) =>
54 set((state) => {
55 if (state.watches[key] === undefined) return state;
56 const { [key]: _settled, ...watches } = state.watches;
57 return { watches };
58 }),
59 setShown: (shownKey) => set({ shownKey }),
60 requestOpen: (openRequestKey) => set({ openRequestKey }),
61}));
62
63export function guideProgressKey(runKey: string, headSha: string): string {
64 return `${runKey}:${headSha}`;
65}
66
67export function useGuideProgress(key: string): GuideProgress {
68 return useGuideRunStore((state) => state.progress[key] ?? NO_PROGRESS);
69}