Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: make the links in the TOC reactive to the visibility on the screen #338

Merged
merged 5 commits into from
Jan 30, 2025
Merged
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
56 changes: 54 additions & 2 deletions app/components/Doc.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,51 @@ export function Doc({

const isTocVisible = shouldRenderToc && headings && headings.length > 1

const markdownContainerRef = React.useRef<HTMLDivElement>(null)
const [activeHeadings, setActiveHeadings] = React.useState<Array<string>>([])

const headingElementRefs = React.useRef<
Record<string, IntersectionObserverEntry>
>({})

React.useEffect(() => {
const callback = (headingsList: Array<IntersectionObserverEntry>) => {
headingElementRefs.current = headingsList.reduce(
(map, headingElement) => {
map[headingElement.target.id] = headingElement
return map
},
headingElementRefs.current
)

const visibleHeadings: Array<IntersectionObserverEntry> = []
Object.keys(headingElementRefs.current).forEach((key) => {
const headingElement = headingElementRefs.current[key]
if (headingElement.isIntersecting) {
visibleHeadings.push(headingElement)
}
})

if (visibleHeadings.length >= 1) {
setActiveHeadings(visibleHeadings.map((h) => h.target.id))
}
}

const observer = new IntersectionObserver(callback, {
rootMargin: '0px',
threshold: 0.2,
})

const headingElements = Array.from(
markdownContainerRef.current?.querySelectorAll(
'h2[id], h3[id], h4[id], h5[id], h6[id]'
) ?? []
)
headingElements.forEach((el) => observer.observe(el))

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

return (
<div
className={twMerge(
Expand All @@ -61,9 +106,11 @@ export function Doc({
<div className="h-px bg-gray-500 opacity-20" />
<div className="h-4" />
<div
ref={markdownContainerRef}
className={twMerge(
'prose prose-gray prose-sm prose-p:leading-7 dark:prose-invert max-w-none',
isTocVisible && 'pr-4 lg:pr-6'
isTocVisible && 'pr-4 lg:pr-6',
'styled-markdown-content'
)}
>
<Markdown htmlMarkup={markup} />
Expand All @@ -83,7 +130,12 @@ export function Doc({

{isTocVisible && (
<div className="border-l border-gray-500/20 max-w-52 w-full hidden 2xl:block transition-all">
<Toc headings={headings} colorFrom={colorFrom} colorTo={colorTo} />
<Toc
headings={headings}
activeHeadings={activeHeadings}
colorFrom={colorFrom}
colorTo={colorTo}
/>
</div>
)}
</div>
Expand Down
19 changes: 8 additions & 11 deletions app/components/Toc.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import * as React from 'react'
import { twMerge } from 'tailwind-merge'
import { HeadingData } from 'marked-gfm-heading-id'
import { useLocation } from '@tanstack/react-router'

const headingLevels: Record<number, string> = {
1: 'pl-2',
Expand All @@ -16,17 +15,15 @@ type TocProps = {
headings: HeadingData[]
colorFrom?: string
colorTo?: string
activeHeadings: Array<string>
}

export function Toc({ headings, colorFrom, colorTo }: TocProps) {
const location = useLocation()

const [hash, setHash] = React.useState('')

React.useEffect(() => {
setHash(location.hash)
}, [location])

export function Toc({
headings,
colorFrom,
colorTo,
activeHeadings,
}: TocProps) {
return (
<nav className="flex flex-col sticky top-2 max-h-screen divide-y divide-gray-500/20">
<div className="p-2">
Expand All @@ -48,7 +45,7 @@ export function Toc({ headings, colorFrom, colorTo }: TocProps) {
<a
title={heading.id}
href={`#${heading.id}`}
aria-current={hash === heading.id && 'location'}
aria-current={activeHeadings.includes(heading.id) && 'location'}
className={`truncate block aria-current:bg-gradient-to-r ${colorFrom} ${colorTo} aria-current:bg-clip-text aria-current:text-transparent`}
dangerouslySetInnerHTML={{
__html: heading.text,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ function Docs() {
return (
<DocContainer>
<Doc
key={filePath}
title={title}
content={content}
repo={library.repo}
Expand Down
2 changes: 1 addition & 1 deletion app/utils/handleRedirects.server.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { redirect } from '@tanstack/react-router';
import { redirect } from '@tanstack/react-router'

type RedirectItem = { from: string; to: string }

Expand Down
2 changes: 1 addition & 1 deletion app/utils/useLocalStorage.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useState, useEffect } from 'react';
import { useState, useEffect } from 'react'

function getWithExpiry<T>(key: string) {
if (typeof window !== 'undefined') {
Expand Down
Loading