Class: Potty::Widgets::Toggle

Inherits:
Base
  • Object
show all
Defined in:
lib/potty/widgets/toggle.rb

Overview

Boolean on/off control. Space (or Enter) flips it when focused. Renders “[u25CF] label” when on, “[u25CB] label” when off. Emits :change(value) when toggled.

Instance Attribute Summary collapse

Attributes inherited from Base

#app, #focused, #parent, #rect

Instance Method Summary collapse

Methods inherited from Base

#activate, #blur, #deactivate, #focus, #handle_escape, #hide, #layout, #on_blur, #on_focus, #on_layout, #show, #theme, #tick, #visible=, #visible?

Methods included from Events

#emit, #listeners?, #off, #on

Constructor Details

#initialize(app, label: '', value: false, on_change: nil) ⇒ Toggle

Returns a new instance of Toggle.



15
16
17
18
19
20
# File 'lib/potty/widgets/toggle.rb', line 15

def initialize(app, label: '', value: false, on_change: nil)
  super(app)
  @label = label
  @value = value
  @on_change = on_change
end

Instance Attribute Details

#labelObject

Returns the value of attribute label.



13
14
15
# File 'lib/potty/widgets/toggle.rb', line 13

def label
  @label
end

#on_changeObject

Returns the value of attribute on_change.



13
14
15
# File 'lib/potty/widgets/toggle.rb', line 13

def on_change
  @on_change
end

#valueObject

Returns the value of attribute value.



12
13
14
# File 'lib/potty/widgets/toggle.rb', line 12

def value
  @value
end

Instance Method Details

#can_focus?Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/potty/widgets/toggle.rb', line 22

def can_focus?
  true
end

#handle_key(ch) ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'lib/potty/widgets/toggle.rb', line 43

def handle_key(ch)
  case ch
  when Keys::SPACE, *Keys::ENTERS
    toggle
    true
  else
    false
  end
end

#preferred_height(_width) ⇒ Object



39
40
41
# File 'lib/potty/widgets/toggle.rb', line 39

def preferred_height(_width)
  1
end

#render(window) ⇒ Object



53
54
55
56
57
58
59
60
61
62
# File 'lib/potty/widgets/toggle.rb', line 53

def render(window)
  return unless @visible && @rect

  knob = @value ? "[\u25CF]" : "[\u25CB]"
  text = "#{knob} #{@label}"[0, @rect.width]
  attr = @focused ? theme.attr(:selected, bold: true) : theme[:normal]

  window.setpos(@rect.y, @rect.x)
  window.attron(attr) { window.addstr(text) }
end

#toggleObject



35
36
37
# File 'lib/potty/widgets/toggle.rb', line 35

def toggle
  self.value = !@value
end