import { PropsWithChildren, createContext, useContext, useEffect, useState, } from "react"; import { AuthSession, ClientConfig, IAppContext, ICanvasPosition, IPosition, } from "@sc07-canvas/lib/src/net"; import Network from "../lib/network"; import { Spinner } from "@nextui-org/react"; import { api } from "../lib/utils"; const appContext = createContext({} as any); export const useAppContext = () => useContext(appContext); export const AppContext = ({ children }: PropsWithChildren) => { const [config, setConfig] = useState(undefined as any); const [auth, setAuth] = useState(); const [canvasPosition, setCanvasPosition] = useState(); const [cursorPosition, setCursorPosition] = useState(); const [connected, setConnected] = useState(false); // --- settings --- const [loadChat, _setLoadChat] = useState(false); const [pixels, setPixels] = useState({ available: 0 }); const [undo, setUndo] = useState<{ available: true; expireAt: number }>(); // overlays visible const [settingsSidebar, setSettingsSidebar] = useState(false); const [hasAdmin, setHasAdmin] = useState(false); useEffect(() => { function loadSettings() { setLoadChat( localStorage.getItem("matrix.enable") === null ? true : localStorage.getItem("matrix.enable") === "true" ); } function handleConfig(config: ClientConfig) { setConfig(config); } function handleUser(user: AuthSession) { setAuth(user); } function handlePixels(pixels: { available: number }) { setPixels(pixels); } function handleUndo( data: { available: false } | { available: true; expireAt: number } ) { if (data.available) { setUndo({ available: true, expireAt: data.expireAt }); } else { setUndo(undefined); } } function handleConnect() { setConnected(true); } function handleDisconnect() { setConnected(false); } api<{}>("/api/admin/check").then(({ status, data }) => { if (status === 200) { if (data.success) { setHasAdmin(true); } } }); Network.on("user", handleUser); Network.on("config", handleConfig); Network.waitFor("pixels").then(([data]) => handlePixels(data)); Network.on("pixels", handlePixels); Network.on("undo", handleUndo); Network.on("connected", handleConnect); Network.on("disconnected", handleDisconnect); Network.socket.connect(); loadSettings(); return () => { Network.off("user", handleUser); Network.off("config", handleConfig); Network.off("pixels", handlePixels); Network.off("undo", handleUndo); Network.off("connected", handleConnect); Network.off("disconnected", handleDisconnect); }; }, []); const setLoadChat = (v: boolean) => { _setLoadChat(v); localStorage.setItem("matrix.enable", v ? "true" : "false"); }; return ( {!config && (
)} {children}
); };