diff --git a/.eslintignore b/.eslintignore index cbba48f7..6e19ceb9 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,4 +1,5 @@ node_modules +ignore dist docs/jsdoc diff --git a/dist/canvg.js b/dist/canvg.js index 2c6df291..9296533b 100644 --- a/dist/canvg.js +++ b/dist/canvg.js @@ -15,42 +15,6 @@ var canvg = (function (exports) { 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) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); @@ -4684,36 +4648,26 @@ var canvg = (function (exports) { }; // load from url - svg.load = - /*#__PURE__*/ - function () { - var _ref12 = _asyncToGenerator( - /*#__PURE__*/ - regeneratorRuntime.mark(function _callee(ctx, url) { - var dom; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return svg.ajax(url, true); + svg.load = function _callee(ctx, url) { + var dom; + return regeneratorRuntime.async(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return regeneratorRuntime.awrap(svg.ajax(url, true)); - case 2: - dom = _context.sent; - return _context.abrupt("return", svg.loadXml(ctx, dom)); + case 2: + dom = _context.sent; + return _context.abrupt("return", svg.loadXml(ctx, dom)); - case 4: - case "end": - return _context.stop(); - } + case 4: + case "end": + return _context.stop(); } - }, _callee); - })); - - return function (_x2, _x3) { - return _ref12.apply(this, arguments); - }; - }(); // load from xml + } + }); + }; // load from xml svg.loadXml = function (ctx, xml) { @@ -4934,9 +4888,9 @@ var canvg = (function (exports) { checkPath: function checkPath(element, ctx) { var _this26 = this; - this.events.forEach(function (_ref13, i) { - var x = _ref13.x, - y = _ref13.y; + this.events.forEach(function (_ref12, i) { + var x = _ref12.x, + y = _ref12.y; if (ctx.isPointInPath && ctx.isPointInPath(x, y)) { _this26.eventElements[i] = element; @@ -4946,9 +4900,9 @@ var canvg = (function (exports) { checkBoundingBox: function checkBoundingBox(element, bb) { var _this27 = this; - this.events.forEach(function (_ref14, i) { - var x = _ref14.x, - y = _ref14.y; + this.events.forEach(function (_ref13, i) { + var x = _ref13.x, + y = _ref13.y; if (bb.isPointInBox(x, y)) { _this27.eventElements[i] = element; diff --git a/dist/extensions/ext-arrows.js b/dist/extensions/ext-arrows.js index c34ac71c..76e7c98b 100644 --- a/dist/extensions/ext-arrows.js +++ b/dist/extensions/ext-arrows.js @@ -1,42 +1,6 @@ var svgEditorExtension_arrows = (function () { '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) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); @@ -211,366 +175,346 @@ var svgEditorExtension_arrows = (function () { */ var extArrows = { name: 'arrows', - init: function () { - var _init = _asyncToGenerator( - /*#__PURE__*/ - regeneratorRuntime.mark(function _callee2(S) { - var strings, svgEditor, svgCanvas, addElem, nonce, $, prefix, selElems, arrowprefix, randomizeIds, setArrowNonce, unsetArrowNonce, pathdata, getLinked, showPanel, resetMarker, addMarker, setArrow, colorChanged, contextTools; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - colorChanged = function _ref10(elem) { - var color = elem.getAttribute('stroke'); - var mtypes = ['start', 'mid', 'end']; - var defs = svgCanvas.findDefs(); - $.each(mtypes, function (i, type) { - var marker = getLinked(elem, 'marker-' + type); + init: function init(S) { + var strings, svgEditor, svgCanvas, addElem, nonce, $, prefix, selElems, arrowprefix, randomizeIds, setArrowNonce, unsetArrowNonce, pathdata, getLinked, showPanel, resetMarker, addMarker, setArrow, colorChanged, contextTools; + return regeneratorRuntime.async(function init$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + colorChanged = function _ref10(elem) { + var color = elem.getAttribute('stroke'); + var mtypes = ['start', 'mid', 'end']; + var defs = svgCanvas.findDefs(); + $.each(mtypes, function (i, type) { + var marker = getLinked(elem, 'marker-' + type); - if (!marker) { - return; + if (!marker) { + return; + } + + var curColor = $(marker).children().attr('fill'); + var curD = $(marker).children().attr('d'); + + if (curColor === color) { + return; + } + + var allMarkers = $(defs).find('marker'); + var newMarker = null; // Different color, check if already made + + 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'); - var curD = $(marker).children().attr('d'); + 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); + } - if (curColor === color) { - return; - } + $(elem).attr('marker-' + type, 'url(#' + newMarker.id + ')'); // Check if last marker can be removed - var allMarkers = $(defs).find('marker'); - var newMarker = null; // Different color, check if already made + var remove = true; + $(S.svgcontent).find('line, polyline, path, polygon').each(function () { + var element = this; // eslint-disable-line consistent-this - 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 - } - }); - - 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; + $.each(mtypes, function (j, mtype) { + if ($(element).attr('marker-' + mtype) === 'url(#' + marker.id + ')') { + remove = false; + return remove; } 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); - return marker; - }; - - 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 (!remove) { + return false; } - if (!start && !mid && !end) { - val = 'none'; - } + return undefined; + }); // Not found, so can safely remove - $('#arrow_list').val(val); + if (remove) { + $(marker).remove(); } - }; + }); + }; - getLinked = function _ref5(elem, attr) { - var str = elem.getAttribute(attr); + setArrow = function _ref9() { + resetMarker(); + var type = this.value; - if (!str) { - return null; - } + if (type === 'none') { + return; + } // Set marker on element - var m = str.match(_wrapRegExp(/\(#(.+)\)/, { - id: 1 - })); - if (!m || !m.groups.id) { - return null; - } + var dir = 'fw'; - 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 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; + 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'; } - 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} - */ + addMarker(dir, type); + svgCanvas.changeSelectedAttribute('marker-' + type, 'url(#' + pathdata[dir].id + ')'); + svgCanvas.call('changed', selElems); + }; - 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 + 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]; - $('#arrow_list option')[0].id = 'connector_no_arrow'; - }, - addLangData: function () { - var _addLangData = _asyncToGenerator( - /*#__PURE__*/ - regeneratorRuntime.mark(function _callee(_ref) { - var lang, importLocale, _ref2, langList; + if (type === 'mid') { + data.refx = 5; + } - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - lang = _ref.lang, importLocale = _ref.importLocale; - _context.next = 3; - return importLocale(); + var marker = svgCanvas.getElem(id); - case 3: - _ref2 = _context.sent; - langList = _ref2.langList; - return _context.abrupt("return", { - data: langList - }); + 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 - 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; - }(), - 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; + marker.setAttribute('refX', data.refx); + return marker; + }; - while (i--) { - var elem = selElems[i]; + resetMarker = function _ref7() { + var el = selElems[0]; + el.removeAttribute('marker-start'); + el.removeAttribute('marker-mid'); + el.removeAttribute('marker-end'); + }; - if (elem && markerElems.includes(elem.tagName)) { - if (opts.selectedElement && !opts.multiselected) { - showPanel(true); - } else { - showPanel(false); - } + 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) { + 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 { 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); + } else { + showPanel(false); } } - }); + }, + elementChanged: function elementChanged(opts) { + var elem = opts.elems[0]; - case 21: - case "end": - return _context2.stop(); - } + 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); + } + } + }); + + case 21: + case "end": + return _context2.stop(); } - }, _callee2, this); - })); - - function init(_x) { - return _init.apply(this, arguments); - } - - return init; - }() + } + }, null, this); + } }; return extArrows; diff --git a/dist/extensions/ext-closepath.js b/dist/extensions/ext-closepath.js index 92f67eb3..a6643596 100644 --- a/dist/extensions/ext-closepath.js +++ b/dist/extensions/ext-closepath.js @@ -1,42 +1,6 @@ var svgEditorExtension_closepath = (function () { '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 * @@ -49,125 +13,115 @@ var svgEditorExtension_closepath = (function () { // The button toggles whether the path is open or closed var extClosepath = { name: 'closepath', - init: function () { - var _init = _asyncToGenerator( - /*#__PURE__*/ - regeneratorRuntime.mark(function _callee(_ref) { - var importLocale, $, strings, svgEditor, selElems, updateButton, showPanel, toggleClosed, buttons; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - importLocale = _ref.importLocale, $ = _ref.$; - _context.next = 3; - return importLocale(); + init: function init(_ref) { + var importLocale, $, strings, svgEditor, selElems, updateButton, showPanel, toggleClosed, buttons; + return regeneratorRuntime.async(function init$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + importLocale = _ref.importLocale, $ = _ref.$; + _context.next = 3; + return regeneratorRuntime.awrap(importLocale()); - case 3: - strings = _context.sent; - svgEditor = this; + case 3: + strings = _context.sent; + svgEditor = this; - updateButton = function updateButton(path) { - var seglist = path.pathSegList, - closed = seglist.getItem(seglist.numberOfItems - 1).pathSegType === 1, - showbutton = closed ? '#tool_openpath' : '#tool_closepath', - hidebutton = closed ? '#tool_closepath' : '#tool_openpath'; - $(hidebutton).hide(); - $(showbutton).show(); - }; + updateButton = function updateButton(path) { + var seglist = path.pathSegList, + closed = seglist.getItem(seglist.numberOfItems - 1).pathSegType === 1, + showbutton = closed ? '#tool_openpath' : '#tool_closepath', + hidebutton = closed ? '#tool_closepath' : '#tool_openpath'; + $(hidebutton).hide(); + $(showbutton).show(); + }; - showPanel = function showPanel(on) { - $('#closepath_panel').toggle(on); + showPanel = function showPanel(on) { + $('#closepath_panel').toggle(on); - if (on) { - var path = selElems[0]; - - if (path) { - updateButton(path); - } - } - }; - - toggleClosed = function toggleClosed() { + if (on) { var path = selElems[0]; 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); } - }; + } + }; - buttons = [{ - id: 'tool_openpath', - icon: svgEditor.curConfig.extIconsPath + 'openpath.png', - type: 'context', - panel: 'closepath_panel', - events: { - click: function click() { - toggleClosed(); - } + toggleClosed = function toggleClosed() { + var path = selElems[0]; + + 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()); } - }, { - id: 'tool_closepath', - icon: svgEditor.curConfig.extIconsPath + 'closepath.png', - type: 'context', - panel: 'closepath_panel', - events: { - click: function click() { - toggleClosed(); - } + + updateButton(path); + } + }; + + buttons = [{ + id: 'tool_openpath', + icon: svgEditor.curConfig.extIconsPath + 'openpath.png', + type: 'context', + panel: 'closepath_panel', + events: { + click: function click() { + toggleClosed(); } - }]; - 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; + } + }, { + id: 'tool_closepath', + icon: svgEditor.curConfig.extIconsPath + 'closepath.png', + type: 'context', + panel: 'closepath_panel', + events: { + click: function click() { + toggleClosed(); + } + } + }]; + 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--) { - var elem = selElems[i]; + while (i--) { + var elem = selElems[i]; - if (elem && elem.tagName === 'path') { - if (opts.selectedElement && !opts.multiselected) { - showPanel(true); - } else { - showPanel(false); - } + if (elem && elem.tagName === 'path') { + if (opts.selectedElement && !opts.multiselected) { + showPanel(true); } else { showPanel(false); } + } else { + showPanel(false); } } - }); + } + }); - case 10: - case "end": - return _context.stop(); - } + case 10: + case "end": + return _context.stop(); } - }, _callee, this); - })); - - function init(_x) { - return _init.apply(this, arguments); - } - - return init; - }() + } + }, null, this); + } }; return extClosepath; diff --git a/dist/extensions/ext-connector.js b/dist/extensions/ext-connector.js index 31ad0ffb..cf43f6a1 100644 --- a/dist/extensions/ext-connector.js +++ b/dist/extensions/ext-connector.js @@ -1,42 +1,6 @@ var svgEditorExtension_connector = (function () { '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); - }); - }; - } - /* eslint-disable unicorn/no-fn-reference-in-iterator */ /** @@ -49,649 +13,639 @@ var svgEditorExtension_connector = (function () { */ var extConnector = { name: 'connector', - init: function () { - var _init = _asyncToGenerator( - /*#__PURE__*/ - regeneratorRuntime.mark(function _callee(S) { - var svgEditor, svgCanvas, getElem, $, svgroot, importLocale, addElem, selManager, connSel, elData, strings, startX, startY, curLine, startElem, endElem, seNs, svgcontent, started, connections, selElems, getBBintersect, getOffset, showPanel, setPoint, updateLine, findConnectors, updateConnectors, init, buttons; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - init = function _ref9() { - // Make sure all connectors have data set - $(svgcontent).find('*').each(function () { - var conn = this.getAttributeNS(seNs, 'connector'); + init: function init(S) { + var svgEditor, svgCanvas, getElem, $, svgroot, importLocale, addElem, selManager, connSel, elData, strings, startX, startY, curLine, startElem, endElem, seNs, svgcontent, started, connections, selElems, getBBintersect, getOffset, showPanel, setPoint, updateLine, findConnectors, updateConnectors, init, buttons; + return regeneratorRuntime.async(function init$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + init = function _ref9() { + // Make sure all connectors have data set + $(svgcontent).find('*').each(function () { + var conn = this.getAttributeNS(seNs, 'connector'); - if (conn) { - this.setAttribute('class', connSel.substr(1)); - var connData = conn.split(' '); - var sbb = svgCanvas.getStrokedBBox([getElem(connData[0])]); - var ebb = svgCanvas.getStrokedBBox([getElem(connData[1])]); - $(this).data('c_start', connData[0]).data('c_end', connData[1]).data('start_bb', sbb).data('end_bb', ebb); - svgCanvas.getEditorNS(true); - } - }); // updateConnectors(); - }; - - updateConnectors = function _ref8(elems) { - // Updates connector lines based on selected elements - // Is not used on mousemove, as it runs getStrokedBBox every time, - // which isn't necessary there. - findConnectors(elems); - - if (connections.length) { - // Update line with element - var i = connections.length; - - while (i--) { - var conn = connections[i]; - var line = conn.connector; - var elem = conn.elem; // const sw = line.getAttribute('stroke-width') * 5; - - var pre = conn.is_start ? 'start' : 'end'; // Update bbox for this element - - var bb = svgCanvas.getStrokedBBox([elem]); - bb.x = conn.start_x; - bb.y = conn.start_y; - elData(line, pre + '_bb', bb); - /* const addOffset = */ - - elData(line, pre + '_off'); - var altPre = conn.is_start ? 'end' : 'start'; // Get center pt of connected element - - var bb2 = elData(line, altPre + '_bb'); - var srcX = bb2.x + bb2.width / 2; - var srcY = bb2.y + bb2.height / 2; // Set point of element being moved - - var pt = getBBintersect(srcX, srcY, bb, getOffset(pre, line)); - setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true); // Set point of connected element - - var pt2 = getBBintersect(pt.x, pt.y, elData(line, altPre + '_bb'), getOffset(altPre, line)); - setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true); // Update points attribute manually for webkit - - if (navigator.userAgent.includes('AppleWebKit')) { - var pts = line.points; - var len = pts.numberOfItems; - var ptArr = []; - - for (var j = 0; j < len; j++) { - pt = pts.getItem(j); - ptArr[j] = pt.x + ',' + pt.y; - } - - line.setAttribute('points', ptArr.join(' ')); - } - } + if (conn) { + this.setAttribute('class', connSel.substr(1)); + var connData = conn.split(' '); + var sbb = svgCanvas.getStrokedBBox([getElem(connData[0])]); + var ebb = svgCanvas.getStrokedBBox([getElem(connData[1])]); + $(this).data('c_start', connData[0]).data('c_end', connData[1]).data('start_bb', sbb).data('end_bb', ebb); + svgCanvas.getEditorNS(true); } - }; + }); // updateConnectors(); + }; - findConnectors = function _ref7() { - var elems = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : selElems; - var connectors = $(svgcontent).find(connSel); - connections = []; // Loop through connectors to see if one is connected to the element + updateConnectors = function _ref8(elems) { + // Updates connector lines based on selected elements + // Is not used on mousemove, as it runs getStrokedBBox every time, + // which isn't necessary there. + findConnectors(elems); - connectors.each(function () { - var addThis; - /** - * - * @returns {void} - */ - - function add() { - if (elems.includes(this)) { - // Pretend this element is selected - addThis = true; - } - } // Grab the ends - - - var parts = []; - ['start', 'end'].forEach(function (pos, i) { - var key = 'c_' + pos; - var part = elData(this, key); - - if (part === null || part === undefined) { - // Does this ever return nullish values? - part = document.getElementById(this.attributes['se:connector'].value.split(' ')[i]); - elData(this, 'c_' + pos, part.id); - elData(this, pos + '_bb', svgCanvas.getStrokedBBox([part])); - } else part = document.getElementById(part); - - parts.push(part); - }, this); - - for (var i = 0; i < 2; i++) { - var cElem = parts[i]; - addThis = false; // The connected element might be part of a selected group - - $(cElem).parents().each(add); - - if (!cElem || !cElem.parentNode) { - $(this).remove(); - continue; - } - - if (elems.includes(cElem) || addThis) { - var bb = svgCanvas.getStrokedBBox([cElem]); - connections.push({ - elem: cElem, - connector: this, - is_start: i === 0, - start_x: bb.x, - start_y: bb.y - }); - } - } - }); - }; - - updateLine = function _ref6(diffX, diffY) { + if (connections.length) { // Update line with element var i = connections.length; while (i--) { var conn = connections[i]; - var line = conn.connector; // const {elem} = conn; + var line = conn.connector; + var elem = conn.elem; // const sw = line.getAttribute('stroke-width') * 5; - var pre = conn.is_start ? 'start' : 'end'; // const sw = line.getAttribute('stroke-width') * 5; - // Update bbox for this element + var pre = conn.is_start ? 'start' : 'end'; // Update bbox for this element - var bb = elData(line, pre + '_bb'); - bb.x = conn.start_x + diffX; - bb.y = conn.start_y + diffY; + var bb = svgCanvas.getStrokedBBox([elem]); + bb.x = conn.start_x; + bb.y = conn.start_y; elData(line, pre + '_bb', bb); + /* const addOffset = */ + + elData(line, pre + '_off'); var altPre = conn.is_start ? 'end' : 'start'; // Get center pt of connected element var bb2 = elData(line, altPre + '_bb'); var srcX = bb2.x + bb2.width / 2; var srcY = bb2.y + bb2.height / 2; // Set point of element being moved - var pt = getBBintersect(srcX, srcY, bb, getOffset(pre, line)); // $(line).data(pre+'_off')?sw:0 - + var pt = getBBintersect(srcX, srcY, bb, getOffset(pre, line)); setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true); // Set point of connected element var pt2 = getBBintersect(pt.x, pt.y, elData(line, altPre + '_bb'), getOffset(altPre, line)); - setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true); - } - }; + setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true); // Update points attribute manually for webkit - setPoint = function _ref5(elem, pos, x, y, setMid) { - var pts = elem.points; - var pt = svgroot.createSVGPoint(); - pt.x = x; - pt.y = y; + if (navigator.userAgent.includes('AppleWebKit')) { + var pts = line.points; + var len = pts.numberOfItems; + var ptArr = []; - if (pos === 'end') { - pos = pts.numberOfItems - 1; - } // TODO: Test for this on init, then use alt only if needed - - - try { - pts.replaceItem(pt, pos); - } catch (err) { - // Should only occur in FF which formats points attr as "n,n n,n", so just split - var ptArr = elem.getAttribute('points').split(' '); - - for (var i = 0; i < ptArr.length; i++) { - if (i === pos) { - ptArr[i] = x + ',' + y; + for (var j = 0; j < len; j++) { + pt = pts.getItem(j); + ptArr[j] = pt.x + ',' + pt.y; } + + line.setAttribute('points', ptArr.join(' ')); + } + } + } + }; + + findConnectors = function _ref7() { + var elems = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : selElems; + var connectors = $(svgcontent).find(connSel); + connections = []; // Loop through connectors to see if one is connected to the element + + connectors.each(function () { + var addThis; + /** + * + * @returns {void} + */ + + function add() { + if (elems.includes(this)) { + // Pretend this element is selected + addThis = true; + } + } // Grab the ends + + + var parts = []; + ['start', 'end'].forEach(function (pos, i) { + var key = 'c_' + pos; + var part = elData(this, key); + + if (part === null || part === undefined) { + // Does this ever return nullish values? + part = document.getElementById(this.attributes['se:connector'].value.split(' ')[i]); + elData(this, 'c_' + pos, part.id); + elData(this, pos + '_bb', svgCanvas.getStrokedBBox([part])); + } else part = document.getElementById(part); + + parts.push(part); + }, this); + + for (var i = 0; i < 2; i++) { + var cElem = parts[i]; + addThis = false; // The connected element might be part of a selected group + + $(cElem).parents().each(add); + + if (!cElem || !cElem.parentNode) { + $(this).remove(); + continue; } - elem.setAttribute('points', ptArr.join(' ')); + if (elems.includes(cElem) || addThis) { + var bb = svgCanvas.getStrokedBBox([cElem]); + connections.push({ + elem: cElem, + connector: this, + is_start: i === 0, + start_x: bb.x, + start_y: bb.y + }); + } + } + }); + }; + + updateLine = function _ref6(diffX, diffY) { + // Update line with element + var i = connections.length; + + while (i--) { + var conn = connections[i]; + var line = conn.connector; // const {elem} = conn; + + var pre = conn.is_start ? 'start' : 'end'; // const sw = line.getAttribute('stroke-width') * 5; + // Update bbox for this element + + var bb = elData(line, pre + '_bb'); + bb.x = conn.start_x + diffX; + bb.y = conn.start_y + diffY; + elData(line, pre + '_bb', bb); + var altPre = conn.is_start ? 'end' : 'start'; // Get center pt of connected element + + var bb2 = elData(line, altPre + '_bb'); + var srcX = bb2.x + bb2.width / 2; + var srcY = bb2.y + bb2.height / 2; // Set point of element being moved + + var pt = getBBintersect(srcX, srcY, bb, getOffset(pre, line)); // $(line).data(pre+'_off')?sw:0 + + setPoint(line, conn.is_start ? 0 : 'end', pt.x, pt.y, true); // Set point of connected element + + var pt2 = getBBintersect(pt.x, pt.y, elData(line, altPre + '_bb'), getOffset(altPre, line)); + setPoint(line, conn.is_start ? 'end' : 0, pt2.x, pt2.y, true); + } + }; + + setPoint = function _ref5(elem, pos, x, y, setMid) { + var pts = elem.points; + var pt = svgroot.createSVGPoint(); + pt.x = x; + pt.y = y; + + if (pos === 'end') { + pos = pts.numberOfItems - 1; + } // TODO: Test for this on init, then use alt only if needed + + + try { + pts.replaceItem(pt, pos); + } catch (err) { + // Should only occur in FF which formats points attr as "n,n n,n", so just split + var ptArr = elem.getAttribute('points').split(' '); + + for (var i = 0; i < ptArr.length; i++) { + if (i === pos) { + ptArr[i] = x + ',' + y; + } } - if (setMid) { - // Add center point - var ptStart = pts.getItem(0); - var ptEnd = pts.getItem(pts.numberOfItems - 1); - setPoint(elem, 1, (ptEnd.x + ptStart.x) / 2, (ptEnd.y + ptStart.y) / 2); + elem.setAttribute('points', ptArr.join(' ')); + } + + if (setMid) { + // Add center point + var ptStart = pts.getItem(0); + var ptEnd = pts.getItem(pts.numberOfItems - 1); + setPoint(elem, 1, (ptEnd.x + ptStart.x) / 2, (ptEnd.y + ptStart.y) / 2); + } + }; + + showPanel = function _ref4(on) { + var connRules = $('#connector_rules'); + + if (!connRules.length) { + connRules = $('').appendTo('head'); + } + + connRules.text(!on ? '' : '#tool_clone, #tool_topath, #tool_angle, #xy_panel { display: none !important; }'); + $('#connector_panel').toggle(on); + }; + + getOffset = function _ref3(side, line) { + var giveOffset = line.getAttribute('marker-' + side); // const giveOffset = $(line).data(side+'_off'); + // TODO: Make this number (5) be based on marker width/height + + var size = line.getAttribute('stroke-width') * 5; + return giveOffset ? size : 0; + }; + + getBBintersect = function _ref2(x, y, bb, offset) { + if (offset) { + offset -= 0; + bb = $.extend({}, bb); + bb.width += offset; + bb.height += offset; + bb.x -= offset / 2; + bb.y -= offset / 2; + } + + var midX = bb.x + bb.width / 2; + var midY = bb.y + bb.height / 2; + var lenX = x - midX; + var lenY = y - midY; + var slope = Math.abs(lenY / lenX); + var ratio; + + if (slope < bb.height / bb.width) { + ratio = bb.width / 2 / Math.abs(lenX); + } else { + ratio = lenY ? bb.height / 2 / Math.abs(lenY) : 0; + } + + return { + x: midX + lenX * ratio, + y: midY + lenY * ratio + }; + }; + + svgEditor = this; + svgCanvas = svgEditor.canvas; + getElem = svgCanvas.getElem; + $ = S.$, svgroot = S.svgroot, importLocale = S.importLocale, addElem = svgCanvas.addSVGElementFromJson, selManager = S.selectorManager, connSel = '.se_connector', elData = $.data; + _context.next = 14; + return regeneratorRuntime.awrap(importLocale()); + + case 14: + strings = _context.sent; + svgcontent = S.svgcontent, started = false, connections = [], selElems = []; + /** + * + * @param {Float} x + * @param {Float} y + * @param {module:utilities.BBoxObject} bb + * @param {Float} offset + * @returns {module:math.XYObject} + */ + + // Do once + (function () { + var gse = svgCanvas.groupSelectedElements; + + svgCanvas.groupSelectedElements = function () { + svgCanvas.removeFromSelection($(connSel).toArray()); + + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; } + + return gse.apply(this, args); }; - showPanel = function _ref4(on) { - var connRules = $('#connector_rules'); + var mse = svgCanvas.moveSelectedElements; - if (!connRules.length) { - connRules = $('').appendTo('head'); + svgCanvas.moveSelectedElements = function () { + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; } - connRules.text(!on ? '' : '#tool_clone, #tool_topath, #tool_angle, #xy_panel { display: none !important; }'); - $('#connector_panel').toggle(on); + var cmd = mse.apply(this, args); + updateConnectors(); + return cmd; }; - getOffset = function _ref3(side, line) { - var giveOffset = line.getAttribute('marker-' + side); // const giveOffset = $(line).data(side+'_off'); - // TODO: Make this number (5) be based on marker width/height + seNs = svgCanvas.getEditorNS(); + })(); + /** + * Do on reset. + * @returns {void} + */ - var size = line.getAttribute('stroke-width') * 5; - return giveOffset ? size : 0; - }; - getBBintersect = function _ref2(x, y, bb, offset) { - if (offset) { - offset -= 0; - bb = $.extend({}, bb); - bb.width += offset; - bb.height += offset; - bb.x -= offset / 2; - bb.y -= offset / 2; - } - - var midX = bb.x + bb.width / 2; - var midY = bb.y + bb.height / 2; - var lenX = x - midX; - var lenY = y - midY; - var slope = Math.abs(lenY / lenX); - var ratio; - - if (slope < bb.height / bb.width) { - ratio = bb.width / 2 / Math.abs(lenX); - } else { - ratio = lenY ? bb.height / 2 / Math.abs(lenY) : 0; + // $(svgroot).parent().mousemove(function (e) { + // // if (started + // // || svgCanvas.getMode() !== 'connector' + // // || e.target.parentNode.parentNode !== svgcontent) return; + // + // console.log('y') + // // if (e.target.parentNode.parentNode === svgcontent) { + // // + // // } + // }); + buttons = [{ + id: 'mode_connect', + type: 'mode', + icon: svgEditor.curConfig.imgPath + 'cut.png', + includeWith: { + button: '#tool_line', + isDefault: false, + position: 1 + }, + events: { + click: function click() { + svgCanvas.setMode('connector'); } + } + }]; + return _context.abrupt("return", { + name: strings.name, + svgicons: svgEditor.curConfig.imgPath + 'conn.svg', + buttons: strings.buttons.map(function (button, i) { + return Object.assign(buttons[i], button); + }), + /* async */ + addLangData: function addLangData(_ref) { + var lang = _ref.lang; + // , importLocale: importLoc return { - x: midX + lenX * ratio, - y: midY + lenY * ratio + data: strings.langList }; - }; + }, + mouseDown: function mouseDown(opts) { + var e = opts.event; + startX = opts.start_x; + startY = opts.start_y; + var mode = svgCanvas.getMode(); + var initStroke = svgEditor.curConfig.initStroke; - svgEditor = this; - svgCanvas = svgEditor.canvas; - getElem = svgCanvas.getElem; - $ = S.$, svgroot = S.svgroot, importLocale = S.importLocale, addElem = svgCanvas.addSVGElementFromJson, selManager = S.selectorManager, connSel = '.se_connector', elData = $.data; - _context.next = 14; - return importLocale(); - - case 14: - strings = _context.sent; - svgcontent = S.svgcontent, started = false, connections = [], selElems = []; - /** - * - * @param {Float} x - * @param {Float} y - * @param {module:utilities.BBoxObject} bb - * @param {Float} offset - * @returns {module:math.XYObject} - */ - - // Do once - (function () { - var gse = svgCanvas.groupSelectedElements; - - svgCanvas.groupSelectedElements = function () { - svgCanvas.removeFromSelection($(connSel).toArray()); - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - return gse.apply(this, args); - }; - - var mse = svgCanvas.moveSelectedElements; - - svgCanvas.moveSelectedElements = function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - - var cmd = mse.apply(this, args); - updateConnectors(); - return cmd; - }; - - seNs = svgCanvas.getEditorNS(); - })(); - /** - * Do on reset. - * @returns {void} - */ - - - // $(svgroot).parent().mousemove(function (e) { - // // if (started - // // || svgCanvas.getMode() !== 'connector' - // // || e.target.parentNode.parentNode !== svgcontent) return; - // - // console.log('y') - // // if (e.target.parentNode.parentNode === svgcontent) { - // // - // // } - // }); - buttons = [{ - id: 'mode_connect', - type: 'mode', - icon: svgEditor.curConfig.imgPath + 'cut.png', - includeWith: { - button: '#tool_line', - isDefault: false, - position: 1 - }, - events: { - click: function click() { - svgCanvas.setMode('connector'); - } - } - }]; - return _context.abrupt("return", { - name: strings.name, - svgicons: svgEditor.curConfig.imgPath + 'conn.svg', - buttons: strings.buttons.map(function (button, i) { - return Object.assign(buttons[i], button); - }), - - /* async */ - addLangData: function addLangData(_ref) { - var lang = _ref.lang; - // , importLocale: importLoc - return { - data: strings.langList - }; - }, - mouseDown: function mouseDown(opts) { - var e = opts.event; - startX = opts.start_x; - startY = opts.start_y; - var mode = svgCanvas.getMode(); - var initStroke = svgEditor.curConfig.initStroke; - - if (mode === 'connector') { - if (started) { - return undefined; - } - - var mouseTarget = e.target; - var parents = $(mouseTarget).parents(); - - if ($.inArray(svgcontent, parents) !== -1) { - // Connectable element - // If child of foreignObject, use parent - var fo = $(mouseTarget).closest('foreignObject'); - startElem = fo.length ? fo[0] : mouseTarget; // Get center of source element - - var bb = svgCanvas.getStrokedBBox([startElem]); - var x = bb.x + bb.width / 2; - var y = bb.y + bb.height / 2; - started = true; - curLine = addElem({ - element: 'polyline', - attr: { - id: svgCanvas.getNextId(), - points: x + ',' + y + ' ' + x + ',' + y + ' ' + startX + ',' + startY, - stroke: '#' + initStroke.color, - 'stroke-width': !startElem.stroke_width || startElem.stroke_width === 0 ? initStroke.width : startElem.stroke_width, - fill: 'none', - opacity: initStroke.opacity, - style: 'pointer-events:none' - } - }); - elData(curLine, 'start_bb', bb); - } - - return { - started: true - }; - } - - if (mode === 'select') { - findConnectors(); - } - - return undefined; - }, - mouseMove: function mouseMove(opts) { - var zoom = svgCanvas.getZoom(); // const e = opts.event; - - var x = opts.mouse_x / zoom; - var y = opts.mouse_y / zoom; - var diffX = x - startX, - diffY = y - startY; - var mode = svgCanvas.getMode(); - - if (mode === 'connector' && started) { - // const sw = curLine.getAttribute('stroke-width') * 3; - // Set start point (adjusts based on bb) - var pt = getBBintersect(x, y, elData(curLine, 'start_bb'), getOffset('start', curLine)); - startX = pt.x; - startY = pt.y; - setPoint(curLine, 0, pt.x, pt.y, true); // Set end point - - setPoint(curLine, 'end', x, y, true); - } else if (mode === 'select') { - var slen = selElems.length; - - while (slen--) { - var elem = selElems[slen]; // Look for selected connector elements - - if (elem && elData(elem, 'c_start')) { - // Remove the "translate" transform given to move - svgCanvas.removeFromSelection([elem]); - svgCanvas.getTransformList(elem).clear(); - } - } - - if (connections.length) { - updateLine(diffX, diffY); - } - } - }, - mouseUp: function mouseUp(opts) { - // const zoom = svgCanvas.getZoom(); - var e = opts.event; // , x = opts.mouse_x / zoom, - // , y = opts.mouse_y / zoom, - - var mouseTarget = e.target; - - if (svgCanvas.getMode() !== 'connector') { + if (mode === 'connector') { + if (started) { return undefined; } - var fo = $(mouseTarget).closest('foreignObject'); - - if (fo.length) { - mouseTarget = fo[0]; - } - + var mouseTarget = e.target; var parents = $(mouseTarget).parents(); - if (mouseTarget === startElem) { - // Start line through click + if ($.inArray(svgcontent, parents) !== -1) { + // Connectable element + // If child of foreignObject, use parent + var fo = $(mouseTarget).closest('foreignObject'); + startElem = fo.length ? fo[0] : mouseTarget; // Get center of source element + + var bb = svgCanvas.getStrokedBBox([startElem]); + var x = bb.x + bb.width / 2; + var y = bb.y + bb.height / 2; started = true; - return { - keep: true, - element: null, - started: started - }; + curLine = addElem({ + element: 'polyline', + attr: { + id: svgCanvas.getNextId(), + points: x + ',' + y + ' ' + x + ',' + y + ' ' + startX + ',' + startY, + stroke: '#' + initStroke.color, + 'stroke-width': !startElem.stroke_width || startElem.stroke_width === 0 ? initStroke.width : startElem.stroke_width, + fill: 'none', + opacity: initStroke.opacity, + style: 'pointer-events:none' + } + }); + elData(curLine, 'start_bb', bb); } - if ($.inArray(svgcontent, parents) === -1) { - // Not a valid target element, so remove line - $(curLine).remove(); - started = false; - return { - keep: false, - element: null, - started: started - }; - } // Valid end element - - - endElem = mouseTarget; - var startId = startElem.id, - endId = endElem.id; - var connStr = startId + ' ' + endId; - var altStr = endId + ' ' + startId; // Don't create connector if one already exists - - var dupe = $(svgcontent).find(connSel).filter(function () { - var conn = this.getAttributeNS(seNs, 'connector'); - - if (conn === connStr || conn === altStr) { - return true; - } - - return false; - }); - - if (dupe.length) { - $(curLine).remove(); - return { - keep: false, - element: null, - started: false - }; - } - - var bb = svgCanvas.getStrokedBBox([endElem]); - var pt = getBBintersect(startX, startY, bb, getOffset('start', curLine)); - setPoint(curLine, 'end', pt.x, pt.y, true); - $(curLine).data('c_start', startId).data('c_end', endId).data('end_bb', bb); - seNs = svgCanvas.getEditorNS(true); - curLine.setAttributeNS(seNs, 'se:connector', connStr); - curLine.setAttribute('class', connSel.substr(1)); - curLine.setAttribute('opacity', 1); - svgCanvas.addToSelection([curLine]); - svgCanvas.moveToBottomSelectedElement(); - selManager.requestSelector(curLine).showGrips(false); - started = false; return { - keep: true, - element: curLine, - started: started + started: true }; - }, - selectedChanged: function selectedChanged(opts) { - // TODO: Find better way to skip operations if no connectors are in use - if (!$(svgcontent).find(connSel).length) { - return; - } + } - if (svgCanvas.getMode() === 'connector') { - svgCanvas.setMode('select'); - } // Use this to update the current selected elements + if (mode === 'select') { + findConnectors(); + } + return undefined; + }, + mouseMove: function mouseMove(opts) { + var zoom = svgCanvas.getZoom(); // const e = opts.event; - selElems = opts.elems; - var i = selElems.length; + var x = opts.mouse_x / zoom; + var y = opts.mouse_y / zoom; + var diffX = x - startX, + diffY = y - startY; + var mode = svgCanvas.getMode(); - while (i--) { - var elem = selElems[i]; + if (mode === 'connector' && started) { + // const sw = curLine.getAttribute('stroke-width') * 3; + // Set start point (adjusts based on bb) + var pt = getBBintersect(x, y, elData(curLine, 'start_bb'), getOffset('start', curLine)); + startX = pt.x; + startY = pt.y; + setPoint(curLine, 0, pt.x, pt.y, true); // Set end point + + setPoint(curLine, 'end', x, y, true); + } else if (mode === 'select') { + var slen = selElems.length; + + while (slen--) { + var elem = selElems[slen]; // Look for selected connector elements if (elem && elData(elem, 'c_start')) { - selManager.requestSelector(elem).showGrips(false); + // Remove the "translate" transform given to move + svgCanvas.removeFromSelection([elem]); + svgCanvas.getTransformList(elem).clear(); + } + } - if (opts.selectedElement && !opts.multiselected) { - // TODO: Set up context tools and hide most regular line tools - showPanel(true); - } else { - showPanel(false); - } + if (connections.length) { + updateLine(diffX, diffY); + } + } + }, + mouseUp: function mouseUp(opts) { + // const zoom = svgCanvas.getZoom(); + var e = opts.event; // , x = opts.mouse_x / zoom, + // , y = opts.mouse_y / zoom, + + var mouseTarget = e.target; + + if (svgCanvas.getMode() !== 'connector') { + return undefined; + } + + var fo = $(mouseTarget).closest('foreignObject'); + + if (fo.length) { + mouseTarget = fo[0]; + } + + var parents = $(mouseTarget).parents(); + + if (mouseTarget === startElem) { + // Start line through click + started = true; + return { + keep: true, + element: null, + started: started + }; + } + + if ($.inArray(svgcontent, parents) === -1) { + // Not a valid target element, so remove line + $(curLine).remove(); + started = false; + return { + keep: false, + element: null, + started: started + }; + } // Valid end element + + + endElem = mouseTarget; + var startId = startElem.id, + endId = endElem.id; + var connStr = startId + ' ' + endId; + var altStr = endId + ' ' + startId; // Don't create connector if one already exists + + var dupe = $(svgcontent).find(connSel).filter(function () { + var conn = this.getAttributeNS(seNs, 'connector'); + + if (conn === connStr || conn === altStr) { + return true; + } + + return false; + }); + + if (dupe.length) { + $(curLine).remove(); + return { + keep: false, + element: null, + started: false + }; + } + + var bb = svgCanvas.getStrokedBBox([endElem]); + var pt = getBBintersect(startX, startY, bb, getOffset('start', curLine)); + setPoint(curLine, 'end', pt.x, pt.y, true); + $(curLine).data('c_start', startId).data('c_end', endId).data('end_bb', bb); + seNs = svgCanvas.getEditorNS(true); + curLine.setAttributeNS(seNs, 'se:connector', connStr); + curLine.setAttribute('class', connSel.substr(1)); + curLine.setAttribute('opacity', 1); + svgCanvas.addToSelection([curLine]); + svgCanvas.moveToBottomSelectedElement(); + selManager.requestSelector(curLine).showGrips(false); + started = false; + return { + keep: true, + element: curLine, + started: started + }; + }, + selectedChanged: function selectedChanged(opts) { + // TODO: Find better way to skip operations if no connectors are in use + if (!$(svgcontent).find(connSel).length) { + return; + } + + if (svgCanvas.getMode() === 'connector') { + svgCanvas.setMode('select'); + } // Use this to update the current selected elements + + + selElems = opts.elems; + var i = selElems.length; + + while (i--) { + var elem = selElems[i]; + + if (elem && elData(elem, 'c_start')) { + selManager.requestSelector(elem).showGrips(false); + + if (opts.selectedElement && !opts.multiselected) { + // TODO: Set up context tools and hide most regular line tools + showPanel(true); } else { showPanel(false); } - } - - updateConnectors(); - }, - elementChanged: function elementChanged(opts) { - var elem = opts.elems[0]; - - if (elem && elem.tagName === 'svg' && elem.id === 'svgcontent') { - // Update svgcontent (can change on import) - svgcontent = elem; - init(); - } // Has marker, so change offset - - - if (elem && (elem.getAttribute('marker-start') || elem.getAttribute('marker-mid') || elem.getAttribute('marker-end'))) { - var start = elem.getAttribute('marker-start'); - var mid = elem.getAttribute('marker-mid'); - var end = elem.getAttribute('marker-end'); - curLine = elem; - $(elem).data('start_off', Boolean(start)).data('end_off', Boolean(end)); - - if (elem.tagName === 'line' && mid) { - // Convert to polyline to accept mid-arrow - var x1 = Number(elem.getAttribute('x1')); - var x2 = Number(elem.getAttribute('x2')); - var y1 = Number(elem.getAttribute('y1')); - var y2 = Number(elem.getAttribute('y2')); - var _elem = elem, - id = _elem.id; - var midPt = ' ' + (x1 + x2) / 2 + ',' + (y1 + y2) / 2 + ' '; - var pline = addElem({ - element: 'polyline', - attr: { - points: x1 + ',' + y1 + midPt + x2 + ',' + y2, - stroke: elem.getAttribute('stroke'), - 'stroke-width': elem.getAttribute('stroke-width'), - 'marker-mid': mid, - fill: 'none', - opacity: elem.getAttribute('opacity') || 1 - } - }); - $(elem).after(pline).remove(); - svgCanvas.clearSelection(); - pline.id = id; - svgCanvas.addToSelection([pline]); - elem = pline; - } - } // Update line if it's a connector - - - if (elem.getAttribute('class') === connSel.substr(1)) { - var _start = getElem(elData(elem, 'c_start')); - - updateConnectors([_start]); } else { - updateConnectors(); + showPanel(false); } - }, - IDsUpdated: function IDsUpdated(input) { - var remove = []; - input.elems.forEach(function (elem) { - if ('se:connector' in elem.attr) { - elem.attr['se:connector'] = elem.attr['se:connector'].split(' ').map(function (oldID) { - return input.changes[oldID]; - }).join(' '); // Check validity - the field would be something like 'svg_21 svg_22', but - // if one end is missing, it would be 'svg_21' and therefore fail this test - - if (!/. ./.test(elem.attr['se:connector'])) { - remove.push(elem.attr.id); - } - } - }); - return { - remove: remove - }; - }, - toolButtonStateUpdate: function toolButtonStateUpdate(opts) { - if (opts.nostroke) { - if ($('#mode_connect').hasClass('tool_button_current')) { - svgEditor.clickSelect(); - } - } - - $('#mode_connect').toggleClass('disabled', opts.nostroke); } - }); - case 19: - case "end": - return _context.stop(); - } + updateConnectors(); + }, + elementChanged: function elementChanged(opts) { + var elem = opts.elems[0]; + + if (elem && elem.tagName === 'svg' && elem.id === 'svgcontent') { + // Update svgcontent (can change on import) + svgcontent = elem; + init(); + } // Has marker, so change offset + + + if (elem && (elem.getAttribute('marker-start') || elem.getAttribute('marker-mid') || elem.getAttribute('marker-end'))) { + var start = elem.getAttribute('marker-start'); + var mid = elem.getAttribute('marker-mid'); + var end = elem.getAttribute('marker-end'); + curLine = elem; + $(elem).data('start_off', Boolean(start)).data('end_off', Boolean(end)); + + if (elem.tagName === 'line' && mid) { + // Convert to polyline to accept mid-arrow + var x1 = Number(elem.getAttribute('x1')); + var x2 = Number(elem.getAttribute('x2')); + var y1 = Number(elem.getAttribute('y1')); + var y2 = Number(elem.getAttribute('y2')); + var _elem = elem, + id = _elem.id; + var midPt = ' ' + (x1 + x2) / 2 + ',' + (y1 + y2) / 2 + ' '; + var pline = addElem({ + element: 'polyline', + attr: { + points: x1 + ',' + y1 + midPt + x2 + ',' + y2, + stroke: elem.getAttribute('stroke'), + 'stroke-width': elem.getAttribute('stroke-width'), + 'marker-mid': mid, + fill: 'none', + opacity: elem.getAttribute('opacity') || 1 + } + }); + $(elem).after(pline).remove(); + svgCanvas.clearSelection(); + pline.id = id; + svgCanvas.addToSelection([pline]); + elem = pline; + } + } // Update line if it's a connector + + + if (elem.getAttribute('class') === connSel.substr(1)) { + var _start = getElem(elData(elem, 'c_start')); + + updateConnectors([_start]); + } else { + updateConnectors(); + } + }, + IDsUpdated: function IDsUpdated(input) { + var remove = []; + input.elems.forEach(function (elem) { + if ('se:connector' in elem.attr) { + elem.attr['se:connector'] = elem.attr['se:connector'].split(' ').map(function (oldID) { + return input.changes[oldID]; + }).join(' '); // Check validity - the field would be something like 'svg_21 svg_22', but + // if one end is missing, it would be 'svg_21' and therefore fail this test + + if (!/. ./.test(elem.attr['se:connector'])) { + remove.push(elem.attr.id); + } + } + }); + return { + remove: remove + }; + }, + toolButtonStateUpdate: function toolButtonStateUpdate(opts) { + if (opts.nostroke) { + if ($('#mode_connect').hasClass('tool_button_current')) { + svgEditor.clickSelect(); + } + } + + $('#mode_connect').toggleClass('disabled', opts.nostroke); + } + }); + + case 19: + case "end": + return _context.stop(); } - }, _callee, this); - })); - - function init(_x) { - return _init.apply(this, arguments); - } - - return init; - }() + } + }, null, this); + } }; return extConnector; diff --git a/dist/extensions/ext-eyedropper.js b/dist/extensions/ext-eyedropper.js index 00bb20bb..c00b7c69 100644 --- a/dist/extensions/ext-eyedropper.js +++ b/dist/extensions/ext-eyedropper.js @@ -1,42 +1,6 @@ var svgEditorExtension_eyedropper = (function () { '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 * @@ -47,160 +11,150 @@ var svgEditorExtension_eyedropper = (function () { */ var extEyedropper = { name: 'eyedropper', - init: function () { - var _init = _asyncToGenerator( - /*#__PURE__*/ - regeneratorRuntime.mark(function _callee(S) { - var strings, svgEditor, $, ChangeElementCommand, svgCanvas, addToHistory, currentStyle, getStyle, buttons; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - getStyle = function _ref(opts) { - // if we are in eyedropper mode, we don't want to disable the eye-dropper tool + init: function init(S) { + var strings, svgEditor, $, ChangeElementCommand, svgCanvas, addToHistory, currentStyle, getStyle, buttons; + return regeneratorRuntime.async(function init$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + getStyle = function _ref(opts) { + // if we are in eyedropper mode, we don't want to disable the eye-dropper tool + var mode = svgCanvas.getMode(); + + if (mode === 'eyedropper') { + return; + } + + var tool = $('#tool_eyedropper'); // enable-eye-dropper if one element is selected + + var 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(); 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)) { - 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 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.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)); } } - }); + } + }); - case 8: - case "end": - return _context.stop(); - } + case 8: + case "end": + return _context.stop(); } - }, _callee, this); - })); - - function init(_x) { - return _init.apply(this, arguments); - } - - return init; - }() + } + }, null, this); + } }; return extEyedropper; diff --git a/dist/extensions/ext-foreignobject.js b/dist/extensions/ext-foreignobject.js index 0c45de8f..b327b8b9 100644 --- a/dist/extensions/ext-foreignobject.js +++ b/dist/extensions/ext-foreignobject.js @@ -1,42 +1,6 @@ var svgEditorExtension_foreignobject = (function () { '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 * @@ -47,325 +11,311 @@ var svgEditorExtension_foreignobject = (function () { */ var extForeignobject = { name: 'foreignobject', - init: function () { - var _init = _asyncToGenerator( - /*#__PURE__*/ - regeneratorRuntime.mark(function _callee2(S) { - var svgEditor, $, text2xml, NS, importLocale, svgCanvas, svgdoc, strings, properlySourceSizeTextArea, showPanel, toggleSourceButtons, selElems, started, newFO, editingforeign, setForeignString, showForeignEditor, setAttr, buttons, contextTools; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - setAttr = function _ref6(attr, val) { - svgCanvas.changeSelectedAttribute(attr, val); - svgCanvas.call('changed', selElems); - }; + init: function init(S) { + var svgEditor, $, text2xml, NS, importLocale, svgCanvas, svgdoc, strings, properlySourceSizeTextArea, showPanel, toggleSourceButtons, selElems, started, newFO, editingforeign, setForeignString, showForeignEditor, setAttr, buttons, contextTools; + return regeneratorRuntime.async(function init$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + setAttr = function _ref5(attr, val) { + svgCanvas.changeSelectedAttribute(attr, val); + svgCanvas.call('changed', selElems); + }; - showForeignEditor = function _ref5() { - var elt = selElems[0]; + showForeignEditor = function _ref4() { + var elt = selElems[0]; - if (!elt || editingforeign) { - return; + if (!elt || editingforeign) { + return; + } + + editingforeign = true; + toggleSourceButtons(true); + elt.removeAttribute('fill'); + var str = svgCanvas.svgToString(elt, 0); + $('#svg_source_textarea').val(str); + $('#svg_source_editor').fadeIn(); + 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('' + xmlString + ''); // 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 = $('').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); - 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 _ref4(xmlString) { - var elt = selElems[0]; // The parent `Element` to append to - - try { - // convert string into XML document - var newDoc = text2xml('' + xmlString + ''); // 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; + } + }, { + id: 'edit_foreign', + icon: svgEditor.curConfig.extIconsPath + 'foreignobject-edit.png', + type: 'context', + panel: 'foreignObject_panel', + events: { + click: function click() { + showForeignEditor(); } - - return true; - }; - - toggleSourceButtons = function _ref3(on) { - $('#tool_source_save, #tool_source_cancel').toggle(!on); - $('#foreign_save, #foreign_cancel').toggle(on); - }; - - showPanel = function _ref2(on) { - var fcRules = $('#fc_rules'); - - if (!fcRules.length) { - fcRules = $('').appendTo('head'); + } + }]; + contextTools = [{ + type: 'input', + panel: 'foreignObject_panel', + id: 'foreign_width', + size: 3, + events: { + change: function change() { + setAttr('width', this.value); } - - 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 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'); - } + } + }, { + type: 'input', + panel: 'foreignObject_panel', + id: 'foreign_height', + events: { + change: function change() { + setAttr('height', this.value); } - }, { - id: 'edit_foreign', - icon: svgEditor.curConfig.extIconsPath + 'foreignobject-edit.png', - type: 'context', - panel: 'foreignObject_panel', - events: { - click: function click() { - showForeignEditor(); - } + } + }, { + type: 'input', + panel: 'foreignObject_panel', + id: 'foreign_font_size', + size: 2, + defval: 16, + events: { + change: function change() { + setAttr('font-size', this.value); } - }]; - contextTools = [{ - type: 'input', - panel: 'foreignObject_panel', - id: 'foreign_width', - size: 3, - events: { - change: function change() { - setAttr('width', this.value); - } - } - }, { - type: 'input', - 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(); + } + }]; + 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() { - $('#svg_source_editor').hide(); - editingforeign = false; - $('#svg_source_textarea').blur(); - toggleSourceButtons(false); - }; // TODO: Needs to be done after orig icon loads + var endChanges = function endChanges() { + $('#svg_source_editor').hide(); + editingforeign = false; + $('#svg_source_textarea').blur(); + toggleSourceButtons(false); + }; // TODO: Needs to be done after orig icon loads - setTimeout(function () { - // Create source save/cancel buttons + setTimeout(function () { + // Create source save/cancel buttons - /* const save = */ - $('#tool_source_save').clone().hide().attr('id', 'foreign_save').unbind().appendTo('#tool_source_back').click( - /*#__PURE__*/ - _asyncToGenerator( - /*#__PURE__*/ - regeneratorRuntime.mark(function _callee() { - var ok; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - 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; + /* const save = */ + $('#tool_source_save').clone().hide().attr('id', 'foreign_save').unbind().appendTo('#tool_source_back').click(function _callee() { + var ok; + return regeneratorRuntime.async(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (editingforeign) { + _context.next = 2; break; + } - case 11: - endChanges(); + return _context.abrupt("return"); - case 12: - case "end": - return _context.stop(); - } + case 2: + if (setForeignString($('#svg_source_textarea').val())) { + _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 { 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 "end": - return _context2.stop(); - } + case 17: + case "end": + return _context2.stop(); } - }, _callee2, this); - })); - - function init(_x) { - return _init.apply(this, arguments); - } - - return init; - }() + } + }, null, this); + } }; return extForeignobject; diff --git a/dist/extensions/ext-grid.js b/dist/extensions/ext-grid.js index def6145b..0c71125e 100644 --- a/dist/extensions/ext-grid.js +++ b/dist/extensions/ext-grid.js @@ -1,42 +1,6 @@ var svgEditorExtension_grid = (function () { '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 * @@ -47,180 +11,170 @@ var svgEditorExtension_grid = (function () { */ var extGrid = { name: 'grid', - init: function () { - var _init = _asyncToGenerator( - /*#__PURE__*/ - regeneratorRuntime.mark(function _callee(_ref) { - var $, NS, getTypeMap, importLocale, strings, svgEditor, svgCanvas, svgdoc, assignAttributes, hcanvas, canvBG, units, intervals, showGrid, canvasGrid, gridDefs, gridPattern, gridimg, gridBox, updateGrid, gridUpdate, buttons; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - gridUpdate = function _ref3() { + init: function init(_ref) { + var $, NS, getTypeMap, importLocale, strings, svgEditor, svgCanvas, svgdoc, assignAttributes, hcanvas, canvBG, units, intervals, showGrid, canvasGrid, gridDefs, gridPattern, gridimg, gridBox, updateGrid, gridUpdate, buttons; + return regeneratorRuntime.async(function init$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + gridUpdate = function _ref3() { + if (showGrid) { + updateGrid(svgCanvas.getZoom()); + } + + $('#canvasGrid').toggle(showGrid); + $('#view_grid').toggleClass('push_button_pressed tool_button'); + }; + + updateGrid = function _ref2(zoom) { + // TODO: Try this with 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) { - updateGrid(svgCanvas.getZoom()); + updateGrid(zoom); } - - $('#canvasGrid').toggle(showGrid); - $('#view_grid').toggleClass('push_button_pressed tool_button'); - }; - - updateGrid = function _ref2(zoom) { - // TODO: Try this with 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); + }, + callback: function callback() { + if (showGrid) { + gridUpdate(); } + }, + buttons: strings.buttons.map(function (button, i) { + return Object.assign(buttons[i], button); + }) + }); - 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 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(); - } + case 27: + case "end": + return _context.stop(); } - }, _callee, this); - })); - - function init(_x) { - return _init.apply(this, arguments); - } - - return init; - }() + } + }, null, this); + } }; return extGrid; diff --git a/dist/extensions/ext-helloworld.js b/dist/extensions/ext-helloworld.js index 8f04bc97..f29718b9 100644 --- a/dist/extensions/ext-helloworld.js +++ b/dist/extensions/ext-helloworld.js @@ -1,42 +1,6 @@ var svgEditorExtension_helloworld = (function () { '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) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } @@ -95,101 +59,91 @@ var svgEditorExtension_helloworld = (function () { */ var extHelloworld = { name: 'helloworld', - init: function () { - var _init = _asyncToGenerator( - /*#__PURE__*/ - regeneratorRuntime.mark(function _callee(_ref) { - var $, importLocale, strings, svgEditor, svgCanvas; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - $ = _ref.$, importLocale = _ref.importLocale; - _context.next = 3; - return importLocale(); + init: function init(_ref) { + var $, importLocale, strings, svgEditor, svgCanvas; + return regeneratorRuntime.async(function init$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + $ = _ref.$, importLocale = _ref.importLocale; + _context.next = 3; + return regeneratorRuntime.awrap(importLocale()); - case 3: - strings = _context.sent; - svgEditor = this; - svgCanvas = svgEditor.canvas; - return _context.abrupt("return", { - name: strings.name, - // For more notes on how to make an icon file, see the source of - // the helloworld-icon.xml - svgicons: svgEditor.curConfig.extIconsPath + 'helloworld-icon.xml', - // Multiple buttons can be added in this array - buttons: [{ - // Must match the icon ID in helloworld-icon.xml - id: 'hello_world', - // Fallback, e.g., for `file:///` access - icon: svgEditor.curConfig.extIconsPath + 'helloworld.png', - // This indicates that the button will be added to the "mode" - // button panel on the left side - type: 'mode', - // Tooltip text - title: strings.buttons[0].title, - // Events - events: { - click: function click() { - // The action taken when the button is clicked on. - // For "mode" buttons, any other button will - // automatically be de-pressed. - 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); + case 3: + strings = _context.sent; + svgEditor = this; + svgCanvas = svgEditor.canvas; + return _context.abrupt("return", { + name: strings.name, + // For more notes on how to make an icon file, see the source of + // the helloworld-icon.xml + svgicons: svgEditor.curConfig.extIconsPath + 'helloworld-icon.xml', + // Multiple buttons can be added in this array + buttons: [{ + // Must match the icon ID in helloworld-icon.xml + id: 'hello_world', + // Fallback, e.g., for `file:///` access + icon: svgEditor.curConfig.extIconsPath + 'helloworld.png', + // This indicates that the button will be added to the "mode" + // button panel on the left side + type: 'mode', + // Tooltip text + title: strings.buttons[0].title, + // Events + events: { + click: function click() { + // The action taken when the button is clicked on. + // For "mode" buttons, any other button will + // automatically be de-pressed. + 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 + }; + } - case 7: - case "end": - return _context.stop(); - } + 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); + } + } + }); + + case 7: + case "end": + return _context.stop(); } - }, _callee, this); - })); - - function init(_x) { - return _init.apply(this, arguments); - } - - return init; - }() + } + }, null, this); + } }; return extHelloworld; diff --git a/dist/extensions/ext-imagelib.js b/dist/extensions/ext-imagelib.js index 66c26365..caaa6301 100644 --- a/dist/extensions/ext-imagelib.js +++ b/dist/extensions/ext-imagelib.js @@ -15,42 +15,6 @@ var svgEditorExtension_imagelib = (function () { 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); - }); - }; - } - /** * ext-imagelib.js * @@ -61,525 +25,505 @@ var svgEditorExtension_imagelib = (function () { */ var extImagelib = { name: 'imagelib', - init: function () { - var _init = _asyncToGenerator( - /*#__PURE__*/ - regeneratorRuntime.mark(function _callee2(_ref) { - var $, decode64, importLocale, dropXMLInternalSubset, imagelibStrings, modularVersion, svgEditor, uiStrings, svgCanvas, extIconsPath, allowedImageLibOrigins, closeBrowser, importImage, pending, mode, multiArr, transferStopped, preview, submit, toggleMulti, showBrowser, buttons; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - showBrowser = function _ref10() { - var browser = $('#imgbrowse'); + init: function init(_ref) { + var $, decode64, importLocale, dropXMLInternalSubset, imagelibStrings, modularVersion, svgEditor, uiStrings, svgCanvas, extIconsPath, allowedImageLibOrigins, closeBrowser, importImage, pending, mode, multiArr, transferStopped, preview, submit, toggleMulti, showBrowser, buttons; + return regeneratorRuntime.async(function init$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + showBrowser = function _ref9() { + var browser = $('#imgbrowse'); - if (!browser.length) { - $('
' + '
').insertAfter('#svg_docprops'); - browser = $('#imgbrowse'); - var allLibs = imagelibStrings.select_lib; - var libOpts = $('