MediaWiki:GameLinks.js

Материал из Guild Wars 2 wiki
Перейти к: навигация, поиск
/* Создание внутриигровых ссылок на основе id объекта
*  Оригинальный код взят с "http://wiki.guildwars2.com/wiki/Widget:Game_link".
*/

/* window.btoa polyfill / WTFPLv2 – https://github.com/davidchambers/Base64.js */ ! function() {
    function t(t) {
        this.message = t
    }
    var e = this,
        r = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    t.prototype = new Error, t.prototype.name = "InvalidCharacterError", e.btoa || (e.btoa = function(e) {
        for (var o, n, a = 0, i = r, c = ""; e.charAt(0 | a) || (i = "=", a % 1); c += i.charAt(63 & o >> 8 - a % 1 * 8)) {
            if (n = e.charCodeAt(a += .75), n > 255) throw new t("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
            o = o << 8 | n
        }
        return c
    })
}();

var gamelink = (function(document, btoa) {
    var linkTypes = {
        item: 2,
        text: 3,
        map: 4,
        skill: 6,
        trait: 7,
        recipe: 9,
        skin: 10,
        outfit: 11
    };

    function encodeChatLink(type, id) {
        if (!type) {
            return 'invalid type';
        }
        type = linkTypes[type.trim().toLowerCase()] || 0;
        if (!type) {
            return 'invalid type';
        }

        var data = [];
        while (id > 0) {
            data.push(id & 255);
            id = id >> 8;
        }
        while (data.length < 4 || data.length % 2 != 0) {
            data.push(0);
        }

        if (type == 2) {
            data.unshift(1);
        }
        data.unshift(type);

        // encode data
        var binary = '';
        for (var i = 0; i < data.length; i++) {
            binary += String.fromCharCode(data[i]);
        }
        return '[&' + btoa(binary) + ']';
    }

    return function(link) {
        if (!link) {
            return;
        }
        var chatLink = encodeChatLink(link.getAttribute('data-type'), +link.getAttribute('data-id'));
        var input = document.createElement('input');
        input.className = 'chatlink';
        input.type = 'text';
        input.value = chatLink;
        input.readOnly = true;
        input.spellcheck = false;

        link.appendChild(document.createTextNode(chatLink));
        link.parentNode.insertBefore(input, link);

        link.addEventListener('click', function() {
            this.style.visibility = 'hidden';
            input.style.display = 'inline-block';
            input.focus();
            input.select();
        }, false);
        input.addEventListener('blur', function() {
            this.style.display = null;
            link.style.visibility = null;
        }, false);
    };
})(document, window.btoa);

[].forEach.call(document.querySelectorAll(".gamelink"), gamelink);