Best JavaScript code snippet using playwright-internal
calculator.js
Source:calculator.js
1(function ($) {2 var patientCount;3 var storedRows;4 var shouldClearOnFocus = false;5 var app;6 Drupal.behaviors.calculator = {7 attach: function (context, settings) {8 // if ie browser version is older than ie79 if($.browser.msie && parseInt($.browser.version, 10) <= 7) {10 $(".overlay-bg", context).show();11 $("#popup-oldbrowser", context).show();12 $("#start-popup", context).hide();13 }14 //Handle printing15 $(".print", context).click(function(event) {16 var type = $(this).hasClass('individual') ? 'individual' : 'simplified';17 Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Print', type]);18 if(settings.monofer.app) {19 window.location = 'print://now';20 } else if(!settings.monofer.printSupported) {21 Drupal.behaviors.calculator.showPopup(Drupal.t('To print, please use your browser\'s built-in print functionality, usually found under settings', {}, {context:'Printing'}), context);22 } else {23 window.print();24 }25 });26 //Handle/init settings if php has not been run (if offline) assume mobile27 if(!window.location.origin) {28 window.location.origin = window.location.protocol+"//"+window.location.host;29 }30 app = settings.monofer.app;31 //Handle disclaimer popup32 var acceptPopup = $.cookie('accept-popup');33 var noPrompt = location.href.indexOf('noprompt')!=-1;34 if(app || noPrompt || acceptPopup!=undefined) {35 $("#start-popup", context).hide();36 $(".overlay-bg", context).hide();37 //Show video for noprompt/app users on first visit38 // if(acceptPopup==undefined && (settings.monofer.app || noPrompt)) {39 // Drupal.behaviors.calculator.setVideoSrc(context, settings);40 // $("body", context).addClass('mobile-overlay');41 // $("#video-prompt", context).show();42 // } else {43 var player = videojs('instruction-video');44 player.dispose();45 // }46 //Extend life of accept-popup cookie47 $.cookie('accept-popup', 'YES', { expires: Drupal.behaviors.calculator.dateWithDaysFromNow(365), path: '/' });48 } else {49 $("body", context).addClass('mobile-prompt');50 }51 $("#video-close", context).click(function(event) {52 var player = videojs('instruction-video');53 player.pause();54 player.dispose();55 $("#video-prompt", context).hide();56 //Show download-app popup if applicable57 if(Drupal.behaviors.calculator.isTouchDevice() && !app) {58 var downloadPopup = $("#popup-downloadapp", context);59 $("#close-downloadapp", context).click(function(event) {60 $(".overlay-bg", context).hide();61 $("body", context).removeClass('mobile-overlay');62 downloadPopup.hide();63 });64 $(".appgo", context).click(function(event) {65 $(".overlay-bg", context).hide();66 $("body", context).removeClass('mobile-overlay');67 downloadPopup.hide();68 });69 downloadPopup.show();70 } else {71 $(".overlay-bg", context).hide();72 $("body", context).removeClass('mobile-overlay');73 }74 });75 $("#start-ok", context).click(function(event) {76 $("#start-popup", context).hide();77 $(".overlay-bg", context).hide();78 $("body", context).removeClass('mobile-prompt');79 $.cookie('accept-popup', 'YES', { expires: Drupal.behaviors.calculator.dateWithDaysFromNow(365), path: '/' });80 //Handle instruction video81 Drupal.behaviors.calculator.setVideoSrc(context, settings);82 $("body", context).addClass('mobile-overlay');83 $("#video-prompt", context).show();84 });85 //Handle tabs86 var activeIndex = 0;87 if(window.location.href.indexOf("simplified-page")!=-1) {88 activeIndex = 1;89 } else if(window.location.href.indexOf("individual-page")!=-1) {90 activeIndex = 0;91 } else {92 var activeTab = $.cookie('active-tab');93 activeIndex = activeTab==undefined ? 0 : activeTab;94 }95 var page = activeIndex == 0 ? 'individual-page' : 'simplified-page';96 Drupal.behaviors.calculator.gaPush(['_trackPageview', '/?' + page]);97 $(".tabs li.last", context).click(function(event) {98 $("body", context).addClass('simplified-isactive');99 });100 $('.tabs li.first', context).click(function(event) {101 $("body", context).removeClass('simplified-isactive');102 });103 $(".content", context).tabs({104 create: function( event, ui ) {105 if ($(".tabs li.last.ui-state-active", context)[0]){106 $("body").addClass('simplified-isactive');107 }108 }, active: activeIndex,109 activate: function(event, ui) {110 $.cookie('active-tab', ui.newTab.index(), { expires: Drupal.behaviors.calculator.dateWithDaysFromNow(365), path: '/' });111 var page = ui.newTab.index() == 0 ? 'individual-page' : 'simplified-page';112 Drupal.behaviors.calculator.gaPush(['_trackPageview', '/?' + page]);113 }114 });115 //Handle tooltips/info popups in general116 $('.tooltip', context).each(function(index, el) {117 var content = '<h3>' + $(this).data("title") + '</h3><p>' + $(this).data("content") + '</p>';118 $(this).tooltipsy({119 className: 'tooltipsy standard',120 content: content,121 show:function(e, $el) {122 if(Drupal.behaviors.calculator.isTouchDevice()) { //Use popup for mobile123 Drupal.behaviors.calculator.showPopup($el.find('.tooltipsy').html(), context);124 } else {125 $el.show();126 }127 }128 });129 });130 $(".close-button", context).click(function(event) {131 $("body").removeClass('mobile-overlay');132 $("#popup").hide();133 $('body').unbind('touchmove');134 });135 //Handle scrolling136 $(".totop", context).click(function() {137 $("html, body", context).animate({ scrollTop: 0 }, "slow");138 });139 //Handle accordion140 $("#acc-wrap", context).accordion({141 header: ".acc-header",142 collapsible: true,143 active: false144 });145 //Handle input types146 $(".integer-only", context).on('keydown',function(e) {147 var allowedKeys = [8, 9, 13, 37, 38, 39, 40, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 110, 188, 190];148 if (allowedKeys.indexOf(e.keyCode)==-1) {149 return(false); //stop processing150 }151 });152 //Handle focus153 $(".integer-only", context).on('focus',function(e) {154 if(shouldClearOnFocus) { //Clear input155 shouldClearOnFocus = false;156 $("input[name='irons']", context).val('');157 $("input[name='targethb']", context).val('');158 $("input[name='actualhb']", context).val('');159 $("input[name='idealbw']", context).val('');160 $("input[name='patient-id']", context).val('');161 //Patient Iron Need162 $('#iron-need-result', context).html('â');163 //Recommendation164 $(".iron-recommendation-result", context).hide();165 $(".empty-result", context).show();166 $(".recommendation .result-image", context).hide();167 $(".info-followup", context).hide();168 //Monofer Dose169 $(".monofer-dose-result", context).html('â');170 }171 });172 //Submit handling173 patientCount = 0;174 $(".patient-submit", context).click(function(event) {175 event.preventDefault();176 if(storedRows.length>0) {177 var patientID = $("input[name='patient-id']", context).val();178 Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Patient ID', 'Individual', patientID]);179 $('.result-table tr:eq(1) .patient', context).html(patientID);180 $(".mobile-patient", context).first().html(patientID);181 storedRows[0].id = patientID;182 Drupal.behaviors.calculator.updateCookie();183 }184 });185 $(".calculate-btn", context).click(function(event) {186 event.preventDefault(); //Avoid submit/refresh187 Drupal.behaviors.calculator.calculate(context, settings);188 });189 //Handle deletion of rows190 $('.delete', context).live('click', function () {191 var index = $(".delete", context).index(this);192 Drupal.behaviors.calculator.deleteRow(index, context);193 });194 $(".mobile-delete", context).live('click', function() {195 var index = $(".mobile-delete", context).index(this);196 Drupal.behaviors.calculator.deleteRow(index, context);197 });198 $("select[name='units']", context).bind($.browser.msie ? 'click' : 'change', function(event) {199 var unitVal = $(this).val();200 $("select[name='units-simplified']", context).val(unitVal);201 $.cookie('unit', unitVal, { expires: Drupal.behaviors.calculator.dateWithDaysFromNow(365), path: '/' });202 Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Unit Selection', 'Individual', unitVal]);203 });204 //Handle custom unit selection205 $(".active-unit", context).click(function(event) {206 $(this).next().show();207 });208 $(".unit-select.individual .unit-list li", context).click(function(event) {209 var unitContainer = $(this).parent().prev().find('.unit-value');210 unitContainer.html($(this).text());211 var data = $(this).data('val');212 unitContainer.data('val', data);213 var simpleContainer = $(".unit-select.simplified .unit-value", context);214 simpleContainer.html($(this).text());215 simpleContainer.data('val', data);216 $(this).parent().hide();217 $.cookie('unit', data, { expires: Drupal.behaviors.calculator.dateWithDaysFromNow(365), path: '/' });218 Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Unit Selection', 'Individual', data]);219 });220 var unit = $.cookie('unit');221 if(unit!==undefined) {222 if(settings.monofer.mobile) { //Use native selects223 $("select[name='units']", context).val(unit);224 $("select[name='units-simplified']", context).val(unit);225 var unitText = $("select[name='units-simplified'] option:selected", context).text();226 Drupal.behaviors.calculator.updateSimplifiedUnits(unit, unitText, settings, context);227 } else {228 var unitText = $(".unit-select.individual ul").find("[data-val='" + unit + "']").html();229 var commonContainer = $(".unit-select .active-unit .unit-value", context);230 commonContainer.html(unitText);231 commonContainer.data('val', unit);232 }233 }234 //And unselection235 $(document).mouseup(function (e) {236 var container = $(".unit-select");237 var child = $(".unit-list");238 if (!container.is(e.target) // if the target of the click isn't the container...239 && container.has(e.target).length === 0) // ... nor a descendant of the container240 {241 child.hide();242 }243 });244 //Simplified table245 $(".simplified-table td.clickable", context).click(function(event) {246 var index = $(this).data("index");247 var simplifiedText = $(".simplified-table tr.simplified-content:eq(" + index + ")", context);248 var action;249 if($(this).hasClass('active')) {250 $(this).removeClass('active');251 simplifiedText.hide();252 action = 'close';253 } else {254 $("td.active", context).removeClass('active');255 $('tr.simplified-content', context).hide();256 $(this).addClass('active');257 simplifiedText.show();258 action = 'open';259 }260 var simplifiedLabel;261 if(index=="0") {262 simplifiedLabel = "1000mg >= 10";263 } else if(index=="1") {264 simplifiedLabel = "1500mg >= 10";265 } else if(index=="2") {266 simplifiedLabel = "1500mg < 10";267 } else {268 simplifiedLabel = "2000mg < 10";269 }270 Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Patient Iron Need', action, simplifiedLabel]);271 });272 $("select[name='units-simplified']", context).bind($.browser.msie ? 'click' : 'change', function(event) {273 var unitVal = $(this).val();274 $("select[name='units']", context).val(unitVal);275 var unitText = $(this).find("option:selected").text();276 Drupal.behaviors.calculator.updateSimplifiedUnits(unitVal, unitText, settings, context);277 Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Unit Selection', 'Simplified', unitVal]);278 });279 $(".unit-select.simplified .unit-list li", context).click(function(event) {280 var unitContainer = $(this).parent().prev().find('.unit-value');281 var unitVal = $(this).data('val');282 var unitText = $(this).text();283 unitContainer.html(unitText);284 unitContainer.data('val', unitVal);285 var individualContainer = $(".unit-select.individual .unit-value", context);286 individualContainer.html(unitText);287 individualContainer.data('val', unitVal);288 Drupal.behaviors.calculator.updateSimplifiedUnits(unitVal, unitText, settings, context);289 $(this).parent().hide();290 Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Unit Selection', 'Simplified', unitVal]);291 });292 $('#mobile-info-tooltip', context).tooltipsy({293 className: 'tooltipsy',294 show:function(e, $el) {295 Drupal.behaviors.calculator.showPopup($("#mobile-info-tooltip-content", context).html(), context, 'mobile-tooltipsy');296 }297 });298 var infotextTable = '<h3>' + Drupal.t('Recommendation') + '</h3>';299 infotextTable += '<p>' + Drupal.t('Monofer can be administered up to 20 mg/kg.') + '</p>';300 infotextTable += '<div class="result-image one-visit"></div>';301 infotextTable += '<p>' + Drupal.t('Full iron correction can be achieved in just one visit') + '</p>';302 infotextTable += '<div class="result-image follow-up"></div>';303 infotextTable += '<p>' + Drupal.t('If the patientâs need for iron exceeds 20 mg/kg body weight, the dose must be divided and administered at intervals of at least one week. It is recommended to administer maximum dose at the first visit.') + '</p>';304 $('#info-followup-table', context).tooltipsy({305 content: infotextTable,306 className: 'tooltipsy info-wide',307 show: function(e, $el) {308 if(Drupal.behaviors.calculator.isTouchDevice()) {309 Drupal.behaviors.calculator.showPopup(infotextTable, context);310 } else {311 $el.show();312 }313 }314 });315 $('.first-dose-tooltip', context).live('click', function() {316 Drupal.behaviors.calculator.showPopup(infotextTable, context);317 });318 //Import stored data from cookie319 storedRows = [];320 if(settings.monofer.app || document.referrer.indexOf(window.location.origin)!=-1) { //Only use stored data if on same domain or an app321 var count = $.cookie('counter');322 if(count!=undefined) {323 patientCount = parseInt(count);324 }325 var rows = $.cookie('rows');326 if(rows!=undefined) {327 rows = JSON.parse(rows);328 var row;329 for (var i = 0; i < rows.length; i++) {330 row = rows[i];331 Drupal.behaviors.calculator.addRow(context,row.id,row.ironNeed,row.dose,row.firstDose,row.stores,row.target,row.actual,row.ideal,row.visitClass);332 }333 if(rows.length>0 && row!=undefined) { //Add info to boxes on recommendation etc.334 //Patient iron need335 $('#iron-need-result', context).html(row.ironNeed + ' mg');336 //Recommendation337 var infotext = '<h3>' + Drupal.t('Recommendation', {}, {context:'Recommendation tooltip'}) + '</h3>' + '<p>' + Drupal.t('Monofer can be administered up to 20 mg/kg.', {}, {context:'Recommendation tooltip'}) + '</p>';338 if(row.visitClass=="one-visit") {339 recommendation = Drupal.t('Full iron correction can be achieved in just one visit', {}, {context:'Recommendation box'});340 $(".info-followup", context).show();341 infotext += '<div class="result-image one-visit"></div>' + '<p>' + Drupal.t('Full iron correction can be achieved in just one visit.', {}, {context:'Recommendation tooltip'}) + '</p>';342 Drupal.behaviors.calculator.updateInfoFollowup(true, infotext, recommendation, row.visitClass, context);343 } else {344 recommendation = Drupal.t('Maximum dose at first visit', {}, {context:'Recommendation box'});345 $(".info-followup", context).show();346 infotext += '<div class="result-image follow-up"></div>' + '<p>' + Drupal.t('If the patientâs need for iron exceeds 20 mg/kg body weight, the dose must be divided and administered at intervals of at least one week. It is recommended to administer maximum dose at the first visit.', {}, {context:'Recommendation tooltip'}) + '</p>';347 recommendation += '<span class="bold">' + Drupal.t(' @d ml', {'@d':row.firstDose}, {context:'Recommendation dose'}) + '</span>';348 Drupal.behaviors.calculator.updateInfoFollowup(false, infotext, recommendation, row.visitClass, context);349 }350 //Monofer Dose351 $('.monofer-dose-result', context).html(row.dose + ' ml');352 }353 }354 } else {355 $.removeCookie('counter');356 $.removeCookie('rows');357 }358 },359 calculate: function(context, settings) {360 //Remove old errors if any361 $('input.error', context).removeClass('error');362 //Verify input values363 var error = false;364 var ironStores = $("input[name='irons']", context).val();365 ironStores = Drupal.behaviors.calculator.parseNumber(ironStores);366 if(!Drupal.behaviors.calculator.isNumber(ironStores)) {367 error = true;368 $("input[name='irons']", context).addClass('error');369 } else {370 ironStores = parseFloat(ironStores);371 }372 var target = $("input[name='targethb']", context).val();373 target = Drupal.behaviors.calculator.parseNumber(target);374 if(!Drupal.behaviors.calculator.isNumber(target)) {375 error = true;376 $("input[name='targethb']", context).addClass('error');377 } else {378 target = parseFloat(target);379 }380 var actual = $("input[name='actualhb']", context).val();381 actual = Drupal.behaviors.calculator.parseNumber(actual);382 if(!Drupal.behaviors.calculator.isNumber(actual)) {383 error = true;384 $("input[name='actualhb']", context).addClass('error');385 } else {386 actual = parseFloat(actual);387 }388 var ideal = $("input[name='idealbw']", context).val();389 ideal = Drupal.behaviors.calculator.parseNumber(ideal);390 if(!Drupal.behaviors.calculator.isNumber(ideal)) {391 error = true;392 $("input[name='idealbw']", context).addClass('error');393 } else {394 ideal = parseFloat(ideal);395 }396 if(!error) { //Verify that397 if(actual>=target) {398 error = true;399 if(Drupal.behaviors.calculator.isTouchDevice()) { //Use popup for mobile400 Drupal.behaviors.calculator.showPopup($(".calc-row.actual-hb .tooltip", context).data('content'), context);401 } else {402 $(".calc-row.actual-hb .tooltip", context).data('tooltipsy').show();403 setTimeout(function() { //timeout and hide popup again404 $(".calc-row.actual-hb .tooltip", context).data('tooltipsy').hide();405 }, 3000);406 }407 }408 }409 if(!error) {410 var unit = $("select[name='units'] option:selected", context).val();411 if(unit==undefined) { //Use the custom select's value412 unit = $(".unit-select.individual .unit-value").data('val');413 }414 var unitScale = unit=='g-dl' ? 1 : unit=='g-l' ? 0.1 : 1.61; //Scale Hb415 var totalIronNeed = ideal * (target*unitScale-actual*unitScale) * 2.4 + ironStores;416 var roundedIronNeed = Math.round(totalIronNeed/100) * 100; //To nearest 100417 var dose = roundedIronNeed/ideal;418 var roundedDose = dose.toFixed(2);419 //Patient iron need420 $('#iron-need-result', context).html(roundedIronNeed + ' mg');421 var recommendation = '';422 var visitClass;423 var infotext = '<h3>' + Drupal.t('Recommendation', {}, {context:'Recommendation tooltip'}) + '</h3>' + '<p>' + Drupal.t('Monofer can be administered up to 20 mg/kg.', {}, {context:'Recommendation tooltip'}) + '</p>';424 var firstDose;425 if(roundedDose<=20) {426 recommendation = Drupal.t('Full iron correction can be achieved in just one visit', {}, {context:'Recommendation box'});427 visitClass = "one-visit";428 $(".info-followup", context).show();429 infotext += '<div class="result-image one-visit"></div>' + '<p>' + Drupal.t('Full iron correction can be achieved in just one visit.', {}, {context:'Recommendation tooltip'}) + '</p>';430 firstDose = roundedIronNeed/100;431 Drupal.behaviors.calculator.updateInfoFollowup(true, infotext, recommendation, visitClass, context);432 } else {433 recommendation = Drupal.t('Dose must be split. Maximum dose at first visit', {}, {context:'Recommendation box'});434 visitClass = "follow-up";435 $(".info-followup", context).show();436 infotext += '<div class="result-image follow-up"></div>' + '<p>' + Drupal.t('If the patientâs need for iron exceeds 20 mg/kg body weight, the dose must be divided and administered at intervals of at least one week. It is recommended to administer maximum dose at the first visit.', {}, {context:'Recommendation tooltip'}) + '</p>';437 // firstDose = Math.round(ideal*20/100);438 firstDose = Math.floor(ideal*20/100);439 recommendation += '<span class="bold">' + Drupal.t(' @d ml', {'@d':firstDose}, {context:'Recommendation dose'}) + '</span>';440 Drupal.behaviors.calculator.updateInfoFollowup(false, infotext, recommendation, visitClass, context);441 }442 patientCount ++;443 var patientID = $("input[name='patient-id']", context).val();444 if(patientID=="") {445 patientID = Drupal.t("ID @id", {'@id':patientCount}, {context:'Patient ID'});446 }447 //Monofer Dose448 roundedDose = roundedIronNeed/100;449 $('.monofer-dose-result', context).html(roundedDose + ' ml');450 Drupal.behaviors.calculator.addRow(context, patientID, roundedIronNeed, roundedDose, firstDose, ironStores, target, actual, ideal, visitClass);451 shouldClearOnFocus = true;452 if(screen.width<768) {453 $('html, body', context).animate({scrollTop:$('#result-anchor', context).offset().top}, 'slow');454 } else {455 $('html, body', context).animate({scrollTop:0}, 'slow');456 }457 Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation status', 'Calculate', 'Calculation success']);458 Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation input', 'Unit Selection', unit]);459 Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation input', 'Iron Stores', '', ironStores]);460 Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation input', 'Target Hb', '', target]);461 Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation input', 'Actual Hb', '', actual]);462 Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation input', 'Body weight', '', ideal]);463 Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation input', 'Patient Iron Need', '', roundedIronNeed]);464 Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation input', 'Monofer Dose', '', roundedDose]);465 Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation input', 'Recommendation', visitClass]);466 } else {467 Drupal.behaviors.calculator.gaPush(['_trackEvent', 'Dose calculation status', 'Calculate', 'Calculation input error']);468 }469 },470 addRow: function(context, id, ironNeed, dose, firstDose, stores, target, actual, ideal, visitClass) {471 $('.result-table .first-row', context).show();472 $('.result-table .last-row', context).removeClass('last-row');473 var unit = $("select[name='units'] option:selected", context).text();474 if(unit=='') { //Use the custom select's value475 unit = $(".unit-select.individual .unit-value").text();476 }477 unit = ' ' + unit;478 var row = '<tr>' +479 '<td class="first-cell"><span class="' + visitClass + '"></span></td>' +480 // '<td class="patient">' + id + '</td>' +481 '<td class="ironneed">' + ironNeed + ' mg</td>' +482 '<td class="monoferdose">' + dose + ' ml</td>' +483 '<td class="firstdose">' + firstDose + ' ml</td>' +484 '<td class="stores">' + stores + ' mg</td>' +485 '<td>' + target + unit + '</td>' +486 '<td>' + actual + unit + '</td>' +487 '<td>' + ideal + ' kg</td>' +488 '<td class="last-cell"><span class="delete"></span></td>' +489 '</tr>';490 $(".result-table tr", context).first().after(row);491 $(".result-table tr:gt(5)", context).remove();492 $(".result-table tr", context).last().addClass('last-row');493 //Mobile table494 $(".history-title", context).show();495 var mobileRow = '<div class="mobile-row">' +496 '<div class="acc-header"><span class="mobile-patient">' + id + '</span><span class="' + visitClass + '"></span><span class="mobile-delete"></span><span class="arrow"></span></div>' +497 '<div class="acc-content">' +498 '<div class="data-row ironneed"><label>' + Drupal.t('Patient iron need', {}, {'context':'Mobile row'}) + '</label><span class="data">' + ironNeed + ' mg</span></div>' +499 '<div class="data-row monoferdose"><label>' + Drupal.t('Monofer dose', {}, {context:'Mobile row'}) + '</label><span class="data">' + dose + ' ml</span></div>' +500 '<div class="data-row firstdose"><label>' + Drupal.t('First dose', {}, {context:'Mobile row'}) + '</label><span class="data">' + firstDose + ' ml</span><span class="first-dose-tooltip"></span></div>' +501 '<div class="data-row stores"><label>' + Drupal.t('Iron stores', {}, {context:'Mobile row'}) + '</label><span class="data">' + stores + ' mg</span></div>' +502 '<div class="data-row"><label>' + Drupal.t('Target Hb', {}, {context:'Mobile row'}) + '</label><span class="data">' + target + unit + '</span></div>' +503 '<div class="data-row"><label>' + Drupal.t('Actual Hb', {}, {context:'Mobile row'}) + '</label><span class="data">' + actual + unit + '</span></div>' +504 '<div class="data-row"><label>' + Drupal.t('Ideal bw', {}, {context:'Mobile row'}) + '</label><span class="data">' + ideal + ' kg</span></div>' +505 '</div>' +506 '</div>';507 $(".mobile-result-table .history-title", context).after(mobileRow);508 $(".mobile-row:gt(4)", context).remove();509 $("#acc-wrap", context).accordion('destroy').accordion({510 header: ".acc-header",511 collapsible: true,512 active: false513 });514 //Maintain storedRows515 storedRows.push({516 'id':id,517 'ironNeed':ironNeed,518 'dose':dose,519 'firstDose':firstDose,520 'stores':stores,521 'target':target,522 'actual':actual,523 'ideal':ideal,524 'visitClass':visitClass525 });526 if(storedRows.length>5) {527 storedRows.splice(0, storedRows.length-5);528 }529 Drupal.behaviors.calculator.updateCookie();530 },531 deleteRow: function(index, context) {532 var row = $(".delete", context).eq(index).closest('tr').remove();533 var rows = $(".result-table tr", context);534 if(rows.length>1) {535 rows.last().addClass('last-row');536 }537 //Delete mobile row538 $(".mobile-row", context)[index].remove();539 storedRows.splice(storedRows.length-index-1, 1);540 Drupal.behaviors.calculator.updateCookie();541 },542 showPopup: function(content, context, customClass) {543 $("#popup-message", context).removeClass();544 if(customClass!==undefined) {545 $("#popup-message", context).addClass(customClass);546 }547 $("#popup-message", context).html(content);548 $("#popup", context).show();549 $("body").addClass('mobile-overlay');550 $('body').bind('touchmove', function(e){e.preventDefault()});551 },552 parseNumber: function(n) {553 if(n!==undefined) {554 n = n.replace(",", ".");555 }556 return n;557 },558 isNumber: function(n) {559 return !isNaN(parseFloat(n)) && isFinite(n);560 },561 updateCookie: function() {562 $.cookie('rows', JSON.stringify(storedRows));563 $.cookie('counter', '' + patientCount);564 $.cookie('counter', Number);565 },566 isTouchDevice: function() {567 //DEBUG568 //return true;569 if(Drupal.behaviors.calculator.isIE()) {570 return false;571 }572 return 'ontouchstart' in window // works on most browsers573 || 'onmsgesturechange' in window; // works on ie10574 },575 updateSimplifiedUnits: function(unitVal, unitText, settings, context) {576 $("#simple-unit-header").html(Drupal.t("Hb (@unit)", {'@unit':unitText}, {context:'Simple unit'}));577 var unitScale = unitVal=='g-dl' ? 1 : unitVal=='g-l' ? 10 : 0.62; //Scale Hb578 var threshold = (10*unitScale);579 $("#simplified-hb-1", context).html('⥠' + threshold);580 $("#simplified-hb-2", context).html('< ' + threshold);581 $.cookie('unit', unitVal, { expires: Drupal.behaviors.calculator.dateWithDaysFromNow(365), path: '/' });582 },583 updateInfoFollowup:function(singleVisit, infotext, recommendation, visitClass, context) {584 if($('.recommendation-tooltip.info-followup', context).data('tooltipsy')!==undefined) {585 $('.tooltipsy.info-wide.info-left', context).parent().remove();586 }587 $('.recommendation-tooltip.info-followup', context).tooltipsy({588 content: infotext,589 className: 'tooltipsy info-wide info-left ' + visitClass + '-tooltip',590 offset: [-1, 0], //Show to the left of the info icon591 show:function(e, $el) {592 if(Drupal.behaviors.calculator.isTouchDevice()) { //Use popup for mobile593 Drupal.behaviors.calculator.showPopup(infotext, context);594 } else {595 $el.show();596 }597 }598 });599 $('.empty-result', context).hide();600 $('.result-box .result-image', context).attr("class",'result-image ' + visitClass);601 $('.result-box .result-image', context).show();602 $('.iron-recommendation-result', context).html(recommendation);603 $('.iron-recommendation-result', context).show(); //Show if it was hidden604 },605 isIE: function() {606 var myNav = navigator.userAgent.toLowerCase();607 // return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;608 return (myNav.indexOf('msie') != -1) ? true : false;609 },610 gaPush: function(vars) {611 if(app) {612 var customUrl = 'analytics://' + vars;613 Drupal.behaviors.calculator.execute(customUrl);614 } else {615 try{616 _gaq.push(vars);617 } catch(err) {618 }619 }620 },621 execute:function(url) {622 var iframe = document.createElement("IFRAME");623 iframe.setAttribute("src", url);624 document.documentElement.appendChild(iframe);625 iframe.parentNode.removeChild(iframe);626 iframe = null;627 },628 dateWithDaysFromNow:function(days) {629 var date = new Date();630 date.setTime(date.getTime() + (days*24*60*60*1000));631 return date;632 },633 setVideoSrc:function(context, settings) {634 var src;635 if(window.screen.width > 760) {636 src = settings.monofer.ipad_video;637 } else {638 src = settings.monofer.mobile_video;639 }640 var player = videojs('instruction-video');641 player.src({ type: "video/mp4", src: src });642 }643 };...
index.js
Source:index.js
...38 constructor(target, metadataKey, metadataDef, sourceRoot) {39 super(AstTypes.class, target, metadataKey, metadataDef, sourceRoot);40 }41 visit(visitor, context) {42 return visitor.visitClass(this, context);43 }44}45exports.ClassAst = ClassAst;46class ClassContext {47 constructor(ast, context) {48 this.context = context;49 this.imports = [];50 this.providers = [];51 this.ast = ast;52 const def = this.ast.metadataDef || {};53 def.imports && def.imports.map(im => {54 const ctx = context.visitType(im);55 return ctx.classes.map(cls => this.imports.push(cls));56 });57 def.imports && def.providers.map(pro => {58 this.providers.push(pro);59 });60 }61 get parent() {62 return this.context.typeContext.parent;63 }64 get sourceRoot() {65 return this.ast.sourceRoot;66 }67 get target() {68 return this.ast.target;69 }70 getParent(metadataKey) {71 if (this.parent) {72 return this.parent.getClass(metadataKey);73 }74 }75 forEachObjectToTypeContent(obj, defs = []) {76 if (obj)77 return Object.keys(obj).map(key => this.context.visitType(obj[key]));78 return defs;79 }80 inject(key) {81 const provider = this.providers.find(pro => {82 if (isClassProvider(pro)) {83 return pro.provide === key;84 }85 else if (isFactoryProvider(pro)) {86 return pro.provide === key;87 }88 else if (isValueProvider(pro)) {89 return pro.provide === key;90 }91 else {92 return pro === key;93 }94 });95 if (provider) {96 if (isClassProvider(provider)) {97 return this.inject(provider.useClass);98 }99 else if (isFactoryProvider(provider)) {100 const deps = provider.deps.map(dep => this.inject(dep));101 return provider.useFactory(...deps);102 }103 else if (isValueProvider(provider)) {104 return provider.useValue;105 }106 for (let im of this.imports) {107 let item = im.inject(key);108 if (item)109 return item;110 }111 }112 }113}114exports.ClassContext = ClassContext;115function isClassAst(val) {116 return val.type === AstTypes.class;117}118exports.isClassAst = isClassAst;119class PropertyAst extends Ast {120 constructor(target, metadataKey, metadataDef, propertyKey, propertyType, sourceRoot) {121 super(AstTypes.property, target, metadataKey, metadataDef, sourceRoot);122 this.propertyKey = propertyKey;123 this.propertyType = propertyType;124 }125 visit(visitor, context) {126 return visitor.visitProperty(this, context);127 }128}129exports.PropertyAst = PropertyAst;130class PropertyContext {131 constructor(ast, context) {132 this.ast = ast;133 this.context = context;134 }135}136exports.PropertyContext = PropertyContext;137function isPropertyAst(val) {138 return val.type === AstTypes.property;139}140exports.isPropertyAst = isPropertyAst;141class MethodAst extends Ast {142 constructor(target, metadataKey, metadataDef, propertyKey, returnType, parameterTypes, parameterLength, descriptor, sourceRoot) {143 super(AstTypes.method, target, metadataKey, metadataDef, sourceRoot);144 this.propertyKey = propertyKey;145 this.returnType = returnType;146 this.parameterTypes = parameterTypes;147 this.parameterLength = parameterLength;148 this.descriptor = descriptor;149 this.parameters = [];150 }151 visit(visitor, context) {152 return visitor.visitMethod(this, context);153 }154}155exports.MethodAst = MethodAst;156class MethodContext {157 constructor(ast, context) {158 this.ast = ast;159 this.context = context;160 this.parameters = [];161 if (ast.parameters)162 this.parameters = ast.parameters.map(par => context.visit(par));163 }164}165exports.MethodContext = MethodContext;166function isMethodAst(val) {167 return val.type === AstTypes.method;168}169exports.isMethodAst = isMethodAst;170class ParameterAst extends Ast {171 constructor(target, metadataKey, metadataDef, propertyKey, parameterType, parameterIndex, sourceRoot) {172 super(AstTypes.parameter, target, metadataKey, metadataDef, sourceRoot);173 this.propertyKey = propertyKey;174 this.parameterType = parameterType;175 this.parameterIndex = parameterIndex;176 }177 visit(visitor, context) {178 return visitor.visitParameter(this, context);179 }180}181exports.ParameterAst = ParameterAst;182class ParameterContext {183 constructor(ast, context) {184 this.ast = ast;185 this.context = context;186 }187}188exports.ParameterContext = ParameterContext;189function isParameterAst(val) {190 return val.type === AstTypes.parameter;191}192exports.isParameterAst = isParameterAst;193class ConstructorAst extends Ast {194 constructor(target, metadataKey, metadataDef, parameterType, parameterIndex, sourceRoot) {195 super(AstTypes.constructor, target, metadataKey, metadataDef, sourceRoot);196 this.parameterType = parameterType;197 this.parameterIndex = parameterIndex;198 }199 visit(visitor, context) {200 return visitor.visitConstructor(this, context);201 }202}203exports.ConstructorAst = ConstructorAst;204class ConstructorContext {205 constructor(ast, context) {206 this.ast = ast;207 }208}209exports.ConstructorContext = ConstructorContext;210function isConstructorAst(val) {211 return val.type === AstTypes.constructor;212}213exports.isConstructorAst = isConstructorAst;214class TypeContext {215 constructor(type, visitor) {216 this.type = type;217 this.visitor = visitor;218 this.children = [];219 this.classes = [];220 this.propertys = [];221 this.methods = [];222 this.constructors = [];223 this.providers = [];224 this.global = new Map();225 const context = getContext(type);226 if (context) {227 this.target = type;228 context.typeContext = this;229 context.visitor = visitor;230 this.classes = context.visitClass();231 this.propertys = context.visitProperty();232 this.methods = context.visitMethod();233 this.constructors = context.visitController();234 this.instance = inject(type);235 }236 else {237 throw new Error(`${type.name} get context error`);238 }239 }240 get instance() {241 const ins = this.get(this.target);242 if (ins)243 return ins;244 }245 set instance(instance) {246 this.set(this.target, instance);247 }248 setParent(parent) {249 this.parent = parent;250 parent.children.push(this);251 }252 get(key) {253 for (let cls of this.classes) {254 if (cls) {255 let item = cls.inject(key);256 if (item)257 return item;258 }259 }260 if (this.global.has(key))261 return this.global.get(key);262 if (this.parent)263 return this.parent.get(key);264 }265 set(key, val) {266 this.global.set(key, val);267 }268 inject(type) {269 return this.get(type);270 }271 getClass(metadataKey) {272 try {273 const item = this.classes.find(cls => cls.ast.metadataKey === metadataKey);274 if (item)275 return item;276 return this.parent && this.parent.getClass(metadataKey);277 }278 catch (e) {279 console.log(`pless ims-common to handler :${metadataKey}`);280 }281 }282 getProperty(metadataKey) {283 if (metadataKey) {284 return this.propertys.filter(cls => cls.ast.metadataKey === metadataKey);285 }286 return this.propertys;287 }288 getMethod(metadataKey) {289 if (metadataKey) {290 return this.methods.filter(cls => cls.ast.metadataKey === metadataKey);291 }292 return this.methods;293 }294 getController(metadataKey) {295 if (metadataKey) {296 return this.constructors.filter(cls => cls.ast.metadataKey === metadataKey);297 }298 return this.constructors;299 }300}301exports.TypeContext = TypeContext;302class NullAstVisitor {303 visit(ast, context) {304 return ast.visit(this, context);305 }306 visitType(type) {307 const context = getContext(type);308 if (context) {309 return new TypeContext(type, this);310 }311 else {312 throw new Error(`visitType:${type.name} get context error`);313 }314 }315 visitClass(ast, context) { }316 visitMethod(ast, context) { }317 visitProperty(ast, context) { }318 visitParameter(ast, context) { }319 visitConstructor(ast, context) { }320}321exports.NullAstVisitor = NullAstVisitor;322class Visitors extends NullAstVisitor {323 constructor(visitors) {324 super();325 this.visitors = visitors;326 this.addons = [];327 }328 visitClass(ast, context) {329 const res = this.visitMap(ast, context);330 if (res)331 return res;332 }333 visitConstructor(ast, context) {334 const res = this.visitMap(ast, context);335 if (res)336 return res;337 }338 visitParameter(ast, context) {339 const res = this.visitMap(ast, context);340 if (res)341 return res;342 }343 visitMethod(ast, context) {344 const res = this.visitMap(ast, context);345 if (res)346 return res;347 }348 visitProperty(ast, context) {349 const res = this.visitMap(ast, context);350 if (res)351 return res;352 }353 visitMap(ast, context) {354 context.visitor = this;355 for (let visitor of this.visitors) {356 const res = ast.visit(visitor, context);357 if (res)358 return res;359 }360 }361}362exports.Visitors = Visitors;363/** è·åParserAstContext */364exports.imsContext = Symbol.for('imsContext');365function getContext(target) {366 return Reflect.get(target, exports.imsContext);367}368exports.getContext = getContext;369class ParserAstContext {370 constructor() {371 this.constructors = [];372 this.classes = [];373 this.propertys = [];374 this.methods = [];375 this.parameters = [];376 this.parametersMap = new Map();377 this.global = {};378 }379 visit(ast) {380 return ast.visit(this.visitor, this);381 }382 visitType(type) {383 const typeContext = this.visitor.visitType(type);384 typeContext.setParent(this.typeContext);385 this.typeContext.set(type, typeContext.instance);386 return typeContext;387 }388 inject(type) {389 return this.typeContext.get(type);390 }391 visitClass(metadataKey) {392 if (metadataKey)393 return this.getClassAst(metadataKey).map(cls => this.visit(cls));394 return this.classes.map(cls => {395 return this.visit(cls);396 });397 }398 visitProperty(metadataKey) {399 if (metadataKey)400 return this.getProperty(metadataKey).map(cls => this.visit(cls));401 return this.propertys.map(cls => this.visit(cls));402 }403 visitMethod(metadataKey) {404 if (metadataKey)405 return this.getMethod(metadataKey).map(cls => this.visit(cls));406 return this.methods.map(cls => this.visit(cls));407 }408 visitController(metadataKey) {409 if (metadataKey)410 return this.getConstructor(metadataKey).map(cls => this.visit(cls));411 return this.constructors.map(cls => this.visit(cls));412 }413 getClassAst(metadataKey) {414 if (metadataKey) {415 return this.classes.filter(cls => cls.metadataKey === metadataKey);416 }417 else {418 return this.classes;419 }420 }421 getProperty(metadataKey) {422 if (metadataKey) {423 return this.propertys.filter(pro => pro.metadataKey === metadataKey);424 }425 else {426 return this.propertys;427 }428 }429 getMethod(metadataKey) {430 if (metadataKey) {431 return this.methods.filter(pro => pro.metadataKey === metadataKey);432 }433 else {434 return this.methods;435 }436 }437 getConstructor(metadataKey) {438 if (metadataKey && this.constructors) {439 return this.constructors.filter(pro => pro.metadataKey === metadataKey);440 }441 else {442 return this.constructors;443 }444 }445 get stats() {446 return this._stats;447 }448 set stats(val) {449 if (this.stats === AstTypes.parameter && val !== AstTypes.parameter) {450 // 离å¼ä¿åæ°æ®451 const ast = this.prevAst;452 if (isParameterAst(ast)) {453 this.parametersMap.set(ast.propertyKey, this.parameters);454 }455 this.parameters = [];456 }457 this._stats = val;458 }459}460exports.ParserAstContext = ParserAstContext;461class ParserVisitor extends NullAstVisitor {462 visitClass(ast, context) {463 context.stats = AstTypes.class;464 context.prevAst = ast;465 context.classes.push(ast);466 ast.target[exports.imsContext] = context;467 }468 visitConstructor(ast, context) {469 context.stats = AstTypes.constructor;470 context.prevAst = ast;471 context.constructors.push(ast);472 }473 visitProperty(ast, context) {474 context.stats = AstTypes.property;475 context.prevAst = ast;476 context.propertys.push(ast);477 }478 visitMethod(ast, context) {479 context.stats = AstTypes.method;480 context.prevAst = ast;481 ast.parameters = context.parametersMap.get(ast.propertyKey);482 context.methods.push(ast);483 }484 visitParameter(ast, context) {485 context.stats = AstTypes.parameter;486 context.prevAst = ast;487 context.parameters.push(ast);488 }489}490exports.ParserVisitor = ParserVisitor;491class ParserManager {492 constructor() {493 this.visitor = new ParserVisitor();494 this._map = new Map();495 }496 getContext(target) {497 if (this._map.has(target))498 return this._map.get(target);499 this._map.set(target, new ParserAstContext());500 return this.getContext(target);501 }502}503exports.ParserManager = ParserManager;504const parserManager = new ParserManager();505function makeDecorator2(metadataKey, pro) {506 return (...params) => {507 const opt = pro(...params);508 return makeDecorator(metadataKey)(opt);509 };510}511exports.makeDecorator2 = makeDecorator2;512function makeDecorator(metadataKey, getDefault = opt => opt.metadataDef || {}) {513 const visitor = parserManager.visitor;514 return (metadataDef) => (target, propertyKey, descriptor) => {515 const sourceRoot = metadataDef && metadataDef.sourceRoot;516 if (propertyKey) {517 if (typeof descriptor === 'number') {518 const context = parserManager.getContext(target.constructor);519 const types = exports.getDesignParamTypes(target, propertyKey);520 metadataDef = getDefault({521 type: 'parameter',522 metadataDef,523 metadataKey,524 target,525 propertyKey,526 parameterIndex: descriptor,527 parameterType: types[descriptor]528 });529 // parameter530 const ast = new ParameterAst(target, metadataKey, metadataDef, propertyKey, types[descriptor], descriptor, sourceRoot);531 visitor.visitParameter(ast, context);532 }533 else if (typeof descriptor === 'undefined') {534 // property535 const context = parserManager.getContext(target.constructor);536 const propertyType = exports.getDesignType(target, propertyKey);537 metadataDef = getDefault({538 type: 'property',539 metadataDef,540 metadataKey,541 target,542 propertyKey,543 propertyType544 });545 const ast = new PropertyAst(target, metadataKey, metadataDef, propertyKey, propertyType, sourceRoot);546 visitor.visitProperty(ast, context);547 }548 else {549 // method550 try {551 const returnType = exports.getDesignReturnType(target, propertyKey);552 const paramTypes = exports.getDesignParamTypes(target, propertyKey);553 const context = parserManager.getContext(target.constructor);554 metadataDef = getDefault({555 type: 'method',556 metadataDef,557 metadataKey,558 target,559 propertyKey,560 paramTypes,561 returnType562 });563 const ast = new MethodAst(target, metadataKey, metadataDef, propertyKey, returnType, paramTypes, target[propertyKey].length, descriptor, sourceRoot);564 visitor.visitMethod(ast, context);565 }566 catch (e) { }567 }568 }569 else {570 if (typeof descriptor === 'number') {571 // constructor572 const context = parserManager.getContext(target);573 const types = exports.getDesignParamTypes(target, 'constructor');574 metadataDef = getDefault({575 type: 'constructor',576 metadataDef,577 metadataKey,578 target,579 parameterType: types[descriptor],580 parameterIndex: descriptor581 });582 const ast = new ConstructorAst(target, metadataKey, metadataDef, types[descriptor], descriptor, sourceRoot);583 visitor.visitConstructor(ast, context);584 }585 else {586 // class587 const context = parserManager.getContext(target);588 metadataDef = getDefault({589 type: 'class',590 metadataDef,591 metadataKey,592 target593 });594 const ast = new ClassAst(target, metadataKey, metadataDef, sourceRoot);595 visitor.visitClass(ast, context);596 return target;597 }598 }599 };600}601exports.makeDecorator = makeDecorator;602function isClassProvider(val) {603 return typeof val.useClass === 'function';604}605exports.isClassProvider = isClassProvider;606function isValueProvider(val) {607 return !!val.useValue;608}609exports.isValueProvider = isValueProvider;...
patch-eslint-scope.js
Source:patch-eslint-scope.js
1"use strict";2var Module = require("module");3var path = require("path");4var t = require("@babel/types");5function getModules() {6 try {7 // avoid importing a local copy of eslint, try to find a peer dependency8 var eslintLoc = Module._resolveFilename("eslint", module.parent);9 } catch (err) {10 try {11 // avoids breaking in jest where module.parent is undefined12 eslintLoc = require.resolve("eslint");13 } catch (err) {14 throw new ReferenceError("couldn't resolve eslint");15 }16 }17 // get modules relative to what eslint will load18 var eslintMod = new Module(eslintLoc);19 eslintMod.filename = eslintLoc;20 eslintMod.paths = Module._nodeModulePaths(path.dirname(eslintLoc));21 try {22 var escope = eslintMod.require("eslint-scope");23 var Definition = eslintMod.require("eslint-scope/lib/definition")24 .Definition;25 var referencer = eslintMod.require("eslint-scope/lib/referencer");26 } catch (err) {27 escope = eslintMod.require("escope");28 Definition = eslintMod.require("escope/lib/definition").Definition;29 referencer = eslintMod.require("escope/lib/referencer");30 }31 var estraverse = eslintMod.require("estraverse");32 if (referencer.__esModule) referencer = referencer.default;33 return {34 Definition,35 escope,36 estraverse,37 referencer,38 };39}40function monkeypatch(modules) {41 var Definition = modules.Definition;42 var escope = modules.escope;43 var estraverse = modules.estraverse;44 var referencer = modules.referencer;45 Object.assign(estraverse.VisitorKeys, t.VISITOR_KEYS);46 estraverse.VisitorKeys.MethodDefinition.push("decorators");47 estraverse.VisitorKeys.Property.push("decorators");48 // if there are decorators, then visit each49 function visitDecorators(node) {50 if (!node.decorators) {51 return;52 }53 for (var i = 0; i < node.decorators.length; i++) {54 if (node.decorators[i].expression) {55 this.visit(node.decorators[i]);56 }57 }58 }59 // iterate through part of t.VISITOR_KEYS60 var flowFlippedAliasKeys = t.FLIPPED_ALIAS_KEYS.Flow.concat([61 "ArrayPattern",62 "ClassDeclaration",63 "ClassExpression",64 "FunctionDeclaration",65 "FunctionExpression",66 "Identifier",67 "ObjectPattern",68 "RestElement",69 ]);70 var visitorKeysMap = Object.keys(t.VISITOR_KEYS).reduce(function(acc, key) {71 var value = t.VISITOR_KEYS[key];72 if (flowFlippedAliasKeys.indexOf(value) === -1) {73 acc[key] = value;74 }75 return acc;76 }, {});77 var propertyTypes = {78 // loops79 callProperties: { type: "loop", values: ["value"] },80 indexers: { type: "loop", values: ["key", "value"] },81 properties: { type: "loop", values: ["argument", "value"] },82 types: { type: "loop" },83 params: { type: "loop" },84 // single property85 argument: { type: "single" },86 elementType: { type: "single" },87 qualification: { type: "single" },88 rest: { type: "single" },89 returnType: { type: "single" },90 // others91 typeAnnotation: { type: "typeAnnotation" },92 typeParameters: { type: "typeParameters" },93 id: { type: "id" },94 };95 function visitTypeAnnotation(node) {96 // get property to check (params, id, etc...)97 var visitorValues = visitorKeysMap[node.type];98 if (!visitorValues) {99 return;100 }101 // can have multiple properties102 for (var i = 0; i < visitorValues.length; i++) {103 var visitorValue = visitorValues[i];104 var propertyType = propertyTypes[visitorValue];105 var nodeProperty = node[visitorValue];106 // check if property or type is defined107 if (propertyType == null || nodeProperty == null) {108 continue;109 }110 if (propertyType.type === "loop") {111 for (var j = 0; j < nodeProperty.length; j++) {112 if (Array.isArray(propertyType.values)) {113 for (var k = 0; k < propertyType.values.length; k++) {114 var loopPropertyNode = nodeProperty[j][propertyType.values[k]];115 if (loopPropertyNode) {116 checkIdentifierOrVisit.call(this, loopPropertyNode);117 }118 }119 } else {120 checkIdentifierOrVisit.call(this, nodeProperty[j]);121 }122 }123 } else if (propertyType.type === "single") {124 checkIdentifierOrVisit.call(this, nodeProperty);125 } else if (propertyType.type === "typeAnnotation") {126 visitTypeAnnotation.call(this, node.typeAnnotation);127 } else if (propertyType.type === "typeParameters") {128 for (var l = 0; l < node.typeParameters.params.length; l++) {129 checkIdentifierOrVisit.call(this, node.typeParameters.params[l]);130 }131 } else if (propertyType.type === "id") {132 if (node.id.type === "Identifier") {133 checkIdentifierOrVisit.call(this, node.id);134 } else {135 visitTypeAnnotation.call(this, node.id);136 }137 }138 }139 }140 function checkIdentifierOrVisit(node) {141 if (node.typeAnnotation) {142 visitTypeAnnotation.call(this, node.typeAnnotation);143 } else if (node.type === "Identifier") {144 this.visit(node);145 } else {146 visitTypeAnnotation.call(this, node);147 }148 }149 function nestTypeParamScope(manager, node) {150 var parentScope = manager.__currentScope;151 var scope = new escope.Scope(152 manager,153 "type-parameters",154 parentScope,155 node,156 false157 );158 manager.__nestScope(scope);159 for (var j = 0; j < node.typeParameters.params.length; j++) {160 var name = node.typeParameters.params[j];161 scope.__define(name, new Definition("TypeParameter", name, name));162 if (name.typeAnnotation) {163 checkIdentifierOrVisit.call(this, name);164 }165 }166 scope.__define = function() {167 return parentScope.__define.apply(parentScope, arguments);168 };169 return scope;170 }171 // visit decorators that are in: ClassDeclaration / ClassExpression172 var visitClass = referencer.prototype.visitClass;173 referencer.prototype.visitClass = function(node) {174 visitDecorators.call(this, node);175 var typeParamScope;176 if (node.typeParameters) {177 typeParamScope = nestTypeParamScope.call(this, this.scopeManager, node);178 }179 // visit flow type: ClassImplements180 if (node.implements) {181 for (var i = 0; i < node.implements.length; i++) {182 checkIdentifierOrVisit.call(this, node.implements[i]);183 }184 }185 if (node.superTypeParameters) {186 for (var k = 0; k < node.superTypeParameters.params.length; k++) {187 checkIdentifierOrVisit.call(this, node.superTypeParameters.params[k]);188 }189 }190 visitClass.call(this, node);191 if (typeParamScope) {192 this.close(node);193 }194 };195 // visit decorators that are in: Property / MethodDefinition196 var visitProperty = referencer.prototype.visitProperty;197 referencer.prototype.visitProperty = function(node) {198 if (node.value && node.value.type === "TypeCastExpression") {199 visitTypeAnnotation.call(this, node.value);200 }201 visitDecorators.call(this, node);202 visitProperty.call(this, node);203 };204 function visitClassProperty(node) {205 if (node.typeAnnotation) {206 visitTypeAnnotation.call(this, node.typeAnnotation);207 }208 this.visitProperty(node);209 }210 // visit ClassProperty as a Property.211 referencer.prototype.ClassProperty = visitClassProperty;212 // visit ClassPrivateProperty as a Property.213 referencer.prototype.ClassPrivateProperty = visitClassProperty;214 // visit OptionalMemberExpression as a MemberExpression.215 referencer.prototype.OptionalMemberExpression =216 referencer.prototype.MemberExpression;217 // visit flow type in FunctionDeclaration, FunctionExpression, ArrowFunctionExpression218 var visitFunction = referencer.prototype.visitFunction;219 referencer.prototype.visitFunction = function(node) {220 var typeParamScope;221 if (node.typeParameters) {222 typeParamScope = nestTypeParamScope.call(this, this.scopeManager, node);223 }224 if (node.returnType) {225 checkIdentifierOrVisit.call(this, node.returnType);226 }227 // only visit if function parameters have types228 if (node.params) {229 for (var i = 0; i < node.params.length; i++) {230 var param = node.params[i];231 if (param.typeAnnotation) {232 checkIdentifierOrVisit.call(this, param);233 } else if (t.isAssignmentPattern(param)) {234 if (param.left.typeAnnotation) {235 checkIdentifierOrVisit.call(this, param.left);236 }237 }238 }239 }240 // set ArrayPattern/ObjectPattern visitor keys back to their original. otherwise241 // escope will traverse into them and include the identifiers within as declarations242 estraverse.VisitorKeys.ObjectPattern = ["properties"];243 estraverse.VisitorKeys.ArrayPattern = ["elements"];244 visitFunction.call(this, node);245 // set them back to normal...246 estraverse.VisitorKeys.ObjectPattern = t.VISITOR_KEYS.ObjectPattern;247 estraverse.VisitorKeys.ArrayPattern = t.VISITOR_KEYS.ArrayPattern;248 if (typeParamScope) {249 this.close(node);250 }251 };252 // visit flow type in VariableDeclaration253 var variableDeclaration = referencer.prototype.VariableDeclaration;254 referencer.prototype.VariableDeclaration = function(node) {255 if (node.declarations) {256 for (var i = 0; i < node.declarations.length; i++) {257 var id = node.declarations[i].id;258 var typeAnnotation = id.typeAnnotation;259 if (typeAnnotation) {260 checkIdentifierOrVisit.call(this, typeAnnotation);261 }262 }263 }264 variableDeclaration.call(this, node);265 };266 function createScopeVariable(node, name) {267 this.currentScope().variableScope.__define(268 name,269 new Definition("Variable", name, node, null, null, null)270 );271 }272 referencer.prototype.InterfaceDeclaration = function(node) {273 createScopeVariable.call(this, node, node.id);274 var typeParamScope;275 if (node.typeParameters) {276 typeParamScope = nestTypeParamScope.call(this, this.scopeManager, node);277 }278 // TODO: Handle mixins279 for (var i = 0; i < node.extends.length; i++) {280 visitTypeAnnotation.call(this, node.extends[i]);281 }282 visitTypeAnnotation.call(this, node.body);283 if (typeParamScope) {284 this.close(node);285 }286 };287 referencer.prototype.TypeAlias = function(node) {288 createScopeVariable.call(this, node, node.id);289 var typeParamScope;290 if (node.typeParameters) {291 typeParamScope = nestTypeParamScope.call(this, this.scopeManager, node);292 }293 if (node.right) {294 visitTypeAnnotation.call(this, node.right);295 }296 if (typeParamScope) {297 this.close(node);298 }299 };300 referencer.prototype.DeclareModule = referencer.prototype.DeclareFunction = referencer.prototype.DeclareVariable = referencer.prototype.DeclareClass = function(301 node302 ) {303 if (node.id) {304 createScopeVariable.call(this, node, node.id);305 }306 var typeParamScope;307 if (node.typeParameters) {308 typeParamScope = nestTypeParamScope.call(this, this.scopeManager, node);309 }310 if (typeParamScope) {311 this.close(node);312 }313 };314 referencer._babelEslintPatched = true;315}316// To patch for each call.317var escope = null;318var escopeAnalyze = null;319module.exports = function(parserOptions) {320 // Patch `Referencer.prototype` once.321 if (!escope) {322 const modules = getModules();323 monkeypatch(modules);324 // Store to patch for each call.325 escope = modules.escope;326 escopeAnalyze = modules.escope.analyze;327 }328 // Patch `escope.analyze` based on the current parserOptions.329 escope.analyze = function(ast, opts) {330 opts = opts || {};331 opts.ecmaVersion = parserOptions.ecmaVersion;332 opts.sourceType = parserOptions.sourceType;333 opts.nodejsScope =334 ast.sourceType === "script" &&335 (parserOptions.ecmaFeatures &&336 parserOptions.ecmaFeatures.globalReturn) === true;337 return escopeAnalyze.call(this, ast, opts);338 };...
missingDocs.js
Source:missingDocs.js
...120 /**121 * @param {string} className122 * @param {!ts.Type} classType123 */124 function visitClass(className, classType) {125 let methods = apiMethods.get(className);126 if (!methods) {127 methods = new Map();128 apiMethods.set(className, methods);129 }130 for (const [name, member] of /** @type {any[]} */(classType.symbol.members || [])) {131 if (shouldSkipMethodByName(className, name))132 continue;133 const memberType = checker.getTypeOfSymbolAtLocation(member, member.valueDeclaration);134 const signature = signatureForType(memberType);135 if (signature)136 methods.set(name, new Set(signature.parameters.map(p => p.escapedName)));137 else138 methods.set(name, new Set());139 }140 for (const baseType of classType.getBaseTypes() || []) {141 const baseTypeName = baseType.symbol ? baseType.symbol.name : '';142 if (apiClassNames.has(baseTypeName))143 visitClass(className, baseType);144 }145 }146 /**147 * @param {!ts.Node} node148 */149 function visitMethods(node) {150 if (ts.isExportSpecifier(node)) {151 const className = node.name.text;152 const exportSymbol = node.name ? checker.getSymbolAtLocation(node.name) : /** @type {any} */ (node).symbol;153 const classType = checker.getDeclaredTypeOfSymbol(exportSymbol);154 if (!classType)155 throw new Error(`Cannot parse class "${className}"`);156 visitClass(className, classType);157 }158 ts.forEachChild(node, visitMethods);159 }160 /**161 * @param {!ts.Node} node162 */163 function visitNames(node) {164 if (ts.isExportSpecifier(node))165 apiClassNames.add(node.name.text);166 ts.forEachChild(node, visitNames);167 }168 visitNames(apiSource);169 visitMethods(apiSource);170 return apiMethods;...
find_nonfinals2.js
Source:find_nonfinals2.js
...69 return Java.super(visitor).visitCompilationUnit(compUnit, p);70 },71 visitClass: function(clazz, p) {72 clsName = clazz.name;73 return Java.super(visitor).visitClass(clazz, p);74 },75 visitMethod: function (method, p) {76 var params = method.parameters;77 for each (var p in params) {78 var modifiers = p.modifiers;79 if (! modifiers.flags.contains(Modifier.FINAL)) {80 print(compUnitName);81 print(pkgName + "." + clsName);82 printMethod(method);83 print("->", p,84 " @ " + lineMap.getLineNumber(p.pos) + ":" +85 lineMap.getColumnNumber(p.pos));86 }87 }...
experiment.js
Source:experiment.js
1var setup = {2 3 controllers: [4 5 //experimentController6 { name: "experimentController",7 8 taskTextButtonTime: 10,9 taskTime: 5,10 11 stepOrder: [ 10, 20 ],12 13 steps: [ 14 { number: 10,15 16 text: [17 "Willkommen beim Experiment LazyDog.",18 "Im Folgenden Verlauf wird die Interaktion mit einer Visualisierung eines Softwaresystems untersucht.",19 "Dazu lösen Sie 6 Aufgaben, bei denen die Zeit und die Fehlerrate gemessen wird.",20 "Zunächst starten Sie jedoch mit einem Tutorial.",21 "Betrachten Sie die Visualisierung kurz im Ãberblick und betätigen Sie anschlieÃend die \"Aufgabe abgeschlossen!\"-Schaltfläche oben rechts zwei mal."22 ], 23 ui: "UI0"24 },25 26 { number: 20,27 28 text: [29 "Sie sehen die Darstellung des Softwaresystems als Stadt(City).",30 "Klassen sind als dunkelblaue Gebäude in hellgrauen Stadtteilen, den Paketen, dargestellt.",31 "Jedes hellblaue Stockwerk ist eine Methode und jeder gelber Schornstein auf dem Dach des Gebäudes ein Attribut.",32 "Beim überfahren der Elemente mit der Maus wird der Name in einem Tooltip angezeigt.",33 "Versuchen Sie sich in der Visualisierung zu bewegen und beenden Sie die Aufgabe wieder über die Schaltfläche."34 ], 35 ui: "UI1",36 entities : [37 "edu_umd_cs_findbugs_visitclass_PreorderVisitor_className",38 "edu_umd_cs_findbugs_visitclass_PreorderVisitor_dottedSuperclassName",39 "edu_umd_cs_findbugs_visitclass_PreorderVisitor_superclassName",40 "edu_umd_cs_findbugs_visitclass_PreorderVisitor_sourceFile",41 "edu_umd_cs_findbugs_visitclass_PreorderVisitor_dottedClassName",42 "edu_umd_cs_findbugs_visitclass_PreorderVisitor_thisClassInfo",43 "edu_umd_cs_findbugs_visitclass_PreorderVisitor_packageName",44 "edu_umd_cs_findbugs_FindBugs_isNoAnalysis___",45 "edu_umd_cs_findbugs_classfile_DescriptorFactory_createClassDescriptor__java_lang_String_____"46 ]47 },48 ]49 50 },51 { name: "defaultLogger",52 logActionConsole : false,53 logEventConsole : false54 }, 55 56 { name: "canvasHoverController",57 },58 { name: "canvasSelectController" 59 }, 60 { name: "canvasResetViewController" 61 },62 63 64 ],65 66 67 68 uis: [69 { name: "UI0",70 71 navigation: {72 //examine, walk, fly, helicopter, lookAt, turntable, game73 type: "none",74 //speed: 1075 }, 76 77 78 79 area: {80 name: "top",81 orientation: "horizontal",82 83 first: { 84 size: "200px", 85 86 controllers: [ 87 { name: "experimentController" },88 { name: "canvasResetViewController" },89 ], 90 },91 second: {92 size: "90%", 93 collapsible: false,94 95 96 97 canvas: { },98 99 controllers: [100 101 { name: "defaultLogger" }, 102 ], 103 }104 }105 106 },107 { name: "UI1",108 109 navigation: {110 //examine, walk, fly, helicopter, lookAt, turntable, game111 type: "examine",112 //speed: 10113 }, 114 115 116 117 area: {118 name: "top",119 orientation: "horizontal",120 121 first: { 122 size: "200px", 123 124 controllers: [ 125 { name: "experimentController" }, 126 { name: "canvasResetViewController" },127 ], 128 },129 second: {130 size: "90%", 131 collapsible: false,132 133 134 135 canvas: { },136 137 controllers: [138 { name: "defaultLogger" }, 139 { name: "canvasHoverController" },140 { name: "canvasSelectController" },141 ], 142 }143 }144 145 }146 147 ]...
enhanced-parser3.js
Source:enhanced-parser3.js
...3const ScopeManager = require("eslint-scope/lib/scope-manager");4const Referencer = require("eslint-scope/lib/referencer");5const vk = require("eslint-visitor-keys");6class EnhancedReferencer extends Referencer {7 visitClass(node) {8 // Visit decorators.9 if (node.experimentalDecorators) {10 for (const decorator of node.experimentalDecorators) {11 this.visit(decorator);12 }13 }14 // Do default.15 super.visitClass(node);16 }17 Decorator(node) {18 if (node.expression) {19 this.visit(node.expression);20 }21 }22}23function analyzeScope(ast) {24 const options = {25 optimistic: false,26 directive: false,27 nodejsScope: false,28 impliedStrict: false,29 sourceType: "script",...
escope.js
Source:escope.js
1const referencer = require("escope/lib/referencer").default;2const { visitClass, visitProperty } = referencer.prototype;3// visit decorators on classes/properties to resolve their identifiers4referencer.prototype.visitClass = function(node) {5 visitDecorators.call(this, node);6 visitClass.call(this, node);7};8referencer.prototype.visitProperty = function(node) {9 visitDecorators.call(this, node);10 visitProperty.call(this, node);11};12function visitDecorators(node) {13 if (!node.decorators) {14 return;15 }16 node.decorators.forEach(d => this.visit(d));17}18// register class properties by visiting them as regular properties19referencer.prototype.ClassProperty = function(node) {20 this.visitProperty(node);21};...
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 for (const browserType of BROWSER) {4 const browser = await playwright[browserType].launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.screenshot({ path: `example-${browserType}.png` });8 await browser.close();9 }10})();11const playwright = require('playwright');12(async () => {13 for (const browserType of BROWSER) {14 const browser = await playwright[browserType].launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 await page.screenshot({ path: `example-${browserType}.png` });18 await browser.close();19 }20})();21const playwright = require('playwright');22(async () => {23 for (const browserType of BROWSER) {24 const browser = await playwright[browserType].launch();25 const context = await browser.newContext();26 const page = await context.newPage();27 await page.screenshot({ path: `example-${browserType}.png` });28 await browser.close();29 }30})();31const playwright = require('playwright');32(async () => {33 for (const browserType of BROWSER) {34 const browser = await playwright[browserType].launch();35 const context = await browser.newContext();36 const page = await context.newPage();37 await page.screenshot({ path: `example-${browserType}.png` });38 await browser.close();39 }40})();41const playwright = require('playwright');42(async () => {43 for (const browserType of BROWSER) {44 const browser = await playwright[browserType].launch();45 const context = await browser.newContext();46 const page = await context.newPage();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.evaluate(() => {7 window.__playwright__internal__objectStorage.get(window).visitClass('HTMLElement', (obj) => {8 if (obj.id === 'hplogo') {9 console.log('Found the logo');10 }11 });12 });13 await browser.close();14})();
Using AI Code Generation
1const playwright = require('playwright');2const { visitClass } = require('playwright/lib/server/supplements/recorder/recorderSupplement.js');3(async () => {4 const browser = await playwright.chromium.launch();5 const page = await browser.newPage();6 await browser.close();7})();8[Apache 2.0](LICENSE)
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!