class Formalist::RichText::Rendering::HTMLCompiler

Constants

EMBEDDED_FORM_TYPE
LIST_ITEM_TYPES

Attributes

embedded_form_renderer[R]
html_renderer[R]

Public Class Methods

new(html_renderer:, embedded_form_renderer:) click to toggle source
# File lib/formalist/rich_text/rendering/html_compiler.rb, line 11
def initialize(html_renderer:, embedded_form_renderer:)
  @html_renderer = html_renderer
  @embedded_form_renderer = embedded_form_renderer
end

Public Instance Methods

call(ast) click to toggle source
# File lib/formalist/rich_text/rendering/html_compiler.rb, line 16
def call(ast)
  html_renderer.nodes(wrap_lists(ast)) do |node|
    visit(node)
  end
end

Private Instance Methods

convert_to_wrapper_node(type, children) click to toggle source
# File lib/formalist/rich_text/rendering/html_compiler.rb, line 90
def convert_to_wrapper_node(type, children)
  ["wrapper", [type, children]]
end
list_item?(type) click to toggle source
# File lib/formalist/rich_text/rendering/html_compiler.rb, line 94
def list_item?(type)
  LIST_ITEM_TYPES.include?(type)
end
visit(node) click to toggle source
# File lib/formalist/rich_text/rendering/html_compiler.rb, line 24
def visit(node)
  type, content = node

  send(:"visit_#{type}", content)
end
visit_block(data) click to toggle source
# File lib/formalist/rich_text/rendering/html_compiler.rb, line 30
def visit_block(data)
  type, key, children = data

  html_renderer.block(type, key, wrap_lists(children)) do |child|
    visit(child)
  end
end
visit_entity(data) click to toggle source
# File lib/formalist/rich_text/rendering/html_compiler.rb, line 52
def visit_entity(data)
  type, key, _mutability, data, children = data

  # FIXME
  # Temporary fix to handle data that comes through with keys as
  # strings instead of symbols
  data = data.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}

  if type == EMBEDDED_FORM_TYPE
    embedded_form_renderer.(data)
  else
    html_renderer.entity(type, key, data, wrap_lists(children)) do |child|
      visit(child)
    end
  end
end
visit_inline(data) click to toggle source
# File lib/formalist/rich_text/rendering/html_compiler.rb, line 46
def visit_inline(data)
  styles, text = data

  html_renderer.inline(styles, text)
end
visit_wrapper(data) click to toggle source
# File lib/formalist/rich_text/rendering/html_compiler.rb, line 38
def visit_wrapper(data)
  type, children = data

  html_renderer.wrapper(type, children) do |child|
    visit(child)
  end
end
wrap_lists(nodes) click to toggle source
# File lib/formalist/rich_text/rendering/html_compiler.rb, line 69
def wrap_lists(nodes)
  chunked = nodes.chunk do |node|
    type, content = node

    if type == "block"
      content[0] # return the block's own type
    else
      type
    end
  end

  chunked.inject([]) { |output, (type, chunk)|
    if list_item?(type)
      output << convert_to_wrapper_node(type, chunk)
    else
      # Flatten again by appending chunk onto array
      output + chunk
    end
  }
end