How to use isClauseCombinator method in Playwright Internal

Best JavaScript code snippet using playwright-internal

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

cssParser.js

Source: cssParser.js Github

copy
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4  value: true
5});
6exports.parseCSS = parseCSS;
7exports.serializeSelector = serializeSelector;
8
9var _selectorErrors = require("./selectorErrors");
10
11var css = _interopRequireWildcard(require("./cssTokenizer"));
12
13function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
14
15function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
16
17/**
18 * Copyright (c) Microsoft Corporation.
19 *
20 * Licensed under the Apache License, Version 2.0 (the "License");
21 * you may not use this file except in compliance with the License.
22 * You may obtain a copy of the License at
23 *
24 * http://www.apache.org/licenses/LICENSE-2.0
25 *
26 * Unless required by applicable law or agreed to in writing, software
27 * distributed under the License is distributed on an "AS IS" BASIS,
28 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29 * See the License for the specific language governing permissions and
30 * limitations under the License.
31 */
32function parseCSS(selector, customNames) {
33  let tokens;
34
35  try {
36    tokens = css.tokenize(selector);
37    if (!(tokens[tokens.length - 1] instanceof css.EOFToken)) tokens.push(new css.EOFToken());
38  } catch (e) {
39    const newMessage = e.message + ` while parsing selector "${selector}"`;
40    const index = (e.stack || '').indexOf(e.message);
41    if (index !== -1) e.stack = e.stack.substring(0, index) + newMessage + e.stack.substring(index + e.message.length);
42    e.message = newMessage;
43    throw e;
44  }
45
46  const unsupportedToken = tokens.find(token => {
47    return token instanceof css.AtKeywordToken || token instanceof css.BadStringToken || token instanceof css.BadURLToken || token instanceof css.ColumnToken || token instanceof css.CDOToken || token instanceof css.CDCToken || token instanceof css.SemicolonToken || // TODO: Consider using these for something, e.g. to escape complex strings.
48    // For example :xpath{ (//div/bar[@attr="foo"])[2]/baz }
49    // Or this way :xpath( {complex-xpath-goes-here("hello")} )
50    token instanceof css.OpenCurlyToken || token instanceof css.CloseCurlyToken || // TODO: Consider treating these as strings?
51    token instanceof css.URLToken || token instanceof css.PercentageToken;
52  });
53  if (unsupportedToken) throw new _selectorErrors.InvalidSelectorError(`Unsupported token "${unsupportedToken.toSource()}" while parsing selector "${selector}"`);
54  let pos = 0;
55  const names = new Set();
56
57  function unexpected() {
58    return new _selectorErrors.InvalidSelectorError(`Unexpected token "${tokens[pos].toSource()}" while parsing selector "${selector}"`);
59  }
60
61  function skipWhitespace() {
62    while (tokens[pos] instanceof css.WhitespaceToken) pos++;
63  }
64
65  function isIdent(p = pos) {
66    return tokens[p] instanceof css.IdentToken;
67  }
68
69  function isString(p = pos) {
70    return tokens[p] instanceof css.StringToken;
71  }
72
73  function isNumber(p = pos) {
74    return tokens[p] instanceof css.NumberToken;
75  }
76
77  function isComma(p = pos) {
78    return tokens[p] instanceof css.CommaToken;
79  }
80
81  function isCloseParen(p = pos) {
82    return tokens[p] instanceof css.CloseParenToken;
83  }
84
85  function isStar(p = pos) {
86    return tokens[p] instanceof css.DelimToken && tokens[p].value === '*';
87  }
88
89  function isEOF(p = pos) {
90    return tokens[p] instanceof css.EOFToken;
91  }
92
93  function isClauseCombinator(p = pos) {
94    return tokens[p] instanceof css.DelimToken && ['>', '+', '~'].includes(tokens[p].value);
95  }
96
97  function isSelectorClauseEnd(p = pos) {
98    return isComma(p) || isCloseParen(p) || isEOF(p) || isClauseCombinator(p) || tokens[p] instanceof css.WhitespaceToken;
99  }
100
101  function consumeFunctionArguments() {
102    const result = [consumeArgument()];
103
104    while (true) {
105      skipWhitespace();
106      if (!isComma()) break;
107      pos++;
108      result.push(consumeArgument());
109    }
110
111    return result;
112  }
113
114  function consumeArgument() {
115    skipWhitespace();
116    if (isNumber()) return tokens[pos++].value;
117    if (isString()) return tokens[pos++].value;
118    return consumeComplexSelector();
119  }
120
121  function consumeComplexSelector() {
122    const result = {
123      simples: []
124    };
125    skipWhitespace();
126
127    if (isClauseCombinator()) {
128      // Put implicit ":scope" at the start. https://drafts.csswg.org/selectors-4/#absolutize
129      result.simples.push({
130        selector: {
131          functions: [{
132            name: 'scope',
133            args: []
134          }]
135        },
136        combinator: ''
137      });
138    } else {
139      result.simples.push({
140        selector: consumeSimpleSelector(),
141        combinator: ''
142      });
143    }
144
145    while (true) {
146      skipWhitespace();
147
148      if (isClauseCombinator()) {
149        result.simples[result.simples.length - 1].combinator = tokens[pos++].value;
150        skipWhitespace();
151      } else if (isSelectorClauseEnd()) {
152        break;
153      }
154
155      result.simples.push({
156        combinator: '',
157        selector: consumeSimpleSelector()
158      });
159    }
160
161    return result;
162  }
163
164  function consumeSimpleSelector() {
165    let rawCSSString = '';
166    const functions = [];
167
168    while (!isSelectorClauseEnd()) {
169      if (isIdent() || isStar()) {
170        rawCSSString += tokens[pos++].toSource();
171      } else if (tokens[pos] instanceof css.HashToken) {
172        rawCSSString += tokens[pos++].toSource();
173      } else if (tokens[pos] instanceof css.DelimToken && tokens[pos].value === '.') {
174        pos++;
175        if (isIdent()) rawCSSString += '.' + tokens[pos++].toSource();else throw unexpected();
176      } else if (tokens[pos] instanceof css.ColonToken) {
177        pos++;
178
179        if (isIdent()) {
180          if (!customNames.has(tokens[pos].value.toLowerCase())) {
181            rawCSSString += ':' + tokens[pos++].toSource();
182          } else {
183            const name = tokens[pos++].value.toLowerCase();
184            functions.push({
185              name,
186              args: []
187            });
188            names.add(name);
189          }
190        } else if (tokens[pos] instanceof css.FunctionToken) {
191          const name = tokens[pos++].value.toLowerCase();
192
193          if (!customNames.has(name)) {
194            rawCSSString += `:${name}(${consumeBuiltinFunctionArguments()})`;
195          } else {
196            functions.push({
197              name,
198              args: consumeFunctionArguments()
199            });
200            names.add(name);
201          }
202
203          skipWhitespace();
204          if (!isCloseParen()) throw unexpected();
205          pos++;
206        } else {
207          throw unexpected();
208        }
209      } else if (tokens[pos] instanceof css.OpenSquareToken) {
210        rawCSSString += '[';
211        pos++;
212
213        while (!(tokens[pos] instanceof css.CloseSquareToken) && !isEOF()) rawCSSString += tokens[pos++].toSource();
214
215        if (!(tokens[pos] instanceof css.CloseSquareToken)) throw unexpected();
216        rawCSSString += ']';
217        pos++;
218      } else {
219        throw unexpected();
220      }
221    }
222
223    if (!rawCSSString && !functions.length) throw unexpected();
224    return {
225      css: rawCSSString || undefined,
226      functions
227    };
228  }
229
230  function consumeBuiltinFunctionArguments() {
231    let s = '';
232
233    while (!isCloseParen() && !isEOF()) s += tokens[pos++].toSource();
234
235    return s;
236  }
237
238  const result = consumeFunctionArguments();
239  if (!isEOF()) throw new _selectorErrors.InvalidSelectorError(`Error while parsing selector "${selector}"`);
240  if (result.some(arg => typeof arg !== 'object' || !('simples' in arg))) throw new _selectorErrors.InvalidSelectorError(`Error while parsing selector "${selector}"`);
241  return {
242    selector: result,
243    names: Array.from(names)
244  };
245}
246
247function serializeSelector(args) {
248  return args.map(arg => {
249    if (typeof arg === 'string') return `"${arg}"`;
250    if (typeof arg === 'number') return String(arg);
251    return arg.simples.map(({
252      selector,
253      combinator
254    }) => {
255      let s = selector.css || '';
256      s = s + selector.functions.map(func => `:${func.name}(${serializeSelector(func.args)})`).join('');
257      if (combinator) s += ' ' + combinator;
258      return s;
259    }).join(' ');
260  }).join(', ');
261}
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Internal on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)