aboutsummaryrefslogtreecommitdiff
path: root/internal/ui/bar.go
blob: c1abce919a85aacd609cd1f491ae2130d03ed9ae (plain)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package ui

import (
	"math"
	"strings"

	"thehouseoficarus/internal/color"
)

type BarStyle struct {
	FilledColor int
	EmptyColor  int
	EmptyDim    bool
}

func RenderBar(current, max, width int, unicode bool) string {
	if max <= 0 {
		max = 1
	}
	if current < 0 {
		current = 0
	}
	if current > max {
		current = max
	}
	filled := int(math.Round(float64(current) * float64(width) / float64(max)))
	if filled > width {
		filled = width
	}
	if filled < 0 {
		filled = 0
	}

	fillRune, emptyRune := barRunes(unicode)
	return strings.Repeat(fillRune, filled) + strings.Repeat(emptyRune, width-filled)
}

func RenderBarF(current, max float64, width int, unicode bool) string {
	if max <= 0 {
		max = 1
	}
	ratio := current / max
	if ratio > 1 {
		ratio = 1
	}
	if ratio < 0 {
		ratio = 0
	}
	filled := int(math.Round(ratio * float64(width)))
	if filled > width {
		filled = width
	}
	if filled < 0 {
		filled = 0
	}

	fillRune, emptyRune := barRunes(unicode)
	return strings.Repeat(fillRune, filled) + strings.Repeat(emptyRune, width-filled)
}

func RenderColoredBar(current, max, width int, unicode bool, style *BarStyle, mode string) string {
	if max <= 0 {
		max = 1
	}
	if current < 0 {
		current = 0
	}
	if current > max {
		current = max
	}
	filled := int(math.Round(float64(current) * float64(width) / float64(max)))
	if filled > width {
		filled = width
	}
	if filled < 0 {
		filled = 0
	}

	fillRune, emptyRune := barRunes(unicode)
	fillStr := strings.Repeat(fillRune, filled)
	emptyStr := strings.Repeat(emptyRune, width-filled)

	if style != nil && mode != "none" && mode != "" {
		if style.FilledColor >= 0 {
			fillStr = color.Render(mode, color.ColorSpec{Fg: style.FilledColor}, fillStr)
		}
		if style.EmptyColor >= 0 {
			spec := color.ColorSpec{Fg: style.EmptyColor}
			if style.EmptyDim {
				spec.Dim = true
			}
			emptyStr = color.Render(mode, spec, emptyStr)
		}
	}

	return fillStr + emptyStr
}

func barRunes(unicode bool) (fill, empty string) {
	return BarRunes(unicode)
}

// BarRunes returns the fill and empty runes used for progress bars, selecting
// Unicode block characters when unicode is true and ASCII otherwise.
func BarRunes(unicode bool) (fill, empty string) {
	if unicode {
		return "█", "░"
	}
	return "#", "."
}