Class: Chamomile::Spinner

Inherits:
Object
  • Object
show all
Defined in:
lib/chamomile/components/spinner.rb

Overview

Animated spinner with configurable frame types and tick-based updates.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type: Spinners::LINE) ⇒ Spinner

Returns a new instance of Spinner.



26
27
28
29
30
31
# File 'lib/chamomile/components/spinner.rb', line 26

def initialize(type: Spinners::LINE)
  @id = self.class.next_id
  @spinner_type = type
  @frame = 0
  @tag = 0
end

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id.



24
25
26
# File 'lib/chamomile/components/spinner.rb', line 24

def id
  @id
end

#spinner_typeObject

Returns the value of attribute spinner_type.



24
25
26
# File 'lib/chamomile/components/spinner.rb', line 24

def spinner_type
  @spinner_type
end

Class Method Details

.next_idObject



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/chamomile/components/spinner.rb', line 12

def self.next_id
  @id_mutex.synchronize do
    if Process.pid != @id_pid
      @id_pid = Process.pid
      @next_id = 0
      @id_mutex = Mutex.new
    end
    @next_id += 1
    "#{@id_pid}-#{@next_id}"
  end
end

Instance Method Details

#handle(msg) ⇒ Object Also known as: update

Advance frame if msg is a matching SpinnerTickMsg; return cmd or nil.



45
46
47
48
49
50
51
52
# File 'lib/chamomile/components/spinner.rb', line 45

def handle(msg)
  return unless msg.is_a?(SpinnerTickMsg)
  return unless msg.id == @id && msg.tag == @tag

  @frame = (@frame + 1) % @spinner_type.frames.size
  @tag += 1
  tick_cmd
end

#resetObject

Reset to first frame, invalidate in-flight ticks.



62
63
64
65
66
# File 'lib/chamomile/components/spinner.rb', line 62

def reset
  @frame = 0
  @tag += 1
  self
end

#tick_cmdObject

Returns a command that sleeps for the frame interval then produces a SpinnerTickMsg.



34
35
36
37
38
39
40
41
42
# File 'lib/chamomile/components/spinner.rb', line 34

def tick_cmd
  captured_id = @id
  captured_tag = @tag
  fps = @spinner_type.fps
  -> {
    sleep(1.0 / fps)
    SpinnerTickMsg.new(id: captured_id, tag: captured_tag, time: Time.now)
  }
end

#viewObject

Current frame string.



57
58
59
# File 'lib/chamomile/components/spinner.rb', line 57

def view
  @spinner_type.frames[@frame]
end