Class: Charming::Presentation::Components::List

Inherits:
Charming::Presentation::Component show all
Includes:
KeyboardHandler
Defined in:
lib/charming/presentation/components/list.rb

Constant Summary collapse

KEY_ACTIONS =

Maps navigation key symbols to instance methods consumed by the KeyboardHandler mixin: :up moves selection up, :down moves down, :home jumps to first item, :end jumps to last. See Viewport#KEY_ACTIONS and Table#KEY_ACTIONS for identical pattern.

{
  up: :move_up,
  down: :move_down,
  home: :move_home,
  end: :move_end
}.freeze

Constants included from KeyboardHandler

KeyboardHandler::VIM_KEYMAP

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from View

#focused?, #layout_assigns

Constructor Details

#initialize(items:, selected_index: 0, height: nil, label: nil, theme: nil, keymap: :vim) ⇒ List

Returns a new instance of List.



21
22
23
24
25
26
27
28
29
# File 'lib/charming/presentation/components/list.rb', line 21

def initialize(items:, selected_index: 0, height: nil, label: nil, theme: nil, keymap: :vim)
  super(theme: theme)
  @items = items
  @selected_index = selected_index
  @height = height
  @label = label || :to_s.to_proc
  @keymap = keymap
  clamp_position
end

Instance Attribute Details

#itemsObject (readonly)

Returns the value of attribute items.



19
20
21
# File 'lib/charming/presentation/components/list.rb', line 19

def items
  @items
end

#selected_indexObject (readonly)

Returns the value of attribute selected_index.



19
20
21
# File 'lib/charming/presentation/components/list.rb', line 19

def selected_index
  @selected_index
end

Instance Method Details

#handle_key(event) ⇒ Object



31
32
33
34
35
# File 'lib/charming/presentation/components/list.rb', line 31

def handle_key(event)
  return [:selected, selected_item] if Charming.key_of(event) == :enter && selected_item

  super
end

#handle_mouse(event) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/charming/presentation/components/list.rb', line 37

def handle_mouse(event)
  return nil unless @height
  return nil unless event.respond_to?(:click?) && event.click?

  clicked = event.y
  return nil if clicked.negative? || clicked >= visible_items.length

  @selected_index = viewport_start + clicked
  clamp_position
  :handled
end

#renderObject



53
54
55
56
57
# File 'lib/charming/presentation/components/list.rb', line 53

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

#selected_itemObject



49
50
51
# File 'lib/charming/presentation/components/list.rb', line 49

def selected_item
  items[selected_index]
end