File
Blob: src/client/stores/workspace-navigation.ts
| 1 | import { create } from "zustand"; |
| 2 | |
| 3 | export interface WorkspaceNavigationState { |
| 4 | lastVisitedWorkspaceId: string | null; |
| 5 | lastVisitedPageIdByWorkspaceId: Record<string, string>; |
| 6 | } |
| 7 | |
| 8 | const initialState: WorkspaceNavigationState = { |
| 9 | lastVisitedWorkspaceId: null, |
| 10 | lastVisitedPageIdByWorkspaceId: {}, |
| 11 | }; |
| 12 | |
| 13 | export const useWorkspaceNavigationStore = create<WorkspaceNavigationState>(() => initialState); |
| 14 | |
| 15 | export interface WorkspaceNavigationProjection { |
| 16 | lastVisitedWorkspaceId: string | null; |
| 17 | lastVisitedPages: { workspaceId: string; pageId: string }[]; |
| 18 | } |
| 19 | |
| 20 | export function applyWorkspaceNavigationProjection(projection: WorkspaceNavigationProjection): void { |
| 21 | const lastVisitedPageIdByWorkspaceId: Record<string, string> = {}; |
| 22 | for (const row of projection.lastVisitedPages) { |
| 23 | lastVisitedPageIdByWorkspaceId[row.workspaceId] = row.pageId; |
| 24 | } |
| 25 | useWorkspaceNavigationStore.setState( |
| 26 | { |
| 27 | lastVisitedWorkspaceId: projection.lastVisitedWorkspaceId, |
| 28 | lastVisitedPageIdByWorkspaceId, |
| 29 | }, |
| 30 | true, |
| 31 | ); |
| 32 | } |
| 33 | |
| 34 | export function resetWorkspaceNavigationProjection(): void { |
| 35 | useWorkspaceNavigationStore.setState(initialState, true); |
| 36 | } |
| 37 | |
| 38 | export function selectLastVisitedWorkspaceId(state: WorkspaceNavigationState): string | null { |
| 39 | return state.lastVisitedWorkspaceId; |
| 40 | } |
| 41 | |
| 42 | export function selectLastVisitedPageId(state: WorkspaceNavigationState, workspaceId: string | null): string | null { |
| 43 | if (!workspaceId) return null; |
| 44 | return state.lastVisitedPageIdByWorkspaceId[workspaceId] ?? null; |
| 45 | } |
| 46 | |
| 47 | export function useLastVisitedWorkspaceId(): string | null { |
| 48 | return useWorkspaceNavigationStore(selectLastVisitedWorkspaceId); |
| 49 | } |
| 50 | |
| 51 | export function useLastVisitedPageId(workspaceId: string | null): string | null { |
| 52 | return useWorkspaceNavigationStore((s) => selectLastVisitedPageId(s, workspaceId)); |
| 53 | } |