Class: Potty::LineEditor

Inherits:
Object
  • Object
show all
Defined in:
lib/potty/line_editor.rb

Overview

The single-line text-editing model shared by the TextInput widget and the list InputItem — a string plus a caret, with insert / delete / navigation. Pure logic, no rendering or curses: widgets own how it’s drawn and when to fire change events (the mutators return whether the text changed).

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text = '', max_length: nil) ⇒ LineEditor

Returns a new instance of LineEditor.



12
13
14
15
16
# File 'lib/potty/line_editor.rb', line 12

def initialize(text = '', max_length: nil)
  @text = text.to_s.dup
  @max_length = max_length
  @cursor = @text.length
end

Instance Attribute Details

#cursorObject (readonly)

Returns the value of attribute cursor.



9
10
11
# File 'lib/potty/line_editor.rb', line 9

def cursor
  @cursor
end

#max_lengthObject

Returns the value of attribute max_length.



10
11
12
# File 'lib/potty/line_editor.rb', line 10

def max_length
  @max_length
end

#textObject

Returns the value of attribute text.



9
10
11
# File 'lib/potty/line_editor.rb', line 9

def text
  @text
end

Instance Method Details

#backspaceObject



32
33
34
35
36
37
38
# File 'lib/potty/line_editor.rb', line 32

def backspace
  return false if @cursor.zero?

  @text.slice!(@cursor - 1)
  @cursor -= 1
  true
end

#delete_forwardObject



40
41
42
43
44
45
# File 'lib/potty/line_editor.rb', line 40

def delete_forward
  return false if @cursor >= @text.length

  @text.slice!(@cursor)
  true
end

#homeObject



50
# File 'lib/potty/line_editor.rb', line 50

def home  = (@cursor = 0)

#insert(str) ⇒ Object

Mutators return true when the text changed (so callers know to notify).



24
25
26
27
28
29
30
# File 'lib/potty/line_editor.rb', line 24

def insert(str)
  return false if @max_length && @text.length >= @max_length

  @text.insert(@cursor, str)
  @cursor += str.length
  true
end

#leftObject

Caret navigation (no text change).



48
# File 'lib/potty/line_editor.rb', line 48

def left  = (@cursor = [@cursor - 1, 0].max)

#rightObject



49
# File 'lib/potty/line_editor.rb', line 49

def right = (@cursor = [@cursor + 1, @text.length].min)

#to_endObject



51
# File 'lib/potty/line_editor.rb', line 51

def to_end = (@cursor = @text.length)