From 250e6202395de23514085fca26be32a1c3d2e08d Mon Sep 17 00:00:00 2001 From: Danila Danko Date: Thu, 4 Jan 2024 18:33:56 +0300 Subject: [PATCH] fix: synchronize scrolling the content and toc --- docs/theme/pagetoc.js | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/docs/theme/pagetoc.js b/docs/theme/pagetoc.js index d6df2848..b7e5c7a7 100644 --- a/docs/theme/pagetoc.js +++ b/docs/theme/pagetoc.js @@ -1,11 +1,11 @@ -var forEach = function (elems, fun) { +function forEach(elems, fun) { Array.prototype.forEach.call(elems, fun); -}; +} // Un-active everything when you click it -var forPagetocElem = function (fun) { +function forPagetocElem(fun) { forEach(document.getElementsByClassName("pagetoc")[0].children, fun); -}; +} forPagetocElem(function (el) { el.addEventHandler("click", function () { @@ -16,11 +16,23 @@ forPagetocElem(function (el) { }); }); +function getRect(element) { + return element.getBoundingClientRect(); +} + +function overflowTop(container, element) { + return getRect(container).top - getRect(element).top; +} + +function overflowBottom(container, element) { + return getRect(container).bottom - getRect(element).bottom; +} + var updateFunction = function () { var id; var elements = document.getElementsByClassName("header"); forEach(elements, function (el) { - if (window.scrollY >= el.offsetTop) { + if (window.scrollY + 100 >= el.offsetTop) { id = el; } }); @@ -28,10 +40,18 @@ var updateFunction = function () { forPagetocElem(function (el) { el.classList.remove("active"); }); + if (!id) return; forPagetocElem(function (el) { if (id.href.localeCompare(el.href) == 0) { el.classList.add("active"); + let pagetoc = document.getElementsByClassName("pagetoc")[0]; + if (overflowTop(pagetoc, el) > 0) { + pagetoc.scrollTop = el.offsetTop; + } + if (overflowBottom(pagetoc, el) < 0) { + pagetoc.scrollTop -= overflowBottom(pagetoc, el); + } } }); };