| 1 | import type { Dispatch, SetStateAction } from "react"; |
| 2 | import { create } from "zustand"; |
| 3 | import type { SettingsInitialFocus } from "../components/SettingsPanel"; |
| 4 | import type { SettingsTab } from "../lib/types"; |
| 5 | import { applySetState } from "./setState"; |
| 6 | |
| 7 | export type AppPage = { kind: "workspace" } | { kind: "settings"; tab: SettingsTab } | { kind: "trash" } | { kind: "automation" }; |
| 8 | type NavigationState = { |
| 9 | page: AppPage; |
| 10 | workspaceFocus: HTMLElement | null; |
| 11 | generation: number; |
| 12 | visitedTrash: boolean; |
| 13 | visitedAutomation: boolean; |
| 14 | lastSettingsTarget: SettingsTab; |
| 15 | settingsFocus: SettingsInitialFocus | null; |
| 16 | automationReturn: boolean; |
| 17 | openPage: (page: AppPage) => void; |
| 18 | returnToWorkspace: () => void; |
| 19 | setSettingsTarget: Dispatch<SetStateAction<SettingsTab | null>>; |
| 20 | setSettingsFocus: Dispatch<SetStateAction<SettingsInitialFocus | null>>; |
| 21 | enterConversation: () => void; |
| 22 | returnFromAutomationLink: (generation: number) => void; |
| 23 | }; |
| 24 | export const useAppNavigationStore = create<NavigationState>((set, get) => ({ |
| 25 | page: { kind: "workspace" }, workspaceFocus: null, generation: 0, visitedTrash: false, visitedAutomation: false, |
| 26 | lastSettingsTarget: "general", settingsFocus: null, automationReturn: false, |
| 27 | openPage: (page) => set((state) => ({ |
| 28 | page, |
| 29 | workspaceFocus: state.page.kind === "workspace" && page.kind !== "workspace" && typeof document !== "undefined" ? document.activeElement as HTMLElement | null : state.workspaceFocus, |
| 30 | generation: state.generation + 1, |
| 31 | visitedTrash: state.visitedTrash || page.kind === "trash", |
| 32 | visitedAutomation: state.visitedAutomation || page.kind === "automation", |
| 33 | lastSettingsTarget: page.kind === "settings" ? page.tab : state.lastSettingsTarget, |
| 34 | automationReturn: false, |
| 35 | })), |
| 36 | returnToWorkspace: () => get().openPage({ kind: "workspace" }), |
| 37 | enterConversation: () => get().openPage({ kind: "workspace" }), |
| 38 | setSettingsTarget: (update) => { |
| 39 | const state = get(); |
| 40 | const target = applySetState(state.page.kind === "settings" ? state.page.tab : null, update); |
| 41 | if (target === null) state.returnToWorkspace(); |
| 42 | else state.openPage({ kind: "settings", tab: target }); |
| 43 | }, |
| 44 | setSettingsFocus: (update) => set((state) => ({ settingsFocus: applySetState(state.settingsFocus, update) })), |
| 45 | returnFromAutomationLink: (generation) => { |
| 46 | if (get().generation === generation) set({ page: { kind: "workspace" }, automationReturn: true }); |
| 47 | }, |
| 48 | })); |
| 49 |