Class: Charming::Components::TextInput

Inherits:
Charming::Component show all
Includes:
KeyboardHandler
Defined in:
lib/charming/presentation/components/text_input.rb

Overview

TextInput is a single-line text editor component. Supports printable character insertion, cursor movement (left/right/home/end), and deletion (backspace/delete). The component exposes its ‘value` and `cursor` positions as reader methods; when an explicit `width:` is given, the rendered output is padded to that width via a UI::Style.

Constant Summary collapse

KEY_ACTIONS =

Maps editing keys (left/right/home/end/backspace/delete) to the instance methods they dispatch via KeyboardHandler. Each symbol key (e.g., :left) maps to a method (e.g., :move_left) that adjusts cursor position or text content.

{
  left: :move_left,
  right: :move_right,
  home: :move_home,
  end: :move_end,
  backspace: :delete_before_cursor,
  delete: :delete_at_cursor
}.freeze

Constants included from KeyboardHandler

KeyboardHandler::VIM_KEYMAP

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from View

#focused?, #layout_assigns

Constructor Details

#initialize(value: "", placeholder: "", width: nil, cursor: nil) ⇒ TextInput

value is the initial text. placeholder is shown when the value is empty. width optionally constrains the rendered output width; cursor defaults to the end.



29
30
31
32
33
34
35
36
# File 'lib/charming/presentation/components/text_input.rb', line 29

def initialize(value: "", placeholder: "", width: nil, cursor: nil)
  super()
  @value = value.dup
  @placeholder = placeholder
  @width = width
  @cursor = cursor || @value.length
  clamp_position
end

Instance Attribute Details

#cursorObject (readonly)

The current input string and the byte offset of the cursor within it.



25
26
27
# File 'lib/charming/presentation/components/text_input.rb', line 25

def cursor
  @cursor
end

#valueObject (readonly)

The current input string and the byte offset of the cursor within it.



25
26
27
# File 'lib/charming/presentation/components/text_input.rb', line 25

def value
  @value
end

Instance Method Details

#handle_key(event) ⇒ Object

Handles key events. Inserts printable characters, otherwise dispatches via KEY_ACTIONS. Returns :handled when the event was consumed, nil otherwise.



40
41
42
43
44
# File 'lib/charming/presentation/components/text_input.rb', line 40

def handle_key(event)
  return :handled if character_event?(event) && insert(event.char)

  super
end

#renderObject

Renders the value with a cursor marker. When width was given at construction, the output is padded to that width via the configured style.



48
49
50
51
# File 'lib/charming/presentation/components/text_input.rb', line 48

def render
  rendered = render_value
  @width ? style.width(@width).render(rendered) : rendered
end