Skip to content

Commit eea5b42

Browse files
committed
feat: sidebar header extraction improvements (close: #238)
1 parent d454b1c commit eea5b42

File tree

2 files changed

+41
-6
lines changed

2 files changed

+41
-6
lines changed

lib/util/index.js

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
1-
const parseEmojis = str => {
2-
const emojiData = require('markdown-it-emoji/lib/data/full.json')
3-
return str.replace(/:(.+?):/g, (placeholder, key) => emojiData[key] || placeholder)
1+
const parseHeaders = require('./parseHeaders')
2+
3+
exports.compose = (...processors) => {
4+
if (processors.length === 0) {
5+
return input => input
6+
}
7+
if (processors.length === 1) {
8+
return processors[0]
9+
}
10+
return processors.reduce((prev, next) => {
11+
return (...args) => next(prev(...args))
12+
})
413
}
514

615
exports.normalizeHeadTag = tag => {
@@ -35,11 +44,11 @@ exports.inferTitle = function (frontmatter) {
3544
return 'Home'
3645
}
3746
if (frontmatter.data.title) {
38-
return parseEmojis(frontmatter.data.title)
47+
return parseHeaders(frontmatter.data.title)
3948
}
4049
const match = frontmatter.content.trim().match(/^#+\s+(.*)/)
4150
if (match) {
42-
return parseEmojis(match[1])
51+
return parseHeaders(match[1])
4352
}
4453
}
4554

@@ -71,7 +80,7 @@ exports.extractHeaders = (content, include = [], md) => {
7180
const res = []
7281
tokens.forEach((t, i) => {
7382
if (t.type === 'heading_open' && include.includes(t.tag)) {
74-
const title = parseEmojis(tokens[i + 1].content)
83+
const title = parseHeaders(tokens[i + 1].content)
7584
const slug = t.attrs.find(([name]) => name === 'id')[1]
7685
res.push({
7786
level: parseInt(t.tag.slice(1), 10),

lib/util/parseHeaders.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
const parseEmojis = str => {
2+
const emojiData = require('markdown-it-emoji/lib/data/full.json')
3+
return str.replace(/:(.+?):/g, (placeholder, key) => emojiData[key] || placeholder)
4+
}
5+
6+
const unescapeHtml = html => html
7+
.replace(/"/g, '"')
8+
.replace(/'/g, '\'')
9+
.replace(/:/g, ':')
10+
.replace(/&lt;/g, '<')
11+
.replace(/&gt;/g, '>')
12+
13+
const removeMarkdownToken = str => str
14+
.replace(/`(.*)`/, '$1')
15+
.replace(/\[(.*)\]\(.*\)/, '$1')
16+
17+
// put here to avoid circular references
18+
const compose = (...processors) => {
19+
if (processors.length === 0) input => input
20+
if (processors.length === 1) processors[0]
21+
return processors.reduce((prev, next) => {
22+
return (...args) => next(prev(...args))
23+
})
24+
}
25+
26+
module.exports = compose(unescapeHtml, parseEmojis, removeMarkdownToken)

0 commit comments

Comments
 (0)