Skip to content

Commit a381dda

Browse files
authored
refactor(toc_helper): utilize hexo-util (#3850)
* refactor(toc_helper): relpace cheerio with htmlparser2 * test(toc_helper): use classic for loop * refactor(toc_helper): utilize tocObj
1 parent 04d34a7 commit a381dda

File tree

2 files changed

+16
-22
lines changed

2 files changed

+16
-22
lines changed

lib/plugins/helper/toc.js

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,29 @@
11
'use strict';
22

3-
let cheerio;
4-
const { escapeHTML } = require('hexo-util');
3+
const { tocObj } = require('hexo-util');
54

65
function tocHelper(str, options = {}) {
7-
if (!cheerio) cheerio = require('cheerio');
6+
options = Object.assign({
7+
max_depth: 6,
8+
class: 'toc',
9+
list_number: true
10+
}, options);
811

9-
const $ = cheerio.load(str);
10-
const headingsMaxDepth = Object.prototype.hasOwnProperty.call(options, 'max_depth') ? options.max_depth : 6;
11-
const headingsSelector = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].slice(0, headingsMaxDepth).join(',');
12-
const headings = $(headingsSelector);
12+
const data = tocObj(str, { max_depth: options.max_depth });
1313

14-
if (!headings.length) return '';
14+
if (!data.length) return '';
15+
16+
const className = options.class;
17+
const listNumber = options.list_number;
1518

16-
const className = options.class || 'toc';
17-
const listNumber = Object.prototype.hasOwnProperty.call(options, 'list_number') ? options.list_number : true;
1819
let result = `<ol class="${className}">`;
1920
const lastNumber = [0, 0, 0, 0, 0, 0];
2021
let firstLevel = 0;
2122
let lastLevel = 0;
2223

23-
function getId(ele) {
24-
const id = $(ele).attr('id');
25-
const $parent = $(ele).parent();
26-
return id || ($parent.length < 1 ? null : getId($parent));
27-
}
28-
29-
headings.each(function() {
30-
const level = +this.name[1];
31-
const id = getId(this);
32-
const text = escapeHTML($(this).text());
24+
for (let i = 0, len = data.length; i < len; i++) {
25+
const el = data[i];
26+
const { level, id, text } = el;
3327

3428
lastNumber[level - 1]++;
3529

@@ -67,7 +61,7 @@ function tocHelper(str, options = {}) {
6761
result += `<span class="${className}-text">${text}</span></a>`;
6862

6963
lastLevel = level;
70-
});
64+
}
7165

7266
for (let i = firstLevel - 1; i < lastLevel; i++) {
7367
result += '</li></ol>';

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,6 @@
4343
"archy": "^1.0.0",
4444
"bluebird": "^3.5.2",
4545
"chalk": "^3.0.0",
46-
"cheerio": "0.22.0",
4746
"hexo-cli": "^3.0.0",
4847
"hexo-front-matter": "^1.0.0",
4948
"hexo-fs": "^2.0.0",
@@ -71,6 +70,7 @@
7170
"@easyops/git-exec-and-restage": "^1.0.4",
7271
"chai": "^4.1.2",
7372
"chai-as-promised": "^7.1.1",
73+
"cheerio": "0.22.0",
7474
"eslint": "^6.0.1",
7575
"eslint-config-hexo": "^4.0.0",
7676
"hexo-renderer-marked": "^2.0.0",

0 commit comments

Comments
 (0)