Difference between revisions of "MediaWiki:Common.js"

m
m (Move more Atlas code to the separate js)
Line 5: Line 5:
 
"use strict";
 
"use strict";
  
var page = window.page = mw.config.values.wgPageName;
 
 
var namespace = window.namespace = mw.config.get('wgCanonicalNamespace');
 
var namespace = window.namespace = mw.config.get('wgCanonicalNamespace');
 
var action = window.action = mw.config.values.wgAction;
 
var action = window.action = mw.config.values.wgAction;
Line 163: Line 162:
 
     $('head').append(makehtml('style', {}, 'input[type=number] {font-size: 13px;font-family: \'Open Sans\',Arial,sans-serif;color: rgb(207, 207, 207);background-color: #101010;padding: 5px 10px;margin-bottom: 2px;border: 1px solid #383838;-webkit-border-radius: 2px;-moz-border-radius: 2px;-khtml-border-radius: 2px;border-radius: 2px;outline: 0;-webkit-box-sizing: border-box;-moz-box-sizing: border-box;-ms-box-sizing: border-box;box-sizing: border-box;min-height: 30}'));
 
     $('head').append(makehtml('style', {}, 'input[type=number] {font-size: 13px;font-family: \'Open Sans\',Arial,sans-serif;color: rgb(207, 207, 207);background-color: #101010;padding: 5px 10px;margin-bottom: 2px;border: 1px solid #383838;-webkit-border-radius: 2px;-moz-border-radius: 2px;-khtml-border-radius: 2px;border-radius: 2px;outline: 0;-webkit-box-sizing: border-box;-moz-box-sizing: border-box;-ms-box-sizing: border-box;box-sizing: border-box;min-height: 30}'));
 
};
 
};
 
if (/^UO\:Atlas/.test(page) && namespace === 'UO' && $('.map-holder').length > 0) { /* Only run on UO Atlas pages which have a map present. */
 
 
    /* Remove unwanted default title attributes that cause browser tooltips. */
 
    $('a').each(function() {
 
        $(this).removeAttr("title");
 
    });
 
 
    /* Keep the map visible while scrolling. */
 
    if (!/&curid/.test(location.search)) { // Don't take effect on edit diff pages
 
        var $body = $('#bodyContent'),
 
            $map = $('.map-holder:not(.noscroll)'),
 
            $doc = $(document);
 
        if ($map.length > 0) {
 
            var mapleft = $map[0].getBoundingClientRect().left;
 
            $map.css({
 
                position: 'fixed',
 
                left: mapleft,
 
                top: $body.offset().top - $doc.scrollTop()
 
            });
 
            $(window).scroll(function() {
 
                var ymax = $body.offset().top + $body.height() - $map.height() - $doc.scrollTop();
 
                if (ymax < 0) {
 
                    $map.css('top', ymax);
 
                } else if ($('#mw-head').isOnScreen()) {
 
                    $map.css('top', $body.offset().top - $doc.scrollTop());
 
                } else {
 
                    $map.css('top', $('#navigation').height());
 
                }
 
            });
 
        }
 
    }
 
    /* Flash icons on hover. */
 
    $("span.pin").each(function () {
 
        $(this).find('img').before('<span>');
 
    });
 
    $("#UOLinksList").on("mouseover", "span", function() {
 
        $("#" + $(this).attr("data-pair")).addClass('highlight').find('span').addClass('pin-circle');
 
    }).on("mouseout", "span", function() {
 
        $("#" + $(this).attr("data-pair")).removeClass('highlight').find('span').removeClass('pin-circle');
 
    });
 
 
    /* Add jCanvas (http://projects.calebevans.me/jcanvas/docs/) */
 
    $('head').append(makehtml('script', {
 
        src: 'https://cdnjs.cloudflare.com/ajax/libs/jcanvas/16.7.3/jcanvas.min.js'
 
    }));
 
 
    /* Adds a new canvas layer for each map */
 
    var addCanvas = function(thisClass, z) {
 
        $('.map:not(.mapcanvas)').each(function() {
 
            var $img = $(this).find('img');
 
            $(this).after(makehtml('div', {
 
                    class: 'map mapcanvas',
 
                    style: $(this).attr('style') + ((z === undefined) ? '' : 'z-index:' + z)
 
                },
 
                makehtml('canvas', {
 
                    class: thisClass,
 
                    width: $img.attr('width'),
 
                    height: $img.attr('height'),
 
                })
 
            ));
 
        });
 
    };
 
 
    /* Create the trigger icon */
 
    $('.map-holder').append(makehtml('aside', {
 
        class: 'pin menutrigger',
 
        style: 'font-size: 25px;color:rgb(224, 171, 67);'
 
    }, '&#9881;'));
 
 
    /* Create and add the base tab html */
 
    var loc = location.href.toString().split('#')[0],
 
        tab1 = makehtml('li', {}, makehtml('a', {
 
            href: loc + '#mapoptions'
 
        }, 'Options')),
 
        tab2 = makehtml('li', {}, makehtml('a', {
 
            href: loc + '#mylocation'
 
        }, 'Find your location')),
 
        tab3 = makehtml('li', {}, makehtml('a', {
 
            href: loc + '#showhide'
 
        }, 'Show/hide icons')),
 
        tab4 = makehtml('li', {}, makehtml('a', {
 
            href: loc + '#addlocation'
 
        }, 'Add location')),
 
        tab5 = makehtml('li', {}, makehtml('a', {
 
            href: loc + '#editlocation'
 
        }, 'Edit location'));
 
    $("#toolmenu").prepend(makehtml('ul', {}, tab1 + tab2 + tab3 + tab4 + tab5));
 
 
    /* Create UI for 'find me' tab */
 
    var xinput = makehtml('input', {
 
            id: 'xcoord',
 
            maxlength: '4',
 
            size: '4',
 
            style: 'margin-top: 13px;padding: 2px 5px;min-height: 0;',
 
            type: 'text'
 
        }),
 
        yinput = makehtml('input', {
 
            id: 'ycoord',
 
            maxlength: '4',
 
            size: '4',
 
            style: 'margin-top: 13px;padding: 2px 5px;min-height: 0;margin-right: 7px;',
 
            type: 'text'
 
        }),
 
        findbutton = makehtml('input', {
 
            id: 'findme',
 
            type: 'button',
 
            value: 'Find me'
 
        }),
 
        removebutton = makehtml('input', {
 
            id: 'findme',
 
            type: 'button',
 
            value: 'Remove me from the map'
 
        });
 
    $('#mylocation').append('x: ' + xinput + 'y: ' + yinput + ' ' + findbutton + ' ' + removebutton);
 
 
    /* Populate the list of pintypes being used */
 
    var $checkboxes = $(makehtml('div', {
 
        id: 'pinlist'
 
    }));
 
    $('.pin-types').each(function() {
 
        var inputText = $(this).attr('data-name'),
 
            inputType = $(this).attr('data-pin');
 
        $checkboxes.append(makehtml('label', {}, makehtml('input', {
 
            'data-type': inputType,
 
            type: 'checkbox',
 
            checked: 'true'
 
        }, inputText)) + '<br>');
 
    });
 
    $('#showhide').append($checkboxes);
 
 
    /* Populate the options tab for the gridlines option */
 
    $('#mapoptions').append(makehtml('label', {}, makehtml('input', {
 
        'data-option': 'gridlines',
 
        type: 'checkbox',
 
      }, 'Show gridlines')));
 
 
    /* Populate the options tab for the radar map option */
 
    $('#mapoptions').append('<br><br>' + makehtml( + 'label', {}, makehtml('input', {
 
        'data-option': 'radarMap',
 
        type: 'checkbox',
 
      }, 'Tilt map like radar view')));
 
 
    /* Enable the HTML for the add location tab */
 
    var $addloc = $('#addlocation');
 
    $addloc.html($addloc.html().replace(/&lt;/g,'<').replace(/&gt;/g,'>'));
 
 
    /* Add the control buttons for the pin edit tabs */
 
    $('.editPinButtons').append([
 
        '<input type="button" class="pinEditCancel" value="Cancel editing this pin" />',
 
        '<input type="button" class="pinEditStore" value="Store edits to this pin" />',
 
        '<input type="button" class="pinEditSubmit" value="Submit all stored edits" />'
 
    ]);
 
 
    /* Load jQuery UI */
 
    mw.loader.using(['jquery.ui.button', 'jquery.ui.tabs', 'jquery.ui.dialog'], function() {
 
 
        /* Initialize tabs and popup dialog */
 
        $("#toolmenu").tabs({
 
            activate: function (event, ui) {
 
                var active = $('#toolmenu').tabs('option', 'active');
 
                $("#toolmenu").dialog({
 
                    height: {
 
                        mylocation:  225,
 
                        mapoptions:  285,
 
                        showhide:    600,
 
                        addlocation:  500,
 
                        editlocation: 400
 
                    }[$("#toolmenu ul>li a").eq(active).attr('href').split('#')[1]]
 
                });
 
            }
 
        }).dialog({
 
            autoOpen: false,
 
            draggable: true,
 
            width: 700,
 
            height: 285
 
        });
 
        $('.pinEditCancel, .pinEditStore, .pinEditSubmit').invis();
 
 
        /* Add event handler for opening the dialog */
 
        $(".menutrigger").on("click", function() {
 
            $('.mapmarker').remove();
 
            $("#toolmenu").dialog("open").parent().css({
 
                opacity: '.8'
 
            });
 
            $(this).parent().find('div:eq(0)').append(makehtml('span', {
 
                class: 'mapmarker'
 
            }));
 
        });
 
 
        /* Add event handler for 'find me' button */
 
        $('#findme').click(function() {
 
 
            var mainAtlas = /^UO\:Atlas\/[A-Za-z]+\//.test(mw.config.values.wgPageName);
 
            $('.mapmarker').after(makehtml('span', {
 
                    class: 'yourposition ' + $('.mapmarker').prev().attr('class'),
 
                    'data-name': 'Your location',
 
                    style: 'left: ' + $("#xcoord").val() + 'px; top: ' + $("#ycoord").val() + 'px;'
 
                },
 
                makehtml('img', {
 
                    src: 'http://stratics.com/w/images/b/b4/UO-icon-player.png',
 
                    width: (mainAtlas ? 6 : 12),
 
                    height: (mainAtlas ? 13 : 26)
 
                })
 
            ));
 
            $("#toolmenu").dialog("close");
 
        });
 
 
        /* Add event handler for 'remove me' button */
 
        $('#removeme').click(function() {
 
            $('.yourposition').remove();
 
        });
 
 
        /* Add event handler for changes to the pin list checkboxes */
 
        $('#pinlist').on('change', 'input', function() {
 
            var pintype = $(this).attr('data-type');
 
            $('.' + pintype)[this.checked ? 'show' : 'hide']();
 
        });
 
 
        /* Add container for the radar map option */
 
        $('.map').parent().wrap('<div class="mapCollection"><div>');
 
 
        /* Add event handler for selections on the options tab */
 
        $('#mapoptions').on('change', 'input', function() {
 
            var option = $(this).attr('data-option');
 
            switch (option) {
 
                case 'gridlines':
 
                case 'serverlines':
 
                    $('.' + option).toggle();
 
                    break;
 
                case 'radarMap':
 
                    $('.mapCollection').toggleClass('radarMap');
 
                    break;
 
            }
 
        });
 
 
        /* Create gridline overlays */
 
        addCanvas('gridlines', 1);
 
        $('.gridlines').hide().each(function() {
 
            var x,
 
                y,
 
                width = $(this).width(),
 
                height = $(this).height(),
 
                scale = $(this).parent().parent().getScale(),
 
                insets = $(this).parent().getInsets();
 
            var visibleX = parseInt(insets[3], 10) + 4 + (96 / scale),
 
                visibleY = parseInt(insets[0], 10) + (72 / scale),
 
                linewidth = Math.ceil(5 / scale),
 
                fontsize = Math.ceil(60 / scale) * 1.4;
 
   
 
            fontsize = (fontsize > 60) ? 60 : fontsize;
 
   
 
            for (y = 0; y < height; y = y + 100) {
 
                $(this).drawLine({
 
                    strokeStyle: 'rgb(224, 171, 67)',
 
                    strokeWidth: linewidth,
 
                    x1: 0,
 
                    y1: y,
 
                    x2: width,
 
                    y2: y
 
                }).drawText({
 
                    fillStyle: '#fff',
 
                    x: visibleX,
 
                    y: y + 5,
 
                    fontSize: fontsize,
 
                    fontFamily: 'Verdana, sans-serif',
 
                    text: y
 
                });
 
            }
 
   
 
            for (x = 100; x < width; x = x + 100) {
 
                $(this).drawLine({
 
                    strokeStyle: 'rgb(224, 171, 67)',
 
                    strokeWidth: linewidth,
 
                    x1: x,
 
                    y1: 0,
 
                    x2: x,
 
                    y2: height
 
                });
 
            }
 
   
 
            for (x = 100; x < width; x = x + ((scale == 1) ? 200 : 100)) {
 
                $(this).drawText({
 
                    fillStyle: '#fff',
 
                    x: x,
 
                    y: visibleY,
 
                    fontSize: fontsize,
 
                    fontFamily: 'Verdana, sans-serif',
 
                    text: x
 
                });
 
            }
 
        });
 
 
        /* Add functionality for the Add Location tab */
 
        addCanvas('addlocation', 3);
 
        $('#getlocbtn').click(function() {
 
            $("#toolmenu").dialog("close");
 
            $('.addlocation,.gridlines,.serverlines').css('cursor', 'crosshair').click(function(event) {
 
                var $this = $(this),
 
                    rect = this.getBoundingClientRect();
 
                var x = Math.round($this.width() / rect.width * (event.clientX - rect.left)),
 
                    y = Math.round($this.height() / rect.height * (event.clientY - rect.top));
 
                var makeWiki = function() {
 
                    var str = '-->{{UOAddPin|';
 
                    str += $('#getlocselect').val() + '|';
 
                    str += x + '|' + y + '|' + $('#getlocdescription').val();
 
                    var wiki = $('#getlocwikipage').val();
 
                    if (wiki.length > 0) {
 
                        str += '|link=' + wiki;
 
                    }
 
                    str += '}}<!--';
 
                    return str;
 
                };
 
 
                $('.addlocation,.gridlines,.serverlines').css('cursor', 'auto');
 
                $('#getloccoords').text(x + ' x ' + y);
 
                $('#getlocresult').text(makeWiki);
 
                $('#getloctext').show();
 
                $("#toolmenu").dialog("open");
 
                $('#getlocwikipage, #getlocselect, #getlocdescription').on("change keyup", function() {
 
                    $('#getlocresult').text(makeWiki);
 
                });
 
            });
 
        });
 
 
        if (/^UO\:Atlas\/(?:Fel|Tram)/.test(page)) { /* Only run on Felucca and Trammel maps. */
 
 
            /* Populate the options tab for the gridlines option */
 
            $('#mapoptions').append('<br><br>' + makehtml('label', {}, makehtml('input', {
 
                'data-option': 'serverlines',
 
                type: 'checkbox',
 
            }, 'Show server lines')));
 
 
            /* Create server line overlays */
 
            addCanvas('serverlines', 2);
 
            $('.serverlines').hide().each(function() {
 
                var $this = $(this);
 
                var height = $this.height(),
 
                    scale = $this.parent().parent().getScale();
 
                var linewidth = Math.ceil(5 / scale);
 
                var makeLine = function(x1, y1, x2, y2) {
 
                    $this.drawLine({
 
                        strokeStyle: 'red',
 
                        strokeWidth: linewidth,
 
                        x1: x1,
 
                        y1: y1,
 
                        x2: x2,
 
                        y2: y2
 
                    });
 
                };
 
 
                makeLine(0, 2030, 2678, 2030);
 
                makeLine(2678, 0, 2678, height);
 
                makeLine(0, 1281, 2679, 1281);
 
                makeLine(1536, 1281, 1536, 0);
 
                makeLine(3838, 0, 3838, height);
 
            });
 
 
        }
 
 
    });
 
 
}
 
  
 
/* Start: collapsible navboxes */
 
/* Start: collapsible navboxes */
Line 558: Line 194:
 
/* Start Atlas Tools */
 
/* Start Atlas Tools */
  
if (/^UO\:Atlas/.test(page) && namespace === 'UO' && $('.map-holder').length > 0) { /* Only run on UO Atlas pages which have a map present. */
+
if (/^UO\:Atlas/.test(mw.config.values.wgPageName) && namespace === 'UO' && $('.map-holder').length > 0) { /* Only run on UO Atlas pages which have a map present. */
  
 
     addjQueryCSS();
 
     addjQueryCSS();

Revision as of 11:17, 11 October 2016

// <nowiki>
/* globals $, mw, uix, XenForo */

(function() {
"use strict";

var namespace = window.namespace = mw.config.get('wgCanonicalNamespace');
var action = window.action = mw.config.values.wgAction;

/* Add a class to allow per-theme styling of the wiki. */
var theme;
if (typeof uix === 'undefined') {
    theme = $("dt:contains('Style')").next().find('a').text();
} else {
    theme = uix.user.themeName;
}
$('#mw-content-text').addClass('w' + theme.replace(/\s/g,''));

/* Add a class to allow per-namespace styling of the wiki. */
$('#mw-content-text').addClass('wNamespace' + namespace);

/* Fix broken mail and alert popups while on the wiki */
XenForo.ExtLoader = function (f) {
    return function () {
        try {
            f.apply(this, arguments);
        } catch (e) {
            var mailreq = 'http://stratics.com/conversations/popup?_xfRequestUri=%2F&_xfNoRedirect=1&_xfResponseType=json&_xfToken=' + $('input[name=_xfToken]:first').attr('value');
            $.getJSON(mailreq, function (data) {
                $('#ConversationsMenu .listPlaceholder').empty().html(data.templateHtml);
            });
            var alertreq = 'http://stratics.com/conversations/alerts-popup?_xfRequestUri=%2F&_xfNoRedirect=1&_xfResponseType=json&_xfToken=' + $('input[name=_xfToken]:first').attr('value');
            $.getJSON(alertreq, function (data) {
                $('#AlertsMenu .listPlaceholder').empty().html(data.templateHtml);
            });
        }
    };
}(XenForo.ExtLoader);

/* Create a common namespace for stratics wiki js */
(function () {
    var temp = {
        f: {
            atlas: {
                ui: {}
            },
            util: {
              makehtml: function (type, obj, text) {
                    var str = "<" + type, key;
                    for (key in obj) {
                        if (obj.hasOwnProperty(key)) {
                            str += ' ' + key + '="' + obj[key] + '"';
                        }
                    }
                    return str + ('input' === type ? '' : '>') + ("input" === type ? '/>' + (undefined === text ? '' : text) 
                                                                                   : (undefined === text ? '' : text) + '</' + type + '>');
                },
              reloadPage: function () { location.reload(); }
            },
            wiki: {
                api: new mw.Api(),
            }
        },
        keycodes: {
            27: 'ESC',
            33: 'NE',
            34: 'SE',
            35: 'SW',
            36: 'NW',
            37: 'W',
            38: 'N',
            39: 'E',
            40: 'S'
        },
        wiki: {
            markup: '',
            openEdits: []
        }
    };

    window.stratics = $.extend(true, (undefined === window.stratics) ? {} : window.stratics ,temp); // Avoid clobbering any existing window.stratics object.
})(window);

/* Tests if an element is visible on the screen. */
$.fn.isOnScreen = function() {
    var element = this.get(0);
    var bounds = element.getBoundingClientRect();
    return bounds.top < window.innerHeight && bounds.bottom > 0;
};

/* Returns the scale transform value for an element. */
$.fn.getScale = function() {
    var vals = this.css('transform');
    return (vals == 'none') ? 1 : vals.split('(')[1].split(')')[0].split(',')[0];
};

/* Returns an array of the 4 inset values for an element. */
$.fn.getInsets = function() {
    var vals = this.css('clip-path');
    if (vals == 'none') {
        vals = this.css('-webkit-clip-path');
    }
    return vals.split('(')[1].split(')')[0].split(/px\s?/);
};

/* Sort the options within a select alphabetically */
$.fn.sortOptions = function () {
    var optionList = this.find('option')
        .sort(function (a, b) {
            return (a.text > b.text ? 1 : (a.text < b.text ? -1 : 0));
        });
    return this.empty()
        .append(optionList);
};

/* Add visibility equivalents to show/hide/toggle */
$.fn.extend({
    vis: function () {
        return this.each(function () {
            $(this).css("visibility", "visible");
        });
    },
    invis: function () {
        return this.each(function () {
            $(this).css("visibility", "hidden");
        });
    },
    toggleVis: function () {
        return this.each(function () {
            $(this).css("visibility", function (b, a) {
                return "visible" == a ? "hidden" : "visible";
            });
        });
    }
});

/* HTML construction helper function */
var makehtml = window.makehtml = function (type, o, text) {
    var i = '<' + type;
    for (var key in o) {
        if (o.hasOwnProperty(key)) {
            i += ' ' + key + '="' + o[key] + '"';
        }
    }
    i += (type === 'input') ? '' : '>';
    i += (type === 'input') ? '/>' + (text || '') : (text || '') + '</' + type + '>';
    return i;
};

/* Add jQuery UI css */
var addjQueryCSS = function () {
    $('head').append(makehtml('link', {
            rel: 'stylesheet',
            type: 'text/css',
            href: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/ui-darkness/jquery-ui.min.css'
        }));

    /* Workaround for jQuery UI/Xenforo/Mediawiki css conflict */
    $('head').append(makehtml('style', {}, 'body .ui-dialog .ui-widget-header,body .ui-button {background:#333!important}'));

    /* Add jQuery UI styling for input[type=number] */
    $('head').append(makehtml('style', {}, 'input[type=number] {font-size: 13px;font-family: \'Open Sans\',Arial,sans-serif;color: rgb(207, 207, 207);background-color: #101010;padding: 5px 10px;margin-bottom: 2px;border: 1px solid #383838;-webkit-border-radius: 2px;-moz-border-radius: 2px;-khtml-border-radius: 2px;border-radius: 2px;outline: 0;-webkit-box-sizing: border-box;-moz-box-sizing: border-box;-ms-box-sizing: border-box;box-sizing: border-box;min-height: 30}'));
};

/* Start: collapsible navboxes */

$('.navbox-inner:gt(0)').addClass('mw-collapsed');
$('.navbox-inner').makeCollapsible();

/* End: collapsible navboxes */

/* Start Item Editor */

if (action === 'edit' && (namespace === 'UO' || namespace === 'User' )) {

    addjQueryCSS();

    /* Load properties JSON */
    $.getScript('/w/index.php?title=MediaWiki:PropertyBuilder.js&action=raw&ctype=text/javascript').complete(function () {

        /* Load jQuery UI */
        mw.loader.using(['jquery.ui.button', 'jquery.ui.tabs', 'jquery.ui.dialog'], function () {

            /* Load Editor */
            $.getScript('/w/index.php?title=MediaWiki:PropertyEditor.js&action=raw&ctype=text/javascript', function () {
                loadEditor();
            });
        });
    });
}

/* End Item Editor  */

/* Start Atlas Tools */

if (/^UO\:Atlas/.test(mw.config.values.wgPageName) && namespace === 'UO' && $('.map-holder').length > 0) { /* Only run on UO Atlas pages which have a map present. */

    addjQueryCSS();

    /* Load jQuery UI */
    mw.loader.using(['jquery.ui.button', 'jquery.ui.tabs', 'jquery.ui.dialog'], function () {

        /* Load Editor */
        $.getScript('/w/index.php?title=MediaWiki:AtlasTools.js&action=raw&ctype=text/javascript');
    });
}

/* End Atlas Tools */

}());

// </nowiki>