summaryrefslogtreecommitdiff
path: root/static/home-filter.js
blob: b2d1a47f6dbda3badc595131b1e14bd39d87bd20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
 * Home Filter — filtra disciplinas conforme você digita
 * Só funciona quando há itens [data-filterable] na página
 */
document.addEventListener('DOMContentLoaded', () => {
  const items = document.querySelectorAll('[data-filterable]');
  if (!items.length) return;

  // Cria campo de busca
  const wrap = document.createElement('div');
  wrap.className = 'filter-container';
  wrap.innerHTML = `
    <input
      type="search"
      id="home-filter"
      class="filter-input"
      placeholder="Buscar disciplina…"
      aria-label="Filtrar disciplinas"
      autocomplete="off"
      spellcheck="false"
    >
    <span class="filter-count" id="filter-count" aria-live="polite"></span>
  `;

  // Insere antes do disc-grid dentro do <main>
  const grid = document.querySelector('.disc-grid');
  if (grid) {
    grid.parentNode.insertBefore(wrap, grid);
  } else {
    const main = document.querySelector('main');
    if (main) main.insertBefore(wrap, main.firstChild);
  }

  const input = document.getElementById('home-filter');
  const count = document.getElementById('filter-count');

  // Normaliza texto para comparação (remove acentos, maiúsculas)
  function normalize(str) {
    return str.normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase();
  }

  input.addEventListener('input', () => {
    const q = normalize(input.value.trim());
    let visible = 0;

    items.forEach(item => {
      const text = normalize(item.textContent);
      const match = !q || text.includes(q);
      item.style.display = match ? '' : 'none';
      if (match) visible++;
    });

    count.textContent = q ? `${visible} resultado${visible !== 1 ? 's' : ''}` : '';
  });

  // Esc limpa e desfoca
  input.addEventListener('keydown', e => {
    if (e.key === 'Escape') {
      input.value = '';
      input.dispatchEvent(new Event('input'));
      input.blur();
    }
  });

  // Foco automático na home com / ou Ctrl+K
  document.addEventListener('keydown', e => {
    if ((e.key === '/' || (e.ctrlKey && e.key === 'k')) && document.activeElement !== input) {
      e.preventDefault();
      input.focus();
    }
  });
});