Skip to content

Commit

Permalink
Split into a few methods
Browse files Browse the repository at this point in the history
  • Loading branch information
route committed Jul 2, 2020
1 parent 55424f8 commit bfcfe08
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 31 deletions.
7 changes: 6 additions & 1 deletion lib/ferrum.rb
Expand Up @@ -8,7 +8,6 @@ class Error < StandardError; end
class NoSuchPageError < Error; end
class NoSuchTargetError < Error; end
class NotImplementedError < Error; end
class NodeIsMovingError < Error; end

class StatusError < Error
def initialize(url, pendings = [])
Expand Down Expand Up @@ -49,6 +48,12 @@ def initialize(message = "Browser is dead or given window is closed")
end
end

class NodeIsMovingError < Error
def initialize(node)
super("Node `#{node.inspect}` that you're trying to click is moving, hence we cannot")
end
end

class BrowserError < Error
attr_reader :response

Expand Down
66 changes: 36 additions & 30 deletions lib/ferrum/node.rb
Expand Up @@ -124,44 +124,31 @@ def inspect
end

def find_position(x: nil, y: nil, position: :top)
offset_x, offset_y = x, y
quads = get_node_quads
x = y = nil

if offset_x && offset_y && position == :top
point = quads.first
x = point[:x] + offset_x.to_i
y = point[:y] + offset_y.to_i
else
x, y = quads.inject([0, 0]) do |memo, point|
[memo[0] + point[:x],
memo[1] + point[:y]]
end

x = x / 4
y = y / 4
end

if offset_x && offset_y && position == :center
x = x + offset_x.to_i
y = y + offset_y.to_i
end

[x, y]
quads = node_quads(x, y)
get_position(quads, x, y)
end

private

def get_node_quads
def get_content_quads
result = page.command("DOM.getContentQuads", nodeId: node_id)
raise "Node is either not visible or not an HTMLElement" if result["quads"].size == 0
result
end

def node_quads(x, y)
prev_result = get_content_quads

result = Ferrum.with_attempts(errors: NodeIsMovingError, max: MOVING_ATTEMPTS, wait: 0) do
sleep(MOVING_WAIT)
current_result = get_content_quads

if current_result["quads"] != prev_result["quads"]
prev_pos = get_position(prev_result, x, y)
current_pos = get_position(current_result, x, y)

prev_result = current_result
raise NodeIsMovingError
raise NodeIsMovingError.new(self, prev_pos, current_pos)
end

current_result
Expand All @@ -176,10 +163,29 @@ def get_node_quads
end.first
end

def get_content_quads
result = page.command("DOM.getContentQuads", nodeId: node_id)
raise "Node is either not visible or not an HTMLElement" if result["quads"].size == 0
result
def get_position(quads, offset_x, offset_y)
x = y = nil

if offset_x && offset_y && position == :top
point = quads.first
x = point[:x] + offset_x.to_i
y = point[:y] + offset_y.to_i
else
x, y = quads.inject([0, 0]) do |memo, point|
[memo[0] + point[:x],
memo[1] + point[:y]]
end

x = x / 4
y = y / 4
end

if offset_x && offset_y && position == :center
x = x + offset_x.to_i
y = y + offset_y.to_i
end

[x, y]
end
end
end

0 comments on commit bfcfe08

Please sign in to comment.