Some basic TUI widgets ported to Go

This commit is contained in:
Kovid Goyal
2022-11-16 12:48:13 +05:30
parent f3b3d6c0ef
commit e70c021371
6 changed files with 294 additions and 2 deletions

61
tools/tui/progress-bar.go Normal file
View File

@@ -0,0 +1,61 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package tui
import (
"fmt"
"kitty/tools/cli/markup"
"strings"
)
var _ = fmt.Print
func RepeatChar(char string, count int) string {
if count <= 5 {
return strings.Repeat(char, count)
}
return fmt.Sprintf("%s\x1b[%db", char, count-1)
}
func RenderProgressBar(frac float64, width int) string {
fc := markup.New(true)
if frac >= 1 {
return fc.Green(RepeatChar("🬋", width))
}
if frac <= 0 {
return fc.Dim(RepeatChar("🬋", width))
}
w := frac * float64(width)
fl := int(w)
overhang := w - float64(fl)
filled := RepeatChar("🬋", fl)
needs_break := false
if overhang < 0.2 {
needs_break = true
} else if overhang < 0.8 {
filled += "🬃"
fl += 1
} else {
if fl < width-1 {
filled += "🬋"
fl += 1
needs_break = true
} else {
filled += "🬃"
fl += 1
}
}
ans := fc.Blue(filled)
unfilled := ""
if width > fl && needs_break {
unfilled = "🬇"
}
filler := width - fl - len(unfilled)
if filler > 0 {
unfilled += RepeatChar("🬋", filler)
}
if unfilled != "" {
ans += fc.Dim(unfilled)
}
return ans
}

27
tools/tui/spinners.go Normal file
View File

@@ -0,0 +1,27 @@
// License: GPLv3 Copyright: 2022, Kovid Goyal, <kovid at kovidgoyal.net>
package tui
import (
"fmt"
"time"
)
var _ = fmt.Print
type Spinner struct {
Name string
interval time.Duration
frames []string
current_frame int
last_change_at time.Time
}
func (self *Spinner) Tick() string {
now := time.Now()
if now.Sub(self.last_change_at) >= self.interval {
self.last_change_at = now
self.current_frame = (self.current_frame + 1) % len(self.frames)
}
return self.frames[self.current_frame]
}