Class: Charming::Components::Form::Multiselect

Inherits:
Field show all
Defined in:
lib/charming/presentation/components/form/multiselect.rb

Overview

Multiselect is a multiple-choice Form field backed by a MultiSelectList. Space toggles the highlighted option's checkbox, navigation keys move the highlight, and the checked set (in option order) becomes the field's value. Enter is left to the Form so it advances/submits like every other field.

Instance Attribute Summary

Attributes inherited from Field

#help, #label, #name, #state

Instance Method Summary collapse

Methods inherited from Field

#focusable?, #render, #validate, #value

Methods inherited from Charming::Component

#captures_text?

Methods inherited from View

#focused?, #layout_assigns, #render

Constructor Details

#initialize(name, options:, selected_indices: [], max_selections: nil, option_label: :to_s.to_proc, **field_options) ⇒ Multiselect

options is the array of selectable values. selected_indices pre-checks options. max_selections caps how many can be checked (nil = unlimited). option_label extracts the display string (default: to_s). All other options are forwarded to Field.



15
16
17
18
19
20
21
# File 'lib/charming/presentation/components/form/multiselect.rb', line 15

def initialize(name, options:, selected_indices: [], max_selections: nil, option_label: :to_s.to_proc, **field_options)
  super(name, **field_options)
  @options = options
  @initial_indices = selected_indices
  @max_selections = max_selections
  @option_label = option_label
end

Instance Method Details

#bind(state) ⇒ Object

Binds the field, then ensures the persisted checked set is applied.



24
25
26
27
# File 'lib/charming/presentation/components/form/multiselect.rb', line 24

def bind(state)
  super
  ensure_selection
end

#handle_key(event) ⇒ Object

Forwards key events to the underlying MultiSelectList, syncing the checked set and highlight cursor back into the field state. Returns :handled when consumed; Enter (the list's submit) is left unconsumed for the Form.



32
33
34
35
36
37
38
39
40
# File 'lib/charming/presentation/components/form/multiselect.rb', line 32

def handle_key(event)
  widget = list
  result = widget.handle_key(event)
  return nil if result.is_a?(Array)
  return nil unless result == :handled

  save_selection(widget)
  :handled
end