app/models/coupdoeil/tag.rb



# frozen_string_literal: true

module Coupdoeil
  class Tag
    def initialize(hovercard:, hovercard_options:, attributes:)
      @hovercard_setup = hovercard
      @attributes = attributes
      hovercard_options = Hovercard::OptionsSet.new(hovercard_options)
      @hovercard_options_set = hovercard_setup.default_options.merge(hovercard_options)
      @hovercard_options_set.validate!
    end

    def render_in(view_context, &block)
      ActiveSupport::Notifications.instrument("render_tag.coupdoeil") do
        content = view_context.capture(&block) if block_given?
        view_context.content_tag("coup-doeil", **@attributes.merge(hovercard_attributes)) do
          if hovercard_options_set.preload?
            view_context.tag.template(view_context.render(hovercard_setup), class: "hovercard-content") + content
          else
            content
          end
        end
      end
    end

    private

    attr_reader :hovercard_options_set, :hovercard_setup

    def hovercard_attributes
      attributes = { hc: hovercard_options_set.to_base36 }

      unless hovercard_options_set.preload?
        params = Params.serialize(hovercard_setup.params).sole.presence&.to_json
        attributes.merge!("hc-type" => hovercard_setup.identifier, "hc-params" => params)
      end

      if Rails.env.local?
        attributes.merge!(hovercard_options_set.to_h.transform_keys { "hovercard-#{_1}" })
      end

      attributes
    end
  end
end