How to use onReturn method in root

Best JavaScript code snippet using root

script.js

Source:script.js Github

copy

Full Screen

...298}299/* BUILT-IN FUNCTIONS */ // TODO: better way to encapsulate these?300function deprecatedFunc(environment,parameters,onReturn) {301 console.log("BITSY SCRIPT WARNING: Tried to use deprecated function");302 onReturn(null);303}304function printFunc(environment, parameters, onReturn) {305 if (parameters[0] != undefined && parameters[0] != null) {306 var textStr = "" + parameters[0];307 environment.GetDialogBuffer().AddText(textStr);308 environment.GetDialogBuffer().AddScriptReturn(function() { onReturn(null); });309 }310 else {311 onReturn(null);312 }313}314function linebreakFunc(environment, parameters, onReturn) {315 // console.log("LINEBREAK FUNC");316 environment.GetDialogBuffer().AddLinebreak();317 environment.GetDialogBuffer().AddScriptReturn(function() { onReturn(null); });318}319function pagebreakFunc(environment, parameters, onReturn) {320 environment.GetDialogBuffer().AddPagebreak(function() { onReturn(null); });321}322function printDrawingFunc(environment, parameters, onReturn) {323 var drawingId = parameters[0];324 environment.GetDialogBuffer().AddDrawing(drawingId);325 environment.GetDialogBuffer().AddScriptReturn(function() { onReturn(null); });326}327function printSpriteFunc(environment,parameters,onReturn) {328 var spriteId = parameters[0];329 if(names.sprite.has(spriteId)) spriteId = names.sprite.get(spriteId); // id is actually a name330 var drawingId = sprite[spriteId].drw;331 printDrawingFunc(environment, [drawingId], onReturn);332}333function printTileFunc(environment,parameters,onReturn) {334 var tileId = parameters[0];335 if(names.tile.has(tileId)) tileId = names.tile.get(tileId); // id is actually a name336 var drawingId = tile[tileId].drw;337 printDrawingFunc(environment, [drawingId], onReturn);338}339function printItemFunc(environment,parameters,onReturn) {340 var itemId = parameters[0];341 if(names.item.has(itemId)) itemId = names.item.get(itemId); // id is actually a name342 var drawingId = item[itemId].drw;343 printDrawingFunc(environment, [drawingId], onReturn);344}345function printFontFunc(environment, parameters, onReturn) {346 var allCharacters = "";347 var font = fontManager.Get( fontName );348 var codeList = font.allCharCodes();349 for (var i = 0; i < codeList.length; i++) {350 allCharacters += String.fromCharCode(codeList[i]) + " ";351 }352 printFunc(environment, [allCharacters], onReturn);353}354function itemFunc(environment,parameters,onReturn) {355 var itemId = parameters[0];356 if (names.item.has(itemId)) {357 // id is actually a name358 itemId = names.item.get(itemId);359 }360 var curItemCount = player().inventory[itemId] ? player().inventory[itemId] : 0;361 if (parameters.length > 1) {362 // TODO : is it a good idea to force inventory to be >= 0?363 player().inventory[itemId] = Math.max(0, parseInt(parameters[1]));364 curItemCount = player().inventory[itemId];365 if (onInventoryChanged != null) {366 onInventoryChanged(itemId);367 }368 }369 onReturn(curItemCount);370}371 function addOrRemoveTextEffect(environment, name, parameters) {372 if (environment.GetDialogBuffer().HasTextEffect(name)) {373 environment.GetDialogBuffer().RemoveTextEffect(name);374 }375 else {376 environment.GetDialogBuffer().AddTextEffect(name, parameters);377 }378}379function rainbowFunc(environment,parameters,onReturn) {380 addOrRemoveTextEffect(environment,"rbw");381 onReturn(null);382}383// TODO : should the colors use a parameter instead of special names?384function color1Func(environment,parameters,onReturn) {385 addOrRemoveTextEffect(environment,"clr1");386 onReturn(null);387}388function color2Func(environment,parameters,onReturn) {389 addOrRemoveTextEffect(environment,"clr2");390 onReturn(null);391}392function color3Func(environment,parameters,onReturn) {393 addOrRemoveTextEffect(environment,"clr3");394 onReturn(null);395}396 397function colorFunc(environment,parameters,onReturn) {398 addOrRemoveTextEffect(environment, "clr", parameters[0]);399 onReturn(null);400 }401function wavyFunc(environment,parameters,onReturn) {402 addOrRemoveTextEffect(environment,"wvy");403 onReturn(null);404}405function shakyFunc(environment,parameters,onReturn) {406 addOrRemoveTextEffect(environment,"shk");407 onReturn(null);408}409function propertyFunc(environment, parameters, onReturn) {410 var outValue = null;411 if (parameters.length > 0 && parameters[0]) {412 var propertyName = parameters[0];413 if (environment.HasProperty(propertyName)) {414 // TODO : in a future update I can handle the case of initializing a new property415 // after which we can move this block outside the HasProperty check416 if (parameters.length > 1) {417 var inValue = parameters[1];418 environment.SetProperty(propertyName, inValue);419 }420 outValue = environment.GetProperty(propertyName);421 }422 }423 console.log("PROPERTY! " + propertyName + " " + outValue);424 onReturn(outValue);425}426function endFunc(environment,parameters,onReturn) {427 isEnding = true;428 isNarrating = true;429 dialogRenderer.SetCentered(true);430 onReturn(null);431}432function exitFunc(environment,parameters,onReturn) {433 var destRoom = parameters[0];434 if (names.room.has(destRoom)) {435 // it's a name, not an id! (note: these could cause trouble if people names things weird)436 destRoom = names.room.get(destRoom);437 }438 var destX = parseInt(parameters[1]);439 var destY = parseInt(parameters[2]);440 if (parameters.length >= 4) {441 var transitionEffect = parameters[3];442 transition.BeginTransition(443 player().room,444 player().x,445 player().y,446 destRoom,447 destX,448 destY,449 transitionEffect);450 transition.UpdateTransition(0);451 }452 player().room = destRoom;453 player().x = destX;454 player().y = destY;455 curRoom = destRoom;456 initRoom(curRoom);457 // TODO : this doesn't play nice with pagebreak because it thinks the dialog is finished!458 if (transition.IsTransitionActive()) {459 transition.OnTransitionComplete(function() { onReturn(null); });460 }461 else {462 onReturn(null);463 }464}465/* BUILT-IN OPERATORS */466function setExp(environment,left,right,onReturn) {467 // console.log("SET " + left.name);468 if(left.type != "variable") {469 // not a variable! return null and hope for the best D:470 onReturn( null );471 return;472 }473 right.Eval(environment,function(rVal) {474 environment.SetVariable( left.name, rVal );475 // console.log("VAL " + environment.GetVariable( left.name ) );476 left.Eval(environment,function(lVal) {477 onReturn( lVal );478 });479 });480}481function equalExp(environment,left,right,onReturn) {482 // console.log("EVAL EQUAL");483 // console.log(left);484 // console.log(right);485 right.Eval(environment,function(rVal){486 left.Eval(environment,function(lVal){487 onReturn( lVal === rVal );488 });489 });490}491function greaterExp(environment,left,right,onReturn) {492 right.Eval(environment,function(rVal){493 left.Eval(environment,function(lVal){494 onReturn( lVal > rVal );495 });496 });497}498function lessExp(environment,left,right,onReturn) {499 right.Eval(environment,function(rVal){500 left.Eval(environment,function(lVal){501 onReturn( lVal < rVal );502 });503 });504}505function greaterEqExp(environment,left,right,onReturn) {506 right.Eval(environment,function(rVal){507 left.Eval(environment,function(lVal){508 onReturn( lVal >= rVal );509 });510 });511}512function lessEqExp(environment,left,right,onReturn) {513 right.Eval(environment,function(rVal){514 left.Eval(environment,function(lVal){515 onReturn( lVal <= rVal );516 });517 });518}519function multExp(environment,left,right,onReturn) {520 right.Eval(environment,function(rVal){521 left.Eval(environment,function(lVal){522 onReturn( lVal * rVal );523 });524 });525}526function divExp(environment,left,right,onReturn) {527 right.Eval(environment,function(rVal){528 left.Eval(environment,function(lVal){529 onReturn( lVal / rVal );530 });531 });532}533function addExp(environment,left,right,onReturn) {534 right.Eval(environment,function(rVal){535 left.Eval(environment,function(lVal){536 onReturn( lVal + rVal );537 });538 });539}540function subExp(environment,left,right,onReturn) {541 right.Eval(environment,function(rVal){542 left.Eval(environment,function(lVal){543 onReturn( lVal - rVal );544 });545 });546}547/* ENVIRONMENT */548var Environment = function() {549 var dialogBuffer = null;550 this.SetDialogBuffer = function(buffer) { dialogBuffer = buffer; };551 this.GetDialogBuffer = function() { return dialogBuffer; };552 var functionMap = new Map();553 functionMap.set("print", printFunc);554 functionMap.set("say", printFunc);555 functionMap.set("br", linebreakFunc);556 functionMap.set("item", itemFunc);557 functionMap.set("rbw", rainbowFunc);558 functionMap.set("clr1", color1Func);559 functionMap.set("clr2", color2Func);560 functionMap.set("clr3", color3Func);561 functionMap.set("clr", colorFunc);562 functionMap.set("wvy", wavyFunc);563 functionMap.set("shk", shakyFunc);564 functionMap.set("printSprite", printSpriteFunc);565 functionMap.set("printTile", printTileFunc);566 functionMap.set("printItem", printItemFunc);567 functionMap.set("debugOnlyPrintFont", printFontFunc); // DEBUG ONLY568 functionMap.set("end", endFunc);569 functionMap.set("exit", exitFunc);570 functionMap.set("pg", pagebreakFunc);571 functionMap.set("property", propertyFunc);572 this.HasFunction = function(name) { return functionMap.has(name); };573 this.EvalFunction = function(name,parameters,onReturn,env) {574 if (env == undefined || env == null) {575 env = this;576 }577 functionMap.get(name)(env, parameters, onReturn);578 }579 var variableMap = new Map();580 this.HasVariable = function(name) { return variableMap.has(name); };581 this.GetVariable = function(name) { return variableMap.get(name); };582 this.SetVariable = function(name,value,useHandler) {583 // console.log("SET VARIABLE " + name + " = " + value);584 if(useHandler === undefined) useHandler = true;585 variableMap.set(name, value);586 if(onVariableChangeHandler != null && useHandler){587 onVariableChangeHandler(name);588 }589 };590 this.DeleteVariable = function(name,useHandler) {591 if(useHandler === undefined) useHandler = true;592 if(variableMap.has(name)) {593 variableMap.delete(name);594 if(onVariableChangeHandler != null && useHandler) {595 onVariableChangeHandler(name);596 }597 }598 };599 var operatorMap = new Map();600 operatorMap.set("=", setExp);601 operatorMap.set("==", equalExp);602 operatorMap.set(">", greaterExp);603 operatorMap.set("<", lessExp);604 operatorMap.set(">=", greaterEqExp);605 operatorMap.set("<=", lessEqExp);606 operatorMap.set("*", multExp);607 operatorMap.set("/", divExp);608 operatorMap.set("+", addExp);609 operatorMap.set("-", subExp);610 this.HasOperator = function(sym) { return operatorMap.get(sym); };611 this.EvalOperator = function(sym,left,right,onReturn) {612 operatorMap.get( sym )( this, left, right, onReturn );613 }614 var scriptMap = new Map();615 this.HasScript = function(name) { return scriptMap.has(name); };616 this.GetScript = function(name) { return scriptMap.get(name); };617 this.SetScript = function(name,script) { scriptMap.set(name, script); };618 var onVariableChangeHandler = null;619 this.SetOnVariableChangeHandler = function(onVariableChange) {620 onVariableChangeHandler = onVariableChange;621 }622 this.GetVariableNames = function() {623 return Array.from( variableMap.keys() );624 }625}626// Local environment for a single run of a script: knows local context627var LocalEnvironment = function(parentEnvironment) {628 // this.SetDialogBuffer // not allowed in local environment?629 this.GetDialogBuffer = function() { return parentEnvironment.GetDialogBuffer(); };630 this.HasFunction = function(name) { return parentEnvironment.HasFunction(name); };631 this.EvalFunction = function(name,parameters,onReturn,env) {632 if (env == undefined || env == null) {633 env = this;634 }635 parentEnvironment.EvalFunction(name,parameters,onReturn,env);636 }637 this.HasVariable = function(name) { return parentEnvironment.HasVariable(name); };638 this.GetVariable = function(name) { return parentEnvironment.GetVariable(name); };639 this.SetVariable = function(name,value,useHandler) { parentEnvironment.SetVariable(name,value,useHandler); };640 // this.DeleteVariable // not needed in local environment?641 this.HasOperator = function(sym) { return parentEnvironment.HasOperator(sym); };642 this.EvalOperator = function(sym,left,right,onReturn,env) {643 if (env == undefined || env == null) {644 env = this;645 }646 parentEnvironment.EvalOperator(sym,left,right,onReturn,env);647 };648 // TODO : I don't *think* any of this is required by the local environment649 // this.HasScript650 // this.GetScript651 // this.SetScript652 // TODO : pretty sure these debug methods aren't required by the local environment either653 // this.SetOnVariableChangeHandler654 // this.GetVariableNames655 /* Here's where specific local context data goes:656 * this includes access to the object running the script657 * and any properties it may have (so far only "locked")658 */659 // The local environment knows what object called it -- currently only used to access properties660 var curObject = null;661 this.HasObject = function() { return curObject != undefined && curObject != null; }662 this.SetObject = function(object) { curObject = object; }663 this.GetObject = function() { return curObject; }664 // accessors for properties of the object that's running the script665 this.HasProperty = function(name) {666 if (curObject && curObject.property && curObject.property.hasOwnProperty(name)) {667 return true;668 }669 else {670 return false;671 }672 };673 this.GetProperty = function(name) {674 if (curObject && curObject.property && curObject.property.hasOwnProperty(name)) {675 return curObject.property[name]; // TODO : should these be getters and setters instead?676 }677 else {678 return null;679 }680 };681 this.SetProperty = function(name, value) {682 // NOTE : for now, we need to gaurd against creating new properties683 if (curObject && curObject.property && curObject.property.hasOwnProperty(name)) {684 curObject.property[name] = value;685 }686 };687}688function leadingWhitespace(depth) {689 var str = "";690 for(var i = 0; i < depth; i++) {691 str += " "; // two spaces per indent692 }693 // console.log("WHITESPACE " + depth + " ::" + str + "::");694 return str;695}696/* NODES */697var TreeRelationship = function() {698 this.parent = null;699 this.children = [];700 this.AddChild = function(node) {701 this.children.push(node);702 node.parent = this;703 };704 this.AddChildren = function(nodeList) {705 for (var i = 0; i < nodeList.length; i++) {706 this.AddChild(nodeList[i]);707 }708 };709 this.SetChildren = function(nodeList) {710 this.children = [];711 this.AddChildren(nodeList);712 };713 this.VisitAll = function(visitor, depth) {714 if (depth == undefined || depth == null) {715 depth = 0;716 }717 visitor.Visit(this, depth);718 for (var i = 0; i < this.children.length; i++) {719 this.children[i].VisitAll( visitor, depth + 1 );720 }721 };722 this.rootId = null; // for debugging723 this.GetId = function() {724 // console.log(this);725 if (this.rootId != null) {726 return this.rootId;727 }728 else if (this.parent != null) {729 var parentId = this.parent.GetId();730 if (parentId != null) {731 return parentId + "_" + this.parent.children.indexOf(this);732 }733 }734 else {735 return null;736 }737 }738}739var DialogBlockNode = function(doIndentFirstLine) {740 Object.assign( this, new TreeRelationship() );741 // Object.assign( this, new Runnable() );742 this.type = "dialog_block";743 this.Eval = function(environment, onReturn) {744 // console.log("EVAL BLOCK " + this.children.length);745 if (isPlayerEmbeddedInEditor && events != undefined && events != null) {746 events.Raise("script_node_enter", { id: this.GetId() });747 }748 var lastVal = null;749 var i = 0;750 function evalChildren(children, done) {751 if (i < children.length) {752 // console.log(">> CHILD " + i);753 children[i].Eval(environment, function(val) {754 // console.log("<< CHILD " + i);755 lastVal = val;756 i++;757 evalChildren(children,done);758 });759 }760 else {761 done();762 }763 };764 var self = this;765 evalChildren(this.children, function() {766 if (isPlayerEmbeddedInEditor && events != undefined && events != null) {767 events.Raise("script_node_exit", { id: self.GetId() });768 }769 onReturn(lastVal);770 });771 }772 if (doIndentFirstLine === undefined) {773 doIndentFirstLine = true; // This is just for serialization774 }775 this.Serialize = function(depth) {776 if (depth === undefined) {777 depth = 0;778 }779 var str = "";780 var lastNode = null;781 for (var i = 0; i < this.children.length; i++) {782 var curNode = this.children[i];783 var curNodeIsNonInlineCode = curNode.type === "code_block" && !isInlineCode(curNode);784 var prevNodeIsNonInlineCode = lastNode && lastNode.type === "code_block" && !isInlineCode(lastNode);785 var shouldIndentFirstLine = (i == 0 && doIndentFirstLine);786 var shouldIndentAfterLinebreak = (lastNode && lastNode.type === "function" && lastNode.name === "br");787 var shouldIndentCodeBlock = i > 0 && curNodeIsNonInlineCode;788 var shouldIndentAfterCodeBlock = prevNodeIsNonInlineCode;789 // need to insert a newline before the first block of non-inline code that isn't 790 // preceded by a {br}, since those will create their own newline791 if (i > 0 && curNodeIsNonInlineCode && !prevNodeIsNonInlineCode && !shouldIndentAfterLinebreak) {792 str += "\n";793 }794 if (shouldIndentFirstLine || shouldIndentAfterLinebreak || shouldIndentCodeBlock || shouldIndentAfterCodeBlock) {795 str += leadingWhitespace(depth);796 }797 str += curNode.Serialize(depth);798 if (i < this.children.length-1 && curNodeIsNonInlineCode) {799 str += "\n";800 }801 lastNode = curNode;802 }803 return str;804 }805 this.ToString = function() {806 return this.type + " " + this.GetId();807 };808}809var CodeBlockNode = function() {810 Object.assign( this, new TreeRelationship() );811 this.type = "code_block";812 this.Eval = function(environment, onReturn) {813 // console.log("EVAL BLOCK " + this.children.length);814 if (isPlayerEmbeddedInEditor && events != undefined && events != null) {815 events.Raise("script_node_enter", { id: this.GetId() });816 }817 var lastVal = null;818 var i = 0;819 function evalChildren(children, done) {820 if (i < children.length) {821 // console.log(">> CHILD " + i);822 children[i].Eval(environment, function(val) {823 // console.log("<< CHILD " + i);824 lastVal = val;825 i++;826 evalChildren(children,done);827 });828 }829 else {830 done();831 }832 };833 var self = this;834 evalChildren(this.children, function() {835 if (isPlayerEmbeddedInEditor && events != undefined && events != null) {836 events.Raise("script_node_exit", { id: self.GetId() });837 }838 onReturn(lastVal);839 });840 }841 this.Serialize = function(depth) {842 if(depth === undefined) {843 depth = 0;844 }845 // console.log("SERIALIZE BLOCK!!!");846 // console.log(depth);847 // console.log(doIndentFirstLine);848 var str = "{"; // todo: increase scope of Sym?849 // TODO : do code blocks ever have more than one child anymore????850 for (var i = 0; i < this.children.length; i++) {851 var curNode = this.children[i];852 str += curNode.Serialize(depth);853 }854 str += "}";855 return str;856 }857 this.ToString = function() {858 return this.type + " " + this.GetId();859 };860}861function isInlineCode(node) {862 return isTextEffectBlock(node) || isUndefinedBlock(node) || isMultilineListBlock(node);863}864function isUndefinedBlock(node) {865 return node.type === "code_block" && node.children.length > 0 && node.children[0].type === "undefined";866}867var textEffectBlockNames = ["clr1", "clr2", "clr3", "clr", "wvy", "shk", "rbw", "printSprite", "printItem", "printTile", "print", "say", "br"];868function isTextEffectBlock(node) {869 if (node.type === "code_block") {870 if (node.children.length > 0 && node.children[0].type === "function") {871 var func = node.children[0];872 return textEffectBlockNames.indexOf(func.name) != -1;873 }874 }875 return false;876}877var listBlockTypes = ["sequence", "cycle", "shuffle", "if"];878function isMultilineListBlock(node) {879 if (node.type === "code_block") {880 if (node.children.length > 0) {881 var child = node.children[0];882 return listBlockTypes.indexOf(child.type) != -1;883 }884 }885 return false;886}887// for round-tripping undefined code through the parser (useful for hacks!)888var UndefinedNode = function(sourceStr) {889 Object.assign(this, new TreeRelationship());890 this.type = "undefined";891 this.source = sourceStr;892 this.Eval = function(environment,onReturn) {893 addOrRemoveTextEffect(environment, "_debug_highlight");894 printFunc(environment, ["{" + sourceStr + "}"], function() {895 onReturn(null);896 });897 addOrRemoveTextEffect(environment, "_debug_highlight");898 }899 this.Serialize = function(depth) {900 return this.source;901 }902 this.ToString = function() {903 return "undefined" + " " + this.GetId();904 }905}906var FuncNode = function(name,args) {907 Object.assign( this, new TreeRelationship() );908 // Object.assign( this, new Runnable() );909 this.type = "function";910 this.name = name;911 this.args = args;912 this.Eval = function(environment,onReturn) {913 if (isPlayerEmbeddedInEditor && events != undefined && events != null) {914 events.Raise("script_node_enter", { id: this.GetId() });915 }916 var self = this; // hack to deal with scope (TODO : move up higher?)917 var argumentValues = [];918 var i = 0;919 function evalArgs(args, done) {920 // TODO : really hacky way to make we get the first921 // symbol's NAME instead of its variable value922 // if we are trying to do something with a property923 if (self.name === "property" && i === 0 && i < args.length) {924 if (args[i].type === "variable") {925 argumentValues.push(args[i].name);926 i++;927 }928 else {929 // first argument for a property MUST be a variable symbol930 // -- so skip everything if it's not!931 i = args.length;932 }933 }934 if (i < args.length) {935 // Evaluate each argument936 args[i].Eval(937 environment,938 function(val) {939 argumentValues.push(val);940 i++;941 evalArgs(args, done);942 });943 }944 else {945 done();946 }947 };948 evalArgs(949 this.args,950 function() {951 if (isPlayerEmbeddedInEditor && events != undefined && events != null) {952 events.Raise("script_node_exit", { id: self.GetId() });953 }954 environment.EvalFunction(self.name, argumentValues, onReturn);955 });956 }957 this.Serialize = function(depth) {958 var isDialogBlock = this.parent.type === "dialog_block";959 if (isDialogBlock && this.name === "print") {960 // TODO this could cause problems with "real" print functions961 return this.args[0].value; // first argument should be the text of the {print} func962 }963 else if (isDialogBlock && this.name === "br") {964 return "\n";965 }966 else {967 var str = "";968 str += this.name;969 for(var i = 0; i < this.args.length; i++) {970 str += " ";971 str += this.args[i].Serialize(depth);972 }973 return str;974 }975 }976 this.ToString = function() {977 return this.type + " " + this.name + " " + this.GetId();978 };979}980var LiteralNode = function(value) {981 Object.assign( this, new TreeRelationship() );982 // Object.assign( this, new Runnable() );983 this.type = "literal";984 this.value = value;985 this.Eval = function(environment,onReturn) {986 onReturn(this.value);987 }988 this.Serialize = function(depth) {989 var str = "";990 if (this.value === null) {991 return str;992 }993 if (typeof this.value === "string") {994 str += '"';995 }996 str += this.value;997 if (typeof this.value === "string") {998 str += '"';999 }1000 return str;1001 }1002 this.ToString = function() {1003 return this.type + " " + this.value + " " + this.GetId();1004 };1005}1006var VarNode = function(name) {1007 Object.assign( this, new TreeRelationship() );1008 // Object.assign( this, new Runnable() );1009 this.type = "variable";1010 this.name = name;1011 this.Eval = function(environment,onReturn) {1012 // console.log("EVAL " + this.name + " " + environment.HasVariable(this.name) + " " + environment.GetVariable(this.name));1013 if( environment.HasVariable(this.name) )1014 onReturn( environment.GetVariable( this.name ) );1015 else1016 onReturn(null); // not a valid variable -- return null and hope that's ok1017 } // TODO: might want to store nodes in the variableMap instead of values???1018 this.Serialize = function(depth) {1019 var str = "" + this.name;1020 return str;1021 }1022 this.ToString = function() {1023 return this.type + " " + this.name + " " + this.GetId();1024 };1025}1026var ExpNode = function(operator, left, right) {1027 Object.assign( this, new TreeRelationship() );1028 this.type = "operator";1029 this.operator = operator;1030 this.left = left;1031 this.right = right;1032 this.Eval = function(environment,onReturn) {1033 // console.log("EVAL " + this.operator);1034 var self = this; // hack to deal with scope1035 environment.EvalOperator( this.operator, this.left, this.right, 1036 function(val){1037 // console.log("EVAL EXP " + self.operator + " " + val);1038 onReturn(val);1039 } );1040 // NOTE : sadly this pushes a lot of complexity down onto the actual operator methods1041 }1042 this.Serialize = function(depth) {1043 var isNegativeNumber = this.operator === "-" && this.left.type === "literal" && this.left.value === null;1044 if (!isNegativeNumber) {1045 var str = "";1046 if (this.left != undefined && this.left != null) {1047 str += this.left.Serialize(depth) + " ";1048 }1049 str += this.operator;1050 if (this.right != undefined && this.right != null) {1051 str += " " + this.right.Serialize(depth);1052 }1053 return str;1054 }1055 else {1056 return this.operator + this.right.Serialize(depth); // hacky but seems to work1057 }1058 }1059 this.VisitAll = function(visitor, depth) {1060 if (depth == undefined || depth == null) {1061 depth = 0;1062 }1063 visitor.Visit( this, depth );1064 if(this.left != null)1065 this.left.VisitAll( visitor, depth + 1 );1066 if(this.right != null)1067 this.right.VisitAll( visitor, depth + 1 );1068 };1069 this.ToString = function() {1070 return this.type + " " + this.operator + " " + this.GetId();1071 };1072}1073var SequenceBase = function() {1074 this.Serialize = function(depth) {1075 var str = "";1076 str += this.type + "\n";1077 for (var i = 0; i < this.children.length; i++) {1078 str += leadingWhitespace(depth + 1) + Sym.List + " ";1079 str += this.children[i].Serialize(depth + 2);1080 str += "\n";1081 }1082 str += leadingWhitespace(depth);1083 return str;1084 }1085 this.VisitAll = function(visitor, depth) {1086 if (depth == undefined || depth == null) {1087 depth = 0;1088 }1089 visitor.Visit(this, depth);1090 for (var i = 0; i < this.children.length; i++) {1091 this.children[i].VisitAll( visitor, depth + 1 );1092 }1093 };1094 this.ToString = function() {1095 return this.type + " " + this.GetId();1096 };1097}1098var SequenceNode = function(options) {1099 Object.assign(this, new TreeRelationship());1100 Object.assign(this, new SequenceBase());1101 this.type = "sequence";1102 this.AddChildren(options);1103 var index = 0;1104 this.Eval = function(environment, onReturn) {1105 // console.log("SEQUENCE " + index);1106 this.children[index].Eval(environment, onReturn);1107 var next = index + 1;1108 if (next < this.children.length) {1109 index = next;1110 }1111 }1112}1113var CycleNode = function(options) {1114 Object.assign(this, new TreeRelationship());1115 Object.assign(this, new SequenceBase());1116 this.type = "cycle";1117 this.AddChildren(options);1118 var index = 0;1119 this.Eval = function(environment, onReturn) {1120 // console.log("CYCLE " + index);1121 this.children[index].Eval(environment, onReturn);1122 var next = index + 1;1123 if (next < this.children.length) {1124 index = next;1125 }1126 else {1127 index = 0;1128 }1129 }1130}1131var ShuffleNode = function(options) {1132 Object.assign(this, new TreeRelationship());1133 Object.assign(this, new SequenceBase());1134 this.type = "shuffle";1135 this.AddChildren(options);1136 var optionsShuffled = [];1137 function shuffle(options) {1138 optionsShuffled = [];1139 var optionsUnshuffled = options.slice();1140 while (optionsUnshuffled.length > 0) {1141 var i = Math.floor(Math.random() * optionsUnshuffled.length);1142 optionsShuffled.push(optionsUnshuffled.splice(i,1)[0]);1143 }1144 }1145 shuffle(this.children);1146 var index = 0;1147 this.Eval = function(environment, onReturn) {1148 optionsShuffled[index].Eval(environment, onReturn);1149 1150 index++;1151 if (index >= this.children.length) {1152 shuffle(this.children);1153 index = 0;1154 }1155 }1156}1157// TODO : rename? ConditionalNode?1158var IfNode = function(conditions, results, isSingleLine) {1159 Object.assign(this, new TreeRelationship());1160 this.type = "if";1161 for (var i = 0; i < conditions.length; i++) {1162 this.AddChild(new ConditionPairNode(conditions[i], results[i]));1163 }1164 var self = this;1165 this.Eval = function(environment, onReturn) {1166 // console.log("EVAL IF");1167 var i = 0;1168 function TestCondition() {1169 self.children[i].Eval(environment, function(result) {1170 if (result.conditionValue == true) {1171 onReturn(result.resultValue);1172 }1173 else if (i+1 < self.children.length) {1174 i++;1175 TestCondition();1176 }1177 else {1178 onReturn(null);1179 }1180 });1181 };1182 TestCondition();1183 }1184 if (isSingleLine === undefined) {1185 isSingleLine = false; // This is just for serialization1186 }1187 this.Serialize = function(depth) {1188 var str = "";1189 if(isSingleLine) {1190 // HACKY - should I even keep this mode???1191 str += this.children[0].children[0].Serialize() + " ? " + this.children[0].children[1].Serialize();1192 if (this.children.length > 1 && this.children[1].children[0].type === Sym.Else) {1193 str += " " + Sym.ElseExp + " " + this.children[1].children[1].Serialize();1194 }1195 }1196 else {1197 str += "\n";1198 for (var i = 0; i < this.children.length; i++) {1199 str += this.children[i].Serialize(depth);1200 }1201 str += leadingWhitespace(depth);1202 }1203 return str;1204 }1205 this.IsSingleLine = function() {1206 return isSingleLine;1207 }1208 this.VisitAll = function(visitor, depth) {1209 if (depth == undefined || depth == null) {1210 depth = 0;1211 }1212 visitor.Visit(this, depth);1213 for (var i = 0; i < this.children.length; i++) {1214 this.children[i].VisitAll(visitor, depth + 1);1215 }1216 };1217 this.ToString = function() {1218 return this.type + " " + this.mode + " " + this.GetId();1219 };1220}1221var ConditionPairNode = function(condition, result) {1222 Object.assign(this, new TreeRelationship());1223 this.type = "condition_pair";1224 this.AddChild(condition);1225 this.AddChild(result);1226 var self = this;1227 this.Eval = function(environment, onReturn) {1228 self.children[0].Eval(environment, function(conditionSuccess) {1229 if (conditionSuccess) {1230 self.children[1].Eval(environment, function(resultValue) {1231 onReturn({ conditionValue:true, resultValue:resultValue });1232 });1233 }1234 else {1235 onReturn({ conditionValue:false });1236 }1237 });1238 }1239 this.Serialize = function(depth) {1240 var str = "";1241 str += leadingWhitespace(depth + 1);1242 str += Sym.List + " " + this.children[0].Serialize(depth) + " " + Sym.ConditionEnd + Sym.Linebreak;1243 str += this.children[1].Serialize(depth + 2) + Sym.Linebreak;1244 return str;1245 }1246 this.VisitAll = function(visitor, depth) {1247 if (depth == undefined || depth == null) {1248 depth = 0;1249 }1250 visitor.Visit(this, depth);1251 for (var i = 0; i < this.children.length; i++) {1252 this.children[i].VisitAll(visitor, depth + 1);1253 }1254 }1255 this.ToString = function() {1256 return this.type + " " + this.GetId();1257 }1258}1259var ElseNode = function() {1260 Object.assign( this, new TreeRelationship() );1261 this.type = Sym.Else;1262 this.Eval = function(environment, onReturn) {1263 onReturn(true);1264 }1265 this.Serialize = function() {1266 return Sym.Else;1267 }1268 this.ToString = function() {1269 return this.type + " " + this.mode + " " + this.GetId();1270 };1271}1272var Sym = {1273 DialogOpen : '"""',1274 DialogClose : '"""',1275 CodeOpen : "{",1276 CodeClose : "}",1277 Linebreak : "\n", // just call it "break" ?...

Full Screen

Full Screen

terminal.ts

Source:terminal.ts Github

copy

Full Screen

...19}20function exeuteFile(file: string, args?: string[]) {21 return executeToObservable((onReturn) =>22 execFile(file, args, (err, out, stderr) => {23 onReturn({ err, out, stderr }, true);24 })25 );26}27function executeToObservable(execteableCaller: (_: resultFunction) => {}) {28 return createObservable((p: any) => {29 const producer = {30 next: p.next,31 error: p.error,32 complete: p.complete ? p.complete : () => {},33 };34 execteableCaller(({ out, err, stderr }, isComplete) => {35 if (isComplete) {36 producer.complete("");37 }38 if (!hasError(err)) {39 producer.next({ out, stderr: stderr ? stderr : "" });40 return;41 }42 when(hasError(err || stderr), () => producer.error(err || stderr));43 });44 });45}46export function newTabExecute(commands: string[]) {47 const scriptLine = commands48 .map((v) => {49 return `do script "${v}"`;50 })51 .join("\n");52 const command = `osascript <<EOF53 tell app "Terminal"54 ${scriptLine}55 end tell 56EOF`;57 return execute(command);58}59function exeuteOnStdout(onReturn: resultFunction, data: string) {60 onReturn({61 out: data.toString(),62 });63}64function exeuteOnStderr(onReturn: resultFunction, data: string) {65 onReturn({66 out: data.toString(),67 });68}69function exeuteOnClose(onReturn: resultFunction, code: number) {70 if (code != 0) {71 console.warn("close code :", code);72 }73 onReturn(74 {75 out: "",76 stderr: "",77 },78 true79 );80}81function executeOnError(onReturn: resultFunction, err: Error) {82 onReturn(83 {84 err,85 out: "",86 stderr: "",87 },88 true89 );90}91export function executeSpawnShell(actionHandle: spawnShellAction) {92 return executeToObservable((onReturn): any => {93 const sp = spawn("bash");94 sp.stdout.on("data", (data) => exeuteOnStdout(onReturn, data));95 sp.stderr.on("data", (data) => exeuteOnStderr(onReturn, data));96 sp.on("close", (code: number) => exeuteOnClose(onReturn, code));97 sp.on("error", (err) => executeOnError(onReturn, err));98 actionHandle(sp);99 sp.stdin.end();100 });101}102export function execute(command: string) {103 return executeToObservable((onReturn): any => {104 exec(command, (err, out, stderr) => {105 onReturn({ err, out, stderr }, true);106 });107 });108}109function openOnWithApp(appPath: string, filePath: string) {110 return execute(`open -a ${appPath} ${filePath}`);111}112function openOnFolder(dir: string) {113 return execute(`open ${dir}`);114}115const Terminal = {116 openOnWithApp,117 openOnFolder,118 execute,119 exeuteFile,...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import {View, Text, TouchableOpacity} from 'react-native';3import {Navigation} from 'react-native-navigation';4class TestScreen extends React.Component {5 constructor(props) {6 super(props);7 }8 render() {9 return (10 <View style={{flex: 1, justifyContent: 'center'}}>11 style={{alignSelf: 'center'}}12 onPress={() => {13 Navigation.dismissModal(this.props.componentId);14 }}>15 );16 }17}18export default TestScreen;

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from "react";2import ReactDOM from "react-dom";3import PropTypes from "prop-types";4class TestComponent extends React.Component {5 constructor(props) {6 super(props);7 this.state = {8 };9 this.handleInputChange = this.handleInputChange.bind(this);10 this.handleSubmit = this.handleSubmit.bind(this);11 }12 handleInputChange(event) {13 this.setState({ value: event.target.value });14 }15 handleSubmit() {16 this.props.onReturn(this.state.value);17 this.setState({ show: false });18 }19 render() {20 return (21 <button onClick={() => this.setState({ show: true })}>22 {this.state.show ? (23 style={{24 backgroundColor: "rgba(0,0,0,0.5)"25 }}26 style={{27 }}28 value={this.state.value}29 onChange={this.handleInputChange}30 <button onClick={this.handleSubmit}>Submit</button>31 ) : null}32 );33 }34}35TestComponent.propTypes = {36};37export default TestComponent;

Full Screen

Using AI Code Generation

copy

Full Screen

1function onReturn() {2 console.log("onReturn called");3}4function onReturn() {5 this.$parent.onReturn();6}

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run root 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