/** * useNavigate (API §8.2) — the nearest scope's imperative navigation surface * (back/forward/up + live canBack/canForward, wrapped in transitions). A * per-consumer handle that delegates to the scope's ONE stable callable. */ import { useMemo } from 'react' import type { MutableNavigate, NavCtx, Navigate } from '../scope.context.js' import { useHistoryVersion, useNavCtx } from '../scope.context.js' /** The nearest scope's imperative navigation surface. Throws outside a scope. */ export function useNavigate(): Navigate { return useNavigateHandle(useNavCtx()) } /** * A per-consumer navigate handle with fresh `canBack`/`canForward`, delegating to * the scope's ONE stable callable. Render-pure: it never mutates the shared * callable during render (a concurrent render could otherwise read flags from a * newer history version than its own snapshot). The wrapper's identity changes * only when navigation availability changes. */ export function useNavigateHandle(ctx: NavCtx): Navigate { useHistoryVersion(ctx.history) const canBack = ctx.history.canBack const canForward = ctx.history.canForward return useMemo( () => wrapNavigate(ctx.navigate, canBack, canForward), [ctx.navigate, canBack, canForward], ) } function wrapNavigate(base: MutableNavigate, canBack: boolean, canForward: boolean): Navigate { const fn = ((to: Parameters[0], opts?: Parameters[1]) => base(to, opts)) as MutableNavigate fn.back = base.back fn.forward = base.forward fn.up = base.up fn.canBack = canBack fn.canForward = canForward return fn }