Class: TerminalNotes::TextField
- Inherits:
-
Object
- Object
- TerminalNotes::TextField
- Defined in:
- lib/terminal-notes/text_field.rb
Constant Summary collapse
- DEFAULT_WIDTH =
10
- BREAK_CHARS =
" -_+=".split('')
Instance Attribute Summary collapse
-
#text ⇒ Object
readonly
Returns the value of attribute text.
Instance Method Summary collapse
- #draw ⇒ Object
-
#initialize(screen, position: Cursor.new, width: DEFAULT_WIDTH) ⇒ TextField
constructor
A new instance of TextField.
- #notify_text_changed ⇒ Object
- #on_key(key) ⇒ Object
- #on_text_changed(&block) ⇒ Object
Constructor Details
#initialize(screen, position: Cursor.new, width: DEFAULT_WIDTH) ⇒ TextField
Returns a new instance of TextField.
8 9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/terminal-notes/text_field.rb', line 8 def initialize(screen, position: Cursor.new, width: DEFAULT_WIDTH) @screen = screen @start = position.dup @end = @start.dup.moveBy(width, 0) @width = width @cursor = @start.dup @clear_text = " " * @width @text = "" @on_text_changed_delegates = [] end |
Instance Attribute Details
#text ⇒ Object (readonly)
Returns the value of attribute text.
3 4 5 |
# File 'lib/terminal-notes/text_field.rb', line 3 def text @text end |
Instance Method Details
#draw ⇒ Object
82 83 84 85 86 87 |
# File 'lib/terminal-notes/text_field.rb', line 82 def draw @screen.move_cursor(@start.to_hash) @screen.draw_string(@text.ljust(@width)) @screen.move_cursor(@cursor.to_hash) end |
#notify_text_changed ⇒ Object
25 26 27 28 29 |
# File 'lib/terminal-notes/text_field.rb', line 25 def notify_text_changed @on_text_changed_delegates.each do |delegate| delegate.call(@text) end end |
#on_key(key) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/terminal-notes/text_field.rb', line 31 def on_key(key) old_text = @text case key when :BACKSPACE @text = @text[0...-1] @cursor.moveBy(-1) unless @text.size == (@width - 1) when :UP, :DOWN when :LEFT @cursor.moveBy(-1) when :RIGHT @cursor.moveBy(1) when :CTRL_K @text = "" when :CTRL_W last = @text.size - 2 while last >= 0 break if BREAK_CHARS.include? @text[last] last -= 1 end @text = @text[0...(last+1)] when :CTRL_E @cursor.moveTo(x: @end.x) when :CTRL_A @cursor.moveTo(x: @start.x) else if !key.nil? && !key.is_a?(Symbol) && @text.size < @width @text += key @cursor.moveBy(1) end end # Make sure we don't move cursor too far left @cursor.moveTo(x: @start.x) if @cursor.x < @start.x # Make sure we don't move cursor too far right max_x = @start.x + @text.size max_x -= 1 if @text.size == @width @cursor.moveTo(x: max_x) if @cursor.x > max_x draw notify_text_changed if old_text != @text end |
#on_text_changed(&block) ⇒ Object
21 22 23 |
# File 'lib/terminal-notes/text_field.rb', line 21 def on_text_changed &block @on_text_changed_delegates << block end |