Jump to content

User:Gary/categorize promoted featured items.js

From Wikipedia, the free encyclopedia
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.
// Generated by CoffeeScript 2.1.1
(function() {
  /*
    CATEGORIZE PROMOTED FEATURED ITEMS

    Description: At [[Wikipedia:Featured articles promoted in 2010]], shows the
      section from [[Wikipedia:Featured articles]] under where each featured
      article is placed.
  */
  var CategorizePromoted;

  CategorizePromoted = class CategorizePromoted {
    static categorizePromotedCallback(obj) {
      var article, content, heading, matches, page, pageType, pages, section, sections;
      // Get the first, and should be only, article from the results
      pages = obj['query']['pages'];
      for (page in pages) {
        article = pages[page];
        break;
      }
      pageType = CategorizePromoted.categorizePromotedPageType();
      content = article['revisions'][0]['*'];
      // split "content" by section first
      sections = {};
      // Go through [[WP:FA]] to find sections and their content
      while (content) {
        // 0: whole thing; 1: section title; 2: articles only
        matches = content.match(/\==+(.*?)==+\n([\s\S]*?)\n\n/);
        heading = matches[1];
        section = matches[2];
        sections[heading] = section;
        content = $.trim(content.replace(matches[0], ''));
        if (!content.match('==')) {
          break;
        }
      }
      return $('#bodyContent').find('.wikitable').each((index, element) => {
        var $table, tbody;
        $table = $(element);
        tbody = $table.children(':first');
        // add a new column at the end of the table
        tbody.children(':first').append($('<th>Category</th>'));
        return tbody.children().each((index, element) => {
          var articlePattern, match, results, row;
          row = $(element);
          // Only continue if the node is an element and it contains something
          if (!(row[0].nodeType === 1 && row.children(':first').children(':first').contents().length)) {
            return true;
          }
          results = [];
          for (heading in sections) {
            articlePattern = new RegExp('\\[\\[' + CategorizePromoted.escapeRegExp(row.children(':first').text()) + '(\\|(.*?))?\\]\\]');
            match = sections[heading].match(articlePattern);
            if (match) {
              // Make article title appear based on formatting on WP:FA
              if (match[2]) {
                row.find('a:first').contents().eq(0).replaceWith(match[2].replace(/''(.*?)''/g, '<i>$1</i>'));
              }
              row.append($('<td><a href="' + '/wiki/' + pageType['all'] + '#' + encodeURIComponent(heading.replace(/\s/g, '_')).replace(/%/g, '.') + '">' + heading + '</a></td>'));
              break;
            } else {
              results.push(void 0);
            }
          }
          return results;
        });
      });
    }

    static categorizePromotedPageType() {
      var conditions, featuredTypes, pageType, type;
      featuredTypes = {
        'articles': {
          'all': 'Wikipedia:Featured articles',
          'promoted': 'Wikipedia:Featured articles promoted in YEAR'
        }
      };
      for (type in featuredTypes) {
        conditions = featuredTypes[type]['promoted'] && window.mw.config.get('wgPageName').replace(/_/g, ' ').indexOf(featuredTypes[type]['promoted'].replace('YEAR', '')) === 0;
        if (conditions) {
          pageType = featuredTypes[type];
          break;
        }
      }
      return pageType;
    }

    static escapeRegExp(str) {
      return str.replace(/[-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
    }

    static init() {
      var pageType, parameters;
      if (!window.mw.config.get('wgPageName')) {
        return false;
      }
      pageType = CategorizePromoted.categorizePromotedPageType();
      if (!pageType) {
        return false;
      }
      // Fix the width of each column
      window.mw.util.addCSS('.wikitable th:nth-child(1) { width: 25%; } .wikitable th:nth-child(2) { width: 15%; } .wikitable th:nth-child(3) { width: 30%; } .wikitable th:nth-child(4) { width: 30%; }');
      parameters = {
        action: 'query',
        prop: 'revisions',
        rvdir: 'older',
        rvlimit: 1,
        rvprop: 'content',
        titles: pageType['all'],
        format: 'json'
      };
      return $.get(window.mw.config.get('wgScriptPath') + '/api.php', parameters, CategorizePromoted.categorizePromotedCallback);
    }

  };

  $(function() {
    return CategorizePromoted.init();
  });

}).call(this);