Jacky Zhao
2023-06-17 917d5791acd6361c691902b445bdc4f7129ba3fc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
import legacyStyle from "./styles/legacyToc.scss"
import modernStyle from "./styles/toc.scss"
 
interface Options {
  layout: 'modern' | 'legacy'
}
 
const defaultOptions: Options = {
  layout: 'modern'
}
 
export default ((opts?: Partial<Options>) => {
  const layout = opts?.layout ?? defaultOptions.layout
  function TableOfContents({ fileData }: QuartzComponentProps) {
    if (!fileData.toc) {
      return null
    }
 
    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")
      }
    }
  }
})
 
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()
 
document.addEventListener("spa_nav", (e) => {
  observer.disconnect()
  init()
})
`
  }
 
  return TableOfContents
}) satisfies QuartzComponentConstructor