Debian Codegraph @

selector.go

raw symbols SCIP
1 package main
2
3 import (
4 "bytes"
5 "fmt"
6 "regexp"
7 "strconv"
8 "strings"
9 "text/scanner"
10
11 "golang.org/x/net/html"
12 )
13
14 type Selector interface {
15 Match(node *html.Node) bool
16 }
17
18 type SelectorFunc func(nodes []*html.Node) []*html.Node
19
20 func Select(s Selector) SelectorFunc {
21 // have to define first to be able to do recursion
22 var selectChildren func(node *html.Node) []*html.Node
23 selectChildren = func(node *html.Node) []*html.Node {
24 selected := []*html.Node{}
25 for child := node.FirstChild; child != nil; child = child.NextSibling {
26 if s.Match(child) {
27 selected = append(selected, child)
28 } else {
29 selected = append(selected, selectChildren(child)...)
30 }
31 }
32 return selected
33 }
34 return func(nodes []*html.Node) []*html.Node {
35 selected := []*html.Node{}
36 for _, node := range nodes {
37 selected = append(selected, selectChildren(node)...)
38 }
39 return selected
40 }
41 }
42
43 // Defined for the '>' selector
44 func SelectNextSibling(s Selector) SelectorFunc {
45 return func(nodes []*html.Node) []*html.Node {
46 selected := []*html.Node{}
47 for _, node := range nodes {
48 for ns := node.NextSibling; ns != nil; ns = ns.NextSibling {
49 if ns.Type == html.ElementNode {
50 if s.Match(ns) {
51 selected = append(selected, ns)
52 }
53 break
54 }
55 }
56 }
57 return selected
58 }
59 }
60
61 // Defined for the '+' selector
62 func SelectFromChildren(s Selector) SelectorFunc {
63 return func(nodes []*html.Node) []*html.Node {
64 selected := []*html.Node{}
65 for _, node := range nodes {
66 for c := node.FirstChild; c != nil; c = c.NextSibling {
67 if s.Match(c) {
68 selected = append(selected, c)
69 }
70 }
71 }
72 return selected
73 }
74 }
75
76 type PseudoClass func(*html.Node) bool
77
78 type CSSSelector struct {
79 Tag string
80 Attrs map[string]*regexp.Regexp
81 Pseudo PseudoClass
82 }
83
84 func (s CSSSelector) Match(node *html.Node) bool {
85 if node.Type != html.ElementNode {
86 return false
87 }
88 if s.Tag != "" {
89 if s.Tag != node.DataAtom.String() {
90 return false
91 }
92 }
93 for attrKey, matcher := range s.Attrs {
94 matched := false
95 for _, attr := range node.Attr {
96 if attrKey == attr.Key {
97 if !matcher.MatchString(attr.Val) {
98 return false
99 }
100 matched = true
101 break
102 }
103 }
104 if !matched {
105 return false
106 }
107 }
108 if s.Pseudo == nil {
109 return true
110 }
111 return s.Pseudo(node)
112 }
113
114 // Parse a selector
115 // e.g. `div#my-button.btn[href^="http"]`
116 func ParseSelector(cmd string) (selector CSSSelector, err error) {
117 selector = CSSSelector{
118 Tag: "",
119 Attrs: map[string]*regexp.Regexp{},
120 Pseudo: nil,
121 }
122 var s scanner.Scanner
123 s.Init(strings.NewReader(cmd))
124 err = ParseTagMatcher(&selector, s)
125 return
126 }
127
128 // Parse the initial tag
129 // e.g. `div`
130 func ParseTagMatcher(selector *CSSSelector, s scanner.Scanner) error {
131 tag := bytes.NewBuffer([]byte{})
132 defer func() {
133 selector.Tag = tag.String()
134 }()
135 for {
136 c := s.Next()
137 switch c {
138 case scanner.EOF:
139 return nil
140 case '.':
141 return ParseClassMatcher(selector, s)
142 case '#':
143 return ParseIdMatcher(selector, s)
144 case '[':
145 return ParseAttrMatcher(selector, s)
146 case ':':
147 return ParsePseudo(selector, s)
148 default:
149 if _, err := tag.WriteRune(c); err != nil {
150 return err
151 }
152 }
153 }
154 }
155
156 // Parse a class matcher
157 // e.g. `.btn`
158 func ParseClassMatcher(selector *CSSSelector, s scanner.Scanner) error {
159 var class bytes.Buffer
160 defer func() {
161 regexpStr := `(\A|\s)` + regexp.QuoteMeta(class.String()) + `(\s|\z)`
162 selector.Attrs["class"] = regexp.MustCompile(regexpStr)
163 }()
164 for {
165 c := s.Next()
166 switch c {
167 case scanner.EOF:
168 return nil
169 case '.':
170 return ParseClassMatcher(selector, s)
171 case '#':
172 return ParseIdMatcher(selector, s)
173 case '[':
174 return ParseAttrMatcher(selector, s)
175 case ':':
176 return ParsePseudo(selector, s)
177 default:
178 if _, err := class.WriteRune(c); err != nil {
179 return err
180 }
181 }
182 }
183 }
184
185 // Parse an id matcher
186 // e.g. `#my-picture`
187 func ParseIdMatcher(selector *CSSSelector, s scanner.Scanner) error {
188 var id bytes.Buffer
189 defer func() {
190 regexpStr := `^` + regexp.QuoteMeta(id.String()) + `$`
191 selector.Attrs["id"] = regexp.MustCompile(regexpStr)
192 }()
193 for {
194 c := s.Next()
195 switch c {
196 case scanner.EOF:
197 return nil
198 case '.':
199 return ParseClassMatcher(selector, s)
200 case '#':
201 return ParseIdMatcher(selector, s)
202 case '[':
203 return ParseAttrMatcher(selector, s)
204 case ':':
205 return ParsePseudo(selector, s)
206 default:
207 if _, err := id.WriteRune(c); err != nil {
208 return err
209 }
210 }
211 }
212 }
213
214 // Parse an attribute matcher
215 // e.g. `[attr^="http"]`
216 func ParseAttrMatcher(selector *CSSSelector, s scanner.Scanner) error {
217 var attrKey bytes.Buffer
218 var attrVal bytes.Buffer
219 hasMatchVal := false
220 matchType := '='
221 defer func() {
222 if hasMatchVal {
223 var regexpStr string
224 switch matchType {
225 case '=':
226 regexpStr = `^` + regexp.QuoteMeta(attrVal.String()) + `$`
227 case '*':
228 regexpStr = regexp.QuoteMeta(attrVal.String())
229 case '$':
230 regexpStr = regexp.QuoteMeta(attrVal.String()) + `$`
231 case '^':
232 regexpStr = `^` + regexp.QuoteMeta(attrVal.String())
233 case '~':
234 regexpStr = `(\A|\s)` + regexp.QuoteMeta(attrVal.String()) + `(\s|\z)`
235 }
236 selector.Attrs[attrKey.String()] = regexp.MustCompile(regexpStr)
237 } else {
238 selector.Attrs[attrKey.String()] = regexp.MustCompile(`^.*$`)
239 }
240 }()
241 // After reaching ']' proceed
242 proceed := func() error {
243 switch s.Next() {
244 case scanner.EOF:
245 return nil
246 case '.':
247 return ParseClassMatcher(selector, s)
248 case '#':
249 return ParseIdMatcher(selector, s)
250 case '[':
251 return ParseAttrMatcher(selector, s)
252 case ':':
253 return ParsePseudo(selector, s)
254 default:
255 return fmt.Errorf("Expected selector indicator after ']'")
256 }
257 }
258 // Parse the attribute key matcher
259 for !hasMatchVal {
260 c := s.Next()
261 switch c {
262 case scanner.EOF:
263 return fmt.Errorf("Unmatched open brace '['")
264 case ']':
265 // No attribute value matcher, proceed!
266 return proceed()
267 case '$', '^', '~', '*':
268 matchType = c
269 hasMatchVal = true
270 if s.Next() != '=' {
271 return fmt.Errorf("'%c' must be followed by a '='", matchType)
272 }
273 case '=':
274 matchType = c
275 hasMatchVal = true
276 default:
277 if _, err := attrKey.WriteRune(c); err != nil {
278 return err
279 }
280 }
281 }
282 // figure out if the value is quoted
283 c := s.Next()
284 inQuote := false
285 switch c {
286 case scanner.EOF:
287 return fmt.Errorf("Unmatched open brace '['")
288 case ']':
289 return proceed()
290 case '"':
291 inQuote = true
292 default:
293 if _, err := attrVal.WriteRune(c); err != nil {
294 return err
295 }
296 }
297 if inQuote {
298 for {
299 c := s.Next()
300 switch c {
301 case '\\':
302 // consume another character
303 if c = s.Next(); c == scanner.EOF {
304 return fmt.Errorf("Unmatched open brace '['")
305 }
306 case '"':
307 switch s.Next() {
308 case ']':
309 return proceed()
310 default:
311 return fmt.Errorf("Quote must end at ']'")
312 }
313 }
314 if _, err := attrVal.WriteRune(c); err != nil {
315 return err
316 }
317 }
318 } else {
319 for {
320 c := s.Next()
321 switch c {
322 case scanner.EOF:
323 return fmt.Errorf("Unmatched open brace '['")
324 case ']':
325 // No attribute value matcher, proceed!
326 return proceed()
327 }
328 if _, err := attrVal.WriteRune(c); err != nil {
329 return err
330 }
331 }
332 }
333 }
334
335 // Parse the selector after ':'
336 func ParsePseudo(selector *CSSSelector, s scanner.Scanner) error {
337 if selector.Pseudo != nil {
338 return fmt.Errorf("Combined multiple pseudo classes")
339 }
340 var b bytes.Buffer
341 for s.Peek() != scanner.EOF {
342 if _, err := b.WriteRune(s.Next()); err != nil {
343 return err
344 }
345 }
346 cmd := b.String()
347 var err error
348 switch {
349 case cmd == "empty":
350 selector.Pseudo = func(n *html.Node) bool {
351 return n.FirstChild == nil
352 }
353 case cmd == "first-child":
354 selector.Pseudo = firstChildPseudo
355 case cmd == "last-child":
356 selector.Pseudo = lastChildPseudo
357 case cmd == "only-child":
358 selector.Pseudo = func(n *html.Node) bool {
359 return firstChildPseudo(n) && lastChildPseudo(n)
360 }
361 case cmd == "first-of-type":
362 selector.Pseudo = firstOfTypePseudo
363 case cmd == "last-of-type":
364 selector.Pseudo = lastOfTypePseudo
365 case cmd == "only-of-type":
366 selector.Pseudo = func(n *html.Node) bool {
367 return firstOfTypePseudo(n) && lastOfTypePseudo(n)
368 }
369 case strings.HasPrefix(cmd, "contains("):
370 selector.Pseudo, err = parseContainsPseudo(cmd[len("contains("):])
371 if err != nil {
372 return err
373 }
374 case strings.HasPrefix(cmd, "nth-child("),
375 strings.HasPrefix(cmd, "nth-last-child("),
376 strings.HasPrefix(cmd, "nth-last-of-type("),
377 strings.HasPrefix(cmd, "nth-of-type("):
378 if selector.Pseudo, err = parseNthPseudo(cmd); err != nil {
379 return err
380 }
381 case strings.HasPrefix(cmd, "not("):
382 if selector.Pseudo, err = parseNotPseudo(cmd[len("not("):]); err != nil {
383 return err
384 }
385 case strings.HasPrefix(cmd, "parent-of("):
386 if selector.Pseudo, err = parseParentOfPseudo(cmd[len("parent-of("):]); err != nil {
387 return err
388 }
389 default:
390 return fmt.Errorf("%s not a valid pseudo class", cmd)
391 }
392 return nil
393 }
394
395 // :first-of-child
396 func firstChildPseudo(n *html.Node) bool {
397 for c := n.PrevSibling; c != nil; c = c.PrevSibling {
398 if c.Type == html.ElementNode {
399 return false
400 }
401 }
402 return true
403 }
404
405 // :last-of-child
406 func lastChildPseudo(n *html.Node) bool {
407 for c := n.NextSibling; c != nil; c = c.NextSibling {
408 if c.Type == html.ElementNode {
409 return false
410 }
411 }
412 return true
413 }
414
415 // :first-of-type
416 func firstOfTypePseudo(node *html.Node) bool {
417 if node.Type != html.ElementNode {
418 return false
419 }
420 for n := node.PrevSibling; n != nil; n = n.PrevSibling {
421 if n.DataAtom == node.DataAtom {
422 return false
423 }
424 }
425 return true
426 }
427
428 // :last-of-type
429 func lastOfTypePseudo(node *html.Node) bool {
430 if node.Type != html.ElementNode {
431 return false
432 }
433 for n := node.NextSibling; n != nil; n = n.NextSibling {
434 if n.DataAtom == node.DataAtom {
435 return false
436 }
437 }
438 return true
439 }
440
441 func parseNthPseudo(cmd string) (PseudoClass, error) {
442 i := strings.IndexRune(cmd, '(')
443 if i < 0 {
444 // really, we should never get here
445 return nil, fmt.Errorf("Fatal error, '%s' does not contain a '('", cmd)
446 }
447 pseudoName := cmd[:i]
448 // Figure out how the counting function works
449 var countNth func(*html.Node) int
450 switch pseudoName {
451 case "nth-child":
452 countNth = func(n *html.Node) int {
453 nth := 1
454 for sib := n.PrevSibling; sib != nil; sib = sib.PrevSibling {
455 if sib.Type == html.ElementNode {
456 nth++
457 }
458 }
459 return nth
460 }
461 case "nth-of-type":
462 countNth = func(n *html.Node) int {
463 nth := 1
464 for sib := n.PrevSibling; sib != nil; sib = sib.PrevSibling {
465 if sib.Type == html.ElementNode && sib.DataAtom == n.DataAtom {
466 nth++
467 }
468 }
469 return nth
470 }
471 case "nth-last-child":
472 countNth = func(n *html.Node) int {
473 nth := 1
474 for sib := n.NextSibling; sib != nil; sib = sib.NextSibling {
475 if sib.Type == html.ElementNode {
476 nth++
477 }
478 }
479 return nth
480 }
481 case "nth-last-of-type":
482 countNth = func(n *html.Node) int {
483 nth := 1
484 for sib := n.NextSibling; sib != nil; sib = sib.NextSibling {
485 if sib.Type == html.ElementNode && sib.DataAtom == n.DataAtom {
486 nth++
487 }
488 }
489 return nth
490 }
491 default:
492 return nil, fmt.Errorf("Unrecognized pseudo '%s'", pseudoName)
493 }
494
495 nthString := cmd[i+1:]
496 i = strings.IndexRune(nthString, ')')
497 if i < 0 {
498 return nil, fmt.Errorf("Unmatched '(' for pseudo class %s", pseudoName)
499 } else if i != len(nthString)-1 {
500 return nil, fmt.Errorf("%s(n) must end selector", pseudoName)
501 }
502 number := nthString[:i]
503
504 // Check if the number is 'odd' or 'even'
505 oddOrEven := -1
506 switch number {
507 case "odd":
508 oddOrEven = 1
509 case "even":
510 oddOrEven = 0
511 }
512 if oddOrEven > -1 {
513 return func(n *html.Node) bool {
514 return n.Type == html.ElementNode && countNth(n)%2 == oddOrEven
515 }, nil
516 }
517 // Check against '3n+4' pattern
518 r := regexp.MustCompile(`([0-9]+)n[ ]?\+[ ]?([0-9])`)
519 subMatch := r.FindAllStringSubmatch(number, -1)
520 if len(subMatch) == 1 && len(subMatch[0]) == 3 {
521 cycle, _ := strconv.Atoi(subMatch[0][1])
522 offset, _ := strconv.Atoi(subMatch[0][2])
523 return func(n *html.Node) bool {
524 return n.Type == html.ElementNode && countNth(n)%cycle == offset
525 }, nil
526 }
527 // check against 'n+2' pattern
528 r = regexp.MustCompile(`n[ ]?\+[ ]?([0-9])`)
529 subMatch = r.FindAllStringSubmatch(number, -1)
530 if len(subMatch) == 1 && len(subMatch[0]) == 2 {
531 offset, _ := strconv.Atoi(subMatch[0][1])
532 return func(n *html.Node) bool {
533 return n.Type == html.ElementNode && countNth(n) >= offset
534 }, nil
535 }
536 // the only other option is a numeric value
537 nth, err := strconv.Atoi(nthString[:i])
538 if err != nil {
539 return nil, err
540 } else if nth <= 0 {
541 return nil, fmt.Errorf("Argument to '%s' must be greater than 0", pseudoName)
542 }
543 return func(n *html.Node) bool {
544 return n.Type == html.ElementNode && countNth(n) == nth
545 }, nil
546 }
547
548 // Parse a :contains("") selector
549 // expects the input to be everything after the open parenthesis
550 // e.g. for `contains("Help")` the argument would be `"Help")`
551 func parseContainsPseudo(cmd string) (PseudoClass, error) {
552 var s scanner.Scanner
553 s.Init(strings.NewReader(cmd))
554 switch s.Next() {
555 case '"':
556 default:
557 return nil, fmt.Errorf("Malformed 'contains(\"\")' selector")
558 }
559 textToContain := bytes.NewBuffer([]byte{})
560 for {
561 r := s.Next()
562 switch r {
563 case '"':
564 // ')' then EOF must follow '"'
565 if s.Next() != ')' {
566 return nil, fmt.Errorf("Malformed 'contains(\"\")' selector")
567 }
568 if s.Next() != scanner.EOF {
569 return nil, fmt.Errorf("'contains(\"\")' must end selector")
570 }
571 text := textToContain.String()
572 contains := func(node *html.Node) bool {
573 for c := node.FirstChild; c != nil; c = c.NextSibling {
574 if c.Type == html.TextNode {
575 if strings.Contains(c.Data, text) {
576 return true
577 }
578 }
579 }
580 return false
581 }
582 return contains, nil
583 case '\\':
584 s.Next()
585 case scanner.EOF:
586 return nil, fmt.Errorf("Malformed 'contains(\"\")' selector")
587 default:
588 if _, err := textToContain.WriteRune(r); err != nil {
589 return nil, err
590 }
591 }
592 }
593 }
594
595 // Parse a :not(selector) selector
596 // expects the input to be everything after the open parenthesis
597 // e.g. for `not(div#id)` the argument would be `div#id)`
598 func parseNotPseudo(cmd string) (PseudoClass, error) {
599 if len(cmd) < 2 {
600 return nil, fmt.Errorf("malformed ':not' selector")
601 }
602 endQuote, cmd := cmd[len(cmd)-1], cmd[:len(cmd)-1]
603 selector, err := ParseSelector(cmd)
604 if err != nil {
605 return nil, err
606 }
607 if endQuote != ')' {
608 return nil, fmt.Errorf("unmatched '('")
609 }
610 return func(n *html.Node) bool {
611 return !selector.Match(n)
612 }, nil
613 }
614
615 // Parse a :parent-of(selector) selector
616 // expects the input to be everything after the open parenthesis
617 // e.g. for `parent-of(div#id)` the argument would be `div#id)`
618 func parseParentOfPseudo(cmd string) (PseudoClass, error) {
619 if len(cmd) < 2 {
620 return nil, fmt.Errorf("malformed ':parent-of' selector")
621 }
622 endQuote, cmd := cmd[len(cmd)-1], cmd[:len(cmd)-1]
623 selector, err := ParseSelector(cmd)
624 if err != nil {
625 return nil, err
626 }
627 if endQuote != ')' {
628 return nil, fmt.Errorf("unmatched '('")
629 }
630 return func(n *html.Node) bool {
631 for c := n.FirstChild; c != nil; c = c.NextSibling {
632 if c.Type == html.ElementNode && selector.Match(c) {
633 return true
634 }
635 }
636 return false
637 }, nil
638 }