Jump to content

User:DStoykov/defaultsort.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by DStoykov (talk | contribs) at 18:31, 16 February 2007. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
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.
/* <pre><nowiki> */

function defaultsort() {
    var txt = document.editform.wpTextbox1;
    var sortkey = '';
    // create an array of all category links
    var catlinks = txt.value.match(/\[\[\s*Category\s*:.*\]\]/ig);
    if (txt.value.match(/\{\{\s*defaultsort/i)) {
        alert('There\'s already a defaultsort statement!');
        return;
    } 
    if (!catlinks) {
        alert('There are no category links!');
        return;
    } 
    for (i=0; i< catlinks.length; i++) {
        // extract the name of the category
        var catname = catlinks[i].replace(/.+\s*:\s*([^|]*[^|\s])\s*(\|.*)?\]\]/,"$1");
        // extract the sort key 
        var match = /\|[^\]]+/.exec(catlinks[i]);
        if (match == null) {
	    alert('Category '+catname+' doesn\'t include a sort key!'); 
            return;
        }
        // strip the '|' and any trailing spaces
        sk = match[0].replace(/\|(.+)/, "$1").replace(/(\S) +$/,"$1");
        if (i == 0) {
            sortkey = sk;
        } else {
            if (sortkey != sk) {
                alert('Not all sort keys are identical!\nThe sort key for category '+catname+' is different.');
                return;
            }
        }
    }
    // Now that we know that everything is OK, we can proceed with modifying the content of the editbox
    txt.value=txt.value.replace(catlinks[0], "{{DEFAULTSORT:"+sortkey+"}}\n"+catlinks[0]);
    for (i=0; i< catlinks.length; i++) {
        subst = catlinks[i].replace(/\|[^\]]+/,"");
        subst = catlinks[i].replace(/\|[^\]]+/,"");
        txt.value=txt.value.replace(catlinks[i], subst);
    }
}

addOnloadHook(function () {
  if(document.forms.editform) {
    addPortletLink('p-cactions', 'javascript:defaultsort()', 'defaultsort', 'ca-defaultsort', '', '', document.getElementById('ca-purge'));
  }
});

/* </nowiki></pre> */