User:V111P/js/wlhFilters.js

From Wikipedia, the free encyclopedia
< User:V111P‎ | js
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
// 2015-03-26
// Note: You must include Template: or Category: before template and category names
// Note: It's not recommended to be used for templates used on large number of pages, or categories with large number of pages

if (mw.config.get('wgCanonicalSpecialPageName') == 'Whatlinkshere')
$(function () {
  var helpPage = '//en.wikipedia.org/wiki/User:V111P/js/What Links Here link filter';
  var spanId = 'vWLHFilter_span';
  var apiOptionNames = [['embeddedin', 'ei'], ['backlinks', 'bl'], ['categorymembers', 'cm']];
  var optionLabels = ['transcluding', 'linking to', 'from category'];
  var $span, $input, $select;


  $('#' + spanId).remove();

  $span = $('<span/>').attr('id', spanId)
    .append(' | Hide pages ')
    .append($('<form id="sart" style="display:inline;">'
              + '<select></select>: '
              + '<input type="text" size="40"/> '
              + '<input type="submit" value="Go"/> (<a href="'
              + helpPage + '" target="_blank">?</a>)</form>'))
    .appendTo($('div#mw-content-text form + fieldset'));

  $input = $span.find('input');
  $select = $span.find('select');
  $.each(optionLabels, function (i, val) {
    $select.append($('<option>' + val + '</option>'));
  });


  $span.find('form').submit(function (e) {
    e.preventDefault();
    pageNames = $input.val().split('|');
    apiOptionNum = $select[0].selectedIndex;
    request(pageNames, apiOptionNames[apiOptionNum]);
  });

  // add a 5000 link next to the 500 link
  var limit500Lnk = $('#mw-content-text > a')
    .filter(function() { return $.text([this]) == '500'; });
  if (limit500Lnk[0]) {
    limit500Lnk.after(' | <a title="' + limit500Lnk.attr('title') + '" href="'
        + limit500Lnk.attr('href').replace(/limit=500/, 'limit=5000') + '">5000</a>');
  }

  function request(pageNames, apiParams, continueFrom) {
    var longName = apiParams[0];
    var shortName = apiParams[1];
    $.ajax({
      url: '/w/api.php?action=query&list=' + longName + '&format=json&rawcontinue=&'
           + shortName + 'limit=max&' + shortName + 'title='
           + encodeURIComponent(pageNames[0]) + (continueFrom ? '&' + shortName + 'continue=' + continueFrom : ''),
      dataType: 'json',
      error: function () {
        $('div#mw-content-text form > fieldset').append(' Error. ');
      },
      success: function (result) {
        var console = window.console || {log: function () {}, error: function (s) {alert(s);}};

        if (!result || !result.query || !result.query[longName]) {
          console.error('What Links Here Script error: No (expected) results received from server.');
          return;
        }

        var p = result.query[longName];
        var titles = [];
        for (var i = 0; i < p.length; i++) {
          titles.push(p[i].title);
        }
        var elsToRemove = [];

        console.log('using page: %s', pageNames[0]);
        console.log('links before removal: %d', $('ul#mw-whatlinkshere-list li').length);
        $('ul#mw-whatlinkshere-list li').each(function (i, li) {
          var lnk = $(li).find('a').first();
          if ($.inArray($(lnk).text(), titles) > -1) {
            elsToRemove.push(li);
          }
        });
        console.log('removed: %d', elsToRemove.length);
        $(elsToRemove).remove();
        console.log('links after removal: %d', $('ul#mw-whatlinkshere-list li').length);

        if (result['query-continue']) {
          var nextContinueFrom = result['query-continue'][longName][shortName + 'continue'];
          console.log('Continue from: %s', nextContinueFrom);
          request(pageNames, apiParams, nextContinueFrom);
        }
        else {
          pageNames.shift();
          if (pageNames.length > 0)
            request(pageNames, apiParams);
        }

      }   // success()
    }); // $.ajax()
  } // request()
});