User:Slate/common.js: Difference between revisions

From Inkipedia, the Splatoon wiki
mNo edit summary
(splashtag)
 
(18 intermediate revisions by 2 users not shown)
Line 1: Line 1:
/* <syntaxhighlight lang="javascript"> */
/* For splashtag testing */
/*
function openTab(evt, tabName) {
* ADVANCED AJAX AUTO-REFRESHING ARTICLES
    var i, tabcontent, tablinks;
*
     tabcontent = document.getElementsByClassName("tabcontent");
* Original by pcj of Wowpedia
     for (i = 0; i < tabcontent.length; i++) {
* Maintenance, cleanup, style and bug fixes by:
        tabcontent[i].style.display = "none";
*  Grunny (http://c.wikia.com/wiki/User:Grunny)
*  Kangaroopower (http://c.wikia.com/wiki/User:Kangaroopower)
*  Cqm (http://c.wikia.com/wiki/User:Cqm)
*
* Directly copied from http://wowwiki.wikia.com/MediaWiki:AjaxRC/code.js
*/
/*jshint browser:true, camelcase:true, curly:true, eqeqeq:true, immed:true, jquery:true, latedef:true, newcap:true, noarg:true, noempty:true, nonew:true, quotmark:single, trailing:true, undef:true, unused:true, onevar:true */
/*global mediaWiki:true, Wikia:true */
(function (window, $, mw, Wikia) {
  'use strict';
  var config = mw.config.get([
      'stylepath',
      'wgAction',
      'wgCanonicalSpecialPageName',
      'wgPageName'
     ]),
  // use common file as it's very likely to be already cached by user
  // used in oasis sidebar loading, preview modal, etc.
    ajaxIndicator = window.ajaxIndicator || config.stylepath + '/common/images/ajax.gif',
     ajaxTimer,
    refreshText = typeof window.AjaxRCRefreshText === 'string' ? window.AjaxRCRefreshText : 'AJAX',
    refreshHover = typeof window.AjaxRCRefreshHoverText === 'string' ? window.AjaxRCRefreshHoverText : 'Enable auto-refreshing page loads',
    ajRefresh = window.ajaxRefresh || 60000,
    ajPages = window.ajaxPages || ['Special:RecentChanges'],
    RecentChangesLocal,
  // don't load on these values of wgAction
  // @todo check if markpatrolled should be here
    disallowActions = [
      'delete',
      'edit',
      'protect',
      'revisiondelete'
    ];
  function storage(setTo) {
    if (localStorage.getItem('AjaxRC-refresh') === null) {
      localStorage.setItem('AjaxRC-refresh', true);
     }
     }
     tablinks = document.getElementsByClassName("tablinks");
     if (setTo === false) {
     for (i = 0; i < tablinks.length; i++) {
      localStorage.setItem('AjaxRC-refresh', false);
        tablinks[i].className = tablinks[i].className.replace(" active", "");
     } else if (setTo === true) {
      localStorage.setItem('AjaxRC-refresh', true);
     }
     }
     document.getElementById(tabName).style.display = "block";
     return JSON.parse(localStorage.getItem('AjaxRC-refresh'));
    evt.currentTarget.className += " active";
  }
}
 
/* Directly from http://wow.gamepedia.com/MediaWiki:Common.js (changed load url) */
  /**
function setStoredValue(key, value, expiredays) {
  * Main function to start the Auto-refresh process
  if (typeof(localStorage) == "undefined") {
  */
     var exdate = new Date();
  function preloadAJAXRL() {
    exdate.setDate(exdate.getDate() + (expiredays ? expiredays : 30));
    // monobook
    document.cookie = key + "=" + escape(value) + ";expires=" + exdate.toGMTString();
    var $appTo = $('.firstHeading').length ? $('.firstHeading') :
  } else {
    // most oasis pages
    try {
      ($('#WikiaPageHeader').length ? $('#WikiaPageHeader') :
      localStorage[key] = value;
    // most oasis special pages
     } catch (e) {
        ($('#AdminDashboardHeader').length ? $('#AdminDashboardHeader > h1') : false)),
       // Usually QUOTA_EXCEEDED_ERR
      $checkbox = $('<span id="ajaxRefresh"></span>')
        .css({ 'font-size': 'xx-small', 'line-height': '100%', 'margin-left': '5px' })
        .append(
          $('<label id="ajaxToggleText" for="ajaxToggle"></label>')
            .css({ 'border-bottom': '1px dotted', 'cursor': 'help' })
            .attr('title', refreshHover).text(refreshText + ':'),
          $('<input type="checkbox" id="ajaxToggle">').css({ 'margin-bottom': 0 }),
          $('<span id="ajaxLoadProgress"></span>').css('display', 'none').append(
            $('<img>').css({ 'vertical-align': 'baseline', 'float': 'none', 'border': 0 })
              .attr('src', ajaxIndicator).attr('alt', 'Refreshing page')
          )
        ),
      $throbber;
    // fallback for pages with profile masthead
    if ($appTo === false) {
      $('#WikiaArticle').prepend($checkbox);
    } else {
      $appTo.append($checkbox);
    }
    $throbber = $appTo.find('#ajaxLoadProgress');
    $(document).ajaxSend(function (event, xhr, settings) {
      if (location.href === settings.url) {
        $throbber.show();
      }
     }).ajaxComplete(function (event, xhr, settings) {
      var $collapsibleElements = $('#mw-content-text').find('.mw-collapsible'),
        ajCallAgain = window.ajaxCallAgain || [],
        i;
      if (location.href === settings.url) {
        $throbber.hide();
        if ($collapsibleElements.length) {
          $collapsibleElements.makeCollapsible();
        }
        if (config.wgCanonicalSpecialPageName === 'Recentchanges') {
          mw.special.recentchanges.init();
          if ($('.mw-recentchanges-table').find('.WikiaDropdown').length) {
            RecentChangesLocal.init();
          }
        }
        if (config.wgCanonicalSpecialPageName === 'WikiActivity') {
          window.WikiActivity.init();
        }
        for (i = 0; i < ajCallAgain.length; i++) {
          ajCallAgain[i]();
        }
      }
     });
    $('#ajaxToggle').click(toggleAjaxReload);
    $('#ajaxToggle').attr('checked', storage());
    if (storage()) {
       loadPageData();
     }
     }
   }
   }
}
  /**
 
  * Turn refresh on and off by toggling the checkbox
function getStoredValue(key, defaultValue) {
  */
  if (typeof(localStorage) == "undefined") {
  function toggleAjaxReload() {
    if (document.cookie && document.cookie.length) {
    if ($('#ajaxToggle').prop('checked') === true) {
       var varr = document.cookie.match("(?:^|;)\\s*" + key + "=([^;]*)");
      storage(true);
       if (varr.length == 2)  
       loadPageData();
        return varr[1];
    } else {
      storage(false);
       clearTimeout(ajaxTimer);
     }
     }
    return defaultValue;
   }
   }
  return localStorage[key] === null ? defaultValue : localStorage[key];
  /**
}
  * Does the actual refresh
 
  */
// AJAX RC
  function loadPageData() {
var ajaxPages = {"Special:RecentChanges" : 1};
    var $temp = $('<div>');
var ajaxRCOverride = false;
var rcRefresh = 120000;
    $temp.load(location.href + ' #mw-content-text', function () {
 
      var $newContent = $temp.children('#mw-content-text');
function ajaxRC() {
  appTo = $(".firstHeading");
      if ($newContent.length) {
  appTo.append('&nbsp;<span style="font-size: xx-small; border-bottom: 1px dotted; cursor:help;" title="Automatically refresh the current page every ' + Math.floor(rcRefresh/1000) + ' seconds">Auto-refresh:</span><input type="checkbox" id="autoRefreshToggle"><span style="position:relative; top:5px; left:5px;" id="autoRefreshProgress"><img src="https://cdn.wikimg.net/en/splatoonwiki/images/1/15/Blue_vs_orange_bounce.gif" border="0" alt="AJAX operation in progress" /></span>');
        $('#mw-content-text').replaceWith($newContent);
  $("#autoRefreshToggle").click(function() {
      }
    setStoredValue("ajaxRC", $("#autoRefreshToggle").is(":checked") ? "on" : "off");
    loadRCData();
      ajaxTimer = setTimeout(loadPageData, ajRefresh);
  });
     });
  $("#autoRefreshProgress").hide();
    $temp.remove();
  if (getStoredValue("ajaxRC") == "on" || ajaxRCOverride) {
    $("#autoRefreshToggle").attr("checked", "checked");
     setTimeout("loadRCData();", rcRefresh);
   }
   }
}
  /**
function handleAutocollapse(root) {
   * Load the script on specific pages
   var $ct = root.find(".mw-collapsible");
   * and only on certain values for wgAction (see disallowActions above)
   var $es = $ct.filter(".mw-autocollapse").not($ct.first()).not(".mw-collapsed, .mw-uncollapsed, .mw-expanded");
  */
   $es.filter(function() {
   $(function () {
    var link = $(this).find(".mw-collapsible-toggle a");
     if (
     if (link.length)
       $.inArray(config.wgPageName, ajPages) !== -1 && $('#ajaxToggle').length === 0 &&
       link.first().click();
      $.inArray(config.wgAction, disallowActions) === -1
   
     ) {
    return !link.length;
       preloadAJAXRL();
  }).toggleClass("mw-collapsed mw-autocollapse");
    }
}
function loadRCData() {
  if (!$("#autoRefreshToggle").is(":checked"))
    return;
 
  $('#autoRefreshProgress').show();
  $(article).load(location.href + " "+article+" > *", function (data) {
    handleAutocollapse($(article));
    $(article + " .mw-collapsible").makeCollapsible();
    $('#autoRefreshProgress').hide();
     if ($("#autoRefreshToggle").is(":checked"))  
       setTimeout("loadRCData();", rcRefresh);
   });
   });
}
  /**
 
  * Temp Hack: copy the RC filter JS since it can't be accessed
$(function() {
  * @source <https://github.com/Wikia/app/blob/dev/extensions/wikia/RecentChanges/js/RecentChanges.js>
  article = "#bodyContent";
  */
  var pagename = mw.config.get('wgPageName');
  RecentChangesLocal = {
  if (pagename && ajaxPages.hasOwnProperty(pagename) && !$("#autoRefreshToggle").length)  
    init: function () {
    ajaxRC();
      this.$table = $('.mw-recentchanges-table');
});
      this.$dropdown = this.$table.find('.WikiaDropdown');
      this.$submit = this.$table.find('input[type="submit"]');
      this.$submit.on('click.RecentChangesDropdown', $.proxy(this.saveFilters, this));
      this.$submit.removeAttr('disabled'); //FF clean
      this.dropdown = new Wikia.MultiSelectDropdown(this.$dropdown);
      this.dropdown.on('change', $.proxy(this.onChange, this));
    },
    saveFilters: function (event) {
      var self = this;
      event.preventDefault();
      self.dropdown.disable();
      self.$submit.attr('disabled', 'disabled');
      if (self.dropdown.getSelectedValues().length === 0) {
        self.dropdown.doSelectAll(true);
      }
      $.nirvana.sendRequest({
        controller: 'RecentChangesController',
        method: 'saveFilters',
        data: {
          filters: self.dropdown.getSelectedValues()
        },
        type: 'POST',
        format: 'json',
        callback: function (data) {
          window.location.reload();
        }
      });
    }
  };
} (this, jQuery, mediaWiki, Wikia));
/* </syntaxhighlight> */

Latest revision as of 18:32, 23 April 2023

/* For splashtag testing */
function openTab(evt, tabName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(tabName).style.display = "block";
    evt.currentTarget.className += " active";
}

/* Directly from http://wow.gamepedia.com/MediaWiki:Common.js (changed load url) */
function setStoredValue(key, value, expiredays) {
  if (typeof(localStorage) == "undefined") {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + (expiredays ? expiredays : 30));
    document.cookie = key + "=" + escape(value) + ";expires=" + exdate.toGMTString();
  } else {
    try {
      localStorage[key] = value;
    } catch (e) {
      // Usually QUOTA_EXCEEDED_ERR
    }
  }
}

function getStoredValue(key, defaultValue) {
  if (typeof(localStorage) == "undefined") {
    if (document.cookie && document.cookie.length) {
      var varr = document.cookie.match("(?:^|;)\\s*" + key + "=([^;]*)");
      if (varr.length == 2) 
        return varr[1];
    }
    return defaultValue;
  }
  return localStorage[key] === null ? defaultValue : localStorage[key];
}

// AJAX RC
var ajaxPages = {"Special:RecentChanges" : 1};
var ajaxRCOverride = false;
var rcRefresh = 120000;

function ajaxRC() {
  appTo = $(".firstHeading");
  appTo.append('&nbsp;<span style="font-size: xx-small; border-bottom: 1px dotted; cursor:help;" title="Automatically refresh the current page every ' + Math.floor(rcRefresh/1000) + ' seconds">Auto-refresh:</span><input type="checkbox" id="autoRefreshToggle"><span style="position:relative; top:5px; left:5px;" id="autoRefreshProgress"><img src="https://cdn.wikimg.net/en/splatoonwiki/images/1/15/Blue_vs_orange_bounce.gif" border="0" alt="AJAX operation in progress" /></span>');
  $("#autoRefreshToggle").click(function() {
    setStoredValue("ajaxRC", $("#autoRefreshToggle").is(":checked") ? "on" : "off");
    loadRCData();
  });
  $("#autoRefreshProgress").hide();
  if (getStoredValue("ajaxRC") == "on" || ajaxRCOverride) {
    $("#autoRefreshToggle").attr("checked", "checked");
    setTimeout("loadRCData();", rcRefresh);
  }
}
function handleAutocollapse(root) {
  var $ct = root.find(".mw-collapsible");
  var $es = $ct.filter(".mw-autocollapse").not($ct.first()).not(".mw-collapsed, .mw-uncollapsed, .mw-expanded");
  $es.filter(function() {
    var link = $(this).find(".mw-collapsible-toggle a");
    if (link.length) 
      link.first().click();
    
    return !link.length;
  }).toggleClass("mw-collapsed mw-autocollapse");
}
function loadRCData() {
  if (!$("#autoRefreshToggle").is(":checked")) 
    return;
  
  $('#autoRefreshProgress').show();
  $(article).load(location.href + " "+article+" > *", function (data) {
    handleAutocollapse($(article));
    $(article + " .mw-collapsible").makeCollapsible();
    $('#autoRefreshProgress').hide();
    if ($("#autoRefreshToggle").is(":checked")) 
      setTimeout("loadRCData();", rcRefresh);
  });
}

$(function() {
  article = "#bodyContent";
  var pagename = mw.config.get('wgPageName');
  if (pagename && ajaxPages.hasOwnProperty(pagename) && !$("#autoRefreshToggle").length) 
    ajaxRC();
});