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. In Internet Explorer and Firefox, hold down the Ctrl key and click the Refresh or Reload button. Opera users have to clear their caches through Tools→Preferences, see the instructions for Opera. Konqueror and Safari users can just click the Reload button.

// 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> */