How to use isLeafNode method in Puppeteer

Best JavaScript code snippet using puppeteer

route_resolvers_service.js

Source:route_resolvers_service.js Github

copy

Full Screen

1define(['angularAMD'], function (angularAMD) {2 angularAMD.service('routeResolvers', ['$rootScope', '$timeout', 'utils', function ($rootScope, $timeout, utils) {3 var accountDataWithReportList = function (args, deferred) {4 args5 .accountService6 .fetchAccountData(args.$route.current.params.accountId)7 .then(function () {8 args.collectiveReportModel9 .getReportList(10 args.$route.current.params.subAccountId,11 args.$route.current.params.advertiserId || -1,12 args.$route.current.params.brandId || -1,13 args.$route.current.params.campaignId || -114 )15 .then(function (response) {16 if (response && response.data.data) {17 args.collectiveReportModel.setReportList(response.data.data);18 deferred.resolve(response.data.data);19 } else {20 deferred.resolve([]);21 }22 args.$route.current.params.campaignId &&23 args.campaignSelectModel.fetchCampaign(args.$route.current.params.subAccountId, args.$route.current.params.campaignId);24 !args.$route.current.params.campaignId && args.campaignSelectModel.setSelectedCampaign({25 id: -1,26 name: 'All Media Plans',27 kpi: 'ctr',28 startDate: '-1',29 endDate: '-1'30 });31 args.$route.current.params.advertiserId && fetchCurrentAdvertiser(args);32 args.$route.current.params.advertiserId && args.$route.current.params.brandId && fetchCurrentBrand(args);33 });34 });35 },36 adsResolver = function (args, mode) {37 var deferred = args.$q.defer(),38 redirect = true;39 console.log('accountService', args.accountService);40 console.log('subAccountService', args.subAccountService);41 args42 .accountService43 .fetchAccountList()44 .then(function () {45 var isLeafNode;46 if (args.accountService.allowedAccount(args.$route.current.params.accountId)) {47 isLeafNode = args.accountService.getSelectedAccount().isLeafNode;48 if (!isLeafNode) {49 args50 .subAccountService51 .fetchSubAccountList(args.$route.current.params.accountId)52 .then(function () {53 if (args.subAccountService.allowedSubAccount(args.$route.current.params.subAccountId)) {54 fetchAccountDataSetWSInfo(args, deferred, redirect, args.constants.ACCOUNT_CHANGE_MSG_ON_CREATE_OR_EDIT_AD_PAGE, mode, true);55 }56 });57 } else {58 fetchAccountDataSetWSInfo(args, deferred, redirect, args.constants.ACCOUNT_CHANGE_MSG_ON_CREATE_OR_EDIT_AD_PAGE, mode, true);59 }60 } else {61 console.log('account not allowed');62 args.$location.url('/tmp');63 }64 });65 return deferred.promise;66 },67 adminHeaderResolver = function (args) {68 var deferred = args.$q.defer(),69 params = args.$route.current.params,70 isLeafNode;71 if (!args.loginModel.getClientData().is_super_admin) {72 args.$location.url('/dashboard');73 }74 args75 .accountService76 .fetchAccountList()77 .then(function () {78 if (args.accountService.allowedAccount(args.$route.current.params.accountId)) {79 isLeafNode = args.accountService.getSelectedAccount().isLeafNode;80 if (!isLeafNode) {81 args82 .subAccountService83 .fetchSubAccountList(args.$route.current.params.accountId)84 .then(function () {85 fetchAccountData(args, params, deferred);86 });87 } else {88 fetchAccountData(args, params, deferred);89 }90 } else {91 console.log('account ' + params.accountId + ' not allowed');92 args.$location.url('/tmp');93 }94 });95 return deferred.promise;96 },97 creativeListResolver = function (args) {98 var deferred = args.$q.defer(),99 redirect = false;100 console.log('creativeResolver(), redirect = ', redirect);101 args102 .accountService103 .fetchAccountList()104 .then(function () {105 var isLeafNode;106 if (args.accountService.allowedAccount(args.$route.current.params.accountId)) {107 isLeafNode = args.accountService.getSelectedAccount().isLeafNode;108 console.log('creativeResolver(): account ALLOWED!');109 if (!isLeafNode) {110 args111 .subAccountService112 .fetchSubAccountList(args.$route.current.params.accountId)113 .then(function () {114 if (args.subAccountService.allowedSubAccount(args.$route.current.params.subAccountId)) {115 fetchAccountDataSetWSInfo(args, deferred, redirect, args.constants.ACCOUNT_CHANGE_MSG_ON_CREATIVE_LIST_PAGE);116 }117 });118 } else {119 fetchAccountDataSetWSInfo(args, deferred, redirect, args.constants.ACCOUNT_CHANGE_MSG_ON_CREATIVE_LIST_PAGE);120 }121 } else {122 console.log('creativeResolver(): account not allowed');123 args.$location.url('/tmp');124 }125 });126 return deferred.promise;127 },128 creativePreviewResolver = function (args) {129 var deferred = args.$q.defer(),130 redirect = false,131 commonPreviewCheckFunc = function(args, deferred, redirect, msg) {132 if (args.$route.current.params.accountId === args.$route.current.params.subAccountId) {133 fetchAccountDataSetWSInfo(args, deferred, redirect, msg);134 } else {135 console.log('account not allowed');136 args.$location.url('/tmp');137 }138 };139 args140 .accountService141 .fetchAccountList()142 .then(function () {143 var isLeafNode;144 if (args.accountService.allowedAccount(args.$route.current.params.accountId)) {145 isLeafNode = args.accountService.getSelectedAccount().isLeafNode;146 if (!isLeafNode && args.$route.current.params.subAccountId) {147 args148 .subAccountService149 .fetchSubAccountList(args.$route.current.params.accountId)150 .then(function () {151 if (args.subAccountService.allowedSubAccount(args.$route.current.params.subAccountId)) {152 fetchAccountDataSetWSInfo(args, deferred, redirect, args.constants.ACCOUNT_CHANGE_MSG_ON_CREATIVE_LIST_PAGE);153 } else {154 commonPreviewCheckFunc(args, deferred, redirect, args.constants.ACCOUNT_CHANGE_MSG_ON_CREATIVE_LIST_PAGE);155 }156 });157 } else {158 fetchAccountDataSetWSInfo(args, deferred, redirect, args.constants.ACCOUNT_CHANGE_MSG_ON_CREATIVE_LIST_PAGE);159 }160 } else {161 commonPreviewCheckFunc(args, deferred, redirect, args.constants.ACCOUNT_CHANGE_MSG_ON_CREATIVE_LIST_PAGE);162 }163 });164 return deferred.promise;165 },166 creativeResolver = function (args) {167 var deferred = args.$q.defer(),168 redirect = false;169 args170 .accountService171 .fetchAccountList()172 .then(function () {173 var isLeafNode;174 if (args.accountService.allowedAccount(args.$route.current.params.accountId)) {175 isLeafNode = args.accountService.getSelectedAccount().isLeafNode;176 if (!isLeafNode) {177 args178 .subAccountService179 .fetchSubAccountList(args.$route.current.params.accountId)180 .then(function () {181 if (args.subAccountService.allowedSubAccount(args.$route.current.params.subAccountId)) {182 fetchAccountDataSetWSInfo(args, deferred, redirect, args.constants.ACCOUNT_CHANGE_MSG_ON_CREATE_OR_EDIT_AD_PAGE);183 }184 });185 } else {186 fetchAccountDataSetWSInfo(args, deferred, redirect, args.constants.ACCOUNT_CHANGE_MSG_ON_CREATE_OR_EDIT_AD_PAGE);187 }188 } else {189 console.log('account not allowed');190 args.$location.url('/tmp');191 }192 });193 return deferred.promise;194 },195 dashboardHeaderResolver = function (args) {196 var deferred = args.$q.defer(),197 params = args.$route.current.params;198 args199 .accountService200 .fetchAccountList()201 .then(function () {202 if (args.accountService.allowedAccount(params.accountId)) {203 args204 .accountService205 .fetchAccountData(params.accountId)206 .then(function () {207 deferred.resolve();208 if (params.advertiserId && params.brandId) {209 console.log('fetching the advertiser & brand before loading dashboard. See resolve function');210 } else {211 // fetch the advertiser async212 params.advertiserId && fetchCurrentAdvertiser(args);213 }214 });215 } else {216 console.log('account not allowed');217 args.$location.url('/tmp');218 }219 });220 return deferred.promise;221 },222 dashboardHeaderResolver2 = function (args) {223 var deferred = args.$q.defer(),224 params = args.$route.current.params;225 args226 .accountService227 .fetchAccountList()228 .then(function () {229 if (args.accountService.allowedAccount(args.$route.current.params.accountId)) {230 args231 .subAccountService232 .fetchSubAccountList(args.$route.current.params.accountId)233 .then(function () {234 if (args.subAccountService.allowedSubAccount(args.$route.current.params.subAccountId)) {235 args236 .accountService237 .fetchAccountData(params.accountId)238 .then(function () {239 deferred.resolve();240 if (params.advertiserId && params.brandId) {241 console.log('fetching the advertiser & brand before loading dashboard. See resolve function');242 } else {243 params.advertiserId && fetchCurrentAdvertiser(args);244 }245 });246 } else {247 console.log('dashboard account ' + params.subAccountId + 'not allowed');248 args.$location.url('/tmp');249 }250 });251 } else {252 console.log('account ' + params.accountId + ' not allowed');253 args.$location.url('/tmp');254 }255 });256 return deferred.promise;257 },258 fetchAccountData = function (args, params, deferred) {259 args260 .accountService261 .fetchAccountData(args.$route.current.params.accountId)262 .then(function () {263 deferred.resolve();264 args.$route.current.params.advertiserId && fetchCurrentAdvertiser(args);265 args.$route.current.params.advertiserId && args.$route.current.params.brandId && fetchCurrentBrand(args);266 });267 },268 fetchAccountDataSetWSInfo = function (args, deferred, redirect, warningMsg, mode, adGroup) {269 args270 .accountService271 .fetchAccountData(args.$route.current.params.accountId)272 .then(function () {273 args.$route.current.params.advertiserId && fetchCurrentAdvertiser(args);274 deferred.resolve();275 if (mode) {276 args.workflowService.setMode(mode);277 }278 if (adGroup) {279 args.workflowService.setIsAdGroup(true);280 }281 args.workflowService.setModuleInfo({282 moduleName: 'WORKFLOW',283 warningMsg: warningMsg,284 redirect: redirect285 });286 });287 },288 fetchAccountDataWithCampaign = function (args, deferred) {289 args290 .accountService291 .fetchAccountData(args.$route.current.params.accountId)292 .then(function () {293 var params = args.$route.current.params,294 currentPath = args.$location.path();295 args296 .campaignSelectModel297 .fetchCampaigns(params.subAccountId, params.advertiserId || -1, params.brandId || -1)298 .then(function (campaignsResponse) {299 var campaign,300 url = '/a/' + params.accountId + '/sa/' + params.subAccountId;301 if (campaignsResponse && campaignsResponse.data.data) {302 campaign = campaignsResponse.data.data[0];303 if (campaign) {304 if (params.advertiserId) {305 //When user selects all brand, it will not be selected as campaign brand id is getting used - Sapna306 url += '/adv/' + campaign.advertiser_id + '/b/' + (params.brandId || 0);307 }308 url += '/mediaplans/' + campaign.campaign_id + '/' + params.reportName;309 } else {310 if (params.advertiserId) {311 utils.cleanSearchParameter();312 args.vistoconfig.setNoMediaPlanFoundMsg(args.constants.MEDIAPLAN_NOT_FOUND_FOR_SELECTED_BRAND);313 (params.advertiserId > 0) && (url += '/adv/' + params.advertiserId);314 (params.advertiserId > 0) && (url += '/b/0');315 url += '/mediaplans/reports' + currentPath.substr(currentPath.lastIndexOf('/'), currentPath.length);316 } else {317 utils.cleanSearchParameter();318 args.vistoconfig.setNoMediaPlanFoundMsg(args.constants.MEDIAPLAN_NOT_FOUND_FOR_SELECTED_ACCOUNT);319 url += '/mediaplans';320 }321 }322 args.$location.url(url);323 }324 deferred.resolve();325 });326 });327 },328 fetchAdvertiserAndBrand = function (args) {329 args.$route.current.params.advertiserId && fetchCurrentAdvertiser(args);330 args.$route.current.params.advertiserId && args.$route.current.params.brandId && fetchCurrentBrand(args);331 },332 fetchCampaignStrategy = function (args, deferred) {333 var resolvedOtherDeferrer = false;334 args335 .campaignSelectModel336 .fetchCampaign(args.$route.current.params.subAccountId || args.$route.current.params.accountId, args.$route.current.params.campaignId)337 .then(function () {338 if (resolvedOtherDeferrer) {339 deferred.resolve();340 $timeout(function() {341 fetchAdvertiserAndBrand(args);342 }, 100);343 } else {344 resolvedOtherDeferrer = true;345 }346 }, function () {347 deferred.reject('Mediaplan not found');348 });349 args350 .strategySelectModel351 .fetchStrategyList(args.$route.current.params.subAccountId || args.$route.current.params.accountId, args.$route.current.params.campaignId)352 .then(function () {353 if (args.strategySelectModel.allowedStrategy(args.$route.current.params.lineitemId)) {354 console.log('broadcast set strategy');355 } else {356 console.log('strategy not allowed');357 args.$location.url('/tmp');358 }359 if (resolvedOtherDeferrer) {360 deferred.resolve();361 $timeout(function() {362 fetchAdvertiserAndBrand(args);363 }, 100);364 } else {365 resolvedOtherDeferrer = true;366 }367 }, function () {368 console.log('strategies not found');369 });370 },371 fetchCurrentAdvertiser = function (args) {372 var params = args.$route.current.params,373 deferred = args.$q.defer();374 args375 .advertiserModel376 .fetchAdvertiserList(params.subAccountId || params.accountId)377 .then(function () {378 var advertiser;379 if (args.advertiserModel.allowedAdvertiser(params.advertiserId)) {380 advertiser = args.advertiserModel.getSelectedAdvertiser();381 $('#advertiser_name_selected').text(advertiser.name);382 $('#advertisersDropdown').attr('placeholder', advertiser.name).val('');383 $rootScope.$broadcast('advertiser:set', advertiser);384 if (args.$location.path().endsWith('/dashboard')) {385 $('#advertiserButton').hide();386 args.dashboardModel.setSelectedAdvertiser(advertiser);387 }388 } else {389 console.log('advertiser not allowed');390 args.$location.url('/tmp');391 }392 deferred.resolve();393 });394 return deferred.promise;395 },396 fetchCurrentBrand = function (args,dashboardSubAccountId) {397 var params = args.$route.current.params,398 accountId = params.subAccountId || params.accountId;399 if (params.subAccountId && dashboardSubAccountId) {400 accountId = dashboardSubAccountId;401 }402 args403 .brandsModel404 .fetchBrandList(accountId, params.advertiserId)405 .then(function () {406 var brand;407 if (args.brandsModel.allowedBrand(params.brandId)) {408 brand = args.brandsModel.getSelectedBrand();409 $('#brand_name_selected').text(brand.name);410 $('#brandsDropdown').attr('placeholder', brand.name).val('');411 $rootScope.$broadcast('brand:set', brand);412 } else {413 console.log('brand not allowed');414 args.$location.url('/tmp');415 }416 });417 },418 invoiceHeader = function (args) {419 var deferred = args.$q.defer(),420 params = args.$route.current.params,421 isLeafNode;422 console.log('invoiceHeader, params = ', params);423 args424 .accountService425 .fetchAccountList()426 .then(function () {427 if (args.accountService.allowedAccount(args.$route.current.params.accountId)) {428 isLeafNode = args.accountService.getSelectedAccount().isLeafNode;429 if (!isLeafNode) {430 args431 .subAccountService432 .fetchSubAccountList(args.$route.current.params.accountId)433 .then(function () {434 if (args.subAccountService.allowedSubAccount(args.$route.current.params.subAccountId)) {435 fetchAccountData(args, params, deferred);436 }437 });438 } else {439 fetchAccountData(args, params, deferred);440 }441 } else {442 console.log('account ' + params.accountId + ' not allowed');443 args.$location.url('/tmp');444 }445 });446 return deferred.promise;447 },448 mediaPlanCreateResolver = function (args, mode) {449 var deferred = args.$q.defer(),450 redirect = true;451 console.log('accountService', args.accountService);452 console.log('subAccountService', args.subAccountService);453 args454 .accountService455 .fetchAccountList()456 .then(function () {457 var isLeafNode;458 if (args.accountService.allowedAccount(args.$route.current.params.accountId)) {459 isLeafNode = args.accountService.getSelectedAccount().isLeafNode;460 if (!isLeafNode) {461 args462 .subAccountService463 .fetchMediaplanCreateSubAccountList(args.$route.current.params.accountId)464 .then(function () {465 if (!args.subAccountService.allowedMediaplanCreateSubAccount(args.$route.current.params.subAccountId)) {466 args.subAccountService.allowedMediaplanCreateSubAccount(args.subAccountService.getMediaplanCreateSubAccounts()[0].id);467 }468 fetchAccountDataSetWSInfo(args, deferred, redirect, args.constants.ACCOUNT_CHANGE_MSG_ON_CREATE_OR_EDIT_CAMPAIGN_PAGE, mode);469 });470 } else {471 fetchAccountDataSetWSInfo(args, deferred, redirect, args.constants.ACCOUNT_CHANGE_MSG_ON_CREATE_OR_EDIT_CAMPAIGN_PAGE, mode);472 }473 } else {474 console.log('account not allowed');475 args.$location.url('/tmp');476 }477 });478 return deferred.promise;479 },480 mediaPlanOverviewResolver = function (args) {481 var deferred = args.$q.defer(),482 redirect = true;483 console.log('accountService', args.accountService);484 console.log('subAccountService', args.subAccountService);485 args486 .accountService487 .fetchAccountList()488 .then(function () {489 var isLeafNode;490 if (args.accountService.allowedAccount(args.$route.current.params.accountId)) {491 isLeafNode = args.accountService.getSelectedAccount().isLeafNode;492 if (!isLeafNode) {493 args494 .subAccountService495 .fetchSubAccountList(args.$route.current.params.accountId)496 .then(function () {497 if (args.subAccountService.allowedSubAccount(args.$route.current.params.subAccountId)) {498 fetchAccountDataSetWSInfo(args, deferred, redirect, args.constants.ACCOUNT_CHANGE_MSG_ON_CAMPIGN_OVERVIEW_PAGE);499 }500 });501 } else {502 fetchAccountDataSetWSInfo(args, deferred, redirect, args.constants.ACCOUNT_CHANGE_MSG_ON_CAMPIGN_OVERVIEW_PAGE);503 }504 } else {505 console.log('account not allowed');506 args.$location.url('/tmp');507 }508 });509 return deferred.promise;510 },511 mediaPlansHeaderResolver = function (args) {512 var deferred = args.$q.defer(),513 params = args.$route.current.params;514 args515 .accountService516 .fetchAccountList()517 .then(function () {518 if (args.accountService.allowedAccount(params.accountId)) {519 args520 .accountService521 .fetchAccountData(params.accountId)522 .then(function () {523 deferred.resolve();524 params.advertiserId && fetchCurrentAdvertiser(args);525 params.advertiserId && params.brandId && fetchCurrentBrand(args);526 });527 } else {528 console.log('account ' + params.accountId + 'not allowed');529 args.$location.url('/tmp');530 }531 });532 return deferred.promise;533 },534 mediaPlansHeaderResolver2 = function (args) {535 var deferred = args.$q.defer(),536 params = args.$route.current.params;537 args538 .accountService539 .fetchAccountList()540 .then(function () {541 var isLeafNode;542 if (args.accountService.allowedAccount(params.accountId)) {543 isLeafNode = args.accountService.getSelectedAccount().isLeafNode;544 if (!isLeafNode) {545 args546 .subAccountService547 .fetchSubAccountList(params.accountId)548 .then(function () {549 if (args.subAccountService.allowedSubAccount(params.subAccountId)) {550 fetchAccountData(args, params, deferred);551 } else {552 console.log('dashboard account not allowed');553 args.$location.url('/tmp');554 }555 });556 } else {557 fetchAccountData(args, params, deferred);558 }559 } else {560 console.log('account ' + params.accountId + 'not allowed');561 args.$location.url('/tmp');562 }563 });564 return deferred.promise;565 },566 reportsHeaderResolverCampStrg = function(deferred,args,params,accountId) {567 var resolvedOtherDeferrer = false;568 args569 .campaignSelectModel570 .fetchCampaign(accountId, args.$route.current.params.campaignId)571 .then(function () {572 if (resolvedOtherDeferrer) {573 deferred.resolve();574 $timeout(function() {575 params.advertiserId && fetchCurrentAdvertiser(args);576 params.advertiserId && params.brandId && fetchCurrentBrand(args);577 }, 100);578 } else {579 resolvedOtherDeferrer = true;580 }581 }, function () {582 deferred.reject('Mediaplan not found');583 });584 args585 .strategySelectModel586 .fetchStrategyList(accountId, args.$route.current.params.campaignId)587 .then(function () {588 if (args.strategySelectModel.allowedStrategy(args.$route.current.params.lineitemId)) {589 console.log('broadcast set strategy');590 } else {591 console.log('strategy not allowed');592 args.$location.url('/tmp');593 }594 if (resolvedOtherDeferrer) {595 deferred.resolve();596 $timeout(function() {597 params.advertiserId && fetchCurrentAdvertiser(args);598 params.advertiserId && params.brandId && fetchCurrentBrand(args);599 }, 100);600 } else {601 resolvedOtherDeferrer = true;602 }603 }, function () {604 console.log('strategies not found');605 });606 },607 reportsHeaderResolver = function (args) {608 var deferred = args.$q.defer(),609 params = args.$route.current.params;610 args611 .accountService612 .fetchAccountList()613 .then(function () {614 var isLeafNode;615 if (args.accountService.allowedAccount(args.$route.current.params.accountId)) {616 isLeafNode = args.accountService.getSelectedAccount().isLeafNode;617 if (!isLeafNode) {618 args619 .subAccountService620 .fetchSubAccountList(args.$route.current.params.accountId)621 .then(function () {622 if (args.subAccountService.allowedSubAccount(args.$route.current.params.subAccountId)) {623 args624 .accountService625 .fetchAccountData(args.$route.current.params.accountId)626 .then(function () {627 reportsHeaderResolverCampStrg(deferred, args, params, args.$route.current.params.subAccountId);628 }, function () {629 deferred.reject('Client data not found');630 });631 }632 });633 } else {634 args635 .accountService636 .fetchAccountData(args.$route.current.params.accountId)637 .then(function () {638 reportsHeaderResolverCampStrg(deferred,args,params,args.$route.current.params.accountId);639 }, function () {640 deferred.reject('Client data not found');641 });642 }643 } else {644 console.log('account not allowed');645 args.$location.url('/tmp');646 }647 });648 return deferred.promise;649 },650 reportsHeaderResolver2 = function (args) {651 var deferred = args.$q.defer();652 args653 .accountService654 .fetchAccountList()655 .then(function () {656 var isLeafNode;657 if (args.accountService.allowedAccount(args.$route.current.params.accountId)) {658 isLeafNode = args.accountService.getSelectedAccount().isLeafNode;659 // if not leaf node i.e having sub-account then fetch sub-account660 if (!isLeafNode) {661 args662 .subAccountService663 .fetchSubAccountList(args.$route.current.params.accountId)664 .then(function () {665 if (args.subAccountService.allowedSubAccount(args.$route.current.params.subAccountId)) {666 args667 .accountService668 .fetchAccountData(args.$route.current.params.accountId)669 .then(function () {670 fetchCampaignStrategy(args, deferred);671 }, function () {672 deferred.reject('Client data not found');673 });674 } else {675 console.log('sub account not allowed');676 args.$location.url('/tmp');677 }678 });679 } else {680 // if it's a leaf node i.e not having subaccount681 args682 .accountService683 .fetchAccountData(args.$route.current.params.accountId)684 .then(function () {685 fetchCampaignStrategy(args, deferred);686 }, function () {687 deferred.reject('Client data not found');688 });689 }690 } else {691 console.log('account not allowed');692 args.$location.url('/tmp');693 }694 });695 return deferred.promise;696 },697 // report header resolver without campaign id - we pick the campaign here698 reportsHeaderResolverWOCampaign = function (args) {699 var deferred = args.$q.defer();700 args701 .accountService702 .fetchAccountList()703 .then(function () {704 if (args.accountService.allowedAccount(args.$route.current.params.accountId)) {705 args706 .accountService707 .fetchAccountData(args.$route.current.params.accountId)708 .then(function () {709 var params = args.$route.current.params;710 args711 .campaignSelectModel712 .fetchCampaigns(params.accountId, params.advertiserId || -1, params.brandId || -1)713 .then(function (campaignsResponse) {714 var campaign,715 url;716 if (campaignsResponse && campaignsResponse.data.data) {717 campaign = campaignsResponse.data.data[0];718 url = '/a/' + params.accountId;719 if (campaign) {720 //url += '/adv/' + campaign.advertiser_id + '/b/' + (campaign.brand_id || 0);721 url += '/mediaplans/' + campaign.campaign_id + '/' + params.reportName;722 } else {723 (params.advertiserId > 0) && (url += '/adv/' + params.advertiserId);724 (params.advertiserId > 0) && (params.brandId > 0) && (url += '/b/' + params.brandId);725 url += '/mediaplans';726 }727 args.$location.url(url);728 }729 deferred.resolve();730 });731 });732 } else {733 console.log('account not allowed');734 args.$location.url('/tmp');735 }736 });737 return deferred.promise;738 },739 reportsHeaderResolverWOCampaign2 = function (args) {740 var deferred = args.$q.defer();741 args742 .accountService743 .fetchAccountList()744 .then(function () {745 var isLeafNode;746 if (args.accountService.allowedAccount(args.$route.current.params.accountId)) {747 isLeafNode = args.accountService.getSelectedAccount().isLeafNode;748 if (!isLeafNode) {749 args750 .subAccountService751 .fetchSubAccountList(args.$route.current.params.accountId)752 .then(function () {753 if (args.subAccountService.allowedSubAccount(args.$route.current.params.subAccountId)) {754 fetchAccountDataWithCampaign(args, deferred);755 } else {756 console.log('sub account not allowed');757 args.$location.url('/tmp');758 }759 });760 } else {761 fetchAccountDataWithCampaign(args, deferred);762 }763 } else {764 console.log('account not allowed');765 args.$location.url('/tmp');766 }767 });768 return deferred.promise;769 },770 scheduleReportListCreateResolver = function (args) {771 var deferred = args.$q.defer(),772 params = args.$route.current.params;773 args774 .accountService775 .fetchAccountList()776 .then(function () {777 if (args.accountService.allowedAccount(params.accountId)) {778 args779 .accountService780 .fetchAccountData(args.$route.current.params.accountId)781 .then(function () {782 deferred.resolve();783 });784 } else {785 console.log('account ' + params.accountId + 'not allowed');786 args.$location.url('/tmp');787 }788 });789 return deferred.promise;790 },791 fetchAccountDataWithReports = function(args, deferred) {792 var params = args.$route.current.params;793 args794 .accountService795 .fetchAccountData(args.$route.current.params.accountId)796 .then(function () {797 args798 .collectiveReportModel799 .getReportList(params.accountId, params.advertiserId || -1, params.brandId || -1, params.campaignId || -1)800 .then(function (response) {801 if (response && response.data.data) {802 args.collectiveReportModel.setReportList(response.data.data);803 deferred.resolve(response.data.data);804 } else {805 deferred.resolve([]);806 }807 params.campaignId && args.campaignSelectModel.fetchCampaign(params.accountId, params.campaignId);808 !params.campaignId && args.campaignSelectModel.setSelectedCampaign({809 id: -1,810 name: 'All Media Plans',811 kpi: 'ctr',812 startDate: '-1',813 endDate: '-1'814 });815 params.advertiserId && fetchCurrentAdvertiser(args);816 params.advertiserId && params.brandId && fetchCurrentBrand(args);817 });818 });819 },820 uploadReportsHeaderResolver = function (args) {821 var deferred = args.$q.defer(),822 isLeafNode;823 args824 .accountService825 .fetchAccountList()826 .then(function () {827 if (args.accountService.allowedAccount(args.$route.current.params.accountId)) {828 isLeafNode = args.accountService.getSelectedAccount().isLeafNode;829 if (!isLeafNode) {830 args831 .subAccountService832 .fetchSubAccountList(args.$route.current.params.accountId)833 .then(function () {834 if (args.subAccountService.allowedSubAccount(args.$route.current.params.subAccountId)) {835 fetchAccountDataWithReports(args, deferred);836 } else {837 console.log('sub account not allowed');838 args.$location.url('/tmp');839 }840 });841 } else {842 fetchAccountDataWithReports(args, deferred);843 }844 } else {845 console.log('account not allowed');846 args.$location.url('/tmp');847 }848 });849 return deferred.promise;850 },851 uploadReportsHeaderResolver2 = function (args) {852 var deferred = args.$q.defer(),853 params = args.$route.current.params;854 args855 .accountService856 .fetchAccountList()857 .then(function () {858 var isLeafNode;859 if (args.accountService.allowedAccount(args.$route.current.params.accountId)) {860 isLeafNode = args.accountService.getSelectedAccount().isLeafNode;861 if (!isLeafNode) {862 args863 .subAccountService864 .fetchSubAccountList(args.$route.current.params.accountId)865 .then(function () {866 if (args.subAccountService.allowedSubAccount(args.$route.current.params.subAccountId)) {867 accountDataWithReportList(args, deferred);868 } else {869 console.log('sub account ' + params.accountId + 'not allowed');870 args.$location.url('/tmp');871 }872 });873 } else {874 accountDataWithReportList(args, deferred);875 }876 } else {877 console.log('account ' + params.accountId + ' not allowed');878 args.$location.url('/tmp');879 }880 });881 return deferred.promise;882 };883 return {884 adsResolver: adsResolver,885 adminHeaderResolver: adminHeaderResolver,886 creativeListResolver: creativeListResolver,887 creativePreviewResolver: creativePreviewResolver,888 creativeResolver: creativeResolver,889 dashboardHeaderResolver: dashboardHeaderResolver,890 dashboardHeaderResolver2: dashboardHeaderResolver2,891 fetchCurrentAdvertiser: fetchCurrentAdvertiser,892 fetchCurrentBrand: fetchCurrentBrand,893 invoiceHeader: invoiceHeader,894 mediaPlanCreateResolver: mediaPlanCreateResolver,895 mediaPlanOverviewResolver: mediaPlanOverviewResolver,896 mediaPlansHeaderResolver: mediaPlansHeaderResolver,897 mediaPlansHeaderResolver2: mediaPlansHeaderResolver2,898 reportsHeaderResolver: reportsHeaderResolver,899 reportsHeaderResolver2: reportsHeaderResolver2,900 reportsHeaderResolverWOCampaign: reportsHeaderResolverWOCampaign,901 reportsHeaderResolverWOCampaign2: reportsHeaderResolverWOCampaign2,902 scheduleReportListCreateResolver: scheduleReportListCreateResolver,903 uploadReportsHeaderResolver: uploadReportsHeaderResolver,904 uploadReportsHeaderResolver2: uploadReportsHeaderResolver2905 };906 }]);...

Full Screen

Full Screen

API Graph.js

Source:API Graph.js Github

copy

Full Screen

1//"use strict";2/* Constants */3var DATA_FILE_PATH = "API Graph Data.json";4var PATH_DELIMITER = "/";5var PACKAGE_DELIMITER = ".";6/* Global Variables */7var svg;8var color9var x_children;10var x_parent;11var y_children;12var y_parent;13var apiTree;14var directoryTree;15var apiViewActive;16var treemap;17/*18 * Initializes the visualization.19 */20function initialize() {21 parseDataFile(DATA_FILE_PATH, function(trees) {22 var width = window.innerWidth,23 height = window.innerHeight;24 25 26 x_children = d3.scale.linear().range([0, width]);27 y_children = d3.scale.linear().range([60, height]);28 x_parent = d3.scale.linear().range([0, width]);29 y_parent = d3.scale.linear().range([0, 60]);30 31 apiTree = trees.apiTree;32 directoryTree = trees.directoryTree;33 34 apiViewActive = true;35 36 displayTreemap();37 38 addViewByButtonClickListeners();39 });40}41function addViewByButtonClickListeners() {42 var width = window.innerWidth,43 height = window.innerHeight;44 d3.select("#viewByApiButton").on("click", function() {45 if (!apiViewActive) {46 apiViewActive = true;47 x_children = d3.scale.linear().range([0, width]);48 y_children = d3.scale.linear().range([60, height]);49 x_parent = d3.scale.linear().range([0, width]);50 y_parent = d3.scale.linear().range([0, 60]);51 52 displayTreemap();53 }54 });55 56 d3.select("#viewByFileButton").on("click", function() {57 if (apiViewActive) {58 apiViewActive = false;59 x_children = d3.scale.linear().range([0, width]);60 y_children = d3.scale.linear().range([60, height]);61 x_parent = d3.scale.linear().range([0, width]);62 y_parent = d3.scale.linear().range([0, 60]);63 64 displayTreemap();65 }66 })67}68function displayTreemap() {69 d3.select("#descriptiveText").text("");70 // update the "View by" selector71 d3.select("#viewByApiButton").classed("selected", function() {72 return apiViewActive; 73 });74 d3.select("#viewByFileButton").classed("selected", function() {75 return !apiViewActive; 76 });77 78 79 80 var width = window.innerWidth,81 height = window.innerHeight;82 83 svg = d3.select("#viewport") //TODO: don't make a global variable84 .attr("width", width)85 .attr("height", height);86 87 // TODO: ugly way to clear treemap; fix88 svg.text(" ");89 var cell;90 if (apiViewActive) {91 color = d3.scale.category20(); //TODO: fix92 treemap = d3.layout.treemap()93 .size([width, height])94 .children(function (d) {95 return d3.entries(d.value.contents); //TODO: clean up96 })97 .value(function (d) {98 return d.value.fileUsageCount || d.value.referencingFiles.length;99 }).sticky(true);100 cell = svg.data(d3.entries(apiTree)).selectAll("g")101 .data(treemap)102 .enter().append("g")103 .attr("class", function(d) {return d.depth == 0 ? "parent" : "child"})104 .attr("transform", function(d) {105 return "translate(" + x_children(d.x) + "," + y_children(d.y) + ")"; })106 .attr("visibility", function(d) {return d.depth == 0 ? "visible" : "hidden"})107 .on("click",onClick)108 ;109 110 cell.append("rect")111 .attr("width", function(d) { return d.dx; })112 .attr("height", function(d) { return d.dy; })113 .style("fill", function(d) {return color(d.data.value.fileUsageCount || d.data.value.referencingFiles.length);})114 ;115 116 cell.append("foreignObject")117.attr("width", function(d) { return d.dx; })118 .attr("height", function(d) { return d.dy; })119 .append("xhtml:div")120 .attr("class", "label")121 .style("font-size", function(d) {122 return d3.scale.linear().domain([0, window.innerHeight * window.innerWidth]).range([1, 3])(d.dx * d.dy) + "em";123 })124 .text(function(d) { return d.data.key + " (referenced by " +125 (d.data.value.fileUsageCount || d.data.value.referencingFiles.length) + " files)"; });126 } else { // show the File view127 color = d3.scale.category20c();128 treemap = d3.layout.treemap()129 .size([width, height])130 .children(function (d) {131 return d3.entries(d.value.contents); //TODO: clean up132 })133 .value(function (d) {134 if (d.value.type === "directory") {135 return d.value.apiUsageCount;136 } else {137 return d.value.apisUsed.length;138 }139 }).sticky(true);140 cell = svg.data(d3.entries(directoryTree)).selectAll("g")141 .data(treemap)142 .enter().append("g")143 .attr("class", function(d) {return d.depth == 0 ? "parent" : "child"})144 .attr("transform", function(d) { return "translate(" + x_children(d.x) + "," + y_children(d.y) + ")"; })145 .attr("visibility", function(d) {return d.depth == 0 ? "visible" : "hidden"})146 .on("click",onClick)147 ;148 149 cell.append("rect")150 .attr("width", function(d) { return d.dx; })151 .attr("height", function(d) { return d.dy; })152 .style("fill", function(d) {return color(d.data.value.apiUsageCount || d.data.value.apisUsed.length);})153;154 155 cell.append("foreignObject")156.attr("width", function(d) { return d.dx; })157 .attr("height", function(d) { return d.dy; })158 .append("xhtml:div")159 .attr("class", "label")160 .style("font-size", function(d) {161 return d3.scale.linear().domain([0, window.innerHeight * window.innerWidth]).range([1, 3])(d.dx * d.dy) + "em";162 })163 .text(function(d) { return d.data.key + " (uses " +164 (d.data.value.apiUsageCount || d.data.value.apisUsed.length) + " APIs)"; });165 } 166}167function onClick(d,i) {168 var path = [d.data.key];169var parent = d.parent;170 while (parent) {171 path.unshift(parent.data.key);172 parent = parent.parent;173 }174 d3.select("#descriptiveText")175 .text(path.join(" > "));176 if (d.children) {177 var clickClass = d3.select(this).attr("class");178 var datum = (clickClass == "parent" && d.depth != 0) ? d.parent : d;179 180 x_parent.domain([d.x, d.x + d.dx]);181 y_parent.domain([d.y, d.y + d.dy]);182 183 if(d.children && d.depth != 0)184 svg.selectAll("g")185 .attr("visibility","hidden")186 ;187 188 svg.selectAll("g")189 .filter(function(d) {190 return d == datum && d.children;191 })192 .attr("class","parent")193 .attr("visibility","visible")194 .transition().duration(750)195 .attr("transform", function(d) { return "translate(" + x_parent(d.x) + "," + y_parent(d.y) + ")"; })196 .select("rect")197 .attr("width", function(d) { return x_parent(d.dx+d.x) - x_parent(d.x); })198 .attr("height", function(d) { return y_parent(d.dy+d.y) - y_parent(d.y); })199 ;200 201 svg.selectAll("g")202 .filter(function(d) {203 return d == datum && d.children;204 })205 .select("foreignObject")206 .attr("width", function(d) { return x_parent(d.dx+d.x) - x_parent(d.x); })207 .attr("height", function(d) { return y_parent(d.dy+d.y) - y_parent(d.y); })208 ;209 x_children.domain([datum.x, datum.x + datum.dx]);210 y_children.domain([datum.y, datum.y + datum.dy]);211 212 svg.selectAll("g")213 .filter(function(d){214 return d.parent ? d.parent == datum : d.depth == 1;215 })216 .transition().duration(750)217 .attr("class","child")218 .attr("visibility","visible")219 .attr("transform", function(d) { return "translate(" + x_children(d.x) + "," + y_children(d.y) + ")"; })220 .select("rect")221 .attr("width", function(d) { return x_children(d.dx+d.x) - x_children(d.x); })222 .attr("height", function(d) { return y_children(d.dy+d.y)-y_children(d.y); })223 ;224 225 svg.selectAll("g")226 .filter(function(d) {227 return d.parent ? d.parent == datum : d.depth == 1;228 })229 .select("foreignObject")230 .attr("width", function(d) { return x_children(d.dx+d.x) - x_children(d.x); })231 .attr("height", function(d) { return y_children(d.dy+d.y)-y_children(d.y); })232 ;233 234 } else { // at child235 var treeNode = d.data.value;236 d3.select("#dialog").html(" ");237 238 d3.select("#dialog").append("h1")239 .text(d.data.key);240 241 d3.select("#dialog").append("h2")242 .text("Type: " + treeNode.type);243 if (apiViewActive) {244 d3.select("#dialog").append("h2")245 .text("Used by");246 247 var list = d3.select("#dialog").append("ul");248 249 treeNode.referencingFiles.forEach(function (file) {250 list.append("li").text(file.file.name + " (line " + file.lineUsingApi + ")");251 })252 } else {253 d3.select("#dialog").append("h2")254 .text("APIs Used");255 256 var list = d3.select("#dialog").append("ul");257 258 treeNode.apisUsed.forEach(function (api) {259 list.append("li").text(api.api.name + " (type: " + api.api.type) + ")";});260 }261 262 d3.select("#dialog").style("display", "block");263 264 d3.select("#dialog").append("a").attr("class", "closeLink").text("Close").on("click", function() {265 d3.select("#dialog").style("display", "none");266 })267 }268}269function getTextDimensions(text) {270 var testElement = document.createElement("span");271 testElement.className = "testElement";272 testElement.textContent = text;273 274 document.body.appendChild(testElement);275 276 var width = testElement.clientWidth;277 var height = testElement.clientHeight;278 279 document.body.removeChild(testElement);280 return {width: width, height: height};281}282function parseDataFile(dataFilePath, callbackFunction) {283 d3.json(dataFilePath, function(apiUsages) {284 var directoryTree = {};285 var apiTree = {};286 287 // need to create directory tree and API tree288 apiUsages.forEach(function (apiUsage) {289 // get the appropriate in directoryTree for the current filename290 // or create the appropriate node if it doesn't exist291 var fileNode = makeDirectoryTreeNodesFromPath(directoryTree,292 apiUsage.filename);293 var apiNode = makeApiTreeNodesFromName(apiTree, apiUsage.useby,294 apiUsage.usebykind);295 296 fileNode.apisUsed.push(new ApiUsage(apiNode, apiUsage.line));297 apiNode.referencingFiles.push(new FileUsage(fileNode, apiUsage.line));298 });299 300 setApiUsageCounts(directoryTree);301 setFileUsageCounts(apiTree);302 303 callbackFunction({304 "apiTree": apiTree,305 "directoryTree": directoryTree306 });307 });308}309function setApiUsageCounts(directoryTree) {310 for (var directory in directoryTree) {311 setApiUsageCountsHelper(directoryTree[directory]);312 }313}314function setApiUsageCountsHelper(directoryNode) {315 if (directoryNode.type == "file") {316 return directoryNode.apisUsed.length;317 }318 319 var count = 0;320 for (var childNode in directoryNode.contents) {321 count += setApiUsageCountsHelper(directoryNode.contents[childNode]);322 }323 directoryNode.apiUsageCount = count;324 return count;325}326function setFileUsageCounts(apiTree) {327 for (var apiName in apiTree) {328 setFileUsageCountsHelper(apiTree[apiName]);329 }330}331function setFileUsageCountsHelper(apiNode) {332 if (apiNode.isLeafNode) {333 return apiNode.referencingFiles.length;334 }335 336 var count = 0;337 for (var childNode in apiNode.contents) {338 count += setFileUsageCountsHelper(apiNode.contents[childNode]);339 }340 apiNode.fileUsageCount = count;341 return count;342}343function makeDirectoryTreeNodesFromPath(tree, path) {344 var pathPieces = path.split(PATH_DELIMITER);345 var pathPiecesLength = pathPieces.length;346 347 var fileNode;348 var currentRootNode = tree;349 350 for (var i = 0; i < pathPiecesLength; i += 1) {351 var pathPiece = pathPieces[i];352 if (pathPiece !== ".") { // ignore the "." folder353 var atLastPiece = (i === (pathPiecesLength - 1));354 355 var nodeType;356 var isLeafNode;357 if (atLastPiece) {358 nodeType = "file";359 isLeafNode = true;360 } else { // not at the last piece361 nodeType = "directory";362 isLeafNode = false;363 }364 365 if (!currentRootNode[pathPiece]) { // node doesn't exist; create one366 currentRootNode[pathPiece] = new DirectoryTreeNode(pathPiece, nodeType, isLeafNode);367 }368 369 if (atLastPiece) {370 fileNode = currentRootNode[pathPiece];371 } else { // not at last piece372 currentRootNode = currentRootNode[pathPiece].contents;373 }374 }375 }376 377 console.assert(fileNode !== undefined && fileNode !== null);378 return fileNode;379}380//TODO: code similar to makeDirectoryTreeNodesFromPath; factor out common code381function makeApiTreeNodesFromName(tree, name, nameType) {382 var namePieces = name.split("(")[0].split(PACKAGE_DELIMITER);383 var namePiecesLength = namePieces.length;384 385 var apiNode;386 var currentRootNode = tree;387 388 for (var i = 0; i < namePiecesLength; i += 1) {389 var namePiece = namePieces[i];390 var atSecondToLastPiece = (i === (namePiecesLength - 2));391 var atLastPiece = (i === (namePiecesLength - 1));392 393 var nodeType;394 var isLeafNode = false;395 if (atLastPiece) {396 nodeType = nameType;397 isLeafNode = true;398 } else if (atSecondToLastPiece && (nameType === "METHOD" || nameType === "CONSTRUCTOR" ||399 nameType === "FIELD")){400 nodeType = "CLASS";401 } else {402 nodeType = "PACKAGE"403 }404 405 if (!currentRootNode[namePiece]) { // node doesn't exist; create one406 currentRootNode[namePiece] = new ApiTreeNode(namePiece, nodeType, isLeafNode);407 }408 409 410 if (atLastPiece) {411 apiNode = currentRootNode[namePiece];412 } else { // not at last piece413 currentRootNode = currentRootNode[namePiece].contents;414 }415 }416 417 console.assert(apiNode !== undefined && apiNode !== null);418 return apiNode;419}420//TODO: make a Node class and have the two node types inherit from it421function DirectoryTreeNode(name, type, isLeafNode) {422 this.name = name;423 this.type = type;424 this.isLeafNode = isLeafNode;425 426 if (type === "directory") {427 this.apiUsageCount = 0;428 this.contents = {};429 } else {430 console.assert(type === "file");431 this.apisUsed = [];432 }433}434function ApiTreeNode(name, type, isLeafNode) {435 this.name = name;436 this.type = type;437 this.fileUsageCount = 0;438 this.isLeafNode = isLeafNode;439 440 this.referencingFiles = [];441 442 if (type === "PACKAGE" || type === "CLASS" || type === "INTERFACE") {443 this.contents = {};444 }445}446function FileUsage(file, lineUsingApi) {447 this.file = file;448 this.lineUsingApi = lineUsingApi;449}450function ApiUsage(api, lineUsingApi) {451 this.api = api;452 this.lineUsingApi = lineUsingApi;453}...

Full Screen

Full Screen

Main.js

Source:Main.js Github

copy

Full Screen

1/*2 * SPARTA Visualization Tool3 * By Chris Rovillos4 */5"use strict";6/* Constants */7var DATA_FILE_PATH = "Output.json";8var PATH_DELIMITER = "/";9var PACKAGE_DELIMITER = ".";10/* Global Variables */11var svg;12var color13var x_children;14var x_parent;15var y_children;16var y_parent;17var apiTree;18var directoryTree;19var apiViewActive;20var treemap;21/*22 * Initializes the visualization.23 */24function initialize() {25 parseDataFile(DATA_FILE_PATH, function(trees) {26 var width = window.innerWidth,27 height = window.innerHeight;28 29 color = d3.scale.category20c();30 31 x_children = d3.scale.linear().range([0, width]);32 y_children = d3.scale.linear().range([30, height]);33 x_parent = d3.scale.linear().range([0, width]);34 y_parent = d3.scale.linear().range([0, 30]);35 36 apiTree = trees.apiTree;37 directoryTree = trees.directoryTree;38 39 apiViewActive = true;40 41 displayTreemap();42 43 addViewByButtonClickListeners();44 });45}46function addViewByButtonClickListeners() {47 d3.select("#viewByApiButton").on("click", function() {48 if (!apiViewActive) {49 apiViewActive = true;50 displayTreemap();51 }52 });53 54 d3.select("#viewByFileButton").on("click", function() {55 if (apiViewActive) {56 apiViewActive = false;57 displayTreemap();58 }59 })60}61function displayTreemap() {62 // update the "View by" selector63 d3.select("#viewByApiButton").classed("selected", function() {64 return apiViewActive; 65 });66 d3.select("#viewByFileButton").classed("selected", function() {67 return !apiViewActive; 68 });69 70 var width = window.innerWidth,71 height = window.innerHeight;72 73 svg = d3.select("#viewport") //TODO: don't make a global variable74 .attr("width", width)75 .attr("height", height);76 77 // TODO: ugly way to clear treemap; fix78 svg.text("blabla");79 var cell;80 if (apiViewActive) {81 treemap = d3.layout.treemap()82 .size([width, height])83 .children(function (d) {84 return d3.entries(d.value.contents); //TODO: clean up85 })86 .value(function (d) {87 return d.value.fileUsageCount;88 }).sticky(true);89 cell = svg.data(d3.entries(apiTree)).selectAll("g")90 .data(treemap)91 .enter().append("g")92 .attr("class", function(d) {return d.depth == 0 ? "parent" : "child"})93 .attr("transform", function(d) {94 return "translate(" + x_children(d.x) + "," + y_children(d.y) + ")"; })95 .attr("visibility", function(d) {return d.depth == 0 ? "visible" : "hidden"})96 .on("click",onClick)97 ;98 99 cell.append("rect")100 .attr("width", function(d) { return d.dx; })101 .attr("height", function(d) { return d.dy; })102 .style("fill", function(d) {return color(d.data.value.fileUsageCount || d.data.value.referencingFiles.length);})103 ;104 105 cell.append("text")106 .attr("dx", "0.5em")107 .attr("dy", "1.5em")108 .text(function(d) { return d.data.key; });109 } else { // show the File view110 treemap = d3.layout.treemap()111 .size([width, height])112 .children(function (d) {113 return d3.entries(d.value.contents); //TODO: clean up114 })115 .value(function (d) {116 if (d.value.type === "directory") {117 return d.value.apiUsageCount;118 } else {119 return d.value.apisUsed.length;120 }121 }).sticky(true);122 cell = svg.data(d3.entries(directoryTree)).selectAll("g")123 .data(treemap)124 .enter().append("g")125 .attr("class", function(d) {return d.depth == 0 ? "parent" : "child"})126 .attr("transform", function(d) { return "translate(" + x_children(d.x) + "," + y_children(d.y) + ")"; })127 .attr("visibility", function(d) {return d.depth == 0 ? "visible" : "hidden"})128 .on("click",onClick)129 ;130 131 cell.append("rect")132 .attr("width", function(d) { return d.dx; })133 .attr("height", function(d) { return d.dy; })134 .style("fill", function(d) {return color(d.data.value.apiUsageCount || d.data.value.apisUsed.length);})135 ;136 137 cell.append("text")138 .attr("dx", "0.5em")139 .attr("dy", "1.5em")140 .text(function(d) { return d.data.key; });141 } 142}143function onClick(d,i) {144 var clickClass = d3.select(this).attr("class");145 var datum = (clickClass == "parent" && d.depth != 0) ? d.parent : d;146 147 x_parent.domain([d.x, d.x + d.dx]);148 y_parent.domain([d.y, d.y + d.dy]);149 150 if(d.children && d.depth != 0)151 svg.selectAll("g")152 .attr("visibility","hidden")153 ;154 155 svg.selectAll("g")156 .filter(function(d) {157 return d == datum && d.children;158 })159 .attr("class","parent")160 .attr("visibility","visible")161 .transition().duration(750)162 .attr("transform", function(d) { return "translate(" + x_parent(d.x) + "," + y_parent(d.y) + ")"; })163 .select("rect")164 .attr("width", function(d) { return x_parent(d.dx+d.x) - x_parent(d.x); })165 .attr("height", function(d) { return y_parent(d.dy+d.y) - y_parent(d.y); })166 ;167 x_children.domain([datum.x, datum.x + datum.dx]);168 y_children.domain([datum.y, datum.y + datum.dy]);169 170 svg.selectAll("g")171 .filter(function(d){172 return d.parent ? d.parent == datum : d.depth == 1;173 })174 .transition().duration(750)175 .attr("class","child")176 .attr("visibility","visible")177 .attr("transform", function(d) { return "translate(" + x_children(d.x) + "," + y_children(d.y) + ")"; })178 .select("rect")179 .attr("width", function(d) { return x_children(d.dx+d.x) - x_children(d.x); })180 .attr("height", function(d) { return y_children(d.dy+d.y)-y_children(d.y); })181 ;182}183function getTextDimensions(text) {184 var testElement = document.createElement("span");185 testElement.className = "testElement";186 testElement.textContent = text;187 188 document.body.appendChild(testElement);189 190 var width = testElement.clientWidth;191 var height = testElement.clientHeight;192 193 document.body.removeChild(testElement);194 return {width: width, height: height};195}196function parseDataFile(dataFilePath, callbackFunction) {197 d3.json(dataFilePath, function(apiUsages) {198 var directoryTree = {};199 var apiTree = {};200 201 // need to create directory tree and API tree202 apiUsages.forEach(function (apiUsage) {203 // get the appropriate in directoryTree for the current filename204 // or create the appropriate node if it doesn't exist205 var fileNode = makeDirectoryTreeNodesFromPath(directoryTree,206 apiUsage.filename);207 var apiNode = makeApiTreeNodesFromName(apiTree, apiUsage.useby,208 apiUsage.usebykind);209 210 fileNode.apisUsed.push(new ApiUsage(apiNode, apiUsage.line));211 apiNode.referencingFiles.push(new FileUsage(fileNode, apiUsage.line));212 });213 214 setApiUsageCounts(directoryTree);215 setFileUsageCounts(apiTree);216 217 callbackFunction({218 "apiTree": apiTree,219 "directoryTree": directoryTree220 });221 });222}223function setApiUsageCounts(directoryTree) {224 for (var directory in directoryTree) {225 setApiUsageCountsHelper(directoryTree[directory]);226 }227}228function setApiUsageCountsHelper(directoryNode) {229 if (directoryNode.type == "file") {230 return directoryNode.apisUsed.length;231 }232 233 var count = 0;234 for (var childNode in directoryNode.contents) {235 count += setApiUsageCountsHelper(directoryNode.contents[childNode]);236 }237 directoryNode.apiUsageCount = count;238 return count;239}240function setFileUsageCounts(apiTree) {241 for (var apiName in apiTree) {242 setFileUsageCountsHelper(apiTree[apiName]);243 }244}245function setFileUsageCountsHelper(apiNode) {246 if (apiNode.isLeafNode) {247 return apiNode.referencingFiles.length;248 }249 250 var count = 0;251 for (var childNode in apiNode.contents) {252 count += setFileUsageCountsHelper(apiNode.contents[childNode]);253 }254 apiNode.fileUsageCount = count;255 return count;256}257function makeDirectoryTreeNodesFromPath(tree, path) {258 var pathPieces = path.split(PATH_DELIMITER);259 var pathPiecesLength = pathPieces.length;260 261 var fileNode;262 var currentRootNode = tree;263 264 for (var i = 0; i < pathPiecesLength; i += 1) {265 var pathPiece = pathPieces[i];266 if (pathPiece !== ".") { // ignore the "." folder267 var atLastPiece = (i === (pathPiecesLength - 1));268 269 var nodeType;270 var isLeafNode;271 if (atLastPiece) {272 nodeType = "file";273 isLeafNode = true;274 } else { // not at the last piece275 nodeType = "directory";276 isLeafNode = false;277 }278 279 if (!currentRootNode[pathPiece]) { // node doesn't exist; create one280 currentRootNode[pathPiece] = new DirectoryTreeNode(pathPiece, nodeType, isLeafNode);281 }282 283 if (atLastPiece) {284 fileNode = currentRootNode[pathPiece];285 } else { // not at last piece286 currentRootNode = currentRootNode[pathPiece].contents;287 }288 }289 }290 291 console.assert(fileNode !== undefined && fileNode !== null);292 return fileNode;293}294//TODO: code similar to makeDirectoryTreeNodesFromPath; factor out common code295function makeApiTreeNodesFromName(tree, name, nameType) {296 var namePieces = name.split("(")[0].split(PACKAGE_DELIMITER);297 var namePiecesLength = namePieces.length;298 299 var apiNode;300 var currentRootNode = tree;301 302 for (var i = 0; i < namePiecesLength; i += 1) {303 var namePiece = namePieces[i];304 var atSecondToLastPiece = (i === (namePiecesLength - 2));305 var atLastPiece = (i === (namePiecesLength - 1));306 307 var nodeType;308 var isLeafNode = false;309 if (atLastPiece) {310 nodeType = nameType;311 isLeafNode = true;312 } else if (atSecondToLastPiece && (nameType === "METHOD" || nameType === "CONSTRUCTOR" ||313 nameType === "FIELD")){314 nodeType = "CLASS";315 } else {316 nodeType = "PACKAGE"317 }318 319 if (!currentRootNode[namePiece]) { // node doesn't exist; create one320 currentRootNode[namePiece] = new ApiTreeNode(namePiece, nodeType, isLeafNode);321 }322 323 324 if (atLastPiece) {325 apiNode = currentRootNode[namePiece];326 } else { // not at last piece327 currentRootNode = currentRootNode[namePiece].contents;328 }329 }330 331 console.assert(apiNode !== undefined && apiNode !== null);332 return apiNode;333}334//TODO: make a Node class and have the two node types inherit from it335function DirectoryTreeNode(name, type, isLeafNode) {336 this.name = name;337 this.type = type;338 this.isLeafNode = isLeafNode;339 340 if (type === "directory") {341 this.apiUsageCount = 0;342 this.contents = {};343 } else {344 console.assert(type === "file");345 this.apisUsed = [];346 }347}348function ApiTreeNode(name, type, isLeafNode) {349 this.name = name;350 this.type = type;351 this.fileUsageCount = 0;352 this.isLeafNode = isLeafNode;353 354 this.referencingFiles = [];355 356 if (type === "PACKAGE" || type === "CLASS" || type === "INTERFACE") {357 this.contents = {};358 }359}360function FileUsage(file, lineUsingApi) {361 this.file = file;362 this.lineUsingApi = lineUsingApi;363}364function ApiUsage(api, lineUsingApi) {365 this.api = api;366 this.lineUsingApi = lineUsingApi;367}...

Full Screen

Full Screen

pagertree.js

Source:pagertree.js Github

copy

Full Screen

...36 },37 _createTreeCell: function (e) {38 var sb = [];39 var node = e.record;40 var isLeaf = this.isLeafNode(node);41 var level = this.getNodeLevel(node);42 var isExpand = this.isExpandedNode(node);43 var cls = e.nodeCls;44 if (!isLeaf) {45 cls = isExpand ? this._expandNodeCls : this._collapseNodeCls;46 }47 if (!isLeaf) {48 cls += " mini-tree-parentNode";49 }50 sb[sb.length] = '<div class="mini-tree-nodetitle ' + cls + '" style="' + e.nodeStyle + '">';51 //_level52 var ii = 0;53 for (var i = ii; i < level - 1; i++) {54 sb[sb.length] = '<span class="mini-tree-indent " ></span>';55 }56 if (!isLeaf) {57 sb[sb.length] = '<a class="' + this._eciconCls + '" href="javascript:void(0);" onclick="return false;" hidefocus></a>';58 } else {59 sb[sb.length] = '<span class="' + this._eciconCls + '" ></span>';60 }61 sb[sb.length] = '<span class="mini-tree-nodeshow">';62 if (e.showTreeIcon) {63 if (e.img) {64 var img = this.imgPath + e.img;65 sb[sb.length] = '<span class="mini-tree-icon" style="background-image:url(' + img + ');"></span>';66 } else {67 sb[sb.length] = '<span class="' + e.iconCls + ' mini-tree-icon"></span>';68 }69 }70 sb[sb.length] = '<span class="mini-tree-nodetext">';71 sb[sb.length] = e.cellHtml;72 sb[sb.length] = '</span>';73 sb[sb.length] = '</span>';74 sb[sb.length] = '</div>';75 e.cellHtml = sb.join('');76 },77 /////////////////////////////////////////////////////////////////////////78 __OnBeforeLoad: function (e) {79 var config = { collapseNodes: this._collapseNodes }; 80 e.data.__ecconfig = mini.encode(config);81 },82 load: function () {83 this._collapseNodes = [];84 return mini.PagerTree.superclass.load.apply(this, arguments);85 },86 expandNode: function (node) {87 node = this._dataSource.getbyId(node)88 if (node && !this.isLeafNode(node)) {89 var id = node[this.getIdField()];90 if (id) {91 this._collapseNodes.remove(id);92 }93 }94 this.reload();95 },96 collapseNode: function (node) {97 node = this._dataSource.getbyId(node) 98 if (node && !this.isLeafNode(node)) {99 var id = node[this.getIdField()];100 if (id) {101 this._collapseNodes.remove(id);102 this._collapseNodes.add(id);103 }104 }105 this.reload();106 },107 toggleNode: function (node) {108 node = this._dataSource.getbyId(node)109 if (!node) {110 this.reload();111 } else {112 if (this.isExpandedNode(node)) {113 this.collapseNode(node);114 } else {115 this.expandNode(node);116 }117 }118 },119 /////////////////////////////////////////////////////////////////////////120 isExpandedNode: function (node) {121 return node.expanded !== false;122 },123 isLeafNode: function (node) {124 return node.isLeaf;125 },126 getNodeLevel: function (node) {127 return node._level;128 },129 _getNodeIcon: function (node) {130 var icon = node[this.iconField];131 if (!icon) {132 if (this.isLeafNode(node)) icon = this.leafIconCls;133 else icon = this.folderIconCls;134 }135 return icon;136 },137 getAttrs: function (el) {138 var attrs = mini.PagerTree.superclass.getAttrs.call(this, el);139 mini._ParseString(el, attrs,140 ["treeColumn", "iconField", "imgField", "imgPath", "idField"141 ]142 );143 mini._ParseBool(el, attrs,144 ["showTreeIcon"145 ]146 );147 return attrs;148 }149});150mini.regClass(mini.PagerTree, "pagertree");151//分页树折叠插件152mini._PagerTree_Expander = function (grid) {153 this.owner = grid;154 mini.on(grid.el, "click", this.__OnClick, this);155}156mini._PagerTree_Expander.prototype = {157 __OnClick: function (e) {158 var tree = this.owner;159 var node = tree.getRecordByEvent(e, false);160 if (!node) return;161 var isLeaf = tree.isLeafNode(node);162 if (mini.findParent(e.target, tree._eciconCls)) {163 if (tree.isLeafNode(node)) return;164 tree.toggleNode(node);165 }166 }...

Full Screen

Full Screen

main5.js

Source:main5.js Github

copy

Full Screen

1class NavigationMenu extends React.Component {2 constructor(props) {3 super(props);4 }5 render() {6 return (7 <div className = "navigation-menu">8 <NavigationButton 9 id = "home-button"10 type = "icon" 11 src = "resources/Images/Site/icon_home.png"12 value = "Home Button"13 path = {[]}14 clickHandler = {this.props.navigator} />15 {this.props.nodeName != "__HOME__" && 16 <NavigationButton 17 type = "topbutton"18 value = {this.props.nodeName}19 path = {20 this.props.isLeafNode ?21 this.props.path.slice(22 0, this.props.path.length - 123 )24 :25 this.props.path.slice()26 }27 isSelected = {!this.props.isLeafNode}28 clickHandler = {this.props.navigator} />29 }30 {this.props.contentList.map(31 (content, index) => (32 <NavigationButton33 value = {content}34 type = "subbutton"35 path = {36 this.props.isLeafNode?37 [38 ...this.props.path.slice(39 0, this.props.path.length - 140 ), 41 index,42 ]43 :44 [...this.props.path, index]45 }46 isSelected = {47 this.props.isLeafNode48 &&49 index == this.props.path[50 this.props.path.length - 151 ]52 }53 clickHandler = {this.props.navigator} />54 )55 )}56 {this.props.nodeName != "__HOME__" &&57 <NavigationButton 58 id = "back-button"59 type = "icon"60 value = "Back Button"61 src = "resources/Images/Site/icon_back.png"62 path = {63 this.props.isLeafNode ?64 this.props.path.slice(65 0, this.props.path.length - 2,66 )67 :68 this.props.path.slice(69 0, this.props.path.length - 1,70 )71 }72 clickHandler = {this.props.navigator} />73 }74 </div>75 );76 }77}78class NavigationButton extends React.Component {79 constructor(props) {80 super(props);81 this.clickHandler = this.clickHandler.bind(this);82 }83 clickHandler() {84 this.props.clickHandler(85 this.props.path86 );87 }88 render() {89 switch (this.props.type) {90 case "icon":91 return (92 <img93 id = {this.props.id}94 src = {this.props.src}95 alt = {this.props.value} 96 onClick = {this.clickHandler} />97 );98 case "topbutton":99 return (100 <h3101 className = {102 "navigation-button top " + (103 this.props.isSelected ? 104 "selected" : "unselected"105 )106 }107 onClick = {this.clickHandler}>108 {this.props.value.toUpperCase()}:109 </h3>110 );111 case "subbutton":112 return (113 <h3114 className = {115 "navigation-button item " + (116 this.props.isSelected ? 117 " selected" : " unselected"118 )119 }120 onClick = {this.clickHandler}>121 <span>122 {"\u00bb "}123 </span>124 {this.props.value}125 </h3>126 );127 default:128 return null;129 }130 }...

Full Screen

Full Screen

function.js

Source:function.js Github

copy

Full Screen

1/*2 * @Author: Zz3 * @Date: 2017-04-19 16:12:044 * @Last Modified by: Zz5 * @Last Modified time: 2017-05-17 13:43:256 */7import { appStore } from '../stores';8export default {9 columnPageDataConvertDB (pageData, epgs, language) {10 const itemObj = JSON.parse(JSON.stringify(pageData));11 const tmp = {12 type: itemObj.type,13 action: itemObj.action,14 isLeafNode: itemObj.isLeafNode,15 // name: itemObj.name,16 description: itemObj.description,17 language: [],18 style: [],19 // userId: appStore.payload.id,20 // userName: appStore.payload.name,21 };22 for (const item in itemObj) {23 const opt = itemObj[item];24 let isBreak = false;25 // 语言配置26 for(const languageItem of language) {27 if (item === languageItem.code) {28 if (opt.name) {29 tmp.language.push(opt);30 }31 isBreak = true;32 break;33 }34 }35 if (isBreak) {36 continue;37 }38 for (const epgItem of epgs) {39 if (item === epgItem) {40 const epgTmp = {41 styleName: opt.styleName,42 content: [],43 };44 for (const lanIt in opt) {45 for(const languageItem of language) {46 if (lanIt === languageItem.code) {47 if (!opt[lanIt].icon.url && !opt[lanIt].highlightIcon.url && opt[lanIt].pics.length === 0) {48 break;49 }50 if (!opt[lanIt].icon.url || !opt[lanIt].highlightIcon.url) {51 return null;52 }53 54 const pics = [{55 type: 13,56 ...opt[lanIt].icon,57 }];58 pics.push({59 type: 14,60 ...opt[lanIt].highlightIcon,61 });62 63 const tmpP = opt[lanIt].pics.map(item => {64 return {65 type: 15,66 ...item,67 }68 });69 opt[lanIt].pics = pics.concat(tmpP);70 delete opt[lanIt].icon;71 delete opt[lanIt].highlightIcon;72 epgTmp.content.push(opt[lanIt]);73 break;74 }75 }76 }77 if (epgTmp.content.length !== 0)78 tmp.style.push(epgTmp);79 }80 }81 }82 return tmp;83 },84 columnDB2PageData (db, epgs, language) {85 const data = db;86 const itemObj = {};87 itemObj.action = data.action;88 itemObj.name = data.name;89 itemObj.isLeafNode = data.isLeafNode;90 itemObj.description = data.description;91 // 栏目名称92 for (const item of data.language) {93 itemObj[item.languageType] = item;94 }95 // epg 配置96 for (const item of data.style) {97 itemObj.epgChecked.push(item.styleName);98 const tmp = {99 styleName: item.styleName,100 langChecked: [],101 }102 for (const it of item.content) {103 const iconData = {104 languageType: it.languageType,105 highlightIcon: it.highlightIcon,106 icon: it.icon,107 pics: it.pics,108 };109 tmp[it.languageType] = iconData;110 for (const lan of language) {111 if (lan.code === it.languageType) {112 tmp.langChecked.push(lan.name);113 tmp[lan.name] = iconData;114 break;115 }116 }117 if (tmp.langChecked.length !== 0) {118 tmp.langTabValue = tmp.langChecked[0];119 tmp.langTabs = tmp.langChecked.map(item => {120 return {121 title: `${item}`,122 name: item,123 };124 });125 }126 }127 itemObj[item.styleName] = tmp;128 }129 return itemObj;130 }...

Full Screen

Full Screen

utils.js

Source:utils.js Github

copy

Full Screen

...20 return Array.prototype.concat.apply([], arr);21}2223export function treeTraverse(path = '', tree, isLeafNode, errorMessage, callback) {24 if (isLeafNode(path, tree)) {25 callback(path, tree);26 } else if (tree === undefined || tree === null) {27 // Do nothing28 } else if (Array.isArray(tree)) {29 tree.forEach((subTree, index) =>30 treeTraverse(`${path}[${index}]`, subTree, isLeafNode, errorMessage, callback),31 );32 } else {33 // It's object and not a leaf node34 if (typeof tree !== 'object') {35 warning(false, errorMessage);36 return;37 }38 Object.keys(tree).forEach(subTreeKey => { ...

Full Screen

Full Screen

TreeNav.js

Source:TreeNav.js Github

copy

Full Screen

1import React from 'react';2export default class TreeNav extends React.Component {3 componentDidMount() {4 if (this.isActiveNode()) {5 this.el.focus();6 }7 }8 isActiveNode() {9 const { isLeafNode, isOnActivePath } = this.props;10 return isLeafNode && isOnActivePath;11 }12 getButtonStyle() {13 return {14 backgroundColor: 'transparent',15 border: 'none',16 padding: '0px',17 color: '#fff',18 font: '16px Arial'19 };20 }21 getAnchorStyle() {22 return {23 color: '#fff'24 };25 }26 render() {27 const { depth, index, isLeafNode, label } = this.props;28 const tabIndex = (depth + 1) * 100 + index;29 const button = <button {...{tabIndex, style: this.getButtonStyle()}}>{label}</button>;30 const anchor = (31 <a {...{32 tabIndex, 33 href: 'http://example.com', 34 ref: (el) => this.el = el,35 style: this.getAnchorStyle()36 }}>{label}</a>37 );38 return isLeafNode ? anchor : button;39 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.screenshot({path: 'example.png'});6 await browser.close();7})();8const puppeteer = require('puppeteer');9(async () => {10 const browser = await puppeteer.launch();11 const page = await browser.newPage();12 await page.screenshot({path: 'example.png'});13 await browser.close();14})();15Your name to display (optional):16Your name to display (optional):17const puppeteer = require('puppeteer');18(async () => {19 const browser = await puppeteer.launch();20 const page = await browser.newPage();21 await page.screenshot({path: 'example.png'});22 const isLeafNode = await page.evaluate(() => {23 const element = document.querySelector('body');24 return element.childNodes.length === 0;25 });26 console.log(isLeafNode);27 await browser.close();28})();29Your name to display (optional):

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.waitForSelector('input[name="q"]');6 await page.type('input[name="q"]', 'puppeteer');7 await page.waitFor(1000);8 await page.keyboard.press('Enter');9 await page.waitForSelector('h3');10 const isLeafNode = await page.$eval('h3', el => el.leafNode);11 console.log(isLeafNode);12 await browser.close();13})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { PuppeteerCrawler } = require('apify');2const { isLeafNode } = require('apify');3const crawler = new PuppeteerCrawler({4 handlePageFunction: async ({ request, page }) => {5 const isLeaf = await isLeafNode(page);6 console.log(`Page ${request.url} is leaf: ${isLeaf}`);7 },8});9await crawler.run();10const { isLeafNode } = require('apify');11const isLeaf = await isLeafNode(page);12console.log(`Page ${request.url} is leaf: ${isLeaf}`);13- [apify-js](

Full Screen

Using AI Code Generation

copy

Full Screen

1const { PuppeteerCrawler } = require("apify");2const { PuppeteerHandlePageInputs } = require("apify/types/crawlers/puppeteer_crawler");3const crawler = new PuppeteerCrawler({4 requestList: new RequestList({5 }),6 handlePageFunction: async ({ page, request }) => {7 if (page.isLeafNode()) return;8 },9});10await crawler.run();11const { CheerioCrawler } = require("apify");12const { CheerioHandlePageInputs } = require("apify/types/crawlers/cheerio_crawler");13const crawler = new CheerioCrawler({14 requestList: new RequestList({15 }),16 handlePageFunction: async ({ $, request }) => {17 if ($.isLeafNode()) return;18 },19});20await crawler.run();21const { BasicCrawler } = require("apify");22const { BasicCrawlerInputs } = require("apify/types/crawlers/basic_crawler");23const crawler = new BasicCrawler({24 requestList: new RequestList({25 }),26 handleRequestFunction: async ({ request }) => {27 if (request.isLeafNode()) return;28 },29});30await crawler.run();31const { AutoscaledPool } = require("apify");

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const { Puppeteer } = require('puppeteer');3(async () => {4 const browser = await puppeteer.launch({headless: false});5 const page = await browser.newPage();6 let isLeafNode = await Puppeteer.isLeafNode(page, 'input[name="q"]');7 console.log(isLeafNode);8 await browser.close();9})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { PuppeteerCrawler } = require("apify");2const { isLeafNode } = require("apify");3const requestQueue = await Apify.openRequestQueue();4const crawler = new PuppeteerCrawler({5 handlePageFunction: async ({ request, page }) => {6 console.log(`Processing ${request.url}...`);7 const isLeaf = await isLeafNode(page);8 console.log(`Is leaf node: ${isLeaf}`);9 },10 handleFailedRequestFunction: async ({ request }) => {11 console.log(`Request ${request.url} failed too many times`);12 },13});14await crawler.run();15await Apify.utils.puppeteer.injectJQuery(page);16const isLeaf = await page.evaluate(() => {17 const $ = window.$;18 const $html = $("html");19 const $body = $("body");20 const $head = $("head");21 if ($html.length !== 1 || $body.length !== 1 || $head.length !== 1) {22 return false;23 }24 if ($html.children().length !== 2) {25 return false;26 }27 if ($body.children().length !== 1) {28 return false;29 }30 if ($head.children().length !== 1) {31 return false;32 }33 return true;34});35console.log(`Is leaf node: ${isLeaf}`);36const { PuppeteerPool } = require("apify");37const { isLeafNode } = require("apify");38const pool = new PuppeteerPool({39});40const browser = await pool.borrowBrowser();41const page = await browser.newPage();42await Apify.utils.puppeteer.injectJQuery(page);43const isLeaf = await page.evaluate(() => {44 const $ = window.$;45 const $html = $("html");46 const $body = $("body");47 const $head = $("head");48 if ($html.length !== 1 || $body.length !== 1 || $head.length !== 1) {49 return false;50 }51 if ($html.children().length !== 2) {52 return false;53 }

Full Screen

Using AI Code Generation

copy

Full Screen

1const { PuppeteerCrawler } = require('apify');2const crawler = new PuppeteerCrawler({3 handlePageFunction: async ({ request, page }) => {4 const isLeaf = await crawler.isLeafNode(request, page);5 console.log(`The page ${request.url} is ${isLeaf ? '' : 'not'} a leaf node.`);6 },7});8await crawler.run();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.goto(url);6 const frame = page.frames().find(f => f.name() === 'iframeResult');7 const elementHandle = await frame.$('body');8 const result = await frame.evaluate(element => element.isLeafNode, elementHandle);9 console.log(result);10 await browser.close();11})();

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

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