-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsrcset.go
More file actions
218 lines (193 loc) · 4.69 KB
/
Copy pathsrcset.go
File metadata and controls
218 lines (193 loc) · 4.69 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// Package srcset `srcset` provides a parser for the HTML5 `srcset` attribute, based on the
// [WHATWG reference algorithm](https://html.spec.whatwg.org/multipage/embedded-content.html#parse-a-srcset-attribute).
// TODO: This works, but I dislike the state manipulation.
// Use more go-like structures for reading and tokenization, like bufio.Scanner
package srcset
import (
"regexp"
"strconv"
)
// ImageSource is a structure that contains an image definition.
type ImageSource struct {
URL string
Width *int64
Height *int64
Density *float64
Offset int
}
// SourceSet is the result of parsing the value of a srcset attribute.
// A SourceSet consists of multiple ImageSource instances.
type SourceSet []ImageSource
const (
comma = ','
leftParens = '('
rightParens = ')'
)
const (
stateNone = iota
stateInDescriptor
stateInParens
stateAfterDescriptor
)
var (
regexLeadingSpaces = regexp.MustCompile("^[ \t\n\r\u000c]+")
regexLeadingCommasOrSpaces = regexp.MustCompile("^[, \t\n\r\u000c]+")
regexLeadingNotSpaces = regexp.MustCompile("^[^ \t\n\r\u000c]+")
regexTrailingCommas = regexp.MustCompile("[,]+$")
regexNonNegativeInteger = regexp.MustCompile(`^\d+$`)
regexFloatingPoint = regexp.MustCompile(`^-?(?:[0-9]+|[0-9]*\.[0-9]+)(?:[eE][+-]?[0-9]+)?$`)
)
func isSpace(c rune) bool {
switch c {
case
'\u0020', // space
'\u0009', // horizontal tab
'\u000A', // new line
'\u000C', // form feed
'\u000D': // carriage return
return true
default:
return false
}
}
// Parse takes the value of a srcset attribute and parses it.
func Parse(input string) SourceSet {
var (
url string
urlPos = 0
pos = 0
currState = stateNone
end = len(input)
candidates = SourceSet{}
descriptors = []string{}
)
collectChars := func(rx *regexp.Regexp) (string, int) {
if match := rx.FindString(input[pos:]); match != "" {
pos += len(match)
return match, pos - len(match)
}
return "", pos
}
parseDescriptors := func() {
var (
isErr = false
h *int64
w *int64
d *float64
)
for _, desc := range descriptors {
lastIdx := len(desc) - 1
lastChar, numericVal := desc[lastIdx], desc[:lastIdx]
intVal, intErr := strconv.ParseInt(numericVal, 10, 64)
floatVal, floatErr := strconv.ParseFloat(numericVal, 64)
switch {
case regexNonNegativeInteger.MatchString(numericVal) && lastChar == 'w':
if w != nil || d != nil {
isErr = true
}
if intErr != nil || intVal == 0 {
isErr = true
} else {
w = &intVal
}
case regexFloatingPoint.MatchString(numericVal) && lastChar == 'x':
if w != nil || d != nil || h != nil {
isErr = true
}
if floatErr != nil || floatVal < 0 {
isErr = true
} else {
d = &floatVal
}
case regexNonNegativeInteger.MatchString(numericVal) && lastChar == 'h':
if h != nil || d != nil {
isErr = true
}
if intErr != nil || intVal == 0 {
isErr = true
} else {
h = &intVal
}
default:
isErr = true
}
}
if !isErr {
candidates = append(candidates, ImageSource{
URL: url,
Offset: urlPos,
Density: d,
Width: w,
Height: h,
})
}
}
tokenize := func() {
collectChars(regexLeadingSpaces)
currDescriptor := ""
currState = stateInDescriptor
for {
if pos == len(input) {
if currState != stateAfterDescriptor && currDescriptor != "" {
descriptors = append(descriptors, currDescriptor)
}
parseDescriptors()
return
}
c := rune(input[pos])
switch currState {
case stateInDescriptor:
switch {
case isSpace(c):
if currDescriptor != "" {
descriptors = append(descriptors, currDescriptor)
currDescriptor = ""
currState = stateAfterDescriptor
}
case c == comma:
pos++
if currDescriptor != "" {
descriptors = append(descriptors, currDescriptor)
parseDescriptors()
return
}
case c == leftParens:
currDescriptor += string(c)
currState = stateInParens
default:
currDescriptor += string(c)
}
case stateInParens:
switch c {
case rightParens:
currDescriptor += string(c)
currState = stateInDescriptor
default:
currDescriptor += string(c)
}
case stateAfterDescriptor:
switch {
case isSpace(c):
default:
currState = stateInDescriptor
pos--
}
}
pos++
}
}
for {
collectChars(regexLeadingCommasOrSpaces)
if pos >= end {
return candidates
}
url, urlPos = collectChars(regexLeadingNotSpaces)
descriptors = []string{}
if url[len(url)-1] == ',' {
url = regexTrailingCommas.ReplaceAllString(url, "")
parseDescriptors()
} else {
tokenize()
}
}
}