|
| 1 | +const createObserver = (headingMap: Record<string, HTMLLIElement>) => { |
| 2 | + return new IntersectionObserver((entries) => { |
| 3 | + const visibleEntry = entries |
| 4 | + .filter((entry) => entry.isIntersecting) |
| 5 | + .sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top)[0]; |
| 6 | + |
| 7 | + if (visibleEntry) { |
| 8 | + const id = (visibleEntry.target as HTMLElement).id; |
| 9 | + |
| 10 | + Object.entries(headingMap).forEach(([headingId, li]) => { |
| 11 | + if (headingId === id) { |
| 12 | + li.classList.add('border-l-2', 'border-blue-500'); |
| 13 | + } else { |
| 14 | + li.classList.remove('border-l-2', 'border-blue-500'); |
| 15 | + } |
| 16 | + }); |
| 17 | + } |
| 18 | + }); |
| 19 | +}; |
| 20 | + |
| 21 | +export const initializeTableContents = () => { |
| 22 | + const content = document.getElementById('content') as HTMLElement; |
| 23 | + const toc = document.getElementById('toc') as HTMLElement; |
| 24 | + |
| 25 | + toc.innerHTML = ''; |
| 26 | + if (!content.querySelector('h1')) return; |
| 27 | + |
| 28 | + const tocTitle = document.createElement('p'); |
| 29 | + const tocList = document.createElement('ul'); |
| 30 | + const headings = content.querySelectorAll('h2, h3'); |
| 31 | + |
| 32 | + tocTitle.classList.add('text-black', 'font-light', 'text-2xl', 'pb-5'); |
| 33 | + tocTitle.textContent = 'Table of contents'; |
| 34 | + |
| 35 | + const headingMap: Record<string, HTMLLIElement> = {}; |
| 36 | + |
| 37 | + headings.forEach((heading, index) => { |
| 38 | + const listItem = document.createElement('li'); |
| 39 | + listItem.classList.add( |
| 40 | + 'max-w-64', |
| 41 | + 'font-extralight', |
| 42 | + 'hover:bg-gray-300', |
| 43 | + 'hover:font-light', |
| 44 | + 'cursor-pointer', |
| 45 | + 'truncate' |
| 46 | + ); |
| 47 | + const link = document.createElement('a'); |
| 48 | + link.classList.add('flex', 'justify-start', 'items-stretch', 'p-1'); |
| 49 | + link.textContent = heading.textContent || ''; |
| 50 | + |
| 51 | + listItem.appendChild(link); |
| 52 | + tocList.appendChild(listItem); |
| 53 | + |
| 54 | + if (heading.tagName === 'H3') { |
| 55 | + listItem.classList.add('pl-3'); |
| 56 | + } |
| 57 | + |
| 58 | + heading.id = `${index}`; |
| 59 | + headingMap[heading.id] = listItem; |
| 60 | + }); |
| 61 | + |
| 62 | + toc.appendChild(tocTitle); |
| 63 | + toc.appendChild(tocList); |
| 64 | + |
| 65 | + const observer = createObserver(headingMap); |
| 66 | + headings.forEach((heading) => observer.observe(heading)); |
| 67 | +}; |
0 commit comments