Fix autolinked CLI headings that already contain a link

Luke Karrys committed Oct 19, 2023 at 12:21 UTC a43b161bd211c9635d6e34bb2687451ed17e03ac
1 file changed +47 -25
src/mdx/index.js
+47 -25
@@ -38,39 +38,61 @@ const StyledHeading = styled(Heading)`
38 }
39 `
40
41 +const HeaderLink = ({autolink, children, ...props}) =>
42 + autolink ? (
43 + <PrimerLink
44 + {...props}
45 + sx={{
46 + color: 'inherit',
47 + '&:hover, &:focus': {
48 + textDecoration: 'none',
49 + },
50 + }}
51 + >
52 + {children}
53 + <Octicon
54 + icon={LinkIcon}
55 + className="octicon-link"
56 + sx={{
57 + ml: 2,
58 + color: 'fg.muted',
59 + // !important is needed here to override default icon styles
60 + verticalAlign: 'middle !important',
61 + }}
62 + />
63 + </PrimerLink>
64 + ) : (
65 + children
66 + )
67 +
68 const Headings = {
69 Markdown: ({children, autolink = true, ...props}) => {
70 + const childArray = React.Children.toArray(children)
71 + const childLink =
72 + React.Children.count(children) > 1 && childArray[0].type?.name === 'Link' ? childArray.shift() : null
73 +
74 const {slugger} = usePage()
75 const text = children ? textContent(children) : ''
76 const id = text ? slugger.slug(text) : ''
77 + const linkProps = {
78 + autolink,
79 + 'aria-label': `${text} permalink`.trim(),
80 + ...(id ? {href: `#${id}`} : {}),
81 + }
82
83 return (
48 - <StyledHeading {...(autolink ? {id} : {})} {...props}>
49 - {autolink ? (
50 - <PrimerLink
51 - href={`#${id}`}
52 - aria-label={`${text} permalink`}
53 - sx={{
54 - color: 'inherit',
55 - '&:hover, &:focus': {
56 - textDecoration: 'none',
57 - },
58 - }}
59 - >
60 - {children}
61 - <Octicon
62 - icon={LinkIcon}
63 - className="octicon-link"
64 - sx={{
65 - ml: 2,
66 - color: 'fg.muted',
67 - // !important is needed here to override default icon styles
68 - verticalAlign: 'middle !important',
69 - }}
70 - />
71 - </PrimerLink>
84 + <StyledHeading {...(autolink && id ? {id} : {})} {...props}>
85 + {childLink ? (
86 + <React.Fragment>
87 + {childLink}
88 + <HeaderLink {...linkProps}>
89 + {childArray.map((child, index) => (
90 + <React.Fragment key={index}>{child}</React.Fragment>
91 + ))}
92 + </HeaderLink>
93 + </React.Fragment>
94 ) : (
73 - children
95 + <HeaderLink {...linkProps}>{children}</HeaderLink>
96 )}
97 </StyledHeading>
98 )