Class: Charming::Components::MultiSelectList

Inherits:
List show all
Defined in:
lib/charming/presentation/components/multi_select_list.rb

Overview

MultiSelectList is a List variant where Space toggles per-item checkmarks and Enter submits the checked set. Renders ‘[x]` / `[ ]` prefixes.

‘handle_key` returns `[:submitted, [item, …]]` on Enter, :handled for toggles and navigation, nil otherwise. max_selections optionally caps how many items can be checked at once.

Constant Summary

Constants inherited from List

List::KEY_ACTIONS

Constants included from KeyboardHandler

KeyboardHandler::VIM_KEYMAP

Instance Attribute Summary collapse

Attributes inherited from List

#items, #selected_index

Instance Method Summary collapse

Methods inherited from List

#handle_mouse, #selected_item

Methods inherited from Charming::Component

#captures_text?

Methods inherited from View

#focused?, #layout_assigns

Constructor Details

#initialize(items:, selected_indices: [], max_selections: nil, **options) ⇒ MultiSelectList

Same options as List, plus selected_indices (initially checked items) and max_selections (cap on simultaneous checks; nil = unlimited).



17
18
19
20
21
# File 'lib/charming/presentation/components/multi_select_list.rb', line 17

def initialize(items:, selected_indices: [], max_selections: nil, **options)
  super(items: items, **options)
  @selected_indices = selected_indices.to_a.map(&:to_i).uniq.select { |index| index.between?(0, items.length - 1) }
  @max_selections = max_selections
end

Instance Attribute Details

#selected_indicesObject (readonly)

The set of selected (checked) item indices.



13
14
15
# File 'lib/charming/presentation/components/multi_select_list.rb', line 13

def selected_indices
  @selected_indices
end

Instance Method Details

#handle_key(event) ⇒ Object

Space toggles the highlighted item, Enter submits the checked items.



24
25
26
27
28
29
30
31
32
# File 'lib/charming/presentation/components/multi_select_list.rb', line 24

def handle_key(event)
  case Charming.key_of(event)
  when :space then toggle_current
  when :enter then [:submitted, selected_items]
  else
    # Bypass List#handle_key (its Enter means single-select); use its navigation.
    keyboard_navigation(event)
  end
end

#renderObject

Renders each visible item with a checkbox prefix; the highlighted row uses the selected style.



41
42
43
44
45
# File 'lib/charming/presentation/components/multi_select_list.rb', line 41

def render
  visible_items.each_with_index.map do |item, index|
    render_checkbox_item(item, viewport_start + index)
  end.join("\n")
end

#selected_itemsObject

The checked items, in list order.



35
36
37
# File 'lib/charming/presentation/components/multi_select_list.rb', line 35

def selected_items
  selected_indices.sort.map { |index| items[index] }
end