Class: Clack::Prompts::Multiselect

Inherits:
Core::Prompt show all
Includes:
Core::OptionsHelper, Core::SelectionManager
Defined in:
lib/clack/prompts/multiselect.rb

Overview

Multiple-selection prompt from a list of options.

Navigate with arrow keys or j/k. Toggle selection with Space. Supports shortcuts: ā€˜a’ to toggle all, ā€˜i’ to invert selection.

Options format is the same as Select.

Examples:

Basic usage

features = Clack.multiselect(
  message: "Select features",
  options: %w[api auth admin]
)

With options and validation

features = Clack.multiselect(
  message: "Select features",
  options: [
    { value: "api", label: "API Mode" },
    { value: "auth", label: "Authentication" }
  ],
  initial_values: ["api"],
  required: true,
  max_items: 5
)

Constant Summary

Constants included from Core::SelectionManager

Core::SelectionManager::REQUIRED_ERROR

Constants inherited from Core::Prompt

Core::Prompt::MIN_TERMINAL_WIDTH

Instance Attribute Summary

Attributes inherited from Core::Prompt

#error_message, #state, #value, #warning_message

Instance Method Summary collapse

Methods included from Core::SelectionManager

#selected_labels, #toggle_value, #update_selection_value, #validate_selection

Methods included from Core::OptionsHelper

#find_initial_cursor, #find_next_enabled, #first_enabled_index, #move_cursor, #move_selection, #navigable_items, normalize_option, #normalize_options, #update_scroll, #visible_options

Methods inherited from Core::Prompt

flush_resize, register, #request_redraw, #run, setup_signal_handler, unregister

Constructor Details

#initialize(message:, options:, initial_values: [], required: true, max_items: nil, cursor_at: nil, **opts) ⇒ Multiselect

Returns a new instance of Multiselect.

Parameters:

  • message (String)

    the prompt message

  • options (Array<Hash, String>)

    list of options

  • initial_values (Array) (defaults to: [])

    values to pre-select

  • required (Boolean) (defaults to: true)

    require at least one selection (default: true)

  • max_items (Integer, nil) (defaults to: nil)

    max visible items (enables scrolling)

  • cursor_at (Object, nil) (defaults to: nil)

    value to position cursor at initially

  • opts (Hash)

    additional options passed to Core::Prompt



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/clack/prompts/multiselect.rb', line 41

def initialize(message:, options:, initial_values: [], required: true, max_items: nil, cursor_at: nil, **opts)
  if opts.key?(:initial_value)
    raise ArgumentError, "Multiselect uses initial_values: (plural), not initial_value:"
  end
  super(message:, **opts)
  @options = normalize_options(options)
  valid_values = Set.new(@options.map { |o| o.value })
  @selected = Set.new(initial_values) & valid_values
  @required = required
  @max_items = max_items
  @scroll_offset = 0
  @option_index = find_initial_cursor(cursor_at)
  update_selection_value
end