Jump to content

User:Zackmann08/scripts/sandboxlinks.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// Adds [sandbox] and [testcases] to the documentation links
// Clicking on [sandbox] and [testcases] will view those respective pages

async function pageExistsForSandbox(title) {
    const api = new mw.Api();
    const response = await api.get({
        action: 'query',
        titles: title,
        format: 'json'
    });

    // Check if the 'missing' property is present in the page object
    const pages = response.query.pages;
    const pageId = Object.keys(pages)[0];
    return !pages[pageId].hasOwnProperty('missing');
}

// TODO: turn links red if the relevant page does not exist
jQuery(document).ready(function($) {
	if((mw.config.get('wgNamespaceNumber') == 10 || mw.config.get('wgNamespaceNumber') == 828) && document.getElementsByClassName('mw-editsection-like plainlinks')) {
		var sandboxExists, testcasesExists;
		var pagename = mw.config.get('wgPageName');
		(async () => {
			sandboxExists = await pageExistsForSandbox(pagename+'/sandbox');
			testcasesExists = await pageExistsForSandbox(pagename.replace(/\/sandbox/g, '')+'/testcases');
			var links = document.getElementsByClassName('mw-editsection-like plainlinks')[0];
			var sandbox = /\/sandbox$/; 
			var sandboxText = '' 
				+ (sandbox.test(pagename) ? '<span rel="mw:WikiLink" style="font-weight:bold">sandbox</span>  | ' : '<a rel="mw:WikiLink" href="/wiki/' 
				+ pagename.replace(/\/sandbox/g, '') 
				+ '/sandbox"'
				+ (sandboxExists ? '' : ' class="new"')
				+ '>sandbox</a>');
			var testcasesText = '' 
				+ '<a rel="mw:WikiLink" href="/wiki/' 
				+ pagename.replace(/\/sandbox/g, '') 
				+ '/testcases"'
				+ (testcasesExists ? '' : ' class="new"')
				+ '>testcases</a>';
			var newHTML = sandboxText + testcasesText;
			links.insertAdjacentHTML("beforeend", newHTML);
		})();
	}
});