Skip to content

Commit

Permalink
feat: support front matter
Browse files Browse the repository at this point in the history
  • Loading branch information
yanglbme committed Jan 5, 2025
1 parent ddff468 commit 7fb7d19
Show file tree
Hide file tree
Showing 4 changed files with 70 additions and 2 deletions.
51 changes: 51 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"csstype": "^3.1.3",
"es-toolkit": "^1.27.0",
"form-data": "4.0.1",
"front-matter": "^4.0.2",
"highlight.js": "^11.10.0",
"juice": "^11.0.0",
"lucide-vue-next": "^0.462.0",
Expand Down
3 changes: 2 additions & 1 deletion src/stores/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,8 @@ export const useStore = defineStore(`store`, () => {
codeThemeChange()
renderer.reset({ citeStatus: isCiteStatus.value, legend: legend.value, isUseIndent: isUseIndent.value })

let outputTemp = marked.parse(editor.value!.getValue()) as string
const { markdownContent } = renderer.parseFrontMatterAndContent(editor.value!.getValue())
let outputTemp = marked.parse(markdownContent) as string

// 去除第一行的 margin-top
outputTemp = outputTemp.replace(/(style=".*?)"/, `$1;margin-top: 0"`)
Expand Down
17 changes: 16 additions & 1 deletion src/utils/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import type { ExtendedProperties, IOpts, ThemeStyles } from '@/types'
import type { PropertiesHyphen } from 'csstype'
import type { Renderer, RendererObject, Tokens } from 'marked'
import { cloneDeep, toMerged } from 'es-toolkit'
import hljs from 'highlight.js'
import frontMatter from 'front-matter'

import hljs from 'highlight.js'
import { marked } from 'marked'
import mermaid from 'mermaid'
import { getStyleString } from '.'
Expand Down Expand Up @@ -110,6 +111,19 @@ export function initRenderer(opts: IOpts) {
return getStyles(styleMapping, tag, addition)
}

function parseFrontMatterAndContent(markdownText: string) {
try {
const parsed = frontMatter(markdownText)
const yamlData = parsed.attributes
const markdownContent = parsed.body
return { yamlData, markdownContent }
}
catch (error) {
console.error(`Error parsing front-matter:`, error)
return { yamlData: {}, markdownContent: markdownText }
}
}

function styledContent(styleLabel: string, content: string, tagName?: string): string {
const tag = tagName ?? styleLabel
return `<${tag} ${styles(styleLabel)}>${content}</${tag}>`
Expand Down Expand Up @@ -280,6 +294,7 @@ export function initRenderer(opts: IOpts) {
buildFootnotes,
setOptions,
reset,
parseFrontMatterAndContent,
createContainer(content: string) {
return styledContent(`container`, content, `section`)
},
Expand Down

0 comments on commit 7fb7d19

Please sign in to comment.