MediaWiki:Gadget-autosort.js

From Old School Near-Reality Wiki
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
 1 /**
 2  * For autosorting sortable tables
 3  * @example <>
 4  */
 5 (function($,mw,rs){
 6 	var $sortables = $('.sortable[class*="autosort="]');
 7 	if (!$sortables.length) return;
 8 	
 9 	rs.autosort = function () {
10         mw.loader.using('jquery.tablesorter', function () {
11         	$sortables.each(function () {
12                 var $this = $(this),
13                     matched = (' ' + $(this).attr( 'class') + ' ')
14                         .match(/autosort=(\d+)[,-]{1}(a|d)/),
15                     $sortCol = $this
16                         .find('> thead th:nth-child(' + matched[1] + ')');
17 
18                 if (matched[2] === 'd') {
19                     // descending
20                     $sortCol.click().click();
21                 } else {
22                     // ascending
23                     $sortCol.click();
24                 }
25             });
26             
27             mw.hook('gadget.autosort.sorted').fire($sortables);
28         });
29     };
30     
31     mw.hook('wikipage.content').add(function init() {
32 	    if ($('.jquery-tablesorter').length) {
33 	    	rs.autosort();
34 	    } else {
35 	    	// tablesorter plugin has not run yet; observe the first
36 	    	// sortable table element and wait for the plugin to add
37 	    	// the 'jquery-tablesorter' class to it
38 	    	new MutationObserver(function(muts, obs) {
39 	    		if (muts[0].target.classList.contains('jquery-tablesorter')) {
40 	    			window.rs.autosort();
41 	    			obs.disconnect();
42 	    		}
43 	    	}).observe($sortables[0], {
44 	    		attributes: true,
45 	    		attributeFilter: ['class'],
46 	    	});
47 	    }
48 	    
49 	    // only run once
50 	    mw.hook('wikipage.content').remove(init);
51     });
52 
53 }(jQuery, mediaWiki, rswiki));