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: add table of contents to advanced blog #249

Open
wants to merge 2 commits into
base: canary
Choose a base branch
from
Open
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 examples/advanced-blog/src/app/(web)/posts/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export default async function Post(params: Params) {
<DocHero {...post} />
<div className="max-w-2xl mx-auto">
<div className="prose prose-outstatic">
<MDXComponent content={post.content} />
<MDXComponent content={post.content} showTOC />
</div>
</div>
</article>
Expand Down
70 changes: 46 additions & 24 deletions examples/advanced-blog/src/components/mdx/mdx-component.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
"use client";
import { getMDXComponent } from "mdx-bundler/client";
import Image from "next/image";
import { ImgHTMLAttributes, useMemo } from "react";
import { CustomCode, Pre } from "./custom-code";
import CustomLink from "./custom-link";
'use client'
import { getMDXComponent } from 'mdx-bundler/client'
import Image from 'next/image'
import { ImgHTMLAttributes, useMemo, useRef, useEffect, useState } from 'react'
import { CustomCode, Pre } from './custom-code'
import CustomLink from './custom-link'
import TOC from './toc'

const MDXComponentsMap = {
a: CustomLink,
Expand All @@ -12,30 +13,51 @@ const MDXComponentsMap = {
<img className="border rounded-lg" {...props} />
),
pre: Pre,
code: CustomCode,
};
code: CustomCode
}

type MDXComponentProps = {
content: string;
components?: Record<string, any>;
};
content: string
components?: Record<string, any>
showTOC?: boolean
}

export const MDXComponent = ({
content,
components = {},
showTOC = false
}: MDXComponentProps) => {
const Component = useMemo(() => getMDXComponent(content), [content]);
const [renderedContent, setRenderedContent] = useState('')
const contentRef = useRef<HTMLDivElement>(null)

const Component = useMemo(() => getMDXComponent(content), [content])

useEffect(() => {
if (contentRef.current) {
setRenderedContent(contentRef.current.innerHTML)
}
}, [content])

const shouldShowTOC = useMemo(() => {
if (showTOC === true) return true
if (showTOC === false) return false
}, [showTOC])

return (
<Component
components={
{
...MDXComponentsMap,
...components,
} as any
}
/>
);
};

export default MDXComponent;
<>
{shouldShowTOC && <TOC content={renderedContent} />}
<div ref={contentRef}>
<Component
components={
{
...MDXComponentsMap,
...components
} as any
}
/>
</div>
</>
)
}

export default MDXComponent
80 changes: 80 additions & 0 deletions examples/advanced-blog/src/components/mdx/toc.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import React, { useEffect, useState, useMemo } from 'react'
import { twMerge } from 'tailwind-merge'

interface TOCItem {
depth: number
value: string
url: string
}

interface TOCProps {
content: string
maxDepth?: number
className?: string
headingClassName?: string
title?: string
}

const TOC: React.FC<TOCProps> = ({
content,
maxDepth = 3,
className = 'toc',
headingClassName = 'toc-heading',
title = 'Table of Contents'
}) => {
const [headings, setHeadings] = useState<TOCItem[]>([])

const extractHeadings = useMemo(
() => () => {
try {
const tempDiv = document.createElement('div')
tempDiv.innerHTML = content

const headingElements = tempDiv.querySelectorAll(
'h1, h2, h3, h4, h5, h6'
)
return Array.from(headingElements)
.filter((el) => parseInt(el.tagName[1]) <= maxDepth)
.map((el) => ({
depth: parseInt(el.tagName[1]),
value: el.textContent?.trim() || '',
url: `#${el.id}`
}))
} catch (error) {
console.error('Error extracting headings:', error)
return []
}
},
[content, maxDepth]
)

useEffect(() => {
setHeadings(extractHeadings())
}, [extractHeadings])

if (headings.length === 0) {
return null
}

return (
<nav className={className}>
<h2 className={twMerge(headingClassName, 'hover:!no-underline')}>
{title}
</h2>
<ul>
{headings.map((heading, index) => (
<li
key={`${heading.url}-${index}`}
style={{ marginLeft: `${(heading.depth - 1) * 16}px` }}
>
<a href={heading.url} className="no-underline hover:underline">
{heading.value}
</a>
</li>
))}
</ul>
</nav>
)
}

export default TOC