zce / velite

Turns Markdown / MDX, YAML, JSON, or others into app's data layer with Zod schema.
http://velite.js.org
MIT License
502 stars 24 forks source link

Is there a way to add id to heading tags so that they can be used as anchor links? #95

Closed Roopaish closed 8 months ago

Roopaish commented 8 months ago

If i have a markdown like

## Some Text

I want it to generate html code like

<h2 id="some-text">Some Text</h2>

so by using any anchor tags like <a href="#some-text">Go to some text</a> ,the page will scroll to above h2 position.

currently only that tag with children is being generated, is there an easy way to add slugified value of children as id too to heading elements only? or something like Github markdown.

Roopaish commented 8 months ago

Okay so i managed to add ids using the prepare function with below code in velite config, in case someone needs it, its here. but it would have been nice if library provides it or I missed something?

  blogs.forEach((blog) => {
      const pattern = /n\(\w\.h[1-7],{[^}]+}\)/g

      let match
      while ((match = pattern.exec(blog.content)) !== null) {
        const matchedText = match[0]

        const childrenMatch = matchedText.match(/children:"([^"]+)"/)
        if (childrenMatch) {
          const childrenText = childrenMatch[1]
          const slugifiedChildren = slugify(childrenText)

          const modifiedText = matchedText.replace(
            /(children:")([^"]+)(")/,
            `$1$2$3,id:"${slugifiedChildren}"`
          )

          blog.content = blog.content.replace(matchedText, modifiedText)
        }
      }
    })
zce commented 8 months ago

https://github.com/rehypejs/rehype-autolink-headings