wiki/quartz/components/TableOfContents.tsx

66 lines
1.8 KiB
TypeScript
Raw Normal View History

2023-06-12 06:46:38 +00:00
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
2023-06-17 02:41:59 +00:00
import legacyStyle from "./styles/legacyToc.scss"
import modernStyle from "./styles/toc.scss"
2023-06-10 06:06:02 +00:00
2023-06-13 05:41:42 +00:00
interface Options {
2023-06-17 02:41:59 +00:00
layout: 'modern' | 'legacy'
2023-06-13 05:41:42 +00:00
}
const defaultOptions: Options = {
2023-06-17 02:41:59 +00:00
layout: 'modern'
2023-06-10 06:06:02 +00:00
}
2023-06-13 05:41:42 +00:00
export default ((opts?: Partial<Options>) => {
const layout = opts?.layout ?? defaultOptions.layout
2023-06-17 02:41:59 +00:00
function TableOfContents({ fileData }: QuartzComponentProps) {
if (!fileData.toc) {
return null
2023-06-13 05:41:42 +00:00
}
2023-06-12 06:46:38 +00:00
2023-06-17 02:41:59 +00:00
return <details class="toc" open>
<summary><h3>Table of Contents</h3></summary>
<ul>
{fileData.toc.map(tocEntry => <li key={tocEntry.slug} class={`depth-${tocEntry.depth}`}>
<a href={`#${tocEntry.slug}`} data-for={tocEntry.slug}>{tocEntry.text}</a>
</li>)}
</ul>
</details>
}
TableOfContents.css = layout === "modern" ? modernStyle : legacyStyle
if (layout === "modern") {
TableOfContents.afterDOMLoaded = `
const bufferPx = 150
const observer = new IntersectionObserver(entries => {
for (const entry of entries) {
const slug = entry.target.id
const tocEntryElement = document.querySelector(\`a[data-for="$\{slug\}"]\`)
const windowHeight = entry.rootBounds?.height
if (windowHeight && tocEntryElement) {
if (entry.boundingClientRect.y < windowHeight) {
tocEntryElement.classList.add("in-view")
} else {
tocEntryElement.classList.remove("in-view")
}
2023-06-13 05:41:42 +00:00
}
2023-06-17 02:41:59 +00:00
}
})
function init() {
const headers = document.querySelectorAll("h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]")
headers.forEach(header => observer.observe(header))
}
init()
2023-06-13 05:41:42 +00:00
2023-06-17 02:41:59 +00:00
document.addEventListener("spa_nav", (e) => {
observer.disconnect()
init()
})
`
2023-06-13 05:41:42 +00:00
}
2023-06-17 02:41:59 +00:00
return TableOfContents
2023-06-13 05:41:42 +00:00
}) satisfies QuartzComponentConstructor