User:TadejM/common.js

// See mw:Manual:Interface/JavaScript for info including variables

mw.loader.using( 'mediawiki.util' ).done(function{

CurNS=mw.config.get('wgCanonicalNamespace'); // Current namespace CurNSnum=mw.config.get('wgNamespaceNumber'); // Current namespace number CurPg=mw.config.get('wgPageName'); // Current page name Action=mw.config.get('wgAction'); Script=mw.config.get('wgScript'); Firefox=navigator.userAgent.match(/(Firefox)/i);

// ===== ROLLBACK CONFIRMATION WITH CUSTOM SUMMARY ====== $(".mw-rollback-link").on('click', function(e) {	var count = e.target.innerText.match(/\d/) ? e.target.innerText.match(/\d+/)[0] : null;	if (count >1) plural="s"; else plural="";	var summary = prompt('Rollback ' + count + ' edit' + plural + ' by ' + mw.util.getParamValue('from',e.target.href) + '?\n\nEnter text to append to custom rollback summary.\n\nLeave blank to use standard rollback.\n\n', "");	if (summary == undefined)		return e.preventDefault;	else if (summary == "")		return true;	summary="Undid edit" + plural + " by $2 (talk); rv to last ver by $1 – " + summary;	e.target.href += "&summary=" + encodeURIComponent(summary);	return true;	});

var styleEle = document.getElementsByTagName("head")[0].appendChild(document.createElement("style")); styleEle.sheet.insertRule(".mw-rollback-link {background-color:#f2deff;}", 0);

// ============= MISC ONE-LINERS =============

importScript('User:Numbermaniac/goToBottom.js');// GO TO BOTTOM importScript('User:Numbermaniac/goToTop.js');	// GO TO TOP

mw.loader.load('//en.wikipedia.org/w/index.php?title=User:Joeytje50/JWB.js/load.js&action=raw&ctype=text/javascript'); // JWB

// ======== PREVENT ACCIDENTAL SUBMIT IF ENTER IS HIT IN EDIT SUMMARY ========

$(document).ready(function{   $('input#wpSummary').keypress(function(e){ if(e.which==13) e.preventDefault; }); });

// ======= ITEMS TO INSTALL ONLY IF NOT ON A MOBILE DEVICE ======= if (!MOBILE) { importScript('MediaWiki:Gadget-popups.js');	// POPUPS importStylesheet('MediaWiki:Gadget-navpop.css'); window.popupStructure='menus'; window.popupHideDelay=0.3; window.popupFixDabs=true; window.popupFixRedirs=true; window.popupRedlinkRemoval=true;

importScript('User:Endo999/GoogleTrans.js');	// GOOGLETRANS mw.util.addPortletLink('p-tb',"javascript:GT.SCSettings", "GoogleTrans", "", "GoogleTrans options");

}

// ========= FOCUS ON TEXTAREA WHEN STARTING EDIT ==========

if(Firefox && Action == 'edit') { $( function {    $( '#wpTextbox1' ).focus;  } ); }

// ================== FORCE DESKTOP VIEW ==================

$(document).ready(function { if(window.location.origin.includes(".m")){	if(window.location.pathname.includes("/wiki/")){		window.location="https://en.wikipedia.org/w/index.php?title="+window.location.pathname.replace("/wiki/","")+"&mobileaction=toggle_view_desktop";	}	else{		window.location=window.location.href.replace(".m","")+"&mobileaction=toggle_view_desktop";	} } });

// ================= ADD ITEMS TO TOOLBOX =================

// === Create new toolbox === function addPortlet(id, title, before, px) { //Some "before" portlets:	navigation: 'p-navigation'	search: 'p-search' //contribute: 'p-interaction'	tools 'p-tb'	languages: 'p-lang' if (!px) px=11; var copy = document.getElementById('p-tb'); var div = document.createElement('div'); div.setAttribute('id', id); div.setAttribute('class', copy.getAttribute('class')); div.innerHTML = ' ' + title + ' '; var pBody = document.createElement('div'); pBody.setAttribute('class', copy.getElementsByTagName('div')[0].getAttribute('class')); pBody.appendChild(document.createElement('ul')); div.appendChild(pBody); if (before && (before = document.getElementById(before))) { copy.parentNode.insertBefore(div, before); } else { copy.parentNode.appendChild(div); }	return pBody; }

addPortlet('p-mx', 'Mx', 'p-tb');

function addlink(action, DispTxt, tb){ // "standard" toolbox is p-tb; function default is p-mx if (!DispTxt) DispTxt=action; if (!tb) tb='mx'; mw.util.addPortletLink( // Help:Customizing toolbars	'p-'+tb, // where to put the link	action, // action	DispTxt, // text to display	'', // internal ID	DispTxt // mouseover text	// ,Shortcut key press	// ,Existing portlet link to place the new portlet link before	);}

if (CurNSnum%2==1||CurNSnum==4) addlink(Script+'?title='+CurPg+'&dtenable=1', 'Section subscribe'); //WP or any talk namespace addlink(Script+'?title=Special:WhatLinksHere/'+CurPg+'&namespace=0', 'What links here (art.)'); addlink(Script+'?title='+CurPg+'&safemode=1', 'Safe mode'); addlink(Script+'?title=Special:UserLogout&returnto='+CurPg, 'Log out'); addlink(Script+'?title=Special:NewPages&action=view', '⇒ New pages', 'tb');

// ====================== TEMPLATESCRIPT ======================== /** TemplateScript * TemplateScript adds configurable templates and scripts to the sidebar, and adds an example regex editor. * @see https://meta.wikimedia.org/wiki/TemplateScript * @update-token */ $.ajax('//tools-static.wmflabs.org/meta/scripts/pathoschild.templatescript.js', { dataType:'script', cache:true }).then(function {	pathoschild.TemplateScript.add([ // add your own templates or scripts here { name: 'welcome', template: ' ~', position: 'after', editSummary: 'welcome!', forNamespaces: 'user talk' }, ]); });

// ========== SHOW DIFF/PERMALINK INFO AT BOTTOM OF PAGE =========== $.when( $.ready, mw.loader.using(["mediawiki.util"]) ).then( function {	var suffix = mw.config.get("wgDiffNewId");	if (suffix) {		if (document.getElementsByClassName("diff-multi").length || CurPg === "Special:ComparePages")			{suffix = mw.config.get("wgDiffOldId") + "/" + suffix;}		showTxt("Special:Diff/" + suffix + "&");		}	else {		var oldidMatch = mw.util.getParamValue("oldid");		if(oldidMatch)			{showTxt("Special:Permalink/" + oldidMatch + "&");}		}	} );

// ======== SHOW AT BOTTOM OF DIFF TALK+ PAGES ========= // For potential unsigned comments on talk, WP, template (for DYK noms) // Works with any of the four Wiki date formats available in Prefs if (mw.config.get('wgDiffNewId') && (CurNSnum%2==1||CurNSnum==4||CurNSnum==10)) {	const month=[]; month["Jan"]="January"; month["Feb"]="February"; month["Mar"]="March"; month["Apr"]="April"; month["May"]="May"; month["Jun"]="June"; month["Jul"]="July"; month["Aug"]="August"; month["Sep"]="September"; month["Oct"]="October"; month["Nov"]="November"; month["Dec"]="December";

usr=document.getElementById('mw-diff-ntitle2').firstChild.firstChild.firstChild.nodeValue; rev=document.getElementById('mw-diff-ntitle1').firstChild.firstChild.firstChild.nodeValue; //Change 09:31, October 25, 2021 to format Apple accepts: October 25, 2021 09:31 var ts = new Date(rev.replace(/(Latest )?Revision as of (..:..), (.*)/i, "$3 $2")); ts=ts.toUTCString; mth=ts.substr(8, 3); //UTCtime:    Sat,   06   Feb   2021   17 : 42  :00 GMT → 09:42, 6 February 2021 (UTC) ts=ts.replace(/..., (\d+) (...) (\d+) (\d+):(\d+).*/,    "$4:$5, $1 $2 $3 (UTC)"); ts=ts.replace(mth, month[mth]).replace(", 0", ", "); showTxt("" + usr + ""); } //============= ADD UNREDIRECTED LINK NEXT TO REDIRECTS =============

$(function {	$('#mw-content-text .mw-redirect').after(function { return this.href.indexOf('redirect=no') !== -1 || this.href.indexOf('action=') !== -1 || this.href.indexOf('diff=') !== -1 ? ''			: ' Я '; });});

// ================= EDIT SUMMARIES ================== // modified from MediaWiki:Gadget-defaultsummaries.js

( function { // Wrap with anonymous function var $summaryBox = $( '#wpSummary' ), clearSummary=' '; generalSummaries = [	clearSummary,	'MOS:&',	'MOS:...',	"MOS:'",	'MOS:AMU',	'MOS:CAPFRAG: "Most captions are ... sentence fragments, which should not end with a period"',	'MOS:CURLY',	'MOS:DATECOMMA',	'MOS:DATERANGE',	'MOS:DATESNO',	'MOS:DATETIES: "Articles on topics with strong ties to a particular English-speaking country should generally use the date format most commonly used in that nation"',	'MOS:DECADE',	'WP:DOFIXIT: "Spelling errors and other mistakes should be corrected. Don\'t link to a misspelled redirect."',	'MOS:EGG',	'MOS:ENDASH',	'MOS:ENTO',	'MOS:GEOCOMMA: "In geographical references that include multiple levels of subordinate divisions ..., a comma separates each element and follows the last element unless followed by other punctuation"', 'MOS:INITIALS', 'MOS:LAYOUT', 'MOS:LINKINNAME', 'WP:MPNOREDIRECT', 'MOS:NUMERAL: "Integers from zero to nine are spelled out in words"', 'MOS:OVERLINK', 'MOS:POINTS: "If an abbreviation ending in a full point ends a sentence, do not use an extra full point"', 'MOS:REFPUNCT – "All ref tags should immediately follow the text to which the footnote applies, with no intervening space"', 'MOS:SEAOFBLUE', 'MOS:SIC – "insignificant spelling and typographic errors should simply be silently corrected"', 'MOS:TIES – US spelling for US subject', 'WP:STUBSPACING', 'WP:WTAF, if notable', ' to prevent italic character from crashing into ")"',	' to prevent italic character from crashing into quotation mark',	'undefined undefined',	' → ',	'Add DEFAULTSORT',	'Add hatnote',	"Add image as required for DYK. Feel free to do a different placement and/or size. If you'd like, you may remove it after the Main Page appearance.",	'Add listas',	'Add missing space',	'Add missing word',	'Add sort key – WP:SORTKEY, WP:NAMESORT',	'As in target article',	'Better link',	'Better redirect target',	'Consistent date format',	'Correct abbreviation form',	'Correct capitalization',	'Correct diacritical marks',	'Correct link/punctuation',	'Correct name',	'Correct name; italics',	'Correct name – MOS:ARTCON: "Proper names use the subject\'s own spelling"',	'Correct name (MOS:ARTCON) – see http://www.acp.int/',	'Correct name (MOS:ARTCON) – see https://www.cgdev.org/', 'Correct name (MOS:ARTCON) – see http://www.fao.org/', 'Correct name (MOS:ARTCON) – see https://www.icao.int/Pages/Contact_us.aspx', 'Correct name (MOS:ARTCON) – see https://www.ilo.org/', 'Correct name (MOS:ARTCON) – see International Maritime Organization https://www.imo.org/', 'Correct name (MOS:ARTCON) – see International Organization for Standardization https://www.iso.org', 'Correct name (MOS:ARTCON) – see https://www.nato.int/', 'Correct name (MOS:ARTCON) – see http://www.oecd.org/about/', 'Correct name (MOS:ARTCON) – see https://www.opcw.org/', 'Correct name (MOS:ARTCON) – see https://www.osce.org/who-we-are', 'Correct name (MOS:ARTCON) – see https://www.unesco.org/en/brief', 'Correct name (MOS:ARTCON) – see https://www.who.int/', 'Correct name (MOS:ARTCON) – see https://www.wipo.int/', 'Correct name (MOS:ARTCON) – see World Organization of the Scout Movement https://www.scout.org/governance', 'Correct name (MOS:ARTCON) – see World Tourism Organization https://www.unwto.org/contact-us', 'Correct name (MOS:ARTCON) – see World Trade Organization https://www.wto.org/', 'Correct punctuation', 'Correct spelling', 'Correct spelling, as in target article', 'Correct spelling/link', 'Correct spelling; italics', "Correct spelling. The source is not online, so I assume that it was transcribed incorrectly; otherwise, it may be restored, with a [sic].", 'Correct symbol', 'Correct term', 'Correct title', 'Correct title; italics', 'Correct word', 'Dab', 'Ditto', 'En dashes', 'Fix broken template', 'Fix broken template, but please complete required fields', 'Fix DISPLAYTITLE conflict', 'Fix double word', 'Fix run-on sentence', 'Fix sort key – WP:NAMESORT', 'Fix sort key conflict – WP:NAMESORT', 'Fix sort key conflict – WP:SORTKEY, WP:NAMESORT', "Fix sort key conflict, using article's DEFAULTSORT", 'Fix template', 'Fix typo', 'Formatting', 'Hyphen', 'Italics', 'It\'s "its", not "it\'s"', 'lc per WP:HEAD', 'Misspelled piped redirect', 'Misspelled redirect piped to the object of the redirect', 'More specific redirect target', 'Oh, there was another one', 'Piped redirect', 'Piped, incorrectly punctuated, redirect', 'publisher → work', 'Re X', 'Redirect piped to the object of the redirect', 'Redirects to dab page with no relevant entry', 'Redirects to wrong page', "Replace unnecessary and incorrect apostrophe template – adds extra space and should only be used with italics", 'rm deprecated or invalid parameter', 'rm stray character', 'rm bizarre pipe', 'rm useless pipe', 'title in italics, not quotation marks – MOS:MAJORWORK', 'title in quotation marks, not italics – MOS:MINORWORK', 'Undo vandalism by X (talk)', 'Unlink – redirects to a dab page with no relevant entries', 'Unsourced', 'Update' ], templateSummaries = [ clearSummary,

'WP:MPNOREDIRECT', ,	,	' (rule C7)', ' ',	"A hook shouldn't have more than one link to the same article", 'Add (pictured)', 'Add bold link to DYK article; please feel free to do it differently', 'Add caption', 'Close nomination', 'Correct article title', 'Current article title', 'Current username', 'Fix credits', 'Fix username', 'Format image', 'Format nomination', 'Label ALT', 'mv the "Please do not write below this line" line below what was written below it', 'Patch in correct article title', 'Patch in current article title', 'rm "." before "?"', 'rm extra ellipsis', 'rm image remnants', 'rm space before "?"', ], articleSummaries = ['-'], talkPageSummaries = ['-'], otherSummaries = ['–'];

function addOptionsToDropdown( mainDropdown, optionTexts ) { mainDropdown.menu.addItems( optionTexts.map( function ( optionText ) { return new OO.ui.MenuOptionWidget( { label: optionText } ); } ) );	}

function onSummarySelect( option ) { // Save original value of edit summary field var editsummOriginalSummary = $summaryBox.val, canned = option.getLabel, newSummary = editsummOriginalSummary;

// Append any old edit summary with space, if last character != space if ( newSummary.length !== 0 && newSummary.charAt( newSummary.length - 1 ) !== ' ' ) { newSummary += ' '; }		newSummary += canned; if (canned==clearSummary) newSummary = ''; $summaryBox.val( newSummary ).trigger( 'change' ); }

function getSummaryDropdowns { // Add edit summaries dropdown box to the form var	mainDropdown = new OO.ui.DropdownWidget( {				label: 'Edit summaries'			} ); auxDropdown = new OO.ui.DropdownWidget( {				label: 'DYK edit summaries'			} ),

mainDropdown.menu.on( 'select', onSummarySelect ); auxDropdown.menu.on( 'select', onSummarySelect );

addOptionsToDropdown( mainDropdown, generalSummaries ); showAuxDropdown=false;

if ( CurNSnum === 0 ) { addOptionsToDropdown( auxDropdown, articleSummaries ); } else if ( CurNSnum === 10 ) { addOptionsToDropdown( auxDropdown, templateSummaries ); showAuxDropdown=true; } else { addOptionsToDropdown( auxDropdown, otherSummaries ); if ( CurNSnum % 2 !== 0 && CurNSnum !== 3 ) { addOptionsToDropdown( auxDropdown, talkPageSummaries ); }		}		if (showAuxDropdown) {return mainDropdown.$element.add( auxDropdown.$element );} else {return mainDropdown.$element;} }	// WikiEditor $.when( mw.loader.using( 'oojs-ui-core' ), $.ready ).then( function {		var $dropdowns,			$editCheckboxes = $( '.editCheckboxes' );

// If we failed to find the editCheckboxes class if ( !$editCheckboxes.length ) { return; }		$dropdowns = getSummaryDropdowns; if (showAuxDropdown) $dropdowns.css( {width: '48%', 'padding-bottom': '1em'} ); $editCheckboxes.before( $dropdowns ); } ); } );

});

//