Class: NitroKit::Accordion

Inherits:
Component
  • Object
show all
Defined in:
app/components/nitro_kit/accordion.rb

Defined Under Namespace

Classes: Item

Constant Summary collapse

MODES =
%i[multiple single].freeze

Constants inherited from Component

Component::ADDITIVE_DATA_ATTRIBUTES, Component::COMPONENT_OWNED_DATA_ATTRIBUTES, Component::FORBIDDEN_ATTRIBUTES, Component::RESERVED_DATA_ATTRIBUTES

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id:, mode: :multiple, html: {}, aria: {}, data: {}, desperately_need_a_class: nil) ⇒ Accordion

Returns a new instance of Accordion.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'app/components/nitro_kit/accordion.rb', line 8

def initialize(
  id:,
  mode: :multiple,
  html: {},
  aria: {},
  data: {},
  desperately_need_a_class: nil
)
  @identifier = component_id(id)
  @mode = validate_choice!(:mode, mode, MODES)
  @items = []

  super(
    component: :accordion,
    attributes: {
      id: @identifier,
      data: { mode: @mode }
    },
    html:,
    aria:,
    data:,
    desperately_need_a_class:
  )
end

Instance Attribute Details

#identifierObject (readonly)

Returns the value of attribute identifier.



33
34
35
# File 'app/components/nitro_kit/accordion.rb', line 33

def identifier
  @identifier
end

#modeObject (readonly)

Returns the value of attribute mode.



33
34
35
# File 'app/components/nitro_kit/accordion.rb', line 33

def mode
  @mode
end

Instance Method Details

#item(key, title:, expanded: false, &content) ⇒ Object

Raises:

  • (ArgumentError)


43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'app/components/nitro_kit/accordion.rb', line 43

def item(key, title:, expanded: false, &content)
  ensure_collecting!

  key = normalize_identity(key, name: "accordion item key")
  title = validate_title!(title)
  expanded = validate_boolean!(:expanded, expanded)
  raise ArgumentError, "Accordion item #{key.inspect} requires content" unless content
  raise ArgumentError, "Duplicate accordion item key #{key.inspect}" if @items.any? { |item| item.key == key }

  if mode == :single && expanded && @items.any?(&:expanded)
    raise ArgumentError, "Single accordion mode accepts only one expanded item"
  end

  @items << Item.new(key:, title:, expanded:, content:)
  nil
end

#view_template(&block) ⇒ Object



35
36
37
38
39
40
41
# File 'app/components/nitro_kit/accordion.rb', line 35

def view_template(&block)
  collect_items(&block)

  div(**root_attributes) do
    @items.each { |item| render_item(item) }
  end
end