@joist/router
Version:
Simple JS router
97 lines • 3.18 kB
JavaScript
import { __decorate } from "tslib";
import { component, State, JoistElement, get, property, } from '@joist/component';
import { Injector } from '@joist/di';
import { Router, RouteCtx, match } from '../router';
let RouterOutletElement = class RouterOutletElement extends JoistElement {
constructor() {
super(...arguments);
this.routes = [];
this.matchers = [];
}
onPropChanges() {
this.matchers = this.routes.map((route) => match(route.path));
if (this.routes.length) {
this.check();
}
}
connectedCallback() {
super.connectedCallback();
this.removeListener = this.router.listen(this.check.bind(this));
}
disconnectedCallback() {
if (this.removeListener) {
this.removeListener();
}
}
check() {
const fragment = this.router.getFragment();
let route = null;
let matcher = null;
let match = null;
for (let i = 0; i < this.matchers.length; i++) {
route = this.routes[i];
matcher = this.matchers[i];
match = matcher(fragment);
if (match) {
break;
}
}
if (route && matcher && match) {
if (!this.state.value.activeRoute || this.state.value.activeRoute.path !== route.path) {
return this.resolve(route, match);
}
return Promise.resolve(void 0);
}
else if (this.state.value.element !== undefined) {
return this.state.setValue({});
}
return Promise.resolve(void 0);
}
resolve(activeRoute, ctx) {
return Promise.resolve(activeRoute.component()).then((element) => {
let el;
if (typeof element === 'function') {
el = new element();
}
else {
el = element;
}
const state = { element: el, activeRoute };
// Only set route context if the HTMLElement has am injector attached
if ('injector' in el) {
const base = el;
if (base.injector instanceof Injector) {
const routeCtx = base.injector.get(RouteCtx);
return routeCtx.setValue(ctx).then(() => this.state.setValue(state));
}
}
return this.state.setValue(state);
});
}
};
__decorate([
get(State)
], RouterOutletElement.prototype, "state", void 0);
__decorate([
get(Router)
], RouterOutletElement.prototype, "router", void 0);
__decorate([
property()
], RouterOutletElement.prototype, "routes", void 0);
RouterOutletElement = __decorate([
component({
state: {},
render({ state, host }) {
let child = host.lastElementChild;
while (child) {
host.removeChild(child);
child = host.lastElementChild;
}
if (state.element) {
host.append(state.element);
}
},
})
], RouterOutletElement);
export { RouterOutletElement };
//# sourceMappingURL=router_outlet.element.js.map