Class: Itonoko::CSS::Matcher

Inherits:
Object
  • Object
show all
Defined in:
lib/itonoko/css/matcher.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(context_node) ⇒ Matcher

Returns a new instance of Matcher.



18
19
20
# File 'lib/itonoko/css/matcher.rb', line 18

def initialize(context_node)
  @context = context_node
end

Class Method Details

.match(context_node, selector_str) ⇒ Object



9
10
11
# File 'lib/itonoko/css/matcher.rb', line 9

def self.match(context_node, selector_str)
  new(context_node).match(selector_str)
end

.matches_selector?(node, selector_str) ⇒ Boolean

Returns:

  • (Boolean)


13
14
15
16
# File 'lib/itonoko/css/matcher.rb', line 13

def self.matches_selector?(node, selector_str)
  groups = Parser.new.parse(selector_str)
  groups.any? { |group| new(nil).matches_group?(node, group) }
end

Instance Method Details

#match(selector_str) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/itonoko/css/matcher.rb', line 22

def match(selector_str)
  groups = Parser.new.parse(selector_str)
  doc    = document_of(@context)
  seen   = {}
  result = []

  all_elements(@context).each do |node|
    next if seen[node.object_id]
    if groups.any? { |group| matches_group?(node, group) }
      seen[node.object_id] = true
      result << node
    end
  end

  XML::NodeSet.new(doc, result)
end

#matches_group?(node, steps) ⇒ Boolean

Returns true if node matches the given selector group (list of Steps).

Returns:

  • (Boolean)


40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/itonoko/css/matcher.rb', line 40

def matches_group?(node, steps)
  return false if steps.empty?

  # The rightmost step must match the node itself.
  last_step = steps.last
  return false unless matches_simple?(node, last_step.simple)

  # Walk leftward through the remaining steps.
  remaining = steps[0..-2]
  return true if remaining.empty?

  prev_step = remaining.last
  combinator = last_step.combinator || " "

  candidate_ancestors = candidates_for_combinator(node, combinator)
  candidate_ancestors.any? do |candidate|
    matches_group?(candidate, remaining)
  end
end