Benutzer:Perhelion/fixConvertToSVG.js
Zur Navigation springen
Zur Suche springen
Hinweis: Leere nach dem Veröffentlichen den Browser-Cache, um die Änderungen sehen zu können.
- Firefox/Safari: Umschalttaste drücken und gleichzeitig Aktualisieren anklicken oder entweder Strg+F5 oder Strg+R (⌘+R auf dem Mac) drücken
- Google Chrome: Umschalttaste+Strg+R (⌘+Umschalttaste+R auf dem Mac) drücken
- Internet Explorer/Edge: Strg+F5 drücken oder Strg drücken und gleichzeitig Aktualisieren anklicken
- Opera: Strg+F5
/**
* SORT CONVERT-TO-SVG TAGS
* @created 2006-02-21
* @source [[c:Template:Convert to SVG]]
* @revision 12:08, 18. Mai 2015 (CEST)
* @author [[User:Ilmari Karonen]], 2006, 2010
* @author [[c:User:Perhelion]], 2010, 2015
* Commons: [[Category:User scripts|fixconverttosvg]] <nowiki>
* @license released in the public domain
* ToDo Ajax implementation
*/
/* global jQuery, mediaWiki, convertToSVGTypes */
(function ($, mw) {
"use strict";
var st = "{Convert to SVG|", // template name
vt = "Vector version available",
ns = mw.config.get('wgNamespaceNumber'),
ac = mw.config.get('wgAction'),
sc = mw.config.get('wgScript'),
ti = mw.config.get('wgTitle');
function replaceTag ( txt, type) {
var reSVG = /\{\{\s?(Convert[_ ]?to|Should[_ ]?Be)?[_ ]?(?:SVG|Vectorize|In SVG konvertieren)[^}]*\}\}\s?/i,
reVVA = /\{\{\s?(((Superseded|Converted to )SVG)|VVA|(((Vector|SVG)[_ ]?(version)?[_ ]?)available))[^}]*\}\}\s?/i,
par = "", lM = "", vva = "";
while ( reSVG.test( txt ) ) { // remove SVG, save parameter
lM = RegExp.lastMatch;
txt = txt.replace(lM, "");
//console.log(txt)
if (/\|+(([^|}]+)\s*|\|([^|}]+))}}\s?$/.test( lM )) // lastMatch
par = RegExp.$1;
//console.log(lM, RegExp.lastMatch, "$1 "+ RegExp.$1+", $2 "+RegExp.$2 +":par: "+par)
}
while ( reVVA.test( txt ) ) { // remove VVA, save parameter
lM = RegExp.lastMatch;
txt = txt.replace(lM, "");
if (/\|\s?([^|}]+\.svg)/i.test( lM )) // lastMatch
vva = RegExp.$1;
//console.log("vva",vva, RegExp.lastMatch)
}
if ( vva || (par && /\.SVG/i.test(par.slice(-4))) ) { // check wrong using of SVG template and correct it
par = vva || par;
par = toSVGname(par);
type = '{{'+ vt +'|'+ par +'}}\n';
return [type + txt, type];
}
if (type) {
if (type === "-")
type = st + " removed-";
else {
var iO = (par.indexOf("vectordata=") === 0);
if (type === "vectordata=")
type = (iO)? /\|([^|}]+\s*\|[^|}]+)/.exec(lM)[1] : par +"|"+ type;
else if (iO)
type += "|"+ par;
par = "{"+ st + type +"}}\n";
/*iO = txt.search(/(?:{{(COA)?Information)[\s\S]+?\n}}\n(?!\|)/); // after Info template
iO += (iO !== -1)? RegExp.lastMatch.length : 1;
txt = (iO)? txt.slice(0, iO) + par + txt.slice(iO) : par + txt;*/
txt = par + txt;
type = par;
}
}
//console.log(txt, type)
return [txt, type];
}
function toSVGname (s) { // try to made valid SVG filename extension
s = s || ti;
s = s.replace(/^[Ff]ile:/,"");
if (!/\.SVG$/.test(s))
s = s.replace(/\.\D{3}\D?$/,'.svg');
/*var a = new mw.Api();
a.get({
titles: "File:" + s
}).done( function ( data ) {
if ( data.query && data.query.pages ) {
$.each( data.query.pages, function ( id, page ) {
id = ( page.pageid ) ? id : "";
alert( "SVG file not exists! " + id );
} );
}
});*/
return s;
}
function toSVGfile ( e ) {
var type = e,
st2 = " set tag ",
SLink = "([[User:Perhelion/fixconverttosvg.js|Script]])";
if (!$("#editform").length) return;
if (typeof(e) !== 'string') {
e = e.target;
type = e.innerText;
//if (e.nodeName == "A") return;
if (e.preventDefault) e.preventDefault();
}
//console.log(e, type, e.nodeName); //TEST
var $textarea = $('#wpTextbox1'),
txt = replaceTag( $textarea.val(), type ),
$sum = $('#wpSummary'),
sum = $sum.val(),
oldSum = sum.indexOf( SLink + st2 );
sum = (sum.indexOf( vt ) === -1) ? sum : ""; // don't add double cmt
oldSum = (oldSum === -1)? sum : sum.slice(0, oldSum);
$textarea.val( txt[0] );
$sum.val(SLink + st2 + txt[1] + " " + oldSum);
$('#wpMinoredit').prop('checked', true);
if (e && typeof(e) === 'string') $('#wpSave').click(); // I'm feeling lucky!
return false;
}
function toVVA () { // Vector version available
var $textarea = $('#wpTextbox1'),
txt = $textarea.val(),
$sum = $('#wpSummary'),
s = $textarea.textSelection('getSelection'),
c = $textarea.textSelection('getCaretPosition') || 0,
p = ""; //existing vva + parameter (file)
console.log("toVVA p ", p, s, txt[0],txt[1]); //TEST
if (s) {
txt = replaceTag( txt.replace(s,"") );
p = txt[1];
txt = txt[0];
s = toSVGname(s);
s = '{{'+ vt +'|'+ s +'}}\n';
txt = (p)? txt.replace(p, s) : s + txt;
alert(p)
p = s;
}
else {
p = replaceTag( txt );
console.log(p.length,p)
if (!p[1]) {
console.log(txt.length, $textarea.val().length)
s = toSVGname();
p = '{{'+ vt +'|'+ ( s || '.svg' ) +'}}\n';
txt = txt.slice(0, c) + p + txt.slice(c);
p = vt;
}
txt = p[0]; // remove templates
}
$textarea.val( txt );
$sum.val( p );
}
function makeTypes () {
var types = ["alphabet", "architecture", "art", "astronomical map", "biology", "chemical", "chemistry", "circuit", "coat of arms", "diagram", "flag", "graph", "icon", "locator map", "logo", "map", "math", "military insignia", "musical notation", "physics", "realistic", "ribbon", "sign", "signature", "sport", "symbol", "technology", "text", "transport map"],
typec = "", t;
if (window.convertToSVGTypes) {
typec = convertToSVGTypes;
if (typeof(typec) == 'string')
typec = typec.split(/,\s*/);
else if ($.isArray(typec)) types = []; // reset default
}
//console.log(types, typec, typec.length)
// append default values
for (t=0; t<typec.length; t++) {
if (types.indexOf(typec[t]) === -1)
types.push(typec[t]);
}
return types.sort().concat("-");
}
function createSection () {
var types = ["vectordata="].concat(makeTypes()),
$textarea = $('#wpTextbox1');
/*t = 0, s;
for (t; t < types.length; t++)
types[t] = [types[t], "{{" + st + "|" + types[t] + "}}"];*/
/*for (t; t < types.length; t++) {
types[t] = {
'label': types[t],
'action': {
'type': 'callback',
'execute': function () {
console.log(s,st)
$textarea.textSelection('encapsulateSelection', { pre: "{"+ st + types[t], post: "}}"
})
}
}
}
}*/
$textarea.wikiEditor('addToToolbar', {
sections : { 'ToSVG' : {
label: 'ToSVG',
'type' : 'booklet',
pages : { 'tosvg' : {
//label : '{'+st, // replaced
layout : 'characters',
characters : types
}}
}},
section: 'main', // Button Vector version available
groups: { 'SVG': {
tools: { "vva": {
label: vt,
type: 'button',
icon: 'http://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gnome-x-office-drawing.svg/22px-Gnome-x-office-drawing.svg.png',
action: {
type: 'callback',
execute: toVVA
}
}}
}
}
});
$('.page.page-tosvg span').off("click").click( toSVGfile ).css("font-size","14px"); //HACK (callback API don't work!?) + made smaller
$('<a>').attr('href','//commons.wikimedia.org/wiki/Template:Convert_to_SVG').text('{'+st).appendTo( 'div.index>div.current' ); //HACK for info link
/*$textarea.wikiEditor('addToToolbar', { // vectordata button
section : 'ToSVG', page : 'tosvg', characters : [{
'label': "vectordata=",
'action': {
'type': 'callback',
'execute': function () {
//toSVGfile()
$textarea.textSelection('encapsulateSelection', { pre: "{"+ st +"|vectordata=", post: "}}\n" })
}
}
}]
});*/
//$('.group.group-SVG').children('img').click( function(){ });
}
function toSVGcategory () {
var types = makeTypes(),
url, frag, link, t,
s = (/(\S*) images that should use vector graphics$/.test(ti))? RegExp.$1 : "";
if (s) {// remove current type from sub-cat
s = s[0].toLowerCase() + s.slice(1); // types need to be start lower case
types = $(types).not([s]);
}
var tLen = types.length; // performance?
/*mw.util.addCSS(
".gallerybox, .gallerybox > div { width:280px !important }"+
".gallerytext > a { white-space:nowrap }"
);*/
// Maybe use $.clone
$('#mw-category-media div.gallerytext').children("a").after(function(){
url = sc +"?title=File:"+ (/\/wiki\/File:([^\n]*?$)/.exec(this.href)[1])+"&action=edit";
this.href = url;
url += "&fixconverttosvg=";
frag = document.createDocumentFragment();
frag.appendChild(document.createElement('br'));
for (t = 0; t < tLen; t++) { // this is faster than jQuery
link = document.createElement('a');
link.href = url + types[t];
//link.onclick = toSVGfile; //Ajax
link.text = types[t];
link.target = "_blank";
//link.style.whiteSpace="nowrap";
frag.appendChild(document.createTextNode("["));
frag.appendChild(link);
frag.appendChild(document.createTextNode("] "));
}
return frag;
});
}
$(
//mw.hook( 'wikipage.content' ).add(
function () {
if (ns === 14)// && ti.indexOf('mages that should use vector graphics') !== -1)
mw.loader.using('mediawiki.util', toSVGcategory());
//else {// if (ns === 6) && ["edit", "submit"].indexOf(ac) > -1 && !/SVG/i.test(ti.slice(-3))) {
if (/[?&]fixconverttosvg=([^&]*)/.test(window.location.search) && ac === 'edit')
toSVGfile(decodeURI(RegExp.$1));
else if (!$('span.tab.tab-ToSVG').length) // don't load (in live preview) again
mw.loader.using(['user.options', 'mediawiki.api'], function () {
if (mw.user.options.get( 'usebetatoolbar' ) && mw.user.options.get( 'showtoolbar' ))
$.when(mw.loader.using(['ext.wikiEditor.toolbar', 'jquery.wikiEditor.toolbar']), $.ready).then(createSection);
});
//}
});
})(jQuery, mediaWiki);