User:Cryptic/reverse-csd.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.
// <!--
/* Reverses the order of months and individual pages at [[User:L3X1/CSD log]].  Change the wgPageName check to use it on a different page.
 * Known defects:
 * * The table of contents is left where it is, in the collapsed table for 2017 (which is now near the bottom of the page).
 * * The order on the table of contents isn't updated.
 * Honestly, you're better off reordering the sections manually, except for the current month's one at the bottom, and maybe putting in javascript to make that one display at the top.
 */

function reverse_sections(context, tags)
{
  var subspec = context + ' > ';
  var spec = '';
  for (var i = 0; i < tags.length; ++i)
    {
      spec += subspec + tags[i];
      if (i == 0)
        subspec = ', ' + subspec;
    }

  var l = $(spec).get();
  var rev = [];
  for (var i = 1; i < l.length; ++i)
    if (l[i].tagName == 'H3')
      {
        rev = l.splice(0, i).concat(rev);
        i = 0;
      }
  rev = l.concat(rev);
  $(context).append(rev);
}

$(function()
  {
    if (mw.config.get('wgPageName') == 'User:L3X1/CSD_log')
      {
        // Reverse top-level sections.  The table is for the {{hat}}/{{hab}} collapsers for each year; the div for the {{cot}}/{{cob}} collapsers for each month.
        reverse_sections('#mw-content-text > .mw-parser-output', ['table', 'div', 'h3', 'ol']);
        // Reverse sections within the year-level collapsed tables.
        var num_tables = $('#mw-content-text > .mw-parser-output > table').length;
        for (var i = 0; i < num_tables; ++i)
          reverse_sections('#mw-content-text > .mw-parser-output > table:nth-of-type(' + (i+1) + ') > tbody > tr:nth-of-type(3) > td', ['div', 'h3', 'ol']);

        // Reverse each list of pages.
        $('#mw-content-text > .mw-parser-output ol').each(function(){ this.reversed='reversed'; var ol = $(this); ol.append(ol.children().get().reverse()); });
      }
   });
// -->