@spa-tools/core-router
Vanilla Reference
The Core Router is designed to be framework agnostic and can be used with any JavaScript library. This reference will cover the usage of the Core Router with Typescript but works for Javascript as well (simply ignore all type usage).
routesFactory()
The routesFactory<R>
function returns a factory method, which when called transforms route
definitions into a routes object. The resulting routes object is what you use in your app whenever
you need to provide routes to a Core Router or when you need to specify a route for navigation.
The generic R
type is used to define the shape of the route that will be created and must
extend the default CoreRoute
type.
Usage
import { CoreRoute, routesFactory } from '@spa-tools/core-router';
// adding custom properties to your routes is as simple
// as creating an interface that extends CoreRoute
interface MyCustomRoute extends CoreRoute {
requiresAuth: boolean;
}
// to create your routes, first generate a route factory method
const createMyRoutes = routesFactory<MyCustomRoute>();
// next define and create all of your routes, which you'll
// typically export to use throughout your app
export const myRoutes = createMyRoutes({
dashboardRoute: {
path: '/',
requiresAuth: true,
},
financialsRoute: {
path: '/financials',
requiresAuth: true,
},
loginRoute: {
path: '/login',
requiresAuth: false,
},
signupRoute: {
path: '/signup',
requiresAuth: false,
},
});
CoreRouter
The CoreRouter
class is used to create a new instance of a Core Router which is where all of the routing logic is encapsulated.
Usage
import { CoreRouter } from '@spa-tools/core-router';
const myRouter = CoreRouter.initialize(myRoutes, myOptions);
myRouter.navigate(myRoutes.dashboardRoute);
Constructor
Parameter | Type | Required? | Default | Comments |
---|---|---|---|---|
routes | Record<string, R> | yes | - | The routes are created using a factory method generated via routesFactory . |
options | CoreRouterOptions | no | - | See the Options section for details. |
navigate()
The navigate
method is used to navigate to a new route.
Parameter | Type | Required? | Default | Comments |
---|---|---|---|---|
route | R or string | yes | - | Must be EITHER one of the routes that were created using the factory method generated via routesFactory OR the respective route's path. |
state | Record<string, unknown> | no | - | The state to be passed to the new route. |
hash | string | no | - | The hash to be passed to the new route, which will trigger an auto-scroll after navigation on target element if one exists. |
CoreRouterOptions
The CoreRouterOptions
type is used to define the options that can be passed to the CoreRouter
constructor.
Usage
import { CoreRouterOptions } from '@spa-tools/core-router';
const myOptions: CoreRouterOptions<MyCustomRoute> = {
basePath: '/app',
fallbackRoute: myRoutes.dashboardRoute,
fallbackState: { error: '404' },
onRouteChange: (route, state) => {
console.log('Route changed to:', route, 'with state:', state);
},
onRouteRequest: (newRoute, newState) => {
console.log('Route requested:', newRoute, 'with state:', newState);
},
};
Properties
Property | Type | Required? | Default | Comments |
---|---|---|---|---|
basePath | string | no | - | Used to build the full URL for each route. An example of a base path is /app which would be used to build the full URL for a route with a path of /home as /app/home . |
fallbackRoute | R | no | - | Route to use when no route is matched. |
fallbackState | Record<string, unknown> | no | - | State to use when no route is matched. |
onRouteChange | OnCoreRouteChange<R> | no | - | Callback that is invoked when a route change has been processed. |
onRouteRequest | OnCoreRouteRequest<R> | no | - | Callback that is invoked when a route change request is pending and ready to act on. |
CoreRoute
CoreRoute
is the base type that all Core Router routes must extend.
Property | Type | Required? | Default | Comments |
---|---|---|---|---|
hashScrollBehavior | ScrollBehavior | no | - | Determines the scroll behavior when hash links are auto-srolled on route navigation. |
path | string | yes | - | The route's path, relative to the app's base path. |
addUnusedStateToQueryString | boolean | no | false | If true , any state that is not used to interpolate URL path params will be added to the query string. |
preEncodeQueryStringValues | string[] | no | [] | The querystring values for all keys provided will be pre-encoded, which in effect applies double-encoding. Example for use is if you have to pass file paths in a querystring and the consuming service requires it to be double URI encoded. |
removeUnusedQueryParams | boolean | no | true | If true , any query string placeholders that are not used to interpolate the URL will be removed from path (i.e. discard orhpaned placeholders). |
CoreRouteChangePayload
CoreRouteChangePayload<R>
is the object that is passed to the onRouteChange
callback when a route change has been processed.
Property | Type | Required? | Default | Comments |
---|---|---|---|---|
route | R | yes | - | The route that was navigated to. |
state | Record<string, unknown> | no | - | The state that was passed to the route. |
CoreRouteRequestPayload
CoreRouteRequestPayload<R>
is the object that is passed to the onRouteRequest
callback when a route change request is pending and ready to act on.
Property | Type | Required? | Default | Comments |
---|---|---|---|---|
newRoute | R | yes | - | The route that is being requested. |
newState | Record<string, unknown> | no | - | The state that is being passed to the requested route. |
oldRoute | R | no | - | The route of the last request that was approved. |
oldState | Record<string, unknown> | no | - | The state of the last request that was approved. |
CoreRouteResponse
CoreRouteResponse<R>
is the response that the consumer returns from within the onRouteRequest
callback when a route change request
is pending and ready to act on. This is used to determine how the Core Router should proceed with the route change request and thus is
the mechanisim by which consumers maintain absolute control over routing flow logic.
Scenario | Return type | Resulting behavior |
---|---|---|
Auto-approve | void (i.e. do nothing) | Request is auto-approved and proceeds with route change. |
Explicit approval/cancellation | Promise<boolean> | Resolving true approves request and proceeds with route change; othwerwise, cancels route change. |
Redirect to route | Promise<R> | Redirects to the provided route. |
Redirect to route with state | Promise<[R, Record<string, unknown>]> | Redirects to the route provided in tuple's first element while applying state provided in second element. |
Redirect to route with state and hash | Promise<[R, Record<string, unknown>, string]> | Redirects to the route provided in tuple's first element while applying state provided in second element and requests scroll to target location's element via hash provided in third element. |
Redirect to route with hash | Promise<[R, string]> | Redirects to the route provided in tuple's first element and requests scroll to target location's element via hash provided in second element. |
Redirect using path | Promise<string> | Redirects to the route corresponding with the respective path. |
Redirect using path with state | Promise<[string, Record<string, unknown>]> | Redirects to the route corresponding with the respective path in tuple's first elment while applying state provided in second element. |
Redirect using path with state and hash | Promise<[string, Record<string, unknown>], string> | Redirects to the route corresponding with the respective path in tuple's first element while applying state provided in second element and requests scroll to target location's element via hash provided in third element. |
Redirect using path and hash | Promise<[string, string]> | Redirects to the route corresponding with the respective path in tuple's first element and requests scroll to target location's element via hash provided in second element. |
OnCoreRouteChange
OnCoreRouteChange<R>
defines the signature for the callback that is invoked after a route change has been processed.
type OnCoreRouteChange<R> = (payload: CoreRouteChangePayload<R>) => void;
Parameter | Type | Required? | Default | Comments |
---|---|---|---|---|
payload | CoreRouteChangePayload<R> | yes | - | Object containing information about the route change that was just processed. |
OnCoreRouteRequest
OnCoreRouteRequest<R>
is the signature for the callback that is invoked when a route change request is pending and ready to act on.
type OnCoreRouteRequest<R> = (payload: CoreRouteRequestPayload<R>) => Promise<CoreRouteResponse<R>> | void;
Parameter | Type | Required? | Default | Comments |
---|---|---|---|---|
payload | CoreRouteRequestPayload<R> | yes | - | Object containing information about the route change that is pending and ready to act on. |