Spaces:
Sleeping

MicProtocol / apps /web /src /lib /workspace.tsx
Benaah's picture
Upload folder using huggingface_hub
fb12607 verified
Raw History Blame Contribute Delete
1.87 kB
"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<WorkspaceContextType | null>(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<string | null>(null);
const setActiveWorkspaceId = useCallback((id: string | null) => {
setActiveWorkspaceIdState(id);
}, []);
const value = React.useMemo(
() => ({ activeWorkspaceId, setActiveWorkspaceId }),
[activeWorkspaceId, setActiveWorkspaceId],
);
return (
<WorkspaceContext.Provider value={value}>
{children}
</WorkspaceContext.Provider>
);
}
/**
* 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 <WorkspaceProvider>");
}
return ctx;
}