Best JavaScript code snippet using playwright-internal
Element.js
Source: Element.js
...99 * å°ç®æ èç¹æ·»å å°å½åå
ç´ ä¸100 * @param ele101 */102 childrenNodesAppend(ele) {103 if (!this.isTextNode()) {104 ele.childrenNodes().forEach(i => this.append(i));105 }106 return this;107 }108 /**109 * å°ç®æ èç¹æ·»å å°å½åå
ç´ ä¸110 * @param ele111 */112 childrenNodesPrepend(ele) {113 if (!this.isTextNode()) {114 ele.childrenNodes().forEach(i => this.prepend(i));115 }116 return this;117 }118 /**119 * å¨å½åå
ç´ ä¸æå
¥æå®èç¹120 * @param ele121 */122 append(ele) {123 if (!this.isTextNode()) {124 if (ele && ele.el) {125 this.el.append(ele.el);126 }127 }128 return this;129 }130 /**131 * å¨å½åå
ç´ ä¸æå
¥æå®èç¹132 * @param ele133 */134 prepend(ele) {135 if (!this.isTextNode()) {136 if (ele && ele.el) {137 this.el.prepend(ele.el);138 }139 }140 return this;141 }142 /**143 * å
ç´ å®ä½144 * @param value145 * @returns {{top: *, left: *, width: *, height: *}|Element}146 */147 offset(value) {148 if (value !== undefined) {149 Object.keys(value).forEach((k) => {150 this.css(k, `${value[k]}px`);151 });152 return this;153 }154 const { offsetTop, offsetLeft } = this.el;155 const { offsetHeight, offsetWidth } = this.el;156 return {157 top: offsetTop,158 left: offsetLeft,159 height: offsetHeight,160 width: offsetWidth,161 };162 }163 /**164 * è·åå½åå
ç´ çç¶èç¹165 * @returns {Element}166 */167 parent() {168 return this.el.parentNode169 ? new Element(this.el.parentNode) : null;170 }171 /**172 * æ·»å Classå称173 * @param name174 * @returns {Element}175 */176 addClass(name) {177 if (!this.isTextNode()) {178 this.el.classList.add(name);179 }180 return this;181 }182 /**183 * æ¯å¦å
·ææå®Classå称184 * @param name185 * @returns {boolean}186 */187 hasClass(name) {188 if (!this.isTextNode()) {189 return this.el.classList.contains(name);190 }191 return false;192 }193 /**194 * æ¯å¦æåå
ç´ 195 * @returns {boolean}196 */197 hasChildElement() {198 return this.children().length > 0;199 }200 /**201 * æ¯å¦æåèç¹202 * @returns {boolean}203 */204 hasChild() {205 return this.childrenNodes().length > 0;206 }207 /**208 * å é¤Classå称209 * @param name210 * @returns {Element}211 */212 removeClass(name) {213 if (!this.isTextNode()) {214 this.el.classList.remove(name);215 }216 return this;217 }218 /**219 * è·åå
ç´ åæ ä¿¡æ¯220 * getBoundingClientRect221 * @returns {DOMRect}222 */223 box() {224 if (!this.isTextNode()) {225 return this.el.getBoundingClientRect();226 }227 return null;228 }229 /**230 * è·åå½å第ä¸ä¸ªåå
ç´ 231 * @returns {*}232 */233 first() {234 if (!this.isTextNode()) {235 return Element.wrapElement(this.el.firstChild);236 }237 return null;238 }239 /**240 * è·åæåä¸ä¸ªåå
ç´ 241 * @returns {*}242 */243 last() {244 if (!this.isTextNode()) {245 return Element.wrapElement(this.el.lastChild);246 }247 return null;248 }249 /**250 * è·å第ä¸ä¸ªææ¬èç¹251 */252 firstTextNode() {253 if (this.isTextNode()) {254 return this;255 }256 let find = null;257 let handle = (elem) => {258 if (elem.hasChild()) {259 elem.childrenNodes().forEach((elem) => {260 if (find === null) {261 handle(elem);262 }263 });264 }265 if (find === null) {266 if (elem.isTextNode()) {267 find = elem;268 }269 }270 };271 handle(this);272 return find;273 }274 /**275 * è·åæåä¸ä¸ªææ¬èç¹276 */277 lastTextNode() {278 if (this.isTextNode()) {279 return this;280 }281 let find = null;282 let handle = (elem) => {283 if (elem.hasChild()) {284 elem.childrenNodes().reverse().forEach((elem) => {285 if (find === null) {286 handle(elem);287 }288 });289 }290 if (find === null) {291 if (elem.isTextNode()) {292 find = elem;293 }294 }295 };296 handle(this);297 return find;298 }299 /**300 * å é¤å½åå
ç´ ä¸çåå
ç´ 301 * @param target302 * @returns {boolean|ActiveX.IXMLDOMNode|*}303 */304 remove(target = null) {305 if (target) {306 if (!this.isTextNode()) {307 this.el.removeChild(target.el || target);308 }309 } else {310 const parent = this.parent();311 if (parent) {312 this.parent().remove(this);313 }314 }315 return this;316 }317 /**318 * å½åå
ç´ æ¯å¦å
å«æå®èç¹319 * @param ele320 * @returns {boolean|*}321 */322 contains(ele) {323 if (this.isTextNode()) {324 return false;325 }326 return this.el.contains(ele.el);327 }328 /**329 * è·åå½åå
ç´ çä¸ä¸ä¸ªå
ç´ 330 * @returns {*}331 */332 prev() {333 return this.el.previousSibling334 ? Element.wrapElement(this.el.previousSibling) : null;335 }336 /**337 * è·åå½åå
ç´ çä¸ä¸ä¸ªå
ç´ 338 * @returns {*}339 */340 next() {341 return this.el.nextSibling342 ? Element.wrapElement(this.el.nextSibling) : null;343 }344 /**345 * 设置å
ç´ çæ¿æ´»ç¶æ346 * @param flag347 * @param cls348 * @returns {Element}349 */350 active(flag = true, cls = 'active') {351 if (!this.isTextNode()) {352 if (flag) this.addClass(cls);353 else this.removeClass(cls);354 }355 return this;356 }357 /**358 * 设置å
ç´ ææ¬359 * @param text360 * @returns {string|Element}361 */362 text(text) {363 if (this.isTextNode()) {364 return this.nodeValue();365 }366 if (text !== undefined) {367 this.el.innerText = text;368 return this;369 }370 return this.el.innerText;371 }372 /**373 * 设置å
ç´ htmlå
容374 * @param html375 * @returns {Element|*}376 */377 html(html) {378 if (this.isTextNode()) {379 return this.nodeValue();380 }381 if (html !== undefined) {382 this.el.innerHTML = html;383 return this;384 }385 return this.el.innerHTML;386 }387 /**388 * å½åå
ç´ è®¾ç½®ç¦ç¹389 */390 focus() {391 if (!this.isTextNode()) {392 this.el.focus();393 }394 return this;395 }396 /**397 * 移é¤ç¦ç¹398 */399 blur() {400 if (!this.isTextNode()) {401 this.el.blur();402 }403 return this;404 }405 /**406 * å é¤å
ç´ å±æ§407 * @param key408 * @returns {Element}409 */410 removeAttr(key) {411 if (!this.isTextNode()) {412 this.el.removeAttribute(key);413 }414 return this;415 }416 /**417 * æ·»å style418 * @param style419 */420 style(style) {421 if (!this.isTextNode()) {422 this.attr('style', style);423 }424 return this;425 }426 /**427 * æ·»å å
ç´ å±æ§428 * @param key429 * @param value430 * @returns {string|Element}431 */432 attr(key, value) {433 if (!this.isTextNode()) {434 if (value !== undefined) {435 if (this.el.setAttribute) {436 this.el.setAttribute(key, value);437 }438 } else {439 if (typeof key === 'string') {440 if (this.el.setAttribute) {441 return this.el.getAttribute(key);442 }443 return null;444 }445 if (this.el.setAttribute) {446 Object.keys(key).forEach((k) => {447 this.el.setAttribute(k, key[k]);448 });449 }450 }451 }452 return this;453 }454 /**455 * 设置å
ç´ Value456 * @param v457 * @returns {Element|*}458 */459 val(v) {460 if (!this.isTextNode()) {461 if (v !== undefined) {462 this.el.value = v;463 return this;464 }465 return this.el.value;466 }467 if (v === undefined) {468 return this.nodeValue();469 }470 return this;471 }472 /**473 * è·ååå§èç¹474 * @returns {*}475 */476 get() {477 return this.el;478 }479 /**480 * å é¤å
ç´ styleå±æ§481 * @param keys482 * @returns {Element}483 */484 cssRemoveKeys(...keys) {485 if (!this.isTextNode()) {486 if (this.el.style) {487 keys.forEach((k) => {488 if (this.el.style) {489 this.el.style.removeProperty(Element.hyphenateRE(k));490 }491 });492 }493 }494 return this;495 }496 /**497 * å é¤å
ç´ styleå±æ§498 * @param key499 * @param value500 * @returns {Element}501 */502 cssRemoveVal(key, value) {503 if (!this.isTextNode()) {504 if (this.el.style) {505 const property = Element.hyphenateRE(key);506 const propertyValue = this.el.style.getPropertyValue(property);507 const newValue = propertyValue.replace(value, '');508 this.css(key, newValue);509 }510 }511 return this;512 }513 /**514 * 设置å
ç´ å±æ§515 * @param name516 * @param value517 * @returns {Element|*}518 */519 css(name, value) {520 if (!this.isTextNode()) {521 if (this.el.style) {522 if (value === undefined && typeof name !== 'string') {523 Object.keys(name).forEach((key) => {524 const property = Element.hyphenateRE(key);525 this.el.style.setProperty(property, name[key]);526 });527 return this;528 }529 if (value !== undefined) {530 const property = Element.hyphenateRE(name);531 this.el.style.setProperty(property, value);532 return this;533 }534 const property = Element.hyphenateRE(name);535 return this.el.style.getPropertyValue(property);536 }537 }538 return null;539 }540 /**541 * è·åå
ç´ è®¡ç®å®æçæ ·å¼542 * @returns {CSSStyleDeclaration}543 */544 computedStyle() {545 if (!this.isTextNode()) {546 return window.getComputedStyle(this.el, null);547 }548 return null;549 }550 /**551 * æ¾ç¤º552 * @returns {Element}553 */554 show() {555 if (!this.isTextNode()) {556 const style = this.computedStyle();557 if (style && style.display !== 'block') {558 this.css('display', 'block');559 }560 }561 return this;562 }563 /**564 * éè565 * @returns {Element}566 */567 hide() {568 if (!this.isTextNode()) {569 const style = this.computedStyle();570 if (style && style.display !== 'none') {571 this.css('display', 'none');572 }573 }574 return this;575 }576 /**577 * äºä»¶è§¦å578 * @param type579 * @param message580 */581 trigger(type, message) {582 if (!this.isTextNode()) {583 switch (type) {584 case 'click': {585 const evt = new MouseEvent(type, {586 detail: message,587 bubbles: true,588 cancelable: false,589 });590 evt.initEvent('click', true, true);591 this.el.dispatchEvent(evt);592 break;593 }594 default: {595 const evt = new CustomEvent(type, {596 detail: message,597 bubbles: true,598 cancelable: false,599 });600 this.el.dispatchEvent(evt);601 break;602 }603 }604 }605 }606 /**607 * æ¥æ¾åå
ç´ 608 * @param select609 * @returns {[]|Element}610 */611 find(select) {612 if (!this.isTextNode()) {613 const result = this.el.querySelectorAll(select);614 if (result && result.length === 1) {615 return new Element(result[0]);616 }617 const array = [];618 if (result) {619 for (const item of result) {620 array.push(new Element(item));621 }622 }623 return array;624 }625 return [];626 }627 /**628 * æ¥æ¾åå
ç´ 629 * @param select630 * @returns {[]|Element}631 */632 finds(select) {633 if (!this.isTextNode()) {634 const result = this.el.querySelectorAll(select);635 const array = [];636 if (result) {637 for (const item of result) {638 array.push(new Element(item));639 }640 }641 return array;642 }643 return [];644 }645 /**646 * è·åå½åå
ç´ çå
å¼èç¹647 * @returns {[]}648 */649 sibling() {650 let sibling = this.el;651 const result = [];652 // eslint-disable-next-line no-cond-assign653 while ((sibling = sibling.previousElementSibling) !== null) result.push(new Element(sibling));654 sibling = this.el;655 // eslint-disable-next-line no-cond-assign656 while ((sibling = sibling.nextElementSibling) !== null) result.push(new Element(sibling));657 return result;658 }659 /**660 * èç¹å称661 * @returns {string}662 */663 tagName() {664 return this.el.nodeName.toLocaleLowerCase();665 }666 /**667 * èç¹å
容668 * @returns {string}669 */670 nodeValue() {671 return this.el.nodeValue;672 }673 /**674 * èç¹ç±»å675 * @returns {number}676 */677 nodeType() {678 return this.el.nodeType;679 }680 /**681 * å¨å½åå
ç´ ä¹åæå
¥æ°å
ç´ 682 * @param ele683 */684 after(ele) {685 if (this.el && ele && ele.el) {686 this.el.after(ele.el);687 }688 return this;689 }690 /**691 * å¨å½åå
ç´ ä¹åæå
¥æ°å
ç´ 692 * @param ele693 */694 before(ele) {695 if (this.el && ele && ele.el) {696 this.el.before(ele.el);697 }698 return this;699 }700 /**701 * å¤å¶702 */703 clone() {704 return new Element(this.el.cloneNode(true));705 }706 /**707 * æ¸
空å
ç´ ä¸çææå
容708 */709 empty() {710 if (!this.isTextNode()) {711 this.html('');712 }713 return this;714 }715 /**716 * ç¸çæ¯è¾717 * @param other718 * @returns {boolean}719 */720 equals(other) {721 return this.el === other.el;722 }723 /**724 * è·åå½åå
ç´ å¨ç¶å
ç´ ä¸çç´¢å¼725 * @returns {number}726 */727 index() {728 let parent = this.parent();729 let index = -1;730 parent.childrenNodes()731 .forEach((v, i) => {732 if (v.equals(this)) {733 index = i;734 }735 });736 return index;737 }738 /**739 * æ¯è¾domæ¯å¦ç¸å740 * @param ele741 * @returns {boolean}742 */743 is(ele) {744 return this.el === ele.el;745 }746 /**747 * æ¯å¦ææ¬èç¹748 * @returns {boolean}749 */750 isTextNode() {751 return this.tagName() === '#text';752 }753 /**754 * æ¯å¦æ¢è¡èç¹755 * @returns {boolean}756 */757 isBreakNode() {758 return this.tagName() === 'br';759 }760 /**761 * æ¯å¦ææ¡£ç¢ç762 * @returns {boolean}763 */764 isDocumentFragment() {...
hero.js
Source: hero.js
1var raf = typeof window !== 'undefined' && window.requestAnimationFrame || setTimeout;2var nextFrame = function nextFrame(fn) {3 raf(function () {4 raf(fn);5 });6};7function setNextFrame(obj, prop, val) {8 nextFrame(function () {9 obj[prop] = val;10 });11}12function getTextNodeRect(textNode) {13 var rect;14 if (document.createRange) {15 var range = document.createRange();16 range.selectNodeContents(textNode);17 if (range.getBoundingClientRect) {18 rect = range.getBoundingClientRect();19 }20 }21 return rect;22}23function calcTransformOrigin(isTextNode, textRect, boundingRect) {24 if (isTextNode) {25 if (textRect) {26 //calculate pixels to center of text from left edge of bounding box27 var relativeCenterX = textRect.left + textRect.width / 2 - boundingRect.left;28 var relativeCenterY = textRect.top + textRect.height / 2 - boundingRect.top;29 return relativeCenterX + 'px ' + relativeCenterY + 'px';30 }31 }32 return '0 0'; //top left33}34function getTextDx(oldTextRect, newTextRect) {35 if (oldTextRect && newTextRect) {36 return oldTextRect.left + oldTextRect.width / 2 - (newTextRect.left + newTextRect.width / 2);37 }38 return 0;39}40function getTextDy(oldTextRect, newTextRect) {41 if (oldTextRect && newTextRect) {42 return oldTextRect.top + oldTextRect.height / 2 - (newTextRect.top + newTextRect.height / 2);43 }44 return 0;45}46function isTextElement(elm) {47 return elm.childNodes.length === 1 && elm.childNodes[0].nodeType === 3;48}49var removed, created;50function pre() {51 removed = {};52 created = [];53}54function create(oldVnode, vnode) {55 var hero = vnode.data.hero;56 if (hero && hero.id) {57 created.push(hero.id);58 created.push(vnode);59 }60}61function destroy(vnode) {62 var hero = vnode.data.hero;63 if (hero && hero.id) {64 var elm = vnode.elm;65 vnode.isTextNode = isTextElement(elm); //is this a text node?66 vnode.boundingRect = elm.getBoundingClientRect(); //save the bounding rectangle to a new property on the vnode67 vnode.textRect = vnode.isTextNode ? getTextNodeRect(elm.childNodes[0]) : null; //save bounding rect of inner text node68 var computedStyle = window.getComputedStyle(elm, void 0); //get current styles (includes inherited properties)69 vnode.savedStyle = JSON.parse(JSON.stringify(computedStyle)); //save a copy of computed style values70 removed[hero.id] = vnode;71 }72}73function post() {74 var i, id, newElm, oldVnode, oldElm, hRatio, wRatio, oldRect, newRect, dx, dy, origTransform, origTransition, newStyle, oldStyle, newComputedStyle, isTextNode, newTextRect, oldTextRect;75 for (i = 0; i < created.length; i += 2) {76 id = created[i];77 newElm = created[i + 1].elm;78 oldVnode = removed[id];79 if (oldVnode) {80 isTextNode = oldVnode.isTextNode && isTextElement(newElm); //Are old & new both text?81 newStyle = newElm.style;82 newComputedStyle = window.getComputedStyle(newElm, void 0); //get full computed style for new element83 oldElm = oldVnode.elm;84 oldStyle = oldElm.style; //Overall element bounding boxes85 newRect = newElm.getBoundingClientRect();86 oldRect = oldVnode.boundingRect; //previously saved bounding rect87 //Text node bounding boxes & distances88 if (isTextNode) {89 newTextRect = getTextNodeRect(newElm.childNodes[0]);90 oldTextRect = oldVnode.textRect;91 dx = getTextDx(oldTextRect, newTextRect);92 dy = getTextDy(oldTextRect, newTextRect);93 } else {94 //Calculate distances between old & new positions95 dx = oldRect.left - newRect.left;96 dy = oldRect.top - newRect.top;97 }98 hRatio = newRect.height / Math.max(oldRect.height, 1);99 wRatio = isTextNode ? hRatio : newRect.width / Math.max(oldRect.width, 1); //text scales based on hRatio100 // Animate new element101 origTransform = newStyle.transform;102 origTransition = newStyle.transition;103 if (newComputedStyle.display === 'inline') newStyle.display = 'inline-block'; //this does not appear to have any negative side effects104 newStyle.transition = origTransition + 'transform 0s';105 newStyle.transformOrigin = calcTransformOrigin(isTextNode, newTextRect, newRect);106 newStyle.opacity = '0';107 newStyle.transform = origTransform + 'translate(' + dx + 'px, ' + dy + 'px) ' + 'scale(' + 1 / wRatio + ', ' + 1 / hRatio + ')';108 setNextFrame(newStyle, 'transition', origTransition);109 setNextFrame(newStyle, 'transform', origTransform);110 setNextFrame(newStyle, 'opacity', '1'); // Animate old element111 for (var key in oldVnode.savedStyle) {112 if (parseInt(key) != key) {113 var ms = key.substring(0, 2) === 'ms';114 var moz = key.substring(0, 3) === 'moz';115 var webkit = key.substring(0, 6) === 'webkit';116 if (!ms && !moz && !webkit) oldStyle[key] = oldVnode.savedStyle[key];117 }118 }119 oldStyle.position = 'absolute';120 oldStyle.top = oldRect.top + 'px'; //start at existing position121 oldStyle.left = oldRect.left + 'px';122 oldStyle.width = oldRect.width + 'px'; //Needed for elements who were sized relative to their parents123 oldStyle.height = oldRect.height + 'px'; //Needed for elements who were sized relative to their parents124 oldStyle.margin = '0'; //Margin on hero element leads to incorrect positioning125 oldStyle.transformOrigin = calcTransformOrigin(isTextNode, oldTextRect, oldRect);126 oldStyle.transform = '';127 oldStyle.opacity = '1';128 document.body.appendChild(oldElm);129 setNextFrame(oldStyle, 'transform', 'translate(' + -dx + 'px, ' + -dy + 'px) scale(' + wRatio + ', ' + hRatio + ')'); //scale must be on far right for translate to be correct130 setNextFrame(oldStyle, 'opacity', '0');131 oldElm.addEventListener('transitionend', function (ev) {132 if (ev.propertyName === 'transform') document.body.removeChild(ev.target);133 });134 }135 }136 removed = created = undefined;137}138export var heroModule = {139 pre: pre,140 create: create,141 destroy: destroy,142 post: post143};...
components.tabularList.js
Source: components.tabularList.js
1/*2 * Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.3 * http://www.jaspersoft.com.4 *5 * Unless you have purchased a commercial license agreement from Jaspersoft,6 * the following license terms apply:7 *8 * This program is free software: you can redistribute it and/or modify9 * it under the terms of the GNU Affero General Public License as10 * published by the Free Software Foundation, either version 3 of the11 * License, or (at your option) any later version.12 *13 * This program is distributed in the hope that it will be useful,14 * but WITHOUT ANY WARRANTY; without even the implied warranty of15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the16 * GNU Affero General Public License for more details.17 *18 * You should have received a copy of the GNU Affero General Public License19 * along with this program. If not, see <http://www.gnu.org/licenses/>.20 */21/**22 * @version: $Id: components.tabularList.js 47331 2014-07-18 09:13:06Z kklein $23 */24Element.addMethods({25 isTextNode: function(element) {26 element = $(element);27 return element.childElements().length == 0 && element.innerHTML.strip().length > 0;28 }29});30var TabularList = Class.create({31 initialize: function(tableId) {32 if(!tableId){33 this.tableId = 'resultsTable';34 } else {35 this.tableId = tableId;36 }37 },38 truncText: function() {39 //find all the nodes in the table that have text40 var textNodes = $$("#" + this.tableId + " .name *").findAll(Element.isTextNode);41 new Truncator(textNodes);42 $$("td.name").each(function (td) {43 td.setAttribute("nowrap", "nowrap");44 });45 textNodes = $$("#" + this.tableId + " .description *").findAll(Element.isTextNode);46 new Truncator(textNodes);47 $$("td.description").each(function (td) {48 td.setAttribute("nowrap", "nowrap");49 });50 textNodes = $$("#" + this.tableId + " .path *").findAll(Element.isTextNode);51 new Truncator(textNodes);52 $$("td.path").each(function (td) {53 td.setAttribute("nowrap", "nowrap");54 });55 textNodes = $$("#" + this.tableId + " .modifiedDate *").findAll(Element.isTextNode);56 new Truncator(textNodes);57 $$("td.modifiedDate").each(function (td) {58 td.setAttribute("nowrap", "nowrap");59 });60 },61 untruncText: function() {62 //find all the nodes in the table that have text63 var textNodes = $$("#" + this.tableId + " .name *").findAll(Element.isTextNode);64 new Truncator().untruncate(textNodes);65 $$("td.name").each(function (td) {66 td.removeAttribute("nowrap");67 });68 textNodes = $$("#" + this.tableId + " .description *").findAll(Element.isTextNode);69 new Truncator().untruncate(textNodes);70 $$("td.description").each(function (td) {71 td.removeAttribute("nowrap");72 });73 textNodes = $$("#" + this.tableId + " .objectPath *").findAll(Element.isTextNode);74 new Truncator(textNodes, 30);75// new Truncator().untruncate(textNodes);76 $$("td.path").each(function (td) {77 td.removeAttribute("nowrap");78 });79 textNodes = $$("#" + this.tableId + " .modifiedDate *").findAll(Element.isTextNode);80 new Truncator().untruncate(textNodes);81 $$("td.modifiedDate").each(function (td) {82 td.removeAttribute("nowrap");83 });84 },85 _isTextNode: function(node) {86 return node.childElements().length == 0 && node.innerHTML.strip().length > 0;87 }...
utils.js
Source: utils.js
...3}4export function sameSign(a, b) {5 return a > 0 && b > 0 || a < 0 && b < 0;6}7export function isTextNode(el) {8 return el.nodeType === 3;9}10export function closest(el, s, limit) {11 if (isTextNode(el)) {12 el = el.parentNode;13 }14 if (!limit.contains(el)) return null;15 do {16 if (!el || !el.matches) {17 debugger18 }19 if (el.matches(s)) return el;20 el = el.parentElement;21 } while (el !== limit);22 return null;23};24export function setDataset(el, vs) {25 el.dataset[vs[0]] = vs[1];26}27export function eqDataset(el, vs) {28 return el.dataset && el.dataset[vs[0]] === vs[1];29}30export function getEqDatasetQuery(vs) {31 return `[data-${vs[0]}=${vs[1]}]`;32}33function traverseNode(n, datasetMap, fn) {34 if (isTextNode(n) || eqDataset(n, datasetMap.void)) {35 return fn(n);;36 }37 let ret = false;;38 if (n.childNodes) {39 for (const c of n.childNodes) {40 ret = traverseNode(c, datasetMap, fn);41 if (ret) {42 break;43 }44 }45 }46 return ret;47}48export function findNodesInBlock(p, datasetMap, { start, end }) {49 const nodes = [];50 let started = !start;51 traverseNode(p, datasetMap, (n) => {52 if (n === start) {53 started = true;54 }55 if (started) {56 let nn = n;57 if (isTextNode(nn)) {58 nn = nn.parentNode;59 }60 nodes.push(nn);61 }62 if (n === end) {63 started = false;64 return true;65 }66 });67 return nodes;68}69export function getChildElement(parent, index) {70 return parent && parent.childNodes && parent.childNodes[index];71}72export function px(i) {73 return i + 'px';74}75export function extendSelection(selection) {76 let { anchorNode, anchorOffset, focusNode, focusOffset } = selection;77 let anchorElement = anchorNode;78 if (!isTextNode(anchorElement)) {79 anchorElement = anchorNode.childNodes[anchorOffset];80 }81 let focusElement = focusNode;82 if (!isTextNode(focusElement)) {83 focusElement = focusNode.childNodes[focusOffset];84 }85 return {86 ...selection,87 focusElement,88 anchorElement,89 };90}91export function eqSelection(s1, s2) {92 return s1.focusNode === s2.focusNode &&93 s1.anchorNode === s2.anchorNode &&94 s1.focusOffset === s2.focusOffset &&95 s1.anchorOffset === s2.anchorOffset;96}97export function isVoidSelected(selection) {98 if (!selection) {99 return false;100 }101 const { focusNode, focusElement, anchorElement } = extendSelection(selection);102 return (!isTextNode(focusNode) && focusElement === anchorElement);...
isTextNode.js
Source: isTextNode.js
23export default describe("Framework/TypeChecks/isTextNode", function() {4 //TRUE5 it("should return true if argument is a text node", function() {6 expect(isTextNode(document.createTextNode('text node'))).toBe(true);7 });8 //FALSE9 it("should return false if argument is a function", function() {10 expect(isTextNode(function(){})).toBe(false);11 });12 it("should return false if argument is an arrow function", function() {13 expect(isTextNode(() => {})).toBe(false);14 });15 it("should return false if argument is a class", function() {16 expect(isTextNode(class A {})).toBe(false);17 });18 it("should return false if argument is a string", function() {19 expect(isTextNode("a string")).toBe(false);20 });21 it("should return false if argument is object", function() {22 expect(isTextNode({})).toBe(false);23 });24 it("should return false if argument is array", function() {25 expect(isTextNode([])).toBe(false);26 });27 it("should return false if argument is a number = 1", function() {28 expect(isTextNode(1)).toBe(false);29 });30 it("should return false if argument is a number = 0", function() {31 expect(isTextNode(0)).toBe(false);32 });33 it("should return false if argument is a number = NaN", function() {34 expect(isTextNode(NaN)).toBe(false);35 });36 it("should return false if argument is a number = Infinity", function() {37 expect(isTextNode(Infinity)).toBe(false);38 });39 it("should return false if argument is a number = -Infinity", function() {40 expect(isTextNode(-Infinity)).toBe(false);41 });42 it("should return false if argument is a number = -1", function() {43 expect(isTextNode(-1)).toBe(false);44 });45 it("should return false if argument is undefined", function() {46 expect(isTextNode(undefined)).toBe(false);47 });48 it("should return false if argument is boolean = false", function() {49 expect(isTextNode(false)).toBe(false);50 });51 it("should return false if argument is boolean = true", function() {52 expect(isTextNode(true)).toBe(false);53 });
...
isTextNode-test.js
Source: isTextNode-test.js
...8 */9var isTextNode = require('isTextNode');10describe('isTextNode', () => {11 it('should reject strings', () => {12 expect(isTextNode('')).toBe(false);13 expect(isTextNode('a real string')).toBe(false);14 });15 it('should accept text nodes from DOM', () => {16 var span = document.createElement('span');17 span.innerHTML = '<b>some text</b>';18 document.body.appendChild(span);19 var textnode = document.body.lastChild.firstChild.firstChild;20 try {21 expect(isTextNode(textnode)).toBe(true);22 } finally {23 document.body.removeChild(span);24 }25 });26 it('should accept dynamically created text nodes', () => {27 var textnode = document.createTextNode('some more text');28 expect(isTextNode(textnode)).toBe(true);29 });...
Using AI Code Generation
1const { isTextNode } = require('playwright/lib/server/dom.js');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const textNodes = await page.$$('body *');8 const node = textNodes.find(isTextNode);9 await node.evaluate(e => e.textContent = 'Hello!');10 await page.screenshot({ path: 'example.png' });11 await browser.close();12})();
Using AI Code Generation
1const { isTextNode } = require('playwright/lib/utils/dom');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const firstTextNode = await page.$eval('body', (element) => {8 for (const node of element.childNodes) {9 if (isTextNode(node)) {10 return node.textContent;11 }12 }13 });14 console.log(firstTextNode);15 await browser.close();16})();
Using AI Code Generation
1const { isTextNode } = require('playwright/lib/web/dom.js');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 const elementHandle = await page.$('input[name="q"]');7 const isTextNode = await elementHandle.evaluate((node) => {8 return isTextNode(node);9 });10 console.log(isTextNode);11 await browser.close();12})();
Using AI Code Generation
1const { isTextNode } = require('playwright/lib/client/selectorEngine');2const { chromium } = require('playwright');3const fs = require('fs');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 const handle = await page.$('input[name="q"]');9 const node = await handle.evaluateHandle((node) => node);10 const isTextNode = await node.evaluate((node) => node.nodeType === 3);11 console.log(isTextNode);12 await browser.close();13})();14const { isTextNode } = require('playwright/lib/client/selectorEngine');15const { chromium } = require('playwright');16const fs = require('fs');17(async () => {18 const browser = await chromium.launch();19 const context = await browser.newContext();20 const page = await context.newPage();21 const handle = await page.$('input[name="q"]');22 const node = await handle.evaluateHandle((node) => node);23 const isTextNode = await node.evaluate((node) => node.nodeType === 3);24 console.log(isTextNode);25 await browser.close();26})();27const { isTextNode } = require('playwright/lib/client/selectorEngine');28const { chromium } = require('playwright');29const fs = require('fs');30(async () => {31 const browser = await chromium.launch();32 const context = await browser.newContext();33 const page = await context.newPage();34 const handle = await page.$('input[name="q"]');35 const node = await handle.evaluateHandle((node) => node);36 const isTextNode = await node.evaluate((node) => node.nodeType === 3);37 console.log(isTextNode);38 await browser.close();39})();40const { isTextNode } = require('playwright/lib/client/selectorEngine');41const { chromium } = require('playwright');42const fs = require('fs');43(async () => {44 const browser = await chromium.launch();
Using AI Code Generation
1const { isTextNode } = require('@playwright/test/lib/server/dom');2const { test, expect } = require('@playwright/test');3test('isTextNode', async ({ page }) => {4 await page.setContent('<div>hello</div>');5 expect(await page.evaluate(isTextNode, page.locator('div').elementHandle())).toBe(false);6 expect(await page.evaluate(isTextNode, page.locator('div >> text=hello').elementHandle())).toBe(true);7});
Using AI Code Generation
1const { isTextNode } = require('playwright/lib/server/dom.js');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch({ headless: false });5 const context = await browser.newContext();6 const page = await context.newPage();7 const result = await page.evaluate(() => {8 const textNodes = [];9 const walk = document.createTreeWalker(10 );11 let node;12 while ((node = walk.nextNode())) {13 textNodes.push(node);14 }15 return textNodes.map((node) => node.textContent);16 });17 console.log(result);
Using AI Code Generation
1const { isTextNode } = require('playwright/lib/server/dom.js');2const textNode = document.createTextNode('some text');3const { isElementNode } = require('playwright/lib/server/dom.js');4const element = document.createElement('div');5const { isShadowRoot } = require('playwright/lib/server/dom.js');6const shadowRoot = document.createElement('div').attachShadow({mode: 'open'});7const { isDocument } = require('playwright/lib/server/dom.js');8const document = document;9const { isWindow } = require('playwright/lib/server/dom.js');10const window = window;11const { isEventTarget } = require('playwright/lib/server/dom.js');12const eventTarget = document;13const { isNode } = require('playwright/lib/server/dom.js');14const node = document.body;
Using AI Code Generation
1const { isTextNode } = require('playwright/lib/server/dom.js');2const { test, expect } = require('@playwright/test');3test('isTextNode', async ({ page }) => {4 await page.setContent('<div>Hello</div>');5 const div = await page.$('div');6 expect(await isTextNode(div)).toBe(false);7 const text = await page.evaluateHandle((div) => div.firstChild, div);8 expect(await isTextNode(text)).toBe(true);9});10const { isElementNode } = require('playwright/lib/server/dom.js');11const { test, expect } = require('@playwright/test');12test('isElementNode', async ({ page }) => {13 await page.setContent('<div>Hello</div>');14 const div = await page.$('div');15 expect(await isElementNode(div)).toBe(true);16 const text = await page.evaluateHandle((div) => div.firstChild, div);17 expect(await isElementNode(text)).toBe(false);18});19const { isShadowRoot } = require('playwright/lib/server/dom.js');20const { test, expect } = require('@playwright/test');21test('isShadowRoot', async ({ page }) => {22 await page.setContent('<div>Hello</div>');23 const div = await page.$('div');24 expect(await isShadowRoot(div)).toBe(false);25 const shadow = await page.evaluateHandle((div) => div.attachShadow({mode: 'open'}), div);26 expect(await isShadowRoot(shadow)).toBe(true);27});28const { isDocument } = require('playwright/lib/server/dom.js');29const { test, expect } = require('@playwright/test');30test('isDocument', async ({ page }) => {31 await page.setContent('<div>Hello</div>');32 const div = await page.$('div');33 expect(await isDocument(div)).toBe(false);34 const document = await page.evaluateHandle(() => document);35 expect(await isDocument(document)).toBe(true);36});
Using AI Code Generation
1const { isTextNode } = require('@playwright/test/lib/server/domSnapshot.js');2const { assert } = require('console');3const { test, expect } = require('@playwright/test');4test('isTextNode', async ({ page }) => {5 await page.setContent('<div>Text</div>');6 const div = await page.$('div');7 const text = await page.evaluateHandle((div) => div.firstChild, div);8 expect(await isTextNode(text)).toBe(true);9});10const { isElementNode } = require('@playwright/test/lib/server/domSnapshot.js');11const { assert } = require('console');12const { test, expect } = require('@playwright/test');13test('isElementNode', async ({ page }) => {14 await page.setContent('<div>Text</div>');15 const div = await page.$('div');16 expect(await isElementNode(div)).toBe(true);17});18const { isShadowRoot } = require('@playwright/test/lib/server/domSnapshot.js');19const { assert } = require('console');20const { test, expect } = require('@playwright/test');21test('isShadowRoot', async ({ page }) => {22 await page.setContent('<div>Text</div>');23 const div = await page.$('div');24 const shadow = await page.evaluateHandle((div) => div.attachShadow({ mode: 'open' }), div);25 expect(await isShadowRoot(shadow)).toBe(true);26});27const { isDocumentNode } = require('@playwright/test/lib/server/domSnapshot.js');28const { assert } = require('console');29const { test, expect } = require('@playwright/test');30test('isDocumentNode', async ({ page }) => {31 await page.setContent('<div>Text</div>');32 const document = await page.evaluateHandle(() => document);33 expect(await isDocumentNode(document)).toBe(true);34});35const { isDocumentTypeNode } = require('@playwright/test/lib/server/domSnapshot.js');36const { assert } = require('console');37const { test, expect } =
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!!