cuprite 0.20.1 → 0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +18 -16
  3. data/lib/capybara/cuprite/browser/extensions.rb +25 -28
  4. data/lib/capybara/cuprite/browser/settings.rb +102 -0
  5. data/lib/capybara/cuprite/browser.rb +47 -13
  6. data/lib/capybara/cuprite/context.rb +26 -0
  7. data/lib/capybara/cuprite/devices.rb +8 -0
  8. data/lib/capybara/cuprite/driver/extensions.rb +4 -0
  9. data/lib/capybara/cuprite/driver.rb +189 -28
  10. data/lib/capybara/cuprite/errors.rb +70 -1
  11. data/lib/capybara/cuprite/finder/hints.rb +51 -0
  12. data/lib/capybara/cuprite/finder.rb +18 -3
  13. data/lib/capybara/cuprite/javascripts/index.js +123 -58
  14. data/lib/capybara/cuprite/node/extensions.rb +13 -3
  15. data/lib/capybara/cuprite/node/typing.rb +75 -0
  16. data/lib/capybara/cuprite/node.rb +193 -44
  17. data/lib/capybara/cuprite/page/frames.rb +5 -7
  18. data/lib/capybara/cuprite/page/modals.rb +51 -35
  19. data/lib/capybara/cuprite/page.rb +49 -8
  20. data/lib/capybara/cuprite/version.rb +3 -1
  21. data/lib/capybara/cuprite.rb +6 -2
  22. data/sig/capybara/cuprite/browser/extensions.rbs +27 -0
  23. data/sig/capybara/cuprite/browser/settings.rbs +42 -0
  24. data/sig/capybara/cuprite/browser.rbs +41 -0
  25. data/sig/capybara/cuprite/context.rbs +7 -0
  26. data/sig/capybara/cuprite/devices.rbs +19 -0
  27. data/sig/capybara/cuprite/driver/extensions.rbs +9 -0
  28. data/sig/capybara/cuprite/driver.rbs +123 -0
  29. data/sig/capybara/cuprite/errors.rbs +62 -0
  30. data/sig/capybara/cuprite/finder/hints.rbs +28 -0
  31. data/sig/capybara/cuprite/finder.rbs +7 -0
  32. data/sig/capybara/cuprite/node/extensions.rbs +9 -0
  33. data/sig/capybara/cuprite/node/typing.rbs +30 -0
  34. data/sig/capybara/cuprite/node.rbs +112 -0
  35. data/sig/capybara/cuprite/page/frames.rbs +37 -0
  36. data/sig/capybara/cuprite/page/modals.rbs +39 -0
  37. data/sig/capybara/cuprite/page.rbs +26 -0
  38. data/sig/capybara/cuprite/version.rbs +5 -0
  39. metadata +24 -8
  40. data/lib/capybara/cuprite/browser/deprecations.rb +0 -26
  41. data/lib/capybara/cuprite/deprecation.rb +0 -13
  42. data/lib/capybara/cuprite/driver/deprecations.rb +0 -198
  43. data/lib/capybara/cuprite/node/deprecations.rb +0 -43
  44. data/lib/capybara/cuprite/options.rb +0 -33
@@ -1,46 +1,75 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "capybara/cuprite/finder"
4
- require "capybara/cuprite/node/deprecations"
5
4
  require "capybara/cuprite/node/extensions"
5
+ require "capybara/cuprite/node/typing"
6
6
 
7
7
  module Capybara
8
8
  module Cuprite
9
+ # An element found by the {Driver}, which Capybara wraps in `Capybara::Node::Element`.
9
10
  class Node < Capybara::Driver::Node
11
+ # @return [Ferrum::Node] the Ferrum node, for what Capybara doesn't cover
10
12
  attr_reader :node
11
13
 
12
- include Deprecations
13
14
  include Extensions
15
+ include Typing
14
16
 
17
+ # Capybara's names of modifier keys mapped to Ferrum's.
18
+ # @api private
15
19
  DRAG_MODIFIER_ALIASES = { control: :ctrl, command: :meta, cmd: :meta }.freeze
20
+ # The script that drags with HTML5 drag and drop events.
21
+ # @api private
16
22
  DRAG_HTML5_JS = File.read(File.expand_path("javascripts/drag.js", __dir__))
17
- TRIGGER_CLICK_WAIT = ENV.fetch("CUPRITE_TRIGGER_CLICK_WAIT", 0.1).to_f
18
-
19
- def initialize(driver, node)
20
- super(driver, self)
23
+ # @param driver [Driver]
24
+ # @param node [Ferrum::Node]
25
+ # @param initial_cache [Hash] what the finder already knows about the element, see Capybara's finder hints
26
+ def initialize(driver, node, initial_cache = {})
27
+ super(driver, self, initial_cache)
21
28
  @node = node
22
29
  end
23
30
 
24
- def find_xpath(selector)
25
- find(:xpath, selector)
31
+ # @param selector [String]
32
+ # @param hints [Hash] Capybara's finder hints
33
+ # @return [Array<Node>] the descendants matching the XPath
34
+ # @raise [InvalidSelector]
35
+ # @raise [ObsoleteNode] when the element is no longer in the DOM
36
+ def find_xpath(selector, **hints)
37
+ find(:xpath, selector, **hints)
26
38
  end
27
39
 
28
- def find_css(selector)
29
- find(:css, selector)
40
+ # @param selector [String]
41
+ # @param hints [Hash] Capybara's finder hints
42
+ # @return [Array<Node>] the descendants matching the CSS selector
43
+ # @raise [InvalidSelector]
44
+ # @raise [ObsoleteNode] when the element is no longer in the DOM
45
+ def find_css(selector, **hints)
46
+ find(:css, selector, **hints)
30
47
  end
31
48
 
49
+ # A text in the initial cache comes only with a node that can't match its query's text, which
50
+ # Capybara reads to filter it out and to describe the failure, and never hands to the caller.
51
+ #
52
+ # @return [String] all the text of the element, visible or not, with whitespace normalized
32
53
  def all_text
33
- filter_text(command { node.text })
54
+ filter_text(initial_cache.fetch(:all_text) { command { node.text } })
34
55
  end
35
56
 
57
+ # @return [String] the text of the element a user can see
58
+ # @raise [ObsoleteNode] when the element is no longer in the DOM
36
59
  def visible_text
37
- command(:visibleText).to_s
38
- .gsub(/\A[[:space:]&&[^\u00a0]]+/, "")
39
- .gsub(/[[:space:]&&[^\u00a0]]+\z/, "")
40
- .gsub(/\n+/, "\n")
41
- .tr("\u00a0", " ")
60
+ text = initial_cache.fetch(:visible_text) { command(:visibleText) }
61
+ text.to_s
62
+ .gsub(/\A[[:space:]&&[^\u00a0]]+/, "")
63
+ .gsub(/[[:space:]&&[^\u00a0]]+\z/, "")
64
+ .gsub(/\n+/, "\n")
65
+ .tr("\u00a0", " ")
42
66
  end
43
67
 
68
+ # Reads a property of the element, or the attribute when the property isn't a scalar. For `src` of an image
69
+ # and `href` of a link it's the resolved property, if the attribute is present.
70
+ #
71
+ # @param name [String, Symbol]
72
+ # @return [String, Numeric, Boolean, nil]
44
73
  def [](name)
45
74
  # Although the attribute matters, the property is consistent. Return that in
46
75
  # preference to the attribute for links and images.
@@ -56,15 +85,39 @@ module Capybara
56
85
  end
57
86
  end
58
87
 
88
+ # @return [String, Array<String>, nil] the value of a form field, every selected one for a multiple select
89
+ # @raise [ObsoleteNode] when the element is no longer in the DOM
59
90
  def value
60
91
  command(:value)
61
92
  end
62
93
 
94
+ # Reads the computed styles of the node. The ones a `:style` filter cached aren't used, they may be out of date.
95
+ #
96
+ # @param styles [Array<String>] the CSS property names
97
+ # @return [Hash{String => String}] the computed value of each property
98
+ def style(styles)
99
+ command { node.evaluate("_cuprite.styles([this], names)", names: styles) }.transform_values(&:first)
100
+ end
101
+
102
+ # Sets the value of a form field. Text inputs and textareas are typed with real key presses.
103
+ #
104
+ # @param value [String, Array<String>, Boolean, Date, Time] the value to set
105
+ # @param options [Hash] Capybara's `fill_options`, the defaults come from `Capybara.default_set_options`. Other
106
+ # options are ignored with a warning, `rapid:` and `clear:` silently on fields other than text ones.
107
+ # @option options [Boolean, nil] :rapid `true` types the first 4 and last 3 characters and sets the middle from
108
+ # JS, `false` types every character, `nil` does it for values over 30 characters
109
+ # @option options [nil, :none, :backspace, Array] :clear `nil` replaces the value, `:none` appends to it,
110
+ # `:backspace` deletes it with Backspace first, an Array of keys is pressed before typing
111
+ # @return [void]
112
+ # @raise [ArgumentError] for an unknown `clear:` value, or an Array on a field without `multiple`
63
113
  def set(value, options = {}) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/AbcSize
64
- warn "Options passed to Node#set but Cuprite doesn't currently support any - ignoring" unless options.empty?
114
+ warn_unsupported(options)
115
+ raise ArgumentError, MULTIPLE_ERROR if value.is_a?(Array) && !multiple?
65
116
 
66
117
  if tag_name == "input"
67
118
  case self[:type]
119
+ when *TYPED_INPUTS
120
+ set_text(value.to_s, **options)
68
121
  when "radio"
69
122
  click
70
123
  when "checkbox"
@@ -95,62 +148,123 @@ module Capybara
95
148
  command(:set, value.to_s)
96
149
  end
97
150
  elsif tag_name == "textarea"
98
- command(:set, value.to_s)
151
+ set_text(value.to_s, **options)
99
152
  elsif self[:isContentEditable]
100
153
  command(:deleteText)
101
154
  click.type(value.to_s)
102
155
  end
103
156
  end
104
157
 
158
+ # Selects the option element.
159
+ #
160
+ # @return [void]
161
+ # @raise [ObsoleteNode] when the element is no longer in the DOM
105
162
  def select_option
106
163
  command(:select, true)
107
164
  end
108
165
 
166
+ # Unselects the option element.
167
+ #
168
+ # @return [void]
169
+ # @raise [Capybara::UnselectNotAllowed] for an option of a single select
170
+ # @raise [ObsoleteNode] when the element is no longer in the DOM
109
171
  def unselect_option
110
172
  command(:select, false) ||
111
173
  raise(Capybara::UnselectNotAllowed, "Cannot unselect option from single select box.")
112
174
  end
113
175
 
176
+ # @return [String] the lowercase tag name, `"ShadowRoot"` for a shadow root
114
177
  def tag_name
115
178
  @tag_name ||= node.description["shadowRootType"] ? "ShadowRoot" : node.description["nodeName"].downcase
116
179
  end
117
180
 
181
+ # @return [Boolean]
182
+ # @raise [ObsoleteNode] when the element is no longer in the DOM
118
183
  def visible?
119
184
  command(:isVisible)
120
185
  end
121
186
 
187
+ # @return [Boolean]
122
188
  def checked?
123
189
  self[:checked]
124
190
  end
125
191
 
192
+ # @return [Boolean]
126
193
  def selected?
127
194
  !!self[:selected]
128
195
  end
129
196
 
197
+ # @return [Boolean] whether the element is disabled, itself or by a disabled fieldset or optgroup
198
+ # @raise [ObsoleteNode] when the element is no longer in the DOM
130
199
  def disabled?
131
200
  command(:isDisabled)
132
201
  end
133
202
 
203
+ # Scrolls the element into view and clicks it with the mouse.
204
+ #
205
+ # @param keys [Array<Symbol>] modifier keys held during the click
206
+ # @param options [Hash]
207
+ # @option options [Integer] :x offset from the position given by `:offset`, along with `:y`
208
+ # @option options [Integer] :y offset from the position given by `:offset`, along with `:x`
209
+ # @option options [:top, :center] :offset what `:x` and `:y` are relative to, the top left by default
210
+ # @option options [Numeric] :delay seconds between pressing and releasing the button
211
+ # @return [void]
212
+ # @raise [MouseEventFailed] when another element would receive the click
213
+ # @raise [ObsoleteNode] when the element is no longer in the DOM
134
214
  def click(keys = [], **options)
135
- prepare_and_click(:left, __method__, keys, options)
215
+ prepare_and_click(__method__, keys, options)
136
216
  end
137
217
 
218
+ # Clicks the element with the right mouse button, see {#click}.
219
+ #
220
+ # @param keys [Array<Symbol>] modifier keys held during the click
221
+ # @param options [Hash] the options of {#click}
222
+ # @return [void]
223
+ # @raise [MouseEventFailed] when another element would receive the click
224
+ # @raise [ObsoleteNode] when the element is no longer in the DOM
138
225
  def right_click(keys = [], **options)
139
- prepare_and_click(:right, __method__, keys, options)
226
+ prepare_and_click(__method__, keys, options, button: :right)
140
227
  end
141
228
 
229
+ # Double-clicks the element, see {#click}.
230
+ #
231
+ # @param keys [Array<Symbol>] modifier keys held during the clicks
232
+ # @param options [Hash] the options of {#click}
233
+ # @return [void]
234
+ # @raise [MouseEventFailed] when another element would receive the click
235
+ # @raise [ObsoleteNode] when the element is no longer in the DOM
142
236
  def double_click(keys = [], **options)
143
- prepare_and_click(:double, __method__, keys, options)
237
+ prepare_and_click(__method__, keys, options, count: 2)
144
238
  end
145
239
 
240
+ # Scrolls the element into view and moves the mouse over it.
241
+ #
242
+ # @return [void]
243
+ # @raise [ObsoleteNode] when the element is no longer in the DOM
146
244
  def hover
147
245
  command do
148
246
  js(:scrollIntoViewport)
149
- x, y = find_position
247
+ x, y = pinpoint
150
248
  driver.browser.page.command("Input.dispatchMouseEvent", type: "mouseMoved", x: x, y: y)
151
249
  end
152
250
  end
153
251
 
252
+ # Drags the element onto another one, with HTML5 drag and drop events when the page uses them.
253
+ #
254
+ # @param other [Node]
255
+ # @param options [Hash]
256
+ # @option options [Integer] :x drop offset, along with `:y`
257
+ # @option options [Integer] :y drop offset, along with `:x`
258
+ # @option options [:top, :center] :offset what the drop offset is relative to, `:center` with `w3c_click_offset`,
259
+ # `:top` otherwise
260
+ # @option options [Numeric] :delay seconds to wait after pressing the button
261
+ # @option options [Integer] :steps mouse moves to reach the target, `1` by default
262
+ # @option options [Boolean] :scroll scroll the elements into view, `true` by default
263
+ # @option options [Boolean, nil] :html5 force or skip HTML5 drag and drop, detected by default
264
+ # @option options [Array<Symbol>] :drop_modifiers modifier keys held while dropping
265
+ # @return [void]
266
+ # @raise [ArgumentError] when only one of `:x` and `:y` is given
267
+ # @raise [ObsoleteNode] when the element is no longer in the DOM
154
268
  def drag_to(other, **options)
155
269
  raise ArgumentError, "You must specify both x: and y: for a drop offset" if options[:x].nil? ^ options[:y].nil?
156
270
 
@@ -162,6 +276,11 @@ module Capybara
162
276
  command { drag(other.node, modifiers, options) }
163
277
  end
164
278
 
279
+ # Drops files or strings onto the element.
280
+ #
281
+ # @param args [Array<String, Pathname>, Array<Hash{String => String}>] file paths, or MIME types mapped to data
282
+ # @return [void]
283
+ # @raise [ObsoleteNode] when the element is no longer in the DOM
165
284
  def drop(*args)
166
285
  command do
167
286
  if args[0].is_a?(String)
@@ -175,14 +294,28 @@ module Capybara
175
294
  end
176
295
  end
177
296
 
297
+ # Dispatches a DOM event on the element without moving the mouse. A `click` watches for the navigation it may
298
+ # start like a real click, for Ferrum's `FERRUM_NAVIGATION_WAIT` seconds.
299
+ #
300
+ # @param event [String, Symbol]
301
+ # @return [void]
302
+ # @raise [ObsoleteNode] when the element is no longer in the DOM
178
303
  def trigger(event)
179
304
  command do
180
- next js(:trigger, event.to_s) unless event.to_s == "click" && TRIGGER_CLICK_WAIT.positive?
305
+ wait = Ferrum::Page::NAVIGATION_WAIT
306
+ next js(:trigger, event.to_s) unless event.to_s == "click" && wait.positive?
181
307
 
182
- driver.browser.wait_for_navigation!(TRIGGER_CLICK_WAIT) { js(:trigger, "click") }
308
+ driver.browser.await_navigation!(watch: wait) { js(:trigger, "click") }
183
309
  end
184
310
  end
185
311
 
312
+ # Scrolls an element into view inside this one, or this one to a location or position.
313
+ #
314
+ # @param element [Node, nil] the element to scroll into view
315
+ # @param location [:top, :bottom, :center, nil]
316
+ # @param position [Array(Numeric, Numeric), nil] the coordinates to scroll to
317
+ # @return [self]
318
+ # @raise [ArgumentError] for an unknown location with an element
186
319
  def scroll_to(element, location, position = nil)
187
320
  if element.is_a?(Node)
188
321
  scroll_element_to_location(element, location)
@@ -194,54 +327,69 @@ module Capybara
194
327
  self
195
328
  end
196
329
 
330
+ # @param x [Numeric]
331
+ # @param y [Numeric]
332
+ # @return [void]
197
333
  def scroll_by(x, y)
198
334
  node.evaluate("this.scrollBy(x, y)", x: x, y: y)
199
335
  end
200
336
 
337
+ # @param other [Capybara::Node::Element, Node]
338
+ # @return [Boolean] whether both are the same DOM element
201
339
  def ==(other)
202
340
  node == other.native.node
203
341
  end
204
342
 
343
+ # Focuses the element, unless it already has focus, and types the keys, at the end of the value of a field.
344
+ #
345
+ # @param keys [Array<String, Symbol, Array>] text, key names and Arrays of keys pressed together
346
+ # @return [void]
347
+ # @raise [ObsoleteNode] when the element is no longer in the DOM
205
348
  def send_keys(*keys)
206
349
  keys = keys.reject { |key| key.nil? || key == "" }
207
350
  return if keys.empty?
208
351
 
209
352
  command do
210
- unless node.evaluate("_cuprite.containsSelection(this) || _cuprite.hasFocus(this)")
211
- before_click("click")
212
- node.click(mode: :left, keys: keys)
213
- end
214
-
215
- driver.browser.keyboard.type(keys)
353
+ keyboard = driver.browser.keyboard
354
+ keyboard.type(:end) if js(:focusForTyping)
355
+ keyboard.type(keys)
216
356
  end
217
357
  end
218
358
 
359
+ # @return [String] an XPath that locates the element
360
+ # @raise [ObsoleteNode] when the element is no longer in the DOM
219
361
  def path
220
362
  command(:path)
221
363
  end
222
364
 
365
+ # @return [Boolean] whether the element is out of the viewport or covered by another one
366
+ # @raise [ObsoleteNode] when the element is no longer in the DOM
223
367
  def obscured?
224
368
  command(:isObscured)
225
369
  end
226
370
 
371
+ # @return [Node, nil] the open shadow root of the element
227
372
  def shadow_root
228
373
  root = driver.browser.evaluate("node.shadowRoot", node: node)
229
374
  root && self.class.new(driver, root)
230
375
  end
231
376
 
377
+ # @return [Hash{String => Numeric}] the bounding rectangle: `x`, `y`, `width`, `height`, `top`, `right`, `bottom`,
378
+ # `left`
232
379
  def rect
233
380
  node.evaluate("this.getBoundingClientRect().toJSON()")
234
381
  end
235
382
 
383
+ # @return [String]
236
384
  def inspect
237
385
  %(#<#{self.class} @node=#{@node.inspect}>)
238
386
  end
239
387
 
240
388
  private
241
389
 
242
- def find(method, selector)
243
- command { Finder.find(driver.browser, method, selector, node) }.map do |node|
244
- self.class.new(driver, node)
390
+ def find(method, selector, **hints)
391
+ command { Finder.find(driver.browser, method, selector, node, **hints) }.map do |native, cache|
392
+ self.class.new(driver, native, cache)
245
393
  end
246
394
  end
247
395
 
@@ -253,12 +401,12 @@ module Capybara
253
401
  raise ObsoleteNode.new(self, e.response)
254
402
  end
255
403
 
256
- def prepare_and_click(mode, name, keys, options)
404
+ def prepare_and_click(name, keys, options, **click)
257
405
  delay = options[:delay].to_i
258
406
  x, y = options.values_at(:x, :y)
259
- offset = { x: x, y: y, position: options[:offset] || :top }
407
+ offset = x && y ? { x: x, y: y, position: options[:offset] || :top } : {}
260
408
  command { before_click(name, offset) }
261
- node.click(mode: mode, keys: keys, offset: offset, delay: delay)
409
+ node.click(modifiers: keys, offset: offset, delay: delay, **click)
262
410
  end
263
411
 
264
412
  def js(function, *args)
@@ -270,18 +418,19 @@ module Capybara
270
418
 
271
419
  # If offset is given it may go outside of the element and likely error
272
420
  # will be raised that we detected another element at this position.
273
- return if offset[:x] || offset[:y]
421
+ return if offset.any?
274
422
 
275
- x, y = find_position(**offset)
423
+ x, y = pinpoint
276
424
  js(:mouseEventTest, name.to_s, x, y)
277
425
  rescue Ferrum::JavaScriptError => e
278
426
  raise MouseEventFailed, e.message if e.class_name == "MouseEventFailed"
427
+ raise ObsoleteNode.new(self, e.response) if e.class_name == "ObsoleteNode"
279
428
 
280
429
  raise
281
430
  end
282
431
 
283
- def find_position(**options)
284
- node.find_position(**options)
432
+ def pinpoint(**options)
433
+ node.pinpoint(**options)
285
434
  rescue Ferrum::BrowserError => e
286
435
  raise MouseEventFailed, "MouseEventFailed: click, none, 0, 0" if e.message == "Could not compute content quads."
287
436
 
@@ -293,8 +442,8 @@ module Capybara
293
442
  delay, scroll, html5, drop_offset = options.values_at(:delay, :scroll, :html5, :drop_offset)
294
443
  browser.execute("_cuprite.dragMousedownTracker()")
295
444
 
296
- node.scroll_into_view if scroll
297
- x1, y1 = node.find_position
445
+ node.scroll if scroll
446
+ x1, y1 = node.pinpoint
298
447
 
299
448
  browser.mouse.move(x: x1, y: y1)
300
449
  browser.mouse.down
@@ -307,8 +456,8 @@ module Capybara
307
456
  driver.evaluate_async_script(DRAG_HTML5_JS, node, other, (delay || 0.05) * 1000, keys, drop_offset)
308
457
  browser.mouse.up
309
458
  else
310
- other.scroll_into_view if scroll
311
- x2, y2 = other.find_position(**drop_offset.to_h)
459
+ other.scroll if scroll
460
+ x2, y2 = other.pinpoint(**drop_offset.to_h)
312
461
 
313
462
  browser.keyboard.hold(*modifiers) { browser.mouse.move(x: x2, y: y2, steps: options[:steps]).up }
314
463
  end
@@ -5,18 +5,20 @@ require "forwardable"
5
5
  module Capybara
6
6
  module Cuprite
7
7
  class Page < Ferrum::Page
8
+ # Runs the page's DOM and JavaScript methods in the frame switched to.
9
+ # @api private
8
10
  module Frames
9
11
  extend Forwardable
10
12
 
11
- delegate %i[at_css at_xpath css xpath
12
- current_url current_title body execution_id execution_id!
13
- evaluate execute] => :active_frame
13
+ delegate %i[at_css at_xpath css xpath html execution_id execution_id! evaluate execute] => :active_frame
14
14
 
15
15
  def initialize(...)
16
16
  @frame_stack = []
17
17
  super
18
18
  end
19
19
 
20
+ # @param handle [String, :parent, :top] a frame id, or the parent or top frame
21
+ # @return [void]
20
22
  def switch_to_frame(handle)
21
23
  case handle
22
24
  when :parent
@@ -28,10 +30,6 @@ module Capybara
28
30
  end
29
31
  end
30
32
 
31
- def title
32
- active_frame.current_title
33
- end
34
-
35
33
  private
36
34
 
37
35
  def active_frame
@@ -3,67 +3,81 @@
3
3
  module Capybara
4
4
  module Cuprite
5
5
  class Page < Ferrum::Page
6
+ # Answers JavaScript dialogs as `accept_modal` and `dismiss_modal` asked, and records their messages.
7
+ # @api private
6
8
  module Modals
7
- MODAL_WAIT = ENV.fetch("CUPRITE_MODAL_WAIT", 0.05).to_f
8
-
9
9
  def initialize(...)
10
10
  @accept_modal = []
11
- @modal_messages = []
11
+ @modal_messages = Thread::Queue.new
12
12
  @modal_response = nil
13
13
  @unhandled_modal_error = nil
14
14
  super
15
15
  end
16
16
 
17
- # The `Page.javascriptDialogOpening` event is handled on Ferrum's
18
- # background CDP dispatcher thread, so raising there wouldn't reach
19
- # the caller and would permanently kill that thread instead. The
20
- # dialog is always accepted immediately from that thread, and the
21
- # error (if any) is stashed here to be raised from the main thread
22
- # the next time it makes a command round trip.
17
+ # Dialogs are handled on Ferrum's background dispatcher thread, so
18
+ # raising there wouldn't reach the caller. The dialog is answered
19
+ # from that thread, skipping the pending error check, and the error
20
+ # (if any) is stashed here to be raised from the calling thread the
21
+ # next time it makes a command round trip.
23
22
  def command(...)
23
+ return super if Thread.current[:cuprite_handling_dialog]
24
+
24
25
  raise_pending_unhandled_modal_error! { super }
25
26
  end
26
27
 
28
+ # Accepts the next dialog.
29
+ # @return [void]
27
30
  def accept_confirm
28
31
  @accept_modal << true
29
32
  end
30
33
 
34
+ # Dismisses the next dialog.
35
+ # @return [void]
31
36
  def dismiss_confirm
32
37
  @accept_modal << false
33
38
  end
34
39
 
40
+ # Accepts the next dialog with a response.
41
+ # @param modal_response [String, nil]
42
+ # @return [void]
35
43
  def accept_prompt(modal_response)
36
44
  @accept_modal << true
37
45
  @modal_response = modal_response
38
46
  end
39
47
 
48
+ # Dismisses the next dialog.
49
+ # @return [void]
40
50
  def dismiss_prompt
41
51
  @accept_modal << false
42
52
  end
43
53
 
54
+ # Waits for a dialog to have been answered.
55
+ #
56
+ # @param options [Hash] `:text` to match and `:wait` in seconds
57
+ # @return [String] the dialog's message
58
+ # @raise [Capybara::ModalNotFound] when no matching dialog was answered in time
44
59
  def find_modal(options)
45
- start = Ferrum::Utils::ElapsedTime.monotonic_time
46
60
  expect_text = options[:text]
47
61
  expect_regexp = expect_text.is_a?(Regexp) ? expect_text : Regexp.escape(expect_text.to_s)
48
62
  not_found_msg = "Unable to find modal dialog"
49
63
  not_found_msg += " with #{expect_text}" if expect_text
50
- wait = options.fetch(:wait, timeout)
64
+ deadline = monotonic_time + options.fetch(:wait, timeout)
51
65
 
52
- begin
53
- modal_text = @modal_messages.shift
54
- raise Capybara::ModalNotFound if modal_text.nil? || (expect_text && !modal_text.match(expect_regexp))
55
- rescue Capybara::ModalNotFound => e
56
- raise e, not_found_msg if Ferrum::Utils::ElapsedTime.timeout?(start, wait)
66
+ loop do
67
+ remaining = deadline - monotonic_time
68
+ raise Capybara::ModalNotFound, not_found_msg if remaining.negative?
57
69
 
58
- sleep(MODAL_WAIT)
59
- retry
70
+ modal_text = @modal_messages.pop(timeout: remaining)
71
+ return modal_text if modal_text && (!expect_text || modal_text.match?(expect_regexp))
60
72
  end
61
-
62
- modal_text
63
73
  end
64
74
 
65
75
  private
66
76
 
77
+ def monotonic_time
78
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
79
+ end
80
+
67
81
  def raise_pending_unhandled_modal_error!
68
82
  error = @unhandled_modal_error
69
83
  @unhandled_modal_error = nil
@@ -78,39 +92,41 @@ module Capybara
78
92
 
79
93
  def prepare_page
80
94
  super
81
- on("Page.javascriptDialogOpening") { |params| handle_javascript_dialog(params) }
95
+ on(:dialog) { |dialog| handle_dialog(dialog) }
82
96
  end
83
97
 
84
- def handle_javascript_dialog(params)
98
+ def handle_dialog(dialog)
85
99
  accept_modal = @accept_modal.last
86
- unhandled_modal_error = nil
87
100
 
88
101
  if [true, false].include?(accept_modal)
89
102
  @accept_modal.pop
90
- @modal_messages << params["message"]
91
- options = { accept: accept_modal }
92
- response = @modal_response || params["defaultPrompt"]
103
+ @modal_messages << dialog.message
104
+ accept = accept_modal
105
+ response = @modal_response
93
106
  else
94
- with_text = params["message"] ? "with text `#{params['message']}` " : ""
107
+ with_text = dialog.message ? "with text `#{dialog.message}` " : ""
95
108
  message = "Modal window #{with_text}has been opened, but you didn't wrap " \
96
109
  "your code into (`accept_prompt` | `dismiss_prompt` | " \
97
110
  "`accept_confirm` | `dismiss_confirm` | `accept_alert`), " \
98
111
  "accepting by default"
99
112
 
100
- if @options.raise_on_unhandled_modal
101
- unhandled_modal_error = UnhandledModalError.new(message)
113
+ if @settings.raise_on_unhandled_modal
114
+ @unhandled_modal_error = UnhandledModalError.new(message)
102
115
  else
103
116
  warn message
104
117
  end
105
118
 
106
- options = { accept: true }
107
- response = params["defaultPrompt"]
119
+ accept = true
108
120
  end
109
- options.merge!(promptText: response) if response
110
- # Skips #command so a pending error isn't raised on the dispatcher thread.
111
- client.command("Page.handleJavaScriptDialog", timeout: timeout, **options)
112
121
 
113
- @unhandled_modal_error = unhandled_modal_error if unhandled_modal_error
122
+ answer_dialog(dialog, accept, response)
123
+ end
124
+
125
+ def answer_dialog(dialog, accept, response)
126
+ Thread.current[:cuprite_handling_dialog] = true
127
+ accept ? dialog.accept(response) : dialog.dismiss
128
+ ensure
129
+ Thread.current[:cuprite_handling_dialog] = nil
114
130
  end
115
131
  end
116
132
  end