"use client"; import React, { createContext, useCallback, useContext, useState } from "react"; interface WorkspaceContextType { /** The currently active workspace ID, or null if none selected yet */ activeWorkspaceId: string | null; /** Set the active workspace ID (called by dashboard layout, workspace switcher, etc.) */ setActiveWorkspaceId: (id: string | null) => void; } const WorkspaceContext = createContext(null); /** * Provider that tracks the active workspace ID. * * The dashboard layout resolves the user's first workspace from the API * and calls `setActiveWorkspaceId()`. The tRPC client reads * `activeWorkspaceId` and sends it as the `x-workspace-id` header on * every request, so `workspaceProcedure` on the API side can verify * membership without requiring the header from every caller manually. */ export function WorkspaceProvider({ children }: { children: React.ReactNode }) { const [activeWorkspaceId, setActiveWorkspaceIdState] = useState(null); const setActiveWorkspaceId = useCallback((id: string | null) => { setActiveWorkspaceIdState(id); }, []); const value = React.useMemo( () => ({ activeWorkspaceId, setActiveWorkspaceId }), [activeWorkspaceId, setActiveWorkspaceId], ); return ( {children} ); } /** * Hook to read/write the active workspace ID. * * Used by: * - Dashboard layout (writes the resolved workspaceId) * - tRPC client header function (reads it for the x-workspace-id header) * - Workspace switcher component (writes when user switches) */ export function useActiveWorkspace() { const ctx = useContext(WorkspaceContext); if (!ctx) { throw new Error("useActiveWorkspace must be used inside "); } return ctx; }