Sha256: f82866d0074d96fc7b7c74d2fbcd297e273c568b2a70d6d77bd3f303a2c014e6

Contents?: true

Size: 1.77 KB

Versions: 4

Compression:

Stored size: 1.77 KB

Contents

module DraftjsHtml
  # This class manages the depth and nesting of the myriad HTML tags generated by DraftjsHtml::ToHtml.
  # It is intended to be a private implementation detail.
  class HtmlDepth # :nodoc:
    BLOCK_TYPE_TO_HTML_WRAPPER = {
      'code-block' => 'pre',
      'ordered-list-item' => 'ol',
      'unordered-list-item' => 'ul',
    }.freeze

    attr_reader :body

    def initialize(body)
      @current_depth = 0
      @body = body
      @previous_parents = [body.parent]
    end

    def apply(block)
      new_wrapper_tag = BLOCK_TYPE_TO_HTML_WRAPPER[block.type]
      if body.parent.name != new_wrapper_tag || block.depth != @current_depth
        if @current_depth < block.depth
          push_depth(body, new_wrapper_tag)
        elsif @current_depth > block.depth
          pop_depth(body, times: @current_depth - block.depth)
          pop_nesting(body) unless new_wrapper_tag
        elsif new_wrapper_tag
          push_nesting(body, new_wrapper_tag)
        elsif @previous_parents.size > 1
          pop_nesting(body)
        end
        @current_depth = block.depth
      end
    end

    private

    def push_depth(builder, tagname)
      @previous_parents << builder.parent
      builder.parent = builder.parent.last_element_child
      push_nesting(builder, tagname)
    end

    def push_nesting(builder, tagname)
      node = create_child(builder, tagname)
      @previous_parents << builder.parent
      builder.parent = node
    end

    def pop_depth(builder, times:)
      times.times do
        pop_nesting(builder)
        pop_nesting(builder)
      end
    end

    def pop_nesting(builder)
      builder.parent = @previous_parents.pop
    end

    def create_child(builder, tagname)
      builder.parent.add_child(builder.doc.create_element(tagname))
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
draftjs_html-0.12.0 lib/draftjs_html/html_depth.rb
draftjs_html-0.11.0 lib/draftjs_html/html_depth.rb
draftjs_html-0.10.0 lib/draftjs_html/html_depth.rb
draftjs_html-0.9.0 lib/draftjs_html/html_depth.rb