How to use evaluateExpression method in Playwright Internal

Best JavaScript code snippet using playwright-internal

Parser.js

Source:Parser.js Github

copy

Full Screen

...38 var left;39 var leftAsBool;40 var right;41 if(expr.operator === "&&") {42 left = this.evaluateExpression(expr.left);43 leftAsBool = left && left.asBool();44 if(leftAsBool === false) return left.setRange(expr.range);45 if(leftAsBool !== true) return;46 right = this.evaluateExpression(expr.right);47 return right.setRange(expr.range);48 } else if(expr.operator === "||") {49 left = this.evaluateExpression(expr.left);50 leftAsBool = left && left.asBool();51 if(leftAsBool === true) return left.setRange(expr.range);52 if(leftAsBool !== false) return;53 right = this.evaluateExpression(expr.right);54 return right.setRange(expr.range);55 }56 });57 this.plugin("evaluate BinaryExpression", function(expr) {58 var left;59 var right;60 var res;61 if(expr.operator === "+") {62 left = this.evaluateExpression(expr.left);63 right = this.evaluateExpression(expr.right);64 if(!left || !right) return;65 res = new BasicEvaluatedExpression();66 if(left.isString()) {67 if(right.isString()) {68 res.setString(left.string + right.string);69 } else if(right.isNumber()) {70 res.setString(left.string + right.number);71 } else if(right.isWrapped() && right.prefix && right.prefix.isString()) {72 res.setWrapped(73 new BasicEvaluatedExpression()74 .setString(left.string + right.prefix.string)75 .setRange(joinRanges(left.range, right.prefix.range)),76 right.postfix);77 } else {78 res.setWrapped(left, null);79 }80 } else if(left.isNumber()) {81 if(right.isString()) {82 res.setString(left.number + right.string);83 } else if(right.isNumber()) {84 res.setNumber(left.number + right.number);85 }86 } else if(left.isWrapped()) {87 if(left.postfix && left.postfix.isString() && right.isString()) {88 res.setWrapped(left.prefix,89 new BasicEvaluatedExpression()90 .setString(left.postfix.string + right.string)91 .setRange(joinRanges(left.postfix.range, right.range))92 );93 } else if(left.postfix && left.postfix.isString() && right.isNumber()) {94 res.setWrapped(left.prefix,95 new BasicEvaluatedExpression()96 .setString(left.postfix.string + right.number)97 .setRange(joinRanges(left.postfix.range, right.range))98 );99 } else if(right.isString()) {100 res.setWrapped(left.prefix, right);101 } else if(right.isNumber()) {102 res.setWrapped(left.prefix,103 new BasicEvaluatedExpression()104 .setString(right.number + "")105 .setRange(right.range));106 } else {107 res.setWrapped(left.prefix, new BasicEvaluatedExpression());108 }109 } else {110 if(right.isString()) {111 res.setWrapped(null, right);112 }113 }114 res.setRange(expr.range);115 return res;116 } else if(expr.operator === "-") {117 left = this.evaluateExpression(expr.left);118 right = this.evaluateExpression(expr.right);119 if(!left || !right) return;120 if(!left.isNumber() || !right.isNumber()) return;121 res = new BasicEvaluatedExpression();122 res.setNumber(left.number - right.number);123 res.setRange(expr.range);124 return res;125 } else if(expr.operator === "*") {126 left = this.evaluateExpression(expr.left);127 right = this.evaluateExpression(expr.right);128 if(!left || !right) return;129 if(!left.isNumber() || !right.isNumber()) return;130 res = new BasicEvaluatedExpression();131 res.setNumber(left.number * right.number);132 res.setRange(expr.range);133 return res;134 } else if(expr.operator === "/") {135 left = this.evaluateExpression(expr.left);136 right = this.evaluateExpression(expr.right);137 if(!left || !right) return;138 if(!left.isNumber() || !right.isNumber()) return;139 res = new BasicEvaluatedExpression();140 res.setNumber(left.number / right.number);141 res.setRange(expr.range);142 return res;143 } else if(expr.operator === "==" || expr.operator === "===") {144 left = this.evaluateExpression(expr.left);145 right = this.evaluateExpression(expr.right);146 if(!left || !right) return;147 res = new BasicEvaluatedExpression();148 res.setRange(expr.range);149 if(left.isString() && right.isString()) {150 return res.setBoolean(left.string === right.string);151 } else if(left.isNumber() && right.isNumber()) {152 return res.setBoolean(left.number === right.number);153 } else if(left.isBoolean() && right.isBoolean()) {154 return res.setBoolean(left.bool === right.bool);155 }156 } else if(expr.operator === "!=" || expr.operator === "!==") {157 left = this.evaluateExpression(expr.left);158 right = this.evaluateExpression(expr.right);159 if(!left || !right) return;160 res = new BasicEvaluatedExpression();161 res.setRange(expr.range);162 if(left.isString() && right.isString()) {163 return res.setBoolean(left.string !== right.string);164 } else if(left.isNumber() && right.isNumber()) {165 return res.setBoolean(left.number !== right.number);166 } else if(left.isBoolean() && right.isBoolean()) {167 return res.setBoolean(left.bool !== right.bool);168 }169 }170 });171 this.plugin("evaluate UnaryExpression", function(expr) {172 if(expr.operator === "typeof") {173 var res;174 if(expr.argument.type === "Identifier") {175 var name = this.scope.renames["$" + expr.argument.name] || expr.argument.name;176 if(this.scope.definitions.indexOf(name) === -1) {177 res = this.applyPluginsBailResult1("evaluate typeof " + name, expr);178 if(res !== undefined) return res;179 }180 }181 if(expr.argument.type === "MemberExpression") {182 var expression = expr.argument;183 var exprName = [];184 while(expression.type === "MemberExpression" && !expression.computed) {185 exprName.unshift(this.scope.renames["$" + expression.property.name] || expression.property.name);186 expression = expression.object;187 }188 if(expression.type === "Identifier") {189 exprName.unshift(this.scope.renames["$" + expression.name] || expression.name);190 if(this.scope.definitions.indexOf(name) === -1) {191 exprName = exprName.join(".");192 res = this.applyPluginsBailResult1("evaluate typeof " + exprName, expr);193 if(res !== undefined) return res;194 }195 }196 }197 if(expr.argument.type === "FunctionExpression") {198 return new BasicEvaluatedExpression().setString("function").setRange(expr.range);199 }200 var arg = this.evaluateExpression(expr.argument);201 if(arg.isString() || arg.isWrapped()) return new BasicEvaluatedExpression().setString("string").setRange(expr.range);202 else if(arg.isNumber()) return new BasicEvaluatedExpression().setString("number").setRange(expr.range);203 else if(arg.isBoolean()) return new BasicEvaluatedExpression().setString("boolean").setRange(expr.range);204 else if(arg.isArray() || arg.isConstArray() || arg.isRegExp()) return new BasicEvaluatedExpression().setString("object").setRange(expr.range);205 } else if(expr.operator === "!") {206 var argument = this.evaluateExpression(expr.argument);207 if(!argument) return;208 if(argument.isBoolean()) {209 return new BasicEvaluatedExpression().setBoolean(!argument.bool).setRange(expr.range);210 } else if(argument.isString()) {211 return new BasicEvaluatedExpression().setBoolean(!argument.string).setRange(expr.range);212 } else if(argument.isNumber()) {213 return new BasicEvaluatedExpression().setBoolean(!argument.number).setRange(expr.range);214 }215 }216 });217 this.plugin("evaluate typeof undefined", function(expr) {218 return new BasicEvaluatedExpression().setString("undefined").setRange(expr.range);219 });220 this.plugin("evaluate Identifier", function(expr) {221 var name = this.scope.renames["$" + expr.name] || expr.name;222 if(this.scope.definitions.indexOf(expr.name) === -1) {223 var result = this.applyPluginsBailResult1("evaluate Identifier " + name, expr);224 if(result) return result;225 return new BasicEvaluatedExpression().setIdentifier(name).setRange(expr.range);226 } else {227 return this.applyPluginsBailResult1("evaluate defined Identifier " + name, expr);228 }229 });230 this.plugin("evaluate MemberExpression", function(expression) {231 var expr = expression;232 var exprName = [];233 while(expr.type === "MemberExpression" &&234 expr.property.type === (expr.computed ? "Literal" : "Identifier")235 ) {236 exprName.unshift(expr.property.name || expr.property.value);237 expr = expr.object;238 }239 if(expr.type === "Identifier") {240 var name = this.scope.renames["$" + expr.name] || expr.name;241 if(this.scope.definitions.indexOf(name) === -1) {242 exprName.unshift(name);243 exprName = exprName.join(".");244 if(this.scope.definitions.indexOf(expr.name) === -1) {245 var result = this.applyPluginsBailResult1("evaluate Identifier " + exprName, expression);246 if(result) return result;247 return new BasicEvaluatedExpression().setIdentifier(exprName).setRange(expression.range);248 } else {249 return this.applyPluginsBailResult1("evaluate defined Identifier " + exprName, expression);250 }251 }252 }253 });254 this.plugin("evaluate CallExpression", function(expr) {255 if(expr.callee.type !== "MemberExpression") return;256 if(expr.callee.property.type !== (expr.callee.computed ? "Literal" : "Identifier")) return;257 var param = this.evaluateExpression(expr.callee.object);258 if(!param) return;259 var property = expr.callee.property.name || expr.callee.property.value;260 return this.applyPluginsBailResult("evaluate CallExpression ." + property, expr, param);261 });262 this.plugin("evaluate CallExpression .replace", function(expr, param) {263 if(!param.isString()) return;264 if(expr.arguments.length !== 2) return;265 var arg1 = this.evaluateExpression(expr.arguments[0]);266 var arg2 = this.evaluateExpression(expr.arguments[1]);267 if(!arg1.isString() && !arg1.isRegExp()) return;268 arg1 = arg1.regExp || arg1.string;269 if(!arg2.isString()) return;270 arg2 = arg2.string;271 return new BasicEvaluatedExpression().setString(param.string.replace(arg1, arg2)).setRange(expr.range);272 });273 ["substr", "substring"].forEach(function(fn) {274 this.plugin("evaluate CallExpression ." + fn, function(expr, param) {275 if(!param.isString()) return;276 var arg1;277 var result, str = param.string;278 switch(expr.arguments.length) {279 case 1:280 arg1 = this.evaluateExpression(expr.arguments[0]);281 if(!arg1.isNumber()) return;282 result = str[fn](arg1.number);283 break;284 case 2:285 arg1 = this.evaluateExpression(expr.arguments[0]);286 var arg2 = this.evaluateExpression(expr.arguments[1]);287 if(!arg1.isNumber()) return;288 if(!arg2.isNumber()) return;289 result = str[fn](arg1.number, arg2.number);290 break;291 default:292 return;293 }294 return new BasicEvaluatedExpression().setString(result).setRange(expr.range);295 });296 /**297 * @param {string} kind "cooked" | "raw"298 * @param {any[]} quasis quasis299 * @param {any[]} expressions expressions300 * @return {BasicEvaluatedExpression[]} Simplified template301 */302 function getSimplifiedTemplateResult(kind, quasis, expressions) {303 var i = 0;304 var parts = [];305 for(i = 0; i < quasis.length; i++) {306 parts.push(new BasicEvaluatedExpression().setString(quasis[i].value[kind]).setRange(quasis[i].range));307 if(i > 0) {308 var prevExpr = parts[parts.length - 2],309 lastExpr = parts[parts.length - 1];310 var expr = this.evaluateExpression(expressions[i - 1]);311 if(!(expr.isString() || expr.isNumber())) continue;312 prevExpr.setString(prevExpr.string + (expr.isString() ? expr.string : expr.number) + lastExpr.string);313 prevExpr.setRange([prevExpr.range[0], lastExpr.range[1]]);314 parts.pop();315 }316 }317 return parts;318 }319 this.plugin("evaluate TemplateLiteral", function(node) {320 var parts = getSimplifiedTemplateResult.call(this, "cooked", node.quasis, node.expressions);321 if(parts.length === 1) {322 return parts[0].setRange(node.range);323 }324 return new BasicEvaluatedExpression().setTemplateString(parts).setRange(node.range);325 });326 this.plugin("evaluate TaggedTemplateExpression", function(node) {327 if(this.evaluateExpression(node.tag).identifier !== "String.raw") return;328 var parts = getSimplifiedTemplateResult.call(this, "raw", node.quasi.quasis, node.quasi.expressions);329 return new BasicEvaluatedExpression().setTemplateString(parts).setRange(node.range);330 });331 }, this);332 this.plugin("evaluate CallExpression .split", function(expr, param) {333 if(!param.isString()) return;334 if(expr.arguments.length !== 1) return;335 var result;336 var arg = this.evaluateExpression(expr.arguments[0]);337 if(arg.isString()) {338 result = param.string.split(arg.string);339 } else if(arg.isRegExp()) {340 result = param.string.split(arg.regExp);341 } else return;342 return new BasicEvaluatedExpression().setArray(result).setRange(expr.range);343 });344 this.plugin("evaluate ConditionalExpression", function(expr) {345 var condition = this.evaluateExpression(expr.test);346 var conditionValue = condition.asBool();347 var res;348 if(conditionValue === undefined) {349 var consequent = this.evaluateExpression(expr.consequent);350 var alternate = this.evaluateExpression(expr.alternate);351 if(!consequent || !alternate) return;352 res = new BasicEvaluatedExpression();353 if(consequent.isConditional())354 res.setOptions(consequent.options);355 else356 res.setOptions([consequent]);357 if(alternate.isConditional())358 res.addOptions(alternate.options);359 else360 res.addOptions([alternate]);361 } else {362 res = this.evaluateExpression(conditionValue ? expr.consequent : expr.alternate);363 }364 res.setRange(expr.range);365 return res;366 });367 this.plugin("evaluate ArrayExpression", function(expr) {368 var items = expr.elements.map(function(element) {369 return element !== null && this.evaluateExpression(element);370 }, this);371 if(!items.every(Boolean)) return;372 return new BasicEvaluatedExpression().setItems(items).setRange(expr.range);373 });374};375Parser.prototype.getRenameIdentifier = function getRenameIdentifier(expr) {376 var result = this.evaluateExpression(expr);377 if(!result) return;378 if(result.isIdentifier()) return result.identifier;379 return;380};381Parser.prototype.walkClass = function walkClass(classy) {382 if(classy.superClass)383 this.walkExpression(classy.superClass);384 if(classy.body && classy.body.type === "ClassBody") {385 classy.body.body.forEach(function(methodDefinition) {386 if(methodDefinition.type === "MethodDefinition")387 this.walkMethodDefinition(methodDefinition);388 }, this);389 }390};391Parser.prototype.walkMethodDefinition = function walkMethodDefinition(methodDefinition) {392 if(methodDefinition.computed && methodDefinition.key)393 this.walkExpression(methodDefinition.key);394 if(methodDefinition.value)395 this.walkExpression(methodDefinition.value);396};397Parser.prototype.walkStatements = function walkStatements(statements) {398 statements.forEach(function(statement) {399 if(this.isHoistedStatement(statement))400 this.walkStatement(statement);401 }, this);402 statements.forEach(function(statement) {403 if(!this.isHoistedStatement(statement))404 this.walkStatement(statement);405 }, this);406};407Parser.prototype.isHoistedStatement = function isHoistedStatement(statement) {408 switch(statement.type) {409 case "ImportDeclaration":410 case "ExportAllDeclaration":411 case "ExportNamedDeclaration":412 return true;413 }414 return false;415};416Parser.prototype.walkStatement = function walkStatement(statement) {417 if(this.applyPluginsBailResult1("statement", statement) !== undefined) return;418 if(this["walk" + statement.type])419 this["walk" + statement.type](statement);420};421// Real Statements422Parser.prototype.walkBlockStatement = function walkBlockStatement(statement) {423 this.walkStatements(statement.body);424};425Parser.prototype.walkExpressionStatement = function walkExpressionStatement(statement) {426 this.walkExpression(statement.expression);427};428Parser.prototype.walkIfStatement = function walkIfStatement(statement) {429 var result = this.applyPluginsBailResult1("statement if", statement);430 if(result === undefined) {431 this.walkExpression(statement.test);432 this.walkStatement(statement.consequent);433 if(statement.alternate)434 this.walkStatement(statement.alternate);435 } else {436 if(result)437 this.walkStatement(statement.consequent);438 else if(statement.alternate)439 this.walkStatement(statement.alternate);440 }441};442Parser.prototype.walkLabeledStatement = function walkLabeledStatement(statement) {443 var result = this.applyPluginsBailResult1("label " + statement.label.name, statement);444 if(result !== true)445 this.walkStatement(statement.body);446};447Parser.prototype.walkWithStatement = function walkWithStatement(statement) {448 this.walkExpression(statement.object);449 this.walkStatement(statement.body);450};451Parser.prototype.walkSwitchStatement = function walkSwitchStatement(statement) {452 this.walkExpression(statement.discriminant);453 this.walkSwitchCases(statement.cases);454};455Parser.prototype.walkReturnStatement =456 Parser.prototype.walkThrowStatement = function walkArgumentStatement(statement) {457 if(statement.argument)458 this.walkExpression(statement.argument);459 };460Parser.prototype.walkTryStatement = function walkTryStatement(statement) {461 if(this.scope.inTry) {462 this.walkStatement(statement.block);463 } else {464 this.scope.inTry = true;465 this.walkStatement(statement.block);466 this.scope.inTry = false;467 }468 if(statement.handler)469 this.walkCatchClause(statement.handler);470 if(statement.finalizer)471 this.walkStatement(statement.finalizer);472};473Parser.prototype.walkWhileStatement =474 Parser.prototype.walkDoWhileStatement = function walkLoopStatement(statement) {475 this.walkExpression(statement.test);476 this.walkStatement(statement.body);477 };478Parser.prototype.walkForStatement = function walkForStatement(statement) {479 if(statement.init) {480 if(statement.init.type === "VariableDeclaration")481 this.walkStatement(statement.init);482 else483 this.walkExpression(statement.init);484 }485 if(statement.test)486 this.walkExpression(statement.test);487 if(statement.update)488 this.walkExpression(statement.update);489 this.walkStatement(statement.body);490};491Parser.prototype.walkForInStatement = function walkForInStatement(statement) {492 if(statement.left.type === "VariableDeclaration")493 this.walkStatement(statement.left);494 else495 this.walkExpression(statement.left);496 this.walkExpression(statement.right);497 this.walkStatement(statement.body);498};499Parser.prototype.walkForOfStatement = function walkForOfStatement(statement) {500 if(statement.left.type === "VariableDeclaration")501 this.walkStatement(statement.left);502 else503 this.walkExpression(statement.left);504 this.walkExpression(statement.right);505 this.walkStatement(statement.body);506};507// Declarations508Parser.prototype.walkFunctionDeclaration = function walkFunctionDeclaration(statement) {509 this.scope.renames["$" + statement.id.name] = undefined;510 this.scope.definitions.push(statement.id.name);511 this.inScope(statement.params, function() {512 if(statement.body.type === "BlockStatement")513 this.walkStatement(statement.body);514 else515 this.walkExpression(statement.body);516 }.bind(this));517};518Parser.prototype.walkImportDeclaration = function walkImportDeclaration(statement) {519 var source = statement.source.value;520 this.applyPluginsBailResult("import", statement, source);521 statement.specifiers.forEach(function(specifier) {522 var name = specifier.local.name;523 this.scope.renames["$" + name] = undefined;524 this.scope.definitions.push(name);525 switch(specifier.type) {526 case "ImportDefaultSpecifier":527 this.applyPluginsBailResult("import specifier", statement, source, "default", name);528 break;529 case "ImportSpecifier":530 this.applyPluginsBailResult("import specifier", statement, source, specifier.imported.name, name);531 break;532 case "ImportNamespaceSpecifier":533 this.applyPluginsBailResult("import specifier", statement, source, null, name);534 break;535 }536 }, this);537};538Parser.prototype.walkExportNamedDeclaration = function walkExportNamedDeclaration(statement) {539 if(statement.source) {540 var source = statement.source.value;541 this.applyPluginsBailResult("export import", statement, source);542 } else {543 this.applyPluginsBailResult1("export", statement);544 }545 if(statement.declaration) {546 if(/Expression$/.test(statement.declaration.type)) {547 throw new Error("Doesn't occur?");548 } else {549 if(!this.applyPluginsBailResult("export declaration", statement, statement.declaration)) {550 var pos = this.scope.definitions.length;551 this.walkStatement(statement.declaration);552 var newDefs = this.scope.definitions.slice(pos);553 newDefs.reverse().forEach(function(def, idx) {554 this.applyPluginsBailResult("export specifier", statement, def, def, idx);555 }, this);556 }557 }558 }559 if(statement.specifiers) {560 statement.specifiers.forEach(function(specifier, idx) {561 switch(specifier.type) {562 case "ExportSpecifier":563 var name = specifier.exported.name;564 if(source)565 this.applyPluginsBailResult("export import specifier", statement, source, specifier.local.name, name, idx);566 else567 this.applyPluginsBailResult("export specifier", statement, specifier.local.name, name, idx);568 break;569 }570 }, this);571 }572};573Parser.prototype.walkExportDefaultDeclaration = function walkExportDefaultDeclaration(statement) {574 this.applyPluginsBailResult1("export", statement);575 if(/Declaration$/.test(statement.declaration.type)) {576 if(!this.applyPluginsBailResult("export declaration", statement, statement.declaration)) {577 var pos = this.scope.definitions.length;578 this.walkStatement(statement.declaration);579 var newDefs = this.scope.definitions.slice(pos);580 newDefs.forEach(function(def) {581 this.applyPluginsBailResult("export specifier", statement, def, "default");582 }, this);583 }584 } else {585 this.walkExpression(statement.declaration);586 if(!this.applyPluginsBailResult("export expression", statement, statement.declaration)) {587 this.applyPluginsBailResult("export specifier", statement, statement.declaration, "default");588 }589 }590};591Parser.prototype.walkExportAllDeclaration = function walkExportAllDeclaration(statement) {592 var source = statement.source.value;593 this.applyPluginsBailResult("export import", statement, source);594 this.applyPluginsBailResult("export import specifier", statement, source, null, null, 0);595};596Parser.prototype.walkVariableDeclaration = function walkVariableDeclaration(statement) {597 if(statement.declarations)598 this.walkVariableDeclarators(statement.declarations);599};600Parser.prototype.walkClassDeclaration = function walkClassDeclaration(statement) {601 this.scope.renames["$" + statement.id.name] = undefined;602 this.scope.definitions.push(statement.id.name);603 this.walkClass(statement);604};605Parser.prototype.walkSwitchCases = function walkSwitchCases(switchCases) {606 switchCases.forEach(function(switchCase) {607 if(switchCase.test)608 this.walkExpression(switchCase.test);609 this.walkStatements(switchCase.consequent);610 }, this);611};612Parser.prototype.walkCatchClause = function walkCatchClause(catchClause) {613 if(catchClause.guard)614 this.walkExpression(catchClause.guard);615 this.inScope([catchClause.param], function() {616 this.walkStatement(catchClause.body);617 }.bind(this));618};619Parser.prototype.walkVariableDeclarators = function walkVariableDeclarators(declarators) {620 var _this = this;621 declarators.forEach(function(declarator) {622 switch(declarator.type) {623 case "VariableDeclarator":624 var renameIdentifier = declarator.init && _this.getRenameIdentifier(declarator.init);625 if(renameIdentifier && declarator.id.type === "Identifier" && _this.applyPluginsBailResult1("can-rename " + renameIdentifier, declarator.init)) {626 // renaming with "var a = b;"627 if(!_this.applyPluginsBailResult1("rename " + renameIdentifier, declarator.init)) {628 _this.scope.renames["$" + declarator.id.name] = _this.scope.renames["$" + renameIdentifier] || renameIdentifier;629 var idx = _this.scope.definitions.indexOf(declarator.id.name);630 if(idx >= 0) _this.scope.definitions.splice(idx, 1);631 }632 } else {633 _this.enterPattern(declarator.id, function(name, decl) {634 if(!_this.applyPluginsBailResult1("var " + name, decl)) {635 _this.scope.renames["$" + name] = undefined;636 _this.scope.definitions.push(name);637 }638 });639 if(declarator.init)640 _this.walkExpression(declarator.init);641 }642 break;643 }644 });645};646Parser.prototype.walkExpressions = function walkExpressions(expressions) {647 expressions.forEach(function(expression) {648 if(expression)649 this.walkExpression(expression);650 }, this);651};652Parser.prototype.walkExpression = function walkExpression(expression) {653 if(this["walk" + expression.type])654 return this["walk" + expression.type](expression);655};656Parser.prototype.walkAwaitExpression = function walkAwaitExpression(expression) {657 var argument = expression.argument;658 if(this["walk" + argument.type])659 return this["walk" + argument.type](argument);660};661Parser.prototype.walkArrayExpression = function walkArrayExpression(expression) {662 if(expression.elements)663 this.walkExpressions(expression.elements);664};665Parser.prototype.walkSpreadElement = function walkSpreadElement(expression) {666 if(expression.argument)667 this.walkExpression(expression.argument);668};669Parser.prototype.walkObjectExpression = function walkObjectExpression(expression) {670 expression.properties.forEach(function(prop) {671 if(prop.computed)672 this.walkExpression(prop.key);673 if(prop.shorthand)674 this.scope.inShorthand = true;675 this.walkExpression(prop.value);676 if(prop.shorthand)677 this.scope.inShorthand = false;678 }, this);679};680Parser.prototype.walkFunctionExpression = function walkFunctionExpression(expression) {681 this.inScope(expression.params, function() {682 if(expression.body.type === "BlockStatement")683 this.walkStatement(expression.body);684 else685 this.walkExpression(expression.body);686 }.bind(this));687};688Parser.prototype.walkArrowFunctionExpression = function walkArrowFunctionExpression(expression) {689 this.inScope(expression.params, function() {690 if(expression.body.type === "BlockStatement")691 this.walkStatement(expression.body);692 else693 this.walkExpression(expression.body);694 }.bind(this));695};696Parser.prototype.walkSequenceExpression = function walkSequenceExpression(expression) {697 if(expression.expressions)698 this.walkExpressions(expression.expressions);699};700Parser.prototype.walkUpdateExpression = function walkUpdateExpression(expression) {701 this.walkExpression(expression.argument);702};703Parser.prototype.walkUnaryExpression = function walkUnaryExpression(expression) {704 if(expression.operator === "typeof") {705 var expr = expression.argument;706 var exprName = [];707 while(expr.type === "MemberExpression" &&708 expr.property.type === (expr.computed ? "Literal" : "Identifier")709 ) {710 exprName.unshift(expr.property.name || expr.property.value);711 expr = expr.object;712 }713 if(expr.type === "Identifier" && this.scope.definitions.indexOf(expr.name) === -1) {714 exprName.unshift(this.scope.renames["$" + expr.name] || expr.name);715 exprName = exprName.join(".");716 var result = this.applyPluginsBailResult1("typeof " + exprName, expression);717 if(result === true)718 return;719 }720 }721 this.walkExpression(expression.argument);722};723Parser.prototype.walkBinaryExpression =724 Parser.prototype.walkLogicalExpression = function walkLeftRightExpression(expression) {725 this.walkExpression(expression.left);726 this.walkExpression(expression.right);727 };728Parser.prototype.walkAssignmentExpression = function walkAssignmentExpression(expression) {729 var renameIdentifier = this.getRenameIdentifier(expression.right);730 if(expression.left.type === "Identifier" && renameIdentifier && this.applyPluginsBailResult1("can-rename " + renameIdentifier, expression.right)) {731 // renaming "a = b;"732 if(!this.applyPluginsBailResult1("rename " + renameIdentifier, expression.right)) {733 this.scope.renames["$" + expression.left.name] = renameIdentifier;734 var idx = this.scope.definitions.indexOf(expression.left.name);735 if(idx >= 0) this.scope.definitions.splice(idx, 1);736 }737 } else if(expression.left.type === "Identifier") {738 if(!this.applyPluginsBailResult1("assigned " + expression.left.name, expression)) {739 this.walkExpression(expression.right);740 }741 this.scope.renames["$" + expression.left.name] = undefined;742 if(!this.applyPluginsBailResult1("assign " + expression.left.name, expression)) {743 this.walkExpression(expression.left);744 }745 } else {746 this.walkExpression(expression.right);747 this.scope.renames["$" + expression.left.name] = undefined;748 this.walkExpression(expression.left);749 }750};751Parser.prototype.walkConditionalExpression = function walkConditionalExpression(expression) {752 var result = this.applyPluginsBailResult1("expression ?:", expression);753 if(result === undefined) {754 this.walkExpression(expression.test);755 this.walkExpression(expression.consequent);756 if(expression.alternate)757 this.walkExpression(expression.alternate);758 } else {759 if(result)760 this.walkExpression(expression.consequent);761 else if(expression.alternate)762 this.walkExpression(expression.alternate);763 }764};765Parser.prototype.walkNewExpression = function walkNewExpression(expression) {766 this.walkExpression(expression.callee);767 if(expression.arguments)768 this.walkExpressions(expression.arguments);769};770Parser.prototype.walkYieldExpression = function walkYieldExpression(expression) {771 if(expression.argument)772 this.walkExpression(expression.argument);773};774Parser.prototype.walkTemplateLiteral = function walkTemplateLiteral(expression) {775 if(expression.expressions)776 this.walkExpressions(expression.expressions);777};778Parser.prototype.walkTaggedTemplateExpression = function walkTaggedTemplateExpression(expression) {779 if(expression.tag)780 this.walkExpression(expression.tag);781 if(expression.quasi && expression.quasi.expressions)782 this.walkExpressions(expression.quasi.expressions);783};784Parser.prototype.walkClassExpression = function walkClassExpression(expression) {785 this.walkClass(expression);786};787Parser.prototype.walkCallExpression = function walkCallExpression(expression) {788 var result;789 function walkIIFE(functionExpression, args) {790 var params = functionExpression.params;791 args = args.map(function(arg) {792 var renameIdentifier = this.getRenameIdentifier(arg);793 if(renameIdentifier && this.applyPluginsBailResult1("can-rename " + renameIdentifier, arg)) {794 if(!this.applyPluginsBailResult1("rename " + renameIdentifier, arg))795 return renameIdentifier;796 }797 this.walkExpression(arg);798 }, this);799 this.inScope(params.filter(function(identifier, idx) {800 return !args[idx];801 }), function() {802 args.forEach(function(arg, idx) {803 if(!arg) return;804 if(!params[idx] || params[idx].type !== "Identifier") return;805 this.scope.renames["$" + params[idx].name] = arg;806 }, this);807 if(functionExpression.body.type === "BlockStatement")808 this.walkStatement(functionExpression.body);809 else810 this.walkExpression(functionExpression.body);811 }.bind(this));812 }813 if(expression.callee.type === "MemberExpression" &&814 expression.callee.object.type === "FunctionExpression" &&815 !expression.callee.computed &&816 (["call", "bind"]).indexOf(expression.callee.property.name) >= 0 &&817 expression.arguments &&818 expression.arguments.length > 1819 ) {820 // (function(...) { }.call/bind(?, ...))821 walkIIFE.call(this, expression.callee.object, expression.arguments.slice(1));822 this.walkExpression(expression.arguments[0]);823 } else if(expression.callee.type === "FunctionExpression" && expression.arguments) {824 // (function(...) { }(...))825 walkIIFE.call(this, expression.callee, expression.arguments);826 } else if(expression.callee.type === "Import") {827 result = this.applyPluginsBailResult1("import-call", expression);828 if(result === true)829 return;830 if(expression.arguments)831 this.walkExpressions(expression.arguments);832 } else {833 var callee = this.evaluateExpression(expression.callee);834 if(callee.isIdentifier()) {835 result = this.applyPluginsBailResult1("call " + callee.identifier, expression);836 if(result === true)837 return;838 }839 if(expression.callee)840 this.walkExpression(expression.callee);841 if(expression.arguments)842 this.walkExpressions(expression.arguments);843 }844};845Parser.prototype.walkMemberExpression = function walkMemberExpression(expression) {846 var expr = expression;847 var exprName = [];848 while(expr.type === "MemberExpression" &&849 expr.property.type === (expr.computed ? "Literal" : "Identifier")850 ) {851 exprName.unshift(expr.property.name || expr.property.value);852 expr = expr.object;853 }854 if(expr.type === "Identifier" && this.scope.definitions.indexOf(expr.name) === -1) {855 exprName.unshift(this.scope.renames["$" + expr.name] || expr.name);856 var result = this.applyPluginsBailResult1("expression " + exprName.join("."), expression);857 if(result === true)858 return;859 exprName[exprName.length - 1] = "*";860 result = this.applyPluginsBailResult1("expression " + exprName.join("."), expression);861 if(result === true)862 return;863 }864 this.walkExpression(expression.object);865 if(expression.computed === true)866 this.walkExpression(expression.property);867};868Parser.prototype.walkIdentifier = function walkIdentifier(expression) {869 if(this.scope.definitions.indexOf(expression.name) === -1) {870 var result = this.applyPluginsBailResult1("expression " + (this.scope.renames["$" + expression.name] || expression.name), expression);871 if(result === true)872 return;873 }874};875Parser.prototype.inScope = function inScope(params, fn) {876 var oldScope = this.scope;877 var _this = this;878 this.scope = {879 inTry: false,880 inShorthand: false,881 definitions: oldScope.definitions.slice(),882 renames: Object.create(oldScope.renames)883 };884 params.forEach(function(param) {885 if(typeof param !== "string") {886 param = _this.enterPattern(param, function(param) {887 _this.scope.renames["$" + param] = undefined;888 _this.scope.definitions.push(param);889 });890 } else {891 _this.scope.renames["$" + param] = undefined;892 _this.scope.definitions.push(param);893 }894 });895 fn();896 _this.scope = oldScope;897};898Parser.prototype.enterPattern = function enterPattern(pattern, onIdent) {899 if(pattern && this["enter" + pattern.type])900 return this["enter" + pattern.type](pattern, onIdent);901};902Parser.prototype.enterIdentifier = function enterIdentifier(pattern, onIdent) {903 onIdent(pattern.name, pattern);904};905Parser.prototype.enterObjectPattern = function enterObjectPattern(pattern, onIdent) {906 pattern.properties.forEach(function(property) {907 this.enterPattern(property.value, onIdent);908 }, this);909};910Parser.prototype.enterArrayPattern = function enterArrayPattern(pattern, onIdent) {911 pattern.elements.forEach(function(pattern) {912 this.enterPattern(pattern, onIdent);913 }, this);914};915Parser.prototype.enterRestElement = function enterRestElement(pattern, onIdent) {916 this.enterPattern(pattern.argument, onIdent);917};918Parser.prototype.enterAssignmentPattern = function enterAssignmentPattern(pattern, onIdent) {919 this.enterPattern(pattern.left, onIdent);920 this.walkExpression(pattern.right);921};922Parser.prototype.evaluateExpression = function evaluateExpression(expression) {923 try {924 var result = this.applyPluginsBailResult1("evaluate " + expression.type, expression);925 if(result !== undefined)926 return result;927 } catch(e) {928 console.warn(e);929 // ignore error930 }931 return new BasicEvaluatedExpression().setRange(expression.range);932};933Parser.prototype.parseString = function parseString(expression) {934 switch(expression.type) {935 case "BinaryExpression":936 if(expression.operator === "+")937 return this.parseString(expression.left) + this.parseString(expression.right);938 break;939 case "Literal":940 return expression.value + "";941 }942 throw new Error(expression.type + " is not supported as parameter for require");943};944Parser.prototype.parseCalculatedString = function parseCalculatedString(expression) {945 switch(expression.type) {946 case "BinaryExpression":947 if(expression.operator === "+") {948 var left = this.parseCalculatedString(expression.left);949 var right = this.parseCalculatedString(expression.right);950 if(left.code) {951 return {952 range: left.range,953 value: left.value,954 code: true955 };956 } else if(right.code) {957 return {958 range: [left.range[0], right.range ? right.range[1] : left.range[1]],959 value: left.value + right.value,960 code: true961 };962 } else {963 return {964 range: [left.range[0], right.range[1]],965 value: left.value + right.value966 };967 }968 }969 break;970 case "ConditionalExpression":971 var consequent = this.parseCalculatedString(expression.consequent);972 var alternate = this.parseCalculatedString(expression.alternate);973 var items = [];974 if(consequent.conditional)975 Array.prototype.push.apply(items, consequent.conditional);976 else if(!consequent.code)977 items.push(consequent);978 else break;979 if(alternate.conditional)980 Array.prototype.push.apply(items, alternate.conditional);981 else if(!alternate.code)982 items.push(alternate);983 else break;984 return {985 value: "",986 code: true,987 conditional: items988 };989 case "Literal":990 return {991 range: expression.range,992 value: expression.value + ""993 };994 }995 return {996 value: "",997 code: true998 };999};1000["parseString", "parseCalculatedString"].forEach(function(fn) {1001 Parser.prototype[fn + "Array"] = function parseXXXArray(expression) {1002 switch(expression.type) {1003 case "ArrayExpression":1004 var arr = [];1005 if(expression.elements)1006 expression.elements.forEach(function(expr) {1007 arr.push(this[fn](expr));1008 }, this);1009 return arr;1010 }1011 return [this[fn](expression)];1012 };1013});1014var POSSIBLE_AST_OPTIONS = [{1015 ranges: true,1016 locations: true,1017 ecmaVersion: 2017,1018 sourceType: "module",1019 plugins: {1020 dynamicImport: true1021 }1022}, {1023 ranges: true,1024 locations: true,1025 ecmaVersion: 2017,1026 sourceType: "script",1027 plugins: {1028 dynamicImport: true1029 }1030}];1031Parser.prototype.parse = function parse(source, initialState) {1032 var ast, comments = [];1033 for(var i = 0; i < POSSIBLE_AST_OPTIONS.length; i++) {1034 if(!ast) {1035 try {1036 comments.length = 0;1037 POSSIBLE_AST_OPTIONS[i].onComment = comments;1038 ast = acorn.parse(source, POSSIBLE_AST_OPTIONS[i]);1039 } catch(e) {1040 // ignore the error1041 }1042 }1043 }1044 if(!ast) {1045 // for the error1046 ast = acorn.parse(source, {1047 ranges: true,1048 locations: true,1049 ecmaVersion: 2017,1050 sourceType: "module",1051 plugins: {1052 dynamicImport: true1053 },1054 onComment: comments1055 });1056 }1057 if(!ast || typeof ast !== "object")1058 throw new Error("Source couldn't be parsed");1059 var oldScope = this.scope;1060 var oldState = this.state;1061 this.scope = {1062 inTry: false,1063 definitions: [],1064 renames: {}1065 };1066 var state = this.state = initialState || {};1067 if(this.applyPluginsBailResult("program", ast, comments) === undefined)1068 this.walkStatements(ast.body);1069 this.scope = oldScope;1070 this.state = oldState;1071 return state;1072};1073Parser.prototype.evaluate = function evaluate(source) {1074 var ast = acorn.parse("(" + source + ")", {1075 ranges: true,1076 locations: true,1077 ecmaVersion: 2017,1078 sourceType: "module",1079 plugins: {1080 dynamicImport: true1081 }1082 });1083 if(!ast || typeof ast !== "object" || ast.type !== "Program")1084 throw new Error("evaluate: Source couldn't be parsed");1085 if(ast.body.length !== 1 || ast.body[0].type !== "ExpressionStatement")1086 throw new Error("evaluate: Source is not a expression");1087 return this.evaluateExpression(ast.body[0].expression);...

Full Screen

Full Screen

function-jim-event-function.js

Source:function-jim-event-function.js Github

copy

Full Screen

...8 "jimPlus": function(parameters, obj) {9 var self = this, value = null, sum=0, i, iLen, parameter;10 if(jimUtil.exists(parameters)) {11 for(i=0, iLen=parameters.length; i<iLen; i+=1) {12 parameter = jimEvent.tryNumberConversion(self.evaluateExpression(parameters[i], obj));13 if(jimEvent.isNumber(parameter)) {14 sum += parameter;15 } else {16 sum = null;17 break;18 }19 }20 value = sum;21 }22 return value;23 },24 "jimMinus": function(parameters, obj) {25 var self = this, value = null, i, iLen, parameter;26 if(jimUtil.exists(parameters)) {27 for(i=0, iLen=parameters.length; i<iLen; i+=1) {28 parameter = jimEvent.tryNumberConversion(self.evaluateExpression(parameters[i], obj));29 if(jimEvent.isNumber(parameter)) {30 value = (jimUtil.exists(value)) ? value - parameter : parameter;31 } else {32 value = null;33 break;34 }35 }36 }37 return value;38 },39 "jimMultiply": function(parameters, obj) {40 var self = this, value = null, i, iLen, parameter;41 if(jimUtil.exists(parameters)) {42 for(i=0, iLen=parameters.length; i<iLen; i+=1) {43 parameter = jimEvent.tryNumberConversion(self.evaluateExpression(parameters[i], obj));44 if(jimEvent.isNumber(parameter)) {45 value = (jimUtil.exists(value)) ? value * parameter : parameter;46 } else {47 value = null;48 break;49 }50 }51 }52 return value;53 },54 "jimDivide": function(parameters, obj) {55 var self = this, value = null, op1, op2;56 if(jimUtil.exists(parameters[0]) && jimUtil.exists(parameters[1])) {57 op1 = jimEvent.tryNumberConversion(self.evaluateExpression(parameters[0], obj));58 op2 = jimEvent.tryNumberConversion(self.evaluateExpression(parameters[1], obj));59 if(jimEvent.isNumber(op1) && jimEvent.isNumber(op2) && op2 !== 0) {60 value = op1 / op2;61 }62 }63 return value;64 },65 "jimMax": function(parameters, obj) {66 var self = this, value = null, max=0, i, iLen, parameter;67 if(jimUtil.exists(parameters)) {68 for(i=0, iLen=parameters.length; i<iLen; i+=1) {69 parameter = jimEvent.tryNumberConversion(self.evaluateExpression(parameters[i], obj));70 if(jimEvent.isNumber(parameter)) {71 max = Math.max(max, parameter);72 } else {73 max = null;74 break;75 }76 }77 value = max;78 }79 return value;80 },81 "jimMin": function(parameters, obj) {82 var self = this, value = null, min = Number.MAX_VALUE, i, iLen, parameter;83 if(jimUtil.exists(parameters)) {84 for(i=0, iLen=parameters.length; i<iLen; i+=1) {85 parameter = jimEvent.tryNumberConversion(self.evaluateExpression(parameters[i], obj));86 if(jimEvent.isNumber(parameter)) {87 min = Math.min(min, parameter);88 } else {89 min = null;90 break;91 }92 }93 value = min;94 }95 return value;96 },97 "jimAvg": function(parameters, obj) {98 var self = this, value = null, sum;99 if(jimUtil.exists(parameters) && parameters.length !== 0) {100 sum = self.jimPlus(parameters, obj);101 if(jimEvent.isNumber(sum)) {102 value = sum / parameters.length;103 }104 }105 return value;106 },107 "jimAbs": function(parameters, obj) {108 var self = this, value = null, op;109 if(jimUtil.exists(parameters[0])) {110 op = jimEvent.tryNumberConversion(self.evaluateExpression(parameters[0], obj));111 if(jimEvent.isNumber(op)) {112 value = Math.abs(op);113 }114 }115 return value;116 },117 "jimRound": function(parameters, obj) {118 var self = this, value, num, dec;119 if(jimUtil.exists(parameters[0]) && jimUtil.exists(parameters[1])) {120 num = jimEvent.tryNumberConversion(self.evaluateExpression(parameters[0], obj));121 dec = jimEvent.tryNumberConversion(self.evaluateExpression(parameters[1], obj));122 if(jimEvent.isNumber(num) && jimEvent.isNumber(dec)) {123 value = (Math.round(num*Math.pow(10,dec))/Math.pow(10,dec)).toFixed(dec);124 }125 }126 return value;127 },128 "jimPercent": function(parameters, obj) {129 var self = this, value = null, op1, op2;130 if(jimUtil.exists(parameters[0]) && jimUtil.exists(parameters[1])) {131 op1 = jimEvent.tryNumberConversion(self.evaluateExpression(parameters[0], obj));132 op2 = jimEvent.tryNumberConversion(self.evaluateExpression(parameters[1], obj));133 if(jimEvent.isNumber(op1) && jimEvent.isNumber(op2)) {134 value = (op1*op2)/100;135 }136 }137 return value;138 },139 "jimSqrt": function(parameters, obj) {140 var self = this, value = null, op;141 if(jimUtil.exists(parameters[0])) {142 op = jimEvent.tryNumberConversion(self.evaluateExpression(parameters[0], obj));143 if(jimEvent.isNumber(op)) {144 value = Math.sqrt(op);145 }146 }147 return value;148 },149 "jimMod": function(parameters, obj) {150 var self = this, value = null, op1, op2;151 if(jimUtil.exists(parameters[0]) && jimUtil.exists(parameters[1])) {152 op1 = jimEvent.tryNumberConversion(self.evaluateExpression(parameters[0], obj));153 op2 = jimEvent.tryNumberConversion(self.evaluateExpression(parameters[1], obj));154 if(jimEvent.isNumber(op1) && jimEvent.isNumber(op2)) {155 value = op1 % op2;156 }157 }158 return value;159 },160 /*************************** END NUMBER FUNCTIONS ******************************/161162 /************************ START COMPARATOR FUNCTIONS ***************************/163 "jimEquals": function(parameters, obj) {164 var self = this, value = null, op1, op2;165 if(jimUtil.exists(parameters[0]) && jimUtil.exists(parameters[1])) {166 op1 = jimEvent.tryNumberConversion(jimEvent.tryBooleanConversion(self.evaluateExpression(parameters[0], obj)));167 op2 = jimEvent.tryNumberConversion(jimEvent.tryBooleanConversion(self.evaluateExpression(parameters[1], obj)));168 value = op1 === op2;169 }170 return value;171 },172 "jimNotEquals": function(parameters, obj) {173 var self = this, value = null, op1, op2;174 if(jimUtil.exists(parameters[0]) && jimUtil.exists(parameters[1])) {175 op1 = jimEvent.tryNumberConversion(jimEvent.tryBooleanConversion(self.evaluateExpression(parameters[0], obj)));176 op2 = jimEvent.tryNumberConversion(jimEvent.tryBooleanConversion(self.evaluateExpression(parameters[1], obj)));177 value = op1 !== op2;178 }179 return value;180 },181 "jimGreater": function(parameters, obj) {182 var self = this, value = null, op1, op2;183 if(jimUtil.exists(parameters[0]) && jimUtil.exists(parameters[1])) {184 op1 = jimEvent.tryNumberConversion(jimEvent.tryDateConversion(self.evaluateExpression(parameters[0], obj)));185 op2 = jimEvent.tryNumberConversion(jimEvent.tryDateConversion(self.evaluateExpression(parameters[1], obj)));186 if(jimEvent.isNumber(op1) && jimEvent.isNumber(op2)) {187 value = op1 > op2;188 }189 }190 return value;191 },192 "jimLess": function(parameters, obj) {193 var self = this, value = null, op1, op2;194 if(jimUtil.exists(parameters[0]) && jimUtil.exists(parameters[1])) {195 op1 = jimEvent.tryNumberConversion(jimEvent.tryDateConversion(self.evaluateExpression(parameters[0], obj)));196 op2 = jimEvent.tryNumberConversion(jimEvent.tryDateConversion(self.evaluateExpression(parameters[1], obj)));197 if(jimEvent.isNumber(op1) && jimEvent.isNumber(op2)) {198 value = op1 < op2;199 }200 }201 return value;202 },203 "jimGreaterOrEquals": function(parameters, obj) {204 var self = this, value = null, op1, op2;205 if(jimUtil.exists(parameters[0]) && jimUtil.exists(parameters[1])) {206 op1 = jimEvent.tryNumberConversion(jimEvent.tryDateConversion(self.evaluateExpression(parameters[0], obj)));207 op2 = jimEvent.tryNumberConversion(jimEvent.tryDateConversion(self.evaluateExpression(parameters[1], obj)));208 if(jimEvent.isNumber(op1) && jimEvent.isNumber(op2)) {209 value = op1 >= op2;210 }211 }212 return value;213 },214 "jimLessOrEquals": function(parameters, obj) {215 var self = this, value = null, op1, op2;216 if(jimUtil.exists(parameters[0]) && jimUtil.exists(parameters[1])) {217 op1 = jimEvent.tryNumberConversion(jimEvent.tryDateConversion(self.evaluateExpression(parameters[0], obj)));218 op2 = jimEvent.tryNumberConversion(jimEvent.tryDateConversion(self.evaluateExpression(parameters[1], obj)));219 if(jimEvent.isNumber(op1) && jimEvent.isNumber(op2)) {220 value = op1 <= op2;221 }222 }223 return value;224 },225 /************************* END COMPARATOR FUNCTIONS ****************************/226227 /*************************** START TEXT FUNCTIONS ******************************/228 "jimCount": function(parameters, obj) {229 var self = this, value = null, op;230 if(jimUtil.exists(parameters[0])) {231 op = self.evaluateExpression(parameters[0], obj);232 value = (op && op.length) ? op.length : 0;233 }234 return value;235 },236 "jimConcat": function(parameters, obj) {237 var self = this, value = null, op1, op2;238 if(jimUtil.exists(parameters[0]) && jimUtil.exists(parameters[1])) {239 op1 = jimEvent.tryStringConversion(self.evaluateExpression(parameters[0], obj));240 op2 = jimEvent.tryStringConversion(self.evaluateExpression(parameters[1], obj));241 if(typeof(op1) === "string" && typeof(op2) === "string") {242 value = op1.concat(op2);243 }244 }245 return value;246 },247 "jimSubstring": function(parameters, obj) {248 var self = this, value = null, string, from, to;249 if(jimUtil.exists(parameters[0]) && jimUtil.exists(parameters[1]) && jimUtil.exists(parameters[2])) {250 string = jimEvent.tryStringConversion(self.evaluateExpression(parameters[0], obj)); /* make sure it's a string */251 from = jimEvent.tryNumberConversion(self.evaluateExpression(parameters[1], obj));252 to = jimEvent.tryNumberConversion(self.evaluateExpression(parameters[2], obj));253 if(typeof(string) === "string" && jimEvent.isNumber(from) && jimEvent.isNumber(to)) {254 value = string.substring(from, to);255 }256 }257 return value;258 },259 "jimIndexOf": function(parameters, obj) {260 var self = this, value = null, string, searchstring, start;261 if(jimUtil.exists(parameters[0]) && jimUtil.exists(parameters[1])) {262 string = jimEvent.tryStringConversion(self.evaluateExpression(parameters[0], obj));263 searchstring = jimEvent.tryStringConversion(self.evaluateExpression(parameters[1], obj));264 start = 0;265 if(parameters[2]) {266 start = jimEvent.tryNumberConversion(self.evaluateExpression(parameters[2], obj));267 }268 if(typeof(string) === "string" && typeof(searchstring) === "string" && jimEvent.isNumber(start)) {269 value = string.indexOf(searchstring, start);270 }271 }272 return value;273 },274 "jimUpper": function(parameters, obj) {275 var self = this, value = null, string;276 if(jimUtil.exists(parameters[0])) {277 string = jimEvent.tryStringConversion(self.evaluateExpression(parameters[0], obj));278 if(typeof(string) === "string") {279 value = string.toUpperCase();280 }281 }282 return value;283 },284 "jimLower": function(parameters, obj) {285 var self = this, value = null, string;286 if(jimUtil.exists(parameters[0])) {287 string = jimEvent.tryStringConversion(self.evaluateExpression(parameters[0], obj));288 if(typeof(string) === "string") {289 value = string.toLowerCase();290 }291 }292 return value;293 },294 "jimFirstUpper": function(parameters, obj) {295 var self = this, value = null, string;296 if(jimUtil.exists(parameters[0])) {297 string = jimEvent.tryStringConversion(self.evaluateExpression(parameters[0], obj));298 if(typeof(string) === "string") {299 value = string.substr(0,1).toUpperCase() + string.substr(1);300 }301 }302 return value;303 },304 "jimContains": function(parameters, obj) {305 var self = this, value = null, string, pattern;306 if(jimUtil.exists(parameters[0] && parameters[1])) {307 string = jimEvent.tryStringConversion(self.evaluateExpression(parameters[0], obj));308 pattern = self.evaluateExpression(parameters[1], obj);309 if(typeof(string) === "string" && typeof(pattern) === "string") {310 value = string.toLowerCase().indexOf(pattern.toLowerCase()) !== -1;311 }312 }313 return value;314 },315 /**************************** END TEXT FUNCTIONS *******************************/316317 /*************************** START LOGIC FUNCTIONS *****************************/318 "jimAnd": function(parameters, obj) {319 var self = this, value = null, op1, op2;320 if(jimUtil.exists(parameters[0]) && jimUtil.exists(parameters[1])) {321 op1 = jimEvent.tryBooleanConversion(self.evaluateExpression(parameters[0], obj));322 if(typeof(op1) === "boolean" && !op1) return false;323 op2 = jimEvent.tryBooleanConversion(self.evaluateExpression(parameters[1], obj));324 if(typeof(op1) === "boolean" && typeof(op2) === "boolean") {325 value = op1 && op2;326 }327 }328 return value;329 },330 "jimOr": function(parameters, obj) {331 var self = this, value = null, op1, op2;332 if(jimUtil.exists(parameters[0]) && jimUtil.exists(parameters[1])) {333 op1 = jimEvent.tryBooleanConversion(self.evaluateExpression(parameters[0], obj));334 if(typeof(op1) === "boolean" && op1) return true;335 op2 = jimEvent.tryBooleanConversion(self.evaluateExpression(parameters[1], obj));336 if(typeof(op1) === "boolean" && typeof(op2) === "boolean") {337 value = op1 || op2;338 }339 }340 return value;341 },342 "jimNot": function(parameters, obj) {343 var self = this, value = null, op;344 if(jimUtil.exists(parameters[0])) {345 op = jimEvent.tryBooleanConversion(self.evaluateExpression(parameters[0], obj));346 if(typeof(op) === "boolean") {347 value = !op;348 }349 }350 return value;351 },352 "jimXOr": function(parameters, obj) {353 var self = this, value = null, op1, op2;354 if(jimUtil.exists(parameters[0]) && jimUtil.exists(parameters[1])) {355 op1 = jimEvent.tryBooleanConversion(self.evaluateExpression(parameters[0], obj));356 op2 = jimEvent.tryBooleanConversion(self.evaluateExpression(parameters[1], obj));357 if(typeof(op1) === "boolean" && typeof(op2) === "boolean") {358 value = (op1 && !op2) || (!op1 && op2);359 }360 }361 return value;362 },363 /**************************** END LOGIC FUNCTIONS ******************************/364365 /************************* START CONSTANTS FUNCTIONS ***************************/366 "jimSystemDate": function() {367 var date = new Date();368 return date.formatDate("MM/dd/yyyy");369 },370 "jimSystemTime": function() {371 var time = new Date();372 return time.formatDate("HH:mm:ss");373 },374 "jimRandom": function() {375 var dec = 8;376 return Math.round(Math.random() * Math.pow(10, dec)) / Math.pow(10, dec);377 },378 "jimRegExp": function(parameters, obj) {379 var self = this, value = null, op, regexp;380 if(jimUtil.exists(parameters[0]) && jimUtil.exists(parameters[1])) {381 op = self.evaluateExpression(parameters[0], obj) + "";382 regexp = new RegExp(self.evaluateExpression(parameters[1], obj));383 value = regexp.test(op);384 }385 return value;386 },387 "jimWindowWidth": function() {388 return jQuery("#simulation").width()*(1/jimUtil.getScale());389 },390 "jimWindowHeight": function() {391 return jQuery("#simulation").height()*(1/jimUtil.getScale());392 },393 "jimWindowScrollX": function() {394 var scrollableElement;395 if(jimUtil.isMobileDevice())396 scrollableElement = jQuery("#simulation")[0];397 else if(window.jimDevice.isMobile())398 scrollableElement = jQuery(".ui-page")[0];399 else400 scrollableElement = jQuery("#simulation")[0];401 var zoom = jimUtil.getTotalScale();402 return scrollableElement.scrollLeft /zoom;403 },404 "jimWindowScrollY": function() {405 var scrollableElement;406 if(jimUtil.isMobileDevice())407 scrollableElement = jQuery("#simulation")[0];408 else if(window.jimDevice.isMobile())409 scrollableElement = jQuery(".ui-page")[0];410 else411 scrollableElement = jQuery("#simulation")[0];412 var zoom = jimUtil.getTotalScale();413 return scrollableElement.scrollTop / zoom;414 },415 "jimCursorX": function() {416 var zoom = jimUtil.getTotalScale();417 return window.mousePos.x / zoom;418 },419 "jimCursorY": function() {420 var zoom = jimUtil.getTotalScale();421 return window.mousePos.y / zoom;422 },423424 /************************* END CONSTANTS FUNCTIONS *****************************/425426 /*************************** START AREA FUNCTIONS ******************************/427 "jimAreaIntersect": function(parameters, obj) {428 var self = this, value = null, op1, op2;429 if(jimUtil.exists(parameters[0]) && jimUtil.exists(parameters[1])) {430 op1 = jimEvent.tryAreaConversion(self.evaluateExpression(parameters[0], obj));431 op2 = jimEvent.tryAreaConversion(self.evaluateExpression(parameters[1], obj));432 if(op1 && op2){433 for(var i=0; i<op1.areas.length; i++) {434 for(var j=0; j<op2.areas.length; j++) {435 if(jimUtil.incompleteIntersect(op1.areas[i].points,op2.areas[j].points))436 return true;437 }438 }439 }440 }441 return false;442 },443 "jimAreaContains": function(parameters, obj) {444 var self = this, value = null, op1, op2;445 if(jimUtil.exists(parameters[0]) && jimUtil.exists(parameters[1])) {446 op2 = jimEvent.tryAreaConversion(self.evaluateExpression(parameters[0], obj));447 op1 = jimEvent.tryAreaConversion(self.evaluateExpression(parameters[1], obj));448 if(op1 && op2){449 for(var i=0; i<op1.areas.length; i++) {450 var contains = false;451 for(var j=0; j<op2.areas.length; j++) {452 if(jimUtil.polygonContains(op1.areas[i].points,op2.areas[j].points))453 contains=true;454 }455 if(!contains)return false;456 }457 return true;458 }459 }460 return false;461 }, ...

Full Screen

Full Screen

function-jim-event-data.js

Source:function-jim-event-data.js Github

copy

Full Screen

...30 31 for(field in args.fields) {32 if(args.fields.hasOwnProperty(field)) {33 value = args.fields[field];34 newInstance.userdata[field] = (jQuery.isEmptyObject(value)) ? "" : self.evaluateExpression(value);35 }36 }37 38 jimData.datamasters[datamaster].push(newInstance);39 }40 41 if(callback) { callback(); }42 }43 },44 "jimUpdateData": function(args, callback) {45 var self = this, datamaster, instances, instance, i, iLen, j, jLen, variable, records, record, value, $dataViews, g, gLen, k, kLen, $datarows, field, $field;46 if (args && args.fields) {47 /* update data */48 instances = jimUtil.toArray(self.evaluateExpression(args));49 if(instances!==undefined && instances[0] !== "") { 50 for(i = 0, iLen = instances.length; i < iLen; i += 1) {51 instance = instances[i];52 53 /* establish association with data master record, may have been lost on unload */54 datamaster = jimData.datamasters[instance.datamaster];55 for(j = 0, jLen = datamaster.length; j < jLen; j += 1) {56 if(datamaster[j].id === instance.id) {57 datamaster[j] = instance;58 break;59 }60 }61 62 /* establish association with variable, may have been lost on unload */63 for(variable in jimData.variables) {64 if(jimData.variables.hasOwnProperty(variable)) {65 records = jimData.variables[variable];66 if(jimUtil.isArray(records)) {67 for(j = 0, jLen = records.length; j < jLen; j += 1) {68 record = records[j]; 69 if(record.datamaster === instance.datamaster && record.id === instance.id) {70 jimData.variables[variable][j] = instance;71 break;72 }73 }74 }75 }76 }77 78 for(field in args.fields) {79 if(args.fields.hasOwnProperty(field)) {80 value = args.fields[field];81 if(!jQuery.isEmptyObject(value)) {82 instance.userdata[field] = self.evaluateExpression(value, instance);83 }84 }85 }86 }87 88 /* update data grid */89 datamaster = args.datamaster || args.parameter && args.parameter.datamaster || instance.datamaster;90 $dataViews = jQuery(".datalist[datamaster='" + datamaster +"'], .datagrid[datamaster='" + datamaster +"']");91 for(g=0, gLen=$dataViews.length; g < gLen; g += 1) {92 var $dataView = jQuery($dataViews[g]);93 for (k=0, kLen=instances.length; k < kLen; k += 1) {94 instance = instances[k];95 var $rowOrGridCell;96 if($dataView.is(".datagrid")){97 $rowOrGridCell = $dataView.find(".gridcell[instance='" + instance.id + "']");98 } else {99 var $datarows = $dataView.find("[name='id'][value='" + instance.id + "']").parents(".datarow");100 if($datarows.length)101 $rowOrGridCell = jQuery($datarows[0]);102 }103 104 if($rowOrGridCell) {105 for (field in instance.userdata) {106 if (instance.userdata.hasOwnProperty(field)) {107 value = instance.userdata[field];108 $field = $rowOrGridCell.find("[name='" + field + "']");109 $field.val(value);110 switch($field.jimGetType()) {111 case itemType.dropdown:112 case itemType.nativedropdown:113 case itemType.selectionlist:114 case itemType.multiselectionlist:115 case itemType.radiobuttonlist:116 case itemType.checkboxlist:117 self.jimSetSelection({"target": $field, "value": value});118 break;119 /* intentional fall-through */ 120 default:121 self.jimSetValue({"target": $field, "value": value});122 break;123 }124 }125 }126 $rowOrGridCell.closest(".datachange").trigger("datachange");127 }128 }129 }130 }131 132 if(callback) { callback(); }133 }134 },135 "jimDeleteData": function(args, callback) {136 var self = this, datamaster, $grid,$gridCell, variable, instances, removeInstances, removeInstance, removeID, i, iLen, j, id;137 if (args) {138 datamaster = args.datamaster || args.parameter && args.parameter.datamaster;139 if (args.datatype === "datamaster") {140 /* delete data master */141 jimData.datamasters[datamaster] = [];142 /* update data grid */143 jQuery(".datalist[datamaster='" + datamaster +"']").each(function(index, grid) {144 jQuery(grid).find("table:first").children("tbody").html("<tr><td></td></tr>");145 });146 /* update variable */147 for(variable in jimData.variables) {148 if(jimData.variables.hasOwnProperty(variable)) {149 instances = jimData.variables[variable];150 if(jimUtil.isArray(instances)) {151 for(i=instances.length-1; i>=0; i-=1) {152 removeInstance = instances[i];153 if(removeInstance.datamaster === datamaster) {154 instances.splice(i,1);155 }156 }157 }158 }159 }160 } else {161 /* delete data master */162 removeInstances = jimUtil.toArray(self.evaluateExpression(args));163 datamaster = datamaster || removeInstances.length && removeInstances[0].datamaster;164 instances = jimData.datamasters[datamaster];165 removeID = [];166 if(instances && removeInstances) {167 for (i=instances.length-1; i>=0 && removeInstances.length; i-=1) {168 for (j=removeInstances.length-1; j>=0; j-=1) {169 id = removeInstances[j].id;170 if (instances[i].id === id) {171 removeID.push(id);172 removeInstances.splice(j, 1);173 instances.splice(i, 1);174 break;175 }176 }177 }178 /* update data grid */179 jQuery(".datalist[datamaster='" + datamaster +"']").each(function(index, grid) {180 $grid = jQuery(grid);181 for (i=0, iLen=removeID.length; i<iLen; i+=1) {182 $grid.find(".datarow:has([name='id'][value='" + removeID[i] + "'])").remove();183 }184 $grid.dataview("updateDataListPage");185 $grid.dataview("updateDataListBounds");186 $grid.trigger("update.dataview");187 });188 189 jQuery(".datagrid[datamaster='" + datamaster +"']").each(function(index, grid) {190 $grid = jQuery(grid);191 192 for (i=0, iLen=removeID.length; i<iLen; i+=1) {193 var $dataViewInstances = $grid.find(".gridcell");194 $gridCell = $grid.find(".gridcell[instance='" + removeID[i] + "']");195 var $visibleCells = $dataViewInstances.filter(":not(.hidden)");196 var maxIndex = 0;197 var j,jLen;198 for (j=0, jLen=$visibleCells.length; j<jLen; j+=1) {199 var instanceNumber = jQuery($visibleCells.get(j)).attr("instance");200 maxIndex = Math.max(maxIndex,instanceNumber);201 }202 maxIndex= maxIndex+1;203 var $nextVisibleCell = $grid.find(".gridcell[instance='" + maxIndex + "']");204 $gridCell.remove();205 $nextVisibleCell.removeClass("hidden");206 }207 $grid.dataview("rebuildDataGridHierarchy");208 $grid.trigger("update.dataview");209 });210 211 212 /* update variable */213 for(variable in jimData.variables) {214 if(jimData.variables.hasOwnProperty(variable)) {215 instances = jimData.variables[variable];216 if(jimUtil.isArray(instances)) {217 for(i=0, iLen=removeID.length; i<iLen; i+=1) {218 for(j=instances.length-1; j>=0; j-=1) {219 removeInstance = instances[j];220 if(removeInstance.datamaster === datamaster && removeInstance.id === removeID[i]) {221 instances.splice(j,1);222 }223 }224 }225 }226 }227 }228 }229 }230 231 if(callback) { callback(); }232 }233 },234 "jimFilterData": function(args) {235 var self = this, filteredInstances = [], instances, i, len, result, searchTokens, searchExpression, search, property;236 if (args) {237 instances = jimUtil.toArray(self.evaluateExpression(args));238 for(i=0, len=instances.length; i < len; i += 1) {239 result = self.evaluateExpression(args.value, instances[i]);240 instance = instances[i]; /* prevent overwrite from other inner filter instances */241 if (typeof (result) === "string") {242 searchTokens = jimUtil.escapeRegex(result).split(' ');243 searchExpression = '^(?=.*?' + searchTokens.join(')(?=.*?') + ').*$';244 search = new RegExp(searchExpression, "i");245 246 /* TODO: apply over whole instance not attributes247 * values = jimUtil.getValues(instance, ["id", "datamaster"]).join(" ");248 * if (search.test(values)) {249 * filteredInstances.push(instance);250 * }251 */252 253 for(property in instance.userdata) {254 if(instance.userdata.hasOwnProperty(property)) {255 if (search.test(instance.userdata[property])) {256 filteredInstances.push(instance);257 break;258 }259 }260 }261 } else if (result) {262 filteredInstances.push(instance);263 }264 }265 }266 return filteredInstances;267 },268 "jimSumData": function(args) {269 var self = this, instances, result = 0, i, len, tmpResult;270 if (args) {271 instances = jimUtil.toArray(self.evaluateExpression(args));272 for(i=0, len=instances.length; i < len; i += 1) {273 tmpResult = jimEvent.tryNumberConversion(self.evaluateExpression(args.value, instances[i]));274 if (jimUtil.exists(tmpResult) && !isNaN(tmpResult)) {275 if(!isNaN(Number(tmpResult)))276 result = (result * 10 + Number(tmpResult) * 10) / 10; //0.2 + 0.1 = 0.30000000000000004277 } else {278 result = null;279 break;280 }281 }282 return result;283 }284 },285 "jimAvgData": function(args) {286 var self = this, result = null, sum, length;287 if (args) {288 length = jimUtil.toArray(self.evaluateExpression(args)).length;289 if (length !== 0) {290 sum = self.jimSumData(args);291 if (sum !== null && !isNaN(sum)) {292 result = sum / length;293 }294 }295 }296 return result;297 },298 "jimMaxData": function(args) {299 var self = this, values = [], instances, i, len;300 if (args) {301 instances = jimUtil.toArray(self.evaluateExpression(args));302 for(i=0, len=instances.length; i < len; i += 1) {303 values.push(self.evaluateExpression(args.value, instances[i]));304 }305 }306 return self.jimMax(values);307 },308 "jimMinData": function(args) {309 var self = this, values = [], instances, i, len;310 if (args) {311 instances = jimUtil.toArray(self.evaluateExpression(args));312 for(i=0, len=instances.length; i < len; i += 1) {313 values.push(self.evaluateExpression(args.value, instances[i]));314 }315 }316 return self.jimMin(values);317 },318 "jimCountData": function(args) {319 var self = this, tmpResult, result = null;320 if (args) {321 tmpResult = self.evaluateExpression(args);322 result = (tmpResult === "") ? 0 : jimUtil.toArray(tmpResult).length;323 }324 return result;325 },326 "jimSelectData": function(args) {327 var self = this, result = [], instances, i, len;328 if (args) {329 instances = jimUtil.toArray(self.evaluateExpression(args));330 for(i=0, len=instances.length; i < len; i += 1) {331 result.push(self.evaluateExpression(args.value, instances[i]));332 }333 }334 return result.join(",");335 },336 "jimSelectDistinctData": function(args) {337 var self = this, result = [], instances, i, len;338 if (args) {339 instances = jimUtil.toArray(self.evaluateExpression(args));340 for(i=0, len=instances.length; i < len; i += 1) {341 instance = {342 "key": self.evaluateExpression(args.value, instances[i]),343 "value": ""344 };345 result.push(instance);346 }347 var aux = jimUtil.unique(result);348 result = [];349 for(i=0, len=aux.length; i < len; i++) {350 result.push(aux[i].key);351 }352 }353 return result.join(",");354 },355 "jimFilterDistinctData": function(args) {356 var self = this, result = [], instances, i, len;357 if(args) {358 instances = jimUtil.toArray(self.evaluateExpression(args));359 for(i=0, len=instances.length; i < len; i += 1) {360 instance = {361 "key": self.evaluateExpression(args.value, instances[i]),362 "value": instances[i]363 };364 result.push(instance);365 }366 var aux = jimUtil.unique(result);367 result = [];368 for(i=0, len=aux.length; i < len; i++) {369 result.push(aux[i].value);370 }371 }372 return result;373 },374 "jimAddToData": function(args) {375 var self = this, result = [], sourceA, datamasterA, sourceB, datamasterB, instances;376 if (jimUtil.exists(args) && jimUtil.exists(args[0]) && jimUtil.exists(args[1])) {377 sourceA = jimUtil.toArray(self.evaluateExpression(args[0]));378 sourceB = jimUtil.toArray(self.evaluateExpression(args[1]));379 380 if(args[0].datamaster) {381 datamasterA = args[0].datamaster;382 } else if (sourceA.length) {383 datamasterA = sourceA[0].datamaster;384 }385386 if(args[1].datamaster) {387 datamasterB = args[1].datamaster;388 } else if (sourceB.length) {389 datamasterB = sourceB[0].datamaster;390 }391 392 if(datamasterA && datamasterB && datamasterA === datamasterB || datamasterA === undefined && datamasterB === undefined) {393 result = jQuery.merge(sourceA, sourceB);394 } else if (datamasterA === undefined && datamasterB) {395 result = sourceB;396 } else {397 result = sourceA;398 }399 }400 return result;401 },402 "jimRemoveFromData": function(args) {403 var self = this, result = [], sourceA, sourceB, i, j;404 if (jimUtil.exists(args) && jimUtil.exists(args[0]) && jimUtil.exists(args[1])) {405 sourceA = jimUtil.toArray(self.evaluateExpression(args[0]));406 sourceB = jimUtil.toArray(self.evaluateExpression(args[1]));407 for (i = sourceB.length - 1; i >= 0 && sourceA.length; i -= 1) {408 for (j = sourceA.length - 1; j >= 0; j -= 1) {409 if (sourceB[i] === sourceA[j]) {410 sourceA.splice(j, 1);411 sourceB.splice(i, 1);412 break;413 }414 }415 }416 result = sourceA;417 }418 return result;419 },420 "jimFirstPageData": function(args, callback) {421 var self = this, size, $dataViewInstances;422 if (args && args.target) {423 var $targets = self.getEventTargets(args.target);424 for (var i in $targets) {425 var $target = $targets[i];426 if ($target.length) {427 size = parseInt($target.attr("size"), 10);428 if(size > 0) {429 $dataViewInstances = getInstances($target);430 $dataViewInstances.addClass("hidden").filter(":lt(" + size + ")").removeClass("hidden");431 $target.trigger("update.dataview");432 }433 }434 }435 if(callback) { callback(); }436 }437 },438 "jimPrevPageData": function(args, callback) {439 var self = this, size, $dataViewInstances, $prev,index;440 if (args && args.target) {441 var $targets = self.getEventTargets(args.target);442 for (var i in $targets) {443 var $target = $targets[i];444 if ($target.length) {445 size = parseInt($target.attr("size"), 10);446 $dataViewInstances = getInstances($target);447 index = $dataViewInstances.index($dataViewInstances.filter(":visible").first())-1;448 if (index>=0) {449 $dataViewInstances.addClass("hidden");450 $prev = jQuery($dataViewInstances[index]);451 while (size>0 && $prev.length) {452 $prev.removeClass("hidden");453 if (index>=0){454 index -=1;455 $prev = jQuery($dataViewInstances[index]);456 }457 size -= 1;458 }459 $target.trigger("update.dataview");460 }461 }462 }463 if(callback) { callback(); }464 }465 },466 "jimNextPageData": function(args, callback) {467 var self = this, size, $dataViewInstances, $next,index;468 if (args && args.target) {469 var $targets = self.getEventTargets(args.target);470 for (var i in $targets) {471 var $target = $targets[i];472 if ($target.length) {473 size = parseInt($target.attr("size"), 10);474 $dataViewInstances = getInstances($target);475 index = $dataViewInstances.index($dataViewInstances.filter(":visible").last())+1;476 if (index<$dataViewInstances.length) {477 $dataViewInstances.addClass("hidden");478 $next = jQuery($dataViewInstances[index]);479 while (size>0 && $next.length) {480 $next.removeClass("hidden");481 if (index<$dataViewInstances.length){482 index +=1;483 $next = jQuery($dataViewInstances[index]);484 }485 size -= 1;486 }487 }488 $target.trigger("update.dataview");489 }490 }491 if(callback) { callback(); }492 }493 },494 "jimLastPageData": function(args, callback) {495 var self = this, $dataViewInstances, gridSize, filterSize, index;496 if (args && args.target) {497 $targets = self.getEventTargets(args.target);498 for (var i in $targets) {499 var $target = $targets[i];500 if ($target.length) {501 $dataViewInstances = getInstances($target);502 gridSize = $dataViewInstances.length;503 filterSize = parseInt($target.attr("size"), 10);504 index = (gridSize % filterSize === 0) ? gridSize - filterSize - 1 : gridSize - (gridSize % filterSize) - 1;505 if(!isNaN(index) && index>0) {506 $dataViewInstances.addClass("hidden").filter(":gt(" + index + ")").removeClass("hidden");507 $target.trigger("update.dataview");508 }509 }510 if(callback) { callback(); }511 }512 }513 },514 "getDataInstancesById": function(instances, ids) {515 var result=[], i, ilen, j, jlen, instance;516 for (i=0, ilen=ids.length; i<ilen; i+=1) {517 for (j=0, jlen=instances.length; j<jlen; j+=1) {518 instance = instances[j];519 if (jimEvent.tryNumberConversion(ids[i]) === instance.id) {520 result.push(instance);521 break;522 }523 }524 }525 return result;526 },527 "jimSortDataAscendant": function(args) {528 var self = this, instances = [];529 if (args) {530 instances = jimUtil.toArray(self.evaluateExpression(args));531 if(instances !== []) {532 instances.sort(function(a, b) {533 if(typeof(jimEvent.tryNumberConversion(a.userdata[args.value.field])) === "number") {534 return a.userdata[args.value.field] - b.userdata[args.value.field]535 }536 else if(typeof(jimEvent.tryDateConversion(a.userdata[args.value.field])) === "object" && typeof(a.userdata[args.value.field]) === "string") {537 return new Date(a.userdata[args.value.field]) - new Date(b.userdata[args.value.field])538 }539 else if(typeof(jimEvent.tryStringConversion(a.userdata[args.value.field])) === "string") {540 if (a.userdata[args.value.field] < b.userdata[args.value.field]) {541 return -1542 }543 if (a.userdata[args.value.field] > b.userdata[args.value.field]) {544 return 1545 }546 return 0547 }548 });549 }550 }551 return instances;552 },553 "jimSortDataDescendant": function(args) {554 var self = this, instances = [];555 if (args) {556 instances = jimUtil.toArray(self.evaluateExpression(args));557 if(instances !== []) {558 instances.sort(function(a, b) {559 if(typeof(jimEvent.tryNumberConversion(a.userdata[args.value.field])) === "number") {560 return b.userdata[args.value.field] - a.userdata[args.value.field]561 }562 else if(typeof(jimEvent.tryDateConversion(a.userdata[args.value.field])) === "object" && typeof(a.userdata[args.value.field]) === "string") {563 return new Date(b.userdata[args.value.field]) - new Date(a.userdata[args.value.field])564 }565 else if(typeof(jimEvent.tryStringConversion(a.userdata[args.value.field])) === "string") {566 if (b.userdata[args.value.field] < a.userdata[args.value.field]) {567 return -1568 }569 if (b.userdata[args.value.field] > a.userdata[args.value.field]) {570 return 1 ...

Full Screen

Full Screen

main.js

Source:main.js Github

copy

Full Screen

...315 methods = {316 317 // Variable assigning318 assign:function(name, value, operation) {319 evaluateExpression(name + ' ' + operation + ' ' + value);320 },321 322 // Changes the title323 title:function(params, extra) {324 title = params[0];325 },326 327 /********************* BRANCHING OPERATIONS *********************/328 select:function(params) {329 $('#dialog').html('<a href="javascript:void(0);" class="select" rel="0">' + variables["strS[1903]"] + '</a><br /><a href="javascript:void(0);" class="select" rel="1">' + variables["strS[1904]"] + '</a>');330 $('.select').unbind('click').click(methods.selectClick);331 exit = true;332 },333 334 selectClick:function(e) {335 var336 rel = parseInt($(e.target).attr('rel')),337 op = code[currentScene][currentOp - 1],338 newCode = op.code.split('=')[0] + ' = ' + rel;339 evaluateExpression(newCode);340 loop();341 },342 343 /********************** AUDIO OPERATIONS ***********************/344 bgmLoop:function(params) {345 if (audio) {346 var file = evaluateExpression(params[0]);347 music.src = './KANON_SE/music/' + file + '.mp3';348 music.loop = true;349 music.load();350 music.play();351 }352 },353 354 bgmPlay:function(params) {355 if (audio) {356 var file = evaluateExpression(params[0]);357 music.src = './KANON_SE/music/' + file + '.mp3';358 music.loop = false;359 music.load();360 music.play();361 }362 },363 364 bgmFadeOutEx:function(params) {365 366 },367 368 bgmFadeOut:function(params) {369 370 },371 372 wavStop:function() {373 if (audio) {374 sfx.pause();375 }376 },377 378 wavPlay:function(params) {379 if (audio) {380 var file = evaluateExpression(params[0]);381 sfx.src = './KANON_SE/sfx/' + file + '.wav';382 sfx.load();383 sfx.play();384 }385 },386 387 koePlay:function(params) {388 389 },390 391 /********************* GRAPHICS OPERATIONS *********************/392 grpOpenBg:function(params) {393 var file = evaluateExpression(params[0]).toUpperCase();394 if (file === '?' || file === '???') {395 396 } else {397 graphics.load(file, 'bg', 0);398 }399 breakForGraphics = true;400 },401 402 recOpenBg:function(params) {403 methods.grpOpenBg(params);404 breakForGraphics = true;405 },406 407 recOpen:function(params) {408 var file = evaluateExpression(params[0]).toUpperCase();409 if (file === '?' || file === '???') {410 } else {411 graphics.load(file, 'obj', 0);412 }413 breakForGraphics = true;414 },415 416 grpMulti:function(params) {417 params[0] = evaluateExpression(params[0]);418 if (typeof(params[0]) === 'string') {419 var file = params[0].toUpperCase();420 graphics.load(file, 'bg', 0);421 multiId = 0;422 } else if (typeof(params[0]) === 'number') {423 graphics.moveLayer('bg', params[0], 0);424 multiId = params[0];425 graphics.clearLayer(multiId);426 }427 for (var i = 1, count = params.length; i < count; i++) {428 params[i] = evaluateExpression(params[i]);429 }430 breakForGraphics = true;431 },432 433 recLoad:function(params) {434 breakForGraphics = true;435 },436 437 objBgOfFile:function(params) {438 var439 file = evaluateExpression(params[1]).toUpperCase(),440 name = evaluateExpression(params[0]),441 visible = typeof(params[2]) === 'undefined' ? false : params[2];442 graphics.load(file, 'bg', name);443 breakForGraphics = true;444 },445 446 objBgClear:function(params) {447 breakForGraphics = true;448 },449 450 objBgMove:function(params) {451 var name = evaluateExpression(params[0]), x = evaluateExpression(params[1]), y = evaluateExpression(params[2]);452 graphics.move('bg', name, x, y);453 breakForGraphics = true;454 },455 456 objMove:function(params) {457 var name = evaluateExpression(params[0]), x = evaluateExpression(params[1]), y = evaluateExpression(params[2]);458 graphics.move('obj', name, x, y);459 },460 461 grpBuffer:function(params) {462 var463 file = evaluateExpression(params[0]).toUpperCase(),464 layer = evaluateExpression(params[1]);465 graphics.load(file, 'bg', layer);466 breakForGraphics = true;467 },468 469 copy:function(params) {470 var file = evaluateExpression(params[0]).toUpperCase();471 graphics.load(file, 'bg', multiId, (new Date()).getTime());472 breakForGraphics = true;473 },474 475 objClear:function(params) {476 graphics.clear('obj', evaluateExpression(params[0]));477 breakForGraphics = true;478 },479 480 objOfFile:function(params) {481 graphics.load(evaluateExpression(params[1]), 'obj', evaluateExpression(params[0]));482 breakForGraphics = true;483 },484 485 objDriftOfFile:function(params) {486 487 },488 489 objBgDriftOfFile:function(params) {490 491 },492 493 objDriftOpts:function(params) {494 495 },496 497 objBgDriftOpts:function(params) {498 499 },500 501 objDispRect:function(params) {502 var503 buf = evaluateExpression(params[0]),504 x = evaluateExpression(params[1]),505 y = evaluateExpression(params[2]),506 width = evaluateExpression(params[3]),507 height = evaluateExpression(params[4]);508 console.log(buf, x, y, width, height);509 // graphics.displayRect('obj', buf, x, y, width, height);510 },511 512 objBgDispRect:function(params) {513 var514 buf = evaluateExpression(params[0]),515 x = evaluateExpression(params[1]),516 y = evaluateExpression(params[2]),517 width = evaluateExpression(params[3]),518 height = evaluateExpression(params[4]);519 console.log(buf, x, y, width, height);520 graphics.displayRect('bg', buf, x, y, width, height);521 },522 523 objCopyFgToBg:function(params) {524 525 },526 527 objShow:function(params) {528 graphics.show('obj', evaluateExpression(params[0]), evaluateExpression(params[1]));529 breakForGraphics = true;530 },531 532 objAlpha:function(params) {533 for (var i in params) {534 params[i] = evaluateExpression(params[i]);535 }536 graphics.alpha('obj', params[0], params[1]);537 },538 539 objPattNo:function(params) {540 graphics.setPattern('obj', evaluateExpression(params[0]), evaluateExpression(params[1]));541 },542 543 objGetPos:function(params) {544 545 },546 547 objGetDims:function(params) {548 549 },550 551 objBgPattNo:function(params) {552 graphics.setPattern('bg', evaluateExpression(params[0]), evaluateExpression(params[1]));553 },554 555 objBgShow:function(params) {556 557 },558 559 refresh:function() {560 breakForGraphics = true;561 },562 563 objAdjust:function(params) {564 // console.log(params);565 graphics.adjust('obj', evaluateExpression(params[0]), evaluateExpression(params[1]), evaluateExpression(params[2]), evaluateExpression(params[3]));566 },567 568 objDelete:function(params) {569 graphics.del(evaluateExpression(params[0]));570 breakForGraphics = true;571 },572 573 index_series:function(params) {574 var 575 retVal = 0,576 index = evaluateExpression(params[0]),577 offset = evaluateExpression(params[1]),578 init = evaluateExpression(params[2]),579 current = index + offset;580 581 for (var i = 3, max = params.length; i < max; i++) {582 583 var584 set = params[i].split(','),585 start = evaluateExpression(set[0]),586 end = evaluateExpression(set[1]),587 endVal = evaluateExpression(set[2]);588 589 if (current < start) {590 // retVal = start;591 } else if (current > end) {592 //retVal = endVal;593 init = endVal;594 } else {595 var 596 deltaOut = endVal - init,597 deltaIn = end - start,598 deltaCurrent = current - start;599 retVal = deltaCurrent / deltaIn * deltaOut + init;600 601 if (params.length > 4) {602 console.log(deltaOut, deltaIn, deltaCurrent, retVal, init);603 }604 605 break;606 }607 608 }609 610 return retVal;611 },612 613 recFill:function(params) {614 var615 x = evaluateExpression(params[0]),616 y = evaluateExpression(params[1]),617 w = evaluateExpression(params[2]),618 h = evaluateExpression(params[3]),619 dc = evaluateExpression(params[4]),620 r = evaluateExpression(params[5]),621 g = evaluateExpression(params[6]),622 b = evaluateExpression(params[7]);623 graphics.solid(dc, x, y, w, h, r, g, b);624 },625 626 InitFrames:function(params) {627 for (var i in params) {628 params[i] = params[i].split(',');629 for (var j in params[i]) {630 params[i][j] = evaluateExpression(params[i][j]);631 }632 var633 timer = params[i][0],634 opts = {startVal:params[i][1], endVal:params[i][2], duration:params[i][3], startTime:(new Date()).getTime()};635 frames[timer] = opts;636 }637 },638 639 InitExFrames:function(params) {640 methods.InitFrames(params);641 },642 643 ReadFrames:function(params) {644 var active = false;645 for (var i in params) {646 params[i] = params[i].split(',');647 var648 timer = evaluateExpression(params[i][0]),649 delta = ((new Date()).getTime() - frames[timer].startTime) / frames[timer].duration;650 delta > 1 ? 1 : delta;651 active = delta < 1 ? true : active;652 var val = (frames[timer].endVal - frames[timer].startVal) * delta + frames[timer].startVal;653 variables[params[i][1]] = Math.floor(val);654 }655 return active;656 },657 658 ReadExFrames:function(params) {659 methods.ReadFrames(params);660 },661 662 SetSkipAnimations:function(params) {663 664 },665 666 msgHide:function() {667 $('#dialog').fadeOut();668 breakForGraphics = true;669 },670 671 CallDLL:function(params) {672 if (params[0] == 0) {673 rlBabel(params);674 }675 },676 677 /********************** GRAPHICS EFFECTS ***********************/678 shake:function(params) {679 680 },681 682 ganPlayEx:function(params) {683 684 },685 686 /********************** TIMER OPERATIONS ***********************/687 ResetTimer:function(params) {688 var timer = 0;689 if (typeof(params[0]) !== 'undefined') {690 timer = evaluateExpression(params[0]);691 }692 timers[timer] = (new Date()).getTime();693 breakForGraphics = true;694 },695 696 Timer:function(params) {697 var timer = 0;698 if (typeof(params[0]) !== 'undefined') {699 timer = evaluateExpression(params[0]);700 }701 return (new Date()).getTime() - timers[timer];702 breakForGraphics = true;703 },704 705 /*********************** JUMP OPERATIONS ***********************/706 gosub:function(params) {707 stack.push({scene:currentScene, op:currentOp});708 // console.log(stack);709 methods.goto(params);710 },711 712 ret:function() {713 var op = stack.pop();714 currentScene = op.scene;715 currentOp = op.op;716 },717 718 rtl:function() {719 methods.ret();720 },721 722 goto:function(params) {723 currentOp = labels[currentScene]['@' + params[0]];724 },725 726 goto_on:function(params) {727 728 },729 730 goto_unless:function(params) {731 var732 e = evaluateExpression(params[0]),733 c = [evaluateExpression(params[1])];734 if (!e) {735 methods.goto(c);736 }737 },738 739 farcall:function(params) {740 stack.push({scene:currentScene, op:currentOp});741 methods.jump([params[0]]);742 },743 744 jump:function(params) {745 currentOp = -1;746 loadScenario(params[0]);747 exit = true;748 },749 750 waitC:function(params) {751 methods.wait(params);752 },753 754 755 wait:function(params) {756 var duration = evaluateExpression(params[0]);757 exit = true;758 setTimeout(loop, duration);759 },760 761 /************************ GENERIC CRAP ************************/762 itoa:function(params) {763 var len = evaluateExpression(params[1]), val = evaluateExpression(params[0]);764 while (('' + val).length < len) {765 val = '0' + val;766 }767 return val;768 },769 770 GetCursorPos:function() {771 772 },773 774 DisableAutoSavepoints:function() {775 776 },777 778 EnableAutoSavepoints:function() {779 780 },781 782 SetAutoMode:function(params) {783 784 },785 786 HideSyscom:function(params) {787 788 },789 790 SetMessageSpeed:function(params) {791 792 },793 794 setrng_stepped:function(params) {795 796 },797 798 pause:function() {799 exit = true;800 $('#container').click(function() { loop(); });801 },802 803 spause:function() {804 exit = true;805 $('#container').click(function() { loop(); });806 }807 808 809 810 },811 812 ajaxCallback = function(data) {813 814 currentScene = data.scene;815 code[currentScene] = data.code;816 labels[currentScene] = {};817 818 // Make a note of where all the labels are819 for (var i = 0, count = code[currentScene].length; i < count; i++) {820 if (typeof(code[currentScene][i].label) !== 'undefined') {821 labels[currentScene]['@' + code[currentScene][i].label] = i;822 }823 }824 loop();825 826 },827 828 executeOp = function(op) {829 // console.log('[' + currentScene + ', ' + op.ln + '] ' + op.code);830 evaluateExpression(op.code);831 },832 833 loop = function() {834 835 var op;836 837 $('#container').unbind('click');838 exit = false;839 840 while (!exit) {841 842 executeOp(code[currentScene][currentOp]);843 844 currentOp++; ...

Full Screen

Full Screen

evalexpr.tests.js

Source:evalexpr.tests.js Github

copy

Full Screen

...7 });89 describe('addition', function () {10 it('should return 3 for 1+2', function () {11 should(eval.evaluateExpression("1+2")).equal(3);12 });1314 it('should return 3 for (1+2)', function () {15 should(eval.evaluateExpression("(1+2)")).equal(3);16 });1718 it('should return 3.1 for 1.1+2', function () {19 should(eval.evaluateExpression("1.1+2")).equal(3.1);20 });21 });2223 describe('substraction', function () {24 it('should return 2 for 3-1', function () {25 should(eval.evaluateExpression("3-1")).equal(2);26 });2728 it('should return 2 for (3-1)', function () {29 should(eval.evaluateExpression("(3-1)")).equal(2);30 });3132 it('should return 2.1 for 3.1-1', function () {33 should(eval.evaluateExpression("3.1-1")).equal(2.1);34 });35 });3637 describe('multiplication', function () {38 it('should return 4 for 2*2', function () {39 should(eval.evaluateExpression("2*2")).equal(4);40 });4142 it('should return 4.2 for 2.1*2', function () {43 should(eval.evaluateExpression("2.1*2")).equal(4.2);44 });45 });4647 describe('division', function () {48 it('should return 0.5 for 1/2', function () {49 should(eval.evaluateExpression("1/2")).equal(0.5);50 });5152 it('should return 0.55 for 1.1/2', function () {53 should(eval.evaluateExpression("1.1/2")).equal(0.55);54 });55 });5657 describe('different operations', function () {58 it('should return 25.5 for 1/2 + 5 + 4*5', function () {59 should(eval.evaluateExpression("1/2 + 5 + 4*5")).equal(25.5);60 });6162 it('should return 45.5 for 1/2 + (5 + 4) * 5', function () {63 should(eval.evaluateExpression("1/2 + (5 + 4) * 5")).equal(45.5);64 });6566 it('should return 45.5 for 1/2    + (5 + 4) * 5', function () {67 should(eval.evaluateExpression("1/2 + (5 + 4) * 5")).equal(45.5);68 });6970 it('should return 52.52 for 1/2 + (5.5 + 4.7) * 5.1', function () {71 should(eval.evaluateExpression("1/2 + (5.5 + 4.7) * 5.1")).equal(52.52);72 });7374 it('should return -52.52 for -1/2 + (-5.5 - 4.7) * 5.1', function () {75 should(eval.evaluateExpression("-1/2 + (-5.5 - 4.7) * 5.1")).equal(-52.52);76 });7778 it('should return 1.67 for 1+2/3', function () {79 should(eval.evaluateExpression("1+2/3")).equal(1.67);80 });8182 it('should return 1 for 1+2/45/78/78', function () {83 should(eval.evaluateExpression("1+2/45/78/78")).equal(1);84 });8586 it('should return 0 for 0', function () {87 should(eval.evaluateExpression("0")).equal(0);88 });8990 it('should return 18 for 18', function () {91 should(eval.evaluateExpression("18")).equal(18);92 });93 });9495 describe('undefined', function () {96 it('should return undefined for "(1/2 + 5 + 4*5', function () {97 should(eval.evaluateExpression("(1/2 + 5 + 4*5")).equal(undefined);98 });99 it('should return undefined for "1/2 ++ 5 + 4) * 5', function () {100 should(eval.evaluateExpression("1/2 ++ 5 + 4) * 5")).equal(undefined);101 });102 it('should return undefined for [1/2] + 5 + 4 * 5', function () {103 should(eval.evaluateExpression("[1/2] + 5 + 4 * 5")).equal(undefined);104 });105 it('should return undefined for 1/2 >> 5 + 4) * 5', function () {106 should(eval.evaluateExpression("1/2 >> 5 + 4) * 5")).equal(undefined);107 });108 it('should return undefined for "1/2 + 5a + 4b * 5', function () {109 should(eval.evaluateExpression("1/2 + 5a + 4b * 5")).equal(undefined);110 });111 it('should return undefined for trololo', function () {112 should(eval.evaluateExpression("trololo")).equal(undefined);113 });114 }); ...

Full Screen

Full Screen

binops.js

Source:binops.js Github

copy

Full Screen

...14 return true;15};16const binOpForms = {17 "+": new SpecialForm((env, args) =>18 binOp((x, y) => x + y, exp => evaluateExpression(exp, env), args)19 ),20 "*": new SpecialForm((env, args) =>21 binOp((x, y) => x * y, exp => evaluateExpression(exp, env), args)22 ),23 "-": new SpecialForm((env, args) => {24 if (size(args) === 1) {25 return -evaluateExpression(head(args), env);26 }27 return binOp((x, y) => x - y, exp => evaluateExpression(exp, env), args);28 }),29 "/": new SpecialForm((env, args) =>30 binOp((x, y) => x / y, exp => evaluateExpression(exp, env), args)31 ),32 "//": new SpecialForm((env, args) =>33 binOp(34 (x, y) => Math.floor(x / y),35 exp => evaluateExpression(exp, env),36 args37 )38 ),39 "%": new SpecialForm((env, args) =>40 binOp((x, y) => x % y, exp => evaluateExpression(exp, env), args)41 ),42 pow: new SpecialForm((env, args) =>43 binOp((x, y) => Math.pow(x, y), exp => evaluateExpression(exp, env), args)44 ),45 sqrt: new SpecialForm((env, args) =>46 binOp((x, y) => Math.sqrt(x, y), exp => evaluateExpression(exp, env), args)47 ),48 max: new SpecialForm((env, args) =>49 binOp((x, y) => Math.max(x, y), exp => evaluateExpression(exp, env), args)50 ),51 min: new SpecialForm((env, args) =>52 binOp((x, y) => Math.min(x, y), exp => evaluateExpression(exp, env), args)53 ),54 ">": new SpecialForm((env, args) =>55 binCmp((x, y) => x > y, exp => evaluateExpression(exp, env), args)56 ),57 "<": new SpecialForm((env, args) =>58 binCmp((x, y) => x < y, exp => evaluateExpression(exp, env), args)59 ),60 ">=": new SpecialForm((env, args) =>61 binCmp((x, y) => x >= y, exp => evaluateExpression(exp, env), args)62 ),63 "<=": new SpecialForm((env, args) =>64 binCmp((x, y) => x <= y, exp => evaluateExpression(exp, env), args)65 ),66 "=": new SpecialForm((env, args) =>67 binCmp((x, y) => x === y, exp => evaluateExpression(exp, env), args)68 ),69 "!=": new SpecialForm((env, args) =>70 binCmp((x, y) => x !== y, exp => evaluateExpression(exp, env), args)71 ),72 or: new SpecialForm((env, args) => {73 for (const arg of args) {74 const value = evaluateExpression(arg, env);75 if (value) {76 return value;77 }78 }79 return false;80 }),81 and: new SpecialForm((env, args) => {82 for (const arg of args) {83 const value = evaluateExpression(arg, env);84 if (!value) {85 return false;86 }87 }88 return true;89 }),90 not: new SpecialForm((env, [arg]) => {91 return !evaluateExpression(arg, env);92 })93};...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require('playwright');2const path = require('path');3const fs = require('fs');4const util = require('util');5const readFile = util.promisify(fs.readFile);6const writeFile = util.promisify(fs.writeFile);7const { evaluateExpression } = require(path.join(__dirname, '../node_modules/playwright/lib/internal/evaluators/Expression.js'));8const test = async () => {9 const browser = await playwright.chromium.launch({ headless: false });10 const context = await browser.newContext();11 const page = await context.newPage();12 const result = await evaluateExpression(page, 'document.querySelector("input[name=q]").value');13 console.log(result);14 await browser.close();15};16test();17const { helper, assert } = require('./../helper');18const { JSHandle } = require('./../JSHandle');19class Expression {20 * @param {!Page} page21 * @param {string} expression22 * @param {!Array<*>} [args]23 * @param {Object=} [options]24 constructor(page, expression, args, options) {25 this._page = page;26 this._expression = expression;27 this._args = args;28 this._options = options || {};29 this._polling = 'raf';30 this._pollingInterval = 100;31 this._timeout = 30000;32 this._stack = new Error().stack;33 this._lastError = null;34 this._lastErrorPollingInterval = 100;35 this._terminated = false;36 this._contextId = null;37 this._executionContext = null;38 this._objectId = null;39 this._handle = null;40 this._lastPollingTime = 0;41 this._lastPollingValue = null;42 this._lastErrorPollingTime = 0;43 this._lastErrorPollingValue = null;44 }45 * @param {string} polling46 * @param {number} pollingInterval47 * @param {number} timeout48 * @param {string} stack49 setup(polling, pollingInterval, timeout, stack) {50 this._polling = polling;

Full Screen

Using AI Code Generation

copy

Full Screen

1const { evaluateExpression } = require('playwright/lib/server/frames');2const { Page } = require('playwright/lib/server/page');3const { Frame } = require('playwright/lib/server/frame');4const { ElementHandle } = require('playwright/lib/server/elementHandler');5const { JSHandle } = require('playwright/lib/server/jsHandle');6const { JSHandleDispatcher } = require('playwright/lib/server/supplements/dispatchers/jsHandleDispatcher');7const page = new Page();8const frame = new Frame(page, 'frameId', null);9const handle = new ElementHandle(frame, 'elementId');10const jsHandle = new JSHandle(frame, 'jsHandleId', 'elementHandle', handle);11const dispatcher = new JSHandleDispatcher(jsHandle);12const expression = 'a => a';13const isFunction = true;14const arg = dispatcher._object;15const returnByValue = false;16const awaitPromise = true;17const result = await evaluateExpression(page, expression, isFunction, [arg], returnByValue, awaitPromise);18console.log(result);19await handle.dispose();20{21 value: {22 objectId: '{"injectedScriptId":1,"id":1}'23 }24}

Full Screen

Using AI Code Generation

copy

Full Screen

1const { evaluateExpression } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');2const { context } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');3const { page } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');4const input = 'document.querySelector(\'input[name="username"]\').value';5const output = await evaluateExpression(context, page, input);6console.log(output);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { evaluateExpression } = require('@playwright/test/lib/server/frames');2const { test } = require('@playwright/test');3test('evaluate expression', async ({ page }) => {4 const title = await evaluateExpression(page.mainFrame(), 'document.title');5 console.log(title);6});

Full Screen

Using AI Code Generation

copy

Full Screen

1const {evaluateExpression} = require('playwright/lib/server/inspector');2const {Page} = require('playwright/lib/server/page');3const {JSHandle} = require('playwright/lib/server/JSHandle');4const {ElementHandle} = require('playwright/lib/server/ElementHandle');5const {Frame} = require('playwright/lib/server/frame');6const {ExecutionContext} = require('playwright/lib/server/executionContext');7const page = new Page();8const frame = new Frame(page, 'frameId', 'frameName');9const context = new ExecutionContext(frame, 'contextId');10const elementHandle = new ElementHandle(context, 'elementHandleId', 'elementHandleName');11const jsHandle = new JSHandle(context, 'jsHandleId', 'jsHandleName');12const result = evaluateExpression('expression', false, false, undefined, elementHandle);13console.log(result);14{

Full Screen

Using AI Code Generation

copy

Full Screen

1const { evaluateExpression } = require('playwright/lib/server/frames');2const frame = page.mainFrame();3const result = await evaluateExpression(frame, 'document.title');4console.log(result.value);5const { evaluateExpression } = require('playwright/lib/server/frames');6const frame = page.mainFrame();7const result = await evaluateExpression(frame, 'document.title');8console.log(result.value);9const { evaluateExpression } = require('playwright/lib/server/frames');10const frame = page.mainFrame();11const result = await evaluateExpression(frame, 'document.title');12console.log(result.value);13const { evaluateExpression } = require('playwright/lib/server/frames');14const frame = page.mainFrame();15const result = await evaluateExpression(frame, 'document.title');16console.log(result.value);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { evaluateExpression } = require('@playwright/test/lib/server/injected/injectedScript');2const result = evaluateExpression('2+2');3console.log(result);4const { evaluateExpression } = require('@playwright/test/lib/server/injected/injectedScript');5const result = evaluateExpression('2+2');6console.log(result);7const { evaluateExpression } = require('@playwright/test/lib/server/injected/injectedScript');8const result = evaluateExpression('2+2');9console.log(result);10const { evaluateExpression } = require('@playwright/test/lib/server/injected/injectedScript');11const result = evaluateExpression('2+2');12console.log(result);13const { evaluateExpression } = require('@playwright/test/lib/server/injected/injectedScript');14const result = evaluateExpression('2+2');15console.log(result);16const { evaluateExpression } = require('@playwright/test/lib/server/injected/injectedScript');17const result = evaluateExpression('2+2');18console.log(result);19const { evaluateExpression } = require('@playwright/test/lib/server/injected/injectedScript');20const result = evaluateExpression('2+2');21console.log(result);22const { evaluateExpression } = require('@playwright/test/lib/server/injected/injectedScript');23const result = evaluateExpression('2+

Full Screen

Playwright tutorial

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.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful