User:Mikevoir/WantedCategories.js

(function{	// Double load protection	if (document.querySelector('a#tu-uf')) {return;}	// Dependencies	var api;	var RUNNING = 0;	var list = document.createElement('ul');	var checked = [];	importArticle({ type: 'script', article: 'u:dev:MediaWiki:Placement.js' });	// Mapn object	var wantedCategories = {		init: function {			api = new mw.Api;			mw.hook('dev.placement').add(function(placement) { placement.script('WantedCategories'); $(placement.element('tools'))[placement.type('prepend')](   			    $('').append($('').attr({ href: '#', id: 't-uf' }).text('Wanted Categories').click(wantedCategories.loadUI))    			); });		},		loadUI: function {			document.querySelector('div#content.page-content').insertBefore(list, document.querySelector('div#mw-content-text.mw-body-content'));			wantedCategories.getCategories;		},		getCategories: function(continueFrom){			if ((!continueFrom||'string' !== typeof continueFrom) && RUNNING>0) {return;}			RUNNING++;			console.log('start running loop #' +RUNNING+' from ', (continueFrom||'__START__'));			var nextContinue;			var params = {				action: 'query',				list: 'allpages',				aplimit: 'max',				apfilterredir: 'all'			};			if (continueFrom && 'string' == typeof continueFrom) {params.apcontinue = continueFrom;}			api.get(params)			.then(function(data){ console.log('then', data); wantedCategories.parseCategories(data); if (data.continue && data.continue.apcontinue) {wantedCategories.getCategories(data.continue.apcontinue);} });		},		parseCategories: function(data) {			if (data.error || !data.query || !data.query.allpages || data.query.allpages.length == 0) {				console.log('early stop:', data);				document.querySelector('div#content.page-content').insertBefore(document.createTextNode('Done loading'), list);				return;			}			console.log('all pages:', data.query.allpages);			data.query.allpages.forEach(function(page){ if (page.categories){ api.get({action:'query', titles: page.categories}).then(function(page_data){						console.log(page_data);						if (!page_data || !page_data.query || !page_data.query.pages || page_data.query.pages['-1']) {							var i = -1;							while (page_data.query.pages[i]) {								if (checked.indexOf(page_data.query.pages[i].title) == -1) {									var link = document.createElement('a');									link.href = '/wiki/' + page_data.query.pages[i].title;									link.innerHTML = page_data.query.pages[i].title;									var bullet = document.createElement('li');									bullet.append(link);									list.append(bullet);								}								checked.push(page_data.query.pages[i].title);								i--;							}						} else {checked.concat(page.categories);}					}); }			});		}	};	mw.loader.using('mediawiki.api').then(wantedCategories.init); });