core/style/style.go

152 lines
2.9 KiB
Go

package style
import (
"fmt"
"sort"
"strings"
"gitea.meta-tech.academy/go/core/util"
"github.com/gookit/color"
)
const KEY_STYLE_NAME = 0
const KEY_STYLE_COLOR = 1
const KEY_STYLE_OPTION = 2
const COLOR_OFF = "\x1b[0m"
var defStyle *Style = &Style{color: color.HEXStyle("#ffffff"), Name: "default"}
type Style struct {
color *color.RGBStyle
Name string
}
type Styles struct {
List map[string]*Style
DefaultKeyStyle string
DefaultValStyle string
DefaultKeyPadding string
DefaultIndent string
}
func (s *Style) Echof(format string, a ...any) {
s.color.Printf(format+COLOR_OFF, a...)
}
func (s *Style) Applyf(format string, a ...any) string {
return s.color.Sprintf(format+COLOR_OFF, a...)
}
func (s *Style) Echo(data string) {
s.Echof("%s", data)
}
func (s *Style) Apply(data string) string {
return s.Applyf("%s", data)
}
func (s *Style) Ln() {
s.Echo("\n")
}
func NewStyleByDef(def string) *Style {
var o []string = []string{}
var c []string = []string{"FFFFFF"}
d := strings.Fields(def)
if len(d) > KEY_STYLE_COLOR {
c = strings.Split(d[KEY_STYLE_COLOR], ",")
if len(d) > KEY_STYLE_OPTION {
o = strings.Split(d[KEY_STYLE_OPTION], ",")
}
}
util.PrependToSliceStr(&c, "#")
var s *color.RGBStyle
switch len(c) {
case 1:
s = color.HEXStyle(c[0])
case 2:
s = color.HEXStyle(c[0], c[1])
}
for _, elm := range o {
s.AddOpts(color.Color(util.Str2int(elm, 10, 0)))
}
// s.Printf(" %-20s\n", d[KEY_STYLE_NAME])
return &Style{s, d[KEY_STYLE_NAME]}
}
func NewStyles() *Styles {
l := &Styles{
List: make(map[string]*Style),
DefaultKeyStyle: "key",
DefaultValStyle: "val",
DefaultKeyPadding: "18",
DefaultIndent: "4",
}
return l
}
func (s *Styles) HasStyle(name string) bool {
var done bool = false
if s.List != nil {
_, done = s.List[name]
}
return done
}
func (s *Styles) Get(name string) *Style {
style := defStyle
if s.HasStyle(name) {
style = s.List[name]
}
return style
}
func (s *Styles) Echo(name string, data string) {
s.Get(name).Echof("%s", data)
}
func (s *Styles) Apply(name string, data string) string {
return s.List[name].Applyf("%s", data)
}
func (s *Styles) Echof(name string, format string, a ...any) {
s.Get(name).Echof(format, a...)
}
func (s *Styles) Applyf(name string, format string, a ...any) string {
return s.Get(name).Applyf(format, a...)
}
func (s *Styles) Keyval(key string, val string, names ...string) {
sk := s.Get(s.DefaultKeyStyle)
sv := s.Get(s.DefaultValStyle)
if len(names) > 1 {
sk = s.Get(names[0])
if len(names) > 2 {
sv = s.Get(names[1])
}
}
fmt.Printf(
"%-"+s.DefaultIndent+"s%s : %s\n",
" ",
sk.Applyf("%-"+s.DefaultKeyPadding+"s", key),
sv.Apply(val),
)
}
func (s *Styles) Render() {
keys := make([]string, 0, len(s.List))
for name := range s.List {
keys = append(keys, name)
}
sort.Strings(keys)
for _, name := range keys {
s.Get(name).Echof(" %s ", name)
defStyle.Ln()
}
}