Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion next-env.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/types/routes.d.ts";
import "./.next/dev/types/routes.d.ts";

// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
146 changes: 129 additions & 17 deletions src/components/mdx/Toc/Toc.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@

import type { DocToC } from '@/app/[...slug]/DocsContext'
import cn from '@/lib/cn'
import { ComponentProps, useCallback, useEffect, useState } from 'react'
import { ComponentProps, useCallback, useEffect, useRef, useState } from 'react'

export function Toc({ className, toc }: ComponentProps<'div'> & { toc: DocToC[] }) {
// console.log('toc', toc)

const [activeIndex, setActiveIndex] = useState<number | undefined>()
const [visibleSections, setVisibleSections] = useState<Set<number>>(new Set())
const tocRef = useRef<HTMLDivElement>(null)
const pathRef = useRef<SVGPathElement>(null)
const itemRefs = useRef<(HTMLElement | null)[]>([])

const updateActiveIndex = useCallback(
(hash: string) => {
Expand All @@ -32,35 +36,127 @@ export function Toc({ className, toc }: ComponentProps<'div'> & { toc: DocToC[]
}
}, [updateActiveIndex])

// React.useEffect(() => {
// const headings = toc.map((heading) => document.getElementById(heading.id))
// Progressive navigation with intersection observer
useEffect(() => {
const headings = toc.map((heading) => document.getElementById(heading.id))

const observer = new IntersectionObserver(
(entries) => {
setVisibleSections((prev) => {
const newVisibleSections = new Set(prev)

entries.forEach((entry) => {
const headingIndex = headings.indexOf(entry.target as HTMLElement)
if (headingIndex !== -1) {
if (entry.isIntersecting) {
newVisibleSections.add(headingIndex)
} else {
newVisibleSections.delete(headingIndex)
}
}
})

return newVisibleSections
})
},
{
rootMargin: '-80px 0px -80px 0px',
threshold: 0,
},
)

for (const heading of headings) {
if (heading) observer.observe(heading)
}

return () => observer.disconnect()
}, [toc])

// Draw and update SVG path
useEffect(() => {
if (!pathRef.current || !tocRef.current || itemRefs.current.length === 0) return

// Maximum stroke-dasharray length - ensures the path extends beyond visible area
const MAX_DASH_LENGTH = 1000

// const observer = new IntersectionObserver(([entry]) => {
// if (entry.intersectionRatio > 0) {
// const headingIndex = headings.indexOf(entry.target as HTMLElement)
// setActiveIndex(headingIndex)
// }
// })
const drawPath = () => {
const path: (string | number)[] = []
let pathIndent = 0
const itemPositions: { pathStart: number; pathEnd: number }[] = []
let pathLength = 0

itemRefs.current.forEach((item, i) => {
if (!item) return

const x = item.offsetLeft - 5
const y = item.offsetTop
const height = item.offsetHeight

if (i === 0) {
path.push('M', x, y, 'L', x, y + height)
pathLength += height
} else {
// Account for horizontal movement in path length
if (pathIndent !== x) {
path.push('L', pathIndent, y)
pathLength += Math.abs(pathIndent - x)
}
path.push('L', x, y)
pathLength += Math.abs(y - (itemRefs.current[i - 1]?.offsetTop ?? 0))
path.push('L', x, y + height)
pathLength += height
}

pathIndent = x
itemPositions[i] = { pathStart: pathLength - height, pathEnd: pathLength }
})

pathRef.current?.setAttribute('d', path.join(' '))

// Update stroke-dasharray based on visible sections
if (visibleSections.size > 0) {
const visibleArray = Array.from(visibleSections).sort((a, b) => a - b)
const pathStart = itemPositions[visibleArray[0]]?.pathStart ?? 0
const pathEnd = itemPositions[visibleArray[visibleArray.length - 1]]?.pathEnd ?? 0

if (pathStart <= pathEnd) {
pathRef.current?.setAttribute('stroke-dashoffset', '1')
pathRef.current?.setAttribute(
'stroke-dasharray',
`1, ${pathStart}, ${pathEnd - pathStart}, ${MAX_DASH_LENGTH}`,
)
pathRef.current?.setAttribute('opacity', '1')
} else {
pathRef.current?.setAttribute('opacity', '0')
}
} else {
pathRef.current?.setAttribute('opacity', '0')
}
}

// for (const heading of headings) {
// if (heading) observer.observe(heading)
// }
drawPath()

// return () => observer.disconnect()
// }, [toc])
window.addEventListener('resize', drawPath)
return () => window.removeEventListener('resize', drawPath)
}, [visibleSections, toc])

return (
<div className={cn(className, 'text-xs')}>
<div ref={tocRef} className={cn(className, 'relative text-xs')}>
<p className="mb-3 font-semibold uppercase tracking-wide text-on-surface-variant/50">
On This Page
</p>
{toc.map(({ title, id, level }, index) => (
<h4 key={`${title}-${index}`}>
<h4
key={`${title}-${index}`}
ref={(el) => {
itemRefs.current[index] = el
}}
>
<a
aria-label={title}
className={cn(
'block text-balance py-2 text-on-surface-variant/50 hover:underline',
index === activeIndex && 'text-on-surface',
(index === activeIndex || visibleSections.has(index)) && 'text-on-surface',
)}
style={{ marginLeft: `${(level - 1) * 1}rem` }}
href={`#${id}`}
Expand All @@ -69,6 +165,22 @@ export function Toc({ className, toc }: ComponentProps<'div'> & { toc: DocToC[]
</a>
</h4>
))}
<svg
className="pointer-events-none absolute left-0 top-0 h-full w-full"
xmlns="http://www.w3.org/2000/svg"
>
<path
ref={pathRef}
stroke="currentColor"
strokeWidth="2"
fill="transparent"
strokeDasharray="0, 0, 0, 1000"
strokeLinecap="round"
strokeLinejoin="round"
opacity="0"
className="text-primary transition-all duration-300 ease-out"
/>
</svg>
</div>
)
}