Skip to content

Instantly share code, notes, and snippets.

@gustavomdsantos
Created August 26, 2026 14:29
Show Gist options
  • Select an option

  • Save gustavomdsantos/ac6091c35a92a947e364046f70a86e68 to your computer and use it in GitHub Desktop.

Select an option

Save gustavomdsantos/ac6091c35a92a947e364046f70a86e68 to your computer and use it in GitHub Desktop.
Planalto Legis - Sumário Lateral - User JS para Tampermonkey / Greasemonkey / Violentmonkey.
// ==UserScript==
// @name Planalto Legis - Sumário Lateral
// @namespace https://github.com/gustavomdsantos
// @version 1.0
// @description Cria um TOC (Table of Contents) nas páginas de texto integral de leis brasileiras.
// @author Gustavo Moraes (gustavomdsantos@pm.me)
// @match https://www.planalto.gov.br/ccivil_03/*/*
// @match http://www.planalto.gov.br/ccivil_03/*/*
// @icon https://www.planalto.gov.br/favicon.ico
// @grant GM_addStyle
// ==/UserScript==
(function() {
'use strict';
// ==============================
// 1. CONFIGURAÇÕES E CONSTANTES
// ==============================
const CONFIG = {
FONT_FAMILY: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Arial, sans-serif',
TOC_MIN_WIDTH: 220,
TOC_MAX_WIDTH: 600,
TOC_DEFAULT_WIDTH: 320,
REGEX_ESTRUTURA: /^(PARTE|LIVRO|TÍTULO|TITULO|CAPÍTULO|CAPITULO|SEÇÃO|SECAO|SUBSEÇÃO|SUBSECAO)\s+([IVXLCDM\d]+[A-Z\-]*)/i
};
// ===============
// 2. ESTILOS CSS
// ===============
const CSS_STYLES = `
*, *::before, *::after {
box-sizing: border-box !important;
}
html, body {
max-width: 100% !important;
overflow-x: hidden !important;
margin: 0 !important;
padding: 0 !important;
background-color: #ffffff;
font-family: ${CONFIG.FONT_FAMILY};
}
body {
min-height: 100vh;
display: flex !important;
flex-direction: row !important;
align-items: flex-start !important;
justify-content: center;
}
/* PAINEL LATERAL (TOC) */
#planalto-toc-sidebar {
width: var(--toc-width, ${CONFIG.TOC_DEFAULT_WIDTH}px);
min-width: ${CONFIG.TOC_MIN_WIDTH}px;
max-width: ${CONFIG.TOC_MAX_WIDTH}px;
height: 100vh;
position: fixed;
top: 0;
left: 0;
background: #ffffff;
border-right: 1px solid #d0d7de;
box-shadow: 2px 0 8px rgba(0,0,0,0.05);
overflow-y: auto;
overflow-x: hidden;
padding: 0 15px 15px 15px;
z-index: 999;
font-size: 13px;
line-height: 1.4;
color: #24292f;
}
/* BORDA INTERATIVA PARA REDIMENSIONAR */
#planalto-toc-resizer {
position: absolute;
top: 0;
right: 0;
width: 6px;
height: 100%;
cursor: col-resize;
user-select: none;
z-index: 1000;
}
#planalto-toc-resizer:hover,
#planalto-toc-resizer.is-resizing {
background-color: #0969da;
}
/* CABEÇALHO FIXO */
#planalto-toc-header {
position: sticky;
top: 0;
background: #ffffff;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 2px solid #0969da;
padding: 15px 0 8px 0;
margin-bottom: 12px;
z-index: 10;
}
#planalto-toc-header h3 {
margin: 0;
font-size: 15px;
font-weight: bold;
color: #0969da;
white-space: nowrap;
font-family: ${CONFIG.FONT_FAMILY};
}
/* CONTAINER DO CONTEÚDO INTEGRAL */
#planalto-main-content {
width: min(80%, 1200px) !important;
margin: 1em auto !important;
padding: 0 15px !important;
/* Transição/animação desativada propositalmente para resposta imediata */
transition: none !important;
}
body:not(.toc-hidden) #planalto-main-content {
margin-left: calc(var(--toc-width, ${CONFIG.TOC_DEFAULT_WIDTH}px) + 20px) !important;
margin-right: auto !important;
width: calc(100% - var(--toc-width, ${CONFIG.TOC_DEFAULT_WIDTH}px) - 40px) !important;
max-width: 1200px !important;
}
#planalto-main-content table,
#planalto-main-content div,
#planalto-main-content center {
max-width: 100% !important;
}
/* INDENTAÇÃO DE NÍVEIS NO TEXTO */
.planalto-secao-texto { padding-left: 20px !important; }
.planalto-subsecao-texto { padding-left: 40px !important; }
/* LISTA DO SUMÁRIO */
#planalto-toc-list {
list-style: none;
padding: 0;
margin: 0;
}
#planalto-toc-list li { margin-bottom: 4px; }
#planalto-toc-list a {
color: #24292f;
text-decoration: none;
display: block;
padding: 5px 8px;
border-radius: 4px;
white-space: nowrap;
}
#planalto-toc-list a:hover {
background-color: #f3f4f6;
color: #0969da;
}
#planalto-toc-list .toc-tipo {
font-weight: bold;
display: block;
font-size: 11px;
text-transform: uppercase;
color: #57606a;
margin-bottom: 2px;
}
#planalto-toc-list .toc-nome {
display: block;
font-size: 13px;
}
#planalto-toc-list li.level-parte,
#planalto-toc-list li.level-livro {
margin-top: 8px;
font-weight: bold;
}
#planalto-toc-list li.level-titulo { padding-left: 6px; }
#planalto-toc-list li.level-capitulo { padding-left: 12px; }
#planalto-toc-list li.level-secao { padding-left: 18px; }
#planalto-toc-list li.level-subsecao { padding-left: 24px; }
/* BOTÕES DE NAVEGAÇÃO */
#planalto-toc-btn-toggle {
position: fixed;
top: 12px;
left: 12px;
z-index: 99999;
background: #ffffff;
border: 1px solid #d0d7de;
border-radius: 6px;
padding: 6px 12px;
font-size: 13px;
font-weight: bold;
color: #24292f;
cursor: pointer;
box-shadow: 0 2px 6px rgba(0,0,0,0.15);
font-family: ${CONFIG.FONT_FAMILY};
display: none;
}
#planalto-toc-btn-close {
background: transparent;
border: none;
font-size: 16px;
cursor: pointer;
color: #57606a;
padding: 0 4px;
}
#planalto-toc-btn-close:hover { color: #cf222e; }
/* CONTROLADORES DE VISIBILIDADE */
body.toc-hidden #planalto-toc-sidebar { display: none !important; }
body.toc-hidden #planalto-toc-btn-toggle { display: block !important; }
`;
// =======================
// 3. ESTRUTURAÇÃO DO DOM
// =======================
function setupDOM() {
const styleElem = document.createElement('style');
styleElem.textContent = CSS_STYLES;
document.head.appendChild(styleElem);
const contentWrapper = document.createElement('div');
contentWrapper.id = 'planalto-main-content';
while (document.body.firstChild) {
contentWrapper.appendChild(document.body.firstChild);
}
const tocSidebar = document.createElement('div');
tocSidebar.id = 'planalto-toc-sidebar';
tocSidebar.innerHTML = `
<div id="planalto-toc-resizer"></div>
<div id="planalto-toc-header">
<h3>Sumário da Lei</h3>
<button id="planalto-toc-btn-close" title="Recolher Sumário">✕</button>
</div>
<ul id="planalto-toc-list"></ul>
`;
const toggleBtn = document.createElement('button');
toggleBtn.id = 'planalto-toc-btn-toggle';
toggleBtn.innerHTML = '📑 Sumário';
document.body.classList.add('toc-hidden');
document.body.appendChild(tocSidebar);
document.body.appendChild(contentWrapper);
document.body.appendChild(toggleBtn);
return { contentWrapper, tocSidebar, toggleBtn };
}
// ======================================
// 4. PARSER E PROCESSAMENTO DE TÓPICOS
// ======================================
function parseAndBuildTOC(contentWrapper) {
const tocList = document.getElementById('planalto-toc-list');
const candidates = contentWrapper.querySelectorAll('p, td, div, font, b, h1, h2, h3, h4');
const fragment = document.createDocumentFragment();
const seenItems = new Set();
let count = 0;
let currentSectionLevel = null;
for (let i = 0; i < candidates.length; i++) {
const el = candidates[i];
if (el.closest('[data-toc-processed="true"]')) continue;
const text = el.innerText ? el.innerText.trim() : '';
if (!text || text.length > 250) continue;
const match = text.match(CONFIG.REGEX_ESTRUTURA);
if (match) {
el.dataset.tocProcessed = "true";
const tipoStr = match[0].toUpperCase();
const tipoChave = match[1].toLowerCase()
.replace('capitulo', 'capitulo')
.replace('secao', 'secao')
.replace('subsecao', 'subsecao')
.replace('titulo', 'titulo');
if (tipoChave.includes('subsecao')) {
currentSectionLevel = 'subsecao';
} else if (tipoChave.includes('secao')) {
currentSectionLevel = 'secao';
} else if (['capitulo', 'titulo', 'livro', 'parte'].includes(tipoChave)) {
currentSectionLevel = null;
}
if (currentSectionLevel) {
el.classList.add(`planalto-${currentSectionLevel}-texto`);
}
let nomeTopico = text.substring(match[0].length).trim().replace(/^[\s:\-\–\—\.]+/g, '').trim();
if (!nomeTopico && i + 1 < candidates.length) {
for (let nextIdx = i + 1; nextIdx < candidates.length && nextIdx <= i + 3; nextIdx++) {
const nextText = candidates[nextIdx].innerText ? candidates[nextIdx].innerText.trim() : '';
if (nextText && !CONFIG.REGEX_ESTRUTURA.test(nextText) && !/^Art\./i.test(nextText) && nextText.length < 150) {
nomeTopico = nextText;
break;
}
}
}
const itemKey = `${tipoStr}|${nomeTopico.toUpperCase()}`;
if (seenItems.has(itemKey)) continue;
seenItems.add(itemKey);
count++;
const id = `toc-anchor-${count}`;
el.id = id;
const li = document.createElement('li');
li.className = `level-${tipoChave}`;
const a = document.createElement('a');
a.href = `#${id}`;
a.innerHTML = nomeTopico
? `<span class="toc-tipo">${tipoStr}</span><span class="toc-nome">${nomeTopico}</span>`
: `<span class="toc-tipo">${tipoStr}</span>`;
a.addEventListener('click', (e) => {
e.preventDefault();
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
});
li.appendChild(a);
fragment.appendChild(li);
} else if (currentSectionLevel && el.tagName.toLowerCase() === 'p') {
el.classList.add(`planalto-${currentSectionLevel}-texto`);
}
}
if (count === 0) {
const emptyLi = document.createElement('li');
emptyLi.style.cssText = 'padding: 10px; color: #57606a;';
emptyLi.innerHTML = '<em>Nenhum tópico de estrutura encontrado.</em>';
fragment.appendChild(emptyLi);
}
tocList.appendChild(fragment);
}
// =============================================
// 5. EVENTOS E REDIMENSIONAMENTO (O(1) REFLOW)
// =============================================
function setupInteractions(tocSidebar, toggleBtn) {
const resizer = document.getElementById('planalto-toc-resizer');
let isResizing = false;
let rafId = null;
resizer.addEventListener('mousedown', () => {
isResizing = true;
resizer.classList.add('is-resizing');
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
});
document.addEventListener('mousemove', (e) => {
if (!isResizing) return;
if (rafId) cancelAnimationFrame(rafId);
rafId = requestAnimationFrame(() => {
const newWidth = Math.max(CONFIG.TOC_MIN_WIDTH, Math.min(e.clientX, CONFIG.TOC_MAX_WIDTH));
document.documentElement.style.setProperty('--toc-width', `${newWidth}px`);
});
});
document.addEventListener('mouseup', () => {
if (isResizing) {
isResizing = false;
resizer.classList.remove('is-resizing');
document.body.style.cursor = '';
document.body.style.userSelect = '';
}
});
document.getElementById('planalto-toc-btn-close').addEventListener('click', () => {
document.body.classList.add('toc-hidden');
});
toggleBtn.addEventListener('click', () => {
document.body.classList.remove('toc-hidden');
});
}
// =================
// 6. INICIALIZAÇÃO
// =================
const { contentWrapper, tocSidebar, toggleBtn } = setupDOM();
parseAndBuildTOC(contentWrapper);
setupInteractions(tocSidebar, toggleBtn);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment