All files route-transition.ts

95.29% Statements 304/319
89.88% Branches 80/89
95.45% Functions 21/22
95.29% Lines 304/319

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 4262x 2x           2x                 2x                     2x 2x 757x 757x 757x 757x 757x 15x 15x 757x   2x 543x 543x 543x 543x 543x 543x     543x   2x 659x 659x 659x 659x 659x 659x 661x 661x 12x 12x 6x 6x 6x 6x 6x 6x 12x 659x 659x 659x   2x 696x 696x 696x 696x 696x     356x 356x 356x     543x 287x 287x 2x 2x     2x 287x 696x   2x 666x 666x 666x 666x 666x     666x 666x 668x 666x     666x 601x 36x 36x 7x 7x 36x 601x 666x   2x 666x 666x 666x 666x     666x     666x 66x 66x 66x 66x     209x   55x 55x 1x 1x     1x 55x 55x 666x   2x 721x 721x 721x 721x   721x 721x 70x 70x 6x 6x 70x 721x   2x 697x 697x 697x 697x 697x             697x 697x 358x 697x 123x 697x 94x 697x 22x 697x 22x 697x   697x 78x 697x 697x 2x               2x 2x 358x 358x 358x 356x 356x 358x 2x 2x 2x 358x 2x 123x 123x 123x 123x 123x 2x 94x 94x 94x 94x 94x 2x 22x 22x 2x 22x 22x 2x       2x 78x 78x 78x 78x 78x 78x 78x 2x                                 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x       2x 2x   2x 2x 2x 2x 2x       2x 2x 2x 2x 2x   2x       2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x   2x 2x   2x 2x 2x 2x 2x 2x 2x 2x             2x 404x   404x     404x     404x 404x 404x 404x   404x 404x 404x   404x 206x 206x 212x 212x 206x   404x 16x 16x 11x 11x 16x   404x 337x 337x 337x   404x 752x 752x 752x 752x 752x 752x 752x 752x 752x 752x 752x 752x 752x 712x 712x 708x   708x 708x 23x 23x 708x   708x 752x   404x 752x 752x 752x 752x 80x 752x 5606x 5606x 752x   752x 752x 752x 752x 752x 752x 752x 752x 404x  
import { Route } from './route';
import {
    type RouteTask,
    RouteTaskController,
    createRouteTask
} from './route-task';
import type { Router } from './router';
import { RouteType } from './types';
 
import type {
    RouteConfirmHook,
    RouteConfirmHookResult,
    RouteHandleHook,
    RouteLocationInput,
    RouteNotifyHook
} from './types';
import {
    isRouteMatched,
    isUrlEqual,
    isValidConfirmHookResult,
    removeFromArray
} from './util';
 
/**
 * Route transition hooks responsible for handling different stages of the navigation process.
 * Each hook is responsible for a specific aspect of route transition.
 */
export const ROUTE_TRANSITION_HOOKS = {
    async fallback(
        to: Route,
        from: Route | null,
        router: Router
    ): Promise<RouteConfirmHookResult> {
        if (to.matched.length === 0) {
            return router.parsedOptions.fallback;
        }
    },
 
    async override(
        to: Route,
        from: Route | null,
        router: Router
    ): Promise<RouteConfirmHookResult> {
        const result = await to.config?.override?.(to, from, router);
        if (isValidConfirmHookResult(result)) {
            return result;
        }
    },
 
    async asyncComponent(
        to: Route,
        from: Route | null,
        router: Router
    ): Promise<RouteConfirmHookResult> {
        await Promise.all(
            to.matched.map(async (matched) => {
                const { asyncComponent, component } = matched;
                if (!component && typeof asyncComponent === 'function') {
                    try {
                        const result = await asyncComponent();
                        matched.component = result;
                    } catch {
                        throw new Error(
                            `Async component '${matched.compilePath}' is not a valid component.`
                        );
                    }
                }
            })
        );
    },
 
    async beforeLeave(
        to: Route,
        from: Route | null,
        router: Router
    ): Promise<RouteConfirmHookResult> {
        if (!from?.matched.length) return;
 
        // Find routes that need to be left (routes in 'from' but not in 'to').
        const leavingRoutes = from.matched.filter(
            (fromRoute) => !to.matched.some((toRoute) => toRoute === fromRoute)
        );
 
        // Execute beforeLeave guards in order from child to parent.
        for (let i = leavingRoutes.length - 1; i >= 0; i--) {
            const route = leavingRoutes[i];
            if (route.beforeLeave) {
                const result = await route.beforeLeave(to, from, router);
                if (isValidConfirmHookResult(result)) {
                    return result;
                }
            }
        }
    },
 
    async beforeEnter(
        to: Route,
        from: Route | null,
        router: Router
    ): Promise<RouteConfirmHookResult> {
        if (!to.matched.length) return;
 
        // Find routes that need to be entered (routes in 'to' but not in 'from').
        const enteringRoutes = to.matched.filter(
            (toRoute) =>
                !from?.matched.some((fromRoute) => fromRoute === toRoute)
        );
 
        // Execute beforeEnter guards in order from parent to child.
        for (const route of enteringRoutes) {
            if (route.beforeEnter) {
                const result = await route.beforeEnter(to, from, router);
                if (isValidConfirmHookResult(result)) {
                    return result;
                }
            }
        }
    },
 
    async beforeUpdate(
        to: Route,
        from: Route | null,
        router: Router
    ): Promise<RouteConfirmHookResult> {
        // beforeUpdate is only executed when parameters change within the exact same route combination.
        // Quick check: if the final route configs are different, it's definitely not the same combination.
        if (!isRouteMatched(to, from, 'route')) return;
 
        // Detailed check: the 'matched' arrays of both routes must be identical.
        if (!from || to.matched.length !== from.matched.length) return;
        const isSameRouteSet = to.matched.every(
            (toRoute, index) => toRoute === from.matched[index]
        );
        if (!isSameRouteSet) return;
 
        // Only execute beforeUpdate when path parameters or query parameters change.
        if (!isRouteMatched(to, from, 'exact')) {
            // Execute beforeUpdate guards in order from parent to child.
            for (const route of to.matched) {
                if (route.beforeUpdate) {
                    const result = await route.beforeUpdate(to, from, router);
                    if (isValidConfirmHookResult(result)) {
                        return result;
                    }
                }
            }
        }
    },
 
    async beforeEach(
        to: Route,
        from: Route | null,
        router: Router
    ): Promise<RouteConfirmHookResult> {
        // Access the transition instance from the router to get guards
        const transition = router.transition;
        for (const guard of transition.guards.beforeEach) {
            const result = await guard(to, from, router);
            if (isValidConfirmHookResult(result)) {
                return result;
            }
        }
    },
 
    async confirm(
        to: Route,
        from: Route | null,
        router: Router
    ): Promise<RouteConfirmHookResult> {
        if (to.confirm) {
            const result = await to.confirm(to, from, router);
            if (isValidConfirmHookResult(result)) {
                return result;
            }
        }
 
        switch (to.type) {
            case RouteType.push:
                return ROUTE_TYPE_HANDLERS.push;
            case RouteType.replace:
                return ROUTE_TYPE_HANDLERS.replace;
            case RouteType.restartApp:
                return ROUTE_TYPE_HANDLERS.restartApp;
            case RouteType.pushWindow:
                return ROUTE_TYPE_HANDLERS.pushWindow;
            case RouteType.replaceWindow:
                return ROUTE_TYPE_HANDLERS.replaceWindow;
            case RouteType.pushLayer:
                return ROUTE_TYPE_HANDLERS.pushLayer;
            default:
                return ROUTE_TYPE_HANDLERS.default;
        }
    }
} satisfies Record<string, RouteConfirmHook>;
 
/**
 * Route type handlers configuration.
 * Maps each route type to its corresponding navigation handler function.
 * These handlers perform the actual navigation operations like updating browser state,
 * managing micro-app updates, and handling different navigation patterns.
 */
export const ROUTE_TYPE_HANDLERS = {
    push(to, from, router) {
        router.transition.route = to;
        router.microApp._update(router);
        if (!isUrlEqual(to.url, from?.url)) {
            const newState = router.navigation.push(to.state, to.url);
            to.applyNavigationState(newState);
        } else {
            const newState = router.navigation.replace(to.state, to.url);
            to.applyNavigationState(newState);
        }
    },
    replace(to, from, router) {
        router.transition.route = to;
        router.microApp._update(router);
        const newState = router.navigation.replace(to.state, to.url);
        to.applyNavigationState(newState);
    },
    restartApp(to, from, router) {
        router.transition.route = to;
        router.microApp._update(router, true);
        const newState = router.navigation.replace(to.state, to.url);
        to.applyNavigationState(newState);
    },
    pushWindow(to, from, router) {
        return router.parsedOptions.fallback(to, from, router);
    },
    replaceWindow(to, from, router) {
        return router.parsedOptions.fallback(to, from, router);
    },
    async pushLayer(to, from, router) {
        const { promise } = await router.createLayer(to);
        return promise;
    },
    default(to, from, router) {
        router.transition.route = to;
        router.microApp._update(router);
        if (!isUrlEqual(to.url, from?.url)) {
            const newState = router.navigation.replace(to.state, to.url);
            to.applyNavigationState(newState);
        }
    }
} satisfies Record<string, RouteHandleHook>;
 
/**
 * Route transition pipeline configuration.
 * Defines the sequence of hooks and guards that should be executed for each route type.
 * The order matters: hooks are executed sequentially from first to last.
 *
 * Pipeline stages:
 * - fallback: Handle unmatched routes
 * - override: Allow route override logic
 * - beforeLeave: Execute before leaving current route
 * - beforeEach: Global navigation guard
 * - beforeUpdate: Execute before updating route (same component)
 * - beforeEnter: Execute before entering new route
 * - asyncComponent: Load async components
 * - confirm: Final confirmation and navigation execution
 */
const ROUTE_TRANSITION_PIPELINE = {
    [RouteType.push]: [
        ROUTE_TRANSITION_HOOKS.fallback,
        ROUTE_TRANSITION_HOOKS.override,
        ROUTE_TRANSITION_HOOKS.beforeLeave,
        ROUTE_TRANSITION_HOOKS.beforeEach,
        ROUTE_TRANSITION_HOOKS.beforeUpdate,
        ROUTE_TRANSITION_HOOKS.beforeEnter,
        ROUTE_TRANSITION_HOOKS.asyncComponent,
        ROUTE_TRANSITION_HOOKS.confirm
    ],
 
    [RouteType.replace]: [
        ROUTE_TRANSITION_HOOKS.fallback,
        ROUTE_TRANSITION_HOOKS.override,
        ROUTE_TRANSITION_HOOKS.beforeLeave,
        ROUTE_TRANSITION_HOOKS.beforeEach,
        ROUTE_TRANSITION_HOOKS.beforeUpdate,
        ROUTE_TRANSITION_HOOKS.beforeEnter,
        ROUTE_TRANSITION_HOOKS.asyncComponent,
        ROUTE_TRANSITION_HOOKS.confirm
    ],
    [RouteType.pushWindow]: [
        ROUTE_TRANSITION_HOOKS.fallback,
        ROUTE_TRANSITION_HOOKS.override,
        // ROUTE_TRANSITION_HOOKS.beforeLeave
        ROUTE_TRANSITION_HOOKS.beforeEach,
        // ROUTE_TRANSITION_HOOKS.beforeUpdate
        // ROUTE_TRANSITION_HOOKS.beforeEnter
        // ROUTE_TRANSITION_HOOKS.asyncComponent
        ROUTE_TRANSITION_HOOKS.confirm
    ],
 
    [RouteType.replaceWindow]: [
        ROUTE_TRANSITION_HOOKS.fallback,
        ROUTE_TRANSITION_HOOKS.override,
        ROUTE_TRANSITION_HOOKS.beforeLeave,
        ROUTE_TRANSITION_HOOKS.beforeEach,
        // ROUTE_TRANSITION_HOOKS.beforeUpdate
        // ROUTE_TRANSITION_HOOKS.beforeEnter
        // ROUTE_TRANSITION_HOOKS.asyncComponent
        ROUTE_TRANSITION_HOOKS.confirm
    ],
    [RouteType.pushLayer]: [
        ROUTE_TRANSITION_HOOKS.fallback,
        ROUTE_TRANSITION_HOOKS.override,
        // ROUTE_TRANSITION_HOOKS.beforeLeave
        ROUTE_TRANSITION_HOOKS.beforeEach,
        // ROUTE_TRANSITION_HOOKS.beforeUpdate
        // ROUTE_TRANSITION_HOOKS.beforeEnter
        // ROUTE_TRANSITION_HOOKS.asyncComponent
        ROUTE_TRANSITION_HOOKS.confirm
    ],
    [RouteType.restartApp]: [
        ROUTE_TRANSITION_HOOKS.fallback,
        // ROUTE_TRANSITION_HOOKS.override,
        ROUTE_TRANSITION_HOOKS.beforeLeave,
        ROUTE_TRANSITION_HOOKS.beforeEach,
        ROUTE_TRANSITION_HOOKS.beforeUpdate,
        ROUTE_TRANSITION_HOOKS.beforeEnter,
        ROUTE_TRANSITION_HOOKS.asyncComponent,
        ROUTE_TRANSITION_HOOKS.confirm
    ],
 
    [RouteType.unknown]: [
        ROUTE_TRANSITION_HOOKS.fallback,
        // ROUTE_TRANSITION_HOOKS.override,
        ROUTE_TRANSITION_HOOKS.beforeLeave,
        ROUTE_TRANSITION_HOOKS.beforeEach,
        ROUTE_TRANSITION_HOOKS.beforeUpdate,
        ROUTE_TRANSITION_HOOKS.beforeEnter,
        ROUTE_TRANSITION_HOOKS.asyncComponent,
        ROUTE_TRANSITION_HOOKS.confirm
    ]
} satisfies Record<string, RouteConfirmHook[]>;
 
/**
 * Route Transition Manager
 * Responsible for managing all route transition logic, including guard execution,
 * task processing, and status updates.
 */
export class RouteTransition {
    private readonly router: Router;
 
    public route: Route | null = null;
 
    // Task controller for the current transition.
    private _controller: RouteTaskController | null = null;
 
    // Guard arrays, responsible for storing navigation guards.
    public readonly guards = {
        beforeEach: [] as RouteConfirmHook[],
        afterEach: [] as RouteNotifyHook[]
    };
 
    constructor(router: Router) {
        this.router = router;
    }
 
    public beforeEach(guard: RouteConfirmHook): () => void {
        this.guards.beforeEach.push(guard);
        return () => {
            removeFromArray(this.guards.beforeEach, guard);
        };
    }
 
    public afterEach(guard: RouteNotifyHook): () => void {
        this.guards.afterEach.push(guard);
        return () => {
            removeFromArray(this.guards.afterEach, guard);
        };
    }
 
    public destroy(): void {
        this._controller?.abort();
        this._controller = null;
    }
 
    public async to(
        toType: RouteType,
        toInput: RouteLocationInput
    ): Promise<Route> {
        const from = this.route;
        const to = await this._runTask(
            new Route({
                options: this.router.parsedOptions,
                toType,
                toInput,
                from: from?.url ?? null
            }),
            from
        );
        if (typeof to.handle === 'function') {
            to.handleResult = await to.handle(to, from, this.router);
        }
 
        if (to.handle) {
            for (const guard of this.guards.afterEach) {
                guard(to, from, this.router);
            }
        }
 
        return to;
    }
 
    private async _runTask(to: Route, from: Route | null): Promise<Route> {
        this._controller?.abort();
        this._controller = new RouteTaskController();
        const taskFunctions: RouteConfirmHook[] =
            ROUTE_TRANSITION_PIPELINE[to.type] ||
            ROUTE_TRANSITION_PIPELINE[RouteType.unknown];
        const tasks = taskFunctions.map<RouteTask>((taskFn) => ({
            name: taskFn.name,
            task: taskFn
        }));
 
        return createRouteTask({
            to,
            from,
            tasks,
            controller: this._controller,
            router: this.router
        });
    }
}