Class: PhlexKit::Switch

Inherits:
BaseComponent show all
Defined in:
app/components/phlex_kit/switch/switch.rb

Overview

On/off toggle rendered as a checkbox styled as a track+thumb. Ported from ruby_ui's RubyUI::Switch — pure CSS (:has(:checked)), no Stimulus. Emits an optional hidden field so an unchecked box still posts a value (Rails idiom).

Constant Summary collapse

SIZES =
{ md: nil, sm: "sm" }.freeze

Instance Method Summary collapse

Methods inherited from BaseComponent

#on

Constructor Details

#initialize(include_hidden: true, checked_value: "1", unchecked_value: "0", size: :md, wrapper: {}, **attrs) ⇒ Switch

Returns a new instance of Switch.



8
9
10
11
12
13
14
15
# File 'app/components/phlex_kit/switch/switch.rb', line 8

def initialize(include_hidden: true, checked_value: "1", unchecked_value: "0", size: :md, wrapper: {}, **attrs)
  @include_hidden = include_hidden
  @checked_value = checked_value
  @unchecked_value = unchecked_value
  @size = size.to_sym
  @wrapper = wrapper
  @attrs = attrs
end

Instance Method Details

#view_templateObject



17
18
19
20
21
22
23
24
25
# File 'app/components/phlex_kit/switch/switch.rb', line 17

def view_template
  label(**mix({ class: [ "pk-switch", fetch_option(SIZES, @size, :size) ].compact.join(" ") }, @wrapper)) do
    input(type: "hidden", name: @attrs[:name], value: @unchecked_value) if @include_hidden && @attrs[:name]
    # role="switch" belongs on the focusable control: native checkedness then
    # maps to aria-checked for AT, and the label stays a plain label.
    input(**mix({ class: "pk-switch-input", role: "switch" }, @attrs).merge(type: "checkbox", value: @checked_value))
    span(class: "pk-switch-thumb")
  end
end