diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c934c6..ebeb82a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ ### Added - `browser.go_to` takes the keywords of Ferrum's `go_to`, like `referrer:` and `timeout:`, it accepted only the URL - `:url_blocklist` and `:url_allowlist` driver options as aliases for `:url_blacklist` and `:url_whitelist` [#330] +- `clear:` set option like Selenium's: `:none` appends, `:backspace` deletes with Backspace, an Array of keys is pressed + first. Options Cuprite doesn't support warn again ### Changed - Text inputs and textareas are filled with real key presses like Selenium, values over 30 characters type the first 4 diff --git a/lib/capybara/cuprite/node.rb b/lib/capybara/cuprite/node.rb index 9b2d8cd..63494e9 100644 --- a/lib/capybara/cuprite/node.rb +++ b/lib/capybara/cuprite/node.rb @@ -2,6 +2,7 @@ require "capybara/cuprite/finder" require "capybara/cuprite/node/extensions" +require "capybara/cuprite/node/typing" module Capybara module Cuprite @@ -9,13 +10,11 @@ class Node < Capybara::Driver::Node attr_reader :node include Extensions + include Typing DRAG_MODIFIER_ALIASES = { control: :ctrl, command: :meta, cmd: :meta }.freeze 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 - TYPED_INPUTS = %w[text password email search tel url].freeze - RAPID_SET_LENGTH = 30 - RAPID_APPEND_TEXT = "this.value = (this.value + value).slice(0, this.maxLength >= 0 ? this.maxLength : undefined)" def initialize(driver, node, initial_cache = {}) super(driver, self, initial_cache) @@ -64,7 +63,20 @@ def value command(:value) end + # Sets the value of a form field. Text inputs and textareas are typed with real key presses. + # + # @param value [String, Array, Boolean, Date, Time] the value to set + # @param options [Hash] Capybara's `fill_options`, the defaults come from `Capybara.default_set_options`. Other + # options are ignored with a warning, `rapid:` and `clear:` silently on fields other than text ones. + # @option options [Boolean, nil] :rapid `true` types the first 4 and last 3 characters and sets the middle from + # JS, `false` types every character, `nil` does it for values over 30 characters + # @option options [nil, :none, :backspace, Array] :clear `nil` replaces the value, `:none` appends to it, + # `:backspace` deletes it with Backspace first, an Array of keys is pressed before typing + # @return [void] + # @raise [ArgumentError] for an unknown `clear:` value def set(value, options = {}) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity, Metrics/AbcSize + warn_unsupported(options) + if tag_name == "input" case self[:type] when *TYPED_INPUTS @@ -243,30 +255,6 @@ def inspect private - def set_text(value, rapid: nil, **) - return command(:set, value) if value.empty? - return if command { node.evaluate("this.readOnly || this.disabled") } - - value = value.gsub(/\r\n?|\n/, "\r") - node.focus - node.evaluate("this.select()") - middle = value[4...-3].to_s - if !middle.empty? && (rapid == true || (value.length > RAPID_SET_LENGTH && rapid != false)) - node.type(value[0..3]) - node.evaluate(RAPID_APPEND_TEXT, value: middle) - node.type(value[-3..]) - else - node.type(value) - end - refocus - end - - def refocus - node.evaluate("this.blur(); this.focus()") - rescue Ferrum::NodeNotFoundError - nil - end - def find(method, selector, **hints) command { Finder.find(driver.browser, method, selector, node, **hints) }.map do |native, cache| self.class.new(driver, native, cache) diff --git a/lib/capybara/cuprite/node/typing.rb b/lib/capybara/cuprite/node/typing.rb new file mode 100644 index 0000000..cc49358 --- /dev/null +++ b/lib/capybara/cuprite/node/typing.rb @@ -0,0 +1,72 @@ +# frozen_string_literal: true + +module Capybara + module Cuprite + class Node < Capybara::Driver::Node + module Typing + TYPED_INPUTS = %w[text password email search tel url].freeze + SET_OPTIONS = %i[rapid clear].freeze + CLEAR_ERROR = "clear: takes nil, :none, :backspace or an Array of keys" + RAPID_SET_LENGTH = 30 + RAPID_APPEND_TEXT = "this.value = (this.value + value)" \ + ".slice(0, this.maxLength >= 0 ? this.maxLength : undefined)" + + private + + def warn_unsupported(options) + unsupported = options.keys - SET_OPTIONS + return if unsupported.empty? + + names = unsupported.map(&:inspect).join(", ") + warn "Options passed to Node#set but Cuprite doesn't support #{names} - ignoring" + end + + def set_text(value, rapid: nil, clear: nil, **) + raise ArgumentError, CLEAR_ERROR unless [nil, :none, :backspace].include?(clear) || clear.is_a?(Array) + return command(:set, value) if value.empty? && clear.nil? + return if command { node.evaluate("this.readOnly || this.disabled") } + + node.focus + clear.nil? ? node.evaluate("this.select()") : move_caret_to_end + keys = clear_keys(clear) + node.type(*keys) unless keys.empty? + type_text(value.gsub(/\r\n?|\n/, "\r"), [nil, :none].include?(clear) ? rapid : false) + refocus + end + + def clear_keys(clear) + case clear + when :backspace then [:backspace] * node.evaluate("this.value.length") + when Array then clear + else [] + end + end + + def type_text(value, rapid) + middle = value[4...-3].to_s + if !middle.empty? && (rapid == true || (value.length > RAPID_SET_LENGTH && rapid != false)) + node.type(value[0..3]) + node.evaluate(RAPID_APPEND_TEXT, value: middle) + node.type(value[-3..]) + elsif !value.empty? + node.type(value) + end + end + + def move_caret_to_end + if tag_name == "textarea" + node.evaluate("this.setSelectionRange(this.value.length, this.value.length)") + else + node.type(:end) + end + end + + def refocus + node.evaluate("this.blur(); this.focus()") + rescue Ferrum::NodeNotFoundError + nil + end + end + end + end +end diff --git a/spec/node_spec.rb b/spec/node_spec.rb index dc6a0ee..4f94dda 100644 --- a/spec/node_spec.rb +++ b/spec/node_spec.rb @@ -477,6 +477,41 @@ expect(element.value).to eq((("a".."z").to_a.join * 2)[0, 30]) end + it "appends to the value with clear: :none" do + element = @session.find(:css, "#change_me") + element.set(" World", clear: :none) + expect(element.value).to eq("Hello! World") + end + + it "appends the middle of a long value from JS with clear: :none and rapid: true" do + element = @session.find(:css, "#change_me") + element.set(("a".."z").to_a.join * 2, clear: :none, rapid: true) + expect(element.value).to eq("Hello!#{('a'..'z').to_a.join * 2}") + end + + it "presses the given keys before typing with clear: Array" do + element = @session.find(:css, "#change_me") + element.set(" there!", clear: [:backspace]) + expect(element.value).to eq("Hello there!") + end + + it "raises for an unknown clear: value" do + element = @session.find(:css, "#change_me") + expect { element.set("a", clear: :foo) } + .to raise_error(ArgumentError, "clear: takes nil, :none, :backspace or an Array of keys") + end + + it "warns about options Cuprite doesn't support" do + element = @session.find(:css, "#change_me") + expect { element.set("a", foo: 1) } + .to output("Options passed to Node#set but Cuprite doesn't support :foo - ignoring\n").to_stderr + end + + it "does not warn about clear: on a checkbox" do + checkbox = @session.find(:css, "input[name=agree]") + expect { checkbox.set(true, clear: :backspace) }.not_to output.to_stderr + end + it "accepts negatives in a number field" do element = @session.find(:css, "#change_me_number") element.set(-100) @@ -759,6 +794,24 @@ input.set("") expect(output.text).to be_empty end + + it "deletes the value with backspaces before typing with clear: :backspace" do + input.set("ab") + input.set("c", clear: :backspace) + expect(output.text).to eq("keydown keypress input keyup keydown keypress input keyup change " \ + "keydown keyup keydown input keyup keydown input keyup " \ + "keydown keypress input keyup change") + expect(input.value).to eq("c") + end + + it "only deletes the value with backspaces for an empty value with clear: :backspace" do + input.set("ab") + input.set("", clear: :backspace) + expect(output.text).to eq("keydown keypress input keyup keydown keypress input keyup change " \ + "keydown keyup keydown input keyup keydown input keyup change") + expect(output["data-input-type"]).to eq("deleteContentBackward") + expect(input.value).to be_empty + end end context "with date fields" do