import type { Key } from '@astrale-os/sdk/schema' import type { ReactElement, ReactNode } from 'react' import { Path } from '@astrale-os/sdk/graph/path' import { createElement } from 'react' import type { NavAdapter } from './adapters/adapter.js' import type { NavSnapshot, SerializedLocation } from './history.js' import { NavScope } from './scope.context.js' import { useNavCtx } from './scope.context.js' import { useHistoryVersion } from './scope.context.js' import { viewKey } from './view-key.js' export interface NavigationParam { encode(value: Value): string decode(value: string | undefined): Value } export function pathParam(_name: string): NavigationParam { return Object.freeze({ encode: (value: Path) => Path.from(value).raw, decode(value: string | undefined) { if (value === undefined) throw new TypeError('Navigation target is missing.') return Path.parse(value) }, }) } export function enumParam( values: Values, fallback: Values[number], ): NavigationParam { if (!values.includes(fallback)) throw new TypeError('Navigation enum fallback is not admitted.') return Object.freeze({ encode(value: Values[number]) { if (!values.includes(value)) throw new TypeError(`Invalid navigation enum value '${value}'.`) return value }, decode(value: string | undefined) { if (value === undefined) return fallback if (!values.includes(value)) throw new TypeError(`Invalid navigation enum value '${value}'.`) return value as Values[number] }, }) } export type NavigationParams = Readonly>> export interface LocationDefinition { readonly view: Key.View readonly target: NavigationParam readonly params: Params } export function location< Target, const Params extends NavigationParams = Readonly>, >(input: { readonly view: Key.View | { readonly key: Key.View } readonly target: NavigationParam readonly params?: Params }): LocationDefinition { return Object.freeze({ view: viewKey(typeof input.view === 'string' ? input.view : input.view.key), target: input.target, params: Object.freeze({ ...input.params }) as Params, }) } type ValueOf = Codec extends NavigationParam ? Value : never type RouteTarget< Routes extends Readonly>>, > = { [Name in keyof Routes]: Readonly<{ name: Name target: ValueOf params: Readonly<{ [Param in keyof Routes[Name]['params']]: ValueOf }> }> }[keyof Routes] export type NavigationRoutes = Readonly< Record> > export interface NavigationDefinition { readonly routes: Routes encode(target: RouteTarget): SerializedLocation decode(location: SerializedLocation): RouteTarget | null admit(location: SerializedLocation): SerializedLocation | null } export function defineNavigation( routes: Routes, ): NavigationDefinition { const names = Object.keys(routes).sort() as (keyof Routes)[] const byView = new Map(names.map((name) => [routes[name]!.view, name] as const)) if (byView.size !== names.length) throw new TypeError('Navigation Views must be unique.') const definition: NavigationDefinition = { routes: Object.freeze({ ...routes }), encode(target) { const route = routes[target.name] if (route === undefined) throw new TypeError(`Unknown navigation location '${String(target.name)}'.`) const params = Object.fromEntries( Object.entries(route.params).map(([name, codec]) => [ name, codec.encode((target.params as Record)[name]), ]), ) return Object.freeze({ node: Path.parse(route.target.encode(target.target)).raw, view: route.view, ...(Object.keys(params).length === 0 ? {} : { params: Object.freeze(params) }), }) }, decode(serialized) { if (serialized.view === undefined) return null const name = byView.get(serialized.view) if (name === undefined) return null const route = routes[name]! try { const params = Object.fromEntries( Object.entries(route.params).map(([param, codec]) => [ param, codec.decode(serialized.params?.[param]), ]), ) if (Object.keys(serialized.params ?? {}).some((param) => !(param in route.params))) return null return Object.freeze({ name, target: route.target.decode(serialized.node), params: Object.freeze(params), }) as RouteTarget } catch { return null } }, admit(serialized) { const decoded = definition.decode(serialized) return decoded === null ? null : definition.encode(decoded) }, } return Object.freeze(definition) } export function NavigationScope(props: { readonly navigation: NavigationDefinition readonly adapter?: NavAdapter readonly restore?: NavSnapshot readonly initial?: RouteTarget readonly children: ReactNode }): ReactElement { return createElement(NavScope, { ...(props.adapter === undefined ? {} : { adapter: props.adapter }), ...(props.restore === undefined ? {} : { restore: props.restore }), ...(props.initial === undefined ? {} : { initial: props.navigation.encode(props.initial) }), admit: props.navigation.admit, children: props.children, }) } export function useNavigation( navigation: NavigationDefinition, ) { const context = useNavCtx() useHistoryVersion(context.history) const current = context.history.current return Object.freeze({ location: current === null ? null : navigation.decode(current), push: (target: RouteTarget) => context.navigate(navigation.encode(target)), replace: (target: RouteTarget) => context.navigate(navigation.encode(target), { replace: true }), back: context.navigate.back, forward: context.navigate.forward, snapshot: () => context.history.snapshot(), }) } export type NavigationTarget = Definition extends NavigationDefinition ? RouteTarget : never