File
Blob: src/client/components/active-page/use-active-page.ts
| 1 | import { createContext, use } from "react"; |
| 2 | import type YProvider from "y-partyserver/provider"; |
| 3 | import type { ActivePagePatch, ActivePageState } from "@/client/lib/active-page-model"; |
| 4 | |
| 5 | export interface ActivePageSyncValue { |
| 6 | syncProvider: YProvider | null; |
| 7 | setSyncProvider: (provider: YProvider | null) => void; |
| 8 | } |
| 9 | |
| 10 | export interface ActivePageActionsValue { |
| 11 | patchPage: (updates: ActivePagePatch) => void; |
| 12 | } |
| 13 | |
| 14 | const ActivePageStateCtx = createContext<ActivePageState | null>(null); |
| 15 | const ActivePageSyncCtx = createContext<ActivePageSyncValue | null>(null); |
| 16 | const ActivePageActionsCtx = createContext<ActivePageActionsValue | null>(null); |
| 17 | |
| 18 | export function useActivePageState(): ActivePageState { |
| 19 | const ctx = use(ActivePageStateCtx); |
| 20 | if (!ctx) throw new Error("useActivePageState must be used inside ActivePageProvider"); |
| 21 | return ctx; |
| 22 | } |
| 23 | |
| 24 | export function useActivePageSync(): ActivePageSyncValue { |
| 25 | const ctx = use(ActivePageSyncCtx); |
| 26 | if (!ctx) throw new Error("useActivePageSync must be used inside ActivePageProvider"); |
| 27 | return ctx; |
| 28 | } |
| 29 | |
| 30 | export function useActivePageActions(): ActivePageActionsValue { |
| 31 | const ctx = use(ActivePageActionsCtx); |
| 32 | if (!ctx) throw new Error("useActivePageActions must be used inside ActivePageProvider"); |
| 33 | return ctx; |
| 34 | } |
| 35 | |
| 36 | export const ActivePageContexts = { |
| 37 | State: ActivePageStateCtx, |
| 38 | Sync: ActivePageSyncCtx, |
| 39 | Actions: ActivePageActionsCtx, |
| 40 | }; |