mirror of https://gitlab.com/curben/blog
refactor(heading-link): replace cheerio with marked:renderer filter
- https://github.com/hexojs/hexo-renderer-marked/pull/129
This commit is contained in:
parent
f4375dc216
commit
3beca85f47
|
@ -3,31 +3,30 @@
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Add Link button next to a heading
|
* Add Link button next to a heading
|
||||||
* cheerio is provided by hexo package
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const cheerio = require('cheerio')
|
const { slugize, stripHTML } = require('hexo-util')
|
||||||
|
const svg = '<svg height="0.75em" viewBox="15 15 1635 1635"><use href="/svg/link.svg#link"></use></svg>'
|
||||||
|
|
||||||
hexo.extend.filter.register('after_render:html', (str) => {
|
const anchorId = (str, transformOption) => {
|
||||||
const $ = cheerio.load(str)
|
return slugize(str.trim(), { transform: transformOption })
|
||||||
const svg = `<svg height="0.75em" viewBox="15 15 1635 1635">
|
}
|
||||||
<use href="/svg/link.svg#link"/>
|
|
||||||
</svg>`
|
|
||||||
|
|
||||||
const headings = ['h2', 'h3']
|
hexo.extend.filter.register('marked:renderer', function (renderer) {
|
||||||
|
const { config } = this
|
||||||
|
renderer.heading = function (text, level) {
|
||||||
|
const transformOption = config.marked.modifyAnchors
|
||||||
|
let id = anchorId(stripHTML(text), transformOption)
|
||||||
|
const headingId = this._headingId
|
||||||
|
|
||||||
headings.forEach(heading => {
|
// Add a number after id if repeated
|
||||||
$(heading).each((index, element) => {
|
if (headingId[id]) {
|
||||||
if ($(element).children('a').children('svg').length === 0) {
|
id += `-${headingId[id]++}`
|
||||||
const text = $(element).text().trim()
|
} else {
|
||||||
|
headingId[id] = 1
|
||||||
|
}
|
||||||
|
|
||||||
$(element).append($(element).children('a').append(svg))
|
// add headerlink
|
||||||
|
return `<h${level} id="${id}">${text} <a href="#${id}" class="headerlink" title="${stripHTML(text)}">${svg}</a></h${level}>`
|
||||||
const cache = $(element).children()
|
}
|
||||||
$(element).text(text + ' ').append(cache)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
|
|
||||||
return $.html()
|
|
||||||
})
|
})
|
||||||
|
|
Loading…
Reference in New Issue