Class: UI::Switch

Inherits:
Phlex::HTML
  • Object
show all
Includes:
SwitchBehavior
Defined in:
app/components/ui/switch.rb

Overview

Switch - Phlex implementation

A toggle control that allows the user to switch between checked and unchecked states. Based on Radix UI Switch primitive.

Examples:

Basic usage

render UI::Switch.new(checked: false, id: "airplane-mode")

With label

div(class: "flex items-center space-x-2") do
  render UI::Switch.new(id: "airplane-mode")
  label(for: "airplane-mode") { "Airplane Mode" }
end

With form

render UI::Switch.new(
  checked: true,
  name: "notifications",
  id: "notifications"
)

Instance Method Summary collapse

Methods included from SwitchBehavior

#switch_classes, #switch_html_attributes, #switch_thumb_classes

Constructor Details

#initialize(checked: false, disabled: false, classes: "", name: nil, id: nil, value: "1", **attributes) ⇒ Switch

Returns a new instance of Switch.

Parameters:

  • checked (Boolean) (defaults to: false)

    Whether the switch is checked

  • disabled (Boolean) (defaults to: false)

    Whether the switch is disabled

  • classes (String) (defaults to: "")

    Additional CSS classes

  • name (String) (defaults to: nil)

    Name for form submission (creates hidden input)

  • id (String) (defaults to: nil)

    ID attribute

  • value (String) (defaults to: "1")

    Value for form submission when checked

  • attributes (Hash)

    Additional HTML attributes



33
34
35
36
37
38
39
40
41
# File 'app/components/ui/switch.rb', line 33

def initialize(checked: false, disabled: false, classes: "", name: nil, id: nil, value: "1", **attributes)
  @checked = checked
  @disabled = disabled
  @classes = classes
  @name = name
  @id = id
  @value = value
  @attributes = attributes
end

Instance Method Details

#view_template(&block) ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'app/components/ui/switch.rb', line 43

def view_template(&block)
  attrs = switch_html_attributes.deep_merge(@attributes)
  attrs[:id] = @id if @id.present?

  button(**attrs) do
    render_thumb
    render_hidden_input if @name.present?
  end
end