home-filter.js (2142B)
1 /** 2 * Home Filter — filtra disciplinas conforme você digita 3 * Só funciona quando há itens [data-filterable] na página 4 */ 5 document.addEventListener('DOMContentLoaded', () => { 6 const items = document.querySelectorAll('[data-filterable]'); 7 if (!items.length) return; 8 9 // Cria campo de busca 10 const wrap = document.createElement('div'); 11 wrap.className = 'filter-container'; 12 wrap.innerHTML = ` 13 <input 14 type="search" 15 id="home-filter" 16 class="filter-input" 17 placeholder="Buscar disciplina…" 18 aria-label="Filtrar disciplinas" 19 autocomplete="off" 20 spellcheck="false" 21 > 22 <span class="filter-count" id="filter-count" aria-live="polite"></span> 23 `; 24 25 // Insere antes do disc-grid dentro do <main> 26 const grid = document.querySelector('.disc-grid'); 27 if (grid) { 28 grid.parentNode.insertBefore(wrap, grid); 29 } else { 30 const main = document.querySelector('main'); 31 if (main) main.insertBefore(wrap, main.firstChild); 32 } 33 34 const input = document.getElementById('home-filter'); 35 const count = document.getElementById('filter-count'); 36 37 // Normaliza texto para comparação (remove acentos, maiúsculas) 38 function normalize(str) { 39 return str.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase(); 40 } 41 42 input.addEventListener('input', () => { 43 const q = normalize(input.value.trim()); 44 let visible = 0; 45 46 items.forEach(item => { 47 const text = normalize(item.textContent); 48 const match = !q || text.includes(q); 49 item.style.display = match ? '' : 'none'; 50 if (match) visible++; 51 }); 52 53 count.textContent = q ? `${visible} resultado${visible !== 1 ? 's' : ''}` : ''; 54 }); 55 56 // Esc limpa e desfoca 57 input.addEventListener('keydown', e => { 58 if (e.key === 'Escape') { 59 input.value = ''; 60 input.dispatchEvent(new Event('input')); 61 input.blur(); 62 } 63 }); 64 65 // Foco automático na home com / ou Ctrl+K 66 document.addEventListener('keydown', e => { 67 if ((e.key === '/' || (e.ctrlKey && e.key === 'k')) && document.activeElement !== input) { 68 e.preventDefault(); 69 input.focus(); 70 } 71 }); 72 });