MediaWiki:Gadget-autosort.js

This is an old revision of this page, as edited by Alex (talk | contribs) at 01:19, 13 October 2024 (Created page with "→‎* * For autosorting sortable tables * @example <>: (function($,mw,rs){ var $sortables = $('.sortable[class*="autosort="]'); if (!$sortables.length) return; rs.autosort = function () { mw.loader.using('jquery.tablesorter', function () { $sortables.each(function () { var $this = $(this), matched = (' ' + $(this).attr( 'class') + ' ') .match(/autosort=(\d+)[,-]{1}(a|d)/),..."). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

After saving, you may need to bypass your browser's cache to see the changes. For further information, see Wikipedia:Bypass your cache.

  • In most Windows and Linux browsers: Hold down Ctrl and press F5.
  • In Safari: Hold down ⇧ Shift and click the Reload button.
  • In Chrome and Firefox for Mac: Hold down both ⌘ Cmd+⇧ Shift and press R.
/**
 * For autosorting sortable tables
 * @example <>
 */
(function($,mw,rs){
	var $sortables = $('.sortable[class*="autosort="]');
	if (!$sortables.length) return;
	
	rs.autosort = function () {
        mw.loader.using('jquery.tablesorter', function () {
        	$sortables.each(function () {
                var $this = $(this),
                    matched = (' ' + $(this).attr( 'class') + ' ')
                        .match(/autosort=(\d+)[,-]{1}(a|d)/),
                    $sortCol = $this
                        .find('> thead th:nth-child(' + matched[1] + ')');

                if (matched[2] === 'd') {
                    // descending
                    $sortCol.click().click();
                } else {
                    // ascending
                    $sortCol.click();
                }
            });
            
            mw.hook('gadget.autosort.sorted').fire($sortables);
        });
    };
    
    mw.hook('wikipage.content').add(function init() {
	    if ($('.jquery-tablesorter').length) {
	    	rs.autosort();
	    } else {
	    	// tablesorter plugin has not run yet; observe the first
	    	// sortable table element and wait for the plugin to add
	    	// the 'jquery-tablesorter' class to it
	    	new MutationObserver(function(muts, obs) {
	    		if (muts[0].target.classList.contains('jquery-tablesorter')) {
	    			window.rs.autosort();
	    			obs.disconnect();
	    		}
	    	}).observe($sortables[0], {
	    		attributes: true,
	    		attributeFilter: ['class'],
	    	});
	    }
	    
	    // only run once
	    mw.hook('wikipage.content').remove(init);
    });

}(jQuery, mediaWiki, rswiki));