UNPKG

@joist/router

Version:
74 lines 2.1 kB
import { __decorate, __param } from "tslib"; import { State } from '@joist/component'; import { service, inject } from '@joist/di'; import { match as ptrMatch } from 'path-to-regexp'; export class RouteCtx extends State { } export function normalize(path) { return path.toString().replace(/^\/|\/$/g, ''); } export function match(path) { return ptrMatch(normalize(path), { decode: decodeURIComponent }); } let Location = class Location { getPath() { return window.location.pathname; } goTo(path) { history.pushState(null, '', path); } onPopState(cb) { const fn = () => cb(); window.addEventListener('popstate', fn); return () => { window.removeEventListener('popstate', fn); }; } }; Location = __decorate([ service() ], Location); export { Location }; let RouterConfig = class RouterConfig { constructor() { this.root = '/'; this.navigateEventName = 'joist_router_navigate'; } }; RouterConfig = __decorate([ service() ], RouterConfig); export { RouterConfig }; let Router = class Router { constructor(location, config) { this.location = location; this.config = config; this.detach = this.location.onPopState(this.notify.bind(this)); } getFragment() { let fragment = ''; fragment = normalize(this.location.getPath()); fragment = this.config.root !== '/' ? fragment.replace(this.config.root, '') : fragment; return normalize(fragment); } navigate(path) { this.location.goTo(this.config.root + normalize(path)); this.notify(); } listen(cb) { addEventListener(this.config.navigateEventName, cb); return () => { removeEventListener(this.config.navigateEventName, cb); }; } notify() { dispatchEvent(new CustomEvent(this.config.navigateEventName)); } }; Router = __decorate([ service(), __param(0, inject(Location)), __param(1, inject(RouterConfig)) ], Router); export { Router }; //# sourceMappingURL=router.js.map