Path: blob/trunk/rb/lib/selenium/webdriver/remote/bridge/locator_converter.rb
1990 views
# frozen_string_literal: true12# Licensed to the Software Freedom Conservancy (SFC) under one3# or more contributor license agreements. See the NOTICE file4# distributed with this work for additional information5# regarding copyright ownership. The SFC licenses this file6# to you under the Apache License, Version 2.0 (the7# "License"); you may not use this file except in compliance8# with the License. You may obtain a copy of the License at9#10# http://www.apache.org/licenses/LICENSE-2.011#12# Unless required by applicable law or agreed to in writing,13# software distributed under the License is distributed on an14# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY15# KIND, either express or implied. See the License for the16# specific language governing permissions and limitations17# under the License.1819module Selenium20module WebDriver21module Remote22class Bridge23class LocatorConverter24ESCAPE_CSS_REGEXP = /(['"\\#.:;,!?+<>=~*^$|%&@`{}\-\[\]()])/25UNICODE_CODE_POINT = 302627#28# Converts a locator to a specification compatible one.29# @param [String, Symbol] how30# @param [String] what31#3233def convert(how, what)34how = SearchContext.finders[how.to_sym] || how3536case how37when 'class name'38how = 'css selector'39what = ".#{escape_css(what.to_s)}"40when 'id'41how = 'css selector'42what = "##{escape_css(what.to_s)}"43when 'name'44how = 'css selector'45what = "*[name='#{escape_css(what.to_s)}']"46end4748if what.is_a?(Hash)49what = what.each_with_object({}) do |(h, w), hash|50h, w = convert(h.to_s, w)51hash[h] = w52end53end5455[how, what]56end5758private5960#61# Escapes invalid characters in CSS selector.62# @see https://mathiasbynens.be/notes/css-escapes63#6465def escape_css(string)66string = string.gsub(ESCAPE_CSS_REGEXP) { |match| "\\#{match}" }67string = "\\#{UNICODE_CODE_POINT + Integer(string[0])} #{string[1..]}" if string[0]&.match?(/[[:digit:]]/)6869string70end71end # LocatorConverter72end # Bridge73end # Remote74end # WebDriver75end # Selenium767778