forked from leg100/otf
-
Notifications
You must be signed in to change notification settings - Fork 6
/
functions.go
85 lines (76 loc) · 2.12 KB
/
functions.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
package html
import (
"fmt"
"html/template"
"net/url"
"reflect"
"github.com/tofutf/tofutf/internal"
"github.com/tofutf/tofutf/internal/resource"
)
// mergeQuery merges the query string into the given url, replacing any existing
// query parameters with the same name.
func mergeQuery(u string, q string) (string, error) {
parsedURL, err := url.Parse(u)
if err != nil {
return "", err
}
mergeQuery, err := url.ParseQuery(q)
if err != nil {
return "", err
}
existingQuery := parsedURL.Query()
for k, v := range mergeQuery {
existingQuery.Set(k, v[0])
}
parsedURL.RawQuery = existingQuery.Encode()
return parsedURL.String(), nil
}
func prevPageQuery(p resource.Pagination) *string {
if p.PreviousPage == nil {
return nil
}
return internal.String(fmt.Sprintf("page[number]=%d", *p.PreviousPage))
}
func nextPageQuery(p resource.Pagination) *string {
if p.NextPage == nil {
return nil
}
return internal.String(fmt.Sprintf("page[number]=%d", *p.NextPage))
}
func disabled(arg any, args ...any) (template.HTMLAttr, error) {
return attrIf("disabled", arg, args...)
}
func selected(arg any, args ...any) (template.HTMLAttr, error) {
return attrIf("selected", arg, args...)
}
func checked(arg any, args ...any) (template.HTMLAttr, error) {
return attrIf("checked", arg, args...)
}
// attrIf returns string as an html attribute, if:
// (a) single arg provided, it is a boolean, and it is true.
// (b) multiple args provided, they are all strings, and they are all equal.
// otherwise it outputs an empty attribute
// This is useful for printing strings in templates or not.
func attrIf(s string, arg any, args ...any) (template.HTMLAttr, error) {
if len(args) == 0 {
if reflect.ValueOf(arg).Kind() == reflect.Bool {
if reflect.ValueOf(arg).Bool() {
return template.HTMLAttr(s), nil
}
}
return "", nil
}
if reflect.ValueOf(arg).Kind() != reflect.String {
return "", nil
}
lastarg := reflect.ValueOf(arg).String()
for _, a := range args {
if reflect.ValueOf(a).Kind() != reflect.String {
return "", nil
}
if reflect.ValueOf(a).String() != lastarg {
return "", nil
}
}
return template.HTMLAttr(s), nil
}