Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
accepts them first and loses dismissals and prompt responses [rubycdp/ferrum#703]
- A closed window is removed from Ferrum's context, which returns a copy of its targets, so `close_window` no longer
leaves it listed until Chrome reports it destroyed [rubycdp/ferrum#707]
- `find_css` and `find_xpath` answer Capybara's finder hints in the call that finds the nodes, so Capybara no longer
asks each node for its visibility and text. As with Selenium, a lazily filtered result keeps the answers [#347]

### Fixed
- A click on a node the page removes before the hit test raises `ObsoleteNode`, which Capybara retries, instead of
Expand Down
12 changes: 6 additions & 6 deletions lib/capybara/cuprite/driver.rb
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,12 @@ def active_element
Node.new(self, browser.evaluate("document.activeElement"))
end

def find_xpath(selector)
find(:xpath, selector)
def find_xpath(selector, **hints)
find(:xpath, selector, **hints)
end

def find_css(selector)
find(:css, selector)
def find_css(selector, **hints)
find(:css, selector, **hints)
end

def evaluate_script(script, *args)
Expand Down Expand Up @@ -229,8 +229,8 @@ def dismiss_modal(type, options = {})

attr_reader :screen_size

def find(method, selector)
Finder.find(browser, method, selector).map { |native| Node.new(self, native) }
def find(method, selector, **hints)
Finder.find(browser, method, selector, **hints).map { |native, cache| Node.new(self, native, cache) }
end

def within_window(handle)
Expand Down
19 changes: 16 additions & 3 deletions lib/capybara/cuprite/finder.rb
Original file line number Diff line number Diff line change
@@ -1,17 +1,30 @@
# frozen_string_literal: true

require "capybara/cuprite/finder/hints"

module Capybara
module Cuprite
module Finder
module_function

def find(browser, method, selector, within = nil)
# Finds the nodes matching a selector and answers Capybara's finder hints in the same call.
#
# @param browser [Browser]
# @param method [Symbol] `:css` or `:xpath`
# @param selector [String]
# @param within [Ferrum::Node, nil] the node to search in, the document by default
# @param hints [Hash] the hints Capybara passes to `find_css` and `find_xpath`
# @return [Array<Array(Ferrum::Node, Hash)>] each node with its initial cache
# @raise [InvalidSelector]
def find(browser, method, selector, within = nil, **hints)
# Capybara appends its text-match hint as `(expr)[...]`, but with `exact_text: true` the hint
# is empty and the result `(expr)[]` is invalid XPath. An empty predicate is never valid, so
# dropping it can't change a valid selector. Remove once teamcapybara/capybara#2860 is released.
selector = selector.delete_suffix("[]") if method == :xpath
nodes = browser.evaluate("_cuprite.find(...arguments)", *[method, selector, within].compact)
nodes.select(&:node?)
hints = Hints.new(**hints)
nodes, *answers = browser.evaluate("_cuprite.findWithHints(method, selector, within, hints)",
method: method, selector: selector, within: within, hints: hints.to_h)
nodes.zip(hints.caches(nodes.size, *answers))
rescue Ferrum::JavaScriptError => e
raise InvalidSelector.new(e.response, method, selector) if e.class_name == "InvalidSelector"

Expand Down
50 changes: 50 additions & 0 deletions lib/capybara/cuprite/finder/hints.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# frozen_string_literal: true

module Capybara
module Cuprite
module Finder
# Capybara's finder hints for one query: what the browser is asked to answer along with
# the nodes it finds, and the initial cache of each node built from that answer.
class Hints
# @param uses_visibility [Boolean] whether the query filters on visibility
# @param texts [Array<String>] the fragments every matching node's text has to contain
# @param styles [Hash, nil] the computed styles the query filters on
# @param position [Boolean] whether the query filters on the position of the nodes
def initialize(uses_visibility: false, texts: [], styles: nil, position: false, **)
@visible = uses_visibility
@texts = texts
@styles = styles.keys.map(&:to_s) if styles.is_a?(Hash)
@position = position
end

# @return [Hash] the hints as `_cuprite.findWithHints` takes them
def to_h
{ visible: @visible, texts: @texts, styles: @styles, position: @position }
end

# Builds the initial cache of each node from the browser's answer, which holds one
# list per hint instead of one cache per node, as Chrome serializes that faster.
#
# @param count [Integer] the number of nodes found
# @param hidden [Array<Integer>, nil] the indexes of the hidden nodes
# @param style [Hash{String => Array<String>}, nil] each style's value for every node
# @param position [Array<Hash>, nil] the bounding rectangle of every node
# @param texts [Array<Array>, nil] all text and visible text of every node
# @return [Array<Hash>] one cache per node, in the order of the nodes
def caches(count, hidden, style, position, texts)
hidden = hidden&.to_set
all_texts, visible_texts = texts

Array.new(count) do |index|
cache = {}
cache[:visible] = !hidden.include?(index) if hidden
cache[:style] = style.transform_values { |values| values[index] } if style
cache[:position] = position[index] if position
cache.merge!(all_text: all_texts[index], visible_text: visible_texts[index]) if texts
cache
end
end
end
end
end
end
125 changes: 99 additions & 26 deletions lib/capybara/cuprite/javascripts/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
FORM: ["submit"]
}

const UNMATCHED_LIMIT = 50;

class Cuprite {
find(method, selector, within = document) {
try {
Expand All @@ -38,8 +40,64 @@
}
}

visibleText(node) {
if (this.isVisible(node)) {
findWithHints(method, selector, within, hints) {
let nodes = this.find(method, selector, within ?? document).filter(node => node.nodeType == Node.ELEMENT_NODE);
let visibility = [new Map(), new Map()];
let texts = null;

if (hints.texts.length > 0) {
let matches = this.filterTexts(nodes, hints.texts, hints.visible, visibility);
if (matches.length > 0) {
nodes = matches;
} else {
nodes = nodes.slice(0, UNMATCHED_LIMIT);
texts = this.texts(nodes, visibility);
}
}

return [
nodes,
hints.visible ? this.hiddenIndexes(nodes, visibility) : null,
hints.styles ? this.styles(nodes, hints.styles) : null,
hints.position ? nodes.map(node => node.getBoundingClientRect().toJSON()) : null,
texts
];
}

// A node can only match when its visible text, or all its text without zero width
// characters, contains every text. A match vouches for its ancestors, so the last node goes first.
filterTexts(nodes, texts, visible, visibility) {
let containsAll = content => texts.every(text => content.includes(text));
let matched = new Set();
return [...nodes].reverse().filter(node => {
if (matched.has(node)) {
return true;
}
if (containsAll(node.textContent.replace(/[\u200b\u200e\u200f]/g, ""))) {
for (let parent = node.parentNode; parent && !matched.has(parent); parent = parent.parentNode) {
matched.add(parent);
}
return true;
}
return visible && containsAll(this.visibleText(node, visibility) || "");
}).reverse();
}

texts(nodes, visibility) {
return [nodes.map(node => node.textContent), nodes.map(node => this.visibleText(node, visibility))];
}

hiddenIndexes(nodes, visibility) {
return [...nodes.keys()].filter(index => !this.isVisible(nodes[index], visibility));
}

styles(nodes, names) {
let computed = nodes.map(node => window.getComputedStyle(node));
return Object.fromEntries(names.map(name => [name, computed.map(style => style.getPropertyValue(name))]));
}

visibleText(node, visibility) {
if (this.isVisible(node, visibility)) {
if (node.nodeName == "TEXTAREA") {
return node.textContent;
}
Expand All @@ -48,15 +106,17 @@
}
if (node instanceof ShadowRoot) {
return Array.from(node.children)
.map(child => this.visibleText(child))
.map(child => this.visibleText(child, visibility))
.filter(text => text)
.join(" ");
}
return node.innerText;
}
}

isVisible(node) {
// Pass the same cache to several calls to share their ancestor walks. An ancestor's
// result depends on whether its opacity still applies, so each case is cached apart.
isVisible(node, cache = [new Map(), new Map()]) {
let mapName, style;
// if node is area, check visibility of relevant image
if (node.tagName === "AREA") {
Expand All @@ -68,39 +128,52 @@
}

let ancestorOpacityApplies = true;
let walked = [];
let visible = true;

while (node) {
if (node instanceof ShadowRoot) {
node = node.host;
} else {
style = window.getComputedStyle(node);
if (style.display === "none" || style.visibility === "hidden" || (ancestorOpacityApplies && parseFloat(style.opacity) === 0)) {
return false;
}
continue;
}

// A node matching :modal or :popover-open is a top-layer element, so
// an ancestor's opacity no longer applies to it once shown.
if (ancestorOpacityApplies) {
try {
if (node.matches(":modal, :popover-open")) {
ancestorOpacityApplies = false;
}
} catch (e) {}
}
let known = cache[+ancestorOpacityApplies].get(node);
if (known !== undefined) {
visible = known;
break;
}
walked.push([node, ancestorOpacityApplies]);

let parent = node.parentElement;
if (parent && parent.tagName === "DETAILS" && !parent.open) {
// In a closed <details> only the first <summary> (and its subtree) is rendered.
if (node !== parent.querySelector(":scope > summary")) {
return false;
style = window.getComputedStyle(node);
if (style.display === "none" || style.visibility === "hidden" || (ancestorOpacityApplies && parseFloat(style.opacity) === 0)) {
visible = false;
break;
}

// A node matching :modal or :popover-open is a top-layer element, so
// an ancestor's opacity no longer applies to it once shown.
if (ancestorOpacityApplies) {
try {
if (node.matches(":modal, :popover-open")) {
ancestorOpacityApplies = false;
}
}
} catch (e) {}
}

node = parent ?? (node.getRootNode() instanceof ShadowRoot && node.getRootNode());
let parent = node.parentElement;
if (parent && parent.tagName === "DETAILS" && !parent.open) {
// In a closed <details> only the first <summary> (and its subtree) is rendered.
if (node !== parent.querySelector(":scope > summary")) {
visible = false;
break;
}
}

node = parent ?? (node.getRootNode() instanceof ShadowRoot && node.getRootNode());
}

return true;
walked.forEach(([node, opacityApplies]) => cache[+opacityApplies].set(node, visible));
return visible;
}

isDisabled(node) {
Expand Down
33 changes: 18 additions & 15 deletions lib/capybara/cuprite/node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,29 +14,32 @@ class Node < Capybara::Driver::Node
DRAG_HTML5_JS = File.read(File.expand_path("javascripts/drag.js", __dir__))
TRIGGER_CLICK_WAIT = ENV.fetch("CUPRITE_TRIGGER_CLICK_WAIT", 0.1).to_f

def initialize(driver, node)
super(driver, self)
def initialize(driver, node, initial_cache = {})
super(driver, self, initial_cache)
@node = node
end

def find_xpath(selector)
find(:xpath, selector)
def find_xpath(selector, **hints)
find(:xpath, selector, **hints)
end

def find_css(selector)
find(:css, selector)
def find_css(selector, **hints)
find(:css, selector, **hints)
end

# A text in the initial cache comes only with a node that can't match its query's text, which
# Capybara reads to filter it out and to describe the failure, and never hands to the caller.
def all_text
filter_text(command { node.text })
filter_text(initial_cache.fetch(:all_text) { command { node.text } })
end

def visible_text
command(:visibleText).to_s
.gsub(/\A[[:space:]&&[^\u00a0]]+/, "")
.gsub(/[[:space:]&&[^\u00a0]]+\z/, "")
.gsub(/\n+/, "\n")
.tr("\u00a0", " ")
text = initial_cache.fetch(:visible_text) { command(:visibleText) }
text.to_s
.gsub(/\A[[:space:]&&[^\u00a0]]+/, "")
.gsub(/[[:space:]&&[^\u00a0]]+\z/, "")
.gsub(/\n+/, "\n")
.tr("\u00a0", " ")
end

def [](name)
Expand Down Expand Up @@ -237,9 +240,9 @@ def inspect

private

def find(method, selector)
command { Finder.find(driver.browser, method, selector, node) }.map do |node|
self.class.new(driver, node)
def find(method, selector, **hints)
command { Finder.find(driver.browser, method, selector, node, **hints) }.map do |native, cache|
self.class.new(driver, native, cache)
end
end

Expand Down
Loading
Loading