"use client" /** * PageScrollNav — back-to-top plus a section outline for long pages. * * The outline is the page counterpart of Ask Leo's transcript outline (shadcn * Transcript Outline): a rail of ticks, one per section, with the current one * emphasised, and a hover / focus card listing the sections as Marker rows that * jump there. The back-to-top button is the page counterpart of * `MessageScrollerButton direction="start"`: it appears once you have scrolled * away from the top and is inert (out of Tab order) while hidden. * * Both read the page's scrollport (`[data-page-scroll]`), not `window`. Mark a * section with `data-outline-section`; its label is the attribute value, else * its first heading. Fewer than `minSections` sections shows no outline. * * Render once per page template, inside a `relative` ancestor. */ import * as React from "react" import { cn } from "../../lib/utils" import { getPageScrollElement, PAGE_SCROLL_ATTR, } from "../../lib/page-scroll-port" import { Button } from "./button" import { HoverCard, HoverCardContent, HoverCardTrigger } from "./hover-card" import { Marker, MarkerContent, MarkerIcon } from "./marker" export const OUTLINE_SECTION_ATTR = "data-outline-section" /** Distance a section's top may sit below the scrollport top and still count as current. */ const CURRENT_SECTION_SLOP_PX = 96 /** Space left above a section when jumping, so sticky chrome does not cover its title. */ const JUMP_OFFSET_PX = 64 type OutlineSection = { el: HTMLElement; label: string } /** A stable React key per section element, so reordering sections does not remount ticks. */ const sectionKeys = new WeakMap() let nextSectionKey = 0 function sectionKey(el: HTMLElement) { let key = sectionKeys.get(el) if (key === undefined) { key = nextSectionKey++ sectionKeys.set(el, key) } return key } function prefersReducedMotion() { return ( typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches ) } function readSections(scroller: HTMLElement): OutlineSection[] { return [ ...scroller.querySelectorAll(`[${OUTLINE_SECTION_ATTR}]`), ] .map((el) => { const explicit = el.getAttribute(OUTLINE_SECTION_ATTR)?.trim() const heading = el.querySelector("h1, h2, h3")?.textContent?.trim() return { el, label: explicit || heading || "" } }) .filter((s) => s.label) } function sectionsEqual(a: OutlineSection[], b: OutlineSection[]) { return ( a.length === b.length && a.every((s, i) => s.el === b[i].el && s.label === b[i].label) ) } /** * The page scrollport next to this nav. Looked up from the nav's own parent, and * re-read when the parent's children change, so a page that swaps its scrollport * (route transitions, Suspense fallbacks) is followed rather than lost. */ function usePageScroller( rootRef: React.RefObject, scrollRef?: React.RefObject, ) { const [scroller, setScroller] = React.useState(null) React.useEffect(() => { const host = rootRef.current?.parentElement const resolve = () => setScroller( scrollRef?.current ?? host?.querySelector(`[${PAGE_SCROLL_ATTR}]`) ?? getPageScrollElement(), ) resolve() if (!host) return const observer = new MutationObserver(resolve) observer.observe(host, { childList: true }) return () => observer.disconnect() }, [rootRef, scrollRef]) return scroller } function PageScrollNav({ backToTopThreshold = 480, minSections = 3, scrollRef, className, }: { /** Scroll distance (px) before back-to-top appears. */ backToTopThreshold?: number /** Fewer sections than this hides the outline. */ minSections?: number /** Scrollport to follow, for a nav inside a bounded region. Defaults to the page's `[data-page-scroll]`. */ scrollRef?: React.RefObject className?: string }) { const rootRef = React.useRef(null) const scroller = usePageScroller(rootRef, scrollRef) const [showTop, setShowTop] = React.useState(false) const [sections, setSections] = React.useState([]) const [currentIndex, setCurrentIndex] = React.useState(0) // Sections come and go as the page (and its tabs) render; re-read on DOM change. // A short timer rather than a frame: a hidden tab pauses frames, and the outline // should already be right when the tab comes back. React.useEffect(() => { if (!scroller) return let timer: number | undefined const read = () => { timer = undefined const next = readSections(scroller) setSections((prev) => (sectionsEqual(prev, next) ? prev : next)) } const schedule = () => { if (timer === undefined) timer = window.setTimeout(read, 60) } read() const observer = new MutationObserver(schedule) observer.observe(scroller, { childList: true, subtree: true }) return () => { observer.disconnect() window.clearTimeout(timer) } }, [scroller]) React.useEffect(() => { if (!scroller) return let timer: number | undefined const update = () => { timer = undefined setShowTop(scroller.scrollTop > backToTopThreshold) const top = scroller.getBoundingClientRect().top let index = 0 sections.forEach((s, i) => { if (s.el.getBoundingClientRect().top - top <= CURRENT_SECTION_SLOP_PX) { index = i } }) setCurrentIndex(index) } // Trailing throttle: scroll fires far faster than the rail needs to move. const schedule = () => { if (timer === undefined) timer = window.setTimeout(update, 50) } update() scroller.addEventListener("scroll", schedule, { passive: true }) return () => { scroller.removeEventListener("scroll", schedule) window.clearTimeout(timer) } }, [scroller, sections, backToTopThreshold]) const scrollBehavior = (): ScrollBehavior => prefersReducedMotion() ? "auto" : "smooth" function jumpTo(section: OutlineSection) { if (!scroller) return const delta = section.el.getBoundingClientRect().top - scroller.getBoundingClientRect().top - JUMP_OFFSET_PX scroller.scrollTo({ top: scroller.scrollTop + delta, behavior: scrollBehavior(), }) } function backToTop() { if (!scroller) return scroller.scrollTo({ top: 0, behavior: scrollBehavior() }) // Keep the keyboard where the content is, not on a button that is about to hide. ;(scroller.closest("#main-content") ?? scroller).focus({ preventScroll: true, }) } const showOutline = sections.length >= minSections return (
{showOutline && (