Sha256: 518a703539ce96730087218571fd6a8d434d17f9a411a1e5f9d949c4aa3e03b1

Contents?: true

Size: 1.24 KB

Versions: 6

Compression:

Stored size: 1.24 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" unless level.zero?

          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" unless level.zero?
        end

        output
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
govuk_tech_docs-4.1.1 lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb
govuk_tech_docs-4.1.0 lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb
govuk_tech_docs-4.0.0 lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb
govuk_tech_docs-3.5.0 lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb
govuk_tech_docs-3.4.5 lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb
govuk_tech_docs-3.4.0 lib/govuk_tech_docs/table_of_contents/heading_tree_renderer.rb