class TTY::Prompt::Keypress

Public Class Methods

new(prompt, **options) click to toggle source

Create keypress question

@param [Prompt] prompt @param [Hash] options

@api public

Calls superclass method
# File lib/tty/prompt/keypress.rb, line 14
def initialize(prompt, **options)
  super
  @echo    = options.fetch(:echo) { false }
  @keys    = options.fetch(:keys) { UndefinedSetting }
  @timeout = options.fetch(:timeout) { UndefinedSetting }
  @interval = options.fetch(:interval) {
    (@timeout != UndefinedSetting && @timeout < 1) ? @timeout : 1
  }
  @decimals = (@interval.to_s.split(".")[1] || []).size
  @countdown = @timeout
  time = timeout? ? Float(@timeout) : nil
  @timer = Timer.new(time, Float(@interval))

  @prompt.subscribe(self)
end

Public Instance Methods

any_key?() click to toggle source

Check if any specific keys are set

# File lib/tty/prompt/keypress.rb, line 37
def any_key?
  @keys == UndefinedSetting
end
countdown(value = (not_set = true)) click to toggle source
# File lib/tty/prompt/keypress.rb, line 30
def countdown(value = (not_set = true))
  return @countdown if not_set

  @countdown = value
end
interval_handler(time) click to toggle source
# File lib/tty/prompt/keypress.rb, line 64
def interval_handler(time)
  return if @done

  question = render_question
  line_size = question.size
  total_lines = @prompt.count_screen_lines(line_size)
  @prompt.print(refresh(question.lines.count, total_lines))
  countdown(time)
  @prompt.print(render_question)
end
keypress(event) click to toggle source
# File lib/tty/prompt/keypress.rb, line 46
def keypress(event)
  if any_key?
    @done = true
  elsif @keys.is_a?(Array) && @keys.include?(event.key.name)
    @done = true
  else
    @done = false
  end
end
process_input(question) click to toggle source
# File lib/tty/prompt/keypress.rb, line 75
def process_input(question)
  @prompt.print(render_question)

  @timer.on_tick do |time|
    interval_handler(time)
  end

  @timer.while_remaining do |remaining|
    break if @done

    @input = @prompt.read_keypress(nonblock: true)
  end
  countdown(0) unless @done

  @evaluator.(@input)
end
refresh(lines, lines_to_clear) click to toggle source
# File lib/tty/prompt/keypress.rb, line 92
def refresh(lines, lines_to_clear)
  @prompt.clear_lines(lines)
end
render_question() click to toggle source
Calls superclass method
# File lib/tty/prompt/keypress.rb, line 56
def render_question
  header = super
  if timeout?
    header.gsub!(/:countdown/, format("%.#{@decimals}f", countdown))
  end
  header
end
timeout?() click to toggle source

Check if timeout is set

# File lib/tty/prompt/keypress.rb, line 42
def timeout?
  @timeout != UndefinedSetting
end