Module: Clack::Core::KeyReader

Defined in:
lib/clack/core/key_reader.rb

Overview

Reads single keystrokes from the terminal in raw mode. Handles escape sequences for arrow keys and other special keys.

The Escape detection window is tunable via the CLACK_ESCAPE_TIMEOUT env var (see Environment.escape_timeout) for high-latency links.

Class Method Summary collapse

Class Method Details

.read(input = nil) ⇒ String?

Read a single keystroke in raw mode. When input is an IO backed by a console, uses raw mode. When input is a StringIO or test double, reads directly.

Parameters:

  • input (IO, nil) (defaults to: nil)

    input stream (defaults to IO.console)

Returns:

  • (String, nil)

    the key code, or nil on EOF



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/clack/core/key_reader.rb', line 20

def read(input = nil)
  io = input || IO.console
  raise IOError, "No console available (not a TTY?)" unless io

  # StringIO / test doubles don't support raw mode
  return read_from(io) unless io.respond_to?(:raw)

  io.raw { |raw_io| read_from(raw_io) }
rescue Errno::EIO, Errno::EBADF, IOError
  # Terminal disconnected or closed - treat as cancel
  "\u0003" # Ctrl+C
end