MediaWiki:Latinify/code.js

/** * Name:       Latinify * Description: Latinifies contents of articles * Version:    1.0 * Author:     KockaAdmiralac <1405223@gmail.com> */ (function {   var config = mw.config.get([ 'wgContentLanguage' ]);   var $buttons = $('.page-header__contribution-buttons .wds-list');    if (!$buttons.exists) {        return;    }    $.get(mw.util.wikiScript('load'), { mode: 'articles', articles: 'u:dev:MediaWiki:Custom-transliteration', only: 'styles', t: $.now }, function(d) { var maps = JSON.parse(d.replace(/\/\*.+\*\//, '')), map = maps[config.wgContentLanguage], i18n = { be: { latinify: 'Łacinka', cyrillify: 'Кірыліца' },               uk: { latinify: 'Latynka', cyrillify: 'Кирилиця' }           }[config.wgContentLanguage], cache = {}, latin; if (!map || !i18n) { return; }       function walk(cb) { var walker = document.createTreeWalker(               document.getElementById('mw-content-text'),                NodeFilter.SHOW_TEXT,                null,                false            ), n;            while (n = walker.nextNode) { cb(n); }       }        function latinify { walk(function(n) {               var text = n.textContent;                for (var i in map) {                    var val = map[i];                    if ( val.length === 2 && i.length === 1 && val === val.toUpperCase ) {                       var index = text.indexOf(i),                            limit = 10;                        if (index !== -1) {                            console.log(text, i, val);                        }                        while (index !== -1) {                            if (--limit === 0) {                                break;                            }                            var next = text[index + 1];                            if (next && next === next.toLowerCase) {                                text = text.replace(i, val[0] + val[1].toLowerCase);                            } else {                                text = text.replace(i, val);                            }                            index = text.indexOf(i);                            console.log(index);                        }                    } else {                        text = text.replace(new RegExp(i, 'g'), val); }               }                if (text !== n.textContent) { cache[text] = n.textContent; }               n.textContent = text; });           $('#Latinify')                .text(i18n.cyrillify)                .off                .click(cyrillify);        }        function cyrillify {            walk(function(n) { var text = n.textContent; if (cache[text]) { n.textContent = cache[text]; }           });            $('#Latinify')                .text(i18n.latinify)                .off                .click(latinify);        }        $buttons.append( $('').append(               $('', { href: '#', text: i18n.latinify, id: 'Latinify' }).click(latinify)           ) );   }); });