All files navigation.ts

96.42% Statements 162/168
95.58% Branches 65/68
90.32% Functions 28/31
96.42% Lines 162/168

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 2032x   2x                 2x   2x 2x 475x 475x 475x   475x   2x 475x 475x 475x 475x 475x 171x 304x 475x 87x 87x 87x 475x 475x 305x 170x 475x 475x 475x 475x 2x 4x 4x   2x 419x 419x 419x 419x 419x 419x 419x 419x 419x 419x 419x   2x 311x 311x 311x 311x 311x 311x 311x 311x 311x 311x 311x 311x   2x 419x 419x   2x 311x 311x   2x       2x       2x       2x 111x 6x 6x 105x 105x 185x 185x 185x 185x 105x 105x 105x 111x 2x 111x 111x 2x 1x 1x 2x 1x 1x   2x 408x 408x 408x 2x   2x 2x 332x 332x 590x 590x 587x 590x 332x 332x     2x 234x 234x 2x 19x 19x   2x 332x 332x 2x 720x 720x   2x 613x 613x 613x 613x   613x 613x 613x 613x   2x 222x 222x 222x 222x 222x 222x 221x 222x 222x   2x 6x 6x 2x 2x 2x 2x 139x 135x 139x 113x 113x   113x 113x 113x 139x   2x 338x 334x 334x 338x 2x   170x     170x 170x 170x 170x  
import { PAGE_ID } from './increment-id';
import type { RouterParsedOptions, RouteState } from './types';
import { RouterMode } from './types';
 
type NavigationSubscribe = (url: string, state: RouteState) => void;
type NavigationGoResult = null | {
    type: 'success';
    url: string;
    state: RouteState;
};
 
const PAGE_ID_KEY = '__pageId__';
 
export class Navigation {
    public readonly options: RouterParsedOptions;
    private readonly _history: History | MemoryHistory;
    private readonly _unSubscribePopState: () => void;
    private _promiseResolve:
        | ((url?: string | null, state?: RouteState) => void)
        | null = null;
 
    public constructor(
        options: RouterParsedOptions,
        onUpdated?: NavigationSubscribe
    ) {
        const history: History =
            options.mode === RouterMode.history
                ? window.history
                : new MemoryHistory();
        const onPopStateChange: NavigationSubscribe = (url, state) => {
            const dispatchEvent = this._promiseResolve || onUpdated;
            dispatchEvent?.(url, state);
        };
        const subscribePopState =
            history instanceof MemoryHistory
                ? history.onPopState(onPopStateChange)
                : subscribeHtmlHistory(onPopStateChange);
        this.options = options;
        this._history = history;
        this._unSubscribePopState = subscribePopState;
    }
    public get length(): number {
        return this._history.length;
    }
 
    private _push(
        history: History,
        data: any,
        url?: string | URL | null
    ): RouteState {
        const state = {
            ...(data || {}),
            [PAGE_ID_KEY]: PAGE_ID.next()
        };
        history.pushState(state, '', url);
        return state;
    }
 
    private _replace(
        history: History,
        data: any,
        url?: string | URL | null
    ): RouteState {
        const oldId = history.state?.[PAGE_ID_KEY];
        const state = {
            ...(data || {}),
            [PAGE_ID_KEY]: typeof oldId === 'number' ? oldId : PAGE_ID.next()
        };
        history.replaceState(state, '', url);
        return state;
    }
 
    public push(data: any, url?: string | URL | null): RouteState {
        return this._push(this._history, data, url);
    }
 
    public replace(data: any, url?: string | URL | null): RouteState {
        return this._replace(this._history, data, url);
    }
 
    public pushHistoryState(data: any, url?: string | URL | null) {
        this._push(history, data, url);
    }
 
    public replaceHistoryState(data: any, url?: string | URL | null) {
        this._replace(history, data, url);
    }
 
    public backHistoryState() {
        return this._go(history, -1);
    }
 
    private _go(history: History, index: number): Promise<NavigationGoResult> {
        if (this._promiseResolve) {
            return Promise.resolve(null);
        }
        return new Promise<NavigationGoResult>((resolve) => {
            this._promiseResolve = (url, state) => {
                this._promiseResolve = null;
                if (typeof url !== 'string') return resolve(null);
                resolve({ type: 'success', url, state: state || {} });
            };
            setTimeout(this._promiseResolve, 80);
            history.go(index);
        });
    }
    public go(delta?: number): Promise<NavigationGoResult> {
        return this._go(this._history, delta || 0);
    }
    public forward(): Promise<NavigationGoResult> {
        return this.go(1);
    }
    public back(): Promise<NavigationGoResult> {
        return this.go(-1);
    }
 
    public destroy() {
        this._promiseResolve?.();
        this._unSubscribePopState();
    }
}
 
export class MemoryHistory implements History {
    private _entries: Array<{ state: any; url: string }> = [];
    private _index = -1;
    private get _curEntry() {
        const idx = this._index;
        if (idx < 0 || idx >= this.length) return null;
        return this._entries[idx];
    }
    private readonly _popStateCbs = new Set<NavigationSubscribe>();
    public scrollRestoration: ScrollRestoration = 'auto';
    // Return null when no current entry to align with browser history.state behavior
    // Browser history.state can be null when no state was provided
    public get state() {
        return this._curEntry?.state ?? null;
    }
    public get url() {
        return this._curEntry?.url ?? '';
    }
 
    constructor() {
        this.pushState(null, '', '/');
    }
    public get length() {
        return this._entries.length;
    }
 
    public pushState(
        data: any,
        unused: string,
        url?: string | URL | null
    ): void {
        // Remove all entries after the current position
        this._entries.splice(this._index + 1);
        this._entries.push({ state: data, url: url?.toString() ?? this.url });
        this._index = this._entries.length - 1;
    }
 
    public replaceState(
        data: any,
        unused: string,
        url?: string | URL | null
    ): void {
        const curEntry = this._curEntry;
        if (!curEntry) return;
        curEntry.state = { ...data };
        if (url) curEntry.url = url.toString();
    }
 
    public back(): void {
        this.go(-1);
    }
    public forward(): void {
        this.go(1);
    }
    public go(delta?: number): void {
        if (!delta) return;
        const newIdx = this._index + delta;
        if (newIdx < 0 || newIdx >= this.length) return;
        this._index = newIdx;
        const entry = this._curEntry!;
        // Simulate the async popstate event of html history as closely as possible
        setTimeout(() => {
            this._popStateCbs.forEach((cb) => cb(entry.url, entry.state));
        });
    }
 
    public onPopState(cb: NavigationSubscribe) {
        if (typeof cb !== 'function') return () => {};
        this._popStateCbs.add(cb);
        return () => this._popStateCbs.delete(cb);
    }
}
 
function subscribeHtmlHistory(cb: NavigationSubscribe) {
    // Use history.state || {} to handle null state from browser history
    // Browser history.state can be null, but we normalize it to empty object
    const wrapper = () => cb(location.href, history.state || {});
    window.addEventListener('popstate', wrapper);
    return () => window.removeEventListener('popstate', wrapper);
}