From bdb772755f1a7eb5fc48076e355bbb0101cb7701 Mon Sep 17 00:00:00 2001 From: Andrew Scholer Date: Sat, 20 Apr 2024 20:23:56 -0700 Subject: [PATCH] Javascript: improve scrolling ToC to active entry (PR #2158) --- js/pretext.js | 35 +++++++++++++++++++++++------------ 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/js/pretext.js b/js/pretext.js index ba586834b..6750932f7 100644 --- a/js/pretext.js +++ b/js/pretext.js @@ -12,20 +12,31 @@ */ function scrollTocToActive() { - pagefilename = window.location.href; - pagefilename = pagefilename.match(/[^\/]*$/)[0]; - possibletocentries = document.querySelectorAll('#ptx-toc a[href="' + pagefilename + '"]'); - if (possibletocentries.length == 0) { - console.log("linked below a subsection"); - pagefilename = pagefilename.match(/^[^\#]*/)[0]; - possibletocentries = document.querySelectorAll('#ptx-toc a[href="' + pagefilename + '"]'); + //Try to figure out current TocItem from URL + let fileNameWHash = window.location.href.split("/").pop(); + let fileName = fileNameWHash.split("#")[0]; + + //Find just the filename in ToC + let tocEntry = document.querySelector('#ptx-toc a[href="' + fileName + '"]'); + if (!tocEntry) { + return; //complete failure, get out } - if (possibletocentries.length == 0) { - console.log("error, cannot find", pagefilename, "in TOC"); - return + + //See if we can also match fileName#hash + let tocEntryWHash = document.querySelector( + '#ptx-toc a[href="' + fileNameWHash + '"]' + ); + if (tocEntryWHash) { + //Matched something below a subsection - activate the list item that contains it + tocEntryWHash.closest("li").classList.add("active"); } - possibletocentries[0].scrollIntoView({block: "center"}); - possibletocentries[0].classList.add("active");} + + //Now activate ToC item for fileName and scroll to it + // Don't use scrollIntoView because it changes users tab position in Chrome + // and messes up keyboard navigation + tocEntry.closest("li").classList.add("active"); + document.querySelector("#ptx-toc").scrollTop = tocEntry.offsetTop; +} function toggletoc() { thesidebar = document.getElementById("ptx-sidebar");