class Ferrum::Mouse

Constants

CLICK_WAIT
VALID_BUTTONS

Public Class Methods

new(page) click to toggle source
# File lib/ferrum/mouse.rb, line 8
def initialize(page)
  @page = page
  @x = @y = 0
end

Public Instance Methods

click(x:, y:, delay: 0, wait: CLICK_WAIT, **options) click to toggle source
# File lib/ferrum/mouse.rb, line 17
def click(x:, y:, delay: 0, wait: CLICK_WAIT, **options)
  move(x: x, y: y)
  down(**options)
  sleep(delay)
  # Potential wait because if some network event is triggered then we have
  # to wait until it's over and frame is loaded or failed to load.
  up(wait: wait, **options)
  self
end
down(**options) click to toggle source
# File lib/ferrum/mouse.rb, line 27
def down(**options)
  tap { mouse_event(type: "mousePressed", **options) }
end
move(x:, y:, steps: 1) click to toggle source
# File lib/ferrum/mouse.rb, line 35
def move(x:, y:, steps: 1)
  from_x, from_y = @x, @y
  @x, @y = x, y

  steps.times do |i|
    new_x = from_x + (@x - from_x) * ((i + 1) / steps.to_f)
    new_y = from_y + (@y - from_y) * ((i + 1) / steps.to_f)

    @page.command("Input.dispatchMouseEvent",
                  slowmoable: true,
                  type: "mouseMoved",
                  x: new_x.to_i,
                  y: new_y.to_i)
  end

  self
end
scroll_to(top, left) click to toggle source
# File lib/ferrum/mouse.rb, line 13
def scroll_to(top, left)
  tap { @page.execute("window.scrollTo(#{top}, #{left})") }
end
up(**options) click to toggle source
# File lib/ferrum/mouse.rb, line 31
def up(**options)
  tap { mouse_event(type: "mouseReleased", **options) }
end

Private Instance Methods

mouse_event(type:, button: :left, count: 1, modifiers: nil, wait: 0) click to toggle source
# File lib/ferrum/mouse.rb, line 55
def mouse_event(type:, button: :left, count: 1, modifiers: nil, wait: 0)
  button = validate_button(button)
  options = { x: @x, y: @y, type: type, button: button, clickCount: count }
  options.merge!(modifiers: modifiers) if modifiers
  @page.command("Input.dispatchMouseEvent", wait: wait, slowmoable: true, **options)
end
validate_button(button) click to toggle source
# File lib/ferrum/mouse.rb, line 62
def validate_button(button)
  button = button.to_s
  unless VALID_BUTTONS.include?(button)
    raise "Invalid button: #{button}"
  end
  button
end