class Mato::Renderers::HtmlTocRenderer
Constants
- ANCHOR_SELECTOR
- H_SELECTOR
Public Instance Methods
call(doc)
click to toggle source
@param [Nokogiri::HTML4::DocumentFragment] doc @return [String]
# File lib/mato/renderers/html_toc_renderer.rb, line 14 def call(doc) s = +'' stack = [0] doc.css(H_SELECTOR).each do |hx| h_level = level(hx) if h_level > stack.last stack.push(h_level) s << %{<ul>\n} elsif h_level < stack.last while h_level < stack.last # keep the user-level stack top element (i.e. [0, #]) here if stack.size <= 2 s << %{</li>\n} stack.pop stack.push(h_level) break else s << %{</li></ul>\n} stack.pop end end else s << %{</li>\n} end node = hx.dup anchor = node.css(ANCHOR_SELECTOR).first s << %{<li>} if anchor s << %{<a href="##{anchor['id']}">} anchor.unlink end node.css('a').each do |a| a.replace(a.children) end s << node.children.to_html(save_with: 0) if anchor s << %{</a>} end end # roll up all the stack elements while stack.last != 0 stack.pop s << %{</li></ul>\n} end s end
Private Instance Methods
level(node)
click to toggle source
@param [Nokogiri::XML::Node] node @return [Integer] 1 to 6
# File lib/mato/renderers/html_toc_renderer.rb, line 75 def level(node) /\d+/.match(node.name)[0].to_i end