Class: AiCli::Helpers::ScriptActionMenu::Menu

Inherits:
Object
  • Object
show all
Defined in:
lib/aicli/helpers/script_action_menu.rb

Instance Method Summary collapse

Constructor Details

#initialize(question, choices) ⇒ Menu

Returns a new instance of Menu.



44
45
46
47
48
49
50
51
# File 'lib/aicli/helpers/script_action_menu.rb', line 44

def initialize(question, choices)
  @question = question
  @choices = choices
  @active = 0
  @done = false
  @result = nil
  @prompt = Theme.prompt(interrupt: :exit)
end

Instance Method Details

#askObject



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/aicli/helpers/script_action_menu.rb', line 53

def ask
  @prompt.print(@prompt.hide)
  @prompt.subscribe(self) do
    until @done
      view = render_view
      lines = line_count(view)
      @prompt.print(view)
      @prompt.read_keypress
      @prompt.print(@prompt.clear_lines(lines)) unless @done
    end
  end
  @result
ensure
  @prompt.print(@prompt.show)
end

#choose_activeObject



98
99
100
101
# File 'lib/aicli/helpers/script_action_menu.rb', line 98

def choose_active
  @result = @choices[@active][:value]
  @done = true
end

#keydownObject Also known as: keytab



80
81
82
# File 'lib/aicli/helpers/script_action_menu.rb', line 80

def keydown(*)
  @active = (@active + 1) % @choices.size
end

#keyenterObject Also known as: keyreturn, keyspace



69
70
71
# File 'lib/aicli/helpers/script_action_menu.rb', line 69

def keyenter(*)
  choose_active
end

#keypress(event) ⇒ Object



86
87
88
89
90
91
92
93
94
95
96
# File 'lib/aicli/helpers/script_action_menu.rb', line 86

def keypress(event)
  value = event.value.to_s
  return if value.empty? || value.start_with?("\e")

  char = value.downcase
  idx = @choices.index { |choice| choice[:key] == char }
  return unless idx

  @active = idx
  choose_active
end

#keyupObject



76
77
78
# File 'lib/aicli/helpers/script_action_menu.rb', line 76

def keyup(*)
  @active = (@active - 1) % @choices.size
end

#line_count(view) ⇒ Object



120
121
122
123
124
# File 'lib/aicli/helpers/script_action_menu.rb', line 120

def line_count(view)
  view.split($INPUT_RECORD_SEPARATOR, -1).sum do |line|
    @prompt.count_screen_lines(line)
  end
end

#render_viewObject



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/aicli/helpers/script_action_menu.rb', line 103

def render_view
  output = ["#{@question}\n"]
  @choices.each_with_index do |choice, index|
    line = if index == @active
             "#{MARKER} #{choice[:label]}"
           else
             "  #{choice[:label]}"
           end
    output << if index == @active
                "#{Theme.accent(line)}\n"
              else
                "#{line}\n"
              end
  end
  output.join
end