MediaWiki:Common.js

From JoJo's Bizarre Encyclopedia - JoJo Wiki
Revision as of 00:52, 22 March 2020 by MetallicKaiser (talk | contribs)
Jump to navigation Jump to search

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.
/* Any JavaScript here will be loaded for all users on every page load. */
syntaxHighlighterConfig = {
	headingColor: "#44466d78", //dark gray
	hrColor: "#44466d78", //dark gray
	boldOrItalicColor: "#44466d78", //dark blue
    tableColor: "#4c3e6563", //purple
    externalLinkColor: "#3792925c", //teal
    templateColor: "#c1a53c82", //brown
    parameterColor: "#D25A5A94", //red
    wikilinkColor: "#457ec78a", //cerulean blue
    tagColor: "#ba5ea070", //pink
    listOrIndentColor: "#A5A5A578", //gray
    entityColor: "#A5A5A578", //gray
    commentColor: "#97a997a1", //gray-green
};

/* Menu 
$(document).ready( function() {
  var topnav = $('#mw-topnavigation');
  $('#p-personal').after( topnav.html() );
  topnav.remove();
});*/

// BEGINNING: JavaScript for placing the fair use rationale template inside the summary box on [[Special:Upload]]. Code by "[[wikipedia:User:Pinky49]]", created and coded specifically for [[wikia:c:cdnmilitary|Duty & Valour]].
 
/*function FairUseRationale() {
	if((wgPageName == 'Special:Upload' || wgPageName == 'Special:MultipleUpload') && document.getElementById('wpDestFile').value == '') {
		document.getElementById('wpUploadDescription').value = '==Source==\n\n==Licensing==\n{{Fairuse}}';
	}
}
jQuery(document).ready(FairUseRationale);*/

/* sliders using jquery by User:Tierrie
mw.loader.using( ['jquery.cookie']);
 
//wsl.loadScript("http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js");
//wsl.loadScript("http://dragonage.wikia.com/index.php?title=MediaWiki:Jquery-ui.min.js&action=raw&ctype=text/javascript");
mw.loader.using( ['jquery.ui.tabs'], function() {
  $( "[class^=portal_vtab]" ).tabs().addClass( "ui-tabs-vertical ui-helper-clearfix" );
  $( "[class^=portal_vtab] li" ).removeClass( "ui-corner-top" ).addClass( "ui-corner-left" );
 
  var $tabs = $("#portal_slider").tabs({ fx: {opacity:'toggle', duration:100} } );
  $("[class*=portal_sliderlink]").click(function() { // bind click event to link
    $tabs.tabs('select', this.className.match(/portal_sliderlink-(\d+)/)[1]);
    console.log("Sliding to " + this.className.match(/portal_sliderlink-(\d+)/)[1]);
    return false;
  });
  $('#portal_next').click(function() {
    $tabs.tabs('select', ($tabs.tabs('option', 'selected') == ($tabs.tabs('length'))-1) ? 0 : $tabs.tabs('option', 'selected') + 1 ); // switch to next tab
    return false;
  });
  $('#portal_prev').click(function() { // bind click event to link
    $tabs.tabs('select', ($tabs.tabs('option', 'selected') == 0) ? ($tabs.tabs('length')-1) : $tabs.tabs('option', 'selected') - 1 ); // switch to previous tab
    return false;
  });
});
*/

//<tabber> extension req
//v2.0, 2017, user:fngplg.
//set active tab: https://jojowiki.com/page#activeTab
(function ($){
    var nstarget = window.location.hash.replace('#', '');
    if (nstarget === '') return;
    //convert wiki-utf 2 ansi
    nstarget = nstarget.replace(/\./g, '%');
    nstarget = decodeURIComponent(nstarget).replace(/_/g, ' ');
    //console.log('trgt:'+nstarget);
    $(function(){
        setTimeout(function() {
            var $nt2a = $('.tabberlive>.tabbernav>Li>a[title="' + nstarget + '"]');
            $nt2a.click();
            $nt2a.get(0).scrollIntoView({inline: "nearest"});
        }, 100);//settimeout
    });//doc.rdy    
})(jQuery);

/* [[QuickDiff]] - quickly view any diff link */
 
/*jslint browser, long */
/*global jQuery, mediaWiki, dev */
 
(function ($, mw) {
    "use strict";
 
    // double-run protection
    if (window.quickDiffLoaded) {
        return;
    }
    window.quickDiffLoaded = true;
 
 
    var diffStylesModule = "mediawiki.action.history.diff";
    var i18n;
    var modal;
    var special = {};
 
    // "Special:Diff/12345" and "Special:ComparePages" link detection
    function initSpecialPageStrings() {
        special.diffDefault = mw.util.getUrl("Special:Diff/");
        special.compareDefault = mw.util.getUrl("Special:ComparePages");
 
        var wiki = mw.config.get("wgDBname");
        var storageKeyDiff = "QuickDiff-specialdiff_" + wiki;
        var storageKeyCompare = "QuickDiff-specialcompare_" + wiki;
 
        try {
            special.diff = localStorage.getItem(storageKeyDiff);
            special.compare = localStorage.getItem(storageKeyCompare);
        } catch (ignore) {}
 
        if (special.diff && special.compare) {
            // using stored values - no need for api request
            return;
        }
 
        $.getJSON(mw.util.wikiScript("api"), {
            action: "parse",
            format: "json",
            prop: "text",
            text: "<span class='diff'>[[Special:Diff/]]</span><span class='compare'>[[Special:ComparePages]]</span>",
            disablepp: "" // note: deprecated in MW 1.26, but needed for older versions
        }).done(function (data) {
            var $parsed = $(data.parse.text["*"]);
 
            special.diff = $parsed.find(".diff > a").attr("href");
            special.compare = $parsed.find(".compare > a").attr("href");
 
            try {
                localStorage.setItem(storageKeyDiff, special.diff);
                localStorage.setItem(storageKeyCompare, special.compare);
            } catch (ignore) {}
        });
    }
 
    function getDiffTitle($diff) {
        var prevTitle = $diff.find("#mw-diff-otitle1 a").attr("title");
        var currTitle = $diff.find("#mw-diff-ntitle1 a").attr("title");
 
        if (prevTitle && prevTitle !== currTitle) {
            return i18n("differences-multipage", prevTitle, currTitle).plain();
        }
 
        return i18n("differences", currTitle).plain();
    }
 
    function loadDiff(url) {
        modal.show({
            loading: true,
            title: !modal.visible && i18n("loading").plain()
        });
 
        // add 'action=render' and 'diffonly' params to save some bytes on each request
        url.extend({
            action: "render",
            diffonly: "1"
        });
 
        // pass through 'bot' param for rollback links if it's in use on the current page
        if (mw.util.getParamValue("bot")) {
            url.extend({bot: "1"});
        }
 
        $.when(
            $.get(url.getRelativePath()),
            mw.loader.using(diffStylesModule)
        ).always(function (response) {
            delete url.query.action;
            delete url.query.diffonly;
            delete url.query.bot;
 
            var data = {
                buttons: [{
                    text: i18n("link").plain(),
                    href: url.toString(),
                    attr: {"data-disable-quickdiff": ""}
                }]
            };
            var $diff;
 
            if (typeof response[0] === "string") {
                var $content = $(response[0]);
                $diff = $content.filter("table.diff, #mw-rev-deleted-no-diff");
 
                if (!$diff.length) {
                    // $content is a complete page - see if a diff can be found
                    // needed for diffs from special pages as they ignore action=render URL parameter
                    $diff = $content.find("table.diff");
                }
            }
 
            if ($diff && $diff.length) {
                data.content = $diff;
                data.hook = "quickdiff.ready";
                data.title = getDiffTitle($diff);
            } else {
                data.content = i18n("error", url.toString()).escape();
            }
 
            modal.show(data);
        });
    }
 
    function linkClickHandler(event) {
        // ignore clicks with modifier keys to avoid overriding browser features
        if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
            return;
        }
 
        // ignore click if link has "data-disable-quickdiff" attribute set
        if (event.currentTarget.dataset.disableQuickdiff !== undefined) {
            return;
        }
 
        var url = event.currentTarget.href;
 
        try {
            url = new mw.Uri(url);
        } catch (ignore) {
            // quit if url couldn't be parsed
            // it wouldn't be a link QuickDiff could handle anyway
            return;
        }
 
        // cross-domain requests not supported
        if (url.host !== location.hostname) {
            return;
        }
 
        // no fragment check is to ensure section links/collapsible trigger links on diff pages are ignored
        var hasDiffParam = url.query.diff !== undefined
                && url.fragment === undefined;
        var isSpecialDiffLink = url.path.indexOf(special.diff) === 0
                || url.path.indexOf(special.diffDefault) === 0;
        var isSpecialCompareLink = url.path.indexOf(special.compare) === 0
                || url.path.indexOf(special.compareDefault) === 0;
 
        if (hasDiffParam || isSpecialDiffLink || isSpecialCompareLink) {
            event.preventDefault();
            loadDiff(url);
        }
    }
 
    function init() {
        modal = new mw.libs.QDmodal("quickdiff-modal");
 
        // full screen modal
        mw.util.addCSS("#quickdiff-modal { height: 100%; width: 100% }");
 
        // diff styles module was renamed in MW 1.28
        if (mw.loader.getState("mediawiki.diff.styles")) {
            diffStylesModule = "mediawiki.diff.styles";
        }
 
        // attach to body for compatibility with ajax-loaded content
        // also, one attached event handler is better than hundreds!
        $(document.body).on("click.quickdiff", "a[href]", linkClickHandler);
 
        initSpecialPageStrings();
    }
 
    function initDependencies() {
    	var loadURL = "/index.php?title=";
        var i18nMsgs = new $.Deferred();
        var waitFor = [
            i18nMsgs,
            mw.loader.using(["mediawiki.Uri", "mediawiki.util"])
        ];
 
        if (!(mw.libs.QDmodal && mw.libs.QDmodal.version >= 20180212)) {
            waitFor.push($.ajax({
                cache: true,
                dataType: "script",
                url: loadURL + "MediaWiki:QDmodal.js&action=raw&ctype=text/javascript"
            }));
        }
 
        if (!(window.dev && dev.i18n && dev.i18n.loadMessages)) {
            mw.loader.load(loadURL + "MediaWiki:I18n-js/code.js&action=raw&ctype=text/javascript");
        }
 
        mw.hook("dev.i18n").add(function (i18njs) {
            i18njs.loadMessages("QuickDiff").done(function (i18nData) {
                i18n = i18nData.msg;
                i18nMsgs.resolve();
            });
        });
 
        $.when.apply($, waitFor).done(init);
    }
 
    initDependencies();
 
 
    // collect action links (edit, undo, rollback, patrol) and add them to footer
    mw.hook("quickdiff.ready").add(function (modal) {
        // edit/undo links use "mw-rev-head-action" class on Wikia,
        // and "mw-diff-edit" or "-undo" class on MW 1.24+
        var $buttons = modal.$content.find(".diff-ntitle").find(
            ".mw-rev-head-action, .mw-diff-edit, .mw-diff-undo, .mw-rollback-link, .patrollink"
        ).clone();
 
        // remove text nodes (the brackets around each link)
        $buttons.contents().filter(function (ignore, element) {
            return element.nodeType === 3;
        }).remove();
 
        $buttons.find("a")
            .addClass("qdmodal-button")
            .attr("target", "_blank");
 
        modal.$footer.append($buttons);
    });
}(jQuery, mediaWiki));

window.hotcat_use_category_links = false;

/**
 * @source https://www.mediawiki.org/wiki/Snippets/Open_specific_links_in_new_window
 * @version 2018-09-15
 */
$( function () {
	$( '#mw-content-text' ).on( 'click', '.newwin > a', function () {
		var otherWindow = window.open();
		otherWindow.opener = null;
		otherWindow.location = this;
		return false;
	} );
} );

// Expand
var state =1;
$(function() {
   $('#collapse-global').html($('<a>', {
       'class': 'mw-ui-button',
       text: 'Expand/Collapse All'
   })).click(function() {
       if(state ===0){
       $('.mw-collapsible-toggle-expanded').click();
       state = 1;
       }
       else {
           $('.mw-collapsible-toggle-collapsed').click();
           state = 0;
       }
      }
)});

///////////////////////
// Table Filter/Sort //
///////////////////////
/**
 * @description Table Filter/Sort
 * TODO ?replace by jQuery plugin datatable?
 *
 * @requires $.resource()
 * @requires $.jI18n.en
 * @returns {undefined}
 */
window.initTableFilterSort = function (){ // see MediaWiki:SortTableFilter.js
/* Note: problem is auto-inserted <tbody></tbody> by the browser: must be removed and
   replaced by thead + tbody. jQuery.unwrap() was not successful */
   // add possibly more classes from http://www.javascripttoolbox.com/lib/table/documentation.php
  // Note: only applies to non-nested tables
  var jAutotables = $('table.table-autosort, table.table-autofilter, table-autostripe,table-sorted-asc,table-sorted-desc, table-filtered');
  if (jAutotables.length) {
    // Note: in MediaWiki:SortTableFilter.js 'SortTableFilter_InputFilterTitle' was not recognized
    $.extend(true, $.jI18n, {
      en: {
        SortTableFilter_AutoSortTitle : 'Click to sort',
        SortTableFilter_FilterAllLabel: 'Filter: All',
        SortTableFilter_InputFilterTitle: 'Filter text (case sensitive, uses reg. expressions)'
      },
      de: {
        SortTableFilter_AutoSortTitle : 'Zum Sortieren klicken',
        SortTableFilter_FilterAllLabel: 'Zeige: alle',
        SortTableFilter_InputFilterTitle: 'Text filtern (GROß/klein!, nutzt reg. Ausdrücke)'
      }
    });
    // get sortable/filterable here already otherwise multiple th-filters
    $.getScript(mw.config.get( 'wgServer' ) + mw.config.get( 'wgScript' ) + '?title=MediaWiki:SortTableFilter.js&action=raw&ctype=text/javascript',
      function(){return true;});
    // modify tables to introduce thead structure
    jAutotables.each(function(index){ //TODO simplify code? if()…
      // There may or may not be a tbody around tr. NOTE: $.unwrap() does not work here!
      // Memo: find('tr th') finds th, .parent() retrieves tr! .wrapAll will wrap inside DOM, not in return value! .detach() returns detached
      // OK in FF 3.6 and IE 7-8, not in IE6 (like the old code)
      // FURTHER WORK: Ideally, all normal tr td should remain in a tbody.
      var jThis = $(this),
        jThead = jThis.find('tr th').parent().detach(),
        jTfoot = jThis.find('tr[class=tfoot] td').parent().detach(),// remove it from the DOM
        jTbody = jThis.find('tbody:first');
      if (jTbody.length===0) {
        jThis.children().wrapAll('<tbody/>');
        jTbody = jThis.find('tbody:first');
      }
      jTbody.before($('<thead/>').append(jThead));
      if (jTfoot.length) {
        jTbody.after($('<tfoot/>').append(jTfoot));
      }
      // th with class="input" gives an input field instead of selections
      $(this).find('th[class=input]').append('<input name="filter" title="'+$.resource('SortTableFilter_InputFilterTitle')+'" size="8" onkeyup="Table.filter(this,this)">');
    });// end each()
  } // END if any autotable
};

/**
 * @description: Collapse the TOC using id="toc-autocollapse"
 * @returns {undefined}
 */
window.initTOCautocollapse = function () {
  if ($('#toc-autocollapse').length) {
    $('#togglelink').click();
  }
};// end initTOCautocollapse()