Module: Clack::Core::SelectionManager

Included in:
Prompts::AutocompleteMultiselect, Prompts::GroupMultiselect, Prompts::Multiselect
Defined in:
lib/clack/core/selection_manager.rb

Overview

Shared selection management for multi-select prompts. Handles toggle, toggle-all, required validation, and value tracking.

Including classes must define:

  • @selected [Set] the set of selected values

  • @required [Boolean] whether at least one selection is required

Constant Summary collapse

REQUIRED_ERROR =
"Please select at least one option. Press %s to select, %s to submit"

Instance Method Summary collapse

Instance Method Details

#resolve_initial_selection(initial_values, valid_values) ⇒ Set

Resolve requested pre-selections against the selectable option values.

Values that don’t match any current option are dropped and reported on stderr, since they’re almost always a typo in initial_values rather than an intentional no-op.

Parameters:

  • initial_values (Array)

    the requested pre-selections

  • valid_values (Set)

    the set of selectable option values

Returns:

  • (Set)

    the subset of initial_values that map to real options



23
24
25
26
27
28
29
30
# File 'lib/clack/core/selection_manager.rb', line 23

def resolve_initial_selection(initial_values, valid_values)
  requested = Set.new(initial_values)
  unknown = requested - valid_values
  unless unknown.empty?
    warn "[clack] ignoring unknown initial_values: #{unknown.to_a.inspect}"
  end
  requested & valid_values
end

#selected_labels(all_options) ⇒ String

Build the final display string from selected options.

Parameters:

  • all_options (Array<Hash>)

    the full options list to match against

Returns:

  • (String)

    comma-separated labels



62
63
64
# File 'lib/clack/core/selection_manager.rb', line 62

def selected_labels(all_options)
  all_options.select { |o| @selected.include?(o.value) }.map { |o| o.label }.join(", ")
end

#toggle_value(value) ⇒ Object

Toggle a value in the selection set.

Parameters:

  • value (Object)

    the value to toggle



34
35
36
37
38
39
40
# File 'lib/clack/core/selection_manager.rb', line 34

def toggle_value(value)
  if @selected.include?(value)
    @selected.delete(value)
  else
    @selected.add(value)
  end
end

#update_selection_valueObject

Update @value from the current selection.



55
56
57
# File 'lib/clack/core/selection_manager.rb', line 55

def update_selection_value
  @value = @selected.to_a
end

#validate_selectionBoolean

Validate that selection meets requirements before submit. Sets error state if required and empty.

Returns:

  • (Boolean)

    true if valid to proceed with submit



45
46
47
48
49
50
51
52
# File 'lib/clack/core/selection_manager.rb', line 45

def validate_selection
  if @required && @selected.empty?
    @error_message = format(REQUIRED_ERROR, Colors.cyan("space"), Colors.cyan("enter"))
    @state = :error
    return false
  end
  true
end