All files / react/src/router navigate.ts

100% Statements 14/14
100% Branches 5/5
100% Functions 1/1
100% Lines 14/14

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 421x                                                 1x 3x 3x 2x 1x   3x   3x 1x 3x 2x 2x   3x 3x  
import { createUrl } from '@anchorlib/router';
import type { AnyRoute, RouteComponent } from './types.js';
 
export interface NavigateOptions {
  query?: Record<string, unknown>;
  params?: Record<string, unknown>;
  replace?: boolean;
}
 
/**
 * Programmatically navigate to a route or path.
 *
 * @param path The path string to navigate to.
 * @param options Query, params, and history replacement options.
 */
export function navigate(path: string, options?: NavigateOptions): void;
 
/**
 * Programmatically navigate to a typed Route component.
 *
 * @param route The Route component defining the destination.
 * @param options Query, params, and history replacement options.
 */
export function navigate<T extends AnyRoute>(route: RouteComponent<T>, options?: NavigateOptions): void;
 
export function navigate(target: string | RouteComponent<AnyRoute>, options: NavigateOptions = {}) {
  const url =
    typeof target === 'string'
      ? createUrl(target, options.params, options.query)
      : createUrl(target.index.path, options.params, options.query);
 
  const state = { href: url, query: options.query, params: options.params };
 
  if (options.replace) {
    history.replaceState(state, '', url);
  } else {
    history.pushState(state, '', url);
  }
 
  window.dispatchEvent(new PopStateEvent('popstate', { state }));
}