Skip to content
File

Blob: src/client/components/active-page/use-active-page.ts

typescript41 lines
1import { createContext, use } from "react";
2import type YProvider from "y-partyserver/provider";
3import type { ActivePagePatch, ActivePageState } from "@/client/lib/active-page-model";
4 
5export interface ActivePageSyncValue {
6 syncProvider: YProvider | null;
7 setSyncProvider: (provider: YProvider | null) => void;
8}
9 
10export interface ActivePageActionsValue {
11 patchPage: (updates: ActivePagePatch) => void;
12}
13 
14const ActivePageStateCtx = createContext<ActivePageState | null>(null);
15const ActivePageSyncCtx = createContext<ActivePageSyncValue | null>(null);
16const ActivePageActionsCtx = createContext<ActivePageActionsValue | null>(null);
17 
18export 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 
24export 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 
30export 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 
36export const ActivePageContexts = {
37 State: ActivePageStateCtx,
38 Sync: ActivePageSyncCtx,
39 Actions: ActivePageActionsCtx,
40};