User:Wesalius/SVGedit.js

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
/**
 * Allow editing SVG file's source code without having to save them locally (aka "download") them.
 * TODO: Code editor
 * TODO: Onpageleave
 *
 * @rev 1 (2014-03-22)
 * @author Rillke, 2014
 */
// List the global variables for jsHint-Validation. Please make sure that it passes http://jshint.com/
// Scheme: globalVariable:allowOverwriting[, globalVariable:allowOverwriting][, globalVariable:allowOverwriting]
/*global jQuery:false, mediaWiki:false*/
 
// Set jsHint-options. You should not set forin or undef to false if your script does not validate.
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, curly:true, browser:true*/
 
( function ( $, mw ) {
"use strict";
 
var svgEdit,
	NS_FILE = 6,
	MYSELF = 'SVGEdit',
	conf = mw.config.get([
		'wgPageName',
		'wgNamespaceNumber',
		'wgRevisionId',
		'wgTitle'
	]);
 
svgEdit = {
	init: function() {
		var $activationLinks = $();

		// File namespace?
		if (conf.wgNamespaceNumber !== NS_FILE || !/\.svg$/.test(conf.wgPageName)) return svgEdit.log('Not a SVG-file. Aborting initialization.');
		if (mw.user.isAnon()) return svgEdit.log('Anonymous users cannot upload files. Aborting initialization.');
		if (conf.wgRevisionId < 1 || $('.filehistory').find('td.filehistory-selected').length === 0) return svgEdit.log('Page or file does not exist.');

		$activationLinks = $activationLinks.add( mw.libs.commons.ui.addEditLink('#SVGedit', "edit SVG", 'e-edit-raw-SVG', "Edit SVG source code") );

		$activationLinks.click(function(e) {
			e.preventDefault();
			svgEdit.run();
		});
		if (mw.util.getParamValue('svgrawedit')) svgEdit.run();
	},
	registerModules: function() {
		// Register custom modules
		if (null === mw.loader.getState('mediawiki.commons.MwJSBot')) mw.loader.implement('mediawiki.commons.MwJSBot', ["//commons.wikimedia.org/w/index.php?action=raw&ctype=text/javascript&title=User:Rillke/MwJSBot.js"], { /*no styles*/
		}, { /*no messages*/
		});
	},
	run: function() {
		// Create GUI
		svgEdit.registerModules();

		mw.loader.using(['mediawiki.commons.MwJSBot', 'user.options'], function() {
			svgEdit.gui();
		});
	},
	gui: function() {
		var $gui = $('<div>'),
			$ta = $('<textarea>').attr({
					rows: mw.user.options.get('rows'),
					cols: mw.user.options.get('cols'),
					disabled: 'disabled'
				}).css({
					width: '99%'
				}).appendTo($gui),
			$sum = $('<input type="text" style="width:99%" maxlength="200" placeholder="upload summary (changes, techniques)"/>').appendTo($gui),
			$saveBtn = $('<button>').attr({
					type: 'button',
					role: 'button',
					disabled: 'disabled'
				}).text("Save SVG").appendTo($gui);
				
		$ta.val("Loading SVG");
		svgEdit.$fetch().done(function(r) {
			$ta.val(r);
			$saveBtn.add($ta).removeAttr('disabled');
		});
		
		$saveBtn.click(function(e) {
			e.preventDefault();
			$saveBtn.attr('disabled', 'disabled');
			svgEdit.save($ta.val(), $sum.val()).done(function() {
				svgEdit.reload();
			}).fail(function() {
				alert("Something went wrong");
			});
		});
		
		$gui.prependTo('#mw-content-text');
	},
	$fetch: function() {
		// Fetch SVG source code
		svgEdit.bot = new MwJSBot();
		svgEdit.fileUrl = '';
		
		$('#file').find('a').each(function(i, el) {
			var href = $(el).attr('href'),
				fileDomain = 'upload.wikimedia.org',
				fileDomainPos = href.indexOf('upload.wikimedia.org');
				
			if (fileDomainPos < 10 && fileDomainPos !== -1 && /\.svg$/.test(href)) {
				svgEdit.fileUrl = href;
				return false;
			}
		});
		if (!svgEdit.fileUrl) {
			svgEdit.log("Unable to extract file URL.");
			throw new Error("Unable to extract file URL.");
		}
		
		// Assuming the SVG is UTF-8-encoded
		return $.ajax({
				url: svgEdit.fileUrl,
				beforeSend: function (xhr) {
					xhr.overrideMimeType("text/plain; charset=UTF-8");
				}
			});
	},
	save: function(text, summary) {
		if (summary) summary += ' // ';

		return svgEdit.bot.multipartMessageForUTF8Files()
			.appendPart('format', 'json')
			.appendPart('action', 'upload')
			.appendPart('filename', conf.wgTitle)
			.appendPart('comment', summary + 'Editing SVG source code using [[User:Rillke/SVGedit.js]]; upload handled by [[User:Rillke/MwJSBot.js]]')
			.appendPart('file', text, conf.wgTitle)
			.appendPart('ignorewarnings', 1)
			.appendPart('token', mw.user.tokens.get('csrfToken'))
			.$send();
	},
	reload: function() {
		window.location.href = mw.util.getUrl(conf.wgPageName);
	},
	log: function() {
		var args = Array.prototype.slice.call(arguments);
		args.unshift(MYSELF);
		mw.log.apply(mw.log, args);
	}
};
 
// Expose globally
window.svgRawEditor = svgEdit;

mw.loader.using(['ext.gadget.editDropdown', 'mediawiki.util', 'mediawiki.user'], svgEdit.init);
 
}( jQuery, mediaWiki ));