AnP/Go/Application/Attributes.go

129 lines
2.9 KiB
Go

package Application
import (
"AnP/Models"
"AnP/Utils"
"slices"
"strings"
)
type Attributes struct {
anp Models.AnPModel
without_values []string
normals []string
}
func NewAttributes(anp Models.AnPModel) Attributes {
var attributes Attributes = Attributes{
anp: anp,
without_values: []string{
"disabled", "readonly",
},
normals: []string{
"src", "class", "title", "id", "alt", "target", "href", "style", "lang",
"type", "name", "placeholder", "min", "max", "value", "step", "disabled",
"readonly",
},
}
return attributes
}
func (_self Attributes) process_fixed(
attributes any,
included []string,
excluded []string,
callback func(name string, value string, has_value bool),
) {
switch group := attributes.(type) {
case map[string]any:
for name, value := range group {
var pascal string = strings.ToLower(Utils.Patterns.Replace(name, Utils.Patterns.RE_ATTRIBUTE_BAD_SET_CHARACTERS, "-"))
if (len(included) == 0 || slices.Contains(included, pascal)) && (len(excluded) == 0 || !slices.Contains(excluded, pascal)) {
var processed_name string = pascal
var processed_value string = ""
var has_value bool = value != nil || slices.Contains(_self.without_values, pascal)
if !slices.Contains(_self.normals, pascal) && !slices.Contains([]string{"data-", "aria-"}, pascal[:5]) {
processed_name = "data-" + processed_name
}
if has_value {
processed_value = Utils.ToString(value)
}
callback(processed_name, processed_value, has_value)
}
}
case []any:
for _, subgroup := range group {
_self.process_fixed(subgroup, included, excluded, callback)
}
}
}
func (_self Attributes) process(
attributes any,
included any,
excluded any,
callback func(name string, value string, has_value bool),
) {
_self.process_fixed(attributes, Utils.GetPascalKeys(included), Utils.GetPascalKeys(excluded), callback)
}
func (_self Attributes) Create(attributes any, included any, excluded any) string {
var html string = ``
_self.process(attributes, included, excluded, func(name string, value string, has_value bool) {
html += ` ` + name
if has_value {
if strings.Contains(value, "\"") {
value = Utils.Base64Encode(value)
}
html += `="` + value + `"`
}
})
return html
}
func GetClasses(classes any) []string {
switch group := classes.(type) {
case string:
return Utils.Patterns.RE_SPACES.Split(group, -1)
case []string:
return group
}
return []string{}
}
func JoinClasses(sets ...any) string {
var attributes []string = []string{}
for _, set := range sets {
attributes = append(attributes, GetClasses(set)...)
}
return strings.Join(Utils.GetPascalKeys(attributes), " ")
}
func AttributesRemove(attributes map[string]any, keys []string) map[string]any {
for _, key := range keys {
_, exists := attributes[key]
if exists {
delete(attributes, key)
}
}
return attributes
}