forked from vuejs/vitepress
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parseHeader.ts
68 lines (59 loc) · 2.41 KB
/
parseHeader.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// Since VuePress needs to extract the header from the markdown source
// file and display it in the sidebar or title (#238), this file simply
// removes some unnecessary elements to make header displays well at
// sidebar or title.
//
// But header's parsing in the markdown content is done by the markdown
// loader based on markdown-it. markdown-it parser will will always keep
// HTML in headers, so in VuePress, after being parsed by the markdown
// loader, the raw HTML in headers will finally be parsed by Vue-loader.
// so that we can write HTML/Vue in the header. One exception is the HTML
// wrapped by <code>(markdown token: '`') tag.
import emojiData from 'markdown-it-emoji/lib/data/full.json'
const parseEmojis = (str: string) => {
return str.replace(
/:(.+?):/g,
(placeholder, key) => (emojiData as any)[key] || placeholder
)
}
const unescapeHtml = (html: string) =>
html
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(/:/g, ':')
.replace(/</g, '<')
.replace(/>/g, '>')
const removeMarkdownTokens = (str: string) =>
str
.replace(/(\[(.[^\]]+)\]\((.[^)]+)\))/g, '$2') // []()
.replace(/(`|\*{1,3}|_)(.*?[^\\])\1/g, '$2') // `{t}` | *{t}* | **{t}** | ***{t}*** | _{t}_
.replace(/(\\)(\*|_|`|\!|<|\$)/g, '$2') // remove escape char '\'
const removeCustomAnchor = (str: string) =>
str.replace(/\{#([a-zA-Z0-9\-_]+?)\}\s*$/, '') // {#custom-header}
const trim = (str: string) => str.trim()
// This method remove the raw HTML but reserve the HTML wrapped by `<code>`.
// e.g.
// Input: "<a> b", Output: "b"
// Input: "`<a>` b", Output: "`<a>` b"
export const removeNonCodeWrappedHTML = (str: string) => {
return String(str).replace(/(^|[^><`\\])<.*>([^><`]|$)/g, '$1$2')
}
const compose = (...processors: ((str: string) => string)[]) => {
if (processors.length === 0) return (input: string) => input
if (processors.length === 1) return processors[0]
return processors.reduce((prev, next) => {
return (str) => next(prev(str))
})
}
// Unescape html, parse emojis and remove some md tokens.
export const parseHeader = compose(
unescapeHtml,
parseEmojis,
removeCustomAnchor,
removeMarkdownTokens,
trim
)
// Also clean the html that isn't wrapped by code.
// Because we want to support using VUE components in headers.
// e.g. https://vuepress.vuejs.org/guide/using-vue.html#badge
export const deeplyParseHeader = compose(removeNonCodeWrappedHTML, parseHeader)