import type { GraphStore, StoreQueryResponse } from '@astrale-os/sdk/client/store' import type { Key } from '@astrale-os/sdk/schema' import type { ReactElement, ReactNode } from 'react' import { NodePath } from '@astrale-os/sdk/graph/path' import { Query } from '@astrale-os/sdk/query' import { createContext, startTransition, useCallback, useContext, useEffect, useMemo, useRef, useSyncExternalStore, } from 'react' import type { NavAdapter } from './adapters/adapter.js' import type { NavSnapshot, SerializedLocation } from './history.js' import type { NavLocation, PointResult } from './location.js' import type { NavTarget } from './snapshot.js' import { UnsupportedFeatureError } from '../graph/memory/read/envelope.js' import { useStoreResource } from '../graph/resource.js' import { useGraphStore } from '../graph/store.js' import { useShell } from '../session/shell.hook.js' import { memoryAdapter } from './adapters/memory.adapter.js' import { NavHistory, seedEntries } from './history.js' import { buildLocation } from './location.js' import { revalidateAndPrune, serializeTarget } from './snapshot.js' import { viewKey } from './view-key.js' export interface Navigate { (to: NavTarget, opts?: { replace?: boolean }): void back(): void forward(): void /** Unsupported until the caller supplies an explicit parent Edge Class. */ up(): never readonly canBack: boolean readonly canForward: boolean } export interface MutableNavigate { (to: Parameters[0], opts?: Parameters[1]): void back(): void forward(): void up(): never canBack: boolean canForward: boolean } export interface NavCtx { readonly history: NavHistory readonly store: GraphStore readonly adapter: NavAdapter readonly navigate: MutableNavigate } export const NavContext = createContext(null) NavContext.displayName = 'AstraleNavContext' export function useNavCtx(): NavCtx { const ctx = useContext(NavContext) if (ctx === null) throw new Error('nav hooks must be used within a ') return ctx } export function useOptionalNavCtx(): NavCtx | null { return useContext(NavContext) } const NOOP_UNSUB = (): void => undefined export function useHistoryVersion(history: NavHistory | null): number { const subscribe = useCallback( (listener: () => void) => (history === null ? NOOP_UNSUB : history.subscribe(listener)), [history], ) const getSnapshot = useCallback(() => (history === null ? 0 : history.getVersion()), [history]) return useSyncExternalStore(subscribe, getSnapshot, getSnapshot) } /** Caller-scoped canonical point read through the provider's one GraphStore. */ export function useGraphPoint(target: NodePath | null): PointResult | null { const query = useMemo( () => target === null ? null : Query.from({ nodes: [target], binding: 'navigation_target' }).select({ kind: 'graph', }), [target], ) const project = useCallback( (response: StoreQueryResponse>) => { const result = response.result if (result.kind !== 'graph' || result.selection.kind !== 'node') return null const id = result.selection.ids[0] return id === undefined ? null : (result.graph.nodes.find((node) => node.id === id) ?? null) }, [query], ) const resource = useStoreResource(query, 1, project) if (target === null) return null return { node: resource.data ?? null, pending: resource.state === 'loading' || resource.state === 'refreshing', error: resource.error, live: false, seq: 0, refetch: resource.refresh, } } type MissingResolver = (location: NavLocation) => NavTarget | null export type MissingPolicy = 'hold' | MissingResolver export interface NavScopeProps { adapter?: NavAdapter restore?: NavSnapshot initial?: NavTarget onChange?: (location: NavLocation, snapshot: NavSnapshot) => void /** Default `hold`; parent fallback requires an explicit caller relationship. */ missing?: MissingPolicy /** Closed codec admission applied before any history or adapter mutation. */ admit?: (location: SerializedLocation) => SerializedLocation | null children: ReactNode } export function NavScope(props: NavScopeProps): ReactElement { const store = useGraphStore() const shell = useShell() const adapterRef = useRef(null) if (adapterRef.current === null) adapterRef.current = props.adapter ?? memoryAdapter() const adapter = adapterRef.current if (adapter.kind === 'browser' && shell.hostCapabilities.navigation.history !== 'browser') { throw new Error('Browser navigation is not granted to this Shell.') } const admitRef = useRef(props.admit) admitRef.current = props.admit const admit = (location: SerializedLocation | null): SerializedLocation | null => { if (location === null) return null const portable = admitLocation(location) return admitRef.current?.(portable) ?? portable } const historyRef = useRef(null) if (historyRef.current === null) { const seed = seedEntries( admit(adapter.read()), props.restore === undefined || props.restore.v !== 1 ? undefined : { entries: props.restore.entries.flatMap((entry) => { const accepted = admit(entry) return accepted === null ? [] : [accepted] }), cursor: props.restore.cursor, }, props.initial === undefined ? null : admit(serializeTarget(props.initial)), ) historyRef.current = new NavHistory(seed.entries, seed.cursor) } const history = historyRef.current const onChangeRef = useRef(props.onChange) onChangeRef.current = props.onChange const missingRef = useRef(props.missing) missingRef.current = props.missing const historyVersion = useHistoryVersion(history) const fireOnChange = useCallback((): void => { onChangeRef.current?.(buildLocation(history.current, null), history.snapshot()) }, [history]) const navigate = useMemo(() => { const commit = (changed: boolean, replace: boolean): void => { if (!changed) return const location = history.current if (location !== null) adapter.write(location, { replace }) fireOnChange() } const nav = ((to: NavTarget, options?: { replace?: boolean }) => { const replace = options?.replace ?? false const location = admit(serializeTarget(to)) if (location === null) throw new TypeError('Navigation target was rejected by its codec.') startTransition(() => commit(history.push(location, replace), replace)) }) as MutableNavigate nav.back = () => startTransition(() => commit(history.back(), false)) nav.forward = () => startTransition(() => commit(history.forward(), false)) nav.up = (): never => { throw new UnsupportedFeatureError('navigation.up requires an explicit parent Edge Class') } nav.canBack = history.canBack nav.canForward = history.canForward return nav }, [history, adapter, fireOnChange, historyVersion]) useEffect(() => { const seed = history.current if (seed !== null && adapter.read() === null) adapter.write(seed, { replace: true }) return adapter.subscribe(() => { const location = admit(adapter.read()) if (location === null) return startTransition(() => { if (history.syncExternal(location)) fireOnChange() }) }) }, [history, adapter, fireOnChange]) useEffect(() => { if (props.restore === undefined) return let current = true void revalidateAndPrune(history, store, shell).then((changed) => { if (!current || !changed) return const accepted = history.current if (accepted === null) adapter.clear({ replace: true }) else adapter.write(accepted, { replace: true }) fireOnChange() }) return () => { current = false } }, [store, shell, history, adapter, props.restore, fireOnChange]) const current = history.current const result = useGraphPoint(current?.node ?? null) const handled = useRef(null) useEffect(() => { if (current === null || result === null || result.pending) return if (result.node !== null) { handled.current = null return } if (handled.current === current.node) return handled.current = current.node const policy = missingRef.current ?? 'hold' if (typeof policy === 'function') { const target = policy(buildLocation(current, result)) if (target !== null) navigate(target, { replace: true }) } }, [current, result, navigate, historyVersion]) const ctx = useMemo( () => ({ history, store, adapter, navigate }), [history, store, adapter, navigate], ) return {props.children} } function admitLocation(location: SerializedLocation): SerializedLocation { if (location === null || typeof location !== 'object' || Array.isArray(location)) { throw new TypeError('Navigation location is invalid.') } const node = NodePath(location.node) let view: Key.View | undefined if (location.view !== undefined) { view = viewKey(location.view) } const params: Record = {} if (location.params !== undefined) { if ( location.params === null || typeof location.params !== 'object' || Array.isArray(location.params) ) { throw new TypeError('Navigation params are invalid.') } for (const [key, value] of Object.entries(location.params)) { if (/token|credential|authorization|secret/i.test(key)) { throw new TypeError(`Navigation param '${key}' is sensitive.`) } if (typeof value !== 'string') throw new TypeError(`Navigation param '${key}' is invalid.`) params[key] = value } } return Object.freeze({ node, ...(view === undefined ? {} : { view }), ...(Object.keys(params).length === 0 ? {} : { params: Object.freeze(params) }), }) }