Class: Daimon::Markdown::Plugin::TableOfContents

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

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 Daimon::Markdown::Plugin::Base

Instance Method Details

#callObject



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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/daimon/markdown/plugin/toc.rb', line 7

def call
  toc_html = ""
  items = []

  headers = Hash.new(0)
  previous_level = 1
  doc.css("h1, h2, h3, h4, h5, h6").each do |header_node|
    level = header_node.name.tr("h", "").to_i
    text = header_node.text
    id = text.downcase
    id.gsub!(/ /, "-")
    id.gsub!(/\s/, "")

    if headers[id] > 0
      unique_id = "#{id}-#{headers[id]}"
    else
      unique_id = id
    end
    headers[id] += 1
    header_content = header_node.children.first
    # TODO: Arrange indent level
    if header_content
      diff = level - previous_level
      case
      when diff > 0
        items.concat(["<ul>"] * diff)
      when diff < 0
        items.concat(["</ul>"] * diff.abs)
      end
      items << list_item(link_to(unique_id, text))
      header_node["id"] = unique_id
    end
    previous_level = level
  end
  toc_class = context[:toc_class] || "section-nav"
  unless items.empty?
    toc_html = %Q(<ul class="#{toc_class}">\n#{items.join("\n")}\n</ul>)
  end
  node.parent.replace(toc_html)
end