cuprite 0.20.1 → 0.22

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 (47) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +35 -31
  3. data/lib/capybara/cuprite/deprecation.rb +8 -1
  4. data/lib/capybara/cuprite/devices.rb +8 -0
  5. data/lib/capybara/cuprite/driver/deprecations.rb +22 -184
  6. data/lib/capybara/cuprite/driver/extensions.rb +50 -0
  7. data/lib/capybara/cuprite/driver/settings.rb +102 -0
  8. data/lib/capybara/cuprite/driver/window/frames.rb +35 -0
  9. data/lib/capybara/cuprite/driver/window/modals.rb +113 -0
  10. data/lib/capybara/cuprite/driver/window.rb +34 -0
  11. data/lib/capybara/cuprite/driver/windows.rb +90 -0
  12. data/lib/capybara/cuprite/driver.rb +331 -66
  13. data/lib/capybara/cuprite/errors.rb +48 -1
  14. data/lib/capybara/cuprite/finder/hints.rb +51 -0
  15. data/lib/capybara/cuprite/finder.rb +18 -3
  16. data/lib/capybara/cuprite/javascripts/index.js +123 -58
  17. data/lib/capybara/cuprite/node/extensions.rb +14 -4
  18. data/lib/capybara/cuprite/node/typing.rb +75 -0
  19. data/lib/capybara/cuprite/node.rb +208 -63
  20. data/lib/capybara/cuprite/version.rb +3 -1
  21. data/lib/capybara/cuprite.rb +1 -4
  22. data/sig/capybara/cuprite/deprecation.rbs +7 -0
  23. data/sig/capybara/cuprite/devices.rbs +19 -0
  24. data/sig/capybara/cuprite/driver/deprecations.rbs +11 -0
  25. data/sig/capybara/cuprite/driver/extensions.rbs +29 -0
  26. data/sig/capybara/cuprite/driver/settings.rbs +42 -0
  27. data/sig/capybara/cuprite/driver/window/frames.rbs +13 -0
  28. data/sig/capybara/cuprite/driver/window/modals.rbs +29 -0
  29. data/sig/capybara/cuprite/driver/window.rbs +22 -0
  30. data/sig/capybara/cuprite/driver/windows.rbs +27 -0
  31. data/sig/capybara/cuprite/driver.rbs +140 -0
  32. data/sig/capybara/cuprite/errors.rbs +56 -0
  33. data/sig/capybara/cuprite/finder/hints.rbs +28 -0
  34. data/sig/capybara/cuprite/finder.rbs +7 -0
  35. data/sig/capybara/cuprite/node/extensions.rbs +9 -0
  36. data/sig/capybara/cuprite/node/typing.rbs +30 -0
  37. data/sig/capybara/cuprite/node.rbs +112 -0
  38. data/sig/capybara/cuprite/version.rbs +5 -0
  39. metadata +27 -11
  40. data/lib/capybara/cuprite/browser/deprecations.rb +0 -26
  41. data/lib/capybara/cuprite/browser/extensions.rb +0 -59
  42. data/lib/capybara/cuprite/browser.rb +0 -108
  43. data/lib/capybara/cuprite/node/deprecations.rb +0 -43
  44. data/lib/capybara/cuprite/options.rb +0 -33
  45. data/lib/capybara/cuprite/page/frames.rb +0 -47
  46. data/lib/capybara/cuprite/page/modals.rb +0 -118
  47. data/lib/capybara/cuprite/page.rb +0 -36
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Capybara
4
+ module Cuprite
5
+ module Finder
6
+ # Capybara's finder hints for one query: what the browser is asked to answer along with
7
+ # the nodes it finds, and the initial cache of each node built from that answer.
8
+ # @api private
9
+ class Hints
10
+ # @param uses_visibility [Boolean] whether the query filters on visibility
11
+ # @param texts [Array<String>] the fragments every matching node's text has to contain
12
+ # @param styles [Hash, nil] the computed styles the query filters on
13
+ # @param position [Boolean] whether the query filters on the position of the nodes
14
+ def initialize(uses_visibility: false, texts: [], styles: nil, position: false, **)
15
+ @visible = uses_visibility
16
+ @texts = texts
17
+ @styles = styles.keys.map(&:to_s) if styles.is_a?(Hash)
18
+ @position = position
19
+ end
20
+
21
+ # @return [Hash] the hints as `_cuprite.findWithHints` takes them
22
+ def to_h
23
+ { visible: @visible, texts: @texts, styles: @styles, position: @position }
24
+ end
25
+
26
+ # Builds the initial cache of each node from the browser's answer, which holds one
27
+ # list per hint instead of one cache per node, as Chrome serializes that faster.
28
+ #
29
+ # @param count [Integer] the number of nodes found
30
+ # @param hidden [Array<Integer>, nil] the indexes of the hidden nodes
31
+ # @param style [Hash{String => Array<String>}, nil] each style's value for every node
32
+ # @param position [Array<Hash>, nil] the bounding rectangle of every node
33
+ # @param texts [Array<Array>, nil] all text and visible text of every node
34
+ # @return [Array<Hash>] one cache per node, in the order of the nodes
35
+ def caches(count, hidden, style, position, texts)
36
+ hidden = hidden&.to_set
37
+ all_texts, visible_texts = texts
38
+
39
+ Array.new(count) do |index|
40
+ cache = {}
41
+ cache[:visible] = !hidden.include?(index) if hidden
42
+ cache[:style] = style.transform_values { |values| values[index] } if style
43
+ cache[:position] = position[index] if position
44
+ cache.merge!(all_text: all_texts[index], visible_text: visible_texts[index]) if texts
45
+ cache
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
51
+ end
@@ -1,17 +1,32 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "capybara/cuprite/finder/hints"
4
+
3
5
  module Capybara
4
6
  module Cuprite
7
+ # Looks up the elements for {Driver} and {Node}.
8
+ # @api private
5
9
  module Finder
6
10
  module_function
7
11
 
8
- def find(browser, method, selector, within = nil)
12
+ # Finds the nodes matching a selector and answers Capybara's finder hints in the same call.
13
+ #
14
+ # @param frame [Ferrum::Frame] the frame to search in
15
+ # @param method [Symbol] `:css` or `:xpath`
16
+ # @param selector [String]
17
+ # @param within [Ferrum::Node, nil] the node to search in, the document by default
18
+ # @param hints [Hash] the hints Capybara passes to `find_css` and `find_xpath`
19
+ # @return [Array<Array(Ferrum::Node, Hash)>] each node with its initial cache
20
+ # @raise [InvalidSelector]
21
+ def find(frame, method, selector, within = nil, **hints)
9
22
  # Capybara appends its text-match hint as `(expr)[...]`, but with `exact_text: true` the hint
10
23
  # is empty and the result `(expr)[]` is invalid XPath. An empty predicate is never valid, so
11
24
  # dropping it can't change a valid selector. Remove once teamcapybara/capybara#2860 is released.
12
25
  selector = selector.delete_suffix("[]") if method == :xpath
13
- nodes = browser.evaluate("_cuprite.find(...arguments)", *[method, selector, within].compact)
14
- nodes.select(&:node?)
26
+ hints = Hints.new(**hints)
27
+ nodes, *answers = frame.evaluate("_cuprite.findWithHints(method, selector, within, hints)",
28
+ method: method, selector: selector, within: within, hints: hints.to_h)
29
+ nodes.zip(hints.caches(nodes.size, *answers))
15
30
  rescue Ferrum::JavaScriptError => e
16
31
  raise InvalidSelector.new(e.response, method, selector) if e.class_name == "InvalidSelector"
17
32
 
@@ -4,6 +4,7 @@
4
4
  class InvalidSelector extends Error {}
5
5
  class TimedOutPromise extends Error {}
6
6
  class MouseEventFailed extends Error {}
7
+ class ObsoleteNode extends Error {}
7
8
 
8
9
  const EVENTS = {
9
10
  FOCUS: ["blur", "focus", "focusin", "focusout"],
@@ -12,11 +13,9 @@
12
13
  FORM: ["submit"]
13
14
  }
14
15
 
15
- class Cuprite {
16
- constructor() {
17
- this._json = JSON; // In case someone overrides it like mootools
18
- }
16
+ const UNMATCHED_LIMIT = 50;
19
17
 
18
+ class Cuprite {
20
19
  find(method, selector, within = document) {
21
20
  try {
22
21
  let results = [];
@@ -41,18 +40,64 @@
41
40
  }
42
41
  }
43
42
 
44
- parents(node) {
45
- let nodes = [];
46
- let parent = node.parentNode;
47
- while (parent != document && parent !== null) {
48
- nodes.push(parent);
49
- parent = parent.parentNode;
43
+ findWithHints(method, selector, within, hints) {
44
+ let nodes = this.find(method, selector, within ?? document).filter(node => node.nodeType == Node.ELEMENT_NODE);
45
+ let visibility = [new Map(), new Map()];
46
+ let texts = null;
47
+
48
+ if (hints.texts.length > 0) {
49
+ let matches = this.filterTexts(nodes, hints.texts, hints.visible, visibility);
50
+ if (matches.length > 0) {
51
+ nodes = matches;
52
+ } else {
53
+ nodes = nodes.slice(0, UNMATCHED_LIMIT);
54
+ texts = this.texts(nodes, visibility);
55
+ }
50
56
  }
51
- return nodes;
57
+
58
+ return [
59
+ nodes,
60
+ hints.visible ? this.hiddenIndexes(nodes, visibility) : null,
61
+ hints.styles ? this.styles(nodes, hints.styles) : null,
62
+ hints.position ? nodes.map(node => node.getBoundingClientRect().toJSON()) : null,
63
+ texts
64
+ ];
65
+ }
66
+
67
+ // A node can only match when its visible text, or all its text without zero width
68
+ // characters, contains every text. A match vouches for its ancestors, so the last node goes first.
69
+ filterTexts(nodes, texts, visible, visibility) {
70
+ let containsAll = content => texts.every(text => content.includes(text));
71
+ let matched = new Set();
72
+ return [...nodes].reverse().filter(node => {
73
+ if (matched.has(node)) {
74
+ return true;
75
+ }
76
+ if (containsAll(node.textContent.replace(/[\u200b\u200e\u200f]/g, ""))) {
77
+ for (let parent = node.parentNode; parent && !matched.has(parent); parent = parent.parentNode) {
78
+ matched.add(parent);
79
+ }
80
+ return true;
81
+ }
82
+ return visible && containsAll(this.visibleText(node, visibility) || "");
83
+ }).reverse();
84
+ }
85
+
86
+ texts(nodes, visibility) {
87
+ return [nodes.map(node => node.textContent), nodes.map(node => this.visibleText(node, visibility))];
88
+ }
89
+
90
+ hiddenIndexes(nodes, visibility) {
91
+ return [...nodes.keys()].filter(index => !this.isVisible(nodes[index], visibility));
92
+ }
93
+
94
+ styles(nodes, names) {
95
+ let computed = nodes.map(node => window.getComputedStyle(node));
96
+ return Object.fromEntries(names.map(name => [name, computed.map(style => style.getPropertyValue(name))]));
52
97
  }
53
98
 
54
- visibleText(node) {
55
- if (this.isVisible(node)) {
99
+ visibleText(node, visibility) {
100
+ if (this.isVisible(node, visibility)) {
56
101
  if (node.nodeName == "TEXTAREA") {
57
102
  return node.textContent;
58
103
  }
@@ -61,7 +106,7 @@
61
106
  }
62
107
  if (node instanceof ShadowRoot) {
63
108
  return Array.from(node.children)
64
- .map(child => this.visibleText(child))
109
+ .map(child => this.visibleText(child, visibility))
65
110
  .filter(text => text)
66
111
  .join(" ");
67
112
  }
@@ -69,7 +114,9 @@
69
114
  }
70
115
  }
71
116
 
72
- isVisible(node) {
117
+ // Pass the same cache to several calls to share their ancestor walks. An ancestor's
118
+ // result depends on whether its opacity still applies, so each case is cached apart.
119
+ isVisible(node, cache = [new Map(), new Map()]) {
73
120
  let mapName, style;
74
121
  // if node is area, check visibility of relevant image
75
122
  if (node.tagName === "AREA") {
@@ -81,39 +128,52 @@
81
128
  }
82
129
 
83
130
  let ancestorOpacityApplies = true;
131
+ let walked = [];
132
+ let visible = true;
84
133
 
85
134
  while (node) {
86
135
  if (node instanceof ShadowRoot) {
87
136
  node = node.host;
88
- } else {
89
- style = window.getComputedStyle(node);
90
- if (style.display === "none" || style.visibility === "hidden" || (ancestorOpacityApplies && parseFloat(style.opacity) === 0)) {
91
- return false;
92
- }
137
+ continue;
138
+ }
93
139
 
94
- // A node matching :modal or :popover-open is a top-layer element, so
95
- // an ancestor's opacity no longer applies to it once shown.
96
- if (ancestorOpacityApplies) {
97
- try {
98
- if (node.matches(":modal, :popover-open")) {
99
- ancestorOpacityApplies = false;
100
- }
101
- } catch (e) {}
102
- }
140
+ let known = cache[+ancestorOpacityApplies].get(node);
141
+ if (known !== undefined) {
142
+ visible = known;
143
+ break;
144
+ }
145
+ walked.push([node, ancestorOpacityApplies]);
103
146
 
104
- let parent = node.parentElement;
105
- if (parent && parent.tagName === "DETAILS" && !parent.open) {
106
- // In a closed <details> only the first <summary> (and its subtree) is rendered.
107
- if (node !== parent.querySelector(":scope > summary")) {
108
- return false;
147
+ style = window.getComputedStyle(node);
148
+ if (style.display === "none" || style.visibility === "hidden" || (ancestorOpacityApplies && parseFloat(style.opacity) === 0)) {
149
+ visible = false;
150
+ break;
151
+ }
152
+
153
+ // A node matching :modal or :popover-open is a top-layer element, so
154
+ // an ancestor's opacity no longer applies to it once shown.
155
+ if (ancestorOpacityApplies) {
156
+ try {
157
+ if (node.matches(":modal, :popover-open")) {
158
+ ancestorOpacityApplies = false;
109
159
  }
110
- }
160
+ } catch (e) {}
161
+ }
111
162
 
112
- node = parent ?? (node.getRootNode() instanceof ShadowRoot && node.getRootNode());
163
+ let parent = node.parentElement;
164
+ if (parent && parent.tagName === "DETAILS" && !parent.open) {
165
+ // In a closed <details> only the first <summary> (and its subtree) is rendered.
166
+ if (node !== parent.querySelector(":scope > summary")) {
167
+ visible = false;
168
+ break;
169
+ }
113
170
  }
171
+
172
+ node = parent ?? (node.getRootNode() instanceof ShadowRoot && node.getRootNode());
114
173
  }
115
174
 
116
- return true;
175
+ walked.forEach(([node, opacityApplies]) => cache[+opacityApplies].set(node, visible));
176
+ return visible;
117
177
  }
118
178
 
119
179
  isDisabled(node) {
@@ -193,7 +253,7 @@
193
253
  this.trigger(node, "focus");
194
254
  this.setValue(node, "");
195
255
 
196
- if (node.type == "number" || node.type == "date" || node.type == "range" || node.type == "time" || node.type == "month" || node.type == "week") {
256
+ if (node.type == "date" || node.type == "range" || node.type == "time" || node.type == "month" || node.type == "week") {
197
257
  this.setValue(node, value);
198
258
  this.input(node);
199
259
  } else if (node.type == "datetime-local") {
@@ -343,6 +403,10 @@
343
403
  }
344
404
 
345
405
  mouseEventTest(node, name, x, y) {
406
+ // The page can remove the node after Ruby checked it; getRootNode() would
407
+ // then return the detached subtree, which has no elementFromPoint.
408
+ if (!node.isConnected) throw new ObsoleteNode();
409
+
346
410
  let frameOffset = this._frameOffset();
347
411
  x -= frameOffset.left;
348
412
  y -= frameOffset.top;
@@ -502,16 +566,6 @@
502
566
  return event;
503
567
  }
504
568
 
505
- getAttributes(node) {
506
- let attrs = {};
507
- for (let i = 0, len = node.attributes.length; i < len; i++) {
508
- let attr = node.attributes[i];
509
- attrs[attr.name] = attr.value.replace("\n", "\\n");
510
- }
511
-
512
- return this._json.stringify(attrs);
513
- }
514
-
515
569
  getAttribute(node, name) {
516
570
  if (name == "checked" || name == "selected") {
517
571
  return node[name];
@@ -522,16 +576,7 @@
522
576
 
523
577
  value(node) {
524
578
  if (node.tagName == "SELECT" && node.multiple) {
525
- let result = []
526
-
527
- for (let i = 0, len = node.children.length; i < len; i++) {
528
- let option = node.children[i];
529
- if (option.selected) {
530
- result.push(option.value);
531
- }
532
- }
533
-
534
- return result;
579
+ return Array.from(node.selectedOptions, option => option.value);
535
580
  } else {
536
581
  return node.value;
537
582
  }
@@ -549,6 +594,26 @@
549
594
  return document.activeElement === node;
550
595
  }
551
596
 
597
+ focusForTyping(node) {
598
+ if (this.containsSelection(node) || this.hasFocus(node)) return false;
599
+
600
+ node.focus();
601
+
602
+ if (node.isContentEditable) {
603
+ let range = document.createRange();
604
+ range.selectNodeContents(node);
605
+ range.collapse(false);
606
+ window.getSelection().removeAllRanges();
607
+ window.getSelection().addRange(range);
608
+ } else if (node.tagName == "INPUT" && ["email", "number"].includes(node.type)) {
609
+ return true;
610
+ } else if ((node.tagName == "INPUT" || node.tagName == "TEXTAREA") && node.selectionStart !== null) {
611
+ node.setSelectionRange(node.value.length, node.value.length);
612
+ }
613
+
614
+ return false;
615
+ }
616
+
552
617
  containsSelection(node) {
553
618
  let selectedNode = document.getSelection().focusNode;
554
619
 
@@ -3,20 +3,30 @@
3
3
  module Capybara
4
4
  module Cuprite
5
5
  class Node < Capybara::Driver::Node
6
+ # Node methods Capybara doesn't need.
6
7
  module Extensions
8
+ # Drags the element by an offset with the mouse.
9
+ #
10
+ # @param x [Numeric]
11
+ # @param y [Numeric]
12
+ # @param steps [Integer] mouse moves to reach the target
13
+ # @param delay [Numeric, nil] seconds to wait after pressing the button
14
+ # @param scroll [Boolean] scroll the page by the offset first
15
+ # @return [void]
16
+ # @raise [ObsoleteNode] when the element is no longer in the DOM
7
17
  def drag_by(x, y, steps: 1, delay: nil, scroll: true)
8
- mouse = driver.browser.mouse
18
+ mouse = driver.current_page.mouse
9
19
 
10
20
  command do
11
- x1, y1 = node.find_position
21
+ x1, y1 = node.pinpoint
12
22
  mouse.move(x: x1, y: y1)
13
23
  mouse.down
14
24
 
15
25
  sleep delay if delay
16
26
 
17
- mouse.scroll_by(x, y) if scroll
27
+ mouse.scroll_by(x: x, y: y) if scroll
18
28
 
19
- x2, y2 = node.find_position
29
+ x2, y2 = node.pinpoint
20
30
  mouse.move(x: x2 + x, y: y2 + y, steps: steps)
21
31
  mouse.up
22
32
  end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Capybara
4
+ module Cuprite
5
+ class Node < Capybara::Driver::Node
6
+ # Typing into text fields for {Node#set}.
7
+ # @api private
8
+ module Typing
9
+ TYPED_INPUTS = %w[text password email search tel url number].freeze
10
+ SET_OPTIONS = %i[rapid clear].freeze
11
+ CLEAR_ERROR = "clear: takes nil, :none, :backspace or an Array of keys"
12
+ MULTIPLE_ERROR = "Value cannot be an Array when 'multiple' attribute is not present"
13
+ RAPID_SET_LENGTH = 30
14
+ RAPID_APPEND_TEXT = "this.value = (this.value + value)" \
15
+ ".slice(0, this.maxLength >= 0 ? this.maxLength : undefined)"
16
+
17
+ private
18
+
19
+ def warn_unsupported(options)
20
+ unsupported = options.keys - SET_OPTIONS
21
+ return if unsupported.empty?
22
+
23
+ names = unsupported.map(&:inspect).join(", ")
24
+ warn "Options passed to Node#set but Cuprite doesn't support #{names} - ignoring"
25
+ end
26
+
27
+ def set_text(value, rapid: nil, clear: nil, **)
28
+ raise ArgumentError, CLEAR_ERROR unless [nil, :none, :backspace].include?(clear) || clear.is_a?(Array)
29
+ return command(:set, value) if value.empty? && clear.nil?
30
+ return if command { node.evaluate("this.readOnly || this.disabled") }
31
+
32
+ node.focus
33
+ clear.nil? ? node.evaluate("this.select()") : move_caret_to_end
34
+ keys = clear_keys(clear)
35
+ node.type(*keys) unless keys.empty?
36
+ type_text(value.gsub(/\r\n?|\n/, "\r"), [nil, :none].include?(clear) ? rapid : false)
37
+ refocus
38
+ end
39
+
40
+ def clear_keys(clear)
41
+ case clear
42
+ when :backspace then [:backspace] * node.evaluate("this.value.length")
43
+ when Array then clear
44
+ else []
45
+ end
46
+ end
47
+
48
+ def type_text(value, rapid)
49
+ middle = value[4...-3].to_s
50
+ if !middle.empty? && (rapid == true || (value.length > RAPID_SET_LENGTH && rapid != false))
51
+ node.type(value[0..3])
52
+ node.evaluate(RAPID_APPEND_TEXT, value: middle)
53
+ node.type(value[-3..])
54
+ elsif !value.empty?
55
+ node.type(value)
56
+ end
57
+ end
58
+
59
+ def move_caret_to_end
60
+ if tag_name == "textarea"
61
+ node.evaluate("this.setSelectionRange(this.value.length, this.value.length)")
62
+ else
63
+ node.type(:end)
64
+ end
65
+ end
66
+
67
+ def refocus
68
+ node.evaluate("this.blur(); this.focus()")
69
+ rescue Ferrum::NodeNotFoundError, Ferrum::NoExecutionContextError, Ferrum::ExecutionContextDestroyedError
70
+ nil
71
+ end
72
+ end
73
+ end
74
+ end
75
+ end