Skip to content

Commit

Permalink
allow headings contain links (#897)
Browse files Browse the repository at this point in the history
  • Loading branch information
dimaMachina committed Oct 18, 2022
1 parent 5238bb4 commit cef5546
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 18 deletions.
7 changes: 7 additions & 0 deletions .changeset/brown-cats-deliver.md
@@ -0,0 +1,7 @@
---
'nextra': patch
'nextra-theme-blog': patch
'nextra-theme-docs': patch
---

allow headings contain links
7 changes: 4 additions & 3 deletions packages/nextra-theme-blog/src/mdx-theme.tsx
Expand Up @@ -36,14 +36,15 @@ const createHeaderLink =
({ children, id, ...props }: ComponentProps<'h2'>): ReactElement => {
return (
<Tag className={`subheading-${Tag}`} {...props}>
<span className="subheading-anchor -mt-8" id={id} />
<a href={`#${id}`}>{children}</a>
{children}
<span className="absolute -mt-7" id={id} />
<a href={`#${id}`} className="subheading-anchor" />
</Tag>
)
}

const A = ({ children, ...props }: ComponentProps<'a'>) => {
const isExternal = props.href && props.href.startsWith('https://')
const isExternal = props.href?.startsWith('https://')
if (isExternal) {
return (
<a target="_blank" rel="noreferrer" {...props}>
Expand Down
7 changes: 4 additions & 3 deletions packages/nextra-theme-docs/src/mdx-components.tsx
Expand Up @@ -85,7 +85,7 @@ const createHeaderLink = (
...props
}: ComponentProps<'h2'>): ReactElement {
setActiveAnchor ??= useSetActiveAnchor()
const obRef = useRef<HTMLSpanElement>(null)
const obRef = useRef<HTMLAnchorElement>(null)

useEffect(() => {
const heading = obRef.current
Expand Down Expand Up @@ -119,8 +119,9 @@ const createHeaderLink = (
)}
{...props}
>
<span className="subheading-anchor -mt-20" id={id} ref={obRef} />
<a href={`#${id}`}>{children}</a>
{children}
<span className="absolute -mt-20" id={id} ref={obRef} />
<a href={`#${id}`} className="subheading-anchor" />
</Tag>
)
}
Expand Down
23 changes: 11 additions & 12 deletions packages/nextra/styles/subheading-anchor.css
@@ -1,18 +1,17 @@
.subheading-anchor {
@apply absolute;
@apply opacity-0 transition-opacity ltr:ml-1 rtl:mr-1;

& + a {
@apply text-current no-underline hover:after:opacity-100;
span:target + &,
:hover > & {
@apply no-underline opacity-100;
}

& + a:after {
@apply absolute /* for not including # in focus ring border */;
@apply content-['#'] text-gray-300 px-2 opacity-0 transition-opacity;
@apply dark:text-neutral-700;
}

&:target + a:after {
@apply text-gray-400 opacity-100;
@apply dark:text-neutral-500;
&:after {
@apply content-['#'] px-1;
@apply text-gray-300 dark:text-neutral-700;
span:target + & {
@apply text-gray-400;
@apply dark:text-neutral-500;
}
}
}

0 comments on commit cef5546

Please sign in to comment.