Last active
November 13, 2024 00:29
-
-
Save barisusakli/9e7a6ddf0048a10a9bf8cc19e3befabb to your computer and use it in GitHub Desktop.
toc for topics
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
handleTOC(); | |
function handleTOC() { | |
$(window).on('action:navigator.update', (ev, { newIndex, index }) => { | |
const mainPost = $('[component="post"][data-index="0"]'); | |
const toc = $('[component="topic/toc"]'); | |
if (!mainPost.length) { | |
toc.addClass('hidden'); | |
return; | |
} | |
const scrollTop = $(window).scrollTop(); | |
// const windowHeight = $(window).height(); | |
const mainPostBottom = mainPost.offset().top + mainPost.outerHeight(true); | |
const isVisible = mainPostBottom > scrollTop; | |
console.log(mainPostBottom, scrollTop); | |
toc.toggleClass('hidden', !isVisible); | |
console.log(isVisible); | |
}); | |
$(window).on('action:topic.loaded action:posts.loaded', () => { | |
const headers = $('[component="post"][data-index="0"] [component="post/content"]').find('h1,h2,h3,h4,h5,h6'); | |
console.log(headers); | |
const toc = $('[component="topic/toc"]'); | |
if (headers.length > 1 && !toc.html()) { | |
headers.each((i, el) => { | |
$(el).attr('toc-id', `toc-id-${i}`); | |
const margin = parseInt(el.nodeName.charAt(1), 10) - 1; | |
const li = $(`<li class="text-truncate text-sm mb-1 ${margin > 0 ? `ms-${margin}` : ''}"><a class="text-reset" href="#toc-id-${i}">${$(el).text()}</a></li>`); | |
li.on('click', 'a', function () { | |
const scrollTop = $(el).offset().top - 100; | |
$('html, body').animate({ | |
scrollTop: scrollTop + 'px', | |
}, 300); | |
}); | |
toc.append(li); | |
}); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment