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

PUNCTUATION_REGEXP =
/[^\p{Word}\- ]/u
DEFAULT_CONFIG =
{
  'min_level' => 1,
  'max_level' => 6
}.freeze

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Parser.



14
15
16
17
18
19
# File 'lib/table_of_contents/parser.rb', line 14

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

Instance Method Details

#build_tocObject



21
22
23
# File 'lib/table_of_contents/parser.rb', line 21

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

#inject_anchors_into_htmlObject



25
26
27
28
29
30
31
# File 'lib/table_of_contents/parser.rb', line 25

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



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

def toc
  build_toc + inject_anchors_into_html
end