|
| 1 | +class TagsHolder extends HTMLElement { |
| 2 | + constructor() { |
| 3 | + super(); |
| 4 | + this.attachShadow({ mode: 'open' }); |
| 5 | + this._selectedTags = []; |
| 6 | + this.render(); |
| 7 | + this.renderTagList(); |
| 8 | + } |
| 9 | + |
| 10 | + addTag(tag) { |
| 11 | + if (!this._selectedTags.includes(tag)) { |
| 12 | + this._selectedTags.push(tag); |
| 13 | + this._selectedTags.sort(); |
| 14 | + this.renderTagList(); |
| 15 | + this.triggerChanged(); |
| 16 | + } |
| 17 | + } |
| 18 | + |
| 19 | + get selectedTags() { |
| 20 | + return this._selectedTags.slice(0); |
| 21 | + } |
| 22 | + |
| 23 | + removeTag(tag) { |
| 24 | + const index = this._selectedTags.indexOf(tag); |
| 25 | + if (index >= 0) { |
| 26 | + this._selectedTags.splice(index, 1); |
| 27 | + this.renderTagList(); |
| 28 | + this.triggerChanged(); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + render() { |
| 33 | + this.shadowRoot.innerHTML = ` |
| 34 | + <link rel="stylesheet" type="text/css" href="../css/semantic.min.css" /> |
| 35 | + <div> |
| 36 | + Filtered by tags: |
| 37 | + <span class="tags"></span> |
| 38 | + </div>`; |
| 39 | + } |
| 40 | + |
| 41 | + renderTagList() { |
| 42 | + const tagsHolderElement = this.shadowRoot.querySelector('.tags'); |
| 43 | + tagsHolderElement.innerHTML = ''; |
| 44 | + |
| 45 | + const tags = this._selectedTags; |
| 46 | + |
| 47 | + if (tags.length == 0) { |
| 48 | + tagsHolderElement.innerHTML = 'No filters'; |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + tags.forEach(tag => { |
| 53 | + const tagEl = document.createElement('span'); |
| 54 | + tagEl.className = "ui label orange"; |
| 55 | + tagEl.addEventListener('click', () => this.triggerTagClicked(tag)); |
| 56 | + tagEl.innerHTML = tag; |
| 57 | + tagsHolderElement.appendChild(tagEl); |
| 58 | + }); |
| 59 | + } |
| 60 | + |
| 61 | + triggerChanged(tag) { |
| 62 | + const event = new CustomEvent('changed', { bubbles: true }); |
| 63 | + this.dispatchEvent(event); |
| 64 | + } |
| 65 | + |
| 66 | + triggerTagClicked(tag) { |
| 67 | + const event = new CustomEvent('tag-clicked', { |
| 68 | + bubbles: true, |
| 69 | + detail: { tag }, |
| 70 | + }); |
| 71 | + this.dispatchEvent(event); |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +customElements.define('tags-holder', TagsHolder); |
0 commit comments