Sha256: f3f9560b6c7490b5bda9cde2125580a7c930f60786168ef08232ba6b14527265

Contents?: true

Size: 1.75 KB

Versions: 3

Compression:

Stored size: 1.75 KB

Contents

# frozen_string_literal: true

module HoTModuLe
  class View < Bridgetown::ERBView
    attr_accessor :child_nodes
  end

  class ComponentRenderer < Bridgetown::Builder
    def build
      registered_tags = {}
      Bridgetown::Component.subclasses.each do |component|
        next unless component.respond_to?(:tag_name)

        registered_tags[component.tag_name] = component
      end

      render_html_modules(registered_tags)
    end

    def render_html_modules(registered_tags) # rubocop:todo Metrics
      inspect_html do |doc, resource| # rubocop:todo Metrics
        view_context = HoTModuLe::View.new(resource)

        registered_tags.each do |tag_name, component|
          doc.xpath("//#{tag_name}").reverse.each do |node|
            if node["hmod:ignore"]
              node.attribute("hmod:ignore").remove
              next
            end

            attrs = node.attributes.transform_values(&:value)
            attrs.reject! { |k| k.start_with?("hmod:") }

            new_attrs = {}
            attrs.each do |k, v|
              next unless k.start_with?("ruby:")

              new_key = k.delete_prefix("ruby:")
              attrs.delete(k)
              new_attrs[new_key] = resource.instance_eval(v)
            end
            attrs.merge!(new_attrs)
            attrs.transform_keys!(&:to_sym)

            view_context.child_nodes = node.children
            new_node = node.replace(
              component.new(**attrs).render_in(view_context) { node.children.to_html.html_safe }
            )
            new_node.first.attribute("hmod:ignore")&.remove
          end
        rescue StandardError => e
          Bridgetown.logger.error "Unable to render <#{tag_name}> (#{component}) in #{resource.path}"
          raise e
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
hot_module-1.0.0.alpha10 lib/hot_module/component_renderer.rb
hot_module-1.0.0.alpha9 lib/hot_module/component_renderer.rb
hot_module-1.0.0.alpha8 lib/hot_module/component_renderer.rb