1
0
Fork 0
mirror of https://github.com/diamondburned/cchat-gtk.git synced 2024-11-01 12:04:15 +00:00
cchat-gtk/internal/ui/rich/parser/attrmap/attrmap.go

85 lines
1.6 KiB
Go
Raw Normal View History

2020-06-28 23:01:08 +00:00
package attrmap
import (
"fmt"
"sort"
"strings"
2020-06-28 23:01:08 +00:00
)
type AppendMap struct {
appended map[int]string // for opening tags
prepended map[int]string // for closing tags
indices []int
2020-06-28 23:01:08 +00:00
}
func NewAppendedMap() AppendMap {
return AppendMap{
appended: map[int]string{},
prepended: map[int]string{},
indices: []int{},
2020-06-28 23:01:08 +00:00
}
}
func (a *AppendMap) appendIndex(ind int) {
// Backwards search which should make things faster.
for i := len(a.indices) - 1; i >= 0; i-- {
if a.indices[i] == ind {
return
}
}
a.indices = append(a.indices, ind)
2020-06-28 23:01:08 +00:00
}
func (a *AppendMap) Span(start, end int, attrs ...string) {
a.Openf(start, "<span %s>", strings.Join(attrs, " "))
a.Close(end, "</span>")
2020-06-28 23:01:08 +00:00
}
func (a *AppendMap) Pair(start, end int, open, close string) {
a.Open(start, open)
a.Close(end, close)
2020-06-28 23:01:08 +00:00
}
func (a *AppendMap) Openf(ind int, f string, argv ...interface{}) {
a.Open(ind, fmt.Sprintf(f, argv...))
2020-06-28 23:01:08 +00:00
}
func (a *AppendMap) Open(ind int, attr string) {
if str, ok := a.appended[ind]; ok {
a.appended[ind] = str + attr // append
2020-06-28 23:01:08 +00:00
return
}
a.appended[ind] = attr
a.appendIndex(ind)
2020-06-28 23:01:08 +00:00
}
func (a *AppendMap) Close(ind int, attr string) {
if str, ok := a.prepended[ind]; ok {
a.prepended[ind] = attr + str // prepend
return
}
a.prepended[ind] = attr
a.appendIndex(ind)
}
func (a AppendMap) Get(ind int) (tags string) {
if t, ok := a.appended[ind]; ok {
tags += t
}
if t, ok := a.prepended[ind]; ok {
tags += t
}
return
2020-06-28 23:01:08 +00:00
}
func (a *AppendMap) Finalize(strlen int) []int {
// make sure there's always a closing tag at the end so the entire string
// gets flushed.
a.Close(strlen, "")
2020-06-28 23:01:08 +00:00
sort.Ints(a.indices)
return a.indices
}