Best JavaScript code snippet using playwright-internal
bdgagencyrule_list.js
Source: bdgagencyrule_list.js
1var mainmenu = null;2var menuid = null;34var qtree = null;5var _qtree = null;6var consoletable = null;7var datatable = null;8var subdatatable = null;910var userdata = null; //´¦ÊÒÓû§11var consolegroup = null; //¿ØÖÆ×é12var productData = null; //²úÆ·ÀàÐÍ1314var form_content_wind = null;15var consoleName = null;16var consoleCode = null;17var formtag = null;18var mainArray = [];19var formId = null;2021var bdgagencyrule_list = function(config, service) {22 mainmenu = config.mainmenu;23 menuid = config.menuid;24 25 userdata = config.userData;26 usergroup = config.userGroup;27 consolegroup = config.consoleGroup;28 productData = config.productList; 29 30 //³õʼ»¯Ö÷Ò³Ãæ 31 initLayoutMain(config); 32 33 qtree = new Ext.lt.Qtree({34 data : userdata,35 linkchild : true,36 linkparend : true,37 parentlinksub : true,38 showRootNode : true,39 selectmode : 'n',40 outformart : '#code-#name'41 });42 qtree.draw(treeDiv); 43 44 //Ê÷µÄ²éѯ·½·¨45 $("#selectInput").keyup(function(){ 46 qtree.searchnode([{field:'code',values:[this.value.trim()]},{field:'name',values:[this.value.trim()]}],'contain');47 48 if(!this.value.trim()) qtree.clearSelected();49 }).keyup();50 51 qtree.on({52 nodeclick : function(tree, param) {53 var selNode = param.data;54 if (selNode.isleaf != 0) {55 var params = {};56 params['bdgagency'] = selNode.itemid;57 params['menuid'] = menuid;58 59 Ext.lt.RCP.server("datacommon_bdgagencyrule_service", "getFromDataByAgency", params, function(data) {60 if (data != null && data.result != null) {61 var code = data.result.toArray(); 62 var consolearr = consoletable.getRecordSet().toArray();63 64 for(var i = 0; i < consolearr.length; i++){65 consolearr[i]["check"] = 0;66 }67 if(code.length != 0){68 var consoledatas = consoletable.getRecordSet().query({CONSOLECODE:code[0].CONSOLECODE});69 70 if(consoledatas){71 consoledatas[0]["check"] = 1; 72 }73 }74 consoletable.reflash();75 }76 },function(){77 alert('´íÎó!'); 78 });79 }80 }81 });82 83 var consolenode = function(td,el,l,c,d){84 var _val = $(el).find("input[type=radio]:checked");85 var name = consoletable.getCol(c).name;86 consoleName = d['CONSOLENAME'];87 consoleCode = d['CONSOLECODE'];88 $("#consolename").val(consoleName);89 if(name == 'CONSOLENAME'){90 copyfrom(1);91 }92 } 93 94 consoletable = new Ext.lt.datatable35(consolegroup);95 consoletable.setCols([96 consoletable.columns.seq,97 consoletable.columns.radio,98 {name:'CONSOLENAME',alias:'¿ØÖÆ×é',width:850,datatype:'S'}99 ]); 100 consoletable.setEditSelectCheckbox(false); 101 consoletable.setMouselight('#597EAA');102 consoletable.mousedrag(false);103 consoletable.setClassName('dttheme_ifmis'); 104 consoletable.setAlign("left");105 consoletable.setAllowClock(false); 106 consoletable.onEvent('onclick',consolenode);107 consoletable.setLayout();108 consoletable.draw(consolegroupDiv); 109 110 //ÐÂÔö²É¼¯±í¿ØÖÆ×鵯³ö´°111 form_content_wind = new Ext.lt.window({title:'¿ØÖÆ×éÉèÖÃ',fitmode:'content',className:'wind7',mark:true,autoshow:true,pop:true,w:425,h:400});112 form_content_wind.draw(form_content);113 $("#form_content").show();114 form_content_wind.hidden();115 116 //ÐÂÔö²É¼¯±í¿ØÖÆ×éÁÐÒªËص¯³ö´°117 form_subdata_wind = new Ext.lt.window({title:'ÒªËØÉèÖÃ',fitmode:'content',className:'wind7',mark:true,autoshow:true,pop:true,w:425,h:400});118 form_subdata_wind.draw(form_subdata);119 $("#form_subdata").show();120 form_subdata_wind.hidden();121}122123//³õʼ»¯Ö÷Ò³Ãæ124function initLayoutMain(config){125 var sb = new StringBuffer();126 127 sb.append("<table align='center' width=\"100%\" border=\"0\">");128 sb.append("<tr><td valign=\"top\" width=\"20%\">");129 sb.append("<div style=\"position:relative;z-index:100;\">");130 sb.append("<input type=\"text\" style=\"width:99%;\" id=\"selectInput\" value=\"\">");131 sb.append("</div>");132 sb.append("</td>");133 sb.append("<td width=\"80%\">");134 sb.append("<div class=\"budget_title\" style=\"position:relative;z-index:100;\">");135 sb.append("<span style=\"vertical-align:middle;\" onmouseover=\"this.className='budget_over'\" onmouseout=\"this.className=''\"><button class=\"budget_clear\" id=\"btn_unBdgagency01\" onclick=\"dosave()\">±£´æ</button></span>");136 sb.append("<span style=\"vertical-align:middle;\" onmouseover=\"this.className='budget_over'\" onmouseout=\"this.className=''\"><button class=\"budget_clear\" id=\"btn_unBdgagency02\" onclick=\"copyfrom(0)\">ÐÂÔö²É¼¯±í¿ØÖÆ×é</button></span>");137 sb.append("<span style=\"vertical-align:middle;\" onmouseover=\"this.className='budget_over'\" onmouseout=\"this.className=''\"><button class=\"budget_clear\" id=\"btn_unBdgagency02\" onclick=\"delForm()\">ɾ³ý¿ØÖÆ×é</button></span>");138 sb.append("</div>");139 sb.append("</td>");140 sb.append("</tr>");141 sb.append("<tr>");142 sb.append("<td valign=\"top\">");143 sb.append("<div id=\"treeDiv\" layout=\"{h:{fit:-25}}\" style=\"background:#fff;border:1px solid #ccc;padding:0px; overflow:auto;height:550px;width:100%;\"></div>");144 sb.append("</td>");145 sb.append("<td valign=\"top\">");146 sb.append("<div id='consolegroupDiv' layout=\"{w:{fit:-250},h:{fit:-25}}\" style=\"background:#fff;border:1px solid #ccc;padding:0px; overflow:auto;height:550px;width:100%;\"></div>");147 sb.append("</td>");148 sb.append("</tr>");149 sb.append("</table>");150 151 sb.append("<div id=\"form_content\" style=\"display:none;\" >");152 sb.append("<div style=\"margin-left:2%;height:20px;\">");153 sb.append("¿ØÖÆ×éÃû³Æ£º<input type=\"text\" id=\"consolename\"></input>");154 sb.append("</div>");155 sb.append("<div style=\"width:425px;height:380px;\">");156 sb.append("<div id='form_content02' style=\"width:99%;height:375px;overflow:scroll;position:absolute;background-color:#FCFCFC;border:1px solid #ccc;\">");157 sb.append("</div>");158 sb.append("</div>");159 sb.append("<div style=\"margin-left:40%;\">");160 sb.append("<input type=\"button\" value=\"±£ ´æ\" onclick=\"dosaveform()\"></input>");161 sb.append("<input type=\"button\" value=\"È¡ Ïû\" onclick=\"form_content_wind.hidden();\"></input>");162 sb.append("</div>");163 sb.append("</div>");164 165 sb.append("<div id=\"form_subdata\" style=\"display:none;\" >");166 sb.append("<div style=\"width:425px;height:400px;\">");167 sb.append("<div id='form_subdata02' style=\"width:99%;height:375px;overflow:scroll;position:absolute;background-color:#FCFCFC;border:1px solid #ccc;\">");168 sb.append("</div>");169 sb.append("</div>");170 sb.append("<div style=\"margin-left:40%;\">");171 sb.append("<input type=\"button\" value=\"±£ ´æ\" onclick=\"dosavesubdata()\"></input>");172 sb.append("<input type=\"button\" value=\"È¡ Ïû\" onclick=\"form_subdata_wind.hidden();\"></input>");173 sb.append("</div>");174 sb.append("</div>");175 176 document.getElementById("template_main").innerHTML = sb.toString();177}178179//ÐÂÔö²É¼¯±í¿ØÖÆ×é180function copyfrom(tag){ 181 formtag = tag;182 mainArray = [];183 184 if(tag == 1){185 var params = {};186 params['menuid'] = menuid;187 params['consoleCode'] = consoleCode;188 Ext.lt.RCP.server("datacommon_bdgagencyrule_service", "getFromData",params,function(data){189 if (data != null && data.result != null) {190 form_content_wind.show(); 191 if(!datatable){192 tableView(data.result, form_content02);193 } else {194 var datas = datatable.getRecordset();195 datas.clear();196 datas.addData(data.result.toArray());197 }198 } else {199 alert("¸Ã¿ØÖÆ×é¶ÔÓ¦µÄ²É¼¯±íÉèÖò»´æÔÚ£¬Çë²é¿´£¡");200 }201 },function(){202 alert('´íÎó!'); 203 });204 } else {205 $("#consolename").val("");206 var params = {};207// params['product'] = $("#producttype").val();208 Ext.lt.RCP.server("datacommon_bdgagencyrule_service", "getMainList",params,function(data){209 form_content_wind.show(); 210 if(!datatable){ 211 tableView(data.mainList, form_content02);212 } else {213 var datas = datatable.getRecordset();214 datas.clear();215 datas.addData(data.mainList.toArray());216 }217 },function(){218 alert('´íÎó!'); 219 });220 }221}222223//ɾ³ý¿ØÖÆ×é224function delForm(){225 var datas = consoletable.getRecordSet().query({check:1});226 if(!consoleCode){227 alert("ÇëÏÈÑ¡Ôñ¿ØÖÆ×é!");228 return;229 } 230 231 if(window.confirm("½«»áɾ³ýÑ¡ÖпØÖÆ×é¼°¿ØÖÆ×éÓйصÄÅäÖã¬È·ÈÏÊÇ·ñɾ³ýÑ¡ÖпØÖÆ×飿")){232 var params = {};233 params['menuid'] = menuid;234 params['consoleCode'] = consoleCode; 235 236 Ext.lt.RCP.server("datacommon_bdgagencyrule_service", "deleteConsoleGroup",params,function(data){237 if (data != null && data.result == 1) {238 consoletable.getRecordSet().remove(datas);239 alert("¿ØÖÆ×éɾ³ý³É¹¦£¡");240 } else {241 if (data.message != null) {242 alert(data.message);243 } else {244 alert("ɾ³ý¿ØÖÆ×éʧ°Ü£¬ÇëÁªÏµ¹ÜÀíÔ±£¡");245 }246 }247 },function(){248 alert('´íÎó!'); 249 });250 }251}252253//±£´æ¿ØÖÆ×é254function dosaveform(){255 var consolename = $("#consolename").val();256 if (consolename == null || consolename == "") {257 alert("ÇëÊäÈë¿ØÖÆ×éÃû³Æ!");258 return;259 }260 261 var mainarrays = datatable.getRecordset().toArray(); 262 263 var params = {};264 params['mainarrays'] = JSON.stringify(mainarrays);265 params['subarrays'] = JSON.stringify(mainArray); 266 params['menuid'] = menuid;267 params['consoleName'] = consolename;268 params['code'] = consoleCode;269 params['formtag'] = formtag;270 271 Ext.lt.RCP.server("datacommon_bdgagencyrule_service", "saveConsoleGroup",params,function(data){272 if (data != null && data.result == 1) {273 alert("¿ØÖÆ×éÉèÖóɹ¦£¡");274 var params = {};275 jumpTo("/datacommon/bdgagencyrule/index.page?mainmenu=" + mainmenu276 + "&submenu=" + menuid + "", "post", params);277 } else {278 if (data.message != null) {279 alert(data.message);280 } else {281 alert("ÉèÖÿØÖÆ×éʧ°Ü£¬ÇëÁªÏµ¹ÜÀíÔ±£¡");282 }283 }284 },function(){285 alert('´íÎó!'); 286 });287}288289//±£´æÒªËØ290function dosavesubdata(){291 var array = [];292 var datas = subdatatable.getRecordset();293 array = datas.toArray();294 for(var i = 0; i < array.length; i++){295 array[i]['FORMID'] = formId;296 }297 for(var i = 0; i < mainArray.length; i++){298 if(mainArray[i][0].FORMID == array[0].FORMID){299 mainArray.splice(i, 1);300 }301 }302 mainArray.push(array); 303 form_subdata_wind.hidden();304}305306//±£´æ²Ëµ¥ºÍ¿ØÖÆ×é¶ÔÓ¦¹Øϵ307function dosave(){308 var userdata = consoletable.getRecordset().query({check:1});309310 if (userdata.length == 0) {311 alert("ÇëÑ¡Ôñ¿ØÖÆ×飡");312 return;313 }314 315 var userData = qtree.getSelected();316 if (userData.length == 0) {317 alert("ÇëÑ¡ÔñÓû§£¡");318 return;319 }320 var itemids = [];321 var j = 0;322 if (userData.length > 0) {323 for ( var i = 0; i < userData.length; i++) {324 if (userData[i].isleaf == '1') {325 itemids[j] = userData[i].itemid;326 j++;327 }328 }329 }330 var userIdes = itemids.join(",");331 332 var params = {};333 params['userarrays'] = userIdes;334 params['menuid'] = menuid;335 params['consoleCode'] = userdata[0].CONSOLECODE;336 337 Ext.lt.RCP.server("datacommon_bdgagencyrule_service", "saveConsoleAndUserGroup",params,function(data){338 if (data != null && data.result == 1) {339 alert("µ¥Î»²É¼¯±íȨÏÞÉèÖóɹ¦£¡");340 } else {341 if (data.message != null) {342 alert(data.message);343 } else {344 alert("µ¥Î»²É¼¯±íȨÏÞÉèÖÃʧ°Ü£¬ÇëÁªÏµ¹ÜÀíÔ±£¡");345 }346 }347 },function(){348 alert('´íÎó!'); 349 });350}351352//²éѯÁÐ353function column(){354 var params = {};355 params['formid'] = formId;356 params['menuid'] = menuid;357 params['consoleCode'] = consoleCode;358 359 Ext.lt.RCP.server("datacommon_bdgagencyrule_service", "getFromSubData",params,function(data){360 if (data != null && data.result != null) {361 form_subdata_wind.show();362 if(!subdatatable){363 subdataView(data.result, form_subdata02);364 } else {365 var datas = subdatatable.getRecordset();366 datas.clear();367 datas.addData(data.result.toArray());368 }369 } else {370 alert("»ñÈ¡²É¼¯±íÒªËØʧ°Ü£¬Çë¼ì²é²É¼¯±í!");371 }372 },function(){373 alert('´íÎó!'); 374 });375}376377//»±í378function tableView(tableData, tableDiv){379 var test = function(i,j,rs,value){380 if(rs.PERM==1){381 return ['<input type="radio" value=1 name='+rs.FORMID+' checked>¿É¸Ä <input type="radio" value=2 name='+rs.FORMID+'>²»¿É¸Ä']382 }383 else{384 return ['<input type="radio" value=1 name='+rs.FORMID+'>¿É¸Ä <input type="radio" value=2 name='+rs.FORMID+' checked>²»¿É¸Ä']385 }386 };387 388 var node = function(td,el,l,c,d){ 389 var _val = $(el).find("input[type=radio]:checked");390 var name = datatable.getCol(c).name;391 formId = d['FORMID'];392 if(_val.val() == 1){393 d['PERM'] = 1;394 } else {395 d['PERM'] = 2;396 }397 if(name == 'NAME'){398 column();399 }400 }401 402 datatable = new Ext.lt.datatable35(tableData);403 datatable.setCols([404 {name:'NAME',alias:'¿ØÖÆ×é',width:200,datatype:'S'},405 {name:'PERM',alias:'ÉèÖÃ',width:200,datatype:'S',fn:test}406 ]); 407 datatable.setEditSelectCheckbox(false); 408 datatable.setMouselight('#597EAA');409 datatable.mousedrag(false);410 datatable.setClassName('dttheme_ifmis'); 411 datatable.setAlign("left");412 datatable.setAllowClock(false); 413 datatable.onEvent('onclick',node); 414 datatable.setLayout();415 datatable.draw(tableDiv);416}417418//ÁÐÒªËØ»±í419function subdataView(tableData, tableDiv){420 var test = function(i,j,rs,value){421 if(rs.PERM==1){422 return ['<input type="radio" value=1 name='+rs.FORMELEMENTID+' checked>¿É¸Ä <input type="radio" value=2 name='+rs.FORMELEMENTID+'>²»¿É¸Ä']423 }424 else{425 return ['<input type="radio" value=1 name='+rs.FORMELEMENTID+'>¿É¸Ä <input type="radio" value=2 name='+rs.FORMELEMENTID+' checked>²»¿É¸Ä']426 }427 };428 429 var node = function(td,el,l,c,d){ 430 var _val = $(el).find("input[type=radio]:checked");431 if(_val.val() == 1){432 d['PERM'] = 1;433 } else {434 d['PERM'] = 2;435 }436 }437 438 subdatatable = new Ext.lt.datatable35(tableData);439 subdatatable.setCols([440 {name:'NAME',alias:'ÒªËØ',width:200,datatype:'S'},441 {name:'PERM',alias:'ÉèÖÃ',width:200,datatype:'S',fn:test}442 ]); 443 subdatatable.setEditSelectCheckbox(false); 444 subdatatable.setMouselight('#597EAA');445 subdatatable.mousedrag(false);446 subdatatable.setClassName('dttheme_ifmis'); 447 subdatatable.setAlign("left");448 subdatatable.setAllowClock(false); 449 subdatatable.onEvent('onclick',node); 450 subdatatable.setLayout();451 subdatatable.draw(tableDiv);
...
queries.js
Source: queries.js
...14// });15// // create promisify version of query16// const query = util.promisify(connection.query).bind(connection);17// // create function that produces tables in console18// function consoleTable(rows) {19// const table = new Table();20// table.addRows(rows, { color: 'cyan' });21// table.printTable();22// }23// // create function to query all data from selected database24// async function queryAllFrom(tableSelection) {25// if (tableSelection == 'departments') {26// try {27// const rows = await query(selectDepartments);28// consoleTable(rows);29// } finally {30// connection.end();31// }32// } else if (tableSelection == 'roles') {33// try {34// const rows = await query(selectRoles);35// consoleTable(rows);36// } finally {37// connection.end();38// }39// } else if (tableSelection == 'employees') {40// try {41// const rows = await query(selectEmployees);42// consoleTable(rows);43// } finally {44// connection.end();45// }46// }47// }48// // create function to query all data from selected database49// async function addDataTo(tableSelection, params) {50// if (tableSelection == 'employees') {51// const { firstName, lastName, roleId, managerId } = params;52// try {53// await query(`INSERT INTO employees (first_name, last_name, role_id, manager_id) VALUES (?,?,?,?);`, [firstName, lastName, roleId, managerId]);54// const rows = await query(selectEmployees);55// consoleTable(rows);56// } finally {57// connection.end();58// }59// } else if (tableSelection == 'roles') {60// const { title, salary, departmentId } = params;61// try {62// await query(`INSERT INTO roles (title, salary, department_id) VALUES (?,?,?);`, [title, salary, departmentId]);63// const rows = await query(selectRoles);64// consoleTable(rows);65// } finally {66// connection.end();67// }68// } else if (tableSelection == 'departments') {69// const { deptName } = params;70// try {71// await query(`INSERT INTO departments (dept_name) VALUES (?);`, [deptName]);72// const rows = await query(selectDepartments);73// consoleTable(rows);74// } finally {75// connection.end();76// }77// }78// }79// // create function to get the current list of employee names80// async function getEmployeeNames() {81// let employeeData = await query(employeeNames);82// let employeeArray = [];83// for (let employee of employeeData) {84// employeeArray.push(`${employee.first_name} ${employee.last_name}`);85// }86// return employeeArray;87// }88// // create function to get the current list of manager names89// async function getManagerNames() {90// let managerData = await query(getAllManagers);91// let managerArray = [];92// for (let manager of managerData) {93// managerArray.push(`${manager.first_name} ${manager.last_name}`);94// }95// return managerArray;96// }97// // create function to display the employees for each manager98// async function queryManagerByEmployee(params) {99// let { manager } = params;100// let managerNameArr = manager.split(" ");101// let managerFirstName = managerNameArr[0];102// let managerLastName = managerNameArr[1];103// let managerIdArr = await query(`SELECT id FROM employees WHERE first_name=? AND last_name= ?;`, [managerFirstName, managerLastName]);104// let managerEmployeeId = managerIdArr[0].id;105// try {106// const rows = await query(`SELECT e.first_name, e.last_name, r.title FROM employees JOIN roles r ON e.role_id = r.id AND e.id = ?;`, [managerEmployeeId]);107// consoleTable(rows);108// } finally {109// connection.end();110// }111// }112// // create function to get the current list of role titles113// async function getRoleTitles() {114// let roleData = await query(roleTitles);115// let roleArray = [];116// for (let role of roleData) {117// roleArray.push(role.title);118// }119// return roleArray;120// }121// // create function to get the current list of departments122// async function getDeptNames() {123// let deptData = await query(departmentNames);124// let deptArray = [];125// for (let dept of deptData) {126// deptArray.push(dept.dept_name);127// }128// return deptArray;129// }130// // create function to update specific things about employees131// async function updateDataIn(tableSelection, params, identifier) {132// if (tableSelection == 'employees' && identifier == 'role') {133// const { selectedEmployee, roleTitle } = params;134// let employeeNameArray = selectedEmployee.split(' ');135// let firstName = employeeNameArray[0];136// try {137// let roleIdArr = await query(`SELECT id FROM roles WHERE title=?;`, [roleTitle]);138// let roleId = roleIdArr[0].id;139// await query(`UPDATE employees SET role_id=? WHERE first_name=?;`, [roleId, firstName]);140// const rows = await query(selectEmployees);141// consoleTable(rows);142// } finally {143// connection.end();144// }145// } else if (tableSelection == 'employees' && identifier == 'manager') {146// const { selectedEmployee, selectedManager } = params;147// let employeeNameArray = selectedEmployee.split(' ');148// let lastName = employeeNameArray[1];149// let managerNameArray = selectedManager.split(' ');150// let managerLast = managerNameArray[1];151// try {152// let managerIdArr = await query(`SELECT id FROM employees WHERE last_name=?;`, [managerLast]);153// let managerId = managerIdArr[0].id;154// await query(`UPDATE employees SET manager_id=? WHERE last_name=?;`, [managerId, lastName]);155// const rows = await query(selectEmployees);156// consoleTable(rows);157// } finally {158// connection.end();159// }160// }161// }162// // create function to delete rows from chosen table163// async function deleteDataFrom(tableSelection, params) {164// if (tableSelection == 'employees') {165// const { deletedEmployee } = params;166// let employeeNameArray = deletedEmployee.split(' ');167// let firstName = employeeNameArray[0];168// let lastName = employeeNameArray[1];169// try {170// let employeeIdArr = await query(`SELECT id FROM employees WHERE first_name=? AND last_name=?;`, [firstName, lastName]);171// let employeeId = employeeIdArr[0].id;172// await query(`DELETE FROM employees WHERE id=?;`, [employeeId]);173// const rows = await query(selectEmployees);174// consoleTable(rows);175// } finally {176// connection.end();177// }178// } else if (tableSelection == 'roles') {179// const { deletedRole } = params;180// try {181// let roleIdArr = await query(`SELECT id FROM roles WHERE title=?;`, [deletedRole]);182// let roleId = roleIdArr[0].id;183// await query(`DELETE FROM roles WHERE id=?;`, [roleId]);184// const rows = await query(selectRoles);185// consoleTable(rows);186// } finally {187// connection.end();188// }189// } else if (tableSelection == 'departments') {190// const { deletedDept } = params;191// try {192// let deptIdArr = await query(`SELECT id FROM departments WHERE dept_name=?;`, [deletedDept]);193// let deptId = deptIdArr[0].id;194// await query(`DELETE FROM departments WHERE id=?;`, [deptId]);195// const rows = await query(selectDepartments);196// consoleTable(rows);197// } finally {198// connection.end();199// }200// }201// }202// // create function to query employees in given department203// async function queryEmployeeByDepartment(params) {204// let { departmentName } = params;205// try {206// let rows = await query(`SELECT e.first_name, e.last_name, r.title FROM employees JOIN roles r ON e.role_id = r.id JOIN departments d ON r.department_id = d.id AND dept_name=?;`, [departmentName]);207// consoleTable(rows);208// } finally {209// connection.end();210// }211// }212// async function queryBudgetsByDepartment() {213// try {214// let rows = await query(getBudgetByDepartment);215// consoleTable(rows);216// } finally {217// connection.end();218// }219// }220// // export the functions!...
console.js
Source: console.js
1define(["require", "exports", "socket"], function (require, exports, socket_1) {2 "use strict";3 var ProcessConsole;4 (function (ProcessConsole) {5 var consoleTable = {};6 var consoleCapacity = 5000;7 var consoleProcess = null;8 var consoleFont = null;9 var consoleFontSize = null;10 function registerConsole() {11 socket_1.EventBus.createRoute("BEGIN", createConsole, null);12 socket_1.EventBus.createRoute('PRINT_ERROR', updateConsole, null);13 socket_1.EventBus.createRoute('PRINT_OUTPUT', updateConsole, null);14 socket_1.EventBus.createRoute('TERMINATE', terminateConsole, null); // clear focus15 socket_1.EventBus.createRoute('EXIT', terminateConsole, null);16 setInterval(showConsole, 200); // prevents reflow overload when console is busy17 }18 ProcessConsole.registerConsole = registerConsole;19 function updateConsoleFont(fontFamily, fontSize) {20 var consoleElement = document.getElementById("console");21 if (consoleElement != null) {22 consoleElement.style.fontFamily = fontFamily;23 consoleElement.style.fontSize = fontSize;24 }25 consoleFont = fontFamily;26 consoleFontSize = fontSize;27 }28 ProcessConsole.updateConsoleFont = updateConsoleFont;29 function updateConsoleCapacity(maxCapacity) {30 consoleCapacity = maxCapacity;31 }32 ProcessConsole.updateConsoleCapacity = updateConsoleCapacity;33 function terminateConsole(socket, type, text) {34 var message = JSON.parse(text);35 var process = message.process;36 if (consoleProcess == process) {37 showConsole();38 }39 var consoleData = consoleTable[process];40 if (consoleData != null) {41 consoleData.valid = false; // means it should be terminated when unfocused42 }43 }44 function clearConsole() {45 var consoleElement = document.getElementById("console");46 if (consoleElement != null) {47 document.getElementById("console").innerHTML = "";48 }49 consoleProcess = null;50 }51 ProcessConsole.clearConsole = clearConsole;52 /**53 * This method can be very slow, we need to improve the merging of nodes54 * so that concatenation reduces the overhead.55 */56 function showConsole() {57 var consoleElement = document.getElementById("console");58 var consoleText = null;59 var previous = null;60 if (consoleElement != null && consoleProcess != null) {61 var currentText = consoleElement.innerHTML;62 var consoleData = consoleTable[consoleProcess]; // is ther an update?63 if (consoleData != null && (currentText == "" || consoleData.update == true)) {64 consoleData.update = false; // clear the update65 for (var i = 0; i < consoleData.list.length; i++) {66 var next = consoleData.list[i];67 if (previous == null) {68 if (next.error) {69 consoleText = "<span class='consoleError'>" + next.text;70 }71 else {72 consoleText = "<span class='consoleNormal'>" + next.text;73 }74 previous = next.error;75 }76 else if (next.error != previous) {77 consoleText += "</span>";78 if (next.error) {79 consoleText += "<span class='consoleError'>" + next.text;80 }81 else {82 consoleText += "<span class='consoleNormal'>" + next.text;83 }84 previous = next.error;85 }86 else {87 consoleText += next.text;88 }89 }90 if (consoleText != null) {91 consoleText += "</span>";92 consoleElement.innerHTML = consoleText;93 consoleElement.scrollTop = consoleElement.scrollHeight;94 }95 }96 if (consoleFont && consoleFontSize) {97 updateConsoleFont(consoleFont, consoleFontSize);98 }99 }100 }101 ProcessConsole.showConsole = showConsole;102 function updateConsoleFocus(processToFocus) {103 if (consoleProcess != processToFocus) {104 deleteAllInvalidConsoles(processToFocus); // delete only on a change of focus105 clearConsole();106 consoleProcess = processToFocus;107 showConsole();108 }109 }110 ProcessConsole.updateConsoleFocus = updateConsoleFocus;111 function deleteAllInvalidConsoles(processToKeep) {112 var validConsoles = {};113 for (var processName in consoleTable) {114 if (consoleTable.hasOwnProperty(processName)) {115 var consoleData = consoleTable[processName];116 if (consoleData.valid || processName == processToKeep) {117 validConsoles[processName] = consoleData;118 }119 }120 }121 consoleTable = validConsoles; // make sure expired consoles are removed122 }123 function createConsole(socket, type, value) {124 var message = JSON.parse(value);125 var newProcess = message.process;126 var consoleData = consoleTable[newProcess];127 consoleTable[newProcess] = {128 list: [],129 size: 0,130 update: true,131 valid: true132 };133 updateConsoleFocus(newProcess);134 }135 /**136 * This function should probably merge the nodes to some extent, it will improve137 * the performance of the console rendering.138 */139 function updateConsole(socket, type, value) {140 var offset = value.indexOf(':');141 var updateProcess = value.substring(0, offset);142 var updateText = value.substring(offset + 1);143 var node = {144 error: type == 'PRINT_ERROR',145 text: updateText146 };147 var consoleData = consoleTable[updateProcess];148 if (consoleData == null) {149 consoleData = {150 list: [],151 size: 0,152 update: true,153 valid: true154 };155 consoleTable[updateProcess] = consoleData;156 }157 consoleData.list.push(node); // put at the end, i.e index consoleTable.length - 1158 consoleData.size += updateText.length; // update the size of the console159 while (consoleData.list.length > 3 && consoleData.size > consoleCapacity) {160 var removeNode = consoleData.list.shift(); // remove from the start, i.e index 0161 if (removeNode != null) {162 consoleData.size -= removeNode.text.length;163 }164 }165 consoleData.update = true;166 }167 })(ProcessConsole = exports.ProcessConsole || (exports.ProcessConsole = {}));168});
...
index.js
Source: index.js
...33 var rows = await Processor.ReturnProcess(data)34 rl.question("Escolha uma das opções a seguir:\n 1-Ver a tabela no console\n 2-Salvar a tabela em arquivo html\n 3-Salvar tabela como PDF\n", (option) => {35 switch (option) {36 case "1":37 consoleTable(rows)38 break39 case "2":40 parseHtml(rows)41 break42 case "3":43 parsePdf(rows)44 break45 default:46 console.log("Opção inválida!")47 break48 }49 rl.close()50 })51 })...
ChannelReportListPTR.jsx
Source: ChannelReportListPTR.jsx
1import React, {Component} from "react";2import {ConsoleTable} from "../../../common/ConsoleTable/ConsoleTable";3import {navigate} from "../../../../functions/navigate";4let $ = require('jquery');5export default class ChannelReportListPTR extends Component {6 componentDidMount() {7 document.title = "Ù
دÛرÛت کاÙا٠Ùا";8 $(document).on("click", "#goBackToChannel", function () {9 navigate('/v1/publisher/channel')10 })11 }12 render() {13 return (14 <div className='page-content'>15 <div className='row'>16 <div className='col-lg-8 col-md-8 col-sm-8 col-xs-12'>17 <h1 className='page-title'> Ù
دÛرÛت کاÙا٠Ùا</h1>18 </div>19 </div>20 <div className='portlet light bordered datatable-parent'>21 <div className='portlet-title'>22 <div className='caption'>23 <span className='caption-subject bold uppercase font-dark'> ÙÛست کاÙا٠Ùا </span>24 </div>25 <div className="actions">26 <div className="btn-group btn-group-devided" data-toggle="buttons">27 <button className="btn btn-transparent blue btn-outline btn-circle btn-sm"28 id="goBackToChannel">بازگشت ب٠ÙÛست کاÙاÙâÙا29 <i className="fa fa-backward" aria-hidden="true" style={{paddingRight: '5px'}}/>30 </button>31 </div>32 </div>33 </div>34 <div className='portlet-body'>35 <ConsoleTable {...this.props} list="channelReport"/>36 </div>37 </div>38 </div>39 )40 }...
network-printer.js
Source: network-printer.js
1const _ = require('lodash');2const Table = require('cli-table');3function printNeuronsState(network){4 console.log('Neuron state:');5 const consoleTable = new Table({colors: false});6 network.layers.forEach((layer, layerIndex) => {7 const layerState = layer.map((n, nind) => `n(${nind})={out=${n.output},b=${_.isNil(n.bias) ? 'N/A': n.bias}}`);8 const key = `Layer ${layerIndex}`;9 consoleTable.push({10 [key]: layerState.join(',')11 });12 });13 console.table(consoleTable.toString());14}15function printWiresState(network){16 console.log('Wires state:');17 const consoleTable = new Table({colors: false});18 network.layers.forEach((layer, layerIndex) => {19 if (layerIndex === network.layers.length - 1){20 return;21 }22 const wiresStates = [];23 layer.forEach((n) => n.outputWires.forEach(w => {24 wiresStates.push(`w(${n.index}-${w.outputNeuron.index})=${w.weight}`);25 }));26 const key = `Wires ${layerIndex}-${layerIndex+1}`;27 consoleTable.push({28 [key]: wiresStates.join(',')29 });30 });31 console.table(consoleTable.toString());32}33function printState(network, {step} = {}){34 if (!_.isNil(step)){35 console.log('Executing step: ' + step);36 }37 printNeuronsState(network);38 printWiresState(network);39}40module.exports = {41 printState...
UsersListPTR.jsx
Source: UsersListPTR.jsx
1import React, {Component} from "react";2import {ConsoleTable} from "../../common/ConsoleTable/ConsoleTable";3import EditUserModalCTR from "./EditUserModalCTR";4import {securify} from "../../../functions/securify";5export default class UsersListPTR extends Component {6 componentDidMount() {7 document.title = "Ù
دÛرÛت کاربراÙ";8 }9 render() {10 return (11 <div className='page-content'>12 <h1 className="page-title"> Ù
دÛرÛت کاربراÙ13 </h1>14 <div className='portlet light datatable-parent bordered'>15 <div className='portlet-title'>16 <div className='caption'>17 <span className='caption-subject bold uppercase font-dark'> ÙÛست کاربرا٠</span>18 </div>19 </div>20 <div className='portlet-body'>21 {securify(22 () => <ConsoleTable {...this.props} list="user"/>,23 ({user}, {canSeeUserList}, run) => run(canSeeUserList())24 )}25 <EditUserModalCTR form="EditUserModalPTR"/>26 </div>27 </div>28 </div>29 )30 }...
TranslationListPTR.jsx
Source: TranslationListPTR.jsx
1import React, {Component} from "react";2import {ConsoleTable} from "./../common/ConsoleTable/ConsoleTable";3export default class TranslationListPTR extends Component {4 componentDidMount() {5 document.title = "Ù
دÛرÛت ترجÙ
Ù Ùا";6 }7 render() {8 return (9 <div className='page-content'>10 <div className='row'>11 <div className='col-lg-8 col-md-8 col-sm-8 col-xs-12'>12 <h1 className='page-title'>ترجÙ
Ù Ùا</h1>13 </div>14 </div>15 <div className='portlet light bordered datatable-parent'>16 <div className='portlet-title'>17 <div className='caption'>18 <span className='caption-subject bold uppercase font-dark'>ÙÛست عبارات </span>19 </div>20 </div>21 <div className='portlet-body'>22 <ConsoleTable {...this.props} list="translation"/>23 </div>24 </div>25 </div>26 )27 }...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.evaluate(() => {7 { name: 'John', age: 25, city: 'New York' },8 { name: 'Peter', age: 18, city: 'Sidney' },9 ];10 console.table(data);11 });12 await browser.close();13})();14│ (index) │ age │ city │15const { chromium } = require('playwright');16(async () => {17 const browser = await chromium.launch();18 const context = await browser.newContext();19 const page = await context.newPage();20 await page.evaluate(() => {21 { name: 'John', age: 25, city: 'New York' },22 { name: 'Peter', age: 18, city: 'Sidney' },23 ];24 console.table(data);25 });26 await browser.close();27})();28│ (index) │ age │ city │29const { chromium } = require('playwright');30(async () => {31 const browser = await chromium.launch();32 const context = await browser.newContext();33 const page = await context.newPage();
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 for (const browserType of ['chromium', 'firefox', 'webkit']) {4 const browser = await playwright[browserType].launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.type('text="Search"', 'Playwright');8 await page.click('input:has-text("Google Search")');9 await page.waitForTimeout(5000);10 await page.screenshot({ path: `example-${browserType}.png` });11 await browser.close();12 }13})();14const { chromium } = require('playwright');15(async () => {16 const browser = await chromium.launch();17 const context = await browser.newContext();18 const page = await context.newPage();19 await page.type('text="Search"', 'Playwright');20 await page.click('input:has-text("Google Search")');21 await page.waitForTimeout(5000);22 await page.screenshot({ path: `example.png` });23 await browser.close();24})();
Using AI Code Generation
1const consoleTable = require('console.table');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 data = await page.$$eval('table', (table) => {8 return table.map((row) => {9 return Array.from(row.querySelectorAll('td')).map((cell) => {10 return cell.textContent;11 });12 });13 });14 consoleTable(data);15 await browser.close();16})();
Using AI Code Generation
1const { Console } = require('console');2const console = new Console(process.stdout, process.stderr);3const { chromium } = require('playwright');4(async () => {5 const browser = await chromium.launch({ headless: false });6 const context = await browser.newContext();7 const page = await context.newPage();8 ];9 console.table(table);10 await browser.close();11})();12│ (index) │ Values │
Using AI Code Generation
1const { Console } = require('console');2const console = new Console(process.stdout, process.stderr);3const { chromium } = require('playwright');4(async () => {5 const browser = await chromium.launch({ headless: false });6 const context = await browser.newContext();7 const page = await context.newPage();8 ];9 console.table(table);10 await browser.close();11})();12│ (index) │ Values │
Using AI Code Generation
1const { Console } = require('console');2const { ConsoleMessage } = require('playwright-core/lib/server/chromium/crConsole');3const { ConsoleMessageLocation } = require('playwright-core/lib/server/chromium/crTypes');4const { ConsoleMessageText } = require('playwright-core/lib/server/chromium/crTypes');5const { ConsoleMessageArgs } = require('playwright-core/lib/server/chromium/crTypes');6const { ConsoleMessageSeverity } = require('playwright-core/lib/server/chromium/crTypes');7const { ConsoleMessageSource } = require('playwright-core/lib/server/chromium/crTypes');8const { ConsoleMessageTimestamp } = require('playwright-core/lib/server/chromium/crTypes');9const { ConsoleMessageUrl } = require('playwright-core/lib/server/chromium/crTypes');10const { ConsoleMessage } = require('playwright-core/lib/server/chromium/crTypes');
Using AI Code Generation
1const { test, expect } = require('@playwright/test');2test('nsoleTable', async ({ page }) => {3 await page.evaluat(() => {4 console.table({ a: 1, b: 'foo' });5 });6 const messages = await page.context().internalConsole().getMessages();7 expect(messages[0].text()).toBe('a\tb8');9});
Using AI Code Generation
1const { test, expect } = require('@playwright/test');2test('consoleTable', async ({ page }) => {3 await page.evaluate(() => {4 console.table({ a: 1, b: 'foo' });5 });6 const messages = await page.context().internalConsole().getMessages();7 expect(messages[0].text()).toBe('a\tb8');9});
Using AI Code Generation
1const { test, expect } = require("@playwright/test");2test.describe("Console Table", () => {3 test("Console Table", async ({ page }) => {4 await page.evaluate(() => {5 console.table([6 {7 },8 {9 },10 ]);11 });12 });13});14const { test, expect } = require("@playwright/test");15test.describe("Console Table", () => {16 test("Console Table", async ({ page }) => {17 await page.evaluate(() => {18 console.table([19 {20 },21 {22 },23 ]);24 });25 });26});27const { test, expect } = require("@playwright/test");28test.describe("Console Table", () => {29 test("Console Table", async ({ page }) => {30 await page.evaluate(() => {31 console.table([32 {33 },34 {35 },36 ]);37 });38 });39});40const { test, expect } = require("@playwright/test");41test.describe("Console Table", () => {42 test("Console Table", async ({ page }) => {43 await page.evaluate(() => {44 console.table([45 {46 },47 {48 },49 ]);50 });51 });52});53const { test, expect } = require("@playwright/test");54test.describe("Console Table", () => {55 test("Console Table", async ({ page }) => {56const { ConsoleMessageLocation } = require('playwright-core/lib/server/chromium/crTypes');57const { ConsoleMessageText } = require('playwright-core/lib/server/chromium/crTypes');58const { ConsoleMessageArgs } = require('playwright-core/lib/server/chromium/crTypes');59const { ConsoleMessageSeverity } = require('playwright-core/lib/server/chromium/crTypes');60const { ConsoleMessageSource } = require('playwright-core/lib/server/chromium/crTypes');61const { ConsoleMessageTimestamp } = require('playwright-core/lib/server/chromium/crTypes');62const { ConsoleMessageUrl } = require('playwright-core/lib/server/chromium/crTypes');63const { ConsoleMessage } = require('playwright-core/lib/server/chromium/crTypes');64const { ConsoleMessageLocation } = require('playwright-core/lib/server/chromium/crTypes');65const { ConsoleMessageText } = require('playwright-core/lib/server/chromium/crTypes');66const { ConsoleMessageArgs } = require('playwright-core/lib/server/chromium/crTypes');67const { ConsoleMessageSeverity } = require('playwright-core/lib/server/chromium/crTypes');68const { ConsoleMessageSource } = require('playwright-core/lib/server/chromium/crTypes');69const { ConsoleMessageTimestamp } = require('playwright-core/lib/server/chromium/crTypes');70const { ConsoleMessageUrl } = require('playwright-core/lib/server/chromium/crTypes');71const { ConsoleMessage } = require('playwright-core
Using AI Code Generation
1const { test, expect } = require("@playwright/test");2test.describe("Console Table", () => {3 test("Console Table", async ({ page }) => {4 await page.evaluate(() => {5 console.table([6 {7 },8 {9 },10 ]);11 });12 });13});14const { test, expect } = require("@playwright/test");15test.describe("Console Table", () => {16 test("Console Table", async ({ page }) => {17 await page.evaluate(() => {18 console.table([19 {20 },21 {22 },23 ]);24 });25 });26});27const { test, expect } = require("@playwright/test");28test.describe("Console Table", () => {29 test("Console Table", async ({ page }) => {30 await page.evaluate(() => {31 console.table([32 {33 },34 {35 },36 ]);37 });38 });39});40const { test, expect } = require("@playwright/test");41test.describe("Console Table", () => {42 test("Console Table", async ({ page }) => {43 await page.evaluate(() => {44 console.table([45 {46 },47 {48 },49 ]);50 });51 });52});53const { test, expect } = require("@playwright/test");54test.describe("Console Table", () => {55 test("Console Table", async ({ page }) => {
Using AI Code Generation
1const { ConsoleMessage } = require('playwright');2ConsoleMessage.prototype.consoleTable = function (data) {3 return this._channel.send('consoleTable', {4 });5};6test('consoleTable', async ({ page }) => {7 await page.evaluate(() => {8 console.table([9 { name: 'John', age: 15 },10 { name: 'Jane', age: 20 }11 ]);12 });13});14const { ConsoleMessage } = require('playwright');15ConsoleMessage.prototype.consoleTable = function (data) {16 return this._channel.send('consoleTable', {17 });18};19test('consoleTable', async ({ page }) => {20 await page.evaluate(() => {21 console.table([22 { name: 'John', age: 15 },23 { name: 'Jane', age: 20 }24 ]);25 });26});
Using AI Code Generation
1const { Console } = require("playwright");2const console = new Console(process.stdout, process.stderr);3console.table([4 { foo: 1, bar: 'A' },5 { foo: 2, bar: 'B' },6]);7import { Console } from "playwright";8const console = new Console(process.stdout, process.stderr);9console.table([10 { foo: 1, bar: 'A' },11 { foo: 2, bar: 'B' },12]);13from playwright.console import Console14console = Console()15console.table([16 { foo: 1, bar: 'A' },17 { foo: 2, bar: 'B' },18# │ (index) │ foo │ bar │
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!!