Class: DaimonMarkdown::Plugin::TableOfContents

Inherits:
Base
  • Object
show all
Defined in:
lib/daimon_markdown/plugin/toc.rb

Defined Under Namespace

Classes: EmptyHeader, Header, ListItem, UnorderedList

Instance Attribute Summary

Attributes inherited from Base

#context, #doc, #node, #result

Instance Method Summary collapse

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from DaimonMarkdown::Plugin::Base

Instance Method Details

#call(limit = nil) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/daimon_markdown/plugin/toc.rb', line 6

def call(limit = nil)
  toc_html = ""
  toc_class = context[:toc_class] || "section-nav"

  ul_list = Hash.new {|h, k| h[k] = UnorderedList.new }
  ul_list[1] = UnorderedList.new(html_class: toc_class)
  previous_level = 1
  doc.css("h1, h2, h3, h4, h5, h6").each do |header_node|
    header = Header.new(header_node)
    next if limit && limit < header.level
    next unless header.content?
    header.unique_id = generate_unique_id(header.text)
    if header.level - previous_level > 0
      (previous_level + 1).upto(header.level) do |level|
        ul_list[level - 1] << ul_list[level]
      end
    end
    ul_list[header.level] << ListItem.new(header: header)
    previous_level = header.level
  end

  unless ul_list[1].items.empty?
    toc_header = context[:toc_header] || ""
    toc_html = "#{toc_header}#{ul_list[1].to_html}"
  end
  node.parent.replace(toc_html)
end