MCPcopy Create free account
hub / github.com/block/buzz / useWorkspacesInternal

Function useWorkspacesInternal

desktop/src/features/workspaces/useWorkspaces.tsx:62–201  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

60}
61
62function useWorkspacesInternal(): UseWorkspacesReturn {
63 const [workspaces, setWorkspacesState] =
64 useState<Workspace[]>(loadWorkspaces);
65 const [activeId, setActiveId] = useState<string | null>(
66 loadActiveWorkspaceId,
67 );
68 const [reinitKey, setReinitKey] = useState(0);
69 const workspacesRef = useRef(workspaces);
70 workspacesRef.current = workspaces;
71
72 const activeWorkspace = useMemo(
73 () => workspaces.find((w) => w.id === activeId) ?? workspaces[0] ?? null,
74 [workspaces, activeId],
75 );
76
77 const addWorkspace = useCallback((workspace: Workspace): string => {
78 const existing = workspacesRef.current.find(
79 (w) => w.relayUrl === workspace.relayUrl,
80 );
81 const resolvedId = existing?.id ?? workspace.id;
82 setWorkspacesState((prev) => {
83 const dup = prev.find((w) => w.relayUrl === workspace.relayUrl);
84 let next: Workspace[];
85 if (dup) {
86 next = prev.map((w) =>
87 w.id === dup.id
88 ? {
89 ...w,
90 name: workspace.name || w.name,
91 token: workspace.token ?? w.token,
92 pubkey: workspace.pubkey ?? w.pubkey,
93 }
94 : w,
95 );
96 } else {
97 next = [...prev, workspace];
98 }
99 saveWorkspaces(next);
100 return next;
101 });
102 return resolvedId;
103 }, []);
104
105 const clearWorkspaces = useCallback(() => {
106 clearWorkspaceStorage();
107 setWorkspacesState([]);
108 setActiveId(null);
109 }, []);
110
111 const removeWorkspace = useCallback(
112 (id: string) => {
113 // GC self-profile caches for the removed workspace's relay. Mirror the
114 // updater guard (length > 1) so we only GC when removal will actually
115 // proceed. Runs outside the updater — updaters can execute twice under
116 // React StrictMode.
117 if (workspaces.length > 1) {
118 const removed = workspaces.find((w) => w.id === id);
119 if (removed) {

Callers 1

WorkspacesProviderFunction · 0.85

Calls 6

saveWorkspacesFunction · 0.90
clearWorkspaceStorageFunction · 0.90
saveActiveWorkspaceIdFunction · 0.90

Tested by

no test coverage detected