@@ -21,6 +21,17 @@ def toc_generate(html)
2121
2222 anchor_prefix = config [ "anchorPrefix" ] || 'tocAnchor-'
2323
24+ # better for traditional page seo, commonlly use h1 as title
25+ toc_top_tag = config [ "tocTopTag" ] || 'h1'
26+ toc_top_tag = toc_top_tag . gsub ( /h/ , '' ) . to_i
27+ if toc_top_tag > 5
28+ toc_top_tag = 5
29+ end
30+ toc_sec_tag = toc_top_tag + 1
31+ toc_top_tag = "h#{ toc_top_tag } "
32+ toc_sec_tag = "h#{ toc_sec_tag } "
33+
34+
2435 # Text labels
2536 contents_label = config [ "contentsLabel" ] || 'Contents'
2637 hide_label = config [ "hideLabel" ] || 'hide'
@@ -36,37 +47,38 @@ def toc_generate(html)
3647 doc = Nokogiri ::HTML ( html )
3748
3849 # Find H1 tag and all its H2 siblings until next H1
39- doc . css ( 'h1' ) . each do |h1 |
50+ doc . css ( toc_top_tag ) . each do |tag |
4051 # TODO This XPATH expression can greatly improved
41- ct = h1 . xpath ( ' count(following-sibling::h1)' )
42- h2s = h1 . xpath ( "following-sibling::h2 [count(following-sibling::h1 )=#{ ct } ]" )
52+ ct = tag . xpath ( " count(following-sibling::#{ toc_top_tag } )" )
53+ sects = tag . xpath ( "following-sibling::#{ toc_sec_tag } [count(following-sibling::#{ toc_top_tag } )=#{ ct } ]" )
4354
4455 level_html = '' ;
4556 inner_section = 0 ;
4657
47- h2s . map . each do |h2 |
58+ sects . map . each do |sect |
4859 inner_section += 1 ;
4960 anchor_id = anchor_prefix + toc_level . to_s + '-' + toc_section . to_s + '-' + inner_section . to_s
50- h2 [ 'id' ] = "#{ anchor_id } "
61+ sect [ 'id' ] = "#{ anchor_id } "
5162
5263 level_html += create_level_html ( anchor_id ,
5364 toc_level + 1 ,
5465 toc_section + inner_section ,
5566 item_number . to_s + '.' + inner_section . to_s ,
56- h2 . text ,
67+ sect . text ,
5768 '' )
5869 end
5970 if level_html . length > 0
6071 level_html = '<ul>' + level_html + '</ul>' ;
6172 end
73+
6274 anchor_id = anchor_prefix + toc_level . to_s + '-' + toc_section . to_s ;
63- h1 [ 'id' ] = "#{ anchor_id } "
75+ tag [ 'id' ] = "#{ anchor_id } "
6476
6577 toc_html += create_level_html ( anchor_id ,
6678 toc_level ,
6779 toc_section ,
6880 item_number ,
69- h1 . text ,
81+ tag . text ,
7082 level_html ) ;
7183
7284 toc_section += 1 + inner_section ;
@@ -92,7 +104,7 @@ def toc_generate(html)
92104 . gsub ( '%2' , toc_html ) ;
93105 doc . css ( 'body' ) . children . before ( toc_table )
94106 end
95- doc . css ( 'body' ) . children . to_html ( )
107+ doc . css ( 'body' ) . children . to_xhtml ( indent : 3 , indent_text : " " )
96108 else
97109 return html
98110 end
@@ -114,4 +126,4 @@ def create_level_html(anchor_id, toc_level, toc_section, tocNumber, tocText, toc
114126 end
115127end
116128
117- Liquid ::Template . register_filter ( Jekyll ::TOCGenerator )
129+ Liquid ::Template . register_filter ( Jekyll ::TOCGenerator )
0 commit comments