From 6ad18e9302f40844dd77ebfc786b222dd5c204f7 Mon Sep 17 00:00:00 2001 From: tompng Date: Sun, 23 Nov 2025 17:36:20 +0900 Subject: [PATCH] Add smooth-scroll handler to link inside heading tag --- lib/rdoc/generator/template/aliki/js/aliki.js | 33 ++++++++++++------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/lib/rdoc/generator/template/aliki/js/aliki.js b/lib/rdoc/generator/template/aliki/js/aliki.js index 05a3d5e7c1..6f0dce8951 100644 --- a/lib/rdoc/generator/template/aliki/js/aliki.js +++ b/lib/rdoc/generator/template/aliki/js/aliki.js @@ -195,6 +195,7 @@ function generateToc() { link.setAttribute('data-target', heading.id); li.appendChild(link); + setHeadingScrollHandler(heading, link); tocList.appendChild(li); }); @@ -271,21 +272,30 @@ function hookTocActiveHighlighting() { targetHeadings.forEach((heading) => { observer.observe(heading); }); +} - // Smooth scroll when clicking TOC links - tocLinks.forEach((link) => { - link.addEventListener('click', (e) => { - e.preventDefault(); - const targetId = link.getAttribute('data-target'); - const targetHeading = document.getElementById(targetId); - if (targetHeading) { - targetHeading.scrollIntoView({ behavior: 'smooth', block: 'start' }); - history.pushState(null, '', `#${targetId}`); - } - }); +function setHeadingScrollHandler(heading, link) { + // Smooth scroll to heading when clicking link + if (!heading.id) return; + + link.addEventListener('click', (e) => { + e.preventDefault(); + heading.scrollIntoView({ behavior: 'smooth', block: 'start' }); + history.pushState(null, '', `#${heading.id}`); }); } +function setHeadingSelfLinkScrollHandlers() { + // Clicking link inside heading scrolls smoothly to heading itself + const headings = document.querySelectorAll('h1, h2, h3, h4, h5, h6'); + headings.forEach((heading) => { + if (!heading.id) return; + + const link = heading.querySelector(`a[href^="#${heading.id}"]`); + if (link) setHeadingScrollHandler(heading, link); + }) +} + /* ===== Mobile Search Modal ===== */ function hookSearchModal() { @@ -466,6 +476,7 @@ document.addEventListener('DOMContentLoaded', () => { hookFocus(); hookSidebar(); generateToc(); + setHeadingSelfLinkScrollHandlers(); hookTocActiveHighlighting(); hookSearchModal(); wrapCodeBlocksWithCopyButton();