All files / router/src/core hashRouter.ts

100% Statements 107/107
91.66% Branches 33/36
93.75% Functions 15/16
100% Lines 107/107

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 2081x                                   1x 16x 16x 16x   16x 28x 16x 16x             1x   22x             22x 22x     22x   22x 22x           22x 5x 4x   5x 2x 2x   5x 3x 3x 3x 3x 5x             22x 13x     13x 11x 11x 11x     13x   13x   13x     13x 13x 13x   24x 24x 24x 24x 24x 13x     13x     13x   1x 1x   13x 13x             22x 3x 3x             22x 14x 14x         22x 2x 2x         22x 1x 1x             22x 9x   9x 9x   22x   22x   22x   22x   22x 7x 7x 7x   7x 7x 7x 7x 7x 7x 22x   22x   22x     22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x   1x  
import { createHash, getParamsFromUrl, getRouteItem, getRouteMap, parseQueryParams } from '#src/helpers';
import { computed } from '@preact/signals';
import { 
    HashNavigation, 
    HashRouter, 
    InitializeRouterConfig, 
    NavigationHistoryEntry, 
    QueryParams, 
    SubscribeChangeConfig 
} from '../types';
import { createHashNavigation } from './hashNavigation';
 
/**
 * Helper function to subscribe to navigation events
 * @param navigation - The navigation object
 * @param callback - Function to call when navigation occurs
 * @returns A function to unsubscribe the listener
 */
const subscribeToNavigationEvents = (
    navigation: HashNavigation,
    callback: (entry: NavigationHistoryEntry, prev?: NavigationHistoryEntry | null) => void
): VoidFunction => {
    // Use the new subscribe method instead of events
    return navigation.subscribe((entry, prevEntry, _hash) => {
        callback(entry, prevEntry);
    });
};
 
/**
 * Creates a hash-based router that implements the HashRouter interface
 * @param createNavigation - The function create navigation object to use for routing operations
 * @returns An object implementing the HashRouter interface
 */
export const createHashRouter = (hashNavigation: HashNavigation): HashRouter => {
    // Store the router configuration
    let routerConfig: InitializeRouterConfig | null = null;
 
    /**
     * Checks if a hash exists in the configured route names
     * @param hash - The hash to check
     * @returns boolean indicating if the hash exists in routes
     */
    const checkExistPage = (hash: string): boolean => {
        if(!routerConfig) return false;
    
        // Remove the leading '#' if present for comparison
        const normalizedHash = hash.startsWith('#') ? hash.substring(1) : hash;
 
        return routerConfig.routeNames.includes(normalizedHash);
    };
 
    /**
     * Replaces the current state and/or hash
     * @param config - Optional configuration for the state replacement
     */
    const replaceState = (config?: { state?: Record<string, unknown>; hash?: string }): void => {        
        if(!config) return;    
        const currentEntry = hashNavigation.currentEntry.value;
    
        if(config.state) {
            hashNavigation.updateCurrentEntry(config.state);
        }
    
        if(config.hash && config.hash !== currentEntry.hash) {
            hashNavigation.navigate(config.hash, { 
                state: config.state || currentEntry.state,
            });
        }
    };
 
    /**
     * Creates the router and subscribes to location changes
     * @param config - Configuration containing onChange handler and router setup
     * @returns A function to unsubscribe the listener
     */
    const create = (config: SubscribeChangeConfig): VoidFunction => {
        const { onChange, config: initConfig, } = config;
 
        // Set initial home as initial hash if it empty
        if(!window.location.hash && initConfig.homeUrl) {            
            window.location.hash = `#${createHash(initConfig.homeUrl)}`;
            hashNavigation.updateCurrentEntryHash(initConfig.homeUrl);
        }
  
        // Store the configuration for future use
        routerConfig = initConfig;
  
        let prevLocation: NavigationHistoryEntry | null = null;
 
        hashNavigation.create();
  
        // Subscribe to navigation events
        const unsubscribe = subscribeToNavigationEvents(
            hashNavigation,
            (entry) => {
                // Only trigger onChange if this is a different location                
                if(!prevLocation || prevLocation.url !== entry.url) {                    
                    onChange(entry);
                    prevLocation = entry;
                }
            }
        );
  
        // Check current hash
        const currentHash = hashNavigation.currentEntry.value.hash;
        
        // If current hash is empty, navigate to home URL
        if(currentHash && !checkExistPage(currentHash) && routerConfig.homeUrl) {
            // Replace the current history entry with the home URL
            replaceState({ hash: routerConfig.homeUrl, });
        }
  
        return unsubscribe;
    };
 
    /**
     * Subscribes to history changes
     * @param callback - Function to call when location changes
     * @returns A function to unsubscribe the listener
     */
    const subscribe = (callback: (update: NavigationHistoryEntry, prevLocation?: NavigationHistoryEntry | null) => void): VoidFunction => {
        return subscribeToNavigationEvents(hashNavigation, callback);
    };
 
    /**
     * Navigates to a specific hash
     * @param hash - The hash to navigate to
     * @param state - Optional state to associate with this navigation
     */
    const navigate = (hash: string, state?: Record<string, unknown>) => {
        return hashNavigation.navigate(hash, { state, });
    };
 
    /**
     * Navigates back in history
     */
    const goBack = (): void => {
        hashNavigation.back();
    };
 
    /**
     * Alias for goBack
     */
    const goToPrev = (): void => {
        hashNavigation.back();
    };
 
    /**
     * Checks if a page exists by hash in the routes provided during initialization
     * @param hash - Optional hash to check (uses current hash if not provided)
     * @returns boolean indicating if the page exists in the configured routes
     */
    const hasPage = (hash?: string): boolean => {
        const hashToCheck = hash || hashNavigation.currentEntry.value.hash;
 
        return checkExistPage(hashToCheck);
    };
 
    const getHash = () => hashNavigation.currentEntry.value.hash;
 
    const getState = () => hashNavigation.currentEntry.value.state;
 
    const destroy = () => hashNavigation.destroy();
 
    const getConfig = () => routerConfig;
 
    const currentEntry = computed(() => {
        const entry = hashNavigation.currentEntry.value;
        const hash = entry.hash;
        const pattern = getRouteItem(getRouteMap(routerConfig?.routeNames ?? []), hash);
 
        return {
            ...entry,
            pattern,
            getParams: <T>() => pattern ? getParamsFromUrl(pattern, hash) as T : {} as T,
            getQuery : <T extends QueryParams>() => parseQueryParams<T>(hash),
        };
    });
 
    const state = computed(() => currentEntry.value.state);
 
    const hash = computed(() => currentEntry.value.hash);
 
    // Return the router object with references to the functions defined in the closure
    return {
        _navigation : hashNavigation,
        entries     : hashNavigation.entries,
        currentEntry,
        state,
        hash,
        canGoBack   : hashNavigation.canGoBack,
        canGoForward: hashNavigation.canGoForward,
        getHash,
        getState,
        create,
        subscribe,
        navigate,
        replaceState,
        goBack,
        goToPrev,
        hasPage,
        destroy,
        getConfig,
    };
};
 
export const hashRouter = createHashRouter(createHashNavigation());