User:Fuddle/Cold Default Sort.js

/*** Hot Default Sort ***/

// Adds an DEFAULT SORT key editor at the bottom of the page above the categories
// Documentation at [[User:BrandonXLF/HotDefaultSort]]
// 99% by [[User:BrandonXLF]], 1% by [[User:Fuddle]]
// <nowiki>

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.pages[mw.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 edit = document.createElement('input');
			edit.style.minWidth = '100px';
			edit.onpaste = resize;
			edit.onkeydown = resize;
			edit.onkeyup = resize;
			edit.onkeypress = resize;
			edit.oninput = resize;
			edit.onchange = resize;
			edit.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 (!edit.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:' + edit.value.trim() + '}}\n' + cats,
						summary: 'Setting DEFAULTSORT key to "' + edit.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.info[151] ? '...' : ''), {type: 'error', title: 'Cannot modify sort key.', tag: 'sortkeymodifyerror'});
		    			} else {
				    		dsort.innerHTML = edit.value;
				    		modify.innerHTML = '(±)';
				    		modify.title = 'Modify';
				    		remove.style.display = 'inline';
							dflt.style.display = 'none';
		    			}
						sort.replaceChild(dsort,edit);
						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 () {
			    edit.value = window.hotDefaultSortInitKey ? window.hotDefaultSortInitKey(dsort.innerHTML, dflt.style.display === 'inline') : dsort.innerHTML;
			    sort.replaceChild(dsort,edit);
				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.info[151] ? '...' : ''), {type: 'error', title: 'Cannot remove sort key.', tag: 'sortkeymodifyerror'});
		    			} else {
			    			dsort.innerHTML = mw.config.get('wgTitle');
			    			edit.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(edit,dsort);
				resize.apply(edit);
				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’' , 'Ang '];
    for (var i = 0; i < articles.length; i++) {
        var article = articles[i];
        if (sortTitle.startsWith(article)) {
            sortTitle = sortTitle.substring(article.length) + ', ' + articles[i].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").replace("æ", "ae");
    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 = key[0].toUpperCase() + key.slice(1);
    
    /* Roman numerals  */
	key = key.replace(" II", " 2").replace(" III", " 3");
	key = key.replace(" IV", " 4").replace(" VIII", " 8");
	key = key.replace(" VII", "7").replace(" VI", "6");
	
    /* Return the key for use by hotDefaultSort */
    return key;
};

// </nowiki>

Content Disclaimer

Informasi ini disarikan dari Wikipedia dan disajikan kembali untuk tujuan edukasi. Konten tersedia di bawah lisensi CC BY-SA 3.0. Kami tidak bertanggung jawab atas ketidakakuratan data yang bersumber dari kontribusi publik tersebut.

  1. The information displayed on this website is sourced in part or in whole from Wikipedia and has been adapted for the purpose of restating it. We strive to provide accurate and relevant information, however:
  2. There is no guarantee of absolute accuracy. Wikipedia is an open, collaborative project that can be edited by anyone, so information is subject to change.
  3. It is not intended to constitute professional advice. The content displayed is for informational and educational purposes only. For important decisions (e.g., medical, legal, or financial), please consult a professional.
  4. Content copyright. Wikipedia is licensed under the Creative Commons Attribution-ShareAlike License (CC BY-SA). This means that content may be reused with appropriate attribution and shared under a similar license.
  5. Responsible use. Any risk arising from the use of information from this website is entirely the responsibility of the user.