-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbar.go
99 lines (86 loc) · 2.62 KB
/
bar.go
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
package gps
import (
"fmt"
"strings"
"text/template"
"github.com/kevincobain2000/go-progress-svg/utils"
)
var barTPL = `
<svg width="{{.Width}}" height="{{.TotalHeight}}" version="1.1" xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" width="100%" height="{{.Height}}" fill="{{.BackgroundColor}}" rx="{{.CornerRadius}}" ry="{{.CornerRadius}}" />
<rect x="0" y="0" width="{{.ProgressWidth}}" height="{{.Height}}" fill="{{.ProgressColor}}" rx="{{.CornerRadius}}" ry="{{.CornerRadius}}" />
<text x="50%" y="{{.HeightHalf}}" font-family="Tohma,Helvetica,Arial,sans-serif,sans-serif" fill="{{.TextColor}}" font-size="{{.TextSize}}px" font-weight="bold" text-anchor="middle" alignment-baseline="middle">{{.Progress}}%</text>
{{if .Caption}}
<text x="50%" y="{{.CaptionY}}" font-family="Tohma,Helvetica,Arial,sans-serif,sans-serif" fill="{{.CaptionColor}}" font-size="{{.CaptionSize}}px" text-anchor="middle">{{.Caption}}</text>
{{end}}
</svg>
`
type Bar struct {
options *BarOptions
strings *utils.Strings
}
type BarOptions struct {
Progress int
Width int
Height int
ProgressWidth string
ProgressColor string
TextColor string
TextSize int
Caption string
CaptionSize int
CaptionColor string
BackgroundColor string
TotalHeight int
HeightHalf int
CaptionY int
CornerRadius int
}
type BarOption func(*BarOptions) error
func NewBar(opts ...BarOption) (*Bar, error) {
options := &BarOptions{
Progress: 0,
Width: 200,
Height: 50,
ProgressColor: "#76e5b1",
TextColor: "#6bdba7",
TextSize: 20,
Caption: "",
CaptionSize: 16,
CaptionColor: "#000000",
BackgroundColor: "#e0e0e0",
CornerRadius: 10,
}
for _, opt := range opts {
err := opt(options)
if err != nil {
return nil, err
}
}
if options.Progress < 3 {
options.Progress = 3
}
options.ProgressWidth = fmt.Sprintf("%d%%", options.Progress)
options.TotalHeight = options.Height + options.CaptionSize + 10 // Additional space for caption
options.HeightHalf = options.Height / 2
options.CaptionY = options.Height + options.CaptionSize // Position caption below the bar
return &Bar{
options: options,
strings: utils.NewStrings(),
}, nil
}
func (b *Bar) SVG() string {
tpl := b.strings.StripXMLWhitespace(barTPL)
tmpl, err := template.New("svg").Parse(tpl)
if err != nil {
fmt.Println("Error parsing template:", err)
return ""
}
var rendered strings.Builder
err = tmpl.Execute(&rendered, b.options)
if err != nil {
fmt.Println("Error rendering template:", err)
return ""
}
return rendered.String()
}