Skip to content

Commit

Permalink
refactor(toc_helper): utilize hexo-util (hexojs#3850)
Browse files Browse the repository at this point in the history
* refactor(toc_helper): relpace cheerio with htmlparser2

* test(toc_helper): use classic for loop

* refactor(toc_helper): utilize tocObj
  • Loading branch information
SukkaW authored and Thomas Parisot committed Jan 17, 2020
1 parent 34b231a commit a8efcdf
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 22 deletions.
36 changes: 15 additions & 21 deletions lib/plugins/helper/toc.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,29 @@
'use strict';

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

function tocHelper(str, options = {}) {
if (!cheerio) cheerio = require('cheerio');
options = Object.assign({
max_depth: 6,
class: 'toc',
list_number: true
}, options);

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

if (!headings.length) return '';
if (!data.length) return '';

const className = options.class;
const listNumber = options.list_number;

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

function getId(ele) {
const id = $(ele).attr('id');
const $parent = $(ele).parent();
return id || ($parent.length < 1 ? null : getId($parent));
}

headings.each(function() {
const level = +this.name[1];
const id = getId(this);
const text = escapeHTML($(this).text());
for (let i = 0, len = data.length; i < len; i++) {
const el = data[i];
const { level, id, text } = el;

lastNumber[level - 1]++;

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

lastLevel = level;
});
}

for (let i = firstLevel - 1; i < lastLevel; i++) {
result += '</li></ol>';
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@
"archy": "^1.0.0",
"bluebird": "^3.5.2",
"chalk": "^3.0.0",
"cheerio": "0.22.0",
"hexo-cli": "^3.0.0",
"hexo-front-matter": "^1.0.0",
"hexo-fs": "^2.0.0",
Expand Down Expand Up @@ -71,6 +70,7 @@
"@easyops/git-exec-and-restage": "^1.0.4",
"chai": "^4.1.2",
"chai-as-promised": "^7.1.1",
"cheerio": "0.22.0",
"eslint": "^6.0.1",
"eslint-config-hexo": "^4.0.0",
"hexo-renderer-marked": "^2.0.0",
Expand Down

0 comments on commit a8efcdf

Please sign in to comment.