Skip to content

Commit

Permalink
fix(docs): fix compileMarkdown heading id generation
Browse files Browse the repository at this point in the history
  • Loading branch information
Kadirsaglm committed Sep 2, 2024
1 parent 2cf4255 commit 527e6d6
Showing 1 changed file with 28 additions and 9 deletions.
37 changes: 28 additions & 9 deletions packages/__docs__/src/compileMarkdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
* SOFTWARE.
*/

import React, { ReactElement, ReactNode } from 'react'
import React, { Children, ReactElement, ReactNode } from 'react'
import Markdown from 'marked-react'
import grayMatter from 'gray-matter'
import { v4 as uuid } from 'uuid'
Expand All @@ -41,14 +41,33 @@ import { Heading } from './Heading'
import { Link } from './Link'
import { trimIndent } from './trimIndent'

const getHeadingId = (children: ReactNode): string => {
return Children.toArray(children).reduce((id, child) => {
if (typeof child === 'string') {
return id + child
}

if (
typeof child === 'object' &&
child !== null &&
'props' in child &&
typeof child.props.children === 'string'
) {
return id + child.props.children
}

return id
}, '') as string
}

const headingVariants: Record<
string,
(key: string, children: ReactNode) => ReactElement
> = {
h1: (key, children) => {
return (
<Heading
id={(children as [string])?.[0]}
id={getHeadingId(children)}
key={key}
level="h1"
margin="0 0 large"
Expand All @@ -59,7 +78,7 @@ const headingVariants: Record<
},
h2: (key, children) => (
<Heading
id={(children as [string])?.[0]}
id={getHeadingId(children)}
key={key}
level="h1"
as="h2"
Expand All @@ -70,7 +89,7 @@ const headingVariants: Record<
),
h3: (key, children) => (
<Heading
id={(children as [string])?.[0]}
id={getHeadingId(children)}
key={key}
level="h2"
as="h3"
Expand All @@ -79,20 +98,20 @@ const headingVariants: Record<
{children}
</Heading>
),
h4: (key, children) => (
<Heading
id={(children as [string])?.[0]}
h4: (key, children) => {
return <Heading
id={getHeadingId(children)}
key={key}
level="h3"
as="h4"
margin="large 0 medium 0"
>
{children}
</Heading>
),
},
h5: (key, children) => (
<Heading
id={(children as [string])?.[0]}
id={getHeadingId(children)}
key={key}
level="h4"
as="h5"
Expand Down

0 comments on commit 527e6d6

Please sign in to comment.