How to use markBegin method in Playwright Internal

Best JavaScript code snippet using playwright-internal

com.bydust.ajax.js

Source:com.bydust.ajax.js Github

copy

Full Screen

1function Delegate() {}2Delegate.create = function (o, f) {3 var a = new Array() ;4 var l = arguments.length ;5 for(var i = 2 ; i < l ; i++) a[i - 2] = arguments[i] ;6 return function() {7 var aP = [].concat(arguments, a) ;8 f.apply(o, aP);9 }10}1112// Tween core13Tween = function(obj, prop, func, begin, finish, duration, suffixe){this.init(obj, prop, func, begin, finish, duration, suffixe)}14var t = Tween.prototype;15t.obj = new Object();16t.prop='';17t.func = function (t, b, c, d) {return c*t/d + b;};18t.begin = 0;19t.change = 0;20t.prevTime = 0;21t.prevPos = 0;22t.looping = false;23t._duration = 0;24t._time = 0;25t._pos = 0;26t._position = 0;27t._startTime = 0;28t._finish = 0;29t.name = '';30t.suffixe = '';31t._listeners = new Array(); 32t.setTime = function(t){this.prevTime = this._time;if (t > this.getDuration()) {if (this.looping) {this.rewind (t - this._duration);this.update();this.broadcastMessage('onMotionLooped',{target:this,type:'onMotionLooped'});} else {this._time = this._duration;this.update();this.stop();this.broadcastMessage('onMotionFinished',{target:this,type:'onMotionFinished'});}} else if (t < 0) {this.rewind();this.update();} else {this._time = t;this.update();}} 33t.getTime = function(){return this._time;} 34t.setDuration = function(d){this._duration = (d == null || d <= 0) ? 100000 : d;} 35t.getDuration = function(){return this._duration;} 36t.setPosition = function(p){this.prevPos = this._pos;var a = this.suffixe != '' ? this.suffixe : '';this.obj[this.prop] = Math.round(p) + a;this._pos = p;this.broadcastMessage('onMotionChanged',{target:this,type:'onMotionChanged'});} 37t.getPosition = function(t){if (t == undefined) t = this._time;return this.func(t, this.begin, this.change, this._duration);}; 38t.setFinish = function(f){this.change = f - this.begin;}; 39t.geFinish = function(){return this.begin + this.change;}; 40t.init = function(obj, prop, func, begin, finish, duration, suffixe){if (!arguments.length) return;this._listeners = new Array();this.addListener(this);if(suffixe) this.suffixe = suffixe;this.obj = obj;this.prop = prop;this.begin = begin;this._pos = begin;this.setDuration(duration);if (func!=null && func!='') {this.func = func;}this.setFinish(finish);} 41t.start = function(){this.rewind();this.startEnterFrame();this.broadcastMessage('onMotionStarted',{target:this,type:'onMotionStarted'});} 42t.rewind = function(t){this.stop();this._time = (t == undefined) ? 0 : t;this.fixTime();this.update();} 43t.fforward = function(){this._time = this._duration;this.fixTime();this.update();} 44t.update = function(){this.setPosition(this.getPosition(this._time));} 45t.startEnterFrame = function(){this.stopEnterFrame();this.isPlaying = true;this.onEnterFrame();} 46t.onEnterFrame = function(){if(this.isPlaying) {this.nextFrame();setTimeout(Delegate.create(this, this.onEnterFrame), 0);}} 47t.nextFrame = function(){this.setTime((this.getTimer() - this._startTime) / 1000);} 48t.stop = function(){this.stopEnterFrame();this.broadcastMessage('onMotionStopped',{target:this,type:'onMotionStopped'});} 49t.stopEnterFrame = function(){this.isPlaying = false;} 50t.continueTo = function(finish, duration){this.begin = this._pos;this.setFinish(finish);if (this._duration != undefined) this.setDuration(duration);this.start();} 51t.resume = function(){this.fixTime();this.startEnterFrame();this.broadcastMessage('onMotionResumed',{target:this,type:'onMotionResumed'});} 52t.yoyo = function (){this.continueTo(this.begin,this._time);} 53t.addListener = function(o){this.removeListener (o);return this._listeners.push(o);} 54t.removeListener = function(o){var a = this._listeners;var i = a.length;while (i--) {if (a[i] == o) {a.splice (i, 1);return true;}}return false;} 55t.broadcastMessage = function(){var arr = new Array();for(var i = 0; i < arguments.length; i++){arr.push(arguments[i])}var e = arr.shift();var a = this._listeners;var l = a.length;for (var i=0; i<l; i++){if(a[i][e]) a[i][e].apply(a[i], arr);}}56t.fixTime = function(){this._startTime = this.getTimer() - this._time * 1000;} 57t.getTimer = function(){return new Date().getTime() - this._time;}5859// Tween types60Tween.backEaseIn = function(t,b,c,d,a,p){if (s == undefined) var s = 1.70158;return c*(t/=d)*t*((s+1)*t - s) + b;} 61Tween.backEaseOut = function(t,b,c,d,a,p){if (s == undefined) var s = 1.70158;return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;} 62Tween.backEaseInOut = function(t,b,c,d,a,p){if (s == undefined) var s = 1.70158;if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;} 63Tween.elasticEaseIn = function(t,b,c,d,a,p){if (t==0) return b;if ((t/=d)==1) return b+c;if (!p) p=d*.3;if (!a || a < Math.abs(c)) {a=c;var s=p/4;} else var s = p/(2*Math.PI) * Math.asin (c/a);return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;} 64Tween.elasticEaseOut = function (t,b,c,d,a,p){if (t==0) return b;if ((t/=d)==1) return b+c;if (!p) p=d*.3;if (!a || a < Math.abs(c)) {a=c;var s=p/4;} else var s = p/(2*Math.PI) * Math.asin (c/a);return (a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b);} 65Tween.elasticEaseInOut = function (t,b,c,d,a,p){if (t==0) return b;if ((t/=d/2)==2) return b+c;if (!p) var p=d*(.3*1.5);if (!a || a < Math.abs(c)) {var a=c;var s=p/4;} else var s = p/(2*Math.PI) * Math.asin (c/a);if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;} 66Tween.bounceEaseOut = function(t,b,c,d){if ((t/=d) < (1/2.75)) {return c*(7.5625*t*t) + b;} else if (t < (2/2.75)) {return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;} else if (t < (2.5/2.75)) {return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;} else {return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;}} 67Tween.bounceEaseIn = function(t,b,c,d){return c - Tween.bounceEaseOut (d-t, 0, c, d) + b;} 68Tween.bounceEaseInOut = function(t,b,c,d){if (t < d/2) return Tween.bounceEaseIn (t*2, 0, c, d) * .5 + b; else return Tween.bounceEaseOut (t*2-d, 0, c, d) * .5 + c*.5 + b;} 69Tween.strongEaseInOut = function(t,b,c,d){return c*(t/=d)*t*t*t*t + b;} 70Tween.regularEaseIn = function(t,b,c,d){return c*(t/=d)*t + b;} 71Tween.regularEaseOut = function(t,b,c,d){return -c *(t/=d)*(t-2) + b;} 72Tween.regularEaseInOut = function(t,b,c,d){if ((t/=d/2) < 1) return c/2*t*t + b;return -c/2 * ((--t)*(t-2) - 1) + b;}73Tween.strongEaseIn = function(t,b,c,d){return c*(t/=d)*t*t*t*t + b;}74Tween.strongEaseOut = function(t,b,c,d){return c*((t=t/d-1)*t*t*t*t + 1) + b;}75Tween.strongEaseInOut = function(t,b,c,d){if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;return c/2*((t-=2)*t*t*t*t + 2) + b;}76 77// Tween opacity 78OpacityTween.prototype = new Tween();OpacityTween.prototype.constructor = Tween;OpacityTween.superclass = Tween.prototype;function OpacityTween(obj,func,fromOpacity,toOpacity,duration){this.targetObject = obj;this.init(new Object(),'x',func,fromOpacity,toOpacity,duration);}var o = OpacityTween.prototype;o.targetObject = {};.onMotionChanged = function(evt){var v = evt.target._pos;var t = this.targetObject;t.style['opacity'] = v / 100;t.style['-moz-opacity'] = v / 100;if(t.filters) t.filters.alpha['opacity'] = v;}7980var bda = {81 ajaxURL : null,82 calculateText : 'Parsing images and other content...',83 currentLoad : 0,84 denyFormRules : Array(),85 denyURLRules : Array(),86 disallowedExt : new Array('zip','rar','jpg','png','jpeg','gif','bmp','tar','iso','img','exe','rss','pdf','ai','psd','txt','dwt'),87 debugMode : 'off',88 debugLog : document.createElement('ol'),89 errorText : '<h1>The page could not be found</h1><p>The page or data you requested could not be retrieved from the server. The server could be down or you could have a problem with your internet connection.</p>',90 eventListeners : new Array(),91 externalLocation : "<h1>External location</h1><p>I can't parse content from the retrieved data.<br/>The page you requested will open in a new window, and you will <a href='javascript:history.go(-1);'>return to the previous page</a> shortly.<p>",92 externalLocationClick : '<p>Click here to open the requested page in a new window: [link]</p>',93 externalLocationTimeout : 5,94 fullDomain : '',95 historyCurrentLocation : '',96 historyCurrentID : '',97 imagesLoaded : new Array(),98 imageLoadTimeout : 20,99 imagesNotLoadedText : 'Some images could not be loaded.<br/>The page will display without these images.',100 isActive : true,101 isLoading : false,102 isIE : false,103 loadText : 'Loading...',104 lastOutput : null,105 notifyRules : Array(),106 pageContent : '',107 primaryRegion : null,108 primaryId : '',109 primaryTween : null,110 secondaryRegions : Array(),111 secondaryIds : Array(),112 transitionTweenType: Tween.regularEaseOut,113 transitionAlpha : true,114 transitionInProgress : false,115 116 start : function(regions){117 if(this.debugMode.indexOf('list') > -1){118 this.debugLog.setAttribute('id','bda_debugLog');119 document.body.appendChild(this.debugLog);120 }121 122 if(navigator.appName.indexOf('Internet Explorer') != -1) this.isIE = true;123 124 if(this.getHTTPRequest()){125 if(regions == 'undefined' && this.regions.length == 0){126 alert('No regions set to refresh!');127 }else{128 for(var i = 0; i < regions.length; i++){129 if(regions[i].substr(0,1) == '!'){130 this.primaryRegion = bd$(regions[i].substr(1));131 this.primaryId = regions[i].substr(1);132 }else{133 this.secondaryRegions.push(bd$(regions[i]));134 this.secondaryIds.push(regions[i]);135 }136 }137 if(this.primaryRegion == null){138 alert('Please define the primary content region by putting an "!" in front of the id');139 }else{140 this.fixDOMObject(document);141 this.setContent(this.primaryRegion.innerHTML);142 this.primaryTween = new Tween(this.primaryRegion.style,'height',this.transitionTweenType,parseInt(this.primaryRegion.offsetHeight),parseInt(this.primaryRegion.offsetHeight),1,'px');143 this.primaryTween.onMotionFinished = function(){bda.triggerEventListeners('tween_complete',{});bda.transitionInProgress = false;};144 this.primaryRegion.style.overflow = 'hidden';145 this.fullDomain = this.getDomain(this.getLocationAsString());146 this.historyCurrentLocation = this.getLocationAsString().split('#')[0];147 this.historyListener();148 }149 }150 }else{151 this.isActive = false;152 }153 },154 addEventListener : function(e, eventHandler){155 /*156 * Adds custom eventhandlers, works crossbrowser157 * 158 * parameters: e ('error','load_begin','load_complete','tween_begin','tween_complete','state_changed'), eventHandler (Function)159 * returns: nothing160 */161 if(!this.eventListeners[e]) this.eventListeners[e] = new Array();162 this.eventListeners[e].push(eventHandler);163 },164 triggerEventListeners : function(e,parameters){165 /*166 * Triggers custom eventhandlers, works crossbrowser167 * 168 * parameters: e (Event), parameters(Array)169 * returns: nothing170 */171 if(!this.eventListeners[e]) return;172 var f_parameters = new Array();173 for(var i in parameters) f_parameters.push(i + ":parameters['" + i + "']");174 for(var eventHandler = 0; eventHandler < this.eventListeners[e].length; eventHandler++){175 var f = this.eventListeners[e][eventHandler] + '({' + f_parameters.join(',') + '});';176 eval(f);177 }178 },179 ajaxRequest : function(url, parameters, requesttype, onlyNotify, urlToLoadWhenReady) {180 if(!url){181 if(bda.ajaxURL) {182 if(http_request.readyState != 4) return;183 url = bda.ajaxURL;184 bda.ajaxURL = null;185 }else return;186 }187 clearInterval(bda.currentLoad);188 if(!onlyNotify){189 onlyNotify = false;190 bda.isLoading = true;191 }192 if(!parameters) parameters = '';193 if(urlToLoadWhenReady) bda.ajaxURL = urlToLoadWhenReady;194 if(!('GET,get,POST,post'.contains(requesttype))) requesttype = 'GET';195 if(requesttype == 'GET' && parameters && parameters.length > 2) url += url.contains('?')?'&' + parameters:'?' + parameters;196 197 if(bda.debugMode.indexOf('nocache') > -1) url += url.contains('?')?'&bda_debug_random=' + Math.random():'?bda_debug_random=' + Math.random();198 if(url != bda.historyCurrentLocation && !onlyNotify){199 document.location = bda.getLocationAsString().split('#')[0] + '#/' + url.substr(bda.fullDomain.length);200 bda.historyCurrentLocation = url;201 bda.historyCurrentID = (new Date()).getTime();202 }203 bda.triggerEventListeners('load_begin',{url:url, parameters:parameters, requesttype:requesttype});204 http_request = false;205 bda.getHTTPRequest();206 http_request.url = url;207 http_request.open(requesttype, url, true);208 http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");209 http_request.setRequestHeader("Content-length", parameters.length);210 http_request.setRequestHeader("Connection", "close");211 if(!onlyNotify) http_request.onreadystatechange = bda.ajaxReady;212 http_request.send(parameters);213 },214 ajaxReady : function() {215 try{216 if (http_request.readyState == 4) {217 if (http_request.status == 200) {218 bda.isLoading = false;219 bda.pageContent = http_request.responseText;220 bda.preloadImages(bda.pageContent);221 } else {222 bda.setState('error',http_request.status);223 bda.triggerEventListeners('error',{url:bda.historyCurrentLocation, bda_function:'ajaxReady', message:'Could not load page ' + bda.historyCurrentLocation});224 }225 }226 }catch(e){bda.debug('ajaxReady had a little error.');}227 },228 allowForLink : function(url){229 if(!url) return false;230 for(var i = 0; i < this.denyURLRules.length; i++) if(eval(this.denyURLRules[i])) return false;231 if(url.contains('bda_ignore')) return false;232 return true;233 },234 allowForForm : function(action){235 for(var i = 0; i < this.denyFormRules.length; i++) if(eval(this.denyFormRules[i])) return false;236 if(action.contains('bda_ignore')) return false;237 return true;238 },239 debug : function(){240 if(this.debugMode == 'off') return;241 var time = new Date();242 var t = time.getHours() + ':' + time.getMinutes() + ':' + time.getSeconds() + ':' + time.getMilliseconds();243 var jsa = 'DEBUG:';244 var lst = t+ ' :: ';245 for (var i = 0; i < arguments.length; i++) {246 jsa += '\n ' + arguments[i];247 lst += arguments[i] + '<br/>';248 }249 if(this.debugMode.indexOf('alert') > -1) alert(jsa);250 if(this.debugMode.indexOf('list') > -1){251 var l = document.createElement('li');252 l.innerHTML = lst + String.fromCharCode(10);253 this.debugLog.appendChild(l);254 }255 try{256 if((this.debugMode.indexOf('console') > -1)) console.info(t,arguments);257 }catch(e){};258 },259 debugClear : function(){260 while(this.debugLog.childNodes.length > 0){261 this.debugLog.removeChild(this.debugLog.firstChild);262 }263 },264 fixDOMObject : function(obj){265 /*266 * Changes links and forms in a DOM-object so they would use our ajax-script.267 * 268 * parameters: DOM-object269 * returns: nothing270 */271 var links = obj.getElementsByTagName('a');272 var forms = obj.getElementsByTagName('form');273 var loc = this.getDomain(this.getLocationAsString());274 275 // links276 for(var i = 0; i<links.length; i++){277 var currentLink = links[i];278 var currentAllowExt = (this.disallowedExt.indexOf(this.getFileExt(currentLink.href)) == -1)?true:false;279 var currentDomain = this.getDomain(currentLink.href);280 var currentAllow = this.allowForLink(currentLink.href);281 282 //this.debug('currentLink: ' + currentLink, 'currentAllow: ' + currentAllow, 'currentAllowedExt: ' + currentAllowExt, 'currentDomain: ' + currentDomain);283284 if(currentLink.href.indexOf('bda_ignore') == -1 && currentLink.className.indexOf('bda_ignore') == -1){285 if((currentLink.href != '') && (currentLink.href != null) && currentAllow && currentAllowExt && (loc == currentDomain)){286 if(this.isIE) currentLink.setAttribute('href',"javascript:bda.getURL('" + currentLink.href + "');");287 else currentLink.setAttribute('onclick','bda.getURL(this.href); return false;');288 }else if((loc != currentDomain) || !currentAllowExt){289 currentLink.target = '_blank';290 }else if(currentLink.href.substr(0,1) == '#'){291 currentLink.removeAttribute('href');292 }293 }294 }295 296 //forms297 for(var i = 0; i < forms.length; i++){298 var currentForm = forms[i];299 var currentAllow = this.allowForForm(currentForm.action);300 if((currentForm.action != null) && (currentForm.action != '') && currentAllow){301 if(currentForm.id == null || currentForm.id == '') currentForm.id = 'bda_' + i;302 currentForm.setAttribute('onsubmit',"bda.postForm(this); return false;");303 }304 }305 },306 fixStringObject : function(str){307 /*308 * Changes links and forms in a String-object so they would use our ajax-script.309 * 310 * parameters: String311 * returns: String312 */313 var input = str.replace('<A ','<a ').replace('<FORM ','<form ').replace('<IMG ','<img ');314 var loc = this.getDomain(this.getLocationAsString());315 var output = '';316 317 // links318 while(input.indexOf('<a ') > -1){319 var markBegin = input.indexOf('<a ');320 var markEnd = input.substr(markBegin).indexOf('>') + markBegin;321 322 var currentLink = input.substring(markBegin,markEnd + 1);323 var currentHref = this.getStringTagAttribute(currentLink,'href');324 var currentAllowExt = (this.disallowedExt.indexOf(this.getFileExt(currentHref)) == -1)?true:false;325 var currentDomain = this.getDomain(currentHref);326 var currentAllow = this.allowForLink(currentHref);327 328 //this.debug('currentLink: ' + currentLink, 'currentAllow: ' + currentAllow, 'currentAllowedExt: ' + currentAllowExt, 'currentDomain: ' + currentDomain);329 if(currentLink.indexOf('bda_ignore') == -1){330 if((currentHref != null) && currentAllow && currentAllowExt && (loc == currentDomain)){331 currentLink = this.setStringTagAttribute(currentLink,'onclick','bda.getURL(this.href); return false;');332 //currentLink = this.fixStringLink(currentLink);333 }else if((loc != currentDomain) || !currentAllowExt){334 currentLink = this.setStringTagAttribute(currentLink,'target','_blank',false);335 }else if(currentHref.substr(0,1) == '#'){336 currentLink = this.removeStringTagAttribute(currentLink,'href');337 }338 }339 340 output += input.substring(0,markBegin);341 output += currentLink;342 input = input.substr(markEnd + 1);343 }344 output += input;345 346 //forms347 input = output;348 output = '';349 while(input.indexOf('<form ') > -1){350 var markBegin = input.indexOf('<form ');351 var markEnd = input.substr(markBegin).indexOf('>') + markBegin;352 353 var currentForm = input.substring(markBegin,markEnd + 1);354 var currentAction = this.getStringTagAttribute(currentForm,'action');355 var currentId = this.getStringTagAttribute(currentForm,'id');356 var currentAllow = (currentAction != null)?this.allowForForm(currentAction):false;357 var currentDomain = this.getDomain(currentAction);358359 360 //this.debug('currentAllow: ' + currentAllow, 'currentAction: ' + currentAction, 'currentDomain: ' + currentDomain);361 362 if(currentAllow){363 if(currentId == null) currentForm = this.setStringTagAttribute(currentForm,'id','bda_' + markBegin);364 //currentForm = this.setStringTagAttribute(currentForm,'onsubmit',"bda.postForm(this.action,this.id); return false;");365 currentForm = this.setStringTagAttribute(currentForm,'onsubmit',"bda.postForm(this); return false;");366 }367 368 output += input.substring(0,markBegin);369 output += currentForm;370 input = input.substr(markEnd + 1);371 }372 output += input;373 374 //images375 input = output;376 output = '';377 while(input.contains('<img ')){378 var markBegin = input.indexOf('<img ');379 var markEnd = input.substr(markBegin).indexOf('>') + markBegin;380 381 var currentImage = input.substring(markBegin,markEnd + 1);382 var currentSource = this.getAbsoluteURL(this.getCurrentLocation(), this.getStringTagAttribute(currentImage,'src'));383 var currentWidth = this.getStringTagAttribute(currentImage,'width');384 var currentHeight = this.getStringTagAttribute(currentImage,'height');385 var currentRes = this.getImageResolution(currentSource);386 387 if(currentRes.width == 0 || currentRes.height == 0) currentRes = this.getImageResolution(currentSource);388 389 //this.debug('currentImage: ' + currentImage, 'currentSource: ' + currentSource, 'currentWidth: ' + currentWidth, 'currentHeight: ' + currentHeight, 'objectWidth: ' + currentRes.width, 'objectHeight: ' + currentRes.height);390 391 if(currentWidth == null && currentHeight == null){392 currentImage = this.setStringTagAttribute(currentImage,'width',currentRes.width);393 currentImage = this.setStringTagAttribute(currentImage,'height',currentRes.height);394 }else if(currentWidth == null && currentHeight != null){395 currentImage = this.setStringTagAttribute(currentImage,'width',Math.round(currentRes.width*(currentHeight/currentRes.height)));396 }else if(currentWidth != null && currentHeight == null){397 currentImage = this.setStringTagAttribute(currentImage,'height',Math.round(currentRes.height*(currentWidth/currentRes.width)));398 }399 400 output += input.substring(0,markBegin);401 output += currentImage;402 input = input.substr(markEnd + 1);403 }404 output += input;405 406 return output;407 },408 historyListener : function(){409 /*410 * Handles browser history changes411 * 412 * parameters: nothing413 * returns: nothing414 */415 var hl = setInterval(function(){416 if(bda.getCurrentLocation() != bda.historyCurrentLocation && !bda.getCurrentLocation().contains('#')) {417 bda.getURL(bda.getCurrentLocation());418 }419 },500);420 },421 get : function(url, parameters){422 /*423 * Orders a "GET" request with the given url and parameters424 * 425 * parameters: url(String), parameters(Array)426 * returns: nothing427 */428 if(parameters == 'undefined' || parameters == null) parameters = '';429 this.ajaxRequest(url,parameters,'GET');430 },431 getChildElements : function(obj){432 /*433 * Returns an array of ALL ( children of children included ) child elements of a DOM-object434 * 435 * parameters: DOM-object436 * returns: Array with DOM-elements437 */438 var elements = Array();439 if(obj != null){440 for(var e = 0; e < obj.childNodes.length; e++){441 if(obj[e] != null){442 elements.push(obj[e]);443 elements.join(this.getChildElements(obj[e]));444 }445 }446 }447 return elements;448 },449 getCurrentLocation : function(){450 /*451 * Returns the raw URL of our current location452 * 453 * parameters: nothing454 * returns: String455 */456 var after = this.getLocationAsString().split('#')[1];457 if(this.getLocationAsString().indexOf('#') != -1 && (after.substr(0,1) == '/' || after.substr(0,1) == '?')){458 return this.fullDomain + this.getLocationAsString().split('#')[1].substr(1);459 }else{460 return this.getLocationAsString();461 }462 },463 getDomain : function(url){464 /*465 * Returns the domain of a given url, for example "bydust.com"466 * If it can't find a valid domain in the given url, it'll return the current domain467 * 468 * parameters: url(String)469 * returns: domain(String)470 */471 if(!url) return 'http://www.unknowndomain.com/';472 var domain = url.split('/');473 if(domain[0].substr(domain[0].length - 1, 1) == ':' && domain[1] == ''){474 return domain[0] + '//' + domain[2] + '/';475 }else{476 return this.getDomain(this.getLocationAsString());477 }478 },479 getLocationAsString : function(){480 /*481 * Returns the document.location482 * 483 * parameters: nothing484 * returns: location(String)485 */486 try{487 //document.write('<br/>start getLocationAsString');488 var loc = '' + document.location;489 //document.write('<br/>end getLocationAsString');490 return loc;491 }catch(e){492 alert('exception catched in bda.getLocationAsString. \n error: ' + e.description);493 //document.write('catch getLocationAsString');494 }495 },496 getFileExt : function(file){497 /*498 * Returns the extension of a given filename499 * If there's no valid extension, it'll return "unknown"500 * 501 * parameters: filename (String)502 * returns: extension (String)503 */504 if(!file) return 'unknown';505 var ext = file.toLowerCase().split('/').pop()506 if(ext.indexOf('.') == -1) return 'unknown';507 ext = ext.split('.').pop();508 ext = ext.split('?').shift();509 ext = ext.split('#').shift();510 if(ext == '') ext = 'unknown';511 return ext;512 },513 getHTTPRequest : function(){514 /*515 * Creates a new HTTP-request in the http_request object516 * 517 * parameters: nothing518 * returns: nothing519 */520 try{521 if (window.XMLHttpRequest) {522 http_request = new XMLHttpRequest();523 if (http_request.overrideMimeType) http_request.overrideMimeType('text/html');524 } else if (window.ActiveXObject) {525 try {526 http_request = new ActiveXObject("Msxml2.XMLHTTP");527 } catch (e) {528 //document.write('catched');529 try {530 http_request = new ActiveXObject("Microsoft.XMLHTTP");531 } catch (e) {}532 }533 }534 if (!http_request) return false;535 else return true;536 }catch(e){537 return false;538 }539 },540 getImageResolution : function(url){541 /*542 * Returns an image object containing the image width and height543 * 544 * parameters: url (String)545 * returns: Image-object ( obj.height, obj.width )546 */547 // werkt alleen als image ingeladen is 548 var newImg = new Image();549 newImg.src = url;550 return newImg;551 },552 getURL : function(url){553 /*554 * Requests a given url555 * 556 * parameters: url (String)557 * returns: nothing558 */559 this.setState('loading');560 var fixedurl = url.split('#')[0];561 if(fixedurl.indexOf('://') == -1) fixedurl = this.getAbsoluteURL(this.getCurrentLocation(), fixedurl);562 this.get(fixedurl,'');563 },564 getAbsoluteURL : function(url_rel_from, url_rel_to){565 /*566 * Calculates an absolute url for a relative url. Needs current location and relative link.567 * If given an absolute link as the relative link parameter, the absolute link will be returned.568 * 569 * parameters: current location (String), (relative) link (String)570 * returns: absolute link (String)571 */572 if(!url_rel_to) return url_rel_from;573 if(!url_rel_from) return url_rel_to;574 var rf = url_rel_from.split('/');575 var rt = url_rel_to.split('/');576 if(url_rel_to.indexOf('://') > 2 && url_rel_to.indexOf('://') < 7) return url_rel_to;577 if(url_rel_to.substr(0,1) == '/') return this.fullDomain + url_rel_to.substr(1);578 if(url_rel_from.substr(url_rel_from.length - 1) != '/') rf.pop();579 for(var i = 0; i < rt.length; i++) if(rt[i] == '..') rf.pop();580 return rf.join('/') + '/' + rt.join('/'); 581 },582 getStringTagAttribute : function(tag,attribute){583 /*584 * Returns the value of the requested attribute in a tag(String)585 * Returns null if the attribute isn't there or if its an empty value586 * 587 * parameters: tag (String), attribute (String)588 * returns: value (String)589 */590 if(tag.indexOf(attribute + '=') == -1) return null;591 592 var markBegin = tag.indexOf(attribute + '=');593 var quotetype = tag.substr(markBegin + attribute.length + 1,1);594 var markEnd = tag.substr(markBegin + attribute.length + 2).indexOf(quotetype) + markBegin + attribute.length + 3;595 var value = tag.substring(markBegin + attribute.length + 2, markEnd - 1);596 return (value != '')?value:null;597 },598 getTitle : function(content){599 /*600 * Returns the content document title601 * 602 * parameters: content (String)603 * returns: title (String)604 */605 content = content.replace('<TITLE>','<title>').replace('</TITLE>','</title>');606 var markBegin = content.indexOf('<title>');607 var markEnd = content.substr(markBegin + 7).indexOf('</title>') + markBegin + 7;608 return content.substring(markBegin + 7,markEnd);609 },610 outputPage : function(content){611 /*612 * Inserts the new content in the page, fires the load_complete event and plays animations613 * 614 * parameters: content (String)615 * returns: nothing616 */617 618 //this.debug('Images loaded on output: ' + this.imagesLoaded.dump());619 if(content == null) content = this.pageContent;620 //primary621 var primary = content.substring(content.indexOf('<!-- begin ' + this.primaryId + ' -->'),content.indexOf('<!-- end ' + this.primaryId + ' -->'));622 var primaryContent = this.fixStringObject(primary);623 624 //errorcatching625 if(primary.length == 0){626 this.setState('error_location');627 window.open(this.historyCurrentLocation);628 this.triggerEventListeners('error',{url:this.historyCurrentLocation, message:'The received data could not be parsed. Most likely another website.', bda_function:'outputPage'});629 setTimeout('history.go(-1)',this.externalLocationTimeout*1000);630 return;631 }632 633 //secondary634 for(var i = 0; i < this.secondaryRegions.length; i++){635 var secondary = content.substring(content.indexOf('<!-- begin ' + this.secondaryIds[i] + ' -->'),content.indexOf('<!-- end ' + this.secondaryIds[i] + ' -->'));636 this.secondaryRegions[i].innerHTML = this.fixStringObject(secondary);637 }638 this.setTitle(this.getTitle(content));639 this.setContent(primaryContent.toSource());640 this.resetTransitionHeight();641 this.triggerEventListeners('load_complete',{url:this.historyCurrentLocation, content:content});642 },643 post : function(action,parameters){644 /*645 * Orders a "POST"-request for the given url and parameters646 * 647 * parameters: url (String), parameters(Array)648 * returns: nothing649 */650 var onlyNotify = false;651 for(var i = 0; i < this.notifyRules.length; i++) if(eval(this.notifyRules[i])) onlyNotify = true;652 this.ajaxRequest(action, parameters, 'POST', onlyNotify, (onlyNotify)?this.historyCurrentLocation:null);653 },654 postForm : function(form, state){655 /*656 * Posts a form to a given url, and sets the documents state657 * 658 * parameters: form (DOM-Object), state (String)(optional)659 * returns: nothing660 */661 //this.debug('postForm ' + url + ',' + form + ',' + state);662 if(this.isActive){663 var elements = form.elements;//this.getChildElements(form);664 var url = form.action;665 var content = '';666 bda.debug(elements);667 for(var i = 0; i < elements.length; i++){668 var e = elements[i];669 var t = e.tagName.toLowerCase();670 var n = (e.name)?e.name:e.id;671 bda.debug(e,n,e.value);672 if(t == 'input' && (e.type == 'text' || e.type == 'password' || e.type == 'hidden' || (e.checked && (e.type == 'checkbox' || e.type == 'radio')) )) content += n + "=" + e.value + "&";673 if(t == 'textarea') content += n + '=' + escape(e.value) + '&';674 if(t == 'select') content += n + "=" + e.options[e.selectedIndex].value + "&";675 if(t == 'input' && e.type == 'file'){676 form.onsubmit = null;677 form.submit();678 return false;679 }680 }681 if(form.method && form.method.toLowerCase() == 'get'){682 this.get(url,content);683 }else{684 this.post(url,content);685 }686 if(state != null) this.setState(state);687 else this.setState('loading');688 }else{689 form.submit();690 }691 },692 preloadImages : function(content){693 this.setState('calculating');694 var input = content.replace('<IMG ','<img ');695 this.imagesLoaded = Array();696 this.currentLoad = setInterval(function(){697 clearInterval(bda.currentLoad); 698 bda.setState('error_images');699 setTimeout('bda.outputPage()',4000);700 },this.imageLoadTimeout*1000);701702 while(input.contains('<img ')){703 var markBegin = input.indexOf('<img ');704 var markEnd = input.substr(markBegin).indexOf('>') + markBegin;705 var currentImage = input.substring(markBegin,markEnd + 1);706 var currentSource = this.getAbsoluteURL(this.getCurrentLocation(), this.getStringTagAttribute(currentImage,'src'));707 708 if(!this.imagesLoaded.getKeys().contains(currentSource)){709 this.imagesLoaded.set(currentSource, false);710 this.preloadImage(currentSource);711 }712 713 input = input.substr(markEnd + 1);714 }715 716 //this.debug(this.imagesLoaded.dump());717 718 if(this.imagesLoaded.size() == 0){719 clearInterval(this.currentLoad);720 this.outputPage();721 }722 },723 preloadImage : function(url){724 var newImg = new Image();725 newImg.onload = function(){726 bda.imagesLoaded.set(url,true);727 //bda.debug('onload ' + this.src + ' : ' + bda.imagesLoaded.dump());728 for(var i in bda.imagesLoaded) if(!bda.imagesLoaded.get(i)) return false;729 clearInterval(bda.currentLoad);730 bda.outputPage();731 this.onload = null;732 };733 newImg.src = url;734 },735 fixStringLink : function(str){736 /*737 * Applies the ajax-link to a given string738 * 739 * parameters: link (String)740 * returns: link (String)741 */742 var markBegin = str.indexOf('href=');743 var quotetype = str.substr(markBegin + 5,1);744 var markEnd = str.substr(markBegin + 6).indexOf(quotetype) + markBegin + 7;745 var href = str.substring(markBegin + 6, markEnd - 1);746 var output = str.substring(0,markBegin + 6);747 var jsquotetype = "'";748 if(quotetype == "'") jsquotetype = '"';749 output += 'javascript:bda.getURL(' + jsquotetype + href + jsquotetype + ');' + str.substr(markEnd - 1);750 return output;751 },752 removeStringTagAttribute : function(tag,attribute){753 /*754 * Removes an attribute from a string tag755 * 756 * parameters: tag (String), attribute (String)757 * returns: tag (String)758 */759 tag = tag.replace(attribute.toUpperCase() + '=',attribute.toLowerCase() + '=');760 var markBegin = tag.indexOf(attribute + '=');761 var quotetype = tag.substr(markBegin + attribute.length + 1,1);762 var markEnd = tag.substr(markBegin + attribute.length + 2).indexOf(quotetype) + markBegin + attribute.length + 3;763 return tag.substring(0,markBegin) + tag.substr(markEnd);764 },765 resetTransitionHeight : function(){766 this.transitionHeight(bd$('bda_content').offsetHeight);767 },768 setContent : function(content){769 /*770 * Inserts the primary content into the page771 * 772 * parameters: content (String)773 * returns: nothing774 */775 this.primaryRegion.innerHTML = '<div id="bda_content">' + content + '</div>';776 },777 setState : function(state,parameters){778 /*779 * Sets the document state780 * 781 * parameters: state (String), parameters (Object)782 * returns: nothing783 */784 this.triggerEventListeners('stage_changed',{state:state, parameters:parameters});785 var output = '';786 switch(state){787 case 'loading':788 output += this.loadText;789 this.isLoading = true;790 alerta791 break;792 case 'calculating':793 output += this.calculateText;794 break;795 case 'error':796 output += this.errorText;797 break;798 case 'error_images':799 output += this.imagesNotLoadedText;800 break;801 case 'error_location':802 output += this.externalLocation + '<br/>' + this.externalLocationClick.replace('[link]','<a href="' + this.historyCurrentLocation + '" target="_blank">open window</a><br/><br/><br/><br/>');803 break;804 default:805 output += state;806 break;807 }808 if(parameters != null && parameters != 'undefined') output += '<br/>' + parameters;809 this.setContent(output);810 this.transitionHeight(bd$('bda_content').offsetHeight);811 },812 setStringTagAttribute : function(tag,attribute,value,overwrite){813 /*814 * Sets an attribute for a string tag815 * 816 * parameters: tag (String), attribute (String), value (String), overwrite (Boolean)817 * returns: tag (String)818 */819 if(overwrite == null) overwrite = true;820 var output = '';821 tag = tag.replace(attribute.toUpperCase() + '=',attribute.toLowerCase() + '=');822 if(tag.contains(' ' + attribute + '=') && overwrite){823 var markBegin = tag.indexOf(' ' + attribute + '=');824 var quotetype = tag.substr(markBegin + attribute.length + 2,1);825 var markEnd = tag.substr(markBegin + attribute.length + 3).indexOf(quotetype) + markBegin + attribute.length + 4;826 output = tag.substr(0,markBegin + attribute.length + 3) + value + tag.substr(markEnd - 1);827 }else if(!tag.contains(attribute + '=')){828 var tagpart = tag.split(' ')[0];829 output = tagpart + ' ' + attribute + '="' + value + '" ' + tag.substr(tagpart.length);830 }else if(tag.contains(' ' + attribute + '=') && !overwrite){831 output = tag;832 }833 return output;834 },835 setTitle : function(title){836 /*837 * Sets the document title838 * 839 * parameters: title (String)840 * returns: nothing841 */842 document.title = title;843 },844 transitionHeight : function(to){845 /*846 * Tweens the primary contents height to the given height847 * 848 * parameters: to (Number)849 * returns: nothing850 */851 852 if(this.transitionInProgress) return;853 if(to < 100) to = 100;854 this.triggerEventListeners('tween_begin',{tween_to:to});855 if(!this.isLoading) this.transitionInProgress = true;856 this.primaryTween.continueTo(parseInt(to),1);857 if(!this.isIE && this.transitionAlpha){858 var opacity_tween = new OpacityTween(this.primaryRegion,this.transitionTweenType, 0,100,1);859 opacity_tween.start();860 861 }862 }863}864var http_request = false;865866function bd$(id){return document.getElementById(id);}867868// Adding String.contains method. Easier if a user wants to add rules.869if(!String.contains){870 String.prototype.contains = function(obj){871 return (this.indexOf(obj) == -1)?false:true;872 } ...

Full Screen

Full Screen

bindings.js

Source:bindings.js Github

copy

Full Screen

...45 },46 'ctrl+a': function() {47 this.markClear(true);48 this.move.beginOfFile(null, true);49 this.markBegin();50 this.move.endOfFile(null, true);51 this.markSet();52 },53 'ctrl+shift+up': function() {54 if (!this.mark.active) {55 this.buffer.moveAreaByLines(-1, { begin: this.caret.pos, end: this.caret.pos });56 this.move.byLines(-1, true);57 } else {58 this.buffer.moveAreaByLines(-1, this.mark.get());59 this.mark.shiftByLines(-1);60 this.move.byLines(-1, true);61 }62 },63 'ctrl+shift+down': function() {64 if (!this.mark.active) {65 this.buffer.moveAreaByLines(+1, { begin: this.caret.pos, end: this.caret.pos });66 this.move.byLines(+1, true);67 } else {68 this.buffer.moveAreaByLines(+1, this.mark.get());69 this.mark.shiftByLines(+1);70 this.move.byLines(+1, true);71 }72 },73 'enter': function() {74 this.insert('\n');75 },76 'backspace': function() {77 this.backspace();78 },79 'delete': function() {80 this.delete();81 },82 'ctrl+backspace': function() {83 if (this.move.isBeginOfFile()) return;84 this.markClear(true);85 this.markBegin();86 this.move.byWord(-1, true);87 this.markSet();88 this.delete();89 },90 'shift+ctrl+backspace': function() {91 this.markClear(true);92 this.markBegin();93 this.move.beginOfLine(null, true);94 this.markSet();95 this.delete();96 },97 'ctrl+delete': function() {98 if (this.move.isEndOfFile()) return;99 this.markClear(true);100 this.markBegin();101 this.move.byWord(+1, true);102 this.markSet();103 this.backspace();104 },105 'shift+ctrl+delete': function() {106 this.markClear(true);107 this.markBegin();108 this.move.endOfLine(null, true);109 this.markSet();110 this.backspace();111 },112 'shift+delete': function() {113 this.markClear(true);114 this.move.beginOfLine(null, true);115 this.markBegin();116 this.move.endOfLine(null, true);117 this.move.byChars(+1, true);118 this.markSet();119 this.backspace();120 },121 'shift+ctrl+d': function() {122 this.markBegin(false);123 var add = 0;124 var area = this.mark.get();125 var lines = area.end.y - area.begin.y;126 if (lines && area.end.x > 0) add += 1;127 if (!lines) add += 1;128 lines += add;129 var text = this.buffer.getAreaText(area.setLeft(0).addBottom(add));130 this.buffer.insert({ x: 0, y: area.end.y }, text);131 this.mark.shiftByLines(lines);132 this.move.byLines(lines, true);133 },134 'shift+ctrl+up': function() {135 this.markBegin(false);136 var area = this.mark.get();137 if (this.buffer.moveAreaByLines(-1, area)) {138 this.mark.shiftByLines(-1);139 this.move.byLines(-1, true);140 }141 },142 'shift+ctrl+down': function() {143 this.markBegin(false);144 var area = this.mark.get();145 if (this.buffer.moveAreaByLines(+1, area)) {146 this.mark.shiftByLines(+1);147 this.move.byLines(+1, true);148 }149 },150 'tab': function() {151 var res = this.suggest();152 if (!res) {153 this.insert(this.tab);154 } else {155 this.markSetArea(res.area);156 this.insert(res.node.value);157 }158 },159 'ctrl+f': function() {160 this.find.open();161 },162 'f3': function() {163 this.findJump(+1);164 },165 'shift+f3': function() {166 this.findJump(-1);167 },168 'ctrl+/': function() {169 var add;170 var area;171 var text;172 var clear = false;173 var caret = this.caret.copy();174 if (!this.mark.active) {175 clear = true;176 this.markClear();177 this.move.beginOfLine(null, true);178 this.markBegin();179 this.move.endOfLine(null, true);180 this.markSet();181 area = this.mark.get();182 text = this.buffer.getArea(area);183 } else {184 area = this.mark.get();185 this.mark.addBottom(area.end.x > 0).setLeft(0);186 text = this.buffer.getArea(this.mark.get());187 }188 //TODO: should check if last line has // also189 if (text.trimLeft().substr(0,2) === '//') {190 add = -3;191 text = text.replace(/^(.*?)\/\/ (.+)/gm, '$1$2');192 } else {193 add = +3;194 text = text.replace(/^([\s]*)(.+)/gm, '$1// $2');195 }196 this.insert(text);197 this.mark.set(area.addRight(add));198 this.mark.active = !clear;199 if (caret.x) caret.addRight(add);200 this.setCaret(caret);201 if (clear) {202 this.markClear();203 }204 },205 'shift+ctrl+/': function() {206 var clear = false;207 var add = 0;208 if (!this.mark.active) clear = true;209 var caret = this.caret.copy();210 this.markBegin(false);211 var area = this.mark.get();212 var text = this.buffer.getArea(area);213 if (text.slice(0,2) === '/*' && text.slice(-2) === '*/') {214 text = text.slice(2,-2);215 add -= 2;216 if (area.end.y === area.begin.y) add -= 2;217 } else {218 text = '/*' + text + '*/';219 add += 2;220 if (area.end.y === area.begin.y) add += 2;221 }222 this.insert(text);223 area.end.x += add;224 this.mark.set(area);225 this.mark.active = !clear;226 this.setCaret(caret.addRight(add));227 if (clear) {228 this.markClear();229 }230 },231};232keys.single = {233 //234};235// selection keys236[ 'home','end',237 'pageup','pagedown',238 'left','up','right','down',239 'ctrl+left','ctrl+right'240].forEach(function(key) {241 keys['shift+'+key] = function(e) {242 this.markBegin();243 keys[key].call(this, e);244 this.markSet();245 };...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1/**2 koa-logger2 - index.js3 (c) 2014 Tomasz Rojek (http://tomrosystems.com/)4 MIT licensed5*/6'use strict';7exports = module.exports = function main(format) {8 var frmt = (format) || 'day/month time ip "method url protocol/httpVer" status size "referer" "userAgent" duration ms';9 var r = 'var outStream = process.stdout;\n'10+ 'return {\n'11+ ' gen: function* (next) {try {' + compile(frmt) + '} catch(e) {console.log(e.stack)}},\n'12+ ' setStream: function (s) { outStream = s; return this; }\n'13+ '}';14 return new Function(r)();15}16// here we are constructing generator function based on format17function compile(fmt) {18 var res = {19 beg: '', // TODO: consider remembering stream in temporary variable ...20 // here goes yield21 end: '' // ... and use it here22 }23 var tokens = {24 '\\n': function(){ return "'\\n'"; } // actually this one is not used25 ,ip: function(){ return 'this.ip'; }26 ,method: function(){ return 'this.method'; }27 ,url: function(){ return 'this.url'; }28 ,status: function(){ return 'this.status'; }29 ,httpVer: function(){ return 'this.req.httpVersion'; }30 ,protocol: function(){ return 'this.protocol.toUpperCase()'; }31 ,size: function(){ return "(this.length || '-')"; }32 ,referer: function(){ return "(this.header['referer'] || '-')"; }33 ,userAgent: function(){ return "(this.header['user-agent'] || '-')"; }34 // === date formating35 ,day: function(){36 if (!this.markBegin) {37 this.markBegin = true;38 this.beg += 'var startAt = new Date();\n';39 }40 return "( startAt.getDate() < 10 ? '0' : '' ) + startAt.getDate()";41 }42 ,month: function(){43 if (!this.markBegin) {44 this.markBegin = true;45 this.beg += 'var startAt = new Date();\n';46 }47 return 'startAt.toString().slice(4,7)'; // short string representation48 }49 ,year: function(){50 if (!this.markBegin) {51 this.markBegin = true;52 this.beg += 'var startAt = new Date();\n';53 }54 return 'startAt.getFullYear()';55 }56 ,hour: function(r){57 if (!this.markBegin) {58 this.markBegin = true;59 this.beg += 'var startAt = new Date();\n';60 }61 return "( startAt.getHours() < 10 ? '0' : '' ) + startAt.getHours()";62 }63 ,time: function(){64 if (!this.markBegin) {65 this.markBegin = true;66 this.beg += 'var startAt = new Date();\n';67 }68 return "startAt.toTimeString().slice(0, 8)";69 }70 ,zone: function(){ // this one highly depends on v8 extension71 if (!this.markBegin) {72 this.markBegin = true;73 this.beg += 'var startAt = new Date();\n';74 }75 return "startAt.toTimeString().slice(12, 17)";76 }77 // extension78 ,duration: function(r){79 if (!this.markBegin) {80 this.markBegin = true;81 this.beg += 'var startAt = new Date();\n';82 }83 if (!this.markEnd) {84 this.markEnd = true;85 this.end += 'var endAt = new Date();\n';86 }87 return "( endAt.getTime() - startAt.getTime() )";88 }89 // custom one90 ,"custom\\[(\\w.+)\\]": function(m, p1, offset, str){91 return "(this." + p1 + " || '-')";92 }93 }94 // build one regular expression from above tokens95 var all = Object.keys(tokens).map(function(it){ return '(?:' + it + ')' }).join('|');96 var reg = new RegExp(all, 'g');97 function which(token){ // maybe there's some better way to do this?98 for(var x in tokens) if (token.match(x)) return x;99 throw 'No pattern found';100 }101 var b = fmt.replace(reg, function(m, p1, offset){102 var t = which(m);103 var r = tokens[t].apply(res, arguments);104 if (r) return "' + " + r + " + '";105 return '';106 });107 res.end += "\noutStream.write('" + b + "\\n');";108 return res.beg + 'yield next;\n' + res.end;...

Full Screen

Full Screen

stability.js

Source:stability.js Github

copy

Full Screen

1'use strict';2// Build stability table to documentation.html/json/md by generated all.json3const fs = require('fs');4const path = require('path');5const unified = require('unified');6const raw = require('rehype-raw');7const markdown = require('remark-parse');8const htmlStringify = require('rehype-stringify');9const gfm = require('remark-gfm');10const remark2rehype = require('remark-rehype');11const visit = require('unist-util-visit');12const source = `${__dirname}/../../out/doc/api`;13const data = require(path.join(source, 'all.json'));14const markBegin = '<!-- STABILITY_OVERVIEW_SLOT_BEGIN -->';15const markEnd = '<!-- STABILITY_OVERVIEW_SLOT_END -->';16const mark = `${markBegin}(.*)${markEnd}`;17const output = {18 json: path.join(source, 'stability.json'),19 docHTML: path.join(source, 'documentation.html'),20 docJSON: path.join(source, 'documentation.json'),21 docMarkdown: path.join(source, 'documentation.md'),22};23function collectStability(data) {24 const stability = [];25 for (const mod of data.modules) {26 if (mod.displayName && mod.stability >= 0) {27 const link = mod.source.replace('doc/api/', '').replace('.md', '.html');28 stability.push({29 api: mod.name,30 link: link,31 stability: mod.stability,32 stabilityText: `(${mod.stability}) ${mod.stabilityText}`,33 });34 }35 }36 stability.sort((a, b) => a.api.localeCompare(b.api));37 return stability;38}39function createMarkdownTable(data) {40 const md = ['| API | Stability |', '| --- | --------- |'];41 for (const mod of data) {42 md.push(`| [${mod.api}](${mod.link}) | ${mod.stabilityText} |`);43 }44 return md.join('\n');45}46function createHTML(md) {47 const file = unified()48 .use(markdown)49 .use(gfm)50 .use(remark2rehype, { allowDangerousHtml: true })51 .use(raw)52 .use(htmlStringify)53 .use(processStability)54 .processSync(md);55 return file.contents.trim();56}57function processStability() {58 return (tree) => {59 visit(tree, { type: 'element', tagName: 'tr' }, (node) => {60 const [api, stability] = node.children;61 if (api.tagName !== 'td') {62 return;63 }64 api.properties.class = 'module_stability';65 const level = stability.children[0].value[1];66 stability.properties.class = `api_stability api_stability_${level}`;67 });68 };69}70function updateStabilityMark(file, value, mark) {71 const fd = fs.openSync(file, 'r+');72 const content = fs.readFileSync(fd, { encoding: 'utf8' });73 const replaced = content.replace(mark, value);74 if (replaced !== content) {75 fs.writeSync(fd, replaced, 0, 'utf8');76 }77 fs.closeSync(fd);78}79const stability = collectStability(data);80// add markdown81const markdownTable = createMarkdownTable(stability);82updateStabilityMark(output.docMarkdown,83 `${markBegin}\n${markdownTable}\n${markEnd}`,84 new RegExp(mark, 's'));85// add html table86const html = createHTML(markdownTable);87updateStabilityMark(output.docHTML, `${markBegin}${html}${markEnd}`,88 new RegExp(mark, 's'));89// add json output90updateStabilityMark(output.docJSON,91 JSON.stringify(`${markBegin}${html}${markEnd}`),...

Full Screen

Full Screen

stability.mjs

Source:stability.mjs Github

copy

Full Screen

1// Build stability table to documentation.html/json/md by generated all.json2import fs from 'fs';3import raw from 'rehype-raw';4import htmlStringify from 'rehype-stringify';5import gfm from 'remark-gfm';6import markdown from 'remark-parse';7import remark2rehype from 'remark-rehype';8import unified from 'unified';9import { visit } from 'unist-util-visit';10const source = new URL('../../out/doc/api/', import.meta.url);11const data = JSON.parse(fs.readFileSync(new URL('./all.json', source), 'utf8'));12const markBegin = '<!-- STABILITY_OVERVIEW_SLOT_BEGIN -->';13const markEnd = '<!-- STABILITY_OVERVIEW_SLOT_END -->';14const mark = `${markBegin}(.*)${markEnd}`;15const output = {16 json: new URL('./stability.json', source),17 docHTML: new URL('./documentation.html', source),18 docJSON: new URL('./documentation.json', source),19 docMarkdown: new URL('./documentation.md', source),20};21function collectStability(data) {22 const stability = [];23 for (const mod of data.modules) {24 if (mod.displayName && mod.stability >= 0) {25 const link = mod.source.replace('doc/api/', '').replace('.md', '.html');26 stability.push({27 api: mod.name,28 link: link,29 stability: mod.stability,30 stabilityText: `(${mod.stability}) ${mod.stabilityText}`,31 });32 }33 }34 stability.sort((a, b) => a.api.localeCompare(b.api));35 return stability;36}37function createMarkdownTable(data) {38 const md = ['| API | Stability |', '| --- | --------- |'];39 for (const mod of data) {40 md.push(`| [${mod.api}](${mod.link}) | ${mod.stabilityText} |`);41 }42 return md.join('\n');43}44function createHTML(md) {45 const file = unified()46 .use(markdown)47 .use(gfm)48 .use(remark2rehype, { allowDangerousHtml: true })49 .use(raw)50 .use(htmlStringify)51 .use(processStability)52 .processSync(md);53 return file.contents.trim();54}55function processStability() {56 return (tree) => {57 visit(tree, { type: 'element', tagName: 'tr' }, (node) => {58 const [api, stability] = node.children;59 if (api.tagName !== 'td') {60 return;61 }62 api.properties.class = 'module_stability';63 const level = stability.children[0].value[1];64 stability.properties.class = `api_stability api_stability_${level}`;65 });66 };67}68function updateStabilityMark(file, value, mark) {69 const fd = fs.openSync(file, 'r+');70 const content = fs.readFileSync(fd, { encoding: 'utf8' });71 const replaced = content.replace(mark, value);72 if (replaced !== content) {73 fs.writeSync(fd, replaced, 0, 'utf8');74 }75 fs.closeSync(fd);76}77const stability = collectStability(data);78// add markdown79const markdownTable = createMarkdownTable(stability);80updateStabilityMark(output.docMarkdown,81 `${markBegin}\n${markdownTable}\n${markEnd}`,82 new RegExp(mark, 's'));83// add html table84const html = createHTML(markdownTable);85updateStabilityMark(output.docHTML, `${markBegin}${html}${markEnd}`,86 new RegExp(mark, 's'));87// add json output88updateStabilityMark(output.docJSON,89 JSON.stringify(`${markBegin}${html}${markEnd}`),...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.markBegin('testMark');7 await page.screenshot({ path: 'testMark.png' });8 await browser.close();9})();10const { chromium } = require('playwright');11(async () => {12 const browser = await chromium.launch();13 const context = await browser.newContext();14 const page = await context.newPage();15 await page.markEnd('testMark');16 await page.screenshot({ path: 'testMark.png' });17 await browser.close();18})();19const { chromium } = require('playwright');20(async () => {21 const browser = await chromium.launch();22 const context = await browser.newContext();23 const page = await context.newPage();24 await page.mark('testMark');25 await page.screenshot({ path: 'testMark.png' });26 await browser.close();27})();28const { chromium } = require('playwright');29(async () => {30 const browser = await chromium.launch();31 const context = await browser.newContext();32 const page = await context.newPage();33 await page.measure('testMark');34 await page.screenshot({ path: 'testMark.png' });35 await browser.close();36})();37const { chromium } = require('playwright');38(async () => {39 const browser = await chromium.launch();40 const context = await browser.newContext();41 const page = await context.newPage();42 await page.goto('https:/'playwright.dev');43 await page.clearMarks()testMark';44 await page.screenshot({ path: 'testMark.png' });45 await browser.close();46})();47const { chromium } = require('playwright');48(async () => {49 const browser = await chromium.launch();50 const context = await browser.newContext();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch('testMark');4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.markBegin();7 await page.screenshot({ path: 'testMark.png' });8 await browser.close();9})();10const { chromium } = require('playwright');11(async () => {12 const browser = await chromium.launch();13 const context = await browser.newContext();14 const page = await context.newPage();15 await page.markEnd('testMark');16 await page.screenshot({ path: 'testMark.png' });17 await browser.close();18})();19const { chromium } = require('playwright');20(async () => {21 const browser = await chromium.launch();22 const context = await browser.newContext();23 const page = await context.newPage();24 await page.mark('testMark');25 await page.screenshot({ path: 'testMark.png' });26 await browser.close();27})();28const { chromium } = require('playwright');29(async () => {30 const browser = await chromium.launch();31 const context = await browser.newContext();32 const page = await context.newPage();33 await page.measure('testMark');34 await page.screenshot({ path: 'testMark.png' });35 await browser.close();36})();37const { chromium } = require('playwright');38(async () => {39 const browser = await chromium.launch();40 const context = await browser.newContext();41 const page = await context.newPage();42 await page.clearMarks('testMark');43 await page.screenshot({ path: 'testMark.png' });44 await browser.close();45})();46const { chromium } = require('playwright');47(async () => {48 const browser = await chromium.launch();49 const context = await browser.newContext();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.markBegin();7 await page.click('text=Get started');8 await page.markEnd();9 await browser.close();10})();11const { chromium } = require('playwright');12(async () => {13 const browser = await chromium.launch();14 const context = await browser.newContext();15 const page = await context.newPage();16 await page.markBegin();17 await page.click('text=Get started');18 await page.markEnd();19 await browser.close();20})();21const { chromium } = require('playwright');22(async () => {23 const browser = await chromium.launch();24 const context = await browser.newContext();25 const page = await context.newPage();26 await page.markBegin();27 await page.click('text=Get started');28 await page.markEnd();29 await browser.close();30})();31const { chromium } = require('playwright');32(async () => {33 const browser = await chromium.launch();34 const context = await browser.newContext();35 const page = await context.newPage();36 await page.markBegin();37 await page.click('text=Get started');38 await page.markEnd();39 await browser.close();40})();41const { chromium } = require('playwright');42(async () => {43 const browser = await chromium.launch();44 const context = await browser.newContext();45 const page = await context.newPage();46 await page.markBegin();47 await page.click('text=Get started');48 await page.markEnd();49 await browser.close();50})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { markBegin } = require('playwright-core/lib/utils/trace');2markBegin('test');3const { markEnd } = require('playwright-core/lib/utils/trace');4markEnd('test');5const { markSnapshot } = require('playwright-core/lib/utils/trace');6markSnapshot('test', 'snapshotName');7const { markStep } = require('playwright-core/lib/utils/trace');8markStep('test', 'stepName');9const { markStart } = require('playwright-core/lib/utils/trace');10markStart('test','satName');11const { markEnd } = require('playwright-core/lib/utils/trace');12markEnd('test', 'endName');13const { markStart } = require('playwright-core/lib/utils/trace');14markStart('test', 'startName');15const { markEnd } = require('playwright-core/lib/utils/trace');16markEnd('test', 'endName');17const { markStart } = require('playwright-core/lib/utils/trace');18markStart('test', 'startName');19const { markEnd } = require('playwright-core/lib/utils/trace');20markEnd('test', 'endName');21const { markStart } = require('playwright-core/lib/utils/trace');22markStart('test', 'startName');23const { markEnd } = require('playwright-core/lib/utils/trace');24markEnd('test', 'endName');25const { markStart } = require('playwright-core/lib/utils/trace');26markStart('test', 'startName');27const { markEnd } = require('playwright-cor28const { chromium } = require('playwright');29(async () => {30 const browser = await chromium.launch();31 const context = await browser.newContext();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Playwright } = require('playwright');2(async () => {3 const playwright = await Playwright.create();4 const browser = await playwright.chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const trace = await page.startTracing(page, { screenshots: true, snapshots: true });8 await page.markBegin(page, 'marker1');9 await page.markEnd(page, 'marker1');10 await trace.stop();11 await browser.close();12})();13Example 2: Using mark() method14const { Playwright } = require('playwright');15(async () => {16 const playwright = await Playwright.create();17 const browser = await playwright.chromium.launch();18 const context = await browser.newContext();19 const page = await context.newPage();20 const trace = await page.startTracing(page, { screenshots: true, snapshots: true });21 await page.mark(page, 'marker1');22 await trace.stop();23 await browser.close();24})();25Example 3: Using mark() method with custom data26const { Playwright } = require('playwright');27(async () => {28 const playwright = await Playwright.create();29 const browser = await playwright.chromium.launch();30 const context = await browser.newContext();31 const page = await context.newPage();32 const trace = await page.startTracing(page, { screenshots: true, snapshots: true });33 await page.mark(page, 'marker1', { color: 'red', label: 'marker1' });34 await trace.stop();35 await browser.close();36})();37Example 4: Using mark() method with custom data38const { Playwright } = require('playwright');39(async () => {40 const playwright = await Playwright.create();41 const browser = await playwright.chromium.launch();42 const context = await browser.newContext();43 const page = await context.newPage();44 const trace = await page.startTracing(page, { screenshots: true

Full Screen

Using AI Code Generation

copy

Full Screen

1const { InternalLogger } = require('@playwright/test');2InternalLogger.markBegin('test');3InternalLogger.markEnd('test');4InternalLogger.markStart('test');5InternalLogger.markEnd('test');6InternalLogger.markStart('test');7InternalLogger.markEnd('test');8InternalLogger.markStart('test');9InternalLogger.markEnd('test');10InternalLogger.markStart('test');11InternalLogger.markEnd('test');12InternalLogger.markStart('test');13InternalLogger.markEnd('test');14InternalLogger.markStart('test');15InternalLogger.markEnd('test');16InternalLogger.markStart('test');17InternalLogger.markEnd('test');18InternalLogger.markStart('test');19InternalLogger.markEnd('test');20InternalLogger.markStart('test');21InternalLogger.markEnd('test');22InternalLogger.markStart('test');23InternalLogger.markEnd('test');24InternalLogger.markStart('test');25InternalLogger.markEnd('test');26InternalLogger.markStart('

Full Screen

Using AI Code Generation

copy

Full Screen

1const { InternalLogger } = require('@playwright/test');2InternalLogger.markBegin('test');3InternalLogger.markEnd('test');4InternalLogger.markStart('test');5InternalLogger.markEnd('test');6InternalLogger.markStart('test');7InternalLogger.markEnd('test');8InternalLogger.markStart('test');9InternalLogger.markEnd('test');10InternalLogger.markStart('test');11InternalLogger.markEnd('test');12InternalLogger.markStart('test');13InternalLogger.markEnd('test');14InternalLogger.markStart('test');15InternalLogger.markEnd('test');16InternalLogger.markStart('test');17InternalLogger.markEnd('test');18InternalLogger.markStart('test');19InternalLogger.markEnd('test');20InternalLogger.markStart('test');21InternalLogger.markEnd('test');22InternalLogger.markStart('test');23InternalLogger.markEnd('test');24InternalLogger.markStart('test');25InternalLogger.markEnd('test');26InternalLogger.markStart('

Full Screen

Using AI Code Generation

copy

Full Screen

1{2 "metadata": {3 "stackFrames": {4 "0": {5 },6 "1": {7 }8 },9 "samples": {10 "0": {11 },12 "1": {13 }14 }15 }16}

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