Jump to content

User:Mike Dillon/Scripts/highlightNonIPA.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.
// Requires: [[User:Mike Dillon/Scripts/i18n.js]]

/* <pre><nowiki> */

/* Messages */
wfAddMsg("en", "ipaClassName", "IPA");

var nonIpaSymbols;
var nonIpaStyle;
addOnloadHook(function () {
    var body = document.getElementById("bodyContent");
    if (!body) return;

    if (!nonIpaSymbols) {
        nonIpaSymbols = /([^a-fh-z\u0250-\u02FFŋǀǃǂǁβθðçχħѵáéíóúàèìòùäëïöüãẽĩõũâêîôûøæœ͡‿\|‖↗↘↓↑̚ⁿ̤̪ ̺̻.\[\]\/,•*<>\s()-])/;
    }
    if (!nonIpaStyle) {
        nonIpaStyle = "background-color: red; color: white";
    }

    var ipaBlocks = getElementsByClassName(body, "span", wfMsgForContent("ipaClassName"));
    for (var i in ipaBlocks) {
        var block = ipaBlocks[i];

        var toReplace = [];
        for (var n in block.childNodes) {
            var node = block.childNodes[n];

            // Skip non-text nodes
            if (node.nodeType != 3) continue;

            if (nonIpaSymbols.test(node.nodeValue)) {
                toReplace.push(node);
            }
        }

        for (var n in toReplace) {
            var node = toReplace[n];
            var replace = document.createElement("span");

            var parts = node.nodeValue.split(nonIpaSymbols);
            for (var m in parts) {
                if (m % 2 == 0) {
                    replace.appendChild(document.createTextNode(parts[m]));
                } else {
                    var highlight = document.createElement("span");
                    highlight.setAttribute("style", nonIpaStyle);
                    highlight.appendChild(document.createTextNode(parts[m]));
                    replace.appendChild(highlight);
                }
            }

            block.replaceChild(replace, node);
        }
    }
});

/* </nowiki></pre> */