Module: Nexmo::OAS::Renderer::Helpers::Navigation

Included in:
Presenters::Navigation
Defined in:
lib/nexmo/oas/renderer/helpers/navigation.rb

Constant Summary collapse

HEADING_TAG_DEPTHS =
{
  'h0' => 0,
  'h1' => 1,
  'h2' => 2,
  'h3' => 3,
  'h4' => 4,
  'h5' => 5,
  'h6' => 6,
}.freeze

Instance Method Summary collapse

Instance Method Details



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
50
51
52
53
54
55
# File 'lib/nexmo/oas/renderer/helpers/navigation.rb', line 18

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--rounded Vlt-sidemenu--flat navigation js-navigation">']
  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 Vlt-grey-darker" 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