Notice: Firmware Links Under Maintenance We are currently undergoing maintenance on all firmware links. If any links are inaccessible, please email or contact Tech Support for the firmware. We appreciate your patience during the maintenance, thank you for your understanding.

Difference between revisions of "User:JP/common.js"

 
(8 intermediate revisions by the same user not shown)
Line 1: Line 1:
// ==UserScript==
+
var tfConfig = {
// @name           Wikipedia Table filter
+
        base_path: 'tablefilter/',
// @namespace      benibela
+
        alternate_rows: true,
// @include        http://*.wikipedia.org/wiki/*
+
        btn_reset: true,
// ==/UserScript==
+
        rows_counter: true,
 +
        loader: true,
 +
        status_bar: true,
 +
        paging: true,
 +
        col_0: 'select',
 +
        col_1: 'select',
 +
        col_2: 'select',
 +
        extensions:[{
 +
            name: 'sort',
 +
            types: [
 +
                'string', 'string', 'number',
 +
                'number', 'number', 'number',
 +
                'number', 'number', 'number'
 +
            ]
 +
        }]
 +
    };
 +
    var tf = new TableFilter(document.querySelector('#demo'), tfConfig);
 +
 
 +
    // Subscribe to events
 +
    // Format cell at initialization
 +
    tf.emitter.on(['initialized'], parseRows);
 +
    // Format cell upon filtering
 +
    tf.emitter.on(['cell-processed'], formatCell);
  
 +
    tf.init();
  
var tables = document.getElementsByClassName("wikitable");
+
    // Process all rows on start-up
var hiddenLists = new Array();
+
    function parseRows(tf){
var hiddenNames = new Array();
+
        var cellIndex = 3; // POP column
var hiddenPropertiesDisplay = "";
+
        var rowsIdx = tf.getValidRows();
 +
        rowsIdx.forEach(function(idx){
 +
            var row = tf.tbl.rows[idx];
 +
            var cell = row.cells[cellIndex];
 +
            formatCell(tf, cellIndex, cell);
 +
        });
 +
    }
  
if (tables.length > 0) {
+
    // Format passed cell with custom logic
 
+
    function formatCell(tf, cellIndex, cell){
function stringContains(str, list) {
+
        if(cellIndex !== 3){
  for (var i=0;i<list.length;i++)
+
            return;
    if (str == list[i] || (list[i] > 3 && str.indexOf(list[i]) >= 0)) return true;
+
        }
  return false;
+
        var cellData = parseInt(cell.innerHTML, 10);
}
 
  
function arrayIndexOf(ar, v) {
+
        // some rows do not contain a numeric value
  for (var i=0;i<ar.length;i++) if (ar[i] == v) return i;
+
        if(isNaN(cellData)){
  return -1;
+
            return;
}
+
        }
function arrayContains(ar, v) {
 
  for (var i=0;i<ar.length;i++) if (ar[i] == v) return true;
 
  return false;
 
}
 
  
function updateHideText(){
+
         if(cellData >= 100000){
  for (var i=0;i<hiddenLists.length;i++)
+
            cell.style.backgroundColor = '#ff0000';
    hiddenLists[i].innerHTML = "<b>Hidden names:</b> " + (hiddenNames.join(", ")).replace("<", "&lt;")+
+
         } else if(cellData < 100000 && cellData >= 50000) {
                              "<br>"+"<b>Hidden properties: </b>" + (hiddenPropertiesDisplay).replace("<", "&lt;");
+
            cell.style.backgroundColor = '#3399ff';
}
+
         } else {
function updateHide(){
+
            cell.style.backgroundColor = '#cfff33';
  for (var i=0;i<tables.length;i++) {
 
    for (var r=0;r<tables[i].rows.length;r++)
 
      if (tables[i].rows[r].cells[0] && ( stringContains(tables[i].rows[r].cells[0].textContent, hiddenNames)) )
 
     
 
         tables[i].rows[r].style.display="none";
 
  }
 
  updateHideText();
 
}
 
 
 
function newButton(){
 
  var deleteThis = document.createElement("a");
 
  deleteThis.textContent = "x";
 
  deleteThis.addEventListener("click", function(e){
 
    var cell = e.target.parentNode;
 
    var row = cell.parentNode;
 
    if (cell == row.cells[0]) {
 
      if (cell.textContent == "x") {
 
        row.style.display = "none";  //empty row (repeated table headers, wikipedias idea of filtering)
 
      } else if (!arrayContains(hiddenNames, cell.textContent)) {
 
        hiddenNames.push(cell.textContent);
 
         updateHide();
 
      }
 
    } else if (row.parentNode.nodeName == "THEAD" || row.parentNode.nodeName == "TFOOT"
 
              || (row.parentNode.nodeName == "TBODY" && row.parentNode.parentNode.rows[0] == row)) {
 
      if (hiddenPropertiesDisplay != "") hiddenPropertiesDisplay += ", ";
 
      hiddenPropertiesDisplay += " Column("+cell.textContent+") ";
 
     
 
      var table = row.parentNode.parentNode; //tbody actually
 
      var pos = arrayIndexOf(row.cells,cell);
 
      for (var i=0;i<table.rows.length;i++)
 
         table.rows[i].cells[pos].style.display = "none";
 
    } else {
 
      var table = row.parentNode; //tbody actually
 
      var pos = arrayIndexOf(row.cells,cell);
 
      var remove = cell.textContent;
 
      for (var i=0;i<table.rows.length;i++)
 
        if (table.rows[i].cells[pos] && table.rows[i].cells[pos].textContent == remove) {
 
          if (!arrayContains(hiddenNames, table.rows[i].cells[0].textContent))
 
            hiddenNames.push(table.rows[i].cells[0].textContent);
 
 
         }
 
         }
      if (hiddenPropertiesDisplay != "") hiddenPropertiesDisplay += ", ";
 
      if (table.nodeName == "TBODY") table = table.parentNode;
 
      hiddenPropertiesDisplay += table.rows[0].cells[pos].textContent + " = " + remove.substr(0, remove.length-1);
 
     
 
      updateHide();
 
 
     }
 
     }
  });
+
// ==UserScript==
  deleteThis.className = "delete-this-button";
+
// @name        Wikitable filter
  return deleteThis;
+
// @description Filter for wiki tables using the jQuery tablesorter filter widget
}
+
// @include    *wiki*
 +
// @grant      none
 +
// @require    http://code.jquery.com/jquery-1.11.3.min.js
 +
// @require    https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.22.1/js/jquery.tablesorter.min.js
 +
// @require    https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.22.1/js/jquery.tablesorter.widgets.js
 +
// @version    1.1
 +
// @namespace https://greasyfork.org/users/12797
 +
// ==/UserScript==
 +
 
 +
// Constants
 +
 
 +
SHOW_FILTERS_CLASS = "wikitable_show_filters";
 +
FILTERED_CLASS = "wikitable_filter_filtered";
  
setTimeout(function(){
+
// Globals
for (var i=0;i<tables.length;i++) {
+
style_initialised = false;
  for (var r=0;r<tables[i].rows.length;r++)
 
    for (var c=0;c<tables[i].rows[r].cells.length;c++) {
 
      tables[i].rows[r].cells[c].appendChild(newButton());
 
    }
 
  var temp = document.createElement("div");
 
  tables[i].parentNode.insertBefore(temp, tables[i].nextSibling);
 
  hiddenLists.push(temp);
 
}}, 100);
 
  
var head = document.getElementsByTagName("head")[0];
+
// Functions
var ele = head.appendChild(window.document.createElement("style"));
 
ele.innerHTML = ".delete-this-button {flush: right; display: inline-block; 0; bottom: 0; color: red; cursor: pointer}";
 
  
 +
showFilters = function() {
 +
  var tbl = $(this).next(".wikitable");
 +
  tbl.addClass("tablesorter");
 +
  tbl.tablesorter({
 +
    "widgets": ["filter"],
 +
    "widgetOptions": {
 +
      "filter_filteredRow": FILTERED_CLASS
 +
    }
 +
  });
 +
  $(this).hide();
 +
  return false;
 
}
 
}
/*
 
SMALLER TEMPLATES
 
Description: Makes maintenance templates such as {cleanup} appear smaller so that they take up less space.
 
*/
 
  
function smallerTemplates()
+
addShowFiltersButton = function() {
{
+
  var btn = $("<button/>",
mw.util.addCSS('\
+
  { "type": "button",
.mbox-image div, .mbox-image .image, .mbox-imageright { display: none; }\
+
    "class": SHOW_FILTERS_CLASS,
table.ambox { margin: 0 15%; }\
+
    "html": "\u2261 Filters" }
table.ambox { border-radius: 0px; }\
+
  );
');
+
  btn.click(showFilters);
+
  return btn;
formatBoxes('ambox-content');
 
formatBoxes('ambox-delete');
 
formatBoxes('ambox-move');
 
formatBoxes('ambox-notice');
 
formatBoxes('ambox-protection');
 
formatBoxes('ambox-style');
 
 
}
 
}
  
function formatBoxes(className)
+
initTables = function(tbl) {
{
+
  if (tbl.length > 0) {
mw.util.addCSS('.' + className + ' td { padding: 0 0.25em !important; font-size: 10px !important; line-height: 1.5em; }');
+
    if (!style_initialised) {
$('.' + className).each(function() { boxInit($(this)); });
+
      // Add our stylesheet
 +
      var styleElem = document.createElement('style');
 +
      document.head.appendChild(styleElem);
 +
      styleSheet = styleElem.sheet;
 +
      styleSheet.insertRule("tr."+FILTERED_CLASS+" { display: none; }", 0);
 +
      style_initialised = true;
 +
    }
 +
    // Add button to show the filters
 +
    tbl.before(addShowFiltersButton);
 +
  }
 
}
 
}
  
function boxInit(box)
+
// Main
{
 
// Collapse the box, using Wikipedia's own "hide" button.
 
var collapseButton = $('.collapseButton:first > a:first', box);
 
if (collapseButton.text() == 'hide') collapseButton.click();
 
}
 
  
if (mw.util.getParamValue('disable') != 'smalltemplates' && ((mw.config.get('wgCanonicalNamespace') == '' || mw.config.get('wgPageName') == 'User:Gary_King/Sandbox' || mw.config.get('wgPageName') == 'Wikipedia:Template_messages/Cleanup') && mw.config.get('wgAction') == 'view')) $(smallerTemplates);
+
// Check if there are wiki tables on this page in the first place
 +
var tbl = $("table.wikitable");
 +
// Initialise them (if necessary)
 +
initTables(tbl.has("thead").has("tbody"));
 +
// Register observer that initialises tables that were modified to fit our
 +
// criteria.
 +
var tblMutationObserver = new MutationObserver(function(mutations) {
 +
  var mutatedNodes = new Array();
 +
  mutations.forEach(function(mutation) {
 +
    mutatedNodes.push(mutation.target);
 +
  });
 +
  var jqMutatedTbl = $(mutatedNodes);
 +
  jqMutatedTbl = jqMutatedTbl.filter(".wikitable").has("thead").has("tbody");
 +
  jqMutatedTbl = $.unique(jqMutatedTbl);
 +
  // Do not initialise tables twice!
 +
  jqMutatedTbl = jqMutatedTbl.not(".tablesorter");
 +
  if (jqMutatedTbl.length <= 0) {
 +
    return null;
 +
  }
 +
  console.log(jqMutatedTbl);
 +
  initTables(jqMutatedTbl);
 +
});
 +
tbl.each(function(index, node) {
 +
  tblMutationObserver.observe(
 +
    // node to be observed
 +
    node,
 +
    // options
 +
    { "childList": true }
 +
  );
 +
});

Latest revision as of 16:43, 4 August 2016

 var tfConfig = {
        base_path: 'tablefilter/',
        alternate_rows: true,
        btn_reset: true,
        rows_counter: true,
        loader: true,
        status_bar: true,
        paging: true,
        col_0: 'select',
        col_1: 'select',
        col_2: 'select',
        extensions:[{
            name: 'sort',
            types: [
                'string', 'string', 'number',
                'number', 'number', 'number',
                'number', 'number', 'number'
            ]
        }]
    };
    var tf = new TableFilter(document.querySelector('#demo'), tfConfig);

    // Subscribe to events
    // Format cell at initialization
    tf.emitter.on(['initialized'], parseRows);
    // Format cell upon filtering
    tf.emitter.on(['cell-processed'], formatCell);

    tf.init();

    // Process all rows on start-up
    function parseRows(tf){
        var cellIndex = 3; // POP column
        var rowsIdx = tf.getValidRows();
        rowsIdx.forEach(function(idx){
            var row = tf.tbl.rows[idx];
            var cell = row.cells[cellIndex];
            formatCell(tf, cellIndex, cell);
        });
    }

    // Format passed cell with custom logic
    function formatCell(tf, cellIndex, cell){
        if(cellIndex !== 3){
            return;
        }
        var cellData = parseInt(cell.innerHTML, 10);

        // some rows do not contain a numeric value
        if(isNaN(cellData)){
            return;
        }

        if(cellData >= 100000){
            cell.style.backgroundColor = '#ff0000';
        } else if(cellData < 100000 && cellData >= 50000) {
            cell.style.backgroundColor = '#3399ff';
        } else {
            cell.style.backgroundColor = '#cfff33';
        }
    }
// ==UserScript==
// @name        Wikitable filter
// @description Filter for wiki tables using the jQuery tablesorter filter widget
// @include     *wiki*
// @grant       none
// @require     http://code.jquery.com/jquery-1.11.3.min.js
// @require     https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.22.1/js/jquery.tablesorter.min.js
// @require     https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.22.1/js/jquery.tablesorter.widgets.js
// @version     1.1
// @namespace https://greasyfork.org/users/12797
// ==/UserScript==

// Constants

SHOW_FILTERS_CLASS = "wikitable_show_filters";
FILTERED_CLASS = "wikitable_filter_filtered";

// Globals
style_initialised = false;

// Functions

showFilters = function() {
  var tbl = $(this).next(".wikitable");
  tbl.addClass("tablesorter");
  tbl.tablesorter({
    "widgets": ["filter"],
    "widgetOptions": {
      "filter_filteredRow": FILTERED_CLASS
    }
  });
  $(this).hide();
  return false;
}

addShowFiltersButton = function() {
  var btn = $("<button/>",
  { "type": "button",
    "class": SHOW_FILTERS_CLASS,
    "html": "\u2261 Filters" }
  );
  btn.click(showFilters);
  return btn;
}

initTables = function(tbl) {
  if (tbl.length > 0) {
    if (!style_initialised) {
      // Add our stylesheet
      var styleElem = document.createElement('style');
      document.head.appendChild(styleElem);
      styleSheet = styleElem.sheet;
      styleSheet.insertRule("tr."+FILTERED_CLASS+" { display: none; }", 0);
      style_initialised = true;
    }
    // Add button to show the filters
    tbl.before(addShowFiltersButton);
  }
}

// Main

// Check if there are wiki tables on this page in the first place
var tbl = $("table.wikitable");
// Initialise them (if necessary)
initTables(tbl.has("thead").has("tbody"));
// Register observer that initialises tables that were modified to fit our
// criteria.
var tblMutationObserver = new MutationObserver(function(mutations) {
  var mutatedNodes = new Array();
  mutations.forEach(function(mutation) {
    mutatedNodes.push(mutation.target);
  });
  var jqMutatedTbl = $(mutatedNodes);
  jqMutatedTbl = jqMutatedTbl.filter(".wikitable").has("thead").has("tbody");
  jqMutatedTbl = $.unique(jqMutatedTbl);
  // Do not initialise tables twice!
  jqMutatedTbl = jqMutatedTbl.not(".tablesorter");
  if (jqMutatedTbl.length <= 0) {
    return null;
  }
  console.log(jqMutatedTbl);
  initTables(jqMutatedTbl);
});
tbl.each(function(index, node) {
  tblMutationObserver.observe(
    // node to be observed
    node,
    // options
    { "childList": true }
  );
});