Sha256: 13426d807ca89c9ae4888fc05f9f6987621d1ca72854ec800940b1f619e655f8

Contents?: true

Size: 1.73 KB

Versions: 19

Compression:

Stored size: 1.73 KB

Contents

# frozen_string_literal: true

require "forwardable"

module Tocer
  # Builds table of contents for a Markdown document.
  class Builder
    extend Forwardable

    CODE_BLOCK_PUNCTUATION = "```"

    def_delegators :comment_block, :start_index, :finish_index, :comments, :prependable?

    def initialize comment_block: Elements::CommentBlock.new, transformer: Transformers::Finder.new
      @comment_block = comment_block
      @transformer = transformer
      @url_count = Hash.new 0
      @code_block = false
    end

    def unbuildable?(lines) = comment_block.empty?(lines) && headers(lines).empty?

    def call lines, label: Configuration::Loader.call.label
      return "" if headers(lines).empty?

      url_count.clear
      assemble(lines, label).join
    end

    private

    attr_reader :comment_block, :transformer, :url_count
    attr_accessor :code_block

    def assemble lines, label
      [
        "#{comment_block.start_tag}\n\n",
        "#{label}\n\n",
        links(lines).join("\n"),
        "\n\n#{comment_block.finish_tag}\n"
      ]
    end

    def links(lines) = headers(lines).map { |markdown| transform markdown }

    def headers lines
      lines.select do |line|
        toggle_code_block line
        line.start_with?(Parsers::Header::PUNCTUATION) && !code_block
      end
    end

    def toggle_code_block line
      return unless line.start_with? CODE_BLOCK_PUNCTUATION

      self.code_block = !code_block
    end

    def transform markdown
      transformer.call(markdown).then do |instance|
        url = instance.url
        link = instance.call url_suffix: url_suffix(url)
        url_count[url] += 1
        link
      end
    end

    def url_suffix(url) = url_count[url].then { |count| count.zero? ? "" : count }
  end
end

Version data entries

19 entries across 19 versions & 1 rubygems

Version Path
tocer-15.2.0 lib/tocer/builder.rb
tocer-15.1.2 lib/tocer/builder.rb
tocer-15.1.1 lib/tocer/builder.rb
tocer-15.1.0 lib/tocer/builder.rb
tocer-15.0.0 lib/tocer/builder.rb
tocer-14.5.0 lib/tocer/builder.rb
tocer-14.4.0 lib/tocer/builder.rb
tocer-14.3.0 lib/tocer/builder.rb
tocer-14.2.0 lib/tocer/builder.rb
tocer-14.1.0 lib/tocer/builder.rb
tocer-14.0.1 lib/tocer/builder.rb
tocer-14.0.0 lib/tocer/builder.rb
tocer-13.3.1 lib/tocer/builder.rb
tocer-13.3.0 lib/tocer/builder.rb
tocer-13.2.0 lib/tocer/builder.rb
tocer-13.1.0 lib/tocer/builder.rb
tocer-13.0.2 lib/tocer/builder.rb
tocer-13.0.1 lib/tocer/builder.rb
tocer-13.0.0 lib/tocer/builder.rb