Raw
1 "use client"
2
3 import React, { useEffect } from "react"
4 import { ToCItem, ToCItemUi } from "types"
5 import { useScrollController } from "../../../hooks/use-scroll-utils"
6 import {
7 ActiveOnScrollItem,
8 useActiveOnScroll,
9 } from "../../../hooks/use-active-on-scroll"
10 import clsx from "clsx"
11 import Link from "next/link"
12 import { useSiteConfig } from "../../../providers/SiteConfig"
13 import { Loading } from "../../Loading"
14 import { ContentMenuSection } from "../Section"
15
16 export const ContentMenuToc = () => {
17 const { toc: items, frontmatter, setToc } = useSiteConfig()
18 const { items: generatedItems, activeItemId } = useActiveOnScroll({
19 maxLevel: 4,
20 })
21
22 const formatHeadingContent = (heading: HTMLHeadingElement): string => {
23 // Use the heading's full text (so inline code, links, etc. are included),
24 // but drop the appended self-anchor permalink (`<a href="#id">#</a>`) that
25 // the heading components add. Content links (e.g. a signature title's return
26 // type) point elsewhere, so they're preserved.
27 const clone = heading.cloneNode(true) as HTMLElement
28 clone.querySelectorAll(`a[href^="#"]`).forEach((anchor) => anchor.remove())
29 return (clone.textContent || "").replace(/\s+/g, " ").trim()
30 }
31
32 const formatHeadingObject = ({
33 heading,
34 children,
35 }: ActiveOnScrollItem): ToCItemUi => {
36 const level = parseInt(heading.tagName.replace("H", ""))
37 return {
38 title: formatHeadingContent(heading),
39 id: heading.id,
40 level,
41 children: children?.map(formatHeadingObject),
42 associatedHeading: heading as HTMLHeadingElement,
43 }
44 }
45
46 useEffect(() => {
47 if (
48 frontmatter.generate_toc &&
49 generatedItems &&
50 items?.length !== generatedItems.length
51 ) {
52 const tocItems: ToCItem[] = generatedItems.map(formatHeadingObject)
53 setToc(tocItems)
54 }
55 }, [frontmatter, generatedItems])
56
57 useEffect(() => {
58 const activeElement = document.querySelector(
59 ".toc-item a[href='#" + activeItemId + "']"
60 ) as HTMLAnchorElement
61 if (!activeElement) {
62 return
63 }
64
65 activeElement.scrollIntoView({
66 behavior: "smooth",
67 block: "center",
68 inline: "nearest",
69 })
70 }, [activeItemId])
71
72 if (items && !items.length) {
73 return <></>
74 }
75
76 return (
77 <ContentMenuSection title="On this page">
78 <div className="h-max max-h-full overflow-y-hidden flex relative flex-col">
79 {items !== null && (
80 <TocList
81 items={items}
82 activeItemId={activeItemId}
83 className="relative overflow-y-auto py-docs_0.75 px-docs_1"
84 />
85 )}
86 {items === null && <EmptyTocItems />}
87 </div>
88 </ContentMenuSection>
89 )
90 }
91
92 type TocListProps = {
93 items: ToCItem[]
94 activeItemId: string
95 className?: string
96 }
97
98 const TocList = ({ items, activeItemId, className }: TocListProps) => {
99 return (
100 <ul className={className} data-testid="toc-list">
101 {items.map((item) => (
102 <TocItem item={item} key={item.id} activeItemId={activeItemId} />
103 ))}
104 </ul>
105 )
106 }
107
108 type TocItemProps = {
109 item: ToCItem
110 activeItemId: string
111 }
112
113 const TocItem = ({ item, activeItemId }: TocItemProps) => {
114 const { scrollToElement } = useScrollController()
115 return (
116 <li className="w-full toc-item" data-testid="toc-item">
117 <Link
118 href={`#${item.id}`}
119 className={clsx(
120 "block w-full relative py-docs_0.25",
121 item.id !== activeItemId &&
122 "text-medusa-fg-subtle hover:text-medusa-fg-base text-x-small",
123 item.id === activeItemId && "text-medusa-fg-base text-x-small-plus",
124 "truncate"
125 )}
126 onClick={(e) => {
127 e.preventDefault()
128 history.pushState({}, "", `#${item.id}`)
129 const elm = document.getElementById(item.id) as HTMLElement
130 scrollToElement(elm)
131 }}
132 >
133 {item.title}
134 </Link>
135 {(item.children?.length ?? 0) > 0 && (
136 <TocList
137 items={item.children!}
138 activeItemId={activeItemId}
139 className="pl-docs_0.75 relative after:content-[''] after:absolute after:left-0 after:top-docs_0.25 after:bottom-docs_0.25 after:w-docs_0.125 after:h-[calc(100%-8px)] after:bg-medusa-border-strong"
140 />
141 )}
142 </li>
143 )
144 }
145
146 const EmptyTocItems = () => {
147 return (
148 <div className="animate-pulse" data-testid="empty-toc-items">
149 <Loading
150 count={5}
151 className="!py-docs_0.75 !px-docs_1 !my-0"
152 barClassName="!h-docs_0.5"
153 />
154 </div>
155 )
156 }