|
| 1 | +import { html } from 'lit-html'; |
| 2 | +import ComponentView from './component-view'; |
| 3 | + |
| 4 | +const EVENT_CLICK = 'nav-view:click'; |
| 5 | +const EVENT_ACTIVE = 'nav-view:active'; |
| 6 | +const EVENT_DEACTIVE = 'nav-view:deactive'; |
| 7 | +const EVENT_DISCONNECTED = 'nav-view:disconnected'; |
| 8 | + |
| 9 | +customElements.define('nav-view', class extends ComponentView { |
| 10 | + constructor() { |
| 11 | + super(); |
| 12 | + this.classList.add('nav'); |
| 13 | + } |
| 14 | + |
| 15 | + get active() { |
| 16 | + return this.querySelector('nav-item-view#active'); |
| 17 | + } |
| 18 | + |
| 19 | + set active(activeItem) { |
| 20 | + this.querySelectorAll('nav-item-view').forEach((item) => { |
| 21 | + if (activeItem === item) { |
| 22 | + if (!item.classList.contains('active')) { |
| 23 | + item.classList.add('active'); |
| 24 | + this.dispatchEvent(new CustomEvent(EVENT_ACTIVE, { detail: item })); |
| 25 | + } |
| 26 | + } else if (item.classList.contains('active')) { |
| 27 | + item.classList.remove('active'); |
| 28 | + this.dispatchEvent(new CustomEvent(EVENT_DEACTIVE, { detail: item })); |
| 29 | + } |
| 30 | + }); |
| 31 | + } |
| 32 | + |
| 33 | + connectedCallback() { |
| 34 | + super.connectedCallback(); |
| 35 | + |
| 36 | + this.querySelectorAll('nav-item-view').forEach((item) => { |
| 37 | + // Add event listeners for 'click' event to nav-item-view elements |
| 38 | + item.addEventListener('click', (e) => { |
| 39 | + this.dispatchEvent(new CustomEvent(EVENT_CLICK, { |
| 40 | + detail: e.target, |
| 41 | + })); |
| 42 | + }); |
| 43 | + // Add event listeners for when an item is removed from the nav-view |
| 44 | + item.addEventListener(EVENT_DISCONNECTED, (e) => { |
| 45 | + if (e.target === this.active) { |
| 46 | + this.active = null; |
| 47 | + } |
| 48 | + }); |
| 49 | + }); |
| 50 | + |
| 51 | + // If no active item is set, set the first one as active |
| 52 | + if (!this.active) { |
| 53 | + this.active = this.querySelector('nav-item-view'); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + appendChild(element) { |
| 58 | + super.appendChild(element); |
| 59 | + this.update(); |
| 60 | + return element; |
| 61 | + } |
| 62 | + |
| 63 | + template() { |
| 64 | + return html` |
| 65 | + <link rel="stylesheet" href="./index.css"> |
| 66 | + <nav class="${this.classList.value}"> |
| 67 | + <slot></slot> |
| 68 | + </nav> |
| 69 | + `; |
| 70 | + } |
| 71 | +}); |
| 72 | + |
| 73 | +// Export event names |
| 74 | +export default { |
| 75 | + EVENT_CLICK, EVENT_ACTIVE, EVENT_DEACTIVE, EVENT_DISCONNECTED, |
| 76 | +}; |
0 commit comments