Class: TuiTui::Prompt

Inherits:
Modal
  • Object
show all
Defined in:
lib/tui_tui/prompt.rb

Overview

Single-line text input modal with terminal-column-aware cursor placement.

Constant Summary collapse

MIN_INNER =
24

Constants inherited from Modal

Modal::PAD

Instance Method Summary collapse

Constructor Details

#initialize(label, value: "", theme: Theme::DEFAULT) ⇒ Prompt

Returns a new instance of Prompt.



13
14
15
16
17
18
# File 'lib/tui_tui/prompt.rb', line 13

def initialize(label, value: "", theme: Theme::DEFAULT)
  @label = DisplayText.new(label)
  @graphemes = value.grapheme_clusters
  @pos = @graphemes.length
  @theme = theme
end

Instance Method Details

#draw(canvas, size) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/tui_tui/prompt.rb', line 51

def draw(canvas, size)
  inner = [MIN_INNER, @label.width + 1 + DisplayText.new(value).width].max
  rect, col = panel(canvas, inner: inner, body_rows: 1)

  canvas.text(rect.row + 1, col, @label, theme.title)
  @text_row = rect.row + 1
  @text_col = col + @label.width + 1
  canvas.text(@text_row, @text_col, value, theme.text)
  draw_cursor(canvas, @text_row, @text_col)
  canvas
end

#handle(key) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/tui_tui/prompt.rb', line 22

def handle(key)
  case key
  when "\r"
    [:ok, value]
  when :escape, KeyCode::CTRL_C
    :cancel
  when KeyCode::BACKSPACE, :backspace
    edit { delete_back }
  when :delete
    edit { delete_forward }
  when :left
    edit { @pos = [@pos - 1, 0].max }
  when :right
    edit { @pos = [@pos + 1, @graphemes.length].min }
  when :home
    edit { @pos = 0 }
  when :end
    edit { @pos = @graphemes.length }
  when String
    edit { insert(key) if printable?(key) }
  end
end

#handle_mouse(event) ⇒ Object



45
46
47
48
49
# File 'lib/tui_tui/prompt.rb', line 45

def handle_mouse(event)
  return nil unless event.action == :press && @text_row == event.row

  edit { @pos = index_at(event.col - @text_col) }
end

#valueObject



20
# File 'lib/tui_tui/prompt.rb', line 20

def value = @graphemes.join