User:KokoroSenshi/MediaWiki:Gadget-Sandbox1.js

From Zelda Wiki, the Zelda encyclopedia
< User:KokoroSenshi
Revision as of 07:23, 1 July 2017 by KokoroSenshi (talk | contribs) (...Done, ready for some testing)
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/*
  Preview button for file uploads. Adapted from http://commons.wikimedia.org/wiki/MediaWiki:UploadForm.js by Lupo, March 2008. 
  Adaptation by http://rationalwiki.org/wiki/User:Nx
  Source: http://rationalwiki.org/wiki/MediaWiki:UploadPreview.js
  Modified for compatibility with Zelda Wiki's FileInfo template.
  Modified according to https://www.mediawiki.org/wiki/ResourceLoader/Legacy_JavaScript
  License: GPL
*/

var pageName = mw.config.get('wgPageName');
var script = mw.config.get('wgScript');
var scriptPath = mw.config.get('wgScriptPath');
var articlePath = mw.config.get('wgArticlePath');
var server = mw.config.get('wgServer');

var UploadForm = {
	
	isInstalled : false,
	isReupload : false,
	formElement : null,
	
	install : function() { //Install
		
		//Don't install in the obvious cases
		var dontInstall =
		       pageName !== 'Special:Upload'
		    || document.URL.indexOf('uploadpreview=disabled') > -1
		    || UploadForm.isInstalled;
		if (dontInstall) return; // Stop if already installed
		
		//Don't install if missing page elements
		var form = document.getElementById('mw-upload-form'),
		    summary = document.getElementById('wpUploadDescription');
		if (!form || !summary) return; // Stop if no form nor summary elements
		
		//Check if reupload
		var reupload = document.getElementById('wpForReUpload'), //A hidden element for a reupload (that has value 1?)
		    destFile = document.getElementById('wpDestFile'); //Destination filename inputbox
		UploadForm.isReupload = ( reupload || document.URL.indexOf('wpForReUpload=1') > -1 );
		
		UploadForm.formElement = form;
		
		if (!UploadForm.isReupload) UploadForm.addPreviewButton();
		
		UploadForm.isInstalled = true;
		
	},
	
	preview : function(e) { //Preview the file page content
		
		wgUploadWarningObj.checkNow($('#wpDestFile').val()); //Check in case the user clicks preview right after changing the filename
		if ( UploadForm.isOverwrite() ) {
			
			UploadForm.showPreview(
				'<div style="border:1px solid red; padding:0.5em;">' +
				'<div class="error">' +
				'You will upload over an already existing file.' +
				'If you proceed, the information in this form will not appear on the description page.' +
				'</div>' +
				'</div>'
			);
			
		} else {
			
			var summaryText   = document.getElementById('wpUploadDescription').value,
			    sourceText    = document.getElementById('mw-input-source').value,
			    licensingText = $('#mw-input-licensing').val(),
			    typeText      = $('#mw-input-type').val(),
			    gameText      = $('#mw-input-game').val(),
			    text =
			    	'<div style="border:1px solid red; padding:0.5em;">\n' + 
			    		'<div class="previewnote">\n' + 
			    			'{{int:previewnote}}\n' + 
			    		'</div>\n' +
			    	'</div>\n' +
			    	'<h2>Preview</h2>\n' +
			    	'{{FileInfo' +
			    	'|summary='   + summaryText +
			    	'|source='    + sourceText +
			    	'|licensing=' + licensingText +
			    	'|type='      + typeText +
			    	'|game='      + gameText +
			    	'}}';
			
			// Make the Ajax call
			var destFilename = document.getElementById('wpDestFile'),
			    destFilenameText = null;
			if (destFilename) destFilenameText = destFilename.value;
			
			$('#wpUploadPreview').injectSpinner('wpUploadPreviewSpinner'); //#wpUploadPreview is the id of the upload preview button
			
			(new mw.Api()).get({ //Does this not cache by default?
				action: 'parse',
				text: text,
				title: ( destFilenameText ? 'File:' + destFilenameText : '' ),
				prop: 'text|categories'
			}).done(function(data){
				var parsedText = data.parse.text['*'],
				    categories = data.parse.categories;
				console.log(parsedText);
				console.log(categories);
				parsedText += UploadForm.makeCatBar(categories);
				UploadForm.showPreview(parsedText);
			}).always(function(){
				$.removeSpinner('wpUploadPreviewSpinner');
			});
			
		}
		
		return true; //For the preview button's onclick?
		
	},
	
	makeCatBar : function( categories ) { //html for a mock-up of a category bar
		
		catBar = '';
		
		if (categories.length > 0) {
			
			//Sort the categories first
			categories.sort(function(a, b){
				var key_a = a['*'].toLowerCase(), 
				    key_b = b['*'].toLowerCase();
				if (key_a < key_b) return -1;
				if (key_a > key_b) return 1;
				return 0;
			});
			
			//Make the category bar
			var catBar =
				'<div id="catlinks" class="catlinks">' +
				'<div id="mw-normal-catlinks" class="mw-normal-catlinks">' +
				'<a href="/Special:Categories" title="Special:Categories">Categories</a>: <ul>';
			
			for (var i = 0; i < categories.length; i++) {
				var catName = categories[i]['*'],
				    catNameEncoded = encodeURIComponent(catName.replace(/ /g, '_'));
				catBar += '<li><a href="/Category:' + catNameEncoded + '" title="Category:' + catNameEncoded + '">' + catName + '</a></li>';
			}
			
			catBar += '</ul></div></div>';
			
		}
		
		return catBar;
		
	},
	
	isOverwrite : function () {
		
		if ( $('#wpDestFile-warning > p').text().startsWith('A file with this name exists') ) {
			return true;
		}
		
		if ( document.getElementById('wpUploadWarningFileexists') ) return true; //?
		var destfileWarning = document.getElementById('wpDestFile-warning');
		if (!destfileWarning) return false; //No warning
		var destFilename = document.getElementById('wpDestFile');
		if (destFilename === null || destFilename.value === null || destFilename.value.length === 0) return false; //No filename entered
		
		//Some other checks I don't feel are necessary at this point:
		
		//var warningLinks = destfileWarning.getElementsByTagName('a');
		//if (warningLinks === null || warningLinks.length === 0) return false; //No links to files (would could indicate a name clash)
		//
		//var fn1 = destFilename.value.replace(/^\s\s*/, '').replace(/\s\s*$/, '').replace(/ /g, '_');
		//    fn1 = fn1.substr(0, 1).toUpperCase() + fn1.substring(1);
		//var fn0 = 'Image:' + fn1;
		//    fn1 = 'File:' + fn1;
		//// Trimmed, blanks replaced by underscores, first character capitalized
		//
		//for (var i = 0; i < warningLinks.length; i++) {
		//	var href = warningLinks[i].getAttribute('href', 2);
		//	if (href.indexOf(script + '?') === 0 || href.indexOf(server + script + '?') === 0) {
		//		var m = /[&?]title=([^&]*)/.exec(href);
		//		if (m && m.length > 1) href = m[1]; else href = null;
		//	} else {
		//		var prefix = articlePath.replace ('$1', '');
		//		if (href.indexOf (prefix) !== 0) prefix = server + prefix; // Fully expanded URL?
		//		if (href.indexOf (prefix) === 0) href = href.substring (prefix.length); else href = null;
		//	}
		//	if (!href) continue;
		//	href = decodeURIComponent(href).replace(/ /g, '_');
		//	if (href == fn0 || href == fn1) return true;
		//}
		
		return false;
		
	},
	
	showPreview : function(content) {
		
		var preview = document.getElementById('wpUploadPreviewDisplay'); //null if not created yet
		if (preview === null) { //Create if not created
			form = UploadForm.formElement;
			preview = document.createElement('div');
			preview.id = 'wpUploadPreviewDisplay';
			
			form.parentNode.insertBefore(preview, form); //Insert preview before the form
		}
		try {
			preview.innerHTML = content;
		} catch(e) {
			preview.innerHTML = ''; // Error message here instead?
		}
		//preview.style.display = ''; // Show it //???
		preview.scrollIntoView();
		
	},
	
	addPreviewButton : function() {
		var uploadButton = document.getElementsByName('wpUpload')[0];
		
		if (uploadButton === null) return; // Stop if can't find the upload button
		
		var previewButton = document.createElement('input');
		previewButton.id        = 'wpUploadPreview';
		previewButton.name      = 'wpUploadPreview';
		previewButton.type      = 'button';
		previewButton.accessKey = 'p';
		previewButton.value     = 'Show preview';
		previewButton.title     = 'Preview your changes, please use this before saving! ['+previewButton.accessKey+']';
		previewButton.style     = 'margin-left: 0.5em;';
		previewButton.onclick   = UploadForm.preview;
		mw.loader.using('jquery.accessKeyLabel').then(function(){
			$(previewButton).updateTooltipAccessKeys();
		});
		uploadButton.parentNode.insertBefore(previewButton, uploadButton.nextSibling);
	},
	
};
	
$(document).ready(UploadForm.install);