import type { Computed } from "#Source/reactor/index.ts" import { computed, signal } from "#Source/reactor/index.ts" import type { Route, RouteHistoryEntry, Router, RouteRecord } from "../router/index.ts" /** * @description 创建路由驱动器时需要的输入项。 */ export interface CreateRouteDriverOptions { router: Router } /** * @description 将 Router 暴露为响应式只读视图的驱动器。 * * 该接口把当前历史记录、当前 Route 以及当前 RouteRecord 暴露为可追踪的计算值, * 方便响应式系统消费。 */ export interface RouteDriver { router: Router routeHistoryEntry: Computed route: Computed routeRecord: Computed } /** * @description 基于 Router 创建一组可响应追踪的当前路由派生值。 * * 返回结果中的计算值会随着 Router 的 `history` 事件自动更新。 */ export const createRouteDriver = (options: CreateRouteDriverOptions): RouteDriver => { const { router } = options const internalCurrentRouteHistoryEntry = signal(() => { return router.getCurrentRouteHistoryEntry() }) router.eventManager.subscribe("history", (routeHistoryEntry) => { internalCurrentRouteHistoryEntry.set(routeHistoryEntry) }) const currentRouteHistoryEntry = computed(() => { return internalCurrentRouteHistoryEntry.get() }) const currentRoute = computed(() => { return currentRouteHistoryEntry.get().to.route }) const currentRouteRecord = computed(() => { return currentRoute.get().getRecord() }) return { router, routeHistoryEntry: currentRouteHistoryEntry, route: currentRoute, routeRecord: currentRouteRecord, } }