1# Copyright (c) 2012 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import re
6
7from telemetry.core import util
8from telemetry.core import exceptions
9from telemetry.page.actions import page_action
10
11def _EscapeSelector(selector):
12  return selector.replace('\'', '\\\'')
13
14class ClickElementAction(page_action.PageAction):
15  def __init__(self, attributes=None):
16    super(ClickElementAction, self).__init__(attributes)
17
18  def RunAction(self, page, tab, previous_action):
19    def DoClick():
20      if hasattr(self, 'selector'):
21        code = ('document.querySelector(\'' + _EscapeSelector(self.selector) +
22            '\').click();')
23        try:
24          tab.ExecuteJavaScript(code)
25        except exceptions.EvaluateException:
26          raise page_action.PageActionFailed(
27              'Cannot find element with selector ' + self.selector)
28      elif hasattr(self, 'text'):
29        callback_code = 'function(element) { element.click(); }'
30        try:
31          util.FindElementAndPerformAction(tab, self.text, callback_code)
32        except exceptions.EvaluateException:
33          raise page_action.PageActionFailed(
34              'Cannot find element with text ' + self.text)
35      elif hasattr(self, 'xpath'):
36        code = ('document.evaluate("%s",'
37                                   'document,'
38                                   'null,'
39                                   'XPathResult.FIRST_ORDERED_NODE_TYPE,'
40                                   'null)'
41                  '.singleNodeValue.click()' % re.escape(self.xpath))
42        try:
43          tab.ExecuteJavaScript(code)
44        except exceptions.EvaluateException:
45          raise page_action.PageActionFailed(
46              'Cannot find element with xpath ' + self.xpath)
47      else:
48        raise page_action.PageActionFailed(
49            'No condition given to click_element')
50
51    DoClick()
52