Jump to content

User:Erutuon/scripts/imageSize.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Erutuon (talk | contribs) at 02:32, 27 May 2017 (mw.notify too). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
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.
var contentModel = mw.config.values.wgPageContentModel;

if ( contentModel === "wikitext" )
{
	var wikitext = $("#wpTextbox1").val();
	
	if ( /\[\[(?:[Ff]ile|[Ii]mage)/.test(wikitext) )
	{
		$("#editform").prepend('<div id="pixel-to-upright-value"><a href="javascript:convertToUpright()">convert pixel to scaling values</a></div>');
		
		var oldWikitext = wikitext;
		
		var convertToUpright = function()
		{
			wikitext = wikitext.replace(
				/\[\[(?:[Ff]ile|[Ii]mage)[^\]]+\]\]/g,
				function(wholematch)
				{
					return wholematch.replace(
						/\|\s*(\d+)px\s*\|/,
						function(wholematch, number)
						{
							// Convert string to number.
							number = Number(number);
							// Convert to upright value.
							number = number / 220;
							// Round to nearest hundredth.
							number = Math.floor( number * 100 ) / 100;
							return "|upright=" + number + "|";
						}
					);
				}
			);
		};
		
		$("#wpTextbox1").val(wikitext);
			
		$("#wpSummary").val(function(index, summary)
			{
				addition = "converted image sizes in pixels to scaling values, as prescribed by [[WP:IMGSIZE]]";
				
				afterSectionName = summary.match(/^\/\*[^\*]+\*\/\s+(.+)/);
				
				if ( afterSectionName && afterSectionName[1].length > 1 )
					addition = "; " + addition;
				
				if ( oldWikitext !== wikitext && ( !afterSectionName || !afterSectionName[1].includes(addition) ) )
					return summary + addition;
				else
				{
					console.log("imageSize.js made no changes.");
					mw.notify("imageSize.js made no changes.");
					return summary;
				}
			}
		);
	}
	else
		console.log("imageSize.js found no images in wikitext.");
		mw.notify("imageSize.js found no images in wikitext.");
}
else
{
	console.log("Content model is not wikitext, so imageSize.js will do nothing.");
	mw.notify("Content model is not wikitext, so imageSize.js will do nothing.");
}