MediaWiki:Gadget-OrangeLinks.js: Difference between revisions

From Linguifex
Jump to navigation Jump to search
No edit summary
m 1 revision imported
 
(2 intermediate revisions by 2 users not shown)
Line 1: Line 1:
// <nowiki>
// <nowiki>
var actionAPI = new mw.Api({ ajax: { headers: { "Api-User-Agent": "Gadget developed by [[User:Ioaxxere]]" } } });
function HTML_unescape(text) {
 
return new DOMParser().parseFromString(text, "text/html").body.textContent;
var HTML_unescape = function(text) {
}
    return new DOMParser().parseFromString(text, "text/html").body.textContent;
};


function getTitleAndAnchor(link) {
function getTitleAndAnchor(link) {
    var pathname = link.pathname;
let linkTitle = decodeURIComponent(link.pathname.split("/wiki/")[1]);
    var linkTitle;
let linkAnchor = decodeURIComponent(link.hash.slice(1) || "");
return [linkTitle, linkAnchor];
}


    if (pathname.startsWith("/w/")) {
mw.util.addCSS(`
        linkTitle = pathname.split("/w/")[1];
.orange-link {
    } else if (pathname.startsWith("/wiki/")) {
color: var(--wikt-palette-gold);
        linkTitle = pathname.split("/wiki/")[1];
}
    } else {
.orange-link:visited {
        linkTitle = ""; // fallback
color: var(--wikt-palette-dullgold);
    }
}
.orange-link:hover, .orange-link:visited:hover {
color: var(--wikt-palette-honey);
}
`);


    linkTitle = decodeURIComponent(linkTitle);
let actionAPI = new mw.Api({ajax: {headers: {"Api-User-Agent": "Gadget developed by [[User:Ioaxxere]]"}}});
    var linkAnchor = decodeURIComponent(link.hash.slice(1) || "");
    return [linkTitle, linkAnchor];
}
 
mw.util.addCSS(
    ".orange-link { color: #b88d00; }" +
    ".orange-link:visited { color: #826f34; }" +
    ".orange-link:hover, .orange-link:visited:hover { color: #81540e; }"
);


// Maps each page to a list of IDs.
// Maps each page to a list of IDs.
var pageIDsOf = {};
let pageIDsOf = new Map();


function makeOrangeLinks(element) {
async function makeOrangeLinks(element) {
    // Get a list of pages and links to process.
// Get a list of pages and links to process.
    var pagesToProcess = [];
let pagesToProcess = [];
    var linksToProcess = [];
let linksToProcess = [];
    var links = element.querySelectorAll("a");
for (let link of element.querySelectorAll("a")) {
// Check whether the link needs to be processed.
if (!link.href.startsWith("https://en.wiktionary.org/wiki/")) continue;
if (link.matches(".orange-link, .not-orange-link, .new, .external")) continue;


    for (var i = 0; i < links.length; i++) {
let [linkTitle, linkAnchor] = getTitleAndAnchor(link);
        var link = links[i];


        // Check whether the link needs to be processed.
if (!linkAnchor || /^[a-z]/.test(linkAnchor)) continue;
        if (link.href.indexOf("https://linguifex.com/w/") !== 0 || link.href.indexOf("https://linguifex.com/wiki/") !== 0) {
            continue;
        }
        if (link.className.match(/orange-link|not-orange-link|new|external/)) {
            continue;
        }


        var parts = getTitleAndAnchor(link);
if (![0, 100, 118].includes(new mw.Title(linkTitle).namespace)) continue; // Main, Appendix, Reconstruction
        var linkTitle = parts[0];
        var linkAnchor = parts[1];


        if (!linkAnchor || /^[a-z]/.test(linkAnchor) || (new mw.Title(linkTitle)).namespace !== 120) {
pagesToProcess.push(linkTitle);
            continue;
linksToProcess.push(link);
        }
}


        pagesToProcess.push(linkTitle);
// Filter out duplicates.
        linksToProcess.push(link);
pagesToProcess = [...new Set(pagesToProcess)];
    }


    // Filter out duplicates.
// Process the array in chunks.
    var uniquePages = {};
let queries = [];
    var pages = [];
for (let i = 0; i < pagesToProcess.length; i += 100) {
    for (var j = 0; j < pagesToProcess.length; j++) {
let chunk = pagesToProcess.slice(i, i + 100);
        if (!uniquePages[pagesToProcess[j]]) {
            uniquePages[pagesToProcess[j]] = true;
            pages.push(pagesToProcess[j]);
        }
    }
    pagesToProcess = pages;


    // Process the array in chunks.
// Query the IDs for all the pages using [[Module:get IDs]].
    var queries = [];
let params = {
    for (var k = 0; k < pagesToProcess.length; k += 100) {
action: "expandtemplates",
        var chunk = pagesToProcess.slice(k, k + 100);
format: "json",
prop: "wikitext",
text: `{{#invoke:get IDs|show|${chunk.join("|")}}}`
};


        // Query the IDs for all the pages using [[Module:get IDs]].
queries.push(actionAPI.post(params).then(response => {
        var wikitext = "{{#invoke:get IDs|show|" + chunk.join("|") + "}}";
// Integrate the results into `pageIDsOf`.
        var params = {
let pageIDs = HTML_unescape(response.expandtemplates.wikitext).split("\n\n");
            action: "expandtemplates",
for (let j = 0; j < chunk.length; j++)
            format: "json",
pageIDsOf.set(chunk[j], pageIDs[j].split(" "));
            prop: "wikitext",
}));
            text: wikitext
}
        };
await Promise.all(queries);


        queries.push(
// After all the queries have returned, determine whether each link needs to be orange.
            actionAPI.post(params).then((function(chunkCopy) {
for (let link of linksToProcess) {
                return function(response) {
let [linkTitle, linkAnchor] = getTitleAndAnchor(link);
                    var pageIDs = HTML_unescape(response.expandtemplates.wikitext).split("\n\n");
let anchorExists = pageIDsOf.get(linkTitle).includes(linkAnchor);
                    for (var m = 0; m < chunkCopy.length; m++) {
link.classList.add(anchorExists ? "not-orange-link" : "orange-link");
                        pageIDsOf[chunkCopy[m]] = pageIDs[m].split(" ");
}
                    }
                };
            })(chunk))
        );
    }
 
    // After all the queries have returned, determine whether each link needs to be orange.
    Promise.all(queries).then(function() {
        for (var n = 0; n < linksToProcess.length; n++) {
            var link = linksToProcess[n];
            var parts = getTitleAndAnchor(link);
            var linkTitle = parts[0];
            var linkAnchor = parts[1];
            if (pageIDsOf[linkTitle] && pageIDsOf[linkTitle].indexOf(linkAnchor) !== -1) {
                link.classList.add("not-orange-link");
            } else {
                link.classList.add("orange-link");
            }
        }
    });
}
}


// Activate the gadget.
// Activate the gadget.
var pageContent = document.querySelector(".mw-parser-output");
let pageContent = document.querySelector(".mw-parser-output");
if (pageContent) {
if (pageContent)
    makeOrangeLinks(pageContent);
makeOrangeLinks(pageContent);
}


// Create a global hook in case any other gadget or script would like to activate it.
// Create a global hook in case any other gadget or script would like to activate it.
window.makeOrangeLinks = makeOrangeLinks;
window.makeOrangeLinks = makeOrangeLinks;
// </nowiki>
// </nowiki>

Latest revision as of 17:52, 4 November 2025

// <nowiki>
function HTML_unescape(text) {
	return new DOMParser().parseFromString(text, "text/html").body.textContent;
}

function getTitleAndAnchor(link) {
	let linkTitle = decodeURIComponent(link.pathname.split("/wiki/")[1]);
	let linkAnchor = decodeURIComponent(link.hash.slice(1) || "");
	return [linkTitle, linkAnchor];
}

mw.util.addCSS(`
	.orange-link {
		color: var(--wikt-palette-gold);
	}
	.orange-link:visited {
		color: var(--wikt-palette-dullgold);
	}
	.orange-link:hover, .orange-link:visited:hover {
		color: var(--wikt-palette-honey);
	}
`);

let actionAPI = new mw.Api({ajax: {headers: {"Api-User-Agent": "Gadget developed by [[User:Ioaxxere]]"}}});

// Maps each page to a list of IDs.
let pageIDsOf = new Map();

async function makeOrangeLinks(element) {
	// Get a list of pages and links to process.
	let pagesToProcess = [];
	let linksToProcess = [];
	for (let link of element.querySelectorAll("a")) {
		// Check whether the link needs to be processed.
		if (!link.href.startsWith("https://en.wiktionary.org/wiki/")) continue;
		if (link.matches(".orange-link, .not-orange-link, .new, .external")) continue;

		let [linkTitle, linkAnchor] = getTitleAndAnchor(link);

		if (!linkAnchor || /^[a-z]/.test(linkAnchor)) continue;

		if (![0, 100, 118].includes(new mw.Title(linkTitle).namespace)) continue; // Main, Appendix, Reconstruction

		pagesToProcess.push(linkTitle);
		linksToProcess.push(link);
	}

	// Filter out duplicates.
	pagesToProcess = [...new Set(pagesToProcess)];

	// Process the array in chunks.
	let queries = [];
	for (let i = 0; i < pagesToProcess.length; i += 100) {
		let chunk = pagesToProcess.slice(i, i + 100);

		// Query the IDs for all the pages using [[Module:get IDs]].
		let params = {
			action: "expandtemplates",
			format: "json",
			prop: "wikitext",
			text: `{{#invoke:get IDs|show|${chunk.join("|")}}}`
		};

		queries.push(actionAPI.post(params).then(response => {
			// Integrate the results into `pageIDsOf`.
			let pageIDs = HTML_unescape(response.expandtemplates.wikitext).split("\n\n");
			for (let j = 0; j < chunk.length; j++)
				pageIDsOf.set(chunk[j], pageIDs[j].split(" "));
		}));
	}
	await Promise.all(queries);

	// After all the queries have returned, determine whether each link needs to be orange.
	for (let link of linksToProcess) {
		let [linkTitle, linkAnchor] = getTitleAndAnchor(link);
		let anchorExists = pageIDsOf.get(linkTitle).includes(linkAnchor);
		link.classList.add(anchorExists ? "not-orange-link" : "orange-link");
	}
}

// Activate the gadget.
let pageContent = document.querySelector(".mw-parser-output");
if (pageContent)
	makeOrangeLinks(pageContent);

// Create a global hook in case any other gadget or script would like to activate it.
window.makeOrangeLinks = makeOrangeLinks;
// </nowiki>