Sha256: 4410bee096c2d0f8e85faca11a9922c53a07e399cc8c8324453519f0784d3806

Contents?: true

Size: 1.75 KB

Versions: 9

Compression:

Stored size: 1.75 KB

Contents

module Nexmo
  module OAS
    module Renderer
      module Filters
        class Heading < Banzai::Filter
          def call(input)
            @input = input
            @headings = []

            heading_tag_list = %w[h1 h2 h3 h4 h5 h6]
            headings = document.children.select do |child|
              heading_tag_list.include? child.name
            end

            headings.each do |heading|
              parameterized_heading = parameterized_heading_without_collision(heading)
              heading['id'] = parameterized_heading
              heading['data-id'] = SecureRandom.hex
              heading['class'] = heading[:class]
              heading['class'] += ' Vlt-title--icon'

              heading.prepend_child <<~HEREDOC
                <a href="##{parameterized_heading}" class="heading-permalink">
                  <svg class="Vlt-grey"><use xlink:href=\"/symbol/volta-icons.svg#Vlt-icon-link\" /></svg>
                </a>
              HEREDOC
            end

            @document.to_html
          end

          private

          def document
            @document ||= Nokogiri::HTML::DocumentFragment.parse(@input)
          end

          def parameterized_heading_without_collision(heading)
            parameterized_heading = nil
            index = nil

            loop do
              if index
                parameterized_heading = "#{heading.text.parameterize}-#{index}"
                index += 1
              else
                parameterized_heading = heading.text.parameterize
                index = 2
              end

              break if @headings.exclude? parameterized_heading
            end

            @headings << parameterized_heading
            parameterized_heading
          end
        end
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
nexmo-oas-renderer-0.3.7 lib/nexmo/oas/renderer/filters/heading.rb
nexmo-oas-renderer-0.3.6 lib/nexmo/oas/renderer/filters/heading.rb
nexmo-oas-renderer-0.3.5 lib/nexmo/oas/renderer/filters/heading.rb
nexmo-oas-renderer-0.3.4 lib/nexmo/oas/renderer/filters/heading.rb
nexmo-oas-renderer-0.3.3 lib/nexmo/oas/renderer/filters/heading.rb
nexmo-oas-renderer-0.3.2 lib/nexmo/oas/renderer/filters/heading.rb
nexmo-oas-renderer-0.3.1 lib/nexmo/oas/renderer/filters/heading.rb
nexmo-oas-renderer-0.3.0 lib/nexmo/oas/renderer/filters/heading.rb
nexmo-oas-renderer-0.2.2 lib/nexmo/oas/renderer/filters/heading.rb