app/models/coupdoeil/tag.rb



# frozen_string_literal: true

module Coupdoeil
  class Tag
    delegate :options, to: :popover_setup, prefix: :popover

    def initialize(popover:, popover_options:, attributes:)
      @popover_setup = popover
      @popover_setup.with_options(popover_options) if popover_options
      @attributes = attributes
      @popover_setup.options.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", **tag_attributes) do
          if popover_options.preload?
            view_context.tag.template(view_context.render(popover_setup), class: "popover-content") + content
          else
            content
          end
        end
      end
    end

    private

    attr_reader :popover_setup

    def popover_attributes
      attributes = { "popover-options": popover_options.to_base36 }

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

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

      attributes
    end

    def tag_attributes
      if @attributes
        @attributes.merge(popover_attributes)
      else
        popover_attributes
      end
    end
  end
end