module WatirExtensions
  module Element
    # Similar to #text method, except returns ONLY text that isn't contained within other tags
    # For example, if the paragraph element contains this HTML: <p><strong>Name: </strong>John Doe</p>
    # And paragraph.text returns "Name: John Doe"
    # Then paragraph.text_node returns only "John Doe"
    def text_node
      get_text_node_script = <<-JS
        var nodes = arguments[0].childNodes;
        var result = "";
        for(var i = 0; i < nodes.length; i++) {
          if(nodes[i].nodeType == Node.TEXT_NODE) { result += nodes[i].nodeValue; }
        }
        return result
      JS

      assert_exists
      driver.execute_script(get_text_node_script, @element)
    end

    # Watir::Element#hover broke when upgrading Selenium-webdriver to 3.4.0
    # TODO: delete this when Watir is updated
    def fixed_hover
      element_call(:wait_for_present) { driver.action.move_to(@element).perform }
    end

    # Workaround since .clear and .set() no longer seems to actually
    # clear or overwrite text fields (respectively) after updating to Chromedriver 2.43
    def clear_text_and_type(input_string)
      send_keys Array.new(value.length, :backspace)
      self.value = input_string
    end
  end
end
