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.

/*** Hot Default Sort ***/



// Adds an DEFAULTSORT key editor at the bottom of the page above the categories

// Documentation at [[User:BrandonXLF/HotDefaultSort]]

// 99% by [[User:BrandonXLF]], 1% by [[User:Fuddle]]



mw.hook( 'wikipage.categories' ).add( function( $cats ){

	function resize () {

		this.style.width = '0px';

		this.style.width = this.scrollWidth + 2 + 'px';

	}

	$.get( mw.config.get('wgScriptPath') + '/api.php', {

		action: 'query',

		pageids: mw.config.get('wgArticleId'),

		prop: 'pageprops',

		format: 'json'

	}).then(function(res){

		var unset = false;

		var pp = res.query.pagesmw.config.get('wgArticleId')].pageprops;

		var key = pp ? pp.defaultsort : (unset = true) && mw.config.get('wgTitle');

		var sort = document.createElement('div');

			sort.innerHTML = 'DEFAULTSORT: ';

			$cats.append(sort);

		var dsort = document.createElement('span');

			dsort.innerHTML = key;

			sort.appendChild(dsort);

		var  = document.createElement('input');

			.style.minWidth = '100px';

			.onpaste = resize;

			.onkeydown = resize;

			.onkeyup = resize;

			.onkeypress = resize;

			.oninput = resize;

			.onchange = resize;

			.value = window.hotDefaultSortInitKey ? window.hotDefaultSortInitKey(key, unset) : key;

		var dflt = document.createElement('span');

			dflt.innerHTML = '(no key)';

			dflt.style.marginLeft = '0.25em';

			dflt.style.display = unset ? 'inline' : 'none';

			dflt.style.fontStyle = 'italic';

			sort.appendChild(dflt);

		var status = document.createElement('span');

			status.style.marginLeft = '0.25em';

			status.style.display = 'none';

			status.innerHTML = 'Saving...';

			sort.appendChild(status);

		var actions = document.createElement('span');

			sort.appendChild(actions);

		var save = document.createElement('a');

			save.innerHTML = '(✓)';

			save.style.marginLeft = '0.25em';

			save.title = 'Save changes';

			save.onclick = function () {

				status.style.display = 'inline';

				if (!.value) {

					cancel.onclick();

					remove.onclick();

					return;

				}

				$.get( mw.config.get('wgScriptPath') + '/index.php', {

					action: 'raw',

					title: mw.config.get('wgPageName')

				}).then(function(text){

					var cat = mw.config.get('wgFormattedNamespaces')[14];

					cat = new RegExp('(\\[\\[[' + cat.charAt(0).toLowerCase() + cat.charAt(0).toUpperCase() + ']' + mw.util.escapeRegExp(cat.substr(1)) + '\\:.*)');

					text = text.replace(/\n*{{DEFAULTSORT:.*?}}\n*/g,'').split(cat);

					var main = text.shift() || ''; 	

					var cats = text.join('');

		    		$.post( mw.config.get('wgScriptPath') + '/api.php', {

						action: 'edit',

						title: mw.config.get('wgPageName'),

						text: main + (main.endsWith('\n') ? '' : '\n\n') + '{{DEFAULTSORT:' + .value.trim() + '}}\n' + cats,

						summary: 'Setting DEFAULTSORT key to "' + .value.trim() + '" using [[User:Fuddle/Cold Default Sort.js|Cold Default Sort]] | [[WP:SORTKEY]]',

						token: mw.user.tokens.get('csrfToken'),

						format: 'json'

		    		}).then(function(r){

		    			status.style.display = 'none';

		    			if (r.error) {

		    				mw.notify(r.error.info.substring(0,150) + (r.error.info151 ? '...' : ''), {type: 'error', title: 'Cannot modify sort key.', tag: 'sortkeymodifyerror'});

		    			} else {

				    		dsort.innerHTML = .value;

				    		modify.innerHTML = '(±)';

				    		modify.title = 'Modify';

				    		remove.style.display = 'inline';

							dflt.style.display = 'none';

		    			}

						sort.replaceChild(dsort,);

						actions.replaceChild(remove,save);

						actions.replaceChild(modify,cancel);

		    		});

				});

			};

		var cancel = document.createElement('a');

			cancel.innerHTML = '(x)';

			cancel.style.marginLeft = '0.25em';

			cancel.title = 'Cancel';

			cancel.onclick = function () {

			    .value = window.hotDefaultSortInitKey ? window.hotDefaultSortInitKey(dsort.innerHTML, dflt.style.display === 'inline') : dsort.innerHTML;

			    sort.replaceChild(dsort,);

				actions.replaceChild(remove,save);

				actions.replaceChild(modify,cancel);

			};

		var remove = document.createElement('a');

			remove.innerHTML = '(−)';

			remove.title = 'Remove (replace with default)';

			remove.style.marginLeft = '0.25em';

			remove.style.display = unset ? 'none' : 'inline';

			remove.onclick = function () {

				status.style.display = 'inline';

				$.get( mw.config.get('wgScriptPath') + '/index.php', {

					action: 'raw',

					title: mw.config.get('wgPageName')

				}).then(function(text){

					var delSort = text.substring(text.indexOf("{{DEFAULTSORT:") );

					delSort = delSort.slice(0, delSort.indexOf("}}") + 2);

		    		$.post( mw.config.get('wgScriptPath') + '/api.php', {

						action: 'edit',

						title: mw.config.get('wgPageName'),

						text: text.replace(/\n*{{DEFAULTSORT:.*?}}\n*/g,'\n\n'),

						summary: 'Removing ' + delSort + ' using [[User:Fuddle/Cold Default Sort.js|Cold Default Sort]] | [[WP:SORTKEY]]',

						token: mw.user.tokens.get('csrfToken'),

						format: 'json'

		    		}).then(function(r){

		    			status.style.display = 'none';

		    			if (r.error) {

		    				mw.notify(r.error.info.substring(0,150) + (r.error.info151 ? '...' : ''), {type: 'error', title: 'Cannot remove sort key.', tag: 'sortkeymodifyerror'});

		    			} else {

			    			dsort.innerHTML = mw.config.get('wgTitle');

			    			.value = window.hotDefaultSortInitKey ? window.hotDefaultSortInitKey(mw.config.get('wgTitle'), true) : mw.config.get('wgTitle');

				    		modify.innerHTML = '(+)';

				    		modify.title = 'Add';

				    		remove.style.display = 'none';

							dflt.style.display = 'inline';

		    			}

		    		});

				});

			};

			actions.appendChild(remove);

		var modify = document.createElement('a');

			modify.innerHTML = unset ? '(+)' : '(±)';

			modify.title = unset ? 'Add' : 'Modify';

			modify.style.marginLeft = '0.25em';

			modify.onclick = function () {

				sort.replaceChild(,dsort);

				resize.apply();

				actions.replaceChild(save,remove);

				actions.replaceChild(cancel,modify);

			};

			actions.appendChild(modify);

	});

});

	

window.hotDefaultSortInitKey = function (key, unset) {

    /* Page title without the Namespace */

    var title = mw.config.get('wgTitle');

    

    /* Suggest new title based on common articles */

    var sortTitle = title;

    var articles =  'The ', 'Los ', 'Las ', 'Les ', 'Den ', 'Der ', 'Das ', 'Die ', 'Det ', 'Ein ', 'Uma ', 'Het ', 'An ', 'El ', 'La ', 'De ', 'Il ', 'Le ', 'Lo ', 'Os ', 'Yr ', 'A ', 'O ', 'Y ', 'L\'', 'L’' ];

    for (var i = 0; i < articles.length; i++) {

        var article = articlesi];

        if (sortTitle.startsWith(article)) {

            sortTitle = sortTitle.substring(article.length) + ', ' + articlesi].trim();

            break;

        }

    }

    

    /* lists */

    if (title.startsWith("List of")) {

    	sortTitle = title.substring(8);

    }

    if (title.startsWith("Lists of")) {

    	sortTitle = title.substring(9);

    }



    /* Last name, First name */

    var tempTitle = title;

    var myCats = document.getElementById('catlinks').innerHTML;

    if (myCats.includes("iving people") || myCats.includes(" births") || myCats.includes(" deaths") || myCats.includes("Fictional ")) {

	    var pos = tempTitle.indexOf("(");

	    if (pos > 0) { /* remove everything after left parens */	

	    	tempTitle = title.slice(0, pos - 1) 

	    } 

	    var suffix = title.slice(title.length - 3);

	    if (suffix == "Jr." || suffix == "Sr." || suffix == "III") {

	      tempTitle = title.slice(0, title.length - 4);

	      var hasSuffix = true

	    }

	    var invertedName = "";

        var lastNameStart = tempTitle.lastIndexOf(" ");

        if (lastNameStart > 0) {     

            invertedName = tempTitle.substring(lastNameStart + 1) + ', ' + tempTitle.substring(0, lastNameStart);             

            if (hasSuffix) {

              invertedName = invertedName + ", " + suffix;

              invertedName = invertedName.replace(",,", ",");

            }                          

        }

    }    

    

    /* Set key to invertedName or sortTitle */

    key = invertedName || sortTitle;

    

    /* Prescribed changes per WP:SORTKEY */

    key = key.replace(" & ", " and ").replace("O'", "O");

    key = key.replace("Mr. ", "Mister ").replace("Mr ", "Mister ");

    key = key.replace("Dr. ", "Doctor ").replace("Dr ", "Doctor ");

    key = key.replace("¡", "").replace("¿", "");

    key = key.replace("...", "").replace("…", "");

    key = key.replace(" 'N' ", " and ").replace(" 'n' ", " and ").replace(" 'n ", " and ");

    key = key.replace("Þ", "th").replace("ð", "d"). replace("ß","ss");

    if (key.startsWith("St.")) { key = key.replace("St.", "Saint") }

    if (key.startsWith("St ")) { key = key.replace("St ", "Saint ") }

    if (key.startsWith("("))   { key = key.replace("(", "").replace(")", "") }

    key = key.replace("-", " ").replace("–", " ");

    key = key0].toUpperCase() + key.slice(1);



    /* Return the key for use by hotDefaultSort */

    return key;

};