UNPKG

1.67 kBJavaScriptView Raw
1_ = require('lodash')
2cssToXPath = require('css-to-xpath')
3
4module.exports = exports = function() { // (text) or (selector, text) or (selector, text, returnSelectorNode)
5 var selector, text
6
7 // Returns XPath as a CasperJS XPath instance (NOT a string, if you want to get a string
8 // from it - get the .path field)
9
10 // Return text nodes which contain 'text'
11 // @param {string} text
12 if (arguments.length === 1) {
13 // Don't do anything if already is XPath (starts with //)
14 if ( /^\(?\/\//.test(arguments[0]) ) {
15 return arguments[0]
16 // If text starts with
17 // . # [ *
18 // treat it as css selector
19 } else if ( /^[\.#\[\*]/.test(arguments[0]) ) {
20 return cssToXPath(arguments[0])
21 } else {
22 text = xPathStringLiteral(arguments[0])
23 return "(//*[not(self::script)][contains(., " + text + ")])[last()]"
24 }
25 }
26
27 // Return the 'selector' nodes which contain 'text' anywhere in them
28 // @param {string} selector
29 // @param {string} text
30 // @param {boolean} returnSelectorNode
31 else if (arguments.length === 2) {
32 selector = arguments[0]
33 text = xPathStringLiteral(arguments[1])
34 return cssToXPath(selector).slice(1) + "[contains(., " + text + ")]"
35 }
36
37 else {
38 throw new Error("Invalid amount of arguments provided - #{ arguments.length }")
39 }
40}
41
42// http://stackoverflow.com/a/3425925
43function xPathStringLiteral(s) {
44 if (s.indexOf('"') === -1)
45 return '"'+s+'"'
46 if (s.indexOf("'") === -1)
47 return "'"+s+"'"
48 return 'concat("'+s.replace(/"/g, '",\'"\',"')+'")'
49}
50
51exports.stringLiteral = xPathStringLiteral
52exports.fromCss = function() {
53 return cssToXPath.apply(this, arguments).slice(1)
54}