Best JavaScript code snippet using playwright-internal
parse-css.min.js
Source: parse-css.min.js
1/**2 * what-input - A global utility for tracking the current input method (mouse, keyboard or touch).3 * @version v4.2.04 * @link https://github.com/ten1seven/what-input5 * @license MIT6 */7/* jQuery based CSS parser8// documentation: http://youngisrael-stl.org/wordpress/2009/01/16/jquery-css-parser/9// Version: 1.510// Copyright (c) 2011 Daniel Wachsstock11// MIT license:12// Permission is hereby granted, free of charge, to any person13// obtaining a copy of this software and associated documentation14// files (the "Software"), to deal in the Software without15// restriction, including without limitation the rights to use,16// copy, modify, merge, publish, distribute, sublicense, and/or sell17// copies of the Software, and to permit persons to whom the18// Software is furnished to do so, subject to the following19// conditions:20// The above copyright notice and this permission notice shall be21// included in all copies or substantial portions of the Software.22// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,23// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES24// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND25// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT26// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,27// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING28// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR29// OTHER DEALINGS IN THE SOFTWARE.*/30(function($){31 // utility function, since we want to allow $('style') and $(document), so we need to look for elements in the jQuery object ($.fn.filter) and elements that are children of the jQuery object ($.fn.find)32 $.fn.findandfilter = function(selector){33 var ret = this.filter(selector).add(this.find(selector));34 ret.prevObject = ret.prevObject.prevObject; // maintain the filter/end chain correctly (the filter and the find both push onto the chain).35 return ret;36 };37 $.fn.parsecss = function(callback, parseAttributes){38 var parse = function(str) { $.parsecss(str, callback) }; // bind the callback39 this40 .findandfilter ('style').each (function(){41 parse(this.innerHTML);42 })43 .end()44 .findandfilter ('link[type="text/css"]').each (function(){45 // only get the stylesheet if it's not disabled, it won't trigger cross-site security (doesn't start with anything like http:) and it uses the appropriate media)46 if (!this.disabled && !/^\w+:/.test($(this).attr('href')) && $.parsecss.mediumApplies(this.media)) $.get(this.href, parse);47 })48 .end();49 if (parseAttributes){50 $.get(location.pathname+location.search, function(HTMLtext) {51 styleAttributes(HTMLtext, callback);52 }, 'text');53 }54 return this;55 };56 $.parsecss = function(str, callback){57 var ret = {};58 str = munge(str).replace(/@(([^;`]|`[^b]|`b[^%])*(`b%)?);?/g, function(s,rule){59 // @rules end with ; or a block, with the semicolon not being part of the rule but the closing brace (represented by `b%) is60 processAtRule($.trim(rule), callback);61 return '';62 });63 $.each (str.split('`b%'), function(i,css){ // split on the end of a block64 css = css.split('%b`'); // css[0] is the selector; css[1] is the index in munged for the cssText65 if (css.length < 2) return; // invalid css66 css[0] = restore(css[0]);67 ret[css[0]] = $.extend(ret[css[0]] || {}, parsedeclarations(css[1]));68 });69 callback(ret);70 };71 // explanation of the above: munge(str) strips comments and encodes strings and brace-delimited blocks, so that72 // %b` corresponds to { and `b% corresponds to }73 // munge(str) replaces blocks with %b`1`b% (for example)74 //75 // str.split('`b%') splits the text by '}' (which ends every CSS statement)76 // Each so the each(munge(str... function(i,css)77 // is called with css being empty (the string after the last delimiter), an @rule, or a css statement of the form78 // selector %b`n where n is a number (the block was turned into %b`n`b% by munge). Splitting on %b` gives the selector and the79 // number corresponding to the declaration block. parsedeclarations will do restore('%b`'+n+'`b%') to get it back.80 // if anyone ever implements http://www.w3.org/TR/cssom-view/#the-media-interface, we're ready81 $.parsecss.mediumApplies = (window.media && window.media.query) || function(str){82 if (!str) return true; // if no descriptor, everything applies83 if (str in media) return media[str];84 var style = $('<style media="'+str+'">body {position: relative; z-index: 1;}</style>').appendTo('head');85 return media[str] = [$('body').css('z-index')==1, style.remove()][0]; // the [x,y][0] is a silly hack to evaluate two expressions and return the first86 };87 $.parsecss.isValidSelector = function(str){88 var s = $('<style>'+str+'{}</style>').appendTo('head')[0];89 // s.styleSheet is IE; it accepts illegal selectors but converts them to UNKNOWN. Standards-based (s.shee.cssRules) just reject the rule90 return [s.styleSheet ? !/UNKNOWN/i.test(s.styleSheet.cssText) : !!s.sheet.cssRules.length, $(s).remove()][0]; // the [x,y][0] is a silly hack to evaluate two expressions and return the first91 };92 $.parsecss.parseArguments = function(str){93 if (!str) return [];94 var ret = [], mungedArguments = munge(str, true).split(/\s+/); // can't use $.map because it flattens arrays !95 for (var i = 0; i < mungedArguments.length; ++i) {96 var a = restore(mungedArguments[i]);97 try{98 ret.push(eval('('+a+')'));99 }catch(err){100 ret.push(a);101 }102 }103 return ret;104 };105 // uses the parsed css to apply useful jQuery functions106 $.parsecss.jquery = function(css){107 for (var selector in css){108 for (var property in css[selector]){109 var match = /^-jquery(-(.*))?/.exec(property);110 if (!match) continue;111 var value = munge(css[selector][property]).split('!'); // exclamation point separates the parts of livequery actions112 var which = match[2];113 dojQuery(selector, which, restore(value[0]), restore(value[1]));114 }115 }116 };117 // expose the styleAttributes function118 $.parsecss.styleAttributes = styleAttributes;119 // caches120 var media = {}; // media description strings121 var munged = {}; // strings that were removed by the parser so they don't mess up searching for specific characters122 // private functions123 function parsedeclarations(index){ // take a string from the munged array and parse it into an object of property: value pairs124 var str = munged[index].replace(/^{|}$/g, ''); // find the string and remove the surrounding braces125 str = munge(str); // make sure any internal braces or strings are escaped126 var parsed = {};127 $.each (str.split(';'), function (i, decl){128 decl = decl.split(':');129 if (decl.length < 2) return;130 parsed[restore(decl[0])] = restore(decl.slice(1).join(':'));131 });132 return parsed;133 }134 // replace strings and brace-surrounded blocks with %s`number`s% and %b`number`b%. By successively taking out the innermost135 // blocks, we ensure that we're matching braces. No way to do this with just regular expressions. Obviously, this assumes no one136 // would use %s` in the real world.137 // Turns out this is similar to the method that Dean Edwards used for his CSS parser in IE7.js (http://code.google.com/p/ie7-js/)138 var REbraces = /{[^{}]*}/;139 var REfull = /\[[^\[\]]*\]|{[^{}]*}|\([^()]*\)|function(\s+\w+)?(\s*%b`\d+`b%){2}/; // match pairs of parentheses, brackets, and braces and function definitions.140 var REatcomment = /\/\*@((?:[^\*]|\*[^\/])*)\*\//g; // comments of the form /*@ text */ have text parsed141 // we have to combine the comments and the strings because comments can contain string delimiters and strings can contain comment delimiters142 // var REcomment = /\/\*(?:[^\*]|\*[^\/])*\*\/|<!--|-->/g; // other comments are stripped. (this is a simplification of real SGML comments (see http://htmlhelp.com/reference/wilbur/misc/comment.html) , but it's what real browsers use)143 // var REstring = /\\.|"(?:[^\\\"]|\\.|\\\n)*"|'(?:[^\\\']|\\.|\\\n)*'/g; // match escaped characters and strings144 var REcomment_string =145 /(?:\/\*(?:[^\*]|\*[^\/])*\*\/)|(\\.|"(?:[^\\\"]|\\.|\\\n)*"|'(?:[^\\\']|\\.|\\\n)*')/g;146 var REmunged = /%\w`(\d+)`\w%/;147 var uid = 0; // unique id number148 function munge(str, full){149 str = str150 .replace(REatcomment,'$1') // strip /*@ comments but leave the text (to let invalid CSS through)151 .replace(REcomment_string, function (s, string){ // strip strings and escaped characters, leaving munged markers, and strip comments152 if (!string) return '';153 var replacement = '%s`'+(++uid)+'`s%';154 munged[uid] = string.replace(/^\\/,''); // strip the backslash now155 return replacement;156 })157 ;158 // need a loop here rather than .replace since we need to replace nested braces159 var RE = full ? REfull : REbraces;160 while (match = RE.exec(str)){161 replacement = '%b`'+(++uid)+'`b%';162 munged[uid] = match[0];163 str = str.replace(RE, replacement);164 }165 return str;166 }167 function restore(str){168 if (str === undefined) return str;169 while (match = REmunged.exec(str)){170 str = str.replace(REmunged, munged[match[1]]);171 }172 return $.trim(str);173 }174 function processAtRule (rule, callback){175 var split = rule.split(/\s+/); // split on whitespace176 var type = split.shift(); // first word177 if (type=='media'){178 var css = restore(split.pop()).slice(1,-1); // last word is the rule; need to strip the outermost braces179 if ($.parsecss.mediumApplies(split.join(' '))){180 $.parsecss(css, callback);181 }182 }else if (type=='import'){183 var url = restore(split.shift());184 if ($.parsecss.mediumApplies(split.join(' '))){185 url = url.replace(/^url\(|\)$/gi, '').replace(/^["']|["']$/g, ''); // remove the url('...') wrapper186 $.get(url, function(str) { $.parsecss(str, callback) });187 }188 }189 }190 function dojQuery (selector, which, value, value2){ // value2 is the value for the livequery no longer match191 if (/show|hide/.test(which)) which += 'Default'; // -jquery-show is a shortcut for -jquery-showDefault192 if (value2 !== undefined && $.livequery){193 // mode is 0 for a static value (can be evaluated when parsed);194 // 1 for delayed (refers to "this" which means it needs to be evaluated separately for each element matched), and195 // 2 for livequery; evaluated whenever elments change196 var mode = 2;197 }else{198 mode = /\bthis\b/.test(value) ? 1 : 0;199 }200 if (which && $.fn[which]){201 // a plugin202 // late bind parseArguments so "this" is defined correctly203 function p (str) { return function() { return $.fn[which].apply($(this), $.parsecss.parseArguments.call(this, str)) } };204 switch (mode){205 case 0: return $.fn[which].apply($(selector), $.parsecss.parseArguments(value));206 case 1: return $(selector).each(p(value));207 case 2: return (new $.livequery(selector, document, undefined, p(value), value2 === '' ? undefined : p(value2))).run();208 }209 }else if (which){210 // a plugin but one that was not defined211 return undefined;212 }else{213 // straight javascript214 switch (mode){215 case 0: return eval(value);216 case 1: return $(selector).each(Function(value));217 case 2: return (new $.livequery(selector, document, undefined, Function(value), value2 === '' ? undefined : Function(value2))).run();218 }219 }220 }221 // override show and hide. $.data(el, 'showDefault') is a function that is to be used for show if no arguments are passed in (if there are arguments, they override the stored function)222 // Many of the effects call the native show/hide() with no arguments, resulting in an infinite loop.223 var _show = {show: $.fn.show, hide: $.fn.hide}; // save the originals224 $.each(['show','hide'], function(){225 var which = this, show = _show[which], plugin = which+'Default';226 $.fn[which] = function(){227 if (arguments.length > 0) return show.apply(this, arguments);228 return this.each(function(){229 var fn = $.data(this, plugin), $this = $(this);230 if (fn){231 $.removeData(this, plugin); // prevent the infinite loop232 fn.call($this);233 $this.queue(function(){$this.data(plugin, fn).dequeue()}); // put the function back at the end of the animation234 }else{235 show.call($this);236 }237 });238 };239 $.fn[plugin] = function(){240 var args = $.makeArray(arguments), name = args[0];241 if ($.fn[name]){ // a plugin242 args.shift();243 var fn = $.fn[name];244 }else if ($.effects && $.effects[name]){ // a jQuery UI effect. They require an options object as the second argument245 if (typeof args[1] != 'object') args.splice(1,0,{});246 fn = _show[which];247 }else{ // regular show/hide248 fn = _show[which];249 }250 return this.data(plugin, function(){fn.apply(this,args)});251 };252 });253 // experimental: find unrecognized style attributes in elements by reloading the code as text254 var RESGMLcomment = /<!--([^-]|-[^-])*-->/g; // as above, a simplification of real comments. Don't put -- in your HTML comments!255 var REnotATag = /(>)[^<]*/g;256 var REtag = /<(\w+)([^>]*)>/g;257 function styleAttributes (HTMLtext, callback) {258 var ret = '', style, tags = {}; // keep track of tags so we can identify elements unambiguously259 HTMLtext = HTMLtext.replace(RESGMLcomment, '').replace(REnotATag, '$1');260 munge(HTMLtext).replace(REtag, function(s, tag, attrs){261 tag = tag.toLowerCase();262 if (tags[tag]) ++tags[tag]; else tags[tag] = 1;263 if (style = /\bstyle\s*=\s*(%s`\d+`s%)/i.exec(attrs)){ // style attributes must be of the form style = "a: bc" ; they must be in quotes. After munging, they are marked with numbers. Grab that number264 var id = /\bid\s*=\s*(\S+)/i.exec(attrs); // find the id if there is one.265 if (id) id = '#'+restore(id[1]).replace(/^['"]|['"]$/g,''); else id = tag + ':eq(' + (tags[tag]-1) + ')';266 ret += [id, '{', restore(style[1]).replace(/^['"]|['"]$/g,''),'}'].join('');267 }268 });269 $.parsecss(ret, callback);270 }...
parse-css.test.js
Source: parse-css.test.js
1// Dependencies2// =============================================================================3import parseCss from '../src/parse-css';4import { expect } from 'chai';5// Suite6// =============================================================================7describe('parse-css', function() {8 const fixtures = window.__FIXTURES__;9 // Tests: Parsing10 // -------------------------------------------------------------------------11 describe('Parsing', function() {12 it('parses CSS to an AST (object)', async function() {13 const css = fixtures['test-parse.css'];14 const ast = parseCss(css);15 expect(ast instanceof Object).to.be.true;16 expect(ast).to.have.property('type', 'stylesheet');17 });18 });19 // Tests: Errors20 // -------------------------------------------------------------------------21 describe('Errors', function() {22 it('throws an error when parsing missing opening bracket', function() {23 const css = 'p color: red; }';24 const badFn = function() {25 parseCss(css);26 };27 expect(badFn).to.throw(Error, 'missing \'{\'');28 });29 it('throws an error when parsing missing @rule opening bracket', function() {30 const css = '@media screen p color: red; }';31 const badFn = function() {32 parseCss(css);33 };34 expect(badFn).to.throw(Error, 'missing \'{\'');35 });36 it('throws an error when parsing missing closing bracket', function() {37 const css = 'p { color: red;';38 const badFn = function() {39 parseCss(css);40 };41 expect(badFn).to.throw(Error, 'missing \'}\'');42 });43 it('throws an error when parsing missing @rule closing bracket', function() {44 const css = '@media screen { p { color: red; }';45 const badFn = function() {46 parseCss(css);47 };48 expect(badFn).to.throw(Error, 'missing \'}\'');49 });50 it('throws an error when parsing missing end of comment', function() {51 const css = '/* Comment *';52 const badFn = function() {53 parseCss(css);54 };55 expect(badFn).to.throw(Error, 'end of comment');56 });57 it('throws an error when parsing extra closing bracket', function() {58 const css = 'p { color: red; }}';59 const badFn = function() {60 parseCss(css);61 };62 expect(badFn).to.throw(Error, 'closing bracket');63 });64 it('throws an error when parsing property missing colon', function() {65 const css = 'p { color red; }';66 const badFn = function() {67 parseCss(css);68 };69 expect(badFn).to.throw(Error, 'property missing \':\'');70 });71 it('throws an error when parsing missing selector', function() {72 const css = '{ color: red; }';73 const badFn = function() {74 parseCss(css);75 };76 expect(badFn).to.throw(Error, 'selector missing');77 });78 it('throws an error when parsing @keyframes with missing name', function() {79 const css = '@keyframes { from { opacity: 0; } to { opacity: 1; } }';80 const badFn = function() {81 parseCss(css);82 };83 expect(badFn).to.throw(Error, '@keyframes missing name');84 });85 it('throws an error when parsing @keyframes with missing open bracket', function() {86 const css = '@keyframes test from { opacity: 0; } to { opacity: 1; } }';87 const badFn = function() {88 parseCss(css);89 };90 expect(badFn).to.throw(Error, '@keyframes missing \'{\'');91 });92 it('throws an error when parsing @keyframes with missing closing bracket', function() {93 const css = '@keyframes test { from { opacity: 0; } to { opacity: 1; }';94 const badFn = function() {95 parseCss(css);96 };97 expect(badFn).to.throw(Error, '@keyframes missing \'}\'');98 });99 });100 // Tests: Options101 // -------------------------------------------------------------------------102 describe('Options', function() {103 describe('onlyVars', function() {104 const cssVarDecl = `105 :root {106 --color: red;107 background: white;108 }109 `;110 const cssVarFunc = `111 p {112 color: var(--color);113 background: white;114 }115 `;116 it('false (keeps all :root declarations)', function() {117 const ast = parseCss(cssVarDecl);118 expect(ast.stylesheet.rules[0].declarations).to.have.lengthOf(2);119 });120 it('false (keeps all declarations)', function() {121 const ast = parseCss(cssVarFunc);122 expect(ast.stylesheet.rules[0].declarations).to.have.lengthOf(2);123 });124 it('true (keeps only :root variable declaration)', function() {125 const ast = parseCss(cssVarDecl, {126 onlyVars: true127 });128 expect(ast.stylesheet.rules[0].declarations).to.have.lengthOf(1);129 });130 it('true (keeps only variable function declarations)', function() {131 const ast = parseCss(cssVarFunc, {132 onlyVars: true133 });134 expect(ast.stylesheet.rules[0].declarations).to.have.lengthOf(1);135 });136 it('true (keeps all @font-face declarations)', function() {137 const css = `138 @font-face {139 test: var(--test);140 font-family: system;141 font-style: normal;142 }143 `;144 const ast = parseCss(css, {145 onlyVars: true146 });147 expect(ast.stylesheet.rules[0].declarations).to.have.lengthOf(3);148 });149 it('true (remove @font-face rule)', function() {150 const css = `151 @font-face {152 font-family: system;153 font-style: normal;154 }155 `;156 const ast = parseCss(css, {157 onlyVars: true158 });159 expect(ast.stylesheet.rules).to.have.lengthOf(0);160 });161 it('true (keeps all @keyframes declarations)', function() {162 const css = `163 @keyframes slidein {164 from {165 test: var(--test);166 height: 50%;167 width: 50%;168 }169 to {170 height: 100%;171 width: 100%;172 }173 }174 `;175 const ast = parseCss(css, {176 onlyVars: true177 });178 expect(ast.stylesheet.rules[0].keyframes[0].declarations).to.have.lengthOf(3);179 expect(ast.stylesheet.rules[0].keyframes[1].declarations).to.have.lengthOf(2);180 });181 it('true (remove @keyframes rule)', function() {182 const css = `183 @keyframes slidein {184 from {185 height: 50%;186 width: 50%;187 }188 to {189 height: 100%;190 width: 100%;191 }192 }193 `;194 const ast = parseCss(css, {195 onlyVars: true196 });197 expect(ast.stylesheet.rules).to.have.lengthOf(0);198 });199 it('true (keeps all @media declarations)', function() {200 const css = `201 @media screen {202 p {203 color: var(--color);204 background: white;205 }206 }207 `;208 const ast = parseCss(css, {209 onlyVars: true210 });211 expect(ast.stylesheet.rules[0].rules[0].declarations).to.have.lengthOf(1);212 });213 it('true (remove @media rule)', function() {214 const css = `215 @media screen {216 p {217 background: white;218 }219 }220 `;221 const ast = parseCss(css, {222 onlyVars: true223 });224 expect(ast.stylesheet.rules).to.have.lengthOf(0);225 });226 it('true (remove unrecognized @ rule)', function() {227 const css = `228 @-ms-viewport {229 background: white;230 }231 `;232 const ast = parseCss(css, {233 onlyVars: true234 });235 expect(ast.stylesheet.rules).to.have.lengthOf(0);236 });237 });238 describe('removeComments', function() {239 const css = `240 /* COMMENT1 */241 p {242 color: red;243 }244 /* COMMENT2 */245 `;246 it('false', function() {247 const ast = parseCss(css);248 expect(ast.stylesheet.rules).to.have.lengthOf(3);249 });250 it('true', function() {251 const ast = parseCss(css, {252 removeComments: true253 });254 expect(ast.stylesheet.rules).to.have.lengthOf(1);255 });256 });257 });258 // Tests: Performance259 // -------------------------------------------------------------------------260 // describe.only('Performance', function() {261 // it('Handles large block of CSS using onlyVars option', function() {262 // const css = `263 // :root { --color: red; }264 // p { color: var(--color); }265 // ${'div { color: red; }'.repeat(10000)}266 // `;267 // console.time('Performance Test');268 // const ast = parseCss(css, {269 // onlyVars: true270 // });271 // console.timeEnd('Performance Test');272 // console.log('CSS:', css.length);273 // console.log('rules:', ast.stylesheet.rules.length);274 // expect(ast instanceof Object).to.be.true;275 // });276 // });...
AtomUI.js
Source: AtomUI.js
...239 },240 setItemRect: function (e, r) {241 var isButton = this.isWeirdControl(e);242 if (r.width) {243 r.width -= this.parseCSS(e, "marginLeft") + this.parseCSS(e, "marginRight");244 if (!isButton) {245 r.width -= this.parseCSS(e, "borderLeftWidth") + this.parseCSS(e, "borderRightWidth");246 r.width -= this.parseCSS(e, "paddingLeft") + this.parseCSS(e, "paddingRight");247 }248 if (r.width < 0)249 r.width = 0;250 e.style.width = r.width + "px";251 }252 if (r.height) {253 //r.height -= $(e).outerWidth(true) - $(e).width();254 r.height -= this.parseCSS(e, "marginTop") + this.parseCSS(e, "marginBottom");255 if (!isButton) {256 r.height -= this.parseCSS(e, "borderTopWidth") + this.parseCSS(e, "borderBottomWidth");257 r.height -= this.parseCSS(e, "paddingTop") + this.parseCSS(e, "paddingBottom");258 }259 if (r.height < 0)260 r.height = 0;261 e.style.height = r.height + "px";262 e.style.maxHeight = r.height + "px";263 }264 if (r.left) {265 e.style.left = r.left + "px";266 }267 if (r.top) {268 e.style.top = r.top + "px";269 }270 },271 getPresenterOwner: function (ctrl, p) {...
cssParsing.test.js
Source: cssParsing.test.js
...32 assert.deepEqual(result, expected, 'fi.prototype.parseRules : parse css rules, containing duplicate directives' ); //assert 933});34QUnit.test('Basic CSS parsing', function(assert) {35 var expected = $.parseJSON(testData.veryBasicCSS.output);36 var parsed = fullInspector.parseCSS(testData.veryBasicCSS.input);37 console.log(expected, parsed);38 assert.deepEqual(parsed, expected, 'The simplest css possible, compressed'); //assert 139 expected = $.parseJSON(testData.basicCSS.output);40 parsed = fullInspector.parseCSS(testData.basicCSS.input);41 assert.deepEqual(parsed, expected, 'The simplest css possible, uncompressed'); //assert 242 expected = $.parseJSON(testData.basicCSS2.output); //adding comments should not change output43 parsed = fullInspector.parseCSS(testData.basicCSS2.input);44 assert.deepEqual(parsed, expected, 'Simple css with comments'); //assert 345 expected = $.parseJSON(testData.basicCSS3.output); //a More complex CSS example46 parsed = fullInspector.parseCSS(testData.basicCSS3.input);47 assert.deepEqual(parsed, expected, 'A More complex CSS example'); //assert 448 expected = $.parseJSON(testData.basicCSS4.output); //a More complex CSS example49 parsed = fullInspector.parseCSS(testData.basicCSS4.input);50 assert.deepEqual(parsed, expected, 'Simple css with multi-line value'); //assert 551 expected = $.parseJSON(testData.basicCSS5.output); //simple css with margin value is "*0"52 parsed = fullInspector.parseCSS(testData.basicCSS5.input);53 assert.deepEqual(parsed, expected, 'simple css with margin value is "*0'); //assert 554});55QUnit.test('Advanced CSS Parsing(support for media queries)', function(assert) {56 var expected = $.parseJSON(testData.advCSS.output);57 var parsed = fullInspector.parseCSS(testData.advCSS.input);58 assert.deepEqual(parsed, expected, 'Basic CSS including only 1 media query'); //assert 1 for media queries59 expected = $.parseJSON(testData.advCSS2.output);60 parsed = fullInspector.parseCSS(testData.advCSS2.input);61 assert.deepEqual(parsed, expected, '2 media queries'); //assert 2 for media queries62 //test a very complex css & media query mixup63 expected = $.parseJSON(testData.advCSS3.output);64 parsed = fullInspector.parseCSS(testData.advCSS3.input);65 assert.deepEqual(parsed, expected, 'Complex css & media query mixup'); //assert 2 for media queries66 expected = $.parseJSON(testData.advCSS4.output);67 parsed = fullInspector.parseCSS(testData.advCSS4.input);68 assert.deepEqual(parsed, expected, 'Simple @font-face containing css');69 expected = $.parseJSON(testData.advCSS5.output);70 parsed = fullInspector.parseCSS(testData.advCSS5.input);71 assert.deepEqual(parsed, expected, 'Simple @font-face with multiline value containing css');72 expected = $.parseJSON(testData.advCSS6.output);73 parsed = fullInspector.parseCSS(testData.advCSS6.input);74 assert.deepEqual(parsed, expected, 'Media query with a comment above it.');75});76/*77 this tests convert css string to object, then to string, then to object and compares the last 2 objects78 to detect incostincies79*/80QUnit.test('CSS parse&toString equality tests', function(assert) {81 for (var i in testData) {82 var original = testData[i].input;83 var parsed = fullInspector.parseCSS(original);84 var converted = fullInspector.getCSSForEditor(parsed);85 var reparsed = fullInspector.parseCSS(converted);86 assert.deepEqual(reparsed, parsed, 'Test of each of above test cases');87 }88});89/*90 Test Cases for CSS diff tool91*/92QUnit.test('CSS Diff Tests', function(assert) {93 var css1 = $.parseJSON(diffTestData.diffBasic.css1);94 var css2 = $.parseJSON(diffTestData.diffBasic.css2);95 var diff = fullInspector.cssDiff(css1, css2);96 var expected = $.parseJSON(diffTestData.diffBasic.diff)97 assert.deepEqual(diff, expected, 'Basic cssDiff');98 css1 = $.parseJSON(diffTestData.diffBasic2.css1);99 css2 = $.parseJSON(diffTestData.diffBasic2.css2);...
parse.js
Source: parse.js
...18var expect = require('expect.js'),19 parse = require('../src/parse');20describe('parseCSS', function() {21 it('should return an empty object - empty', function() {22 expect(parse.parseCSS('')).to.be.eql({});23 });24 it('should correctly split global and classList css', function() {25 var css = [26 'a { color: blue; }',27 'a.link { color: red; }'28 ].join('');29 expect(parse.parseCSS(css)).to.be.eql({30 globalCss: ['a{color:blue}'],31 classListCssPairs: [32 [['link'], 'a.link{color:red}']33 ]34 });35 });36 it('should correctly handle multiple similar classList css', function() {37 var css = [38 '.link { color: blue; display: none; }',39 'a.link { color: red; }'40 ].join('');41 expect(parse.parseCSS(css)).to.be.eql({42 classListCssPairs: [43 [['link'], '.link{color:blue;display:none}'],44 [['link'], 'a.link{color:red}']45 ]46 });47 });48 it('should not split multiple selectors with similar classList css', function() {49 var css = '.link:before,.link a { color: blue; display: none; }';50 expect(parse.parseCSS(css)).to.be.eql({51 classListCssPairs: [52 [['link'], '.link:before,.link a{color:blue;display:none}']53 ]54 });55 });56 it('should correctly handle @media at rules', function() {57 var css = [58 '@media screen {',59 '.link { color: blue; display: none; }',60 '}',61 'a.link { color: red; }'62 ].join('');63 expect(parse.parseCSS(css)).to.be.eql({64 classListCssPairs: [65 [['link'], '@media screen{.link{color:blue;display:none}}'],66 [['link'], 'a.link{color:red}']67 ]68 });69 });70 it('should correctly handle @fontface at rules', function() {71 var css = [72 '@font-face{',73 'font-family:\'q-icons\';',74 'src:url(\'/static/fonts/q-icons/q-icons.eot\')',75 '}'76 ].join('');77 expect(parse.parseCSS(css)).to.be.eql({fontfaceCss: [css]});78 });79 it('should corretly handle @keyframes at rules', function() {80 var css = [81 '@keyframes fadeOut{',82 'from{opacity:1}',83 'to{opacity:0}',84 '}'85 ].join('');86 expect(parse.parseCSS(css)).to.be.eql({87 keyframesCss: [88 ['fadeOut', css]89 ]90 });91 });92 it('should corretly handle vendor prefixed @keyframes at rules', function() {93 var css1 = [94 '@keyframes fadeOut{',95 'from{opacity:1}',96 'to{opacity:0}',97 '}'98 ].join('');99 var css2 = [100 '@-webkit-keyframes fadeOut{',101 'from{opacity:1}',102 'to{opacity:0}',103 '}'104 ].join('');105 expect(parse.parseCSS(css1 + '\n' + css2)).to.be.eql({106 keyframesCss: [107 ['fadeOut', css1],108 ['fadeOut', css2]109 ]110 });111 });...
parser.js
Source: parser.js
...36 }37 if (current.length) out.push(current.join(''))38 return out;39}40function parseCSS(string, obj) {41 if (!obj) obj = []42 if (!string) return obj;43 if (string.charAt(0) === '"') {44 var match = string.match(/("(?:[^"\\]|\\.)*")(?: (.*))?/);45 obj.push([3, match[1]]);46 parseCSS(match[2], obj);47 } else if (string.charAt(0) === "'") {48 var match = string.match(/('(?:[^'\\]|\\.)*')(?: (.*))?/);49 obj.push([3, match[1]]);50 parseCSS(match[2], obj);51 } else {52 var number = string.match(/^(\-?[0-9\.]*)(em|ex|%|px|cm|mm|in|pt|pc|ch|rem|vh|vw|vmin|vmax|s|ms|deg|grad|rad|turn|Q)?(?: (.*))?/);53 if (number[1]) { // number54 obj.push([0, parseFloat(number[1]), number[2] || '']);55 parseCSS(number[3], obj);56 } else {57 var func = string.match(/^([a-z\-]*?)\(([^\)]*)\)(?: (.*))?/)58 if (func && func[1]) {59 if (func[1] === 'rgb') {60 obj.push([2, splitSafe(func[2]).map((arg) => {61 return parseInt(arg);62 })]);63 } else {64 var args = splitSafe(func[2]).map((arg) => {65 return parseCSS(arg.trim());66 });67 obj.push([1, func[1], args]);68 }69 parseCSS(func[3], obj);70 } else {71 if (string.charAt(0) === '#') {72 var results = string.match(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})(?: (.*))?/);73 obj.push([2, hexToRgb(results[1])]);74 parseCSS(results[2], obj);75 } else {76 var res = string.match(/^([a-z\-]*?)(?: (.*))/);77 if (res && res[1]) {78 if (Colors[res[1]]) {79 obj.push([2, Colors[res[1]].slice(0)])80 } else {81 obj.push([3, res[1]]);82 }83 parseCSS(res[2], obj);84 } else {85 if (Colors[string]) {86 obj.push([2, Colors[string].slice(0)])87 } else {88 obj.push([3, string]);89 }90 }91 }92 }93 }94 }95 return obj;...
jquery.inlinelabel.js
Source: jquery.inlinelabel.js
...20 var hint = $(input).next(".inline-hint");21 $(input).parent().css("position","relative");22 var input_pos = $(input).position();23 //get the hint set up24 var hint_line_height = $(input).outerHeight() - parseCSS($(input).css("borderTopWidth"));25 var hint_css_left = parseCSS(input_pos.left) + parseCSS($(input).css("marginLeft")) + parseCSS($(input).css("borderLeftWidth")) + 5;26 var hint_css_top = parseCSS(input_pos.top) + parseCSS($(input).css("marginTop")) + parseCSS($(input).css("borderTopWidth"));27 28 //would like to just add a class but not sure how best to do that yet since so much has to change29 $(hint).css("position","absolute")30 .css("color", "#aeaeae")31 .css("margin", "0")32 .css("fontSize", "12px")33 .css("lineHeight", hint_line_height + "px")34 .css("left", hint_css_left)35 .css("top", hint_css_top);36 return hint; 37 };38 39 var parseCSS = function(property){40 //all this crud is necessary for IE8 to not blow up...
canvas-style-loader.js
Source: canvas-style-loader.js
1/**2 * @author monkeywang3 * Date: 2018/5/24 */5const css = require('css')6module.exports = function (source, other) {7 let cssAST = css.parse(source)8 let parseCss = new ParseCss(cssAST)9 parseCss.parse()10 this.cacheable();11 this.callback(null, parseCss.declareStyle(), other);12};13class ParseCss {14 constructor(cssAST) {15 this.rules = cssAST.stylesheet.rules16 this.targetStyle = {}17 }18 parse () {19 this.rules.forEach((rule) => {20 let selector = rule.selectors[0]21 this.targetStyle[selector] = {}22 rule.declarations.forEach((dec) => {23 this.targetStyle[selector][dec.property] = this.formatValue(dec.value)24 })25 })26 }27 formatValue (string) {28 string = string.replace(/"/g, '').replace(/'/g, '')29 return string.indexOf('px') !== -1 ? parseInt(string) : string30 }31 declareStyle (property) {32 return `window.${property || 'vStyle'} = ${JSON.stringify(this.targetStyle)}`33 }...
Using AI Code Generation
1const { parseCSS } = require('playwright/lib/utils/cssParser');2const css = 'h1 { font-size: 10px; }';3const ast = parseCSS(css);4console.log(ast);5const { parseCSS } = require('puppeteer/lib/cjs/puppeteer/common/CSS.js');6const css = 'h1 { font-size: 10px; }';7const ast = parseCSS(css);8console.log(ast);9const { parseCSS } = require('puppeteer/lib/cjs/puppeteer/common/CSS.js');10const css = 'h1 { font-size: 10px; }';11const ast = parseCSS(css);12console.log(ast);13const { parseCSS } = require('puppeteer/lib/cjs/puppeteer/common/CSS.js');14const css = 'h1 { font-size: 10px; }';15const ast = parseCSS(css);16console.log(ast);17const { parseCSS } = require('puppeteer/lib/cjs/puppeteer/common/CSS.js');18const css = 'h1 { font-size: 10px; }';19const ast = parseCSS(css);20console.log(ast);21const { parseCSS } = require('puppeteer/lib/cjs/puppeteer/common/CSS.js');22const css = 'h1 { font-size: 10px; }';23const ast = parseCSS(css);24console.log(ast);25const { parseCSS } = require('puppeteer/lib/cjs/puppeteer/common/CSS.js');26const css = 'h1 { font-size: 10px; }';27const ast = parseCSS(css);28console.log(ast);29const { parseCSS } = require('puppeteer/lib/cjs/puppeteer/common/CSS.js');30const css = 'h1 { font-size: 10px; }';31const ast = parseCSS(css);32console.log(ast);33const { parseCSS } = require('
Using AI Code Generation
1const playwright = require('playwright');2const css = require('css');3const fs = require('fs');4const path = require('path');5const { parseCSS } = require('playwright/lib/server/cssParser');6const cssFile = fs.readFileSync(path.join(__dirname, 'test.css'), 'utf8');7const cssAST = css.parse(cssFile);8const parsedCSS = parseCSS(cssAST);9console.log(parsedCSS);10body {
Using AI Code Generation
1const { parseCSS } = require('playwright/lib/server/frames');2const parsed = parseCSS('body {color: red}');3console.log(parsed);4const { parseCSS } = require('playwright/lib/server/frames');5const parsed = parseCSS('body {color: red}');6console.log(parsed);7const { parseCSS } = require('playwright/lib/server/frames');8const parsed = parseCSS('body {color: red}');9console.log(parsed);
Using AI Code Generation
1const { parseCSS } = require('playwright/lib/server/frames');2const { parse } = require('playwright/lib/utils/cssParser');3 .foo {4 color: red;5 }6 .bar {7 color: blue;8 }9`;10const ast = parse(css);11const rules = parseCSS(ast);12console.log(rules);
Using AI Code Generation
1const { parseCSS } = require('playwright/lib/utils/cssParser');2const css = `#foo { color: red; }`;3const ast = parseCSS(css);4console.log(JSON.stringify(ast, null, 2));5const { parseCSS } = require('playwright/lib/utils/cssParser');6const css = `#foo { color: red; }`;7const ast = parseCSS(css);8console.log(JSON.stringify(ast, null, 2));9const { parseCSS } = require('playwright/lib/utils/cssParser');10const css = `#foo { color: red; }`;11const ast = parseCSS(css);12console.log(JSON.stringify(ast, null, 2));13const {
Using AI Code Generation
1const { parseCSS } = require('playwright/lib/server/cssParser');2const css = 'a { color: red; }';3const parsed = parseCSS(css);4console.log(parsed);5 {6 }7const { parseCSS } = require('playwright/lib/server/cssParser');8const css = 'a { color: red; }';9const parsed = parseCSS(css);10console.log(parsed[0].rules[0].selectorText);11const { parseCSS } = require('playwright/lib/server/cssParser');12const css = 'a { color: red; }';13const parsed = parseCSS(css);14console.log(parsed[0].rules[0].style);15CSSStyleDeclaration {16 _style: Map(1) { 'color' => 'red' },17 _parentRule: CSSStyleRule {18 }19}20const { parseCSS } = require('playwright/lib/server/cssParser');21const css = 'a { color: red; }';22const parsed = parseCSS(css);23console.log(parsed[0].rules[0].style._style);24Map(1) { 'color' => 'red' }25const { parseCSS } = require('playwright/lib/server/cssParser');26const css = 'a { color: red; }';27const parsed = parseCSS(css);28console.log(parsed[0].rules[0].style._style.get('color'));29const { parseCSS } = require('playwright/lib/server/cssParser');30const css = 'a { color: red; }';31const parsed = parseCSS(css
Using AI Code Generation
1const playwright = require('playwright');2const { parseCSS } = playwright.internal;3const css = '#id .class { color: red; }';4const parsed = parseCSS(css);5console.log(parsed);6const playwright = require('playwright');7const { parseSelector } = playwright.internal;8const selector = 'css=#id .class';9const parsed = parseSelector(selector);10console.log(parsed);11const playwright = require('playwright');12const { parseSelectorList } = playwright.internal;13const selector = 'css=#id .class,css=#id .class';14const parsed = parseSelectorList(selector);15console.log(parsed);16const playwright = require('playwright');17const { parseURL } = playwright.internal;18const parsed = parseURL(url);19console.log(parsed);20const playwright = require('playwright');21const { parseURL } = playwright.internal;22const parsed = parseURL(url);23console.log(parsed);24const playwright = require('playwright');25const { parseURL } = playwright.internal;26const parsed = parseURL(url);27console.log(parsed);28const playwright = require('playwright');29const { parseURL } = playwright.internal;30const parsed = parseURL(url);31console.log(parsed);32const playwright = require('playwright');33const { parseURL } = playwright.internal;34const parsed = parseURL(url);35console.log(parsed);36const playwright = require('playwright');37const { parseURL } = playwright.internal;38const parsed = parseURL(url);39console.log(parsed);40const playwright = require('playwright');41const { parseURL } = playwright.internal;
Jest + Playwright - Test callbacks of event-based DOM library
firefox browser does not start in playwright
Is it possible to get the selector from a locator object in playwright?
How to run a list of test suites in a single file concurrently in jest?
Running Playwright in Azure Function
firefox browser does not start in playwright
This question is quite close to a "need more focus" question. But let's try to give it some focus:
Does Playwright has access to the cPicker object on the page? Does it has access to the window object?
Yes, you can access both cPicker and the window object inside an evaluate call.
Should I trigger the events from the HTML file itself, and in the callbacks, print in the DOM the result, in some dummy-element, and then infer from that dummy element text that the callbacks fired?
Exactly, or you can assign values to a javascript variable:
const cPicker = new ColorPicker({
onClickOutside(e){
},
onInput(color){
window['color'] = color;
},
onChange(color){
window['result'] = color;
}
})
And then
it('Should call all callbacks with correct arguments', async() => {
await page.goto(`http://localhost:5000/tests/visual/basic.html`, {waitUntil:'load'})
// Wait until the next frame
await page.evaluate(() => new Promise(requestAnimationFrame))
// Act
// Assert
const result = await page.evaluate(() => window['color']);
// Check the value
})
Check out the latest blogs from LambdaTest on this topic:
Native apps are developed specifically for one platform. Hence they are fast and deliver superior performance. They can be downloaded from various app stores and are not accessible through browsers.
One of the essential parts when performing automated UI testing, whether using Selenium or another framework, is identifying the correct web elements the tests will interact with. However, if the web elements are not located correctly, you might get NoSuchElementException in Selenium. This would cause a false negative result because we won’t get to the actual functionality check. Instead, our test will fail simply because it failed to interact with the correct element.
Smartphones have changed the way humans interact with technology. Be it travel, fitness, lifestyle, video games, or even services, it’s all just a few touches away (quite literally so). We only need to look at the growing throngs of smartphone or tablet users vs. desktop users to grasp this reality.
As part of one of my consulting efforts, I worked with a mid-sized company that was looking to move toward a more agile manner of developing software. As with any shift in work style, there is some bewilderment and, for some, considerable anxiety. People are being challenged to leave their comfort zones and embrace a continuously changing, dynamic working environment. And, dare I say it, testing may be the most ‘disturbed’ of the software roles in agile development.
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!!