JSLint extensions

git-svn-id: http://svg-edit.googlecode.com/svn/trunk@2695 eee81c28-f429-11dd-99c0-75d572ba1ddd
This commit is contained in:
Brett Zamir
2014-02-12 09:38:38 +00:00
parent d97e21b604
commit d6cc464ba5
17 changed files with 767 additions and 664 deletions

View File

@@ -1,3 +1,5 @@
/*globals svgEditor, svgCanvas, $*/
/*jslint vars: true, eqeq: true*/
/* /*
* ext-arrows.js * ext-arrows.js
* *
@@ -12,7 +14,7 @@ svgEditor.addExtension('Arrows', function(S) {
addElem = S.addSvgElementFromJson, addElem = S.addSvgElementFromJson,
nonce = S.nonce, nonce = S.nonce,
randomize_ids = S.randomize_ids, randomize_ids = S.randomize_ids,
selElems, selElems, pathdata,
lang_list = { lang_list = {
'en':[ 'en':[
{'id': 'arrow_none', 'textContent': 'No arrow' } {'id': 'arrow_none', 'textContent': 'No arrow' }
@@ -21,22 +23,9 @@ svgEditor.addExtension('Arrows', function(S) {
{'id': 'arrow_none', 'textContent': 'Sans flèche' } {'id': 'arrow_none', 'textContent': 'Sans flèche' }
] ]
}, },
arrowprefix,
prefix = 'se_arrow_'; prefix = 'se_arrow_';
svgCanvas.bind('setnonce', setArrowNonce);
svgCanvas.bind('unsetnonce', unsetArrowNonce);
if (randomize_ids) {
var arrowprefix = prefix + nonce + '_';
} else {
var arrowprefix = prefix;
}
var pathdata = {
fw: {d: 'm0,0l10,5l-10,5l5,-5l-5,-5z', refx: 8, id: arrowprefix + 'fw'},
bk: {d: 'm10,0l-10,5l10,5l-5,-5l5,-5z', refx: 2, id: arrowprefix + 'bk'}
};
function setArrowNonce(window, n) { function setArrowNonce(window, n) {
randomize_ids = true; randomize_ids = true;
arrowprefix = prefix + n + '_'; arrowprefix = prefix + n + '_';
@@ -51,9 +40,24 @@ svgEditor.addExtension('Arrows', function(S) {
pathdata.bk.id = arrowprefix + 'bk'; pathdata.bk.id = arrowprefix + 'bk';
} }
svgCanvas.bind('setnonce', setArrowNonce);
svgCanvas.bind('unsetnonce', unsetArrowNonce);
if (randomize_ids) {
arrowprefix = prefix + nonce + '_';
} else {
arrowprefix = prefix;
}
pathdata = {
fw: {d: 'm0,0l10,5l-10,5l5,-5l-5,-5z', refx: 8, id: arrowprefix + 'fw'},
bk: {d: 'm10,0l-10,5l10,5l-5,-5l5,-5z', refx: 2, id: arrowprefix + 'bk'}
};
function getLinked(elem, attr) { function getLinked(elem, attr) {
var str = elem.getAttribute(attr); var str = elem.getAttribute(attr);
if(!str) return null; if(!str) {return null;}
var m = str.match(/\(\#(.*)\)/); var m = str.match(/\(\#(.*)\)/);
if(!m || m.length !== 2) { if(!m || m.length !== 2) {
return null; return null;
@@ -70,20 +74,20 @@ svgEditor.addExtension('Arrows', function(S) {
var mid = el.getAttribute('marker-mid'); var mid = el.getAttribute('marker-mid');
var val; var val;
if(end && start) { if (end && start) {
val = 'both'; val = 'both';
} else if(end) { } else if (end) {
val = 'end'; val = 'end';
} else if(start) { } else if (start) {
val = 'start'; val = 'start';
} else if(mid) { } else if (mid) {
val = 'mid'; val = 'mid';
if(mid.indexOf('bk') != -1) { if (mid.indexOf('bk') !== -1) {
val = 'mid_bk'; val = 'mid_bk';
} }
} }
if(!start && !mid && !end) { if (!start && !mid && !end) {
val = 'none'; val = 'none';
} }
@@ -105,11 +109,11 @@ svgEditor.addExtension('Arrows', function(S) {
var marker = S.getElem(id); var marker = S.getElem(id);
var data = pathdata[dir]; var data = pathdata[dir];
if(type == 'mid') { if (type == 'mid') {
data.refx = 5; data.refx = 5;
} }
if(!marker) { if (!marker) {
marker = addElem({ marker = addElem({
'element': 'marker', 'element': 'marker',
'attr': { 'attr': {
@@ -143,16 +147,16 @@ svgEditor.addExtension('Arrows', function(S) {
var type = this.value; var type = this.value;
resetMarker(); resetMarker();
if(type == 'none') { if (type == 'none') {
return; return;
} }
// Set marker on element // Set marker on element
var dir = 'fw'; var dir = 'fw';
if(type == 'mid_bk') { if (type == 'mid_bk') {
type = 'mid'; type = 'mid';
dir = 'bk'; dir = 'bk';
} else if(type == 'both') { } else if (type == 'both') {
addMarker('bk', type); addMarker('bk', type);
svgCanvas.changeSelectedAttribute('marker-start', 'url(#' + pathdata.bk.id + ')'); svgCanvas.changeSelectedAttribute('marker-start', 'url(#' + pathdata.bk.id + ')');
type = 'end'; type = 'end';
@@ -173,12 +177,12 @@ svgEditor.addExtension('Arrows', function(S) {
$.each(mtypes, function(i, type) { $.each(mtypes, function(i, type) {
var marker = getLinked(elem, 'marker-'+type); var marker = getLinked(elem, 'marker-'+type);
if(!marker) return; if(!marker) {return;}
var cur_color = $(marker).children().attr('fill'); var cur_color = $(marker).children().attr('fill');
var cur_d = $(marker).children().attr('d'); var cur_d = $(marker).children().attr('d');
var new_marker = null; var new_marker = null;
if(cur_color === color) return; if(cur_color === color) {return;}
var all_markers = $(defs).find('marker'); var all_markers = $(defs).find('marker');
// Different color, check if already made // Different color, check if already made
@@ -208,10 +212,11 @@ svgEditor.addExtension('Arrows', function(S) {
var elem = this; var elem = this;
$.each(mtypes, function(j, mtype) { $.each(mtypes, function(j, mtype) {
if($(elem).attr('marker-' + mtype) === 'url(#' + marker.id + ')') { if($(elem).attr('marker-' + mtype) === 'url(#' + marker.id + ')') {
return remove = false; remove = false;
return remove;
} }
}); });
if(!remove) return false; if(!remove) {return false;}
}); });
// Not found, so can safely remove // Not found, so can safely remove
@@ -259,7 +264,7 @@ svgEditor.addExtension('Arrows', function(S) {
var marker_elems = ['line', 'path', 'polyline', 'polygon']; var marker_elems = ['line', 'path', 'polyline', 'polygon'];
while(i--) { while(i--) {
var elem = selElems[i]; var elem = selElems[i];
if(elem && $.inArray(elem.tagName, marker_elems) != -1) { if(elem && $.inArray(elem.tagName, marker_elems) !== -1) {
if(opts.selectedElement && !opts.multiselected) { if(opts.selectedElement && !opts.multiselected) {
showPanel(true); showPanel(true);
} else { } else {

View File

@@ -1,3 +1,5 @@
/*globals svgEditor, $*/
/*jslint vars: true, eqeq: true*/
/* /*
* ext-closepath.js * ext-closepath.js
* *
@@ -9,7 +11,7 @@
// This extension adds a simple button to the contextual panel for paths // This extension adds a simple button to the contextual panel for paths
// The button toggles whether the path is open or closed // The button toggles whether the path is open or closed
svgEditor.addExtension('ClosePath', function() { svgEditor.addExtension('ClosePath', function() {'use strict';
var selElems, var selElems,
updateButton = function(path) { updateButton = function(path) {
var seglist = path.pathSegList, var seglist = path.pathSegList,
@@ -23,7 +25,7 @@ svgEditor.addExtension('ClosePath', function() {
$('#closepath_panel').toggle(on); $('#closepath_panel').toggle(on);
if (on) { if (on) {
var path = selElems[0]; var path = selElems[0];
if (path) updateButton(path); if (path) {updateButton(path);}
} }
}, },
toggleClosed = function() { toggleClosed = function() {

View File

@@ -1,3 +1,5 @@
/*globals svgEditor, svgCanvas, $*/
/*jslint vars: true, continue: true, eqeq: true, todo: true*/
/* /*
* ext-connector.js * ext-connector.js
* *
@@ -24,10 +26,9 @@ svgEditor.addExtension("Connector", function(S) {
connections = [], connections = [],
conn_sel = ".se_connector", conn_sel = ".se_connector",
se_ns, se_ns,
// connect_str = "-SE_CONNECT-", // connect_str = "-SE_CONNECT-",
selElems = []; selElems = [],
elData = $.data;
elData = $.data;
var lang_list = { var lang_list = {
"en":[ "en":[
@@ -38,181 +39,6 @@ svgEditor.addExtension("Connector", function(S) {
] ]
}; };
function getOffset(side, line) {
var give_offset = !!line.getAttribute('marker-' + side);
// var give_offset = $(line).data(side+'_off');
// TODO: Make this number (5) be based on marker width/height
var size = line.getAttribute('stroke-width') * 5;
return give_offset ? size : 0;
}
function showPanel(on) {
var conn_rules = $('#connector_rules');
if(!conn_rules.length) {
conn_rules = $('<style id="connector_rules"><\/style>').appendTo('head');
}
conn_rules.text(!on?"":"#tool_clone, #tool_topath, #tool_angle, #xy_panel { display: none !important; }");
$('#connector_panel').toggle(on);
}
function setPoint(elem, pos, x, y, setMid) {
var pts = elem.points;
var pt = svgroot.createSVGPoint();
pt.x = x;
pt.y = y;
if(pos === 'end') pos = pts.numberOfItems-1;
// TODO: Test for this on init, then use alt only if needed
try {
pts.replaceItem(pt, pos);
} catch(err) {
// Should only occur in FF which formats points attr as "n,n n,n", so just split
var pt_arr = elem.getAttribute("points").split(" ");
for(var i=0; i< pt_arr.length; i++) {
if(i == pos) {
pt_arr[i] = x + ',' + y;
}
}
elem.setAttribute("points",pt_arr.join(" "));
}
if(setMid) {
// Add center point
var pt_start = pts.getItem(0);
var pt_end = pts.getItem(pts.numberOfItems-1);
setPoint(elem, 1, (pt_end.x + pt_start.x)/2, (pt_end.y + pt_start.y)/2);
}
}
function updateLine(diff_x, diff_y) {
// Update line with element
var i = connections.length;
while(i--) {
var conn = connections[i];
var line = conn.connector;
var elem = conn.elem;
var pre = conn.is_start?'start':'end';
// var sw = line.getAttribute('stroke-width') * 5;
// Update bbox for this element
var bb = elData(line, pre+'_bb');
bb.x = conn.start_x + diff_x;
bb.y = conn.start_y + diff_y;
elData(line, pre+'_bb', bb);
var alt_pre = conn.is_start?'end':'start';
// Get center pt of connected element
var bb2 = elData(line, alt_pre+'_bb');
var src_x = bb2.x + bb2.width/2;
var src_y = bb2.y + bb2.height/2;
// Set point of element being moved
var pt = getBBintersect(src_x, src_y, bb, getOffset(pre, line)); // $(line).data(pre+'_off')?sw:0
setPoint(line, conn.is_start?0:'end', pt.x, pt.y, true);
// Set point of connected element
var pt2 = getBBintersect(pt.x, pt.y, elData(line, alt_pre + '_bb'), getOffset(alt_pre, line));
setPoint(line, conn.is_start?'end':0, pt2.x, pt2.y, true);
}
}
function findConnectors(elems) {
if(!elems) elems = selElems;
var connectors = $(svgcontent).find(conn_sel);
connections = [];
// Loop through connectors to see if one is connected to the element
connectors.each(function() {
var start = elData(this, "c_start");
var end = elData(this, "c_end");
var parts = [getElem(start), getElem(end)];
for(var i=0; i<2; i++) {
var c_elem = parts[i];
var add_this = false;
// The connected element might be part of a selected group
$(c_elem).parents().each(function() {
if($.inArray(this, elems) !== -1) {
// Pretend this element is selected
add_this = true;
}
});
if(!c_elem || !c_elem.parentNode) {
$(this).remove();
continue;
}
if($.inArray(c_elem, elems) !== -1 || add_this) {
var bb = svgCanvas.getStrokedBBox([c_elem]);
connections.push({
elem: c_elem,
connector: this,
is_start: (i === 0),
start_x: bb.x,
start_y: bb.y
});
}
}
});
}
function updateConnectors(elems) {
// Updates connector lines based on selected elements
// Is not used on mousemove, as it runs getStrokedBBox every time,
// which isn't necessary there.
findConnectors(elems);
if(connections.length) {
// Update line with element
var i = connections.length;
while(i--) {
var conn = connections[i];
var line = conn.connector;
var elem = conn.elem;
var sw = line.getAttribute('stroke-width') * 5;
var pre = conn.is_start?'start':'end';
// Update bbox for this element
var bb = svgCanvas.getStrokedBBox([elem]);
bb.x = conn.start_x;
bb.y = conn.start_y;
elData(line, pre+'_bb', bb);
var add_offset = elData(line, pre+'_off');
var alt_pre = conn.is_start?'end':'start';
// Get center pt of connected element
var bb2 = elData(line, alt_pre+'_bb');
var src_x = bb2.x + bb2.width/2;
var src_y = bb2.y + bb2.height/2;
// Set point of element being moved
var pt = getBBintersect(src_x, src_y, bb, getOffset(pre, line));
setPoint(line, conn.is_start?0:'end', pt.x, pt.y, true);
// Set point of connected element
var pt2 = getBBintersect(pt.x, pt.y, elData(line, alt_pre + '_bb'), getOffset(alt_pre, line));
setPoint(line, conn.is_start?'end':0, pt2.x, pt2.y, true);
// Update points attribute manually for webkit
if(navigator.userAgent.indexOf('AppleWebKit') != -1) {
var pts = line.points;
var len = pts.numberOfItems;
var pt_arr = Array(len);
for(var j=0; j< len; j++) {
var pt = pts.getItem(j);
pt_arr[j] = pt.x + ',' + pt.y;
}
line.setAttribute("points",pt_arr.join(" "));
}
}
}
}
function getBBintersect(x, y, bb, offset) { function getBBintersect(x, y, bb, offset) {
if(offset) { if(offset) {
offset -= 0; offset -= 0;
@@ -242,6 +68,184 @@ svgEditor.addExtension("Connector", function(S) {
return { return {
x: mid_x + len_x * ratio, x: mid_x + len_x * ratio,
y: mid_y + len_y * ratio y: mid_y + len_y * ratio
};
}
function getOffset(side, line) {
var give_offset = !!line.getAttribute('marker-' + side);
// var give_offset = $(line).data(side+'_off');
// TODO: Make this number (5) be based on marker width/height
var size = line.getAttribute('stroke-width') * 5;
return give_offset ? size : 0;
}
function showPanel(on) {
var conn_rules = $('#connector_rules');
if(!conn_rules.length) {
conn_rules = $('<style id="connector_rules"><\/style>').appendTo('head');
}
conn_rules.text(!on?"":"#tool_clone, #tool_topath, #tool_angle, #xy_panel { display: none !important; }");
$('#connector_panel').toggle(on);
}
function setPoint(elem, pos, x, y, setMid) {
var i, pts = elem.points;
var pt = svgroot.createSVGPoint();
pt.x = x;
pt.y = y;
if (pos === 'end') {pos = pts.numberOfItems - 1;}
// TODO: Test for this on init, then use alt only if needed
try {
pts.replaceItem(pt, pos);
} catch(err) {
// Should only occur in FF which formats points attr as "n,n n,n", so just split
var pt_arr = elem.getAttribute("points").split(" ");
for (i = 0; i < pt_arr.length; i++) {
if (i === pos) {
pt_arr[i] = x + ',' + y;
}
}
elem.setAttribute("points",pt_arr.join(" "));
}
if(setMid) {
// Add center point
var pt_start = pts.getItem(0);
var pt_end = pts.getItem(pts.numberOfItems-1);
setPoint(elem, 1, (pt_end.x + pt_start.x)/2, (pt_end.y + pt_start.y)/2);
}
}
function updateLine(diff_x, diff_y) {
// Update line with element
var i = connections.length;
while(i--) {
var conn = connections[i];
var line = conn.connector;
var elem = conn.elem;
var pre = conn.is_start?'start':'end';
// var sw = line.getAttribute('stroke-width') * 5;
// Update bbox for this element
var bb = elData(line, pre+'_bb');
bb.x = conn.start_x + diff_x;
bb.y = conn.start_y + diff_y;
elData(line, pre+'_bb', bb);
var alt_pre = conn.is_start?'end':'start';
// Get center pt of connected element
var bb2 = elData(line, alt_pre+'_bb');
var src_x = bb2.x + bb2.width/2;
var src_y = bb2.y + bb2.height/2;
// Set point of element being moved
var pt = getBBintersect(src_x, src_y, bb, getOffset(pre, line)); // $(line).data(pre+'_off')?sw:0
setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true);
// Set point of connected element
var pt2 = getBBintersect(pt.x, pt.y, elData(line, alt_pre + '_bb'), getOffset(alt_pre, line));
setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true);
}
}
function findConnectors(elems) {
var i;
if (!elems) {elems = selElems;}
var connectors = $(svgcontent).find(conn_sel);
connections = [];
// Loop through connectors to see if one is connected to the element
connectors.each(function() {
var add_this;
function add () {
if ($.inArray(this, elems) !== -1) {
// Pretend this element is selected
add_this = true;
}
}
var start = elData(this, "c_start");
var end = elData(this, "c_end");
var parts = [getElem(start), getElem(end)];
for (i = 0; i < 2; i++) {
var c_elem = parts[i];
add_this = false;
// The connected element might be part of a selected group
$(c_elem).parents().each(add);
if(!c_elem || !c_elem.parentNode) {
$(this).remove();
continue;
}
if($.inArray(c_elem, elems) !== -1 || add_this) {
var bb = svgCanvas.getStrokedBBox([c_elem]);
connections.push({
elem: c_elem,
connector: this,
is_start: (i === 0),
start_x: bb.x,
start_y: bb.y
});
}
}
});
}
function updateConnectors(elems) {
// Updates connector lines based on selected elements
// Is not used on mousemove, as it runs getStrokedBBox every time,
// which isn't necessary there.
var i, j;
findConnectors(elems);
if (connections.length) {
// Update line with element
i = connections.length;
while (i--) {
var conn = connections[i];
var line = conn.connector;
var elem = conn.elem;
var sw = line.getAttribute('stroke-width') * 5;
var pre = conn.is_start?'start':'end';
// Update bbox for this element
var bb = svgCanvas.getStrokedBBox([elem]);
bb.x = conn.start_x;
bb.y = conn.start_y;
elData(line, pre+'_bb', bb);
var add_offset = elData(line, pre+'_off');
var alt_pre = conn.is_start?'end':'start';
// Get center pt of connected element
var bb2 = elData(line, alt_pre+'_bb');
var src_x = bb2.x + bb2.width/2;
var src_y = bb2.y + bb2.height/2;
// Set point of element being moved
var pt = getBBintersect(src_x, src_y, bb, getOffset(pre, line));
setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true);
// Set point of connected element
var pt2 = getBBintersect(pt.x, pt.y, elData(line, alt_pre + '_bb'), getOffset(alt_pre, line));
setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true);
// Update points attribute manually for webkit
if (navigator.userAgent.indexOf('AppleWebKit') !== -1) {
var pts = line.points;
var len = pts.numberOfItems;
var pt_arr = [];
for (j = 0; j < len; j++) {
pt = pts.getItem(j);
pt_arr[j] = pt.x + ',' + pt.y;
}
line.setAttribute('points', pt_arr.join(' '));
}
}
} }
} }
@@ -252,7 +256,7 @@ svgEditor.addExtension("Connector", function(S) {
svgCanvas.groupSelectedElements = function() { svgCanvas.groupSelectedElements = function() {
svgCanvas.removeFromSelection($(conn_sel).toArray()); svgCanvas.removeFromSelection($(conn_sel).toArray());
return gse.apply(this, arguments); return gse.apply(this, arguments);
} };
var mse = svgCanvas.moveSelectedElements; var mse = svgCanvas.moveSelectedElements;
@@ -261,7 +265,7 @@ svgEditor.addExtension("Connector", function(S) {
var cmd = mse.apply(this, arguments); var cmd = mse.apply(this, arguments);
updateConnectors(); updateConnectors();
return cmd; return cmd;
} };
se_ns = svgCanvas.getEditorNS(); se_ns = svgCanvas.getEditorNS();
}()); }());
@@ -283,19 +287,19 @@ svgEditor.addExtension("Connector", function(S) {
svgCanvas.getEditorNS(true); svgCanvas.getEditorNS(true);
} }
}); });
// updateConnectors(); // updateConnectors();
} }
// $(svgroot).parent().mousemove(function(e) { // $(svgroot).parent().mousemove(function(e) {
// // if(started // // if(started
// // || svgCanvas.getMode() != "connector" // // || svgCanvas.getMode() != "connector"
// // || e.target.parentNode.parentNode != svgcontent) return; // // || e.target.parentNode.parentNode != svgcontent) return;
// //
// console.log('y') // console.log('y')
// // if(e.target.parentNode.parentNode === svgcontent) { // // if(e.target.parentNode.parentNode === svgcontent) {
// // // //
// // } // // }
// }); // });
return { return {
name: "Connector", name: "Connector",
@@ -323,19 +327,19 @@ svgEditor.addExtension("Connector", function(S) {
}, },
mouseDown: function(opts) { mouseDown: function(opts) {
var e = opts.event; var e = opts.event;
start_x = opts.start_x, start_x = opts.start_x;
start_y = opts.start_y; start_y = opts.start_y;
var mode = svgCanvas.getMode(); var mode = svgCanvas.getMode();
if(mode == "connector") { if (mode == "connector") {
if(started) return; if (started) {return;}
var mouse_target = e.target; var mouse_target = e.target;
var parents = $(mouse_target).parents(); var parents = $(mouse_target).parents();
if($.inArray(svgcontent, parents) != -1) { if($.inArray(svgcontent, parents) !== -1) {
// Connectable element // Connectable element
// If child of foreignObject, use parent // If child of foreignObject, use parent
@@ -365,7 +369,8 @@ svgEditor.addExtension("Connector", function(S) {
return { return {
started: true started: true
}; };
} else if(mode == "select") { }
if (mode == "select") {
findConnectors(); findConnectors();
} }
}, },
@@ -380,7 +385,7 @@ svgEditor.addExtension("Connector", function(S) {
var mode = svgCanvas.getMode(); var mode = svgCanvas.getMode();
if(mode == "connector" && started) { if (mode == "connector" && started) {
var sw = cur_line.getAttribute('stroke-width') * 3; var sw = cur_line.getAttribute('stroke-width') * 3;
// Set start point (adjusts based on bb) // Set start point (adjusts based on bb)
@@ -392,7 +397,7 @@ svgEditor.addExtension("Connector", function(S) {
// Set end point // Set end point
setPoint(cur_line, 'end', x, y, true); setPoint(cur_line, 'end', x, y, true);
} else if(mode == "select") { } else if (mode == "select") {
var slen = selElems.length; var slen = selElems.length;
while(slen--) { while(slen--) {
@@ -421,19 +426,20 @@ svgEditor.addExtension("Connector", function(S) {
if(svgCanvas.getMode() == "connector") { if(svgCanvas.getMode() == "connector") {
var fo = $(mouse_target).closest("foreignObject"); var fo = $(mouse_target).closest("foreignObject");
if(fo.length) mouse_target = fo[0]; if (fo.length) {mouse_target = fo[0];}
var parents = $(mouse_target).parents(); var parents = $(mouse_target).parents();
if(mouse_target == start_elem) { if (mouse_target == start_elem) {
// Start line through click // Start line through click
started = true; started = true;
return { return {
keep: true, keep: true,
element: null, element: null,
started: started started: started
} };
} else if($.inArray(svgcontent, parents) === -1) { }
if ($.inArray(svgcontent, parents) === -1) {
// Not a valid target element, so remove line // Not a valid target element, so remove line
$(cur_line).remove(); $(cur_line).remove();
started = false; started = false;
@@ -441,55 +447,54 @@ svgEditor.addExtension("Connector", function(S) {
keep: false, keep: false,
element: null, element: null,
started: started started: started
} };
} else {
// Valid end element
end_elem = mouse_target;
var start_id = start_elem.id, end_id = end_elem.id;
var conn_str = start_id + " " + end_id;
var alt_str = end_id + " " + start_id;
// Don't create connector if one already exists
var dupe = $(svgcontent).find(conn_sel).filter(function() {
var conn = this.getAttributeNS(se_ns, "connector");
if(conn == conn_str || conn == alt_str) return true;
});
if(dupe.length) {
$(cur_line).remove();
return {
keep: false,
element: null,
started: false
}
}
var bb = svgCanvas.getStrokedBBox([end_elem]);
var pt = getBBintersect(start_x, start_y, bb, getOffset('start', cur_line));
setPoint(cur_line, 'end', pt.x, pt.y, true);
$(cur_line)
.data("c_start", start_id)
.data("c_end", end_id)
.data("end_bb", bb);
se_ns = svgCanvas.getEditorNS(true);
cur_line.setAttributeNS(se_ns, "se:connector", conn_str);
cur_line.setAttribute('class', conn_sel.substr(1));
cur_line.setAttribute('opacity', 1);
svgCanvas.addToSelection([cur_line]);
svgCanvas.moveToBottomSelectedElement();
selManager.requestSelector(cur_line).showGrips(false);
started = false;
return {
keep: true,
element: cur_line,
started: started
}
} }
// Valid end element
end_elem = mouse_target;
var start_id = start_elem.id, end_id = end_elem.id;
var conn_str = start_id + " " + end_id;
var alt_str = end_id + " " + start_id;
// Don't create connector if one already exists
var dupe = $(svgcontent).find(conn_sel).filter(function() {
var conn = this.getAttributeNS(se_ns, "connector");
if (conn == conn_str || conn == alt_str) {return true;}
});
if(dupe.length) {
$(cur_line).remove();
return {
keep: false,
element: null,
started: false
};
}
var bb = svgCanvas.getStrokedBBox([end_elem]);
var pt = getBBintersect(start_x, start_y, bb, getOffset('start', cur_line));
setPoint(cur_line, 'end', pt.x, pt.y, true);
$(cur_line)
.data("c_start", start_id)
.data("c_end", end_id)
.data("end_bb", bb);
se_ns = svgCanvas.getEditorNS(true);
cur_line.setAttributeNS(se_ns, "se:connector", conn_str);
cur_line.setAttribute('class', conn_sel.substr(1));
cur_line.setAttribute('opacity', 1);
svgCanvas.addToSelection([cur_line]);
svgCanvas.moveToBottomSelectedElement();
selManager.requestSelector(cur_line).showGrips(false);
started = false;
return {
keep: true,
element: cur_line,
started: started
};
} }
}, },
selectedChanged: function(opts) { selectedChanged: function(opts) {
// TODO: Find better way to skip operations if no connectors are in use // TODO: Find better way to skip operations if no connectors are in use
if(!$(svgcontent).find(conn_sel).length) return; if(!$(svgcontent).find(conn_sel).length) {return;}
if(svgCanvas.getMode() == 'connector') { if(svgCanvas.getMode() == 'connector') {
svgCanvas.setMode('select'); svgCanvas.setMode('select');
@@ -518,19 +523,20 @@ svgEditor.addExtension("Connector", function(S) {
}, },
elementChanged: function(opts) { elementChanged: function(opts) {
var elem = opts.elems[0]; var elem = opts.elems[0];
if (elem && elem.tagName == 'svg' && elem.id == "svgcontent") { if (elem && elem.tagName === 'svg' && elem.id === 'svgcontent') {
// Update svgcontent (can change on import) // Update svgcontent (can change on import)
svgcontent = elem; svgcontent = elem;
init(); init();
} }
// Has marker, so change offset // Has marker, so change offset
if(elem && ( var start;
if (elem && (
elem.getAttribute("marker-start") || elem.getAttribute("marker-start") ||
elem.getAttribute("marker-mid") || elem.getAttribute("marker-mid") ||
elem.getAttribute("marker-end") elem.getAttribute("marker-end")
)) { )) {
var start = elem.getAttribute("marker-start"); start = elem.getAttribute("marker-start");
var mid = elem.getAttribute("marker-mid"); var mid = elem.getAttribute("marker-mid");
var end = elem.getAttribute("marker-end"); var end = elem.getAttribute("marker-end");
cur_line = elem; cur_line = elem;
@@ -538,13 +544,13 @@ svgEditor.addExtension("Connector", function(S) {
.data("start_off", !!start) .data("start_off", !!start)
.data("end_off", !!end); .data("end_off", !!end);
if(elem.tagName == "line" && mid) { if (elem.tagName === 'line' && mid) {
// Convert to polyline to accept mid-arrow // Convert to polyline to accept mid-arrow
var x1 = elem.getAttribute('x1')-0; var x1 = Number(elem.getAttribute('x1'));
var x2 = elem.getAttribute('x2')-0; var x2 = Number(elem.getAttribute('x2'));
var y1 = elem.getAttribute('y1')-0; var y1 = Number(elem.getAttribute('y1'));
var y2 = elem.getAttribute('y2')-0; var y2 = Number(elem.getAttribute('y2'));
var id = elem.id; var id = elem.id;
var mid_pt = (' '+((x1+x2)/2)+','+((y1+y2)/2) + ' '); var mid_pt = (' '+((x1+x2)/2)+','+((y1+y2)/2) + ' ');
@@ -567,17 +573,17 @@ svgEditor.addExtension("Connector", function(S) {
} }
} }
// Update line if it's a connector // Update line if it's a connector
if(elem.getAttribute('class') == conn_sel.substr(1)) { if (elem.getAttribute('class') == conn_sel.substr(1)) {
var start = getElem(elData(elem, 'c_start')); start = getElem(elData(elem, 'c_start'));
updateConnectors([start]); updateConnectors([start]);
} else { } else {
updateConnectors(); updateConnectors();
} }
}, },
toolButtonStateUpdate: function(opts) { toolButtonStateUpdate: function(opts) {
if(opts.nostroke) { if (opts.nostroke) {
if ($('#mode_connect').hasClass('tool_button_current')) { if ($('#mode_connect').hasClass('tool_button_current')) {
clickSelect(); svgEditor.clickSelect();
} }
} }
$('#mode_connect') $('#mode_connect')

View File

@@ -1,3 +1,5 @@
/*globals svgEditor, svgedit, $*/
/*jslint vars: true, eqeq: true*/
/* /*
* ext-eyedropper.js * ext-eyedropper.js
* *
@@ -13,97 +15,98 @@
// 3) svg_editor.js // 3) svg_editor.js
// 4) svgcanvas.js // 4) svgcanvas.js
svgEditor.addExtension("eyedropper", function(S) { svgEditor.addExtension("eyedropper", function(S) {'use strict';
var NS = svgedit.NS, var // NS = svgedit.NS,
svgcontent = S.svgcontent, // svgcontent = S.svgcontent,
svgdoc = S.svgroot.parentNode.ownerDocument, // svgdoc = S.svgroot.parentNode.ownerDocument,
svgCanvas = svgEditor.canvas, svgCanvas = svgEditor.canvas,
ChangeElementCommand = svgedit.history.ChangeElementCommand, ChangeElementCommand = svgedit.history.ChangeElementCommand,
addToHistory = function(cmd) { svgCanvas.undoMgr.addCommandToHistory(cmd); }, addToHistory = function(cmd) { svgCanvas.undoMgr.addCommandToHistory(cmd); },
currentStyle = {fillPaint: "red", fillOpacity: 1.0, currentStyle = {
strokePaint: "black", strokeOpacity: 1.0, fillPaint: "red", fillOpacity: 1.0,
strokeWidth: 5, strokeDashArray: null, strokePaint: "black", strokeOpacity: 1.0,
opacity: 1.0, strokeWidth: 5, strokeDashArray: null,
strokeLinecap: 'butt', opacity: 1.0,
strokeLinejoin: 'miter', strokeLinecap: 'butt',
}; strokeLinejoin: 'miter'
};
function getStyle(opts) { function getStyle(opts) {
// if we are in eyedropper mode, we don't want to disable the eye-dropper tool // if we are in eyedropper mode, we don't want to disable the eye-dropper tool
var mode = svgCanvas.getMode(); var mode = svgCanvas.getMode();
if (mode == "eyedropper") return; if (mode == "eyedropper") {return;}
var elem = null;
var tool = $('#tool_eyedropper');
// enable-eye-dropper if one element is selected
if (!opts.multiselected && opts.elems[0] &&
$.inArray(opts.elems[0].nodeName, ['svg', 'g', 'use']) == -1)
{
elem = opts.elems[0];
tool.removeClass('disabled');
// grab the current style
currentStyle.fillPaint = elem.getAttribute("fill") || "black";
currentStyle.fillOpacity = elem.getAttribute("fill-opacity") || 1.0;
currentStyle.strokePaint = elem.getAttribute("stroke");
currentStyle.strokeOpacity = elem.getAttribute("stroke-opacity") || 1.0;
currentStyle.strokeWidth = elem.getAttribute("stroke-width");
currentStyle.strokeDashArray = elem.getAttribute("stroke-dasharray");
currentStyle.strokeLinecap = elem.getAttribute("stroke-linecap");
currentStyle.strokeLinejoin = elem.getAttribute("stroke-linejoin");
currentStyle.opacity = elem.getAttribute("opacity") || 1.0;
}
// disable eye-dropper tool
else {
tool.addClass('disabled');
}
var elem = null;
var tool = $('#tool_eyedropper');
// enable-eye-dropper if one element is selected
if (!opts.multiselected && opts.elems[0] &&
$.inArray(opts.elems[0].nodeName, ['svg', 'g', 'use']) === -1
) {
elem = opts.elems[0];
tool.removeClass('disabled');
// grab the current style
currentStyle.fillPaint = elem.getAttribute("fill") || "black";
currentStyle.fillOpacity = elem.getAttribute("fill-opacity") || 1.0;
currentStyle.strokePaint = elem.getAttribute("stroke");
currentStyle.strokeOpacity = elem.getAttribute("stroke-opacity") || 1.0;
currentStyle.strokeWidth = elem.getAttribute("stroke-width");
currentStyle.strokeDashArray = elem.getAttribute("stroke-dasharray");
currentStyle.strokeLinecap = elem.getAttribute("stroke-linecap");
currentStyle.strokeLinejoin = elem.getAttribute("stroke-linejoin");
currentStyle.opacity = elem.getAttribute("opacity") || 1.0;
}
// disable eye-dropper tool
else {
tool.addClass('disabled');
} }
return { }
name: "eyedropper",
svgicons: svgEditor.curConfig.extPath + "eyedropper-icon.xml", return {
buttons: [{ name: "eyedropper",
id: "tool_eyedropper", svgicons: svgEditor.curConfig.extPath + "eyedropper-icon.xml",
type: "mode", buttons: [{
title: "Eye Dropper Tool", id: "tool_eyedropper",
key: "I", type: "mode",
events: { title: "Eye Dropper Tool",
"click": function() { key: "I",
svgCanvas.setMode("eyedropper"); events: {
} "click": function() {
svgCanvas.setMode("eyedropper");
} }
}], }
}],
// if we have selected an element, grab its paint and enable the eye dropper button // if we have selected an element, grab its paint and enable the eye dropper button
selectedChanged: getStyle, selectedChanged: getStyle,
elementChanged: getStyle, elementChanged: getStyle,
mouseDown: function(opts) { mouseDown: function(opts) {
var mode = svgCanvas.getMode(); var mode = svgCanvas.getMode();
if (mode == "eyedropper") { if (mode == "eyedropper") {
var e = opts.event; var e = opts.event;
var target = e.target; var target = e.target;
if ($.inArray(target.nodeName, ['svg', 'g', 'use']) == -1) { if ($.inArray(target.nodeName, ['svg', 'g', 'use']) === -1) {
var changes = {}; var changes = {};
var change = function(elem, attrname, newvalue) { var change = function(elem, attrname, newvalue) {
changes[attrname] = elem.getAttribute(attrname); changes[attrname] = elem.getAttribute(attrname);
elem.setAttribute(attrname, newvalue); elem.setAttribute(attrname, newvalue);
}; };
if (currentStyle.fillPaint) change(target, "fill", currentStyle.fillPaint); if (currentStyle.fillPaint) {change(target, "fill", currentStyle.fillPaint);}
if (currentStyle.fillOpacity) change(target, "fill-opacity", currentStyle.fillOpacity); if (currentStyle.fillOpacity) {change(target, "fill-opacity", currentStyle.fillOpacity);}
if (currentStyle.strokePaint) change(target, "stroke", currentStyle.strokePaint); if (currentStyle.strokePaint) {change(target, "stroke", currentStyle.strokePaint);}
if (currentStyle.strokeOpacity) change(target, "stroke-opacity", currentStyle.strokeOpacity); if (currentStyle.strokeOpacity) {change(target, "stroke-opacity", currentStyle.strokeOpacity);}
if (currentStyle.strokeWidth) change(target, "stroke-width", currentStyle.strokeWidth); if (currentStyle.strokeWidth) {change(target, "stroke-width", currentStyle.strokeWidth);}
if (currentStyle.strokeDashArray) change(target, "stroke-dasharray", currentStyle.strokeDashArray); if (currentStyle.strokeDashArray) {change(target, "stroke-dasharray", currentStyle.strokeDashArray);}
if (currentStyle.opacity) change(target, "opacity", currentStyle.opacity); if (currentStyle.opacity) {change(target, "opacity", currentStyle.opacity);}
if (currentStyle.strokeLinecap) change(target, "stroke-linecap", currentStyle.strokeLinecap); if (currentStyle.strokeLinecap) {change(target, "stroke-linecap", currentStyle.strokeLinecap);}
if (currentStyle.strokeLinejoin) change(target, "stroke-linejoin", currentStyle.strokeLinejoin); if (currentStyle.strokeLinejoin) {change(target, "stroke-linejoin", currentStyle.strokeLinejoin);}
addToHistory(new ChangeElementCommand(target, changes)); addToHistory(new ChangeElementCommand(target, changes));
}
} }
}, }
}; }
};
}); });

View File

@@ -1,3 +1,5 @@
/*globals svgEditor, svgedit, svgCanvas, $*/
/*jslint vars: true, eqeq: true, todo: true*/
/* /*
* ext-foreignobject.js * ext-foreignobject.js
* *
@@ -10,6 +12,7 @@
svgEditor.addExtension("foreignObject", function(S) { svgEditor.addExtension("foreignObject", function(S) {
var NS = svgedit.NS, var NS = svgedit.NS,
Utils = svgedit.utilities,
svgcontent = S.svgcontent, svgcontent = S.svgcontent,
addElem = S.addSvgElementFromJson, addElem = S.addSvgElementFromJson,
selElems, selElems,
@@ -18,7 +21,7 @@ svgEditor.addExtension("foreignObject", function(S) {
started, started,
newFO; newFO;
var properlySourceSizeTextArea = function(){ var properlySourceSizeTextArea = function () {
// TODO: remove magic numbers here and get values from CSS // TODO: remove magic numbers here and get values from CSS
var height = $('#svg_source_container').height() - 80; var height = $('#svg_source_container').height() - 80;
$('#svg_source_textarea').css('height', height); $('#svg_source_textarea').css('height', height);
@@ -67,7 +70,7 @@ svgEditor.addExtension("foreignObject", function(S) {
function showForeignEditor() { function showForeignEditor() {
var elt = selElems[0]; var elt = selElems[0];
if (!elt || editingforeign) return; if (!elt || editingforeign) {return;}
editingforeign = true; editingforeign = true;
toggleSourceButtons(true); toggleSourceButtons(true);
elt.removeAttribute('fill'); elt.removeAttribute('fill');
@@ -93,7 +96,7 @@ svgEditor.addExtension("foreignObject", function(S) {
title: "Foreign Object Tool", title: "Foreign Object Tool",
events: { events: {
'click': function() { 'click': function() {
svgCanvas.setMode('foreign') svgCanvas.setMode('foreign');
} }
} }
},{ },{
@@ -155,7 +158,7 @@ svgEditor.addExtension("foreignObject", function(S) {
editingforeign = false; editingforeign = false;
$('#svg_source_textarea').blur(); $('#svg_source_textarea').blur();
toggleSourceButtons(false); toggleSourceButtons(false);
} };
// TODO: Needs to be done after orig icon loads // TODO: Needs to be done after orig icon loads
setTimeout(function() { setTimeout(function() {
@@ -164,11 +167,11 @@ svgEditor.addExtension("foreignObject", function(S) {
.hide().attr('id', 'foreign_save').unbind() .hide().attr('id', 'foreign_save').unbind()
.appendTo("#tool_source_back").click(function() { .appendTo("#tool_source_back").click(function() {
if (!editingforeign) return; if (!editingforeign) {return;}
if (!setForeignString($('#svg_source_textarea').val())) { if (!setForeignString($('#svg_source_textarea').val())) {
$.confirm("Errors found. Revert to original?", function(ok) { $.confirm("Errors found. Revert to original?", function(ok) {
if(!ok) return false; if(!ok) {return false;}
endChanges(); endChanges();
}); });
} else { } else {
@@ -218,20 +221,20 @@ svgEditor.addExtension("foreignObject", function(S) {
newFO.appendChild(m); newFO.appendChild(m);
return { return {
started: true started: true
} };
} }
}, },
mouseUp: function(opts) { mouseUp: function(opts) {
var e = opts.event; var e = opts.event;
if(svgCanvas.getMode() == "foreign" && started) { if(svgCanvas.getMode() == "foreign" && started) {
var attrs = $(newFO).attr(["width", "height"]); var attrs = $(newFO).attr(["width", "height"]);
keep = (attrs.width != 0 || attrs.height != 0); var keep = (attrs.width != 0 || attrs.height != 0);
svgCanvas.addToSelection([newFO], true); svgCanvas.addToSelection([newFO], true);
return { return {
keep: keep, keep: keep,
element: newFO element: newFO
} };
} }
@@ -244,7 +247,7 @@ svgEditor.addExtension("foreignObject", function(S) {
while(i--) { while(i--) {
var elem = selElems[i]; var elem = selElems[i];
if(elem && elem.tagName == "foreignObject") { if(elem && elem.tagName === 'foreignObject') {
if(opts.selectedElement && !opts.multiselected) { if(opts.selectedElement && !opts.multiselected) {
$('#foreign_font_size').val(elem.getAttribute("font-size")); $('#foreign_font_size').val(elem.getAttribute("font-size"));
$('#foreign_width').val(elem.getAttribute("width")); $('#foreign_width').val(elem.getAttribute("width"));

View File

@@ -1,3 +1,5 @@
/*globals svgEditor, svgedit, svgCanvas, $*/
/*jslint vars: true*/
/* /*
* ext-grid.js * ext-grid.js
* *
@@ -12,7 +14,7 @@
// 1) units.js // 1) units.js
// 2) everything else // 2) everything else
svgEditor.addExtension('view_grid', function() { svgEditor.addExtension('view_grid', function() { 'use strict';
var NS = svgedit.NS, var NS = svgedit.NS,
svgdoc = document.getElementById('svgcanvas').ownerDocument, svgdoc = document.getElementById('svgcanvas').ownerDocument,
@@ -73,16 +75,17 @@ svgEditor.addExtension('view_grid', function() {
$('#canvasGrid').append(gridBox); $('#canvasGrid').append(gridBox);
function updateGrid(zoom) { function updateGrid(zoom) {
var i;
// TODO: Try this with <line> elements, then compare performance difference // TODO: Try this with <line> elements, then compare performance difference
var unit = units[svgEditor.curConfig.baseUnit]; // 1 = 1px var unit = units[svgEditor.curConfig.baseUnit]; // 1 = 1px
var u_multi = unit * zoom; var u_multi = unit * zoom;
// Calculate the main number interval // Calculate the main number interval
var raw_m = 100 / u_multi; var raw_m = 100 / u_multi;
var multi = 1; var multi = 1;
for(var i = 0; i < intervals.length; i++) { for (i = 0; i < intervals.length; i++) {
var num = intervals[i]; var num = intervals[i];
multi = num; multi = num;
if(raw_m <= num) { if (raw_m <= num) {
break; break;
} }
} }
@@ -97,7 +100,7 @@ svgEditor.addExtension('view_grid', function() {
ctx.globalAlpha = 0.2; ctx.globalAlpha = 0.2;
ctx.strokeStyle = svgEditor.curConfig.gridColor; ctx.strokeStyle = svgEditor.curConfig.gridColor;
for (var i = 1; i < 10; i++) { for (i = 1; i < 10; i++) {
var sub_d = Math.round(part * i) + 0.5; var sub_d = Math.round(part * i) + 0.5;
// var line_num = (i % 2)?12:10; // var line_num = (i % 2)?12:10;
var line_num = 0; var line_num = 0;
@@ -129,7 +132,7 @@ svgEditor.addExtension('view_grid', function() {
svgicons: svgEditor.curConfig.extPath + 'grid-icon.xml', svgicons: svgEditor.curConfig.extPath + 'grid-icon.xml',
zoomChanged: function(zoom) { zoomChanged: function(zoom) {
if(showGrid) updateGrid(zoom); if (showGrid) {updateGrid(zoom);}
}, },
buttons: [{ buttons: [{

View File

@@ -1,3 +1,5 @@
/*globals svgEditor, svgCanvas, $*/
/*jslint vars: true, eqeq: true*/
/* /*
* ext-helloworld.js * ext-helloworld.js
* *
@@ -10,10 +12,10 @@
/* /*
This is a very basic SVG-Edit extension. It adds a "Hello World" button in This is a very basic SVG-Edit extension. It adds a "Hello World" button in
the left panel. Clicking on the button, and then the canvas will show the the left panel. Clicking on the button, and then the canvas will show the
user the point on the canvas that was clicked on. user the point on the canvas that was clicked on.
*/ */
svgEditor.addExtension("Hello World", function() { svgEditor.addExtension("Hello World", function() {'use strict';
return { return {
name: "Hello World", name: "Hello World",

View File

@@ -1,3 +1,5 @@
/*globals svgEditor, svgCanvas, $*/
/*jslint vars: true, eqeq: true, todo: true */
/* /*
* ext-markers.js * ext-markers.js
* *
@@ -31,9 +33,9 @@
*/ */
svgEditor.addExtension("Markers", function(S) { svgEditor.addExtension("Markers", function(S) {
var svgcontent = S.svgcontent, var // svgcontent = S.svgcontent,
addElem = S.addSvgElementFromJson, addElem = S.addSvgElementFromJson,
selElems; selElems;
var mtypes = ['start','mid','end']; var mtypes = ['start','mid','end'];
@@ -69,8 +71,8 @@ svgEditor.addExtension("Markers", function(S) {
triangle: triangle:
{element:'path', attr:{d:'M10,80 L50,20 L80,80 Z'}}, {element:'path', attr:{d:'M10,80 L50,20 L80,80 Z'}},
mcircle: mcircle:
{element:'circle', attr:{r:30, cx:50, cy:50}}, {element:'circle', attr:{r:30, cx:50, cy:50}}
} };
var lang_list = { var lang_list = {
@@ -95,7 +97,7 @@ svgEditor.addExtension("Markers", function(S) {
{id: "box_o", title: "Open Box" }, {id: "box_o", title: "Open Box" },
{id: "star_o", title: "Open Star" }, {id: "star_o", title: "Open Star" },
{id: "triangle_o", title: "Open Triangle" }, {id: "triangle_o", title: "Open Triangle" },
{id: "mcircle_o", title: "Open Circle" }, {id: "mcircle_o", title: "Open Circle" }
] ]
}; };
@@ -110,7 +112,7 @@ svgEditor.addExtension("Markers", function(S) {
// returns the marker element that is linked to the graphic element // returns the marker element that is linked to the graphic element
function getLinked(elem, attr) { function getLinked(elem, attr) {
var str = elem.getAttribute(attr); var str = elem.getAttribute(attr);
if(!str) return null; if(!str) {return null;}
var m = str.match(/\(\#(.*)\)/); var m = str.match(/\(\#(.*)\)/);
if(!m || m.length !== 2) { if(!m || m.length !== 2) {
return null; return null;
@@ -118,7 +120,14 @@ svgEditor.addExtension("Markers", function(S) {
return S.getElem(m[1]); return S.getElem(m[1]);
} }
//toggles context tool panel off/on function setIcon(pos,id) {
if (id.substr(0,1) !== '\\') {id = '\\textmarker';}
var ci = '#'+id_prefix+pos+'_'+id.substr(1);
svgEditor.setIcon('#cur_' + pos +'_marker_list', $(ci).children());
$(ci).addClass('current').siblings().removeClass('current');
}
// toggles context tool panel off/on
//sets the controls with the selected element's settings //sets the controls with the selected element's settings
function showPanel(on) { function showPanel(on) {
$('#marker_panel').toggle(on); $('#marker_panel').toggle(on);
@@ -129,26 +138,26 @@ svgEditor.addExtension("Markers", function(S) {
var ci; var ci;
$.each(mtypes, function(i, pos) { $.each(mtypes, function(i, pos) {
var m=getLinked(el,"marker-"+pos); var m = getLinked(el,"marker-"+pos);
var txtbox = $('#'+pos+'_marker'); var txtbox = $('#'+pos+'_marker');
if (!m) { if (!m) {
val='\\nomarker'; val = '\\nomarker';
ci=val; ci = val;
txtbox.hide() // hide text box txtbox.hide(); // hide text box
} else { } else {
if (!m.attributes.se_type) return; // not created by this extension if (!m.attributes.se_type) {return;} // not created by this extension
val='\\'+m.attributes.se_type.textContent; val = '\\' + m.attributes.se_type.textContent;
ci=val; ci = val;
if (val=='\\textmarker') { if (val === '\\textmarker') {
val=m.lastChild.textContent; val=m.lastChild.textContent;
//txtbox.show(); // show text box //txtbox.show(); // show text box
} else { } else {
txtbox.hide() // hide text box txtbox.hide(); // hide text box
} }
} }
txtbox.val(val); txtbox.val(val);
setIcon(pos,ci); setIcon(pos,ci);
}) });
} }
} }
@@ -159,9 +168,9 @@ svgEditor.addExtension("Markers", function(S) {
var marker = S.getElem(id); var marker = S.getElem(id);
if (marker) return; if (marker) {return;}
if (val=='' || val=='\\nomarker') return; if (val == '' || val == '\\nomarker') {return;}
var el = selElems[0]; var el = selElems[0];
var color = el.getAttribute('stroke'); var color = el.getAttribute('stroke');
@@ -174,12 +183,13 @@ svgEditor.addExtension("Markers", function(S) {
var markerWidth = 5; var markerWidth = 5;
var markerHeight = 5; var markerHeight = 5;
var strokeWidth = 10; var strokeWidth = 10;
if (val.substr(0,1)=='\\') se_type=val.substr(1); var se_type;
else se_type='textmarker'; if (val.substr(0,1) === '\\') {se_type = val.substr(1);}
else {se_type = 'textmarker';}
if (!marker_types[se_type]) return; // an unknown type! if (!marker_types[se_type]) {return;} // an unknown type!
// create a generic marker // create a generic marker
marker = addElem({ marker = addElem({
"element": "marker", "element": "marker",
"attr": { "attr": {
@@ -191,13 +201,13 @@ svgEditor.addExtension("Markers", function(S) {
} }
}); });
if (se_type!='textmarker') { if (se_type != 'textmarker') {
var mel = addElem(marker_types[se_type]); var mel = addElem(marker_types[se_type]);
var fillcolor = color; var fillcolor = color;
if (se_type.substr(-2)=='_o') fillcolor='none'; if (se_type.substr(-2) === '_o') {fillcolor = 'none';}
mel.setAttribute('fill',fillcolor); mel.setAttribute('fill', fillcolor);
mel.setAttribute('stroke',color); mel.setAttribute('stroke', color);
mel.setAttribute('stroke-width',strokeWidth); mel.setAttribute('stroke-width', strokeWidth);
marker.appendChild(mel); marker.appendChild(mel);
} else { } else {
var text = addElem(marker_types[se_type]); var text = addElem(marker_types[se_type]);
@@ -248,42 +258,17 @@ svgEditor.addExtension("Markers", function(S) {
return marker; return marker;
} }
function setMarker() {
var poslist={'start_marker':'start','mid_marker':'mid','end_marker':'end'};
var pos = poslist[this.id];
var marker_name = 'marker-'+pos;
var val = this.value;
var el = selElems[0];
var marker = getLinked(el, marker_name);
if (marker) $(marker).remove();
el.removeAttribute(marker_name);
if (val=='') val='\\nomarker';
if (val=='\\nomarker') {
setIcon(pos,val);
S.call("changed", selElems);
return;
}
// Set marker on element
var id = marker_prefix + pos + '_' + el.id;
addMarker(id, val);
svgCanvas.changeSelectedAttribute(marker_name, "url(#" + id + ")");
if (el.tagName == "line" && pos=='mid') el=convertline(el);
S.call("changed", selElems);
setIcon(pos,val);
}
function convertline(elem) { function convertline(elem) {
// this routine came from the connectors extension // this routine came from the connectors extension
// it is needed because midpoint markers don't work with line elements // it is needed because midpoint markers don't work with line elements
if (!(elem.tagName == "line")) return elem; if (!(elem.tagName === 'line')) {return elem;}
// Convert to polyline to accept mid-arrow // Convert to polyline to accept mid-arrow
var x1 = elem.getAttribute('x1')-0; var x1 = Number(elem.getAttribute('x1'));
var x2 = elem.getAttribute('x2')-0; var x2 = Number(elem.getAttribute('x2'));
var y1 = elem.getAttribute('y1')-0; var y1 = Number(elem.getAttribute('y1'));
var y2 = elem.getAttribute('y2')-0; var y2 = Number(elem.getAttribute('y2'));
var id = elem.id; var id = elem.id;
var mid_pt = (' '+((x1+x2)/2)+','+((y1+y2)/2) + ' '); var mid_pt = (' '+((x1+x2)/2)+','+((y1+y2)/2) + ' ');
@@ -300,7 +285,7 @@ svgEditor.addExtension("Markers", function(S) {
$.each(mtypes, function(i, pos) { // get any existing marker definitions $.each(mtypes, function(i, pos) { // get any existing marker definitions
var nam = 'marker-'+pos; var nam = 'marker-'+pos;
var m = elem.getAttribute(nam); var m = elem.getAttribute(nam);
if (m) pline.setAttribute(nam,elem.getAttribute(nam)); if (m) {pline.setAttribute(nam,elem.getAttribute(nam));}
}); });
var batchCmd = new S.BatchCommand(); var batchCmd = new S.BatchCommand();
@@ -315,6 +300,30 @@ svgEditor.addExtension("Markers", function(S) {
return pline; return pline;
} }
function setMarker() {
var poslist={'start_marker':'start','mid_marker':'mid','end_marker':'end'};
var pos = poslist[this.id];
var marker_name = 'marker-'+pos;
var val = this.value;
var el = selElems[0];
var marker = getLinked(el, marker_name);
if (marker) {$(marker).remove();}
el.removeAttribute(marker_name);
if (val == '') {val = '\\nomarker';}
if (val == '\\nomarker') {
setIcon(pos,val);
S.call("changed", selElems);
return;
}
// Set marker on element
var id = marker_prefix + pos + '_' + el.id;
addMarker(id, val);
svgCanvas.changeSelectedAttribute(marker_name, "url(#" + id + ")");
if (el.tagName === 'line' && pos == 'mid') {el = convertline(el);}
S.call("changed", selElems);
setIcon(pos,val);
}
// called when the main system modifies an object // called when the main system modifies an object
// this routine changes the associated markers to be the same color // this routine changes the associated markers to be the same color
function colorChanged(elem) { function colorChanged(elem) {
@@ -322,34 +331,34 @@ svgEditor.addExtension("Markers", function(S) {
$.each(mtypes, function(i, pos) { $.each(mtypes, function(i, pos) {
var marker = getLinked(elem, 'marker-'+pos); var marker = getLinked(elem, 'marker-'+pos);
if (!marker) return; if (!marker) {return;}
if (!marker.attributes.se_type) return; //not created by this extension if (!marker.attributes.se_type) {return;} // not created by this extension
var ch = marker.lastElementChild; var ch = marker.lastElementChild;
if (!ch) return; if (!ch) {return;}
var curfill = ch.getAttribute("fill"); var curfill = ch.getAttribute('fill');
var curstroke = ch.getAttribute("stroke") var curstroke = ch.getAttribute('stroke');
if (curfill && curfill!='none') ch.setAttribute("fill",color); if (curfill && curfill != 'none') {ch.setAttribute('fill', color);}
if (curstroke && curstroke!='none') ch.setAttribute("stroke",color); if (curstroke && curstroke != 'none') {ch.setAttribute('stroke', color);}
}); });
} }
// called when the main system creates or modifies an object // called when the main system creates or modifies an object
// primary purpose is create new markers for cloned objects // primary purpose is create new markers for cloned objects
function updateReferences(el) { function updateReferences(el) {
$.each(mtypes, function (i,pos) { $.each(mtypes, function (i, pos) {
var id = marker_prefix + pos + '_' + el.id; var id = marker_prefix + pos + '_' + el.id;
var marker_name = 'marker-'+pos; var marker_name = 'marker-'+pos;
var marker = getLinked(el, marker_name); var marker = getLinked(el, marker_name);
if (!marker || !marker.attributes.se_type) return; //not created by this extension if (!marker || !marker.attributes.se_type) {return;} // not created by this extension
var url = el.getAttribute(marker_name); var url = el.getAttribute(marker_name);
if (url) { if (url) {
var len = el.id.length; var len = el.id.length;
var linkid = url.substr(-len-1,len); var linkid = url.substr(-len-1, len);
if (el.id != linkid) { if (el.id != linkid) {
var val = $('#'+pos+'_marker').attr('value'); var val = $('#'+pos + '_marker').attr('value');
addMarker(id, val); addMarker(id, val);
svgCanvas.changeSelectedAttribute(marker_name, "url(#" + id + ")"); svgCanvas.changeSelectedAttribute(marker_name, "url(#" + id + ")");
if (el.tagName == "line" && pos=='mid') el=convertline(el); if (el.tagName === 'line' && pos == 'mid') {el = convertline(el);}
S.call("changed", selElems); S.call("changed", selElems);
} }
} }
@@ -357,21 +366,23 @@ svgEditor.addExtension("Markers", function(S) {
} }
// simulate a change event a text box that stores the current element's marker type // simulate a change event a text box that stores the current element's marker type
function triggerTextEntry(pos,val) { function triggerTextEntry(pos, val) {
$('#'+pos+'_marker').val(val); $('#'+pos+'_marker').val(val);
$('#'+pos+'_marker').change(); $('#'+pos+'_marker').change();
var txtbox = $('#'+pos+'_marker'); // var txtbox = $('#'+pos+'_marker');
//if (val.substr(0,1)=='\\') txtbox.hide(); // if (val.substr(0,1)=='\\') {txtbox.hide();}
//else txtbox.show(); // else {txtbox.show();}
} }
function setIcon(pos,id) { function showTextPrompt(pos) {
if (id.substr(0,1)!='\\') id='\\textmarker' var def = $('#'+pos+'_marker').val();
var ci = '#'+id_prefix+pos+'_'+id.substr(1); if (def.substr(0,1) === '\\') {def = '';}
svgEditor.setIcon('#cur_' + pos +'_marker_list', $(ci).children()); $.prompt('Enter text for ' + pos + ' marker', def , function(txt) {
$(ci).addClass('current').siblings().removeClass('current'); if (txt) {triggerTextEntry(pos, txt);}
});
} }
/*
function setMarkerSet(obj) { function setMarkerSet(obj) {
var parts = this.id.split('_'); var parts = this.id.split('_');
var set = parts[2]; var set = parts[2];
@@ -393,32 +404,28 @@ svgEditor.addExtension("Markers", function(S) {
break; break;
} }
} }
*/
function showTextPrompt(pos) {
var def = $('#'+pos+'_marker').val();
if (def.substr(0,1)=='\\') def='';
$.prompt('Enter text for ' + pos + ' marker', def , function(txt) { if (txt) triggerTextEntry(pos,txt); });
}
// callback function for a toolbar button click // callback function for a toolbar button click
function setArrowFromButton(obj) { function setArrowFromButton(obj) {
var parts = this.id.split('_'); var parts = this.id.split('_');
var pos = parts[1]; var pos = parts[1];
var val = parts[2]; var val = parts[2];
if (parts[3]) val+='_'+parts[3]; if (parts[3]) { val += '_' + parts[3];}
if (val!='textmarker') { if (val != 'textmarker') {
triggerTextEntry(pos,'\\'+val); triggerTextEntry(pos, '\\'+val);
} else { } else {
showTextPrompt(pos); showTextPrompt(pos);
} }
} }
function getTitle(lang,id) { function getTitle(lang,id) {
var list = lang_list[lang]; var i, list = lang_list[lang];
for (var i in list) { for (i in list) {
if (list[i].id==id) return list[i].title; if (list.hasOwnProperty(i) && list[i].id == id) {
return list[i].title;
}
} }
return id; return id;
} }
@@ -428,7 +435,7 @@ svgEditor.addExtension("Markers", function(S) {
// TODO: need to incorporate language specific titles // TODO: need to incorporate language specific titles
function buildButtonList() { function buildButtonList() {
var buttons=[]; var buttons=[];
var i=0; // var i = 0;
/* /*
buttons.push({ buttons.push({
id:id_prefix + 'markers_off', id:id_prefix + 'markers_off',
@@ -452,10 +459,10 @@ svgEditor.addExtension("Markers", function(S) {
panel: 'marker_panel' panel: 'marker_panel'
}); });
*/ */
$.each(mtypes,function(k,pos) { $.each(mtypes,function(k, pos) {
var listname = pos + "_marker_list"; var listname = pos + "_marker_list";
var def = true; var def = true;
$.each(marker_types,function(id,v) { $.each(marker_types,function(id, v) {
var title = getTitle('en',id); var title = getTitle('en',id);
buttons.push({ buttons.push({
id:id_prefix + pos + "_" + id, id:id_prefix + pos + "_" + id,
@@ -543,7 +550,7 @@ svgEditor.addExtension("Markers", function(S) {
while(i--) { while(i--) {
var elem = selElems[i]; var elem = selElems[i];
if(elem && $.inArray(elem.tagName, marker_elems) != -1) { if(elem && $.inArray(elem.tagName, marker_elems) !== -1) {
if(opts.selectedElement && !opts.multiselected) { if(opts.selectedElement && !opts.multiselected) {
showPanel(true); showPanel(true);
} else { } else {
@@ -558,7 +565,7 @@ svgEditor.addExtension("Markers", function(S) {
elementChanged: function(opts) { elementChanged: function(opts) {
//console.log('elementChanged',opts); //console.log('elementChanged',opts);
var elem = opts.elems[0]; var elem = opts.elems[0];
if(elem && ( if (elem && (
elem.getAttribute("marker-start") || elem.getAttribute("marker-start") ||
elem.getAttribute("marker-mid") || elem.getAttribute("marker-mid") ||
elem.getAttribute("marker-end") elem.getAttribute("marker-end")
@@ -566,7 +573,7 @@ svgEditor.addExtension("Markers", function(S) {
colorChanged(elem); colorChanged(elem);
updateReferences(elem); updateReferences(elem);
} }
changing_flag = false; // changing_flag = false; // Not apparently in use
} }
}; };
}); });

View File

@@ -1,3 +1,5 @@
/*globals MathJax, svgEditor, svgCanvas, $*/
/*jslint es5: true, todo: true, vars: true*/
/* /*
* ext-mathjax.js * ext-mathjax.js
* *
@@ -7,11 +9,11 @@
* *
*/ */
svgEditor.addExtension("mathjax", function() { svgEditor.addExtension("mathjax", function() {'use strict';
// Configuration of the MathJax extention. // Configuration of the MathJax extention.
// This will be added to the head tag before MathJax is loaded. // This will be added to the head tag before MathJax is loaded.
var mathjaxConfiguration = '<script type="text/x-mathjax-config">\ var /*mathjaxConfiguration = '<script type="text/x-mathjax-config">\
MathJax.Hub.Config({\ MathJax.Hub.Config({\
extensions: ["tex2jax.js"],\ extensions: ["tex2jax.js"],\
jax: ["input/TeX","output/SVG"],\ jax: ["input/TeX","output/SVG"],\
@@ -23,7 +25,7 @@ svgEditor.addExtension("mathjax", function() {
style: {color: "#CC0000", "font-style":"italic"}\ style: {color: "#CC0000", "font-style":"italic"}\
},\ },\
elements: [],\ elements: [],\
tex2jax: {\ tex2jax: {\
ignoreClass: "tex2jax_ignore2", processClass: "tex2jax_process2",\ ignoreClass: "tex2jax_ignore2", processClass: "tex2jax_process2",\
},\ },\
TeX: {\ TeX: {\
@@ -31,9 +33,9 @@ svgEditor.addExtension("mathjax", function() {
},\ },\
"SVG": {\ "SVG": {\
}\ }\
});\ });\
</script>', </script>',*/
mathjaxSrc = 'http://cdn.mathjax.org/mathjax/latest/MathJax.js', // mathjaxSrc = 'http://cdn.mathjax.org/mathjax/latest/MathJax.js',
mathjaxSrcSecure = 'https://c328740.ssl.cf1.rackcdn.com/mathjax/latest/MathJax.js?config=TeX-AMS-MML_SVG.js', mathjaxSrcSecure = 'https://c328740.ssl.cf1.rackcdn.com/mathjax/latest/MathJax.js?config=TeX-AMS-MML_SVG.js',
math, math,
locationX, locationX,
@@ -76,13 +78,13 @@ svgEditor.addExtension("mathjax", function() {
var mathjaxMath = $('.MathJax_SVG'); var mathjaxMath = $('.MathJax_SVG');
var svg = $(mathjaxMath.html()); var svg = $(mathjaxMath.html());
svg.find('use').each(function() { svg.find('use').each(function() {
var x, y, transform; var x, y, id, transform;
// TODO: find a less pragmatic and more elegant solution to this. // TODO: find a less pragmatic and more elegant solution to this.
if ($(this).attr('href')) { if ($(this).attr('href')) {
var id = $(this).attr('href').slice(1); // Works in Chrome. id = $(this).attr('href').slice(1); // Works in Chrome.
} else { } else {
var id = $(this).attr('xlink:href').slice(1); // Works in Firefox. id = $(this).attr('xlink:href').slice(1); // Works in Firefox.
} }
var glymph = $('#' + id).clone().removeAttr('id'); var glymph = $('#' + id).clone().removeAttr('id');

View File

@@ -1,3 +1,5 @@
/*globals svgEditor, svgedit, $ */
/*jslint es5: true, vars: true*/
/* /*
* ext-overview_window.js * ext-overview_window.js
* *
@@ -7,8 +9,8 @@
* *
*/ */
var overviewWindowGlobals={}; var overviewWindowGlobals = {};
svgEditor.addExtension("overview_window", function() { svgEditor.addExtension("overview_window", function() { 'use strict';
//define and insert the base html element //define and insert the base html element
var propsWindowHtml= "\ var propsWindowHtml= "\
<div id=\"overview_window_content_pane\" style=\" width:100%; word-wrap:break-word; display:inline-block; margin-top:20px;\">\ <div id=\"overview_window_content_pane\" style=\" width:100%; word-wrap:break-word; display:inline-block; margin-top:20px;\">\
@@ -47,7 +49,7 @@ svgEditor.addExtension("overview_window", function() {
}; };
$("#workarea").scroll(function(){ $("#workarea").scroll(function(){
if(!(overviewWindowGlobals.viewBoxDragging)){ if(!(overviewWindowGlobals.viewBoxDragging)){
updateViewBox() updateViewBox();
} }
}); });
$("#workarea").resize(updateViewBox); $("#workarea").resize(updateViewBox);
@@ -111,8 +113,8 @@ svgEditor.addExtension("overview_window", function() {
var viewBoxWidth =parseFloat($("#overview_window_view_box").css("min-width" )); var viewBoxWidth =parseFloat($("#overview_window_view_box").css("min-width" ));
var viewBoxHeight=parseFloat($("#overview_window_view_box").css("min-height")); var viewBoxHeight=parseFloat($("#overview_window_view_box").css("min-height"));
var viewBoxX=mouseX-.5*viewBoxWidth; var viewBoxX=mouseX - 0.5 * viewBoxWidth;
var viewBoxY=mouseY-.5*viewBoxHeight; var viewBoxY=mouseY- 0.5 * viewBoxHeight;
//deal with constraints //deal with constraints
if(viewBoxX<0){ if(viewBoxX<0){
viewBoxX=0; viewBoxX=0;

View File

@@ -1,3 +1,5 @@
/*globals svgEditor, svgCanvas*/
/*jslint eqeq: true*/
/* /*
* ext-panning.js * ext-panning.js
* *
@@ -11,7 +13,7 @@
This is a very basic SVG-Edit extension to let tablet/mobile devices panning without problem This is a very basic SVG-Edit extension to let tablet/mobile devices panning without problem
*/ */
svgEditor.addExtension('ext-panning', function() { svgEditor.addExtension('ext-panning', function() {'use strict';
return { return {
name: 'Extension Panning', name: 'Extension Panning',
svgicons: svgEditor.curConfig.extPath + 'ext-panning.xml', svgicons: svgEditor.curConfig.extPath + 'ext-panning.xml',
@@ -26,13 +28,13 @@ svgEditor.addExtension('ext-panning', function() {
} }
}], }],
mouseDown: function() { mouseDown: function() {
if(svgCanvas.getMode() == 'ext-panning') { if (svgCanvas.getMode() == 'ext-panning') {
svgEditor.setPanning(true); svgEditor.setPanning(true);
return {started: true}; return {started: true};
} }
}, },
mouseUp: function() { mouseUp: function() {
if(svgCanvas.getMode() == 'ext-panning') { if (svgCanvas.getMode() == 'ext-panning') {
svgEditor.setPanning(false); svgEditor.setPanning(false);
return { return {
keep: false, keep: false,

View File

@@ -1,3 +1,5 @@
/*globals svgEditor, svgCanvas, svgedit, $*/
/*jslint vars: true, eqeq: true, todo: true */
/* /*
* ext-polygon.js * ext-polygon.js
* *
@@ -6,23 +8,29 @@
* All rights reserved * All rights reserved
* *
*/ */
svgEditor.addExtension("polygon", function(S){ svgEditor.addExtension("polygon", function(S) {'use strict';
var NS = svgedit.NS, var // NS = svgedit.NS,
svgcontent = S.svgcontent, // svgcontent = S.svgcontent,
addElem = S.addSvgElementFromJson, // addElem = S.addSvgElementFromJson,
selElems, selElems,
editingitex = false, svgdoc = S.svgroot.parentNode.ownerDocument, started, newFO, edg = 0, newFOG, newFOGParent, newDef, newImageName, newMaskID, undoCommand = "Not image", modeChangeG; editingitex = false,
// svgdoc = S.svgroot.parentNode.ownerDocument,
// newFOG, newFOGParent, newDef, newImageName, newMaskID, modeChangeG,
// edg = 0,
// undoCommand = "Not image";
started, newFO;
var ccZoom; // var ccZoom;
var wEl, hEl; // var wEl, hEl;
var wOffset, hOffset; // var wOffset, hOffset;
var ccRBG, ccRgbEl; // var ccRBG;
var ccOpacity; var ccRgbEl;
var brushW, brushH, shape; // var ccOpacity;
// var brushW, brushH;
var ccDebug = document.getElementById('debugpanel'); var shape;
// var ccDebug = document.getElementById('debugpanel');
/* var properlySourceSizeTextArea = function(){ /* var properlySourceSizeTextArea = function(){
// TODO: remove magic numbers here and get values from CSS // TODO: remove magic numbers here and get values from CSS
@@ -38,10 +46,12 @@ svgEditor.addExtension("polygon", function(S){
$('#polygon_panel').toggle(on); $('#polygon_panel').toggle(on);
} }
/*
function toggleSourceButtons(on){ function toggleSourceButtons(on){
$('#tool_source_save, #tool_source_cancel').toggle(!on); $('#tool_source_save, #tool_source_cancel').toggle(!on);
$('#polygon_save, #polygon_cancel').toggle(on); $('#polygon_save, #polygon_cancel').toggle(on);
} }
*/
function setAttr(attr, val){ function setAttr(attr, val){
svgCanvas.changeSelectedAttribute(attr, val); svgCanvas.changeSelectedAttribute(attr, val);
@@ -50,14 +60,57 @@ svgEditor.addExtension("polygon", function(S){
function cot(n){ function cot(n){
return 1 / Math.tan(n); return 1 / Math.tan(n);
}; }
function sec(n){ function sec(n){
return 1 / Math.cos(n); return 1 / Math.cos(n);
}; }
/**
* Obtained from http://code.google.com/p/passenger-top/source/browse/instiki/public/svg-edit/editor/extensions/ext-itex.js?r=3
* This function sets the content of of the currently-selected foreignObject element,
* based on the itex contained in string.
* @param {string} tex The itex text.
* @returns This function returns false if the set was unsuccessful, true otherwise.
*/
/*
function setItexString(tex) {
var mathns = 'http://www.w3.org/1998/Math/MathML',
xmlnsns = 'http://www.w3.org/2000/xmlns/',
ajaxEndpoint = '../../itex';
var elt = selElems[0];
try {
var math = svgdoc.createElementNS(mathns, 'math');
math.setAttributeNS(xmlnsns, 'xmlns', mathns);
math.setAttribute('display', 'inline');
var semantics = document.createElementNS(mathns, 'semantics');
var annotation = document.createElementNS(mathns, 'annotation');
annotation.setAttribute('encoding', 'application/x-tex');
annotation.textContent = tex;
var mrow = document.createElementNS(mathns, 'mrow');
semantics.appendChild(mrow);
semantics.appendChild(annotation);
math.appendChild(semantics);
// make an AJAX request to the server, to get the MathML
$.post(ajaxEndpoint, {'tex': tex, 'display': 'inline'}, function(data){
var children = data.documentElement.childNodes;
while (children.length > 0) {
mrow.appendChild(svgdoc.adoptNode(children[0], true));
}
S.sanitizeSvg(math);
S.call("changed", [elt]);
});
elt.replaceChild(math, elt.firstChild);
S.call("changed", [elt]);
svgCanvas.clearSelection();
} catch(e) {
console.log(e);
return false;
}
return true;
}
*/
return { return {
name: "polygon", name: "polygon",
svgicons: svgEditor.curConfig.extPath + "polygon-icons.svg", svgicons: svgEditor.curConfig.extPath + "polygon-icons.svg",
@@ -95,20 +148,22 @@ svgEditor.addExtension("polygon", function(S){
$('#polygon_panel').hide(); $('#polygon_panel').hide();
var endChanges = function(){ var endChanges = function(){
} };
// TODO: Needs to be done after orig icon loads // TODO: Needs to be done after orig icon loads
setTimeout(function(){ setTimeout(function(){
// Create source save/cancel buttons // Create source save/cancel buttons
var save = $('#tool_source_save').clone().hide().attr('id', 'polygon_save').unbind().appendTo("#tool_source_back").click(function(){ var save = $('#tool_source_save').clone().hide().attr('id', 'polygon_save').unbind().appendTo("#tool_source_back").click(function(){
if (!editingitex) if (!editingitex) {
return; return;
}
// Todo: Uncomment the setItexString() function above and handle ajaxEndpoint?
if (!setItexString($('#svg_source_textarea').val())) { if (!setItexString($('#svg_source_textarea').val())) {
$.confirm("Errors found. Revert to original?", function(ok){ $.confirm("Errors found. Revert to original?", function(ok){
if (!ok) if (!ok) {
return false; return false;
}
endChanges(); endChanges();
}); });
} }
@@ -125,13 +180,13 @@ svgEditor.addExtension("polygon", function(S){
}, 3000); }, 3000);
}, },
mouseDown: function(opts){ mouseDown: function(opts){
var e = opts.event; // var e = opts.event;
rgb = svgCanvas.getColor("fill"); var rgb = svgCanvas.getColor("fill");
ccRgbEl = rgb.substring(1, rgb.length); ccRgbEl = rgb.substring(1, rgb.length);
var sRgb = svgCanvas.getColor("stroke");
// ccSRgbEl = sRgb.substring(1, rgb.length);
sRgb = svgCanvas.getColor("stroke"); sRgb = svgCanvas.getColor("stroke");
ccSRgbEl = sRgb.substring(1, rgb.length); var sWidth = svgCanvas.getStrokeWidth();
sRgb = svgCanvas.getColor("stroke");
sWidth = svgCanvas.getStrokeWidth();
if (svgCanvas.getMode() == "polygon") { if (svgCanvas.getMode() == "polygon") {
started = true; started = true;
@@ -154,27 +209,31 @@ svgEditor.addExtension("polygon", function(S){
return { return {
started: true started: true
} };
} }
}, },
mouseMove: function(opts){ mouseMove: function(opts){
if (!started) if (!started) {
return; return;
}
if (svgCanvas.getMode() == "polygon") { if (svgCanvas.getMode() == "polygon") {
var e = opts.event; // var e = opts.event;
var x = opts.mouse_x; var x = opts.mouse_x;
var y = opts.mouse_y; var y = opts.mouse_y;
var c = $(newFO).attr(["cx", "cy", "sides", "orient", "fill", "strokecolor", "strokeWidth"]); var c = $(newFO).attr(["cx", "cy", "sides", "orient", "fill", "strokecolor", "strokeWidth"]);
var cx = c.cx, cy = c.cy, fill = c.fill, strokecolor = c.strokecolor, strokewidth = c.strokeWidth, sides = c.sides, orient = c.orient, edg = (Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy))) / 1.5; var cx = c.cx, cy = c.cy, fill = c.fill, strokecolor = c.strokecolor, strokewidth = c.strokeWidth, sides = c.sides,
// orient = c.orient,
edg = (Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy))) / 1.5;
newFO.setAttributeNS(null, "edge", edg); newFO.setAttributeNS(null, "edge", edg);
var inradius = (edg / 2) * cot(Math.PI / sides); var inradius = (edg / 2) * cot(Math.PI / sides);
var circumradius = inradius * sec(Math.PI / sides); var circumradius = inradius * sec(Math.PI / sides);
var points = ''; var points = '';
for (var s = 0; sides >= s; s++) { var s;
for (s = 0; sides >= s; s++) {
var angle = 2.0 * Math.PI * s / sides; var angle = 2.0 * Math.PI * s / sides;
var x = (circumradius * Math.cos(angle)) + cx; x = (circumradius * Math.cos(angle)) + cx;
var y = (circumradius * Math.sin(angle)) + cy; y = (circumradius * Math.sin(angle)) + cy;
points += x + ',' + y + ' '; points += x + ',' + y + ' ';
} }
@@ -190,7 +249,7 @@ svgEditor.addExtension("polygon", function(S){
//DrawPoly(cx, cy, sides, edg, orient); //DrawPoly(cx, cy, sides, edg, orient);
return { return {
started: true started: true
} };
} }
}, },
@@ -198,12 +257,12 @@ svgEditor.addExtension("polygon", function(S){
mouseUp: function(opts){ mouseUp: function(opts){
if (svgCanvas.getMode() == "polygon") { if (svgCanvas.getMode() == "polygon") {
var attrs = $(newFO).attr("edge"); var attrs = $(newFO).attr("edge");
keep = (attrs.edge != 0); var keep = (attrs.edge != 0);
// svgCanvas.addToSelection([newFO], true); // svgCanvas.addToSelection([newFO], true);
return { return {
keep: keep, keep: keep,
element: newFO element: newFO
} };
} }
}, },
@@ -215,7 +274,7 @@ svgEditor.addExtension("polygon", function(S){
while (i--) { while (i--) {
var elem = selElems[i]; var elem = selElems[i];
if (elem && elem.getAttributeNS(null, 'shape') == "regularPoly") { if (elem && elem.getAttributeNS(null, 'shape') === 'regularPoly') {
if (opts.selectedElement && !opts.multiselected) { if (opts.selectedElement && !opts.multiselected) {
$('#polySides').val(elem.getAttribute("sides")); $('#polySides').val(elem.getAttribute("sides"));
@@ -231,7 +290,7 @@ svgEditor.addExtension("polygon", function(S){
} }
}, },
elementChanged: function(opts){ elementChanged: function(opts){
var elem = opts.elems[0]; // var elem = opts.elems[0];
} }
}; };
}); });

View File

@@ -1,3 +1,5 @@
/*globals svgEditor, svgedit, svgCanvas, canvg, $, top*/
/*jslint vars: true*/
/* /*
* ext-server_moinsave.js * ext-server_moinsave.js
* *
@@ -11,7 +13,7 @@
*/ */
svgEditor.addExtension("server_opensave", { svgEditor.addExtension("server_opensave", {
callback: function() { callback: function() {'use strict';
var save_svg_action = '/+modify'; var save_svg_action = '/+modify';
@@ -31,24 +33,25 @@ svgEditor.addExtension("server_opensave", {
c.width = svgCanvas.contentW; c.width = svgCanvas.contentW;
c.height = svgCanvas.contentH; c.height = svgCanvas.contentH;
$.getScript('canvg/canvg.js', function() { $.getScript('canvg/canvg.js', function() {
canvg(c, svg, {renderCallback: function() { canvg(c, svg, {renderCallback: function() {
var datauri = c.toDataURL('image/png'); var datauri = c.toDataURL('image/png');
var uiStrings = svgEditor.uiStrings; // var uiStrings = svgEditor.uiStrings;
var png_data = svgedit.utilities.encode64(datauri); var png_data = svgedit.utilities.encode64(datauri);
var form = $('<form>').attr({ var form = $('<form>').attr({
method: 'post', method: 'post',
action: save_svg_action + '/' + name, action: save_svg_action + '/' + name,
target: 'output_frame' target: 'output_frame'
}) .append('<input type="hidden" name="png_data" value="' + png_data + '">') }).append('<input type="hidden" name="png_data" value="' + png_data + '">')
.append('<input type="hidden" name="filepath" value="' + svg_data + '">') .append('<input type="hidden" name="filepath" value="' + svg_data + '">')
.append('<input type="hidden" name="filename" value="' + 'drawing.svg">') .append('<input type="hidden" name="filename" value="' + 'drawing.svg">')
.append('<input type="hidden" name="contenttype" value="application/x-svgdraw">') .append('<input type="hidden" name="contenttype" value="application/x-svgdraw">')
.appendTo('body') .appendTo('body')
.submit().remove(); .submit().remove();
}})}); }});
});
alert("Saved! Return to Item View!"); alert("Saved! Return to Item View!");
top.window.location = '/'+name; top.window.location = '/'+name;
}, }
}); });
} }

View File

@@ -1,4 +1,5 @@
/*globals svgEditor, svgCanvas, canvg, $*/ /*globals svgEditor, svgedit, svgCanvas, canvg, $*/
/*jslint eqeq: true*/
/* /*
* ext-server_opensave.js * ext-server_opensave.js
* *
@@ -70,7 +71,7 @@ svgEditor.addExtension("server_opensave", {
canvg(c, data.svg, {renderCallback: function() { canvg(c, data.svg, {renderCallback: function() {
var pre, filename, suffix, var pre, filename, suffix,
datauri = quality ? c.toDataURL(mimeType, quality) : c.toDataURL(mimeType), datauri = quality ? c.toDataURL(mimeType, quality) : c.toDataURL(mimeType),
uiStrings = svgEditor.uiStrings, // uiStrings = svgEditor.uiStrings,
note = ''; note = '';
// Check if there are issues // Check if there are issues

View File

@@ -1,3 +1,5 @@
/*globals svgEditor, $, DOMParser*/
/*jslint es5: true, vars: true, eqeq: true*/
/* /*
* ext-shapes.js * ext-shapes.js
* *
@@ -8,7 +10,7 @@
* *
*/ */
svgEditor.addExtension('shapes', function() { svgEditor.addExtension('shapes', function() {'use strict';
var current_d, cur_shape_id; var current_d, cur_shape_id;
var canv = svgEditor.canvas; var canv = svgEditor.canvas;
var cur_shape; var cur_shape;
@@ -73,34 +75,12 @@ svgEditor.addExtension('shapes', function() {
var cur_lib = library.basic; var cur_lib = library.basic;
var mode_id = 'shapelib'; var mode_id = 'shapelib';
var startClientPos = {}; var startClientPos = {};
function loadIcons() { function loadIcons() {
$('#shape_buttons').empty().append(cur_lib.buttons); $('#shape_buttons').empty().append(cur_lib.buttons);
} }
function loadLibrary(cat_id) {
var lib = library[cat_id];
if (!lib) {
$('#shape_buttons').html('Loading...');
$.getJSON(svgEditor.curConfig.extPath + 'shapelib/' + cat_id + '.json', function(result) {
cur_lib = library[cat_id] = {
data: result.data,
size: result.size,
fill: result.fill
};
makeButtons(cat_id, result);
loadIcons();
});
return;
}
cur_lib = lib;
if (!lib.buttons.length) makeButtons(cat_id, lib);
loadIcons();
}
function makeButtons(cat, shapes) { function makeButtons(cat, shapes) {
var size = cur_lib.size || 300; var size = cur_lib.size || 300;
var fill = cur_lib.fill || false; var fill = cur_lib.fill || false;
@@ -120,8 +100,8 @@ svgEditor.addExtension('shapes', function() {
var data = shapes.data; var data = shapes.data;
cur_lib.buttons = []; cur_lib.buttons = [];
var id;
for (var id in data) { for (id in data) {
var path_d = data[id]; var path_d = data[id];
var icon = svg_elem.clone(); var icon = svg_elem.clone();
icon.find('path').attr('d', path_d); icon.find('path').attr('d', path_d);
@@ -135,6 +115,28 @@ svgEditor.addExtension('shapes', function() {
} }
} }
function loadLibrary(cat_id) {
var lib = library[cat_id];
if (!lib) {
$('#shape_buttons').html('Loading...');
$.getJSON(svgEditor.curConfig.extPath + 'shapelib/' + cat_id + '.json', function(result) {
cur_lib = library[cat_id] = {
data: result.data,
size: result.size,
fill: result.fill
};
makeButtons(cat_id, result);
loadIcons();
});
return;
}
cur_lib = lib;
if (!lib.buttons.length) {makeButtons(cat_id, lib);}
loadIcons();
}
return { return {
svgicons: svgEditor.curConfig.extPath + 'ext-shapes.xml', svgicons: svgEditor.curConfig.extPath + 'ext-shapes.xml',
buttons: [{ buttons: [{
@@ -189,7 +191,7 @@ svgEditor.addExtension('shapes', function() {
$('#shape_buttons').mouseup(function(evt) { $('#shape_buttons').mouseup(function(evt) {
var btn = $(evt.target).closest('div.tool_button'); var btn = $(evt.target).closest('div.tool_button');
if (!btn.length) return; if (!btn.length) {return;}
var copy = btn.children().clone(); var copy = btn.children().clone();
shower.children(':not(.flyout_arrow_horiz)').remove(); shower.children(':not(.flyout_arrow_horiz)').remove();
@@ -239,14 +241,16 @@ svgEditor.addExtension('shapes', function() {
}, },
mouseDown: function(opts) { mouseDown: function(opts) {
var mode = canv.getMode(); var mode = canv.getMode();
if (mode !== mode_id) return; if (mode !== mode_id) {return;}
var x = start_x = opts.start_x; start_x = opts.start_x;
var y = start_y = opts.start_y; var x = start_x;
start_y = opts.start_y;
var y = start_y;
var cur_style = canv.getStyle(); var cur_style = canv.getStyle();
startClientPos.x = opts.event.clientX; startClientPos.x = opts.event.clientX;
startClientPos.y = opts.event.clientY; startClientPos.y = opts.event.clientY;
cur_shape = canv.addSvgElementFromJson({ cur_shape = canv.addSvgElementFromJson({
'element': 'path', 'element': 'path',
@@ -279,7 +283,7 @@ svgEditor.addExtension('shapes', function() {
}, },
mouseMove: function(opts) { mouseMove: function(opts) {
var mode = canv.getMode(); var mode = canv.getMode();
if (mode !== mode_id) return; if (mode !== mode_id) {return;}
var zoom = canv.getZoom(); var zoom = canv.getZoom();
var evt = opts.event; var evt = opts.event;
@@ -311,7 +315,7 @@ svgEditor.addExtension('shapes', function() {
if (x < start_x) { if (x < start_x) {
tx = lastBBox.width; tx = lastBBox.width;
} }
if (y < start_y) ty = lastBBox.height; if (y < start_y) {ty = lastBBox.height;}
// update the transform list with translate,scale,translate // update the transform list with translate,scale,translate
var translateOrigin = svgroot.createSVGTransform(), var translateOrigin = svgroot.createSVGTransform(),
@@ -338,7 +342,7 @@ svgEditor.addExtension('shapes', function() {
}, },
mouseUp: function(opts) { mouseUp: function(opts) {
var mode = canv.getMode(); var mode = canv.getMode();
if (mode !== mode_id) return; if (mode !== mode_id) {return;}
var keepObject = (opts.event.clientX != startClientPos.x && opts.event.clientY != startClientPos.y); var keepObject = (opts.event.clientX != startClientPos.x && opts.event.clientY != startClientPos.y);

View File

@@ -1,3 +1,5 @@
/*globals svgEditor, svgedit, svgCanvas, $*/
/*jslint vars: true, eqeq: true*/
/* /*
* ext-star.js * ext-star.js
* *
@@ -7,31 +9,19 @@
* *
*/ */
svgEditor.addExtension('star', function(S){ svgEditor.addExtension('star', function(S){'use strict';
var NS = svgedit.NS, var // NS = svgedit.NS,
svgcontent = S.svgcontent, // svgcontent = S.svgcontent,
selElems, selElems,
editingitex = false, // editingitex = false,
svgdoc = S.svgroot.parentNode.ownerDocument, // svgdoc = S.svgroot.parentNode.ownerDocument,
started, started,
newFO, newFO,
edg = 0, // edg = 0,
newFOG, // newFOG, newFOGParent, newDef, newImageName, newMaskID,
newFOGParent, // undoCommand = 'Not image',
newDef, // modeChangeG, ccZoom, wEl, hEl, wOffset, hOffset, ccRgbEl, brushW, brushH,
newImageName,
newMaskID,
undoCommand = 'Not image',
modeChangeG,
ccZoom,
wEl,
hEl,
wOffset,
hOffset,
ccRgbEl,
brushW,
brushH,
shape; shape;
function showPanel(on){ function showPanel(on){
@@ -43,15 +33,18 @@ svgEditor.addExtension('star', function(S){
$('#star_panel').toggle(on); $('#star_panel').toggle(on);
} }
/*
function toggleSourceButtons(on){ function toggleSourceButtons(on){
$('#star_save, #star_cancel').toggle(on); $('#star_save, #star_cancel').toggle(on);
} }
*/
function setAttr(attr, val){ function setAttr(attr, val){
svgCanvas.changeSelectedAttribute(attr, val); svgCanvas.changeSelectedAttribute(attr, val);
S.call('changed', selElems); S.call('changed', selElems);
} }
/*
function cot(n){ function cot(n){
return 1 / Math.tan(n); return 1 / Math.tan(n);
} }
@@ -59,6 +52,7 @@ svgEditor.addExtension('star', function(S){
function sec(n){ function sec(n){
return 1 / Math.cos(n); return 1 / Math.cos(n);
} }
*/
return { return {
name: 'star', name: 'star',
@@ -113,13 +107,13 @@ svgEditor.addExtension('star', function(S){
}], }],
callback: function(){ callback: function(){
$('#star_panel').hide(); $('#star_panel').hide();
var endChanges = function(){}; // var endChanges = function(){};
}, },
mouseDown: function(opts){ mouseDown: function(opts){
var rgb = svgCanvas.getColor('fill'); var rgb = svgCanvas.getColor('fill');
var ccRgbEl = rgb.substring(1, rgb.length); // var ccRgbEl = rgb.substring(1, rgb.length);
var sRgb = svgCanvas.getColor('stroke'); var sRgb = svgCanvas.getColor('stroke');
var ccSRgbEl = sRgb.substring(1, rgb.length); // var ccSRgbEl = sRgb.substring(1, rgb.length);
var sWidth = svgCanvas.getStrokeWidth(); var sWidth = svgCanvas.getStrokeWidth();
if (svgCanvas.getMode() == 'star') { if (svgCanvas.getMode() == 'star') {
@@ -148,8 +142,9 @@ svgEditor.addExtension('star', function(S){
} }
}, },
mouseMove: function(opts){ mouseMove: function(opts){
if (!started) if (!started) {
return; return;
}
if (svgCanvas.getMode() == 'star') { if (svgCanvas.getMode() == 'star') {
var x = opts.mouse_x; var x = opts.mouse_x;
var y = opts.mouse_y; var y = opts.mouse_y;
@@ -160,7 +155,8 @@ svgEditor.addExtension('star', function(S){
newFO.setAttributeNS(null, 'r2', inradius); newFO.setAttributeNS(null, 'r2', inradius);
var polyPoints = ''; var polyPoints = '';
for (var s = 0; point >= s; s++) { var s;
for (s = 0; point >= s; s++) {
var angle = 2.0 * Math.PI * (s / point); var angle = 2.0 * Math.PI * (s / point);
if ('point' == orient) { if ('point' == orient) {
angle -= (Math.PI / 2); angle -= (Math.PI / 2);
@@ -218,7 +214,7 @@ svgEditor.addExtension('star', function(S){
while (i--) { while (i--) {
var elem = selElems[i]; var elem = selElems[i];
if (elem && elem.getAttributeNS(null, 'shape') == 'star') { if (elem && elem.getAttributeNS(null, 'shape') === 'star') {
if (opts.selectedElement && !opts.multiselected) { if (opts.selectedElement && !opts.multiselected) {
// $('#starRadiusMulitplier').val(elem.getAttribute('r2')); // $('#starRadiusMulitplier').val(elem.getAttribute('r2'));
$('#starNumPoints').val(elem.getAttribute('point')); $('#starNumPoints').val(elem.getAttribute('point'));
@@ -234,7 +230,7 @@ svgEditor.addExtension('star', function(S){
} }
}, },
elementChanged: function(opts){ elementChanged: function(opts){
var elem = opts.elems[0]; // var elem = opts.elems[0];
} }
}; };
}); });

View File

@@ -12,50 +12,53 @@
<a href="../../images/logo.png">logo.png</a> <a href="../../images/logo.png">logo.png</a>
<script> <script>
/*globals $*/
$('a').click(function() { /*jslint vars: true*/
$('a').click(function() {'use strict';
var meta_str;
var href = this.href; var href = this.href;
var target = window.parent; var target = window.parent;
// Convert Non-SVG images to data URL first // Convert Non-SVG images to data URL first
// (this could also have been done server-side by the library) // (this could also have been done server-side by the library)
if(this.href.indexOf('.svg') === -1) { if (this.href.indexOf('.svg') === -1) {
var meta_str = JSON.stringify({ meta_str = JSON.stringify({
name: $(this).text(), name: $(this).text(),
id: href id: href
}); });
target.postMessage(meta_str, "*"); target.postMessage(meta_str, '*');
var img = new Image(); var img = new Image();
img.onload = function() { img.onload = function() {
var canvas = document.createElement("canvas"); var canvas = document.createElement('canvas');
canvas.width = this.width; canvas.width = this.width;
canvas.height = this.height; canvas.height = this.height;
// load the raster image into the canvas // load the raster image into the canvas
canvas.getContext("2d").drawImage(this,0,0); canvas.getContext('2d').drawImage(this, 0, 0);
// retrieve the data: URL // retrieve the data: URL
var dataurl;
try { try {
var dataurl = canvas.toDataURL(); dataurl = canvas.toDataURL();
} catch(err) { } catch(err) {
// This fails in Firefox with file:// URLs :( // This fails in Firefox with file:// URLs :(
alert("Data URL conversion failed: " + err); alert("Data URL conversion failed: " + err);
var dataurl = ""; dataurl = "";
} }
target.postMessage('|' + href + '|' + dataurl, "*"); target.postMessage('|' + href + '|' + dataurl, '*');
} };
img.src = href; img.src = href;
} else { } else {
// Send metadata (also indicates file is about to be sent) // Send metadata (also indicates file is about to be sent)
var meta_str = JSON.stringify({ meta_str = JSON.stringify({
name: $(this).text(), name: $(this).text(),
id: href id: href
}); });
target.postMessage(meta_str, "*"); target.postMessage(meta_str, '*');
// Do ajax request for image's href value // Do ajax request for image's href value
$.get(href, function(data) { $.get(href, function(data) {
data = '|' + href + '|' + data; data = '|' + href + '|' + data;
// This is where the magic happens! // This is where the magic happens!
target.postMessage(data, "*"); target.postMessage(data, '*');
}, 'html'); // 'html' is necessary to keep returned data as a string }, 'html'); // 'html' is necessary to keep returned data as a string
} }