1
1
'use strict' ;
2
2
3
- let cheerio ;
4
3
const { escapeHTML } = require ( 'hexo-util' ) ;
4
+ const { DomHandler, DomUtils, Parser } = require ( 'htmlparser2' ) ;
5
+
6
+ const parseHtml = ( html ) => {
7
+ const handler = new DomHandler ( null , { } ) ;
8
+ new Parser ( handler , { } ) . end ( html ) ;
9
+ return handler . dom ;
10
+ } ;
5
11
6
12
function tocHelper ( str , options = { } ) {
7
- if ( ! cheerio ) cheerio = require ( 'cheerio' ) ;
13
+ const dom = parseHtml ( str ) ;
8
14
9
- const $ = cheerio . load ( str ) ;
10
15
const headingsMaxDepth = Object . prototype . hasOwnProperty . call ( options , 'max_depth' ) ? options . max_depth : 6 ;
11
16
const headingsSelector = [ 'h1' , 'h2' , 'h3' , 'h4' , 'h5' , 'h6' ] . slice ( 0 , headingsMaxDepth ) . join ( ',' ) ;
12
- const headings = $ ( headingsSelector ) ;
17
+
18
+ const headings = DomUtils . find ( el => headingsSelector . includes ( el . tagName ) , dom , true ) ;
13
19
14
20
if ( ! headings . length ) return '' ;
15
21
@@ -21,15 +27,15 @@ function tocHelper(str, options = {}) {
21
27
let lastLevel = 0 ;
22
28
23
29
function getId ( ele ) {
24
- const id = $ ( ele ) . attr ( 'id' ) ;
25
- const $ parent = $ ( ele ) . parent ( ) ;
26
- return id || ( $ parent. length < 1 ? null : getId ( $ parent) ) ;
30
+ const { id } = ele . attribs ;
31
+ const { parent } = ele ;
32
+ return id || ( parent . length < 1 ? null : getId ( parent ) ) ;
27
33
}
28
34
29
- headings . each ( function ( ) {
30
- const level = + this . name [ 1 ] ;
31
- const id = getId ( this ) ;
32
- const text = escapeHTML ( $ ( this ) . text ( ) ) ;
35
+ for ( const el of headings ) {
36
+ const level = + el . name [ 1 ] ;
37
+ const id = getId ( el ) ;
38
+ const text = escapeHTML ( DomUtils . getText ( el ) ) ;
33
39
34
40
lastNumber [ level - 1 ] ++ ;
35
41
@@ -67,7 +73,7 @@ function tocHelper(str, options = {}) {
67
73
result += `<span class="${ className } -text">${ text } </span></a>` ;
68
74
69
75
lastLevel = level ;
70
- } ) ;
76
+ }
71
77
72
78
for ( let i = firstLevel - 1 ; i < lastLevel ; i ++ ) {
73
79
result += '</li></ol>' ;
0 commit comments