User:Sobloku/global.js

From Meta, a Wikimedia project coordination wiki

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/*
https://ru.wikipedia.org/wiki/Википедия:Форум/Архив/Новости/2016/08#Скрипт_для_чтения_всплывающих_подсказок_на_сенсорных_устройствах
Участник:Jack who built the house/accessibleTooltips.js
importScript('https://meta.wikimedia.org/wiki/User:Sobloku/user--Jack-who-built-the-house--accessibleTooltips.js');*/


/*
(function () {
	var wgLangPrefs = mw.config.get('wgLangPrefs');
	if(! $.isArray(wgLangPrefs) ) {
		wgLangPrefs = Array();
	}
	if ($.inArray("en", wgLangPrefs) == -1) {
		wgLangPrefs.push("en");
	}
	mw.config.set('wgLangPrefs', wgLangPrefs);
}()); */


/* Скрипт для чтения всплывающих подсказок на сенсорных устройствах

Источники:
https://ru.wikipedia.org/wiki/Википедия:Форум/Архив/Новости/2016/08#Скрипт_для_чтения_всплывающих_подсказок_на_сенсорных_устройствах
https://ru.wikipedia.org/wiki/Участник:Jack_who_built_the_house/accessibleTooltips.js
*/

/**
 * accessibleTooltips.js — 27.08.2016
 * By Jack who built the house
 * Licenced under GNU Free Documentation License (https://www.gnu.org/licenses/fdl.html) and CC-BY-SA 4.0
 * (https://creativecommons.org/licenses/by-sa/4.0/)
 * 
 * The code responsible for the tooltips mechanism was copied from the Google Chrome—pretty-printed version of
 * [[:ru:MediaWiki:Gadget-referenceTooltips.js]] as of 17 August 2016 with certain changes (for instance,
 * namespace check removed). See [[mw:Reference Tooltips]]. That gadget, created by [[:en:User:Yair_rand]],
 * is licenced under GNU Free Documentation License (https://www.gnu.org/licenses/fdl.html) and CC-BY-SA 3.0
 * (https://creativecommons.org/licenses/by-sa/3.0/), as stated by its author
 * at [[:en:User_talk:Yair_rand/ReferenceTooltips#Which_copyright_agreements_this_gadget_use.3F]].
 */

function accessibleTooltips($content) {
    if (typeof accessibleTooltips_touchscreensOnly == 'undefined')
	   	window.accessibleTooltips_touchscreensOnly = true;
	
	var isReallyTouchscreen = "ontouchstart" in document.documentElement;
	if (accessibleTooltips_touchscreensOnly && !isReallyTouchscreen)
		return;
    
    function toggleRT(o) {
        mw.cookie.set('RTsettings', o + "|" + settings[1] + "|" + settings[2]);
        location.reload();
    }
    var settings = mw.cookie.get('RTsettings');
    settings = settings ? settings.split("|") : [1, 200, +("ontouchstart" in document.documentElement)];
    if (settings[0] == 0) {
        var footer = $("#footer-places, #f-list");
        if (footer.length == 0) {
            footer = $("#footer li").parent();
        }
        footer.append($("<li>").append($("<a>").text("Включить всплывающие подсказки").attr("href", "#").click(function() {
            toggleRT(1);
        })));
        return;
    }
    var isTouchscreen = +settings[2], timerLength = isTouchscreen ? 0 : +settings[1], settingsMenu;
	
	var elements = $('span[style*="border-bottom: 1px dotted"], span[style*="border-bottom:1px dotted"], span[style*="border-bottom-width: 1px; border-bottom-style: dotted;"], abbr[title]:not([class]):not(.navbar.mini span abbr[title])');
	if (!elements.length)
		return;
	
	var titles = [];
	var texts = [];
	for (i = 0; i < elements.length; i++) {
	    texts[i] = elements[i].innerHTML;
	    titles[i] = elements[i].title;
	    $(elements[i]).after(
	          '<span class="accessibleTooltip" style="font-size:inherit;">'
	        + '<span href="#cite_note-accessibleTooltip-' + i + '" style="border-bottom:1px dotted; cursor:help;">' + texts[i] + '</span>'
	        + '</span>'
	        ).remove();
	}
	
	var accessibleTooltipPseudorefs =
	      '<div class="references-small" style="display:none;">'
	    + '<ol class="references">';
	for (i = 0; i < elements.length; i++) {
	    accessibleTooltipPseudorefs +=
	          '<li id="cite_note-accessibleTooltip-' + i + '">'
	        + '<b><a href="#cite_ref-accessibleTooltip-' + i + '">↑</a></b>'
	        + '<span class="reference-text">' + titles[i] + '</span>'
	        + '</li>';
	}
	accessibleTooltipPseudorefs +=
	      '</ol>'
	    + '</div>';
	
	$('.mw-body').after(accessibleTooltipPseudorefs);
    
    $content.find('.accessibleTooltip').each(function() {
        var tooltipNode, hideTimer, showTimer, checkFlip = !1;
        function findRef(h) {
            h = h.firstChild.getAttribute("href");
            h = h && h.split("#");
            h = h && h[1];
            h = h && document.getElementById(h);
            h = h && h.nodeName == "LI" && h;
            return h;
        }
        function hide(refLink) {
            if (tooltipNode && tooltipNode.parentNode == document.body) {
                hideTimer = setTimeout(function() {
                    $(tooltipNode).animate({
                        opacity: 0
                    }, 100, function() {
                        document.body.removeChild(tooltipNode);
                    });
                }, isTouchscreen ? 16 : 100);
            } else {
                var h = findRef(refLink);
                h && (h.style.border = "");
            }
        }
        function show() {
            if (!tooltipNode.parentNode || tooltipNode.parentNode.nodeType === 11) {
                document.body.appendChild(tooltipNode);
                checkFlip = !0;
            }
            $(tooltipNode).stop().animate({
                opacity: 1
            }, 100);
            clearTimeout(hideTimer);
        }
        function openSettingsMenu() {
            if (settingsMenu) {
                settingsMenu.dialog("open");
            } else {
                settingsMenu = $("<form>").append($("<button>").css("width", "100%").text("Отключить всплывающие подсказки").button().click(function() {
                    toggleRT(0);
                }), $("<br>"), $("<small>").text("После отключения всплывающие подсказки могут быть повторно включены при помощи ссылки в подвале страницы."), $("<hr>"), $("<label>").text("Задержка перед появлением подсказки (в миллисекундах): ").append($("<input>").attr({
                    "type": "number",
                    "value": settings[1],
                    step: 50,
                    min: 0,
                    max: 5000
                })), $("<br>"), $("<span>").text("Подсказка появляется при"), $("<label>").append($("<input>").attr({
                    "type": "radio",
                    "name": "RTActivate",
                    "checked": settings[2] == 0 && "checked",
                    "disabled": "ontouchstart" in document.documentElement && "disabled"
                }), "наведении"), $("<label>").append($("<input>").attr({
                    "type": "radio",
                    "name": "RTActivate",
                    "checked": settings[2] == 1 && "checked"
                }), "клике")).submit(function(e) {
                    e.preventDefault();
                }).dialog({
                    modal: !0,
                    width: 500,
                    title: "Настройки всплывающих подсказок",
                    buttons: {
                        "Сохранить настройки": function() {
                            var a = this.getElementsByTagName("input")
                              , b = +a[0].value;
                            mw.cookie.set('RTsettings', "1|" + (b > -1 && b < 5001 ? b : settings[1]) + (a[1].checked ? "|0" : "|1"));
                            location.reload();
                        }
                    }
                });
            }
        }
        $(this)[isTouchscreen ? 'click' : 'hover'](function(e) {
            var _this = this;
            if (isTouchscreen) {
                e.preventDefault();
                (!isReallyTouchscreen && tooltipNode && tooltipNode.parentNode == document.body) ||
                setTimeout(function() {
                    $(document.body).on("click touchstart", function(e) {
                        e = e || event;
                        e = e.target || e.srcElement;
                        for (; e && !$(e).hasClass("referencetooltip"); )
                            e = e.parentNode;
                        if (!e) {
                            clearTimeout(showTimer);
                            hide(_this);
                            $(document.body).off("click touchstart", arguments.callee);
                        }
                    });
                }, 0);
            }
            showTimer && clearTimeout(showTimer);
            showTimer = setTimeout(function() {
                var h = findRef(_this);
                if (!h)
                    return;
                if (!tooltipNode) {
                    tooltipNode = document.createElement("ul");
                    tooltipNode.className = "referencetooltip";
                    var c = tooltipNode.appendChild(h.cloneNode(true));
                    try {
                        if (c.firstChild.nodeName != "A") {
                            while (c.childNodes[1].nodeName == "A" && c.childNodes[1].getAttribute("href").indexOf("#cite_ref-") !== -1) {
                                do {
                                    c.removeChild(c.childNodes[1]);
                                } while (c.childNodes[1].nodeValue == " ");
                            }
                        }
                    } catch (e) {
                        mw.log(e);
                    }
                    c.removeChild(c.firstChild);
                    $(tooltipNode.firstChild.insertBefore(document.createElement("span"), tooltipNode.firstChild.firstChild)).addClass("RTsettings").attr("title", "Настройки всплывающих подсказок").click(function() {
                        mw.loader.using(["jquery.ui"], openSettingsMenu);
                    });
                    tooltipNode.appendChild(document.createElement("li"));
                    isTouchscreen || $(tooltipNode).hover(show, hide);
                }
                show();
                var o = $(_this).offset()
                  , oH = tooltipNode.offsetHeight;
                $(tooltipNode).css({
                    top: o.top - oH,
                    left: e.pageX - 14
                });
                if (tooltipNode.offsetHeight > oH) {
                    $(tooltipNode).css({
                        left: 'auto',
                        right: 0
                    });
                    tooltipNode.lastChild.style.marginLeft = (o.left - tooltipNode.offsetLeft) + "px";
                }
                if (checkFlip) {
                    if (o.top < tooltipNode.offsetHeight + (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0)) {
                        $(tooltipNode).addClass("RTflipped").css({
                            top: o.top + 12
                        });
                    } else if (tooltipNode.className === "referencetooltip RTflipped") {
                        $(tooltipNode).removeClass("RTflipped");
                    }
                    checkFlip = !1;
                }
            }, timerLength);
        }, isTouchscreen ? undefined : function() {
            clearTimeout(showTimer);
            hide(this);
        }
        );
    });
}

mw.hook('wikipage.content').add(accessibleTooltips);