-
Notifications
You must be signed in to change notification settings - Fork 0
/
autoid.go
82 lines (69 loc) · 2.31 KB
/
autoid.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
package aform
import (
"fmt"
"regexp"
"strings"
)
const (
defaultAutoID = "id_%s"
disabledAutoID = ""
)
// validAutoID checks if the provided auto ID is correct.
// Correct values are:
// - empty string to deactivate auto ID e.g. ""
// - string containing one verb '%s' to customize auto ID. e.g. "id_%s"
//
// A non-empty string without a verb '%s' is invalid.
func validAutoID(autoID string) error {
if isDisabledAutoID(autoID) {
return nil
}
switch strings.Count(autoID, "%s") {
case 1:
return nil
default:
return fmt.Errorf("autoID must contain one %%s verb (e.g. %s). To disable auto ID use DisableAutoID(). Given: %s", defaultAutoID, autoID)
}
}
func hasID(fld fieldReader) bool {
return !isDisabledAutoID(fld.AutoID())
}
// isDisabledAutoID returns true if autoID is the disabled Auto ID
func isDisabledAutoID(autoID string) bool {
return autoID == disabledAutoID
}
func normalizedIDForField(fld fieldReader) string {
if !hasID(fld) {
return disabledAutoID
}
singleSpacePattern := regexp.MustCompile(`\s+`)
return fmt.Sprintf(fld.AutoID(), strings.ToLower(singleSpacePattern.ReplaceAllString(fld.Name(), "_")))
}
func normalizedNameForField(fld fieldReader) string {
return normalizedName(fld.Name())
}
func normalizedName(name string) string {
singleSpacePattern := regexp.MustCompile(`\s+`)
return strings.ToLower(singleSpacePattern.ReplaceAllString(name, "_"))
}
func normalizedDescribedByIDErrList(fld fieldReader, numberOfError int) []string {
ids := make([]string, numberOfError)
for i := 0; i < numberOfError; i++ {
ids[i] = normalizedDescribedByIDForErr(fld, i)
}
return ids
}
// normalizedDescribedByIDForErr generates IDs for errors pointed by the aria-describedby tag.
func normalizedDescribedByIDForErr(fld fieldReader, index int) string {
return fmt.Sprintf("err_%d_", index) + normalizedIDForField(fld)
}
func normalizedGroupID(normalizedID string, index uint) string {
return normalizedID + fmt.Sprintf("_%d", index)
}
func normalizedSubGroupID(normalizedID string, index, subIndex uint) string {
return normalizedID + fmt.Sprintf("_%d_%d", index, subIndex)
}
// normalizedDescribedByIDForHelpText generates the ID for the help text pointed by the aria-describedby tag.
func normalizedDescribedByIDForHelpText(fld fieldReader) string {
return "helptext_" + normalizedIDForField(fld)
}