summaryrefslogtreecommitdiff
path: root/static/toc.js
blob: 950533eae8781ec759d6625371e276b6a0023db2 (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
/**
 * Table of Contents - Gera sumário automático de headings
 */

document.addEventListener('DOMContentLoaded', () => {
  const prose = document.getElementById('prose');
  const tocNav = document.getElementById('toc-nav');
  const tocList = document.getElementById('toc-list');

  if (!prose || !tocNav || !tocList) return;

  const headings = prose.querySelectorAll('h2, h3');
  if (!headings.length) return;

  const used = new Set();

  headings.forEach((h) => {
    // Gerar ID único baseado no texto
    let base = h.textContent
      .trim()
      .normalize('NFD')
      .replace(/[\u0300-\u036f]/g, '')
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/^-+|-+$/g, '');

    let id = base || 'sec';
    let i = 2;
    while (used.has(id)) id = base + '-' + i++;

    h.id = id;
    used.add(id);

    // Criar item no sumário
    const li = document.createElement('li');
    li.className = 'toc-' + h.tagName.toLowerCase();

    const a = document.createElement('a');
    a.href = '#' + id;
    a.textContent = h.textContent;
    a.addEventListener('click', (e) => {
      e.preventDefault();
      h.scrollIntoView({ behavior: 'smooth', block: 'start' });
    });

    li.appendChild(a);
    tocList.appendChild(li);
  });

  // Mostrar sumário se houver conteúdo
  tocNav.style.display = '';
});