Sha256: aafb393e3e30c000b12528a470efee3ccfb0f0836742e219cbafd34682051ead

Contents?: true

Size: 991 Bytes

Versions: 5

Compression:

Stored size: 991 Bytes

Contents

# frozen_string_literal: true

module Bs5
  module Modal
    class ControllerComponent < ViewComponent::Base
      def initialize(modal_id:)
        @modal_id = modal_id
      end

      def content
        return nil if @content.blank?

        if actionable_element?
          set_actionable_element_attributes
          actionable_element.to_html.html_safe # rubocop:disable Rails/OutputSafety
        else
          @content
        end
      end

      def set_actionable_element_attributes
        actionable_element['data-bs-toggle'] = 'modal'
        actionable_element['data-bs-target'] = "##{@modal_id}"
      end

      def actionable_element
        @actionable_element ||= begin
          if (elements = Nokogiri::HTML::DocumentFragment.parse(@content).elements).one? &&
             (element = elements.first).name.in?(%w[a button])
            element
          end
        end
      end

      def actionable_element?
        !!actionable_element
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
bs5-0.0.31 app/components/bs5/modal/controller_component.rb
bs5-0.0.30 app/components/bs5/modal/controller_component.rb
bs5-0.0.29 app/components/bs5/modal/controller_component.rb
bs5-0.0.28 app/components/bs5/modal/controller_component.rb
bs5-0.0.27 app/components/bs5/modal/controller_component.rb