Class: Thaum::TextInput

Inherits:
Object
  • Object
show all
Includes:
Sigil
Defined in:
lib/thaum/sigils/text_input.rb

Constant Summary collapse

SubmittedEvent =
Thaum::Event.define(:value)

Instance Attribute Summary collapse

Attributes included from Sigil

#handler_parent, #rect, #thaum_app

Instance Method Summary collapse

Methods included from Sigil

#emit, #focusable?, #focused?, #on_blur, #on_focus, #on_mount, #on_mouse, #on_paste, #on_tick, #on_unmount, #on_update, #request_render

Constructor Details

#initialize(value: "") ⇒ TextInput

Returns a new instance of TextInput.



11
12
13
14
# File 'lib/thaum/sigils/text_input.rb', line 11

def initialize(value: "")
  @value  = value.dup
  @cursor = @value.length
end

Instance Attribute Details

#cursorObject (readonly)

Returns the value of attribute cursor.



9
10
11
# File 'lib/thaum/sigils/text_input.rb', line 9

def cursor
  @cursor
end

#valueObject (readonly)

Returns the value of attribute value.



9
10
11
# File 'lib/thaum/sigils/text_input.rb', line 9

def value
  @value
end

Instance Method Details

#clearObject



16
17
18
19
# File 'lib/thaum/sigils/text_input.rb', line 16

def clear
  @value  = +""
  @cursor = 0
end

#on_key(event) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/thaum/sigils/text_input.rb', line 21

def on_key(event)
  key = event.key
  case key
  when String        then insert(key) unless event.ctrl? || event.alt?
  when :backspace    then backspace
  when :delete       then delete_forward
  when :left         then @cursor = [@cursor - 1, 0].max
  when :right        then @cursor = [@cursor + 1, @value.length].min
  when :home         then @cursor = 0
  when :end          then @cursor = @value.length
  when :enter        then emit SubmittedEvent.new(value: @value)
  else                    emit event
  end
end

#render(canvas:, theme:) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/thaum/sigils/text_input.rb', line 36

def render(canvas:, theme:)
  offset    = scroll_offset(canvas.width)
  visible   = @value[offset..] || ""
  cursor_x  = display_width(@value[offset...@cursor])
  canvas.fill(bg: theme.input_bg)
  canvas.text(content: visible, fg: theme.fg, bg: theme.input_bg)
  canvas.cursor(x: cursor_x, y: 0) if focused?
end