User:The Transhumanist/StripSearchSorted.js

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.
// <syntaxhighlight lang="javascript">

/* 
StripSearchSorted.js: strips search results down to bare pagenames, sorts them 
alphabetically, and formats each item in wikicode as a bullet list item for easy 
copying/pasting into list articles. For vector skin only.

Initially derived from [[User:The_Transhumanist/StripSearchInWikicode.js]], see:
https://en.wikipedia.org/w/index.php?title=User:The_Transhumanist/StripSearchInWikicode.js&oldid=806430787 

The function to sort the search results and strip out the details (which was barely started here) was rewritten, 
completed, and made operational by User:Evad37 at: 
https://en.wikipedia.org/w/index.php?title=User:Evad37/StripSearchSorted.js&oldid=808314637
starting from the following version of this script page: 
https://en.wikipedia.org/w/index.php?title=User:The_Transhumanist/StripSearchSorted.js&oldid=807569292
Thank you Evad37.

Evad37 also provided the last two lines of the TrueMatch function, the filter that
makes it truly match! 
Evad37, thank you again.

This script uses the core control structure and subroutines from
[[User:The Transhumanist/OutlineViewAnnotationToggler.js]]:
https://en.wikipedia.org/w/index.php?title=User:The_Transhumanist/OutlineViewAnnotationToggler.js&oldid=807301505

Brief comments are provided within the sourcecode below. For extensive explanatory 
notes on what the source code does and how it works, see the Script's workshop on 
the talk page. (Not ready yet.)

*/

// ============== Set up ==============

// Start off with a bodyguard function to reserve the aliases mw and $
( function ( mw, $ ) {

    // we can now rely on mw and $ within the safety of our “bodyguard” function, to mean 
    // "mediawiki" and "jQuery", respectively (they follow the closing curly bracket - see the end of the script)

	// ============== Load dependencies ============== 
	mw.loader.using( ['mediawiki.util'], function () {
	
    // ============== ready() event listener/handler ==============
    // below is jQuery short-hand for $(document).ready(function() { ... });
    // it makes the rest of the script wait until the page's DOM is loaded and ready
    $(function() {
        
		// ============== activation filters ==============
        // Only activate on Vector skin
        if ( mw.config.get( 'skin' ) === 'vector' ) {

	        // Run this script only if " - Search results - Wikipedia" is in the page title
			if (document.title.indexOf(" - Search results - Wikipedia") != -1) {

				// End of set up
			
        	    // =================== Prep work =====================
				
				// Variable declarations, etc., go here

    	        var SRSortSwitch; 

            	// ================== Core program =================== 

				// Strip out redirected entries, and entries from matching categories
				$("li").has(".searchalttitle").remove();

				// True match = make "intitle:" work the way it is supposed to
				// Call TrueMatch function - see in Subroutines at program's end
				TrueMatch();

                // get the value of our status variable from memory
                // (this tells us what mode to start in)
                // "SR" stands for "search results"
                var SRSortStatus = localStorage.getItem('SRSortStatus');

				// Core control construct:				
                // run the function corresponding to the current status
                if ( SRSortStatus === "on" ) {
                    SRSortOn();
                } else {
                    SRSortOff();
                }
            }
        }

        // ======================== Subroutines ===========================
        // Functions (aka subroutines) are activated only when they are called.
        // Below are the functions called in the core control structure of the program above.
        // They are placed at the end of the program, so that the script's flow 
        // is easier to follow.

		// ============ TrueMatch function to make intitle work right =============
		function TrueMatch() {
			// The purpose of this function is to make the intitle search
			// feature actually work, by filtering out the entries that do
			// not contain the intitle search string in their titles.

	        // Activation filter:
	        // Run this function only if 'intitle:"' is in the page title
	        // Notice the lone " after intitle:
			if (document.title.indexOf('intitle:"') != -1) {

				// Body of function
				// Create variable with page title
				var docTitle = document.title;

				// Extract the intitle search string from the page title
				// We want the part between the quotation marks
				var regexIntitle = new RegExp('intitle:"(.+?)(")(.*)','i');
				var intitle;
				intitle = docTitle.replace(regexIntitle,"$1");
				//alert ( intitle );
				
				// Filter out search results that do not match the intitle search string
				// First, mark true results with a class
				$('.mw-search-results').find('li').has( 'div > a:contains("' + intitle + '")' ).addClass('truematch');
				// Now remove the other results
				$('.mw-search-results').find('li').not('.truematch').remove();
			}
		}
		
        // ============ Function to sort the search results and strip out the details ==============
        function SRSortOn() {
            // store status so it persists across page loads
            localStorage.setItem("SRSortStatus", "on");

			// Replace the search results by hiding the original results and use .after to insert a modified version of those results
			$('ul.mw-search-results').hide().after(
				$('<div id="Stripped"></div>').append(
					$('ul.mw-search-results')
					.children()
					.map( function() {
						return $(this).find('a').text();
					})
					.get()
					.sort()
					.map( function(title) {
						return $('<div></div>').append(
							'* [[',
							$('<a>').attr({
								'href':'https://en.wikipedia.org/wiki/'+mw.util.wikiUrlencode(title),
								'target':'_blank'
							}).text(title),
							']]'
						);
					})
				)	
			);
			
			// Hide interwiki results (per http://api.jquery.com/hide)
			$('#mw-interwiki-results').hide();

            // now we have to update the menu item 
            // (referred to in this script as "SRSortSwitch"). 
            // To do that, first we remove it (if it exists):  
            if ( SRSortSwitch ) {
                SRSortSwitch.parentNode.removeChild(SRSortSwitch);
            }

            // and then we create it (or its replacement) from scratch:
            SRSortSwitch = mw.util.addPortletLink( 'p-tb', '#', 'SR sort \(turn off\)', 'Show original search results with detail' );

            // make the menu item clickable by binding it to a click handler
            // (which activates the actions between the curly brackets when clicked):
            $( SRSortSwitch ).click( function ( e ) {
                e.preventDefault();     // prevents any default action -- we want only the following action to run: 
                SRSortOff();
            } );
        }
   
        // ============ Function to show original search results ==============
        function SRSortOff() {
            // store status so it persists across page loads
            localStorage.setItem("SRSortStatus", "off");

			// Show full results
			// But first, we must remove the .after chain to which we assigned the id "Stripped"
			$( "#Stripped" ).remove();
			// Now show the original results:
			$('ul.mw-search-results').show().find('*').show();
			
			// Show interwiki results (per http://api.jquery.com/show)
			$('#mw-interwiki-results').show();

            // now we have to update the menu item 
            // (referred to in this script as "SRSortSwitch"). 
            // To do that, first we remove it (if it exists):  
            if ( SRSortSwitch ) {
                SRSortSwitch.parentNode.removeChild(SRSortSwitch);
            }

            // and then we create it (or its replacement) from scratch:
            SRSortSwitch = mw.util.addPortletLink( 'p-tb', '#', 'SR sort \(turn on\)', 'Sort search results and strip details' );

            $( SRSortSwitch ).click( function ( e ) {
                e.preventDefault();     // prevents any default action -- we want only the following action to run:
                SRSortOn();
            } );
        }
    } );
    } );
}( mediaWiki, jQuery ) );
// </syntaxhighlight>