Difference between revisions of "MediaWiki:Common.js"

m
m
Line 253: Line 253:
 
         $('.pin a img').removeClass('pin-not_circle');
 
         $('.pin a img').removeClass('pin-not_circle');
 
         $('#' + $(this).data('pair') + ' a img').removeClass('pin-circle');
 
         $('#' + $(this).data('pair') + ' a img').removeClass('pin-circle');
 +
    });
 +
    /* Highlight map region on hover. */
 +
    $('body').on('mouseover', '.overlayhighlighter', function () {
 +
        $('.mapgrid').hide();
 +
        $([...$(this).find('span:first').text().split(',')].map((x) => { return `.grid${x}` }).join(', ')).show();
 +
    })
 +
    .on('mouseout', 'article', function () {
 +
        $('.mapgrid').hide();
 
     });
 
     });
 
     /* End Atlas Tools */
 
     /* End Atlas Tools */

Revision as of 02:25, 28 September 2020

/*jshint esversion:6 */
/* globals $, mw, uix */

(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);

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

        /* Add jQuery UI styling for input[type=number] */
        $('head').append(stratics.f.util.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}'));
    };

    /* Create a common namespace for stratics wiki js */
    (function() {
    	    window.stratics = {
	            data: {},
	            f: {
            	    atlas: {
        	            ui: {}
    	            },
	                util: {
                	    /* Get the current time. */
            	        getTime: function() {
        	                var j;
    	                    var now = new Date(),
	                            time = [now.getHours(), now.getMinutes(), now.getSeconds()],
                            	suffix = time[0] < 12 ? "AM" : "PM";
                        	for (j = 1; 3 > j; j++) {
                    	        time[j] = ('0' + time[j]).slice(-2);
                	        }
            	            return [time.join(":"), ' ', suffix].join('');
        	            },
    	                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 + '>');
                    	},
                	    purgePage: function() {
	                    	new mw.Api().post({
    							action: 'purge',
							    titles: document.location.search.match(/title=(.[^&]+)/)[1],
							    format: 'json'
    						});
							location.reload();
        	            },
                	    reloadPage: function() {
            	            location.reload();
        	            }
    	            },
	                wiki: {
        	            /* Retrieves the wiki markup for a page; defaults to the current page. */
    	                getMarkup: function(page) {
	                        var getPage = function(callback, page) {
                        	    $.get('https://wiki.stratics.com/api.php?action=query&prop=revisions&rvprop=content&format=json&formatversion=2&titles=' + page, function(data) {
                    	            callback.apply(data);
                	            });
            	            };
        	                getPage(function() {
    	                    /* Allow scripts to be cached. */
	                            $.ajaxSetup({
                            	    cache: false
                        	    });
                    	        window.stratics.wiki.markup = this.query.pages[0].revisions[0].content;
                	            $('body').trigger('markupArrived');
            	            }, page || mw.config.get("wgPageName"));
        	            },
    	                /* Submits a markup edit to the server */
	                    submitMarkup: function(summary, content) {
                    	    window.stratics.f.wiki.api.postWithToken("edit", {
                	            action: "edit",
            	                title: mw.config.get("wgPageName"),
        	                    summary: summary,
    	                        text: content
	                        }).done(function(result, jqXHR) {
                            	mw.log("Saved successfully");
                            	$('body').trigger('submitMarkupSuccess');
                        	}).fail(function(code, result) {
                            	if (code === "http") {
                                	mw.log("HTTP error: " + result.textStatus); // result.xhr contains the jqXHR object
                            	} else if (code === "ok-but-empty") {
                                	mw.log("Got an empty response from the server");
                            	} else {
                                	mw.log("API error: " + code);
                            	}
                            	$('body').trigger('submitMarkupFailure');
                        	});
                    	}
	                }
    	        },
        	    keycodes: {
            	    27: 'ESC',
                	33: 'NE',
	                34: 'SE',
    	            35: 'SW',
        	        36: 'NW',
            	    37: 'W',
                	38: 'N',
	                39: 'E',
    	            40: 'S'
        	    },
            	wiki: {
                	markup: '',
                	openEdits: []
            	}
        	};
    })(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);
    };

    $.fn.extend({
        /* Allow changing tip text */
        changeTip: function (newText) {
            return this.each(function() {
                var $e = $(this).find('.tooltipstered');
                $e.data($e.data('tooltipster-ns')[0]).Content[0].innerText = newText;
            });
        },
        /* Allow retrieving tip text */
        getTip: function (newText) {
            return this.data(this.data('tooltipster-ns')[0]).Content[0].innerText;
        },

        /* Add visibility equivalents to show/hide/toggle */
        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";
                });
            });
        }
    });

    /* Start: collapsible navboxes */

    $('.navbox-inner:gt(0)').each(function () {
        $(this)[$(this).hasClass('expanded') ? 'removeClass' : 'addClass']('mw-collapsed');
    });
	mw.loader.using( 'jquery.makeCollapsible' ).then( function () {
    	$('.navbox-inner').makeCollapsible();
	});

    /* End: collapsible navboxes */

   	/* Start Item Editor */

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

   		addjQueryCSS();

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

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

               	/* Load Editor */
               	$.getScript('/index.php?title=MediaWiki:PropertyEditor.js&action=raw&ctype=text/javascript&1.0.0', 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('/index.php?title=MediaWiki:AtlasTools.js&action=raw&ctype=text/javascript');
//        });
//    }

    /* Flash icons on hover. */
    $('#UOLinksList').on('mouseover', 'span', function () {
        $('.pin a img').addClass('pin-not_circle');
        $('#' + $(this).data('pair') + ' a img').addClass('pin-circle').removeClass('pin-not_circle');
    })
    .on('mouseout', 'span', function () {
        $('.pin a img').removeClass('pin-not_circle');
        $('#' + $(this).data('pair') + ' a img').removeClass('pin-circle');
    });
    /* Highlight map region on hover. */
    $('body').on('mouseover', '.overlayhighlighter', function () {
        $('.mapgrid').hide();
        $([...$(this).find('span:first').text().split(',')].map((x) => { return `.grid${x}` }).join(', ')).show();
    })
    .on('mouseout', 'article', function () {
        $('.mapgrid').hide();
    });
    /* End Atlas Tools */
    
    /* Start Hunter's Guide scripts */

    if ($('a[title="Category:UO:Mobile"]').length > 0) {

        /* Block clicks to the edit tab as early as possible. */
        $('a[accesskey="e"]').click(function(e) {
            e.preventDefault();
            $('body').data('editClicked', true);
            return false;
        });

        /* Allow scripts to be cached. */
        $.ajaxSetup({
            cache: true
        });

        addjQueryCSS();

        	/* Load jQuery UI */
        	mw.loader.using(['mediawiki.api', 'jquery.ui.button', 'jquery.ui.tabs', 'jquery.ui.dialog', 'jquery.ui.selectable'], function() {
	        	window.stratics.f.wiki.api = new mw.Api();
        	
            	/* Load jQuery UI selectmenu */
            	$.getScript('https://cdn.rawgit.com/jquery/jquery-ui/master/ui/widgets/selectmenu.js').complete(function() {

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

            	        /* Load Mob Editor */
        	            $.getScript('/index.php?title=MediaWiki:Mob%20Editor.js&action=raw&ctype=text/javascript&1.1.6');

    	                /* Load Animal Lore Editor */
	                    $.getScript('/index.php?title=MediaWiki:AnimalLoreTool.js&action=raw&ctype=text/javascript&1.2.23');

                	});
            	});

            	/* Load OrgChart generator script */
            	$.getScript('/index.php?title=MediaWiki:Orgchart.js&action=raw&ctype=text/javascript&1.0.0').complete(function() {

                	/* Load Mob taxonomy data */
                	$.getScript('/index.php?title=MediaWiki:MobData.js&action=raw&ctype=text/javascript&1.0.8').complete(function() {

                    	/* Load Taxonomy chart builder */
                    	$.getScript('/index.php?title=MediaWiki:MobTaxonomy.js&action=raw&ctype=text/javascript&1.0.1').complete(function() {

                    	});
                	});
            	});
        	});
    }

    /* Add quick links to the Hunter's Guide main page. */
    if (/\?title=UO:Hunter%27s_Guide/.test(location.search)) {
        $.getScript('/index.php?title=MediaWiki:AddQuickLinks.js&action=raw&ctype=text/javascript&1.0.0');
    }

    /* End Hunter's Guide scripts */

    /* Start suit-page scripts */
    // This sorts the display order of suit parts, regardless of the order they are specified in the template call.
    if ($('table.suittable').length > 0) {
        $.getScript('/index.php?title=MediaWiki:Stupidtable.min.js&action=raw&ctype=text/javascript&1.0.0').complete(function() {
           $('.suittable').stupidtable().each(function () {
               $(this).find("th").eq(3).click(); 
           });
        });
    }
    /* End suit-page scripts */

    /* Start crafter table script */

    if ($('table.crafteditems').length > 0) {
        /* Load StupidTable plugin */
        $.getScript('/index.php?title=MediaWiki:Stupidtable.min.js&action=raw&ctype=text/javascript&1.0.0').complete(function() {

            // This next works around the fact that mediawiki doesn't build proper HTML for tables.
            $('.crafteditems:not(.nosort)').each(function () {
                var th, trs, $this = $(this);
                th = $this.find('tr:first').detach();
                trs = $this.find('tr').detach();
                $this.empty();
                $this.append('<thead></thead><tbody></tbody>');
                $this.find('thead').append(th);
                $this.find('tbody').append(trs);
            });

            // Init stupidtable
            $('table.crafteditems').stupidtable();
            setTimeout(function(){ 
                $('.craftablecategory').click();
            }, 1);

        });
    }

   /* End crafter table scripts */

    /* Allow combining DPL results that need to be broken into multiple queries (ie, mobiles). */
    $('.mergetablefrom').find('th').parent().remove();
    $('.mergetableto').append($('.mergetablefrom').find('tr').detach());
    $('.mergetablefrom').remove();

   	/* Automate purge page confirmation */
	if (action === 'purge'){
	    $('button[type="submit"]').click();
	}
	
	/* css selector level 4 spec.  Works in jQuery, but not yet implemented in browsers. */
	$('dl.hideEmpty:not(:has(dd))').hide();
}());