All files / router/src/core hashNavigation.ts

88.11% Statements 215/244
98.18% Branches 54/55
94.11% Functions 16/17
88.11% Lines 215/244

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 426 427 428 429 430 431 432 433 434 435 436 437 4381x                                       1x   47x 47x 47x 47x     47x     47x 47x 47x 47x     47x   16x   16x     16x 16x 16x 16x 16x 16x     47x                                                                                         47x 54x 54x 54x 54x   54x     54x   54x     54x 54x 12x 12x 54x 54x 54x   54x 54x     47x 8x 8x 8x 8x 8x     8x 8x 8x 8x     8x 8x   8x 8x   47x 12x 12x 12x 12x 12x     12x 12x 12x 12x 12x     12x 12x   12x 12x   47x 12x 12x 12x 12x 12x               47x 20x         20x   20x       20x     20x     20x 37x 37x     37x 17x 17x 17x 20x     20x 19x 19x 19x     20x     20x 20x     47x   45x 45x     45x   42x     42x     42x     42x       42x     42x 42x 42x 42x 42x     42x 45x   3x   3x   1x   1x     1x 1x     2x 2x 45x   47x 4x   4x 1x 1x   3x 3x     3x   4x   1x 1x 1x     3x     3x 4x   47x 9x 3x 3x 3x   6x 6x     9x   1x 1x 1x     6x     6x 9x   47x 4x 1x 1x   3x 3x     4x   1x 1x 1x     3x     3x 4x   47x 2x     2x 2x     2x 1x 1x 1x     2x     2x     2x   2x 2x   2x 2x   47x 3x     3x     3x 3x     47x 143x   143x 12x 12x 47x   47x   16x 16x 16x   47x 28x     28x 28x     28x 28x     47x   47x 47x 47x 47x     47x 47x 47x 47x 47x 47x     47x     47x     47x   47x 47x 47x     1x  
import { signal, computed, effect, batch } from '@preact/signals';
 
import type { 
    NavigationResult, 
    NavigationState, 
    NavigationHistoryEntry, 
    NavigationOptions, 
    HashNavigation
} from '#src/types';
import { 
    createHistoryEntry, 
    createNavigationResult, 
    getHash, 
    createHash 
} from '#src/helpers';
 
/**
 * Implementation of hash-based router core using Preact signals
 * and following the Navigation API interface, while using window.history for compatibility
 */
export const createHashNavigation = (): HashNavigation => {
    // Internal signals to manage router state
    const _currentURL = signal<string>(window.location.href);
    const _entries = signal<NavigationHistoryEntry[]>([createHistoryEntry(window.location.href)]);
    const _currentIndex = signal<number>(0);
    const _navigations = signal<Map<string, NavigationResult>>(new Map());
    
    // Storage for active subscriptions
    const _subscriptions = new Set<VoidFunction>();
    
    // Public computed signals that reflect the router state
    const currentEntry = computed(() => _entries.value[_currentIndex.value]);
    const entries = computed(() => [..._entries.value]);
    const canGoBack = computed(() => _currentIndex.value > 0);
    const canGoForward = computed(() => _currentIndex.value < _entries.value.length - 1);
 
    // Initialize the router state from the current location
    const initializeFromLocation = (): void => {
        // Try to get existing state from the history API        
        const state = window.history.state ?? currentEntry.value.state;
        
        const initialEntry = createHistoryEntry(_currentURL.value, state);
        
        // Using batch to update multiple signals at once
        batch(() => {
            _currentURL.value = initialEntry.url as string;
            _entries.value = [initialEntry];
            _currentIndex.value = 0;
        });
    };
 
    // Handle hash change events from the window
    const handleHashChange = (event: HashChangeEvent): void => {        
        // This is triggered by the browser, so we need to update our state
        const newUrl = event.newURL;
        const state = window.history.state;
        
        // Check if this is a navigation we already know about
        const existingEntryIndex = _entries.value.findIndex((entry) => entry.url === newUrl);
        
        if(existingEntryIndex >= 0) {
            // If we already have this entry, just update the index
            _currentIndex.value = existingEntryIndex;
            
            // Update state if it has changed
            const existingEntry = _entries.value[existingEntryIndex];
 
            if(JSON.stringify(existingEntry.state) !== JSON.stringify(state)) {
                const updatedEntries = [..._entries.value];
 
                updatedEntries[existingEntryIndex] = {
                    ...existingEntry,
                    state,
                };
                _entries.value = updatedEntries;
            }
        } else {
            // Otherwise, create a new entry
            const newEntry = createHistoryEntry(newUrl, state, _entries.value.length);
            const newEntries = [..._entries.value];
            
            // If we navigated from a point in history, remove the forward entries
            if(_currentIndex.value < _entries.value.length - 1) {
                newEntries.splice(_currentIndex.value + 1);
            }
            
            newEntries.push(newEntry);
            
            // Using batch to update multiple signals at once
            batch(() => {
                _entries.value = newEntries;
                _currentIndex.value = newEntries.length - 1;
            });
        }
    };
 
    // Helper function to update navigation state
    const updateNavigationState = (
        destination: NavigationHistoryEntry,
        newCurrentIndex: number,
        newUrl?: string
    ): NavigationResult => {
        // Create a navigation result
        const result = createNavigationResult(destination);
        
        // Store the navigation for potential future reference
        const navigations = new Map(_navigations.value);
 
        navigations.set(destination.key, result);
        
        // Using batch to update multiple signals at once
        batch(() => {
            if(newUrl) {
                _currentURL.value = newUrl;
            }
            _currentIndex.value = newCurrentIndex;
            _navigations.value = navigations;
        });
        
        return result;
    };
 
    // Handle entry state updates
    const updateEntryState = (
        entryIndex: number,
        newState: NavigationState | null | undefined
    ): NavigationHistoryEntry => {
        const newEntries = [..._entries.value];
        const entry = newEntries[entryIndex];
        
        // Create updated entry with new state
        const updatedEntry = {
            ...entry,
            state: newState,
        };
        
        // Update our entries array
        newEntries[entryIndex] = updatedEntry;
        _entries.value = newEntries;
        
        return updatedEntry;
    };
 
    const updateEntryUrl = (
        entryIndex: number,
        newUrl: string
    ): NavigationHistoryEntry => {
        const newEntries = [..._entries.value];
        const entry = newEntries[entryIndex];
        
        // Create updated entry with new url
        const updatedEntry = {
            ...entry,
            url : newUrl,
            hash: getHash(newUrl),
        };
        
        // Update our entries array
        newEntries[entryIndex] = updatedEntry;
        _entries.value = newEntries;
        
        return updatedEntry;
    };
 
    const updateCurrentEntryHash = (hash: string) => {
        return updateEntryUrl(
            _currentIndex.value, 
            new URL(`#${createHash(hash)}`, window.location.href).href
        );
    };
    
    /**
     * Subscribe to navigation changes with current and previous history entries
     * and current hash route
     * @param callback - Callback function called when navigation changes
     * @returns Unsubscribe function
     */
    const subscribe = (
        callback: (
            entry: NavigationHistoryEntry, 
            prevEntry: NavigationHistoryEntry | null, 
            hash: string
        ) => void
    ): VoidFunction => {        
        // Get the current entry before setting up the effect
        const current = currentEntry.value;
        
        // Track the previous entry for change detection
        // Initialize with current to avoid double call
        let previousEntry: NavigationHistoryEntry | null = current;
        
        // Call the callback with the current value on initial subscription
        callback(current, null, current.hash);
        
        // Create an effect that tracks changes in the currentEntry signal
        const unsubscribe = effect(() => {
            const entry = currentEntry.value;
            const currentHash = entry.hash;
            
            // Call the callback with current and previous entries
            if(previousEntry !== entry) {
                callback(entry, previousEntry, currentHash);
                previousEntry = entry;
            }
        });
        
        // Create a complete unsubscribe function that also removes the subscription from storage
        const completeUnsubscribe = () => {
            unsubscribe();
            _subscriptions.delete(completeUnsubscribe);
        };
        
        // Save the subscription in storage
        _subscriptions.add(completeUnsubscribe);
        
        // Return the unsubscribe function
        return completeUnsubscribe;
    };
    
    // Public API methods
    const navigate = (hash: string, options: NavigationOptions = {}): NavigationResult => {
        // Create full URL by resolving against current location
        const originalHash = currentEntry.value.hash;
        const fullUrl = new URL(`#${createHash(hash)}`, window.location.href).href;
        
        // Only navigate if the hash part actually changed
        if(originalHash !== hash) {            
            // Create a new destination with state from options
            const destination = createHistoryEntry(fullUrl, options.state as NavigationState, _entries.value.length);
            
            // Use history pushState to update the URL without reloading
            window.history.pushState(options.state || null, '', fullUrl);
            
            // Update our internal state
            const newEntries = [..._entries.value];
            
            // If we navigated from a point in history, remove the forward entries
            if(_currentIndex.value < _entries.value.length - 1) {
                newEntries.splice(_currentIndex.value + 1);
            }
            
            newEntries.push(destination);
            
            // Using batch to update multiple signals at once
            batch(() => {
                _entries.value = newEntries;
                _currentIndex.value = newEntries.length - 1;
                _currentURL.value = fullUrl;
            });
            
            // Update navigation state
            return updateNavigationState(destination, newEntries.length - 1);
        } else {
            // If hash didn't change, check if state changed
            const currentEntryValue = currentEntry.value;
 
            if(options.state && JSON.stringify(currentEntryValue.state) !== JSON.stringify(options.state)) {
                // Update state without changing URL
                window.history.replaceState(options.state, '', fullUrl);
                
                const updatedEntry = updateEntryState(_currentIndex.value, options.state as NavigationState);
                
                // Create and return a navigation result for the updated entry
                return createNavigationResult(updatedEntry);
            }
            
            // If nothing changed, return a result that resolves immediately with current entry
            return createNavigationResult(currentEntryValue);
        }
    };
 
    const traverseTo = (key: string, options: NavigationOptions = {}): NavigationResult | null => {
        const entryIndex = _entries.value.findIndex((entry) => entry.key === key);
        
        if(entryIndex === -1) {
            return null;
        }
        
        const destination = _entries.value[entryIndex];
        const delta = entryIndex - _currentIndex.value;
        
        // Handle potential state update if options include state
        let updatedDestination = destination;
 
        if(options.state) {
            // Update history state and our entries
            window.history.replaceState(options.state, '', destination.url);
            updatedDestination = updateEntryState(entryIndex, options.state as NavigationState);
        }
        
        // Use history.go to navigate through history
        window.history.go(delta);
        
        // Update navigation state
        return updateNavigationState(updatedDestination, entryIndex, updatedDestination.url);
    };
 
    const back = (options: NavigationOptions = {}): NavigationResult | null => {
        if(!canGoBack.value) {
            window.history.back();
            return null;
        }
        
        const prevIndex = _currentIndex.value - 1;
        let destination = _entries.value[prevIndex];
        
        // Handle potential state update if options include state
        if(options.state) {
            // Update history state before going back
            window.history.replaceState(options.state, '', destination.url);
            destination = updateEntryState(prevIndex, options.state as NavigationState);
        }
        
        // Use history.back to navigate back
        window.history.back();
        
        // Update navigation state
        return updateNavigationState(destination, prevIndex, destination.url);
    };
 
    const forward = (options: NavigationOptions = {}): NavigationResult | null => {
        if(!canGoForward.value) {
            return null;
        }
        
        const nextIndex = _currentIndex.value + 1;
        let destination = _entries.value[nextIndex];
        
        // Handle potential state update if options include state
        if(options.state) {
            // Update history state before going forward
            window.history.replaceState(options.state, '', destination.url);
            destination = updateEntryState(nextIndex, options.state as NavigationState);
        }
        
        // Use history.forward to navigate forward
        window.history.forward();
        
        // Update navigation state
        return updateNavigationState(destination, nextIndex, destination.url);
    };
 
    const reload = (options: NavigationOptions = {}): NavigationResult => {
        const currentEntryValue = currentEntry.value;
        
        // Create a new destination to represent the reload, potentially with updated state
        const state = options.state !== undefined ? options.state : currentEntryValue.state;
        const destination = createHistoryEntry(currentEntryValue.url, state, currentEntryValue.index);
        
        // Update history state if new state is provided
        if(options.state !== undefined) {
            window.history.replaceState(options.state, '', currentEntryValue.url);
            updateEntryState(_currentIndex.value, options.state as NavigationState);
        }
        
        // Actually reload the current hash route
        window.location.hash = getHash(currentEntryValue.url);
        
        // Update navigation state
        const result = createNavigationResult(destination);
        
        // Store the navigation for potential future reference
        const navigations = new Map(_navigations.value);
 
        navigations.set(destination.key, result);
        _navigations.value = navigations;
        
        return result;
    };
 
    const updateCurrentEntry = (options: NavigationOptions = {}): void => {
        const currentIndex = _currentIndex.value;
        
        // Update the history state
        window.history.replaceState(options.state || null, '', window.location.hash);
        
        // Update entry state
        updateEntryState(currentIndex, options.state as NavigationState || null);
    };
 
    // Set up effect to synchronize URL with current entry
    const unsubscribe = effect(() => {
        const currentEntryValue = currentEntry.value;
        
        if(currentEntryValue && getHash(_currentURL.value) !== getHash(currentEntryValue.url as string)) {
            _currentURL.value = currentEntryValue.url as string;
        }
    });
 
    const create = () => {
        // Initialize and set up event listeners
        initializeFromLocation();
        window.addEventListener('hashchange', handleHashChange);
    };
 
    const destroy = (): void => {
        window.removeEventListener('hashchange', handleHashChange);
        
        // Cancel all active subscriptions
        _subscriptions.forEach((unsub) => unsub());
        _subscriptions.clear();
        
        // Cancel internal synchronization effect
        unsubscribe();
    };
 
    // Return the public API
    return {
        // Public signals
        currentEntry,
        entries,
        canGoBack,
        canGoForward,
        
        // Navigation methods
        navigate,
        traverseTo,
        back,
        forward,
        reload,
        updateCurrentEntry,
        
        // Subscription method
        subscribe,
        
        // Service methods
        updateCurrentEntryHash,
        
        // Init
        create,
        // Cleanup
        destroy,
    };
};
 
// Export a singleton instance for convenience
export const hashNavigation = createHashNavigation();