Class: TTY::Prompt::Carousel

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/tty/prompt/carousel.rb

Constant Summary collapse

DEFAULT_KEY_MAP =
{
  left: :left,
  right: :right,
  end_keys: [:return]
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options, start_at: 0, key_map: DEFAULT_KEY_MAP, input: $stdin, output: $stdout, env: ENV, interrupt: :error, track_history: true, option_style: nil, margin: 0, padding: 2) ⇒ Carousel

rubocop:disable Metrics/MethodLength



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/tty/prompt/carousel.rb', line 17

def initialize(options, start_at: 0, key_map: DEFAULT_KEY_MAP,
               input: $stdin, output: $stdout, env: ENV, interrupt: :error,
               track_history: true, option_style: nil, margin: 0, padding: 2)
  @reader = TTY::Reader.new(
    input: input,
    output: output,
    interrupt: interrupt,
    track_history: track_history,
    env: env
  )
  @key_map = DEFAULT_KEY_MAP.merge(key_map)
  @output = output
  @options = options
  @max_option_length = @options.map(&:length).max
  @padding = padding
  @content_size = @padding + @max_option_length + @padding
  @current_index = start_at
  @cursor = TTY::Cursor
  @pastel = Pastel.new
  @option_style = option_style
  @margin = margin
end

Instance Attribute Details

#option_styleObject

Returns the value of attribute option_style.



8
9
10
# File 'lib/tty/prompt/carousel.rb', line 8

def option_style
  @option_style
end

Instance Method Details

#contentObject



50
51
52
53
54
55
# File 'lib/tty/prompt/carousel.rb', line 50

def content
  padding = content_size - selected_option.length
  padding_left = padding / 2
  padding_right = padding - padding_left
  (' ' * padding_left) + style_option + (' ' * padding_right)
end

#move_leftObject



57
58
59
60
# File 'lib/tty/prompt/carousel.rb', line 57

def move_left
  @current_index -= 1
  @current_index = @options.length - 1 if current_index.negative?
end

#move_rightObject



62
63
64
65
# File 'lib/tty/prompt/carousel.rb', line 62

def move_right
  @current_index += 1
  @current_index = 0 if current_index >= options.length
end

#redrawObject



67
68
69
70
# File 'lib/tty/prompt/carousel.rb', line 67

def redraw
  output.print(clear_lines(1))
  render
end

#renderObject



46
47
48
# File 'lib/tty/prompt/carousel.rb', line 46

def render
  output.print("#{' ' * margin}#{left_arrow}#{content}#{right_arrow}")
end

#selectObject

rubocop:enable Metrics/MethodLength



41
42
43
44
# File 'lib/tty/prompt/carousel.rb', line 41

def select
  render
  capture_keys
end

#selected_optionObject



72
73
74
# File 'lib/tty/prompt/carousel.rb', line 72

def selected_option
  options[current_index]
end