How to use collection.eq method in Cypress

Best JavaScript code snippet using cypress

tts.js

Source:tts.js Github

copy

Full Screen

1var tts = {2 config:{3 callbacks:{},4 cache:{}, /*CACHE CODE*/5 spans:{},6 services:{},7 prefetch:{},8 phrase:{9 beforeSplitRE:/((([^\.]\s*[^A-Z]\.)|([;,\?!*]))($|(?=\s)))/g,10 afterSplitRE:/(\s(\s+\-+\s+|that|because|but|instead|and|or|which|according)(\s|$))/gi,11 libSplits:/(\s|^)(between|to|in|except|from|for|from|when|with)(\s|$)/gi,12 splitRegExp:/\_\}\_/,13 stringDelimiter:"_}_"14 },15 TTS:{}16 },17 phraseFinder:{18 splitString:function(str){19 if(typeof str !== 'string') {20 return [];21 }22 str = str.replace(tts.config.phrase.beforeSplitRE, '$1' + tts.config.phrase.stringDelimiter);23 str = str.replace(tts.config.phrase.afterSplitRE, tts.config.phrase.stringDelimiter + '$1');24 25 return tts.phraseFinder.splitByDelim(str, tts.config.phrase.stringDelimiter, true);26 },27 liberalSplit:function(str){28 str = str.replace(tts.config.phrase.libSplits, tts.config.phrase.stringDelimiter + '$1$2$3');29 return tts.phraseFinder.splitByDelim(str, tts.config.phrase.stringDelimiter, false);30 },31 trim:function(str){32 return ((str == null) ? null : str);33 },34 countWords:function(str){35 return (tts.phraseFinder.trim(str).split(/\s+/).length);36 },37 splitByCapacity:function(strToProcess){38 var segments = [];39 var whitespaces = [];40 var pattern = /\s/;41 42 for (i=0;i<strToProcess.length;i++){43 if (pattern.test(strToProcess.charAt(i))){44 whitespaces.push(i);45 }46 }47 48 if (whitespaces.length == 0){49 segments.push(strToProcess);50 }else if (whitespaces.length == 1){51 segments.push(strToProcess.slice(0, whitespaces[0] -1));52 segments.push(strToProcess.slice(whitespaces[0]));53 }else if (whitespaces.length > 1){54 for (i = 0; i < whitespaces.length; i++) {55 //check if first56 if (i==0){57 segments.push(strToProcess.slice(0, whitespaces[i+1]+1));58 }59 if (i > 0 && i != whitespaces.length -1){60 //*to debug later61 62 segments.push(strToProcess.slice(whitespaces[i] + 1, whitespaces[i+1]+1));63 }64 if (i == whitespaces.length -1){65 segments.push(strToProcess.slice(whitespaces[i] + 1)); 66 }67 }68 }69 70 //For each segment. check the segment length. if it is greater than capacity, 71 for (i = 0; i < segments.length; i++){72 if (segments[i].length > tts.config.spans.CurrentSpanCapacity){73 var newSegments = [];74 while (segments[i].length > tts.config.spans.CurrentSpanCapacity){75 newSegments.push(segments[i].slice(0,tts.config.spans.CurrentSpanCapacity -1));76 segments[i] = segments[i].slice(tts.config.spans.CurrentSpanCapacity);77 }78 //for(j=0;j<newSegments.length;j++){console.log(newSegments[j]);}79 newSegments.push(segments[i]);80 newSegments.unshift(i,1);81 i+= newSegments.length + 1;82 segments.splice.apply(segments, newSegments);83 delete newSegments;84 }85 }86 delete whitespaces;87 delete pattern;88 return segments;89 90 },91 splitByDelim:function(str, delim, lib_recurse) {92 // Construct the initial array of strings.93 var phrases = str.split(tts.config.phrase.splitRegExp);94 var stillWorking = true;95 var keepWorking = false;96 // Iterate over the phrases that were found, adjusting them97 // based on number of words. 98 while (stillWorking == true){99 //keep working will become true if subsequent conditions are satisfied100 keepWorking = false;101 102 //process phrases103 for(var i=0; i<phrases.length; i++) {104 105 //replacement may be redundant from createspans()106 phrase = phrases[i].replace(/\s+/g,' ');107 //remove empty phrases to prevent infinite recursion108 if (phrase.length == 0){109 phrases.splice(i,1);110 i--;111 continue;112 }113 114 var numWords = tts.phraseFinder.countWords(phrase);115 //add clauses to check next phrase size and deny transaction if it is overlarge116 //possibly put both for loops in a do until to naturalize things a bit more117 //eventually no moves will be possible and no phrases will exceede capacity118 119 // If it's too short, combine with one of the phrases around it.120 //this logic produces phrases of between 3 and 7 words which are less than [capacity] characters and are broken on words from the regular expression constants121 if(numWords<3 && phrases.length > 1) {122 if(i==0) {123 // Prepend to next one.124 if (phrase.length + phrases[i+1].length < tts.config.spans.CurrentSpanCapacity){125 //keepWorking = true;126 phrases[i+1] = phrase + phrases[i+1];127 phrases.splice(i,1);128 i--;129 }130 } else if(i==phrases.length-1) {131 // Append to last one.132 if (phrase.length + phrases[i-1].length < tts.config.spans.CurrentSpanCapacity){133 //keepWorking = true;134 phrases[i] = phrases[i-1] + phrase;135 phrases.splice(i-1,1);136 i--;137 }138 } else {139 // Combine with the smaller of its neighbors.140 if(phrases[i-1].length < phrases[i+1].length) {141 if (phrase.length + phrases[i-1].length < tts.config.spans.CurrentSpanCapacity){142 //keepWorking = true;143 phrases[i] = phrases[i-1] + phrase;144 phrases.splice(i-1,1);145 i--;146 }147 } else {148 if (phrase.length + phrases[i+1].length < tts.config.spans.CurrentSpanCapacity){149 //keepWorking = true;150 phrases[i+1] = phrase + phrases[i+1];151 phrases.splice(i,1);152 i--;153 }154 }155 }156 } else if(numWords > 6 && lib_recurse) { // Break long strings liberally.157 //keepWorking = true;158 var newPhrases = tts.phraseFinder.liberalSplit(phrase);159 newPhrases.unshift(i, 1);160 i+= newPhrases.length + 1;161 phrases.splice.apply(phrases, newPhrases);162 delete newPhrases;163 }164 }165 166 for(var i=0; i<phrases.length; i++) {167 if (phrases[i].length > tts.config.spans.CurrentSpanCapacity){168 keepWorking = true;169 var newPhrases = tts.phraseFinder.splitByCapacity(phrases[i]);170 newPhrases.unshift(i, 1);171 i+= newPhrases.length + 1;172 phrases.splice.apply(phrases, newPhrases);173 delete newPhrases;174 }175 }176 177 if (keepWorking == true){178 //console.log('keep working');179 stillWorking = true;180 }181 else{182 stillWorking = false;183 }184 }185 delete stillWorking;186 delete keepWorking;187 delete numWords;188 return phrases;189 } 190 },191 init:{192 getJSONConfig:function(){193 //make a post request for a JSON object.194 $.ajax({195 asynch:false,196 cache:false,197 dataType:'json',198 error:function(){},199 global:false,200 success:function(result){201 var obj = result;202 if (typeof obj !== 'undefined'){203 var course = tts.config.TTS.course;204 $.extend(tts.config,obj);205 $.extend(tts.config.TTS,{TTSConfigured:true,course:course});206 delete course;207 delete tts.config.TTS.TTSConfigurationRequested;208 /*BROWSER HACK vs IE 'FEATURE'*/209 210 if(typeof tts.config.cache.ie === 'undefined'){211 $.extend(tts.config.cache,{ie:$.browser.msie});212 if(tts.config.cache.ie){213 var timestamp = new Date().getTime();214 //tts.config.TTS.SM_SWF_URL = tts.config.TTS.SM_SWF_URL + '?' + String(timestamp);215 //console.log(tts.config.TTS.SM_SWF_URL);216 tts.init.startSoundManager2(); 217 }218 else{219 //console.log('not ie');220 tts.init.startSoundManager2();221 }222 223 }224 else{225 tts.init.startSoundManager2();226 }227 /*---*/228 229 /*CACHE CODE - check if the browser can do this*/230 $.storage = new $.store();231 232 if($.storage.driver.scope == "browser"){233 $.extend(tts.config.cache,{enabled:true});234 }235 else{236 $.extend(tts.config.cache,{enabled:false});237 } 238 }239 else{240 setTimeout(tts.init.getJSONConfig,500);241 }242 },243 timeout:15000,244 type:"GET",245 url:tts.config.TTS.TTSConfigURL246 });247 },248 startSoundManager2:function(){249 //lazy loading sound manager 2 to accomadate non-automatic starting of TTS250 window.SM2_DEFER = true;251 var smScript = document.createElement('script');252 smScript.type = 'text/javascript';253 smScript.onreadystatechange = function(){254 var rs = this.readyState;255 if (rs == 'loaded' || rs == 'complete') {256 this.onreadystatechange = null;257 this.onload = null;258 tts.init.smScriptLoaded();259 }260 };261 smScript.onload = function(){262 this.onreadystatechange = null;263 this.onload = null;264 window.setTimeout(function(){tts.init.smScriptLoaded()},20); 265 };266 smScript.src = tts.config.TTS.SM_SCRIPT_URL;267 document.getElementsByTagName('head')[0].appendChild(smScript);268 },269 smScriptLoaded:function(){270 //console.log('sm2 script loaded');271 soundManager = new SoundManager();272 //would be better to do this in a key value loop and provide them through config.php273 soundManager.onready(function(){274 //console.log('ready');275 //do the successful initialization callback which may affect the UI.276 if (typeof tts.config.callbacks.initSuccess == 'function'){277 tts.config.callbacks.initSuccess();278 }279 });280 //if SM2 times out, do the fail callback so UI can be informed.281 soundManager.ontimeout(function(){282 //console.log('ontimeout');283 if (typeof tts.config.callbacks.initFail == 'function'){284 tts.config.callbacks.initFail();285 }286 }); 287 $.extend(soundManager,{288 url:tts.config.TTS.SM_SWF_URL,289 useConsole:true,290 debugMode:false,291 consoleOnly:false,292 waitForWindowLoad:true,293 defaultOptions:{294 glboalMute:false,295 premute:tts.config.TTS.SM_STARTING_VOLUME,296 multiShot:false,297 autoLoad:true,298 volume:tts.config.TTS.SM_STARTING_VOLUME 299 }300 });301 soundManager.beginDelayedInit();302 //console.log(soundManager);303 },304//also rebuilds spans... this should be renamed.305 wipeSpanData:function(){306 var timer = 0;307 if (typeof tts.config.spans.spanCollection !== 'undefined'){308 tts.config.spans.spanCollection309 .each(function(){310 $this = $(this);311 if (typeof $this.data('sound') !== 'undefined'){312 //SoundManager2 instance is destroyed313 $this.data('sound').destruct();314 $this.removeData('sound');315 }316 $this317 .removeData('errors')318 .removeData('state')319 .removeData('file')320 .removeData('number')321 .removeData('dirty_mp3')322 .removeData('error_sound_loaded')323 .removeData('text_to_speak')324 .removeData('bad_mp3_url')325 .unbind();326 //if cache is enabled, destroy that data too327 if (typeof tts.config.cache.enabled !== 'undefined' && tts.config.cache.enabled === true ){328 $this329 .removeData('key')330 .removeData('value')331 .removeData('stored');332 }333 });334 /*CACHE CODE - wipe out cache fields here. Also reset global caching variables*/335 //global state variables pertaining to caching should also be reset.336 //reseting the timestamp so that Internet Explorer is happy with the new mp3s is necessary337 //This if clause executes ONLY IF this is NOT the first time spans are being wiped of data338 //This is prudent if a voice is being changed without refreshing the page.339 if(tts.config.spans.spanCollection.length > 0){340 //recursing until execution of function is appropriate341 function delayedBuildSound(f,param,time){342 setTimeout(function(){f(param);},time);343 }344 //reinitialize dirty IE work arounds345 var timer = 100;346 var timestamp = new Date().getTime();347 var dirty = String(timestamp) + '?' + String(timestamp);348 tts.config.spans.spanCollection.each(function(n){349 $this = $(this);350 $this351 .data('errors',0)352 .data('state',tts.config.prefetch.NOT_PREFETCHED)353 .data('number',n)354 .data('dirty_mp3',false)355 .data('error_sound_loaded',false)356 .data('bad_mp3_url','empty')357 .data('text_to_speak',$this.text().replace(/\s+/g,' '))358 .click( function( event ) {359 $this = $(this);360 if ($this.parents("a").length > 0){361 tts.spanController.pauseAll();362 return;363 }364 if(n == tts.config.spans.currentSpan){365 366 if(typeof $this.data('sound') !== 'undefined'){367 //check playstate and readystate368 if ($this.data('sound').readyState == 3){369 if($this.data('sound').playState == 1){370 tts.spanController.pauseAll();371 }372 else{373 tts.spanController.pauseAll();374 tts.spanController.playCurrentSpan();375 }376 }377 }378 }else{379 tts.spanController.skip(n - tts.config.spans.currentSpan);380 }381 });382 /*383 CACHE CODE - if there is caching in the browser(global), generate .data('key')384 Also use data('key') to set data('stored') by looking up if the key value exists.385 This will be used by other functions to prevent unnecessary server load.386 */ 387 if (typeof tts.config.cache.enabled !== 'undefined' && tts.config.cache.enabled === true ){388 //console.log('can cache');389 $this.data('key',hex_md4(tts.config.services.currentService + tts.config.services.currentVoice + $this.data('text_to_speak')));390 //check if stored.391 if ($.storage.get($this.data('key')) !== null){392 $this393 .data('stored',true)394 .data('value',$.storage.get($this.data('key')))395 .data('state',3); 396 397 if(tts.config.cache.ie){398 $this.data('file',$this.data('value') + '?' +dirty ); 399 }400 else{401 $this.data('file',$this.data('value'));402 }403 //debug code. uncomment to get more information about what is happening with caching. 404 //console.log($this.data('key'));405 //console.log($this.data('stored'));406 //console.log($this.data('value'));407 //console.log($this.data('file'));408 //console.log($this.data('state'));409 //$("#xhtml").append('<p>building sound from cache '+$this.data('file')+'</p>');410 //$("#xhtml").append($this);411 //$("#xhtml").append(this);412 delayedBuildSound(tts.prefetcher.buildSound,$this,timer);413 //setTimeout(function(){tts.prefetcher.buildSound($this);},timer); //fix for ie threading.414 //tts.prefetcher.buildSound($this);415 timer = timer + 200;416 }417 else{418 $this.data('stored',false);419 }420 }421 });422 423 /*BROWSER HACK - ie*/424 425 if (tts.config.cache.ie){426 var timestamp = new Date().getTime();427 var dirtyTime = String(timestamp) + '?' + String(timestamp);428 $.extend(tts.config.cache,{ieDirty:dirtyTime});429 }430 431 432 /*--- */433 $.extend(tts.config.spans,{434 currentSpan:0,435 previousSpan:-1,436 nextSpanToPlay:0,437 firstPlay:true,438 playingSpans:0,439 notWaitingToPlayCurrent:true,440 globalMute:false441 });442 $.extend(tts.config.prefetch,{443 blockFatFetch:false,444 fatFetchInProgress:false,445 fatFetchAttempts:0,446 firstErrorPass:true,447 unfinishedSounds:[],448 errorSpans:[],449 alreadyReporting:false,450 blockDialogFetch:true451 });452 /*CACHE CODE - reset globals here*/453 }454 if(typeof tts.config.prefetch.MAX_REQUESTS !== 'undefined'){455 //start logging requests456 if(typeof tts.config.prefetch.currentRequests !== 'undefined'){457 delete tts.config.prefetch.currentRequests;458 } 459 }460 if (typeof tts.config.SM !== 'undefined' && typeof tts.config.SM.HAS_ONREADY !== 'undefined'){461 delete tts.config.SM;462 }463 }464 },465 createSpans:function(){466 if (typeof tts.config.spans.spanCollection !== 'undefined'){467 tts.config.spans.spanCollection468 .each(function(){469 $(this).replaceWith($(this).contents());470 });471 }472 //creates spans by capacity and phrase rules currentSpan473 474 //var test = $(tts.config.spans.selector).contents();475 476 var ret = [];477 //#contents in this case478 $(tts.config.spans.selector)479 .contents()480 //everything except the configuration blacklist481 .not(tts.config.spans.not)482 .each(function(){483 //if the node is a text node484 if (this.nodeType == 3)485 ret.push(this);486 else487 //drill deeper. this node is an ancestor of a text node.488 //I think arguments.callee is depreciated in ECMA 5.489 $(this).contents().not(tts.config.spans.not).each(arguments.callee);490 });491 //for each text node in the array492 $(ret).each(function(i){493 $this = $(this);494 var temp_str ='';495 //debugging496 //$("#xhtml").append('text node: '+$this.text()+' ');497 498 //the phrases in the text node are returned by phrase finder499 var phrases = tts.phraseFinder.splitString($this.text());500 //each text node becomes an array of phrases, each phrase is assigned a number and wrapped in a <span>501 for(var j=0; j<phrases.length; j++) {502 //$("#xhtml").append(' phrase['+ j +']: '+phrases[j]);503 if(/\w/.test(phrases[j])) {504 //normalize spaces across browsers. This allows consistent hashing and caching.505 phrases[j] = phrases[j].replace(/\s+/g,' ');506 phrases[j] = '<span class="'+ tts.config.spans.spanClass +'">' + phrases[j] + '</span>'507 temp_str = temp_str + phrases[j];508 }509 }510 if(/\w/.test(temp_str)) {511 $this.replaceWith(temp_str);512 }513 514 delete temp_str;515 delete phrases;516 });517 $.extend(tts.config.spans,{spanCollection:$("span." + tts.config.spans.spanClass)});518 519 },520 //TTS starts here.521 initialize:function(obj,success,fail){ 522 //setup url, service, voice if supplied then destory obj523 if ( typeof obj === 'object') {524 if (obj.url){525 if( typeof obj.url === 'string'){526 $.extend(tts.config.TTS, {TTSConfigURL:obj.url});527 }528 }529 //google, yahoo, festival, ATT, etc.530 if (obj.service){531 if( typeof obj.service === 'string'){532 $.extend(tts.config.services, {requestedService:obj.service});533 }534 }535 //voice that service is using536 if (obj.voice){537 if( typeof obj.voice === 'string'){538 $.extend(tts.config.services, {requestedVoice:obj.voice});539 } 540 }541 542 if (obj.course){543 if( typeof obj.course === 'number'){544 $.extend(tts.config.TTS, {course:obj.course});545 }546 }547 548 $.each( obj || {}, function( key, value ) {549 delete obj[key];550 });551 if(success){552 if (typeof success === 'function'){553 //console.log('success');554 $.extend(tts.config.callbacks, {initSuccess:success});555 }556 }557 if(fail){558 if (typeof fail === 'function'){559 //console.log('fail');560 $.extend(tts.config.callbacks, {initFail:fail});561 }562 }563 }564 565 //if tts is configured, check if service is different than current service566 //IF TTS is NOT YET set up, the else clause is executed.567 if (typeof tts.config.TTS.TTSConfigured !=='undefined'){568 //see if there is a service change request and if it is to the same as the current service569 if ((typeof tts.config.services.requestedService !== 'undefined')&&(tts.config.services.requestedService != tts.config.services.currentService)&&(typeof tts.config.services.requestedService === 'string' && $.inArray( tts.config.services.requestedService, tts.config.services.serviceList ) != -1 )){570 $.extend(tts.config.services, {currentService:tts.config.services.requestedService,newService:true});571 delete tts.config.services.requestedService;572 }573 //see if there is a voice change request574 if ((typeof tts.config.services.requestedVoice !=='undefined')&&(tts.config.services.requestedVoice != tts.config.services.currentVoice)){575 //see if the voice change request is in the current voices for the service576 if (typeof tts.config.services.requestedVoice == 'string' && $.inArray( tts.config.services.requestedVoice, tts.config.services[tts.config.services.currentService].voices ) != -1 ) {577 $.extend(tts.config.services, {currentVoice:tts.config.services.requestedVoice,newVoice:true});578 delete tts.config.services.requestedVoice;579 }580 else{581 //voice is not in voice list for service, check if there is a new service being used so that a default can be set for it582 if(typeof tts.config.services.newService !== 'undefined'){ //new service, bad voice583 $.extend(tts.config.services, {currentVoice:ts.config.services[tts.config.services.currentService].defaultVoice,newVoice:true});584 delete tts.config.services.requestedVoice;585 } 586 } 587 }588 //if the service is changed, check to see that span pharases need to have different capacities589 if((typeof tts.config.services.newService !== 'undefined') && (tts.config.spans.CurrentSpanCapacity != tts.config.services[tts.config.services.currentService].capacity)){ 590 delete tts.config.services.newService;591 $.extend(tts.config.spans,{CurrentSpanCapacity:tts.config.services[tts.config.services.currentService].capacity});592 $.extend(tts.config.prefetch,{startFetching:true});593 tts.init.createSpans();594 595 }596 597 //if the voices have changed (always the case if service has changed), redo the span data. and restart the prefetcher.598 if(typeof tts.config.services.newVoice !== 'undefined'){599 delete tts.config.services.newVoice;600 $.extend(tts.config.prefetch,{startFetching:true});601 tts.init.wipeSpanData();602 }603 //start Prefetcher if things have changed. It will destroy its submission then rebuild it and call itself.604 if(typeof tts.config.prefetch.startFetching !== 'undefined'){605 delete tts.config.prefetch.startFetching;606 //**************may need to do the SM2 enabled check here.607 delete tts.config.prefetch.currentRequests;608 609 //tts.prefetcher.fetch(-1);610 tts.prefetcher.fetchController();611 /*CACHE CODE - call prefetch director here instead.*/612 }613 }614 else{ //tts is not configured, call the configuration script615 if (typeof tts.config.TTS.TTSConfigURL === 'string'){616 //if it has already requested config.php, it waits and checks 1000ms later617 if (typeof tts.config.TTS.TTSConfigurationRequested !== 'undefined'){618 setTimeout(tts.init.initialize,1000);619 }620 else{621 //config.php request is made and the fact that the request has been made is registered.622 tts.init.getJSONConfig();623 $.extend(tts.config.TTS,{TTSConfigurationRequested:true});624 setTimeout(tts.init.initialize,2500);625 }626 }627 else{628 alert('invalid config URL');629 }630 }631 }632 },633 prefetcher:{634 //attempts fatfetch of all mp3s first then begins fetch which dialogs with the server to build the mp3 library server-side.635 //fetchController has many state variables which control application flow.636 fetchController: function(){637 //console.log('fetchController called');638 if(typeof soundManager === 'undefined'){639 setTimeout(tts.prefetcher.fetchController,500);640 //console.log('no sm2');641 return;642 }643 if(!soundManager.enabled){644 setTimeout(tts.prefetcher.fetchController,500);645 //console.log(soundManager.enabled);646 return; 647 }648 649 if (tts.config.prefetch.blockFatFetch === false && typeof tts.config.prefetch.blockFatFetch !== 'undefined' && tts.config.prefetch.fatFetchInProgress === false){650 //console.log('inside fetch controller');651 tts.config.prefetch.fatFetchInProgress = true;652 var allSpans = tts.config.spans.spanCollection.length;653 var datas = {654 "span_count":allSpans,655 "voice":tts.config.services.currentVoice,656 "service":tts.config.services.currentService,657 "course":tts.config.TTS.course658 };659 660 //collect all of the spans with status of 0.661 var datas_has_data = false;662 var obj={};663 //console.log('allspans '+allSpans);664 for (i=0;i<allSpans;i++){665 var $span = tts.config.spans.spanCollection.eq(i);666 //console.log($span.data('state'));667 if ($span.data('state') == tts.config.prefetch.NOT_PREFETCHED){668 datas_has_data = true;669 var $property_span ="span_"+i;670 var $property_text ="text_"+i;671 obj[$property_span] = i;672 obj[$property_text] = $span.data('text_to_speak'); 673 } 674 }675 //console.log(obj);676 $.extend(datas, obj);677 //console.log(datas);678 //console.log(obj);679 680 if (datas_has_data !== false){681 //console.log('datas has data attemps '+tts.config.prefetch.fatFetchAttempts);682 tts.config.prefetch.fatFetchAttempts += 1;683 $.ajax({684 asynch:false,685 cache:false,686 context:$span,687 data:datas,global:false,688 dataType:'json',689 beforeSend: function(x) {690 if(x && x.overrideMimeType) {691 x.overrideMimeType("application/j-son;charset=UTF-8");692 }693 },694 timeout:60000,695 type:"POST",696 url:tts.config.prefetch.FAT_FETCH_URL,697 error:function(){698 if (tts.config.prefetch.fatFetchAttempts <= tts.config.prefetch.maxFatFetchAttempts){699 tts.config.prefetch.fatFetchInProgress = false;700 tts.prefetcher.fetchController();701 }702 else{703 //do not do this again704 tts.config.prefetch.blockFatFetch = true;705 tts.config.prefetch.blockDialogFetch = false;706 tts.config.prefetch.fatFetchInProgress = false;707 tts.prefetcher.fetchController();708 }709 },710 success:function(result){711 //console.log(result);712// $("#xhtml").append('<p>performed fat fetch</p>');713 if (typeof result === 'object'){714 $.each(result, function(j,val) {715 $.each(val, function(k,val2){716 var keySpan = tts.config.spans.spanCollection.eq(val2.span);717 //console.log(val2);718 //console.log(val2.span);719 //console.log(val2.url);720 if (!keySpan.data('sound')){721 keySpan.data('state',tts.config.prefetch.SERVER_HAS_MP3);722 keySpan.data('file',val2.url.replace("\\",""));723 tts.prefetcher.buildSound(keySpan);724 //console.log(keySpan.data('state'));725 //console.log(keySpan.data('file'));726 //console.log(keySpan.data('number'));727 //console.log(keySpan);728 } 729 });730 });731 }732 tts.config.prefetch.blockFatFetch = true;733 tts.config.prefetch.blockDialogFetch = false;734 tts.config.prefetch.fatFetchInProgress = false;735 tts.prefetcher.fetchController(); 736 737 }738 });//ajax end739 }740 741 }742 743 if(tts.config.prefetch.blockDialogFetch === false && typeof tts.config.prefetch.blockDialogFetch !== 'undefined'){744 tts.prefetcher.fetch(-1);745 }746 747 },748 //n is the number attached to a span in the SpanCollection. $.data('number')749 fetch: function(n){750 //if there is no soundManager2, try 1 second from now.751 if (typeof soundManager.enabled == 'undefined' || !soundManager.enabled){752 setTimeout(function(){tts.prefetcher.fetch(n)},1000);753 return;754 }755 756 //if no specific span is specified, check that ALL spans have a sound attached. If they do, terminate.757 if (n == -1){//no index is being referenced.758 759 if(typeof tts.config.prefetch.MAX_REQUESTS !== 'undefined'){760 //start logging requests761 if(typeof tts.config.prefetch.currentRequests === 'undefined'){762 //create the variable763 //current requests is HOW MANY fetchers should be allowed to run simultaneously.764 //this impacts performance but should be increased when building cache from scratch.765 $.extend(tts.config.prefetch,{currentRequests:1});766 }767 //start making more fetchers768 769 }770 771 var fetchIndex;772 //if a span needs a sound, attach a 'fetcher' process to it.773 for (i=tts.config.spans.currentSpan;i<tts.config.spans.spanCollection.length;i++){774 if (tts.config.spans.spanCollection.eq(i).data('state') == tts.config.prefetch.NOT_PREFETCHED){775 //tts.config.spans.spanCollection.eq(i).data('state',tts.config.prefetch.PREFETCH_IN_PROGRESS);776 fetchIndex = i;777 break;778 //tts.prefetcher.fetch(i);779 //return;780 }781 }782 783 if (typeof fetchIndex === 'undefined'){784 for (i=0;i<tts.config.spans.currentSpan;i++){785 if (tts.config.spans.spanCollection.eq(i).data('state') == tts.config.prefetch.NOT_PREFETCHED){786 //tts.config.spans.spanCollection.eq(i).data('state',tts.config.prefetch.PREFETCH_IN_PROGRESS);787 fetchIndex = i;788 break;789 //tts.prefetcher.fetch(i);790 //return;791 }792 }793 }794 795 if (typeof fetchIndex !== 'undefined'){796 tts.config.spans.spanCollection.eq(fetchIndex).data('state',tts.config.prefetch.PREFETCH_IN_PROGRESS);797 tts.prefetcher.fetch(fetchIndex)798 }799 800 delete fetchIndex;801 802 //if more workers should be called, spawn a new fetcher process803 if(tts.config.prefetch.currentRequests <= tts.config.prefetch.MAX_REQUESTS){804 //start another fetcher which will do the same805 tts.config.prefetch.currentRequests = tts.config.prefetch.currentRequests + 1;806 setTimeout(function(){tts.prefetcher.fetch(-1)},1000);807 }808 }809 else{810 //ask server for mp3 that is not yet server-side cached811 $span = tts.config.spans.spanCollection.eq(n);812 if ($span.data('state') < tts.config.prefetch.SERVER_HAS_MP3){813 //get rid of anything that is not alphanumeric814 var textToSpeak = $span.text();815 textToSpeak = textToSpeak.replace(/\s+/g,' ');816 //JSON request817 var data =818 {819 "service":tts.config.services.currentService,820 "voice":tts.config.services.currentVoice,821 "span": n,822 "text": $span.data('text_to_speak'),823 "state": $span.data('state'),824 "course":tts.config.TTS.course825 };826 $.ajax({827 asynch:false,828 cache:false,829 context:$span,830 //data:dataString,831 data:data,832 dataType:'json',833 beforeSend: function(x) {834 if(x && x.overrideMimeType) {835 x.overrideMimeType("application/j-son;charset=UTF-8");836 }837 },838 error:function(){839 //increment errors if an error is thrown. change span state to SPAN_THREW_ERROR if MAX ERRORS are reached.840 if (typeof this.data('errors') !== 'undefined'){841 $this.data('errors',$this.data('errors') + 1);842 if (this.data('errors') >= tts.config.prefetch.MAX_ERRORS){843 this.data('state',tts.config.prefetch.SPAN_THREW_ERROR);844 setTimeout(function(){tts.prefetcher.fetch(-1)},2000);845 return;846 }847 }848 setTimeout(function(){tts.prefetcher.fetch($this.data('number'))},2000);849 },850 global:false,851 success:function(result){852 var obj = result;853 obj.file = obj.file.replace("\\","");854 //call again855 if (obj.state < tts.config.prefetch.SERVER_HAS_MP3){856 this.data('state',obj.state);857 858 setTimeout(function(){tts.prefetcher.fetch(obj.span)},2500);859 }860 //build sound routine861 if (obj.state == tts.config.prefetch.SERVER_HAS_MP3){862 this.data('state',obj.state);863 if (!this.data('sound')){864 this.data('file',obj.file);865 this.data('state',obj.state);866 tts.prefetcher.buildSound(this);867 }868 setTimeout(function(){tts.prefetcher.fetch(-1)},500);869 }870 if (obj.error){ 871 if (typeof this.data('errors') !== 'undefined'){872 this.data('errors', this.data('errors') + 1);873 if (this.data('errors') > tts.config.prefetch.MAX_ERRORS){874 this.data('state',tts.config.prefetch.SPAN_THREW_ERROR);875 setTimeout(function(){tts.prefetcher.fetch(-1)},2500);876 return;877 }878 }879 var num = this.data('number');880 setTimeout(function(){tts.prefetcher.fetch(num);delete num;},3000);881 }882 },883 timeout:60000,884 type:"POST",885 url:tts.config.prefetch.FETCH_URL886 });//ajax end887 }888 }889 },890 /*CACHE CODE - need to overhaul this function to do caching and dirty cache/dirty address failover*/891 /*CACHE CODE - need buildErrorSound*/892 //param sel is a jQuery span893 buildSound: function(sel){894 895 //var test = soundManager.canPlayMIME('wav');896 //alert(test);897 898 if (soundManager.enabled){899 //$("#xhtml").append('<p>sound manager enabled</p>');900 var soundURL;901 /*BROWSER HACK*/902 if (tts.config.cache.ie){903 //append query string so that IE will not use browser cache.904 soundURL = sel.data('file') + '?'+tts.config.cache.ieDirty;905 //solution to same phrase repeating causing failiure in IE906 tts.config.cache.ieDirty = tts.config.cache.ieDirty + 1;907 }908 else{909 soundURL = sel.data('file');910 }911 912 //soundURL = sel.data('file');913 //SoundManager2 specific code914 sel.915 data( 'sound', soundManager.createSound({916 id : 'sound' + sel.data('number'),917 url : soundURL,918 span : sel, //for referencing the span if scrolling is on. may also help for highlite.919 /**alteration**/920 onload: function(){921 //$("#tts_init_message").append('<p>sound onload fired ' + sel.data('sound').readyState + ' '+sel.data('file')+'</p>');922 //SoundManager2 sounds have load states which are checked here.923 if ( sel.data('sound').readyState == 2 ){924 //destroy the sound and build it again.925 //$("#xhtml").append('<p>sound failed to load</p>');926 sel.data('sound').destruct();927 sel.removeData('sound'); 928 929 if(sel.data('error_sound_loaded')){930 return;931 }932 //load null sound if span has repeatedly failed to acquire mp3933 if (sel.data('dirty_mp3') === true){934 sel.data('bad_mp3_url',sel.data('file'));935 var errorURL;936 if (tts.config.cache.ie){937 errorURL = tts.config.prefetch.ERROR_SOUND_URL + '?' +tts.config.cache.ieDirty;938 }939 else{940 errorURL = tts.config.prefetch.ERROR_SOUND_URL;941 942 }943 sel.data('file',errorURL);944 sel.data('error_sound_loaded',true);945 sel.data('state',tts.config.prefetch.SPAN_THREW_ERROR);946 tts.prefetcher.buildSound(sel);947 return;948 }949 //check if storing950 if(tts.config.cache.enabled === true){951 if (sel.data('stored') === true){952 $.storage.del(sel.data('key'));953 }954 }955 sel.data('dirty_mp3',true);956 var timestamp = new Date().getTime();957 sel.data('file',sel.data('file') + timestamp);958 tts.prefetcher.buildSound(sel); 959 960 }961 else{962 //if span has failed completely, add the span to the error report.963 if(sel.data('error_sound_loaded')){964 //$("#xhtml").append('<p>error sound loaded</p>');965 //add to error report array966 tts.config.prefetch.errorSpans.push(sel.data('number'));967 //may want to check typeof and set it up if it does not exist?968 //will also need to reset this and error spans in wipespans and possibly in json config969 if (tts.config.prefetch.alreadyReporting === false){970 tts.config.prefetch.alreadyReporting = true;971 tts.prefetcher.reportErrors();972 }//call error report array973 return;974 }975 else{976 //$("#xhtml").append('<p>sound has loaded</p>');977 sel.data('state',tts.config.prefetch.SPAN_HAS_LOADED_SOUND);978 if(tts.config.cache.enabled === true){979 if (sel.data('stored') === false){980 $.storage.set( sel.data('key'), sel.data('file'));981 sel.data('stored',true);982 }983 } 984 }985 }986 },987 /** end alteration **/988 onfinish: function(){989 if ((tts.config.spans.currentSpan < tts.config.spans.spanCollection.length -1 ) && (tts.config.spans.currentSpan > -1)){ 990 if(tts.config.spans.nextSpanToPlay == -1){991 tts.config.spans.nextSpanToPlay = sel.data('number');992 tts.config.spans.nextSpanToPlay++; 993 }994 tts.config.spans.playingSpans = 0;995 tts.spanController.playCurrentSpan(); 996 997 }998 //for the last span. it should pause everything instead of playing the next.999 else{1000 tts.config.spans.nextSpanToPlay = sel.data('number');1001 tts.spanController.pauseAll();1002 1003 }1004 }1005 } ) ); 1006 }1007 else{//build a queue1008 //$("#xhtml").append('<p>sound manager not enabled</p>');1009 if (typeof tts.config.SM !== 'undefined' && typeof tts.config.SM.HAS_ONREADY !== 'undefined'){1010 tts.config.SM.indices.push(sel.data('number'));1011 }1012 else{1013 //set up an onready event for soundManager to make a sound for each item in queue1014 $.extend(tts.config,{SM:{HAS_ONREADY:true,indices:[]}});1015 soundManager.onready(function(){1016 $.each( tts.config.SM.indices, function( index, value ) {1017 tts.prefetcher.buildSound(tts.config.spans.spanCollection.eq(value));1018 });1019 });1020 }1021 1022 }1023 },1024 reportErrors: function(){1025 1026 //prep things if necessary1027 if(typeof tts.config.prefetch.firstErrorPass !== 'undefined' && tts.config.prefetch.firstErrorPass === true){1028 if(typeof tts.config.prefetch.unfinishedSounds === 'undefined'){1029 //instantiate1030 $.extend(tts.config.prefetch,{1031 unfinishedSounds:[]1032 });1033 }1034 var unfinished = [];1035 for (i=0;i<tts.config.spans.spanCollection.length;i++){1036 var $span = tts.config.spans.spanCollection.eq(i);1037 if ($span.data('state') < tts.config.prefetch.SPAN_HAS_LOADED_SOUND){1038 unfinished.push = $span.data('number');1039 }1040 }1041 $.extend(tts.config.prefetch,{1042 unfinishedSounds:unfinished1043 });1044 tts.config.prefetch.firstErrorPass = false;1045 setTimeout(tts.prefetcher.reportErrors,2000);1046 return;1047 }1048 1049 //traverse the unfinished sounds and update the array1050 if(tts.config.prefetch.unfinishedSounds.length === 0){1051 var unfinished = [];1052 for (i=0;i<tts.config.prefetch.unfinishedSounds.length;i++){1053 var n = tts.config.prefetch.unfinishedSounds[i];1054 var $span = tts.config.spans.spanCollection.eq(n);1055 if ($span.data('state') < tts.config.prefetch.SPAN_HAS_LOADED_SOUND){1056 unfinished.push = $span.data('number');1057 }1058 }1059 $.extend(tts.config.prefetch,{1060 unfinishedSounds:unfinished1061 }); 1062 if (unfinished.length === 0){1063 var errors = tts.config.prefetch.errorSpans.length;1064 if (errors !== 0){1065 //ajax call to report to server.1066 var datas = {1067 "errors":errors,1068 "thisURL":window.location.pathname1069 };1070 1071 //collect all of the spans with status of 0.1072 for (i=0;i<errors;i++){1073 var $span = tts.config.spans.spanCollection.eq(tts.config.prefetch.errorSpans[i]);1074 var property_file = "file_"+i;1075 var property_text = "text_"+i;1076 $.extend(datas,{1077 property_file:$span.data('file'),1078 property_text:$span.data('text_to_speak')1079 });1080 }1081 1082 $.ajax({1083 asynch:false,1084 cache:false,1085 data:datas,1086 global:false,1087 dataType:'json',1088 beforeSend: function(x) {1089 if(x && x.overrideMimeType) {1090 x.overrideMimeType("application/j-son;charset=UTF-8");1091 }1092 },1093 timeout:60000,1094 type:"POST",1095 url:tts.config.prefetch.ERROR_REPORT_URL,1096 error:function(){1097 //possibly do variable reset here?1098 },1099 success:function(){1100 }1101 });//ajax end 1102 }1103 }1104 }1105 else {1106 setTimeout(tts.prefetcher.reportErrors,2000); 1107 }1108 }1109 },1110 spanController:{1111 changeCurrentSpan:function(){1112 //this overrides the next span called by onfinish1113 1114 if(tts.config.spans.nextSpanToPlay != -1){1115 tts.config.spans.previousSpan = tts.config.spans.currentSpan;1116 tts.config.spans.currentSpan = tts.config.spans.nextSpanToPlay;1117 tts.config.spans.nextSpanToPlay = -1; 1118 }1119 //if it has sound, reset it and pause it1120 //could put in a previousSpan != -1 clause1121 if(tts.config.spans.previousSpan != -1){1122 if(tts.config.spans.spanCollection.eq(tts.config.spans.previousSpan).data('state') == tts.config.prefetch.SPAN_HAS_LOADED_SOUND){1123 tts.config.spans.spanCollection.eq(tts.config.spans.previousSpan).data('sound').setPosition(0);1124 tts.config.spans.spanCollection.eq(tts.config.spans.previousSpan).data('sound').stop();1125 }1126 //if it has highlite/loading classes, remove them1127 if(tts.config.spans.spanCollection.eq(tts.config.spans.previousSpan).hasClass(tts.config.spans.highliteClass)){1128 tts.config.spans.spanCollection.eq(tts.config.spans.previousSpan).removeClass(tts.config.spans.highliteClass);1129 }1130 if(tts.config.spans.spanCollection.eq(tts.config.spans.previousSpan).hasClass(tts.config.spans.loadingClass)){1131 tts.config.spans.spanCollection.eq(tts.config.spans.previousSpan).removeClass(tts.config.spans.loadingClass);1132 }1133 }1134 //if span has a loaded sound1135 if(tts.config.spans.spanCollection.eq(tts.config.spans.currentSpan).data('state') == tts.config.prefetch.SPAN_HAS_LOADED_SOUND){1136 //remove the loading class if it is present1137 if(tts.config.spans.spanCollection.eq(tts.config.spans.currentSpan).hasClass(tts.config.spans.loadingClass)){1138 tts.config.spans.spanCollection.eq(tts.config.spans.currentSpan).removeClass(tts.config.spans.loadingClass);1139 }1140 //add the highlite class if it is not1141 if(!tts.config.spans.spanCollection.eq(tts.config.spans.currentSpan).hasClass(tts.config.spans.highliteClass)){1142 tts.config.spans.spanCollection.eq(tts.config.spans.currentSpan).addClass(tts.config.spans.highliteClass);1143 }1144 //reset the span position1145 tts.config.spans.spanCollection.eq(tts.config.spans.currentSpan).data('sound').setPosition(0);1146 tts.config.spans.spanCollection.eq(tts.config.spans.currentSpan).data('sound').stop();1147 }1148 else{1149 //add the loading class if it exists1150 if(!tts.config.spans.spanCollection.eq(tts.config.spans.currentSpan).hasClass(tts.config.spans.loadingClass)){1151 tts.config.spans.spanCollection.eq(tts.config.spans.currentSpan).addClass(tts.config.spans.loadingClass);1152 }1153 //remove the highlite class if it exists. this should not happen.1154 if(tts.config.spans.spanCollection.eq(tts.config.spans.currentSpan).hasClass(tts.config.spans.highliteClass)){1155 tts.config.spans.spanCollection.eq(tts.config.spans.currentSpan).addClass(tts.config.spans.highliteClass);1156 } 1157 } 1158 },1159 playCurrentSpan:function(){1160 1161 if (typeof tts.config.spans.spanCollection !== 'undefined' && tts.config.spans.spanCollection.length > 0){1162 1163 if (tts.config.spans.playingSpans < tts.config.spans.maxSimultaneousSpans){1164 tts.spanController.changeCurrentSpan();1165 if(tts.config.spans.spanCollection.eq(tts.config.spans.currentSpan).data('state') == tts.config.prefetch.SPAN_HAS_LOADED_SOUND){1166 tts.config.spans.spanCollection.eq(tts.config.spans.currentSpan).data('sound').play();1167 tts.config.spans.playingSpans = 1;1168 //console.log('now playing span: '+tts.config.spans.currentSpan);1169 }1170 }1171 }1172 },1173 pauseAll:function(){1174 if (soundManager.enabled){1175 //tts.config.spans.spanCollection.eq(tts.config.spans.currentSpan).data('sound').pause();1176 soundManager.stopAll();1177 if (tts.config.spans.playingSpans == 1){1178 tts.config.spans.playingSpans = 0;1179 }1180 1181 }1182 },1183 skip:function(n){1184 //change the currentSpan and call playCurrentSpan1185 if (typeof tts.config.spans.spanCollection !== 'undefined'){1186 tts.spanController.pauseAll();1187 if (((n + tts.config.spans.currentSpan) < tts.config.spans.spanCollection.length)&&((n + tts.config.spans.currentSpan) > -1)){1188 tts.config.spans.nextSpanToPlay = n + tts.config.spans.currentSpan;1189 notWaitingToPlayCurrent = true;1190 tts.spanController.playCurrentSpan();1191 return true;1192 }1193 else{1194 return false;1195 }1196 }1197 },1198 setVolume : function(n){1199 if (!soundManager.enabled){return;}1200 if (typeof tts.config.spans.spanCollection ==='undefined'){return;}1201 1202 //change volume property of the global object.1203 if (n >= 0 && n <= 100){1204 soundManager.defaultOptions.volume = n;1205 }1206 tts.config.spans.spanCollection.each(function(){1207 $this = $(this);1208 if (typeof $this.data('sound') !== 'undefined'){1209 $this.data('sound').setVolume(soundManager.defaultOptions.volume);1210 }1211 });1212 },1213 seekVolume: function(n){1214 if (!soundManager.enabled){return;}1215 if (typeof tts.config.spans.spanCollection ==='undefined'){return;}1216 if((soundManager.defaultOptions.volume + n <= 100) &&(soundManager.defaultOptions.volume + n >= 0)){1217 tts.spanController.setVolume(soundManager.defaultOptions.volume + n);1218 $( "#tts_volume_slider" ).slider('value', soundManager.defaultOptions.volume + n);1219 }1220 },1221 1222 mute : function(){1223 if (!soundManager.enabled){return;}1224 if (typeof tts.config.spans.spanCollection ==='undefined'){return;}1225 1226 //if currently muted, unmute everything.1227 if(soundManager.defaultOptions.globalMute){1228 soundManager.defaultOptions.globalMute = false1229 tts.spanController.setVolume(soundManager.defaultOptions.premute);1230 $( "#tts_volume_slider" ).slider('value', soundManager.defaultOptions.premute);1231 }1232 else{1233 //save the premute volume and set the volume of all of the sound objects to 01234 soundManager.defaultOptions.globalMute = true;1235 soundManager.defaultOptions.premute = soundManager.defaultOptions.volume;1236 tts.spanController.setVolume(0);1237 $( "#tts_volume_slider" ).slider('value', 0);1238 }1239 }1240 },1241 //should move UI to the controller file1242 UI:{1243 //with all of these, if sm is not configured and configuration is false, do not fire.1244 play : function(){1245 if (typeof tts.config.TTS.TTSConfigured ==='undefined'){return;}1246 tts.spanController.playCurrentSpan();1247 },1248 pause : function(){1249 if (typeof tts.config.TTS.TTSConfigured ==='undefined'){return;}1250 tts.spanController.pauseAll();1251 },1252 skipBack : function(){1253 tts.spanController.skip(-1);1254 },1255 skipForward: function(){1256 tts.spanController.skip(1);1257 },1258 volumeUp:function(){1259 tts.spanController.seekVolume(5);1260 },1261 volumeDown:function(){1262 tts.spanController.seekVolume(-5);1263 },1264 toggleMute:function(){1265 tts.spanController.mute();1266 },1267 setVolume:function(){1268 tts.spanController.setVolume( $( "#tts_volume_slider" ).slider('value') );1269 }1270 }...

Full Screen

Full Screen

EditBP.js

Source:EditBP.js Github

copy

Full Screen

1var buf='';2var ValId, ValCol, Str=0, Count=0;3$(document).ready(function(){4$(".color_table tr:not(#first_tr)").addClass("colors");5$(".colors:last").css("background-color", "#90ee90");6var tr_clr=$(".colors:last").css("background-color");7$(".colors:last").css("background-color", "white");8$(function()9{10 var CurCol;11 12 $('.color_table').on('mouseenter', 'tr', function()13 {14 if (this.className!="first_tr")15 { 16 CurCol=$(this).css("background-color");17 $(this).css("background-color", "yellow");18 }19 });20 $('.color_table').on('mouseleave', 'tr', function()21 { 22 if (this.className!="first_tr")23 $(this).css("background-color", CurCol);24 });25 26 $('.color_table').on('click', 'tr', function() 27 { 28 if(this.className!="first_tr" && CurCol!="rgb(255, 0, 0)")29 $(this).css("background-color", "red");30 else if (this.className!="first_tr")31 $(this).css("background-color", "");32 33 CurCol=$(this).css("background-color");34 });35 $('.color_table').on('dblclick', 'td', function(e) 36 {37 var t = e.target || e.srcElement;38 var elm_name = t.tagName.toLowerCase();39 if(elm_name != 'td')40 return false;41 42 window.Str= $(this).parent('tr').index();43 window.ValCol=$(this).index();44 window.ValId=$("#ColorTable tr:eq({0}) td:first".format(window.Str)).html();45 var val=$(this).html();46 window.buf=val;47 $(this).empty().append('<input type="text" id="edit" value="{0}"/>'.format(val));48 $('#edit').focus();49 $('#edit').blur(function() 50 {51 $(this).parent().empty().html(window.buf); 52 });53 });54});55$(window).keydown(function(event)56{57 if(event.keyCode == 13 && document.getElementById('edit')==document.activeElement) 58 {59 var ValData=$('#edit').val();60 RememberChanges(ValData, window.ValId, window.ValCol);61 window.buf=ValData;62 $('#edit').blur();63 }64});65});66/*67function isNumeric(n) {68 return !isNaN(parseFloat(n)) && isFinite(n);69}*/70function RememberChanges(ValData, ValId, ValCol)71{ 72 $("#DataField").append("<option selected value={0}>{0}</option>".format(ValData));73 $("#IdField").append("<option selected value={0}>{0}</option>".format(ValId));74 $("#ColumnField").append("<option selected value={0}>{0}</option>".format(ValCol));75}76function AddStr()77{78 var Id=$("#ColorTable tr:last td:first").html();79 if (isNumeric(Id)==true)80 Id++;81 else 82 Id=1;83 84 $("#AddStrField").append("<option selected value={0}>{0}</option>".format(Id));85 $("#ColorTable").append("<tr></tr>");86 $("#ColorTable tr:last").append("<td>{0}</td>".format(Id));87 88 for (i=1; i<$("#ColorTable tr:first td").length; i++)89 $("#ColorTable tr:last").append("<td></td>");90 91 return Id;92}93function AddColumn()94{ 95 $("#myform").append("<p>Введите имя нового столбца</p>");96 $("#myform").append("<p><input name='NewColName' id='NewColName'/></p>");97 $("#myform").append("<p>Введите тип данных нового столбца</p>");98 $("#myform").append("<p><select id=NewColType name=NewColType></select></p>");99 $("#NewColType").append("<option selected value={0}>{0}</option>".format('Целый'));100 $("#NewColType").append("<option value={0}>{0}</option>".format('Вещественный'));101 $("#NewColType").append("<option value={0}>{0}</option>".format('Текстовый'));102 $("#NewColType").append("<option value={0}>{0}</option>".format('Другой'));103 $("#myform").append("<p><input type='submit' name='DataEdit' value='{0}' onclick='ValidateColName(event)'/></p>".format('Записать столбец'));104}105function ValidateColName(event)106{107 if ($("#NewColName").val()=='')108 {109 $("#NewColName").css("border-color", "red");110 event.preventDefault();111 } 112}113function DelStr()114{115 for (i=$("#ColorTable tr").length-1; i>=1; i--)116 if ($("#ColorTable tr:eq({0})".format(i)).css("background-color")=="rgb(255, 0, 0)")117 {118 var Id=$("#ColorTable tr:eq({0}) td:eq({1})".format(i, 0)).html();119 $("#DelStrField").append("<option selected value={0}>{0}</option>".format(Id));120 $("#ColorTable tr:eq({0})".format(i)).remove();121 }122}123/*124function AddColumn2()125{126 var Table=document.getElementById("ColorTable");127 var inpt=document.createElement("input");128 var sel=document.createElement("select");129 var cell=document.createElement("td");130 131 inpt.name="AddColName"+window.Count;132 sel.name="AddColType"+window.Count++;133 sel.options[0] = new Option("INTEGER", "INTEGER", true, true);134 sel.options[1] = new Option("REAL", "REAL");135 sel.options[2] = new Option("TEXT", "TEXT");136 sel.options[3] = new Option("HZ", "HZ");137 cell.width=140; 138 cell.appendChild(inpt);139 cell.appendChild(sel);140 Table.rows[0].appendChild(cell);141 142 for (i=1; i<Table.rows.length; i++)143 {144 var cell=document.createElement("td");145 cell.width=140;146 Table.rows[i].appendChild(cell);147 }148}*/149function AddColumn2()150{ 151 $("#ColorTable tr:first").height(50);152 $("#ColorTable tr:first").append("<p><input name='AddColName{0}'/></p>".format(window.Count));153 $("#ColorTable tr:first").append("<p><select id=AddColType{0} name=AddColType{0}></select></p>".format(window.Count));154 $("#AddColType{0}".format(window.Count)).append("<option selected value={0}>{0}</option>".format('Целый'));155 $("#AddColType{0}".format(window.Count)).append("<option value={0}>{0}</option>".format('Вещественный'));156 $("#AddColType{0}".format(window.Count)).append("<option value={0}>{0}</option>".format('Текстовый'));157 $("#AddColType{0}".format(window.Count)).append("<option value={0}>{0}</option>".format('Другой'));158 159 window.Count++;160 161 for (i=1; i<$("#ColorTable tr").length; i++)162 $("#ColorTable tr:eq({0})".format(i)).append("<td></td>");163}164function ValidateAddCol()165{166 $("#AddColCount").val(window.Count);167}168function AddDataFromFile(filem)169{170 var reader=new FileReader();171 tfile=filem.files[0];172 173 reader.onload = function(event) 174 {175 var text = event.target.result, data='';176 var CurRow=$("#ColorTable tr").length, CurCol=1, NewId;177 178 if (text.length!=0) NewId=AddStr();179 180 for (var i=0; i<text.length; i++)181 {182 switch(text[i])183 {184 case ';':185 case ',':186 $("#ColorTable tr:eq({0}) td:eq({1})".format(CurRow, CurCol)).html(data);187 RememberChanges(data, NewId, CurCol);188 CurCol++;189 data='';190 break;191 case '\n':192 $("#ColorTable tr:eq({0}) td:eq({1})".format(CurRow, CurCol)).html(data);193 RememberChanges(data, NewId, CurCol);194 CurRow++;195 CurCol=1;196 data='';197 if (i+1<text.length) NewId=AddStr();198 break;199 default:200 data+=text[i];201 }202 }203 204 $("#ColorTable tr:eq({0}) td:eq({1})".format(CurRow, CurCol)).html(data);205 RememberChanges(data, NewId, CurCol);206 };207 208 reader.readAsText(tfile);209}210function Algorithms(AlgorithmValue)211{212 switch(AlgorithmValue)213 {214 case 'Classification':215 $("#DivKMeans").attr("hidden", true);216 $("#DivClassification").attr("hidden", false);217 break;218 case 'KMeans':219 $("#DivKMeans").attr("hidden", false);220 $("#DivClassification").attr("hidden", true);221 break;222 case 'TimurAlgorithm':223 $("#DivKMeans").attr("hidden", true);224 $("#DivClassification").attr("hidden", true);225 break;226 }227}228/*-----Новый код-----*/229var DelArr={}, DelTdArr={}, TabCh;230// ----- Код WorkWithStrings -----231function HighlightStr()232{233 var TrCollection=$("#TabData tr"),234 HFrom=$("#HighlightFrom").val(), HTo=$("#HighlightTo").val(), 235 TrNumFrom=GetId(TrCollection, HFrom), TrNumTo=GetId(TrCollection, HTo),236 Color="red";237 238 if ($("[name=Highlight]:checked").val()=='off')239 Color="";240 if (HFrom!=+TrCollection.eq(TrNumFrom).find("td").eq(0).html())241 {242 alert("Введите существующий id начала диапазона!");243 return;244 }245 if (HTo!=+TrCollection.eq(TrNumTo).find("td").eq(0).html())246 {247 alert("Введите существующий id конца диапазона!");248 return;249 }250 251 var fragment=document.createDocumentFragment();252 253 for (i=TrNumFrom; i<=TrNumTo; i++)254 TrCollection.eq(i).clone().css("background-color", Color).appendTo(fragment);255 256 for (i=TrNumFrom; i<=TrNumTo; i++)257 TrCollection.eq(i).remove();258 259 TrCollection.eq(TrNumFrom-1).after(fragment);260 261 //$("#TabData").append(fragment);262 //alert("TrNumFrom: {0} TrNumTo: {1}".format(TrNumFrom, TrNumTo));263}264function RandomHighlightStr()265{266 var TrCollection=$("#TabData tr"),267 HFrom=$("#RandomHighlightFrom").val(), HTo=$("#RandomHighlightTo").val(),268 TrNumFrom=GetId(TrCollection, HFrom), TrNumTo=GetId(TrCollection, HTo),269 HCount=$("#RandomHighlightCount").val(),270 Color="red", Id;271 272 if (HFrom!=+TrCollection.eq(TrNumFrom).find("td").eq(0).html())273 {274 alert("Введите существующий id начала диапазона!");275 return;276 }277 if (HTo!=+TrCollection.eq(TrNumTo).find("td").eq(0).html())278 {279 alert("Введите существующий id конца диапазона!");280 return;281 }282 283 if (HTo-HFrom+1<=HCount)284 {285 var fragment=document.createDocumentFragment();286 287 for (i=TrNumFrom; i<=TrNumTo; i++)288 TrCollection.eq(i).clone().css("background-color", Color).appendTo(fragment);289 290 for (i=TrNumFrom; i<=TrNumTo; i++)291 TrCollection.eq(i).remove();292 293 TrCollection.eq(TrNumFrom-1).after(fragment);294 }295 else296 {297 for (i=0; i<HCount; i++)298 {299 for (j=0; j<1;)300 {301 Id = TrNumFrom + Math.random() * (TrNumTo + 1 - TrNumFrom);302 Id = Math.floor(Id);303 if (TrCollection.eq(Id).css("background-color")!="rgb(255, 0, 0)")304 {305 TrCollection.eq(Id).css("background-color", "red");306 j++;307 }308 }309 }310 }311}312function InsertStr()313{314 var CountStr=$("#InsertStrCount").val();315 $.ajax({316 type: "POST", 317 url: "/EditBPRequest",318 data: {TableChoice: TabCh, Operation: "Insert", Count: CountStr},319 success: function(data){320 var json=JSON.parse(data), fragment=document.createDocumentFragment(), tr;321 for (i=0; i<json['LastInsertRowId'].length; i++)322 {323 tr=document.createElement("tr");324 $("<td/>", {text: json['LastInsertRowId'][i]}).appendTo(tr)325 for (j=1; j<$("#TabData tr:first th").length; j++)326 tr.insertCell(j);327 328 fragment.appendChild(tr);329 }330 331 $("#TabData").append(fragment);332 }333 });334}335function DeleteStr()336{337 //var TabCh=$("#TableChoice option:selected").text();338 339 $.ajax({340 type: "POST", 341 url: "/EditBPRequest",342 data: {TableChoice: TabCh, Operation: "Delete", JsonObj: JSON.stringify(DelArr)},343 success: function(data){344 for (var i in DelTdArr)345 DelTdArr[i].remove();346 alert('Success Delete');347 }348 });349}350function DeleteAllStr()351{352 $.ajax({353 type: "POST", 354 url: "/EditBPRequest",355 data: {TableChoice: TabCh, Operation: "DeleteAll"},356 success: function(data){357 var th=$("#TabData tbody tr:first");358 $("#TabData tbody").replaceWith("<tbody></tbody>");359 $("#TabData").append(th);360 alert('Success DeleteAll');361 }362 });363}364// -------------------------365// ----- Код WorkWithColumns -----366function InsertColumn()367{368 //var AddColDiv=$("<div><p>Название столбца<input type='text' id='ColumName'></p><input type='button' ><></div>");369 var Div=$("<div>");370 Div.append($("<p>", {text: "Название столбца"}));371 Div.append($("<input>", {type: 'button', text: 'Cоздать столбец'}));372 alert('OK');373}374// -------------------------375// ----- Код WorkWithData -----376function AddDataFromFile()377{378 var tfile=$("#ImportBPFile").prop('files')[0], FD= new FormData();379 FD.append("ImportBPFile", tfile);380 FD.append("TableChoice", TabCh);381 FD.append("Operation", "Load From File");382 $.ajax({383 type: "POST", 384 url: "/EditBPRequest",385 data: FD,386 cache: false,387 dataType: 'json',388 processData: false,389 contentType: false,390 success: function(data){391 LoadBP(TabCh, data['LastId'], data['TCBI'], data['TCAI'], 150);392 alert('Success Load From File');393 }394 });395}396function ExportTestSampleToFile()397{398 var TestSample=$("#TabData tr"), Id="";399 for (i=1; i<TestSample.length; i++)400 if (TestSample.eq(i).css("background-color")=="rgb(255, 0, 0)")401 Id+=TestSample.eq(i).find("td").eq(0).html()+",";402 $("[name=HiddenTableChoice]").val(TabCh); 403 $("[name=HiddenTestSample]").val(Id.slice(0, Id.length-1));404}405// -------------------------406// ----- Код WorkWithTable -----407function DeleteBP()408{ 409 var BPChoice={}, SelectedTables=$("#TabSelect a[class='list-group-item active']");410 411 $(SelectedTables).each(function(i){412 BPChoice[i]=$(this).html();413 });414 $.ajax({415 type: "POST",416 async: false, //Подумай над синхронностью... 417 url: "/DeleteBP",418 data: {BPChoice: JSON.stringify(BPChoice)},419 success: function(){420 $(SelectedTables).each(function(i){421 if ($(this).html()==TabCh)422 {423 $("#TabData tbody").replaceWith("<tbody></tbody>").append("<tr></tr>");424 $("#DescrTabData tbody").replaceWith("<tbody></tbody>").append("<tr></tr>");425 $("#TableChoiceTab a span").html("Выберите базу");426 }427 $(this).remove();428 });429 }430 });431}432function RenameBP()433{434 var NewBPNames={}, RenamedTables=$("#TabSelect a");435 436 $(RenamedTables).each(function(i){437 NewBPNames[i]=$(this).html();438 });439 440 $.ajax({441 type: "POST",442 url: "/RenameBP",443 data: {NewBPNames: JSON.stringify(NewBPNames)},444 success: function(){445 alert("Переименовывание таблиц успешно завершено!");446 }447 }); 448}449// -------------------------450// ----- Код ImproveEfficiency -----451function Optimization()452{453 var OptAlgol=$("#OptAlgol option:selected").val(),454 OptArr={"OptAlgol": OptAlgol};455 switch(OptAlgol)456 {457 case 'Classification':458 OptArr['ClassSimilarity']=$("#ClassSimilarity").val();459 OptArr['ClassMetric']=$("#ClassMetric option:selected").val();460 break;461 case 'KMeans':462 OptArr['KMClusterCount']=$("#KMClusterCount").val();463 OptArr['KMPrimaryCenter']=$("#KMPrimaryCenter option:selected").val();464 OptArr['KMMetric']=$("#KMMetric option:selected").val();465 break;466 case 'TimurAlgorithm':467 break;468 }469 470 $.ajax({471 type: "POST", 472 url: "/OptimizationBP",473 data: {TableChoice: TabCh, JsonObj: JSON.stringify(OptArr)},474 success: function(data){475 alert('Success Optimization!');476 }477 });478}479function ShowOptAlgolOptions()480{481 var OptAlgol=$("#OptAlgol option:selected").val();482 switch(OptAlgol)483 {484 case 'Classification':485 $("#DivKMeans").hide();486 $("#DivClassification").show();487 break;488 case 'KMeans':489 $("#DivClassification").hide();490 $("#DivKMeans").show();491 break;492 case 'TimurAlgorithm':493 $("#DivClassification").hide();494 $("#DivKMeans").hide();495 break;496 }497}498// -------------------------499function EditBPRequest()500{501 //TabCh=$("#TableChoice option:selected").text();502 LookBPRequest();503}504/*505function InsertStr(Count)506{507 //var TabCh=$("#TableChoice option:selected").text(),508 var tr=document.createElement("tr"),509 td=tr.insertCell(0);510 511 512 513 for (var i=1; i<$("#TabData tr:first th").length; i++)514 tr.insertCell(i);515 516 $("#TabData").append(tr);517 518 $.ajax({519 type: "POST", 520 url: "/EditBPRequest",521 data: {TableChoice: TabCh, Operation: "Insert"},522 success: function(data){523 var json=JSON.parse(data);524 td.innerHTML=json['LastInsertRowId'];525 }526 });527}*/528/*529function UpdateStr()530{531 //var TabCh=$("#TableChoice option:selected").text();532 533 if (jsonObj)534 {535 $.ajax({536 type: "POST", 537 url: "/EditBPRequest",538 data: {TableChoice: TabCh, Operation: "Update", JsonObj: JSON.stringify(UpdArr)},539 success: function(data){540 alert('Success Update');541 }542 });543 }544}*/545//Наведения курсора на таблицы546$(function()547{548 // ----- Наведение и клики по таблице прецедентов -----549 var CurCol;550 551 $('#TabData').on('mouseenter', 'tr', function()552 {553 if (this.className!="first_tr")554 { 555 CurCol=$(this).css("background-color");556 $(this).css("background-color", "yellow");557 }558 });559 $('#TabData').on('mouseleave', 'tr', function()560 { 561 if (this.className!="first_tr")562 $(this).css("background-color", CurCol);563 });564 565 $('#TabData').on('click', 'tr', function() 566 { 567 if(this.className!="first_tr" && $(this).css("background-color")!="rgb(255, 0, 0)")568 {569 $(this).css("background-color", "red");570 DelArr[$(this).find('td')[0].innerHTML]=$(this).find('td')[0].innerHTML;571 DelTdArr[$(this).find('td')[0].innerHTML]=$(this);572 //alert(DelTdArr[$(this).find('td')[0].innerHTML]);573 }574 else if (this.className!="first_tr")575 {576 $(this).css("background-color", "");577 delete DelArr[$(this).find('td')[0].innerHTML];578 delete DelTdArr[$(this).find('td')[0].innerHTML];579 }580 581 CurCol=$(this).css("background-color");582 });583 // --------------------------584 585 // ----- Двойные клики по таблице прецедентов -----586 587 $("#TabData").on('dblclick', 'td', function(){588 if ($(this).find('input').length==0)589 {590 var Val=$(this).html();591 592 $('<input>', {593 'id': 'EditTd',594 'type': 'text',595 'class': 'form-control',596 'value': Val,597 'css': {598 'color': 'black',599 'text-align': 'center',600 'height': '100%',601 },602 }).appendTo($(this).empty()).focus(); 603 604 $("#EditTd").on('blur', function()605 {606 $("#EditTd").parent().empty().html(Val);607 });608 609 $("#EditTd").on('keydown', function(e){610 if (e.keyCode==13)611 {612 var Val=$("#EditTd").val(), 613 ColName=$("#TabData tr:first").find("th").eq($(this).parent().index()).html(),614 Id=$("#EditTd").parent().parent().find('td')[0].innerHTML,615 UpdArr={"Id":Id, "ColName":ColName, "Value": Val};616 617 $.ajax({618 type: "POST", 619 url: "/EditBPRequest",620 data: {TableChoice: TabCh, Operation: "Update", JsonObj: JSON.stringify(UpdArr)},621 success: function(data){622 alert('Success Update');623 $("#EditTd").parent().empty().html(Val);624 }625 });626 }627 });628 }629 });630 631 $("#TabData").on('dblclick', 'th', function(){632 if ($(this).find('input').length==0)633 {634 var Val=$(this).html();635 636 $('<input>', {637 'id': 'EditTh',638 'type': 'text',639 'class': 'form-control',640 'value': Val,641 'css': {642 'color': 'black',643 'text-align': 'center',644 'height': '100%',645 },646 }).appendTo($(this).empty()).focus(); 647 648 $("#EditTh").on('blur', function()649 {650 $("#EditTh").parent().empty().html(Val);651 });652 653 $("#EditTh").on('keydown', function(e){654 if (e.keyCode==13)655 {656 var Val=$("#EditTh").val(), 657 ColName=$("#TabData tr:first").find("th").eq($("#EditTh").parent().index()).html(),658 UpdArr={"ColName":ColName, "Value": Val};659 660 $.ajax({661 type: "POST", 662 url: "/EditBPRequest",663 data: {TableChoice: TabCh, Operation: "RenameColumn", JsonObj: JSON.stringify(UpdArr)},664 success: function(data){665 alert('Success Rename Column');666 $("#EditTh").parent().empty().html(Val);667 }668 });669 }670 });671 }672 });673 // --------------------------674 675 // ------- Клики по списку с именами БП -------676 $("#TabSelect").on('click', 'a', function(){677 if ($(this).find('input').length==0)678 {679 if ($(this).attr("class")=="list-group-item")680 $(this).attr("class", "list-group-item active");681 else682 $(this).attr("class", "list-group-item");683 }684 });685 686 $("#TabSelect").on('dblclick', 'a', function(){687 if ($(this).find('input').length==0)688 {689 var Val=$(this).html();690 691 $('<input>', {692 'id': 'NewBPName',693 'type': 'text',694 'class': 'form-control',695 'value': Val,696 'css': {697 'color': 'black',698 'text-align': 'center',699 'height': '100%',700 },701 }).appendTo($(this).empty()).focus();702 703 $("#NewBPName").on('blur', function(){704 $("#NewBPName").parent().empty().html(Val);705 });706 707 $("#NewBPName").on('keydown', function(e){708 if (e.keyCode==13)709 {710 var Val=$("#NewBPName").val();711 $("#NewBPName").parent().empty().html(Val);712 }713 });714 }715 });716 // ----------------------------717});718//Обработчики кнопок719$(function(){720 $('#InsertManyStr').on('click', InsertStr);721 722 $('#ExportBPToFile').on('click', function(){723 $("[name=HiddenTableChoice]").val(TabCh);724 });725 726 $('#ExportTestSampleToFile').on('click', ExportTestSampleToFile);727 728 $('#ExportTrainSampleToFile').on('click', ExportTestSampleToFile);729 730 $("#TableChoiceTab ul li").on('click', 'a', function()731 {732 TabCh=$(this).html();733 $("#TableChoiceTab a span").html(TabCh);734 LookBPRequest(TabCh);735 });736 737 $('.btn-file input[type=file]',).on('change', function (){738 var FileName=$(this).val();739 //alert($(this).parent());740 $('.btn-file .btn-file-name').html(FileName);741 });742 743 $("#RenameBP").on('click', RenameBP);744 745 $("#DeleteBP").on('click', DeleteBP);746 747 $("#HighlightStr").on('click', HighlightStr);748 749 $("#RandomHighlightStr").on('click', RandomHighlightStr);750 $("#OptAlgol").on('change', ShowOptAlgolOptions);751 $("#DeleteStr").on('click', DeleteStr);752 $("#DeleteAllStr").on('click', DeleteAllStr);753 $("#InsertColumn").on('click', InsertColumn);754 $("#AddDataFromFile").on('click', AddDataFromFile);755});756function GetId(TrCollection, Id)757{758 var TrId=+TrCollection.eq(Id).find("td").eq(0).html(), 759 TrNumId=TrId;760 if(TrId!=Id)761 { 762 if (TrId>Id && TrId-Id<=Id)763 {764 for (TrNumId=TrId; TrNumId>=0 && TrId!=Id; TrNumId--)765 TrId=+TrCollection.eq(TrNumId).find("td").eq(0).html();766 767 TrNumId++;768 }769 else if (TrId>Id && TrId-Id>Id)770 {771 for (TrNumId=0; TrNumId<TrCollection.length && TrId!=Id; TrNumId++)772 TrId=+TrCollection.eq(TrNumId).find("td").eq(0).html();773 774 TrNumId--;775 }776 else if (TrId<Id && Id-TrId<=$("#TabData tr").length-Id) 777 {778 for (TrNumId=TrId; TrNumId<TrCollection.length && TrId!=Id; TrNumId++)779 TrId=+TrCollection.eq(TrNumId).find("td").eq(0).html();780 781 TrNumId--;782 }783 else if (TrId<Id && Id-TrId>$("#TabData tr").length-Id)784 {785 for (TrNumId=TrCollection.length-1; TrNumId>=0 && TrId!=Id; TrNumId--)786 TrId=+TrCollection.eq(TrNumId).find("td").eq(0).html();787 788 TrNumId++;789 }790 else791 {792 for (TrNumId=0; TrNumId<TrCollection.length && TrId!=Id; TrNumId++)793 TrId=+TrCollection.eq(TrNumId).find("td").eq(0).html();794 795 TrNumId--;796 }797 }798 799 return TrNumId;...

Full Screen

Full Screen

eeTransitionEffects.js

Source:eeTransitionEffects.js Github

copy

Full Screen

1//This JS library contains methods to accomplish the generic transition effect/23// smooth scrolling variables4var headerHeight = $('header').height() + 140;567function genericSaveAndContinueTransition(currentPanelId, nextPanelId)8{910 11 //animation for Save12 if(typeof currentPanelId !== 'undefined'){13 var currentSaveId = $('#'+currentPanelId).find('.btn.btn-primary.btn-large.saveButton').attr('id');14 var currentEditId = $('#'+currentPanelId).find('.btn.btn-inverse.btn-large.priorCardButton').attr('id');15 var currentSectionID = $('#'+currentPanelId).find('.section').attr('id');16 17 //If container had a form section disable it18 if(typeof currentSectionID !== 'undefined'){19 toggleFormControls(currentSectionID, true);20 $('#'+currentSectionID).addClass('transparent');21 }22 //If container has a save button hide it23 if(typeof currentSaveId !== 'undefined'){24 $('#'+currentSaveId).hide();25 }26 //If container has a edit button show it27 if(typeof currentEditId !== 'undefined'){28 $('#'+currentEditId).show();29 }30 31 }32 33 if(typeof nextPanelId !== 'undefined'){34 var nextSection = $('#'+nextPanelId).find('.section');35 36 if(nextSection.hasClass('transparent')){37 //remove previous transition38 genericPreviousTransition(nextPanelId);39 }else{40 //Default next panel transition41 var scrollToPosition = $('#'+nextPanelId).offset().top - headerHeight;42 $('html, body').animate({ scrollTop: scrollToPosition }, 500);43 }44 }4546}4748function genericPreviousTransition(currentPanelId)49{50 //animation for Edit51 if(typeof currentPanelId !== 'undefined'){52 var scrollToPosition = $('#'+currentPanelId).offset().top - headerHeight;53 $('html, body').animate({ scrollTop: scrollToPosition }, 500);54 $('#'+currentPanelId + ' > div > .transparent').removeClass('transparent');55 var currentSaveId = $('#'+currentPanelId).find('.btn.btn-primary.btn-large.saveButton').attr('id');56 var currentEditId = $('#'+currentPanelId).find('.btn.btn-inverse.btn-large.priorCardButton').attr('id'); 57 var currentSectionID = $('#'+currentPanelId).find('.section').attr('id');5859 //If container had a form section enable it60 if(typeof currentSectionID !== 'undefined'){61 toggleFormControls(currentSectionID, false);62 }63 //If container has a save button hide it64 if(typeof currentSaveId !== 'undefined'){65 $('#'+currentSaveId).show();66 }67 //If container has a edit button hide it68 if(typeof currentEditId !== 'undefined'){69 $('#'+currentEditId).hide();70 }71 }72}7374/**75 * Utility function currently utilized for backwards navigation transitions in the income section. Should be usable by other sections.76 *77 * @param evt the click event78 * @param BBview a reference to the backbone view handling the click event79 * @param router a reference to the backbone router object80 * @param cardName the name of the card to navigate to in the router81 * @param transitionId the id of the page to transition to, visually82 *83 */84function rewindToCard(evt, BBview, router, cardName, transitionId) {85 var target = evt.target || evt.srcElement; // some browsers use target, others use srcElement86 var indexMatch = target.id.match(/\d+$/);87 if (indexMatch) {88 index = indexMatch[0];89 } else {90 index = "";91 }92 indAppState.setIndex(parseInt(index, 10));93 if(isEmpty(index)){94 indAppState.setIndex(0);95 index = "";96 }97 genericPreviousTransition(transitionId + index);98 $("#" + transitionId + index).nextAll(".cardContainer").hide();99 router.navigate(cardName, {trigger: true});100 BBview.refreshTemplate();101}102103104/**105 * Set the designated top-level section as the active section of the application106 * 107 * @param sectionId the section to make the active section108 * @param subsectionHtml optional HTML to use for subsections. If nothing is passed here the function will check for hidden subsection <li>s pre-added by a template109 * 110 */111function updateAppProgress(sectionId, subsectionHtml) {112 jqEle = $("#" + sectionId);113 114 // set classes and HiddenText for current section115 jqEle116 .addClass("complete")117 118 .children("i")119 .removeClass("icon-circle_ok iconCustom-circle-blank")120 .addClass("icon-circle_arrow_down")121 122 .siblings("a")123 .removeClass("disabledItem").attr("href","#")124 125 .siblings("span.HiddenText")126 .text(", current section");127 128 // set classes for previous sections 129 jqEle130 .prevAll(".nav-header")131 .addClass("complete")132 133 .children("i")134 .removeClass("icon-circle_arrow_down iconCustom-circle-blank")135 .addClass("icon-circle_ok")136 137 .siblings("a")138 .removeClass("disabledItem").attr("href","#")139 140 .siblings("span.HiddenText")141 .text(", completed section");142143 // set classes for upcoming sections144 jqEle145 .nextAll(".nav-header")146 .removeClass("active")147 148 .children("i")149 .removeClass("icon-ok_2 complete")150 151 .siblings("a")152 .addClass("disabledItem").removeAttr("href")153 154 .siblings("span.HiddenText")155 .text(", upcoming section");156 157 // hide subsection HTML for all sections158 $(".nav-subsection").hide();159 // add back subsection HTML for this section160 if (typeof subsectionHtml !== "undefined") {161 $('<ul class="nav nav-pills nav-stacked nav-subsection"></ul>').appendTo("#" + sectionId).append(subsectionHtml);162 } else {163 $("#" + sectionId + " .nav-subsection").show();164 }165 166 // number subsections167 if ($("#" + sectionId + " .nav-subsection li").length > 0) {168 $("#" + sectionId + " .nav-subsection li i.icon-number").each(function(i,ele){169 $(this).text(i+1).data("displayindex", i+1);170 });171 }172}173174/**175 * Gives the specified progress substep the "active" class and removes active class from all other substeps176 * 177 * @param id the id of the substep to designate as active178 * @return void179 */180function updateAppSubsectionProgress(id) {181 jqEle = $("#" + id);182 183 // set this subsection to active subsection184 jqEle185 .addClass("active")186 .children("i")187 .attr("class", "icon-number")188 .each(function(){189 $(this).text($(this).data("displayindex"));190 })191 .siblings("span.HiddenText")192 .text(", current step");193194 // set stuff for previous subsections 195 jqEle196 .prevAll("li[id*='subSection']")197 .removeClass("active")198 .children("i")199 .attr("class", "icon-ok_2 complete")200 .text("")201 .siblings("span.HiddenText")202 .text(", completed step");203204 // set classes for upcoming sections205 jqEle206 .nextAll("li[id*='subSection']")207 .removeClass("active")208 .children("i")209 .attr("class", "icon-number")210 .each(function(){211 $(this).text($(this).data("displayindex"));212 })213 .siblings("span.HiddenText")214 .text(", upcoming step");215}216217/**218 * Converts an application members object to HTML for use as subsections in the application progress area.219 * Resulting markup can be fed into updateAppProgress()220 * 221 * @param members Array of application members222 * @param target id of the nav element representing the current top-level section (Income, FAH, etc.)223 * @return HTML string224 */225function convertMembersToSubsectionHtml(members, target) {226 if ((typeof members !== "undefined") && (typeof target !== "undefined") && (!isEmpty(members))) {227 var listHtml = '';228 for (var i = 0; i < members.length; i++) {229 if (members[i] !== null) {230 memberName = getAppMemberFullName(members[i]);231 232 var liStr = '<li id="' + target + 'subSection' + i + '"' +233 '><i class="icon-number"></i>' + '<a href="#" class="wordWrap">' +234 memberName +235 '</a></li>';236 237 listHtml += liStr;238 }239 }240 return listHtml;241 }242}243244function createSubsectionHtml(displayName, identifier, target) {245 var html = '<li id="' + target + 'subSection' + identifier + '"><i class="icon-number"></i><a href="#">' + displayName + '</a></li>';246 return html;247}248249/**250 * Toggles the display of the income substep251 * 252 * @param boolean value, true indicates show the substep, false indicates hide253 * @return void254 */255function toggleIncomeSubstepDisplay(toggle) {256 if (toggle)257 {258 $('#indAppStep2').show();259 }260 else261 {262 $('#indAppStep2').hide();263 }264}265266// DEPRECATED267//////////////////////////Update Left Nav/////////////////////////268//takes in a string and a collection of elements and and index to set the progressBar269//userSection - section or subsection user is on270//elementCollection - collection of elements271//index - used for income update272//// NOTE -- these functions are deprecated in favor of updateAppSubsectionProgress and updateAppProgress above.273// these functions can be erased when all references to them are removed274function setAppProgress(userSection, elementCollection, index){275 var i, num, previousSelect, innerElement, listNum, innerLink, innerSpan;276 // users current section gotten either from userSecttion or index277 // index for when the user is in the income section278 if(!isEmpty(userSection)){279 // passing 10 as radix 280 userSection = parseInt(userSection.replace(/[^0-9]+/gi, ''), 10);281 }else if(!isEmpty(index)){282 userSection = index;283 }284 285 for(i = 0; i < elementCollection.length; i++){286 287 // item from progress bar288 // passing 10 as radix289 num = parseInt(elementCollection.eq(i).attr('id').replace(/[^0-9]+/gi, ''), 10);290 listNum = num +1;291 previousSelect = userSection - num;292 innerElement = elementCollection.eq(i).children().eq(0);293 innerLink = elementCollection.eq(i).children().eq(1);294 innerSpan = elementCollection.eq(i).children().eq(2);295 296 297 // users current progress298 if(userSection > num){299 // This means user has gone past this section300 301 elementCollection.eq(i).removeClass('active');302 innerElement.removeClass('icon-number');303 if (innerSpan.is("span")) {304 innerSpan.text(', completed step');305 } 306 307 innerElement.addClass('icon-ok_2');308 innerElement.addClass('complete');309 innerElement.text('');310 //Navigate back based on navigation item count311 innerLink.attr("href", "javascript:window.history.go(-"+ previousSelect +");");312 313 314 }else if(userSection === num){315 // This means user is on this section316 317 // remove un-needed classes318 innerElement.removeClass('icon-ok_2');319 innerElement.removeClass('complete');320 if (innerSpan.is("span")) {321 innerSpan.remove();322 } 323324 elementCollection.eq(i).addClass('active');325 elementCollection.eq(i).append('<span class="HiddenText">, current step</span>');326327 //Accounts for backwards re-selection of nav item328 if(innerElement.text() === ''){329 innerElement.text(''+listNum+'');330 innerElement.addClass('icon-number');331 }332 333 }else if(userSection < num){334 // This means user has yet to complete this section335336 // remove un-needed classes337 innerElement.removeClass('icon-ok_2');338 innerElement.removeClass('complete');339 innerElement.addClass('icon-number');340 if (innerSpan.is("span")) {341 innerSpan.text(', upcoming step');342 } 343344 innerElement.text(i+1);345 elementCollection.eq(i).removeClass('active');346 }347 }348}349350// this function is deprecated, see above351function setAppSectionProgress(userSection, elementCollection, index){352 var i, num, innerElement, innerSpan, nextElement;353 // users current section gotten either from userSecttion or index354 // index for when the user is in the income section355 if(!isEmpty(userSection)){356 // passing 10 as radix 357 userSection = parseInt(userSection.replace(/[^0-9]+/gi, ''), 10);358 }else if(!isEmpty(index)){359 userSection = index;360 }361 362 for(i = 0; i < elementCollection.length; i++){363 364 // item from progress bar365 // passing 10 as radix366 num = parseInt(elementCollection.eq(i).attr('id').replace(/[^0-9]+/gi, ''), 10);367 innerElement = elementCollection.eq(i).children().eq(0);368 innerSpan = elementCollection.eq(i).children().eq(2);369 // users current progress370 371 //<i class="icon-ok_2 complete" aria-hidden="true"></i>372 373 if(userSection > num){374 // user has gone past this section375376 // remove un-needed classes377 innerElement.removeClass('icon-circle_arrow_down');378 innerElement.removeClass('iconCustom-circle-blank');379 if (innerSpan.is("span")) {380 innerSpan.text(', completed section');381 } 382 383 // add necessary classes384 innerElement.addClass('icon-circle_ok');385 elementCollection.eq(i).addClass('complete');386 387 //hide subsections388 nextElement = elementCollection.eq(i).next();389 while (!nextElement.hasClass('divider') && nextElement.length !== 0)390 {391 nextElement.hide();392 nextElement = nextElement.next();393 }394 395 }else if(userSection === num){396 // user is on this section397 398 // remove un-needed classes399 innerElement.removeClass('icon-circle_ok');400 innerElement.removeClass('iconCustom-circle-blank');401 if (innerSpan.is("span")) {402 innerSpan.text(', current section');403 } 404405 // add necessary classes406 innerElement.addClass('icon-circle_arrow_down');407 elementCollection.eq(i).addClass('complete');408 409 //$(".nav-header").removeClass("divider") // remove divider from all indApp progress sections410 // .not(elementCollection.eq(i), " :last").addClass("divider"); // then add it back to all except target and final sections411 412 //show all subsections413 nextElement = elementCollection.eq(i).next();414 while (!nextElement.hasClass('divider') && nextElement.length !== 0)415 {416 nextElement.show();417 nextElement = nextElement.next();418 }419 420 }else if(userSection < num){421 // user has yet to complete this section422423 // remove un-needed classes424 innerElement.removeClass('icon-circle_ok');425 innerElement.removeClass('icon-circle_arrow_down');426 elementCollection.eq(i).removeClass('complete');427428 // add necessary classes429 innerElement.addClass('iconCustom-circle-blank');430 431 //hide all subsections432 nextElement = elementCollection.eq(i).next();433 while (!nextElement.hasClass('divider') && nextElement.length !== 0)434 {435 nextElement.hide();436 nextElement = nextElement.next();437 }438 }439 }440}441442 ...

Full Screen

Full Screen

slide.js

Source:slide.js Github

copy

Full Screen

1//====================================================================================================2// [插件名称] jQuery ImgSlider3//----------------------------------------------------------------------------------------------------4//[描 述] 一个图片切换插件,可以预览,可以动态做出图片说明5//[使用方法] 生成一个DIV,包含需要幻灯演示的图片,然后用一个DIV包裹,并且用这个包裹的DIV直接调用ImgSlider方法6// 如:<div id="diva"><div class="divb">你的图片</div></div>7//简单调用:$("#diva").ImgSlider();8//[源码下载] http://files.cnblogs.com/walkerwang/slideImg.rar9//----------------------------------------------------------------------------------------------------10// [作者网名] walkerwang11// [邮 箱] walkerwzy@gmail.com12// [作者博客] http://walkerwang.cnblogs.com13// [更新日期] 2010-08-0214// [版 本 号] ver1.1.115//====================================================================================================16(function($) {17 $.fn.ImgSlider = function(options) {18 var options = $.extend({}, $.fn.ImgSlider.defaults, options);19 this.each(function() {20 var flag=0;//标识小图hover时是否执行切换事件,0未执行,默认21 var objH;//当前大图片对象句柄22 var m;//小图切换setinterval标识23 var th;//小图hover事件settimeout标识24 var forceIndex=-1;//强制移动到索引,-1表示不强制25 var indexbefore;//上一个图片的索引26 var thisWrap=this;27 var bigImgWrap;//大图片容器28 var titleWrap=$("<div class=\"imgtitle\"/>");//标题和介绍区容器,默认类别imgtitle29 var naviWrap=$("<div class=\"smallimgs\"/>");//导航区容器,默认类名smallimgs30 var naviNumWrap=$("<div/>",{"class":"numNavi"});//数字导航容器,默认类名numNavi31 var imgCollection;//切换的大图片集合32 var imgPrev;//小图片容器集合33 var numNavis;//数字导航对象集合34 //初始化35 bigImgWrap=$("."+options.wrapName,this).eq(0);36 imgCollection=bigImgWrap.find("img");37 $(this).append(titleWrap).append(naviWrap);//标题、导航容器加入DOM树38 titleWrap.append("<div class='it_bg'/>").append("<div class='it_title'/>").append("<div class='it_cont'/>");//title加入Dom树 39 40 //生成导航41 var imgCount=imgCollection.size();42 for(var i=0;i<imgCount;i++){43 //图片44 var imgWrap=$("<div class='imgs'/>");45 var imgElement=$("<img/>",{alt:'',src:imgCollection.eq(i).attr("src")});46 imgWrap.append(imgElement).appendTo(naviWrap);47 //数字48 var numElement=$("<span>"+(i+1)+"</span>");49 numElement.appendTo(naviNumWrap);50 //处理没有图片介绍属性(cont)的情况:每张图片有地址,标题,和描述三个属性51 //if(!imgCollection[i].hasAttribute("cont")) imgCollection.eq(i).attr("cont",""); //IE不支持52 if(typeof imgCollection.eq(i).attr("cont") =="undefined") imgCollection.eq(i).attr("cont","");53 }54 imgPrev=$(".imgs",naviWrap);//取得小图容器集合55 numNavis=$("span",naviNumWrap);//取得数字导航按钮集合56 57 //填充标题58 if(options.hideCaptial) $(".imgtitle",this).hide();59 else{60 objH=imgCollection.eq(0);61 titleWrap.find(".it_title").html(objH.attr("title")).end().find(".it_cont").html(objH.attr("cont"));62 }63 64 if(options.hidePreview){//判断是否显示导航,如不显示,则显示数字65 naviWrap.hide();66 $(this).append(naviNumWrap);67 }68 69 //css部分70 naviWrap.css({backgroundPosition: options.arrPosition+ "px 0"});//初始箭头位置71 $(this).css({width:options.wrapWidth,height:options.wrapHeight,position:"relative",overflow:"hidden"});72 bigImgWrap.css({height:options.wrapHeight,width:options.wrapWidth,overflow:"visible",whiteSpace:"nowrap", marginLeft:-options.wrapWidth});73 bigImgWrap.find("img").css({height:options.wrapHeight,width:options.wrapWidth,cursor:"pointer"});74 $(".imgtitle, .it_bg",this).css({textAlign:"center",width:"100%",position:"absolute",top:0,left:0,color:"#fff"});75 $(".it_bg",this).css({background:"black",filter:"alpha(opacity=40)",opacity:0.4,height:"100%"});76 $(".it_title",this).css({font:"800 1.5em 宋体",position:"relative",paddingTop:5});77 $(".it_cont",this).css({whiteSpace:"normal",textAlign:"left",position:"relative",padding:"5px 15px"});78 79 bigImgWrap.prepend(bigImgWrap.find("img:last").clone());//scroll fix80 if($.browser.msie){ //重设预览图宽度,ie hacker81 imgPrev.find("img").removeAttr("width").removeAttr("height");82 }83 //当前导航位置84 imgPrev.eq(0).addClass("highlight_img");85 if(options.hidePreview) numNavis.eq(0).addClass("current");86 87 m=setInterval(imgscroll,options.interval);88 89 //主算法90 function imgscroll(){91 var i;92 //计算下一个索引93 if(forceIndex==-1){94 i=naviWrap.find(".imgs").index($("div.highlight_img",thisWrap));//当前高亮位置95 if(i==imgCollection.length-1) i=0;96 else i++;97 }else i=forceIndex;98 99 if(indexbefore+1==imgCollection.length){100 if(i==0) bigImgWrap.css({marginLeft:0});//scroll fix101 }102 bigImgWrap.animate({marginLeft:options.wrapWidth*(-i-1)},options.speed,options.effect);//移动大图103 //移动光标、高亮框104 $(".highlight_img",thisWrap).removeClass("highlight_img");105 var measureElement=imgPrev.eq(0);106 var moveAmount=measureElement.width()+parseInt(measureElement.css("margin-left"))+parseInt(measureElement.css("margin-right"))+parseInt(measureElement.css("border-left-width"))+parseInt(measureElement.css("border-right-width"));107 //$("#fixie67").html(moveAmount);//测试用108 var imgleft=options.arrPosition+i*moveAmount;109 naviWrap.animate({backgroundPosition:imgleft+"px 0"},options.speed,function(){$(".imgs",thisWrap).eq(i).addClass("highlight_img");});110 //移动数字导航111 $(".current",naviNumWrap).removeClass("current");112 numNavis.eq(i).addClass("current");113 indexbefore=i;//保存本次索引114 if(!options.hideCaptial){115 titleWrap.hide();116 objH=bigImgWrap.find("img").eq(i+1);117 titleWrap.find(".it_title").html(objH.attr("title")).end().find(".it_cont").html(objH.attr("cont")).end().slideDown(options.speed);118 }119 }120 121 //响应hover事件——预览图122 $(".smallimgs",thisWrap).find(".imgs").live("mouseover",function(){123 var thisobj=$(this);124 th=setTimeout(function(){125 clearInterval(m);126 forceIndex=$(".smallimgs",thisWrap).find(".imgs").index(thisobj);127 imgscroll(i);128 flag=1;//延时被执行到的标识129 },300);130 });131 132 $(".smallimgs",thisWrap).find(".imgs").live("mouseout",function(){133 clearTimeout(th);134 if(flag==1){135 m=setInterval(imgscroll,options.interval);136 flag=0;137 forceIndex=-1;138 }139 });140 141 //响应hover事件——数字142 $(".numNavi",thisWrap).find("span").live("mouseover",function(){143 var i=numNavis.index(this);//得到索引144 $(".smallimgs",thisWrap).find(".imgs").eq(i).trigger("mouseover");145 });146 $(".numNavi",thisWrap).find("span").live("mouseout",function(){147 clearTimeout(th);148 if(flag==1){149 m=setInterval(imgscroll,options.interval);150 flag=0;151 forceIndex=-1;152 }153 });154 });155 };156 //默认值157 $.fn.ImgSlider.defaults = {158 wrapName:'imgb',//窗口内唯一包裹所有幻灯图片的div的类名159 wrapWidth:351,//容器宽度160 wrapHeight:396,//容器高度161 speed:1000,//切换速度162 interval:3000,//切换间隔163 arrPosition:-403,//预览图箭头初始位置 164 hidePreview:false,//隐藏预览图,隐藏后会显示数字导航165 hideCaptial:false,//隐藏标题/介绍166 effect:"swing"//动画效果167 }...

Full Screen

Full Screen

slider.js

Source:slider.js Github

copy

Full Screen

...146 var prev = this.current - 1,147 next = this.current + 1;148 prev = (prev < 0) ? this.last : prev;149 next = (next > this.last) ? 0 : next;150 this.$collection.eq(prev).css('left', '-100%');151 this.$collection.eq(this.current).css('left', '0%');152 this.$collection.eq(next).css('left', '100%');153 setTimeout(function() {154 Pandora.cssTransition(self.$collection, '');155 setTimeout(function() {156 self.moving = false;157 }, 50);158 }, this.config.duration + 50);159 }160 return this;161 },162 setPanPosition: function(delta) {163 if (this.config.type != 'fade') {164 var prev = this.current - 1,165 next = this.current + 1;166 prev = (prev < 0) ? this.last : prev;167 next = (next > this.last) ? 0 : next;168 this.$collection.eq(prev).css('left', -100 + delta + '%');169 this.$collection.eq(this.current).css('left', delta + '%');170 this.$collection.eq(next).css('left', 100 + delta + '%');171 }172 return this;173 },174 resetPositions: function(self) {175 if (this.config.type != 'fade') {176 this.$collection.each(function(index) {177 var pos = 0;178 if (index < self.current) {179 pos = -100;180 }181 if (index > self.current) {182 pos = 100;183 }184 if ((index - 1) > self.current) {185 pos = 200;186 }187 $(this).css('left', pos + '%');188 });189 if (this.current === 0) {190 this.$collection.eq(this.last).css('left', '-100%');191 }192 if (this.current === this.last) {193 this.$collection.eq(0).css('left', '100%');194 }195 }196 return this;197 },198 setContentPosition: function() {199 this.$content.each(function() {200 var $this = $(this),201 h = -.5 * $this.height();202 $this.css('margin-top', h + 'px');203 });204 return this;205 },206 updatePager: function() {207 if (this.config.pages) {208 this.$pager.find('span').removeClass('current').eq(this.current).addClass('current');209 }210 return this;211 },212 change: function(num) {213 var dir = (num >= this.current) ? -1 : 1,214 next = num;215 if (num < 0) {216 next = this.last;217 dir = 1;218 }219 if (num > this.last) {220 next = 0;221 dir = -1;222 }223 if (!this.moving && next !== this.current) {224 Pandora.cssTransition(this.$collection, this.textTransition);225 var self = this;226 this.moving = true;227 switch (this.config.type) {228 case 'fade':229 this.$collection.eq(next).css({230 'z-index': '12',231 'opacity': '1'232 });233 setTimeout(function() {234 Pandora.cssTransition(self.$collection, '');235 self.$collection.eq(self.current).css({236 'z-index': '10',237 'opacity': '0'238 });239 self.$collection.eq(next).css({240 'z-index': '11'241 });242 self.current = next;243 setTimeout(function() {244 self.updatePager();245 self.moving = false;246 }, 50);247 }, this.config.duration + 50);248 break;249 default:250 this.$collection.eq(next).addClass('current').css('left', '0%');251 this.$collection.eq(this.current).removeClass('current').css('left', dir * 100 + '%');252 setTimeout(function() {253 Pandora.cssTransition(self.$collection, '');254 self.current = next;255 setTimeout(function() {256 self.resetPositions(self).updatePager();257 self.moving = false;258 }, 50);259 }, this.config.duration + 50);260 }261 this.setContentPosition();262 }263 return this;264 },265 setEvents: function(self) {...

Full Screen

Full Screen

image.js

Source:image.js Github

copy

Full Screen

1import React from "react"2import { graphql, useStaticQuery } from "gatsby"3import { GatsbyImage } from "gatsby-plugin-image"4import { classNames } from "../infra/functions"5import Link from "./link"6import * as style from "./image.module.css"7import metaData from "../../images/images.json"8const Image = ({ id, type, className }) => {9 const image = getImage(id, type)10 return (11 <div {...classNames(className, style.container)}>12 <GatsbyImage image={image.data} alt={image.alt}/>13 {showCredits(type) && credits(image.credits, type)}14 </div>15 )16}17const credits = (credits, type) => {18 if (!credits || (!credits.author && !credits.source && !credits.license)) return null19 const classes = [style.credits].concat(typeClasses(type))20 const source = responsiveText("src", "source")21 const author = responsiveText(22 credits.author.name === "me" ? "me" : "dev",23 credits.author.name === "me" ? "me" : "artist"24 )25 const license = responsiveText("lic", "license")26 return (27 <div {...classNames(classes)}>28 {credits.source && credits.source.url && (29 <span key="source">30 <Link to={credits.source.url}>{source}</Link>31 </span>32 )}33 {credits.author && credits.author.url && (34 <span key="author">35 <Link to={credits.author.url}>{author}</Link>36 {credits.edited && <span> (edited by me)</span>}37 </span>38 )}39 {credits.license && credits.license.url && (40 <span key="license">41 <Link to={credits.license.url}>{license}</Link>42 </span>43 )}44 </div>45 )46}47const responsiveText = (short, long) => {48 return (49 <React.Fragment>50 <span className={style.short}>{short}</span>51 <span className={style.long}>{long}</span>52 </React.Fragment>53 )54}55const typeClasses = type => {56 switch (type) {57 case "content":58 case "sidebar":59 return [style.sideCredits]60 case "postTitle":61 return [style.topCredit]62 case "postCard":63 case "videoThumbnail":64 default:65 return []66 }67}68export const getImageMeta = (id, type) => {69 const image = getImage(id, type)70 return {71 path: image.data.images.fallback.src,72 alt: image.alt73 }74}75const getImage = (id, type) => {76 const img = getImageData(id, type)77 const data = img.gatsbyImageData78 const json = metaData.find(image => image.slug === id)79 const alt = json?.alt || ""80 const credits = findCreditsInData(json)81 return {82 data,83 alt,84 credits,85 }86}87const getImageData = (id, type) => {88 const imagesData = getImagesData()89 const image = findImageInData(imagesData, type, id)90 if (!image) {91 const message = `Missing ${type} image: ${id}`92 throw new Error(message)93 }94 return image95}96const getImagesData = () => {97 return useStaticQuery(98 graphql`99 query {100 articleTitle: allImageSharp(101 filter: { fields: { collection: { eq: "article-title-images" } } }102 ) {103 nodes {104 fields {105 id106 }107 gatsbyImageData(layout: FULL_WIDTH breakpoints: [1000, 2000] jpgOptions: { quality: 60 } placeholder: BLURRED)108 }109 }110 courseTitle: allImageSharp(111 filter: { fields: { collection: { eq: "course-title-images" } } }112 ) {113 nodes {114 fields {115 id116 }117 gatsbyImageData(layout: FULL_WIDTH breakpoints: [1000, 2000] jpgOptions: { quality: 60 } placeholder: BLURRED)118 }119 }120 pageTitle: allImageSharp(121 filter: { fields: { collection: { eq: "page-title-images" } } }122 ) {123 nodes {124 fields {125 id126 }127 gatsbyImageData(layout: FULL_WIDTH breakpoints: [1000, 2000] jpgOptions: { quality: 60 } placeholder: BLURRED)128 }129 }130 talkTitle: allImageSharp(131 filter: { fields: { collection: { eq: "talk-title-images" } } }132 ) {133 nodes {134 fields {135 id136 }137 gatsbyImageData(layout: FULL_WIDTH breakpoints: [1000, 2000] jpgOptions: { quality: 60 } placeholder: BLURRED)138 }139 }140 videoTitle: allImageSharp(141 filter: { fields: { collection: { eq: "video-title-images" } } }142 ) {143 nodes {144 fields {145 id146 }147 gatsbyImageData(layout: FULL_WIDTH breakpoints: [1000, 2000] jpgOptions: { quality: 60 } placeholder: BLURRED)148 }149 }150 videoThumbnail: allImageSharp(151 filter: { fields: { collection: { eq: "video-thumbnail-images" } } }152 ) {153 nodes {154 fields {155 id156 }157 gatsbyImageData(layout: FULL_WIDTH breakpoints: [1000, 2000] jpgOptions: { quality: 60 } placeholder: BLURRED)158 }159 }160 content: allImageSharp(161 filter: { fields: { collection: { eq: "content-images" } } }162 ) {163 nodes {164 fields {165 id166 }167 gatsbyImageData(layout: CONSTRAINED width: 800 jpgOptions: { quality: 60 } placeholder: BLURRED)168 }169 }170 eventLogos: allImageSharp(171 filter: { fields: { collection: { eq: "event-logos" } } }172 ) {173 nodes {174 fields {175 id176 }177 gatsbyImageData(layout: FULL_WIDTH breakpoints: [800] jpgOptions: { quality: 60 } placeholder: BLURRED)178 }179 }180 }181 `182 )183}184const findImageInData = (imageData, type, id) => {185 switch (type) {186 case "postTitle":187 case "postCard":188 return (189 imageData.articleTitle.nodes.find(node => node.fields.id === id) ||190 imageData.courseTitle.nodes.find(node => node.fields.id === id) ||191 imageData.pageTitle.nodes.find(node => node.fields.id === id) ||192 imageData.talkTitle.nodes.find(node => node.fields.id === id) ||193 imageData.videoTitle.nodes.find(node => node.fields.id === id)194 )195 case "eventCard":196 return imageData.eventLogos.nodes.find(node => node.fields.id === id)197 case "content":198 case "sidebar":199 return imageData.content.nodes.find(node => node.fields.id === id)200 case "videoThumbnail":201 return (202 imageData.videoThumbnail.nodes.find(node => node.fields.id === id) ||203 // a video post's title image and the video's thumbnail are often identical;204 // to reduce duplication of images, we fall through from the thumbnail folder to the video title image folder205 // (I would've preferred the other way around, but we don't know what kind of post [e.g. article vs video]206 // we're looking for a title image for)207 imageData.videoTitle.nodes.find(node => node.fields.id === id)208 )209 }210}211const findCreditsInData = json => {212 if (!json || !json.credits) return undefined213 if (json.credits.author && json.credits.author.name === "me")214 return {215 author: {216 name: "me",217 url: "/nicolai-parlog",218 },219 license: {220 name: "CC-BY-NC 4.0",221 url: "https://creativecommons.org/licenses/by-nc/4.0/",222 },223 }224 return json.credits225}226const showCredits = type => {227 switch (type) {228 case "postTitle":229 case "content":230 case "sidebar":231 return true232 case "postCard":233 case "videoThumbnail":234 case "eventCard":235 return false236 default:237 throw new Error(`Unknown image type "${type}".`)238 }239}...

Full Screen

Full Screen

interface.js

Source:interface.js Github

copy

Full Screen

1function slider () {2 var $slider = $('.slider');3 var $imgWrapCollection = $slider.find('.img-wrap');4 var $nextControl = $slider.find('.right');5 var $prevControl = $slider.find('.left');6 var $activeImg = $imgWrapCollection.eq(0);7 var timerId = null;8 $imgWrapCollection.hide();9 $activeImg.show();10 function next () {11 var $nextImg = $activeImg.next();12 if (!$nextImg[0]) {13 $nextImg = $imgWrapCollection.eq(0);14 }15 $nextImg.fadeIn('slow');16 $activeImg.fadeOut('slow');17 $activeImg = $nextImg;18 };19 function prev () {20 var $prevImg = $activeImg.prev();21 if (!$prevImg[0]) {22 $prevImg = $imgWrapCollection.eq($imgWrapCollection.length -1);23 }24 $prevImg.fadeIn();25 $activeImg.fadeOut();26 $activeImg = $prevImg;27 };28 function startSlide () {29 timerId = setTimeout(function(){30 next();31 startSlide();32 }, 4000); 33 };34 function stopSlide () {35 clearTimeout(timerId);36 };37 function restartSlider () {38 stopSlide();39 startSlide();40 }41 $nextControl.click(next).click(restartSlider);;42 $prevControl.click(prev).click(restartSlider);;43 startSlide();44}45$(function(){46 // slider init47 slider();48 // slider end49 // popup50 $('.js-popup-open').click(function(e){51 var idPopup = '#' + $(this).attr('data-popup');52 $(idPopup).fadeToggle('fast');53 });54 $('.close').click(function(){55 $(this).closest('.popup').fadeToggle('fast');56 });57 // popup end58 $('.js-subcatalog-open').click(function(e){59 $(this).parent().find('.catalog-sublist').slideToggle();60 e.preventDefault();61 });62 $(window).load(function(){63 var wrapperHeight = $('.wrapper').outerHeight();64 $('.backdrop').height(wrapperHeight);65 });...

Full Screen

Full Screen

icon.js

Source:icon.js Github

copy

Full Screen

1/**2 * Created by Colin on 14-5-26.3 */4define(function(require, exports, module) {5 var $ = require('libs/jquery/jquery.js'); // 使用jquery6 var font=$('.fontIcon').find('i');7 var triangle=$('.triangle').find('div');8 var num=font.length;9 for(var i=0;i<num;i++){10 font.get(i).index=i;11 font.get(i).onmouseover=function(){12 var index=this.index;13 block(index,triangle);14 };15 font.get(i).onmouseout=function(){16 for(var i=0;i<num;i++){17 triangle.eq(i).css('visibility','hidden');18 }19 }20 }21 function block(index,htmlCollection){22 var num=htmlCollection.length;23 for(var i=0;i<num;i++){24 htmlCollection.eq(i).css('visibility','hidden');25 }26 htmlCollection.eq(index).css('visibility','visible');27 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.pause()4 cy.contains('type').click()5 cy.url().should('include', '/commands/actions')6 cy.get('.action-email')7 .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.pause()4 cy.contains('type').click()5 cy.url().should('include', '/commands/actions')6 cy.get('.action-email')7 .type('fake@email')8 .should('have.value', 'fake@email')9 })10 })11describe('My First Test', function() {12 it('Does not do much!', function() {13 cy.pause()14 cy.contains('type').click()15 cy.url().should('include', '/commands/actions')16 cy.get('.action-email')17 .type('fake@email')18 .should('have.value', 'fake@email')19 })20 })21describe('My First Test', function() {22 it('Does not do much!', function() {23 cy.pause()24 cy.contains('type').click()25 cy.url().should('include', '/commands/actions')26 cy.get('.action-email')27 .type('fake@email')28 .should('have.value', 'fake@email')29 })30 })31describe('My First Test', function() {32 it('Does not do much!', function() {33 cy.pause()34 cy.contains('type').click()35 cy.url().should('include', '/commands/actions')36 cy.get('.action-email')37 .type('fake@email')38 .should('have.value', 'fake@email')39 })40 })41describe('My First Test', function() {42 it('Does not do much!', function() {43 cy.pause()44 cy.contains('type').click()45 cy.url().should('include', '/commands/actions')46 cy.get('.action-email')47 .type('fake@email')48 .should('have.value', 'fake@email')49 })50 })51describe('My First Test', function() {52 it('Does not do much!', function() {

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function () {2 it('Does not do much!', function () {3 cy.pause()4 cy.contains('type').click()5 cy.url().should('include', '/commands/actions')6 cy.get('.action-email')7 .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 expect(true).to.equal(true)4 })5 })6 describe('My First Test', function() {7 it('Does not do much!', function() {8 expect(true).to.equal(false)9 })10 })11 describe('My First Test', function() {12 it('Visits the Kitchen Sink', function() {13 cy.pause()14 cy.contains('type').click()15 cy.url().should('include', '/commands/actions')16 cy.get('.action-email')17 .type('fake@email')18 .should('have.value', 'fake@email')19 })20 })21 describe('My First Test', function() {22 it('Finds an element', function() {23 cy.contains('type').click()24 cy.url().should('include', '/commands/actions')25 cy.get('.action-email')26 .type('fake@email')27 .should('have.value', 'fake@email')28 })29 })30 describe('My First Test', function() {31 it('Gets, types and asserts', function() {32 cy.pause()33 cy.contains('type').click()34 cy.url().should('include', '/commands/actions')35 cy.get('.action-email')36 .type('fake@email')37 .should('have.value', 'fake@email')38 })39 })40 describe('My First Test', function() {41 it('Gets, types and asserts', function() {42 cy.contains('type').click()43 cy.url().should('include', '/commands/actions')

Full Screen

Using AI Code Generation

copy

Full Screen

1describe("My First Test", () => {2 it("Does not do much!", () => {3 expect(true).to.equal(true);4 });5});6describe("My Second Test", () => {7 it("Visits the Kitchen Sink", () => {8 cy.contains("type").click();9 cy.url().should("include", "/commands/actions");10 cy.get(".action-email")11 .type("

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.get('.todo-list li').eq(1).click();4 cy.get('.todo-list li').eq(1).click();5 })6 })

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.get('button').click()4 cy.get('button').eq(0).click()5 cy.get('button').eq(1).click()6 cy.get('button').eq(2).click()7 cy.get('button').eq(3).click()8 cy.get('button').eq(4).click()9 cy.get('button').eq(5).click()10 cy.get('button').eq(6).click()11 cy.get('button').eq(7).click()12 cy.get('button').eq(8).click()13 cy.get('button').eq(9).click()14 cy.get('button').eq(10).click()15 cy.get('button').eq(11).click()16 cy.get('button').eq(12).click()17 cy.get('button').eq(13).click()18 cy.get('button').eq(14).click()19 cy.get('button').eq(15).click()20 cy.get('button').eq(16).click()21 cy.get('button').eq(17).click()22 cy.get('button').eq(18).click()23 cy.get('button').eq(19).click()24 cy.get('button').eq(20).click()25 cy.get('button').eq(21).click()26 cy.get('button').eq(22).click()27 cy.get('button').eq(23).click()28 cy.get('button').eq(24).click()29 cy.get('button').eq(25).click()30 cy.get('button').eq(26).click()31 cy.get('button').eq(27).click()32 cy.get('button').eq(28).click()33 cy.get('button').eq(29).click()34 cy.get('button').eq(30).click()35 cy.get('button').eq(31).click()36 cy.get('button').eq(32).click()37 cy.get('button').eq(33).click()38 cy.get('button').eq(34).click()39 cy.get('button').eq(35).click()

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

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