Jump to content

User:RetroCraft314/taxobox.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.
// <nowiki>
jQuery(function() {
  mw.loader.using(['mediawiki.util'], function() {
    if (mw.config.get('wgAction') == 'edit') {
      $(mw.util.addPortletLink(
        "p-tb",
        "#",
        "Taxobox",
        "t-taxobox",
        "Automatize taxobox",
        "$"
      )).click(function(e) {
        e.preventDefault();

        $el = $('.mw-editfont-monospace')[0];
        source = $el.value;
        ixs = [ source.search(/{{taxobox/i), source.search(/\n}}\n/)+3 ];
        taxobox = source.substring(...ixs);
        taxon = taxobox.match(/(\w+)\s*=\s*'''''(.*)'''''/);
        lines = taxobox.split('\n');
        removedLines = [];
        newTaxobox = lines.reduce(function(arr, line) {
          ranks = ['regnum', 'phylum', 'classis', 'ordo', 'familia', 'genus', 'species'];
          species = taxon[1] == 'species';
          if (/taxobox/i.test(line)) return [...arr, `{{${species ? 'speciesbox' : 'automatic taxobox'}`];
          param = line.match(/^\s*\|\s*(\w+)\s*=\s*(.+)/i);
          if (!param) return [...arr, line];
          if (param[1] == taxon[1]) return [...arr, `| taxon = ${taxon[2]}`];
          if (param[1] == `${taxon[1]}_authority`) return [...arr, `| authority = ${param[2]}`];
          if (!ranks.includes(param[1])) return [...arr, line];
          removedLines.push(param[1]);
          return arr;
        }, []).join('\n');
        newSource = source.substring(0, ixs[0]) + newTaxobox + source.substring(ixs[1]);
        alert(`removed lines: ${removedLines.join(', ')}`);
        $el.value = newSource;

        $('[name=wpSummary]')[0].value = `use automatic ${species ? 'speciesbox' : 'taxobox'}`;
      });
    }
  });
});
// </nowiki>