MediaWiki:Gadget-UploadPreview.js

/* 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 UploadForm = { isInstalled : false, isReupload : false, formElement : null, install : function { //Install //Don't install in the obvious cases var dontInstall = mw.config.get('wgPageName') !== 'Special:Upload' || document.URL.indexOf('uploadpreview=disabled') > -1 || UploadForm.isInstalled; if (dontInstall) return; // Stop if shouldn't install //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) { //Generate then 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(				' ' +				' ' +				'You will upload over an already existing file.' +				'If you proceed, the information in this form will not appear on the description page.' +				' ' +				' '			); } 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 = ' \n' + 'Preview \n' + ' \n' + '\n' + ' \n' + ' \n' + ' \n' + '';			//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 var 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 catBar = ' ' +				' ' +				'Categories: '; for (var i = 0; i < categories.length; i++) { var catName = categories[i]['*'].replace(/_/g, ' '), catNameEncoded = encodeURIComponent(categories[i]['*'].replace(/ /g, '_')); catBar += '' + catName + ''; }			catBar += ' '; }		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 script = mw.config.get('wgScript'); //var articlePath = mw.config.get('wgArticlePath'); //var server = mw.config.get('wgServer'); //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 );