Module: NavigationHelper

Defined in:
lib/nexmo_developer/app/helpers/navigation_helper.rb

Instance Method Summary collapse

Instance Method Details



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
47
48
49
# File 'lib/nexmo_developer/app/helpers/navigation_helper.rb', line 12

def navigation_from_content(content:, title: nil)
  content = "<h0 class='injected'>#{title}</h0>\n" + content if title
  document = build_document(content)

  nodes = ['<ul class="Vlt-sidemenu Vlt-sidemenu--flat navigation js-navigation"><h4>On this page: </h4>']
  last_node = nil

  document.css('.reveal').remove

  document.css('h0,h2,h3,h4,h5,h6').each do |heading|
    # If it's a header within tabbed content (including Code Snippets) we don't want to treat
    # the header as a navigation item in the sidebar
    next unless heading.ancestors('.Vlt-tabs').empty?

    # Same with callouts
    next unless heading.ancestors('.Vlt-callout').empty?

    if last_node.nil? || heading.name == last_node.name
      # Do nothing (cleaner than adding wrapping further conditions)
    elsif heading.name >= last_node.name # e.g. h2 -> h3
      nodes << '<ul>'
    else # e.g. h4 -> h2
      (HEADING_TAG_DEPTHS[last_node.name] - HEADING_TAG_DEPTHS[heading.name]).times do
        nodes << '</li></ul>'
      end
    end

    nodes << <<~HEREDOC
      <li>
        <a class="Vlt-sidemenu__link" href="##{heading.attributes['id']}" data-scrollspy-id="#{heading['data-id']}">
          #{heading.text}
        </a>
    HEREDOC
    last_node = heading
  end
  nodes << '</li></ul>'
  nodes.join("\n").html_safe
end