- Linting: Add `ignore` folder to ignore file; ensure license versions are valid semver

- npm: Update devDeps
master
Brett Zamir 2019-11-13 14:16:06 +08:00
parent d808cc22de
commit a09c47283e
37 changed files with 12859 additions and 15105 deletions

View File

@ -1,4 +1,5 @@
node_modules node_modules
ignore
dist dist
docs/jsdoc docs/jsdoc

92
dist/canvg.js vendored
View File

@ -15,42 +15,6 @@ var canvg = (function (exports) {
return _typeof(obj); return _typeof(obj);
} }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
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);
});
};
}
function _classCallCheck(instance, Constructor) { function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) { if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function"); throw new TypeError("Cannot call a class as a function");
@ -4684,36 +4648,26 @@ var canvg = (function (exports) {
}; // load from url }; // load from url
svg.load = svg.load = function _callee(ctx, url) {
/*#__PURE__*/ var dom;
function () { return regeneratorRuntime.async(function _callee$(_context) {
var _ref12 = _asyncToGenerator( while (1) {
/*#__PURE__*/ switch (_context.prev = _context.next) {
regeneratorRuntime.mark(function _callee(ctx, url) { case 0:
var dom; _context.next = 2;
return regeneratorRuntime.wrap(function _callee$(_context) { return regeneratorRuntime.awrap(svg.ajax(url, true));
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return svg.ajax(url, true);
case 2: case 2:
dom = _context.sent; dom = _context.sent;
return _context.abrupt("return", svg.loadXml(ctx, dom)); return _context.abrupt("return", svg.loadXml(ctx, dom));
case 4: case 4:
case "end": case "end":
return _context.stop(); return _context.stop();
}
} }
}, _callee); }
})); });
}; // load from xml
return function (_x2, _x3) {
return _ref12.apply(this, arguments);
};
}(); // load from xml
svg.loadXml = function (ctx, xml) { svg.loadXml = function (ctx, xml) {
@ -4934,9 +4888,9 @@ var canvg = (function (exports) {
checkPath: function checkPath(element, ctx) { checkPath: function checkPath(element, ctx) {
var _this26 = this; var _this26 = this;
this.events.forEach(function (_ref13, i) { this.events.forEach(function (_ref12, i) {
var x = _ref13.x, var x = _ref12.x,
y = _ref13.y; y = _ref12.y;
if (ctx.isPointInPath && ctx.isPointInPath(x, y)) { if (ctx.isPointInPath && ctx.isPointInPath(x, y)) {
_this26.eventElements[i] = element; _this26.eventElements[i] = element;
@ -4946,9 +4900,9 @@ var canvg = (function (exports) {
checkBoundingBox: function checkBoundingBox(element, bb) { checkBoundingBox: function checkBoundingBox(element, bb) {
var _this27 = this; var _this27 = this;
this.events.forEach(function (_ref14, i) { this.events.forEach(function (_ref13, i) {
var x = _ref14.x, var x = _ref13.x,
y = _ref14.y; y = _ref13.y;
if (bb.isPointInBox(x, y)) { if (bb.isPointInBox(x, y)) {
_this27.eventElements[i] = element; _this27.eventElements[i] = element;

View File

@ -1,42 +1,6 @@
var svgEditorExtension_arrows = (function () { var svgEditorExtension_arrows = (function () {
'use strict'; 'use strict';
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
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);
});
};
}
function _inherits(subClass, superClass) { function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) { if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function"); throw new TypeError("Super expression must either be null or a function");
@ -211,366 +175,346 @@ var svgEditorExtension_arrows = (function () {
*/ */
var extArrows = { var extArrows = {
name: 'arrows', name: 'arrows',
init: function () { init: function init(S) {
var _init = _asyncToGenerator( var strings, svgEditor, svgCanvas, addElem, nonce, $, prefix, selElems, arrowprefix, randomizeIds, setArrowNonce, unsetArrowNonce, pathdata, getLinked, showPanel, resetMarker, addMarker, setArrow, colorChanged, contextTools;
/*#__PURE__*/ return regeneratorRuntime.async(function init$(_context2) {
regeneratorRuntime.mark(function _callee2(S) { while (1) {
var strings, svgEditor, svgCanvas, addElem, nonce, $, prefix, selElems, arrowprefix, randomizeIds, setArrowNonce, unsetArrowNonce, pathdata, getLinked, showPanel, resetMarker, addMarker, setArrow, colorChanged, contextTools; switch (_context2.prev = _context2.next) {
return regeneratorRuntime.wrap(function _callee2$(_context2) { case 0:
while (1) { colorChanged = function _ref10(elem) {
switch (_context2.prev = _context2.next) { var color = elem.getAttribute('stroke');
case 0: var mtypes = ['start', 'mid', 'end'];
colorChanged = function _ref10(elem) { var defs = svgCanvas.findDefs();
var color = elem.getAttribute('stroke'); $.each(mtypes, function (i, type) {
var mtypes = ['start', 'mid', 'end']; var marker = getLinked(elem, 'marker-' + type);
var defs = svgCanvas.findDefs();
$.each(mtypes, function (i, type) {
var marker = getLinked(elem, 'marker-' + type);
if (!marker) { if (!marker) {
return; 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
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; // eslint-disable-line consistent-this
} }
});
var curColor = $(marker).children().attr('fill'); if (!newMarker) {
var curD = $(marker).children().attr('d'); // 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);
}
if (curColor === color) { $(elem).attr('marker-' + type, 'url(#' + newMarker.id + ')'); // Check if last marker can be removed
return;
}
var allMarkers = $(defs).find('marker'); var remove = true;
var newMarker = null; // Different color, check if already made $(S.svgcontent).find('line, polyline, path, polygon').each(function () {
var element = this; // eslint-disable-line consistent-this
allMarkers.each(function () { $.each(mtypes, function (j, mtype) {
var attrs = $(this).children().attr(['fill', 'd']); if ($(element).attr('marker-' + mtype) === 'url(#' + marker.id + ')') {
remove = false;
if (attrs.fill === color && attrs.d === curD) { return remove;
// Found another marker with this color and this path
newMarker = this; // eslint-disable-line consistent-this
}
});
if (!newMarker) {
// 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 + ')'); // Check if last marker can be removed
var remove = true;
$(S.svgcontent).find('line, polyline, path, polygon').each(function () {
var element = this; // eslint-disable-line consistent-this
$.each(mtypes, function (j, mtype) {
if ($(element).attr('marker-' + mtype) === 'url(#' + marker.id + ')') {
remove = false;
return remove;
}
return undefined;
});
if (!remove) {
return false;
} }
return undefined; return undefined;
}); // Not found, so can safely remove
if (remove) {
$(marker).remove();
}
});
};
setArrow = function _ref9() {
resetMarker();
var type = this.value;
if (type === 'none') {
return;
} // Set marker on element
var dir = 'fw';
if (type === 'mid_bk') {
type = 'mid';
dir = 'bk';
} else if (type === 'both') {
addMarker('bk', type);
svgCanvas.changeSelectedAttribute('marker-start', 'url(#' + pathdata.bk.id + ')');
type = 'end';
dir = 'fw';
} else if (type === 'start') {
dir = 'bk';
}
addMarker(dir, type);
svgCanvas.changeSelectedAttribute('marker-' + type, 'url(#' + pathdata[dir].id + ')');
svgCanvas.call('changed', selElems);
};
addMarker = function _ref8(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') {
data.refx = 5;
}
var marker = svgCanvas.getElem(id);
if (!marker) {
marker = addElem({
element: 'marker',
attr: {
viewBox: '0 0 10 10',
id: id,
refY: 5,
markerUnits: 'strokeWidth',
markerWidth: 5,
markerHeight: 5,
orient: 'auto',
style: 'pointer-events:none' // Currently needed for Opera
}
}); });
var arrow = addElem({
element: 'path',
attr: {
d: data.d,
fill: '#000000'
}
});
marker.append(arrow);
svgCanvas.findDefs().append(marker);
}
marker.setAttribute('refX', data.refx); if (!remove) {
return marker; return false;
};
resetMarker = function _ref7() {
var el = selElems[0];
el.removeAttribute('marker-start');
el.removeAttribute('marker-mid');
el.removeAttribute('marker-end');
};
showPanel = function _ref6(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;
if (end && start) {
val = 'both';
} else if (end) {
val = 'end';
} else if (start) {
val = 'start';
} else if (mid) {
val = 'mid';
if (mid.includes('bk')) {
val = 'mid_bk';
}
} }
if (!start && !mid && !end) { return undefined;
val = 'none'; }); // Not found, so can safely remove
}
$('#arrow_list').val(val); if (remove) {
$(marker).remove();
} }
}; });
};
getLinked = function _ref5(elem, attr) { setArrow = function _ref9() {
var str = elem.getAttribute(attr); resetMarker();
var type = this.value;
if (!str) { if (type === 'none') {
return null; return;
} } // Set marker on element
var m = str.match(_wrapRegExp(/\(#(.+)\)/, {
id: 1
}));
if (!m || !m.groups.id) { var dir = 'fw';
return null;
}
return svgCanvas.getElem(m.groups.id); if (type === 'mid_bk') {
}; type = 'mid';
dir = 'bk';
unsetArrowNonce = function _ref4(win) { } else if (type === 'both') {
randomizeIds = false; addMarker('bk', type);
arrowprefix = prefix; svgCanvas.changeSelectedAttribute('marker-start', 'url(#' + pathdata.bk.id + ')');
pathdata.fw.id = arrowprefix + 'fw'; type = 'end';
pathdata.bk.id = arrowprefix + 'bk'; dir = 'fw';
}; } else if (type === 'start') {
dir = 'bk';
setArrowNonce = function _ref3(win, n) {
randomizeIds = true;
arrowprefix = prefix + n + '_';
pathdata.fw.id = arrowprefix + 'fw';
pathdata.bk.id = arrowprefix + 'bk';
};
_context2.next = 10;
return S.importLocale();
case 10:
strings = _context2.sent;
svgEditor = this;
svgCanvas = svgEditor.canvas;
// {svgcontent} = S,
addElem = svgCanvas.addSVGElementFromJson, nonce = S.nonce, $ = S.$, prefix = 'se_arrow_';
randomizeIds = S.randomize_ids;
/**
* @param {Window} win
* @param {!(string|Integer)} n
* @returns {void}
*/
svgCanvas.bind('setnonce', setArrowNonce);
svgCanvas.bind('unsetnonce', unsetArrowNonce);
if (randomizeIds) {
arrowprefix = prefix + nonce + '_';
} else {
arrowprefix = prefix;
} }
pathdata = { addMarker(dir, type);
fw: { svgCanvas.changeSelectedAttribute('marker-' + type, 'url(#' + pathdata[dir].id + ')');
d: 'm0,0l10,5l-10,5l5,-5l-5,-5z', svgCanvas.call('changed', selElems);
refx: 8, };
id: arrowprefix + 'fw'
},
bk: {
d: 'm10,0l-10,5l10,5l-5,-5l5,-5z',
refx: 2,
id: arrowprefix + 'bk'
}
};
/**
* Gets linked element.
* @param {Element} elem
* @param {string} attr
* @returns {Element}
*/
contextTools = [{ addMarker = function _ref8(dir, type, id) {
type: 'select', // TODO: Make marker (or use?) per arrow type, since refX can be different
panel: 'arrow_panel', id = id || arrowprefix + dir;
id: 'arrow_list', var data = pathdata[dir];
defval: 'none',
events: {
change: setArrow
}
}];
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_list option')[0].id = 'connector_no_arrow'; if (type === 'mid') {
}, data.refx = 5;
addLangData: function () { }
var _addLangData = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(_ref) {
var lang, importLocale, _ref2, langList;
return regeneratorRuntime.wrap(function _callee$(_context) { var marker = svgCanvas.getElem(id);
while (1) {
switch (_context.prev = _context.next) {
case 0:
lang = _ref.lang, importLocale = _ref.importLocale;
_context.next = 3;
return importLocale();
case 3: if (!marker) {
_ref2 = _context.sent; marker = addElem({
langList = _ref2.langList; element: 'marker',
return _context.abrupt("return", { attr: {
data: langList viewBox: '0 0 10 10',
}); id: id,
refY: 5,
markerUnits: 'strokeWidth',
markerWidth: 5,
markerHeight: 5,
orient: 'auto',
style: 'pointer-events:none' // Currently needed for Opera
case 6:
case "end":
return _context.stop();
}
}
}, _callee);
}));
function addLangData(_x2) {
return _addLangData.apply(this, arguments);
} }
});
var arrow = addElem({
element: 'path',
attr: {
d: data.d,
fill: '#000000'
}
});
marker.append(arrow);
svgCanvas.findDefs().append(marker);
}
return addLangData; marker.setAttribute('refX', data.refx);
}(), return marker;
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--) { resetMarker = function _ref7() {
var elem = selElems[i]; var el = selElems[0];
el.removeAttribute('marker-start');
el.removeAttribute('marker-mid');
el.removeAttribute('marker-end');
};
if (elem && markerElems.includes(elem.tagName)) { showPanel = function _ref6(on) {
if (opts.selectedElement && !opts.multiselected) { $('#arrow_panel').toggle(on);
showPanel(true);
} else { if (on) {
showPanel(false); var el = selElems[0];
} var end = el.getAttribute('marker-end');
var start = el.getAttribute('marker-start');
var mid = el.getAttribute('marker-mid');
var val;
if (end && start) {
val = 'both';
} else if (end) {
val = 'end';
} else if (start) {
val = 'start';
} else if (mid) {
val = 'mid';
if (mid.includes('bk')) {
val = 'mid_bk';
}
}
if (!start && !mid && !end) {
val = 'none';
}
$('#arrow_list').val(val);
}
};
getLinked = function _ref5(elem, attr) {
var str = elem.getAttribute(attr);
if (!str) {
return null;
}
var m = str.match(_wrapRegExp(/\(#(.+)\)/, {
id: 1
}));
if (!m || !m.groups.id) {
return null;
}
return svgCanvas.getElem(m.groups.id);
};
unsetArrowNonce = function _ref4(win) {
randomizeIds = false;
arrowprefix = prefix;
pathdata.fw.id = arrowprefix + 'fw';
pathdata.bk.id = arrowprefix + 'bk';
};
setArrowNonce = function _ref3(win, n) {
randomizeIds = true;
arrowprefix = prefix + n + '_';
pathdata.fw.id = arrowprefix + 'fw';
pathdata.bk.id = arrowprefix + 'bk';
};
_context2.next = 10;
return regeneratorRuntime.awrap(S.importLocale());
case 10:
strings = _context2.sent;
svgEditor = this;
svgCanvas = svgEditor.canvas;
// {svgcontent} = S,
addElem = svgCanvas.addSVGElementFromJson, nonce = S.nonce, $ = S.$, prefix = 'se_arrow_';
randomizeIds = S.randomize_ids;
/**
* @param {Window} win
* @param {!(string|Integer)} n
* @returns {void}
*/
svgCanvas.bind('setnonce', setArrowNonce);
svgCanvas.bind('unsetnonce', unsetArrowNonce);
if (randomizeIds) {
arrowprefix = prefix + nonce + '_';
} else {
arrowprefix = prefix;
}
pathdata = {
fw: {
d: 'm0,0l10,5l-10,5l5,-5l-5,-5z',
refx: 8,
id: arrowprefix + 'fw'
},
bk: {
d: 'm10,0l-10,5l10,5l-5,-5l5,-5z',
refx: 2,
id: arrowprefix + 'bk'
}
};
/**
* Gets linked element.
* @param {Element} elem
* @param {string} attr
* @returns {Element}
*/
contextTools = [{
type: 'select',
panel: 'arrow_panel',
id: 'arrow_list',
defval: 'none',
events: {
change: setArrow
}
}];
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_list option')[0].id = 'connector_no_arrow';
},
addLangData: function addLangData(_ref) {
var lang, importLocale, _ref2, langList;
return regeneratorRuntime.async(function addLangData$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
lang = _ref.lang, importLocale = _ref.importLocale;
_context.next = 3;
return regeneratorRuntime.awrap(importLocale());
case 3:
_ref2 = _context.sent;
langList = _ref2.langList;
return _context.abrupt("return", {
data: langList
});
case 6:
case "end":
return _context.stop();
}
}
});
},
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);
} else { } else {
showPanel(false); showPanel(false);
} }
} } else {
}, showPanel(false);
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');
// const end = elem.getAttribute('marker-end');
// Has marker, so see if it should match color
colorChanged(elem);
} }
} }
}); },
elementChanged: function elementChanged(opts) {
var elem = opts.elems[0];
case 21: if (elem && (elem.getAttribute('marker-start') || elem.getAttribute('marker-mid') || elem.getAttribute('marker-end'))) {
case "end": // const start = elem.getAttribute('marker-start');
return _context2.stop(); // const mid = elem.getAttribute('marker-mid');
} // const end = elem.getAttribute('marker-end');
// Has marker, so see if it should match color
colorChanged(elem);
}
}
});
case 21:
case "end":
return _context2.stop();
} }
}, _callee2, this); }
})); }, null, this);
}
function init(_x) {
return _init.apply(this, arguments);
}
return init;
}()
}; };
return extArrows; return extArrows;

View File

@ -1,42 +1,6 @@
var svgEditorExtension_closepath = (function () { var svgEditorExtension_closepath = (function () {
'use strict'; 'use strict';
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
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-closepath.js * ext-closepath.js
* *
@ -49,125 +13,115 @@ var svgEditorExtension_closepath = (function () {
// The button toggles whether the path is open or closed // The button toggles whether the path is open or closed
var extClosepath = { var extClosepath = {
name: 'closepath', name: 'closepath',
init: function () { init: function init(_ref) {
var _init = _asyncToGenerator( var importLocale, $, strings, svgEditor, selElems, updateButton, showPanel, toggleClosed, buttons;
/*#__PURE__*/ return regeneratorRuntime.async(function init$(_context) {
regeneratorRuntime.mark(function _callee(_ref) { while (1) {
var importLocale, $, strings, svgEditor, selElems, updateButton, showPanel, toggleClosed, buttons; switch (_context.prev = _context.next) {
return regeneratorRuntime.wrap(function _callee$(_context) { case 0:
while (1) { importLocale = _ref.importLocale, $ = _ref.$;
switch (_context.prev = _context.next) { _context.next = 3;
case 0: return regeneratorRuntime.awrap(importLocale());
importLocale = _ref.importLocale, $ = _ref.$;
_context.next = 3;
return importLocale();
case 3: case 3:
strings = _context.sent; strings = _context.sent;
svgEditor = this; svgEditor = this;
updateButton = function updateButton(path) { updateButton = function updateButton(path) {
var seglist = path.pathSegList, var seglist = path.pathSegList,
closed = seglist.getItem(seglist.numberOfItems - 1).pathSegType === 1, closed = seglist.getItem(seglist.numberOfItems - 1).pathSegType === 1,
showbutton = closed ? '#tool_openpath' : '#tool_closepath', showbutton = closed ? '#tool_openpath' : '#tool_closepath',
hidebutton = closed ? '#tool_closepath' : '#tool_openpath'; hidebutton = closed ? '#tool_closepath' : '#tool_openpath';
$(hidebutton).hide(); $(hidebutton).hide();
$(showbutton).show(); $(showbutton).show();
}; };
showPanel = function showPanel(on) { showPanel = function showPanel(on) {
$('#closepath_panel').toggle(on); $('#closepath_panel').toggle(on);
if (on) { if (on) {
var path = selElems[0];
if (path) {
updateButton(path);
}
}
};
toggleClosed = function toggleClosed() {
var path = selElems[0]; var path = selElems[0];
if (path) { if (path) {
var seglist = path.pathSegList,
last = seglist.numberOfItems - 1; // is closed
if (seglist.getItem(last).pathSegType === 1) {
seglist.removeItem(last);
} else {
seglist.appendItem(path.createSVGPathSegClosePath());
}
updateButton(path); updateButton(path);
} }
}; }
};
buttons = [{ toggleClosed = function toggleClosed() {
id: 'tool_openpath', var path = selElems[0];
icon: svgEditor.curConfig.extIconsPath + 'openpath.png',
type: 'context', if (path) {
panel: 'closepath_panel', var seglist = path.pathSegList,
events: { last = seglist.numberOfItems - 1; // is closed
click: function click() {
toggleClosed(); if (seglist.getItem(last).pathSegType === 1) {
} seglist.removeItem(last);
} else {
seglist.appendItem(path.createSVGPathSegClosePath());
} }
}, {
id: 'tool_closepath', updateButton(path);
icon: svgEditor.curConfig.extIconsPath + 'closepath.png', }
type: 'context', };
panel: 'closepath_panel',
events: { buttons = [{
click: function click() { id: 'tool_openpath',
toggleClosed(); icon: svgEditor.curConfig.extIconsPath + 'openpath.png',
} type: 'context',
panel: 'closepath_panel',
events: {
click: function click() {
toggleClosed();
} }
}]; }
return _context.abrupt("return", { }, {
name: strings.name, id: 'tool_closepath',
svgicons: svgEditor.curConfig.extIconsPath + 'closepath_icons.svg', icon: svgEditor.curConfig.extIconsPath + 'closepath.png',
buttons: strings.buttons.map(function (button, i) { type: 'context',
return Object.assign(buttons[i], button); panel: 'closepath_panel',
}), events: {
callback: function callback() { click: function click() {
$('#closepath_panel').hide(); toggleClosed();
}, }
selectedChanged: function selectedChanged(opts) { }
selElems = opts.elems; }];
var i = selElems.length; return _context.abrupt("return", {
name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'closepath_icons.svg',
buttons: strings.buttons.map(function (button, i) {
return Object.assign(buttons[i], button);
}),
callback: function callback() {
$('#closepath_panel').hide();
},
selectedChanged: function selectedChanged(opts) {
selElems = opts.elems;
var i = selElems.length;
while (i--) { while (i--) {
var elem = selElems[i]; var elem = selElems[i];
if (elem && elem.tagName === 'path') { if (elem && elem.tagName === 'path') {
if (opts.selectedElement && !opts.multiselected) { if (opts.selectedElement && !opts.multiselected) {
showPanel(true); showPanel(true);
} else {
showPanel(false);
}
} else { } else {
showPanel(false); showPanel(false);
} }
} else {
showPanel(false);
} }
} }
}); }
});
case 10: case 10:
case "end": case "end":
return _context.stop(); return _context.stop();
}
} }
}, _callee, this); }
})); }, null, this);
}
function init(_x) {
return _init.apply(this, arguments);
}
return init;
}()
}; };
return extClosepath; return extClosepath;

File diff suppressed because it is too large Load Diff

View File

@ -1,42 +1,6 @@
var svgEditorExtension_eyedropper = (function () { var svgEditorExtension_eyedropper = (function () {
'use strict'; 'use strict';
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
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-eyedropper.js * ext-eyedropper.js
* *
@ -47,160 +11,150 @@ var svgEditorExtension_eyedropper = (function () {
*/ */
var extEyedropper = { var extEyedropper = {
name: 'eyedropper', name: 'eyedropper',
init: function () { init: function init(S) {
var _init = _asyncToGenerator( var strings, svgEditor, $, ChangeElementCommand, svgCanvas, addToHistory, currentStyle, getStyle, buttons;
/*#__PURE__*/ return regeneratorRuntime.async(function init$(_context) {
regeneratorRuntime.mark(function _callee(S) { while (1) {
var strings, svgEditor, $, ChangeElementCommand, svgCanvas, addToHistory, currentStyle, getStyle, buttons; switch (_context.prev = _context.next) {
return regeneratorRuntime.wrap(function _callee$(_context) { case 0:
while (1) { getStyle = function _ref(opts) {
switch (_context.prev = _context.next) { // if we are in eyedropper mode, we don't want to disable the eye-dropper tool
case 0: var mode = svgCanvas.getMode();
getStyle = function _ref(opts) {
// if we are in eyedropper mode, we don't want to disable the eye-dropper tool if (mode === 'eyedropper') {
return;
}
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
currentStyle.fillPaint = elem.getAttribute('fill') || 'black';
currentStyle.fillOpacity = elem.getAttribute('fill-opacity') || 1.0;
currentStyle.strokePaint = elem.getAttribute('stroke');
currentStyle.strokeOpacity = elem.getAttribute('stroke-opacity') || 1.0;
currentStyle.strokeWidth = elem.getAttribute('stroke-width');
currentStyle.strokeDashArray = elem.getAttribute('stroke-dasharray');
currentStyle.strokeLinecap = elem.getAttribute('stroke-linecap');
currentStyle.strokeLinejoin = elem.getAttribute('stroke-linejoin');
currentStyle.opacity = elem.getAttribute('opacity') || 1.0; // disable eye-dropper tool
} else {
tool.addClass('disabled');
}
};
_context.next = 3;
return regeneratorRuntime.awrap(S.importLocale());
case 3:
strings = _context.sent;
svgEditor = this;
$ = S.$, 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,
opacity: 1.0,
strokeLinecap: 'butt',
strokeLinejoin: 'miter'
};
/**
*
* @param {module:svgcanvas.SvgCanvas#event:ext_selectedChanged|module:svgcanvas.SvgCanvas#event:ext_elementChanged} opts
* @returns {void}
*/
buttons = [{
id: 'tool_eyedropper',
icon: svgEditor.curConfig.extIconsPath + 'eyedropper.png',
type: 'mode',
events: {
click: function click() {
svgCanvas.setMode('eyedropper');
}
}
}];
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(); var mode = svgCanvas.getMode();
if (mode === 'eyedropper') { if (mode === 'eyedropper') {
return; var e = opts.event;
} var target = e.target;
var tool = $('#tool_eyedropper'); // enable-eye-dropper if one element is selected if (!['svg', 'g', 'use'].includes(target.nodeName)) {
var changes = {};
var elem = null; var change = function change(elem, attrname, newvalue) {
changes[attrname] = elem.getAttribute(attrname);
elem.setAttribute(attrname, newvalue);
};
if (!opts.multiselected && opts.elems[0] && !['svg', 'g', 'use'].includes(opts.elems[0].nodeName)) { if (currentStyle.fillPaint) {
elem = opts.elems[0]; change(target, 'fill', currentStyle.fillPaint);
tool.removeClass('disabled'); // grab the current style
currentStyle.fillPaint = elem.getAttribute('fill') || 'black';
currentStyle.fillOpacity = elem.getAttribute('fill-opacity') || 1.0;
currentStyle.strokePaint = elem.getAttribute('stroke');
currentStyle.strokeOpacity = elem.getAttribute('stroke-opacity') || 1.0;
currentStyle.strokeWidth = elem.getAttribute('stroke-width');
currentStyle.strokeDashArray = elem.getAttribute('stroke-dasharray');
currentStyle.strokeLinecap = elem.getAttribute('stroke-linecap');
currentStyle.strokeLinejoin = elem.getAttribute('stroke-linejoin');
currentStyle.opacity = elem.getAttribute('opacity') || 1.0; // disable eye-dropper tool
} else {
tool.addClass('disabled');
}
};
_context.next = 3;
return S.importLocale();
case 3:
strings = _context.sent;
svgEditor = this;
$ = S.$, 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,
opacity: 1.0,
strokeLinecap: 'butt',
strokeLinejoin: 'miter'
};
/**
*
* @param {module:svgcanvas.SvgCanvas#event:ext_selectedChanged|module:svgcanvas.SvgCanvas#event:ext_elementChanged} opts
* @returns {void}
*/
buttons = [{
id: 'tool_eyedropper',
icon: svgEditor.curConfig.extIconsPath + 'eyedropper.png',
type: 'mode',
events: {
click: function click() {
svgCanvas.setMode('eyedropper');
}
}
}];
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;
if (!['svg', 'g', 'use'].includes(target.nodeName)) {
var changes = {};
var change = function change(elem, attrname, newvalue) {
changes[attrname] = elem.getAttribute(attrname);
elem.setAttribute(attrname, newvalue);
};
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);
}
addToHistory(new ChangeElementCommand(target, changes));
} }
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);
}
addToHistory(new ChangeElementCommand(target, changes));
} }
} }
}); }
});
case 8: case 8:
case "end": case "end":
return _context.stop(); return _context.stop();
}
} }
}, _callee, this); }
})); }, null, this);
}
function init(_x) {
return _init.apply(this, arguments);
}
return init;
}()
}; };
return extEyedropper; return extEyedropper;

View File

@ -1,42 +1,6 @@
var svgEditorExtension_foreignobject = (function () { var svgEditorExtension_foreignobject = (function () {
'use strict'; 'use strict';
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
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-foreignobject.js * ext-foreignobject.js
* *
@ -47,325 +11,311 @@ var svgEditorExtension_foreignobject = (function () {
*/ */
var extForeignobject = { var extForeignobject = {
name: 'foreignobject', name: 'foreignobject',
init: function () { init: function init(S) {
var _init = _asyncToGenerator( var svgEditor, $, text2xml, NS, importLocale, svgCanvas, svgdoc, strings, properlySourceSizeTextArea, showPanel, toggleSourceButtons, selElems, started, newFO, editingforeign, setForeignString, showForeignEditor, setAttr, buttons, contextTools;
/*#__PURE__*/ return regeneratorRuntime.async(function init$(_context2) {
regeneratorRuntime.mark(function _callee2(S) { while (1) {
var svgEditor, $, text2xml, NS, importLocale, svgCanvas, svgdoc, strings, properlySourceSizeTextArea, showPanel, toggleSourceButtons, selElems, started, newFO, editingforeign, setForeignString, showForeignEditor, setAttr, buttons, contextTools; switch (_context2.prev = _context2.next) {
return regeneratorRuntime.wrap(function _callee2$(_context2) { case 0:
while (1) { setAttr = function _ref5(attr, val) {
switch (_context2.prev = _context2.next) { svgCanvas.changeSelectedAttribute(attr, val);
case 0: svgCanvas.call('changed', selElems);
setAttr = function _ref6(attr, val) { };
svgCanvas.changeSelectedAttribute(attr, val);
svgCanvas.call('changed', selElems);
};
showForeignEditor = function _ref5() { showForeignEditor = function _ref4() {
var elt = selElems[0]; var elt = selElems[0];
if (!elt || editingforeign) { if (!elt || editingforeign) {
return; return;
}
editingforeign = true;
toggleSourceButtons(true);
elt.removeAttribute('fill');
var str = svgCanvas.svgToString(elt, 0);
$('#svg_source_textarea').val(str);
$('#svg_source_editor').fadeIn();
properlySourceSizeTextArea();
$('#svg_source_textarea').focus();
};
setForeignString = function _ref3(xmlString) {
var elt = selElems[0]; // The parent `Element` to append to
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
svgCanvas.sanitizeSvg(newDoc.documentElement);
elt.replaceWith(svgdoc.importNode(newDoc.documentElement.firstChild, true));
svgCanvas.call('changed', [elt]);
svgCanvas.clearSelection();
} catch (e) {
// Todo: Surface error to user
console.log(e); // eslint-disable-line no-console
return false;
}
return true;
};
toggleSourceButtons = function _ref2(on) {
$('#tool_source_save, #tool_source_cancel').toggle(!on);
$('#foreign_save, #foreign_cancel').toggle(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);
};
svgEditor = this;
$ = S.$, text2xml = S.text2xml, NS = S.NS, importLocale = S.importLocale;
svgCanvas = svgEditor.canvas;
svgdoc = S.svgroot.parentNode.ownerDocument;
_context2.next = 11;
return regeneratorRuntime.awrap(importLocale());
case 11:
strings = _context2.sent;
properlySourceSizeTextArea = function properlySourceSizeTextArea() {
// TODO: remove magic numbers here and get values from CSS
var height = $('#svg_source_container').height() - 80;
$('#svg_source_textarea').css('height', height);
};
/**
* @param {boolean} on
* @returns {void}
*/
editingforeign = false;
/**
* This function sets the content of element elt to the input XML.
* @param {string} xmlString - The XML text
* @returns {boolean} This function returns false if the set was unsuccessful, true otherwise.
*/
buttons = [{
id: 'tool_foreign',
icon: svgEditor.curConfig.extIconsPath + 'foreignobject-tool.png',
type: 'mode',
events: {
click: function click() {
svgCanvas.setMode('foreign');
} }
}
editingforeign = true; }, {
toggleSourceButtons(true); id: 'edit_foreign',
elt.removeAttribute('fill'); icon: svgEditor.curConfig.extIconsPath + 'foreignobject-edit.png',
var str = svgCanvas.svgToString(elt, 0); type: 'context',
$('#svg_source_textarea').val(str); panel: 'foreignObject_panel',
$('#svg_source_editor').fadeIn(); events: {
properlySourceSizeTextArea(); click: function click() {
$('#svg_source_textarea').focus(); showForeignEditor();
};
setForeignString = function _ref4(xmlString) {
var elt = selElems[0]; // The parent `Element` to append to
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
svgCanvas.sanitizeSvg(newDoc.documentElement);
elt.replaceWith(svgdoc.importNode(newDoc.documentElement.firstChild, true));
svgCanvas.call('changed', [elt]);
svgCanvas.clearSelection();
} catch (e) {
// Todo: Surface error to user
console.log(e); // eslint-disable-line no-console
return false;
} }
}
return true; }];
}; contextTools = [{
type: 'input',
toggleSourceButtons = function _ref3(on) { panel: 'foreignObject_panel',
$('#tool_source_save, #tool_source_cancel').toggle(!on); id: 'foreign_width',
$('#foreign_save, #foreign_cancel').toggle(on); size: 3,
}; events: {
change: function change() {
showPanel = function _ref2(on) { setAttr('width', this.value);
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); type: 'input',
}; panel: 'foreignObject_panel',
id: 'foreign_height',
svgEditor = this; events: {
$ = S.$, text2xml = S.text2xml, NS = S.NS, importLocale = S.importLocale; change: function change() {
svgCanvas = svgEditor.canvas; setAttr('height', this.value);
svgdoc = S.svgroot.parentNode.ownerDocument;
_context2.next = 11;
return importLocale();
case 11:
strings = _context2.sent;
properlySourceSizeTextArea = function properlySourceSizeTextArea() {
// TODO: remove magic numbers here and get values from CSS
var height = $('#svg_source_container').height() - 80;
$('#svg_source_textarea').css('height', height);
};
/**
* @param {boolean} on
* @returns {void}
*/
editingforeign = false;
/**
* This function sets the content of element elt to the input XML.
* @param {string} xmlString - The XML text
* @returns {boolean} This function returns false if the set was unsuccessful, true otherwise.
*/
buttons = [{
id: 'tool_foreign',
icon: svgEditor.curConfig.extIconsPath + 'foreignobject-tool.png',
type: 'mode',
events: {
click: function click() {
svgCanvas.setMode('foreign');
}
} }
}, { }
id: 'edit_foreign', }, {
icon: svgEditor.curConfig.extIconsPath + 'foreignobject-edit.png', type: 'input',
type: 'context', panel: 'foreignObject_panel',
panel: 'foreignObject_panel', id: 'foreign_font_size',
events: { size: 2,
click: function click() { defval: 16,
showForeignEditor(); events: {
} change: function change() {
setAttr('font-size', this.value);
} }
}]; }
contextTools = [{ }];
type: 'input', return _context2.abrupt("return", {
panel: 'foreignObject_panel', name: strings.name,
id: 'foreign_width', svgicons: svgEditor.curConfig.extIconsPath + 'foreignobject-icons.xml',
size: 3, buttons: strings.buttons.map(function (button, i) {
events: { return Object.assign(buttons[i], button);
change: function change() { }),
setAttr('width', this.value); context_tools: strings.contextTools.map(function (contextTool, i) {
} return Object.assign(contextTools[i], contextTool);
} }),
}, { callback: function callback() {
type: 'input', $('#foreignObject_panel').hide();
panel: 'foreignObject_panel',
id: 'foreign_height',
events: {
change: function change() {
setAttr('height', this.value);
}
}
}, {
type: 'input',
panel: 'foreignObject_panel',
id: 'foreign_font_size',
size: 2,
defval: 16,
events: {
change: function change() {
setAttr('font-size', this.value);
}
}
}];
return _context2.abrupt("return", {
name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'foreignobject-icons.xml',
buttons: strings.buttons.map(function (button, i) {
return Object.assign(buttons[i], button);
}),
context_tools: strings.contextTools.map(function (contextTool, i) {
return Object.assign(contextTools[i], contextTool);
}),
callback: function callback() {
$('#foreignObject_panel').hide();
var endChanges = function endChanges() { var endChanges = function endChanges() {
$('#svg_source_editor').hide(); $('#svg_source_editor').hide();
editingforeign = false; editingforeign = false;
$('#svg_source_textarea').blur(); $('#svg_source_textarea').blur();
toggleSourceButtons(false); toggleSourceButtons(false);
}; // TODO: Needs to be done after orig icon loads }; // TODO: Needs to be done after orig icon loads
setTimeout(function () { setTimeout(function () {
// Create source save/cancel buttons // Create source save/cancel buttons
/* const save = */ /* const save = */
$('#tool_source_save').clone().hide().attr('id', 'foreign_save').unbind().appendTo('#tool_source_back').click( $('#tool_source_save').clone().hide().attr('id', 'foreign_save').unbind().appendTo('#tool_source_back').click(function _callee() {
/*#__PURE__*/ var ok;
_asyncToGenerator( return regeneratorRuntime.async(function _callee$(_context) {
/*#__PURE__*/ while (1) {
regeneratorRuntime.mark(function _callee() { switch (_context.prev = _context.next) {
var ok; case 0:
return regeneratorRuntime.wrap(function _callee$(_context) { if (editingforeign) {
while (1) { _context.next = 2;
switch (_context.prev = _context.next) {
case 0:
if (editingforeign) {
_context.next = 2;
break;
}
return _context.abrupt("return");
case 2:
if (setForeignString($('#svg_source_textarea').val())) {
_context.next = 11;
break;
}
_context.next = 5;
return $.confirm('Errors found. Revert to original?');
case 5:
ok = _context.sent;
if (ok) {
_context.next = 8;
break;
}
return _context.abrupt("return");
case 8:
endChanges();
_context.next = 12;
break; break;
}
case 11: return _context.abrupt("return");
endChanges();
case 12: case 2:
case "end": if (setForeignString($('#svg_source_textarea').val())) {
return _context.stop(); _context.next = 11;
} break;
}
_context.next = 5;
return regeneratorRuntime.awrap($.confirm('Errors found. Revert to original?'));
case 5:
ok = _context.sent;
if (ok) {
_context.next = 8;
break;
}
return _context.abrupt("return");
case 8:
endChanges();
_context.next = 12;
break;
case 11:
endChanges();
case 12:
case "end":
return _context.stop();
} }
}, _callee);
})));
/* 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') {
return undefined;
}
started = true;
newFO = svgCanvas.addSVGElementFromJson({
element: 'foreignObject',
attr: {
x: opts.start_x,
y: opts.start_y,
id: svgCanvas.getNextId(),
'font-size': 16,
// cur_text.font_size,
width: '48',
height: '20',
style: 'pointer-events:inherit'
}
});
var m = svgdoc.createElementNS(NS.MATH, 'math');
m.setAttributeNS(NS.XMLNS, 'xmlns', NS.MATH);
m.setAttribute('display', 'inline');
var mi = svgdoc.createElementNS(NS.MATH, 'mi');
mi.setAttribute('mathvariant', 'normal');
mi.textContent = "\u03A6";
var mo = svgdoc.createElementNS(NS.MATH, 'mo');
mo.textContent = "\u222A";
var mi2 = svgdoc.createElementNS(NS.MATH, 'mi');
mi2.textContent = "\u2133";
m.append(mi, mo, mi2);
newFO.append(m);
return {
started: true
};
},
mouseUp: function mouseUp(opts) {
// const e = opts.event;
if (svgCanvas.getMode() !== 'foreign' || !started) {
return undefined;
}
var attrs = $(newFO).attr(['width', 'height']);
var keep = attrs.width !== '0' || attrs.height !== '0';
svgCanvas.addToSelection([newFO], true);
return {
keep: keep,
element: newFO
};
},
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'));
$('#foreign_width').val(elem.getAttribute('width'));
$('#foreign_height').val(elem.getAttribute('height'));
showPanel(true);
} else {
showPanel(false);
} }
});
});
/* 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') {
return undefined;
}
started = true;
newFO = svgCanvas.addSVGElementFromJson({
element: 'foreignObject',
attr: {
x: opts.start_x,
y: opts.start_y,
id: svgCanvas.getNextId(),
'font-size': 16,
// cur_text.font_size,
width: '48',
height: '20',
style: 'pointer-events:inherit'
}
});
var m = svgdoc.createElementNS(NS.MATH, 'math');
m.setAttributeNS(NS.XMLNS, 'xmlns', NS.MATH);
m.setAttribute('display', 'inline');
var mi = svgdoc.createElementNS(NS.MATH, 'mi');
mi.setAttribute('mathvariant', 'normal');
mi.textContent = "\u03A6";
var mo = svgdoc.createElementNS(NS.MATH, 'mo');
mo.textContent = "\u222A";
var mi2 = svgdoc.createElementNS(NS.MATH, 'mi');
mi2.textContent = "\u2133";
m.append(mi, mo, mi2);
newFO.append(m);
return {
started: true
};
},
mouseUp: function mouseUp(opts) {
// const e = opts.event;
if (svgCanvas.getMode() !== 'foreign' || !started) {
return undefined;
}
var attrs = $(newFO).attr(['width', 'height']);
var keep = attrs.width !== '0' || attrs.height !== '0';
svgCanvas.addToSelection([newFO], true);
return {
keep: keep,
element: newFO
};
},
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'));
$('#foreign_width').val(elem.getAttribute('width'));
$('#foreign_height').val(elem.getAttribute('height'));
showPanel(true);
} else { } else {
showPanel(false); showPanel(false);
} }
} else {
showPanel(false);
} }
},
elementChanged: function elementChanged(opts) {// const elem = opts.elems[0];
} }
}); },
elementChanged: function elementChanged(opts) {// const elem = opts.elems[0];
}
});
case 17: case 17:
case "end": case "end":
return _context2.stop(); return _context2.stop();
}
} }
}, _callee2, this); }
})); }, null, this);
}
function init(_x) {
return _init.apply(this, arguments);
}
return init;
}()
}; };
return extForeignobject; return extForeignobject;

View File

@ -1,42 +1,6 @@
var svgEditorExtension_grid = (function () { var svgEditorExtension_grid = (function () {
'use strict'; 'use strict';
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
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-grid.js * ext-grid.js
* *
@ -47,180 +11,170 @@ var svgEditorExtension_grid = (function () {
*/ */
var extGrid = { var extGrid = {
name: 'grid', name: 'grid',
init: function () { init: function init(_ref) {
var _init = _asyncToGenerator( var $, NS, getTypeMap, importLocale, strings, svgEditor, svgCanvas, svgdoc, assignAttributes, hcanvas, canvBG, units, intervals, showGrid, canvasGrid, gridDefs, gridPattern, gridimg, gridBox, updateGrid, gridUpdate, buttons;
/*#__PURE__*/ return regeneratorRuntime.async(function init$(_context) {
regeneratorRuntime.mark(function _callee(_ref) { while (1) {
var $, NS, getTypeMap, importLocale, strings, svgEditor, svgCanvas, svgdoc, assignAttributes, hcanvas, canvBG, units, intervals, showGrid, canvasGrid, gridDefs, gridPattern, gridimg, gridBox, updateGrid, gridUpdate, buttons; switch (_context.prev = _context.next) {
return regeneratorRuntime.wrap(function _callee$(_context) { case 0:
while (1) { gridUpdate = function _ref3() {
switch (_context.prev = _context.next) { if (showGrid) {
case 0: updateGrid(svgCanvas.getZoom());
gridUpdate = function _ref3() { }
$('#canvasGrid').toggle(showGrid);
$('#view_grid').toggleClass('push_button_pressed tool_button');
};
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 rawM = 100 / uMulti;
var multi = 1;
intervals.some(function (num) {
multi = num;
return rawM <= num;
});
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 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);
gridimg.parentNode.setAttribute('width', bigInt);
gridimg.parentNode.setAttribute('height', bigInt);
svgCanvas.setHref(gridimg, datauri);
};
$ = _ref.$, NS = _ref.NS, getTypeMap = _ref.getTypeMap, importLocale = _ref.importLocale;
_context.next = 5;
return regeneratorRuntime.awrap(importLocale());
case 5:
strings = _context.sent;
svgEditor = this;
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%',
height: '100%',
x: 0,
y: 0,
overflow: 'visible',
display: 'none'
});
canvBG.append(canvasGrid);
gridDefs = svgdoc.createElementNS(NS.SVG, 'defs'); // 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
width: 100,
height: 100
});
gridimg = svgdoc.createElementNS(NS.SVG, 'image');
assignAttributes(gridimg, {
x: 0,
y: 0,
width: 100,
height: 100
});
gridPattern.append(gridimg);
gridDefs.append(gridPattern);
$('#canvasGrid').append(gridDefs); // grid-box
gridBox = svgdoc.createElementNS(NS.SVG, 'rect');
assignAttributes(gridBox, {
width: '100%',
height: '100%',
x: 0,
y: 0,
'stroke-width': 0,
stroke: 'none',
fill: 'url(#gridpattern)',
style: 'pointer-events: none; display:visible;'
});
$('#canvasGrid').append(gridBox);
/**
*
* @param {Float} zoom
* @returns {void}
*/
buttons = [{
id: 'view_grid',
icon: svgEditor.curConfig.extIconsPath + 'grid.png',
type: 'context',
panel: 'editor_panel',
events: {
click: function click() {
svgEditor.curConfig.showGrid = showGrid = !showGrid;
gridUpdate();
}
}
}];
return _context.abrupt("return", {
name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'grid-icon.xml',
zoomChanged: function zoomChanged(zoom) {
if (showGrid) { if (showGrid) {
updateGrid(svgCanvas.getZoom()); updateGrid(zoom);
} }
},
$('#canvasGrid').toggle(showGrid); callback: function callback() {
$('#view_grid').toggleClass('push_button_pressed tool_button'); if (showGrid) {
}; gridUpdate();
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 rawM = 100 / uMulti;
var multi = 1;
intervals.some(function (num) {
multi = num;
return rawM <= num;
});
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 lineNum = 0;
ctx.moveTo(subD, bigInt);
ctx.lineTo(subD, lineNum);
ctx.moveTo(bigInt, subD);
ctx.lineTo(lineNum, subD);
} }
},
buttons: strings.buttons.map(function (button, i) {
return Object.assign(buttons[i], button);
})
});
ctx.stroke(); case 27:
ctx.beginPath(); case "end":
ctx.globalAlpha = 0.5; return _context.stop();
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);
gridimg.parentNode.setAttribute('width', bigInt);
gridimg.parentNode.setAttribute('height', bigInt);
svgCanvas.setHref(gridimg, datauri);
};
$ = _ref.$, NS = _ref.NS, getTypeMap = _ref.getTypeMap, importLocale = _ref.importLocale;
_context.next = 5;
return importLocale();
case 5:
strings = _context.sent;
svgEditor = this;
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%',
height: '100%',
x: 0,
y: 0,
overflow: 'visible',
display: 'none'
});
canvBG.append(canvasGrid);
gridDefs = svgdoc.createElementNS(NS.SVG, 'defs'); // 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
width: 100,
height: 100
});
gridimg = svgdoc.createElementNS(NS.SVG, 'image');
assignAttributes(gridimg, {
x: 0,
y: 0,
width: 100,
height: 100
});
gridPattern.append(gridimg);
gridDefs.append(gridPattern);
$('#canvasGrid').append(gridDefs); // grid-box
gridBox = svgdoc.createElementNS(NS.SVG, 'rect');
assignAttributes(gridBox, {
width: '100%',
height: '100%',
x: 0,
y: 0,
'stroke-width': 0,
stroke: 'none',
fill: 'url(#gridpattern)',
style: 'pointer-events: none; display:visible;'
});
$('#canvasGrid').append(gridBox);
/**
*
* @param {Float} zoom
* @returns {void}
*/
buttons = [{
id: 'view_grid',
icon: svgEditor.curConfig.extIconsPath + 'grid.png',
type: 'context',
panel: 'editor_panel',
events: {
click: function click() {
svgEditor.curConfig.showGrid = showGrid = !showGrid;
gridUpdate();
}
}
}];
return _context.abrupt("return", {
name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'grid-icon.xml',
zoomChanged: function zoomChanged(zoom) {
if (showGrid) {
updateGrid(zoom);
}
},
callback: function callback() {
if (showGrid) {
gridUpdate();
}
},
buttons: strings.buttons.map(function (button, i) {
return Object.assign(buttons[i], button);
})
});
case 27:
case "end":
return _context.stop();
}
} }
}, _callee, this); }
})); }, null, this);
}
function init(_x) {
return _init.apply(this, arguments);
}
return init;
}()
}; };
return extGrid; return extGrid;

View File

@ -1,42 +1,6 @@
var svgEditorExtension_helloworld = (function () { var svgEditorExtension_helloworld = (function () {
'use strict'; 'use strict';
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
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);
});
};
}
function _slicedToArray(arr, i) { function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
} }
@ -95,101 +59,91 @@ var svgEditorExtension_helloworld = (function () {
*/ */
var extHelloworld = { var extHelloworld = {
name: 'helloworld', name: 'helloworld',
init: function () { init: function init(_ref) {
var _init = _asyncToGenerator( var $, importLocale, strings, svgEditor, svgCanvas;
/*#__PURE__*/ return regeneratorRuntime.async(function init$(_context) {
regeneratorRuntime.mark(function _callee(_ref) { while (1) {
var $, importLocale, strings, svgEditor, svgCanvas; switch (_context.prev = _context.next) {
return regeneratorRuntime.wrap(function _callee$(_context) { case 0:
while (1) { $ = _ref.$, importLocale = _ref.importLocale;
switch (_context.prev = _context.next) { _context.next = 3;
case 0: return regeneratorRuntime.awrap(importLocale());
$ = _ref.$, importLocale = _ref.importLocale;
_context.next = 3;
return importLocale();
case 3: case 3:
strings = _context.sent; strings = _context.sent;
svgEditor = this; svgEditor = this;
svgCanvas = svgEditor.canvas; svgCanvas = svgEditor.canvas;
return _context.abrupt("return", { return _context.abrupt("return", {
name: strings.name, name: strings.name,
// For more notes on how to make an icon file, see the source of // For more notes on how to make an icon file, see the source of
// the helloworld-icon.xml // the helloworld-icon.xml
svgicons: svgEditor.curConfig.extIconsPath + 'helloworld-icon.xml', svgicons: svgEditor.curConfig.extIconsPath + 'helloworld-icon.xml',
// Multiple buttons can be added in this array // Multiple buttons can be added in this array
buttons: [{ buttons: [{
// Must match the icon ID in helloworld-icon.xml // Must match the icon ID in helloworld-icon.xml
id: 'hello_world', id: 'hello_world',
// Fallback, e.g., for `file:///` access // Fallback, e.g., for `file:///` access
icon: svgEditor.curConfig.extIconsPath + 'helloworld.png', icon: svgEditor.curConfig.extIconsPath + 'helloworld.png',
// This indicates that the button will be added to the "mode" // This indicates that the button will be added to the "mode"
// button panel on the left side // button panel on the left side
type: 'mode', type: 'mode',
// Tooltip text // Tooltip text
title: strings.buttons[0].title, title: strings.buttons[0].title,
// Events // Events
events: { events: {
click: function click() { click: function click() {
// The action taken when the button is clicked on. // The action taken when the button is clicked on.
// For "mode" buttons, any other button will // For "mode" buttons, any other button will
// automatically be de-pressed. // automatically be de-pressed.
svgCanvas.setMode('hello_world'); svgCanvas.setMode('hello_world');
}
}
}],
// This is triggered when the main mouse button is pressed down
// on the editor canvas (not the tool panels)
mouseDown: function mouseDown() {
// Check the mode on mousedown
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 undefined;
},
// 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(); // Get the actual coordinate by dividing by the zoom value
var x = opts.mouse_x / zoom;
var y = opts.mouse_y / zoom; // We do our own formatting
var text = strings.text;
[['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
$.alert(text);
} }
} }
}); }],
// This is triggered when the main mouse button is pressed down
// on the editor canvas (not the tool panels)
mouseDown: function mouseDown() {
// Check the mode on mousedown
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
};
}
case 7: return undefined;
case "end": },
return _context.stop(); // 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(); // Get the actual coordinate by dividing by the zoom value
var x = opts.mouse_x / zoom;
var y = opts.mouse_y / zoom; // We do our own formatting
var text = strings.text;
[['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
$.alert(text);
}
}
});
case 7:
case "end":
return _context.stop();
} }
}, _callee, this); }
})); }, null, this);
}
function init(_x) {
return _init.apply(this, arguments);
}
return init;
}()
}; };
return extHelloworld; return extHelloworld;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,42 +1,6 @@
var svgEditorExtension_mathjax = (function () { var svgEditorExtension_mathjax = (function () {
'use strict'; 'use strict';
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
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);
});
};
}
/** /**
* Add any of the whitelisted attributes to the script tag. * Add any of the whitelisted attributes to the script tag.
* @param {HTMLScriptElement} script * @param {HTMLScriptElement} script
@ -52,6 +16,14 @@ var svgEditorExtension_mathjax = (function () {
} }
}); });
} // Additions by Brett } // Additions by Brett
/**
*
* @author Brett Zamir (other items are from `dynamic-import-polyfill`)
* @param {string|string[]} url
* @param {PlainObject} [atts={}]
* @returns {Promise<void|Error>} Resolves to `undefined` or rejects with an `Error` upon a
* script loading error
*/
function importScript(url) { function importScript(url) {
var atts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var atts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
@ -101,272 +73,253 @@ var svgEditorExtension_mathjax = (function () {
}); });
} }
/* globals MathJax */
var extMathjax = { var extMathjax = {
name: 'mathjax', name: 'mathjax',
init: function () { init: function init(_ref) {
var _init = _asyncToGenerator( var $, importLocale, strings, svgEditor, svgCanvas, mathjaxSrcSecure, uiStrings, math, locationX, locationY, mathjaxLoaded, saveMath, buttons;
/*#__PURE__*/ return regeneratorRuntime.async(function init$(_context2) {
regeneratorRuntime.mark(function _callee2(_ref) { while (1) {
var $, importLocale, strings, svgEditor, svgCanvas, mathjaxSrcSecure, uiStrings, math, locationX, locationY, mathjaxLoaded, saveMath, buttons; switch (_context2.prev = _context2.next) {
return regeneratorRuntime.wrap(function _callee2$(_context2) { case 0:
while (1) { saveMath = function _ref2() {
switch (_context2.prev = _context2.next) { var code = $('#mathjax_code_textarea').val(); // displaystyle to force MathJax NOT to use the inline style. Because it is
case 0: // less fancy!
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 * 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 * every symbol (glymph) you need only once. These are saved in a `<svg>` on
* the top of your html document, just under the body tag. Each glymph has * the top of your html document, just under the body tag. Each glymph has
* its unique id and is saved as a `<path>` in the `<defs>` tag of the `<svg>` * its unique id and is saved as a `<path>` in the `<defs>` tag of the `<svg>`
*
* Then when the symbols are needed in the rest of your html document they
* are refferd to by a `<use>` tag.
* Because of bug 1076 we can't just grab the defs tag on the top and add it
* 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());
svg.find('use').each(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) {
glymph.attr('transform', transform);
} else if (x || y) {
glymph.attr('transform', 'translate(' + x + ',' + y + ')');
}
$(this).replaceWith(glymph);
}); // 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.
// This should only be once!
svgCanvas.moveSelectedElements(locationX, locationY, true);
});
};
$ = _ref.$, importLocale = _ref.importLocale;
_context2.next = 4;
return importLocale();
case 4:
strings = _context2.sent;
svgEditor = this;
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">
MathJax.Hub.Config({
extensions: ['tex2jax.js'],
jax: ['input/TeX', 'output/SVG'],
showProcessingMessages: true,
showMathMenu: false,
showMathMenuMSIE: false,
errorSettings: {
message: ['[Math Processing Error]'],
style: {color: '#CC0000', 'font-style': 'italic'}
},
elements: [],
tex2jax: {
ignoreClass: 'tex2jax_ignore2', processClass: 'tex2jax_process2',
},
TeX: {
extensions: ['AMSmath.js', 'AMSsymbols.js', 'noErrors.js', 'noUndefined.js']
},
SVG: {
}
});
</script>`, */
// mathjaxSrc = 'http://cdn.mathjax.org/mathjax/latest/MathJax.js',
// 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;
mathjaxLoaded = false; // TODO: Implement language support. Move these uiStrings to the locale files and
// the code to the langReady callback. Also i18nize alert and HTML below
$.extend(uiStrings, {
mathjax: {
embed_svg: 'Save as mathematics',
embed_mathml: 'Save as figure',
svg_save_warning: 'The math will be transformed into a figure is manipulatable like everything else. You will not be able to manipulate the TeX-code anymore. ',
mathml_save_warning: 'Advised. The math will be saved as a figure.',
title: 'Mathematics code editor'
}
});
/**
* *
* @returns {void} * Then when the symbols are needed in the rest of your html document they
* are refferd to by a `<use>` tag.
* Because of bug 1076 we can't just grab the defs tag on the top and add it
* to your formula's `<svg>` and copy the lot. So we have to replace each
* `<use>` tag by its `<path>`.
*/ */
buttons = [{ MathJax.Hub.queue.Push(function () {
id: 'tool_mathjax', var mathjaxMath = $('.MathJax_SVG');
type: 'mode', var svg = $(mathjaxMath.html());
icon: svgEditor.curConfig.extIconsPath + 'mathjax.png', svg.find('use').each(function () {
events: { // TODO: find a less pragmatic and more elegant solution to this.
click: function () { var id = $(this).attr('href') ? $(this).attr('href').slice(1) // Works in Chrome.
var _click = _asyncToGenerator( : $(this).attr('xlink:href').slice(1); // Works in Firefox.
/*#__PURE__*/
regeneratorRuntime.mark(function _callee() {
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
// Set the mode.
svgCanvas.setMode('mathjax'); // 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)) { var glymph = $('#' + id).clone().removeAttr('id');
_context.next = 17; var x = $(this).attr('x');
break; var y = $(this).attr('y');
} var transform = $(this).attr('transform');
$('<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. if (transform && (x || y)) {
glymph.attr('transform', transform + ' translate(' + x + ',' + y + ')');
$('#mathjax_container').draggable({ } else if (transform) {
cancel: 'button,fieldset', glymph.attr('transform', transform);
containment: 'window' } else if (x || y) {
}); // Add functionality and picture to cancel button. glymph.attr('transform', 'translate(' + x + ',' + y + ')');
$('#tool_mathjax_cancel').prepend($.getSvgIcon('cancel', true)).on('click touched', function () {
$('#mathjax').hide();
}); // 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.
$('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 ||
window.svgEditor.modules !== false;
// Add as second argument to `importScript`
{
type: modularVersion
? 'module' // Make this the default when widely supported
: 'text/javascript'
}
// If only using modules, just use this:
const {default: MathJax} = await importModule( // or `import()` when widely supported
svgEditor.curConfig.extIconsPath + mathjaxSrcSecure
);
*/
// We use `extIconsPath` here for now as it does not vary with
// the modular type as does `extPath`
_context.prev = 7;
_context.next = 10;
return importScript(svgEditor.curConfig.extIconsPath + mathjaxSrcSecure);
case 10:
// When MathJax is loaded get the div where the math will be rendered.
MathJax.Hub.queue.Push(function () {
math = MathJax.Hub.getAllJax('#mathjax_creator')[0];
console.log(math); // eslint-disable-line no-console
mathjaxLoaded = true;
console.log('MathJax Loaded'); // eslint-disable-line no-console
});
_context.next = 17;
break;
case 13:
_context.prev = 13;
_context.t0 = _context["catch"](7);
console.log('Failed loading MathJax.'); // eslint-disable-line no-console
$.alert('Failed loading MathJax. You will not be able to change the mathematics.');
case 17:
case "end":
return _context.stop();
}
}
}, _callee, null, [[7, 13]]);
}));
function click() {
return _click.apply(this, arguments);
}
return click;
}()
}
}];
return _context2.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 undefined; $(this).replaceWith(glymph);
}, }); // Remove the style tag because it interferes with SVG-Edit.
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
locationX = opts.mouse_x / zoom; svg.removeAttr('style');
locationY = opts.mouse_y / zoom; svg.attr('xmlns', 'http://www.w3.org/2000/svg');
$('#mathjax').show(); svgCanvas.importSvgString($('<div>').append(svg.clone()).html(), true);
return { svgCanvas.ungroupSelectedElement(); // TODO: To undo the adding of the Formula you now have to undo twice.
started: false // This should only be once!
}; // Otherwise the last selected object dissapears.
}
return undefined; svgCanvas.moveSelectedElements(locationX, locationY, true);
},
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.
// $(mathjaxConfiguration).appendTo('head');
}
}); });
};
case 12: $ = _ref.$, importLocale = _ref.importLocale;
case "end": _context2.next = 4;
return _context2.stop(); return regeneratorRuntime.awrap(importLocale());
}
case 4:
strings = _context2.sent;
svgEditor = this;
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">
MathJax.Hub.Config({
extensions: ['tex2jax.js'],
jax: ['input/TeX', 'output/SVG'],
showProcessingMessages: true,
showMathMenu: false,
showMathMenuMSIE: false,
errorSettings: {
message: ['[Math Processing Error]'],
style: {color: '#CC0000', 'font-style': 'italic'}
},
elements: [],
tex2jax: {
ignoreClass: 'tex2jax_ignore2', processClass: 'tex2jax_process2',
},
TeX: {
extensions: ['AMSmath.js', 'AMSsymbols.js', 'noErrors.js', 'noUndefined.js']
},
SVG: {
}
});
</script>`, */
// mathjaxSrc = 'http://cdn.mathjax.org/mathjax/latest/MathJax.js',
// 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;
mathjaxLoaded = false; // TODO: Implement language support. Move these uiStrings to the locale files and
// the code to the langReady callback. Also i18nize alert and HTML below
$.extend(uiStrings, {
mathjax: {
embed_svg: 'Save as mathematics',
embed_mathml: 'Save as figure',
svg_save_warning: 'The math will be transformed into a figure is manipulatable like everything else. You will not be able to manipulate the TeX-code anymore. ',
mathml_save_warning: 'Advised. The math will be saved as a figure.',
title: 'Mathematics code editor'
}
});
/**
*
* @returns {void}
*/
buttons = [{
id: 'tool_mathjax',
type: 'mode',
icon: svgEditor.curConfig.extIconsPath + 'mathjax.png',
events: {
click: function click() {
return regeneratorRuntime.async(function click$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
// Set the mode.
svgCanvas.setMode('mathjax'); // 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)) {
_context.next = 17;
break;
}
$('<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.
$('#mathjax_container').draggable({
cancel: 'button,fieldset',
containment: 'window'
}); // 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.
$('#tool_mathjax_save').prepend($.getSvgIcon('ok', true)).on('click touched', function () {
saveMath();
$('#mathjax').hide();
}); // MathJax preprocessing has to ignore most of the page.
$('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 ||
window.svgEditor.modules !== false;
// Add as second argument to `importScript`
{
type: modularVersion
? 'module' // Make this the default when widely supported
: 'text/javascript'
}
// If only using modules, just use this:
const {default: MathJax} = await importModule( // or `import()` when widely supported
svgEditor.curConfig.extIconsPath + mathjaxSrcSecure
);
*/
// We use `extIconsPath` here for now as it does not vary with
// the modular type as does `extPath`
_context.prev = 7;
_context.next = 10;
return regeneratorRuntime.awrap(importScript(svgEditor.curConfig.extIconsPath + mathjaxSrcSecure));
case 10:
// When MathJax is loaded get the div where the math will be rendered.
MathJax.Hub.queue.Push(function () {
math = MathJax.Hub.getAllJax('#mathjax_creator')[0];
console.log(math); // eslint-disable-line no-console
mathjaxLoaded = true;
console.log('MathJax Loaded'); // eslint-disable-line no-console
});
_context.next = 17;
break;
case 13:
_context.prev = 13;
_context.t0 = _context["catch"](7);
console.log('Failed loading MathJax.'); // eslint-disable-line no-console
$.alert('Failed loading MathJax. You will not be able to change the mathematics.');
case 17:
case "end":
return _context.stop();
}
}
}, null, null, [[7, 13]]);
}
}
}];
return _context2.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 undefined;
},
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
locationX = opts.mouse_x / zoom;
locationY = opts.mouse_y / zoom;
$('#mathjax').show();
return {
started: false
}; // Otherwise the last selected object dissapears.
}
return undefined;
},
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.
// $(mathjaxConfiguration).appendTo('head');
}
});
case 12:
case "end":
return _context2.stop();
} }
}, _callee2, this); }
})); }, null, this);
}
function init(_x) {
return _init.apply(this, arguments);
}
return init;
}()
}; };
return extMathjax; return extMathjax;

View File

@ -1,42 +1,6 @@
var svgEditorExtension_panning = (function () { var svgEditorExtension_panning = (function () {
'use strict'; 'use strict';
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
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 * ext-panning.js
* *
@ -51,76 +15,66 @@ var svgEditorExtension_panning = (function () {
*/ */
var extPanning = { var extPanning = {
name: 'panning', name: 'panning',
init: function () { init: function init(_ref) {
var _init = _asyncToGenerator( var importLocale, strings, svgEditor, svgCanvas, buttons;
/*#__PURE__*/ return regeneratorRuntime.async(function init$(_context) {
regeneratorRuntime.mark(function _callee(_ref) { while (1) {
var importLocale, strings, svgEditor, svgCanvas, buttons; switch (_context.prev = _context.next) {
return regeneratorRuntime.wrap(function _callee$(_context) { case 0:
while (1) { importLocale = _ref.importLocale;
switch (_context.prev = _context.next) { _context.next = 3;
case 0: return regeneratorRuntime.awrap(importLocale());
importLocale = _ref.importLocale;
_context.next = 3;
return importLocale();
case 3: case 3:
strings = _context.sent; strings = _context.sent;
svgEditor = this; svgEditor = this;
svgCanvas = svgEditor.canvas; svgCanvas = svgEditor.canvas;
buttons = [{ buttons = [{
id: 'ext-panning', id: 'ext-panning',
icon: svgEditor.curConfig.extIconsPath + 'panning.png', icon: svgEditor.curConfig.extIconsPath + 'panning.png',
type: 'mode', type: 'mode',
events: { events: {
click: function click() { click: function click() {
svgCanvas.setMode('ext-panning'); svgCanvas.setMode('ext-panning');
}
} }
}]; }
return _context.abrupt("return", { }];
name: strings.name, return _context.abrupt("return", {
svgicons: svgEditor.curConfig.extIconsPath + 'ext-panning.xml', name: strings.name,
buttons: strings.buttons.map(function (button, i) { svgicons: svgEditor.curConfig.extIconsPath + 'ext-panning.xml',
return Object.assign(buttons[i], button); buttons: strings.buttons.map(function (button, i) {
}), return Object.assign(buttons[i], button);
mouseDown: function mouseDown() { }),
if (svgCanvas.getMode() === 'ext-panning') { mouseDown: function mouseDown() {
svgEditor.setPanning(true); if (svgCanvas.getMode() === 'ext-panning') {
return { svgEditor.setPanning(true);
started: true return {
}; started: true
} };
return undefined;
},
mouseUp: function mouseUp() {
if (svgCanvas.getMode() === 'ext-panning') {
svgEditor.setPanning(false);
return {
keep: false,
element: null
};
}
return undefined;
} }
});
case 8: return undefined;
case "end": },
return _context.stop(); mouseUp: function mouseUp() {
} if (svgCanvas.getMode() === 'ext-panning') {
svgEditor.setPanning(false);
return {
keep: false,
element: null
};
}
return undefined;
}
});
case 8:
case "end":
return _context.stop();
} }
}, _callee, this); }
})); }, null, this);
}
function init(_x) {
return _init.apply(this, arguments);
}
return init;
}()
}; };
return extPanning; return extPanning;

File diff suppressed because it is too large Load Diff

View File

@ -1,42 +1,6 @@
var svgEditorExtension_polygon = (function () { var svgEditorExtension_polygon = (function () {
'use strict'; 'use strict';
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
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-polygon.js * ext-polygon.js
* *
@ -46,268 +10,258 @@ var svgEditorExtension_polygon = (function () {
*/ */
var extPolygon = { var extPolygon = {
name: 'polygon', name: 'polygon',
init: function () { init: function init(S) {
var _init = _asyncToGenerator( var svgEditor, svgCanvas, $, importLocale, editingitex, strings, selElems, started, newFO, showPanel, setAttr, cot, sec, buttons, contextTools;
/*#__PURE__*/ return regeneratorRuntime.async(function init$(_context) {
regeneratorRuntime.mark(function _callee(S) { while (1) {
var svgEditor, svgCanvas, $, importLocale, editingitex, strings, selElems, started, newFO, showPanel, setAttr, cot, sec, buttons, contextTools; switch (_context.prev = _context.next) {
return regeneratorRuntime.wrap(function _callee$(_context) { case 0:
while (1) { sec = function _ref4(n) {
switch (_context.prev = _context.next) { return 1 / Math.cos(n);
case 0: };
sec = function _ref4(n) {
return 1 / Math.cos(n);
};
cot = function _ref3(n) { cot = function _ref3(n) {
return 1 / Math.tan(n); return 1 / Math.tan(n);
}; };
setAttr = function _ref2(attr, val) { setAttr = function _ref2(attr, val) {
svgCanvas.changeSelectedAttribute(attr, val); svgCanvas.changeSelectedAttribute(attr, val);
svgCanvas.call('changed', selElems); svgCanvas.call('changed', selElems);
}; };
showPanel = function _ref(on) { showPanel = function _ref(on) {
var fcRules = $('#fc_rules'); var fcRules = $('#fc_rules');
if (!fcRules.length) { if (!fcRules.length) {
fcRules = $('<style id="fc_rules"></style>').appendTo('head'); fcRules = $('<style id="fc_rules"></style>').appendTo('head');
}
fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }');
$('#polygon_panel').toggle(on);
};
svgEditor = this;
svgCanvas = svgEditor.canvas;
$ = S.$, importLocale = S.importLocale, editingitex = false;
_context.next = 9;
return importLocale();
case 9:
strings = _context.sent;
/**
* Obtained from http://code.google.com/p/passenger-top/source/browse/instiki/public/svg-edit/editor/extensions/ext-itex.js?r=3
* This function sets the content of of the currently-selected foreignObject element,
* based on the itex contained in string.
* @param {string} tex The itex text.
* @returns {boolean} This function returns false if the set was unsuccessful, true otherwise.
*/
/*
function setItexString(tex) {
const mathns = 'http://www.w3.org/1998/Math/MathML',
xmlnsns = 'http://www.w3.org/2000/xmlns/',
ajaxEndpoint = '../../itex';
const elt = selElems[0];
try {
const math = svgdoc.createElementNS(mathns, 'math');
math.setAttributeNS(xmlnsns, 'xmlns', mathns);
math.setAttribute('display', 'inline');
const semantics = document.createElementNS(mathns, 'semantics');
const annotation = document.createElementNS(mathns, 'annotation');
annotation.setAttribute('encoding', 'application/x-tex');
annotation.textContent = tex;
const mrow = document.createElementNS(mathns, 'mrow');
semantics.append(mrow, annotation);
math.append(semantics);
// make an AJAX request to the server, to get the MathML
$.post(ajaxEndpoint, {tex, display: 'inline'}, function(data){
const children = data.documentElement.childNodes;
while (children.length > 0) {
mrow.append(svgdoc.adoptNode(children[0], true));
}
svgCanvas.sanitizeSvg(math);
svgCanvas.call('changed', [elt]);
});
elt.firstChild.replaceWith(math);
svgCanvas.call('changed', [elt]);
svgCanvas.clearSelection();
} catch(e) {
console.log(e);
return false;
}
return true;
} }
*/
buttons = [{ fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }');
id: 'tool_polygon', $('#polygon_panel').toggle(on);
icon: svgEditor.curConfig.extIconsPath + 'polygon.png', };
type: 'mode',
position: 11, svgEditor = this;
events: { svgCanvas = svgEditor.canvas;
click: function click() { $ = S.$, importLocale = S.importLocale, editingitex = false;
svgCanvas.setMode('polygon'); _context.next = 9;
showPanel(true); return regeneratorRuntime.awrap(importLocale());
case 9:
strings = _context.sent;
/**
* Obtained from http://code.google.com/p/passenger-top/source/browse/instiki/public/svg-edit/editor/extensions/ext-itex.js?r=3
* This function sets the content of of the currently-selected foreignObject element,
* based on the itex contained in string.
* @param {string} tex The itex text.
* @returns {boolean} This function returns false if the set was unsuccessful, true otherwise.
*/
/*
function setItexString(tex) {
const mathns = 'http://www.w3.org/1998/Math/MathML',
xmlnsns = 'http://www.w3.org/2000/xmlns/',
ajaxEndpoint = '../../itex';
const elt = selElems[0];
try {
const math = svgdoc.createElementNS(mathns, 'math');
math.setAttributeNS(xmlnsns, 'xmlns', mathns);
math.setAttribute('display', 'inline');
const semantics = document.createElementNS(mathns, 'semantics');
const annotation = document.createElementNS(mathns, 'annotation');
annotation.setAttribute('encoding', 'application/x-tex');
annotation.textContent = tex;
const mrow = document.createElementNS(mathns, 'mrow');
semantics.append(mrow, annotation);
math.append(semantics);
// make an AJAX request to the server, to get the MathML
$.post(ajaxEndpoint, {tex, display: 'inline'}, function(data){
const children = data.documentElement.childNodes;
while (children.length > 0) {
mrow.append(svgdoc.adoptNode(children[0], true));
} }
svgCanvas.sanitizeSvg(math);
svgCanvas.call('changed', [elt]);
});
elt.firstChild.replaceWith(math);
svgCanvas.call('changed', [elt]);
svgCanvas.clearSelection();
} catch(e) {
console.log(e);
return false;
}
return true;
}
*/
buttons = [{
id: 'tool_polygon',
icon: svgEditor.curConfig.extIconsPath + 'polygon.png',
type: 'mode',
position: 11,
events: {
click: function click() {
svgCanvas.setMode('polygon');
showPanel(true);
} }
}]; }
contextTools = [{ }];
type: 'input', contextTools = [{
panel: 'polygon_panel', type: 'input',
id: 'polySides', panel: 'polygon_panel',
size: 3, id: 'polySides',
defval: 5, size: 3,
events: { defval: 5,
change: function change() { events: {
setAttr('sides', this.value); change: function change() {
} setAttr('sides', this.value);
} }
}]; }
return _context.abrupt("return", { }];
name: strings.name, return _context.abrupt("return", {
svgicons: svgEditor.curConfig.extIconsPath + 'polygon-icons.svg', name: strings.name,
buttons: strings.buttons.map(function (button, i) { svgicons: svgEditor.curConfig.extIconsPath + 'polygon-icons.svg',
return Object.assign(buttons[i], button); buttons: strings.buttons.map(function (button, i) {
}), return Object.assign(buttons[i], button);
context_tools: strings.contextTools.map(function (contextTool, i) { }),
return Object.assign(contextTools[i], contextTool); context_tools: strings.contextTools.map(function (contextTool, i) {
}), return Object.assign(contextTools[i], contextTool);
callback: function callback() { }),
$('#polygon_panel').hide(); callback: function callback() {
$('#polygon_panel').hide();
setTimeout(function () { setTimeout(function () {
// Create source save/cancel buttons // Create source save/cancel buttons
/* const save = */ /* const save = */
$('#tool_source_save').clone().hide().attr('id', 'polygon_save').unbind().appendTo('#tool_source_back').click(function () { $('#tool_source_save').clone().hide().attr('id', 'polygon_save').unbind().appendTo('#tool_source_back').click(function () {
if (!editingitex) { if (!editingitex) {
return; return;
} // Todo: Uncomment the setItexString() function above and handle ajaxEndpoint? } // Todo: Uncomment the setItexString() function above and handle ajaxEndpoint?
// setSelectMode(); // setSelectMode();
});
/* const cancel = */
$('#tool_source_cancel').clone().hide().attr('id', 'polygon_cancel').unbind().appendTo('#tool_source_back').click(function () {
});
}, 3000);
},
mouseDown: function mouseDown(opts) {
if (svgCanvas.getMode() !== 'polygon') {
return undefined;
} // 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 sWidth = svgCanvas.getStrokeWidth();
started = true;
newFO = svgCanvas.addSVGElementFromJson({
element: 'polygon',
attr: {
cx: opts.start_x,
cy: opts.start_y,
id: svgCanvas.getNextId(),
shape: 'regularPoly',
sides: document.getElementById('polySides').value,
orient: 'x',
edge: 0,
fill: rgb,
strokecolor: sRgb,
strokeWidth: sWidth
}
}); });
return { /* const cancel = */
started: true
}; $('#tool_source_cancel').clone().hide().attr('id', 'polygon_cancel').unbind().appendTo('#tool_source_back').click(function () {
}, });
mouseMove: function mouseMove(opts) { }, 3000);
if (!started || svgCanvas.getMode() !== 'polygon') { },
return undefined; mouseDown: function mouseDown(opts) {
} // const e = opts.event; if (svgCanvas.getMode() !== 'polygon') {
return undefined;
} // const e = opts.event;
var c = $(newFO).attr(['cx', 'cy', 'sides', 'orient', 'fill', 'strokecolor', 'strokeWidth']); var rgb = svgCanvas.getColor('fill'); // const ccRgbEl = rgb.substring(1, rgb.length);
var x = opts.mouse_x;
var y = opts.mouse_y;
var cx = c.cx,
cy = c.cy,
fill = c.fill,
strokecolor = c.strokecolor,
strokeWidth = c.strokeWidth,
sides = c.sides,
edg = Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy)) / 1.5;
newFO.setAttribute('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 sRgb = svgCanvas.getColor('stroke'); // ccSRgbEl = sRgb.substring(1, rgb.length);
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');
var sWidth = svgCanvas.getStrokeWidth();
newFO.setAttribute('points', points); started = true;
newFO.setAttribute('fill', fill); newFO = svgCanvas.addSVGElementFromJson({
newFO.setAttribute('stroke', strokecolor); element: 'polygon',
newFO.setAttribute('stroke-width', strokeWidth); // newFO.setAttribute('transform', 'rotate(-90)'); attr: {
// const shape = newFO.getAttribute('shape'); cx: opts.start_x,
// newFO.append(poly); cy: opts.start_y,
// DrawPoly(cx, cy, sides, edg, orient); id: svgCanvas.getNextId(),
shape: 'regularPoly',
return { sides: document.getElementById('polySides').value,
started: true orient: 'x',
}; edge: 0,
}, fill: rgb,
mouseUp: function mouseUp(opts) { strokecolor: sRgb,
if (svgCanvas.getMode() !== 'polygon') { strokeWidth: sWidth
return undefined;
} }
});
return {
started: true
};
},
mouseMove: function mouseMove(opts) {
if (!started || svgCanvas.getMode() !== 'polygon') {
return undefined;
} // const e = opts.event;
var attrs = $(newFO).attr('edge');
var keep = attrs.edge !== '0'; // svgCanvas.addToSelection([newFO], true);
return { var c = $(newFO).attr(['cx', 'cy', 'sides', 'orient', 'fill', 'strokecolor', 'strokeWidth']);
keep: keep, var x = opts.mouse_x;
element: newFO var y = opts.mouse_y;
}; var cx = c.cx,
}, cy = c.cy,
selectedChanged: function selectedChanged(opts) { fill = c.fill,
// Use this to update the current selected elements strokecolor = c.strokecolor,
selElems = opts.elems; strokeWidth = c.strokeWidth,
var i = selElems.length; sides = c.sides,
edg = Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy)) / 1.5;
newFO.setAttribute('edge', edg);
var inradius = edg / 2 * cot(Math.PI / sides);
var circumradius = inradius * sec(Math.PI / sides);
var points = '';
while (i--) { for (var s = 0; sides >= s; s++) {
var elem = selElems[i]; 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');
if (elem && elem.getAttribute('shape') === 'regularPoly') {
if (opts.selectedElement && !opts.multiselected) { newFO.setAttribute('points', points);
$('#polySides').val(elem.getAttribute('sides')); newFO.setAttribute('fill', fill);
showPanel(true); newFO.setAttribute('stroke', strokecolor);
} else { newFO.setAttribute('stroke-width', strokeWidth); // newFO.setAttribute('transform', 'rotate(-90)');
showPanel(false); // const shape = newFO.getAttribute('shape');
} // newFO.append(poly);
// DrawPoly(cx, cy, sides, edg, orient);
return {
started: true
};
},
mouseUp: function mouseUp(opts) {
if (svgCanvas.getMode() !== 'polygon') {
return undefined;
}
var attrs = $(newFO).attr('edge');
var keep = attrs.edge !== '0'; // svgCanvas.addToSelection([newFO], true);
return {
keep: keep,
element: newFO
};
},
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.getAttribute('shape') === 'regularPoly') {
if (opts.selectedElement && !opts.multiselected) {
$('#polySides').val(elem.getAttribute('sides'));
showPanel(true);
} else { } else {
showPanel(false); showPanel(false);
} }
} else {
showPanel(false);
} }
},
elementChanged: function elementChanged(opts) {// const elem = opts.elems[0];
} }
}); },
elementChanged: function elementChanged(opts) {// const elem = opts.elems[0];
}
});
case 13: case 13:
case "end": case "end":
return _context.stop(); return _context.stop();
}
} }
}, _callee, this); }
})); }, null, this);
}
function init(_x) {
return _init.apply(this, arguments);
}
return init;
}()
}; };
return extPolygon; return extPolygon;

View File

@ -15,42 +15,6 @@ var svgEditorExtension_server_moinsave = (function () {
return _typeof(obj); return _typeof(obj);
} }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
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);
});
};
}
function _classCallCheck(instance, Constructor) { function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) { if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function"); throw new TypeError("Cannot call a class as a function");
@ -4684,36 +4648,26 @@ var svgEditorExtension_server_moinsave = (function () {
}; // load from url }; // load from url
svg.load = svg.load = function _callee(ctx, url) {
/*#__PURE__*/ var dom;
function () { return regeneratorRuntime.async(function _callee$(_context) {
var _ref12 = _asyncToGenerator( while (1) {
/*#__PURE__*/ switch (_context.prev = _context.next) {
regeneratorRuntime.mark(function _callee(ctx, url) { case 0:
var dom; _context.next = 2;
return regeneratorRuntime.wrap(function _callee$(_context) { return regeneratorRuntime.awrap(svg.ajax(url, true));
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return svg.ajax(url, true);
case 2: case 2:
dom = _context.sent; dom = _context.sent;
return _context.abrupt("return", svg.loadXml(ctx, dom)); return _context.abrupt("return", svg.loadXml(ctx, dom));
case 4: case 4:
case "end": case "end":
return _context.stop(); return _context.stop();
}
} }
}, _callee); }
})); });
}; // load from xml
return function (_x2, _x3) {
return _ref12.apply(this, arguments);
};
}(); // load from xml
svg.loadXml = function (ctx, xml) { svg.loadXml = function (ctx, xml) {
@ -4934,9 +4888,9 @@ var svgEditorExtension_server_moinsave = (function () {
checkPath: function checkPath(element, ctx) { checkPath: function checkPath(element, ctx) {
var _this26 = this; var _this26 = this;
this.events.forEach(function (_ref13, i) { this.events.forEach(function (_ref12, i) {
var x = _ref13.x, var x = _ref12.x,
y = _ref13.y; y = _ref12.y;
if (ctx.isPointInPath && ctx.isPointInPath(x, y)) { if (ctx.isPointInPath && ctx.isPointInPath(x, y)) {
_this26.eventElements[i] = element; _this26.eventElements[i] = element;
@ -4946,9 +4900,9 @@ var svgEditorExtension_server_moinsave = (function () {
checkBoundingBox: function checkBoundingBox(element, bb) { checkBoundingBox: function checkBoundingBox(element, bb) {
var _this27 = this; var _this27 = this;
this.events.forEach(function (_ref14, i) { this.events.forEach(function (_ref13, i) {
var x = _ref14.x, var x = _ref13.x,
y = _ref14.y; y = _ref13.y;
if (bb.isPointInBox(x, y)) { if (bb.isPointInBox(x, y)) {
_this27.eventElements[i] = element; _this27.eventElements[i] = element;
@ -4992,103 +4946,83 @@ var svgEditorExtension_server_moinsave = (function () {
var extServer_moinsave = { var extServer_moinsave = {
name: 'server_moinsave', name: 'server_moinsave',
init: function () { init: function init(_ref) {
var _init = _asyncToGenerator( var $, encode64, importLocale, strings, svgEditor, svgCanvas, saveSvgAction;
/*#__PURE__*/ return regeneratorRuntime.async(function init$(_context2) {
regeneratorRuntime.mark(function _callee2(_ref) { while (1) {
var $, encode64, importLocale, strings, svgEditor, svgCanvas, saveSvgAction; switch (_context2.prev = _context2.next) {
return regeneratorRuntime.wrap(function _callee2$(_context2) { case 0:
while (1) { $ = _ref.$, encode64 = _ref.encode64, importLocale = _ref.importLocale;
switch (_context2.prev = _context2.next) { _context2.next = 3;
case 0: return regeneratorRuntime.awrap(importLocale());
$ = _ref.$, encode64 = _ref.encode64, importLocale = _ref.importLocale;
_context2.next = 3;
return importLocale();
case 3: case 3:
strings = _context2.sent; strings = _context2.sent;
svgEditor = this; svgEditor = this;
svgCanvas = svgEditor.canvas; svgCanvas = svgEditor.canvas;
saveSvgAction = '/+modify'; // Create upload target (hidden iframe) saveSvgAction = '/+modify'; // Create upload target (hidden iframe)
// Hiding by size instead of display to avoid FF console errors // Hiding by size instead of display to avoid FF console errors
// with `getBBox` in browser.js `supportsPathBBox_`) // with `getBBox` in browser.js `supportsPathBBox_`)
/* const target = */ /* const target = */
$("<iframe name=\"output_frame\" title=\"".concat(strings.hiddenframe, "\"\n style=\"width: 0; height: 0;\" src=\"#\"/>")).appendTo('body'); $("<iframe name=\"output_frame\" title=\"".concat(strings.hiddenframe, "\"\n style=\"width: 0; height: 0;\" src=\"#\"/>")).appendTo('body');
svgEditor.setCustomHandlers({ svgEditor.setCustomHandlers({
save: function () { save: function save(win, data) {
var _save = _asyncToGenerator( var svg, qstr, _qstr$substr$split, _qstr$substr$split2, name, svgData, c, datauri, pngData;
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(win, data) {
var svg, qstr, _qstr$substr$split, _qstr$substr$split2, name, svgData, c, datauri, pngData;
return regeneratorRuntime.wrap(function _callee$(_context) { return regeneratorRuntime.async(function save$(_context) {
while (1) { while (1) {
switch (_context.prev = _context.next) { switch (_context.prev = _context.next) {
case 0: case 0:
svg = '<?xml version="1.0"?>\n' + data; svg = '<?xml version="1.0"?>\n' + data;
qstr = $.param.querystring(); qstr = $.param.querystring();
_qstr$substr$split = qstr.substr(9).split('/+get/'), _qstr$substr$split2 = _slicedToArray(_qstr$substr$split, 2), name = _qstr$substr$split2[1]; _qstr$substr$split = qstr.substr(9).split('/+get/'), _qstr$substr$split2 = _slicedToArray(_qstr$substr$split, 2), name = _qstr$substr$split2[1];
svgData = encode64(svg); svgData = encode64(svg);
if (!$('#export_canvas').length) { if (!$('#export_canvas').length) {
$('<canvas>', { $('<canvas>', {
id: 'export_canvas' id: 'export_canvas'
}).hide().appendTo('body'); }).hide().appendTo('body');
}
c = $('#export_canvas')[0];
c.width = svgCanvas.contentW;
c.height = svgCanvas.contentH;
_context.next = 10;
return canvg(c, svg);
case 10:
datauri = c.toDataURL('image/png'); // const {uiStrings} = svgEditor;
pngData = encode64(datauri); // Brett: This encoding seems unnecessary
/* const form = */
$('<form>').attr({
method: 'post',
action: saveSvgAction + '/' + name,
target: 'output_frame'
}).append("\n <input type=\"hidden\" name=\"png_data\" value=\"".concat(pngData, "\">\n <input type=\"hidden\" name=\"filepath\" value=\"").concat(svgData, "\">\n <input type=\"hidden\" name=\"filename\" value=\"drawing.svg\">\n <input type=\"hidden\" name=\"contenttype\" value=\"application/x-svgdraw\">\n ")).appendTo('body').submit().remove();
$.alert(strings.saved);
top.window.location = '/' + name;
case 15:
case "end":
return _context.stop();
} }
}
}, _callee);
}));
function save(_x2, _x3) { c = $('#export_canvas')[0];
return _save.apply(this, arguments); c.width = svgCanvas.contentW;
c.height = svgCanvas.contentH;
_context.next = 10;
return regeneratorRuntime.awrap(canvg(c, svg));
case 10:
datauri = c.toDataURL('image/png'); // const {uiStrings} = svgEditor;
pngData = encode64(datauri); // Brett: This encoding seems unnecessary
/* const form = */
$('<form>').attr({
method: 'post',
action: saveSvgAction + '/' + name,
target: 'output_frame'
}).append("\n <input type=\"hidden\" name=\"png_data\" value=\"".concat(pngData, "\">\n <input type=\"hidden\" name=\"filepath\" value=\"").concat(svgData, "\">\n <input type=\"hidden\" name=\"filename\" value=\"drawing.svg\">\n <input type=\"hidden\" name=\"contenttype\" value=\"application/x-svgdraw\">\n ")).appendTo('body').submit().remove();
$.alert(strings.saved);
top.window.location = '/' + name;
case 15:
case "end":
return _context.stop();
}
} }
});
}
});
return save; case 9:
}() case "end":
}); return _context2.stop();
case 9:
case "end":
return _context2.stop();
}
} }
}, _callee2, this); }
})); }, null, this);
}
function init(_x) {
return _init.apply(this, arguments);
}
return init;
}()
}; };
return extServer_moinsave; return extServer_moinsave;

View File

@ -15,42 +15,6 @@ var svgEditorExtension_server_opensave = (function () {
return _typeof(obj); return _typeof(obj);
} }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
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);
});
};
}
function _classCallCheck(instance, Constructor) { function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) { if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function"); throw new TypeError("Cannot call a class as a function");
@ -4684,36 +4648,26 @@ var svgEditorExtension_server_opensave = (function () {
}; // load from url }; // load from url
svg.load = svg.load = function _callee(ctx, url) {
/*#__PURE__*/ var dom;
function () { return regeneratorRuntime.async(function _callee$(_context) {
var _ref12 = _asyncToGenerator( while (1) {
/*#__PURE__*/ switch (_context.prev = _context.next) {
regeneratorRuntime.mark(function _callee(ctx, url) { case 0:
var dom; _context.next = 2;
return regeneratorRuntime.wrap(function _callee$(_context) { return regeneratorRuntime.awrap(svg.ajax(url, true));
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return svg.ajax(url, true);
case 2: case 2:
dom = _context.sent; dom = _context.sent;
return _context.abrupt("return", svg.loadXml(ctx, dom)); return _context.abrupt("return", svg.loadXml(ctx, dom));
case 4: case 4:
case "end": case "end":
return _context.stop(); return _context.stop();
}
} }
}, _callee); }
})); });
}; // load from xml
return function (_x2, _x3) {
return _ref12.apply(this, arguments);
};
}(); // load from xml
svg.loadXml = function (ctx, xml) { svg.loadXml = function (ctx, xml) {
@ -4934,9 +4888,9 @@ var svgEditorExtension_server_opensave = (function () {
checkPath: function checkPath(element, ctx) { checkPath: function checkPath(element, ctx) {
var _this26 = this; var _this26 = this;
this.events.forEach(function (_ref13, i) { this.events.forEach(function (_ref12, i) {
var x = _ref13.x, var x = _ref12.x,
y = _ref13.y; y = _ref12.y;
if (ctx.isPointInPath && ctx.isPointInPath(x, y)) { if (ctx.isPointInPath && ctx.isPointInPath(x, y)) {
_this26.eventElements[i] = element; _this26.eventElements[i] = element;
@ -4946,9 +4900,9 @@ var svgEditorExtension_server_opensave = (function () {
checkBoundingBox: function checkBoundingBox(element, bb) { checkBoundingBox: function checkBoundingBox(element, bb) {
var _this27 = this; var _this27 = this;
this.events.forEach(function (_ref14, i) { this.events.forEach(function (_ref13, i) {
var x = _ref14.x, var x = _ref13.x,
y = _ref14.y; y = _ref13.y;
if (bb.isPointInBox(x, y)) { if (bb.isPointInBox(x, y)) {
_this27.eventElements[i] = element; _this27.eventElements[i] = element;
@ -4990,363 +4944,334 @@ var svgEditorExtension_server_opensave = (function () {
}; };
} }
/**
* ext-server_opensave.js
*
* @license MIT
*
* @copyright 2010 Alexis Deveria
*
*/
var extServer_opensave = { var extServer_opensave = {
name: 'server_opensave', name: 'server_opensave',
init: function () { init: function init(_ref) {
var _init = _asyncToGenerator( var $, decode64, encode64, importLocale, strings, svgEditor, _svgEditor$curConfig, extPath, avoidClientSide, avoidClientSideDownload, avoidClientSideOpen, svgCanvas, getFileNameFromTitle, xhtmlEscape, clientDownloadSupport, saveSvgAction, saveImgAction, cancelled, openSvgAction, importSvgAction, importImgAction, openSvgForm, importSvgForm, importImgForm, rebuildInput;
/*#__PURE__*/
regeneratorRuntime.mark(function _callee5(_ref) {
var $, decode64, encode64, importLocale, strings, svgEditor, _svgEditor$curConfig, extPath, avoidClientSide, avoidClientSideDownload, avoidClientSideOpen, svgCanvas, getFileNameFromTitle, xhtmlEscape, clientDownloadSupport, saveSvgAction, saveImgAction, cancelled, openSvgAction, importSvgAction, importImgAction, openSvgForm, importSvgForm, importImgForm, rebuildInput;
return regeneratorRuntime.wrap(function _callee5$(_context5) { return regeneratorRuntime.async(function init$(_context5) {
while (1) { while (1) {
switch (_context5.prev = _context5.next) { switch (_context5.prev = _context5.next) {
case 0: case 0:
rebuildInput = function _ref7(form) { rebuildInput = function _ref5(form) {
form.empty(); form.empty();
var inp = $('<input type="file" name="svg_file">').appendTo(form); var inp = $('<input type="file" name="svg_file">').appendTo(form);
/**
* Submit the form, empty its contents for reuse and show
* uploading message.
* @returns {Promise<void>}
*/
function submit() {
return _submit.apply(this, arguments);
}
function _submit() {
_submit = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee4() {
return regeneratorRuntime.wrap(function _callee4$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
// This submits the form, which returns the file data using `svgEditor.processFile()`
form.submit();
rebuildInput(form);
_context4.next = 4;
return $.process_cancel(strings.uploading);
case 4:
cancelled = true;
$('#dialog_box').hide();
case 6:
case "end":
return _context4.stop();
}
}
}, _callee4);
}));
return _submit.apply(this, arguments);
}
if (form[0] === openSvgForm[0]) {
inp.change(
/*#__PURE__*/
_asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee2() {
var ok;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return svgEditor.openPrep();
case 2:
ok = _context2.sent;
if (ok) {
_context2.next = 6;
break;
}
rebuildInput(form);
return _context2.abrupt("return");
case 6:
_context2.next = 8;
return submit();
case 8:
case "end":
return _context2.stop();
}
}
}, _callee2);
})));
} else {
inp.change(
/*#__PURE__*/
_asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee3() {
return regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return submit();
case 2:
case "end":
return _context3.stop();
}
}
}, _callee3);
})));
}
};
clientDownloadSupport = function _ref6(filename, suffix, uri) {
if (avoidClientSide || avoidClientSideDownload) {
return false;
}
var support = $('<a>')[0].download === '';
var a;
if (support) {
a = $('<a>hidden</a>').attr({
download: (filename || 'image') + suffix,
href: uri
}).css('display', 'none').appendTo('body');
a[0].click();
return true;
}
return false;
};
xhtmlEscape = function _ref5(str) {
return str.replace(/&(?!amp;)/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;'); // < is actually disallowed above anyways
};
getFileNameFromTitle = function _ref4() {
var title = svgCanvas.getDocumentTitle(); // We convert (to underscore) only those disallowed Win7 file name characters
return title.trim().replace(/[/\\:*?"<>|]/g, '_');
};
$ = _ref.$, decode64 = _ref.decode64, encode64 = _ref.encode64, importLocale = _ref.importLocale;
_context5.next = 7;
return importLocale();
case 7:
strings = _context5.sent;
svgEditor = this;
_svgEditor$curConfig = svgEditor.curConfig, extPath = _svgEditor$curConfig.extPath, avoidClientSide = _svgEditor$curConfig.avoidClientSide, avoidClientSideDownload = _svgEditor$curConfig.avoidClientSideDownload, avoidClientSideOpen = _svgEditor$curConfig.avoidClientSideOpen, svgCanvas = svgEditor.canvas;
/** /**
* * Submit the form, empty its contents for reuse and show
* @returns {string} * uploading message.
* @returns {Promise<void>}
*/ */
saveSvgAction = extPath + 'filesave.php', saveImgAction = extPath + 'filesave.php'; // Create upload target (hidden iframe) function submit() {
return regeneratorRuntime.async(function submit$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
// This submits the form, which returns the file data using `svgEditor.processFile()`
form.submit();
rebuildInput(form);
_context2.next = 4;
return regeneratorRuntime.awrap($.process_cancel(strings.uploading));
cancelled = false; // Hiding by size instead of display to avoid FF console errors case 4:
// with `getBBox` in browser.js `supportsPathBBox_`) cancelled = true;
$('#dialog_box').hide();
$("<iframe name=\"output_frame\" title=\"".concat(strings.hiddenframe, "\"\n style=\"width: 0; height: 0;\" src=\"#\"/>")).appendTo('body'); case 6:
svgEditor.setCustomHandlers({ case "end":
save: function save(win, data) { return _context2.stop();
var svg = '<?xml version="1.0" encoding="UTF-8"?>\n' + data, }
// Firefox doesn't seem to know it is UTF-8 (no matter whether we use or skip the clientDownload code) despite the Content-Disposition header containing UTF-8, but adding the encoding works
filename = getFileNameFromTitle();
if (clientDownloadSupport(filename, '.svg', 'data:image/svg+xml;charset=UTF-8;base64,' + encode64(svg))) {
return;
} }
});
$('<form>').attr({
method: 'post',
action: saveSvgAction,
target: 'output_frame'
}).append("\n <input type=\"hidden\" name=\"output_svg\" value=\"".concat(xhtmlEscape(svg), "\">\n <input type=\"hidden\" name=\"filename\" value=\"").concat(xhtmlEscape(filename), "\">\n ")).appendTo('body').submit().remove();
},
exportPDF: function exportPDF(win, data) {
var filename = getFileNameFromTitle(),
datauri = data.output;
if (clientDownloadSupport(filename, '.pdf', datauri)) {
return;
}
$('<form>').attr({
method: 'post',
action: saveImgAction,
target: 'output_frame'
}).append("\n <input type=\"hidden\" name=\"output_img\" value=\"".concat(datauri, "\">\n <input type=\"hidden\" name=\"mime\" value=\"application/pdf\">\n <input type=\"hidden\" name=\"filename\" value=\"").concat(xhtmlEscape(filename), "\">\n ")).appendTo('body').submit().remove();
},
// Todo: Integrate this extension with a new built-in exportWindowType, "download"
exportImage: function () {
var _exportImage = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(win, data) {
var issues, mimeType, quality, c, datauri, pre, note, filename, suffix;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
issues = data.issues, mimeType = data.mimeType, quality = data.quality;
if (!$('#export_canvas').length) {
$('<canvas>', {
id: 'export_canvas'
}).hide().appendTo('body');
}
c = $('#export_canvas')[0];
c.width = svgCanvas.contentW;
c.height = svgCanvas.contentH;
_context.next = 7;
return canvg(c, data.svg);
case 7:
datauri = quality ? c.toDataURL(mimeType, quality) : c.toDataURL(mimeType); // {uiStrings} = svgEditor;
// Check if there are issues
note = '';
if (issues.length) {
pre = "\n \u2022 "; // Bullet
note += '\n\n' + pre + issues.join(pre);
}
if (!note.length) {
_context.next = 13;
break;
}
_context.next = 13;
return $.alert(note);
case 13:
filename = getFileNameFromTitle();
suffix = '.' + data.type.toLowerCase();
if (!clientDownloadSupport(filename, suffix, datauri)) {
_context.next = 17;
break;
}
return _context.abrupt("return");
case 17:
$('<form>').attr({
method: 'post',
action: saveImgAction,
target: 'output_frame'
}).append("\n <input type=\"hidden\" name=\"output_img\" value=\"".concat(datauri, "\">\n <input type=\"hidden\" name=\"mime\" value=\"").concat(mimeType, "\">\n <input type=\"hidden\" name=\"filename\" value=\"").concat(xhtmlEscape(filename), "\">\n ")).appendTo('body').submit().remove();
case 18:
case "end":
return _context.stop();
}
}
}, _callee);
}));
function exportImage(_x2, _x3) {
return _exportImage.apply(this, arguments);
}
return exportImage;
}()
}); // Do nothing if client support is found
if (!(window.FileReader && !avoidClientSideOpen)) {
_context5.next = 16;
break;
} }
return _context5.abrupt("return"); if (form[0] === openSvgForm[0]) {
inp.change(function _callee() {
var ok;
return regeneratorRuntime.async(function _callee$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return regeneratorRuntime.awrap(svgEditor.openPrep());
case 16: case 2:
// Change these to appropriate script file ok = _context3.sent;
openSvgAction = extPath + 'fileopen.php?type=load_svg';
importSvgAction = extPath + 'fileopen.php?type=import_svg';
importImgAction = extPath + 'fileopen.php?type=import_img'; // Set up function for PHP uploader to use
svgEditor.processFile = function (str64, type) { if (ok) {
var xmlstr; _context3.next = 6;
break;
}
if (cancelled) { rebuildInput(form);
cancelled = false; return _context3.abrupt("return");
case 6:
_context3.next = 8;
return regeneratorRuntime.awrap(submit());
case 8:
case "end":
return _context3.stop();
}
}
});
});
} else {
inp.change(function _callee2() {
return regeneratorRuntime.async(function _callee2$(_context4) {
while (1) {
switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return regeneratorRuntime.awrap(submit());
case 2:
case "end":
return _context4.stop();
}
}
});
});
}
};
clientDownloadSupport = function _ref4(filename, suffix, uri) {
if (avoidClientSide || avoidClientSideDownload) {
return false;
}
var support = $('<a>')[0].download === '';
var a;
if (support) {
a = $('<a>hidden</a>').attr({
download: (filename || 'image') + suffix,
href: uri
}).css('display', 'none').appendTo('body');
a[0].click();
return true;
}
return false;
};
xhtmlEscape = function _ref3(str) {
return str.replace(/&(?!amp;)/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;'); // < is actually disallowed above anyways
};
getFileNameFromTitle = function _ref2() {
var title = svgCanvas.getDocumentTitle(); // We convert (to underscore) only those disallowed Win7 file name characters
return title.trim().replace(/[/\\:*?"<>|]/g, '_');
};
$ = _ref.$, decode64 = _ref.decode64, encode64 = _ref.encode64, importLocale = _ref.importLocale;
_context5.next = 7;
return regeneratorRuntime.awrap(importLocale());
case 7:
strings = _context5.sent;
svgEditor = this;
_svgEditor$curConfig = svgEditor.curConfig, extPath = _svgEditor$curConfig.extPath, avoidClientSide = _svgEditor$curConfig.avoidClientSide, avoidClientSideDownload = _svgEditor$curConfig.avoidClientSideDownload, avoidClientSideOpen = _svgEditor$curConfig.avoidClientSideOpen, svgCanvas = svgEditor.canvas;
/**
*
* @returns {string}
*/
saveSvgAction = extPath + 'filesave.php', saveImgAction = extPath + 'filesave.php'; // Create upload target (hidden iframe)
cancelled = false; // Hiding by size instead of display to avoid FF console errors
// with `getBBox` in browser.js `supportsPathBBox_`)
$("<iframe name=\"output_frame\" title=\"".concat(strings.hiddenframe, "\"\n style=\"width: 0; height: 0;\" src=\"#\"/>")).appendTo('body');
svgEditor.setCustomHandlers({
save: function save(win, data) {
var svg = '<?xml version="1.0" encoding="UTF-8"?>\n' + data,
// Firefox doesn't seem to know it is UTF-8 (no matter whether we use or skip the clientDownload code) despite the Content-Disposition header containing UTF-8, but adding the encoding works
filename = getFileNameFromTitle();
if (clientDownloadSupport(filename, '.svg', 'data:image/svg+xml;charset=UTF-8;base64,' + encode64(svg))) {
return; return;
} }
$('#dialog_box').hide(); $('<form>').attr({
method: 'post',
action: saveSvgAction,
target: 'output_frame'
}).append("\n <input type=\"hidden\" name=\"output_svg\" value=\"".concat(xhtmlEscape(svg), "\">\n <input type=\"hidden\" name=\"filename\" value=\"").concat(xhtmlEscape(filename), "\">\n ")).appendTo('body').submit().remove();
},
exportPDF: function exportPDF(win, data) {
var filename = getFileNameFromTitle(),
datauri = data.output;
if (type !== 'import_img') { if (clientDownloadSupport(filename, '.pdf', datauri)) {
xmlstr = decode64(str64); return;
} }
switch (type) { $('<form>').attr({
case 'load_svg': method: 'post',
svgCanvas.clear(); action: saveImgAction,
svgCanvas.setSvgString(xmlstr); target: 'output_frame'
svgEditor.updateCanvas(); }).append("\n <input type=\"hidden\" name=\"output_img\" value=\"".concat(datauri, "\">\n <input type=\"hidden\" name=\"mime\" value=\"application/pdf\">\n <input type=\"hidden\" name=\"filename\" value=\"").concat(xhtmlEscape(filename), "\">\n ")).appendTo('body').submit().remove();
break; },
// Todo: Integrate this extension with a new built-in exportWindowType, "download"
exportImage: function exportImage(win, data) {
var issues, mimeType, quality, c, datauri, pre, note, filename, suffix;
return regeneratorRuntime.async(function exportImage$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
issues = data.issues, mimeType = data.mimeType, quality = data.quality;
case 'import_svg': if (!$('#export_canvas').length) {
svgCanvas.importSvgString(xmlstr); $('<canvas>', {
svgEditor.updateCanvas(); id: 'export_canvas'
break; }).hide().appendTo('body');
}
case 'import_img': c = $('#export_canvas')[0];
svgCanvas.setGoodImage(str64); c.width = svgCanvas.contentW;
break; c.height = svgCanvas.contentH;
} _context.next = 7;
}; // Create upload form return regeneratorRuntime.awrap(canvg(c, data.svg));
case 7:
datauri = quality ? c.toDataURL(mimeType, quality) : c.toDataURL(mimeType); // {uiStrings} = svgEditor;
// Check if there are issues
note = '';
if (issues.length) {
pre = "\n \u2022 "; // Bullet
note += '\n\n' + pre + issues.join(pre);
}
if (!note.length) {
_context.next = 13;
break;
}
_context.next = 13;
return regeneratorRuntime.awrap($.alert(note));
case 13:
filename = getFileNameFromTitle();
suffix = '.' + data.type.toLowerCase();
if (!clientDownloadSupport(filename, suffix, datauri)) {
_context.next = 17;
break;
}
return _context.abrupt("return");
case 17:
$('<form>').attr({
method: 'post',
action: saveImgAction,
target: 'output_frame'
}).append("\n <input type=\"hidden\" name=\"output_img\" value=\"".concat(datauri, "\">\n <input type=\"hidden\" name=\"mime\" value=\"").concat(mimeType, "\">\n <input type=\"hidden\" name=\"filename\" value=\"").concat(xhtmlEscape(filename), "\">\n ")).appendTo('body').submit().remove();
case 18:
case "end":
return _context.stop();
}
}
});
}
}); // Do nothing if client support is found
if (!(window.FileReader && !avoidClientSideOpen)) {
_context5.next = 16;
break;
}
return _context5.abrupt("return");
case 16:
// Change these to appropriate script file
openSvgAction = extPath + 'fileopen.php?type=load_svg';
importSvgAction = extPath + 'fileopen.php?type=import_svg';
importImgAction = extPath + 'fileopen.php?type=import_img'; // Set up function for PHP uploader to use
svgEditor.processFile = function (str64, type) {
var xmlstr;
if (cancelled) {
cancelled = false;
return;
}
$('#dialog_box').hide();
if (type !== 'import_img') {
xmlstr = decode64(str64);
}
switch (type) {
case 'load_svg':
svgCanvas.clear();
svgCanvas.setSvgString(xmlstr);
svgEditor.updateCanvas();
break;
case 'import_svg':
svgCanvas.importSvgString(xmlstr);
svgEditor.updateCanvas();
break;
case 'import_img':
svgCanvas.setGoodImage(str64);
break;
}
}; // Create upload form
openSvgForm = $('<form>'); openSvgForm = $('<form>');
openSvgForm.attr({ openSvgForm.attr({
enctype: 'multipart/form-data', enctype: 'multipart/form-data',
method: 'post', method: 'post',
action: openSvgAction, action: openSvgAction,
target: 'output_frame' target: 'output_frame'
}); // Create import form }); // Create import form
importSvgForm = openSvgForm.clone().attr('action', importSvgAction); // Create image form importSvgForm = openSvgForm.clone().attr('action', importSvgAction); // Create image form
importImgForm = openSvgForm.clone().attr('action', importImgAction); // It appears necessary to rebuild this input every time a file is importImgForm = openSvgForm.clone().attr('action', importImgAction); // It appears necessary to rebuild this input every time a file is
// selected so the same file can be picked and the change event can fire. // selected so the same file can be picked and the change event can fire.
/** /**
* *
* @param {external:jQuery} form * @param {external:jQuery} form
* @returns {void} * @returns {void}
*/ */
// Create the input elements // Create the input elements
rebuildInput(openSvgForm); rebuildInput(openSvgForm);
rebuildInput(importSvgForm); rebuildInput(importSvgForm);
rebuildInput(importImgForm); // Add forms to buttons rebuildInput(importImgForm); // Add forms to buttons
$('#tool_open').show().prepend(openSvgForm); $('#tool_open').show().prepend(openSvgForm);
$('#tool_import').show().prepend(importSvgForm); $('#tool_import').show().prepend(importSvgForm);
$('#tool_image').prepend(importImgForm); $('#tool_image').prepend(importImgForm);
case 30: case 30:
case "end": case "end":
return _context5.stop(); return _context5.stop();
}
} }
}, _callee5, this); }
})); }, null, this);
}
function init(_x) {
return _init.apply(this, arguments);
}
return init;
}()
}; };
return extServer_opensave; return extServer_opensave;

View File

@ -1,42 +1,6 @@
var svgEditorExtension_shapes = (function () { var svgEditorExtension_shapes = (function () {
'use strict'; 'use strict';
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
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);
});
};
}
function _slicedToArray(arr, i) { function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
} }
@ -89,339 +53,329 @@ var svgEditorExtension_shapes = (function () {
*/ */
var extShapes = { var extShapes = {
name: 'shapes', name: 'shapes',
init: function () { init: function init(_ref) {
var _init = _asyncToGenerator( var $, importLocale, strings, svgEditor, canv, svgroot, lastBBox, categories, library, modeId, startClientPos, currentD, curShapeId, curShape, startX, startY, curLib, loadIcons, makeButtons, loadLibrary, buttons;
/*#__PURE__*/ return regeneratorRuntime.async(function init$(_context) {
regeneratorRuntime.mark(function _callee(_ref) { while (1) {
var $, importLocale, strings, svgEditor, canv, svgroot, lastBBox, categories, library, modeId, startClientPos, currentD, curShapeId, curShape, startX, startY, curLib, loadIcons, makeButtons, loadLibrary, buttons; switch (_context.prev = _context.next) {
return regeneratorRuntime.wrap(function _callee$(_context) { case 0:
while (1) { loadLibrary = function _ref8(catId) {
switch (_context.prev = _context.next) { var lib = library[catId];
case 0:
loadLibrary = function _ref8(catId) {
var lib = library[catId];
if (!lib) { if (!lib) {
$('#shape_buttons').html(strings.loading); $('#shape_buttons').html(strings.loading);
$.getJSON(svgEditor.curConfig.extIconsPath + 'shapelib/' + catId + '.json', function (result) { $.getJSON(svgEditor.curConfig.extIconsPath + 'shapelib/' + catId + '.json', function (result) {
curLib = library[catId] = { curLib = library[catId] = {
data: result.data, data: result.data,
size: result.size, size: result.size,
fill: result.fill fill: result.fill
};
makeButtons(catId, result);
loadIcons();
});
return;
}
curLib = lib;
if (!lib.buttons.length) {
makeButtons(catId, lib);
}
loadIcons();
};
makeButtons = function _ref7(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 = Object.entries(data).map(function (_ref2) {
var _ref3 = _slicedToArray(_ref2, 2),
id = _ref3[0],
pathD = _ref3[1];
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
return iconBtn[0];
});
};
loadIcons = function _ref6() {
$('#shape_buttons').empty().append(curLib.buttons);
};
$ = _ref.$, importLocale = _ref.importLocale;
_context.next = 6;
return importLocale();
case 6:
strings = _context.sent;
svgEditor = this;
canv = svgEditor.canvas;
svgroot = canv.getRootElem();
lastBBox = {}; // This populates the category list
categories = strings.categories;
library = {
basic: {
data: {
heart: 'm150,73c61,-175 300,0 0,225c-300,-225 -61,-400 0,-225z',
frame: 'm0,0l300,0l0,300l-300,0zm35,-265l0,230l230,0l0,-230z',
donut: 'm1,150l0,0c0,-82.29042 66.70958,-149 149,-149l0,0c39.51724,0 77.41599,15.69816 105.35889,43.64108c27.94293,27.94293 43.64111,65.84165 43.64111,105.35892l0,0c0,82.29041 -66.70958,149 -149,149l0,0c-82.29041,0 -149,-66.70959 -149,-149zm74.5,0l0,0c0,41.1452 33.35481,74.5 74.5,74.5c41.14522,0 74.5,-33.3548 74.5,-74.5c0,-41.1452 -33.3548,-74.5 -74.5,-74.5l0,0c-41.14519,0 -74.5,33.35481 -74.5,74.5z',
triangle: 'm1,280.375l149,-260.75l149,260.75z',
right_triangle: 'm1,299l0,-298l298,298z',
diamond: 'm1,150l149,-149l149,149l-149,149l-149,-149z',
pentagon: 'm1.00035,116.97758l148.99963,-108.4053l148.99998,108.4053l-56.91267,175.4042l-184.1741,0l-56.91284,-175.4042z',
hexagon: 'm1,149.99944l63.85715,-127.71428l170.28572,0l63.85713,127.71428l-63.85713,127.71428l-170.28572,0l-63.85715,-127.71428z',
septagon1: 'm0.99917,191.06511l29.51249,-127.7108l119.48833,-56.83673l119.48836,56.83673l29.51303,127.7108l-82.69087,102.41679l-132.62103,0l-82.69031,-102.41679z',
heptagon: 'm1,88.28171l87.28172,-87.28171l123.43653,0l87.28172,87.28171l0,123.43654l-87.28172,87.28172l-123.43653,0l-87.28172,-87.28172l0,-123.43654z',
decagon: 'm1,150.00093l28.45646,-88.40318l74.49956,-54.63682l92.08794,0l74.50002,54.63682l28.45599,88.40318l-28.45599,88.40318l-74.50002,54.63681l-92.08794,0l-74.49956,-54.63681l-28.45646,-88.40318z',
dodecagon: 'm1,110.07421l39.92579,-69.14842l69.14842,-39.92579l79.85159,0l69.14842,39.92579l39.92578,69.14842l0,79.85159l-39.92578,69.14842l-69.14842,39.92578l-79.85159,0l-69.14842,-39.92578l-39.92579,-69.14842l0,-79.85159z',
star_points_5: 'm1,116.58409l113.82668,0l35.17332,-108.13487l35.17334,108.13487l113.82666,0l-92.08755,66.83026l35.17514,108.13487l-92.08759,-66.83208l-92.08757,66.83208l35.17515,-108.13487l-92.08758,-66.83026z',
trapezoid: 'm1,299l55.875,-298l186.25001,0l55.87498,298z',
arrow_up: 'm1.49805,149.64304l148.50121,-148.00241l148.50121,148.00241l-74.25061,0l0,148.71457l-148.5012,0l0,-148.71457z',
vertical_scrool: 'm37.375,261.625l0,-242.9375l0,0c0,-10.32083 8.36669,-18.6875 18.6875,-18.6875l224.25,0c10.32083,0 18.6875,8.36667 18.6875,18.6875c0,10.32081 -8.36667,18.6875 -18.6875,18.6875l-18.6875,0l0,242.9375c0,10.32083 -8.36668,18.6875 -18.6875,18.6875l-224.25,0l0,0c-10.32083,0 -18.6875,-8.36667 -18.6875,-18.6875c0,-10.32083 8.36667,-18.6875 18.6875,-18.6875zm37.375,-261.625l0,0c10.32081,0 18.6875,8.36667 18.6875,18.6875c0,10.32081 -8.36669,18.6875 -18.6875,18.6875c-5.1604,0 -9.34375,-4.18335 -9.34375,-9.34375c0,-5.16041 4.18335,-9.34375 9.34375,-9.34375l18.6875,0m186.875,18.6875l-205.5625,0m-37.375,224.25l0,0c5.1604,0 9.34375,4.18335 9.34375,9.34375c0,5.1604 -4.18335,9.34375 -9.34375,9.34375l18.6875,0m-18.6875,18.6875l0,0c10.32081,0 18.6875,-8.36667 18.6875,-18.6875l0,-18.6875',
smiley: 'm68.49886,214.78838q81.06408,55.67332 161.93891,0m-144.36983,-109.9558c0,-8.60432 6.97517,-15.57949 15.57948,-15.57949c8.60431,0 15.57948,6.97517 15.57948,15.57949c0,8.60431 -6.97517,15.57947 -15.57948,15.57947c-8.60431,0 -15.57948,-6.97516 -15.57948,-15.57947m95.83109,0c0,-8.60432 6.97517,-15.57949 15.57948,-15.57949c8.60431,0 15.57947,6.97517 15.57947,15.57949c0,8.60431 -6.97516,15.57947 -15.57947,15.57947c-8.60429,0 -15.57948,-6.97516 -15.57948,-15.57947m-181.89903,44.73038l0,0c0,-82.60133 66.96162,-149.56296 149.56296,-149.56296c82.60135,0 149.56296,66.96162 149.56296,149.56296c0,82.60135 -66.96161,149.56296 -149.56296,149.56296c-82.60133,0 -149.56296,-66.96161 -149.56296,-149.56296zm0,0l0,0c0,-82.60133 66.96162,-149.56296 149.56296,-149.56296c82.60135,0 149.56296,66.96162 149.56296,149.56296c0,82.60135 -66.96161,149.56296 -149.56296,149.56296c-82.60133,0 -149.56296,-66.96161 -149.56296,-149.56296z',
left_braket: 'm174.24565,298.5c-13.39009,0 -24.24489,-1.80908 -24.24489,-4.04065l0,-140.4187c0,-2.23158 -10.85481,-4.04065 -24.2449,-4.04065l0,0c13.39009,0 24.2449,-1.80907 24.2449,-4.04065l0,-140.4187l0,0c0,-2.23159 10.8548,-4.04066 24.24489,-4.04066',
uml_actor: 'm40.5,100l219,0m-108.99991,94.00006l107,105m-107.00009,-106.00006l-100,106m99.5,-231l0,125m33.24219,-158.75781c0,18.35916 -14.88303,33.24219 -33.24219,33.24219c-18.35916,0 -33.2422,-14.88303 -33.2422,-33.24219c0.00002,-18.35915 14.88304,-33.24219 33.2422,-33.24219c18.35916,0 33.24219,14.88304 33.24219,33.24219z',
dialog_balloon_1: 'm0.99786,35.96579l0,0c0,-19.31077 15.28761,-34.96524 34.14583,-34.96524l15.52084,0l0,0l74.50001,0l139.68748,0c9.05606,0 17.74118,3.68382 24.14478,10.24108c6.40356,6.55726 10.00107,15.45081 10.00107,24.72416l0,87.41311l0,0l0,52.44785l0,0c0,19.31078 -15.2876,34.96524 -34.14584,34.96524l-139.68748,0l-97.32507,88.90848l22.82506,-88.90848l-15.52084,0c-18.85822,0 -34.14583,-15.65446 -34.14583,-34.96524l0,0l0,-52.44785l0,0z',
cloud: 'm182.05086,34.31005c-0.64743,0.02048 -1.27309,0.07504 -1.92319,0.13979c-10.40161,1.03605 -19.58215,7.63722 -24.24597,17.4734l-2.47269,7.44367c0.53346,-2.57959 1.35258,-5.08134 2.47269,-7.44367c-8.31731,-8.61741 -19.99149,-12.59487 -31.52664,-10.72866c-11.53516,1.8662 -21.55294,9.3505 -27.02773,20.19925c-15.45544,-9.51897 -34.72095,-8.94245 -49.62526,1.50272c-14.90431,10.44516 -22.84828,28.93916 -20.43393,47.59753l1.57977,7.58346c-0.71388,-2.48442 -1.24701,-5.01186 -1.57977,-7.58346l-0.2404,0.69894c-12.95573,1.4119 -23.58103,11.46413 -26.34088,24.91708c-2.75985,13.45294 2.9789,27.25658 14.21789,34.21291l17.54914,4.26352c-6.1277,0.50439 -12.24542,-0.9808 -17.54914,-4.26352c-8.66903,9.71078 -10.6639,24.08736 -4.94535,35.96027c5.71854,11.87289 17.93128,18.70935 30.53069,17.15887l7.65843,-2.02692c-2.46413,1.0314 -5.02329,1.70264 -7.65843,2.02692c7.15259,13.16728 19.01251,22.77237 32.93468,26.5945c13.92217,3.82214 28.70987,1.56322 41.03957,-6.25546c10.05858,15.86252 27.91113,24.19412 45.81322,21.38742c17.90208,-2.8067 32.66954,-16.26563 37.91438,-34.52742l1.82016,-10.20447c-0.27254,3.46677 -0.86394,6.87508 -1.82016,10.20447c12.31329,8.07489 27.80199,8.52994 40.52443,1.18819c12.72244,-7.34175 20.6609,-21.34155 20.77736,-36.58929l-4.56108,-22.7823l-17.96776,-15.41455c13.89359,8.70317 22.6528,21.96329 22.52884,38.19685c16.5202,0.17313 30.55292,-13.98268 36.84976,-30.22897c6.29684,-16.24631 3.91486,-34.76801 -6.2504,-48.68089c4.21637,-10.35873 3.96622,-22.14172 -0.68683,-32.29084c-4.65308,-10.14912 -13.23602,-17.69244 -23.55914,-20.65356c-2.31018,-13.45141 -11.83276,-24.27162 -24.41768,-27.81765c-12.58492,-3.54603 -25.98557,0.82654 -34.41142,11.25287l-5.11707,8.63186c1.30753,-3.12148 3.01521,-6.03101 5.11707,-8.63186c-5.93959,-8.19432 -15.2556,-12.8181 -24.96718,-12.51096z',
cylinder: 'm299.0007,83.77844c0,18.28676 -66.70958,33.11111 -149.00002,33.11111m149.00002,-33.11111l0,0c0,18.28676 -66.70958,33.11111 -149.00002,33.11111c-82.29041,0 -148.99997,-14.82432 -148.99997,-33.11111m0,0l0,0c0,-18.28674 66.70956,-33.1111 148.99997,-33.1111c82.29044,0 149.00002,14.82436 149.00002,33.1111l0,132.44449c0,18.28674 -66.70958,33.11105 -149.00002,33.11105c-82.29041,0 -148.99997,-14.82431 -148.99997,-33.11105z',
arrow_u_turn: 'm1.00059,299.00055l0,-167.62497l0,0c0,-72.00411 58.37087,-130.37499 130.375,-130.37499l0,0l0,0c34.57759,0 67.73898,13.7359 92.18906,38.18595c24.45006,24.45005 38.18593,57.61144 38.18593,92.18904l0,18.625l37.24997,0l-74.49995,74.50002l-74.50002,-74.50002l37.25,0l0,-18.625c0,-30.8589 -25.0161,-55.87498 -55.87498,-55.87498l0,0l0,0c-30.85892,0 -55.875,25.01608 -55.875,55.87498l0,167.62497z',
arrow_left_up: 'm0.99865,224.5l74.50004,-74.5l0,37.25l111.74991,0l0,-111.75l-37.25,0l74.5,-74.5l74.5,74.5l-37.25,0l0,186.25l-186.24989,0l0,37.25l-74.50005,-74.5z',
maximize: 'm1.00037,150.34581l55.30305,-55.30267l0,27.65093l22.17356,0l0,-44.21833l44.21825,0l0,-22.17357l-27.65095,0l55.30267,-55.30292l55.3035,55.30292l-27.65175,0l0,22.17357l44.21835,0l0,44.21833l22.17357,0l0,-27.65093l55.30345,55.30267l-55.30345,55.3035l0,-27.65175l-22.17357,0l0,44.21834l-44.21835,0l0,22.17355l27.65175,0l-55.3035,55.30348l-55.30267,-55.30348l27.65095,0l0,-22.17355l-44.21825,0l0,-44.21834l-22.17356,0l0,27.65175l-55.30305,-55.3035z',
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 = {};
curLib = library.basic;
/**
*
* @returns {void}
*/
buttons = [{
id: 'tool_shapelib',
icon: svgEditor.curConfig.extIconsPath + 'shapes.png',
type: 'mode_flyout',
// _flyout
position: 6,
events: {
click: function click() {
canv.setMode(modeId);
}
}
}];
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("\n #shape_buttons {\n overflow: auto;\n width: 180px;\n max-height: 300px;\n display: table-cell;\n vertical-align: middle;\n }\n #shape_cats {\n min-width: 110px;\n display: table-cell;\n vertical-align: middle;\n height: 300px;\n }\n #shape_cats > div {\n line-height: 1em;\n padding: .5em;\n border:1px solid #B0B0B0;\n background: #E8E8E8;\n margin-bottom: -1px;\n }\n #shape_cats div:hover {\n background: #FFFFCC;\n }\n #shape_cats div.current {\n font-weight: bold;\n }\n ").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
$('#shape_buttons').mouseup(function (evt) {
var btn = $(evt.target).closest('div.tool_button');
if (!btn.length) {
return;
}
var copy = btn.children().clone();
shower.children(':not(.flyout_arrow_horiz)').remove();
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
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
var cats = {};
Object.entries(categories).forEach(function (_ref4) {
var _ref5 = _slicedToArray(_ref4, 2),
o = _ref5[0],
categoryName = _ref5[1];
cats['#shape_cats [data-cat="' + o + '"]'] = categoryName;
});
this.setStrings('content', cats);
},
mouseDown: function mouseDown(opts) {
var mode = canv.getMode();
if (mode !== modeId) {
return undefined;
}
startX = opts.start_x;
var x = startX;
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,
attr: {
d: currentD,
id: canv.getNextId(),
opacity: curStyle.opacity / 2,
style: 'pointer-events:none'
}
}); // 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 = */
canv.getTransformList(curShape);
lastBBox = curShape.getBBox();
return {
started: true
}; };
}, makeButtons(catId, result);
mouseMove: function mouseMove(opts) { loadIcons();
var mode = canv.getMode(); });
return;
}
if (mode !== modeId) { curLib = lib;
if (!lib.buttons.length) {
makeButtons(catId, lib);
}
loadIcons();
};
makeButtons = function _ref7(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 = Object.entries(data).map(function (_ref2) {
var _ref3 = _slicedToArray(_ref2, 2),
id = _ref3[0],
pathD = _ref3[1];
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
return iconBtn[0];
});
};
loadIcons = function _ref6() {
$('#shape_buttons').empty().append(curLib.buttons);
};
$ = _ref.$, importLocale = _ref.importLocale;
_context.next = 6;
return regeneratorRuntime.awrap(importLocale());
case 6:
strings = _context.sent;
svgEditor = this;
canv = svgEditor.canvas;
svgroot = canv.getRootElem();
lastBBox = {}; // This populates the category list
categories = strings.categories;
library = {
basic: {
data: {
heart: 'm150,73c61,-175 300,0 0,225c-300,-225 -61,-400 0,-225z',
frame: 'm0,0l300,0l0,300l-300,0zm35,-265l0,230l230,0l0,-230z',
donut: 'm1,150l0,0c0,-82.29042 66.70958,-149 149,-149l0,0c39.51724,0 77.41599,15.69816 105.35889,43.64108c27.94293,27.94293 43.64111,65.84165 43.64111,105.35892l0,0c0,82.29041 -66.70958,149 -149,149l0,0c-82.29041,0 -149,-66.70959 -149,-149zm74.5,0l0,0c0,41.1452 33.35481,74.5 74.5,74.5c41.14522,0 74.5,-33.3548 74.5,-74.5c0,-41.1452 -33.3548,-74.5 -74.5,-74.5l0,0c-41.14519,0 -74.5,33.35481 -74.5,74.5z',
triangle: 'm1,280.375l149,-260.75l149,260.75z',
right_triangle: 'm1,299l0,-298l298,298z',
diamond: 'm1,150l149,-149l149,149l-149,149l-149,-149z',
pentagon: 'm1.00035,116.97758l148.99963,-108.4053l148.99998,108.4053l-56.91267,175.4042l-184.1741,0l-56.91284,-175.4042z',
hexagon: 'm1,149.99944l63.85715,-127.71428l170.28572,0l63.85713,127.71428l-63.85713,127.71428l-170.28572,0l-63.85715,-127.71428z',
septagon1: 'm0.99917,191.06511l29.51249,-127.7108l119.48833,-56.83673l119.48836,56.83673l29.51303,127.7108l-82.69087,102.41679l-132.62103,0l-82.69031,-102.41679z',
heptagon: 'm1,88.28171l87.28172,-87.28171l123.43653,0l87.28172,87.28171l0,123.43654l-87.28172,87.28172l-123.43653,0l-87.28172,-87.28172l0,-123.43654z',
decagon: 'm1,150.00093l28.45646,-88.40318l74.49956,-54.63682l92.08794,0l74.50002,54.63682l28.45599,88.40318l-28.45599,88.40318l-74.50002,54.63681l-92.08794,0l-74.49956,-54.63681l-28.45646,-88.40318z',
dodecagon: 'm1,110.07421l39.92579,-69.14842l69.14842,-39.92579l79.85159,0l69.14842,39.92579l39.92578,69.14842l0,79.85159l-39.92578,69.14842l-69.14842,39.92578l-79.85159,0l-69.14842,-39.92578l-39.92579,-69.14842l0,-79.85159z',
star_points_5: 'm1,116.58409l113.82668,0l35.17332,-108.13487l35.17334,108.13487l113.82666,0l-92.08755,66.83026l35.17514,108.13487l-92.08759,-66.83208l-92.08757,66.83208l35.17515,-108.13487l-92.08758,-66.83026z',
trapezoid: 'm1,299l55.875,-298l186.25001,0l55.87498,298z',
arrow_up: 'm1.49805,149.64304l148.50121,-148.00241l148.50121,148.00241l-74.25061,0l0,148.71457l-148.5012,0l0,-148.71457z',
vertical_scrool: 'm37.375,261.625l0,-242.9375l0,0c0,-10.32083 8.36669,-18.6875 18.6875,-18.6875l224.25,0c10.32083,0 18.6875,8.36667 18.6875,18.6875c0,10.32081 -8.36667,18.6875 -18.6875,18.6875l-18.6875,0l0,242.9375c0,10.32083 -8.36668,18.6875 -18.6875,18.6875l-224.25,0l0,0c-10.32083,0 -18.6875,-8.36667 -18.6875,-18.6875c0,-10.32083 8.36667,-18.6875 18.6875,-18.6875zm37.375,-261.625l0,0c10.32081,0 18.6875,8.36667 18.6875,18.6875c0,10.32081 -8.36669,18.6875 -18.6875,18.6875c-5.1604,0 -9.34375,-4.18335 -9.34375,-9.34375c0,-5.16041 4.18335,-9.34375 9.34375,-9.34375l18.6875,0m186.875,18.6875l-205.5625,0m-37.375,224.25l0,0c5.1604,0 9.34375,4.18335 9.34375,9.34375c0,5.1604 -4.18335,9.34375 -9.34375,9.34375l18.6875,0m-18.6875,18.6875l0,0c10.32081,0 18.6875,-8.36667 18.6875,-18.6875l0,-18.6875',
smiley: 'm68.49886,214.78838q81.06408,55.67332 161.93891,0m-144.36983,-109.9558c0,-8.60432 6.97517,-15.57949 15.57948,-15.57949c8.60431,0 15.57948,6.97517 15.57948,15.57949c0,8.60431 -6.97517,15.57947 -15.57948,15.57947c-8.60431,0 -15.57948,-6.97516 -15.57948,-15.57947m95.83109,0c0,-8.60432 6.97517,-15.57949 15.57948,-15.57949c8.60431,0 15.57947,6.97517 15.57947,15.57949c0,8.60431 -6.97516,15.57947 -15.57947,15.57947c-8.60429,0 -15.57948,-6.97516 -15.57948,-15.57947m-181.89903,44.73038l0,0c0,-82.60133 66.96162,-149.56296 149.56296,-149.56296c82.60135,0 149.56296,66.96162 149.56296,149.56296c0,82.60135 -66.96161,149.56296 -149.56296,149.56296c-82.60133,0 -149.56296,-66.96161 -149.56296,-149.56296zm0,0l0,0c0,-82.60133 66.96162,-149.56296 149.56296,-149.56296c82.60135,0 149.56296,66.96162 149.56296,149.56296c0,82.60135 -66.96161,149.56296 -149.56296,149.56296c-82.60133,0 -149.56296,-66.96161 -149.56296,-149.56296z',
left_braket: 'm174.24565,298.5c-13.39009,0 -24.24489,-1.80908 -24.24489,-4.04065l0,-140.4187c0,-2.23158 -10.85481,-4.04065 -24.2449,-4.04065l0,0c13.39009,0 24.2449,-1.80907 24.2449,-4.04065l0,-140.4187l0,0c0,-2.23159 10.8548,-4.04066 24.24489,-4.04066',
uml_actor: 'm40.5,100l219,0m-108.99991,94.00006l107,105m-107.00009,-106.00006l-100,106m99.5,-231l0,125m33.24219,-158.75781c0,18.35916 -14.88303,33.24219 -33.24219,33.24219c-18.35916,0 -33.2422,-14.88303 -33.2422,-33.24219c0.00002,-18.35915 14.88304,-33.24219 33.2422,-33.24219c18.35916,0 33.24219,14.88304 33.24219,33.24219z',
dialog_balloon_1: 'm0.99786,35.96579l0,0c0,-19.31077 15.28761,-34.96524 34.14583,-34.96524l15.52084,0l0,0l74.50001,0l139.68748,0c9.05606,0 17.74118,3.68382 24.14478,10.24108c6.40356,6.55726 10.00107,15.45081 10.00107,24.72416l0,87.41311l0,0l0,52.44785l0,0c0,19.31078 -15.2876,34.96524 -34.14584,34.96524l-139.68748,0l-97.32507,88.90848l22.82506,-88.90848l-15.52084,0c-18.85822,0 -34.14583,-15.65446 -34.14583,-34.96524l0,0l0,-52.44785l0,0z',
cloud: 'm182.05086,34.31005c-0.64743,0.02048 -1.27309,0.07504 -1.92319,0.13979c-10.40161,1.03605 -19.58215,7.63722 -24.24597,17.4734l-2.47269,7.44367c0.53346,-2.57959 1.35258,-5.08134 2.47269,-7.44367c-8.31731,-8.61741 -19.99149,-12.59487 -31.52664,-10.72866c-11.53516,1.8662 -21.55294,9.3505 -27.02773,20.19925c-15.45544,-9.51897 -34.72095,-8.94245 -49.62526,1.50272c-14.90431,10.44516 -22.84828,28.93916 -20.43393,47.59753l1.57977,7.58346c-0.71388,-2.48442 -1.24701,-5.01186 -1.57977,-7.58346l-0.2404,0.69894c-12.95573,1.4119 -23.58103,11.46413 -26.34088,24.91708c-2.75985,13.45294 2.9789,27.25658 14.21789,34.21291l17.54914,4.26352c-6.1277,0.50439 -12.24542,-0.9808 -17.54914,-4.26352c-8.66903,9.71078 -10.6639,24.08736 -4.94535,35.96027c5.71854,11.87289 17.93128,18.70935 30.53069,17.15887l7.65843,-2.02692c-2.46413,1.0314 -5.02329,1.70264 -7.65843,2.02692c7.15259,13.16728 19.01251,22.77237 32.93468,26.5945c13.92217,3.82214 28.70987,1.56322 41.03957,-6.25546c10.05858,15.86252 27.91113,24.19412 45.81322,21.38742c17.90208,-2.8067 32.66954,-16.26563 37.91438,-34.52742l1.82016,-10.20447c-0.27254,3.46677 -0.86394,6.87508 -1.82016,10.20447c12.31329,8.07489 27.80199,8.52994 40.52443,1.18819c12.72244,-7.34175 20.6609,-21.34155 20.77736,-36.58929l-4.56108,-22.7823l-17.96776,-15.41455c13.89359,8.70317 22.6528,21.96329 22.52884,38.19685c16.5202,0.17313 30.55292,-13.98268 36.84976,-30.22897c6.29684,-16.24631 3.91486,-34.76801 -6.2504,-48.68089c4.21637,-10.35873 3.96622,-22.14172 -0.68683,-32.29084c-4.65308,-10.14912 -13.23602,-17.69244 -23.55914,-20.65356c-2.31018,-13.45141 -11.83276,-24.27162 -24.41768,-27.81765c-12.58492,-3.54603 -25.98557,0.82654 -34.41142,11.25287l-5.11707,8.63186c1.30753,-3.12148 3.01521,-6.03101 5.11707,-8.63186c-5.93959,-8.19432 -15.2556,-12.8181 -24.96718,-12.51096z',
cylinder: 'm299.0007,83.77844c0,18.28676 -66.70958,33.11111 -149.00002,33.11111m149.00002,-33.11111l0,0c0,18.28676 -66.70958,33.11111 -149.00002,33.11111c-82.29041,0 -148.99997,-14.82432 -148.99997,-33.11111m0,0l0,0c0,-18.28674 66.70956,-33.1111 148.99997,-33.1111c82.29044,0 149.00002,14.82436 149.00002,33.1111l0,132.44449c0,18.28674 -66.70958,33.11105 -149.00002,33.11105c-82.29041,0 -148.99997,-14.82431 -148.99997,-33.11105z',
arrow_u_turn: 'm1.00059,299.00055l0,-167.62497l0,0c0,-72.00411 58.37087,-130.37499 130.375,-130.37499l0,0l0,0c34.57759,0 67.73898,13.7359 92.18906,38.18595c24.45006,24.45005 38.18593,57.61144 38.18593,92.18904l0,18.625l37.24997,0l-74.49995,74.50002l-74.50002,-74.50002l37.25,0l0,-18.625c0,-30.8589 -25.0161,-55.87498 -55.87498,-55.87498l0,0l0,0c-30.85892,0 -55.875,25.01608 -55.875,55.87498l0,167.62497z',
arrow_left_up: 'm0.99865,224.5l74.50004,-74.5l0,37.25l111.74991,0l0,-111.75l-37.25,0l74.5,-74.5l74.5,74.5l-37.25,0l0,186.25l-186.24989,0l0,37.25l-74.50005,-74.5z',
maximize: 'm1.00037,150.34581l55.30305,-55.30267l0,27.65093l22.17356,0l0,-44.21833l44.21825,0l0,-22.17357l-27.65095,0l55.30267,-55.30292l55.3035,55.30292l-27.65175,0l0,22.17357l44.21835,0l0,44.21833l22.17357,0l0,-27.65093l55.30345,55.30267l-55.30345,55.3035l0,-27.65175l-22.17357,0l0,44.21834l-44.21835,0l0,22.17355l27.65175,0l-55.3035,55.30348l-55.30267,-55.30348l27.65095,0l0,-22.17355l-44.21825,0l0,-44.21834l-22.17356,0l0,27.65175l-55.30305,-55.3035z',
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 = {};
curLib = library.basic;
/**
*
* @returns {void}
*/
buttons = [{
id: 'tool_shapelib',
icon: svgEditor.curConfig.extIconsPath + 'shapes.png',
type: 'mode_flyout',
// _flyout
position: 6,
events: {
click: function click() {
canv.setMode(modeId);
}
}
}];
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("\n #shape_buttons {\n overflow: auto;\n width: 180px;\n max-height: 300px;\n display: table-cell;\n vertical-align: middle;\n }\n #shape_cats {\n min-width: 110px;\n display: table-cell;\n vertical-align: middle;\n height: 300px;\n }\n #shape_cats > div {\n line-height: 1em;\n padding: .5em;\n border:1px solid #B0B0B0;\n background: #E8E8E8;\n margin-bottom: -1px;\n }\n #shape_cats div:hover {\n background: #FFFFCC;\n }\n #shape_cats div.current {\n font-weight: bold;\n }\n ").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
$('#shape_buttons').mouseup(function (evt) {
var btn = $(evt.target).closest('div.tool_button');
if (!btn.length) {
return; return;
} }
var zoom = canv.getZoom(); var copy = btn.children().clone();
var evt = opts.event; shower.children(':not(.flyout_arrow_horiz)').remove();
var x = opts.mouse_x / zoom; shower.append(copy).attr('data-curopt', '#' + btn[0].id) // This sets the current mode
var y = opts.mouse_y / zoom; .mouseup();
var tlist = canv.getTransformList(curShape), canv.setMode(modeId);
box = curShape.getBBox(), curShapeId = btn[0].id.substr((modeId + '_').length);
left = box.x, currentD = curLib.data[curShapeId];
top = box.y; // {width, height} = box, $('.tools_flyout').fadeOut();
// const dx = (x - startX), dy = (y - startY); });
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
var newbox = { return false;
x: Math.min(startX, x), });
y: Math.min(startY, y), shapeCats.children().eq(0).addClass('current');
width: Math.abs(x - startX), $('#tools_shapelib').append(shapeCats);
height: Math.abs(y - startY) shower.mouseup(function () {
}; canv.setMode(currentD ? modeId : 'select');
/* });
// This is currently serving no purpose, so commenting out $('#tool_shapelib').remove();
let sy = height ? (height + dy) / height : 1, var h = $('#tools_shapelib').height();
sx = width ? (width + dx) / width : 1; $('#tools_shapelib').css({
*/ 'margin-top': -(h / 2 - 15),
'margin-left': 3
}); // Now add shape categories from locale
var sx = newbox.width / lastBBox.width || 1; var cats = {};
var sy = newbox.height / lastBBox.height || 1; // Not perfect, but mostly works... Object.entries(categories).forEach(function (_ref4) {
var _ref5 = _slicedToArray(_ref4, 2),
o = _ref5[0],
categoryName = _ref5[1];
var tx = 0; cats['#shape_cats [data-cat="' + o + '"]'] = categoryName;
});
this.setStrings('content', cats);
},
mouseDown: function mouseDown(opts) {
var mode = canv.getMode();
if (x < startX) { if (mode !== modeId) {
tx = lastBBox.width; return undefined;
}
var ty = 0;
if (y < startY) {
ty = lastBBox.height;
} // 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);
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 undefined;
}
var keepObject = opts.event.clientX !== startClientPos.x && opts.event.clientY !== startClientPos.y;
return {
keep: keepObject,
element: curShape,
started: false
};
} }
});
case 18: startX = opts.start_x;
case "end": var x = startX;
return _context.stop(); 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,
attr: {
d: currentD,
id: canv.getNextId(),
opacity: curStyle.opacity / 2,
style: 'pointer-events:none'
}
}); // 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 = */
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,
// const dx = (x - startX), dy = (y - startY);
var newbox = {
x: Math.min(startX, x),
y: Math.min(startY, y),
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,
sx = width ? (width + dx) / width : 1;
*/
var sx = newbox.width / lastBBox.width || 1;
var sy = newbox.height / lastBBox.height || 1; // 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
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);
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 undefined;
}
var keepObject = opts.event.clientX !== startClientPos.x && opts.event.clientY !== startClientPos.y;
return {
keep: keepObject,
element: curShape,
started: false
};
}
});
case 18:
case "end":
return _context.stop();
} }
}, _callee, this); }
})); }, null, this);
}
function init(_x) {
return _init.apply(this, arguments);
}
return init;
}()
}; };
return extShapes; return extShapes;

View File

@ -1,42 +1,6 @@
var svgEditorExtension_star = (function () { var svgEditorExtension_star = (function () {
'use strict'; 'use strict';
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
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-star.js * ext-star.js
* *
@ -46,160 +10,170 @@ var svgEditorExtension_star = (function () {
*/ */
var extStar = { var extStar = {
name: 'star', name: 'star',
init: function () { init: function init(S) {
var _init = _asyncToGenerator( var svgEditor, svgCanvas, $, importLocale, selElems, started, newFO, strings, showPanel, setAttr, buttons, contextTools;
/*#__PURE__*/ return regeneratorRuntime.async(function init$(_context) {
regeneratorRuntime.mark(function _callee(S) { while (1) {
var svgEditor, svgCanvas, $, importLocale, selElems, started, newFO, strings, showPanel, setAttr, buttons, contextTools; switch (_context.prev = _context.next) {
return regeneratorRuntime.wrap(function _callee$(_context) { case 0:
while (1) { setAttr = function _ref2(attr, val) {
switch (_context.prev = _context.next) { svgCanvas.changeSelectedAttribute(attr, val);
case 0: svgCanvas.call('changed', selElems);
setAttr = function _ref2(attr, val) { };
svgCanvas.changeSelectedAttribute(attr, val);
svgCanvas.call('changed', selElems);
};
showPanel = function _ref(on) { showPanel = function _ref(on) {
var fcRules = $('#fc_rules'); var fcRules = $('#fc_rules');
if (!fcRules.length) { if (!fcRules.length) {
fcRules = $('<style id="fc_rules"></style>').appendTo('head'); fcRules = $('<style id="fc_rules"></style>').appendTo('head');
}
fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }');
$('#star_panel').toggle(on);
};
svgEditor = this;
svgCanvas = svgEditor.canvas;
$ = S.$, importLocale = S.importLocale; // {svgcontent},
_context.next = 7;
return importLocale();
case 7:
strings = _context.sent;
/*
function cot(n){
return 1 / Math.tan(n);
} }
function sec(n){
return 1 / Math.cos(n); fcRules.text(!on ? '' : ' #tool_topath { display: none !important; }');
$('#star_panel').toggle(on);
};
svgEditor = this;
svgCanvas = svgEditor.canvas;
$ = S.$, importLocale = S.importLocale; // {svgcontent},
_context.next = 7;
return regeneratorRuntime.awrap(importLocale());
case 7:
strings = _context.sent;
/*
function cot(n){
return 1 / Math.tan(n);
}
function sec(n){
return 1 / Math.cos(n);
}
*/
buttons = [{
id: 'tool_star',
icon: svgEditor.curConfig.extIconsPath + 'star.png',
type: 'mode',
position: 12,
events: {
click: function click() {
showPanel(true);
svgCanvas.setMode('star');
}
} }
*/ }];
buttons = [{ contextTools = [{
id: 'tool_star', type: 'input',
icon: svgEditor.curConfig.extIconsPath + 'star.png', panel: 'star_panel',
type: 'mode', id: 'starNumPoints',
position: 12, size: 3,
events: { defval: 5,
click: function click() { events: {
showPanel(true); change: function change() {
svgCanvas.setMode('star'); setAttr('point', this.value);
}
} }
}]; }
contextTools = [{ }, {
type: 'input', type: 'input',
panel: 'star_panel', panel: 'star_panel',
id: 'starNumPoints', id: 'starRadiusMulitplier',
size: 3, size: 3,
defval: 5, defval: 2.5
events: { }, {
change: function change() { type: 'input',
setAttr('point', this.value); panel: 'star_panel',
} id: 'radialShift',
size: 3,
defval: 0,
events: {
change: function change() {
setAttr('radialshift', this.value);
} }
}, { }
type: 'input', }];
panel: 'star_panel', return _context.abrupt("return", {
id: 'starRadiusMulitplier', name: strings.name,
size: 3, svgicons: svgEditor.curConfig.extIconsPath + 'star-icons.svg',
defval: 2.5 buttons: strings.buttons.map(function (button, i) {
}, { return Object.assign(buttons[i], button);
type: 'input', }),
panel: 'star_panel', context_tools: strings.contextTools.map(function (contextTool, i) {
id: 'radialShift', return Object.assign(contextTools[i], contextTool);
size: 3, }),
defval: 0, callback: function callback() {
events: { $('#star_panel').hide(); // const endChanges = function(){};
change: function change() { },
setAttr('radialshift', this.value); 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 sWidth = svgCanvas.getStrokeWidth();
if (svgCanvas.getMode() === 'star') {
started = true;
newFO = svgCanvas.addSVGElementFromJson({
element: 'polygon',
attr: {
cx: opts.start_x,
cy: opts.start_y,
id: svgCanvas.getNextId(),
shape: 'star',
point: document.getElementById('starNumPoints').value,
r: 0,
radialshift: document.getElementById('radialShift').value,
r2: 0,
orient: 'point',
fill: rgb,
strokecolor: sRgb,
strokeWidth: sWidth
}
});
return {
started: true
};
} }
}];
return _context.abrupt("return", {
name: strings.name,
svgicons: svgEditor.curConfig.extIconsPath + 'star-icons.svg',
buttons: strings.buttons.map(function (button, i) {
return Object.assign(buttons[i], button);
}),
context_tools: strings.contextTools.map(function (contextTool, i) {
return Object.assign(contextTools[i], contextTool);
}),
callback: function callback() {
$('#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 sWidth = svgCanvas.getStrokeWidth();
if (svgCanvas.getMode() === 'star') {
started = true;
newFO = svgCanvas.addSVGElementFromJson({
element: 'polygon',
attr: {
cx: opts.start_x,
cy: opts.start_y,
id: svgCanvas.getNextId(),
shape: 'star',
point: document.getElementById('starNumPoints').value,
r: 0,
radialshift: document.getElementById('radialShift').value,
r2: 0,
orient: 'point',
fill: rgb,
strokecolor: sRgb,
strokeWidth: sWidth
}
});
return {
started: true
};
}
return undefined;
},
mouseMove: function mouseMove(opts) {
if (!started) {
return undefined; return undefined;
}, }
mouseMove: function mouseMove(opts) {
if (!started) {
return undefined;
}
if (svgCanvas.getMode() === 'star') { if (svgCanvas.getMode() === 'star') {
var c = $(newFO).attr(['cx', 'cy', 'point', 'orient', 'fill', 'strokecolor', 'strokeWidth', 'radialshift']); var c = $(newFO).attr(['cx', 'cy', 'point', 'orient', 'fill', 'strokecolor', 'strokeWidth', 'radialshift']);
var x = opts.mouse_x; var x = opts.mouse_x;
var y = opts.mouse_y; var y = opts.mouse_y;
var cx = c.cx, var cx = c.cx,
cy = c.cy, cy = c.cy,
fill = c.fill, fill = c.fill,
strokecolor = c.strokecolor, strokecolor = c.strokecolor,
strokeWidth = c.strokeWidth, strokeWidth = c.strokeWidth,
radialshift = c.radialshift, radialshift = c.radialshift,
point = c.point, point = c.point,
orient = c.orient, orient = c.orient,
circumradius = Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy)) / 1.5, circumradius = Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy)) / 1.5,
inradius = circumradius / document.getElementById('starRadiusMulitplier').value; inradius = circumradius / document.getElementById('starRadiusMulitplier').value;
newFO.setAttribute('r', circumradius); newFO.setAttribute('r', circumradius);
newFO.setAttribute('r2', inradius); newFO.setAttribute('r2', inradius);
var polyPoints = ''; var polyPoints = '';
for (var s = 0; point >= s; s++) { for (var s = 0; point >= s; s++) {
var angle = 2.0 * Math.PI * (s / point); var angle = 2.0 * Math.PI * (s / point);
if (orient === 'point') {
angle -= Math.PI / 2;
} else if (orient === 'edge') {
angle = angle + Math.PI / point - Math.PI / 2;
}
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') { if (orient === 'point') {
angle -= Math.PI / 2; angle -= Math.PI / 2;
@ -207,92 +181,72 @@ var svgEditorExtension_star = (function () {
angle = angle + Math.PI / point - Math.PI / 2; angle = angle + Math.PI / point - Math.PI / 2;
} }
x = circumradius * Math.cos(angle) + cx; angle += radialshift;
y = circumradius * Math.sin(angle) + cy; x = inradius * Math.cos(angle) + cx;
y = inradius * Math.sin(angle) + cy;
polyPoints += x + ',' + y + ' '; 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;
x = inradius * Math.cos(angle) + cx;
y = inradius * Math.sin(angle) + cy;
polyPoints += x + ',' + y + ' ';
}
} }
newFO.setAttribute('points', polyPoints);
newFO.setAttribute('fill', fill);
newFO.setAttribute('stroke', strokecolor);
newFO.setAttribute('stroke-width', strokeWidth);
/* const shape = */
newFO.getAttribute('shape');
return {
started: true
};
} }
return undefined; newFO.setAttribute('points', polyPoints);
}, newFO.setAttribute('fill', fill);
mouseUp: function mouseUp() { newFO.setAttribute('stroke', strokecolor);
if (svgCanvas.getMode() === 'star') { newFO.setAttribute('stroke-width', strokeWidth);
var attrs = $(newFO).attr(['r']); // svgCanvas.addToSelection([newFO], true); /* const shape = */
return { newFO.getAttribute('shape');
keep: attrs.r !== '0', return {
element: newFO started: true
}; };
} }
return undefined; return undefined;
}, },
selectedChanged: function selectedChanged(opts) { mouseUp: function mouseUp() {
// Use this to update the current selected elements if (svgCanvas.getMode() === 'star') {
selElems = opts.elems; var attrs = $(newFO).attr(['r']); // svgCanvas.addToSelection([newFO], true);
var i = selElems.length;
while (i--) { return {
var elem = selElems[i]; keep: attrs.r !== '0',
element: newFO
};
}
if (elem && elem.getAttribute('shape') === 'star') { return undefined;
if (opts.selectedElement && !opts.multiselected) { },
// $('#starRadiusMulitplier').val(elem.getAttribute('r2')); selectedChanged: function selectedChanged(opts) {
$('#starNumPoints').val(elem.getAttribute('point')); // Use this to update the current selected elements
$('#radialShift').val(elem.getAttribute('radialshift')); selElems = opts.elems;
showPanel(true); var i = selElems.length;
} else {
showPanel(false); while (i--) {
} var elem = selElems[i];
if (elem && elem.getAttribute('shape') === 'star') {
if (opts.selectedElement && !opts.multiselected) {
// $('#starRadiusMulitplier').val(elem.getAttribute('r2'));
$('#starNumPoints').val(elem.getAttribute('point'));
$('#radialShift').val(elem.getAttribute('radialshift'));
showPanel(true);
} else { } else {
showPanel(false); showPanel(false);
} }
} else {
showPanel(false);
} }
},
elementChanged: function elementChanged(opts) {// const elem = opts.elems[0];
} }
}); },
elementChanged: function elementChanged(opts) {// const elem = opts.elems[0];
}
});
case 11: case 11:
case "end": case "end":
return _context.stop(); return _context.stop();
}
} }
}, _callee, this); }
})); }, null, this);
}
function init(_x) {
return _init.apply(this, arguments);
}
return init;
}()
}; };
return extStar; return extStar;

View File

@ -1,42 +1,6 @@
var svgEditorExtension_storage = (function () { var svgEditorExtension_storage = (function () {
'use strict'; 'use strict';
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
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);
});
};
}
function _inherits(subClass, superClass) { function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) { if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function"); throw new TypeError("Super expression must either be null or a function");
@ -415,184 +379,174 @@ var svgEditorExtension_storage = (function () {
var loaded = false; var loaded = false;
return { return {
name: 'storage', name: 'storage',
langReady: function () { langReady: function langReady(_ref4) {
var _langReady = _asyncToGenerator( var importLocale, _$$deparam$querystrin, storagePrompt, confirmSetStorage, message, storagePrefsAndContent, storagePrefsOnly, storagePrefs, storageNoPrefsOrContent, storageNoPrefs, rememberLabel, rememberTooltip, options, oldContainerWidth, oldContainerMarginLeft, oldContentHeight, oldContainerHeight, _ref5, pref, checked;
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(_ref4) {
var importLocale, _$$deparam$querystrin, storagePrompt, confirmSetStorage, message, storagePrefsAndContent, storagePrefsOnly, storagePrefs, storageNoPrefsOrContent, storageNoPrefs, rememberLabel, rememberTooltip, options, oldContainerWidth, oldContainerMarginLeft, oldContentHeight, oldContainerHeight, _ref5, pref, checked;
return regeneratorRuntime.wrap(function _callee$(_context) { return regeneratorRuntime.async(function langReady$(_context) {
while (1) { while (1) {
switch (_context.prev = _context.next) { switch (_context.prev = _context.next) {
case 0: case 0:
importLocale = _ref4.importLocale; importLocale = _ref4.importLocale;
_$$deparam$querystrin = $.deparam.querystring(true), storagePrompt = _$$deparam$querystrin.storagePrompt; _$$deparam$querystrin = $.deparam.querystring(true), storagePrompt = _$$deparam$querystrin.storagePrompt;
_context.next = 4; _context.next = 4;
return importLocale(); return regeneratorRuntime.awrap(importLocale());
case 4: case 4:
confirmSetStorage = _context.sent; 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 // changes the language
if (!loaded) { if (!loaded) {
_context.next = 8; _context.next = 8;
break; break;
} }
return _context.abrupt("return"); return _context.abrupt("return");
case 8: case 8:
loaded = true; // Note that the following can load even if "noStorageOnLoad" is loaded = true; // Note that the following can load even if "noStorageOnLoad" is
// set to false; to avoid any chance of storage, avoid this // set to false; to avoid any chance of storage, avoid this
// extension! (and to avoid using any prior storage, set the // extension! (and to avoid using any prior storage, set the
// config option "noStorageOnLoad" to true). // 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 // user (e.g., so one can be pointed to a URL where one
// can alter one's settings, say to prevent future storage)... // 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 // storage prompt (as we use for users who
// don't want to set cookies at all but who don't want // don't want to set cookies at all but who don't want
// continual prompts about it)... // continual prompts about it)...
storagePrompt !== false && // ...and this user hasn't previously indicated a desire for storage storagePrompt !== false && // ...and this user hasn't previously indicated a desire for storage
!document.cookie.match(/(?:^|;\s*)svgeditstore=(?:prefsAndContent|prefsOnly)/) // ...then show the storage prompt. !document.cookie.match(/(?:^|;\s*)svgeditstore=(?:prefsAndContent|prefsOnly)/) // ...then show the storage prompt.
))) { ))) {
_context.next = 44; _context.next = 44;
break; break;
} }
options = []; options = [];
if (storage) { if (storage) {
options.unshift({ options.unshift({
value: 'prefsAndContent', value: 'prefsAndContent',
text: storagePrefsAndContent text: storagePrefsAndContent
}, { }, {
value: 'prefsOnly', value: 'prefsOnly',
text: storagePrefsOnly text: storagePrefsOnly
}, { }, {
value: 'noPrefsOrContent', value: 'noPrefsOrContent',
text: storageNoPrefsOrContent text: storageNoPrefsOrContent
});
} else {
options.unshift({
value: 'prefsOnly',
text: storagePrefs
}, {
value: 'noPrefsOrContent',
text: storageNoPrefs
});
} // 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
// From svg-editor.js
svgEditor.storagePromptState = 'waiting';
_context.next = 20;
return $.select(message, options, null, null, {
label: rememberLabel,
checked: true,
tooltip: rememberTooltip
}); });
} else {
options.unshift({
value: 'prefsOnly',
text: storagePrefs
}, {
value: 'noPrefsOrContent',
text: storageNoPrefs
});
} // Hack to temporarily provide a wide and high enough dialog
case 20:
_ref5 = _context.sent;
pref = _ref5.response;
checked = _ref5.checked;
if (!(pref && pref !== 'noPrefsOrContent')) { oldContainerWidth = $('#dialog_container')[0].style.width, oldContainerMarginLeft = $('#dialog_container')[0].style.marginLeft, oldContentHeight = $('#dialog_content')[0].style.height, oldContainerHeight = $('#dialog_container')[0].style.height;
_context.next = 30; $('#dialog_content')[0].style.height = '120px';
break; $('#dialog_container')[0].style.height = '170px';
} $('#dialog_container')[0].style.width = '800px';
$('#dialog_container')[0].style.marginLeft = '-400px'; // Open select-with-checkbox dialog
// From svg-editor.js
// Regardless of whether the user opted svgEditor.storagePromptState = 'waiting';
// to remember the choice (and move to a URL which won't _context.next = 20;
// ask them again), we have to assume the user return regeneratorRuntime.awrap($.select(message, options, null, null, {
// doesn't even want to remember their not wanting label: rememberLabel,
// storage, so we don't set the cookie or continue on with checked: true,
// setting storage on beforeunload tooltip: rememberTooltip
// eslint-disable-next-line require-atomic-updates }));
document.cookie = 'svgeditstore=' + encodeURIComponent(pref) + '; expires=Fri, 31 Dec 9999 23:59:59 GMT'; // 'prefsAndContent' | 'prefsOnly'
// If the URL was configured to always insist on a prompt, if
// 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)) { case 20:
_context.next = 28; _ref5 = _context.sent;
break; pref = _ref5.response;
} checked = _ref5.checked;
replaceStoragePrompt(); if (!(pref && pref !== 'noPrefsOrContent')) {
return _context.abrupt("return"); _context.next = 30;
break;
}
case 28: // Regardless of whether the user opted
// to remember the choice (and move to a URL which won't
// ask them again), we have to assume the user
// doesn't even want to remember their not wanting
// storage, so we don't set the cookie or continue on with
// setting storage on beforeunload
// eslint-disable-next-line require-atomic-updates
document.cookie = 'svgeditstore=' + encodeURIComponent(pref) + '; expires=Fri, 31 Dec 9999 23:59:59 GMT'; // 'prefsAndContent' | 'prefsOnly'
// If the URL was configured to always insist on a prompt, if
// 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)) {
_context.next = 28;
break;
}
replaceStoragePrompt();
return _context.abrupt("return");
case 28:
_context.next = 35;
break;
case 30:
// 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)) {
_context.next = 35; _context.next = 35;
break; break;
}
case 30: // Open a URL which won't set storage and won't prompt user about storage
// The user does not wish storage (or cancelled, which we treat equivalently) replaceStoragePrompt('false');
removeStoragePrefCookie(); return _context.abrupt("return");
if (pref && // If the user explicitly expresses wish for no storage case 35:
emptyStorageOnDecline) { // Reset width/height of dialog (e.g., for use by Export)
emptyStorage(); $('#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
// 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
if (!(pref && checked)) { setupBeforeUnloadListener();
_context.next = 35; svgEditor.storagePromptState = 'closed';
break; updateCanvas(true);
} _context.next = 45;
break;
// Open a URL which won't set storage and won't prompt user about storage
replaceStoragePrompt('false');
return _context.abrupt("return");
case 35:
// 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
// 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
case 44:
if (!noStorageOnLoad || forceStorage) {
setupBeforeUnloadListener(); setupBeforeUnloadListener();
svgEditor.storagePromptState = 'closed'; }
updateCanvas(true);
_context.next = 45;
break;
case 44: case 45:
if (!noStorageOnLoad || forceStorage) { case "end":
setupBeforeUnloadListener(); return _context.stop();
}
case 45:
case "end":
return _context.stop();
}
} }
}, _callee); }
})); });
}
function langReady(_x) {
return _langReady.apply(this, arguments);
}
return langReady;
}()
}; };
} }
}; };

View File

@ -1,42 +1,6 @@
var svgEditorExtension_webappfind = (function () { var svgEditorExtension_webappfind = (function () {
'use strict'; 'use strict';
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
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} * Depends on Firefox add-on and executables from {@link https://github.com/brettz9/webappfind}
* @author Brett Zamir * @author Brett Zamir
@ -45,133 +9,123 @@ var svgEditorExtension_webappfind = (function () {
*/ */
var extWebappfind = { var extWebappfind = {
name: 'webappfind', name: 'webappfind',
init: function () { init: function init(_ref) {
var _init = _asyncToGenerator( var importLocale, $, strings, svgEditor, saveMessage, readMessage, excludedMessages, pathID, buttons;
/*#__PURE__*/ return regeneratorRuntime.async(function init$(_context) {
regeneratorRuntime.mark(function _callee(_ref) { while (1) {
var importLocale, $, strings, svgEditor, saveMessage, readMessage, excludedMessages, pathID, buttons; switch (_context.prev = _context.next) {
return regeneratorRuntime.wrap(function _callee$(_context) { case 0:
while (1) { importLocale = _ref.importLocale, $ = _ref.$;
switch (_context.prev = _context.next) { _context.next = 3;
case 0: return regeneratorRuntime.awrap(importLocale());
importLocale = _ref.importLocale, $ = _ref.$;
_context.next = 3;
return importLocale();
case 3: case 3:
strings = _context.sent; strings = _context.sent;
svgEditor = this; svgEditor = this;
saveMessage = 'save', readMessage = 'read', excludedMessages = [readMessage, saveMessage]; saveMessage = 'save', readMessage = 'read', excludedMessages = [readMessage, saveMessage];
this.canvas.bind('message', this.canvas.bind('message',
/** /**
* @param {external:Window} win * @param {external:Window} win
* @param {module:svgcanvas.SvgCanvas#event:message} data * @param {module:svgcanvas.SvgCanvas#event:message} data
* @listens module:svgcanvas.SvgCanvas#event:message * @listens module:svgcanvas.SvgCanvas#event:message
* @throws {Error} Unexpected event type * @throws {Error} Unexpected event type
* @returns {void} * @returns {void}
*/ */
function (win, _ref2) { function (win, _ref2) {
var data = _ref2.data, var data = _ref2.data,
origin = _ref2.origin; origin = _ref2.origin;
// eslint-disable-line no-shadow // eslint-disable-line no-shadow
// console.log('data, origin', data, origin); // console.log('data, origin', data, origin);
var type, content; var type, content;
try { try {
var _data$webappfind = data.webappfind; var _data$webappfind = data.webappfind;
type = _data$webappfind.type; type = _data$webappfind.type;
pathID = _data$webappfind.pathID; pathID = _data$webappfind.pathID;
content = _data$webappfind.content; content = _data$webappfind.content;
// May throw if data is not an object // 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 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) 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)
) { ) {
return; return;
}
} catch (err) {
return;
}
switch (type) {
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 ".concat(pathID, "!"));
break;
default:
throw new Error('Unexpected WebAppFind event type');
}
});
/*
window.postMessage({
webappfind: {
type: readMessage
}
}, window.location.origin === 'null'
// Avoid "null" string error for `file:` protocol (even though
// file protocol not currently supported by Firefox)
? '*'
: window.location.origin
);
*/
buttons = [{
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)")
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
// though file protocol not currently supported by add-on)
? '*' : window.location.origin);
} }
} catch (err) {
return;
}
switch (type) {
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 ".concat(pathID, "!"));
break;
default:
throw new Error('Unexpected WebAppFind event type');
}
});
/*
window.postMessage({
webappfind: {
type: readMessage
}
}, window.location.origin === 'null'
// Avoid "null" string error for `file:` protocol (even though
// file protocol not currently supported by Firefox)
? '*'
: window.location.origin
);
*/
buttons = [{
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)")
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
// though file protocol not currently supported by add-on)
? '*' : window.location.origin);
} }
}]; }
return _context.abrupt("return", { }];
name: strings.name, return _context.abrupt("return", {
svgicons: svgEditor.curConfig.extIconsPath + 'webappfind-icon.svg', name: strings.name,
buttons: strings.buttons.map(function (button, i) { svgicons: svgEditor.curConfig.extIconsPath + 'webappfind-icon.svg',
return Object.assign(buttons[i], button); buttons: strings.buttons.map(function (button, i) {
}) return Object.assign(buttons[i], button);
}); })
});
case 9: case 9:
case "end": case "end":
return _context.stop(); return _context.stop();
}
} }
}, _callee, this); }
})); }, null, this);
}
function init(_x) {
return _init.apply(this, arguments);
}
return init;
}()
}; };
return extWebappfind; return extWebappfind;

View File

@ -15,42 +15,6 @@
return _typeof(obj); return _typeof(obj);
} }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
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);
});
};
}
function _classCallCheck(instance, Constructor) { function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) { if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function"); throw new TypeError("Cannot call a class as a function");
@ -303,20 +267,35 @@
return obj; return obj;
} }
function _objectSpread(target) { function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) { for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {}; var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') { if (i % 2) {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { ownKeys(source, true).forEach(function (key) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable; _defineProperty(target, key, source[key]);
})); });
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(source).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
} }
ownKeys.forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} }
return target; return target;
@ -494,6 +473,10 @@
} }
function _iterableToArrayLimit$1(arr, i) { function _iterableToArrayLimit$1(arr, i) {
if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
return;
}
var _arr = []; var _arr = [];
var _n = true; var _n = true;
var _d = false; var _d = false;
@ -683,7 +666,7 @@
* @static * @static
* @param {Element} el DOM element to which to attach the event * @param {Element} el DOM element to which to attach the event
* @param {string} type The DOM event (without 'on') to attach to the element * @param {string} type The DOM event (without 'on') to attach to the element
* @param {Function} handler The event handler to attach to the element * @param {EventListener} handler The event handler to attach to the element
* @param {boolean} [capturing] Whether or not the event should be * @param {boolean} [capturing] Whether or not the event should be
* capturing (W3C-browsers only); default is false; NOT IN USE * capturing (W3C-browsers only); default is false; NOT IN USE
* @returns {void} * @returns {void}
@ -725,7 +708,7 @@
} // Todo: Make as public utility } // Todo: Make as public utility
/** /**
* @param {*} o * @param {any} o
* @returns {boolean} * @returns {boolean}
*/ */
@ -737,7 +720,7 @@
/** /**
* @private * @private
* @static * @static
* @param {string|object|Array|Element|DocumentFragment} item * @param {string|JamilihAttributes|JamilihArray|Element|DocumentFragment} item
* @returns {"string"|"null"|"array"|"element"|"fragment"|"object"} * @returns {"string"|"null"|"array"|"element"|"fragment"|"object"}
*/ */
@ -833,7 +816,7 @@
return jml(arg); return jml(arg);
} }
/** /**
* @typedef {Array} AttributeArray * @typedef {JamilihAttributes} AttributeArray
* @property {string} 0 The key * @property {string} 0 The key
* @property {string} 1 The value * @property {string} 1 The value
*/ */
@ -921,10 +904,10 @@
* @private * @private
* @static * @static
function _DOMfromJMLOrString (childNodeJML) { function _DOMfromJMLOrString (childNodeJML) {
if (typeof childNodeJML === 'string') { if (typeof childNodeJML === 'string') {
return doc.createTextNode(childNodeJML); return doc.createTextNode(childNodeJML);
} }
return jml(...childNodeJML); return jml(...childNodeJML);
} }
*/ */
@ -932,12 +915,16 @@
* @typedef {Element|DocumentFragment} JamilihReturn * @typedef {Element|DocumentFragment} JamilihReturn
*/ */
/**
* @typedef {PlainObject} JamilihAttributes
*/
/** /**
* @typedef {GenericArray} JamilihArray * @typedef {GenericArray} JamilihArray
* @property {string} 0 The element to create (by lower-case name) * @property {string} 0 The element to create (by lower-case name)
* @property {Object} [1] Attributes to add with the key as the attribute name * @property {JamilihAttributes} [1] Attributes to add with the key as the
* and value as the attribute value; important for IE where the input * attribute name and value as the attribute value; important for IE where
* element's type cannot be added later after already added to the page * the input element's type cannot be added later after already added to the page
* @param {Element[]} [children] The optional children of this element * @param {Element[]} [children] The optional children of this element
* (but raw DOM elements required to be specified within arrays since * (but raw DOM elements required to be specified within arrays since
* could not otherwise be distinguished from siblings being added) * could not otherwise be distinguished from siblings being added)
@ -999,9 +986,9 @@
0. {$xmlDocument: []} // doc.implementation.createDocument 0. {$xmlDocument: []} // doc.implementation.createDocument
0. Accept array for any attribute with first item as prefix and second as value? 0. Accept array for any attribute with first item as prefix and second as value?
0. {$: ['xhtml', 'div']} for prefixed elements 0. {$: ['xhtml', 'div']} for prefixed elements
case '$': // Element with prefix? case '$': // Element with prefix?
nodes[nodes.length] = elem = doc.createElementNS(attVal[0], attVal[1]); nodes[nodes.length] = elem = doc.createElementNS(attVal[0], attVal[1]);
break; break;
*/ */
case '#': case '#':
{ {
@ -1287,7 +1274,7 @@
/* /*
// Todo: // Todo:
if (attVal.internalSubset) { if (attVal.internalSubset) {
node = {}; node = {};
} }
else else
*/ */
@ -1320,13 +1307,13 @@
/* /*
// Todo: Should we auto-copy another node's properties/methods (like DocumentType) excluding or changing its non-entity node values? // Todo: Should we auto-copy another node's properties/methods (like DocumentType) excluding or changing its non-entity node values?
const node = { const node = {
nodeName: attVal.name, nodeName: attVal.name,
nodeValue: null, nodeValue: null,
publicId: attVal.publicId, publicId: attVal.publicId,
systemId: attVal.systemId, systemId: attVal.systemId,
notationName: attVal.notationName, notationName: attVal.notationName,
nodeType: 6, nodeType: 6,
childNodes: attVal.childNodes.map(_DOMfromJMLOrString) childNodes: attVal.childNodes.map(_DOMfromJMLOrString)
}; };
*/ */
break; break;
@ -1472,9 +1459,9 @@
/* /*
// The following reorders which is troublesome for serialization, e.g., as used in our testing // The following reorders which is troublesome for serialization, e.g., as used in our testing
if (elem.style.cssText !== undefined) { if (elem.style.cssText !== undefined) {
elem.style.cssText += attVal; elem.style.cssText += attVal;
} else { // Opera } else { // Opera
elem.style += attVal; elem.style += attVal;
} }
*/ */
@ -1569,8 +1556,6 @@
obj = dataVal[1] || defaultMap[1]; obj = dataVal[1] || defaultMap[1];
} // Map } // Map
/* eslint-disable-next-line unicorn/no-unsafe-regex */
} else if (/^\[object (?:Weak)?Map\]$/.test([].toString.call(dataVal))) { } else if (/^\[object (?:Weak)?Map\]$/.test([].toString.call(dataVal))) {
map = dataVal; map = dataVal;
obj = defaultMap[1]; // Non-map data object obj = defaultMap[1]; // Non-map data object
@ -1823,11 +1808,11 @@
/** /**
* Converts a DOM object or a string of HTML into a Jamilih object (or string). * Converts a DOM object or a string of HTML into a Jamilih object (or string).
* @param {string|HTMLElement} [dom=document.documentElement] Defaults to converting the current document. * @param {string|HTMLElement} [dom=document.documentElement] Defaults to converting the current document.
* @param {object} [config={stringOutput:false}] Configuration object * @param {PlainObject} [config] Configuration object
* @param {boolean} [config.stringOutput=false] Whether to output the Jamilih object as a string. * @param {boolean} [config.stringOutput=false] Whether to output the Jamilih object as a string.
* @returns {Array|string} Array containing the elements which represent a Jamilih object, or, * @returns {JamilihArray|string} Array containing the elements which represent
if `stringOutput` is true, it will be the stringified version of * a Jamilih object, or, if `stringOutput` is true, it will be the stringified
such an object * version of such an object
*/ */
@ -1890,7 +1875,7 @@
} }
/** /**
* *
* @param {*} val * @param {any} val
* @returns {void} * @returns {void}
*/ */
@ -1938,11 +1923,11 @@
/* /*
if ((node.prefix && node.prefix.includes(':')) || (node.localName && node.localName.includes(':'))) { if ((node.prefix && node.prefix.includes(':')) || (node.localName && node.localName.includes(':'))) {
invalidStateError(); invalidStateError();
} }
*/ */
var type = 'nodeType' in node ? node.nodeType : null; var type = 'nodeType' in node ? node.nodeType : null;
namespaces = _objectSpread({}, namespaces); namespaces = _objectSpread2({}, namespaces);
var xmlChars = /([\t\n\r -\uD7FF\uE000-\uFFFD]|(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF]))(?:(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))*$/; // eslint-disable-line no-control-regex var xmlChars = /([\t\n\r -\uD7FF\uE000-\uFFFD]|(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF]))(?:(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))*$/; // eslint-disable-line no-control-regex
if ([2, 3, 4, 7, 8].includes(type) && !xmlChars.test(node.nodeValue)) { if ([2, 3, 4, 7, 8].includes(type) && !xmlChars.test(node.nodeValue)) {
@ -2018,7 +2003,7 @@
break; break;
} }
case undefined: // Treat as attribute node until this is fixed: https://github.com/tmpvar/jsdom/issues/1641 / https://github.com/tmpvar/jsdom/pull/1822 case undefined: // Treat as attribute node until this is fixed: https://github.com/jsdom/jsdom/issues/1641 / https://github.com/jsdom/jsdom/pull/1822
case 2: case 2:
// ATTRIBUTE (should only get here if passing in an attribute node) // ATTRIBUTE (should only get here if passing in an attribute node)
@ -3235,256 +3220,227 @@
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
function processResults(_x) { function processResults(url) {
return _processResults.apply(this, arguments); var queryLink, r, json, payload, _json$info, numResults, pages, currentPage, semiColonSep;
}
function _processResults() { return regeneratorRuntime.async(function processResults$(_context2) {
_processResults = _asyncToGenerator( while (1) {
/*#__PURE__*/ switch (_context2.prev = _context2.next) {
regeneratorRuntime.mark(function _callee3(url) { case 0:
var queryLink, r, json, payload, _json$info, numResults, pages, currentPage, semiColonSep; queryLink = function _ref2(query) {
return ['a', {
return regeneratorRuntime.wrap(function _callee3$(_context3) { href: jsVoid,
while (1) { dataset: {
switch (_context3.prev = _context3.next) { value: query
case 0: },
queryLink = function _ref4(query) { $on: {
return ['a', { click: function click(e) {
href: jsVoid, e.preventDefault();
dataset: { var value = this.dataset.value;
value: query $$1('#query')[0].$set(value);
}, $$1('#openclipart')[0].$submit();
$on: {
click: function click(e) {
e.preventDefault();
var value = this.dataset.value;
$$1('#query')[0].$set(value);
$$1('#openclipart')[0].$submit();
}
} }
}, [query]]; }
}; }, [query]];
};
_context3.next = 3; _context2.next = 3;
return fetch(url); return regeneratorRuntime.awrap(fetch(url));
case 3: case 3:
r = _context3.sent; r = _context2.sent;
_context3.next = 6; _context2.next = 6;
return r.json(); return regeneratorRuntime.awrap(r.json());
case 6: case 6:
json = _context3.sent; json = _context2.sent;
if (!(!json || json.msg !== 'success')) { if (!(!json || json.msg !== 'success')) {
_context3.next = 10; _context2.next = 10;
break; break;
} }
// Todo: This could use a generic alert library instead // Todo: This could use a generic alert library instead
alert('There was a problem downloading the results'); // eslint-disable-line no-alert alert('There was a problem downloading the results'); // eslint-disable-line no-alert
return _context3.abrupt("return"); return _context2.abrupt("return");
case 10: case 10:
payload = json.payload, _json$info = json.info, numResults = _json$info.results, pages = _json$info.pages, currentPage = _json$info.current_page; // $('#page')[0].value = currentPage; payload = json.payload, _json$info = json.info, numResults = _json$info.results, pages = _json$info.pages, currentPage = _json$info.current_page; // $('#page')[0].value = currentPage;
// $('#page')[0].max = pages; // $('#page')[0].max = pages;
// Unused properties: // Unused properties:
// - `svg_filesize` always 0? // - `svg_filesize` always 0?
// - `dimensions: { // - `dimensions: {
// png_thumb: {width, height}, // png_thumb: {width, height},
// png_full_lossy: {width, height} // png_full_lossy: {width, height}
// }` object of relevance? // }` object of relevance?
// - No need for `tags` with `tags_array` // - No need for `tags` with `tags_array`
// - `svg`'s: `png_thumb`, `png_full_lossy`, `png_2400px` // - `svg`'s: `png_thumb`, `png_full_lossy`, `png_2400px`
semiColonSep = '; ' + nbsp; semiColonSep = '; ' + nbsp;
$$1('#results').jml('div', [['span', ['Number of results: ', numResults]], semiColonSep, ['span', ['page ', currentPage, ' out of ', pages]]].concat(_toConsumableArray(payload.map(function (_ref3) { $$1('#results').jml('div', [['span', ['Number of results: ', numResults]], semiColonSep, ['span', ['page ', currentPage, ' out of ', pages]]].concat(_toConsumableArray(payload.map(function (_ref) {
var title = _ref3.title, var title = _ref.title,
description = _ref3.description, description = _ref.description,
id = _ref3.id, id = _ref.id,
uploader = _ref3.uploader, uploader = _ref.uploader,
created = _ref3.created, created = _ref.created,
svgURL = _ref3.svg.url, svgURL = _ref.svg.url,
detailLink = _ref3.detail_link, detailLink = _ref.detail_link,
tagsArray = _ref3.tags_array, tagsArray = _ref.tags_array,
downloadedBy = _ref3.downloaded_by, downloadedBy = _ref.downloaded_by,
totalFavorites = _ref3.total_favorites; totalFavorites = _ref.total_favorites;
var imgHW = '100px'; var imgHW = '100px';
var colonSep = ': ' + nbsp; var colonSep = ': ' + nbsp;
return ['div', [['button', { return ['div', [['button', {
style: 'margin-right: 8px; border: 2px solid black;', style: 'margin-right: 8px; border: 2px solid black;',
dataset: { dataset: {
id: id, id: id,
value: svgURL value: svgURL
}, },
$on: { $on: {
click: function () { click: function click(e) {
var _click = _asyncToGenerator( var svgurl, post, result, svg;
/*#__PURE__*/ return regeneratorRuntime.async(function click$(_context) {
regeneratorRuntime.mark(function _callee2(e) { while (1) {
var svgurl, post, result, svg; switch (_context.prev = _context.next) {
return regeneratorRuntime.wrap(function _callee2$(_context2) { case 0:
while (1) { e.preventDefault();
switch (_context2.prev = _context2.next) { svgurl = this.dataset.value; // console.log('this', id, svgurl);
case 0:
e.preventDefault();
svgurl = this.dataset.value; // console.log('this', id, svgurl);
post = function post(message) { post = function post(message) {
// Todo: Make origin customizable as set by opening window // Todo: Make origin customizable as set by opening window
// Todo: If dropping IE9, avoid stringifying // Todo: If dropping IE9, avoid stringifying
window.parent.postMessage(JSON.stringify(_extends({ window.parent.postMessage(JSON.stringify(_extends({
namespace: 'imagelib' namespace: 'imagelib'
}, message)), '*'); }, message)), '*');
}; // Send metadata (also indicates file is about to be sent) }; // Send metadata (also indicates file is about to be sent)
post({ post({
name: title, name: title,
id: svgurl id: svgurl
}); });
_context2.next = 6; _context.next = 6;
return fetch(svgurl); return regeneratorRuntime.awrap(fetch(svgurl));
case 6: case 6:
result = _context2.sent; result = _context.sent;
_context2.next = 9; _context.next = 9;
return result.text(); return regeneratorRuntime.awrap(result.text());
case 9: case 9:
svg = _context2.sent; svg = _context.sent;
// console.log('url and svg', svgurl, svg); // console.log('url and svg', svgurl, svg);
post({ post({
href: svgurl, href: svgurl,
data: svg data: svg
}); });
case 11: case 11:
case "end": case "end":
return _context2.stop(); return _context.stop();
} }
}
}, _callee2, this);
}));
function click(_x2) {
return _click.apply(this, arguments);
} }
}, null, this);
}
}
}, [// If we wanted interactive versions despite security risk:
// ['object', {data: svgURL, type: 'image/svg+xml'}]
['img', {
src: svgURL,
style: "width: ".concat(imgHW, "; height: ").concat(imgHW, ";")
}]]], ['b', [title]], ' ', ['i', [description]], ' ', ['span', ['(ID: ', ['a', {
href: jsVoid,
dataset: {
value: id
},
$on: {
click: function click(e) {
e.preventDefault();
var value = this.dataset.value;
$$1('#byids')[0].$set(value);
$$1('#openclipart')[0].$submit();
}
}
}, [id]], ')']], ' ', ['i', [['a', {
href: detailLink,
target: '_blank'
}, ['Details']]]], ['br'], ['span', [['u', ['Uploaded by']], colonSep, queryLink(uploader), semiColonSep]], ['span', [['u', ['Download count']], colonSep, downloadedBy, semiColonSep]], ['span', [['u', ['Times used as favorite']], colonSep, totalFavorites, semiColonSep]], ['span', [['u', ['Created date']], colonSep, created]], ['br'], ['u', ['Tags']], colonSep].concat(_toConsumableArray(tagsArray.map(function (tag) {
return ['span', [' ', queryLink(tag)]];
})))];
})), [['br'], ['br'], currentPage === 1 || pages <= 2 ? '' : ['span', [['a', {
href: jsVoid,
$on: {
click: function click(e) {
e.preventDefault();
$$1('#page')[0].value = 1;
$$1('#openclipart')[0].$submit();
}
}
}, ['First']], ' ']], currentPage === 1 ? '' : ['span', [['a', {
href: jsVoid,
$on: {
click: function click(e) {
e.preventDefault();
$$1('#page')[0].value = currentPage - 1;
$$1('#openclipart')[0].$submit();
}
}
}, ['Prev']], ' ']], currentPage === pages ? '' : ['span', [['a', {
href: jsVoid,
$on: {
click: function click(e) {
e.preventDefault();
$$1('#page')[0].value = currentPage + 1;
$$1('#openclipart')[0].$submit();
}
}
}, ['Next']], ' ']], currentPage === pages || pages <= 2 ? '' : ['span', [['a', {
href: jsVoid,
$on: {
click: function click(e) {
e.preventDefault();
$$1('#page')[0].value = pages;
$$1('#openclipart')[0].$submit();
}
}
}, ['Last']], ' ']]]));
return click; case 13:
}() case "end":
} return _context2.stop();
}, [// If we wanted interactive versions despite security risk:
// ['object', {data: svgURL, type: 'image/svg+xml'}]
['img', {
src: svgURL,
style: "width: ".concat(imgHW, "; height: ").concat(imgHW, ";")
}]]], ['b', [title]], ' ', ['i', [description]], ' ', ['span', ['(ID: ', ['a', {
href: jsVoid,
dataset: {
value: id
},
$on: {
click: function click(e) {
e.preventDefault();
var value = this.dataset.value;
$$1('#byids')[0].$set(value);
$$1('#openclipart')[0].$submit();
}
}
}, [id]], ')']], ' ', ['i', [['a', {
href: detailLink,
target: '_blank'
}, ['Details']]]], ['br'], ['span', [['u', ['Uploaded by']], colonSep, queryLink(uploader), semiColonSep]], ['span', [['u', ['Download count']], colonSep, downloadedBy, semiColonSep]], ['span', [['u', ['Times used as favorite']], colonSep, totalFavorites, semiColonSep]], ['span', [['u', ['Created date']], colonSep, created]], ['br'], ['u', ['Tags']], colonSep].concat(_toConsumableArray(tagsArray.map(function (tag) {
return ['span', [' ', queryLink(tag)]];
})))];
})), [['br'], ['br'], currentPage === 1 || pages <= 2 ? '' : ['span', [['a', {
href: jsVoid,
$on: {
click: function click(e) {
e.preventDefault();
$$1('#page')[0].value = 1;
$$1('#openclipart')[0].$submit();
}
}
}, ['First']], ' ']], currentPage === 1 ? '' : ['span', [['a', {
href: jsVoid,
$on: {
click: function click(e) {
e.preventDefault();
$$1('#page')[0].value = currentPage - 1;
$$1('#openclipart')[0].$submit();
}
}
}, ['Prev']], ' ']], currentPage === pages ? '' : ['span', [['a', {
href: jsVoid,
$on: {
click: function click(e) {
e.preventDefault();
$$1('#page')[0].value = currentPage + 1;
$$1('#openclipart')[0].$submit();
}
}
}, ['Next']], ' ']], currentPage === pages || pages <= 2 ? '' : ['span', [['a', {
href: jsVoid,
$on: {
click: function click(e) {
e.preventDefault();
$$1('#page')[0].value = pages;
$$1('#openclipart')[0].$submit();
}
}
}, ['Last']], ' ']]]));
case 13:
case "end":
return _context3.stop();
}
} }
}, _callee3); }
})); });
return _processResults.apply(this, arguments);
} }
jml('div', [['style', [".control {\n padding-top: 10px;\n }"]], ['form', { jml('div', [['style', [".control {\n padding-top: 10px;\n }"]], ['form', {
id: 'openclipart', id: 'openclipart',
$custom: { $custom: {
$submit: function () { $submit: function $submit() {
var _$submit = _asyncToGenerator( var url;
/*#__PURE__*/ return regeneratorRuntime.async(function $submit$(_context3) {
regeneratorRuntime.mark(function _callee() { while (1) {
var url; switch (_context3.prev = _context3.next) {
return regeneratorRuntime.wrap(function _callee$(_context) { case 0:
while (1) { url = new URL(baseAPIURL);
switch (_context.prev = _context.next) { ['query', 'sort', 'amount', 'page', 'byids'].forEach(function (prop) {
case 0: var value = $$1('#' + prop)[0].value;
url = new URL(baseAPIURL);
['query', 'sort', 'amount', 'page', 'byids'].forEach(function (prop) {
var value = $$1('#' + prop)[0].value;
if (value) { if (value) {
url.searchParams.set(prop, value); url.searchParams.set(prop, value);
} }
}); });
_context.next = 4; _context3.next = 4;
return processResults(url); return regeneratorRuntime.awrap(processResults(url));
case 4: case 4:
case "end": case "end":
return _context.stop(); return _context3.stop();
}
} }
}, _callee); }
})); });
}
function $submit() {
return _$submit.apply(this, arguments);
}
return $submit;
}()
}, },
$on: { $on: {
submit: function submit(e) { submit: function submit(e) {
@ -3532,11 +3488,11 @@
}, [['label', ['Sort by: ', ['select', { }, [['label', ['Sort by: ', ['select', {
id: 'sort' id: 'sort'
}, [// Todo: i18nize first values }, [// Todo: i18nize first values
['Date', 'date'], ['Downloads', 'downloads'], ['Favorited', 'favorites']].map(function (_ref) { ['Date', 'date'], ['Downloads', 'downloads'], ['Favorited', 'favorites']].map(function (_ref3) {
var _ref2 = _slicedToArray(_ref, 2), var _ref4 = _slicedToArray(_ref3, 2),
text = _ref2[0], text = _ref4[0],
_ref2$ = _ref2[1], _ref4$ = _ref4[1],
value = _ref2$ === void 0 ? text : _ref2$; value = _ref4$ === void 0 ? text : _ref4$;
return ['option', { return ['option', {
value: value value: value

3905
dist/index-es.js vendored

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

3909
dist/index-umd.js vendored

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

597
dist/svgcanvas-iife.js vendored
View File

@ -15,42 +15,6 @@ var SvgCanvas = (function () {
return _typeof(obj); return _typeof(obj);
} }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
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);
});
};
}
function _classCallCheck(instance, Constructor) { function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) { if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function"); throw new TypeError("Cannot call a class as a function");
@ -11449,8 +11413,38 @@ var SvgCanvas = (function () {
* any other value depends on the export of the targeted module. * any other value depends on the export of the targeted module.
*/ */
function importSetGlobal(_x, _x2) { function importSetGlobal(url, _ref) {
return _importSetGlobal.apply(this, arguments); var glob, returnDefault, modularVersion;
return regeneratorRuntime.async(function importSetGlobal$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
glob = _ref.global, returnDefault = _ref.returnDefault;
// Todo: Replace calls to this function with `import()` when supported
modularVersion = !('svgEditor' in window) || !window.svgEditor || window.svgEditor.modules !== false;
if (!modularVersion) {
_context.next = 4;
break;
}
return _context.abrupt("return", importModule(url, undefined, {
returnDefault: returnDefault
}));
case 4:
_context.next = 6;
return regeneratorRuntime.awrap(importScript(url));
case 6:
return _context.abrupt("return", window[glob]);
case 7:
case "end":
return _context.stop();
}
}
});
} }
/** /**
* *
@ -11461,45 +11455,6 @@ var SvgCanvas = (function () {
* script loading error * script loading error
*/ */
function _importSetGlobal() {
_importSetGlobal = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee(url, _ref) {
var glob, returnDefault, modularVersion;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
glob = _ref.global, returnDefault = _ref.returnDefault;
// Todo: Replace calls to this function with `import()` when supported
modularVersion = !('svgEditor' in window) || !window.svgEditor || window.svgEditor.modules !== false;
if (!modularVersion) {
_context.next = 4;
break;
}
return _context.abrupt("return", importModule(url, undefined, {
returnDefault: returnDefault
}));
case 4:
_context.next = 6;
return importScript(url);
case 6:
return _context.abrupt("return", window[glob]);
case 7:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return _importSetGlobal.apply(this, arguments);
}
function importScript(url) { function importScript(url) {
var atts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var atts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
@ -12351,16 +12306,16 @@ var SvgCanvas = (function () {
// } // }
var angle = getRotationAngle(child); var angle = getRotationAngle(child);
oldStartTransform = context_.getStartTransform(); oldStartTransform = context_.getStartTransform(); // const childxforms = [];
var childxforms = [];
context_.setStartTransform(child.getAttribute('transform')); context_.setStartTransform(child.getAttribute('transform'));
if (angle || hasMatrixTransform(childTlist)) { if (angle || hasMatrixTransform(childTlist)) {
var e2t = svgroot.createSVGTransform(); var e2t = svgroot.createSVGTransform();
e2t.setMatrix(matrixMultiply(tm, sm, tmn, _m)); e2t.setMatrix(matrixMultiply(tm, sm, tmn, _m));
childTlist.clear(); childTlist.clear();
childTlist.appendItem(e2t); childTlist.appendItem(e2t); // childxforms.push(e2t);
childxforms.push(e2t); // if not rotated or skewed, push the [T][S][-T] down to the child // if not rotated or skewed, push the [T][S][-T] down to the child
} else { } else {
// update the transform list with translate,scale,translate // update the transform list with translate,scale,translate
// slide the [T][S][-T] from the front to the back // slide the [T][S][-T] from the front to the back
@ -12384,10 +12339,10 @@ var SvgCanvas = (function () {
translateBack.setTranslate(t2.e, t2.f); translateBack.setTranslate(t2.e, t2.f);
childTlist.appendItem(translateBack); childTlist.appendItem(translateBack);
childTlist.appendItem(scale); childTlist.appendItem(scale);
childTlist.appendItem(translateOrigin); childTlist.appendItem(translateOrigin); // childxforms.push(translateBack);
childxforms.push(translateBack); // childxforms.push(scale);
childxforms.push(scale); // childxforms.push(translateOrigin);
childxforms.push(translateOrigin); // logMatrix(translateBack.matrix); // logMatrix(translateBack.matrix);
// logMatrix(scale.matrix); // logMatrix(scale.matrix);
} // not rotated } // not rotated
@ -14628,84 +14583,74 @@ var SvgCanvas = (function () {
*/ */
this.addExtension = this.addExtension = function _callee(name, extInitFunc, _ref3) {
/*#__PURE__*/ var jq, importLocale, argObj, extObj;
function () { return regeneratorRuntime.async(function _callee$(_context) {
var _ref4 = _asyncToGenerator( while (1) {
/*#__PURE__*/ switch (_context.prev = _context.next) {
regeneratorRuntime.mark(function _callee(name, extInitFunc, _ref3) { case 0:
var jq, importLocale, argObj, extObj; jq = _ref3.$, importLocale = _ref3.importLocale;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
jq = _ref3.$, importLocale = _ref3.importLocale;
if (!(typeof extInitFunc !== 'function')) { if (!(typeof extInitFunc !== 'function')) {
_context.next = 3; _context.next = 3;
break; break;
} }
throw new TypeError('Function argument expected for `svgcanvas.addExtension`'); throw new TypeError('Function argument expected for `svgcanvas.addExtension`');
case 3: case 3:
if (!(name in extensions)) { if (!(name in extensions)) {
_context.next = 5; _context.next = 5;
break; break;
} }
throw new Error('Cannot add extension "' + name + '", an extension by that name already exists.'); throw new Error('Cannot add extension "' + name + '", an extension by that name already exists.');
case 5: case 5:
// Provide private vars/funcs here. Is there a better way to do this? // Provide private vars/funcs here. Is there a better way to do this?
/** /**
* @typedef {module:svgcanvas.PrivateMethods} module:svgcanvas.ExtensionArgumentObject * @typedef {module:svgcanvas.PrivateMethods} module:svgcanvas.ExtensionArgumentObject
* @property {SVGSVGElement} svgroot See {@link module:svgcanvas~svgroot} * @property {SVGSVGElement} svgroot See {@link module:svgcanvas~svgroot}
* @property {SVGSVGElement} svgcontent See {@link module:svgcanvas~svgcontent} * @property {SVGSVGElement} svgcontent See {@link module:svgcanvas~svgcontent}
* @property {!(string|Integer)} nonce See {@link module:draw.Drawing#getNonce} * @property {!(string|Integer)} nonce See {@link module:draw.Drawing#getNonce}
* @property {module:select.SelectorManager} selectorManager * @property {module:select.SelectorManager} selectorManager
* @property {module:SVGEditor~ImportLocale} importLocale * @property {module:SVGEditor~ImportLocale} importLocale
*/ */
/** /**
* @type {module:svgcanvas.ExtensionArgumentObject} * @type {module:svgcanvas.ExtensionArgumentObject}
* @see {@link module:svgcanvas.PrivateMethods} source for the other methods/properties * @see {@link module:svgcanvas.PrivateMethods} source for the other methods/properties
*/ */
argObj = $$8.extend(canvas.getPrivateMethods(), { argObj = $$8.extend(canvas.getPrivateMethods(), {
$: jq, $: jq,
importLocale: importLocale, importLocale: importLocale,
svgroot: svgroot, svgroot: svgroot,
svgcontent: svgcontent, svgcontent: svgcontent,
nonce: getCurrentDrawing().getNonce(), nonce: getCurrentDrawing().getNonce(),
selectorManager: selectorManager selectorManager: selectorManager
}); });
_context.next = 8; _context.next = 8;
return extInitFunc(argObj); return regeneratorRuntime.awrap(extInitFunc(argObj));
case 8: case 8:
extObj = _context.sent; extObj = _context.sent;
if (extObj) { if (extObj) {
extObj.name = name; extObj.name = name;
} // eslint-disable-next-line require-atomic-updates } // eslint-disable-next-line require-atomic-updates
extensions[name] = extObj; extensions[name] = extObj;
return _context.abrupt("return", call('extension_added', extObj)); return _context.abrupt("return", call('extension_added', extObj));
case 12: case 12:
case "end": case "end":
return _context.stop(); return _context.stop();
}
} }
}, _callee); }
})); });
};
return function (_x, _x2, _x3) {
return _ref4.apply(this, arguments);
};
}();
/** /**
* This method sends back an array or a NodeList full of elements that * This method sends back an array or a NodeList full of elements that
* intersect the multi-select rubber-band-box on the currentLayer only. * intersect the multi-select rubber-band-box on the currentLayer only.
@ -17826,115 +17771,105 @@ var SvgCanvas = (function () {
* @returns {Promise<module:svgcanvas.ImageExportedResults>} Resolves to {@link module:svgcanvas.ImageExportedResults} * @returns {Promise<module:svgcanvas.ImageExportedResults>} Resolves to {@link module:svgcanvas.ImageExportedResults}
*/ */
this.rasterExport = this.rasterExport = function _callee2(imgType, quality, exportWindowName) {
/*#__PURE__*/ var opts,
function () { type,
var _ref5 = _asyncToGenerator( mimeType,
/*#__PURE__*/ _getIssues,
regeneratorRuntime.mark(function _callee2(imgType, quality, exportWindowName) { issues,
var opts, issueCodes,
type, svg,
mimeType, _ref4,
_getIssues, c,
issues, _args2 = arguments;
issueCodes,
svg,
_ref6,
c,
_args2 = arguments;
return regeneratorRuntime.wrap(function _callee2$(_context2) { return regeneratorRuntime.async(function _callee2$(_context2) {
while (1) { while (1) {
switch (_context2.prev = _context2.next) { switch (_context2.prev = _context2.next) {
case 0: case 0:
opts = _args2.length > 3 && _args2[3] !== undefined ? _args2[3] : {}; opts = _args2.length > 3 && _args2[3] !== undefined ? _args2[3] : {};
type = imgType === 'ICO' ? 'BMP' : imgType || 'PNG'; type = imgType === 'ICO' ? 'BMP' : imgType || 'PNG';
mimeType = 'image/' + type.toLowerCase(); mimeType = 'image/' + type.toLowerCase();
_getIssues = getIssues(), issues = _getIssues.issues, issueCodes = _getIssues.issueCodes; _getIssues = getIssues(), issues = _getIssues.issues, issueCodes = _getIssues.issueCodes;
svg = this.svgCanvasToString(); svg = this.svgCanvasToString();
if (canvg) { if (canvg) {
_context2.next = 10; _context2.next = 10;
break; break;
} }
_context2.next = 8; _context2.next = 8;
return importSetGlobal(curConfig.canvgPath + 'canvg.js', { return regeneratorRuntime.awrap(importSetGlobal(curConfig.canvgPath + 'canvg.js', {
global: 'canvg' global: 'canvg'
}); }));
case 8: case 8:
_ref6 = _context2.sent; _ref4 = _context2.sent;
canvg = _ref6.canvg; canvg = _ref4.canvg;
case 10: case 10:
if (!$$8('#export_canvas').length) { if (!$$8('#export_canvas').length) {
$$8('<canvas>', { $$8('<canvas>', {
id: 'export_canvas' id: 'export_canvas'
}).hide().appendTo('body'); }).hide().appendTo('body');
} }
c = $$8('#export_canvas')[0]; c = $$8('#export_canvas')[0];
c.width = canvas.contentW; c.width = canvas.contentW;
c.height = canvas.contentH; c.height = canvas.contentH;
_context2.next = 16; _context2.next = 16;
return canvg(c, svg); return regeneratorRuntime.awrap(canvg(c, svg));
case 16: case 16:
return _context2.abrupt("return", new Promise(function (resolve, reject) { return _context2.abrupt("return", new Promise(function (resolve, reject) {
// eslint-disable-line promise/avoid-new // eslint-disable-line promise/avoid-new
var dataURLType = type.toLowerCase(); var dataURLType = type.toLowerCase();
var datauri = quality ? c.toDataURL('image/' + dataURLType, quality) : c.toDataURL('image/' + dataURLType); var datauri = quality ? c.toDataURL('image/' + dataURLType, quality) : c.toDataURL('image/' + dataURLType);
var bloburl; var bloburl;
/** /**
* Called when `bloburl` is available for export. * Called when `bloburl` is available for export.
* @returns {void} * @returns {void}
*/ */
function done() { function done() {
var obj = { var obj = {
datauri: datauri, datauri: datauri,
bloburl: bloburl, bloburl: bloburl,
svg: svg, svg: svg,
issues: issues, issues: issues,
issueCodes: issueCodes, issueCodes: issueCodes,
type: imgType, type: imgType,
mimeType: mimeType, mimeType: mimeType,
quality: quality, quality: quality,
exportWindowName: exportWindowName exportWindowName: exportWindowName
}; };
if (!opts.avoidEvent) { if (!opts.avoidEvent) {
call('exported', obj); call('exported', obj);
}
resolve(obj);
} }
if (c.toBlob) { resolve(obj);
c.toBlob(function (blob) { }
bloburl = createObjectURL(blob);
done();
}, mimeType, quality);
return;
}
bloburl = dataURLToObjectURL(datauri); if (c.toBlob) {
done(); c.toBlob(function (blob) {
})); bloburl = createObjectURL(blob);
done();
}, mimeType, quality);
return;
}
case 17: bloburl = dataURLToObjectURL(datauri);
case "end": done();
return _context2.stop(); }));
}
case 17:
case "end":
return _context2.stop();
} }
}, _callee2, this); }
})); }, null, this);
};
return function (_x4, _x5, _x6) {
return _ref5.apply(this, arguments);
};
}();
/** /**
* @external jsPDF * @external jsPDF
*/ */
@ -17974,103 +17909,93 @@ var SvgCanvas = (function () {
*/ */
this.exportPDF = this.exportPDF = function _callee3(exportWindowName) {
/*#__PURE__*/ var outputType,
function () { modularVersion,
var _ref7 = _asyncToGenerator( res,
/*#__PURE__*/ orientation,
regeneratorRuntime.mark(function _callee3(exportWindowName) { unit,
var outputType, doc,
modularVersion, docTitle,
res, _getIssues2,
orientation, issues,
unit, issueCodes,
doc, svg,
docTitle, obj,
_getIssues2, _args3 = arguments;
issues,
issueCodes,
svg,
obj,
_args3 = arguments;
return regeneratorRuntime.wrap(function _callee3$(_context3) { return regeneratorRuntime.async(function _callee3$(_context3) {
while (1) { while (1) {
switch (_context3.prev = _context3.next) { switch (_context3.prev = _context3.next) {
case 0: case 0:
outputType = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : isChrome() ? 'save' : undefined; outputType = _args3.length > 1 && _args3[1] !== undefined ? _args3[1] : isChrome() ? 'save' : undefined;
if (window.jsPDF) {
_context3.next = 7;
break;
}
_context3.next = 4;
return importScript([// We do not currently have these paths configurable as they are
// currently global-only, so not Rolled-up
'jspdf/underscore-min.js', 'jspdf/jspdf.min.js']);
case 4:
modularVersion = !('svgEditor' in window) || !window.svgEditor || window.svgEditor.modules !== false; // Todo: Switch to `import()` when widely supported and available (also allow customization of path)
if (window.jsPDF) {
_context3.next = 7; _context3.next = 7;
return importScript(curConfig.jspdfPath + 'jspdf.plugin.svgToPdf.js', { break;
type: modularVersion ? 'module' : 'text/javascript' }
});
case 7: _context3.next = 4;
res = getResolution(); return regeneratorRuntime.awrap(importScript([// We do not currently have these paths configurable as they are
orientation = res.w > res.h ? 'landscape' : 'portrait'; // currently global-only, so not Rolled-up
unit = 'pt'; // curConfig.baseUnit; // We could use baseUnit, but that is presumably not intended for export purposes 'jspdf/underscore-min.js', 'jspdf/jspdf.min.js']));
// Todo: Give options to use predefined jsPDF formats like "a4", etc. from pull-down (with option to keep customizable)
doc = jsPDF({ case 4:
orientation: orientation, modularVersion = !('svgEditor' in window) || !window.svgEditor || window.svgEditor.modules !== false; // Todo: Switch to `import()` when widely supported and available (also allow customization of path)
unit: unit,
format: [res.w, res.h] // , compressPdf: true
}); _context3.next = 7;
docTitle = getDocumentTitle(); return regeneratorRuntime.awrap(importScript(curConfig.jspdfPath + 'jspdf.plugin.svgToPdf.js', {
doc.setProperties({ type: modularVersion ? 'module' : 'text/javascript'
title: docTitle }));
/* ,
subject: '',
author: '',
keywords: '',
creator: '' */
}); case 7:
_getIssues2 = getIssues(), issues = _getIssues2.issues, issueCodes = _getIssues2.issueCodes; res = getResolution();
svg = this.svgCanvasToString(); orientation = res.w > res.h ? 'landscape' : 'portrait';
doc.addSVG(svg, 0, 0); // doc.output('save'); // Works to open in a new unit = 'pt'; // curConfig.baseUnit; // We could use baseUnit, but that is presumably not intended for export purposes
// window; todo: configure this and other export // Todo: Give options to use predefined jsPDF formats like "a4", etc. from pull-down (with option to keep customizable)
// options to optionally work in this manner as
// opposed to opening a new tab
outputType = outputType || 'dataurlstring'; doc = jsPDF({
obj = { orientation: orientation,
svg: svg, unit: unit,
issues: issues, format: [res.w, res.h] // , compressPdf: true
issueCodes: issueCodes,
exportWindowName: exportWindowName,
outputType: outputType
};
obj.output = doc.output(outputType, outputType === 'save' ? exportWindowName || 'svg.pdf' : undefined);
call('exportedPDF', obj);
return _context3.abrupt("return", obj);
case 21: });
case "end": docTitle = getDocumentTitle();
return _context3.stop(); doc.setProperties({
} title: docTitle
/* ,
subject: '',
author: '',
keywords: '',
creator: '' */
});
_getIssues2 = getIssues(), issues = _getIssues2.issues, issueCodes = _getIssues2.issueCodes;
svg = this.svgCanvasToString();
doc.addSVG(svg, 0, 0); // doc.output('save'); // Works to open in a new
// window; todo: configure this and other export
// options to optionally work in this manner as
// opposed to opening a new tab
outputType = outputType || 'dataurlstring';
obj = {
svg: svg,
issues: issues,
issueCodes: issueCodes,
exportWindowName: exportWindowName,
outputType: outputType
};
obj.output = doc.output(outputType, outputType === 'save' ? exportWindowName || 'svg.pdf' : undefined);
call('exportedPDF', obj);
return _context3.abrupt("return", obj);
case 21:
case "end":
return _context3.stop();
} }
}, _callee3, this); }
})); }, null, this);
};
return function (_x7) {
return _ref7.apply(this, arguments);
};
}();
/** /**
* Returns the current drawing as raw SVG XML text. * Returns the current drawing as raw SVG XML text.
* @function module:svgcanvas.SvgCanvas#getSvgString * @function module:svgcanvas.SvgCanvas#getSvgString
@ -18798,10 +18723,10 @@ var SvgCanvas = (function () {
leaveContext: leaveContext, leaveContext: leaveContext,
setContext: setContext setContext: setContext
}; };
Object.entries(dr).forEach(function (_ref8) { Object.entries(dr).forEach(function (_ref5) {
var _ref9 = _slicedToArray(_ref8, 2), var _ref6 = _slicedToArray(_ref5, 2),
prop = _ref9[0], prop = _ref6[0],
propVal = _ref9[1]; propVal = _ref6[1];
canvas[prop] = propVal; canvas[prop] = propVal;
}); });

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -8,10 +8,9 @@
* *
* @module jQueryContextMenu * @module jQueryContextMenu
* @todo Update to latest version and adapt (and needs jQuery update as well): {@link https://github.com/swisnl/jQuery-contextMenu} * @todo Update to latest version and adapt (and needs jQuery update as well): {@link https://github.com/swisnl/jQuery-contextMenu}
* @version 1.01 * @version 1.0.1
* *
* @license * @license (GPL-2.0-or-later OR MIT)
* Terms of Use
* *
* This plugin is dual-licensed under the GNU General Public License * This plugin is dual-licensed under the GNU General Public License
* and the MIT License and is copyright A Beautiful Site, LLC. * and the MIT License and is copyright A Beautiful Site, LLC.

View File

@ -2,7 +2,7 @@
/** /**
* ext-mathjax.js * ext-mathjax.js
* *
* @license Apache * @license Apache-2.0
* *
* @copyright 2013 Jo Segaert * @copyright 2013 Jo Segaert
* *

File diff suppressed because it is too large Load Diff

38
package-lock.json generated
View File

@ -4011,9 +4011,9 @@
} }
}, },
"eslint-config-ash-nazg": { "eslint-config-ash-nazg": {
"version": "11.3.0", "version": "11.4.0",
"resolved": "https://registry.npmjs.org/eslint-config-ash-nazg/-/eslint-config-ash-nazg-11.3.0.tgz", "resolved": "https://registry.npmjs.org/eslint-config-ash-nazg/-/eslint-config-ash-nazg-11.4.0.tgz",
"integrity": "sha512-mQ6yQXBCxSy2nVk0LRNfyJWxUGMwXRhtOJyQJjF3lIHyjUdjYd2IMDpPBg7Ie/tftkkk6zEzQ+TBuUsHVHEtfg==", "integrity": "sha512-5HvR9GtShur4y1+QFzpF6v3aB4juRtAA8vi+cQA1gIPd6/rq3zSVwKgjefsU1DY3LttnE68DTLgfoYPnvDgPiA==",
"dev": true "dev": true
}, },
"eslint-config-standard": { "eslint-config-standard": {
@ -4229,17 +4229,27 @@
} }
}, },
"eslint-plugin-jsdoc": { "eslint-plugin-jsdoc": {
"version": "17.1.1", "version": "18.0.1",
"resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-17.1.1.tgz", "resolved": "https://registry.npmjs.org/eslint-plugin-jsdoc/-/eslint-plugin-jsdoc-18.0.1.tgz",
"integrity": "sha512-astLOTsj87UIzvDyiuAKbkgQgtChutazTDVxdG254tAtcvIVlWnPmlN7/dLnMYld/aHBhB4SWiUalMuKwTaynQ==", "integrity": "sha512-ofNW3JmuZD9Gqn+qp/M6vPUfyaWHtfiNdmuoYmjyBcf5Xh2SMe1dnFa+gTGpfZLrjvBCdIbjxryRiF2QdqlQ0g==",
"dev": true, "dev": true,
"requires": { "requires": {
"comment-parser": "^0.7.0", "comment-parser": "^0.7.0",
"debug": "^4.1.1", "debug": "^4.1.1",
"jsdoctypeparser": "^5.1.1", "jsdoctypeparser": "^6.0.0",
"lodash": "^4.17.15", "lodash": "^4.17.15",
"object.entries-ponyfill": "^1.0.1", "object.entries-ponyfill": "^1.0.1",
"regextras": "^0.6.1" "regextras": "^0.6.1",
"semver": "^6.3.0",
"spdx-expression-parse": "^3.0.0"
},
"dependencies": {
"semver": {
"version": "6.3.0",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz",
"integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
"dev": true
}
} }
}, },
"eslint-plugin-markdown": { "eslint-plugin-markdown": {
@ -5942,9 +5952,9 @@
} }
}, },
"jsdoctypeparser": { "jsdoctypeparser": {
"version": "5.1.1", "version": "6.0.0",
"resolved": "https://registry.npmjs.org/jsdoctypeparser/-/jsdoctypeparser-5.1.1.tgz", "resolved": "https://registry.npmjs.org/jsdoctypeparser/-/jsdoctypeparser-6.0.0.tgz",
"integrity": "sha512-APGygIJrT5bbz5lsVt8vyLJC0miEbQf/z9ZBfTr4RYvdia8AhWMRlYgivvwHG5zKD/VW3d6qpChCy64hpQET3A==", "integrity": "sha512-61VtBXLkHfOFSIdp/VDVNMksxK0ID0cPTNvxDR92tPA6K7r2AX0OcJegYxhJIwtpWKU4p3D9L3U02hhlP1kQLQ==",
"dev": true "dev": true
}, },
"jsdom": { "jsdom": {
@ -8042,9 +8052,9 @@
} }
}, },
"rollup": { "rollup": {
"version": "1.26.5", "version": "1.27.0",
"resolved": "https://registry.npmjs.org/rollup/-/rollup-1.26.5.tgz", "resolved": "https://registry.npmjs.org/rollup/-/rollup-1.27.0.tgz",
"integrity": "sha512-c6Pv0yWzjYNpy2DIhLFUnyP6e1UTGownr4IfpJcPY/k186RJjpaGGPRwKQ62KCauctG6dgtHt88pw1EGrPRkuA==", "integrity": "sha512-yaMna4MJ8LLEHhHl1ilgHakylf0LKeQctDxhngZLQ+W57GnXa5vtH7XKaK8zlAhNEhlWiH5YFVFt+QCDPUmNkw==",
"dev": true, "dev": true,
"requires": { "requires": {
"@types/estree": "*", "@types/estree": "*",

View File

@ -88,14 +88,14 @@
"babel-plugin-transform-object-rest-spread": "^7.0.0-beta.3", "babel-plugin-transform-object-rest-spread": "^7.0.0-beta.3",
"core-js-bundle": "^3.4.1", "core-js-bundle": "^3.4.1",
"eslint": "6.6.0", "eslint": "6.6.0",
"eslint-config-ash-nazg": "11.3.0", "eslint-config-ash-nazg": "11.4.0",
"eslint-config-standard": "14.1.0", "eslint-config-standard": "14.1.0",
"eslint-plugin-array-func": "^3.1.3", "eslint-plugin-array-func": "^3.1.3",
"eslint-plugin-compat": "^3.3.0", "eslint-plugin-compat": "^3.3.0",
"eslint-plugin-eslint-comments": "^3.1.2", "eslint-plugin-eslint-comments": "^3.1.2",
"eslint-plugin-html": "^6.0.0", "eslint-plugin-html": "^6.0.0",
"eslint-plugin-import": "2.18.2", "eslint-plugin-import": "2.18.2",
"eslint-plugin-jsdoc": "^17.1.1", "eslint-plugin-jsdoc": "^18.0.1",
"eslint-plugin-markdown": "^1.0.1", "eslint-plugin-markdown": "^1.0.1",
"eslint-plugin-no-use-extend-native": "^0.4.1", "eslint-plugin-no-use-extend-native": "^0.4.1",
"eslint-plugin-node": "10.0.0", "eslint-plugin-node": "10.0.0",
@ -118,7 +118,7 @@
"regenerator-runtime": "^0.13.3", "regenerator-runtime": "^0.13.3",
"remark-cli": "^7.0.1", "remark-cli": "^7.0.1",
"remark-lint-ordered-list-marker-value": "^1.0.3", "remark-lint-ordered-list-marker-value": "^1.0.3",
"rollup": "1.26.5", "rollup": "1.27.0",
"rollup-plugin-babel": "^4.3.3", "rollup-plugin-babel": "^4.3.3",
"rollup-plugin-re": "^1.0.7", "rollup-plugin-re": "^1.0.7",
"rollup-plugin-terser": "^5.1.2", "rollup-plugin-terser": "^5.1.2",

File diff suppressed because it is too large Load Diff