A web-based router
that is framework agnostic
.
add to your project using :
npm i @riadh-adrani/dom-router
create a router object that manages and react to location/history changes.
new Router<T>(RouterConfig<T>);
will throw if
base
is invalid; does not start with/
.
unload router and perform need actions.
process current path and return a boolean
that indicates if an update should happen or not.
navigate to the given destination and perform necessary updates if needed.
get element at a given depth or undefined
otherwise.
get current path, stripped out of base.
get closest route params.
get current route search query params.
transform a destination route to a valid href string or undefined
otherwise.
check if url
is valid as a relative path
function isUrlNavigatable(url: string): boolean;
enum RouterType {
Browser = 'browser',
Hash = 'hash',
}
interface RouterConfig<T = unknown> {
/** array of routes that will be considered by the router */
routes: Array<RawRoute<T>>;
/** handler that will run each time the url changes */
onChanged: () => void;
/** router type, ``Browser`` by default */
type?: RouterType;
/** router base, should start with `/` */
base?: string;
/** define if the router should scroll the document body to the top */
correctScrolling?: boolean;
/** function that will transform a title, useful for setting title prefix and suffixes */
transformTitle?: (title?: string) => string;
}
interface IndexRawRoute<T = unknown> {
path: '';
name?: string;
element?: T;
title?: string;
}
interface CatchRawRoute<T = unknown> {
path: '*';
title?: string;
element?: T;
}
interface PathRawRoute<T = unknown> {
path: string;
name?: string;
element?: T;
title?: string;
children?: Array<RawRoute<T>>;
}
interface LayoutRawRoute<T = unknown> {
element: T;
children?: Array<RawRoute<T>>;
}
type RawRoute<T = unknown> =
| LayoutRawRoute<T>
| IndexRawRoute<T>
| CatchRawRoute<T>
| PathRawRoute<T>;
interface DestinationOptions {
replace?: boolean;
}
type PathDestinationRequest = string;
type RelativeDestinationRequest = number;
interface NamedDestinationRequest {
name: string;
query?: Record<string, string | number>;
params?: Record<string, string>;
hash?: string;
}
type DestinationRequest =
| NamedDestinationRequest
| PathDestinationRequest
| RelativeDestinationRequest;