UNPKG

@joist/router

Version:
69 lines 2.29 kB
import { __decorate } from "tslib"; import { JoistElement, get, property } from '@joist/component'; import { Router, normalize } from '../router'; export class RouterLinkElement extends JoistElement { constructor() { super(...arguments); this.path = this.getAttribute('path') || ''; this.pathMatch = this.getAttribute('path-match') || 'startsWith'; this.activeClass = this.getAttribute('active-class') || 'active'; this.normalizedPath = normalize(this.path); } onPropChanges(changes) { const keys = changes.map((change) => change.key); if (keys.includes('path')) { this.normalizedPath = normalize(this.path); } } connectedCallback() { super.connectedCallback(); this.removeListener = this.router.listen(() => { this.setActiveClass(); }); const child = this.children[0]; if (child && child instanceof HTMLAnchorElement) { this.path = child.pathname; this.normalizedPath = normalize(this.path); } this.addEventListener('click', (e) => { e.preventDefault(); this.router.navigate(this.normalizedPath); }); this.setActiveClass(); } disconnectedCallback() { if (this.removeListener) { this.removeListener(); } } setActiveClass() { const fragment = this.router.getFragment(); if (this.pathMatch === 'full') { if (fragment === this.normalizedPath) { this.classList.add(this.activeClass); } else { this.classList.remove(this.activeClass); } } else if (fragment.startsWith(this.normalizedPath)) { this.classList.add(this.activeClass); } else { this.classList.remove(this.activeClass); } } } __decorate([ get(Router) ], RouterLinkElement.prototype, "router", void 0); __decorate([ property() ], RouterLinkElement.prototype, "path", void 0); __decorate([ property() ], RouterLinkElement.prototype, "pathMatch", void 0); __decorate([ property() ], RouterLinkElement.prototype, "activeClass", void 0); //# sourceMappingURL=router_link.element.js.map