Class: Shadcn::SwitchComponent

Inherits:
BaseComponent
  • Object
show all
Defined in:
app/components/shadcn/switch_component.rb

Overview

Switch component for toggle inputs Uses a custom button element with hidden input for form submission Requires Stimulus controller for interactivity

Examples:

Basic switch

<%= render Shadcn::SwitchComponent.new(name: "notifications") %>

With integrated label

<%= render Shadcn::SwitchComponent.new(name: "dark_mode") { "Enable dark mode" } %>

Checked by default

<%= render Shadcn::SwitchComponent.new(name: "active", checked: true) %>

Constant Summary collapse

BASE_CLASSES =
[
  "peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full",
  "border-2 border-transparent shadow-sm transition-colors",
  "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",
  "disabled:cursor-not-allowed disabled:opacity-50",
  "data-[state=checked]:bg-primary data-[state=unchecked]:bg-input"
].join(" ")
THUMB_CLASSES =
[
  "pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0",
  "transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0"
].join(" ")

Instance Attribute Summary

Attributes inherited from BaseComponent

#class_name, #data, #html_options

Instance Method Summary collapse

Methods inherited from BaseComponent

#content

Methods included from Rails::Helpers::ClassNameHelper

#cn

Constructor Details

#initialize(name: nil, id: nil, value: "1", checked: false, disabled: false, required: false, **options) ⇒ SwitchComponent

Returns a new instance of SwitchComponent.

Parameters:

  • name (String, nil) (defaults to: nil)

    Input name attribute

  • id (String, nil) (defaults to: nil)

    Input id attribute

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

    Value when checked

  • checked (Boolean) (defaults to: false)

    Whether switch is on

  • disabled (Boolean) (defaults to: false)

    Whether switch is disabled

  • required (Boolean) (defaults to: false)

    Whether switch is required



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'app/components/shadcn/switch_component.rb', line 37

def initialize(
  name: nil,
  id: nil,
  value: "1",
  checked: false,
  disabled: false,
  required: false,
  **options
)
  super(**options)
  @name = name
  @id = id || (name ? "switch-#{name}" : nil)
  @value = value
  @checked = checked
  @disabled = disabled
  @required = required
end