import type { PathLike } from '@astrale-os/sdk/graph/path' import type { NodeTarget, SpaceNode } from '@astrale-os/shell' import { Path } from '@astrale-os/sdk/graph/path' /** * useSpaces (API §12.2) — the spaces list, the selected space, and a `switch` * Action that repoints the `selected_space` edge. Reads the SAME per-Shell * current-space store as useCurrentSpace/useApps, so a switch re-themes every * consumer in the window at once — optimistically ahead of the round-trip (§1.6), * commit reconciles, failure rolls back. Reads are one-shot today (§12 flag). */ import { useEffect, useMemo, useSyncExternalStore } from 'react' import type { Action } from '../../graph/action.js' import type { ReadState } from '../../graph/memory/read/envelope.js' import { useAction } from '../../graph/action.js' import { useAsyncResource } from '../../graph/async.js' import { useShell } from '../../session/shell.hook.js' import { isOsPlaneAvailable } from '../user/user.store.js' import { currentSpaceStore, idleSnapshot, noopSubscribe } from './current-space.store.js' const NO_SPACES: readonly SpaceNode[] = [] export interface SpacesResult extends ReadState { /** Spaces-dir children, live (one-shot today), the caller's readable set. */ readonly spaces: readonly SpaceNode[] /** The `selected_space` target — optimistically ahead during a `switch`. */ readonly selected: SpaceNode | null /** `user::switchSpace` with a manual optimistic overlay (§1.6). */ readonly switch: Action<[NodeTarget], void> } export function useSpaces(): SpacesResult { const shell = useShell() const available = isOsPlaneAvailable(shell) const store = currentSpaceStore(shell) const spacesRes = useAsyncResource( available ? () => shell.spaces.list() : null, NO_SPACES, [shell, available], ) useEffect(() => { if (available) store.ensure() }, [store, available]) const selectedSnap = useSyncExternalStore( available ? store.subscribe : noopSubscribe, available ? store.getSnapshot : idleSnapshot, available ? store.getSnapshot : idleSnapshot, ) const spaces = spacesRes.data const switchAction = useAction(async (ref: NodeTarget): Promise => { // Optimistic override on the SHARED store, so useCurrentSpace / useApps ahead // of the round-trip too (§12.2). Only overlay a known target (a path ref that // matches nothing in the list simply skips the preview). const target = findSpace(spaces, ref) if (target !== null) store.setOptimistic(target) try { await shell.user.switchSpace(ref) await store.refresh() // reconcile confirmed truth BEFORE dropping the preview store.clearOptimistic() } catch (error) { store.clearOptimistic() // rollback: reveal the confirmed (previous) space throw error } }) return useMemo( () => ({ spaces, selected: selectedSnap.space, switch: switchAction, pending: spacesRes.pending || selectedSnap.pending, error: spacesRes.error ?? selectedSnap.error, live: false, seq: 0, refetch: async () => { await Promise.all([spacesRes.refetch(), store.refresh()]) }, }), [ spaces, selectedSnap, switchAction, spacesRes.pending, spacesRes.error, spacesRes.refetch, store, ], ) } /** The space in `spaces` denoted by `ref`, or `null` (path refs don't match by id). */ function findSpace(spaces: readonly SpaceNode[], ref: NodeTarget): SpaceNode | null { const id = refIdOf(ref) if (id === null) return null return spaces.find((s) => s.id === id) ?? null } /** A bound-node-ish subject carries a graph id. */ function hasId(x: unknown): x is { readonly id: string } { return typeof x === 'object' && x !== null && 'id' in x } /** The graph id a subject denotes, or `null` when it is a path (no id to match). */ function refIdOf(x: NodeTarget | { readonly id: string }): string | null { if (hasId(x)) return x.id if (typeof x === 'string' && !x.startsWith('@') && !x.startsWith('/')) return x try { const path = Path.from(x as PathLike) return path.ast.anchor.kind === 'id' && path.ast.steps.length === 0 ? path.ast.anchor.id : null } catch { return null } }