Module: Pecorb

Extended by:
Pecorb
Included in:
Pecorb
Defined in:
lib/pecorb.rb,
lib/pecorb/version.rb

Constant Summary collapse

KILL_LINE_CHAR =
"\x1B[K"
CURSOR_UP_CHAR =
"\x1B[A"
CSI =
"\e["
SELECTED_COLOR =
"#{CSI}\e[36m"
RESET_COLOR =
"#{CSI}\e[0m"
VERSION =
"1.0.2"

Instance Method Summary collapse

Instance Method Details

#prompt(items, prompt = "Select an item: ") ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/pecorb.rb', line 20

def prompt(items, prompt="Select an item: ")
  @displayed_items = @items = items
  @prompt = prompt

  $stderr.puts prompt
  print_items(items)
  move_cursor_from_end_to_start

  while c = read_char
    case c
    when /[\r]/
      break
    when /[]/
      @input = ""
      break
    when "" # Backspace key
      next if @input.empty? || @cursor <= 0
      @input.slice!(@cursor-1)
      replace_input(@input)
      replace_items { filter_items(@items, @input) }
      $stderr.print "\b"
      @cursor -= 1
    when "#{CSI}D" # Left arrow key
      next unless @cursor > 0
      $stderr.print c
      @cursor -= 1
    when "#{CSI}C" # Right arrow key
      next unless @cursor < @input.length
      $stderr.print c
      @cursor += 1
    when "#{CSI}A" # Up arrow key
      @selected -= 1 if @selected > 0
      replace_items { filter_items(@items, @input) }
    when "#{CSI}B" # Down arrow key
      @selected += 1 if @selected < @displayed_items.size - 1
      replace_items { filter_items(@items, @input) }
    else
      @input.insert(@cursor, c)
      replace_input(@input)
      replace_items { filter_items(@items, @input) }
      $stderr.print c
      @cursor += 1
    end
  end

  move_cursor_from_start_to_end
  $stdout.puts @displayed_items[@selected]
  @displayed_items[@selected]
end