Best JavaScript code snippet using playwright-internal
n2.schema.js
Source:n2.schema.js
...45var ARRAY = ':array';46const TAG = ':tag';47//============================================================48// Object49function parseSelectorString(selStr){50 if( '.' === selStr ){51 return new $n2.objectSelector.ObjectSelector([]);52 };53 54 var selectors = selStr.split('.');55 return new $n2.objectSelector.ObjectSelector(selectors);56};57//============================================================58var customFieldHandlers = {};59function registerCustomFieldHandler(opts_){60 var opts = $n2.extend({61 customType: null62 ,handler: null63 },opts_);64 65 if( typeof opts.customType === 'string'66 && typeof opts.handler === 'function' ){67 customFieldHandlers[opts.customType] = opts.handler;68 };69};70//============================================================71function _localizeString() {72 var args = [];73 args.push.apply(args,arguments);74 var options = args.pop();75 // Gets the text between start and end tags76 var text = options.fn(this);77 // Syntax is: <selector>(,<option>)*78 var splits = text.split(',');79 var key = splits[0];80 // <option> is one of:81 // - optionName82 // - optionName=optionValue83 // - optionsName=value1+value2+...84 var opts = {};85 for(var i=1,e=splits.length;i<e;++i){86 var optStr = splits[i];87 var optSplit = optStr.split('=');88 if( optSplit.length > 1 ){89 var valSplits = optSplit[1].split('+');90 if( valSplits.length > 1 ) {91 opts[optSplit[0]]=valSplits;92 } else {93 opts[optSplit[0]]=[optSplit[1]];94 };95 } else {96 opts[optSplit[0]]=[];97 };98 };99 100 // Get data from key101 var objSel = parseSelectorString(key);102 var s = objSel.getValue(this);103 if( s104 && typeof(s) === 'object' 105 && s.nunaliit_type === 'localized') {106 var lang = 'en';107 if( $n2.l10n && $n2.l10n.getLocale ){108 lang = $n2.l10n.getLocale().lang;109 };110 111 if( s[lang] ) {112 if( opts.html ) {113 return s[lang];114 };115 116 var escaped = $n2.utils.escapeHtml(s[lang]);117 return escaped;118 119 } else {120 // Find a language to fall back on121 var fbLang = 'en';122 if( !s[fbLang] ) {123 fbLang = null;124 for(var l in s){125 if( l.length > 0 && l[0] === ':' ){126 // ignore127 } else if( l === 'nunaliit_type' ) {128 // ignore129 } else if( s[l] ) { // ignore empty string130 fbLang = l;131 break;132 };133 };134 };135 136 if( fbLang ){137 var result = [];138 result.push('<span class="n2_localized_string n2_localize_fallback">');139 result.push('<span class="n2_localize_fallback_lang">(');140 result.push(fbLang);141 result.push(')</span>');142 if( s[fbLang] ){143 if( opts.html ) {144 result.push(''+s[fbLang]);145 } else {146 var escaped = $n2.utils.escapeHtml(s[fbLang]);147 result.push(escaped);148 };149 };150 result.push('</span>');151 return result.join('');152 153 } else {154 return '';155 };156 };157 158 } else if( typeof(s) === 'undefined' ) {159 return '';160 } else if( s === null ) {161 return '';162 163 } else {164 // Must be string, number, boolean, float, ...165 // From Handlebars, we do not get a real "string". Instead,166 // "this" is an object that reacts like string. ''+s becomes167 // a real javascript string.168 if( opts.html ) {169 return ''+s;170 };171 172 var escaped = $n2.utils.escapeHtml(''+s);173 return escaped;174 175 };176};177function _formSingleField(r,completeSelectors,options){178 179 // option: textarea180 if( options.textarea ){181 r.push('<textarea');182 } else if( options.checkbox ){183 r.push('<input type="checkbox"');184 } else if(options.tag) {185 r.push('<input type="search" placeholder="' + _loc('Add a tag') + '"');186 } else {187 r.push('<input type="text"');188 };189 190 // placeholder191 if( options.placeholder 192 && typeof options.placeholder[0] === 'string' ){193 var placeHolderValue = options.placeholder[0];194 placeHolderValue = placeHolderValue.replace(/&/g, '&');195 placeHolderValue = placeHolderValue.replace(/"/g, '"');196 r.push(' placeholder="');197 r.push( _loc(placeHolderValue) );198 r.push('"');199 };200 201 r.push(' class="n2schema_input');202 203 var selClass = createClassStringFromSelector(completeSelectors);204 r.push(' '+selClass);205 206 if( options.date ){207 r.push(' ' + typeClassStringPrefix + 'date');208 209 } else if( options.numeric ){210 r.push(' ' + typeClassStringPrefix + 'numeric');211 212 } else if( options.layers ){213 r.push(' ' + typeClassStringPrefix + 'layers');214 215 } else if( options.localized ){216 r.push(' ' + typeClassStringPrefix + 'localized');217 218 } else if(options.tag) {219 r.push(' ' + typeClassStringPrefix + 'tag');220 }221 if( options.textarea ){222 r.push('"></textarea>');223 } else if( options.checkbox ){224 r.push('"/>');225 } else {226 r.push('"/>');227 };228 if( options.date ){229 r.push('<div class="n2schema_help_date"></div>');230 }231 232 if( options.wikiTransform ){233 r.push('<div class="n2schema_help_wiki"></div>');234 };235};236function _formField() {237 // The arguments to handlebars block expression functions are:238 // ([obj,]options)239 // obj is not provided in this case, since we do not expect any arguments240 // to {{:field}}241 // options.fn is a function to render inner content242 // options.data is provided by helper that is rendering current portion243 // options.data.n2_selector is provided by the _array() helper244 // this points to the current object245 //246 // Syntax to :form is:247 // {{#:field}}<selector>(,<option>)*{{/:field}}248 var args = [];249 args.push.apply(args,arguments);250 var options = args.pop();251 252 // Compute current selector253 var currentSelector = null;254 if( options 255 && options.data 256 && options.data.n2_selector ){257 // Within an array, the current selector is passed in options258 currentSelector = options.data.n2_selector;259 } else if( typeof this === 'object' 260 && this !== null 261 && this[SELECT]){262 currentSelector = this[SELECT];263 };264 // Gets the text between start and end tags and265 // parse it266 var text = options.fn(this);267 268 var splits = text.split(',');269 var identifier = splits[0];270 var objSel = parseSelectorString(identifier);271 var obj = objSel.getValue(this);272 var completeSelectors = currentSelector.getChildSelector(objSel);273 274 if( obj275 && typeof obj === 'object'276 && !obj[SELECT] ){277 obj[SELECT] = completeSelectors;278 };279 280 // <option> is one of:281 // - optionName282 // - optionName=optionValue283 // - optionsName=value1+value2+...284 var opts = {};285 for(var i=1,e=splits.length;i<e;++i){286 var optStr = splits[i];287 var optSplit = optStr.split('=');288 if( optSplit.length > 1 ){289 var valSplits = optSplit[1].split('+');290 for(var j=0,k=valSplits.length; j<k; ++j){291 valSplits[j] = decodeURIComponent( valSplits[j] );292 };293 opts[optSplit[0]]=valSplits;294 } else {295 opts[optSplit[0]]=[];296 };297 };298 299 var r = [];300 301 r.push('<div class="n2schema_field_wrapper">');302 if( opts.custom ){303 r.push('<div class="n2schema_field_container n2schema_field_custom"');304 if( opts.custom.length > 0 && typeof opts.custom[0] === 'string'){305 r.push(' n2-custom-type="'+opts.custom+'"');306 } else {307 r.push(' nunaliit-error="Custom type not specified"');308 };309 r.push(' nunaliit-selector="'+completeSelectors.encodeForDomAttribute()+'"');310 r.push('>');311 r.push('</div>');312 313 314 } else if( obj && obj.nunaliit_type === 'localized' ) {315 var langs = getSortedLanguages(opts.localized, obj);316 317 // Turn on "localized" option, if not already on318 if( !opts.localized ){319 opts.localized = [];320 };321 322 for(var i=0,e=langs.length;i<e;++i){323 var lang = langs[i];324 325 var langSel = completeSelectors.getChildSelector(lang);326 r.push('<div class="n2schema_field_container n2schema_field_container_localized');327 if( opts.textarea ){328 r.push(' n2schema_field_container_textarea');329 };330 r.push('">');331 r.push('<span class="n2_localize_lang">('+lang+')</span>');332 _formSingleField(r,langSel,opts);333 r.push('</div>');334 };335 336 } else if( !obj && opts.localized ) {337 // This is a localized string that does not yet exist338 // This condition is true if obj is an empty string or339 // if obj is undefined (or null)340 var langs = getSortedLanguages(opts.localized, null);341 342 for(var i=0,e=langs.length;i<e;++i){343 var lang = langs[i];344 345 var langSel = completeSelectors.getChildSelector(lang);346 347 r.push('<div class="n2schema_field_container n2schema_field_container_localized');348 if( opts.textarea ){349 r.push(' n2schema_field_container_textarea');350 };351 r.push('">');352 r.push('<span class="n2_localize_lang">('+lang+')</span>');353 _formSingleField(r,langSel,opts);354 r.push('</div>');355 };356 } else if( opts.reference ) {357 var attr = completeSelectors.encodeForDomAttribute();358 r.push('<span class="n2schema_field_reference" nunaliit-selector="'+attr+'"');359 if( opts.search 360 && opts.search[0] ){361 r.push(' n2-search-func="'+opts.search[0]+'"');362 };363 r.push('></span>');364 } else if( opts.geometry ) {365 var attr = completeSelectors.encodeForDomAttribute();366 r.push('<textarea class="n2schema_field_geometry" nunaliit-selector="'+attr+'"');367 r.push('></textarea>');368 369 } else {370 r.push('<div class="n2schema_field_container');371 if( opts.textarea ){372 r.push(' n2schema_field_container_textarea');373 };374 r.push('">');375 _formSingleField(r,completeSelectors,opts);376 r.push('</div>');377 };378 r.push('</div>');379 380 return r.join('');381 382 function getSortedLanguages(langOpts, localizedStr){383 var langMap = {};384 385 if( localizedStr ){386 for(var lang in localizedStr){387 if( lang === 'nunaliit_type' || lang[0] === ':' ){388 // ignore389 } else {390 langMap[lang] = true;391 };392 };393 };394 if( langOpts ){395 for(var i=0,e=langOpts.length;i<e;++i){396 var lang = langOpts[i];397 langMap[lang] = true;398 };399 };400 401 var languages = $n2.languageSupport.getLanguages();402 if( languages ){403 for(var i=0,e=languages.length; i<e; ++i){404 var lang = languages[i].code;405 langMap[lang] = true;406 };407 };408 409 var langs = [];410 for(var lang in langMap){411 langs.push(lang);412 };413 414 var locale = $n2.l10n.getLocale();415 var localeLang = locale.lang;416 langs.sort(function(l1,l2){417 if( l1 === localeLang ) return -1;418 if( l2 === localeLang ) return 1;419 if( l1 < l2 ) return -1;420 if( l1 > l2 ) return 1;421 return 0;422 });423 424 return langs;425 };426};427function _inputField() {428 var args = [];429 args.push.apply(args,arguments);430 var options = args.pop();431 432 var text = options.fn(this);433 // Syntax is: <selector>(,<type>)?434 var splits = text.split(',');435 var key = splits[0];436 437 var completeSelectors = null;438 if( options439 && options.data440 && options.data.n2_selector ){441 completeSelectors = options.data.n2_selector;442 } else if( this[SELECT] ) {443 completeSelectors = this[SELECT];444 } else {445 return '';446 };447 if( '.' === key ) {448 // Current selector is fine449 } else {450 var sels = key.split('.');451 completeSelectors = completeSelectors.getChildSelector(sels);452 }; 453 454 var cl = 'n2schema_input ' + createClassStringFromSelector(completeSelectors);455 var type = '';456 if( splits[1] ) {457 type = ' n2schema_type_'+splits[1];458 };459 460 return cl + type;461};462function _arrayField() {463 var args = [];464 args.push.apply(args,arguments);465 var options = args.pop();466 467 var obj = args[0];468 var newType = null;469 if( args.length > 1 ){470 newType = args[1];471 };472 473 var r = [];474 475 r.push('<div class="n2schema_array">');476 if( obj && obj.length ) {477 for(var i=0,e=obj.length; i<e; ++i){478 var item = obj[i];479 480 var completeSelectors = obj[SELECT];481 completeSelectors = completeSelectors.getChildSelector(i);482 var cl = createClassStringFromSelector(completeSelectors);483 484 r.push('<div class="n2schema_array_item">');485 r.push('<div class="n2schema_array_item_buttons">');486 487 r.push('<div class="n2schema_array_item_delete '+cl+'"></div>');488 489 r.push('<div class="n2schema_array_item_up '+cl+'"></div>');490 491 r.push('<div class="n2schema_array_item_down '+cl+'"></div>');492 r.push('</div>'); // close buttons493 494 r.push('<div class="n2schema_array_item_wrapper">');495 496 r.push( options.fn(item,{data:{n2_selector:completeSelectors}}) );497 498 r.push('</div></div>');499 };500 };501 // Add a new item502 var arraySelector = undefined;503 if( obj ){504 arraySelector = obj[SELECT];505 } else if( options && options.ids && options.ids.length ){506 var selectors = [];507 pathFromData(options.data, selectors);508 selectors.push(options.ids[0]);509 arraySelector = new $n2.objectSelector.ObjectSelector(selectors);510 };511 if( arraySelector ){512 var arrayClass = createClassStringFromSelector(arraySelector);513 r.push('<div class="n2schema_array_add '+arrayClass+'"');514 if( newType ) {515 r.push('n2_array_new_type="'+newType+'"');516 };517 r.push('></div>');518 };519 520 r.push('</div>');521 522 return r.join('');523 524 function pathFromData(data, path){525 if( data._parent ){526 pathFromData(data._parent, path);527 };528 if( data.contextPath ){529 path.push(data.contextPath);530 };531 };532};533function _tagField() {534 var args = [];535 args.push.apply(args,arguments);536 var options = args.pop();537 538 var obj = args[0];539 540 var r = [];541 542 if( obj ) {543 var tags = obj.tags;544 if(tags && tags.length > 0) {545 for(var i=0,e=tags.length; i<e; ++i){546 var item = tags[i];547 548 var completeSelectors = tags[SELECT];549 completeSelectors = completeSelectors.getChildSelector(i);550 var cl = createClassStringFromSelector(completeSelectors);551 552 r.push('<div class="n2_tag_element">');553 r.push('<span>'+item+'</span>');554 r.push('<span aria-label="delete this tag" class="n2schema_tag_item_delete '+cl+'">×</span>')555 r.push('</div>');556 }557 }558 }559 var tagSelector = undefined;560 if( obj ){561 tagSelector = obj[SELECT];562 } else if( options && options.ids && options.ids.length ){563 var selectors = [];564 pathFromData(options.data, selectors);565 selectors.push(options.ids[0]);566 tagSelector = new $n2.objectSelector.ObjectSelector(selectors);567 }568 569 return r.join('');570 571 function pathFromData(data, path){572 if( data._parent ){573 pathFromData(data._parent, path);574 };575 if( data.contextPath ){576 path.push(data.contextPath);577 };578 };579};580function _selectorField(){581 // The arguments to handlebars block expression functions are:582 // ([obj,]options)583 // obj is not provided in this case, since we do not expect any arguments584 // to {{#:selector}}585 // options.fn is a function to render inner content586 // options.data is provided by helper that is rendering current portion587 // options.data.n2_selector is provided by the _array() helper588 // this points to the current object589 //590 // Syntax to :form is:591 // {{#:selector}}<selector>{{/:selector}}592 var args = [];593 args.push.apply(args,arguments);594 var options = args.pop();595 596 // Compute current selector597 var currentSelector = null;598 if( options 599 && options.data 600 && options.data.n2_selector ){601 // Within an array, the current selector is passed in options602 currentSelector = options.data.n2_selector;603 } else if( typeof this === 'object' 604 && this !== null 605 && this[SELECT]){606 currentSelector = this[SELECT];607 };608 609 if( !currentSelector ){610 return '';611 };612 // Gets the text between start and end tags and613 // parse it614 var text = options.fn(this);615 616 var objSel = parseSelectorString(text);617 var completeSelectors = currentSelector.getChildSelector(objSel);618 return completeSelectors.encodeForDomAttribute();619};620if( typeof(Handlebars) !== 'undefined' 621 && Handlebars.registerHelper ) {622 Handlebars.registerHelper(LOCALIZE ,_localizeString );623 Handlebars.registerHelper(FIELD ,_formField );624 Handlebars.registerHelper(INPUT ,_inputField );625 Handlebars.registerHelper(ARRAY ,_arrayField );626 Handlebars.registerHelper(TAG ,_tagField );627 Handlebars.registerHelper(SELECTOR ,_selectorField );628} else {629 $n2.log('Unable to register helper functions with Handlebars. Schemas will not work properly.');630};...
matchers.test.js
Source:matchers.test.js
...14 parseSelectorString,15} from '../src';16describe( 'matchElementName', () => {17 it( 'should match an explicit tag name', () => {18 const selectors = parseSelectorString( 'article' );19 const element = new Element( 'article' );20 expect( matchElementName( element, selectors[ 0 ] ) ).toBeTruthy();21 } );22 it( 'should match the universal selector', () => {23 const selectors = parseSelectorString( '*' );24 const element = new Element( 'article' );25 expect( matchElementName( element, selectors[ 0 ] ) ).toBeTruthy();26 } );27 it( 'should match if the selector does not contain a tag name', () => {28 const selectors = parseSelectorString( '.article' );29 const element = new Element( 'article' );30 expect( matchElementName( element, selectors[ 0 ] ) ).toBeTruthy();31 } );32 it( 'should not match if the selector contains a different tag name', () => {33 const selectors = parseSelectorString( 'div' );34 const element = new Element( 'article' );35 expect( matchElementName( element, selectors[ 0 ] ) ).not.toBeTruthy();36 } );37} );38describe( 'matchClassNames', () => {39 it( 'should match anything if the selector has no class names', () => {40 const selectors = parseSelectorString( 'div' );41 const element = new Element( 'div', { className: 'article' } );42 expect( matchClassNames( element, selectors[ 0 ] ) ).toBeTruthy();43 } );44 it( 'should match if neither the selector or the element has any class names', () => {45 const selectors = parseSelectorString( 'div' );46 const element = new Element( 'article' );47 expect( matchClassNames( element, selectors[ 0 ] ) ).toBeTruthy();48 } );49 it( 'should not match anything if the element has no class names', () => {50 const selectors = parseSelectorString( '.article' );51 const element = new Element( 'div' );52 expect( matchClassNames( element, selectors[ 0 ] ) ).not.toBeTruthy();53 } );54 it( 'should match if there is a 1:1 match', () => {55 const selectors = parseSelectorString( '.article' );56 const element = new Element( 'div', { className: 'article' } );57 expect( matchClassNames( element, selectors[ 0 ] ) ).toBeTruthy();58 } );59 it( 'should match if the selector includes one of the element classes', () => {60 const selectors = parseSelectorString( '.article' );61 const element = new Element( 'div', { className: 'post article' } );62 expect( matchClassNames( element, selectors[ 0 ] ) ).toBeTruthy();63 } );64 it( 'should not match if the selector includes more than the element classes', () => {65 const selectors = parseSelectorString( '.article.post' );66 const element = new Element( 'div', { className: 'article' } );67 expect( matchClassNames( element, selectors[ 0 ] ) ).not.toBeTruthy();68 } );69} );70describe( 'matchId', () => {71 it( 'should match when neither the element or selector have an id', () => {72 const selectors = parseSelectorString( 'div' );73 const element = new Element( 'article' );74 expect( matchId( element, selectors[ 0 ] ) ).toBeTruthy();75 } );76 it( 'should match when the element and selector have the same id', () => {77 const selectors = parseSelectorString( 'div#post-12' );78 const element = new Element( 'article', { id: 'post-12' } );79 expect( matchId( element, selectors[ 0 ] ) ).toBeTruthy();80 } );81 it( 'should match when the element has an id but the selector does not', () => {82 const selectors = parseSelectorString( 'div' );83 const element = new Element( 'article', { id: 'post-12' } );84 expect( matchId( element, selectors[ 0 ] ) ).toBeTruthy();85 } );86 it( 'should not match when the selector has an id but the element does not', () => {87 const selectors = parseSelectorString( 'div#post-12' );88 const element = new Element( 'article' );89 expect( matchId( element, selectors[ 0 ] ) ).not.toBeTruthy();90 } );91 it( 'should not match when the element and selector have a different id', () => {92 const selectors = parseSelectorString( 'div#post-12' );93 const element = new Element( 'article', { id: 'post-20' } );94 expect( matchId( element, selectors[ 0 ] ) ).not.toBeTruthy();95 } );96} );97describe( 'matchPseudos', () => {98 it( 'should match when the selector does not have pseudos', () => {99 const selectors = parseSelectorString( 'div' );100 const element = new Element( 'article' );101 expect( matchPseudos( element, selectors[ 0 ] ) ).toBeTruthy();102 } );103 it( 'should not match when the selector has pseudos', () => {104 const selectors = parseSelectorString( 'div:last-child' );105 const element = new Element( 'article' );106 expect( matchPseudos( element, selectors[ 0 ] ) ).not.toBeTruthy();107 } );108} );109describe( 'matchElement', () => {110 it( 'should match when all components match exactly', () => {111 const selectors = parseSelectorString( 'div#block-1.block.selected' );112 const element = new Element( 'div', { id: 'block-1', className: 'block selected' } );113 expect( matchElement( element, selectors[ 0 ] ) ).toBeTruthy();114 } );115 it( 'should not match when ID differs', () => {116 const selectors = parseSelectorString( 'div#block-2.block.selected' );117 const element = new Element( 'div', { id: 'block-1', className: 'block selected' } );118 expect( matchElement( element, selectors[ 0 ] ) ).not.toBeTruthy();119 } );120 it( 'should not match when class name differs', () => {121 const selectors = parseSelectorString( 'div#block-1.block.selected' );122 const element = new Element( 'div', { id: 'block-1', className: 'block' } );123 expect( matchElement( element, selectors[ 0 ] ) ).not.toBeTruthy();124 } );125 it( 'should not match when tagName differs', () => {126 const selectors = parseSelectorString( 'div#block-1.block.selected' );127 const element = new Element( 'section', { id: 'block-1', className: 'block selected' } );128 expect( matchElement( element, selectors[ 0 ] ) ).not.toBeTruthy();129 } );130 it( 'should not match when pseudos differ', () => {131 const selectors = parseSelectorString( 'div#block-1.block.selected:last-child' );132 const element = new Element( 'div', { id: 'block-1', className: 'block selected' } );133 expect( matchElement( element, selectors[ 0 ] ) ).not.toBeTruthy();134 } );135} );136describe( 'matchCSSPathWithSelector', () => {137 it( 'should match a selector with a single rule', () => {138 const selectors = parseSelectorString( 'div#block-1.block.selected' );139 const element = new Element( 'div', { id: 'block-1', className: 'block selected' } );140 const path = new Path( element );141 expect( matchCSSPathWithSelector( path, selectors[ 0 ] ) ).toBeTruthy();142 } );143 it( 'should match a selector with a descendant', () => {144 const selectors = parseSelectorString( '#main .post .post-title' );145 const main = new Element( 'main', { id: 'main' } );146 const article = new Element( 'article', { id: 'post-12', className: 'post published' } );147 const title = new Element( 'h1', { className: 'post-title' } );148 const path = new Path(149 title,150 new Path(151 article,152 new Path(153 main154 )155 )156 );157 expect( matchCSSPathWithSelector( path, selectors[ 0 ] ) ).toBeTruthy();158 } );159 it( 'should match a selector with an unsupported descendant operator', () => {160 const selectors = parseSelectorString( '#main>.post>.post-title' );161 const main = new Element( 'main', { id: 'main' } );162 const article = new Element( 'article', { id: 'post-12', className: 'post published' } );163 const title = new Element( 'h1', { className: 'post-title' } );164 const path = new Path(165 title,166 new Path(167 article,168 new Path(169 main170 )171 )172 );173 expect( matchCSSPathWithSelector( path, selectors[ 0 ] ) ).not.toBeTruthy();174 } );175 it( 'should not match a selector if the element does not have a matching parent', () => {176 const selectors = parseSelectorString( '.post .post-title' );177 const title = new Element( 'h1', { className: 'post-title' } );178 const path = new Path(179 title180 );181 expect( matchCSSPathWithSelector( path, selectors[ 0 ] ) ).not.toBeTruthy();182 } );183 it( 'should not match a selector with a descendant when one of the elements doesn not match', () => {184 const selectors = parseSelectorString( '#main .post .post-title' );185 const main = new Element( 'main' );186 const article = new Element( 'article', { id: 'post-12', className: 'post published' } );187 const title = new Element( 'h1', { className: 'post-title' } );188 const path = new Path(189 title,190 new Path(191 article,192 new Path(193 main194 )195 )196 );197 expect( matchCSSPathWithSelector( path, selectors[ 0 ] ) ).not.toBeTruthy();198 } );...
selectorParser.js
Source:selectorParser.js
...22 */23const customCSSNames = new Set(['not', 'is', 'where', 'has', 'scope', 'light', 'visible', 'text', 'text-matches', 'text-is', 'has-text', 'above', 'below', 'right-of', 'left-of', 'near', 'nth-match']);24exports.customCSSNames = customCSSNames;25function parseSelector(selector) {26 const result = parseSelectorString(selector);27 const parts = result.parts.map(part => {28 if (part.name === 'css' || part.name === 'css:light') {29 if (part.name === 'css:light') part.body = ':light(' + part.body + ')';30 const parsedCSS = (0, _cssParser.parseCSS)(part.body, customCSSNames);31 return {32 name: 'css',33 body: parsedCSS.selector34 };35 }36 return part;37 });38 return {39 selector,40 capture: result.capture,41 parts42 };43}44function parseSelectorString(selector) {45 let index = 0;46 let quote;47 let start = 0;48 const result = {49 parts: []50 };51 const append = () => {52 const part = selector.substring(start, index).trim();53 const eqIndex = part.indexOf('=');54 let name;55 let body;56 if (eqIndex !== -1 && part.substring(0, eqIndex).trim().match(/^[a-zA-Z_0-9-+:*]+$/)) {57 name = part.substring(0, eqIndex).trim();58 body = part.substring(eqIndex + 1);...
selectors.test.js
Source:selectors.test.js
...3 */4import { parseSelectorString, Selector, SelectorParent } from '../src';5describe( 'parseSelectorString', () => {6 it( 'should return an empty array from an empty string', () => {7 const selectors = parseSelectorString( '' );8 expect( selectors ).toBeInstanceOf( Array );9 } );10 it( 'should parse a single selector', () => {11 const selectors = parseSelectorString( 'article#post-12.post.published' );12 expect( selectors ).toBeInstanceOf( Array );13 expect( selectors.length ).toBe( 1 );14 const selector = selectors[ 0 ];15 expect( selector ).toBeInstanceOf( Selector );16 expect( selector.tagName ).toBe( 'article' );17 expect( selector.classNames ).toEqual( [ 'post', 'published' ] );18 expect( selector.id ).toBe( 'post-12' );19 expect( selector.pseudos ).toBeUndefined();20 expect( selector.attributes ).toBeUndefined();21 expect( selector.parent ).toBeUndefined();22 } );23 it( 'should parse a selector with descendants', () => {24 const selectors = parseSelectorString( 'main#main>article#post-12.post.published>h1.post-title' );25 expect( selectors ).toBeInstanceOf( Array );26 expect( selectors.length ).toBe( 1 );27 const headingSelector = selectors[ 0 ];28 expect( headingSelector ).toBeInstanceOf( Selector );29 expect( headingSelector.tagName ).toBe( 'h1' );30 expect( headingSelector.classNames ).toEqual( [ 'post-title' ] );31 expect( headingSelector.id ).toBeUndefined();32 expect( headingSelector.attributes ).toBeUndefined();33 expect( headingSelector.pseudos ).toBeUndefined();34 expect( headingSelector.parent ).toBeInstanceOf( SelectorParent );35 expect( headingSelector.parent.nestingOperator ).toBe( '>' );36 expect( headingSelector.parent.selector ).toBeDefined();37 const postSelector = headingSelector.parent.selector;38 expect( postSelector ).toBeInstanceOf( Selector );39 expect( postSelector.tagName ).toBe( 'article' );40 expect( postSelector.classNames ).toEqual( [ 'post', 'published' ] );41 expect( postSelector.id ).toBe( 'post-12' );42 expect( postSelector.attributes ).toBeUndefined();43 expect( postSelector.pseudos ).toBeUndefined();44 expect( postSelector.parent ).toBeInstanceOf( SelectorParent );45 expect( postSelector.parent.nestingOperator ).toBe( '>' );46 expect( postSelector.parent.selector ).toBeDefined();47 const mainSelector = postSelector.parent.selector;48 expect( mainSelector ).toBeInstanceOf( Selector );49 expect( mainSelector.tagName ).toBe( 'main' );50 expect( mainSelector.classNames ).toBeUndefined();51 expect( mainSelector.id ).toBe( 'main' );52 expect( mainSelector.attributes ).toBeUndefined();53 expect( mainSelector.pseudos ).toBeUndefined();54 expect( mainSelector.parent ).toBeUndefined();55 } );56 it( 'should parse a selector with attributes', () => {57 const selectors = parseSelectorString( 'a[target=_blank]' );58 expect( selectors ).toBeInstanceOf( Array );59 expect( selectors.length ).toBe( 1 );60 const selector = selectors[ 0 ];61 expect( selector ).toBeInstanceOf( Selector );62 expect( selector.tagName ).toBe( 'a' );63 expect( selector.classNames ).toBeUndefined();64 expect( selector.id ).toBeUndefined();65 expect( selector.pseudos ).toBeUndefined();66 expect( selector.attributes ).toMatchObject( [ {67 name: 'target',68 value: '_blank',69 operator: '=',70 } ] );71 expect( selector.parent ).toBeUndefined();...
selectors.js
Source:selectors.js
...7var _cssSelectorParser = require("css-selector-parser");8function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }9function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }10function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }11function parseSelectorString(selectorString) {12 var parser = new _cssSelectorParser.CssSelectorParser();13 parser.registerNestingOperators('>', '+', '~');14 parser.registerAttrEqualityMods('^', '$', '*', '~');15 var parsedRules = parser.parse(selectorString);16 /*17 CssSelectorParser converts a selector string into it's own structure.18 - For an empty string, it will return null.19 - If the string contains a single selector, it will return an object20 of type ruleSet.21 - If the string contains multiple selectors, it will return an object22 of type selectors, containing multiple ruleSets.23 */24 var rules;25 if (!parsedRules) {...
index.js
Source:index.js
1var Util = require('cts/util');2var JsonParser = require('./json-parser');3var CtsParser = require('./cts-parser');4var DependencySpec = require('./spec/dependency-spec');5var ForrestSpec = require('./spec/forrest-spec');6var SelectionSpec = require('./spec/selection-spec');7var TreeSpec = require('./spec/tree-spec');8var RelationSpec = require('./spec/relation-spec');9/* Helper: separates inline spec into FORMAT and BODY.10 *11 * Args:12 * - str: The string encoding of a CTS spec.13 *14 * str may be either <format>:<cts spec> or <cts spec>15 * <format> may be either 'json' or 'str'16 *17 * Returns:18 * Tuple of [format, specBody]19 */20var _typeAndBodyForInline = function(str) {21 var res = /^([a-zA-Z]+):(.*)$/.exec(str);22 if (res === null) {23 return ['string', str];24 } else {25 return [res[1], res[2]];26 }27};28/* Parses a forrest (externally linked) CTS sheet.29 *30 * Args:31 * - spec: the spec to parse32 * - format: the format which encodes the spec33 * - fromUrl: the url which loaded the spec34 *35 * Returns:36 * Promise for a ForrestSpec object37 */38var parseForrestSpec = function(spec, format, fromUrl) {39 if (format == 'json') {40 return JsonParser.parseForrestSpec(spec, fromUrl);41 } else if (format == 'string') {42 return CtsParser.parseForrestSpec(spec, fromUrl);43 } else {44 return Util.Promise.reject("I don't understand the CTS Format:" + format);45 }46};47/* Helper function which wraps parseForrestSpec.48 *49 * Args:50 * - spec: the spec to parse51 * - kind: the format which encodes the spec52 * - fromUrl: the url which loaded the spec53 */54var parse = function(spec, format, fromUrl) {55 if (typeof format == 'undefined') {56 format = 'string';57 }58 return parseForrestSpec(spec, format, fromUrl);59};60var parseSelectorString = function(str) {61 return CtsParser.parseSelector(str);62};63/* Parses an inline (in a DOM Note attribute) CTS sheet.64 *65 * Args:66 * - spec: the spec to parse67 * - node: the CTS node on which the spec was inlined68 * - intoForrest: the forrest into which to add this inline spec69 * - realizeTrees: (bool) should any unrealized trees referenced within70 * be automatically realized before promise is resolved?71 *72 * Returns:73 * Promise for a ForrestSpec object.74 */75var parseInlineSpecs = function(spec, node, intoForrest, realizeTrees) {76 var tup = _typeAndBodyForInline(spec);77 var kind = tup[0];78 var body = tup[1];79 if (kind == 'json') {80 return JsonParser.parseInlineSpecs(body, node, intoForrest, realizeTrees);81 } else if (kind == 'string') {82 return CtsParser.parseInlineSpecs(body, node, intoForrest, realizeTrees);83 } else {84 return Util.Promise.reject("I don't understand the CTS Format:" + kind);85 }86};87// var tryPop = function(str, r) {88// var match = r.exec(str);89// console.log(match);90// return;91// },92module.exports = {93 parseForrestSpec: parseForrestSpec,94 parse: parse,95 parseInlineSpecs: parseInlineSpecs,96 parseSelectorString: parseSelectorString,97 TreeSpec: TreeSpec,98 SelectionSpec: SelectionSpec,99 RelationSpec: RelationSpec,100 ForrestSpec: ForrestSpec,101 DependencySpec: DependencySpec...
matchers.js
Source:matchers.js
...64 matchParent( path, selector );65}66/* throws */67function matchCSSPathWithSelectorString( path, selectorString ) {68 const selectors = parseSelectorString( selectorString );69 for ( const selector of selectors ) {70 if ( matchCSSPathWithSelector( path, selector ) ) {71 return true;72 }73 }74 return false;75}76export {77 matchClassNames,78 matchCSSPathWithSelector,79 matchCSSPathWithSelectorString,80 matchElement,81 matchElementName,82 matchId,...
classns_c_s_s_parser.js
Source:classns_c_s_s_parser.js
1var classns_c_s_s_parser =2[3 [ "nsCSSParser", "db/d98/classns_c_s_s_parser.html#aa37247136e9959761fcdf805fe34a9e0", null ],4 [ "~nsCSSParser", "db/d98/classns_c_s_s_parser.html#aef1c1f8ece0d8a5e5bfc14f74382c072", null ],5 [ "EvaluateSupportsCondition", "db/d98/classns_c_s_s_parser.html#a7fedd5928541a62822692751511c9a4a", null ],6 [ "EvaluateSupportsDeclaration", "db/d98/classns_c_s_s_parser.html#a152a87eefa32f099bd7426c48da13089", null ],7 [ "ParseColorString", "db/d98/classns_c_s_s_parser.html#a659930538b174dec4233152ff8e47e0e", null ],8 [ "ParseDeclarations", "db/d98/classns_c_s_s_parser.html#ad4cfd841e8a303e53efcaab5a69c09d6", null ],9 [ "ParseKeyframeRule", "db/d98/classns_c_s_s_parser.html#a5e1f190a22aa2a149251961650533a83", null ],10 [ "ParseKeyframeSelectorString", "db/d98/classns_c_s_s_parser.html#a7c89edeb528275de0a98d145012998d5", null ],11 [ "ParseMediaList", "db/d98/classns_c_s_s_parser.html#a0fd797de8701f3649ef51244a4b315d0", null ],12 [ "ParseProperty", "db/d98/classns_c_s_s_parser.html#a021f1abfedc6ff42231fdae1515fb0a5", null ],13 [ "ParseRule", "db/d98/classns_c_s_s_parser.html#a933fd3d3ab7bb28bf38a3a6d471ada8c", null ],14 [ "ParseSelectorString", "db/d98/classns_c_s_s_parser.html#adebd81a26e6f648bdfeb031d90b0dfff", null ],15 [ "ParseSheet", "db/d98/classns_c_s_s_parser.html#a8db4fbed89137f8a43fc7daadb6ba191", null ],16 [ "ParseStyleAttribute", "db/d98/classns_c_s_s_parser.html#a88cc91a677d5b8137b11af5e6745d3aa", null ],17 [ "SetChildLoader", "db/d98/classns_c_s_s_parser.html#a16addf6766e36d482ee8747edec2f518", null ],18 [ "SetQuirkMode", "db/d98/classns_c_s_s_parser.html#a2c18c7566e3eebef3c97368aaf749adb", null ],19 [ "SetStyleSheet", "db/d98/classns_c_s_s_parser.html#ab068fbad8ff57956a40048ac3237e83e", null ],20 [ "Shutdown", "db/d98/classns_c_s_s_parser.html#a4ae8fccd6452c795040444f382460b2b", null ],21 [ "mImpl", "db/d98/classns_c_s_s_parser.html#ac555372cd6612dafdfa16f8de8d892af", null ]...
Using AI Code Generation
1const { parseSelectorString } = require('@playwright/test/lib/utils/selectorParser');2const { parseSelectorString } = require('@playwright/test/lib/utils/selectorParser');3const selector = parseSelectorString('css=div#id.class');4console.log(selector);5const { parseSelectorString } = require('@playwright/test/lib/utils/selectorParser');6const { parseSelectorString } = require('@playwright/test/lib/utils/selectorParser');7const selector = parseSelectorString('css=div#id.class');8console.log(selector);9const { parseSelectorString } = require('@playwright/test/lib/utils/selectorParser');10const { parseSelectorString } = require('@playwright/test/lib/utils/selectorParser');11const selector = parseSelectorString('css=div#id.class');12console.log(selector);13const { parseSelectorString } = require('@playwright/test/lib/utils/selectorParser');14const { parseSelectorString } = require('@playwright/test/lib/utils/selectorParser');15const selector = parseSelectorString('css=div#id.class');16console.log(selector);17const { parseSelectorString } = require('@playwright/test/lib/utils/selectorParser');18const { parseSelectorString } = require('@playwright/test/lib/utils/selectorParser');19const selector = parseSelectorString('css=div#id.class');20console.log(selector);21const { parseSelectorString } = require('@playwright/test/lib/utils/selectorParser');22const { parseSelectorString } = require('@playwright/test/lib/utils/selectorParser');23const selector = parseSelectorString('css=div#id.class');24console.log(selector);
Using AI Code Generation
1const { parseSelectorString } = require('playwright/lib/server/common/selectors');2const selector = parseSelectorString('css=button');3console.log(selector);4console.log(selector1);5const selector2 = parseSelectorString('text=Click me');6console.log(selector2);7const { parseSelectorString } = require('playwright/lib/server/common/selectors');8const selector = parseSelectorString('css=button');9console.log(selector);10console.log(selector1);11const selector2 = parseSelectorString('text=Click me');12console.log(selector2);13{ name: 'css', engine: 'css', selector: 'button' }14{ name: 'text', engine: 'text', selector: 'Click me' }15{ name: 'css', engine: 'css', selector: 'button' }16{ name: 'text', engine: 'text', selector: 'Click me' }17const { test, expect } = require('@playwright/test');18const { parseSelectorString } = require('playwright/lib/server/common/selectors');19test('My Test', async ({ page }) => {20 const selector = parseSelectorString('css=button');21 console.log(selector);22 console.log(selector1);23 const selector2 = parseSelectorString('text=Click me');24 console.log(selector2);25});26{ name: 'css', engine: 'css', selector: 'button' }27{ name: 'text', engine: 'text', selector: 'Click me' }
Using AI Code Generation
1const { parseSelectorString } = require('playwright/lib/server/selectors/selectorEngine');2const { parseSelector } = require('playwright/lib/server/selectors/selectorParser');3const selector = parseSelector('text=hello world');4const parsedSelector = parseSelectorString(selector);5console.log(parsedSelector);6const { parseSelectorString } = require('playwright/lib/server/selectors/selectorEngine');7const { parseSelector } = require('playwright/lib/server/selectors/selectorParser');8const selector = parseSelector('text=hello world');9const parsedSelector = parseSelectorString(selector);10console.log(parsedSelector);11const { parseSelectorString } = require('playwright/lib/server/selectors/selectorEngine');12const { parseSelector } = require('playwright/lib/server/selectors/selectorParser');13const selector = parseSelector('text=hello world');14const parsedSelector = parseSelectorString(selector);15console.log(parsedSelector);16const { parseSelectorString } = require('playwright/lib/server/selectors/selectorEngine');17const { parseSelector } = require('playwright/lib/server/selectors/selectorParser');18const selector = parseSelector('text=hello world');19const parsedSelector = parseSelectorString(selector);20console.log(parsedSelector);21const { parseSelectorString } = require('playwright/lib/server/selectors/selectorEngine');22const { parseSelector } = require('playwright/lib/server/selectors/selectorParser');23const selector = parseSelector('text=hello world');24const parsedSelector = parseSelectorString(selector);25console.log(parsedSelector);26const { parseSelectorString } =
Using AI Code Generation
1const { parseSelectorString } = require('@playwright/test/lib/server/selectors/selectorEngine');2const parsedSelector = parseSelectorString('css=div');3console.log(parsedSelector);4const { parseSelectorString } = require('@playwright/test/lib/server/selectors/selectorEngine');5const parsedSelector = parseSelectorString('css=div');6console.log(parsedSelector);7I am trying to use the parseSelectorString method of Playwright Internal API. I am using the following code to import the method. But I am getting an error that the module is not found. I am using the latest version of Playwright. I am using the following code to import the method. But I am getting an error that the module is not found. I am using the latest
Using AI Code Generation
1const { parseSelectorString } = require('playwright/lib/server/selectors/selectorEngine');2const selectorString = 'text=Sign In';3const { engine, selector, ...rest } = parseSelectorString(selectorString);4console.log(engine, selector, rest);5const { parseSelectorString } = require('playwright/lib/server/selectors/selectorEngine');6const { engine, selector, ...rest } = parseSelectorString(selectorString);7console.log(engine, selector, rest);8const { parseSelectorString } = require('playwright/lib/server/selectors/selectorEngine');9const selectorString = 'css=button';10const { engine, selector, ...rest } = parseSelectorString(selectorString);11console.log(engine, selector, rest);12const { parseSelectorString } = require('playwright/lib/server/selectors/selectorEngine');13const selectorString = 'css=button#signin';14const { engine, selector, ...rest } = parseSelectorString(selectorString);15console.log(engine, selector, rest);16const { parseSelectorString } = require('playwright/lib/server/selectors/selectorEngine');17const selectorString = 'css=button#signin';18const { engine, selector, ...rest } = parseSelectorString(selectorString);19console.log(engine, selector, rest);20const { parseSelectorString } = require('playwright/lib/server/selectors/selectorEngine');21const selectorString = 'css=button#signin';22const { engine, selector, ...rest } = parseSelectorString(selectorString);23console.log(engine, selector, rest);
Using AI Code Generation
1const { parseSelectorString } = require('@playwright/test/lib/server/selectorParser');2const selectorString = 'css=div > span';3const selector = parseSelectorString(selectorString);4console.log(selector);5const selector = parseSelectorString(selectorString);6console.log(selector);7const selectorString = 'text=Hello World';8const selector = parseSelectorString(selectorString);9console.log(selector);10const selectorString = 'data-testid=foo';11const selector = parseSelectorString(selectorString);12console.log(selector);13const selectorString = 'data-test-id=foo';14const selector = parseSelectorString(selectorString);15console.log(selector);16const selectorString = 'data-test=foo';17const selector = parseSelectorString(selectorString);18console.log(selector);19const selectorString = 'data-testid=foo >> text=Hello World';20const selector = parseSelectorString(selectorString);21console.log(selector);22const selectorString = 'data-testid=foo >> text=Hello World >> css=div > span';23const selector = parseSelectorString(selectorString);24console.log(selector);25const selector = parseSelectorString(selectorString);26console.log(selector);27const selector = parseSelectorString(selectorString);28console.log(selector);29const selector = parseSelectorString(selectorString);
Using AI Code Generation
1const { parseSelectorString } = require('playwright/lib/server/selectors/selectorEngine');2let selector = 'text=Click me';3let parsedSelector = parseSelectorString(selector);4console.log(parsedSelector);5const { parseSelectorString } = require('playwright/lib/server/selectors/selectorEngine');6let selector = 'text=Click me';7let parsedSelector = parseSelectorString(selector);8console.log(parsedSelector);9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const page = await browser.newPage();13 const selector = await page.$eval('text=Click me', (e) => e.getAttribute('selector'));14 console.log(selector);15 await browser.close();16})();
Using AI Code Generation
1const { parseSelectorString } = require('playwright/lib/utils/selectorParser');2console.log(parseSelectorString('text=Hello, World!'));3console.log(parseSelectorString('css=div >> text=Hello, World!'));4const { parseSelectorString } = require('playwright/lib/utils/selectorParser');5console.log(parseSelectorString('text=Hello, World!'));6console.log(parseSelectorString('css=div >> text=Hello, World!'));7const { parseSelectorString } = require('playwright/lib/utils/selectorParser');8console.log(parseSelectorString('text=Hello, World!'));9console.log(parseSelectorString('css=div >> text=Hello, World!'));
Using AI Code Generation
1const { parseSelectorString } = require('playwright/lib/client/selectorParser');2const selector = parseSelectorString('css=div');3console.log(selector);4{ name: 'css', engine: 'css', args: [ 'div' ] }5const { parseSelectorString } = require('playwright/lib/client/selectorParser');6class HelloSelector {7 constructor(selector) {8 this._selector = parseSelectorString(selector);9 }10 async _queryOne(engine, root) {11 const elements = await engine.querySelectorAll(this._selector, root);12 if (elements.length === 0) return null;13 const text = await elements[0].textContent();14 await elements[0].fill(text + ' Hello');15 return elements[0];16 }17 async queryAll(engine, root) {18 const elements = await engine.querySelectorAll(this._selector, root);19 for (const element of elements) {20 const text = await element.textContent();21 await element.fill(text + ' Hello');22 }23 return elements;24 }25}26module.exports = { HelloSelector };27const { HelloSelector } = require('./helloSelector');28const selector = new HelloSelector('css=div');29await page.waitForSelector(selector);30const selector = new HelloSelector('css=div');
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!