|
1 | 1 | 'use strict';
|
2 | 2 |
|
3 |
| -let cheerio; |
4 |
| -const { escapeHTML } = require('hexo-util'); |
| 3 | +const { tocObj } = require('hexo-util'); |
5 | 4 |
|
6 | 5 | 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); |
8 | 11 |
|
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 }); |
13 | 13 |
|
14 |
| - if (!headings.length) return ''; |
| 14 | + if (!data.length) return ''; |
| 15 | + |
| 16 | + const className = options.class; |
| 17 | + const listNumber = options.list_number; |
15 | 18 |
|
16 |
| - const className = options.class || 'toc'; |
17 |
| - const listNumber = Object.prototype.hasOwnProperty.call(options, 'list_number') ? options.list_number : true; |
18 | 19 | let result = `<ol class="${className}">`;
|
19 | 20 | const lastNumber = [0, 0, 0, 0, 0, 0];
|
20 | 21 | let firstLevel = 0;
|
21 | 22 | let lastLevel = 0;
|
22 | 23 |
|
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; |
33 | 27 |
|
34 | 28 | lastNumber[level - 1]++;
|
35 | 29 |
|
@@ -67,7 +61,7 @@ function tocHelper(str, options = {}) {
|
67 | 61 | result += `<span class="${className}-text">${text}</span></a>`;
|
68 | 62 |
|
69 | 63 | lastLevel = level;
|
70 |
| - }); |
| 64 | + } |
71 | 65 |
|
72 | 66 | for (let i = firstLevel - 1; i < lastLevel; i++) {
|
73 | 67 | result += '</li></ol>';
|
|
0 commit comments