Class: Jekyll::TableOfContents::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/table_of_contents/parser.rb

Overview

Parse html contents and generate table of contents

Constant Summary collapse

NO_TOC_CLASS_NAME =
'no_toc'
PUNCTUATION_REGEXP =
/[^\p{Word}\- ]/u
DEFAULT_CONFIG =
{
  'no_toc_section_class' => 'no_toc_section',
  'min_level' => 1,
  'max_level' => 6,
  'list_class' => 'section-nav',
  'sublist_class' => '',
  'item_class' => 'toc-entry',
  'item_prefix' => 'toc-'
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(html, options = {}) ⇒ Parser

Returns a new instance of Parser.



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/table_of_contents/parser.rb', line 20

def initialize(html, options = {})
  @doc = Nokogiri::HTML::DocumentFragment.parse(html)
  options = generate_option_hash(options)
  @toc_levels = options['min_level']..options['max_level']
  @no_toc_section_class = options['no_toc_section_class']
  @list_class = options['list_class']
  @sublist_class = options['sublist_class']
  @item_class = options['item_class']
  @item_prefix = options['item_prefix']
  @entries = parse_content
end

Instance Method Details

#build_tocObject



36
37
38
# File 'lib/table_of_contents/parser.rb', line 36

def build_toc
  %(<ul class="#{@list_class}">\n#{build_toc_list(@entries)}</ul>)
end

#inject_anchors_into_htmlObject



40
41
42
43
44
45
46
47
48
# File 'lib/table_of_contents/parser.rb', line 40

def inject_anchors_into_html
  @entries.each do |entry|
    entry[:content_node].add_previous_sibling(
      %(<a id="#{entry[:id]}#{entry[:uniq]}" class="anchor" href="##{entry[:id]}#{entry[:uniq]}" aria-hidden="true"><span class="octicon octicon-link"></span></a>)
    )
  end

  @doc.inner_html
end

#tocObject



32
33
34
# File 'lib/table_of_contents/parser.rb', line 32

def toc
  build_toc + inject_anchors_into_html
end