~adnano/astronaut

ref: 5b2ba7d7bffd153f57a7eac22f172a5d4d56c6a9 astronaut/ui/spinner.go -rw-r--r-- 717 bytes
5b2ba7d7Adnan Maolood ui/view: Remove focus variable 7 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package ui

import (
	"time"
)

var spinner = []rune("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏")

// Spinner represents a progress spinner.
type Spinner struct {
	i    int
	on   bool
	next time.Time
}

func (s *Spinner) Update(view *View, on bool) {
	if !s.on {
		if on {
			s.on = true
			view.Invalidate()
		}
		return
	} else if !on {
		s.on = false
		s.i = 0
		s.next = time.Time{}
		view.Invalidate()
		return
	}

	const interval = 100 * time.Millisecond
	if s.next.IsZero() {
		s.next = time.Now().Add(interval)
	} else if time.Now().After(s.next) {
		s.next = s.next.Add(interval)
		s.i++
		s.i %= len(spinner)
		view.Invalidate()
	}
}

func (s *Spinner) Rune() rune {
	if !s.on {
		return ' '
	}
	return spinner[s.i]
}