jooy2/vitepress-sidebar

Use `gray-matter` to parse frontmatter data

Closed this issue · 4 comments

The current implementation of useTitleFromFrontmatter (https://github.com/jooy2/vitepress-sidebar/blob/080b083d99de84adecdd5b05a6a4795233d579cc/lib/index.ts#LL227C1-L246C6) doesn't parse Frontmatter correctly.

It works for simple titles, but it doesn't if you have colons or special characters in the title. The only way of making it work is to put the title between quotes, but then the quotes are added to the submenu...

YAML supports the use of > for these cases but this is not a solution either, because the current implementation would just use > in the submenu.

It would make more sense to use gray-matter directly, like Vitepress does: https://github.com/vuejs/vitepress/blob/80e734d67763fea449647b7b21dfde0bde1c360b/src/node/contentLoader.ts#L5

Something like this should work (not tested):

// there are other imports here

import matter from 'gray-matter'

// there is code here

if (options.useTitleFromFrontmatter) {
  // Use content frontmatter title value instead of file name
  try {
    const src = readFileSync(filePath, 'utf-8');
    const { data: frontmatter } = matter(src);
    if (frontmatter.title) {
      const str = frontmatter.title.toString();
      return options.capitalizeFirst ? str.charAt(0).toUpperCase() + str.slice(1) : str;
    }
  } catch {
    return 'Unknown';
  }
}
jooy2 commented

Hello, Can you provide an example of Frontmatter that contains the special characters or colons you're having trouble with? If you can leave the entire Frontmatter before the body in a comment, I'll take a look.

The expected correct Frontmatter would look like this:

---
title: This is title
---

I try to avoid using external package dependencies in vitepress-sidebar as much as possible, but if that doesn't work, i'll consider using the module you provided.

Regards,

Well, you could try with these:

---
title: 'This won't work: a colon needs quotes, and quotes will be printed'
---
---
title: >
  YAML allows this format: but this won't work either in the current sidebar, it will just show `>`
---

I suggested to use gray-matter because it is already needed for vitepress. And anybody using vitepress-sidebar will already have vitepress installed...

jooy2 commented

Hello,

As per your request, i have released version 1.8.0 with new frontmatter parsing.
Could you please upgrade to that version and check if the issue is resolved?

Thanks.

jooy2 commented

I'm closing this issue as complete, please open a new issue if you have any issues.

Thanks,