|
| 1 | +const tagsToFilterBy = []; |
| 2 | + |
| 3 | +const searchBoxElement = document.querySelector('search-box'); |
| 4 | +searchBoxElement.addEventListener('changed', (e) => applyFilters()); |
| 5 | + |
| 6 | +function addTagFilter() { |
| 7 | + Array.from(document.querySelectorAll('.extra .label')) |
| 8 | + .forEach(tagEl => { |
| 9 | + tagEl.addEventListener('click', () => { |
| 10 | + if (!tagsToFilterBy.includes(tagEl.innerHTML)) { |
| 11 | + tagsToFilterBy.push(tagEl.innerHTML); |
| 12 | + applyFilters(); |
| 13 | + } |
| 14 | + }); |
| 15 | + }); |
| 16 | +} |
| 17 | + |
| 18 | +function applyFilters() { |
| 19 | + createListForProducts(filterByText(filterByTags(products))); |
| 20 | + addTagFilter(); |
| 21 | + updateTagFilterList(); |
| 22 | +} |
| 23 | + |
| 24 | +function createTagFilterLabel(tag) { |
| 25 | + const el = document.createElement('span'); |
| 26 | + el.className = 'ui label orange'; |
| 27 | + el.innerText = tag; |
| 28 | + |
| 29 | + el.addEventListener('click', () => { |
| 30 | + const index = tagsToFilterBy.indexOf(tag); |
| 31 | + tagsToFilterBy.splice(index, 1); |
| 32 | + applyFilters(); |
| 33 | + }); |
| 34 | + return el; |
| 35 | +} |
| 36 | + |
| 37 | +function filterByTags(products) { |
| 38 | + let filtered = products; |
| 39 | + tagsToFilterBy.forEach((t) => filtered = filtered.filter(p => p.tags.includes(t))); |
| 40 | + return filtered; |
| 41 | +} |
| 42 | + |
| 43 | +function filterByText(products) { |
| 44 | + const txt = searchBoxElement.searchText.toLowerCase(); |
| 45 | + return products.filter((p) => { |
| 46 | + return p.name.toLowerCase().includes(txt) |
| 47 | + || p.description.toLowerCase().includes(txt); |
| 48 | + }); |
| 49 | +} |
| 50 | + |
| 51 | +function updateTagFilterList() { |
| 52 | + const tagHolder = document.querySelector('.item span.tags'); |
| 53 | + |
| 54 | + if (tagsToFilterBy.length == 0) { |
| 55 | + tagHolder.innerHTML = 'No filters'; |
| 56 | + } else { |
| 57 | + tagHolder.innerHTML = ''; |
| 58 | + tagsToFilterBy.sort(); |
| 59 | + tagsToFilterBy.map(createTagFilterLabel) |
| 60 | + .forEach((tEl) => tagHolder.appendChild(tEl)); |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +applyFilters(); |
0 commit comments