Module: UI::ToggleBehavior

Included in:
Toggle, ToggleComponent
Defined in:
app/behaviors/ui/toggle_behavior.rb

Overview

UI::ToggleBehavior

Instance Method Summary collapse

Instance Method Details

#render_toggle(&content_block) ⇒ String

Renders the toggle HTML This method can be used by both ERB partials and ViewComponents

Parameters:

  • content_block (Proc)

    Block that returns the toggle content

Returns:

  • (String)

    HTML string for the toggle



31
32
33
34
# File 'app/behaviors/ui/toggle_behavior.rb', line 31

def render_toggle(&content_block)
  all_attributes = toggle_html_attributes.deep_merge(@attributes)
  (:button, **all_attributes, &content_block)
end

#toggle_classesObject

Returns combined CSS classes for the toggle



58
59
60
61
62
63
64
65
66
# File 'app/behaviors/ui/toggle_behavior.rb', line 58

def toggle_classes
  classes_value = respond_to?(:classes, true) ? classes : @classes
  TailwindMerge::Merger.new.merge([
    toggle_base_classes,
    toggle_variant_classes,
    toggle_size_classes,
    classes_value
  ].compact.join(" "))
end

#toggle_html_attributesObject

Returns HTML attributes for the toggle element



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'app/behaviors/ui/toggle_behavior.rb', line 37

def toggle_html_attributes
  attrs = {
    class: toggle_classes,
    type: @type || "button",
    disabled: @disabled ? true : nil,
    "aria-pressed": @pressed ? "true" : "false",
    data: {
      controller: "ui--toggle",
      action: "click->ui--toggle#toggle",
      "ui--toggle-pressed-value": @pressed ? "true" : "false"
    }
  }

  # Add state attribute for CSS targeting
  attrs[:"data-state"] = @pressed ? "on" : "off"
  attrs[:"data-disabled"] = "" if @disabled

  attrs.compact
end