Skip to content

Commit 315ca82

Browse files
author
Dimitri POSTOLOV
authoredOct 11, 2023
[v3] remove possible links in toc elements (#2427)
1 parent d3e9fdb commit 315ca82

File tree

4 files changed

+27
-4
lines changed

4 files changed

+27
-4
lines changed
 

‎.changeset/two-scissors-prove.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'nextra-theme-docs': patch
3+
---
4+
5+
remove possible links in toc elements

‎packages/nextra-theme-blog/src/mdx-theme.tsx

-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,6 @@ const A = ({ children, href = '', ...props }: ComponentProps<'a'>) => {
6363
return (
6464
<a href={href} target="_blank" rel="noreferrer" {...props}>
6565
{children}
66-
<span className="_sr-only _select-none"> (opens in a new tab)</span>
6766
</a>
6867
)
6968
}

‎packages/nextra-theme-docs/src/components/anchor.tsx

-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ export const Anchor = forwardRef<HTMLAnchorElement, AnchorProps>(function (
2222
{...props}
2323
>
2424
{children}
25-
<span className="_sr-only _select-none"> (opens in a new tab)</span>
2625
</a>
2726
)
2827
}

‎packages/nextra-theme-docs/src/components/toc.tsx

+22-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import cn from 'clsx'
22
import type { Heading } from 'nextra'
33
import type { ReactElement } from 'react'
4-
import { useEffect, useRef } from 'react'
4+
import { Children, cloneElement, useEffect, useRef } from 'react'
55
import scrollIntoView from 'scroll-into-view-if-needed'
66
import { useActiveAnchor, useThemeConfig } from '../contexts'
77
import { renderComponent } from '../utils'
@@ -18,6 +18,26 @@ const linkClassName = cn(
1818
'contrast-more:_text-gray-800 contrast-more:dark:_text-gray-50'
1919
)
2020

21+
type TOCElement = ReactElement | string
22+
23+
function isLink(node: TOCElement): node is ReactElement {
24+
return typeof node !== 'string' && !!node.props.href
25+
}
26+
27+
function removeLinks(node: TOCElement): TOCElement[] {
28+
return Children.map(node, child => {
29+
if (isLink(child)) {
30+
child = child.props.children
31+
}
32+
33+
return typeof child === 'string'
34+
? child
35+
: cloneElement(child, {
36+
children: removeLinks(child.props.children)
37+
})
38+
})
39+
}
40+
2141
export function TOC({ toc, filePath }: TOCProps): ReactElement {
2242
const activeAnchor = useActiveAnchor()
2343
const tocRef = useRef<HTMLDivElement>(null)
@@ -84,7 +104,7 @@ export function TOC({ toc, filePath }: TOCProps): ReactElement {
84104
'contrast-more:_text-gray-900 contrast-more:_underline contrast-more:dark:_text-gray-50 _w-full _break-words'
85105
)}
86106
>
87-
{value}
107+
{removeLinks(value)}
88108
</a>
89109
</li>
90110
))}

0 commit comments

Comments
 (0)
Please sign in to comment.