123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833 |
- package cascadia
- import (
- "bytes"
- "fmt"
- "regexp"
- "strings"
- "golang.org/x/net/html"
- )
- type Matcher interface {
- Match(n *html.Node) bool
- }
- type Sel interface {
- Matcher
- Specificity() Specificity
- }
- func Parse(sel string) (Sel, error) {
- p := &parser{s: sel}
- compiled, err := p.parseSelector()
- if err != nil {
- return nil, err
- }
- if p.i < len(sel) {
- return nil, fmt.Errorf("parsing %q: %d bytes left over", sel, len(sel)-p.i)
- }
- return compiled, nil
- }
- func ParseGroup(sel string) (SelectorGroup, error) {
- p := &parser{s: sel}
- compiled, err := p.parseSelectorGroup()
- if err != nil {
- return nil, err
- }
- if p.i < len(sel) {
- return nil, fmt.Errorf("parsing %q: %d bytes left over", sel, len(sel)-p.i)
- }
- return compiled, nil
- }
- type Selector func(*html.Node) bool
- func Compile(sel string) (Selector, error) {
- compiled, err := ParseGroup(sel)
- if err != nil {
- return nil, err
- }
- return Selector(compiled.Match), nil
- }
- func MustCompile(sel string) Selector {
- compiled, err := Compile(sel)
- if err != nil {
- panic(err)
- }
- return compiled
- }
- func (s Selector) MatchAll(n *html.Node) []*html.Node {
- return s.matchAllInto(n, nil)
- }
- func (s Selector) matchAllInto(n *html.Node, storage []*html.Node) []*html.Node {
- if s(n) {
- storage = append(storage, n)
- }
- for child := n.FirstChild; child != nil; child = child.NextSibling {
- storage = s.matchAllInto(child, storage)
- }
- return storage
- }
- func queryInto(n *html.Node, m Matcher, storage []*html.Node) []*html.Node {
- for child := n.FirstChild; child != nil; child = child.NextSibling {
- if m.Match(child) {
- storage = append(storage, child)
- }
- storage = queryInto(child, m, storage)
- }
- return storage
- }
- func QueryAll(n *html.Node, m Matcher) []*html.Node {
- return queryInto(n, m, nil)
- }
- func (s Selector) Match(n *html.Node) bool {
- return s(n)
- }
- func (s Selector) MatchFirst(n *html.Node) *html.Node {
- if s.Match(n) {
- return n
- }
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- m := s.MatchFirst(c)
- if m != nil {
- return m
- }
- }
- return nil
- }
- func Query(n *html.Node, m Matcher) *html.Node {
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- if m.Match(c) {
- return c
- }
- if matched := Query(c, m); matched != nil {
- return matched
- }
- }
- return nil
- }
- func (s Selector) Filter(nodes []*html.Node) (result []*html.Node) {
- for _, n := range nodes {
- if s(n) {
- result = append(result, n)
- }
- }
- return result
- }
- func Filter(nodes []*html.Node, m Matcher) (result []*html.Node) {
- for _, n := range nodes {
- if m.Match(n) {
- result = append(result, n)
- }
- }
- return result
- }
- type tagSelector struct {
- tag string
- }
- func (t tagSelector) Match(n *html.Node) bool {
- return n.Type == html.ElementNode && n.Data == t.tag
- }
- func (c tagSelector) Specificity() Specificity {
- return Specificity{0, 0, 1}
- }
- type classSelector struct {
- class string
- }
- func (t classSelector) Match(n *html.Node) bool {
- return matchAttribute(n, "class", func(s string) bool {
- return matchInclude(t.class, s)
- })
- }
- func (c classSelector) Specificity() Specificity {
- return Specificity{0, 1, 0}
- }
- type idSelector struct {
- id string
- }
- func (t idSelector) Match(n *html.Node) bool {
- return matchAttribute(n, "id", func(s string) bool {
- return s == t.id
- })
- }
- func (c idSelector) Specificity() Specificity {
- return Specificity{1, 0, 0}
- }
- type attrSelector struct {
- key, val, operation string
- regexp *regexp.Regexp
- }
- func (t attrSelector) Match(n *html.Node) bool {
- switch t.operation {
- case "":
- return matchAttribute(n, t.key, func(string) bool { return true })
- case "=":
- return matchAttribute(n, t.key, func(s string) bool { return s == t.val })
- case "!=":
- return attributeNotEqualMatch(t.key, t.val, n)
- case "~=":
-
- return matchAttribute(n, t.key, func(s string) bool { return matchInclude(t.val, s) })
- case "|=":
- return attributeDashMatch(t.key, t.val, n)
- case "^=":
- return attributePrefixMatch(t.key, t.val, n)
- case "$=":
- return attributeSuffixMatch(t.key, t.val, n)
- case "*=":
- return attributeSubstringMatch(t.key, t.val, n)
- case "#=":
- return attributeRegexMatch(t.key, t.regexp, n)
- default:
- panic(fmt.Sprintf("unsuported operation : %s", t.operation))
- }
- }
- func matchAttribute(n *html.Node, key string, f func(string) bool) bool {
- if n.Type != html.ElementNode {
- return false
- }
- for _, a := range n.Attr {
- if a.Key == key && f(a.Val) {
- return true
- }
- }
- return false
- }
- func attributeNotEqualMatch(key, val string, n *html.Node) bool {
- if n.Type != html.ElementNode {
- return false
- }
- for _, a := range n.Attr {
- if a.Key == key && a.Val == val {
- return false
- }
- }
- return true
- }
- func matchInclude(val, s string) bool {
- for s != "" {
- i := strings.IndexAny(s, " \t\r\n\f")
- if i == -1 {
- return s == val
- }
- if s[:i] == val {
- return true
- }
- s = s[i+1:]
- }
- return false
- }
- func attributeDashMatch(key, val string, n *html.Node) bool {
- return matchAttribute(n, key,
- func(s string) bool {
- if s == val {
- return true
- }
- if len(s) <= len(val) {
- return false
- }
- if s[:len(val)] == val && s[len(val)] == '-' {
- return true
- }
- return false
- })
- }
- func attributePrefixMatch(key, val string, n *html.Node) bool {
- return matchAttribute(n, key,
- func(s string) bool {
- if strings.TrimSpace(s) == "" {
- return false
- }
- return strings.HasPrefix(s, val)
- })
- }
- func attributeSuffixMatch(key, val string, n *html.Node) bool {
- return matchAttribute(n, key,
- func(s string) bool {
- if strings.TrimSpace(s) == "" {
- return false
- }
- return strings.HasSuffix(s, val)
- })
- }
- func attributeSubstringMatch(key, val string, n *html.Node) bool {
- return matchAttribute(n, key,
- func(s string) bool {
- if strings.TrimSpace(s) == "" {
- return false
- }
- return strings.Contains(s, val)
- })
- }
- func attributeRegexMatch(key string, rx *regexp.Regexp, n *html.Node) bool {
- return matchAttribute(n, key,
- func(s string) bool {
- return rx.MatchString(s)
- })
- }
- func (c attrSelector) Specificity() Specificity {
- return Specificity{0, 1, 0}
- }
- type relativePseudoClassSelector struct {
- name string
- match SelectorGroup
- }
- func (s relativePseudoClassSelector) Match(n *html.Node) bool {
- if n.Type != html.ElementNode {
- return false
- }
- switch s.name {
- case "not":
-
- return !s.match.Match(n)
- case "has":
-
- return hasDescendantMatch(n, s.match)
- case "haschild":
-
- return hasChildMatch(n, s.match)
- default:
- panic(fmt.Sprintf("unsupported relative pseudo class selector : %s", s.name))
- }
- }
- func hasChildMatch(n *html.Node, a Matcher) bool {
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- if a.Match(c) {
- return true
- }
- }
- return false
- }
- func hasDescendantMatch(n *html.Node, a Matcher) bool {
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- if a.Match(c) || (c.Type == html.ElementNode && hasDescendantMatch(c, a)) {
- return true
- }
- }
- return false
- }
- func (s relativePseudoClassSelector) Specificity() Specificity {
- var max Specificity
- for _, sel := range s.match {
- newSpe := sel.Specificity()
- if max.Less(newSpe) {
- max = newSpe
- }
- }
- return max
- }
- type containsPseudoClassSelector struct {
- own bool
- value string
- }
- func (s containsPseudoClassSelector) Match(n *html.Node) bool {
- var text string
- if s.own {
-
- text = strings.ToLower(nodeOwnText(n))
- } else {
-
- text = strings.ToLower(nodeText(n))
- }
- return strings.Contains(text, s.value)
- }
- func (s containsPseudoClassSelector) Specificity() Specificity {
- return Specificity{0, 1, 0}
- }
- type regexpPseudoClassSelector struct {
- own bool
- regexp *regexp.Regexp
- }
- func (s regexpPseudoClassSelector) Match(n *html.Node) bool {
- var text string
- if s.own {
-
- text = nodeOwnText(n)
- } else {
-
- text = nodeText(n)
- }
- return s.regexp.MatchString(text)
- }
- func writeNodeText(n *html.Node, b *bytes.Buffer) {
- switch n.Type {
- case html.TextNode:
- b.WriteString(n.Data)
- case html.ElementNode:
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- writeNodeText(c, b)
- }
- }
- }
- func nodeText(n *html.Node) string {
- var b bytes.Buffer
- writeNodeText(n, &b)
- return b.String()
- }
- func nodeOwnText(n *html.Node) string {
- var b bytes.Buffer
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- if c.Type == html.TextNode {
- b.WriteString(c.Data)
- }
- }
- return b.String()
- }
- func (s regexpPseudoClassSelector) Specificity() Specificity {
- return Specificity{0, 1, 0}
- }
- type nthPseudoClassSelector struct {
- a, b int
- last, ofType bool
- }
- func (s nthPseudoClassSelector) Match(n *html.Node) bool {
- if s.a == 0 {
- if s.last {
- return simpleNthLastChildMatch(s.b, s.ofType, n)
- } else {
- return simpleNthChildMatch(s.b, s.ofType, n)
- }
- }
- return nthChildMatch(s.a, s.b, s.last, s.ofType, n)
- }
- func nthChildMatch(a, b int, last, ofType bool, n *html.Node) bool {
- if n.Type != html.ElementNode {
- return false
- }
- parent := n.Parent
- if parent == nil {
- return false
- }
- if parent.Type == html.DocumentNode {
- return false
- }
- i := -1
- count := 0
- for c := parent.FirstChild; c != nil; c = c.NextSibling {
- if (c.Type != html.ElementNode) || (ofType && c.Data != n.Data) {
- continue
- }
- count++
- if c == n {
- i = count
- if !last {
- break
- }
- }
- }
- if i == -1 {
-
- return false
- }
- if last {
- i = count - i + 1
- }
- i -= b
- if a == 0 {
- return i == 0
- }
- return i%a == 0 && i/a >= 0
- }
- func simpleNthChildMatch(b int, ofType bool, n *html.Node) bool {
- if n.Type != html.ElementNode {
- return false
- }
- parent := n.Parent
- if parent == nil {
- return false
- }
- if parent.Type == html.DocumentNode {
- return false
- }
- count := 0
- for c := parent.FirstChild; c != nil; c = c.NextSibling {
- if c.Type != html.ElementNode || (ofType && c.Data != n.Data) {
- continue
- }
- count++
- if c == n {
- return count == b
- }
- if count >= b {
- return false
- }
- }
- return false
- }
- func simpleNthLastChildMatch(b int, ofType bool, n *html.Node) bool {
- if n.Type != html.ElementNode {
- return false
- }
- parent := n.Parent
- if parent == nil {
- return false
- }
- if parent.Type == html.DocumentNode {
- return false
- }
- count := 0
- for c := parent.LastChild; c != nil; c = c.PrevSibling {
- if c.Type != html.ElementNode || (ofType && c.Data != n.Data) {
- continue
- }
- count++
- if c == n {
- return count == b
- }
- if count >= b {
- return false
- }
- }
- return false
- }
- func (s nthPseudoClassSelector) Specificity() Specificity {
- return Specificity{0, 1, 0}
- }
- type onlyChildPseudoClassSelector struct {
- ofType bool
- }
- func (s onlyChildPseudoClassSelector) Match(n *html.Node) bool {
- if n.Type != html.ElementNode {
- return false
- }
- parent := n.Parent
- if parent == nil {
- return false
- }
- if parent.Type == html.DocumentNode {
- return false
- }
- count := 0
- for c := parent.FirstChild; c != nil; c = c.NextSibling {
- if (c.Type != html.ElementNode) || (s.ofType && c.Data != n.Data) {
- continue
- }
- count++
- if count > 1 {
- return false
- }
- }
- return count == 1
- }
- func (s onlyChildPseudoClassSelector) Specificity() Specificity {
- return Specificity{0, 1, 0}
- }
- type inputPseudoClassSelector struct{}
- func (s inputPseudoClassSelector) Match(n *html.Node) bool {
- return n.Type == html.ElementNode && (n.Data == "input" || n.Data == "select" || n.Data == "textarea" || n.Data == "button")
- }
- func (s inputPseudoClassSelector) Specificity() Specificity {
- return Specificity{0, 1, 0}
- }
- type emptyElementPseudoClassSelector struct{}
- func (s emptyElementPseudoClassSelector) Match(n *html.Node) bool {
- if n.Type != html.ElementNode {
- return false
- }
- for c := n.FirstChild; c != nil; c = c.NextSibling {
- switch c.Type {
- case html.ElementNode, html.TextNode:
- return false
- }
- }
- return true
- }
- func (s emptyElementPseudoClassSelector) Specificity() Specificity {
- return Specificity{0, 1, 0}
- }
- type rootPseudoClassSelector struct{}
- func (s rootPseudoClassSelector) Match(n *html.Node) bool {
- if n.Type != html.ElementNode {
- return false
- }
- if n.Parent == nil {
- return false
- }
- return n.Parent.Type == html.DocumentNode
- }
- func (s rootPseudoClassSelector) Specificity() Specificity {
- return Specificity{0, 1, 0}
- }
- type compoundSelector struct {
- selectors []Sel
- }
- func (t compoundSelector) Match(n *html.Node) bool {
- if len(t.selectors) == 0 {
- return n.Type == html.ElementNode
- }
- for _, sel := range t.selectors {
- if !sel.Match(n) {
- return false
- }
- }
- return true
- }
- func (s compoundSelector) Specificity() Specificity {
- var out Specificity
- for _, sel := range s.selectors {
- out = out.Add(sel.Specificity())
- }
- return out
- }
- type combinedSelector struct {
- first Sel
- combinator byte
- second Sel
- }
- func (t combinedSelector) Match(n *html.Node) bool {
- if t.first == nil {
- return false
- }
- switch t.combinator {
- case 0:
- return t.first.Match(n)
- case ' ':
- return descendantMatch(t.first, t.second, n)
- case '>':
- return childMatch(t.first, t.second, n)
- case '+':
- return siblingMatch(t.first, t.second, true, n)
- case '~':
- return siblingMatch(t.first, t.second, false, n)
- default:
- panic("unknown combinator")
- }
- }
- func descendantMatch(a, d Matcher, n *html.Node) bool {
- if !d.Match(n) {
- return false
- }
- for p := n.Parent; p != nil; p = p.Parent {
- if a.Match(p) {
- return true
- }
- }
- return false
- }
- func childMatch(a, d Matcher, n *html.Node) bool {
- return d.Match(n) && n.Parent != nil && a.Match(n.Parent)
- }
- func siblingMatch(s1, s2 Matcher, adjacent bool, n *html.Node) bool {
- if !s2.Match(n) {
- return false
- }
- if adjacent {
- for n = n.PrevSibling; n != nil; n = n.PrevSibling {
- if n.Type == html.TextNode || n.Type == html.CommentNode {
- continue
- }
- return s1.Match(n)
- }
- return false
- }
-
- for c := n.PrevSibling; c != nil; c = c.PrevSibling {
- if s1.Match(c) {
- return true
- }
- }
- return false
- }
- func (s combinedSelector) Specificity() Specificity {
- spec := s.first.Specificity()
- if s.second != nil {
- spec = spec.Add(s.second.Specificity())
- }
- return spec
- }
- type SelectorGroup []Sel
- func (s SelectorGroup) Match(n *html.Node) bool {
- for _, sel := range s {
- if sel.Match(n) {
- return true
- }
- }
- return false
- }
|