2019-08-09 12:42:07 +00:00
|
|
|
'use strict'
|
|
|
|
/* global hexo */
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Add Link button next to a heading
|
2024-06-07 12:38:33 +00:00
|
|
|
* based on https://github.com/hexojs/hexo-renderer-marked/blob/master/lib/renderer.js
|
2019-08-09 12:42:07 +00:00
|
|
|
*/
|
|
|
|
|
2024-06-07 12:38:33 +00:00
|
|
|
const { slugize, stripHTML, unescapeHTML: unescape } = require('hexo-util')
|
2019-12-24 04:38:02 +00:00
|
|
|
|
|
|
|
const anchorId = (str, transformOption) => {
|
2024-06-08 04:45:34 +00:00
|
|
|
return slugize(stripHTML(unescape(str.replace('.', ''))).trim(), { transform: transformOption })
|
2019-12-24 04:38:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
hexo.extend.filter.register('marked:renderer', function (renderer) {
|
|
|
|
const { config } = this
|
2024-06-08 02:46:12 +00:00
|
|
|
const headingId = {}
|
2019-12-24 04:38:02 +00:00
|
|
|
renderer.heading = function (text, level) {
|
2024-06-07 12:38:33 +00:00
|
|
|
const { modifyAnchors } = config.marked
|
2024-06-08 02:46:12 +00:00
|
|
|
const transformOption = modifyAnchors
|
2024-06-07 12:38:33 +00:00
|
|
|
let id = anchorId(text, transformOption)
|
2019-12-24 04:38:02 +00:00
|
|
|
|
|
|
|
// Add a number after id if repeated
|
|
|
|
if (headingId[id]) {
|
|
|
|
id += `-${headingId[id]++}`
|
|
|
|
} else {
|
|
|
|
headingId[id] = 1
|
|
|
|
}
|
|
|
|
|
|
|
|
// add headerlink
|
2021-11-30 08:18:07 +00:00
|
|
|
return `<h${level} id="${id}">${text} <a href="#${id}" class="headerlink" title="${stripHTML(text)}">§</a></h${level}>`
|
2019-12-24 04:38:02 +00:00
|
|
|
}
|
2019-08-09 12:42:07 +00:00
|
|
|
})
|