Class: RubyRich::SlashInput

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_rich/slash_input.rb

Constant Summary collapse

DEFAULT_MENU_LIMIT =
8

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(prompt: "> ", items: [], width: nil, menu_limit: DEFAULT_MENU_LIMIT, on_select: nil, on_submit: nil) ⇒ SlashInput

Returns a new instance of SlashInput.



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/ruby_rich/slash_input.rb', line 9

def initialize(prompt: "> ", items: [], width: nil, menu_limit: DEFAULT_MENU_LIMIT, on_select: nil, on_submit: nil)
  @prompt = prompt
  @items = normalize_items(items)
  @width = width
  @menu_limit = menu_limit
  @on_select = on_select
  @on_submit = on_submit
  @value = ""
  @selected_index = 0
  @menu_open = false
end

Instance Attribute Details

#selected_indexObject (readonly)

Returns the value of attribute selected_index.



5
6
7
# File 'lib/ruby_rich/slash_input.rb', line 5

def selected_index
  @selected_index
end

#valueObject (readonly)

Returns the value of attribute value.



5
6
7
# File 'lib/ruby_rich/slash_input.rb', line 5

def value
  @value
end

Instance Method Details

#attach(layout, priority: 100) ⇒ Object



21
22
23
24
25
26
27
28
29
# File 'lib/ruby_rich/slash_input.rb', line 21

def attach(layout, priority: 100)
  [:string, :backspace, :up, :down, :enter, :escape].each do |event_name|
    layout.key(event_name, priority) do |event_data, live|
      handle_key(event_data, live)
      false
    end
  end
  self
end

#handle_key(event_data, live = nil) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/ruby_rich/slash_input.rb', line 31

def handle_key(event_data, live = nil)
  case event_data[:name]
  when :string
    append(event_data[:value].to_s)
  when :backspace
    backspace
  when :up
    move_selection(-1)
  when :down
    move_selection(1)
  when :enter
    enter(live)
  when :escape
    close_menu
  end
end

Returns:

  • (Boolean)


64
65
66
# File 'lib/ruby_rich/slash_input.rb', line 64

def menu_open?
  @menu_open
end

#renderObject



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/ruby_rich/slash_input.rb', line 48

def render
  lines = [input_line]
  return fit_lines(lines) unless menu_open?

  matches = filtered_items.first(@menu_limit)
  if matches.empty?
    lines << "#{AnsiCode.color(:yellow)}  No matches#{AnsiCode.reset}"
  else
    matches.each_with_index do |item, index|
      lines << render_item(item, index == @selected_index)
    end
  end

  fit_lines(lines)
end