Class: UI::SheetTriggerComponent

Inherits:
ViewComponent::Base
  • Object
show all
Defined in:
app/view_components/ui/sheet_trigger_component.rb

Overview

Sheet trigger component (ViewComponent) Opens the sheet on click

Examples:

As button (default)

<%= render UI::TriggerComponent.new { "Open Sheet" } %>

As child (composition pattern)

<%= render UI::TriggerComponent.new(as_child: true) do %>
  <%= render UI::ButtonComponent.new { "Open" } %>
<% end %>

Instance Method Summary collapse

Constructor Details

#initialize(as_child: false, **attributes) ⇒ SheetTriggerComponent

Returns a new instance of SheetTriggerComponent.

Parameters:

  • as_child (Boolean) (defaults to: false)

    merge attributes into child element

  • attributes (Hash)

    additional HTML attributes



16
17
18
19
# File 'app/view_components/ui/sheet_trigger_component.rb', line 16

def initialize(as_child: false, **attributes)
  @as_child = as_child
  @attributes = attributes
end

Instance Method Details

#callObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'app/view_components/ui/sheet_trigger_component.rb', line 21

def call
  trigger_attrs = {
    data: {action: "click->ui--dialog#open"}
  }.deep_merge(@attributes)

  if @as_child
    # asChild mode: merge attributes into child element
    rendered = content.to_s
    doc = Nokogiri::HTML::DocumentFragment.parse(rendered)
    first_element = doc.children.find { |node| node.element? }

    if first_element
      # Merge data attributes (convert Rails naming to HTML)
      trigger_attrs.fetch(:data, {}).each do |key, value|
        html_key = key.to_s.gsub("__", "--").tr("_", "-")
        first_element["data-#{html_key}"] = value
      end

      # Merge CSS classes with TailwindMerge
      if trigger_attrs[:class]
        existing_classes = first_element["class"] || ""
        merged_classes = TailwindMerge::Merger.new.merge([existing_classes, trigger_attrs[:class]].join(" "))
        first_element["class"] = merged_classes
      end

      # Merge other attributes (except data and class)
      trigger_attrs.except(:data, :class).each do |key, value|
        first_element[key.to_s] = value
      end

      doc.to_html.html_safe
    else
      content
    end
  else
    # Default: render as button
     :button, content, **trigger_attrs
  end
end