From a8efcdf3259d7b8cbf71110e15be9f14dac1404c Mon Sep 17 00:00:00 2001 From: Sukka Date: Fri, 20 Dec 2019 15:01:27 +0800 Subject: [PATCH] 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 --- lib/plugins/helper/toc.js | 36 +++++++++++++++--------------------- package.json | 2 +- 2 files changed, 16 insertions(+), 22 deletions(-) diff --git a/lib/plugins/helper/toc.js b/lib/plugins/helper/toc.js index 51d0ef33e0..4eb5093e8f 100644 --- a/lib/plugins/helper/toc.js +++ b/lib/plugins/helper/toc.js @@ -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 = `
    `; 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]++; @@ -67,7 +61,7 @@ function tocHelper(str, options = {}) { result += `${text}`; lastLevel = level; - }); + } for (let i = firstLevel - 1; i < lastLevel; i++) { result += '
'; diff --git a/package.json b/package.json index 1c088b017c..6cc13bd407 100644 --- a/package.json +++ b/package.json @@ -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", @@ -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",