Sha256: 88336d1b13a7735e2edf5fb397d9a49f02f23dc683a43d416aa8104f8e27ef37

Contents?: true

Size: 1.21 KB

Versions: 12

Compression:

Stored size: 1.21 KB

Contents

module GovukTechDocs
  module TableOfContents
    class HeadingTreeRenderer
      DEFAULT_MAX_LEVEL = Float::INFINITY
      DEFAULT_INDENTATION = "".freeze
      INDENTATION_INCREMENT = "  ".freeze

      def initialize(heading_tree, max_level: nil)
        @heading_tree = heading_tree
        @max_level = max_level || DEFAULT_MAX_LEVEL
      end

      def html
        render_tree(@heading_tree, level: 0)
      end

    private

      def render_tree(tree, indentation: DEFAULT_INDENTATION, level: nil)
        output = ""

        if tree.heading
          output += indentation + %{<a href="#{tree.heading.href}"><span>#{tree.heading.title}</span></a>\n}
        end

        if tree.children.any? && level < @max_level
          output += indentation + "<ul>\n"

          tree.children.each do |child|
            output += indentation + INDENTATION_INCREMENT + "<li>\n"
            output += render_tree(
              child,
              indentation: indentation + INDENTATION_INCREMENT * 2,
              level: level + 1,
            )
            output += indentation + INDENTATION_INCREMENT + "</li>\n"
          end

          output += indentation + "</ul>\n"
        end

        output
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
govuk_tech_docs-2.3.0 lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb
govuk_tech_docs-2.2.2 lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb
govuk_tech_docs-2.2.1 lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb
govuk_tech_docs-2.2.0 lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb
govuk_tech_docs-2.1.1 lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb
govuk_tech_docs-2.1.0 lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb
govuk_tech_docs-2.0.13 lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb
govuk_tech_docs-2.0.12 lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb
govuk_tech_docs-2.0.11 lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb
govuk_tech_docs-2.0.10 lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb
govuk_tech_docs-2.0.9 lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb
govuk_tech_docs-2.0.8 lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb