User:Isaac (WMF)/link to qid.js

// Code largely borrowed from: https://en.wikipedia.org/wiki/User:TayIorRobinson/wikigender.js

(async => {	// https://en.wikipedia.org/w/api.php?action=query&generator=links&gplnamespace=0&gpllimit=10&prop=pageprops&format=json&formatversion=2&redirects&ppprop=wikibase_item&titles=Modern_art   const QUERY_PARAMS = "action=query&generator=links&gplnamespace=0&gpllimit=50&prop=pageprops&format=json&formatversion=2&redirects&ppprop=wikibase_item&titles=";    /**     * Requests the clickstream data for the current page.     * @param {String} lang Wikipedia language to query.     * @returns {Promise} The latest clickstream data for the page.     */    async function fetchData {        let titleToQID = {};    	let lang = mw.config.get("wgDBname").replace("wiki","");        let title = mw.config.get("wgPageName");        let queryContinue = "";        while (true) {        	if (queryContinue.length > 0) {        		queryContinue = "&gplcontinue=" + queryContinue;        	} let response = await fetch("https://" + lang + ".wikipedia.org/w/api.php?" + QUERY_PARAMS + title + queryContinue); let data = await response.json; let batch = await processResults(data); titleToQID = Object.assign({}, titleToQID, batch); if (!('continue' in data)) { break; } else { queryContinue = data.continue.gplcontinue; }       }        return titleToQID; }   async function processResults(data) { let redirects = {}; let titleToQID = {}; if ('redirects' in data.query) { for (let rd of data.query.redirects) { redirects[rd.to.toLowerCase.replace(/_/g, " ")] = rd.from.toLowerCase.replace(/_/g, " "); }       }        for (let p of data.query.pages) { let pt = p.title.toLowerCase.replace(/_/g, " "); if ("pageprops" in p) { titleToQID[pt] = p.pageprops.wikibase_item; if (pt in redirects) { titleToQID[redirects[pt]] = p.pageprops.wikibase_item; }       	}        }        return titleToQID; }

/**    * Applies colour to links on the page * @param {ClickstreamLink[]} links The links to colour. * .toLowerCase.replace(/_/g, " ") */   function rewriteLinks(titleToQID) { let pageLinks = document.querySelector("#bodyContent").querySelectorAll("a[href^=\"/wiki/\"]"); // Update link text for (let link of pageLinks) { if ('title' in link) { let linkText = decodeURIComponent(link.title.toLowerCase.replace(/_/g, " ")); // Build array of all instances of a link appearing on page if (!(linkText in titleToQID)) { // link.text = '-'.repeat(link.text.length); continue; } else { link.text = titleToQID[linkText]; }       	}        }    }

// run script let titleToQID = await fetchData; rewriteLinks(titleToQID); });