- Build: Babel 7

- npm: Update qr-manipulation
master
Brett Zamir 2018-09-26 21:14:12 +08:00
parent 9f7f7b9732
commit ae58be8277
64 changed files with 45118 additions and 31331 deletions

View File

@ -1,13 +1,5 @@
{
"presets": [
[
"env",
{
"modules": false
}
]
],
"plugins": [
"external-helpers"
["@babel/preset-env"]
]
}

2560
dist/canvg.js vendored

File diff suppressed because it is too large Load Diff

25
dist/dom-polyfill.js vendored
View File

@ -2,13 +2,13 @@
'use strict';
// From https://github.com/inexorabletash/polyfill/blob/master/dom.js
function mixin(o, ps) {
if (!o) return;
Object.keys(ps).forEach(function (p) {
if (p in o || p in o.prototype) {
return;
}
try {
Object.defineProperty(o.prototype, p, Object.getOwnPropertyDescriptor(ps, p));
} catch (ex) {
@ -22,9 +22,11 @@
nodes = nodes.map(function (node) {
return !(node instanceof Node) ? document.createTextNode(node) : node;
});
if (nodes.length === 1) {
return nodes[0];
}
var node = document.createDocumentFragment();
nodes.forEach(function (n) {
node.appendChild(n);
@ -34,7 +36,7 @@
var ParentNode = {
prepend: function prepend() {
for (var _len = arguments.length, nodes = Array(_len), _key = 0; _key < _len; _key++) {
for (var _len = arguments.length, nodes = new Array(_len), _key = 0; _key < _len; _key++) {
nodes[_key] = arguments[_key];
}
@ -42,7 +44,7 @@
this.insertBefore(nodes, this.firstChild);
},
append: function append() {
for (var _len2 = arguments.length, nodes = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
for (var _len2 = arguments.length, nodes = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
nodes[_key2] = arguments[_key2];
}
@ -50,12 +52,10 @@
this.appendChild(nodes);
}
};
mixin(Document || HTMLDocument, ParentNode); // HTMLDocument for IE8
mixin(DocumentFragment, ParentNode);
mixin(Element, ParentNode);
// Mixin ChildNode
mixin(DocumentFragment, ParentNode);
mixin(Element, ParentNode); // Mixin ChildNode
// https://dom.spec.whatwg.org/#interface-childnode
var ChildNode = {
@ -64,13 +64,14 @@
if (!parent) return;
var viablePreviousSibling = this.previousSibling;
for (var _len3 = arguments.length, nodes = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
for (var _len3 = arguments.length, nodes = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
nodes[_key3] = arguments[_key3];
}
while (nodes.includes(viablePreviousSibling)) {
viablePreviousSibling = viablePreviousSibling.previousSibling;
}
var node = convertNodesIntoANode(nodes);
parent.insertBefore(node, viablePreviousSibling ? viablePreviousSibling.nextSibling : parent.firstChild);
},
@ -79,13 +80,14 @@
if (!parent) return;
var viableNextSibling = this.nextSibling;
for (var _len4 = arguments.length, nodes = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
for (var _len4 = arguments.length, nodes = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
nodes[_key4] = arguments[_key4];
}
while (nodes.includes(viableNextSibling)) {
viableNextSibling = viableNextSibling.nextSibling;
}
var node = convertNodesIntoANode(nodes);
parent.insertBefore(node, viableNextSibling);
},
@ -94,13 +96,14 @@
if (!parent) return;
var viableNextSibling = this.nextSibling;
for (var _len5 = arguments.length, nodes = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
for (var _len5 = arguments.length, nodes = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
nodes[_key5] = arguments[_key5];
}
while (nodes.includes(viableNextSibling)) {
viableNextSibling = viableNextSibling.nextSibling;
}
var node = convertNodesIntoANode(nodes);
if (this.parentNode === parent) {
@ -113,10 +116,10 @@
if (!this.parentNode) {
return;
}
this.parentNode.removeChild(this);
}
};
mixin(DocumentType, ChildNode);
mixin(Element, ChildNode);
mixin(CharacterData, ChildNode);

View File

@ -1,11 +1,7 @@
var svgEditorExtension_arrows = (function () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
@ -17,20 +13,32 @@ var svgEditorExtension_arrows = (function () {
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
Promise.resolve(value).then(_next, _throw);
}
}
return step("next");
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
};
}
/* globals jQuery */
/**
* ext-arrows.js
*
@ -42,34 +50,38 @@ var svgEditorExtension_arrows = (function () {
var extArrows = {
name: 'arrows',
init: function () {
var _ref = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(S) {
var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee2(S) {
var strings, svgEditor, svgCanvas, $, addElem, nonce, prefix, selElems, arrowprefix, randomizeIds, setArrowNonce, unsetArrowNonce, pathdata, getLinked, showPanel, resetMarker, addMarker, setArrow, colorChanged, contextTools;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
colorChanged = function colorChanged(elem) {
colorChanged = function _ref9(elem) {
var color = elem.getAttribute('stroke');
var mtypes = ['start', 'mid', 'end'];
var defs = svgCanvas.findDefs();
$.each(mtypes, function (i, type) {
var marker = getLinked(elem, 'marker-' + type);
if (!marker) {
return;
}
var curColor = $(marker).children().attr('fill');
var curD = $(marker).children().attr('d');
if (curColor === color) {
return;
}
var allMarkers = $(defs).find('marker');
var newMarker = null;
// Different color, check if already made
var newMarker = null; // Different color, check if already made
allMarkers.each(function () {
var attrs = $(this).children().attr(['fill', 'd']);
if (attrs.fill === color && attrs.d === curD) {
// Found another marker with this color and this path
newMarker = this;
@ -80,15 +92,12 @@ var svgEditorExtension_arrows = (function () {
// Create a new marker with this color
var lastId = marker.id;
var dir = lastId.includes('_fw') ? 'fw' : 'bk';
newMarker = addMarker(dir, type, arrowprefix + dir + allMarkers.length);
$(newMarker).children().attr('fill', color);
}
$(elem).attr('marker-' + type, 'url(#' + newMarker.id + ')');
$(elem).attr('marker-' + type, 'url(#' + newMarker.id + ')'); // Check if last marker can be removed
// Check if last marker can be removed
var remove = true;
$(S.svgcontent).find('line, polyline, path, polygon').each(function () {
var elem = this;
@ -98,28 +107,29 @@ var svgEditorExtension_arrows = (function () {
return remove;
}
});
if (!remove) {
return false;
}
});
}); // Not found, so can safely remove
// Not found, so can safely remove
if (remove) {
$(marker).remove();
}
});
};
setArrow = function setArrow() {
setArrow = function _ref8() {
resetMarker();
var type = this.value;
if (type === 'none') {
return;
}
} // Set marker on element
// Set marker on element
var dir = 'fw';
if (type === 'mid_bk') {
type = 'mid';
dir = 'bk';
@ -137,10 +147,9 @@ var svgEditorExtension_arrows = (function () {
svgCanvas.call('changed', selElems);
};
addMarker = function addMarker(dir, type, id) {
addMarker = function _ref7(dir, type, id) {
// TODO: Make marker (or use?) per arrow type, since refX can be different
id = id || arrowprefix + dir;
var data = pathdata[dir];
if (type === 'mid') {
@ -148,6 +157,7 @@ var svgEditorExtension_arrows = (function () {
}
var marker = svgCanvas.getElem(id);
if (!marker) {
marker = addElem({
element: 'marker',
@ -160,6 +170,7 @@ var svgEditorExtension_arrows = (function () {
markerHeight: 5,
orient: 'auto',
style: 'pointer-events:none' // Currently needed for Opera
}
});
var arrow = addElem({
@ -174,25 +185,26 @@ var svgEditorExtension_arrows = (function () {
}
marker.setAttribute('refX', data.refx);
return marker;
};
resetMarker = function resetMarker() {
resetMarker = function _ref6() {
var el = selElems[0];
el.removeAttribute('marker-start');
el.removeAttribute('marker-mid');
el.removeAttribute('marker-end');
};
showPanel = function showPanel(on) {
showPanel = function _ref5(on) {
$('#arrow_panel').toggle(on);
if (on) {
var el = selElems[0];
var end = el.getAttribute('marker-end');
var start = el.getAttribute('marker-start');
var mid = el.getAttribute('marker-mid');
var val = void 0;
var val;
if (end && start) {
val = 'both';
} else if (end) {
@ -201,6 +213,7 @@ var svgEditorExtension_arrows = (function () {
val = 'start';
} else if (mid) {
val = 'mid';
if (mid.includes('bk')) {
val = 'mid_bk';
}
@ -214,26 +227,30 @@ var svgEditorExtension_arrows = (function () {
}
};
getLinked = function getLinked(elem, attr) {
getLinked = function _ref4(elem, attr) {
var str = elem.getAttribute(attr);
if (!str) {
return null;
}
var m = str.match(/\(#(.*)\)/);
if (!m || m.length !== 2) {
return null;
}
return svgCanvas.getElem(m[1]);
};
unsetArrowNonce = function unsetArrowNonce(window) {
unsetArrowNonce = function _ref3(window) {
randomizeIds = false;
arrowprefix = prefix;
pathdata.fw.id = arrowprefix + 'fw';
pathdata.bk.id = arrowprefix + 'bk';
};
setArrowNonce = function setArrowNonce(window, n) {
setArrowNonce = function _ref2(window, n) {
randomizeIds = true;
arrowprefix = prefix + n + '_';
pathdata.fw.id = arrowprefix + 'fw';
@ -250,9 +267,7 @@ var svgEditorExtension_arrows = (function () {
$ = jQuery;
// {svgcontent} = S,
addElem = svgCanvas.addSVGElementFromJson, nonce = S.nonce, prefix = 'se_arrow_';
selElems = void 0, arrowprefix = void 0, randomizeIds = S.randomize_ids;
randomizeIds = S.randomize_ids;
svgCanvas.bind('setnonce', setArrowNonce);
svgCanvas.bind('unsetnonce', unsetArrowNonce);
@ -263,8 +278,16 @@ var svgEditorExtension_arrows = (function () {
}
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' }
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'
}
};
contextTools = [{
type: 'select',
@ -275,56 +298,56 @@ var svgEditorExtension_arrows = (function () {
change: setArrow
}
}];
return _context2.abrupt('return', {
return _context2.abrupt("return", {
name: strings.name,
context_tools: strings.contextTools.map(function (contextTool, i) {
return Object.assign(contextTools[i], contextTool);
}),
callback: function callback() {
$('#arrow_panel').hide();
// Set ID so it can be translated in locale file
$('#arrow_panel').hide(); // Set ID so it can be translated in locale file
$('#arrow_list option')[0].id = 'connector_no_arrow';
},
addLangData: function () {
var _ref3 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref2) {
var lang = _ref2.lang,
importLocale = _ref2.importLocale;
var strings;
var _addLangData = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(_ref) {
var lang, importLocale, strings;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
lang = _ref.lang, importLocale = _ref.importLocale;
_context.next = 3;
return importLocale();
case 2:
case 3:
strings = _context.sent;
return _context.abrupt('return', {
return _context.abrupt("return", {
data: strings.langList
});
case 4:
case 'end':
case 5:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function addLangData(_x2) {
return _ref3.apply(this, arguments);
}
return addLangData;
return function addLangData(_x2) {
return _addLangData.apply(this, arguments);
};
}(),
selectedChanged: function selectedChanged(opts) {
// Use this to update the current selected elements
selElems = opts.elems;
var markerElems = ['line', 'path', 'polyline', 'polygon'];
var i = selElems.length;
while (i--) {
var elem = selElems[i];
if (elem && markerElems.includes(elem.tagName)) {
if (opts.selectedElement && !opts.multiselected) {
showPanel(true);
@ -338,6 +361,7 @@ var svgEditorExtension_arrows = (function () {
},
elementChanged: function elementChanged(opts) {
var elem = opts.elems[0];
if (elem && (elem.getAttribute('marker-start') || elem.getAttribute('marker-mid') || elem.getAttribute('marker-end'))) {
// const start = elem.getAttribute('marker-start');
// const mid = elem.getAttribute('marker-mid');
@ -349,18 +373,16 @@ var svgEditorExtension_arrows = (function () {
});
case 22:
case 'end':
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function init(_x) {
return _ref.apply(this, arguments);
}
return init;
return function init(_x) {
return _init.apply(this, arguments);
};
}()
};

View File

@ -1,11 +1,7 @@
var svgEditorExtension_closepath = (function () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
@ -17,20 +13,32 @@ var svgEditorExtension_closepath = (function () {
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
Promise.resolve(value).then(_next, _throw);
}
}
return step("next");
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
};
}
/* globals jQuery */
/**
* ext-closepath.js
*
@ -39,27 +47,27 @@ var svgEditorExtension_closepath = (function () {
* @copyright 2010 Jeff Schiller
*
*/
// This extension adds a simple button to the contextual panel for paths
// The button toggles whether the path is open or closed
var extClosepath = {
name: 'closepath',
init: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) {
var importLocale = _ref.importLocale;
var strings, $, svgEditor, selElems, updateButton, showPanel, toggleClosed, buttons;
var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(_ref) {
var importLocale, strings, $, svgEditor, selElems, updateButton, showPanel, toggleClosed, buttons;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
importLocale = _ref.importLocale;
_context.next = 3;
return importLocale();
case 2:
case 3:
strings = _context.sent;
$ = jQuery;
svgEditor = this;
selElems = void 0;
updateButton = function updateButton(path) {
var seglist = path.pathSegList,
@ -72,8 +80,10 @@ var svgEditorExtension_closepath = (function () {
showPanel = function showPanel(on) {
$('#closepath_panel').toggle(on);
if (on) {
var path = selElems[0];
if (path) {
updateButton(path);
}
@ -82,15 +92,17 @@ var svgEditorExtension_closepath = (function () {
toggleClosed = function toggleClosed() {
var path = selElems[0];
if (path) {
var seglist = path.pathSegList,
last = seglist.numberOfItems - 1;
// is closed
last = seglist.numberOfItems - 1; // is closed
if (seglist.getItem(last).pathSegType === 1) {
seglist.removeItem(last);
} else {
seglist.appendItem(path.createSVGPathSegClosePath());
}
updateButton(path);
}
};
@ -116,7 +128,7 @@ var svgEditorExtension_closepath = (function () {
}
}
}];
return _context.abrupt('return', {
return _context.abrupt("return", {
name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'closepath_icons.svg',
buttons: strings.buttons.map(function (button, i) {
@ -128,8 +140,10 @@ var svgEditorExtension_closepath = (function () {
selectedChanged: function selectedChanged(opts) {
selElems = opts.elems;
var i = selElems.length;
while (i--) {
var elem = selElems[i];
if (elem && elem.tagName === 'path') {
if (opts.selectedElement && !opts.multiselected) {
showPanel(true);
@ -144,18 +158,16 @@ var svgEditorExtension_closepath = (function () {
});
case 11:
case 'end':
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function init(_x) {
return _ref2.apply(this, arguments);
}
return init;
return function init(_x) {
return _init.apply(this, arguments);
};
}()
};

View File

@ -1,11 +1,7 @@
var svgEditorExtension_connector = (function () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
@ -17,20 +13,32 @@ var svgEditorExtension_connector = (function () {
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
Promise.resolve(value).then(_next, _throw);
}
}
return step("next");
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
};
}
/* globals jQuery */
/**
* ext-connector.js
*
@ -39,20 +47,22 @@ var svgEditorExtension_connector = (function () {
* @copyright 2010 Alexis Deveria
*
*/
var extConnector = {
name: 'connector',
init: function () {
var _ref = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(S) {
var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee2(S) {
var $, svgEditor, svgCanvas, getElem, svgroot, importLocale, addElem, selManager, connSel, elData, strings, startX, startY, curLine, startElem, endElem, seNs, svgcontent, started, connections, selElems, getBBintersect, getOffset, showPanel, setPoint, updateLine, findConnectors, updateConnectors, init, buttons;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
init = function init() {
init = function _ref9() {
// Make sure all connectors have data set
$(svgcontent).find('*').each(function () {
var conn = this.getAttributeNS(seNs, 'connector');
if (conn) {
this.setAttribute('class', connSel.substr(1));
var connData = conn.split(' ');
@ -61,104 +71,102 @@ var svgEditorExtension_connector = (function () {
$(this).data('c_start', connData[0]).data('c_end', connData[1]).data('start_bb', sbb).data('end_bb', ebb);
svgCanvas.getEditorNS(true);
}
});
// updateConnectors();
}); // updateConnectors();
};
updateConnectors = function updateConnectors(elems) {
updateConnectors = function _ref8(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 elem = conn.elem; // const sw = line.getAttribute('stroke-width') * 5;
// const sw = line.getAttribute('stroke-width') * 5;
var pre = conn.is_start ? 'start' : 'end'; // Update bbox for this element
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);
/* const addOffset = */elData(line, pre + '_off');
/* const addOffset = */
var altPre = conn.is_start ? 'end' : 'start';
elData(line, pre + '_off');
var altPre = conn.is_start ? 'end' : 'start'; // Get center pt of connected element
// Get center pt of connected element
var bb2 = elData(line, altPre + '_bb');
var srcX = bb2.x + bb2.width / 2;
var srcY = bb2.y + bb2.height / 2;
var srcY = bb2.y + bb2.height / 2; // Set point of element being moved
// Set point of element being moved
var pt = getBBintersect(srcX, srcY, bb, getOffset(pre, line));
setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true);
setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true); // Set point of connected element
// Set point of connected element
var pt2 = getBBintersect(pt.x, pt.y, elData(line, altPre + '_bb'), getOffset(altPre, line));
setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true);
setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true); // Update points attribute manually for webkit
// Update points attribute manually for webkit
if (navigator.userAgent.includes('AppleWebKit')) {
var pts = line.points;
var len = pts.numberOfItems;
var ptArr = [];
for (var j = 0; j < len; j++) {
pt = pts.getItem(j);
ptArr[j] = pt.x + ',' + pt.y;
}
line.setAttribute('points', ptArr.join(' '));
}
}
}
};
findConnectors = function findConnectors() {
findConnectors = function _ref7() {
var elems = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : selElems;
var connectors = $(svgcontent).find(connSel);
connections = [];
connections = []; // Loop through connectors to see if one is connected to the element
// Loop through connectors to see if one is connected to the element
connectors.each(function () {
var addThis = void 0;
var addThis;
function add() {
if (elems.includes(this)) {
// Pretend this element is selected
addThis = true;
}
}
} // Grab the ends
// Grab the ends
var parts = [];
['start', 'end'].forEach(function (pos, i) {
var key = 'c_' + pos;
var part = elData(this, key);
if (part == null) {
part = document.getElementById(this.attributes['se:connector'].value.split(' ')[i]);
elData(this, 'c_' + pos, part.id);
elData(this, pos + '_bb', svgCanvas.getStrokedBBox([part]));
} else part = document.getElementById(part);
parts.push(part);
}.bind(this));
for (var i = 0; i < 2; i++) {
var cElem = parts[i];
addThis = false; // The connected element might be part of a selected group
addThis = false;
// The connected element might be part of a selected group
$(cElem).parents().each(add);
if (!cElem || !cElem.parentNode) {
$(this).remove();
continue;
}
if (elems.includes(cElem) || addThis) {
var bb = svgCanvas.getStrokedBBox([cElem]);
connections.push({
@ -173,59 +181,59 @@ var svgEditorExtension_connector = (function () {
});
};
updateLine = function updateLine(diffX, diffY) {
updateLine = function _ref6(diffX, diffY) {
// Update line with element
var i = connections.length;
while (i--) {
var conn = connections[i];
var line = conn.connector;
// const {elem} = conn;
var pre = conn.is_start ? 'start' : 'end';
// const sw = line.getAttribute('stroke-width') * 5;
var line = conn.connector; // const {elem} = conn;
var pre = conn.is_start ? 'start' : 'end'; // const sw = line.getAttribute('stroke-width') * 5;
// Update bbox for this element
var bb = elData(line, pre + '_bb');
bb.x = conn.start_x + diffX;
bb.y = conn.start_y + diffY;
elData(line, pre + '_bb', bb);
var altPre = conn.is_start ? 'end' : 'start'; // Get center pt of connected element
var altPre = conn.is_start ? 'end' : 'start';
// Get center pt of connected element
var bb2 = elData(line, altPre + '_bb');
var srcX = bb2.x + bb2.width / 2;
var srcY = bb2.y + bb2.height / 2;
var srcY = bb2.y + bb2.height / 2; // Set point of element being moved
// Set point of element being moved
var pt = getBBintersect(srcX, srcY, 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
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, altPre + '_bb'), getOffset(altPre, line));
setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true);
}
};
setPoint = function setPoint(elem, pos, x, y, setMid) {
setPoint = function _ref5(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
} // 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 ptArr = elem.getAttribute('points').split(' ');
for (var i = 0; i < ptArr.length; i++) {
if (i === pos) {
ptArr[i] = x + ',' + y;
}
}
elem.setAttribute('points', ptArr.join(' '));
}
@ -237,25 +245,26 @@ var svgEditorExtension_connector = (function () {
}
};
showPanel = function showPanel(on) {
showPanel = function _ref4(on) {
var connRules = $('#connector_rules');
if (!connRules.length) {
connRules = $('<style id="connector_rules"></style>').appendTo('head');
}
connRules.text(!on ? '' : '#tool_clone, #tool_topath, #tool_angle, #xy_panel { display: none !important; }');
$('#connector_panel').toggle(on);
};
getOffset = function getOffset(side, line) {
var giveOffset = !!line.getAttribute('marker-' + side);
// const giveOffset = $(line).data(side+'_off');
getOffset = function _ref3(side, line) {
var giveOffset = !!line.getAttribute('marker-' + side); // const giveOffset = $(line).data(side+'_off');
// TODO: Make this number (5) be based on marker width/height
var size = line.getAttribute('stroke-width') * 5;
return giveOffset ? size : 0;
};
getBBintersect = function getBBintersect(x, y, bb, offset) {
getBBintersect = function _ref2(x, y, bb, offset) {
if (offset) {
offset -= 0;
bb = $.extend({}, bb);
@ -269,10 +278,9 @@ var svgEditorExtension_connector = (function () {
var midY = bb.y + bb.height / 2;
var lenX = x - midX;
var lenY = y - midY;
var slope = Math.abs(lenY / lenX);
var ratio;
var ratio = void 0;
if (slope < bb.height / bb.width) {
ratio = bb.width / 2 / Math.abs(lenX);
} else {
@ -295,12 +303,7 @@ var svgEditorExtension_connector = (function () {
case 15:
strings = _context2.sent;
startX = void 0, startY = void 0, curLine = void 0, startElem = void 0, endElem = void 0, seNs = void 0, svgcontent = S.svgcontent, started = false, connections = [], selElems = [];
/**
*
* @param {Element[]} [elem=selElems] Array of elements
*/
svgcontent = S.svgcontent, started = false, connections = [], selElems = [];
// Do once
(function () {
@ -320,9 +323,7 @@ var svgEditorExtension_connector = (function () {
};
seNs = svgCanvas.getEditorNS();
})();
// Do on reset
})(); // Do on reset
// $(svgroot).parent().mousemove(function (e) {
@ -335,7 +336,6 @@ var svgEditorExtension_connector = (function () {
// //
// // }
// });
buttons = [{
id: 'mode_connect',
type: 'mode',
@ -351,37 +351,37 @@ var svgEditorExtension_connector = (function () {
}
}
}];
return _context2.abrupt('return', {
return _context2.abrupt("return", {
name: strings.name,
svgicons: svgEditor.curConfig.imgPath + 'conn.svg',
buttons: strings.buttons.map(function (button, i) {
return Object.assign(buttons[i], button);
}),
addLangData: function () {
var _ref3 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref2) {
var lang = _ref2.lang,
importLocale = _ref2.importLocale;
var _addLangData = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(_ref) {
var lang, importLocale;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt('return', {
lang = _ref.lang, importLocale = _ref.importLocale;
return _context.abrupt("return", {
data: strings.langList
});
case 1:
case 'end':
case 2:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function addLangData(_x3) {
return _ref3.apply(this, arguments);
}
return addLangData;
return function addLangData(_x2) {
return _addLangData.apply(this, arguments);
};
}(),
mouseDown: function mouseDown(opts) {
var e = opts.event;
@ -390,28 +390,23 @@ var svgEditorExtension_connector = (function () {
var mode = svgCanvas.getMode();
var initStroke = svgEditor.curConfig.initStroke;
if (mode === 'connector') {
if (started) {
return;
}
var mouseTarget = e.target;
var parents = $(mouseTarget).parents();
if ($.inArray(svgcontent, parents) !== -1) {
// Connectable element
// If child of foreignObject, use parent
var fo = $(mouseTarget).closest('foreignObject');
startElem = fo.length ? fo[0] : mouseTarget;
startElem = fo.length ? fo[0] : mouseTarget; // Get center of source element
// Get center of source element
var bb = svgCanvas.getStrokedBBox([startElem]);
var x = bb.x + bb.width / 2;
var y = bb.y + bb.height / 2;
started = true;
curLine = addElem({
element: 'polyline',
@ -427,23 +422,23 @@ var svgEditorExtension_connector = (function () {
});
elData(curLine, 'start_bb', bb);
}
return {
started: true
};
}
if (mode === 'select') {
findConnectors();
}
},
mouseMove: function mouseMove(opts) {
var zoom = svgCanvas.getZoom();
// const e = opts.event;
var zoom = svgCanvas.getZoom(); // const e = opts.event;
var x = opts.mouse_x / zoom;
var y = opts.mouse_y / zoom;
var diffX = x - startX,
diffY = y - startY;
var mode = svgCanvas.getMode();
if (mode === 'connector' && started) {
@ -452,22 +447,22 @@ var svgEditorExtension_connector = (function () {
var pt = getBBintersect(x, y, elData(curLine, 'start_bb'), getOffset('start', curLine));
startX = pt.x;
startY = pt.y;
setPoint(curLine, 0, pt.x, pt.y, true); // Set end point
setPoint(curLine, 0, pt.x, pt.y, true);
// Set end point
setPoint(curLine, 'end', x, y, true);
} else if (mode === 'select') {
var slen = selElems.length;
while (slen--) {
var elem = selElems[slen];
// Look for selected connector elements
var elem = selElems[slen]; // Look for selected connector elements
if (elem && elData(elem, 'c_start')) {
// Remove the "translate" transform given to move
svgCanvas.removeFromSelection([elem]);
svgCanvas.getTransformList(elem).clear();
}
}
if (connections.length) {
updateLine(diffX, diffY);
}
@ -475,15 +470,17 @@ var svgEditorExtension_connector = (function () {
},
mouseUp: function mouseUp(opts) {
// const zoom = svgCanvas.getZoom();
var e = opts.event;
// , x = opts.mouse_x / zoom,
var e = opts.event; // , x = opts.mouse_x / zoom,
// , y = opts.mouse_y / zoom,
var mouseTarget = e.target;
if (svgCanvas.getMode() !== 'connector') {
return;
}
var fo = $(mouseTarget).closest('foreignObject');
if (fo.length) {
mouseTarget = fo[0];
}
@ -499,6 +496,7 @@ var svgEditorExtension_connector = (function () {
started: started
};
}
if ($.inArray(svgcontent, parents) === -1) {
// Not a valid target element, so remove line
$(curLine).remove();
@ -508,21 +506,23 @@ var svgEditorExtension_connector = (function () {
element: null,
started: started
};
}
// Valid end element
endElem = mouseTarget;
} // Valid end element
endElem = mouseTarget;
var startId = startElem.id,
endId = endElem.id;
var connStr = startId + ' ' + endId;
var altStr = endId + ' ' + startId;
// Don't create connector if one already exists
var altStr = endId + ' ' + startId; // Don't create connector if one already exists
var dupe = $(svgcontent).find(connSel).filter(function () {
var conn = this.getAttributeNS(seNs, 'connector');
if (conn === connStr || conn === altStr) {
return true;
}
});
if (dupe.length) {
$(curLine).remove();
return {
@ -533,7 +533,6 @@ var svgEditorExtension_connector = (function () {
}
var bb = svgCanvas.getStrokedBBox([endElem]);
var pt = getBBintersect(startX, startY, bb, getOffset('start', curLine));
setPoint(curLine, 'end', pt.x, pt.y, true);
$(curLine).data('c_start', startId).data('c_end', endId).data('end_bb', bb);
@ -559,16 +558,18 @@ var svgEditorExtension_connector = (function () {
if (svgCanvas.getMode() === 'connector') {
svgCanvas.setMode('select');
}
} // Use this to update the current selected elements
// Use this to update the current selected elements
selElems = opts.elems;
var i = selElems.length;
while (i--) {
var elem = selElems[i];
if (elem && elData(elem, 'c_start')) {
selManager.requestSelector(elem).showGrips(false);
if (opts.selectedElement && !opts.multiselected) {
// TODO: Set up context tools and hide most regular line tools
showPanel(true);
@ -579,17 +580,19 @@ var svgEditorExtension_connector = (function () {
showPanel(false);
}
}
updateConnectors();
},
elementChanged: function elementChanged(opts) {
var elem = opts.elems[0];
if (elem && elem.tagName === 'svg' && elem.id === 'svgcontent') {
// Update svgcontent (can change on import)
svgcontent = elem;
init();
}
} // Has marker, so change offset
// Has marker, so change offset
if (elem && (elem.getAttribute('marker-start') || elem.getAttribute('marker-mid') || elem.getAttribute('marker-end'))) {
var start = elem.getAttribute('marker-start');
var mid = elem.getAttribute('marker-mid');
@ -599,15 +602,12 @@ var svgEditorExtension_connector = (function () {
if (elem.tagName === 'line' && mid) {
// Convert to polyline to accept mid-arrow
var x1 = Number(elem.getAttribute('x1'));
var x2 = Number(elem.getAttribute('x2'));
var y1 = Number(elem.getAttribute('y1'));
var y2 = Number(elem.getAttribute('y2'));
var _elem = elem,
id = _elem.id;
var midPt = ' ' + (x1 + x2) / 2 + ',' + (y1 + y2) / 2 + ' ';
var pline = addElem({
element: 'polyline',
@ -626,10 +626,12 @@ var svgEditorExtension_connector = (function () {
svgCanvas.addToSelection([pline]);
elem = pline;
}
}
// Update line if it's a connector
} // Update line if it's a connector
if (elem.getAttribute('class') === connSel.substr(1)) {
var _start = getElem(elData(elem, 'c_start'));
updateConnectors([_start]);
} else {
updateConnectors();
@ -641,16 +643,17 @@ var svgEditorExtension_connector = (function () {
if ('se:connector' in elem.attr) {
elem.attr['se:connector'] = elem.attr['se:connector'].split(' ').map(function (oldID) {
return input.changes[oldID];
}).join(' ');
// Check validity - the field would be something like 'svg_21 svg_22', but
}).join(' '); // Check validity - the field would be something like 'svg_21 svg_22', but
// if one end is missing, it would be 'svg_21' and therefore fail this test
if (!/. ./.test(elem.attr['se:connector'])) {
remove.push(elem.attr.id);
}
}
});
return { remove: remove };
return {
remove: remove
};
},
toolButtonStateUpdate: function toolButtonStateUpdate(opts) {
if (opts.nostroke) {
@ -658,23 +661,22 @@ var svgEditorExtension_connector = (function () {
svgEditor.clickSelect();
}
}
$('#mode_connect').toggleClass('disabled', opts.nostroke);
}
});
case 20:
case 'end':
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function init(_x) {
return _ref.apply(this, arguments);
}
return init;
return function init(_x) {
return _init.apply(this, arguments);
};
}()
};

View File

@ -1,11 +1,7 @@
var svgEditorExtension_eyedropper = (function () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
@ -17,20 +13,32 @@ var svgEditorExtension_eyedropper = (function () {
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
Promise.resolve(value).then(_next, _throw);
}
}
return step("next");
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
};
}
/* globals jQuery */
/**
* ext-eyedropper.js
*
@ -39,30 +47,33 @@ var svgEditorExtension_eyedropper = (function () {
* @copyright 2010 Jeff Schiller
*
*/
var extEyedropper = {
name: 'eyedropper',
init: function () {
var _ref = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(S) {
var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(S) {
var strings, svgEditor, $, ChangeElementCommand, svgCanvas, addToHistory, currentStyle, getStyle, buttons;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
getStyle = function getStyle(opts) {
getStyle = function _ref(opts) {
// if we are in eyedropper mode, we don't want to disable the eye-dropper tool
var mode = svgCanvas.getMode();
if (mode === 'eyedropper') {
return;
}
var tool = $('#tool_eyedropper');
// enable-eye-dropper if one element is selected
var tool = $('#tool_eyedropper'); // enable-eye-dropper if one element is selected
var elem = null;
if (!opts.multiselected && opts.elems[0] && !['svg', 'g', 'use'].includes(opts.elems[0].nodeName)) {
elem = opts.elems[0];
tool.removeClass('disabled');
// grab the current style
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');
@ -71,8 +82,7 @@ var svgEditorExtension_eyedropper = (function () {
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
currentStyle.opacity = elem.getAttribute('opacity') || 1.0; // disable eye-dropper tool
} else {
tool.addClass('disabled');
}
@ -88,9 +98,12 @@ var svgEditorExtension_eyedropper = (function () {
ChangeElementCommand = S.ChangeElementCommand, svgCanvas = svgEditor.canvas, addToHistory = function addToHistory(cmd) {
svgCanvas.undoMgr.addCommandToHistory(cmd);
}, currentStyle = {
fillPaint: 'red', fillOpacity: 1.0,
strokePaint: 'black', strokeOpacity: 1.0,
strokeWidth: 5, strokeDashArray: null,
fillPaint: 'red',
fillOpacity: 1.0,
strokePaint: 'black',
strokeOpacity: 1.0,
strokeWidth: 5,
strokeDashArray: null,
opacity: 1.0,
strokeLinecap: 'butt',
strokeLinejoin: 'miter'
@ -105,19 +118,18 @@ var svgEditorExtension_eyedropper = (function () {
}
}
}];
return _context.abrupt('return', {
return _context.abrupt("return", {
name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'eyedropper-icon.xml',
buttons: strings.buttons.map(function (button, i) {
return Object.assign(buttons[i], button);
}),
// if we have selected an element, grab its paint and enable the eye dropper button
selectedChanged: getStyle,
elementChanged: getStyle,
mouseDown: function mouseDown(opts) {
var mode = svgCanvas.getMode();
if (mode === 'eyedropper') {
var e = opts.event;
var target = e.target;
@ -133,27 +145,35 @@ var svgEditorExtension_eyedropper = (function () {
if (currentStyle.fillPaint) {
change(target, 'fill', currentStyle.fillPaint);
}
if (currentStyle.fillOpacity) {
change(target, 'fill-opacity', currentStyle.fillOpacity);
}
if (currentStyle.strokePaint) {
change(target, 'stroke', currentStyle.strokePaint);
}
if (currentStyle.strokeOpacity) {
change(target, 'stroke-opacity', currentStyle.strokeOpacity);
}
if (currentStyle.strokeWidth) {
change(target, 'stroke-width', currentStyle.strokeWidth);
}
if (currentStyle.strokeDashArray) {
change(target, 'stroke-dasharray', currentStyle.strokeDashArray);
}
if (currentStyle.opacity) {
change(target, 'opacity', currentStyle.opacity);
}
if (currentStyle.strokeLinecap) {
change(target, 'stroke-linecap', currentStyle.strokeLinecap);
}
if (currentStyle.strokeLinejoin) {
change(target, 'stroke-linejoin', currentStyle.strokeLinejoin);
}
@ -165,18 +185,16 @@ var svgEditorExtension_eyedropper = (function () {
});
case 9:
case 'end':
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function init(_x) {
return _ref.apply(this, arguments);
}
return init;
return function init(_x) {
return _init.apply(this, arguments);
};
}()
};

View File

@ -1,11 +1,7 @@
var svgEditorExtension_foreignobject = (function () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
@ -17,20 +13,32 @@ var svgEditorExtension_foreignobject = (function () {
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
Promise.resolve(value).then(_next, _throw);
}
}
return step("next");
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
};
}
/* globals jQuery */
/**
* ext-foreignobject.js
*
@ -39,30 +47,32 @@ var svgEditorExtension_foreignobject = (function () {
* @copyright 2010 Jacques Distler, 2010 Alexis Deveria
*
*/
var extForeignobject = {
name: 'foreignobject',
init: function () {
var _ref = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(S) {
var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(S) {
var svgEditor, text2xml, NS, importLocale, $, svgCanvas, svgdoc, strings, properlySourceSizeTextArea, showPanel, toggleSourceButtons, selElems, started, newFO, editingforeign, setForeignString, showForeignEditor, setAttr, buttons, contextTools;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
setAttr = function setAttr(attr, val) {
setAttr = function _ref5(attr, val) {
svgCanvas.changeSelectedAttribute(attr, val);
svgCanvas.call('changed', selElems);
};
showForeignEditor = function showForeignEditor() {
showForeignEditor = function _ref4() {
var elt = selElems[0];
if (!elt || editingforeign) {
return;
}
editingforeign = true;
toggleSourceButtons(true);
elt.removeAttribute('fill');
var str = svgCanvas.svgToString(elt, 0);
$('#svg_source_textarea').val(str);
$('#svg_source_editor').fadeIn();
@ -70,12 +80,13 @@ var svgEditorExtension_foreignobject = (function () {
$('#svg_source_textarea').focus();
};
setForeignString = function setForeignString(xmlString) {
setForeignString = function _ref3(xmlString) {
var elt = selElems[0];
try {
// convert string into XML document
var newDoc = text2xml('<svg xmlns="' + NS.SVG + '" xmlns:xlink="' + NS.XLINK + '">' + xmlString + '</svg>');
// run it through our sanitizer to remove anything we do not support
var newDoc = text2xml('<svg xmlns="' + NS.SVG + '" xmlns:xlink="' + NS.XLINK + '">' + xmlString + '</svg>'); // run it through our sanitizer to remove anything we do not support
svgCanvas.sanitizeSvg(newDoc.documentElement);
elt.replaceWith(svgdoc.importNode(newDoc.documentElement.firstChild, true));
svgCanvas.call('changed', [elt]);
@ -88,16 +99,18 @@ var svgEditorExtension_foreignobject = (function () {
return true;
};
toggleSourceButtons = function toggleSourceButtons(on) {
toggleSourceButtons = function _ref2(on) {
$('#tool_source_save, #tool_source_cancel').toggle(!on);
$('#foreign_save, #foreign_cancel').toggle(on);
};
showPanel = function showPanel(on) {
showPanel = function _ref(on) {
var fcRules = $('#fc_rules');
if (!fcRules.length) {
fcRules = $('<style id="fc_rules"></style>').appendTo('head');
}
fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }');
$('#foreignObject_panel').toggle(on);
};
@ -119,8 +132,7 @@ var svgEditorExtension_foreignobject = (function () {
$('#svg_source_textarea').css('height', height);
};
selElems = void 0, started = void 0, newFO = void 0, editingforeign = false;
editingforeign = false;
/**
* This function sets the content of element elt to the input XML.
* @param {string} xmlString - The XML text
@ -179,7 +191,7 @@ var svgEditorExtension_foreignobject = (function () {
}
}
}];
return _context.abrupt('return', {
return _context.abrupt("return", {
name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'foreignobject-icons.xml',
buttons: strings.buttons.map(function (button, i) {
@ -196,12 +208,14 @@ var svgEditorExtension_foreignobject = (function () {
editingforeign = false;
$('#svg_source_textarea').blur();
toggleSourceButtons(false);
};
}; // TODO: Needs to be done after orig icon loads
// TODO: Needs to be done after orig icon loads
setTimeout(function () {
// Create source save/cancel buttons
/* const save = */$('#tool_source_save').clone().hide().attr('id', 'foreign_save').unbind().appendTo('#tool_source_back').click(function () {
/* const save = */
$('#tool_source_save').clone().hide().attr('id', 'foreign_save').unbind().appendTo('#tool_source_back').click(function () {
if (!editingforeign) {
return;
}
@ -211,22 +225,23 @@ var svgEditorExtension_foreignobject = (function () {
if (!ok) {
return false;
}
endChanges();
});
} else {
endChanges();
}
// setSelectMode();
});
} // setSelectMode();
/* const cancel = */$('#tool_source_cancel').clone().hide().attr('id', 'foreign_cancel').unbind().appendTo('#tool_source_back').click(function () {
});
/* const cancel = */
$('#tool_source_cancel').clone().hide().attr('id', 'foreign_cancel').unbind().appendTo('#tool_source_back').click(function () {
endChanges();
});
}, 3000);
},
mouseDown: function mouseDown(opts) {
// const e = opts.event;
if (svgCanvas.getMode() === 'foreign') {
started = true;
newFO = svgCanvas.addSVGElementFromJson({
@ -235,7 +250,8 @@ var svgEditorExtension_foreignobject = (function () {
x: opts.start_x,
y: opts.start_y,
id: svgCanvas.getNextId(),
'font-size': 16, // cur_text.font_size,
'font-size': 16,
// cur_text.font_size,
width: '48',
height: '20',
style: 'pointer-events:inherit'
@ -246,11 +262,11 @@ var svgEditorExtension_foreignobject = (function () {
m.setAttribute('display', 'inline');
var mi = svgdoc.createElementNS(NS.MATH, 'mi');
mi.setAttribute('mathvariant', 'normal');
mi.textContent = '\u03A6';
mi.textContent = "\u03A6";
var mo = svgdoc.createElementNS(NS.MATH, 'mo');
mo.textContent = '\u222A';
mo.textContent = "\u222A";
var mi2 = svgdoc.createElementNS(NS.MATH, 'mi');
mi2.textContent = '\u2133';
mi2.textContent = "\u2133";
m.append(mi, mo, mi2);
newFO.append(m);
return {
@ -264,7 +280,6 @@ var svgEditorExtension_foreignobject = (function () {
var attrs = $(newFO).attr(['width', 'height']);
var keep = attrs.width !== '0' || attrs.height !== '0';
svgCanvas.addToSelection([newFO], true);
return {
keep: keep,
element: newFO
@ -274,10 +289,11 @@ var svgEditorExtension_foreignobject = (function () {
selectedChanged: function selectedChanged(opts) {
// Use this to update the current selected elements
selElems = opts.elems;
var i = selElems.length;
while (i--) {
var elem = selElems[i];
if (elem && elem.tagName === 'foreignObject') {
if (opts.selectedElement && !opts.multiselected) {
$('#foreign_font_size').val(elem.getAttribute('font-size'));
@ -292,24 +308,20 @@ var svgEditorExtension_foreignobject = (function () {
}
}
},
elementChanged: function elementChanged(opts) {
// const elem = opts.elems[0];
}
elementChanged: function elementChanged(opts) {}
});
case 18:
case 'end':
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function init(_x) {
return _ref.apply(this, arguments);
}
return init;
return function init(_x) {
return _init.apply(this, arguments);
};
}()
};

View File

@ -1,11 +1,7 @@
var svgEditorExtension_grid = (function () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
@ -17,20 +13,32 @@ var svgEditorExtension_grid = (function () {
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
Promise.resolve(value).then(_next, _throw);
}
}
return step("next");
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
};
}
/* globals jQuery */
/**
* ext-grid.js
*
@ -39,71 +47,72 @@ var svgEditorExtension_grid = (function () {
* @copyright 2010 Redou Mine, 2010 Alexis Deveria
*
*/
var extGrid = {
name: 'grid',
init: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) {
var NS = _ref.NS,
getTypeMap = _ref.getTypeMap,
importLocale = _ref.importLocale;
var strings, svgEditor, $, svgCanvas, svgdoc, assignAttributes, hcanvas, canvBG, units, intervals, showGrid, canvasGrid, gridPattern, gridimg, gridBox, updateGrid, gridUpdate, buttons;
var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(_ref) {
var NS, getTypeMap, importLocale, strings, svgEditor, $, svgCanvas, svgdoc, assignAttributes, hcanvas, canvBG, units, intervals, showGrid, canvasGrid, gridPattern, gridimg, gridBox, updateGrid, gridUpdate, buttons;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
gridUpdate = function gridUpdate() {
gridUpdate = function _ref3() {
if (showGrid) {
updateGrid(svgCanvas.getZoom());
}
$('#canvasGrid').toggle(showGrid);
$('#view_grid').toggleClass('push_button_pressed tool_button');
};
updateGrid = function updateGrid(zoom) {
updateGrid = function _ref2(zoom) {
// TODO: Try this with <line> elements, then compare performance difference
var unit = units[svgEditor.curConfig.baseUnit]; // 1 = 1px
var uMulti = unit * zoom;
// Calculate the main number interval
var uMulti = unit * zoom; // Calculate the main number interval
var rawM = 100 / uMulti;
var multi = 1;
for (var i = 0; i < intervals.length; i++) {
var num = intervals[i];
multi = num;
if (rawM <= num) {
break;
}
}
var bigInt = multi * uMulti;
// Set the canvas size to the width of the container
var bigInt = multi * uMulti; // Set the canvas size to the width of the container
hcanvas.width = bigInt;
hcanvas.height = bigInt;
var ctx = hcanvas.getContext('2d');
var curD = 0.5;
var part = bigInt / 10;
ctx.globalAlpha = 0.2;
ctx.strokeStyle = svgEditor.curConfig.gridColor;
for (var _i = 1; _i < 10; _i++) {
var subD = Math.round(part * _i) + 0.5;
// const lineNum = (i % 2)?12:10;
var subD = Math.round(part * _i) + 0.5; // const lineNum = (i % 2)?12:10;
var lineNum = 0;
ctx.moveTo(subD, bigInt);
ctx.lineTo(subD, lineNum);
ctx.moveTo(bigInt, subD);
ctx.lineTo(lineNum, subD);
}
ctx.stroke();
ctx.beginPath();
ctx.globalAlpha = 0.5;
ctx.moveTo(curD, bigInt);
ctx.lineTo(curD, 0);
ctx.moveTo(bigInt, curD);
ctx.lineTo(0, curD);
ctx.stroke();
var datauri = hcanvas.toDataURL('image/png');
gridimg.setAttribute('width', bigInt);
gridimg.setAttribute('height', bigInt);
@ -112,22 +121,19 @@ var svgEditorExtension_grid = (function () {
svgCanvas.setHref(gridimg, datauri);
};
_context.next = 4;
NS = _ref.NS, getTypeMap = _ref.getTypeMap, importLocale = _ref.importLocale;
_context.next = 5;
return importLocale();
case 4:
case 5:
strings = _context.sent;
svgEditor = this;
$ = jQuery;
svgCanvas = svgEditor.canvas;
svgdoc = document.getElementById('svgcanvas').ownerDocument, assignAttributes = svgCanvas.assignAttributes, hcanvas = document.createElement('canvas'), canvBG = $('#canvasBackground'), units = getTypeMap(), intervals = [0.01, 0.1, 1, 10, 100, 1000];
showGrid = svgEditor.curConfig.showGrid || false;
$(hcanvas).hide().appendTo('body');
canvasGrid = svgdoc.createElementNS(NS.SVG, 'svg');
assignAttributes(canvasGrid, {
id: 'canvasGrid',
width: '100%',
@ -137,22 +143,20 @@ var svgEditorExtension_grid = (function () {
overflow: 'visible',
display: 'none'
});
canvBG.append(canvasGrid);
canvBG.append(canvasGrid); // grid-pattern
// grid-pattern
gridPattern = svgdoc.createElementNS(NS.SVG, 'pattern');
assignAttributes(gridPattern, {
id: 'gridpattern',
patternUnits: 'userSpaceOnUse',
x: 0, // -(value.strokeWidth / 2), // position for strokewidth
y: 0, // -(value.strokeWidth / 2), // position for strokewidth
x: 0,
// -(value.strokeWidth / 2), // position for strokewidth
y: 0,
// -(value.strokeWidth / 2), // position for strokewidth
width: 100,
height: 100
});
gridimg = svgdoc.createElementNS(NS.SVG, 'image');
assignAttributes(gridimg, {
x: 0,
y: 0,
@ -160,11 +164,9 @@ var svgEditorExtension_grid = (function () {
height: 100
});
gridPattern.append(gridimg);
$('#svgroot defs').append(gridPattern);
$('#svgroot defs').append(gridPattern); // grid-box
// grid-box
gridBox = svgdoc.createElementNS(NS.SVG, 'rect');
assignAttributes(gridBox, {
width: '100%',
height: '100%',
@ -176,7 +178,6 @@ var svgEditorExtension_grid = (function () {
style: 'pointer-events: none; display:visible;'
});
$('#canvasGrid').append(gridBox);
buttons = [{
id: 'view_grid',
icon: svgEditor.curConfig.extIconsPath + 'grid.png',
@ -189,10 +190,9 @@ var svgEditorExtension_grid = (function () {
}
}
}];
return _context.abrupt('return', {
return _context.abrupt("return", {
name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'grid-icon.xml',
zoomChanged: function zoomChanged(zoom) {
if (showGrid) {
updateGrid(zoom);
@ -203,25 +203,22 @@ var svgEditorExtension_grid = (function () {
gridUpdate();
}
},
buttons: strings.buttons.map(function (button, i) {
return Object.assign(buttons[i], button);
})
});
case 25:
case 'end':
case 26:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function init(_x) {
return _ref2.apply(this, arguments);
}
return init;
return function init(_x) {
return _init.apply(this, arguments);
};
}()
};

View File

@ -1,11 +1,7 @@
var svgEditorExtension_helloworld = (function () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
@ -17,21 +13,39 @@ var svgEditorExtension_helloworld = (function () {
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
Promise.resolve(value).then(_next, _throw);
}
}
return step("next");
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
};
}
var slicedToArray = function () {
function sliceIterator(arr, i) {
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
@ -48,7 +62,7 @@ var svgEditorExtension_helloworld = (function () {
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
@ -57,18 +71,12 @@ var svgEditorExtension_helloworld = (function () {
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
/* globals jQuery */
/**
* ext-helloworld.js
*
@ -86,42 +94,39 @@ var svgEditorExtension_helloworld = (function () {
var extHelloworld = {
name: 'helloworld',
init: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) {
var importLocale = _ref.importLocale;
var strings, svgEditor, $, svgCanvas;
var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(_ref) {
var importLocale, strings, svgEditor, $, svgCanvas;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
importLocale = _ref.importLocale;
_context.next = 3;
return importLocale();
case 2:
case 3:
strings = _context.sent;
svgEditor = this;
$ = jQuery;
svgCanvas = svgEditor.canvas;
return _context.abrupt('return', {
return _context.abrupt("return", {
name: strings.name,
// For more notes on how to make an icon file, see the source of
// the helloworld-icon.xml
svgicons: svgEditor.curConfig.extIconsPath + 'helloworld-icon.xml',
// Multiple buttons can be added in this array
buttons: [{
// Must match the icon ID in helloworld-icon.xml
id: 'hello_world',
// Fallback, e.g., for `file:///` access
icon: svgEditor.curConfig.extIconsPath + 'helloworld.png',
// This indicates that the button will be added to the "mode"
// button panel on the left side
type: 'mode',
// Tooltip text
title: strings.buttons[0].title,
// Events
events: {
click: function click() {
@ -139,52 +144,46 @@ var svgEditorExtension_helloworld = (function () {
if (svgCanvas.getMode() === 'hello_world') {
// The returned object must include "started" with
// a value of true in order for mouseUp to be triggered
return { started: true };
return {
started: true
};
}
},
// This is triggered from anywhere, but "started" must have been set
// to true (see above). Note that "opts" is an object with event info
mouseUp: function mouseUp(opts) {
// Check the mode on mouseup
if (svgCanvas.getMode() === 'hello_world') {
var zoom = svgCanvas.getZoom();
var zoom = svgCanvas.getZoom(); // Get the actual coordinate by dividing by the zoom value
// Get the actual coordinate by dividing by the zoom value
var x = opts.mouse_x / zoom;
var y = opts.mouse_y / zoom;
var y = opts.mouse_y / zoom; // We do our own formatting
// We do our own formatting
var text = strings.text;
[['x', x], ['y', y]].forEach(function (_ref3) {
var _ref4 = slicedToArray(_ref3, 2),
prop = _ref4[0],
val = _ref4[1];
[['x', x], ['y', y]].forEach(function (_ref2) {
var _ref3 = _slicedToArray(_ref2, 2),
prop = _ref3[0],
val = _ref3[1];
text = text.replace('{' + prop + '}', val);
});
}); // Show the text using the custom alert function
// Show the text using the custom alert function
$.alert(text);
}
}
});
case 7:
case 'end':
case 8:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function init(_x) {
return _ref2.apply(this, arguments);
}
return init;
return function init(_x) {
return _init.apply(this, arguments);
};
}()
};

View File

@ -1,17 +1,21 @@
var svgEditorExtension_imagelib = (function () {
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
function _typeof(obj) {
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
} : function (obj) {
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
return _typeof(obj);
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
@ -23,20 +27,32 @@ var svgEditorExtension_imagelib = (function () {
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
Promise.resolve(value).then(_next, _throw);
}
}
return step("next");
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
};
}
/* globals jQuery */
/**
* ext-imagelib.js
*
@ -48,33 +64,29 @@ var svgEditorExtension_imagelib = (function () {
var extImagelib = {
name: 'imagelib',
init: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) {
var decode64 = _ref.decode64,
importLocale = _ref.importLocale,
dropXMLInternalSubset = _ref.dropXMLInternalSubset;
var imagelibStrings, modularVersion, svgEditor, $, uiStrings, svgCanvas, extIconsPath, allowedImageLibOrigins, closeBrowser, importImage, pending, mode, multiArr, transferStopped, preview, submit, toggleMulti, showBrowser, buttons;
var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(_ref) {
var decode64, importLocale, dropXMLInternalSubset, imagelibStrings, modularVersion, svgEditor, $, uiStrings, svgCanvas, extIconsPath, allowedImageLibOrigins, closeBrowser, importImage, pending, mode, multiArr, transferStopped, preview, submit, toggleMulti, showBrowser, buttons;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
showBrowser = function showBrowser() {
showBrowser = function _ref9() {
var browser = $('#imgbrowse');
if (!browser.length) {
$('<div id=imgbrowse_holder><div id=imgbrowse class=toolbar_button>' + '</div></div>').insertAfter('#svg_docprops');
browser = $('#imgbrowse');
var allLibs = imagelibStrings.select_lib;
var libOpts = $('<ul id=imglib_opts>').appendTo(browser);
var frame = $('<iframe/>').prependTo(browser).hide().wrap('<div id=lib_framewrap>');
var header = $('<h1>').prependTo(browser).text(allLibs).css({
position: 'absolute',
top: 0,
left: 0,
width: '100%'
});
var cancel = $('<button>' + uiStrings.common.cancel + '</button>').appendTo(browser).on('click touchend', function () {
$('#imgbrowse_holder').hide();
}).css({
@ -82,9 +94,11 @@ var svgEditorExtension_imagelib = (function () {
top: 5,
right: -10
});
var leftBlock = $('<span>').css({ position: 'absolute', top: 5, left: 10 }).appendTo(browser);
var leftBlock = $('<span>').css({
position: 'absolute',
top: 5,
left: 10
}).appendTo(browser);
var back = $('<button hidden>' + imagelibStrings.show_list + '</button>').appendTo(leftBlock).on('click touchend', function () {
frame.attr('src', 'about:blank').hide();
libOpts.show();
@ -93,9 +107,11 @@ var svgEditorExtension_imagelib = (function () {
}).css({
'margin-right': 5
}).hide();
/* const type = */
/* const type = */$('<select><option value=s>' + imagelibStrings.import_single + '</option><option value=m>' + imagelibStrings.import_multi + '</option><option value=o>' + imagelibStrings.open + '</option></select>').appendTo(leftBlock).change(function () {
$('<select><option value=s>' + imagelibStrings.import_single + '</option><option value=m>' + imagelibStrings.import_multi + '</option><option value=o>' + imagelibStrings.open + '</option></select>').appendTo(leftBlock).change(function () {
mode = $(this).val();
switch (mode) {
case 's':
case 'o':
@ -110,29 +126,29 @@ var svgEditorExtension_imagelib = (function () {
}).css({
'margin-top': 10
});
cancel.prepend($.getSvgIcon('cancel', true));
back.prepend($.getSvgIcon('tool_imagelib', true));
imagelibStrings.imgLibs.forEach(function (_ref6) {
var name = _ref6.name,
url = _ref6.url,
description = _ref6.description;
imagelibStrings.imgLibs.forEach(function (_ref5) {
var name = _ref5.name,
url = _ref5.url,
description = _ref5.description;
$('<li>').appendTo(libOpts).text(name).on('click touchend', function () {
frame.attr('src', url).show();
header.text(name);
libOpts.hide();
back.show();
}).append('<span>' + description + '</span>');
}).append("<span>".concat(description, "</span>"));
});
} else {
$('#imgbrowse_holder').show();
}
};
toggleMulti = function toggleMulti(show) {
$('#lib_framewrap, #imglib_opts').css({ right: show ? 200 : 10 });
toggleMulti = function _ref8(show) {
$('#lib_framewrap, #imglib_opts').css({
right: show ? 200 : 10
});
if (!preview) {
preview = $('<div id=imglib_preview>').css({
position: 'absolute',
@ -143,16 +159,17 @@ var svgEditorExtension_imagelib = (function () {
background: '#fff',
overflow: 'auto'
}).insertAfter('#lib_framewrap');
submit = $('<button disabled>Import selected</button>').appendTo('#imgbrowse').on('click touchend', function () {
$.each(multiArr, function (i) {
var type = this[0];
var data = this[1];
if (type === 'svg') {
svgCanvas.importSvgString(data);
} else {
importImage(data);
}
svgCanvas.moveSelectedElements(i * 20, i * 20, false);
});
preview.empty();
@ -169,7 +186,7 @@ var svgEditorExtension_imagelib = (function () {
submit.toggle(show);
};
importImage = function importImage(url) {
importImage = function _ref7(url) {
var newImage = svgCanvas.addSVGElementFromJson({
element: 'image',
attr: {
@ -186,32 +203,34 @@ var svgEditorExtension_imagelib = (function () {
svgCanvas.setImageURL(url);
};
closeBrowser = function closeBrowser() {
closeBrowser = function _ref6() {
$('#imgbrowse_holder').hide();
};
_context.next = 6;
decode64 = _ref.decode64, importLocale = _ref.importLocale, dropXMLInternalSubset = _ref.dropXMLInternalSubset;
_context.next = 7;
return importLocale();
case 6:
case 7:
imagelibStrings = _context.sent;
modularVersion = !('svgEditor' in window) || !window.svgEditor || window.svgEditor.modules !== false;
svgEditor = this;
$ = jQuery;
uiStrings = svgEditor.uiStrings, svgCanvas = svgEditor.canvas, extIconsPath = svgEditor.curConfig.extIconsPath;
imagelibStrings.imgLibs = imagelibStrings.imgLibs.map(function (_ref3) {
var name = _ref3.name,
url = _ref3.url,
description = _ref3.description;
imagelibStrings.imgLibs = imagelibStrings.imgLibs.map(function (_ref2) {
var name = _ref2.name,
url = _ref2.url,
description = _ref2.description;
// Todo: Adopt some standard formatting library like `fluent.js` instead
url = url.replace(/\{path\}/g, extIconsPath).replace(/\{modularVersion\}/g, modularVersion ? imagelibStrings.moduleEnding || '-es' : '');
return { name: name, url: url, description: description };
return {
name: name,
url: url,
description: description
};
});
allowedImageLibOrigins = imagelibStrings.imgLibs.map(function (_ref4) {
var url = _ref4.url;
allowedImageLibOrigins = imagelibStrings.imgLibs.map(function (_ref3) {
var url = _ref3.url;
try {
return new URL(url).origin;
@ -223,32 +242,34 @@ var svgEditorExtension_imagelib = (function () {
mode = 's';
multiArr = [];
transferStopped = false;
preview = void 0, submit = void 0;
// Receive `postMessage` data
window.addEventListener('message', function (_ref4) {
var origin = _ref4.origin,
response = _ref4.data;
window.addEventListener('message', function (_ref5) {
var origin = _ref5.origin,
response = _ref5.data;
if (!response || !['string', 'object'].includes(typeof response === 'undefined' ? 'undefined' : _typeof(response))) {
if (!response || !['string', 'object'].includes(_typeof(response))) {
// Do nothing
return;
}
var id = void 0;
var type = void 0;
var id;
var type;
try {
// Todo: This block can be removed (and the above check changed to
// insist on an object) if embedAPI moves away from a string to
// an object (if IE9 support not needed)
response = (typeof response === 'undefined' ? 'undefined' : _typeof(response)) === 'object' ? response : JSON.parse(response);
response = _typeof(response) === 'object' ? response : JSON.parse(response);
if (response.namespace !== 'imagelib') {
return;
}
if (!allowedImageLibOrigins.includes('*') && !allowedImageLibOrigins.includes(origin)) {
console.log('Origin ' + origin + ' not whitelisted for posting to ' + window.origin);
console.log("Origin ".concat(origin, " not whitelisted for posting to ").concat(window.origin));
return;
}
var hasName = 'name' in response;
var hasHref = 'href' in response;
@ -260,9 +281,9 @@ var svgEditorExtension_imagelib = (function () {
if (hasHref) {
id = response.href;
response = response.data;
}
} // Hide possible transfer dialog box
// Hide possible transfer dialog box
$('#dialog_box').hide();
type = hasName ? 'meta' : response.charAt(0);
} catch (e) {
@ -285,28 +306,23 @@ var svgEditorExtension_imagelib = (function () {
}
}
var entry = void 0,
curMeta = void 0,
svgStr = void 0,
imgStr = void 0;
var entry, curMeta, svgStr, imgStr;
switch (type) {
case 'meta':
{
// Metadata
transferStopped = false;
curMeta = response;
curMeta = response; // Should be safe to add dynamic property as passed metadata
// Should be safe to add dynamic property as passed metadata
pending[curMeta.id] = curMeta; // lgtm [js/remote-property-injection]
var name = curMeta.name || 'file';
var message = uiStrings.notification.retrieving.replace('%s', name);
if (mode !== 'm') {
$.process_cancel(message, function () {
transferStopped = true;
// Should a message be sent back to the frame?
transferStopped = true; // Should a message be sent back to the frame?
$('#dialog_box').hide();
});
@ -318,9 +334,11 @@ var svgEditorExtension_imagelib = (function () {
return;
}
case '<':
svgStr = true;
break;
case 'd':
{
if (response.startsWith('data:image/svg+xml')) {
@ -335,26 +353,26 @@ var svgEditorExtension_imagelib = (function () {
}
}
// Else fall through
default:
// TODO: See if there's a way to base64 encode the binary data stream
// const str = 'data:;base64,' + svgedit.utilities.encode64(response, true);
// Assume it's raw image data
// importImage(str);
// Don't give warning as postMessage may have been used by something else
if (mode !== 'm') {
closeBrowser();
} else {
pending[id].entry.remove();
}
// $.alert('Unexpected data was returned: ' + response, function() {
} // $.alert('Unexpected data was returned: ' + response, function() {
// if (mode !== 'm') {
// closeBrowser();
// } else {
// pending[id].entry.remove();
// }
// });
return;
}
@ -366,13 +384,16 @@ var svgEditorExtension_imagelib = (function () {
} else if (imgStr) {
importImage(response);
}
closeBrowser();
break;
case 'm':
// Import multiple
multiArr.push([svgStr ? 'svg' : 'img', response]);
curMeta = pending[id];
var title = void 0;
var title;
if (svgStr) {
if (curMeta && curMeta.name) {
title = curMeta.name;
@ -380,8 +401,10 @@ var svgEditorExtension_imagelib = (function () {
// Try to find a title
// `dropXMLInternalSubset` is to help prevent the billion laughs attack
var xml = new DOMParser().parseFromString(dropXMLInternalSubset(response), 'text/xml').documentElement; // lgtm [js/xml-bomb]
title = $(xml).children('title').first().text() || '(SVG #' + response.length + ')';
}
if (curMeta) {
preview.children().each(function () {
if ($(this).data('id') === id) {
@ -390,6 +413,7 @@ var svgEditorExtension_imagelib = (function () {
} else {
$(this).text(title);
}
submit.removeAttr('disabled');
}
});
@ -401,6 +425,7 @@ var svgEditorExtension_imagelib = (function () {
if (curMeta && curMeta.preview_url) {
title = curMeta.name || '';
}
if (curMeta && curMeta.preview_url) {
entry = $('<span>').append($('<img>').attr('src', curMeta.preview_url), document.createTextNode(title));
} else {
@ -419,35 +444,38 @@ var svgEditorExtension_imagelib = (function () {
submit.removeAttr('disabled');
}
}
break;
case 'o':
// Open
if (!svgStr) {
break;
}
svgEditor.openPrep(function (ok) {
if (!ok) {
return;
}
svgCanvas.clear();
svgCanvas.setSvgString(response);
// updateCanvas();
svgCanvas.setSvgString(response); // updateCanvas();
});
closeBrowser();
break;
}
}, true);
buttons = [{
id: 'tool_imagelib',
type: 'app_menu', // _flyout
type: 'app_menu',
// _flyout
icon: extIconsPath + 'imagelib.png',
position: 4,
events: {
mouseup: showBrowser
}
}];
return _context.abrupt('return', {
return _context.abrupt("return", {
svgicons: extIconsPath + 'ext-imagelib.xml',
buttons: imagelibStrings.buttons.map(function (button, i) {
return Object.assign(buttons[i], button);
@ -458,18 +486,16 @@ var svgEditorExtension_imagelib = (function () {
});
case 21:
case 'end':
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function init(_x) {
return _ref2.apply(this, arguments);
}
return init;
return function init(_x) {
return _init.apply(this, arguments);
};
}()
};

View File

@ -3,7 +3,10 @@ var svgEditorExtensionLocale_arrows_en = (function () {
var en = {
name: 'Arrows',
langList: [{ id: 'arrow_none', textContent: 'No arrow' }],
langList: [{
id: 'arrow_none',
textContent: 'No arrow'
}],
contextTools: [{
title: 'Select arrow type',
options: {

View File

@ -3,7 +3,10 @@ var svgEditorExtensionLocale_arrows_fr = (function () {
var fr = {
name: 'Arrows',
langList: [{ id: 'arrow_none', textContent: 'Sans flèche' }],
langList: [{
id: 'arrow_none',
textContent: 'Sans flèche'
}],
contextTools: [{
title: 'Select arrow type',
options: {

View File

@ -3,7 +3,10 @@ var svgEditorExtensionLocale_connector_en = (function () {
var en = {
name: 'Connector',
langList: [{ id: 'mode_connect', title: 'Connect two objects' }],
langList: [{
id: 'mode_connect',
title: 'Connect two objects'
}],
buttons: [{
title: 'Connect two objects'
}]

View File

@ -3,7 +3,10 @@ var svgEditorExtensionLocale_connector_fr = (function () {
var fr = {
name: 'Connector',
langList: [{ id: 'mode_connect', title: 'Connecter deux objets' }],
langList: [{
id: 'mode_connect',
title: 'Connecter deux objets'
}],
buttons: [{
title: 'Connect two objects'
}]

View File

@ -27,6 +27,7 @@ var svgEditorExtensionLocale_imagelib_de = (function () {
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
}]
};

View File

@ -17,14 +17,14 @@ var svgEditorExtensionLocale_imagelib_en = (function () {
}, {
name: 'IAN Symbol Libraries',
url: 'https://ian.umces.edu/symbols/catalog/svgedit/album_chooser.php?svgedit=3',
description: 'Free library of illustrations'
// The site is no longer using our API, and they have added an
description: 'Free library of illustrations' // The site is no longer using our API, and they have added an
// `X-Frame-Options` header which prevents our usage cross-origin:
// Getting messages like this in console:
// Refused to display 'https://openclipart.org/detail/307176/sign-bike' in a frame
// because it set 'X-Frame-Options' to 'sameorigin'.
// url: 'https://openclipart.org/svgedit',
// However, they do have a custom API which we are using here:
/*
{
name: 'Openclipart',
@ -32,6 +32,7 @@ var svgEditorExtensionLocale_imagelib_en = (function () {
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
}]
};

View File

@ -27,6 +27,7 @@ var svgEditorExtensionLocale_imagelib_fr = (function () {
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
}]
};

View File

@ -27,6 +27,7 @@ var svgEditorExtensionLocale_imagelib_pl = (function () {
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
}]
};

View File

@ -27,6 +27,7 @@ var svgEditorExtensionLocale_imagelib_pt_BR = (function () {
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
}]
};

View File

@ -27,6 +27,7 @@ var svgEditorExtensionLocale_imagelib_ro = (function () {
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
}]
};

View File

@ -27,6 +27,7 @@ var svgEditorExtensionLocale_imagelib_sk = (function () {
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
}]
};

View File

@ -27,6 +27,7 @@ var svgEditorExtensionLocale_imagelib_sl = (function () {
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
}]
};

View File

@ -27,6 +27,7 @@ var svgEditorExtensionLocale_imagelib_zh_CN = (function () {
description: 'Share and Use Images. Over 100,000 Public Domain SVG Images and Growing.'
}
*/
}]
};

View File

@ -3,7 +3,61 @@ var svgEditorExtensionLocale_markers_en = (function () {
var en = {
name: 'Markers',
langList: [{ id: 'nomarker', title: 'No Marker' }, { id: 'leftarrow', title: 'Left Arrow' }, { id: 'rightarrow', title: 'Right Arrow' }, { id: 'textmarker', title: 'Text Marker' }, { id: 'forwardslash', title: 'Forward Slash' }, { id: 'reverseslash', title: 'Reverse Slash' }, { id: 'verticalslash', title: 'Vertical Slash' }, { id: 'box', title: 'Box' }, { id: 'star', title: 'Star' }, { id: 'xmark', title: 'X' }, { id: 'triangle', title: 'Triangle' }, { id: 'mcircle', title: 'Circle' }, { id: 'leftarrow_o', title: 'Open Left Arrow' }, { id: 'rightarrow_o', title: 'Open Right Arrow' }, { id: 'box_o', title: 'Open Box' }, { id: 'star_o', title: 'Open Star' }, { id: 'triangle_o', title: 'Open Triangle' }, { id: 'mcircle_o', title: 'Open Circle' }],
langList: [{
id: 'nomarker',
title: 'No Marker'
}, {
id: 'leftarrow',
title: 'Left Arrow'
}, {
id: 'rightarrow',
title: 'Right Arrow'
}, {
id: 'textmarker',
title: 'Text Marker'
}, {
id: 'forwardslash',
title: 'Forward Slash'
}, {
id: 'reverseslash',
title: 'Reverse Slash'
}, {
id: 'verticalslash',
title: 'Vertical Slash'
}, {
id: 'box',
title: 'Box'
}, {
id: 'star',
title: 'Star'
}, {
id: 'xmark',
title: 'X'
}, {
id: 'triangle',
title: 'Triangle'
}, {
id: 'mcircle',
title: 'Circle'
}, {
id: 'leftarrow_o',
title: 'Open Left Arrow'
}, {
id: 'rightarrow_o',
title: 'Open Right Arrow'
}, {
id: 'box_o',
title: 'Open Box'
}, {
id: 'star_o',
title: 'Open Star'
}, {
id: 'triangle_o',
title: 'Open Triangle'
}, {
id: 'mcircle_o',
title: 'Open Circle'
}],
contextTools: [{
title: 'Start marker',
label: 's'

View File

@ -1,11 +1,7 @@
var svgEditorExtension_markers = (function () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
@ -17,20 +13,32 @@ var svgEditorExtension_markers = (function () {
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
Promise.resolve(value).then(_next, _throw);
}
}
return step("next");
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
};
}
/* globals jQuery */
/**
* ext-markers.js
*
@ -64,15 +72,17 @@ var svgEditorExtension_markers = (function () {
var extMarkers = {
name: 'markers',
init: function () {
var _ref = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(S) {
var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee2(S) {
var strings, svgEditor, $, svgCanvas, addElem, mtypes, markerPrefix, idPrefix, markerTypes, getLinked, setIcon, selElems, showPanel, addMarker, convertline, setMarker, colorChanged, updateReferences, triggerTextEntry, showTextPrompt, setArrowFromButton, getTitle, buildButtonList, contextTools;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
buildButtonList = function buildButtonList(lang) {
var buttons = [];
// const i = 0;
buildButtonList = function _ref14(lang) {
var buttons = []; // const i = 0;
/*
buttons.push({
id: idPrefix + 'markers_off',
@ -96,6 +106,7 @@ var svgEditorExtension_markers = (function () {
panel: 'marker_panel'
});
*/
$.each(mtypes, function (k, pos) {
var listname = pos + '_marker_list';
var def = true;
@ -107,7 +118,9 @@ var svgEditorExtension_markers = (function () {
icon: svgEditor.curConfig.extIconsPath + 'markers-' + id + '.png',
title: title,
type: 'context',
events: { click: setArrowFromButton },
events: {
click: setArrowFromButton
},
panel: 'marker_panel',
list: listname,
isDefault: def
@ -118,19 +131,19 @@ var svgEditorExtension_markers = (function () {
return buttons;
};
getTitle = function getTitle(id) {
getTitle = function _ref13(id) {
var langList = strings.langList;
var item = langList.find(function (item) {
return item.id === id;
});
return item ? item.title : id;
};
setArrowFromButton = function setArrowFromButton(obj) {
setArrowFromButton = function _ref12(obj) {
var parts = this.id.split('_');
var pos = parts[1];
var val = parts[2];
if (parts[3]) {
val += '_' + parts[3];
}
@ -142,11 +155,13 @@ var svgEditorExtension_markers = (function () {
}
};
showTextPrompt = function showTextPrompt(pos) {
showTextPrompt = function _ref11(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);
@ -154,111 +169,132 @@ var svgEditorExtension_markers = (function () {
});
};
triggerTextEntry = function triggerTextEntry(pos, val) {
triggerTextEntry = function _ref10(pos, val) {
$('#' + pos + '_marker').val(val);
$('#' + pos + '_marker').change();
// const txtbox = $('#'+pos+'_marker');
$('#' + pos + '_marker').change(); // const txtbox = $('#'+pos+'_marker');
// if (val.substr(0,1)=='\\') {txtbox.hide();}
// else {txtbox.show();}
};
updateReferences = function updateReferences(el) {
updateReferences = function _ref9(el) {
$.each(mtypes, function (i, pos) {
var id = markerPrefix + pos + '_' + el.id;
var markerName = 'marker-' + pos;
var marker = getLinked(el, markerName);
if (!marker || !marker.attributes.se_type) {
return;
} // not created by this extension
var url = el.getAttribute(markerName);
if (url) {
var len = el.id.length;
var linkid = url.substr(-len - 1, len);
if (el.id !== linkid) {
var val = $('#' + pos + '_marker').attr('value');
addMarker(id, val);
svgCanvas.changeSelectedAttribute(markerName, 'url(#' + id + ')');
if (el.tagName === 'line' && pos === 'mid') {
el = convertline(el);
}
svgCanvas.call('changed', selElems);
}
}
});
};
colorChanged = function colorChanged(elem) {
colorChanged = function _ref8(elem) {
var color = elem.getAttribute('stroke');
$.each(mtypes, function (i, pos) {
var marker = getLinked(elem, 'marker-' + pos);
if (!marker) {
return;
}
if (!marker.attributes.se_type) {
return;
} // not created by this extension
var ch = marker.lastElementChild;
if (!ch) {
return;
}
var curfill = ch.getAttribute('fill');
var curstroke = ch.getAttribute('stroke');
if (curfill && curfill !== 'none') {
ch.setAttribute('fill', color);
}
if (curstroke && curstroke !== 'none') {
ch.setAttribute('stroke', color);
}
});
};
setMarker = function setMarker() {
var poslist = { start_marker: 'start', mid_marker: 'mid', end_marker: 'end' };
setMarker = function _ref7() {
var poslist = {
start_marker: 'start',
mid_marker: 'mid',
end_marker: 'end'
};
var pos = poslist[this.id];
var markerName = 'marker-' + pos;
var el = selElems[0];
var marker = getLinked(el, markerName);
if (marker) {
$(marker).remove();
}
el.removeAttribute(markerName);
var val = this.value;
if (val === '') {
val = '\\nomarker';
}
if (val === '\\nomarker') {
setIcon(pos, val);
svgCanvas.call('changed', selElems);
return;
}
// Set marker on element
} // Set marker on element
var id = markerPrefix + pos + '_' + el.id;
addMarker(id, val);
svgCanvas.changeSelectedAttribute(markerName, 'url(#' + id + ')');
if (el.tagName === 'line' && pos === 'mid') {
convertline(el);
}
svgCanvas.call('changed', selElems);
setIcon(pos, val);
};
convertline = function convertline(elem) {
convertline = function _ref6(elem) {
// this routine came from the connectors extension
// it is needed because midpoint markers don't work with line elements
if (!(elem.tagName === 'line')) {
return elem;
}
} // Convert to polyline to accept mid-arrow
// Convert to polyline to accept mid-arrow
var x1 = Number(elem.getAttribute('x1'));
var x2 = Number(elem.getAttribute('x2'));
var y1 = Number(elem.getAttribute('y1'));
var y2 = Number(elem.getAttribute('y2'));
var id = elem.id;
var midPt = ' ' + (x1 + x2) / 2 + ',' + (y1 + y2) / 2 + ' ';
var pline = addElem({
element: 'polyline',
@ -274,15 +310,14 @@ var svgEditorExtension_markers = (function () {
// get any existing marker definitions
var nam = 'marker-' + pos;
var m = elem.getAttribute(nam);
if (m) {
pline.setAttribute(nam, elem.getAttribute(nam));
}
});
var batchCmd = new S.BatchCommand();
batchCmd.addSubCommand(new S.RemoveElementCommand(elem, elem.parentNode));
batchCmd.addSubCommand(new S.InsertElementCommand(pline));
$(elem).after(pline).remove();
svgCanvas.clearSelection();
pline.id = id;
@ -291,12 +326,12 @@ var svgEditorExtension_markers = (function () {
return pline;
};
addMarker = function addMarker(id, val) {
addMarker = function _ref5(id, val) {
var txtBoxBg = '#ffffff';
var txtBoxBorder = 'none';
var txtBoxStrokeWidth = 0;
var marker = svgCanvas.getElem(id);
if (marker) {
return;
}
@ -306,17 +341,18 @@ var svgEditorExtension_markers = (function () {
}
var el = selElems[0];
var color = el.getAttribute('stroke');
// NOTE: Safari didn't like a negative value in viewBox
var color = el.getAttribute('stroke'); // NOTE: Safari didn't like a negative value in viewBox
// so we use a standardized 0 0 100 100
// with 50 50 being mapped to the marker position
var strokeWidth = 10;
var refX = 50;
var refY = 50;
var viewBox = '0 0 100 100';
var markerWidth = 5;
var markerHeight = 5;
var seType = void 0;
var seType;
if (val.substr(0, 1) === '\\') {
seType = val.substr(1);
} else {
@ -326,8 +362,9 @@ var svgEditorExtension_markers = (function () {
if (!markerTypes[seType]) {
return;
} // an unknown type!
// create a generic marker
marker = addElem({
element: 'marker',
attr: {
@ -342,33 +379,32 @@ var svgEditorExtension_markers = (function () {
if (seType !== 'textmarker') {
var mel = addElem(markerTypes[seType]);
var fillcolor = seType.substr(-2) === '_o' ? 'none' : color;
mel.setAttribute('fill', fillcolor);
mel.setAttribute('stroke', color);
mel.setAttribute('stroke-width', strokeWidth);
marker.append(mel);
} else {
var text = addElem(markerTypes[seType]);
// have to add text to get bounding box
var text = addElem(markerTypes[seType]); // have to add text to get bounding box
text.textContent = val;
var tb = text.getBBox();
// alert(tb.x + ' ' + tb.y + ' ' + tb.width + ' ' + tb.height);
var tb = text.getBBox(); // alert(tb.x + ' ' + tb.y + ' ' + tb.width + ' ' + tb.height);
var pad = 1;
var bb = tb;
bb.x = 0;
bb.y = 0;
bb.width += pad * 2;
bb.height += pad * 2;
// shift text according to its size
bb.height += pad * 2; // shift text according to its size
text.setAttribute('x', pad);
text.setAttribute('y', bb.height - pad - tb.height / 4); // kludge?
text.setAttribute('fill', color);
refX = bb.width / 2 + pad;
refY = bb.height / 2 + pad;
viewBox = bb.x + ' ' + bb.y + ' ' + bb.width + ' ' + bb.height;
markerWidth = bb.width / 10;
markerHeight = bb.height / 10;
var box = addElem({
element: 'rect',
attr: {
@ -391,21 +427,19 @@ var svgEditorExtension_markers = (function () {
marker.setAttribute('refX', refX);
marker.setAttribute('refY', refY);
svgCanvas.findDefs().append(marker);
return marker;
};
showPanel = function showPanel(on) {
showPanel = function _ref4(on) {
$('#marker_panel').toggle(on);
if (on) {
var el = selElems[0];
var val = void 0,
ci = void 0;
var val, ci;
$.each(mtypes, function (i, pos) {
var m = getLinked(el, 'marker-' + pos);
var txtbox = $('#' + pos + '_marker');
if (!m) {
val = '\\nomarker';
ci = val;
@ -414,39 +448,47 @@ var svgEditorExtension_markers = (function () {
if (!m.attributes.se_type) {
return;
} // not created by this extension
val = '\\' + m.attributes.se_type.textContent;
ci = val;
if (val === '\\textmarker') {
val = m.lastChild.textContent;
// txtbox.show(); // show text box
val = m.lastChild.textContent; // txtbox.show(); // show text box
} else {
txtbox.hide(); // hide text box
}
}
txtbox.val(val);
setIcon(pos, ci);
});
}
};
setIcon = function setIcon(pos, id) {
setIcon = function _ref3(pos, id) {
if (id.substr(0, 1) !== '\\') {
id = '\\textmarker';
}
var ci = '#' + idPrefix + pos + '_' + id.substr(1);
svgEditor.setIcon('#cur_' + pos + '_marker_list', $(ci).children());
$(ci).addClass('current').siblings().removeClass('current');
};
getLinked = function getLinked(elem, attr) {
getLinked = function _ref2(elem, attr) {
var str = elem.getAttribute(attr);
if (!str) {
return null;
}
var m = str.match(/\(#(.*)\)/);
if (!m || m.length !== 2) {
return null;
}
return svgCanvas.getElem(m[1]);
};
@ -461,9 +503,7 @@ var svgEditorExtension_markers = (function () {
addElem = svgCanvas.addSVGElementFromJson;
mtypes = ['start', 'mid', 'end'];
markerPrefix = 'se_marker_';
idPrefix = 'mkr_';
// note - to add additional marker types add them below with a unique id
idPrefix = 'mkr_'; // note - to add additional marker types add them below with a unique id
// and add the associated icon(s) to marker-icons.svg
// the geometry is normalized to a 100x100 box with the origin at lower left
// Safari did not like negative values for low left of viewBox
@ -471,153 +511,184 @@ var svgEditorExtension_markers = (function () {
markerTypes = {
nomarker: {},
leftarrow: { element: 'path', attr: { d: 'M0,50 L100,90 L70,50 L100,10 Z' } },
rightarrow: { element: 'path', attr: { d: 'M100,50 L0,90 L30,50 L0,10 Z' } },
textmarker: { element: 'text', attr: { x: 0, y: 0, 'stroke-width': 0, stroke: 'none', 'font-size': 75, 'font-family': 'serif', 'text-anchor': 'left',
'xml:space': 'preserve' } },
forwardslash: { element: 'path', attr: { d: 'M30,100 L70,0' } },
reverseslash: { element: 'path', attr: { d: 'M30,0 L70,100' } },
verticalslash: { element: 'path', attr: { d: 'M50,0 L50,100' } },
box: { element: 'path', attr: { d: 'M20,20 L20,80 L80,80 L80,20 Z' } },
star: { element: 'path', attr: { d: 'M10,30 L90,30 L20,90 L50,10 L80,90 Z' } },
xmark: { element: 'path', attr: { d: 'M20,80 L80,20 M80,80 L20,20' } },
triangle: { element: 'path', attr: { d: 'M10,80 L50,20 L80,80 Z' } },
mcircle: { element: 'circle', attr: { r: 30, cx: 50, cy: 50 } }
};
// duplicate shapes to support unfilled (open) marker types with an _o suffix
leftarrow: {
element: 'path',
attr: {
d: 'M0,50 L100,90 L70,50 L100,10 Z'
}
},
rightarrow: {
element: 'path',
attr: {
d: 'M100,50 L0,90 L30,50 L0,10 Z'
}
},
textmarker: {
element: 'text',
attr: {
x: 0,
y: 0,
'stroke-width': 0,
stroke: 'none',
'font-size': 75,
'font-family': 'serif',
'text-anchor': 'left',
'xml:space': 'preserve'
}
},
forwardslash: {
element: 'path',
attr: {
d: 'M30,100 L70,0'
}
},
reverseslash: {
element: 'path',
attr: {
d: 'M30,0 L70,100'
}
},
verticalslash: {
element: 'path',
attr: {
d: 'M50,0 L50,100'
}
},
box: {
element: 'path',
attr: {
d: 'M20,20 L20,80 L80,80 L80,20 Z'
}
},
star: {
element: 'path',
attr: {
d: 'M10,30 L90,30 L20,90 L50,10 L80,90 Z'
}
},
xmark: {
element: 'path',
attr: {
d: 'M20,80 L80,20 M80,80 L20,20'
}
},
triangle: {
element: 'path',
attr: {
d: 'M10,80 L50,20 L80,80 Z'
}
},
mcircle: {
element: 'circle',
attr: {
r: 30,
cx: 50,
cy: 50
}
}
}; // duplicate shapes to support unfilled (open) marker types with an _o suffix
['leftarrow', 'rightarrow', 'box', 'star', 'mcircle', 'triangle'].forEach(function (v) {
markerTypes[v + '_o'] = markerTypes[v];
});
/**
* @param {Element} elem - A graphic element will have an attribute like marker-start
* @param {"marker-start"|"marker-mid"|"marker-end"} attr
* @returns {Element} The marker element that is linked to the graphic element
*/
selElems = void 0;
// toggles context tool panel off/on
// sets the controls with the selected element's settings
// called when the main system modifies an object
// this routine changes the associated markers to be the same color
// called when the main system creates or modifies an object
// primary purpose is create new markers for cloned objects
// simulate a change event a text box that stores the current element's marker type
/*
function setMarkerSet(obj) {
const parts = this.id.split('_');
const set = parts[2];
switch (set) {
case 'off':
triggerTextEntry('start','\\nomarker');
triggerTextEntry('mid','\\nomarker');
triggerTextEntry('end','\\nomarker');
break;
case 'dimension':
triggerTextEntry('start','\\leftarrow');
triggerTextEntry('end','\\rightarrow');
showTextPrompt('mid');
break;
case 'label':
triggerTextEntry('mid','\\nomarker');
triggerTextEntry('end','\\rightarrow');
showTextPrompt('start');
break;
}
}
*/
// callback function for a toolbar button click
// build the toolbar button array from the marker definitions
contextTools = [{
type: 'input',
panel: 'marker_panel',
id: 'start_marker',
size: 3,
events: { change: setMarker }
events: {
change: setMarker
}
}, {
type: 'button-select',
panel: 'marker_panel',
id: 'start_marker_list',
colnum: 3,
events: { change: setArrowFromButton }
events: {
change: setArrowFromButton
}
}, {
type: 'input',
panel: 'marker_panel',
id: 'mid_marker',
defval: '',
size: 3,
events: { change: setMarker }
events: {
change: setMarker
}
}, {
type: 'button-select',
panel: 'marker_panel',
id: 'mid_marker_list',
colnum: 3,
events: { change: setArrowFromButton }
events: {
change: setArrowFromButton
}
}, {
type: 'input',
panel: 'marker_panel',
id: 'end_marker',
size: 3,
events: { change: setMarker }
events: {
change: setMarker
}
}, {
type: 'button-select',
panel: 'marker_panel',
id: 'end_marker_list',
colnum: 3,
events: { change: setArrowFromButton }
events: {
change: setArrowFromButton
}
}];
return _context2.abrupt('return', {
return _context2.abrupt("return", {
name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'markers-icons.xml',
callback: function callback() {
$('#marker_panel').addClass('toolset').hide();
},
addLangData: function () {
var _ref3 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref2) {
var importLocale = _ref2.importLocale,
lang = _ref2.lang;
var _addLangData = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(_ref) {
var importLocale, lang;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt('return', { data: strings.langList });
importLocale = _ref.importLocale, lang = _ref.lang;
return _context.abrupt("return", {
data: strings.langList
});
case 1:
case 'end':
case 2:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function addLangData(_x2) {
return _ref3.apply(this, arguments);
}
return addLangData;
return function addLangData(_x2) {
return _addLangData.apply(this, arguments);
};
}(),
selectedChanged: function selectedChanged(opts) {
// Use this to update the current selected elements
// console.log('selectChanged',opts);
selElems = opts.elems;
var markerElems = ['line', 'path', 'polyline', 'polygon'];
var i = selElems.length;
while (i--) {
var elem = selElems[i];
if (elem && markerElems.includes(elem.tagName)) {
if (opts.selectedElement && !opts.multiselected) {
showPanel(true);
@ -632,32 +703,30 @@ var svgEditorExtension_markers = (function () {
elementChanged: function elementChanged(opts) {
// console.log('elementChanged',opts);
var elem = opts.elems[0];
if (elem && (elem.getAttribute('marker-start') || elem.getAttribute('marker-mid') || elem.getAttribute('marker-end'))) {
colorChanged(elem);
updateReferences(elem);
}
// changing_flag = false; // Not apparently in use
},
} // changing_flag = false; // Not apparently in use
},
buttons: buildButtonList(),
context_tools: strings.contextTools.map(function (contextTool, i) {
return Object.assign(contextTools[i], contextTool);
})
});
case 28:
case 'end':
case 27:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function init(_x) {
return _ref.apply(this, arguments);
}
return init;
return function init(_x) {
return _init.apply(this, arguments);
};
}()
};

View File

@ -1,11 +1,7 @@
var svgEditorExtension_mathjax = (function () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
@ -17,44 +13,28 @@ var svgEditorExtension_mathjax = (function () {
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
Promise.resolve(value).then(_next, _throw);
}
}
return step("next");
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
};
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
// MIT License
// From: https://github.com/uupaa/dynamic-import-polyfill/blob/master/importModule.js
/**
* @module importModule
*/
function toAbsoluteURL(url) {
var a = document.createElement('a');
a.setAttribute('href', url); // <a href="hoge.html">
return a.cloneNode(false).href; // -> "http://example.com/hoge.html"
}
function addScriptAtts(script, atts) {
@ -63,85 +43,8 @@ var svgEditorExtension_mathjax = (function () {
script[prop] = atts[prop];
}
});
}
} // Additions by Brett
// Additions by Brett
/**
* @typedef {PlainObject} module:importModule.ImportConfig
* @property {string} global The variable name to set on `window` (when not using the modular version)
* @property {boolean} [returnDefault=false]
*/
/**
* @function module:importModule.importSetGlobalDefault
* @param {string} url
* @param {module:importModule.ImportConfig} config
* @returns {*} The return depends on the export of the targeted module.
*/
var importSetGlobalDefault = function () {
var _ref = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(url, config) {
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
return _context.abrupt('return', importSetGlobal(url, _extends({}, config, { returnDefault: true })));
case 1:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
return function importSetGlobalDefault(_x, _x2) {
return _ref.apply(this, arguments);
};
}();
/**
* @function module:importModule.importSetGlobal
* @param {string} url
* @param {module:importModule.ImportConfig} config
* @returns {ArbitraryModule|*} The return depends on the export of the targeted module.
*/
var importSetGlobal = function () {
var _ref3 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(url, _ref2) {
var global = _ref2.global,
returnDefault = _ref2.returnDefault;
var modularVersion;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
// Todo: Replace calls to this function with `import()` when supported
modularVersion = !('svgEditor' in window) || !window.svgEditor || window.svgEditor.modules !== false;
if (!modularVersion) {
_context2.next = 3;
break;
}
return _context2.abrupt('return', importModule(url, undefined, { returnDefault: returnDefault }));
case 3:
_context2.next = 5;
return importScript(url);
case 5:
return _context2.abrupt('return', window[global]);
case 6:
case 'end':
return _context2.stop();
}
}
}, _callee2, this);
}));
return function importSetGlobal(_x3, _x4) {
return _ref3.apply(this, arguments);
};
}();
// Addition by Brett
function importScript(url) {
var atts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
@ -150,91 +53,51 @@ var svgEditorExtension_mathjax = (function () {
return importScript(u, atts);
}));
}
return new Promise(function (resolve, reject) {
var script = document.createElement('script');
var destructor = function destructor() {
script.onerror = null;
script.onload = null;
script.remove();
script.src = '';
};
script.defer = 'defer';
addScriptAtts(script, atts);
script.onerror = function () {
reject(new Error('Failed to import: ' + url));
reject(new Error("Failed to import: ".concat(url)));
destructor();
};
script.onload = function () {
resolve();
destructor();
};
script.src = url;
document.head.append(script);
});
}
function importModule(url) {
var atts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _ref4 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
_ref4$returnDefault = _ref4.returnDefault,
returnDefault = _ref4$returnDefault === undefined ? false : _ref4$returnDefault;
if (Array.isArray(url)) {
return Promise.all(url.map(function (u) {
return importModule(u, atts);
}));
}
return new Promise(function (resolve, reject) {
var vector = '$importModule$' + Math.random().toString(32).slice(2);
var script = document.createElement('script');
var destructor = function destructor() {
delete window[vector];
script.onerror = null;
script.onload = null;
script.remove();
URL.revokeObjectURL(script.src);
script.src = '';
};
addScriptAtts(script, atts);
script.defer = 'defer';
script.type = 'module';
script.onerror = function () {
reject(new Error('Failed to import: ' + url));
destructor();
};
script.onload = function () {
resolve(window[vector]);
destructor();
};
var absURL = toAbsoluteURL(url);
var loader = 'import * as m from \'' + absURL.replace(/'/g, "\\'") + '\'; window.' + vector + ' = ' + (returnDefault ? 'm.default || ' : '') + 'm;'; // export Module
var blob = new Blob([loader], { type: 'text/javascript' });
script.src = URL.createObjectURL(blob);
document.head.append(script);
});
}
/* globals jQuery, MathJax */
var extMathjax = {
name: 'mathjax',
init: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) {
var importLocale = _ref.importLocale;
var strings, svgEditor, $, svgCanvas, mathjaxSrcSecure, uiStrings, math, locationX, locationY, mathjaxLoaded, saveMath, buttons;
var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(_ref) {
var importLocale, strings, svgEditor, $, svgCanvas, mathjaxSrcSecure, uiStrings, math, locationX, locationY, mathjaxLoaded, saveMath, buttons;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
saveMath = function saveMath() {
var code = $('#mathjax_code_textarea').val();
// displaystyle to force MathJax NOT to use the inline style. Because it is
saveMath = function _ref2() {
var code = $('#mathjax_code_textarea').val(); // displaystyle to force MathJax NOT to use the inline style. Because it is
// less fancy!
MathJax.Hub.queue.Push(['Text', math, '\\displaystyle{' + code + '}']);
MathJax.Hub.queue.Push(['Text', math, '\\displaystyle{' + code + '}']);
/*
* The MathJax library doesn't want to bloat your webpage so it creates
* every symbol (glymph) you need only once. These are saved in a `<svg>` on
@ -247,6 +110,7 @@ var svgEditorExtension_mathjax = (function () {
* to your formula's `<svg>` and copy the lot. So we have to replace each
* `<use>` tag by its `<path>`.
*/
MathJax.Hub.queue.Push(function () {
var mathjaxMath = $('.MathJax_SVG');
var svg = $(mathjaxMath.html());
@ -254,10 +118,12 @@ var svgEditorExtension_mathjax = (function () {
// TODO: find a less pragmatic and more elegant solution to this.
var id = $(this).attr('href') ? $(this).attr('href').slice(1) // Works in Chrome.
: $(this).attr('xlink:href').slice(1); // Works in Firefox.
var glymph = $('#' + id).clone().removeAttr('id');
var x = $(this).attr('x');
var y = $(this).attr('y');
var transform = $(this).attr('transform');
if (transform && (x || y)) {
glymph.attr('transform', transform + ' translate(' + x + ',' + y + ')');
} else if (transform) {
@ -265,30 +131,29 @@ var svgEditorExtension_mathjax = (function () {
} else if (x || y) {
glymph.attr('transform', 'translate(' + x + ',' + y + ')');
}
$(this).replaceWith(glymph);
});
// Remove the style tag because it interferes with SVG-Edit.
}); // Remove the style tag because it interferes with SVG-Edit.
svg.removeAttr('style');
svg.attr('xmlns', 'http://www.w3.org/2000/svg');
svgCanvas.importSvgString($('<div>').append(svg.clone()).html(), true);
svgCanvas.ungroupSelectedElement();
// TODO: To undo the adding of the Formula you now have to undo twice.
svgCanvas.ungroupSelectedElement(); // TODO: To undo the adding of the Formula you now have to undo twice.
// This should only be once!
svgCanvas.moveSelectedElements(locationX, locationY, true);
});
};
_context.next = 3;
importLocale = _ref.importLocale;
_context.next = 4;
return importLocale();
case 3:
case 4:
strings = _context.sent;
svgEditor = this;
$ = jQuery;
svgCanvas = svgEditor.canvas;
// Configuration of the MathJax extention.
svgCanvas = svgEditor.canvas; // Configuration of the MathJax extention.
// This will be added to the head tag before MathJax is loaded.
/* mathjaxConfiguration = `<script type="text/x-mathjax-config">
@ -317,9 +182,7 @@ var svgEditorExtension_mathjax = (function () {
// Had been on https://c328740.ssl.cf1.rackcdn.com/mathjax/latest/MathJax.js?config=TeX-AMS-MML_SVG.js
// Obtained Text-AMS-MML_SVG.js from https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.3/config/TeX-AMS-MML_SVG.js
mathjaxSrcSecure = 'mathjax/MathJax.min.js?config=TeX-AMS-MML_SVG.js', uiStrings = svgEditor.uiStrings;
math = void 0, locationX = void 0, locationY = void 0, mathjaxLoaded = false;
// TODO: Implement language support. Move these uiStrings to the locale files and the code to the langReady callback.
mathjaxLoaded = false; // TODO: Implement language support. Move these uiStrings to the locale files and the code to the langReady callback.
$.extend(uiStrings, {
mathjax: {
@ -330,7 +193,6 @@ var svgEditorExtension_mathjax = (function () {
title: 'Mathematics code editor'
}
});
buttons = [{
id: 'tool_mathjax',
type: 'mode',
@ -340,32 +202,27 @@ var svgEditorExtension_mathjax = (function () {
// Only load Mathjax when needed, we don't want to strain Svg-Edit any more.
// From this point on it is very probable that it will be needed, so load it.
if (mathjaxLoaded === false) {
$('<div id="mathjax">' + '<!-- Here is where MathJax creates the math -->' + '<div id="mathjax_creator" class="tex2jax_process" style="display:none">' + '$${}$$' + '</div>' + '<div id="mathjax_overlay"></div>' + '<div id="mathjax_container">' + '<div id="tool_mathjax_back" class="toolbar_button">' + '<button id="tool_mathjax_save">OK</button>' + '<button id="tool_mathjax_cancel">Cancel</button>' + '</div>' + '<fieldset>' + '<legend id="mathjax_legend">Mathematics Editor</legend>' + '<label>' + '<span id="mathjax_explication">Please type your mathematics in ' + '<a href="https://en.wikipedia.org/wiki/Help:Displaying_a_formula" target="_blank">TeX</a> code.</span></label>' + '<textarea id="mathjax_code_textarea" spellcheck="false"></textarea>' + '</fieldset>' + '</div>' + '</div>').insertAfter('#svg_prefs').hide();
$('<div id="mathjax">' + '<!-- Here is where MathJax creates the math -->' + '<div id="mathjax_creator" class="tex2jax_process" style="display:none">' + '$${}$$' + '</div>' + '<div id="mathjax_overlay"></div>' + '<div id="mathjax_container">' + '<div id="tool_mathjax_back" class="toolbar_button">' + '<button id="tool_mathjax_save">OK</button>' + '<button id="tool_mathjax_cancel">Cancel</button>' + '</div>' + '<fieldset>' + '<legend id="mathjax_legend">Mathematics Editor</legend>' + '<label>' + '<span id="mathjax_explication">Please type your mathematics in ' + '<a href="https://en.wikipedia.org/wiki/Help:Displaying_a_formula" target="_blank">TeX</a> code.</span></label>' + '<textarea id="mathjax_code_textarea" spellcheck="false"></textarea>' + '</fieldset>' + '</div>' + '</div>').insertAfter('#svg_prefs').hide(); // Make the MathEditor draggable.
// Make the MathEditor draggable.
$('#mathjax_container').draggable({
cancel: 'button,fieldset',
containment: 'window'
});
}); // Add functionality and picture to cancel button.
// Add functionality and picture to cancel button.
$('#tool_mathjax_cancel').prepend($.getSvgIcon('cancel', true)).on('click touched', function () {
$('#mathjax').hide();
});
}); // Add functionality and picture to the save button.
// Add functionality and picture to the save button.
$('#tool_mathjax_save').prepend($.getSvgIcon('ok', true)).on('click touched', function () {
saveMath();
$('#mathjax').hide();
});
}); // MathJax preprocessing has to ignore most of the page.
// MathJax preprocessing has to ignore most of the page.
$('body').addClass('tex2jax_ignore');
// Now get (and run) the MathJax Library.
$('body').addClass('tex2jax_ignore'); // Now get (and run) the MathJax Library.
// Todo: insert script with modules once widely supported
// and if MathJax (and its `TeX-AMS-MML_SVG.js` dependency) ends up
// providing an ES6 module export: https://github.com/mathjax/MathJax/issues/1998
/*
const modularVersion = !('svgEditor' in window) ||
!window.svgEditor ||
@ -381,6 +238,7 @@ var svgEditorExtension_mathjax = (function () {
svgEditor.curConfig.extIconsPath + mathjaxSrcSecure
);
*/
importScript(svgEditor.curConfig.extIconsPath + mathjaxSrcSecure).then(function () {
// When MathJax is loaded get the div where the math will be rendered.
MathJax.Hub.queue.Push(function () {
@ -393,57 +251,56 @@ var svgEditorExtension_mathjax = (function () {
console.log('Failed loadeing MathJax.');
$.alert('Failed loading MathJax. You will not be able to change the mathematics.');
});
}
// Set the mode.
} // Set the mode.
svgCanvas.setMode('mathjax');
}
}
}];
return _context.abrupt('return', {
return _context.abrupt("return", {
name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'mathjax-icons.xml',
buttons: strings.buttons.map(function (button, i) {
return Object.assign(buttons[i], button);
}),
mouseDown: function mouseDown() {
if (svgCanvas.getMode() === 'mathjax') {
return { started: true };
return {
started: true
};
}
},
mouseUp: function mouseUp(opts) {
if (svgCanvas.getMode() === 'mathjax') {
// Get the coordinates from your mouse.
var zoom = svgCanvas.getZoom();
// Get the actual coordinate by dividing by the zoom value
var zoom = svgCanvas.getZoom(); // Get the actual coordinate by dividing by the zoom value
locationX = opts.mouse_x / zoom;
locationY = opts.mouse_y / zoom;
$('#mathjax').show();
return { started: false }; // Otherwise the last selected object dissapears.
return {
started: false
}; // Otherwise the last selected object dissapears.
}
},
callback: function callback() {
$('<style>').text('#mathjax fieldset{' + 'padding: 5px;' + 'margin: 5px;' + 'border: 1px solid #DDD;' + '}' + '#mathjax label{' + 'display: block;' + 'margin: .5em;' + '}' + '#mathjax legend {' + 'max-width:195px;' + '}' + '#mathjax_overlay {' + 'position: absolute;' + 'top: 0;' + 'left: 0;' + 'right: 0;' + 'bottom: 0;' + 'background-color: black;' + 'opacity: 0.6;' + 'z-index: 20000;' + '}' + '#mathjax_container {' + 'position: absolute;' + 'top: 50px;' + 'padding: 10px;' + 'background-color: #B0B0B0;' + 'border: 1px outset #777;' + 'opacity: 1.0;' + 'font-family: Verdana, Helvetica, sans-serif;' + 'font-size: .8em;' + 'z-index: 20001;' + '}' + '#tool_mathjax_back {' + 'margin-left: 1em;' + 'overflow: auto;' + '}' + '#mathjax_legend{' + 'font-weight: bold;' + 'font-size:1.1em;' + '}' + '#mathjax_code_textarea {\\n' + 'margin: 5px .7em;' + 'overflow: hidden;' + 'width: 416px;' + 'display: block;' + 'height: 100px;' + '}').appendTo('head');
// Add the MathJax configuration.
$('<style>').text('#mathjax fieldset{' + 'padding: 5px;' + 'margin: 5px;' + 'border: 1px solid #DDD;' + '}' + '#mathjax label{' + 'display: block;' + 'margin: .5em;' + '}' + '#mathjax legend {' + 'max-width:195px;' + '}' + '#mathjax_overlay {' + 'position: absolute;' + 'top: 0;' + 'left: 0;' + 'right: 0;' + 'bottom: 0;' + 'background-color: black;' + 'opacity: 0.6;' + 'z-index: 20000;' + '}' + '#mathjax_container {' + 'position: absolute;' + 'top: 50px;' + 'padding: 10px;' + 'background-color: #B0B0B0;' + 'border: 1px outset #777;' + 'opacity: 1.0;' + 'font-family: Verdana, Helvetica, sans-serif;' + 'font-size: .8em;' + 'z-index: 20001;' + '}' + '#tool_mathjax_back {' + 'margin-left: 1em;' + 'overflow: auto;' + '}' + '#mathjax_legend{' + 'font-weight: bold;' + 'font-size:1.1em;' + '}' + '#mathjax_code_textarea {\\n' + 'margin: 5px .7em;' + 'overflow: hidden;' + 'width: 416px;' + 'display: block;' + 'height: 100px;' + '}').appendTo('head'); // Add the MathJax configuration.
// $(mathjaxConfiguration).appendTo('head');
}
});
case 12:
case 'end':
case 13:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function init(_x) {
return _ref2.apply(this, arguments);
}
return init;
return function init(_x) {
return _init.apply(this, arguments);
};
}()
};

View File

@ -2,6 +2,7 @@ var svgEditorExtension_overview_window = (function () {
'use strict';
/* globals jQuery */
/**
* ext-overview_window.js
*
@ -15,24 +16,23 @@ var svgEditorExtension_overview_window = (function () {
init: function init(_ref) {
var isChrome = _ref.isChrome,
isIE = _ref.isIE;
var $ = jQuery;
var overviewWindowGlobals = {};
// Disabled in Chrome 48-, see https://github.com/SVG-Edit/svgedit/issues/26 and
var overviewWindowGlobals = {}; // Disabled in Chrome 48-, see https://github.com/SVG-Edit/svgedit/issues/26 and
// https://code.google.com/p/chromium/issues/detail?id=565120.
if (isChrome()) {
var verIndex = navigator.userAgent.indexOf('Chrome/') + 7;
var chromeVersion = parseInt(navigator.userAgent.substring(verIndex), 10);
if (chromeVersion < 49) {
return;
}
}
} // Define and insert the base html element.
// Define and insert the base html element.
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" style="position:relative; left:12px; top:0px;">' + '<div style="background-color:#A0A0A0; display:inline-block; overflow:visible;">' + '<svg id="overviewMiniView" width="150" height="100" x="0" y="0" viewBox="0 0 4800 3600" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">' + '<use x="0" y="0" xlink:href="#svgroot"> </use>' + '</svg>' + '<div id="overview_window_view_box" style="min-width:50px; min-height:50px; position:absolute; top:30px; left:30px; z-index:5; background-color:rgba(255,0,102,0.3);">' + '</div>' + '</div>' + '</div>' + '</div>';
$('#sidepanels').append(propsWindowHtml);
$('#sidepanels').append(propsWindowHtml); // Define dynamic animation of the view box.
// Define dynamic animation of the view box.
var updateViewBox = function updateViewBox() {
var portHeight = parseFloat($('#workarea').css('height'));
var portWidth = parseFloat($('#workarea').css('width'));
@ -42,32 +42,30 @@ var svgEditorExtension_overview_window = (function () {
var windowHeight = parseFloat($('#svgcanvas').css('height'));
var overviewWidth = $('#overviewMiniView').attr('width');
var overviewHeight = $('#overviewMiniView').attr('height');
var viewBoxX = portX / windowWidth * overviewWidth;
var viewBoxY = portY / windowHeight * overviewHeight;
var viewBoxWidth = portWidth / windowWidth * overviewWidth;
var viewBoxHeight = portHeight / windowHeight * overviewHeight;
$('#overview_window_view_box').css('min-width', viewBoxWidth + 'px');
$('#overview_window_view_box').css('min-height', viewBoxHeight + 'px');
$('#overview_window_view_box').css('top', viewBoxY + 'px');
$('#overview_window_view_box').css('left', viewBoxX + 'px');
};
$('#workarea').scroll(function () {
if (!overviewWindowGlobals.viewBoxDragging) {
updateViewBox();
}
});
$('#workarea').resize(updateViewBox);
updateViewBox();
updateViewBox(); // Compensate for changes in zoom and canvas size.
// Compensate for changes in zoom and canvas size.
var updateViewDimensions = function updateViewDimensions() {
var viewWidth = $('#svgroot').attr('width');
var viewHeight = $('#svgroot').attr('height');
var viewX = 640;
var viewY = 480;
if (isIE()) {
// This has only been tested with Firefox 10 and IE 9 (without chrome frame).
// I am not sure if if is Firefox or IE that is being non compliant here.
@ -85,10 +83,11 @@ var svgEditorExtension_overview_window = (function () {
$('#overviewMiniView').attr('height', svgHeightNew);
updateViewBox();
};
updateViewDimensions();
// Set up the overview window as a controller for the view port.
updateViewDimensions(); // Set up the overview window as a controller for the view port.
overviewWindowGlobals.viewBoxDragging = false;
var updateViewPortFromViewBox = function updateViewPortFromViewBox() {
var windowWidth = parseFloat($('#svgcanvas').css('width'));
var windowHeight = parseFloat($('#svgcanvas').css('height'));
@ -96,13 +95,12 @@ var svgEditorExtension_overview_window = (function () {
var overviewHeight = $('#overviewMiniView').attr('height');
var viewBoxX = parseFloat($('#overview_window_view_box').css('left'));
var viewBoxY = parseFloat($('#overview_window_view_box').css('top'));
var portX = viewBoxX / overviewWidth * windowWidth;
var portY = viewBoxY / overviewHeight * windowHeight;
$('#workarea').scrollLeft(portX);
$('#workarea').scrollTop(portY);
};
$('#overview_window_view_box').draggable({
containment: 'parent',
drag: updateViewPortFromViewBox,
@ -121,19 +119,21 @@ var svgEditorExtension_overview_window = (function () {
var overviewHeight = $('#overviewMiniView').attr('height');
var viewBoxWidth = parseFloat($('#overview_window_view_box').css('min-width'));
var viewBoxHeight = parseFloat($('#overview_window_view_box').css('min-height'));
var viewBoxX = mouseX - 0.5 * viewBoxWidth;
var viewBoxY = mouseY - 0.5 * viewBoxHeight;
// deal with constraints
var viewBoxY = mouseY - 0.5 * viewBoxHeight; // deal with constraints
if (viewBoxX < 0) {
viewBoxX = 0;
}
if (viewBoxY < 0) {
viewBoxY = 0;
}
if (viewBoxX + viewBoxWidth > overviewWidth) {
viewBoxX = overviewWidth - viewBoxWidth;
}
if (viewBoxY + viewBoxHeight > overviewHeight) {
viewBoxY = overviewHeight - viewBoxHeight;
}
@ -142,7 +142,6 @@ var svgEditorExtension_overview_window = (function () {
$('#overview_window_view_box').css('left', viewBoxX + 'px');
updateViewPortFromViewBox();
});
return {
name: 'overview window',
canvasUpdated: updateViewDimensions,

View File

@ -1,11 +1,7 @@
var svgEditorExtension_panning = (function () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
@ -17,18 +13,29 @@ var svgEditorExtension_panning = (function () {
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
Promise.resolve(value).then(_next, _throw);
}
}
return step("next");
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
};
}
/**
* ext-panning.js
@ -38,23 +45,26 @@ var svgEditorExtension_panning = (function () {
* @copyright 2013 Luis Aguirre
*
*/
/*
This is a very basic SVG-Edit extension to let tablet/mobile devices pan without problem
*/
var extPanning = {
name: 'panning',
init: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) {
var importLocale = _ref.importLocale;
var strings, svgEditor, svgCanvas, buttons;
var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(_ref) {
var importLocale, strings, svgEditor, svgCanvas, buttons;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
importLocale = _ref.importLocale;
_context.next = 3;
return importLocale();
case 2:
case 3:
strings = _context.sent;
svgEditor = this;
svgCanvas = svgEditor.canvas;
@ -68,7 +78,7 @@ var svgEditorExtension_panning = (function () {
}
}
}];
return _context.abrupt('return', {
return _context.abrupt("return", {
name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'ext-panning.xml',
buttons: strings.buttons.map(function (button, i) {
@ -77,7 +87,9 @@ var svgEditorExtension_panning = (function () {
mouseDown: function mouseDown() {
if (svgCanvas.getMode() === 'ext-panning') {
svgEditor.setPanning(true);
return { started: true };
return {
started: true
};
}
},
mouseUp: function mouseUp() {
@ -91,19 +103,17 @@ var svgEditorExtension_panning = (function () {
}
});
case 7:
case 'end':
case 8:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function init(_x) {
return _ref2.apply(this, arguments);
}
return init;
return function init(_x) {
return _init.apply(this, arguments);
};
}()
};

View File

@ -4,24 +4,27 @@ var svgEditorExtension_php_savefile = (function () {
/* globals jQuery */
// TODO: Might add support for "exportImage" custom
// handler as in "ext-server_opensave.js" (and in savefile.php)
var extPhp_savefile = {
name: 'php_savefile',
init: function init() {
var svgEditor = this;
var $ = jQuery;
var svgCanvas = svgEditor.canvas;
function getFileNameFromTitle() {
var title = svgCanvas.getDocumentTitle();
return title.trim();
}
var saveSvgAction = svgEditor.curConfig.extPath + 'savefile.php';
svgEditor.setCustomHandlers({
save: function save(win, data) {
var svg = '<?xml version="1.0" encoding="UTF-8"?>\n' + data,
filename = getFileNameFromTitle();
$.post(saveSvgAction, { output_svg: svg, filename: filename });
$.post(saveSvgAction, {
output_svg: svg,
filename: filename
});
}
});
}

View File

@ -1,11 +1,7 @@
var svgEditorExtension_polygon = (function () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
@ -17,20 +13,32 @@ var svgEditorExtension_polygon = (function () {
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
Promise.resolve(value).then(_next, _throw);
}
}
return step("next");
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
};
}
/* globals jQuery */
/**
* ext-polygon.js
*
@ -41,30 +49,34 @@ var svgEditorExtension_polygon = (function () {
var extPolygon = {
name: 'polygon',
init: function () {
var _ref = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(S) {
var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(S) {
var svgEditor, $, svgCanvas, importLocale, editingitex, strings, selElems, started, newFO, showPanel, setAttr, cot, sec, buttons, contextTools;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
sec = function sec(n) {
sec = function _ref4(n) {
return 1 / Math.cos(n);
};
cot = function cot(n) {
cot = function _ref3(n) {
return 1 / Math.tan(n);
};
setAttr = function setAttr(attr, val) {
setAttr = function _ref2(attr, val) {
svgCanvas.changeSelectedAttribute(attr, val);
svgCanvas.call('changed', selElems);
};
showPanel = function showPanel(on) {
showPanel = function _ref(on) {
var fcRules = $('#fc_rules');
if (!fcRules.length) {
fcRules = $('<style id="fc_rules"></style>').appendTo('head');
}
fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }');
$('#polygon_panel').toggle(on);
};
@ -78,30 +90,6 @@ var svgEditorExtension_polygon = (function () {
case 10:
strings = _context.sent;
selElems = void 0, started = void 0, newFO = void 0;
// const ccZoom;
// const wEl, hEl;
// const wOffset, hOffset;
// const ccRBG;
// const ccOpacity;
// const brushW, brushH;
// const ccDebug = document.getElementById('debugpanel');
/* const properlySourceSizeTextArea = function(){
// TODO: remove magic numbers here and get values from CSS
const height = $('#svg_source_container').height() - 80;
$('#svg_source_textarea').css('height', height);
}; */
/*
function toggleSourceButtons(on){
$('#tool_source_save, #tool_source_cancel').toggle(!on);
$('#polygon_save, #polygon_cancel').toggle(on);
}
*/
/**
* Obtained from http://code.google.com/p/passenger-top/source/browse/instiki/public/svg-edit/editor/extensions/ext-itex.js?r=3
@ -110,6 +98,7 @@ var svgEditorExtension_polygon = (function () {
* @param {string} tex The itex text.
* @returns {boolean} This function returns false if the set was unsuccessful, true otherwise.
*/
/*
function setItexString(tex) {
const mathns = 'http://www.w3.org/1998/Math/MathML',
@ -170,7 +159,7 @@ var svgEditorExtension_polygon = (function () {
}
}
}];
return _context.abrupt('return', {
return _context.abrupt("return", {
name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'polygon-icons.svg',
buttons: strings.buttons.map(function (button, i) {
@ -179,36 +168,36 @@ var svgEditorExtension_polygon = (function () {
context_tools: strings.contextTools.map(function (contextTool, i) {
return Object.assign(contextTools[i], contextTool);
}),
callback: function callback() {
$('#polygon_panel').hide();
// TODO: Needs to be done after orig icon loads
setTimeout(function () {
// Create source save/cancel buttons
/* const save = */$('#tool_source_save').clone().hide().attr('id', 'polygon_save').unbind().appendTo('#tool_source_back').click(function () {
/* const save = */
$('#tool_source_save').clone().hide().attr('id', 'polygon_save').unbind().appendTo('#tool_source_back').click(function () {
if (!editingitex) {
return;
}
// }
} // Todo: Uncomment the setItexString() function above and handle ajaxEndpoint?
// setSelectMode();
});
/* const cancel = */
/* const cancel = */$('#tool_source_cancel').clone().hide().attr('id', 'polygon_cancel').unbind().appendTo('#tool_source_back').click(function () {
$('#tool_source_cancel').clone().hide().attr('id', 'polygon_cancel').unbind().appendTo('#tool_source_back').click(function () {
});
}, 3000);
},
mouseDown: function mouseDown(opts) {
// const e = opts.event;
var rgb = svgCanvas.getColor('fill');
// const ccRgbEl = rgb.substring(1, rgb.length);
var sRgb = svgCanvas.getColor('stroke');
// ccSRgbEl = sRgb.substring(1, rgb.length);
var rgb = svgCanvas.getColor('fill'); // const ccRgbEl = rgb.substring(1, rgb.length);
var sRgb = svgCanvas.getColor('stroke'); // ccSRgbEl = sRgb.substring(1, rgb.length);
var sWidth = svgCanvas.getStrokeWidth();
if (svgCanvas.getMode() === 'polygon') {
started = true;
newFO = svgCanvas.addSVGElementFromJson({
element: 'polygon',
attr: {
@ -224,7 +213,6 @@ var svgEditorExtension_polygon = (function () {
strokeWidth: sWidth
}
});
return {
started: true
};
@ -234,6 +222,7 @@ var svgEditorExtension_polygon = (function () {
if (!started) {
return;
}
if (svgCanvas.getMode() === 'polygon') {
// const e = opts.event;
var c = $(newFO).attr(['cx', 'cy', 'sides', 'orient', 'fill', 'strokecolor', 'strokeWidth']);
@ -246,29 +235,27 @@ var svgEditorExtension_polygon = (function () {
strokeWidth = c.strokeWidth,
sides = c.sides,
edg = Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy)) / 1.5;
newFO.setAttributeNS(null, 'edge', edg);
var inradius = edg / 2 * cot(Math.PI / sides);
var circumradius = inradius * sec(Math.PI / sides);
var points = '';
for (var s = 0; sides >= s; s++) {
var angle = 2.0 * Math.PI * s / sides;
x = circumradius * Math.cos(angle) + cx;
y = circumradius * Math.sin(angle) + cy;
points += x + ',' + y + ' ';
}
} // const poly = newFO.createElementNS(NS.SVG, 'polygon');
// const poly = newFO.createElementNS(NS.SVG, 'polygon');
newFO.setAttributeNS(null, 'points', points);
newFO.setAttributeNS(null, 'fill', fill);
newFO.setAttributeNS(null, 'stroke', strokecolor);
newFO.setAttributeNS(null, 'stroke-width', strokeWidth);
// newFO.setAttributeNS(null, 'transform', 'rotate(-90)');
newFO.setAttributeNS(null, 'stroke-width', strokeWidth); // newFO.setAttributeNS(null, 'transform', 'rotate(-90)');
// const shape = newFO.getAttributeNS(null, 'shape');
// newFO.append(poly);
// DrawPoly(cx, cy, sides, edg, orient);
return {
started: true
};
@ -277,8 +264,8 @@ var svgEditorExtension_polygon = (function () {
mouseUp: function mouseUp(opts) {
if (svgCanvas.getMode() === 'polygon') {
var attrs = $(newFO).attr('edge');
var keep = attrs.edge !== '0';
// svgCanvas.addToSelection([newFO], true);
var keep = attrs.edge !== '0'; // svgCanvas.addToSelection([newFO], true);
return {
keep: keep,
element: newFO
@ -288,14 +275,14 @@ var svgEditorExtension_polygon = (function () {
selectedChanged: function selectedChanged(opts) {
// Use this to update the current selected elements
selElems = opts.elems;
var i = selElems.length;
while (i--) {
var elem = selElems[i];
if (elem && elem.getAttributeNS(null, 'shape') === 'regularPoly') {
if (opts.selectedElement && !opts.multiselected) {
$('#polySides').val(elem.getAttribute('sides'));
showPanel(true);
} else {
showPanel(false);
@ -305,24 +292,20 @@ var svgEditorExtension_polygon = (function () {
}
}
},
elementChanged: function elementChanged(opts) {
// const elem = opts.elems[0];
}
elementChanged: function elementChanged(opts) {}
});
case 15:
case 'end':
case 14:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function init(_x) {
return _ref.apply(this, arguments);
}
return init;
return function init(_x) {
return _init.apply(this, arguments);
};
}()
};

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,11 +1,7 @@
var svgEditorExtension_shapes = (function () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
@ -17,20 +13,32 @@ var svgEditorExtension_shapes = (function () {
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
Promise.resolve(value).then(_next, _throw);
}
}
return step("next");
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
};
}
/* globals jQuery */
/**
* ext-shapes.js
*
@ -42,14 +50,15 @@ var svgEditorExtension_shapes = (function () {
var extShapes = {
name: 'shapes',
init: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) {
var importLocale = _ref.importLocale;
var strings, svgEditor, $, canv, svgroot, lastBBox, categories, library, modeId, startClientPos, currentD, curShapeId, curShape, startX, startY, curLib, loadIcons, makeButtons, loadLibrary, buttons;
var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(_ref) {
var importLocale, strings, svgEditor, $, canv, svgroot, lastBBox, categories, library, modeId, startClientPos, currentD, curShapeId, curShape, startX, startY, curLib, loadIcons, makeButtons, loadLibrary, buttons;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
loadLibrary = function loadLibrary(catId) {
loadLibrary = function _ref4(catId) {
var lib = library[catId];
if (!lib) {
@ -65,61 +74,59 @@ var svgEditorExtension_shapes = (function () {
});
return;
}
curLib = lib;
if (!lib.buttons.length) {
makeButtons(catId, lib);
}
loadIcons();
};
makeButtons = function makeButtons(cat, shapes) {
makeButtons = function _ref3(cat, shapes) {
var size = curLib.size || 300;
var fill = curLib.fill || false;
var off = size * 0.05;
var vb = [-off, -off, size + off * 2, size + off * 2].join(' ');
var stroke = fill ? 0 : size / 30;
var shapeIcon = new DOMParser().parseFromString('<svg xmlns="http://www.w3.org/2000/svg">' + '<svg viewBox="' + vb + '">' + '<path fill="' + (fill ? '#333' : 'none') + '" stroke="#000" stroke-width="' + stroke + '" /></svg></svg>', 'text/xml');
var width = 24;
var height = 24;
shapeIcon.documentElement.setAttribute('width', width);
shapeIcon.documentElement.setAttribute('height', height);
var svgElem = $(document.importNode(shapeIcon.documentElement, true));
var data = shapes.data;
curLib.buttons = [];
for (var id in data) {
var pathD = data[id];
var icon = svgElem.clone();
icon.find('path').attr('d', pathD);
var iconBtn = icon.wrap('<div class="tool_button">').parent().attr({
id: modeId + '_' + id,
title: id
});
// Store for later use
}); // Store for later use
curLib.buttons.push(iconBtn[0]);
}
};
loadIcons = function loadIcons() {
loadIcons = function _ref2() {
$('#shape_buttons').empty().append(curLib.buttons);
};
_context.next = 5;
importLocale = _ref.importLocale;
_context.next = 6;
return importLocale();
case 5:
case 6:
strings = _context.sent;
svgEditor = this;
$ = jQuery;
canv = svgEditor.canvas;
svgroot = canv.getRootElem();
lastBBox = {};
// This populates the category list
lastBBox = {}; // This populates the category list
categories = strings.categories;
library = {
@ -153,19 +160,18 @@ var svgEditorExtension_shapes = (function () {
cross: 'm0.99844,99.71339l98.71494,0l0,-98.71495l101.26279,0l0,98.71495l98.71495,0l0,101.2628l-98.71495,0l0,98.71494l-101.26279,0l0,-98.71494l-98.71494,0z',
plaque: 'm-0.00197,49.94376l0,0c27.5829,0 49.94327,-22.36036 49.94327,-49.94327l199.76709,0l0,0c0,27.5829 22.36037,49.94327 49.94325,49.94327l0,199.7671l0,0c-27.58289,0 -49.94325,22.36034 -49.94325,49.94325l-199.76709,0c0,-27.58292 -22.36037,-49.94325 -49.94327,-49.94325z',
page: 'm249.3298,298.99744l9.9335,-39.73413l39.73413,-9.93355l-49.66763,49.66768l-248.33237,0l0,-298.00001l298.00001,0l0,248.33234'
},
buttons: []
}
};
modeId = 'shapelib';
startClientPos = {};
currentD = void 0, curShapeId = void 0, curShape = void 0, startX = void 0, startY = void 0;
curLib = library.basic;
buttons = [{
id: 'tool_shapelib',
icon: svgEditor.curConfig.extIconsPath + 'shapes.png',
type: 'mode_flyout', // _flyout
type: 'mode_flyout',
// _flyout
position: 6,
events: {
click: function click() {
@ -173,22 +179,18 @@ var svgEditorExtension_shapes = (function () {
}
}
}];
return _context.abrupt('return', {
return _context.abrupt("return", {
svgicons: svgEditor.curConfig.extIconsPath + 'ext-shapes.xml',
buttons: strings.buttons.map(function (button, i) {
return Object.assign(buttons[i], button);
}),
callback: function callback() {
$('<style>').text('#shape_buttons {' + 'overflow: auto;' + 'width: 180px;' + 'max-height: 300px;' + 'display: table-cell;' + 'vertical-align: middle;' + '}' + '#shape_cats {' + 'min-width: 110px;' + 'display: table-cell;' + 'vertical-align: middle;' + 'height: 300px;' + '}' + '#shape_cats > div {' + 'line-height: 1em;' + 'padding: .5em;' + 'border:1px solid #B0B0B0;' + 'background: #E8E8E8;' + 'margin-bottom: -1px;' + '}' + '#shape_cats div:hover {' + 'background: #FFFFCC;' + '}' + '#shape_cats div.current {' + 'font-weight: bold;' + '}').appendTo('head');
var btnDiv = $('<div id="shape_buttons">');
$('#tools_shapelib > *').wrapAll(btnDiv);
var shower = $('#tools_shapelib_show');
loadLibrary('basic'); // Do mouseup on parent element rather than each button
loadLibrary('basic');
// Do mouseup on parent element rather than each button
$('#shape_buttons').mouseup(function (evt) {
var btn = $(evt.target).closest('div.tool_button');
@ -201,53 +203,46 @@ var svgEditorExtension_shapes = (function () {
shower.append(copy).attr('data-curopt', '#' + btn[0].id) // This sets the current mode
.mouseup();
canv.setMode(modeId);
curShapeId = btn[0].id.substr((modeId + '_').length);
currentD = curLib.data[curShapeId];
$('.tools_flyout').fadeOut();
});
var shapeCats = $('<div id="shape_cats">');
var catStr = '';
$.each(categories, function (id, label) {
catStr += '<div data-cat=' + id + '>' + label + '</div>';
});
shapeCats.html(catStr).children().bind('mouseup', function () {
var catlink = $(this);
catlink.siblings().removeClass('current');
catlink.addClass('current');
loadLibrary(catlink.attr('data-cat')); // Get stuff
loadLibrary(catlink.attr('data-cat'));
// Get stuff
return false;
});
shapeCats.children().eq(0).addClass('current');
$('#tools_shapelib').append(shapeCats);
shower.mouseup(function () {
canv.setMode(currentD ? modeId : 'select');
});
$('#tool_shapelib').remove();
var h = $('#tools_shapelib').height();
$('#tools_shapelib').css({
'margin-top': -(h / 2 - 15),
'margin-left': 3
});
// Now add shape categories from locale
}); // Now add shape categories from locale
var cats = {};
for (var o in categories) {
cats['#shape_cats [data-cat="' + o + '"]'] = categories[o];
}
this.setStrings('content', cats);
},
mouseDown: function mouseDown(opts) {
var mode = canv.getMode();
if (mode !== modeId) {
return;
}
@ -257,10 +252,8 @@ var svgEditorExtension_shapes = (function () {
startY = opts.start_y;
var y = startY;
var curStyle = canv.getStyle();
startClientPos.x = opts.event.clientX;
startClientPos.y = opts.event.clientY;
curShape = canv.addSVGElementFromJson({
element: 'path',
curStyles: true,
@ -270,43 +263,39 @@ var svgEditorExtension_shapes = (function () {
opacity: curStyle.opacity / 2,
style: 'pointer-events:none'
}
});
}); // Make sure shape uses absolute values
// Make sure shape uses absolute values
if (/[a-z]/.test(currentD)) {
currentD = curLib.data[curShapeId] = canv.pathActions.convertPath(curShape);
curShape.setAttribute('d', currentD);
canv.pathActions.fixEnd(curShape);
}
curShape.setAttribute('transform', 'translate(' + x + ',' + y + ') scale(0.005) translate(' + -x + ',' + -y + ')');
canv.recalculateDimensions(curShape);
/* const tlist = */
/* const tlist = */canv.getTransformList(curShape);
canv.getTransformList(curShape);
lastBBox = curShape.getBBox();
return {
started: true
};
},
mouseMove: function mouseMove(opts) {
var mode = canv.getMode();
if (mode !== modeId) {
return;
}
var zoom = canv.getZoom();
var evt = opts.event;
var x = opts.mouse_x / zoom;
var y = opts.mouse_y / zoom;
var tlist = canv.getTransformList(curShape),
box = curShape.getBBox(),
left = box.x,
top = box.y;
// {width, height} = box,
top = box.y; // {width, height} = box,
// const dx = (x - startX), dy = (y - startY);
var newbox = {
@ -315,7 +304,6 @@ var svgEditorExtension_shapes = (function () {
width: Math.abs(x - startX),
height: Math.abs(y - startY)
};
/*
// This is currently serving no purpose, so commenting out
let sy = height ? (height + dy) / height : 1,
@ -323,49 +311,48 @@ var svgEditorExtension_shapes = (function () {
*/
var sx = newbox.width / lastBBox.width || 1;
var sy = newbox.height / lastBBox.height || 1;
var sy = newbox.height / lastBBox.height || 1; // Not perfect, but mostly works...
// Not perfect, but mostly works...
var tx = 0;
if (x < startX) {
tx = lastBBox.width;
}
var ty = 0;
if (y < startY) {
ty = lastBBox.height;
}
} // update the transform list with translate,scale,translate
// update the transform list with translate,scale,translate
var translateOrigin = svgroot.createSVGTransform(),
scale = svgroot.createSVGTransform(),
translateBack = svgroot.createSVGTransform();
translateOrigin.setTranslate(-(left + tx), -(top + ty));
if (!evt.shiftKey) {
var max = Math.min(Math.abs(sx), Math.abs(sy));
sx = max * (sx < 0 ? -1 : 1);
sy = max * (sy < 0 ? -1 : 1);
}
scale.setScale(sx, sy);
scale.setScale(sx, sy);
translateBack.setTranslate(left + tx, top + ty);
tlist.appendItem(translateBack);
tlist.appendItem(scale);
tlist.appendItem(translateOrigin);
canv.recalculateDimensions(curShape);
lastBBox = curShape.getBBox();
},
mouseUp: function mouseUp(opts) {
var mode = canv.getMode();
if (mode !== modeId) {
return;
}
var keepObject = opts.event.clientX !== startClientPos.x && opts.event.clientY !== startClientPos.y;
return {
keep: keepObject,
element: curShape,
@ -375,18 +362,16 @@ var svgEditorExtension_shapes = (function () {
});
case 19:
case 'end':
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function init(_x) {
return _ref2.apply(this, arguments);
}
return init;
return function init(_x) {
return _init.apply(this, arguments);
};
}()
};

View File

@ -1,11 +1,7 @@
var svgEditorExtension_star = (function () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
@ -17,20 +13,32 @@ var svgEditorExtension_star = (function () {
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
Promise.resolve(value).then(_next, _throw);
}
}
return step("next");
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
};
}
/* globals jQuery */
/**
* ext-star.js
*
@ -41,22 +49,26 @@ var svgEditorExtension_star = (function () {
var extStar = {
name: 'star',
init: function () {
var _ref = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(S) {
var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(S) {
var svgEditor, $, svgCanvas, importLocale, selElems, started, newFO, strings, showPanel, setAttr, buttons, contextTools;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
setAttr = function setAttr(attr, val) {
setAttr = function _ref2(attr, val) {
svgCanvas.changeSelectedAttribute(attr, val);
svgCanvas.call('changed', selElems);
};
showPanel = function showPanel(on) {
showPanel = function _ref(on) {
var fcRules = $('#fc_rules');
if (!fcRules.length) {
fcRules = $('<style id="fc_rules"></style>').appendTo('head');
}
fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }');
$('#star_panel').toggle(on);
};
@ -66,19 +78,12 @@ var svgEditorExtension_star = (function () {
svgCanvas = svgEditor.canvas;
importLocale = S.importLocale; // {svgcontent},
selElems = void 0, started = void 0, newFO = void 0;
// edg = 0,
// newFOG, newFOGParent, newDef, newImageName, newMaskID,
// undoCommand = 'Not image',
// modeChangeG, ccZoom, wEl, hEl, wOffset, hOffset, ccRgbEl, brushW, brushH;
_context.next = 9;
_context.next = 8;
return importLocale();
case 9:
case 8:
strings = _context.sent;
/*
function cot(n){
return 1 / Math.tan(n);
@ -128,7 +133,7 @@ var svgEditorExtension_star = (function () {
}
}
}];
return _context.abrupt('return', {
return _context.abrupt("return", {
name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'star-icons.svg',
buttons: strings.buttons.map(function (button, i) {
@ -138,19 +143,17 @@ var svgEditorExtension_star = (function () {
return Object.assign(contextTools[i], contextTool);
}),
callback: function callback() {
$('#star_panel').hide();
// const endChanges = function(){};
$('#star_panel').hide(); // const endChanges = function(){};
},
mouseDown: function mouseDown(opts) {
var rgb = svgCanvas.getColor('fill');
// const ccRgbEl = rgb.substring(1, rgb.length);
var sRgb = svgCanvas.getColor('stroke');
// const ccSRgbEl = sRgb.substring(1, rgb.length);
var rgb = svgCanvas.getColor('fill'); // const ccRgbEl = rgb.substring(1, rgb.length);
var sRgb = svgCanvas.getColor('stroke'); // const ccSRgbEl = sRgb.substring(1, rgb.length);
var sWidth = svgCanvas.getStrokeWidth();
if (svgCanvas.getMode() === 'star') {
started = true;
newFO = svgCanvas.addSVGElementFromJson({
element: 'polygon',
attr: {
@ -177,9 +180,9 @@ var svgEditorExtension_star = (function () {
if (!started) {
return;
}
if (svgCanvas.getMode() === 'star') {
var c = $(newFO).attr(['cx', 'cy', 'point', 'orient', 'fill', 'strokecolor', 'strokeWidth', 'radialshift']);
var x = opts.mouse_x;
var y = opts.mouse_y;
var cx = c.cx,
@ -192,13 +195,13 @@ var svgEditorExtension_star = (function () {
orient = c.orient,
circumradius = Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy)) / 1.5,
inradius = circumradius / document.getElementById('starRadiusMulitplier').value;
newFO.setAttributeNS(null, 'r', circumradius);
newFO.setAttributeNS(null, 'r2', inradius);
var polyPoints = '';
for (var s = 0; point >= s; s++) {
var angle = 2.0 * Math.PI * (s / point);
if (orient === 'point') {
angle -= Math.PI / 2;
} else if (orient === 'edge') {
@ -207,30 +210,31 @@ var svgEditorExtension_star = (function () {
x = circumradius * Math.cos(angle) + cx;
y = circumradius * Math.sin(angle) + cy;
polyPoints += x + ',' + y + ' ';
if (!isNaN(inradius)) {
angle = 2.0 * Math.PI * (s / point) + Math.PI / point;
if (orient === 'point') {
angle -= Math.PI / 2;
} else if (orient === 'edge') {
angle = angle + Math.PI / point - Math.PI / 2;
}
angle += radialshift;
angle += radialshift;
x = inradius * Math.cos(angle) + cx;
y = inradius * Math.sin(angle) + cy;
polyPoints += x + ',' + y + ' ';
}
}
newFO.setAttributeNS(null, 'points', polyPoints);
newFO.setAttributeNS(null, 'fill', fill);
newFO.setAttributeNS(null, 'stroke', strokecolor);
newFO.setAttributeNS(null, 'stroke-width', strokeWidth);
/* const shape = */newFO.getAttributeNS(null, 'shape');
/* const shape = */
newFO.getAttributeNS(null, 'shape');
return {
started: true
};
@ -238,8 +242,8 @@ var svgEditorExtension_star = (function () {
},
mouseUp: function mouseUp() {
if (svgCanvas.getMode() === 'star') {
var attrs = $(newFO).attr(['r']);
// svgCanvas.addToSelection([newFO], true);
var attrs = $(newFO).attr(['r']); // svgCanvas.addToSelection([newFO], true);
return {
keep: attrs.r !== '0',
element: newFO
@ -249,10 +253,11 @@ var svgEditorExtension_star = (function () {
selectedChanged: function selectedChanged(opts) {
// Use this to update the current selected elements
selElems = opts.elems;
var i = selElems.length;
while (i--) {
var elem = selElems[i];
if (elem && elem.getAttributeNS(null, 'shape') === 'star') {
if (opts.selectedElement && !opts.multiselected) {
// $('#starRadiusMulitplier').val(elem.getAttribute('r2'));
@ -267,24 +272,20 @@ var svgEditorExtension_star = (function () {
}
}
},
elementChanged: function elementChanged(opts) {
// const elem = opts.elems[0];
}
elementChanged: function elementChanged(opts) {}
});
case 13:
case 'end':
case 12:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function init(_x) {
return _ref.apply(this, arguments);
}
return init;
return function init(_x) {
return _init.apply(this, arguments);
};
}()
};

View File

@ -1,11 +1,7 @@
var svgEditorExtension_storage = (function () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
@ -17,20 +13,32 @@ var svgEditorExtension_storage = (function () {
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
Promise.resolve(value).then(_next, _throw);
}
}
return step("next");
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
};
}
/* globals jQuery */
/**
* ext-storage.js
*
@ -58,23 +66,22 @@ var svgEditorExtension_storage = (function () {
init: function init() {
var svgEditor = this;
var $ = jQuery;
var svgCanvas = svgEditor.canvas;
// We could empty any already-set data for users when they decline storage,
var svgCanvas = svgEditor.canvas; // We could empty any already-set data for users when they decline storage,
// but it would be a risk for users who wanted to store but accidentally
// said "no"; instead, we'll let those who already set it, delete it themselves;
// to change, set the "emptyStorageOnDecline" config setting to true
// in svgedit-config-iife.js/svgedit-config-es.js.
var _svgEditor$curConfig = svgEditor.curConfig,
emptyStorageOnDecline = _svgEditor$curConfig.emptyStorageOnDecline,
noStorageOnLoad = _svgEditor$curConfig.noStorageOnLoad,
forceStorage = _svgEditor$curConfig.forceStorage;
var storage = svgEditor.storage;
function replaceStoragePrompt(val) {
val = val ? 'storagePrompt=' + val : '';
var loc = top.location; // Allow this to work with the embedded editor as well
if (loc.href.includes('storagePrompt=')) {
loc.href = loc.href.replace(/([&?])storagePrompt=[^&]*(&?)/, function (n0, n1, amp) {
return (val ? n1 : '') + val + (!val && amp ? n1 : amp || '');
@ -83,9 +90,11 @@ var svgEditorExtension_storage = (function () {
loc.href += (loc.href.includes('?') ? '&' : '?') + val;
}
}
function setSVGContentStorage(val) {
if (storage) {
var name = 'svgedit-' + svgEditor.curConfig.canvasName;
if (!val) {
storage.removeItem(name);
} else {
@ -104,18 +113,19 @@ var svgEditorExtension_storage = (function () {
function emptyStorage() {
setSVGContentStorage('');
for (var name in svgEditor.curPrefs) {
if (svgEditor.curPrefs.hasOwnProperty(name)) {
name = 'svg-edit-' + name;
if (storage) {
storage.removeItem(name);
}
expireCookie(name);
}
}
}
// emptyStorage();
} // emptyStorage();
/**
* Listen for unloading: If and only if opted in by the user, set the content
@ -125,31 +135,37 @@ var svgEditorExtension_storage = (function () {
* 2. Use localStorage to set SVG contents (potentially too large to allow in cookies)
* 3. Use localStorage (where available) or cookies to set preferences.
*/
function setupBeforeUnloadListener() {
window.addEventListener('beforeunload', function (e) {
// Don't save anything unless the user opted in to storage
if (!document.cookie.match(/(?:^|;\s*)store=(?:prefsAndContent|prefsOnly)/)) {
return;
}
if (document.cookie.match(/(?:^|;\s*)store=prefsAndContent/)) {
setSVGContentStorage(svgCanvas.getSvgString());
}
svgEditor.setConfig({ no_save_warning: true }); // No need for explicit saving at all once storage is on
svgEditor.setConfig({
no_save_warning: true
}); // No need for explicit saving at all once storage is on
// svgEditor.showSaveWarning = false;
var curPrefs = svgEditor.curPrefs;
for (var key in curPrefs) {
if (curPrefs.hasOwnProperty(key)) {
// It's our own config, so we don't need to iterate up the prototype chain
var val = curPrefs[key];
var store = val !== undefined;
key = 'svg-edit-' + key;
if (!store) {
continue;
}
if (storage) {
storage.setItem(key, val);
} else if (window.widget) {
@ -167,72 +183,79 @@ var svgEditorExtension_storage = (function () {
return {
name: 'storage',
langReady: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) {
var importLocale = _ref.importLocale;
var _$$deparam$querystrin, storagePrompt, confirmSetStorage, message, storagePrefsAndContent, storagePrefsOnly, storagePrefs, storageNoPrefsOrContent, storageNoPrefs, rememberLabel, rememberTooltip, options, oldContainerWidth, oldContainerMarginLeft, oldContentHeight, oldContainerHeight;
var _langReady = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(_ref) {
var importLocale, _$$deparam$querystrin, storagePrompt, confirmSetStorage, message, storagePrefsAndContent, storagePrefsOnly, storagePrefs, storageNoPrefsOrContent, storageNoPrefs, rememberLabel, rememberTooltip, options, oldContainerWidth, oldContainerMarginLeft, oldContentHeight, oldContainerHeight;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
importLocale = _ref.importLocale;
_$$deparam$querystrin = $.deparam.querystring(true), storagePrompt = _$$deparam$querystrin.storagePrompt;
_context.next = 3;
_context.next = 4;
return importLocale();
case 3:
case 4:
confirmSetStorage = _context.sent;
message = confirmSetStorage.message, storagePrefsAndContent = confirmSetStorage.storagePrefsAndContent, storagePrefsOnly = confirmSetStorage.storagePrefsOnly, storagePrefs = confirmSetStorage.storagePrefs, storageNoPrefsOrContent = confirmSetStorage.storageNoPrefsOrContent, storageNoPrefs = confirmSetStorage.storageNoPrefs, rememberLabel = confirmSetStorage.rememberLabel, rememberTooltip = confirmSetStorage.rememberTooltip;
// No need to run this one-time dialog again just because the user
message = confirmSetStorage.message, storagePrefsAndContent = confirmSetStorage.storagePrefsAndContent, storagePrefsOnly = confirmSetStorage.storagePrefsOnly, storagePrefs = confirmSetStorage.storagePrefs, storageNoPrefsOrContent = confirmSetStorage.storageNoPrefsOrContent, storageNoPrefs = confirmSetStorage.storageNoPrefs, rememberLabel = confirmSetStorage.rememberLabel, rememberTooltip = confirmSetStorage.rememberTooltip; // No need to run this one-time dialog again just because the user
// changes the language
if (!loaded) {
_context.next = 7;
_context.next = 8;
break;
}
return _context.abrupt('return');
return _context.abrupt("return");
case 7:
loaded = true;
// Note that the following can load even if "noStorageOnLoad" is
case 8:
loaded = true; // Note that the following can load even if "noStorageOnLoad" is
// set to false; to avoid any chance of storage, avoid this
// extension! (and to avoid using any prior storage, set the
// config option "noStorageOnLoad" to true).
if (!forceStorage && (
// If the URL has been explicitly set to always prompt the
if (!forceStorage && ( // If the URL has been explicitly set to always prompt the
// user (e.g., so one can be pointed to a URL where one
// can alter one's settings, say to prevent future storage)...
storagePrompt === true ||
// ...or...if the URL at least doesn't explicitly prevent a
storagePrompt === true || // ...or...if the URL at least doesn't explicitly prevent a
// storage prompt (as we use for users who
// don't want to set cookies at all but who don't want
// continual prompts about it)...
storagePrompt !== false &&
// ...and this user hasn't previously indicated a desire for storage
!document.cookie.match(/(?:^|;\s*)store=(?:prefsAndContent|prefsOnly)/)
// ...then show the storage prompt.
storagePrompt !== false && // ...and this user hasn't previously indicated a desire for storage
!document.cookie.match(/(?:^|;\s*)store=(?:prefsAndContent|prefsOnly)/) // ...then show the storage prompt.
)) {
options = [];
if (storage) {
options.unshift({ value: 'prefsAndContent', text: storagePrefsAndContent }, { value: 'prefsOnly', text: storagePrefsOnly }, { value: 'noPrefsOrContent', text: storageNoPrefsOrContent });
options.unshift({
value: 'prefsAndContent',
text: storagePrefsAndContent
}, {
value: 'prefsOnly',
text: storagePrefsOnly
}, {
value: 'noPrefsOrContent',
text: storageNoPrefsOrContent
});
} else {
options.unshift({ value: 'prefsOnly', text: storagePrefs }, { value: 'noPrefsOrContent', text: storageNoPrefs });
}
options.unshift({
value: 'prefsOnly',
text: storagePrefs
}, {
value: 'noPrefsOrContent',
text: storageNoPrefs
});
} // Hack to temporarily provide a wide and high enough dialog
// Hack to temporarily provide a wide and high enough dialog
oldContainerWidth = $('#dialog_container')[0].style.width, oldContainerMarginLeft = $('#dialog_container')[0].style.marginLeft, oldContentHeight = $('#dialog_content')[0].style.height, oldContainerHeight = $('#dialog_container')[0].style.height;
$('#dialog_content')[0].style.height = '120px';
$('#dialog_container')[0].style.height = '170px';
$('#dialog_container')[0].style.width = '800px';
$('#dialog_container')[0].style.marginLeft = '-400px';
// Open select-with-checkbox dialog
$('#dialog_container')[0].style.marginLeft = '-400px'; // Open select-with-checkbox dialog
// From svg-editor.js
$.select(message, options, function (pref, checked) {
if (pref && pref !== 'noPrefsOrContent') {
// Regardless of whether the user opted
@ -246,6 +269,7 @@ var svgEditorExtension_storage = (function () {
// the user does indicate a wish to store their info, we
// don't want ask them again upon page refresh so move
// them instead to a URL which does not always prompt
if (storagePrompt === true && checked) {
replaceStoragePrompt();
return;
@ -253,34 +277,33 @@ var svgEditorExtension_storage = (function () {
} else {
// The user does not wish storage (or cancelled, which we treat equivalently)
removeStoragePrefCookie();
if (pref && // If the user explicitly expresses wish for no storage
emptyStorageOnDecline) {
emptyStorage();
}
if (pref && checked) {
// Open a URL which won't set storage and won't prompt user about storage
replaceStoragePrompt('false');
return;
}
}
} // Reset width/height of dialog (e.g., for use by Export)
// Reset width/height of dialog (e.g., for use by Export)
$('#dialog_container')[0].style.width = oldContainerWidth;
$('#dialog_container')[0].style.marginLeft = oldContainerMarginLeft;
$('#dialog_content')[0].style.height = oldContentHeight;
$('#dialog_container')[0].style.height = oldContainerHeight;
// It should be enough to (conditionally) add to storage on
$('#dialog_container')[0].style.height = oldContainerHeight; // It should be enough to (conditionally) add to storage on
// beforeunload, but if we wished to update immediately,
// we might wish to try setting:
// svgEditor.setConfig({noStorageOnLoad: true});
// and then call:
// svgEditor.loadContentAndPrefs();
// We don't check for noStorageOnLoad here because
// the prompt gives the user the option to store data
setupBeforeUnloadListener();
setupBeforeUnloadListener();
svgEditor.storagePromptClosed = true;
}, null, null, {
label: rememberLabel,
@ -291,19 +314,17 @@ var svgEditorExtension_storage = (function () {
setupBeforeUnloadListener();
}
case 9:
case 'end':
case 10:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function langReady(_x) {
return _ref2.apply(this, arguments);
}
return langReady;
return function langReady(_x) {
return _langReady.apply(this, arguments);
};
}()
};
}

View File

@ -1,11 +1,7 @@
var svgEditorExtension_webappfind = (function () {
'use strict';
var asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
@ -17,18 +13,29 @@ var svgEditorExtension_webappfind = (function () {
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
Promise.resolve(value).then(_next, _throw);
}
}
return step("next");
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
};
}
/**
* Depends on Firefox add-on and executables from {@link https://github.com/brettz9/webappfind}
@ -36,26 +43,25 @@ var svgEditorExtension_webappfind = (function () {
* @license MIT
* @todo See WebAppFind Readme for SVG-related todos
*/
var extWebappfind = {
name: 'webappfind',
init: function () {
var _ref2 = asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref) {
var importLocale = _ref.importLocale;
var strings, svgEditor, saveMessage, readMessage, excludedMessages, pathID, buttons;
var _init = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(_ref) {
var importLocale, strings, svgEditor, saveMessage, readMessage, excludedMessages, pathID, buttons;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
importLocale = _ref.importLocale;
_context.next = 3;
return importLocale();
case 2:
case 3:
strings = _context.sent;
svgEditor = this;
saveMessage = 'save', readMessage = 'read', excludedMessages = [readMessage, saveMessage];
pathID = void 0;
this.canvas.bind('message',
/**
* @param {external:Window} win
@ -64,19 +70,19 @@ var svgEditorExtension_webappfind = (function () {
* @throws {Error} Unexpected event type
* @returns {undefined}
*/
function (win, _ref3) {
var data = _ref3.data,
origin = _ref3.origin;
function (win, _ref2) {
var data = _ref2.data,
origin = _ref2.origin;
// console.log('data, origin', data, origin);
var type = void 0,
content = void 0;
var type, content;
try {
// May throw if data is not an object
var _data$webappfind = data.webappfind;
type = _data$webappfind.type;
pathID = _data$webappfind.pathID;
content = _data$webappfind.content;
// May throw if data is not an object
if (origin !== location.origin || // We are only interested in a message sent as though within this URL by our browser add-on
excludedMessages.includes(type) // Avoid our post below (other messages might be possible in the future which may also need to be excluded if your subsequent code makes assumptions on the type of message this is)
) {
@ -90,19 +96,20 @@ var svgEditorExtension_webappfind = (function () {
case 'view':
// Populate the contents
svgEditor.loadFromString(content);
/* if ($('#tool_save_file')) {
$('#tool_save_file').disabled = false;
} */
break;
case 'save-end':
alert('save complete for pathID ' + pathID + '!');
alert("save complete for pathID ".concat(pathID, "!"));
break;
default:
throw new Error('Unexpected WebAppFind event type');
}
});
/*
window.postMessage({
webappfind: {
@ -115,31 +122,34 @@ var svgEditorExtension_webappfind = (function () {
: window.location.origin
);
*/
buttons = [{
id: 'webappfind_save', //
id: 'webappfind_save',
//
icon: svgEditor.curConfig.extIconsPath + 'webappfind.png',
type: 'app_menu',
position: 4, // Before 0-based index position 4 (after the regular "Save Image (S)")
position: 4,
// Before 0-based index position 4 (after the regular "Save Image (S)")
events: {
click: function click() {
if (!pathID) {
// Not ready yet as haven't received first payload
return;
}
window.postMessage({
webappfind: {
type: saveMessage,
pathID: pathID,
content: svgEditor.canvas.getSvgString()
}
}, window.location.origin === 'null'
// Avoid "null" string error for `file:` protocol (even
}, window.location.origin === 'null' // Avoid "null" string error for `file:` protocol (even
// though file protocol not currently supported by add-on)
? '*' : window.location.origin);
}
}
}];
return _context.abrupt('return', {
return _context.abrupt("return", {
name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'webappfind-icon.svg',
buttons: strings.buttons.map(function (button, i) {
@ -148,18 +158,16 @@ var svgEditorExtension_webappfind = (function () {
});
case 9:
case 'end':
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function init(_x) {
return _ref2.apply(this, arguments);
}
return init;
return function init(_x) {
return _init.apply(this, arguments);
};
}()
};

View File

@ -1,21 +1,39 @@
var svgEditorExtension_xdomain_messaging = (function () {
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
function _typeof(obj) {
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
} : function (obj) {
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
var toConsumableArray = function (arr) {
return _typeof(obj);
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
} else {
return Array.from(arr);
}
};
}
function _iterableToArray(iter) {
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
/**
* Should not be needed for same domain control (just call via child frame),
@ -27,40 +45,46 @@ var svgEditorExtension_xdomain_messaging = (function () {
init: function init() {
var svgEditor = this;
var svgCanvas = svgEditor.canvas;
try {
window.addEventListener('message', function (e) {
// We accept and post strings for the sake of IE9 support
if (!e.data || !['string', 'object'].includes(_typeof(e.data)) || e.data.charAt() === '|') {
return;
}
var data = _typeof(e.data) === 'object' ? e.data : JSON.parse(e.data);
if (!data || (typeof data === 'undefined' ? 'undefined' : _typeof(data)) !== 'object' || data.namespace !== 'svgCanvas') {
if (!data || _typeof(data) !== 'object' || data.namespace !== 'svgCanvas') {
return;
}
// The default is not to allow any origins, including even the same domain or
} // The default is not to allow any origins, including even the same domain or
// if run on a `file:///` URL. See `svgedit-config-es.js` for an example of how
// to configure
var allowedOrigins = svgEditor.curConfig.allowedOrigins;
if (!allowedOrigins.includes('*') && !allowedOrigins.includes(e.origin)) {
console.log('Origin ' + e.origin + ' not whitelisted for posting to ' + window.origin);
console.log("Origin ".concat(e.origin, " not whitelisted for posting to ").concat(window.origin));
return;
}
var cbid = data.id;
var name = data.name,
args = data.args;
var message = {
namespace: 'svg-edit',
id: cbid
};
try {
// Now that we know the origin is trusted, we perform otherwise
// unsafe arbitrary canvas method execution
message.result = svgCanvas[name].apply(svgCanvas, toConsumableArray(args)); // lgtm [js/remote-property-injection]
message.result = svgCanvas[name].apply(svgCanvas, _toConsumableArray(args)); // lgtm [js/remote-property-injection]
} catch (err) {
message.error = err.message;
}
e.source.postMessage(JSON.stringify(message), '*');
}, false);
} catch (err) {

View File

@ -1,7 +1,8 @@
(function () {
'use strict';
var _extends = Object.assign || function (target) {
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
@ -15,36 +16,43 @@
return target;
};
return _extends.apply(this, arguments);
}
/* globals jQuery */
var $ = jQuery;
$('a').click(function () {
var href = this.href;
var target = window.parent;
var post = function post(message) {
// Todo: Make origin customizable as set by opening window
// Todo: If dropping IE9, avoid stringifying
target.postMessage(JSON.stringify(_extends({
namespace: 'imagelib'
}, message)), '*');
};
// 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)
// Send metadata (also indicates file is about to be sent)
post({
name: $(this).text(),
id: href
});
if (!href.includes('.svg')) {
var img = new Image();
img.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = this.width;
canvas.height = this.height;
// load the raster image into the canvas
canvas.getContext('2d').drawImage(this, 0, 0);
// retrieve the data: URL
var data = void 0;
canvas.height = this.height; // load the raster image into the canvas
canvas.getContext('2d').drawImage(this, 0, 0); // retrieve the data: URL
var data;
try {
data = canvas.toDataURL();
} catch (err) {
@ -52,15 +60,24 @@
alert('Data URL conversion failed: ' + err);
data = '';
}
post({ href: href, data: data });
post({
href: href,
data: data
});
};
img.src = href;
} else {
// Do ajax request for image's href value
$.get(href, function (data) {
post({ href: href, data: data });
post({
href: href,
data: data
});
}, 'html'); // 'html' is necessary to keep returned data as a string
}
return false;
});

File diff suppressed because it is too large Load Diff

13159
dist/index-es.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

13145
dist/index-umd.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,14 +1,13 @@
(function () {
'use strict';
var classCallCheck = function (instance, Constructor) {
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
}
var createClass = function () {
function defineProperties(target, props) {
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
@ -18,15 +17,37 @@
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
};
}();
}
var slicedToArray = function () {
function sliceIterator(arr, i) {
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
}
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArray(iter) {
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
@ -43,7 +64,7 @@
_e = err;
} finally {
try {
if (!_n && _i["return"]) _i["return"]();
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
@ -52,26 +73,13 @@
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
var toConsumableArray = function (arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
} else {
return Array.from(arr);
}
};
/**
* For parsing color values
@ -224,9 +232,8 @@
whitesmoke: 'f5f5f5',
yellow: 'ffff00',
yellowgreen: '9acd32'
};
}; // array of color definition objects
// array of color definition objects
var colorDefs = [{
re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
@ -246,136 +253,141 @@
return [parseInt(bits[1] + bits[1], 16), parseInt(bits[2] + bits[2], 16), parseInt(bits[3] + bits[3], 16)];
}
}];
/**
* A class to parse color values
*/
var RGBColor = function () {
var RGBColor =
/*#__PURE__*/
function () {
/**
* @param {string} colorString
*/
function RGBColor(colorString) {
classCallCheck(this, RGBColor);
_classCallCheck(this, RGBColor);
this.ok = false;
this.ok = false; // strip any leading #
// strip any leading #
if (colorString.charAt(0) === '#') {
// remove # if any
colorString = colorString.substr(1, 6);
}
colorString = colorString.replace(/ /g, '');
colorString = colorString.toLowerCase();
// before getting into regexps, try simple matches
colorString = colorString.toLowerCase(); // before getting into regexps, try simple matches
// and overwrite the input
if (colorString in simpleColors) {
colorString = simpleColors[colorString];
}
// end of simple type-in colors
} // end of simple type-in colors
// search through the definitions to find a match
for (var i = 0; i < colorDefs.length; i++) {
var re = colorDefs[i].re;
var processor = colorDefs[i].process;
var bits = re.exec(colorString);
if (bits) {
var _processor = processor(bits),
_processor2 = slicedToArray(_processor, 3),
_processor2 = _slicedToArray(_processor, 3),
r = _processor2[0],
g = _processor2[1],
b = _processor2[2];
Object.assign(this, { r: r, g: g, b: b });
Object.assign(this, {
r: r,
g: g,
b: b
});
this.ok = true;
}
}
} // validate/cleanup values
// validate/cleanup values
this.r = this.r < 0 || isNaN(this.r) ? 0 : this.r > 255 ? 255 : this.r;
this.g = this.g < 0 || isNaN(this.g) ? 0 : this.g > 255 ? 255 : this.g;
this.b = this.b < 0 || isNaN(this.b) ? 0 : this.b > 255 ? 255 : this.b;
}
} // some getters
// some getters
/**
* @returns {string}
*/
createClass(RGBColor, [{
key: 'toRGB',
_createClass(RGBColor, [{
key: "toRGB",
value: function toRGB() {
return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
}
/**
* @returns {string}
*/
}, {
key: 'toHex',
key: "toHex",
value: function toHex() {
var r = this.r.toString(16);
var g = this.g.toString(16);
var b = this.b.toString(16);
if (r.length === 1) {
r = '0' + r;
}
if (g.length === 1) {
g = '0' + g;
}
if (b.length === 1) {
b = '0' + b;
}
return '#' + r + g + b;
}
/**
* help
* @returns {HTMLUListElement}
*/
}, {
key: 'getHelpXML',
key: "getHelpXML",
value: function getHelpXML() {
var examples = [];
// add regexps
var examples = []; // add regexps
for (var i = 0; i < colorDefs.length; i++) {
var example = colorDefs[i].example;
for (var j = 0; j < example.length; j++) {
examples[examples.length] = example[j];
}
}
// add type-in colors
examples.push.apply(examples, toConsumableArray(Object.keys(simpleColors)));
} // add type-in colors
examples.push.apply(examples, _toConsumableArray(Object.keys(simpleColors)));
var xml = document.createElement('ul');
xml.setAttribute('id', 'rgbcolor-examples');
for (var _i = 0; _i < examples.length; _i++) {
try {
var listItem = document.createElement('li');
var listColor = new RGBColor(examples[_i]);
var exampleDiv = document.createElement('div');
exampleDiv.style.cssText = 'margin: 3px;\nborder: 1px solid black;\nbackground: ' + listColor.toHex() + ';\ncolor: ' + listColor.toHex() + ';';
exampleDiv.style.cssText = "margin: 3px;\nborder: 1px solid black;\nbackground: ".concat(listColor.toHex(), ";\ncolor: ").concat(listColor.toHex(), ";");
exampleDiv.append('test');
var listItemValue = ' ' + examples[_i] + ' -> ' + listColor.toRGB() + ' -> ' + listColor.toHex();
var listItemValue = " ".concat(examples[_i], " -> ").concat(listColor.toRGB(), " -> ").concat(listColor.toHex());
listItem.append(exampleDiv, listItemValue);
xml.append(listItem);
} catch (e) {}
}
return xml;
}
}]);
return RGBColor;
}();
/* globals jsPDF */
var jsPDFAPI = jsPDF.API;
var pdfSvgAttr = {
// allowed attributes. all others are removed from the preview.
@ -405,29 +417,32 @@
toRemove.push(a.name);
}
});
toRemove.forEach(function (a) {
node.removeAttribute(a.name);
});
};
var numRgx = /[+-]?(?:\d+\.\d*|\d+|\.\d+)(?:[eE][+-]?\d+)?/g;
var getLinesOptionsOfPoly = function getLinesOptionsOfPoly(node) {
var nums = node.getAttribute('points');
nums = nums && nums.match(numRgx) || [];
if (nums && nums.length) {
nums = nums.map(Number);
if (nums.length % 2) {
nums.length--;
}
}
if (nums.length < 4) {
console.log('invalid points attribute:', node);
return;
}
var _nums = nums,
_nums2 = slicedToArray(_nums, 2),
_nums2 = _slicedToArray(_nums, 2),
x = _nums2[0],
y = _nums2[1],
lines = [];
@ -435,7 +450,12 @@
for (var i = 2; i < nums.length; i += 2) {
lines.push([nums[i] - nums[i - 2], nums[i + 1] - nums[i - 1]]);
}
return { x: x, y: y, lines: lines };
return {
x: x,
y: y,
lines: lines
};
};
var svgElementToPdf = function svgElementToPdf(element, pdf, options) {
@ -448,11 +468,14 @@
// console.log('passing: ', node);
// let hasStrokeColor = false;
var hasFillColor = false;
var fillRGB = void 0;
var fillRGB;
if (nodeIs(node, ['g', 'line', 'rect', 'ellipse', 'circle', 'polygon', 'polyline', 'text'])) {
var fillColor = node.getAttribute('fill');
if (attributeIsNotEmpty(fillColor)) {
fillRGB = new RGBColor(fillColor);
if (fillRGB.ok) {
hasFillColor = true;
colorMode = 'F';
@ -461,19 +484,25 @@
}
}
}
if (nodeIs(node, ['g', 'line', 'rect', 'ellipse', 'circle', 'polygon', 'polyline'])) {
if (hasFillColor) {
pdf.setFillColor(fillRGB.r, fillRGB.g, fillRGB.b);
}
if (attributeIsNotEmpty(node, 'stroke-width')) {
pdf.setLineWidth(k * parseInt(node.getAttribute('stroke-width'), 10));
}
var strokeColor = node.getAttribute('stroke');
if (attributeIsNotEmpty(strokeColor)) {
var strokeRGB = new RGBColor(strokeColor);
if (strokeRGB.ok) {
// hasStrokeColor = true;
pdf.setDrawColor(strokeRGB.r, strokeRGB.g, strokeRGB.b);
if (colorMode === 'F') {
colorMode = 'FD';
} else {
@ -484,7 +513,9 @@
}
}
}
var tag = node.tagName.toLowerCase();
switch (tag) {
case 'svg':
case 'a':
@ -492,48 +523,63 @@
svgElementToPdf(node, pdf, options);
removeAttributes(node, pdfSvgAttr.g);
break;
case 'line':
pdf.line(k * parseInt(node.getAttribute('x1'), 10), k * parseInt(node.getAttribute('y1'), 10), k * parseInt(node.getAttribute('x2'), 10), k * parseInt(node.getAttribute('y2'), 10));
removeAttributes(node, pdfSvgAttr.line);
break;
case 'rect':
pdf.rect(k * parseInt(node.getAttribute('x'), 10), k * parseInt(node.getAttribute('y'), 10), k * parseInt(node.getAttribute('width'), 10), k * parseInt(node.getAttribute('height'), 10), colorMode);
removeAttributes(node, pdfSvgAttr.rect);
break;
case 'ellipse':
pdf.ellipse(k * parseInt(node.getAttribute('cx'), 10), k * parseInt(node.getAttribute('cy'), 10), k * parseInt(node.getAttribute('rx'), 10), k * parseInt(node.getAttribute('ry'), 10), colorMode);
removeAttributes(node, pdfSvgAttr.ellipse);
break;
case 'circle':
pdf.circle(k * parseInt(node.getAttribute('cx'), 10), k * parseInt(node.getAttribute('cy'), 10), k * parseInt(node.getAttribute('r'), 10), colorMode);
removeAttributes(node, pdfSvgAttr.circle);
break;
case 'polygon':
case 'polyline':
var linesOptions = getLinesOptionsOfPoly(node);
if (linesOptions) {
pdf.lines(linesOptions.lines, k * linesOptions.x, k * linesOptions.y, [k, k], colorMode, tag === 'polygon' // polygon is closed, polyline is not closed
);
}
removeAttributes(node, pdfSvgAttr.polygon);
break;
// TODO: path
case 'text':
if (node.hasAttribute('font-family')) {
switch ((node.getAttribute('font-family') || '').toLowerCase()) {
case 'serif':
pdf.setFont('times');break;
pdf.setFont('times');
break;
case 'monospace':
pdf.setFont('courier');break;
pdf.setFont('courier');
break;
default:
node.setAttribute('font-family', 'sans-serif');
pdf.setFont('helvetica');
}
}
if (hasFillColor) {
pdf.setTextColor(fillRGB.r, fillRGB.g, fillRGB.b);
}
var fontType = '';
if (node.hasAttribute('font-weight')) {
if (node.getAttribute('font-weight') === 'bold') {
fontType = 'bold';
@ -541,6 +587,7 @@
node.removeAttribute('font-weight');
}
}
if (node.hasAttribute('font-style')) {
if (node.getAttribute('font-style') === 'italic') {
fontType += 'italic';
@ -548,11 +595,13 @@
node.removeAttribute('font-style');
}
}
pdf.setFontType(fontType);
var pdfFontSize = node.hasAttribute('font-size') ? parseInt(node.getAttribute('font-size'), 10) : 16;
var getWidth = function getWidth(node) {
var box = void 0;
var box;
try {
box = node.getBBox(); // Firefox on MacOS will raise error here
} catch (err) {
@ -561,43 +610,60 @@
var svg = node.ownerSVGElement.cloneNode(false);
svg.appendChild(nodeCopy);
document.body.appendChild(svg);
try {
box = nodeCopy.getBBox();
} catch (err) {
box = { width: 0 };
box = {
width: 0
};
}
document.body.removeChild(svg);
}
return box.width;
};
// FIXME: use more accurate positioning!!
var x = void 0,
y = void 0,
}; // FIXME: use more accurate positioning!!
var x,
y,
xOffset = 0;
if (node.hasAttribute('text-anchor')) {
switch (node.getAttribute('text-anchor')) {
case 'end':
xOffset = getWidth(node);break;
xOffset = getWidth(node);
break;
case 'middle':
xOffset = getWidth(node) / 2;break;
xOffset = getWidth(node) / 2;
break;
case 'start':
break;
case 'default':
node.setAttribute('text-anchor', 'start');break;
node.setAttribute('text-anchor', 'start');
break;
}
x = parseInt(node.getAttribute('x'), 10) - xOffset;
y = parseInt(node.getAttribute('y'), 10);
}
// console.log('fontSize:', pdfFontSize, 'text:', node.textContent);
} // console.log('fontSize:', pdfFontSize, 'text:', node.textContent);
pdf.setFontSize(pdfFontSize).text(k * x, k * y, node.textContent);
removeAttributes(node, pdfSvgAttr.text);
break;
// TODO: image
default:
if (remove) {
console.log("can't translate to pdf:", node);
node.remove();
}
}
});
return pdf;
@ -611,6 +677,7 @@
if (typeof element === 'string') {
element = new DOMParser().parseFromString(element, 'text/xml').documentElement;
}
svgElementToPdf(element, this, options);
return this;
};

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,7 @@
<title>-</title>
<link rel="icon" type="image/png" href="../../images/logo.png"/>
<script src="../../jquery.min.js"></script>
<script src="../../external/babel-polyfill/polyfill.min.js"></script>
<script src="../../external/@babel/polyfill/polyfill.min.js"></script>
<script type="module" src="index.js"></script>
</head>
<body>

View File

@ -6,7 +6,7 @@
<title>-</title>
<link rel="icon" type="image/png" href="../../images/logo.png"/>
<script src="../../jquery.min.js"></script>
<script src="../../external/babel-polyfill/polyfill.min.js"></script>
<script src="../../external/@babel/polyfill/polyfill.min.js"></script>
<script defer="defer" src="../../../dist/extensions/imagelib/index.js"></script>
</head>
<body>

View File

@ -5,7 +5,7 @@
<title>-</title>
<link rel="icon" type="image/png" href="../../images/logo.png"/>
<script src="../../external/dom-polyfill/dom-polyfill.js"></script>
<script src="../../external/babel-polyfill/polyfill.min.js"></script>
<script src="../../external/@babel/polyfill/polyfill.min.js"></script>
<script type="module" src="openclipart.js"></script>
</head>
<body>

View File

@ -6,7 +6,7 @@
<title>-</title>
<link rel="icon" type="image/png" href="../../images/logo.png"/>
<script src="../../../dist/dom-polyfill.js"></script>
<script src="../../external/babel-polyfill/polyfill.min.js"></script>
<script src="../../external/@babel/polyfill/polyfill.min.js"></script>
<script defer="defer" src="../../../dist/extensions/imagelib/openclipart.js"></script>
</head>
<body>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -25,7 +25,7 @@
<!-- The following could be removed for more modern browsers; currently
using for at least `String.prototype.includes`, `Array.prototype.includes`,
`String.prototype.startsWith` -->
<script src="external/babel-polyfill/polyfill.min.js"></script>
<script src="external/@babel/polyfill/polyfill.min.js"></script>
<!-- If you do not wish to add extensions by URL, you can load them
by creating the following file and adding by calls to svgEditor.setConfig -->
<script type="module" src="../svgedit-config-es.js"></script>

View File

@ -26,7 +26,7 @@
<!-- The following could be removed for more modern browsers; currently
using for at least `String.prototype.includes`, `Array.prototype.includes`,
`String.prototype.startsWith` -->
<script src="external/babel-polyfill/polyfill.min.js"></script>
<script src="external/@babel/polyfill/polyfill.min.js"></script>
<!-- If you do not wish to add extensions by URL, you can load them
by creating the following file and adding by calls to svgEditor.setConfig -->
<script defer="defer" src="../svgedit-config-iife.js"></script>

View File

@ -25,7 +25,7 @@
<!-- The following could be removed for more modern browsers; currently
using for at least `String.prototype.includes`, `Array.prototype.includes`,
`String.prototype.startsWith` -->
<script src="external/babel-polyfill/polyfill.min.js"></script>
<script src="external/@babel/polyfill/polyfill.min.js"></script>
<!-- If you do not wish to add extensions by URL, you can load them
by creating the following file and adding by calls to svgEditor.setConfig -->
<script type="module" src="xdomain-svgedit-config-es.js"></script>

View File

@ -26,7 +26,7 @@
<!-- The following could be removed for more modern browsers; currently
using for at least `String.prototype.includes`, `Array.prototype.includes`,
`String.prototype.startsWith` -->
<script src="external/babel-polyfill/polyfill.min.js"></script>
<script src="external/@babel/polyfill/polyfill.min.js"></script>
<!-- If you do not wish to add extensions by URL, you can load them
by creating the following file and adding by calls to svgEditor.setConfig -->
<script defer="defer" src="xdomain-svgedit-config-iife.js"></script>

File diff suppressed because one or more lines are too long

1718
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -18,7 +18,7 @@
"build-doc": "rm -rf docs/jsdoc/*;jsdoc --pedantic -c docs/jsdoc-config.json editor",
"build-html": "node build-html.js",
"compress-images": "imageoptim 'chrome-app/*.png' && imageoptim 'editor/extensions/*.png' && imageoptim 'editor/spinbtn/*.png' && imageoptim 'editor/jgraduate/images/*.{png,gif}' && imageoptim 'editor/images/*.png'",
"copy-deps": "cp node_modules/load-stylesheets/dist/index-es.js editor/external/load-stylesheets/index-es.js && cp node_modules/babel-polyfill/dist/polyfill.min.js editor/external/babel-polyfill/polyfill.min.js && cp node_modules/babel-polyfill/dist/polyfill.js editor/external/babel-polyfill/polyfill.js && cp node_modules/jamilih/dist/jml-es.js editor/external/jamilih/jml-es.js",
"copy-deps": "cp node_modules/load-stylesheets/dist/index-es.js editor/external/load-stylesheets/index-es.js && cp node_modules/@babel/polyfill/dist/polyfill.min.js editor/external/@babel/polyfill/polyfill.min.js && cp node_modules/@babel/polyfill/dist/polyfill.js editor/external/@babel/polyfill/polyfill.js && cp node_modules/jamilih/dist/jml-es.js editor/external/jamilih/jml-es.js",
"eslint": "eslint .",
"rollup": "rollup -c",
"start-embedded": "echo \"Open file to http://localhost:8000/editor/embedapi.html\" && static -p 8000 | static -p 8001 -H '{\"Access-Control-Allow-Origin\": \"*\"}'",
@ -53,12 +53,10 @@
"homepage": "https://github.com/SVG-Edit/svgedit#readme",
"dependencies": {},
"devDependencies": {
"babel-core": "6.26.3",
"babel-plugin-external-helpers": "^6.22.0",
"babel-plugin-transform-builtin-extend": "^1.1.2",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"@babel/core": "^7.1.0",
"@babel/polyfill": "^7.0.0",
"@babel/preset-env": "^7.1.0",
"babel-plugin-transform-object-rest-spread": "^7.0.0-beta.3",
"eslint": "5.6.0",
"eslint-config-standard": "12.0.0",
"eslint-plugin-import": "2.14.0",
@ -74,11 +72,11 @@
"node-static": "^0.7.11",
"opn-cli": "^3.1.0",
"promise-fs": "^1.3.0",
"qr-manipulation": "^0.7.0",
"qr-manipulation": "https://github.com/brettz9/qr-manipulation",
"query-result": "https://github.com/WebReflection/query-result",
"qunit": "^2.6.2",
"rollup": "0.66.2",
"rollup-plugin-babel": "^3.0.7",
"rollup-plugin-babel": "^4.0.3",
"rollup-plugin-commonjs": "^9.1.8",
"rollup-plugin-json": "^3.1.0",
"rollup-plugin-node-builtins": "^2.1.2",

View File

@ -114,9 +114,7 @@ export default [
},
plugins: [
babel({
plugins: ['transform-object-rest-spread', ['babel-plugin-transform-builtin-extend', {
globals: ['Array']
}]]
plugins: ['transform-object-rest-spread']
})
]
},

File diff suppressed because one or more lines are too long